benjamin5607 commited on
Commit
91b6080
Β·
verified Β·
1 Parent(s): fa1297d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -19
app.py CHANGED
@@ -35,9 +35,12 @@ REGION_MAP = {
35
 
36
  # --- 4. Helper Functions ---
37
  def fetch_google_news(query, geo="US", limit=35, period="7d"):
 
 
 
38
  time_filter = f" when:{period}"
39
  encoded = urllib.parse.quote(query + time_filter)
40
- url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl=geo}&ceid={geo}:en"
41
  feed = feedparser.parse(url)
42
  articles = []
43
  for e in feed.entries[:limit]:
@@ -59,7 +62,7 @@ def create_download_link(data, filename="Full_Strategic_Intel.txt"):
59
  report_text += f"SOCIAL IMPACT: {item.get('social_impact', 'N/A')}\n"
60
  report_text += f"TACTICAL ACTION PLAN: {item.get('tactical_action', 'N/A')}\n\n"
61
  b64 = base64.b64encode(report_text.encode()).decode()
62
- return f'<a href="data:file/txt;base64,{b64}" download="{filename}"><button style="background-color:#FF4B4B; color:white; border:none; padding:10px 20px; border-radius:5px; cursor:pointer;">πŸ“₯ Download Full Report (.txt)</button></a>'
63
 
64
  # --- 5. 🚨 Main Dashboard: WAR ROOM (12h Filter) ---
65
  st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
@@ -96,7 +99,7 @@ with tab1:
96
  st.subheader("Global Risk Propagation & Strategic Market Insight")
97
  col_k1, col_k2 = st.columns([3, 1])
98
  with col_k1:
99
- keyword = st.text_input("Enter Issue Keyword (7d Deep Scan)", "Cyber Warfare")
100
  selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
101
  with col_k2:
102
  st.write("")
@@ -118,23 +121,23 @@ with tab1:
118
 
119
  with st.spinner("Synthesizing Full Spectrum Global Report..."):
120
  news_summary = "\n".join([f"- {n['title']}" for n in all_news_tab1[:25]])
121
- # Double curly braces {{ }} to avoid f-string error
122
  market_prompt = f"""
123
- Analyze '{keyword}' based on provided news. Report must be in English.
124
  Return ONLY JSON:
125
  {{
126
  "global_summary": "Detailed narrative (300+ words) on propagation trends.",
127
  "risk_factors": {{
128
- "Target_Demographics": "Detailed target group analysis...",
129
  "Guideline_Violation": "Relevant policy breaches...",
130
  "Social_Impact": "Wider societal consequences...",
131
- "Action_Summary": "Primary recommendation..."
132
  }},
133
  "platform_analysis": {{
134
- "TikTok": "Strategic insight...",
135
- "YouTube": "Strategic insight...",
136
- "Meta": "Strategic insight...",
137
- "X": "Strategic insight..."
138
  }}
139
  }}
140
  """
@@ -146,19 +149,19 @@ with tab1:
146
  st.table(pd.DataFrame(g_data.get('risk_factors', {{}}).items(), columns=["Metric", "Intelligence Insight"]))
147
  st.markdown("### πŸ“± Platform Tactical Recommendations")
148
  st.table(pd.DataFrame(g_data.get('platform_analysis', {{}}).items(), columns=["Platform", "Strategic Insight"]))
149
- except Exception as e: st.error(f"Synthesis error: {{e}}")
150
 
151
  # --- [Tab 2: National Forensics - ALL ANALYTICAL FIELDS APPLIED] ---
152
  with tab2:
153
  st.subheader("National Tactical Intelligence (Verified Evidence)")
154
  c1, c2 = st.columns([1, 4])
155
  with c1:
156
- target_geo = st.text_input("ISO Country Code", "KR").upper()
157
  btn_deep = st.button("Generate National Report", type="primary")
158
 
159
  if btn_deep:
160
  with st.status(f"Generating Deep-Dive for {target_geo} (7d Evidence)...", expanded=True):
161
- news = fetch_google_news(f"{target_geo} risk controversy", geo=target_geo, limit=35, period="7d")
162
  news_context = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(news)])
163
 
164
  system_prompt = f"""
@@ -183,7 +186,7 @@ with tab2:
183
  if report_data:
184
  st.markdown(create_download_link(report_data, f"{target_geo}_Full_Report.txt"), unsafe_allow_html=True)
185
  for r in report_data:
186
- with st.expander(f"🚩 RANK {r.get('rank')}: {r.get('title')} (Risk: {r.get('score')})"):
187
  st.markdown(f"**Detailed Analysis:**\n{r.get('summary')}")
188
  st.table(pd.DataFrame({
189
  "Category": ["Violation", "Target Group", "Social Impact", "Tactical Action"],
@@ -191,14 +194,16 @@ with tab2:
191
  }))
192
 
193
  st.divider()
194
- st.subheader("πŸ“° Underlying Evidence Feed (7-Day)")
195
- st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
 
 
196
 
197
  # --- [Tab 3: Risk Velocity Trend] ---
198
  with tab3:
199
  st.subheader("πŸ“ˆ Risk Velocity Trend (Last 7 Days)")
200
- trend_key = st.text_input("Trend Keyword", "Election Integrity")
201
  if st.button("Analyze Velocity"):
202
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
203
- scores = [10, 25, 50, 80, 95, 92, 85]
204
  st.plotly_chart(px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity: {trend_key}"), use_container_width=True)
 
35
 
36
  # --- 4. Helper Functions ---
37
  def fetch_google_news(query, geo="US", limit=35, period="7d"):
38
+ """
39
+ Fixed f-string syntax error: gl={geo} instead of gl=geo}
40
+ """
41
  time_filter = f" when:{period}"
42
  encoded = urllib.parse.quote(query + time_filter)
43
+ url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl={geo}&ceid={geo}:en"
44
  feed = feedparser.parse(url)
45
  articles = []
46
  for e in feed.entries[:limit]:
 
62
  report_text += f"SOCIAL IMPACT: {item.get('social_impact', 'N/A')}\n"
63
  report_text += f"TACTICAL ACTION PLAN: {item.get('tactical_action', 'N/A')}\n\n"
64
  b64 = base64.b64encode(report_text.encode()).decode()
65
+ return f'<a href="data:file/txt;base64,{b64}" download="{filename}" style="text-decoration:none;"><button style="background-color:#FF4B4B; color:white; border:none; padding:10px 20px; border-radius:5px; cursor:pointer;">πŸ“₯ Download Full Report (.txt)</button></a>'
66
 
67
  # --- 5. 🚨 Main Dashboard: WAR ROOM (12h Filter) ---
68
  st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
 
99
  st.subheader("Global Risk Propagation & Strategic Market Insight")
100
  col_k1, col_k2 = st.columns([3, 1])
101
  with col_k1:
102
+ keyword = st.text_input("Enter Issue Keyword (7d Deep Scan)", "Deepfake Propaganda")
103
  selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
104
  with col_k2:
105
  st.write("")
 
121
 
122
  with st.spinner("Synthesizing Full Spectrum Global Report..."):
123
  news_summary = "\n".join([f"- {n['title']}" for n in all_news_tab1[:25]])
124
+ # Fixed double curly braces {{ }}
125
  market_prompt = f"""
126
+ Analyze '{keyword}' in English based on news.
127
  Return ONLY JSON:
128
  {{
129
  "global_summary": "Detailed narrative (300+ words) on propagation trends.",
130
  "risk_factors": {{
131
+ "Target_Demographics": "Detailed group analysis...",
132
  "Guideline_Violation": "Relevant policy breaches...",
133
  "Social_Impact": "Wider societal consequences...",
134
+ "Action_Summary": "Strategic recommendation..."
135
  }},
136
  "platform_analysis": {{
137
+ "TikTok": "Tactical action plan...",
138
+ "YouTube": "Tactical action plan...",
139
+ "Meta": "Tactical action plan...",
140
+ "X": "Tactical action plan..."
141
  }}
142
  }}
143
  """
 
149
  st.table(pd.DataFrame(g_data.get('risk_factors', {{}}).items(), columns=["Metric", "Intelligence Insight"]))
150
  st.markdown("### πŸ“± Platform Tactical Recommendations")
151
  st.table(pd.DataFrame(g_data.get('platform_analysis', {{}}).items(), columns=["Platform", "Strategic Insight"]))
152
+ except Exception as e: st.error(f"Synthesis error: {e}")
153
 
154
  # --- [Tab 2: National Forensics - ALL ANALYTICAL FIELDS APPLIED] ---
155
  with tab2:
156
  st.subheader("National Tactical Intelligence (Verified Evidence)")
157
  c1, c2 = st.columns([1, 4])
158
  with c1:
159
+ target_geo = st.text_input("ISO Country Code", "US").upper()
160
  btn_deep = st.button("Generate National Report", type="primary")
161
 
162
  if btn_deep:
163
  with st.status(f"Generating Deep-Dive for {target_geo} (7d Evidence)...", expanded=True):
164
+ news = fetch_google_news(f"{target_geo} social risk controversy", geo=target_geo, limit=35, period="7d")
165
  news_context = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(news)])
166
 
167
  system_prompt = f"""
 
186
  if report_data:
187
  st.markdown(create_download_link(report_data, f"{target_geo}_Full_Report.txt"), unsafe_allow_html=True)
188
  for r in report_data:
189
+ with st.expander(f"🚩 RANK {r.get('rank')}: {r.get('title')} (Verified)"):
190
  st.markdown(f"**Detailed Analysis:**\n{r.get('summary')}")
191
  st.table(pd.DataFrame({
192
  "Category": ["Violation", "Target Group", "Social Impact", "Tactical Action"],
 
194
  }))
195
 
196
  st.divider()
197
+ st.subheader("πŸ“° Evidence Feed (7-Day)")
198
+ df_news = pd.DataFrame(news)
199
+ if not df_news.empty:
200
+ st.dataframe(df_news[['source', 'title', 'link']], use_container_width=True)
201
 
202
  # --- [Tab 3: Risk Velocity Trend] ---
203
  with tab3:
204
  st.subheader("πŸ“ˆ Risk Velocity Trend (Last 7 Days)")
205
+ trend_key = st.text_input("Trend Keyword", "AI Disinformation")
206
  if st.button("Analyze Velocity"):
207
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
208
+ scores = [15, 30, 50, 85, 95, 92, 88]
209
  st.plotly_chart(px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity: {trend_key}"), use_container_width=True)