File size: 1,373 Bytes
124bd7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py

import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification

# Load model and tokenizer
model_name = "hamzab/roberta-fake-news-classification"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

# Prediction function
def predict_fake(title, text):
    input_str = f"<title>{title}<content>{text}<end>"
    inputs = tokenizer.encode_plus(
        input_str,
        max_length=512,
        padding="max_length",
        truncation=True,
        return_tensors="pt"
    )
    with torch.no_grad():
        outputs = model(
            inputs["input_ids"].to(device),
            attention_mask=inputs["attention_mask"].to(device)
        )
    probs = torch.nn.functional.softmax(outputs.logits, dim=1)[0]
    return {"Fake": float(probs[0]), "Real": float(probs[1])}

# Gradio interface
iface = gr.Interface(
    fn=predict_fake,
    inputs=[
        gr.Textbox(label="Title"),
        gr.Textbox(label="Content", lines=6)
    ],
    outputs=gr.Label(num_top_classes=2),
    title="Fake News Detector",
    description="Enter a news headline and content to classify as Real or Fake using a RoBERTa model."
)

if __name__ == "__main__":
    iface.launch()