Spaces:
Build error
Build error
Shujaat Ali
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -3,14 +3,15 @@ import gradio as gr
|
|
3 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, T5Tokenizer, T5ForConditionalGeneration
|
4 |
import torch
|
5 |
import nltk
|
|
|
|
|
6 |
import spacy
|
7 |
-
|
8 |
-
import subprocess
|
9 |
|
10 |
# Download NLTK data (if not already downloaded)
|
11 |
nltk.download('punkt')
|
12 |
nltk.download('stopwords')
|
13 |
-
nltk.download('wordnet') # Download WordNet
|
14 |
|
15 |
# Download spaCy model if not already installed
|
16 |
try:
|
@@ -30,39 +31,97 @@ model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-unca
|
|
30 |
paraphrase_tokenizer = T5Tokenizer.from_pretrained("SRDdev/Paraphrase")
|
31 |
paraphrase_model = T5ForConditionalGeneration.from_pretrained("SRDdev/Paraphrase").to(device)
|
32 |
|
33 |
-
#
|
34 |
-
def
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
return
|
40 |
|
41 |
-
#
|
42 |
-
def replace_with_synonyms(text):
|
43 |
doc = nlp(text)
|
44 |
-
|
45 |
for token in doc:
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
|
|
52 |
else:
|
53 |
-
|
54 |
-
return " ".join(
|
55 |
|
56 |
-
#
|
57 |
-
def
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
def humanize_text(AI_text):
|
67 |
paragraphs = AI_text.split("\n")
|
68 |
paraphrased_paragraphs = []
|
@@ -71,36 +130,38 @@ def humanize_text(AI_text):
|
|
71 |
inputs = paraphrase_tokenizer(paragraph, return_tensors="pt", max_length=512, truncation=True).to(device)
|
72 |
paraphrased_ids = paraphrase_model.generate(
|
73 |
inputs['input_ids'],
|
74 |
-
max_length=inputs['input_ids'].shape[-1] + 20,
|
75 |
-
num_beams=
|
76 |
early_stopping=True,
|
77 |
-
length_penalty=
|
78 |
-
no_repeat_ngram_size=
|
|
|
|
|
|
|
79 |
)
|
80 |
paraphrased_text = paraphrase_tokenizer.decode(paraphrased_ids[0], skip_special_tokens=True)
|
81 |
paraphrased_paragraphs.append(paraphrased_text)
|
82 |
return "\n\n".join(paraphrased_paragraphs)
|
83 |
|
84 |
-
# Main function to handle the overall process
|
85 |
def main_function(AI_text):
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
# Detect AI-generated content
|
90 |
-
ai_probability = detect_ai_generated(text_with_synonyms)
|
91 |
|
92 |
-
#
|
93 |
-
humanized_text = humanize_text(
|
|
|
94 |
|
95 |
-
return f"AI-Generated Content: {
|
96 |
|
97 |
# Gradio interface definition
|
98 |
interface = gr.Interface(
|
99 |
fn=main_function,
|
100 |
inputs="textbox",
|
101 |
outputs="textbox",
|
102 |
-
title="AI Text Humanizer
|
103 |
-
description="Enter AI-generated text and get a human-written version
|
104 |
)
|
105 |
|
106 |
# Launch the Gradio app
|
|
|
3 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, T5Tokenizer, T5ForConditionalGeneration
|
4 |
import torch
|
5 |
import nltk
|
6 |
+
import random
|
7 |
+
import string
|
8 |
import spacy
|
9 |
+
import subprocess # Import subprocess for downloading spaCy models
|
|
|
10 |
|
11 |
# Download NLTK data (if not already downloaded)
|
12 |
nltk.download('punkt')
|
13 |
nltk.download('stopwords')
|
14 |
+
nltk.download('wordnet') # Download WordNet for enhanced synonym lookup
|
15 |
|
16 |
# Download spaCy model if not already installed
|
17 |
try:
|
|
|
31 |
paraphrase_tokenizer = T5Tokenizer.from_pretrained("SRDdev/Paraphrase")
|
32 |
paraphrase_model = T5ForConditionalGeneration.from_pretrained("SRDdev/Paraphrase").to(device)
|
33 |
|
34 |
+
# AI detection function using DistilBERT with batch processing
|
35 |
+
def detect_ai_generated(texts):
|
36 |
+
inputs = tokenizer(texts, return_tensors="pt", truncation=True, max_length=512, padding=True).to(device)
|
37 |
+
with torch.no_grad():
|
38 |
+
outputs = model(**inputs)
|
39 |
+
probabilities = torch.softmax(outputs.logits, dim=1)[:, 1].cpu().tolist() # List of AI-generated probabilities
|
40 |
+
return probabilities
|
41 |
|
42 |
+
# Synonym replacement using spaCy
|
43 |
+
def replace_with_synonyms(text, probability=0.3):
|
44 |
doc = nlp(text)
|
45 |
+
new_text = []
|
46 |
for token in doc:
|
47 |
+
if random.random() < probability and token.pos_ in ("NOUN", "VERB", "ADJ", "ADV"):
|
48 |
+
synonyms = [synonym.lemma_ for synonym in token.vocab if synonym.is_lower == token.is_lower]
|
49 |
+
if synonyms:
|
50 |
+
new_word = random.choice(synonyms)
|
51 |
+
new_text.append(new_word)
|
52 |
+
else:
|
53 |
+
new_text.append(token.text)
|
54 |
else:
|
55 |
+
new_text.append(token.text)
|
56 |
+
return " ".join(new_text)
|
57 |
|
58 |
+
# Random text transformations to simulate human-like errors
|
59 |
+
def random_capitalize(word):
|
60 |
+
if word.isalpha() and random.random() < 0.1:
|
61 |
+
return word.capitalize()
|
62 |
+
return word
|
63 |
+
|
64 |
+
def random_remove_punctuation(text):
|
65 |
+
if random.random() < 0.2:
|
66 |
+
text = list(text)
|
67 |
+
indices = [i for i, c in enumerate(text) if c in string.punctuation]
|
68 |
+
if indices:
|
69 |
+
remove_indices = random.sample(indices, min(3, len(indices)))
|
70 |
+
for idx in sorted(remove_indices, reverse=True):
|
71 |
+
text.pop(idx)
|
72 |
+
return ''.join(text)
|
73 |
+
return text
|
74 |
+
|
75 |
+
def random_double_period(text):
|
76 |
+
if random.random() < 0.2:
|
77 |
+
text = text.replace('.', '..', 3)
|
78 |
+
return text
|
79 |
|
80 |
+
def random_double_space(text):
|
81 |
+
if random.random() < 0.2:
|
82 |
+
words = text.split()
|
83 |
+
for _ in range(min(3, len(words) - 1)):
|
84 |
+
idx = random.randint(0, len(words) - 2)
|
85 |
+
words[idx] += ' '
|
86 |
+
return ' '.join(words)
|
87 |
+
return text
|
88 |
+
|
89 |
+
def random_replace_comma_space(text, period_replace_percentage=0.33):
|
90 |
+
comma_occurrences = text.count(", ")
|
91 |
+
period_occurrences = text.count(". ")
|
92 |
+
replace_count_comma = max(1, comma_occurrences // 3)
|
93 |
+
replace_count_period = max(1, period_occurrences // 3)
|
94 |
+
comma_indices = [i for i in range(len(text)) if text.startswith(", ", i)]
|
95 |
+
period_indices = [i for i in range(len(text)) if text.startswith(". ", i)]
|
96 |
+
replace_indices_comma = random.sample(comma_indices, min(replace_count_comma, len(comma_indices)))
|
97 |
+
replace_indices_period = random.sample(period_indices, min(replace_count_period, len(period_indices)))
|
98 |
+
for idx in sorted(replace_indices_comma + replace_indices_period, reverse=True):
|
99 |
+
if text.startswith(", ", idx):
|
100 |
+
text = text[:idx] + " ," + text[idx + 2:]
|
101 |
+
if text.startswith(". ", idx):
|
102 |
+
text = text[:idx] + " ." + text[idx + 2:]
|
103 |
+
return text
|
104 |
+
|
105 |
+
def transform_paragraph(paragraph):
|
106 |
+
words = paragraph.split()
|
107 |
+
if len(words) > 12:
|
108 |
+
words = [random_capitalize(word) for word in words]
|
109 |
+
transformed_paragraph = ' '.join(words)
|
110 |
+
transformed_paragraph = random_remove_punctuation(transformed_paragraph)
|
111 |
+
transformed_paragraph = random_double_period(transformed_paragraph)
|
112 |
+
transformed_paragraph = random_double_space(transformed_paragraph)
|
113 |
+
transformed_paragraph = random_replace_comma_space(transformed_paragraph)
|
114 |
+
transformed_paragraph = replace_with_synonyms(transformed_paragraph) # Use spaCy for synonyms
|
115 |
+
else:
|
116 |
+
transformed_paragraph = paragraph
|
117 |
+
return transformed_paragraph
|
118 |
+
|
119 |
+
def transform_text(text):
|
120 |
+
paragraphs = text.split('\n')
|
121 |
+
transformed_paragraphs = [transform_paragraph(paragraph) for paragraph in paragraphs]
|
122 |
+
return '\n'.join(transformed_paragraphs)
|
123 |
+
|
124 |
+
# Humanize the AI-detected text using the SRDdev Paraphrase model with optimized parameters
|
125 |
def humanize_text(AI_text):
|
126 |
paragraphs = AI_text.split("\n")
|
127 |
paraphrased_paragraphs = []
|
|
|
130 |
inputs = paraphrase_tokenizer(paragraph, return_tensors="pt", max_length=512, truncation=True).to(device)
|
131 |
paraphrased_ids = paraphrase_model.generate(
|
132 |
inputs['input_ids'],
|
133 |
+
max_length=inputs['input_ids'].shape[-1] + 20,
|
134 |
+
num_beams=2, # Reduced beam size for speed
|
135 |
early_stopping=True,
|
136 |
+
length_penalty=0.8, # Lower penalty to generate faster
|
137 |
+
no_repeat_ngram_size=2, # Reduced for performance
|
138 |
+
do_sample=True, # Enable sampling to add randomness
|
139 |
+
top_k=50, # Top-k sampling
|
140 |
+
top_p=0.95, # Top-p (nucleus) sampling
|
141 |
)
|
142 |
paraphrased_text = paraphrase_tokenizer.decode(paraphrased_ids[0], skip_special_tokens=True)
|
143 |
paraphrased_paragraphs.append(paraphrased_text)
|
144 |
return "\n\n".join(paraphrased_paragraphs)
|
145 |
|
146 |
+
# Main function to handle the overall process with batch processing
|
147 |
def main_function(AI_text):
|
148 |
+
sentences = nltk.sent_tokenize(AI_text)
|
149 |
+
ai_probabilities = detect_ai_generated(sentences)
|
150 |
+
ai_generated_percentage = sum([1 for prob in ai_probabilities if prob > 0.5]) / len(ai_probabilities) * 100
|
|
|
|
|
151 |
|
152 |
+
# Transform AI text to make it more human-like
|
153 |
+
humanized_text = humanize_text(AI_text)
|
154 |
+
humanized_text = transform_text(humanized_text) # Add randomness to simulate human errors
|
155 |
|
156 |
+
return f"AI-Generated Content: {ai_generated_percentage:.2f}%\n\nHumanized Text:\n{humanized_text}"
|
157 |
|
158 |
# Gradio interface definition
|
159 |
interface = gr.Interface(
|
160 |
fn=main_function,
|
161 |
inputs="textbox",
|
162 |
outputs="textbox",
|
163 |
+
title="AI Text Humanizer",
|
164 |
+
description="Enter AI-generated text and get a human-written version. This space uses models from Hugging Face directly."
|
165 |
)
|
166 |
|
167 |
# Launch the Gradio app
|