Spaces:
Running
Running
import streamlit as st | |
import torch | |
from transformers import AutoTokenizer, AutoModelForSequenceClassification | |
import requests | |
import json | |
st.set_page_config(page_title="News Prediction", page_icon=":earth_africa:") | |
# Load tokenizer and model | |
tokenizer = AutoTokenizer.from_pretrained("hamzab/roberta-fake-news-classification") | |
model = AutoModelForSequenceClassification.from_pretrained("hamzab/roberta-fake-news-classification") | |
from deep_translator import GoogleTranslator | |
def translate_to_english(text): | |
try: | |
return GoogleTranslator(source='auto', target='en').translate(text) | |
except Exception as e: | |
return f"Error in translation: {e}" | |
def predict_fake(title, text): | |
input_str = "<title>" + title + "<content>" + text + "<end>" | |
input_ids = tokenizer.encode_plus(input_str, max_length=512, padding="max_length", truncation=True, return_tensors="pt") | |
device = 'cuda' if torch.cuda.is_available() else 'cpu' | |
model.to(device) | |
with torch.no_grad(): | |
output = model(input_ids["input_ids"].to(device), attention_mask=input_ids["attention_mask"].to(device)) | |
return dict(zip(["Fake", "Real"], [x.item() for x in list(torch.nn.Softmax()(output.logits)[0])])) | |
def fact_check_with_google(api_key, query): | |
url = f"https://factchecktools.googleapis.com/v1alpha1/claims:search" | |
params = { | |
"query": query, | |
"key": api_key | |
} | |
response = requests.get(url, params=params) | |
if response.status_code == 200: | |
return response.json() | |
else: | |
return {"error": f"Unable to fetch results from Google Fact Check API. HTTP {response.status_code}: {response.text}"} | |
def main(): | |
st.title("Fake News Prediction") | |
# Load Google API key from a secure location or environment variable | |
# Create the form for user input | |
with st.form("news_form"): | |
st.subheader("Enter News Details") | |
title = st.text_input("Title") | |
text = st.text_area("Text") | |
language = st.selectbox("Select Language", options=["English", "Other"]) | |
submit_button = st.form_submit_button("Submit") | |
# Process form submission and make prediction | |
if submit_button: | |
if language == "Other": | |
title = translate_to_english(title) | |
text = translate_to_english(text) | |
prediction = predict_fake(title, text) | |
st.subheader("Prediction:") | |
st.write("Prediction: ", prediction) | |
if prediction.get("Real") > 0.5: | |
st.write("This news is predicted to be **real** :muscle:") | |
else: | |
st.write("This news is predicted to be **fake** :shit:") | |
if __name__ == "__main__": | |
main() | |