sashdev commited on
Commit
30196dc
1 Parent(s): 670df0e

Update app.py

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