Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,17 +3,17 @@ import torch
|
|
3 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
4 |
from deep_translator import GoogleTranslator
|
5 |
import requests
|
6 |
-
import
|
7 |
|
8 |
-
# Load
|
9 |
tokenizer = AutoTokenizer.from_pretrained("hamzab/roberta-fake-news-classification")
|
10 |
model = AutoModelForSequenceClassification.from_pretrained("hamzab/roberta-fake-news-classification")
|
11 |
|
12 |
-
|
13 |
-
summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
|
14 |
|
15 |
-
|
16 |
-
|
|
|
17 |
|
18 |
def translate_to_english(text):
|
19 |
try:
|
@@ -22,11 +22,10 @@ def translate_to_english(text):
|
|
22 |
return f"Error in translation: {e}"
|
23 |
|
24 |
def summarize_text(text):
|
25 |
-
|
26 |
-
summary = summarizer(text, max_length=
|
27 |
return summary[0]['summary_text']
|
28 |
-
|
29 |
-
return f"Error in summarization: {e}"
|
30 |
|
31 |
def predict_fake(title, text):
|
32 |
input_str = "<title>" + title + "<content>" + text + "<end>"
|
@@ -35,59 +34,109 @@ def predict_fake(title, text):
|
|
35 |
model.to(device)
|
36 |
with torch.no_grad():
|
37 |
output = model(input_ids["input_ids"].to(device), attention_mask=input_ids["attention_mask"].to(device))
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
def fact_check_with_google(api_key, query):
|
41 |
url = f"https://factchecktools.googleapis.com/v1alpha1/claims:search"
|
42 |
params = {"query": query, "key": api_key}
|
43 |
response = requests.get(url, params=params)
|
44 |
-
if response.status_code == 200:
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
else:
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
st.
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
st.info("No fact-check results found.")
|
91 |
-
|
92 |
-
if __name__ == "__main__":
|
93 |
-
main()
|
|
|
3 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
4 |
from deep_translator import GoogleTranslator
|
5 |
import requests
|
6 |
+
import plotly.graph_objects as go
|
7 |
|
8 |
+
# Load models
|
9 |
tokenizer = AutoTokenizer.from_pretrained("hamzab/roberta-fake-news-classification")
|
10 |
model = AutoModelForSequenceClassification.from_pretrained("hamzab/roberta-fake-news-classification")
|
11 |
|
12 |
+
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
|
|
13 |
|
14 |
+
st.set_page_config(page_title="Fake News Detector", page_icon="π°")
|
15 |
+
|
16 |
+
# --- Functions ---
|
17 |
|
18 |
def translate_to_english(text):
|
19 |
try:
|
|
|
22 |
return f"Error in translation: {e}"
|
23 |
|
24 |
def summarize_text(text):
|
25 |
+
if len(text) > 100:
|
26 |
+
summary = summarizer(text[:1024], max_length=80, min_length=30, do_sample=False)
|
27 |
return summary[0]['summary_text']
|
28 |
+
return text
|
|
|
29 |
|
30 |
def predict_fake(title, text):
|
31 |
input_str = "<title>" + title + "<content>" + text + "<end>"
|
|
|
34 |
model.to(device)
|
35 |
with torch.no_grad():
|
36 |
output = model(input_ids["input_ids"].to(device), attention_mask=input_ids["attention_mask"].to(device))
|
37 |
+
probs = torch.nn.Softmax(dim=1)(output.logits)[0]
|
38 |
+
return {"Fake": probs[0].item(), "Real": probs[1].item()}
|
39 |
+
|
40 |
+
def render_confidence_chart(confidence):
|
41 |
+
fig = go.Figure(data=[go.Pie(
|
42 |
+
values=[confidence, 100 - confidence],
|
43 |
+
labels=['Confidence', 'Uncertainty'],
|
44 |
+
hole=0.6,
|
45 |
+
marker_colors=[
|
46 |
+
f'hsl({confidence * 1.2}, 70%, 50%)',
|
47 |
+
'rgb(240, 240, 240)'
|
48 |
+
],
|
49 |
+
textinfo='label+percent',
|
50 |
+
hoverinfo='label+value'
|
51 |
+
)])
|
52 |
+
fig.update_layout(
|
53 |
+
showlegend=False,
|
54 |
+
margin=dict(t=10, b=10, l=10, r=10),
|
55 |
+
annotations=[dict(text=f'{confidence}%', x=0.5, y=0.5, font_size=20, showarrow=False)],
|
56 |
+
height=300
|
57 |
+
)
|
58 |
+
st.plotly_chart(fig, use_container_width=True)
|
59 |
+
|
60 |
+
def simulate_detected_patterns(text):
|
61 |
+
patterns = []
|
62 |
+
if "breaking" in text.lower():
|
63 |
+
patterns.append({"phrase": "breaking", "category": "clickbait", "impact": -5})
|
64 |
+
if "confirmed" in text.lower():
|
65 |
+
patterns.append({"word": "confirmed", "category": "assertive", "impact": 5})
|
66 |
+
if "shocking" in text.lower():
|
67 |
+
patterns.append({"word": "shocking", "category": "exaggeration", "impact": -10})
|
68 |
+
return patterns
|
69 |
|
70 |
def fact_check_with_google(api_key, query):
|
71 |
url = f"https://factchecktools.googleapis.com/v1alpha1/claims:search"
|
72 |
params = {"query": query, "key": api_key}
|
73 |
response = requests.get(url, params=params)
|
74 |
+
return response.json() if response.status_code == 200 else {"error": f"Error: {response.status_code}"}
|
75 |
+
|
76 |
+
# --- App UI ---
|
77 |
+
|
78 |
+
st.title("π° Fake News Detection App")
|
79 |
+
st.markdown("Enter a news article to predict its credibility and view confidence metrics.")
|
80 |
+
|
81 |
+
with st.form("news_form"):
|
82 |
+
title = st.text_input("π Title")
|
83 |
+
text = st.text_area("π Content")
|
84 |
+
language = st.selectbox("π Language of Input", ["English", "Other"])
|
85 |
+
summarize_option = st.checkbox("π§ Summarize before fact check")
|
86 |
+
check_fact = st.checkbox("π Check with Google Fact Check")
|
87 |
+
GOOGLE_API_KEY = st.text_input("π Google API Key (optional)", type="password")
|
88 |
+
submit_button = st.form_submit_button("π Predict")
|
89 |
+
|
90 |
+
if submit_button:
|
91 |
+
if language != "English":
|
92 |
+
title = translate_to_english(title)
|
93 |
+
text = translate_to_english(text)
|
94 |
+
|
95 |
+
if summarize_option:
|
96 |
+
summary = summarize_text(title + " " + text)
|
97 |
+
st.markdown("### βοΈ Summary Used for Fact Check")
|
98 |
+
st.info(summary)
|
99 |
else:
|
100 |
+
summary = title + " " + text
|
101 |
+
|
102 |
+
prediction = predict_fake(title, text)
|
103 |
+
confidence = round(prediction["Real"] * 100)
|
104 |
+
verdict = "Real" if confidence > 60 else "Fake" if confidence < 40 else "Uncertain"
|
105 |
+
color = "green" if verdict == "Real" else "red" if verdict == "Fake" else "orange"
|
106 |
+
|
107 |
+
# Output
|
108 |
+
st.subheader("β
Prediction Result")
|
109 |
+
st.markdown(f"""
|
110 |
+
<div style='background-color:#f7f9fc;padding:1rem;border-radius:10px'>
|
111 |
+
<b>Verdict:</b> <span style='color:{color}; font-weight:600'>{verdict}</span><br>
|
112 |
+
<b>Confidence:</b> {confidence}%
|
113 |
+
</div>
|
114 |
+
""", unsafe_allow_html=True)
|
115 |
+
|
116 |
+
render_confidence_chart(confidence)
|
117 |
+
|
118 |
+
# Detected Patterns
|
119 |
+
patterns = simulate_detected_patterns(title + " " + text)
|
120 |
+
if patterns:
|
121 |
+
st.subheader("π Detected Language Patterns")
|
122 |
+
for p in patterns:
|
123 |
+
word = p.get("word") or p.get("phrase")
|
124 |
+
st.markdown(f"- **{word}** ({p['category']}) β "
|
125 |
+
f"<span style='color:{'green' if p['impact']>0 else 'red'};'>{p['impact']:+}</span>",
|
126 |
+
unsafe_allow_html=True)
|
127 |
+
|
128 |
+
GOOGLE_API_KEY = "AIzaSyAf5v5380xkpo0Rk3kBiSxpxYVBQwcDi2A"
|
129 |
+
# Google Fact Check
|
130 |
+
if check_fact and GOOGLE_API_KEY:
|
131 |
+
st.subheader("π Google Fact Check Results")
|
132 |
+
facts = fact_check_with_google(GOOGLE_API_KEY, summary)
|
133 |
+
if "claims" in facts:
|
134 |
+
for claim in facts["claims"]:
|
135 |
+
st.markdown(f"**Claim:** {claim.get('text', 'N/A')}")
|
136 |
+
for review in claim.get("claimReview", []):
|
137 |
+
st.write(f"- **Publisher**: {review.get('publisher', {}).get('name', 'N/A')}")
|
138 |
+
st.write(f"- **Rating**: {review.get('textualRating', 'N/A')}")
|
139 |
+
st.write(f"- **URL**: {review.get('url', 'N/A')}")
|
140 |
+
st.write("---")
|
141 |
+
else:
|
142 |
+
st.warning("No fact-check results found.")
|
|
|
|
|
|
|
|