benjamin5607 commited on
Commit
c0b64b1
Β·
verified Β·
1 Parent(s): 21cf7f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -67
app.py CHANGED
@@ -33,8 +33,8 @@ REGION_MAP = {
33
  "ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
34
  }
35
 
36
- # --- 4. News Fetching Logic (Dual-Timeline) ---
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"
@@ -48,30 +48,30 @@ def fetch_google_news(query, geo="US", limit=35, period="7d"):
48
  })
49
  return articles
50
 
51
- def create_download_link(data, filename="Full_Strategic_Intel.txt"):
52
- report_text = f"--- FULL STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d')}) ---\n\n"
53
  for item in data:
54
  report_text += f"RANK {item.get('rank', '-')}: {item.get('title', 'N/A')}\n"
55
  report_text += f"ANALYSIS: {item.get('summary', 'N/A')}\n"
56
- report_text += f"GUIDELINE VIOLATION: {item.get('violation', 'N/A')}\n"
57
- report_text += f"TARGET DEMOGRAPHICS: {item.get('demographics', 'N/A')}\n"
58
  report_text += f"SOCIAL IMPACT: {item.get('social_impact', 'N/A')}\n"
59
  report_text += f"TACTICAL ACTION: {item.get('tactical_action', 'N/A')}\n\n"
60
  b64 = base64.b64encode(report_text.encode()).decode()
61
- 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 Strategic Report</button></a>'
62
 
63
- # --- 5. 🚨 War Room (12-Hour Freshness) ---
64
  st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
65
- st.markdown(f"**Emergency Intelligence Feed (12h Window):** `{datetime.now().strftime('%H:%M:%S')} UTC`")
66
 
67
  if st.button("πŸ”„ Refresh Dashboard"):
68
  if 'hot_issues' in st.session_state: del st.session_state.hot_issues
69
 
70
  if 'hot_issues' not in st.session_state:
71
  with st.spinner("Analyzing 12h urgent feeds..."):
72
- raw_news = fetch_google_news("breaking news risk security crisis", limit=20, period="12h")
73
  news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
74
- system_msg = """Identify 3 most critical events. Return ONLY JSON: {"issues": [{"event_title": "..", "three_line_summary": ["..", "..", ".."], "source_link": ".."}]}"""
75
  try:
76
  res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}], response_format={"type": "json_object"})
77
  st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])
@@ -83,48 +83,47 @@ for i, issue in enumerate(st.session_state.hot_issues):
83
  with st.container(border=True):
84
  st.error(f"**{issue.get('event_title')}**")
85
  for line in issue.get('three_line_summary', []): st.markdown(f"- {line}")
86
- st.markdown(f"[πŸ”— View Source]({issue.get('source_link')})")
87
 
88
  st.divider()
89
 
90
- # --- 6. Strategic Tabs (7-Day Horizon) ---
91
- tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL TRACKING & MARKET", "πŸ” NATIONAL DEEP-DIVE", "πŸ“ˆ RISK VELOCITY"])
92
 
93
- # --- [Tab 1: Global Tracking & Full Market Insight] ---
94
  with tab1:
95
- st.subheader("Global Risk Propagation & Market Intelligence (7 Days)")
96
- keyword = st.text_input("Deep Scan Keyword", "Digital Propaganda")
97
- selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
98
-
99
- if st.button("πŸ—ΊοΈ Execute Global Analysis", type="primary"):
100
  all_news_tab1 = []
101
  target_countries = []
102
- for reg in selected_regions: target_countries.extend(REGION_MAP[reg])
103
 
104
- with st.spinner("Gathering global news nodes..."):
105
- for geo in target_countries[:12]: # Balanced for API speed
106
- all_news_tab1.extend(fetch_google_news(keyword, geo=geo, limit=5, period="7d"))
 
 
107
 
108
 
109
 
110
- with st.spinner("Synthesizing Full-Spectrum Strategic Report..."):
111
- news_summary = "\n".join([n['title'] for n in all_news_tab1[:30]])
112
- # Double curly braces {{ }} for f-string JSON
113
  global_prompt = f"""
114
- Analyze '{keyword}' based on provided news. Return ONLY JSON in English:
115
  {{
116
- "global_summary": "300+ word narrative on propagation and threat level.",
117
- "analysis_fields": {{
118
- "Target_Demographics": "Detailed analysis of targeted groups.",
119
- "Guideline_Violation": "Relevant community policy breaches.",
120
  "Social_Impact": "Societal and political consequences.",
121
- "Tactical_Action": "Global mitigation recommendation."
122
  }},
123
- "platform_analysis": {{
124
- "TikTok": "Platform-specific risk insight.",
125
- "YouTube": "Platform-specific risk insight.",
126
- "Meta": "Platform-specific risk insight.",
127
- "X": "Platform-specific risk insight."
128
  }}
129
  }}
130
  """
@@ -134,38 +133,33 @@ with tab1:
134
 
135
  st.info(f"**🌍 Global Intelligence Narrative:**\n\n{g_data.get('global_summary')}")
136
 
137
- # FULL SPECTRUM FIELDS IN TAB 1
138
- st.markdown("### πŸ” Global Risk Factor Breakdown")
139
- st.table(pd.DataFrame(g_data.get('analysis_fields', {}).items(), columns=["Metric", "Intelligence Insight"]))
140
 
141
- st.markdown("### πŸ“± Platform-Specific Market Tactical Insights")
142
- st.table(pd.DataFrame(g_data.get('platform_analysis', {}).items(), columns=["Platform", "Strategic Action"]))
143
- except Exception as e: st.error(f"Synthesis failed: {e}")
144
 
145
- # --- [Tab 2: National Forensics - EVERY FIELD INCLUDED] ---
146
  with tab2:
147
- st.subheader("National Tactical Intelligence (Verified 7-Day Evidence)")
148
- target_geo = st.text_input("ISO Country Code (e.g., US, KR, GB)", "US").upper()
149
- if st.button("Generate National Forensics Report"):
150
- with st.status(f"Scanning Evidence for {target_geo}...", expanded=True):
151
- news = fetch_google_news(f"{target_geo} social risk controversy", geo=target_geo, limit=30, period="7d")
152
  news_titles = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(news)])
153
 
154
 
155
 
156
  system_prompt = f"""
157
- Identify Top 5 Risks for {target_geo} in English.
158
- For each risk, provide 300+ word summary citing REFs.
159
  Return ONLY JSON:
160
  {{
161
  "risks": [
162
  {{
163
- "rank": 1, "title": "..", "score": 90,
164
- "summary": "Deep analysis citing REFs",
165
- "violation": "Specific guideline breach",
166
- "demographics": "Targeted groups",
167
- "social_impact": "Socio-political impact",
168
- "tactical_action": "Platform mitigation steps"
169
  }}
170
  ]
171
  }}
@@ -177,25 +171,24 @@ with tab2:
177
  if report_data:
178
  st.markdown(create_download_link(report_data, f"{target_geo}_Deep_Intel.txt"), unsafe_allow_html=True)
179
  for r in report_data:
180
- with st.expander(f"🚩 RANK {r.get('rank')}: {r.get('title')} (Risk: {r.get('score')})"):
181
  st.write(r.get('summary'))
182
 
183
 
184
 
185
  st.table(pd.DataFrame({
186
- "Category": ["Violation", "Target Group", "Social Impact", "Tactical Action"],
187
- "Insight": [r.get('violation'), r.get('demographics'), r.get('social_impact'), r.get('tactical_action')]
188
  }))
189
-
190
  st.divider()
191
- st.subheader("πŸ“° Underlying Evidence Feed")
192
  st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
193
  except Exception as e: st.error(f"Forensics error: {e}")
194
 
195
- # --- [Tab 3: Risk Velocity] ---
196
  with tab3:
197
- st.subheader("πŸ“ˆ Risk Velocity & Forecast (Last 7 Days)")
198
- trend_key = st.text_input("Trend Keyword", "AI Disinformation")
199
  if st.button("Analyze Velocity"):
200
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
201
- st.plotly_chart(px.line(x=dates, y=[15, 25, 55, 70, 95, 90, 85], markers=True, title=f"Risk Score Velocity: {trend_key}"), use_container_width=True)
 
33
  "ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
34
  }
35
 
36
+ # --- 4. High-Volume Evidence Fetcher ---
37
+ def fetch_extensive_news(query, geo="US", limit=60, 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"
 
48
  })
49
  return articles
50
 
51
+ def create_download_link(data, filename="Full_Intelligence_Report.txt"):
52
+ report_text = f"--- STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d')}) ---\n\n"
53
  for item in data:
54
  report_text += f"RANK {item.get('rank', '-')}: {item.get('title', 'N/A')}\n"
55
  report_text += f"ANALYSIS: {item.get('summary', 'N/A')}\n"
56
+ report_text += f"VIOLATION: {item.get('violation', 'N/A')}\n"
57
+ report_text += f"DEMOGRAPHICS: {item.get('demographics', 'N/A')}\n"
58
  report_text += f"SOCIAL IMPACT: {item.get('social_impact', 'N/A')}\n"
59
  report_text += f"TACTICAL ACTION: {item.get('tactical_action', 'N/A')}\n\n"
60
  b64 = base64.b64encode(report_text.encode()).decode()
61
+ 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</button></a>'
62
 
63
+ # --- 5. 🚨 Dashboard (12h Window) ---
64
  st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
65
+ st.markdown(f"**Emergency Feed (12h):** `{datetime.now().strftime('%H:%M:%S')} UTC`")
66
 
67
  if st.button("πŸ”„ Refresh Dashboard"):
68
  if 'hot_issues' in st.session_state: del st.session_state.hot_issues
69
 
70
  if 'hot_issues' not in st.session_state:
71
  with st.spinner("Analyzing 12h urgent feeds..."):
72
+ raw_news = fetch_extensive_news("breaking news crisis risk", limit=25, period="12h")
73
  news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
74
+ system_msg = """Return ONLY JSON: {"issues": [{"event_title": "..", "three_line_summary": ["..", "..", ".."], "source_link": ".."}]}"""
75
  try:
76
  res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}], response_format={"type": "json_object"})
77
  st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])
 
83
  with st.container(border=True):
84
  st.error(f"**{issue.get('event_title')}**")
85
  for line in issue.get('three_line_summary', []): st.markdown(f"- {line}")
86
+ st.markdown(f"[πŸ”— Source]({issue.get('source_link')})")
87
 
88
  st.divider()
89
 
90
+ # --- 6. Strategic Tabs (7d Window) ---
91
+ tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL TRACKING", "πŸ” NATIONAL FORENSICS", "πŸ“ˆ RISK VELOCITY"])
92
 
93
+ # --- [Tab 1: Global Tracking - ALL FIELDS RESTORED] ---
94
  with tab1:
95
+ st.subheader("Global Risk Propagation & Strategic Market Insight (20+ Sources)")
96
+ keyword = st.text_input("Enter Issue for Global Scan", "Deepfake Propaganda")
97
+ if st.button("πŸ—ΊοΈ Run Extensive Global Analysis", type="primary"):
 
 
98
  all_news_tab1 = []
99
  target_countries = []
100
+ for reg in REGION_MAP: target_countries.extend(REGION_MAP[reg])
101
 
102
+ with st.spinner("Gathering 20+ Global Evidence Sources..."):
103
+ for geo in target_countries[:15]:
104
+ all_news_tab1.extend(fetch_extensive_news(keyword, geo=geo, limit=6, period="7d"))
105
+
106
+ st.success(f"βœ… Gathered {len(all_news_tab1)} source articles. Grounding Analysis...")
107
 
108
 
109
 
110
+ with st.spinner("Synthesizing Full Strategic Report..."):
111
+ news_summary = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(all_news_tab1[:40])])
 
112
  global_prompt = f"""
113
+ Analyze '{keyword}' based on provided news. Return ONLY JSON:
114
  {{
115
+ "global_summary": "300+ word narrative on propagation trends.",
116
+ "analysis_report": {{
117
+ "Target_Demographics": "Detailed groups at risk.",
118
+ "Community_Violation": "Specific policy breaches.",
119
  "Social_Impact": "Societal and political consequences.",
120
+ "Strategic_Action": "Primary recommendation."
121
  }},
122
+ "market_tactics": {{
123
+ "TikTok": "Risk & Recommendation...",
124
+ "YouTube": "Risk & Recommendation...",
125
+ "Meta": "Risk & Recommendation...",
126
+ "X": "Risk & Recommendation..."
127
  }}
128
  }}
129
  """
 
133
 
134
  st.info(f"**🌍 Global Intelligence Narrative:**\n\n{g_data.get('global_summary')}")
135
 
136
+ st.markdown("### πŸ” Risk Factor Forensics (Missing Fields Restored)")
137
+ st.table(pd.DataFrame(g_data.get('analysis_report', {}).items(), columns=["Category", "Insight"]))
 
138
 
139
+ st.markdown("### πŸ“± Platform Market Strategies")
140
+ st.table(pd.DataFrame(g_data.get('market_tactics', {}).items(), columns=["Platform", "Action Plan"]))
141
+ except Exception as e: st.error(f"Synthesis error: {e}")
142
 
143
+ # --- [Tab 2: National Forensics - ALL FIELDS RESTORED] ---
144
  with tab2:
145
+ st.subheader("National Tactical Forensics (Verified Evidence)")
146
+ target_geo = st.text_input("ISO Country Code", "KR").upper()
147
+ if st.button("Generate National Forensic Report"):
148
+ with st.status(f"Scanning 20+ Evidence for {target_geo}...", expanded=True):
149
+ news = fetch_extensive_news(f"{target_geo} social risk", geo=target_geo, limit=40, period="7d")
150
  news_titles = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(news)])
151
 
152
 
153
 
154
  system_prompt = f"""
155
+ Identify Top 5 Risks for {target_geo} in English using 30+ references.
156
+ For each risk, return EXACTLY these fields: summary (300+ words citing REFs), violation, demographics, social_impact, tactical_action.
157
  Return ONLY JSON:
158
  {{
159
  "risks": [
160
  {{
161
+ "rank": 1, "title": "..", "score": 95, "summary": "..",
162
+ "violation": "..", "demographics": "..", "social_impact": "..", "tactical_action": ".."
 
 
 
 
163
  }}
164
  ]
165
  }}
 
171
  if report_data:
172
  st.markdown(create_download_link(report_data, f"{target_geo}_Deep_Intel.txt"), unsafe_allow_html=True)
173
  for r in report_data:
174
+ with st.expander(f"🚩 RANK {r.get('rank')}: {r.get('title')} (Source-Verified)"):
175
  st.write(r.get('summary'))
176
 
177
 
178
 
179
  st.table(pd.DataFrame({
180
+ "Field": ["Violation", "Target Group", "Social Impact", "Tactical Action"],
181
+ "Intelligence": [r.get('violation'), r.get('demographics'), r.get('social_impact'), r.get('tactical_action')]
182
  }))
 
183
  st.divider()
184
+ st.subheader(f"πŸ“° Underlying Evidence ({len(news)} Sources)")
185
  st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
186
  except Exception as e: st.error(f"Forensics error: {e}")
187
 
188
+ # --- [Tab 3: Trend Analysis] ---
189
  with tab3:
190
+ st.subheader("πŸ“ˆ Risk Velocity Trend (Last 7 Days)")
191
+ trend_key = st.text_input("Trend Keyword", "AI Integrity")
192
  if st.button("Analyze Velocity"):
193
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
194
+ st.plotly_chart(px.line(x=dates, y=[10, 20, 50, 75, 95, 90, 85], markers=True, title=f"Risk Score: {trend_key}"), use_container_width=True)