Download app.py from ma4389/Fake_Classification_Page_Public: direct link, hf CLI and curl.
- Browser
- Download file 1.28 kB
-
https://huggingface.co/spaces/ma4389/Fake_Classification_Page_Public/resolve/main/app.py
- Command line
-
hf download hf://spaces/ma4389/Fake_Classification_Page_Public/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ma4389/Fake_Classification_Page_Public/resolve/main/app.py
1.28 kB
| 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() | |