File size: 11,483 Bytes
5ef9a99
26fb31d
5ef9a99
 
 
3ed3f31
5ef9a99
 
 
 
 
3ed3f31
5ef9a99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ed3f31
5ef9a99
 
 
 
 
 
 
 
3ed3f31
5ef9a99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5e2e1e
911958d
5ef9a99
3ed3f31
5ef9a99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ed3f31
5ef9a99
 
 
 
 
 
 
3ed3f31
 
5ef9a99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ed3f31
5ef9a99
3ed3f31
 
 
 
 
 
 
 
5ef9a99
 
 
 
 
 
 
 
 
 
3ed3f31
5ef9a99
3ed3f31
26fb31d
5ef9a99
 
3ed3f31
5ef9a99
 
 
 
 
3ed3f31
5ef9a99
 
 
 
3ed3f31
5ef9a99
 
 
 
 
 
3ed3f31
 
5ef9a99
3ed3f31
 
5ef9a99
 
3ed3f31
 
 
5ef9a99
 
 
 
3ed3f31
5ef9a99
 
3ed3f31
 
 
 
 
 
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
"""
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,
    )