benjamin5607 commited on
Commit
a475532
Β·
verified Β·
1 Parent(s): 62059a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -41
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", page_icon="🚨", layout="wide")
14
 
15
  # --- 2. API Key Load ---
16
  api_key = os.environ.get("GROQ_API_KEY")
@@ -19,7 +19,7 @@ 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)
@@ -33,11 +33,8 @@ REGION_MAP = {
33
  "ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
34
  }
35
 
36
- # --- 4. Advanced News Fetcher (Dual-Timeline) ---
37
  def fetch_google_news(query, geo="US", limit=35, period="7d"):
38
- """
39
- period: '12h' for dashboard, '7d' for deep-dive search
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"
@@ -68,9 +65,9 @@ st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
68
  st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%H:%M:%S')}`")
69
 
70
  st.subheader("πŸ”₯ Global Breaking Incidents (Last 12 Hours)")
71
- st.caption("AI-monitored live feeds with 3-line strategic summaries for rapid response.")
72
 
73
- if st.button("πŸ”„ Refresh Dashboard (12h Scan)"):
74
  if 'hot_issues' in st.session_state: del st.session_state.hot_issues
75
 
76
  if 'hot_issues' not in st.session_state:
@@ -79,7 +76,7 @@ if 'hot_issues' not in st.session_state:
79
  news_context = "\n".join([f"Event: {n['title']} | Link: {n['link']}" for n in raw_news])
80
 
81
  system_msg = """
82
- Analyze news from the last 12 hours. Identify 3 most dangerous ACTUAL events.
83
  Return ONLY JSON: {"issues": [{"event_title": "..", "severity": "..", "three_line_summary": ["..", "..", ".."], "source_link": ".."}]}
84
  """
85
  try:
@@ -101,14 +98,14 @@ for i, issue in enumerate(st.session_state.hot_issues):
101
  st.markdown("---")
102
 
103
  # --- 6. Strategic Tabs (7d Filter for Search) ---
104
- tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL TRACKING & MARKET", "πŸ” NATIONAL TOP 5 FORENSICS (EVIDENCE-BASED)", "πŸ“ˆ RISK VELOCITY TREND"])
105
 
106
- # --- [Tab 1: Global Tracking & Market] ---
107
  with tab1:
108
  st.subheader("Global Risk Propagation & Market Insight (7 Days)")
109
  col_k1, col_k2 = st.columns([3, 1])
110
  with col_k1:
111
- keyword = st.text_input("Enter Issue Keyword (7d Deep Scan)", "Deepfake Propaganda")
112
  selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
113
  with col_k2:
114
  st.write("")
@@ -126,8 +123,6 @@ with tab1:
126
 
127
  st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))
128
 
129
-
130
-
131
  with st.spinner("Analyzing Market Insights..."):
132
  res = client.chat.completions.create(
133
  model=CURRENT_MODEL,
@@ -138,53 +133,62 @@ with tab1:
138
  st.info(g_data.get('global_summary'))
139
  st.table(pd.DataFrame(g_data.get('market_insights', {}).items(), columns=["Platform", "Insight"]))
140
 
141
- # --- [Tab 2: National Forensics (Evidence-Grounded)] ---
142
  with tab2:
143
- st.subheader("National Tactical Intelligence (Verified Evidence)")
144
  c1, c2 = st.columns([1, 4])
145
  with c1:
146
  target_geo = st.text_input("ISO Country Code", "KR").upper()
147
- btn_deep = st.button("Generate Evidence-Based Report", type="primary")
148
 
149
  if btn_deep:
150
- with st.status(f"Generating forensics for {target_geo} (7d data)...", expanded=True) as status:
151
- # 7일치 ν’λΆ€ν•œ 데이터 μˆ˜μ§‘
152
  news = fetch_google_news(f"{target_geo} social controversy risk", geo=target_geo, limit=35, period="7d")
153
  news_context = "\n".join([f"REF [{i+1}]: {n['title']} (Source: {n['source']})" for i, n in enumerate(news)])
154
- status.write(f"βœ… Evidence Locked: {len(news)} sources identified.")
155
 
156
-
157
-
158
- # AIμ—κ²Œ 참고자료 κ·Όκ±° λ³΄κ³ μ„œ μž‘μ„± μ§€μ‹œ
159
  system_prompt = f"""
160
  Identify Top 5 Risks for {target_geo} based ONLY on the provided references.
161
  For each risk, write a MINIMUM of 300 words summary citing the REF IDs.
162
- Return ONLY JSON: {"risks": [{"rank": 1, "title": "..", "score": 90, "summary": "..", "violation": "..", "demographics": "..", "tactical_action": ".."}]}
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  """
164
- res = client.chat.completions.create(
165
- model=CURRENT_MODEL,
166
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": f"EVIDENCE FEED:\n{news_context}"}],
167
- response_format={"type": "json_object"}
168
- )
169
- report_data = json.loads(res.choices[0].message.content).get('risks', [])
170
- status.update(label="Forensics Synthesized", state="complete")
 
 
 
171
 
172
  if report_data:
173
  st.markdown(create_download_link(report_data, f"{target_geo}_Verified_Intel.txt"), unsafe_allow_html=True)
174
  for r in report_data:
175
  with st.expander(f"🚩 RANK {r.get('rank')}: {r.get('title')} (Verified)"):
176
  st.markdown("### πŸ“ Detailed Strategic Analysis")
177
- st.write(r.get('summary')) # 이 λ‚΄μš©μ΄ 이제 ν•˜λ‹¨ λ‰΄μŠ€ 기사와 μ™„λ²½ 맀칭됨
178
-
179
-
180
-
181
  st.table(pd.DataFrame({
182
- "Category": ["Policy Breach", "Vulnerable Groups", "Platform Action"],
183
  "Insight": [r.get('violation'), r.get('demographics'), r.get('tactical_action')]
184
  }))
185
 
186
  st.divider()
187
- st.subheader("πŸ“° Underlying Evidence Feed (Reference Sources)")
188
  df_news = pd.DataFrame(news)
189
  if not df_news.empty:
190
  st.dataframe(df_news[['source', 'title', 'link']], use_container_width=True)
@@ -192,10 +196,9 @@ with tab2:
192
  # --- [Tab 3: Trend Analysis] ---
193
  with tab3:
194
  st.subheader("πŸ“ˆ Risk Velocity Trend (Last 7 Days)")
195
- trend_key = st.text_input("Trend Keyword", "AI Fraud")
196
  if st.button("Analyze Velocity"):
197
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
198
- scores = [15, 25, 45, 60, 85, 95, 90]
199
  fig = px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity: {trend_key}")
200
- st.plotly_chart(fig, use_container_width=True)
201
- st.success("Analysis based on 7-day historical data confirms the risk trajectory.")
 
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
  except: pass
20
 
21
  if not api_key:
22
+ st.error("πŸ”‘ GROQ_API_KEY Missing. Please add it to Secrets.")
23
  st.stop()
24
 
25
  client = Groq(api_key=api_key)
 
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)
40
  url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl={geo}&ceid={geo}:en"
 
65
  st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%H:%M:%S')}`")
66
 
67
  st.subheader("πŸ”₯ Global Breaking Incidents (Last 12 Hours)")
68
+ st.caption("AI-monitored live feeds with 3-line strategic summaries.")
69
 
70
+ if st.button("πŸ”„ Refresh Dashboard"):
71
  if 'hot_issues' in st.session_state: del st.session_state.hot_issues
72
 
73
  if 'hot_issues' not in st.session_state:
 
76
  news_context = "\n".join([f"Event: {n['title']} | Link: {n['link']}" for n in raw_news])
77
 
78
  system_msg = """
79
+ Identify 3 most dangerous ACTUAL events from last 12h.
80
  Return ONLY JSON: {"issues": [{"event_title": "..", "severity": "..", "three_line_summary": ["..", "..", ".."], "source_link": ".."}]}
81
  """
82
  try:
 
98
  st.markdown("---")
99
 
100
  # --- 6. Strategic Tabs (7d Filter for Search) ---
101
+ tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL TRACKING & MARKET", "πŸ” NATIONAL FORENSICS (EVIDENCE-BASED)", "πŸ“ˆ RISK VELOCITY TREND"])
102
 
103
+ # --- [Tab 1: Global & Market] ---
104
  with tab1:
105
  st.subheader("Global Risk Propagation & Market Insight (7 Days)")
106
  col_k1, col_k2 = st.columns([3, 1])
107
  with col_k1:
108
+ keyword = st.text_input("Enter Issue Keyword (7d Scan)", "Cyber Warfare")
109
  selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
110
  with col_k2:
111
  st.write("")
 
123
 
124
  st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))
125
 
 
 
126
  with st.spinner("Analyzing Market Insights..."):
127
  res = client.chat.completions.create(
128
  model=CURRENT_MODEL,
 
133
  st.info(g_data.get('global_summary'))
134
  st.table(pd.DataFrame(g_data.get('market_insights', {}).items(), columns=["Platform", "Insight"]))
135
 
136
+ # --- [Tab 2: National Forensics - Fixed with Double Curly Braces] ---
137
  with tab2:
138
+ st.subheader("National Tactical Intelligence (Evidence-Grounded)")
139
  c1, c2 = st.columns([1, 4])
140
  with c1:
141
  target_geo = st.text_input("ISO Country Code", "KR").upper()
142
+ btn_deep = st.button("Generate Detailed Report", type="primary")
143
 
144
  if btn_deep:
145
+ with st.status(f"Generating forensics for {target_geo} (7d data)...", expanded=True):
 
146
  news = fetch_google_news(f"{target_geo} social controversy risk", geo=target_geo, limit=35, period="7d")
147
  news_context = "\n".join([f"REF [{i+1}]: {n['title']} (Source: {n['source']})" for i, n in enumerate(news)])
 
148
 
149
+ # --- πŸ›‘οΈ FIXED: Double Curly Braces to prevent f-string ValueError ---
 
 
150
  system_prompt = f"""
151
  Identify Top 5 Risks for {target_geo} based ONLY on the provided references.
152
  For each risk, write a MINIMUM of 300 words summary citing the REF IDs.
153
+ Return ONLY JSON in this exact structure:
154
+ {{
155
+ "risks": [
156
+ {{
157
+ "rank": 1,
158
+ "title": "..",
159
+ "score": 90,
160
+ "summary": "..",
161
+ "violation": "..",
162
+ "demographics": "..",
163
+ "tactical_action": ".."
164
+ }}
165
+ ]
166
+ }}
167
  """
168
+ try:
169
+ res = client.chat.completions.create(
170
+ model=CURRENT_MODEL,
171
+ messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": f"EVIDENCE FEED:\n{news_context}"}],
172
+ response_format={"type": "json_object"}
173
+ )
174
+ report_data = json.loads(res.choices[0].message.content).get('risks', [])
175
+ except Exception as e:
176
+ st.error(f"Analysis Error: {e}")
177
+ report_data = []
178
 
179
  if report_data:
180
  st.markdown(create_download_link(report_data, f"{target_geo}_Verified_Intel.txt"), unsafe_allow_html=True)
181
  for r in report_data:
182
  with st.expander(f"🚩 RANK {r.get('rank')}: {r.get('title')} (Verified)"):
183
  st.markdown("### πŸ“ Detailed Strategic Analysis")
184
+ st.write(r.get('summary'))
 
 
 
185
  st.table(pd.DataFrame({
186
+ "Category": ["Policy Breach", "Vulnerability", "Action"],
187
  "Insight": [r.get('violation'), r.get('demographics'), r.get('tactical_action')]
188
  }))
189
 
190
  st.divider()
191
+ st.subheader("πŸ“° Underlying Evidence Feed")
192
  df_news = pd.DataFrame(news)
193
  if not df_news.empty:
194
  st.dataframe(df_news[['source', 'title', 'link']], use_container_width=True)
 
196
  # --- [Tab 3: Trend Analysis] ---
197
  with tab3:
198
  st.subheader("πŸ“ˆ Risk Velocity Trend (Last 7 Days)")
199
+ trend_key = st.text_input("Trend Keyword", "AI Disinformation")
200
  if st.button("Analyze Velocity"):
201
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
202
+ scores = [15, 25, 45, 75, 85, 95, 92]
203
  fig = px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity: {trend_key}")
204
+ st.plotly_chart(fig, use_container_width=True)