manasagangotri commited on
Commit
2873ab7
·
verified ·
1 Parent(s): 7ac347d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -98
app.py CHANGED
@@ -1,19 +1,19 @@
1
  import streamlit as st
2
  import torch
3
- from transformers import AutoTokenizer, AutoModelForSequenceClassification,pipeline
4
-
5
  import requests
6
- import json
7
-
8
 
9
- st.set_page_config(page_title="News Prediction", page_icon=":earth_africa:")
10
-
11
- # Load tokenizer and model
12
  tokenizer = AutoTokenizer.from_pretrained("hamzab/roberta-fake-news-classification")
13
  model = AutoModelForSequenceClassification.from_pretrained("hamzab/roberta-fake-news-classification")
14
 
 
 
15
 
16
- from deep_translator import GoogleTranslator
 
17
 
18
  def translate_to_english(text):
19
  try:
@@ -21,7 +21,12 @@ def translate_to_english(text):
21
  except Exception as e:
22
  return f"Error in translation: {e}"
23
 
24
-
 
 
 
 
 
25
 
26
  def predict_fake(title, text):
27
  input_str = "<title>" + title + "<content>" + text + "<end>"
@@ -34,111 +39,46 @@ def predict_fake(title, text):
34
 
35
  def fact_check_with_google(api_key, query):
36
  url = f"https://factchecktools.googleapis.com/v1alpha1/claims:search"
37
- params = {
38
- "query": query,
39
- "key": api_key
40
- }
41
  response = requests.get(url, params=params)
42
  if response.status_code == 200:
43
  return response.json()
44
  else:
45
- return {"error": f"Unable to fetch results from Google Fact Check API. HTTP {response.status_code}: {response.text}"}
46
-
47
- '''def main():
48
- st.title("Fake News Prediction")
49
-
50
- # Load Google API key from a secure location or environment variable
51
-
52
-
53
- # Create the form for user input
54
- with st.form("news_form"):
55
- st.subheader("Enter News Details")
56
- title = st.text_input("Title")
57
- text = st.text_area("Text")
58
- language = st.selectbox("Select Language", options=["English", "Other"])
59
- submit_button = st.form_submit_button("Submit")
60
-
61
- # Process form submission and make prediction
62
- if submit_button:
63
- if language == "Other":
64
- title = translate_to_english(title)
65
- text = translate_to_english(text)
66
-
67
- prediction = predict_fake(title, text)
68
-
69
- st.subheader("Prediction:")
70
- st.write("Prediction: ", prediction)
71
-
72
- if prediction.get("Real") > 0.5:
73
- st.write("This news is predicted to be **real** :muscle:")
74
- else:
75
- st.write("This news is predicted to be **fake** :shit:")
76
-
77
- '''
78
- # Load summarizer
79
- @st.cache_resource
80
- def load_summarizer():
81
- return pipeline("summarization", model="facebook/bart-large-cnn")
82
-
83
- summarizer = load_summarizer()
84
-
85
-
86
-
87
- def summarize_text(text):
88
- try:
89
- summary = summarizer(text, max_length=30, min_length=5, do_sample=False)
90
- return summary[0]['summary_text']
91
- except Exception as e:
92
- return f"Error in summarization: {e}"
93
-
94
 
95
  def main():
96
- st.title("Fake News Prediction")
97
-
98
- # Store your API key here or load from environment variable
99
- GOOGLE_API_KEY = "AIzaSyAf5v5380xkpo0Rk3kBiSxpxYVBQwcDi2A" # 🔐 Replace this!
100
 
101
  with st.form("news_form"):
102
- st.subheader("Enter News Details")
103
- title = st.text_input("Title")
104
- text = st.text_area("Text")
105
- language = st.selectbox("Select Language", options=["English", "Other"])
106
- check_fact = st.checkbox("Also check with Google Fact Check API")
107
- submit_button = st.form_submit_button("Submit")
108
 
109
  if submit_button:
110
  if language == "Other":
111
  title = translate_to_english(title)
112
  text = translate_to_english(text)
113
-
114
  prediction = predict_fake(title, text)
115
 
116
- st.subheader("Prediction:")
117
- st.write("Prediction: ", prediction)
118
-
119
- if prediction.get("Real") > 0.5:
120
- st.write("This news is predicted to be **real** :muscle:")
121
- else:
122
- st.write("This news is predicted to be **fake** :shit:")
123
-
124
 
125
  if check_fact and GOOGLE_API_KEY:
126
- st.subheader("Google Fact Check Results")
127
-
128
- # Optional: user-provided claim input
129
- # custom_claim = st.text_input("Optional: Enter a specific claim to fact-check", "")
130
- # query = custom_claim if custom_claim else title # Use custom claim if provided
131
- summarized_claim = summarize_text(title)
132
- st.info(f"🔍 Fact check query (summarized): **{summarized_claim}**")
133
-
134
- fact_check_data = fact_check_with_google(GOOGLE_API_KEY, summarized_claim)
135
-
136
- # Optional: show raw data for debugging
137
- # st.json(fact_check_data)
138
-
139
 
 
 
 
140
 
141
- if "claims" in fact_check_data and len(fact_check_data["claims"]) > 0:
142
  for claim in fact_check_data["claims"]:
143
  st.markdown(f"**Claim:** {claim.get('text', 'N/A')}")
144
  for review in claim.get("claimReview", []):
@@ -147,9 +87,7 @@ def main():
147
  st.write(f"- **URL**: {review.get('url', 'N/A')}")
148
  st.write("---")
149
  else:
150
- st.warning("No fact-check results found. Try changing the title or query.")
151
 
152
-
153
  if __name__ == "__main__":
154
  main()
155
-
 
1
  import streamlit as st
2
  import torch
3
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
4
+ from deep_translator import GoogleTranslator
5
  import requests
6
+ import os
 
7
 
8
+ # Load tokenizer and fake news model
 
 
9
  tokenizer = AutoTokenizer.from_pretrained("hamzab/roberta-fake-news-classification")
10
  model = AutoModelForSequenceClassification.from_pretrained("hamzab/roberta-fake-news-classification")
11
 
12
+ # Load summarizer pipeline
13
+ summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
14
 
15
+ # Google Fact Check API key (replace with your actual key or use st.secrets)
16
+ GOOGLE_API_KEY = "AIzaSyAf5v5380xkpo0Rk3kBiSxpxYVBQwcDi2A"
17
 
18
  def translate_to_english(text):
19
  try:
 
21
  except Exception as e:
22
  return f"Error in translation: {e}"
23
 
24
+ def summarize_text(text):
25
+ try:
26
+ summary = summarizer(text, max_length=60, min_length=15, do_sample=False)
27
+ return summary[0]['summary_text']
28
+ except Exception as e:
29
+ return f"Error in summarization: {e}"
30
 
31
  def predict_fake(title, text):
32
  input_str = "<title>" + title + "<content>" + text + "<end>"
 
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
  return response.json()
46
  else:
47
+ return {"error": f"Unable to fetch fact-checks. HTTP {response.status_code}: {response.text}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  def main():
50
+ st.set_page_config(page_title="News Credibility Checker", page_icon="🧠")
51
+ st.title("🧠 Fake News Detection & Fact Check")
 
 
52
 
53
  with st.form("news_form"):
54
+ title = st.text_input("News Title")
55
+ text = st.text_area("News Content")
56
+ language = st.selectbox("Select Language", ["English", "Other"])
57
+ check_fact = st.checkbox("Check with Google Fact Check API")
58
+ submit_button = st.form_submit_button("Analyze")
 
59
 
60
  if submit_button:
61
  if language == "Other":
62
  title = translate_to_english(title)
63
  text = translate_to_english(text)
64
+
65
  prediction = predict_fake(title, text)
66
 
67
+ st.subheader("Prediction Result:")
68
+ st.write("Prediction Score:", prediction)
69
+ verdict = "real" if prediction.get("Real") > 0.5 else "fake"
70
+ st.success(f"This news is predicted to be **{verdict}**.")
 
 
 
 
71
 
72
  if check_fact and GOOGLE_API_KEY:
73
+ # Generate summary for fact-checking
74
+ summary_text = summarize_text(title + ". " + text)
75
+ st.markdown("**Fact-check Query (Summary):** " + summary_text)
 
 
 
 
 
 
 
 
 
 
76
 
77
+ # Call Google Fact Check API
78
+ fact_check_data = fact_check_with_google(GOOGLE_API_KEY, summary_text)
79
+ st.subheader("Google Fact Check Results")
80
 
81
+ if "claims" in fact_check_data:
82
  for claim in fact_check_data["claims"]:
83
  st.markdown(f"**Claim:** {claim.get('text', 'N/A')}")
84
  for review in claim.get("claimReview", []):
 
87
  st.write(f"- **URL**: {review.get('url', 'N/A')}")
88
  st.write("---")
89
  else:
90
+ st.info("No fact-check results found.")
91
 
 
92
  if __name__ == "__main__":
93
  main()