Sankalp3011 commited on
Commit
33a6118
Β·
verified Β·
1 Parent(s): a595c48

Enhanced AI detector with detailed analysis and improved UI

Browse files
Files changed (1) hide show
  1. app.py +263 -16
app.py CHANGED
@@ -1,29 +1,276 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
  import torch
 
 
 
4
 
 
5
  model_name = "roberta-base-openai-detector"
6
  tokenizer = AutoTokenizer.from_pretrained(model_name)
7
  model = AutoModelForSequenceClassification.from_pretrained(model_name)
8
 
9
- def detect_ai(text):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
 
11
  with torch.no_grad():
12
  logits = model(**inputs).logits
13
- prob = logits.softmax(dim=1).tolist()[0]
14
- out = {
15
- "Human Probability (%)": round(prob[0] * 100, 2),
16
- "AI Probability (%)": round(prob[1] * 100, 2)
17
- }
18
- return out
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- iface = gr.Interface(
21
- fn=detect_ai,
22
- inputs=gr.TextArea(lines=8, label="Paste your text"),
23
- outputs="label",
24
- title="Open Source AI Text Detector",
25
- description="Paste text below. Returns % probability for AI or human-generated content."
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == "__main__":
29
- iface.launch()
 
1
  import gradio as gr
 
2
  import torch
3
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
+ import re
5
+ from datetime import datetime
6
 
7
+ # Load the model and tokenizer
8
  model_name = "roberta-base-openai-detector"
9
  tokenizer = AutoTokenizer.from_pretrained(model_name)
10
  model = AutoModelForSequenceClassification.from_pretrained(model_name)
11
 
12
+ def analyze_text_patterns(text):
13
+ """Analyze text patterns that might indicate AI generation"""
14
+ patterns = {
15
+ 'repetitive_phrases': 0,
16
+ 'avg_sentence_length': 0,
17
+ 'complex_words': 0,
18
+ 'transition_words': 0,
19
+ 'formal_language': 0
20
+ }
21
+
22
+ sentences = re.split(r'[.!?]+', text)
23
+ sentences = [s.strip() for s in sentences if s.strip()]
24
+
25
+ if sentences:
26
+ # Average sentence length
27
+ patterns['avg_sentence_length'] = sum(len(s.split()) for s in sentences) / len(sentences)
28
+
29
+ # Check for repetitive phrases
30
+ words = text.lower().split()
31
+ word_freq = {}
32
+ for word in words:
33
+ word_freq[word] = word_freq.get(word, 0) + 1
34
+
35
+ # Count words used more than expected
36
+ total_words = len(words)
37
+ if total_words > 0:
38
+ patterns['repetitive_phrases'] = sum(1 for freq in word_freq.values() if freq > max(2, total_words * 0.02))
39
+
40
+ # Transition words (common in AI text)
41
+ transition_words = ['furthermore', 'moreover', 'additionally', 'consequently', 'therefore', 'however', 'nevertheless']
42
+ patterns['transition_words'] = sum(1 for word in transition_words if word in text.lower())
43
+
44
+ # Complex words (>7 characters)
45
+ patterns['complex_words'] = sum(1 for word in words if len(word) > 7)
46
+
47
+ # Formal language indicators
48
+ formal_indicators = ['utilize', 'demonstrate', 'facilitate', 'implement', 'Subsequently']
49
+ patterns['formal_language'] = sum(1 for indicator in formal_indicators if indicator.lower() in text.lower())
50
+
51
+ return patterns
52
+
53
+ def highlight_suspicious_sentences(text, ai_probability):
54
+ """Highlight sentences that might be AI-generated"""
55
+ if ai_probability < 0.5:
56
+ return text
57
+
58
+ sentences = re.split(r'([.!?]+)', text)
59
+ highlighted_text = ""
60
+
61
+ for i in range(0, len(sentences)-1, 2):
62
+ sentence = sentences[i].strip()
63
+ punctuation = sentences[i+1] if i+1 < len(sentences) else ""
64
+
65
+ if sentence:
66
+ # Simple heuristics for highlighting suspicious sentences
67
+ suspicious = False
68
+
69
+ # Very long sentences
70
+ if len(sentence.split()) > 30:
71
+ suspicious = True
72
+
73
+ # Contains multiple transition words
74
+ transition_count = sum(1 for word in ['furthermore', 'moreover', 'additionally', 'consequently', 'therefore', 'however', 'nevertheless'] if word in sentence.lower())
75
+ if transition_count >= 2:
76
+ suspicious = True
77
+
78
+ # Very formal language
79
+ formal_words = sum(1 for word in ['utilize', 'demonstrate', 'facilitate', 'implement', 'subsequently'] if word.lower() in sentence.lower())
80
+ if formal_words >= 2:
81
+ suspicious = True
82
+
83
+ if suspicious and ai_probability > 0.7:
84
+ highlighted_text += f"**πŸ€– {sentence}**{punctuation} "
85
+ else:
86
+ highlighted_text += f"{sentence}{punctuation} "
87
+
88
+ return highlighted_text
89
+
90
+ def generate_detailed_report(text, ai_prob, human_prob, patterns):
91
+ """Generate a comprehensive analysis report"""
92
+ report = f"""## πŸ“Š AI Detection Analysis Report
93
+
94
+ **Analysis Date:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
95
+
96
+ ### 🎯 Detection Results
97
+ - **AI Probability:** {ai_prob:.1f}%
98
+ - **Human Probability:** {human_prob:.1f}%
99
+ - **Confidence Level:** {'High' if abs(ai_prob - human_prob) > 40 else 'Medium' if abs(ai_prob - human_prob) > 20 else 'Low'}
100
+
101
+ ### πŸ“ˆ Text Analysis Metrics
102
+ - **Average Sentence Length:** {patterns['avg_sentence_length']:.1f} words
103
+ - **Repetitive Phrases Detected:** {patterns['repetitive_phrases']}
104
+ - **Transition Words Count:** {patterns['transition_words']}
105
+ - **Complex Words (>7 chars):** {patterns['complex_words']}
106
+ - **Formal Language Indicators:** {patterns['formal_language']}
107
+
108
+ ### πŸ” Assessment
109
+ """
110
+
111
+ if ai_prob > 80:
112
+ report += "**Very High AI Likelihood** - Multiple indicators suggest this text was likely generated by AI."
113
+ elif ai_prob > 60:
114
+ report += "**High AI Likelihood** - Several patterns consistent with AI-generated content detected."
115
+ elif ai_prob > 40:
116
+ report += "**Moderate AI Likelihood** - Some AI-like patterns present, but not conclusive."
117
+ else:
118
+ report += "**Low AI Likelihood** - Text patterns are more consistent with human writing."
119
+
120
+ # Add specific observations
121
+ observations = []
122
+ if patterns['avg_sentence_length'] > 25:
123
+ observations.append("β€’ Sentences are longer than typical human writing")
124
+ if patterns['transition_words'] > 3:
125
+ observations.append("β€’ High use of transition words (common in AI text)")
126
+ if patterns['formal_language'] > 2:
127
+ observations.append("β€’ Elevated formal language usage")
128
+ if patterns['repetitive_phrases'] > 5:
129
+ observations.append("β€’ Some repetitive phrasing detected")
130
+
131
+ if observations:
132
+ report += "\n\n### πŸ“‹ Key Observations\n" + "\n".join(observations)
133
+
134
+ report += "\n\n### ⚠️ Important Notes\n"
135
+ report += "- This analysis is for informational purposes only\n"
136
+ report += "- AI detection is not 100% accurate and should be used as guidance\n"
137
+ report += "- Human-AI collaborative writing may produce mixed results\n"
138
+ report += "- Consider multiple factors when evaluating text authenticity"
139
+
140
+ return report
141
+
142
+ def detect_ai_advanced(text):
143
+ """Enhanced AI detection with detailed analysis"""
144
+ if not text or len(text.strip()) < 10:
145
+ return "Please enter at least 10 characters of text.", "", ""
146
+
147
+ # Get model prediction
148
  inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
149
+
150
  with torch.no_grad():
151
  logits = model(**inputs).logits
152
+
153
+ probabilities = torch.softmax(logits, dim=-1)
154
+ human_prob = probabilities[0][0].item() * 100
155
+ ai_prob = probabilities[0][1].item() * 100
156
+
157
+ # Analyze text patterns
158
+ patterns = analyze_text_patterns(text)
159
+
160
+ # Generate highlighted text
161
+ highlighted_text = highlight_suspicious_sentences(text, ai_prob/100)
162
+
163
+ # Generate detailed report
164
+ report = generate_detailed_report(text, ai_prob, human_prob, patterns)
165
+
166
+ # Create probability display
167
+ prob_display = f"""## 🎯 Detection Results
168
+
169
+ **AI Probability:** {ai_prob:.1f}% {'πŸ€–' if ai_prob > 50 else ''}
170
+ **Human Probability:** {human_prob:.1f}% {'πŸ‘€' if human_prob > 50 else ''}
171
 
172
+ **Verdict:** {'Likely AI-Generated' if ai_prob > 50 else 'Likely Human-Written'}
173
+ """
174
+
175
+ return prob_display, highlighted_text, report
176
+
177
+ # Create the Gradio interface using Blocks for better layout
178
+ with gr.Blocks(
179
+ title="πŸ€– Advanced AI Text Detector",
180
+ theme=gr.themes.Soft(),
181
+ css="""
182
+ .highlight-box {
183
+ border-left: 4px solid #ff6b6b;
184
+ background-color: #fff5f5;
185
+ padding: 10px;
186
+ margin: 10px 0;
187
+ }
188
+ .result-box {
189
+ border: 2px solid #4ecdc4;
190
+ border-radius: 10px;
191
+ padding: 15px;
192
+ margin: 10px 0;
193
+ }
194
+ """
195
+ ) as iface:
196
+
197
+ gr.Markdown("""
198
+ # πŸ€– Advanced AI Text Detector
199
+
200
+ **Paste your text below to analyze whether it was written by AI or humans.**
201
+
202
+ This enhanced detector provides:
203
+ - 🎯 Probability scores for AI vs Human authorship
204
+ - πŸ” Sentence-level highlighting of suspicious content
205
+ - πŸ“Š Detailed analysis report with text metrics
206
+ - ⚑ Real-time pattern analysis
207
+
208
+ *Note: AI detection is not 100% accurate. Use results as guidance only.*
209
+ """)
210
+
211
+ with gr.Row():
212
+ with gr.Column(scale=1):
213
+ text_input = gr.Textbox(
214
+ label="πŸ“ Enter Text to Analyze",
215
+ placeholder="Paste your text here... (minimum 10 characters)",
216
+ lines=8,
217
+ max_lines=15
218
+ )
219
+
220
+ with gr.Row():
221
+ analyze_btn = gr.Button("πŸ” Analyze Text", variant="primary", size="lg")
222
+ clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
223
+
224
+ with gr.Row():
225
+ with gr.Column(scale=1):
226
+ probability_output = gr.Markdown(label="🎯 Detection Results")
227
+
228
+ with gr.Column(scale=1):
229
+ highlighted_output = gr.Markdown(label="πŸ” Text Analysis (Suspicious sentences marked with πŸ€–)")
230
+
231
+ with gr.Row():
232
+ detailed_report = gr.Markdown(label="πŸ“Š Detailed Analysis Report")
233
+
234
+ # Event handlers
235
+ analyze_btn.click(
236
+ fn=detect_ai_advanced,
237
+ inputs=[text_input],
238
+ outputs=[probability_output, highlighted_output, detailed_report]
239
+ )
240
+
241
+ clear_btn.click(
242
+ fn=lambda: ("", "", "", ""),
243
+ outputs=[text_input, probability_output, highlighted_output, detailed_report]
244
+ )
245
+
246
+ # Add examples
247
+ gr.Examples(
248
+ examples=[
249
+ ["The quick brown fox jumps over the lazy dog. This is a simple test sentence."],
250
+ ["Furthermore, it is important to note that the implementation of advanced technological solutions facilitates the optimization of operational efficiency. Moreover, the utilization of artificial intelligence demonstrates significant potential for enhancing productivity across various sectors."],
251
+ ["I love spending time with my friends on weekends. We usually go to the park or watch movies together. It's always fun and relaxing!"]
252
+ ],
253
+ inputs=[text_input],
254
+ label="πŸ“š Try these examples:"
255
+ )
256
+
257
+ gr.Markdown("""
258
+ ---
259
+
260
+ ### πŸ”¬ How it works:
261
+ - Uses a fine-tuned RoBERTa model trained on AI vs human text
262
+ - Analyzes linguistic patterns, sentence structure, and vocabulary usage
263
+ - Provides confidence scores and detailed explanations
264
+ - Highlights potentially AI-generated sentences
265
+
266
+ ### ⚠️ Limitations:
267
+ - Not 100% accurate - use as a guidance tool
268
+ - Works best with longer text samples (50+ words)
269
+ - May struggle with mixed human-AI content
270
+ - Performance varies by text domain and AI model used
271
+
272
+ **Built with ❀️ using Gradio and Hugging Face Transformers**
273
+ """)
274
 
275
  if __name__ == "__main__":
276
+ iface.launch()