NoNewsLite is a deep learning model designed to classify news articles as either real or fake. It uses a Bidirectional LSTM with Attention architecture trained on the ISOT Fake News Dataset. The model analyzes text from news titles and content to predict authenticity with high accuracy.
The attention mechanism allows the model to explain its decisions by showing which words contributed most to the final prediction.
1pip install torch nltk gradio scikit-learn pandas numpy
2
3# Run this script to start the demo
4import gradio as gr
5import torch
6import json
7import re
8from nltk.corpus import stopwords
9from nltk.tokenize import word_tokenize
10
11# Load vocabulary
12with open("vocab.json", "r") as f:
13 word2idx = json.load(f)
14
15# Define model architecture (see full implementation above)
16class BiLSTM_Attention(nn.Module):
17 # ... (model definition as provided earlier)
18 pass
19
20# Load model weights
21device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
22model = BiLSTM_Attention(vocab_size=len(word2idx)).to(device)
23model.load_state_dict(torch.load("pytorch_model.bin", map_location=device))
24model.eval()
25
26# Text preprocessing functions
27def clean_and_preprocess_text(title, text):
28 combined = f"{title} {text}".lower()
29 combined = re.sub(r'https?://\S+|www\.\S+', '', combined)
30 combined = re.sub(r'<.*?>', '', combined)
31 combined = re.sub(r'[^a-zA-Z\s]', '', combined)
32 combined = re.sub(r'\s+', ' ', combined).strip()
33 tokens = word_tokenize(combined)
34 tokens = [word for word in tokens if word not in stopwords.words('english')]
35 return ' '.join(tokens)
36
37def text_to_sequence(text, word2idx, max_len=512):
38 tokens = text.split()
39 seq = [word2idx.get(word, word2idx["<UNK>"]) for word in tokens]
40 if len(seq) > max_len:
41 seq = seq[:max_len]
42 else:
43 pad_token = word2idx["<PAD>"]
44 seq += [pad_token] * (max_len - len(seq))
45 return torch.tensor(seq, dtype=torch.long).unsqueeze(0)
46
47def predict(title, text):
48 cleaned = clean_and_preprocess_text(title, text)
49 seq = text_to_sequence(cleaned, word2idx)
50 seq = seq.to(device)
51
52 with torch.no_grad():
53 output, _ = model(seq)
54 prob = output.item()
55 prediction = "Real News" if prob > 0.5 else "Fake News"
56 confidence = prob if prob > 0.5 else 1 - prob
57
58 return f"**Prediction:** {prediction}\n\n**Confidence:** {confidence:.2%}"
59
60# Launch Gradio interface
61demo = gr.Interface(
62 fn=predict,
63 inputs=[
64 gr.Textbox(placeholder="Enter news title...", label="Title"),
65 gr.Textbox(placeholder="Enter news content...", label="Content", lines=6)
66 ],
67 outputs=gr.Markdown(label="Result"),
68 title="🔍 NoNewsLite: Fake News Detection",
69 description="Enter a news article's title and content to detect if it's real or fake using a Bi-LSTM with Attention.",
70
71 examples=[
72 ["Donald Trump Dies in Car Crash", "Breaking news: Former President Donald Trump has died in a tragic accident."],
73 ["U.S. Republicans Flip Fiscal Script", "The Republican party has reversed its long-standing opposition to deficit spending."]
74 ],
75 theme="default"
76)
77
78demo.launch(share=True) # Generates a public link
79
80 or local inference with
81
82# Example usage
83title = "Scientists Confirm Climate Change Is Real"
84text = "New study shows global temperatures rising due to greenhouse gas emissions."
85
86result = predict(title, text)
87print(result)