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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -96
app.py CHANGED
@@ -10,7 +10,7 @@ from datetime import datetime, timedelta
10
  import base64
11
 
12
  # --- 1. Page Config ---
13
- st.set_page_config(page_title="Omni-Watch War Room Pro", page_icon="🚨", layout="wide")
14
 
15
  # --- 2. API Key Load ---
16
  api_key = os.environ.get("GROQ_API_KEY")
@@ -19,13 +19,13 @@ if not api_key:
19
  except: pass
20
 
21
  if not api_key:
22
- st.error("πŸ”‘ GROQ_API_KEY Missing in Secrets. Please add it to continue.")
23
  st.stop()
24
 
25
  client = Groq(api_key=api_key)
26
  CURRENT_MODEL = "llama-3.3-70b-versatile"
27
 
28
- # --- 3. Configuration & Region Mapping ---
29
  REGION_MAP = {
30
  "Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "IN", "AU", "SG"],
31
  "Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL"],
@@ -33,7 +33,7 @@ REGION_MAP = {
33
  "ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
34
  }
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)
@@ -49,29 +49,29 @@ def fetch_google_news(query, geo="US", limit=35, period="7d"):
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 %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', [])
@@ -85,131 +85,117 @@ for i, issue in enumerate(st.session_state.hot_issues):
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.markdown("---")
89
 
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("")
102
- run_global = st.button("πŸ—ΊοΈ Run Global Scan", type="primary", use_container_width=True)
103
-
104
- if run_global:
105
  target_countries = []
106
  for reg in selected_regions: target_countries.extend(REGION_MAP[reg])
107
- results = []
108
- all_news_tab1 = []
109
- progress = st.progress(0)
110
- for i, geo in enumerate(target_countries):
111
- n_list = fetch_google_news(keyword, geo=geo, limit=5, period="7d")
112
- all_news_tab1.extend(n_list)
113
- results.append({"Country": geo, "Risk": min(len(n_list) * 20, 100)})
114
- progress.progress((i + 1) / len(target_countries))
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')]
203
- }))
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)
 
10
  import base64
11
 
12
  # --- 1. Page Config ---
13
+ st.set_page_config(page_title="Omni-Watch Intelligence Center", page_icon="🚨", layout="wide")
14
 
15
  # --- 2. API Key Load ---
16
  api_key = os.environ.get("GROQ_API_KEY")
 
19
  except: pass
20
 
21
  if not api_key:
22
+ st.error("πŸ”‘ GROQ_API_KEY Missing. Please check your deployment settings.")
23
  st.stop()
24
 
25
  client = Groq(api_key=api_key)
26
  CURRENT_MODEL = "llama-3.3-70b-versatile"
27
 
28
+ # --- 3. Configuration ---
29
  REGION_MAP = {
30
  "Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "IN", "AU", "SG"],
31
  "Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL"],
 
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)
 
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', [])
 
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
  """
131
  try:
132
+ res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": global_prompt}, {"role": "user", "content": news_summary}], response_format={"type": "json_object"})
133
  g_data = json.loads(res.choices[0].message.content)
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
  }}
172
  """
173
  try:
174
+ res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}], response_format={"type": "json_object"})
175
  report_data = json.loads(res.choices[0].message.content).get('risks', [])
176
+
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)