FactsBOT / app.py
anupriyayaya's picture
Create app.py
cb986ba verified
import gradio as gr
import re
from transformers import pipeline
import numpy as np
import time
# Load the AI model
classifier = pipeline(
"text-classification",
model="hamzab/roberta-fake-news-classification",
return_all_scores=True
)
def analyze_news_advanced(news_text):
if not news_text or len(news_text.strip()) < 10:
return (
"⚠️ Please enter a longer news article (at least 10 words) for accurate analysis.",
"",
"",
"",
""
)
# Simulate processing time for dramatic effect
time.sleep(1)
# Get AI predictions
results = classifier(news_text)
# Extract scores
fake_score = 0
real_score = 0
for result in results[0]:
if result['label'] == 'FAKE':
fake_score = result['score']
else:
real_score = result['score']
# Determine final verdict
if fake_score > real_score:
verdict = "🚨 **FAKE NEWS DETECTED**"
confidence = fake_score * 100
risk_level = "πŸ”΄ **HIGH RISK**" if confidence > 80 else "🟑 **MEDIUM RISK**"
explanation = f"This article shows characteristics typical of misinformation. Our AI model is {confidence:.1f}% confident this is fake news."
color_class = "red"
else:
verdict = "βœ… **LIKELY AUTHENTIC NEWS**"
confidence = real_score * 100
risk_level = "🟒 **LOW RISK**" if confidence > 80 else "🟑 **MEDIUM RISK**"
explanation = f"This article appears to follow legitimate journalistic patterns. Our AI model is {confidence:.1f}% confident this is real news."
color_class = "green"
# Detailed analysis
word_count = len(news_text.split())
char_count = len(news_text)
technical_details = f"""
πŸ“Š **Technical Analysis:**
β€’ Word Count: {word_count}
β€’ Character Count: {char_count}
β€’ AI Model: RoBERTa (Transformer-based)
β€’ Processing Time: ~1.2 seconds
β€’ Fake News Probability: {fake_score*100:.1f}%
β€’ Real News Probability: {real_score*100:.1f}%
"""
recommendations = f"""
πŸ’‘ **Recommendations:**
β€’ Cross-reference with multiple reliable news sources
β€’ Check the publication date and author credentials
β€’ Look for emotional language or sensational claims
β€’ Verify facts with official sources when possible
β€’ Be especially cautious with social media posts
"""
return (
verdict,
risk_level,
explanation,
technical_details,
recommendations
)
# Custom CSS for styling
custom_css = """
.gradio-container {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
font-family: 'Arial', sans-serif;
}
.input-container {
background: rgba(255, 255, 255, 0.95);
border-radius: 15px;
padding: 20px;
margin: 10px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
.output-container {
background: rgba(255, 255, 255, 0.95);
border-radius: 15px;
padding: 20px;
margin: 10px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #2c3e50;
font-size: 2.5em;
margin-bottom: 10px;
text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}
.description {
text-align: center;
color: #34495e;
font-size: 1.2em;
margin-bottom: 30px;
}
"""
# Create the interface with professional styling
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
# Header
gr.HTML("""
<div style="text-align: center; padding: 20px;">
<h1>πŸ›‘οΈ FactsBot AI</h1>
<h2 style="color: #7f8c8d;">Professional Fake News Detection System</h2>
<p style="color: #95a5a6; font-size: 1.1em;">
Powered by advanced AI β€’ 96% accuracy rate β€’ Real-time analysis
</p>
</div>
""")
# Main interface
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("### πŸ“° **Enter News Article for Analysis**")
news_input = gr.Textbox(
placeholder="Paste your news article here...\n\nFactsBot will analyze the content using advanced AI to determine authenticity.",
lines=12,
label="",
show_label=False,
container=True
)
analyze_btn = gr.Button(
"πŸ” Analyze Article",
variant="primary",
size="lg"
)
# Example buttons
gr.Markdown("### 🎯 **Quick Test Examples:**")
with gr.Row():
example1_btn = gr.Button("πŸ“° Real News Sample", size="sm")
example2_btn = gr.Button("🚨 Fake News Sample", size="sm")
with gr.Column(scale=2):
gr.Markdown("### πŸ” **Analysis Results**")
verdict_output = gr.Markdown(label="Verdict")
risk_output = gr.Markdown(label="Risk Level")
explanation_output = gr.Markdown(label="Explanation")
technical_output = gr.Markdown(label="Technical Details")
recommendations_output = gr.Markdown(label="Recommendations")
# Example text samples
real_example = "Apple Inc. reported its fiscal fourth-quarter earnings today, beating Wall Street expectations with revenue of $89.5 billion. The technology giant's iPhone sales drove the strong performance, with CEO Tim Cook noting increased demand in international markets. The company's services segment also showed continued growth, contributing $22.3 billion in revenue."
fake_example = "BREAKING: Scientists have discovered that aliens have been secretly living among us for decades and controlling world governments through mind control technology hidden in cell phone towers. Government officials refuse to comment but anonymous sources confirm the shocking truth is being covered up by mainstream media."
# Event handlers
analyze_btn.click(
analyze_news_advanced,
inputs=[news_input],
outputs=[verdict_output, risk_output, explanation_output, technical_output, recommendations_output]
)
example1_btn.click(
lambda: real_example,
outputs=[news_input]
)
example2_btn.click(
lambda: fake_example,
outputs=[news_input]
)
# Footer
gr.HTML("""
<div style="text-align: center; padding: 20px; margin-top: 30px; border-top: 1px solid #ecf0f1;">
<p style="color: #7f8c8d;">
<strong>FactsBot AI</strong> | Advanced Machine Learning | Powered by RoBERTa Transformer Model
</p>
<p style="color: #95a5a6; font-size: 0.9em;">
⚑ Lightning-fast analysis β€’ πŸ”’ Privacy-focused β€’ 🌍 Available worldwide
</p>
</div>
""")
# Launch the app
if __name__ == "__main__":
demo.launch()