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