File size: 1,279 Bytes
f10dbd8 |
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 |
import torch
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
import gradio as gr
# Load tokenizer and model
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', num_labels=2)
model.load_state_dict(torch.load('best_model (4).pth', map_location=torch.device('cpu')))
model.eval()
# Prediction function
def classify_news(text):
inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True, max_length=512)
with torch.no_grad():
outputs = model(**inputs)
probs = torch.nn.functional.softmax(outputs.logits, dim=1)
predicted_class = torch.argmax(probs, dim=1).item()
labels = ["Fake", "True"]
return {labels[0]: float(probs[0][0]), labels[1]: float(probs[0][1])}
# Gradio interface
iface = gr.Interface(
fn=classify_news,
inputs=gr.Textbox(lines=10, placeholder="Paste a news article here..."),
outputs=gr.Label(num_top_classes=2),
title="Fake News Detector",
description="Detect whether a news article is real or fake using a fine-tuned DistilBERT model."
)
# Launch the app
if __name__ == "__main__":
iface.launch()
|