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()