Abs6187 commited on
Commit
edc611c
Β·
verified Β·
1 Parent(s): bc6c25c

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +241 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,243 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
1
+ import os
 
 
2
  import streamlit as st
3
+ import google.generativeai as genai
4
+ from dotenv import load_dotenv
5
+ from PIL import Image
6
+ import pandas as pd
7
+ import numpy as np
8
+ from typing import Dict, Any, List
9
+
10
+ # Load environment variables
11
+ load_dotenv()
12
+
13
+ # Configure Google Generative AI
14
+ genai.configure(api_key=os.getenv('GOOGLE_API_KEY'))
15
+
16
+ # Page Configuration
17
+ st.set_page_config(
18
+ page_title="Advanced Fake News Detector πŸ•΅οΈβ€β™€οΈ",
19
+ page_icon="🚨",
20
+ layout="wide"
21
+ )
22
+
23
+ # Custom CSS
24
+ st.markdown("""
25
+ <style>
26
+ .main-container {
27
+ background-color: #f0f2f6;
28
+ padding: 2rem;
29
+ border-radius: 15px;
30
+ }
31
+ .analysis-box {
32
+ background-color: white;
33
+ border-radius: 10px;
34
+ padding: 1.5rem;
35
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
36
+ }
37
+ .stButton>button {
38
+ background-color: #4CAF50;
39
+ color: white;
40
+ font-weight: bold;
41
+ border: none;
42
+ padding: 10px 20px;
43
+ border-radius: 5px;
44
+ transition: all 0.3s ease;
45
+ }
46
+ .stButton>button:hover {
47
+ background-color: #45a049;
48
+ transform: scale(1.05);
49
+ }
50
+ </style>
51
+ """, unsafe_allow_html=True)
52
+
53
+ class FakeNewsDetector:
54
+ def __init__(self):
55
+ """Initialize the Fake News Detection system"""
56
+ self.model = genai.GenerativeModel('gemini-2.0-flash')
57
+
58
+ def analyze_article(self, article_text: str) -> Dict[str, Any]:
59
+ """
60
+ Analyze the article using Gemini AI
61
+
62
+ Args:
63
+ article_text (str): Full text of the article
64
+
65
+ Returns:
66
+ Dict containing analysis results
67
+ """
68
+ prompt = f"""Comprehensive Fake News Analysis:
69
+
70
+ Article Text:
71
+ {article_text}
72
+
73
+ Provide a detailed analysis with:
74
+ 1. Fake News Probability (0-100%)
75
+ 2. Credibility Score (0-10)
76
+ 3. Key Red Flags
77
+ 4. Verification Recommendations
78
+ 5. Potential Bias Indicators
79
+ 6. Source Reliability Assessment
80
+
81
+ Format response as a structured JSON."""
82
+
83
+ try:
84
+ response = self.model.generate_content(prompt)
85
+ return self._parse_analysis(response.text)
86
+ except Exception as e:
87
+ st.error(f"Analysis Error: {e}")
88
+ return {}
89
+
90
+ def _parse_analysis(self, analysis_text: str) -> Dict[str, Any]:
91
+ """
92
+ Parse the AI-generated analysis into a structured format
93
+
94
+ Args:
95
+ analysis_text (str): Raw analysis text
96
+
97
+ Returns:
98
+ Parsed analysis dictionary
99
+ """
100
+ try:
101
+ # Basic parsing logic (can be enhanced)
102
+ return {
103
+ 'fake_news_probability': self._extract_percentage(analysis_text),
104
+ 'credibility_score': self._extract_score(analysis_text),
105
+ 'red_flags': self._extract_red_flags(analysis_text),
106
+ 'verification_steps': self._extract_verification_steps(analysis_text),
107
+ 'bias_indicators': self._extract_bias_indicators(analysis_text),
108
+ 'source_reliability': self._extract_source_reliability(analysis_text)
109
+ }
110
+ except Exception as e:
111
+ st.warning(f"Parsing Error: {e}")
112
+ return {}
113
+
114
+ def _extract_percentage(self, text: str) -> float:
115
+ """Extract fake news probability percentage"""
116
+ import re
117
+ match = re.search(r'(\d+(?:\.\d+)?)\s*%', text)
118
+ return float(match.group(1)) if match else 50.0
119
+
120
+ def _extract_score(self, text: str) -> float:
121
+ """Extract credibility score"""
122
+ import re
123
+ match = re.search(r'Credibility Score[:\s]*(\d+(?:\.\d+)?)', text)
124
+ return float(match.group(1)) if match else 5.0
125
+
126
+ def _extract_red_flags(self, text: str) -> List[str]:
127
+ """Extract red flags from the analysis"""
128
+ import re
129
+ flags = re.findall(r'Red Flags?[:\s]*([^\n]+)', text, re.IGNORECASE)
130
+ return flags[:3] if flags else ["No specific red flags identified"]
131
+
132
+ def _extract_verification_steps(self, text: str) -> List[str]:
133
+ """Extract verification recommendations"""
134
+ import re
135
+ steps = re.findall(r'Verification[:\s]*([^\n]+)', text, re.IGNORECASE)
136
+ return steps[:3] if steps else ["Conduct independent research"]
137
+
138
+ def _extract_bias_indicators(self, text: str) -> List[str]:
139
+ """Extract potential bias indicators"""
140
+ import re
141
+ biases = re.findall(r'Bias[:\s]*([^\n]+)', text, re.IGNORECASE)
142
+ return biases[:3] if biases else ["No clear bias detected"]
143
+
144
+ def _extract_source_reliability(self, text: str) -> str:
145
+ """Extract source reliability assessment"""
146
+ import re
147
+ match = re.search(r'Source Reliability[:\s]*([^\n]+)', text, re.IGNORECASE)
148
+ return match.group(1) if match else "Reliability not conclusively determined"
149
+
150
+ def main():
151
+ st.title("🚨 Advanced Fake News Detector")
152
+ st.markdown("Powered by Google's Gemini 2.0 Flash AI")
153
+
154
+ # Sidebar Configuration
155
+ st.sidebar.header("πŸ› οΈ Detection Settings")
156
+ confidence_threshold = st.sidebar.slider(
157
+ "Confidence Threshold",
158
+ min_value=0.0,
159
+ max_value=1.0,
160
+ value=0.7,
161
+ step=0.05
162
+ )
163
+
164
+ # Article Input
165
+ st.header("πŸ“ Article Analysis")
166
+ article_text = st.text_area(
167
+ "Paste the full article text",
168
+ height=300,
169
+ help="Copy and paste the complete article for comprehensive analysis"
170
+ )
171
+
172
+ # Image Upload (Optional)
173
+ st.header("πŸ–ΌοΈ Article Evidence")
174
+ uploaded_image = st.file_uploader(
175
+ "Upload supporting/source image",
176
+ type=['png', 'jpg', 'jpeg'],
177
+ help="Optional: Upload an image related to the article for additional context"
178
+ )
179
+
180
+ # Analyze Button
181
+ if st.button("πŸ” Detect Fake News", key="analyze_btn"):
182
+ if not article_text:
183
+ st.error("Please provide an article to analyze.")
184
+ return
185
+
186
+ # Initialize Detector
187
+ detector = FakeNewsDetector()
188
+
189
+ # Perform Analysis
190
+ with st.spinner('Analyzing article...'):
191
+ analysis = detector.analyze_article(article_text)
192
+
193
+ # Display Results
194
+ if analysis:
195
+ st.subheader("πŸ”¬ Detailed Analysis")
196
+
197
+ # Credibility Visualization
198
+ col1, col2, col3 = st.columns(3)
199
+
200
+ with col1:
201
+ st.metric(
202
+ "Fake News Probability",
203
+ f"{analysis.get('fake_news_probability', 50):.2f}%"
204
+ )
205
+
206
+ with col2:
207
+ st.metric(
208
+ "Credibility Score",
209
+ f"{analysis.get('credibility_score', 5):.2f}/10"
210
+ )
211
+
212
+ with col3:
213
+ st.metric(
214
+ "Risk Level",
215
+ "High" if analysis.get('fake_news_probability', 50) > 50 else "Low"
216
+ )
217
+
218
+ # Detailed Insights
219
+ st.subheader("🚩 Red Flags")
220
+ for flag in analysis.get('red_flags', []):
221
+ st.warning(flag)
222
+
223
+ st.subheader("πŸ•΅οΈ Verification Steps")
224
+ for step in analysis.get('verification_steps', []):
225
+ st.info(step)
226
+
227
+ # Image Analysis (if uploaded)
228
+ if uploaded_image:
229
+ image = Image.open(uploaded_image)
230
+ st.subheader("πŸ“Έ Uploaded Image")
231
+ st.image(image, caption="Article Supporting Image", use_column_width=True)
232
+
233
+ # Final Recommendation
234
+ st.markdown("---")
235
+ st.markdown("""
236
+ ### πŸ€” How to Interpret Results
237
+ - **Low Probability**: Article seems credible
238
+ - **High Probability**: Exercise caution, verify sources
239
+ - **Always cross-reference with multiple sources**
240
+ """)
241
 
242
+ if __name__ == "__main__":
243
+ main()