Spaces:
Sleeping
Sleeping
Download app.py from pankajkr07/FAKENEWSDETECTOR: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/spaces/pankajkr07/FAKENEWSDETECTOR/resolve/main/app.py
- Command line
-
hf download hf://spaces/pankajkr07/FAKENEWSDETECTOR/app.py
-
curl -L -o app.py https://huggingface.co/spaces/pankajkr07/FAKENEWSDETECTOR/resolve/main/app.py
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% | 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) | |
| | **Ensemble**: BERT 85% + Heuristic 15% | |
| | **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, | |
| ) |