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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -46
app.py CHANGED
@@ -35,9 +35,6 @@ REGION_MAP = {
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"
@@ -55,27 +52,26 @@ def create_download_link(data, filename="Full_Strategic_Intel.txt"):
55
  report_text = f"--- FULL STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n\n"
56
  for item in data:
57
  report_text += f"RANK {item.get('rank', '-')}: {item.get('title', 'N/A')}\n"
58
- report_text += f"SCORE: {item.get('score', 0)}/100\n"
59
  report_text += f"DETAILED ANALYSIS: {item.get('summary', 'N/A')}\n"
60
- report_text += f"COMMUNITY GUIDELINE VIOLATION: {item.get('violation', 'N/A')}\n"
61
  report_text += f"TARGET DEMOGRAPHICS: {item.get('demographics', 'N/A')}\n"
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")
69
- st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%H:%M:%S')}`")
70
 
71
- if st.button("πŸ”„ Refresh War Room"):
72
  if 'hot_issues' in st.session_state: del st.session_state.hot_issues
73
 
74
  if 'hot_issues' not in st.session_state:
75
  with st.spinner("Analyzing ultra-fresh 12-hour incidents..."):
76
- raw_news = fetch_google_news("breaking news risk security crisis controversy", limit=20, period="12h")
77
- news_context = "\n".join([f"Event: {n['title']} | Link: {n['link']}" for n in raw_news])
78
- system_msg = """Identify 3 most dangerous events from last 12h. Return ONLY JSON: {"issues": [{"event_title": "..", "severity": "..", "three_line_summary": ["..", "..", ".."], "source_link": ".."}]}"""
79
  try:
80
  res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}], response_format={"type": "json_object"})
81
  st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])
@@ -94,12 +90,12 @@ st.markdown("---")
94
  # --- 6. Strategic Tabs ---
95
  tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL TRACKING & MARKET", "πŸ” NATIONAL TOP 5 FORENSICS", "πŸ“ˆ RISK VELOCITY TREND"])
96
 
97
- # --- [Tab 1: Global & Market - ALL ANALYTICAL FIELDS APPLIED] ---
98
  with tab1:
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("")
@@ -119,75 +115,88 @@ with tab1:
119
 
120
  st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))
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
  """
144
  try:
145
  res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": market_prompt}, {"role": "user", "content": f"News:\n{news_summary}"}], response_format={"type": "json_object"})
146
  g_data = json.loads(res.choices[0].message.content)
147
- st.info(f"**🌍 Global Strategic Narrative:**\n\n{g_data.get('global_summary')}")
 
 
 
148
  st.markdown("### πŸ” Risk Factor Breakdown")
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"""
168
- Analyze Risks for {target_geo} in English.
169
- Include: violation, demographics, social_impact, tactical_action.
170
  Summary must be 300+ words citing REF IDs.
171
  Return ONLY JSON:
172
  {{
173
  "risks": [
174
  {{
175
  "rank": 1, "title": "..", "score": 90, "summary": "..",
176
- "violation": "..", "demographics": "..", "social_impact": "..", "tactical_action": ".."
 
 
 
177
  }}
178
  ]
179
  }}
180
  """
181
  try:
182
- res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": f"Evidence Feed:\n{news_context}"}], response_format={"type": "json_object"})
183
  report_data = json.loads(res.choices[0].message.content).get('risks', [])
184
  except: report_data = []
185
 
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"],
193
  "Intelligence": [r.get('violation'), r.get('demographics'), r.get('social_impact'), r.get('tactical_action')]
@@ -195,15 +204,12 @@ with tab2:
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)
 
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"
 
52
  report_text = f"--- FULL STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\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"DETAILED ANALYSIS: {item.get('summary', 'N/A')}\n"
56
+ report_text += f"POLICY 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 PLAN: {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 (.txt)</button></a>'
62
 
63
  # --- 5. 🚨 Main Dashboard: WAR ROOM (12h Filter) ---
64
  st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
65
+ st.markdown(f"**Live Analysis (UTC):** `{datetime.now().strftime('%H:%M:%S')}`")
66
 
67
+ if st.button("πŸ”„ Refresh War Room (12h Scan)"):
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 ultra-fresh 12-hour incidents..."):
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 dangerous ACTUAL events from last 12h. Return ONLY JSON: {"issues": [{"event_title": "..", "severity": "..", "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', [])
 
90
  # --- 6. Strategic Tabs ---
91
  tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL TRACKING & MARKET", "πŸ” NATIONAL TOP 5 FORENSICS", "πŸ“ˆ RISK VELOCITY TREND"])
92
 
93
+ # --- [Tab 1: Global & Market - FULL SPECTRUM] ---
94
  with tab1:
95
+ st.subheader("Global Risk Propagation & Strategic Market Insight (7 Days)")
96
  col_k1, col_k2 = st.columns([3, 1])
97
  with col_k1:
98
+ keyword = st.text_input("Enter Issue Keyword (7d Deep Scan)", "Digital Extremism")
99
  selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
100
  with col_k2:
101
  st.write("")
 
115
 
116
  st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))
117
 
118
+
119
+
120
+ with st.spinner("Synthesizing Full Strategic Global Report..."):
121
  news_summary = "\n".join([f"- {n['title']}" for n in all_news_tab1[:25]])
122
+ # ESCAPED BRACES {{ }} FOR JSON
123
  market_prompt = f"""
124
+ Analyze '{keyword}' based on provided news. Return ONLY JSON:
 
125
  {{
126
+ "global_summary": "Detailed narrative (300+ words) on propagation.",
127
+ "analysis_fields": {{
128
+ "Target_Demographics": "Who is at risk and why.",
129
+ "Guideline_Violation": "Specific policy breaches.",
130
+ "Social_Impact": "Societal and political consequences.",
131
+ "Primary_Tactical_Action": "Primary recommendation for platforms."
132
  }},
133
  "platform_analysis": {{
134
+ "TikTok": "Strategic recommendation...",
135
+ "YouTube": "Strategic recommendation...",
136
+ "Meta": "Strategic recommendation...",
137
+ "X": "Strategic recommendation..."
138
  }}
139
  }}
140
  """
141
  try:
142
  res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": market_prompt}, {"role": "user", "content": f"News:\n{news_summary}"}], response_format={"type": "json_object"})
143
  g_data = json.loads(res.choices[0].message.content)
144
+
145
+ st.info(f"**🌍 Global Strategic Summary:**\n\n{g_data.get('global_summary')}")
146
+
147
+ # Full Field Analysis for Tab 1
148
  st.markdown("### πŸ” Risk Factor Breakdown")
149
+ st.table(pd.DataFrame(g_data.get('analysis_fields', {{}}).items(), columns=["Metric", "Intelligence Insight"]))
150
+
151
  st.markdown("### πŸ“± Platform Tactical Recommendations")
152
  st.table(pd.DataFrame(g_data.get('platform_analysis', {{}}).items(), columns=["Platform", "Strategic Insight"]))
153
  except Exception as e: st.error(f"Synthesis error: {e}")
154
 
155
+ # --- [Tab 2: National Forensics - FULL SPECTRUM] ---
156
  with tab2:
157
+ st.subheader("National Tactical Intelligence (7-Day Evidence)")
158
  c1, c2 = st.columns([1, 4])
159
  with c1:
160
  target_geo = st.text_input("ISO Country Code", "US").upper()
161
  btn_deep = st.button("Generate National Report", type="primary")
162
 
163
  if btn_deep:
164
+ with st.status(f"Generating Deep-Dive for {target_geo}...", expanded=True):
165
+ news = fetch_google_news(f"{target_geo} social controversy", geo=target_geo, limit=35, period="7d")
166
  news_context = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(news)])
167
 
168
+
169
+
170
+ # ESCAPED BRACES {{ }} FOR JSON
171
  system_prompt = f"""
172
+ Identify Top 5 Risks for {target_geo} in English.
 
173
  Summary must be 300+ words citing REF IDs.
174
  Return ONLY JSON:
175
  {{
176
  "risks": [
177
  {{
178
  "rank": 1, "title": "..", "score": 90, "summary": "..",
179
+ "violation": "Specific guideline breach",
180
+ "demographics": "Vulnerable target groups",
181
+ "social_impact": "Societal/political consequences",
182
+ "tactical_action": "Platform-specific action plan"
183
  }}
184
  ]
185
  }}
186
  """
187
  try:
188
+ res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": f"Evidence:\n{news_context}"}], response_format={"type": "json_object"})
189
  report_data = json.loads(res.choices[0].message.content).get('risks', [])
190
  except: report_data = []
191
 
192
  if report_data:
193
+ st.markdown(create_download_link(report_data, f"{target_geo}_Full_Intel.txt"), unsafe_allow_html=True)
194
  for r in report_data:
195
  with st.expander(f"🚩 RANK {r.get('rank')}: {r.get('title')} (Verified)"):
196
  st.markdown(f"**Detailed Analysis:**\n{r.get('summary')}")
197
+
198
+
199
+
200
  st.table(pd.DataFrame({
201
  "Category": ["Violation", "Target Group", "Social Impact", "Tactical Action"],
202
  "Intelligence": [r.get('violation'), r.get('demographics'), r.get('social_impact'), r.get('tactical_action')]
 
204
 
205
  st.divider()
206
  st.subheader("πŸ“° Evidence Feed (7-Day)")
207
+ st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
 
 
208
 
209
+ # --- [Tab 3: Risk Velocity] ---
210
  with tab3:
211
  st.subheader("πŸ“ˆ Risk Velocity Trend (Last 7 Days)")
212
+ trend_key = st.text_input("Trend Keyword", "Election Safety")
213
  if st.button("Analyze Velocity"):
214
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
215
+ st.plotly_chart(px.line(x=dates, y=[15, 25, 45, 75, 85, 95, 92], markers=True, title=f"Risk Score Velocity: {trend_key}"), use_container_width=True)