pankajkr07's picture
Update app.py
911958d verified
Raw History Blame Contribute Delete
11.5 kB
"""
Misinformation Detection Using Deep Learning
"""
import re
import json
import torch
import gradio as gr
from transformers import BertTokenizer, BertForSequenceClassification
# ── Configuration ────────────────────────────────────────────────────────────
MODEL_PATH = "."
MAX_LEN = 256
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ── Load Model ───────────────────────────────────────────────────────────────
print(f"Loading model from: {MODEL_PATH}")
print(f"Device: {device}")
tokenizer = BertTokenizer.from_pretrained(MODEL_PATH)
model = BertForSequenceClassification.from_pretrained(MODEL_PATH).to(device)
model.eval()
print("βœ… Model loaded successfully!")
# ── Conspiracy / Clickbait Phrases ───────────────────────────────────────────
CONSPIRACY_PHRASES = [
"they don't want you to know", "wake up", "share before deleted",
"deep state", "cover up", "mainstream media hiding", "bombshell",
"whistleblower", "classified document", "microchip", "population control",
"new world order", "government hiding", "censored", "banned video",
"truth revealed", "global conspiracy", "secret underground", "fake pandemic",
"5g tower", "poison water", "depopulation", "shadow government",
"false flag", "staged attack", "crisis actor", "illuminati",
"chemtrail", "mind control", "breaking news", "shocking truth",
]
# ── Text Cleaning ─────────────────────────────────────────────────────────────
def clean_text(text):
text = str(text)
text = re.sub(r"http\S+|www\S+", "", text)
text = re.sub(r"<.*?>", "", text)
text = re.sub(r"[^\w\s\.\,\!\?\'\"-]", " ", text)
text = re.sub(r"\s+", " ", text).strip()
return text[:512]
# ── BERT Inference ────────────────────────────────────────────────────────────
def bert_predict(text):
cleaned = clean_text(text)
encoding = tokenizer(
cleaned,
max_length=MAX_LEN,
padding="max_length",
truncation=True,
return_tensors="pt",
)
input_ids = encoding["input_ids"].to(device)
attention_mask = encoding["attention_mask"].to(device)
with torch.no_grad():
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
probs = torch.softmax(outputs.logits, dim=1).cpu().numpy()[0]
# ⚠️ Model learned FLIPPED labels: idx1=Fake, idx0=Real
return float(probs[1]), float(probs[0])
# ── Heuristic Scoring ─────────────────────────────────────────────────────────
def heuristic_score(text):
text_lower = text.lower()
score = 0.0
details = []
phrase_count = sum(1 for p in CONSPIRACY_PHRASES if p in text_lower)
if phrase_count >= 3:
score += 0.40
details.append(f"Conspiracy phrases: {phrase_count}")
elif phrase_count >= 1:
score += 0.20
details.append(f"Conspiracy phrases: {phrase_count}")
alpha_chars = [c for c in text if c.isalpha()]
if alpha_chars:
caps_ratio = sum(1 for c in alpha_chars if c.isupper()) / len(alpha_chars)
if caps_ratio > 0.4:
score += 0.25
details.append(f"High caps ratio: {caps_ratio:.2f}")
elif caps_ratio > 0.25:
score += 0.10
details.append(f"Elevated caps ratio: {caps_ratio:.2f}")
words = text.split()
if words:
excl_density = text.count("!") / len(words)
if excl_density > 0.1:
score += 0.20
details.append(f"High exclamation density: {excl_density:.2f}")
elif excl_density > 0.05:
score += 0.10
details.append(f"Elevated exclamation density: {excl_density:.2f}")
return min(score, 1.0), details
# ── Ensemble Detection ────────────────────────────────────────────────────────
def detect_news(title, content):
title = str(title).strip() if title else ""
content = str(content).strip() if content else ""
text = f"{title}. {content}".strip()
if len(text) < 20:
return (
'<div style="color:#ff4444;padding:20px;text-align:center;">⚠️ Please provide at least 20 characters.</div>',
{"error": "Text too short"}
)
bert_fake, bert_real = bert_predict(text)
h_fake, h_details = heuristic_score(text)
combined_fake = (bert_fake * 0.85) + (h_fake * 0.15)
combined_real = 1.0 - combined_fake
if combined_fake >= 0.70:
verdict = "FAKE NEWS"
icon = "πŸ”΄"
color = "#FF3355"
glow = "#FF335544"
sub = "High probability of misinformation detected"
elif combined_fake >= 0.40:
verdict = "SUSPICIOUS"
icon = "🟑"
color = "#FFCC00"
glow = "#FFCC0044"
sub = "Mixed signals β€” verify from trusted sources"
else:
verdict = "REAL NEWS"
icon = "🟒"
color = "#00FF88"
glow = "#00FF8844"
sub = "Content appears credible and well-sourced"
confidence = max(combined_fake, combined_real) * 100
html = f"""
<div style="background:linear-gradient(135deg,#0d0d0d,#111);border-radius:20px;
padding:44px 40px 36px;text-align:center;font-family:Inter,sans-serif;
border:2px solid {color};box-shadow:0 0 50px {glow};max-width:660px;margin:0 auto;">
<div style="font-size:52px;margin-bottom:10px;">{icon}</div>
<div style="font-size:44px;font-weight:900;color:{color};letter-spacing:5px;
text-shadow:0 0 30px {glow};margin-bottom:6px;">{verdict}</div>
<div style="color:#777;font-size:14px;margin-bottom:30px;font-style:italic;">{sub}</div>
<div style="margin-bottom:26px;">
<div style="display:flex;justify-content:space-between;margin-bottom:8px;">
<span style="color:#aaa;font-size:11px;font-weight:700;letter-spacing:2px;">CONFIDENCE</span>
<span style="color:{color};font-size:13px;font-weight:800;">{confidence:.1f}%</span>
</div>
<div style="height:10px;background:#1a1a2e;border-radius:8px;overflow:hidden;">
<div style="width:{confidence}%;height:100%;background:linear-gradient(90deg,{color}88,{color});
border-radius:8px;box-shadow:0 0 12px {glow};"></div>
</div>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:20px;">
<div style="background:#1a1a2e;border-radius:12px;padding:16px;">
<div style="color:#aaa;font-size:10px;letter-spacing:2px;margin-bottom:6px;">BERT MODEL</div>
<div style="color:#FF3355;font-size:20px;font-weight:800;">Fake: {bert_fake*100:.1f}%</div>
<div style="color:#00FF88;font-size:14px;">Real: {bert_real*100:.1f}%</div>
</div>
<div style="background:#1a1a2e;border-radius:12px;padding:16px;">
<div style="color:#aaa;font-size:10px;letter-spacing:2px;margin-bottom:6px;">HEURISTIC</div>
<div style="color:#FF3355;font-size:20px;font-weight:800;">Risk: {h_fake*100:.1f}%</div>
<div style="color:#888;font-size:12px;margin-top:4px;">{'; '.join(h_details) if h_details else 'No red flags'}</div>
</div>
</div>
<div style="color:#555;font-size:11px;border-top:1px solid #222;padding-top:14px;">
Ensemble: BERT 85% + Heuristic 15% &nbsp;|&nbsp; Model: bert-base-uncased fine-tuned on WELFake
</div>
</div>
"""
json_data = {
"verdict": verdict.replace(" NEWS", ""),
"confidence": round(confidence, 2),
"fake_probability": round(combined_fake, 4),
"real_probability": round(combined_real, 4),
"bert_fake": round(bert_fake, 4),
"bert_real": round(bert_real, 4),
"heuristic_fake": round(h_fake, 4),
"heuristic_details": "; ".join(h_details) if h_details else "No red flags",
}
return html, json_data
# ── Gradio Interface ──────────────────────────────────────────────────────────
EXAMPLES = [
["NASA Confirms Giant Asteroid Will Destroy Earth on 25 December 2026!",
"World leaders secretly building underground shelters. Classified government documents leaked! They don't want you to know!"],
["Reserve Bank of India holds benchmark interest rate unchanged at 6.5 percent",
"The Monetary Policy Committee voted unanimously on Friday. Governor Das cited easing food inflation and stable growth outlook."],
["Bill Gates Admits Microchips in COVID Vaccines to Control Population",
"Underground sources confirm global conspiracy. Mainstream media hiding this bombshell! Banned video resurfaces!"],
["ISRO successfully launches NVS-02 navigation satellite",
"The satellite launched aboard GSLV-F15 from Sriharikota on January 29 2025, marking the 16th consecutive successful mission."],
]
with gr.Blocks(
title="🧠 Fake News Detector",
theme=gr.themes.Base(
primary_hue="cyan",
secondary_hue="green",
neutral_hue="slate",
font=gr.themes.GoogleFont("Inter"),
),
css=".gradio-container{max-width:800px!important}footer{display:none!important}",
) as demo:
gr.Markdown("""
# Misinformation Detection Using Deep Learning
### BERT-powered misinformation detection engine
Paste any news article text below and click **Analyze** to get an instant verdict.
""")
with gr.Column():
title_input = gr.Textbox(
label="πŸ“° Article Title",
placeholder="Enter the news headline here...",
lines=1, max_lines=3,
)
content_input = gr.Textbox(
label="πŸ“ Article Content",
placeholder="Paste the full news article text here...",
lines=6, max_lines=15,
)
analyze_btn = gr.Button("πŸ” Analyze Article", variant="primary", size="lg")
html_output = gr.HTML(label="Verdict")
json_output = gr.JSON(label="Detailed Results")
analyze_btn.click(
fn=detect_news,
inputs=[title_input, content_input],
outputs=[html_output, json_output],
api_name="predict" # ← endpoint: /gradio_api/call/predict
)
gr.Examples(examples=EXAMPLES, inputs=[title_input, content_input], label="πŸ“‹ Try an Example")
gr.Markdown("""
---
**Model**: `bert-base-uncased` fine-tuned on WELFake Dataset (72K articles)
&nbsp;|&nbsp; **Ensemble**: BERT 85% + Heuristic 15%
&nbsp;|&nbsp; **Built by**: Pankaj Kumar & Team
""")
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
# βœ… KEY FIX: Allow all origins so frontend HTML can call this API
share=False,
)