benjamin5607 commited on
Commit
d131605
Β·
verified Β·
1 Parent(s): dc8071d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -78
app.py CHANGED
@@ -9,8 +9,8 @@ import plotly.express as px
9
  import plotly.graph_objects as go
10
  from datetime import datetime, timedelta
11
 
12
- # --- 1. Page Config (Mobile Optimized) ---
13
- st.set_page_config(page_title="Omni-Watch Mobile", page_icon="🚨", layout="wide")
14
 
15
  # --- 2. API Key Load ---
16
  api_key = os.environ.get("GROQ_API_KEY")
@@ -33,8 +33,9 @@ REGION_MAP = {
33
  "ME & Africa": ["IL", "SA", "AE", "TR"]
34
  }
35
 
36
- # --- 4. Core Functions ---
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"
@@ -45,7 +46,6 @@ def fetch_extensive_news(query, geo="US", limit=60, period="7d"):
45
  return articles
46
 
47
  def render_gauge(score, title):
48
- # 상세 νƒ­(Tab 2)μ—μ„œλŠ” μ—¬μ „νžˆ κ²Œμ΄μ§€λ₯Ό μ‚¬μš©ν•˜μ—¬ 깊이 μžˆλŠ” μ‹œκ°ν™”λ₯Ό 제곡
49
  fig = go.Figure(go.Indicator(
50
  mode = "gauge+number",
51
  value = score,
@@ -60,19 +60,19 @@ def render_gauge(score, title):
60
  fig.update_layout(height=180, margin=dict(l=10, r=10, t=40, b=10), paper_bgcolor="rgba(0,0,0,0)")
61
  return fig
62
 
63
- # --- 5. 🚨 GLOBAL WAR ROOM (Mobile: Top 3 & Numbers Only) ---
64
  st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
65
- st.caption(f"Last Updated: {datetime.now().strftime('%H:%M:%S')} UTC")
66
 
67
- if st.button("πŸ”„ Refresh"):
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("Scanning feeds..."):
72
- raw_news = fetch_extensive_news("breaking news crisis risk security", limit=35, period="12h")
73
- news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
74
- # TOP 3 Only
75
- system_msg = """Identify TOP 3 critical incidents. Return ONLY JSON: {"issues": [{"title": "..", "score": 85, "summary": ["..", "..", ".."], "link": ".."}]}"""
76
  try:
77
  res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}], response_format={"type": "json_object"})
78
  st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])[:3]
@@ -83,37 +83,33 @@ if st.session_state.hot_issues:
83
  for i, issue in enumerate(st.session_state.hot_issues):
84
  with cols[i]:
85
  with st.container(border=True):
86
- # War Room: μš”μ²­ν•˜μ‹  λŒ€λ‘œ κ²Œμ΄μ§€ λΉΌκ³  '큰 숫자'둜 ν‘œμ‹œ
87
  st.markdown(f"<h1 style='text-align: center; color: #FF4B4B; margin: 0;'>{issue.get('score', 50)}</h1>", unsafe_allow_html=True)
88
  st.markdown("<p style='text-align: center; color: gray; font-size: 0.8em;'>Severity Index</p>", unsafe_allow_html=True)
89
  st.error(f"**{issue.get('title')}**")
90
  for line in issue.get('summary', []): st.caption(f"β€’ {line}")
91
- st.markdown(f"[πŸ”— Link]({issue.get('link')})")
92
 
93
  st.divider()
94
 
95
  # --- 6. Strategic Tabs ---
96
- tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL", "πŸ” FORENSICS", "πŸ“ˆ TRENDS"])
97
 
98
- # --- [Tab 1: Strategic Global Scan] ---
99
  with tab1:
100
- st.header("Strategic Briefing (SIB)")
101
- keyword = st.text_input("Keyword", "Cyber Warfare")
102
- if st.button("Generate Report", type="primary"):
103
- with st.status("Analyzing 20+ Sources...", expanded=True) as status:
104
  all_news = []
105
  for reg in REGION_MAP:
106
  for geo in REGION_MAP[reg][:2]:
107
- # 데이터 μˆ˜μ§‘ 둜직 μœ μ§€ (깊이 보쑴)
108
- all_news.extend(fetch_extensive_news(keyword, geo=geo, limit=6, period="7d"))
109
- status.write(f"βœ… Found {len(all_news)} articles. Synthesizing...")
110
 
111
  news_summary = "\n".join([n['title'] for n in all_news[:45]])
112
- # ν”„λ‘¬ν”„νŠΈ: λͺ¨λ“  뢄석 ν•„λ“œ(Risk Landscape, Platform Matrix λ“±) μ™„λ²½ μœ μ§€
113
  global_prompt = f"""
114
- Analyze '{keyword}' in English.
115
- Executive Summary MUST be a clean narrative (300+ words). NO 'REF' tags.
116
- Use bullet points and paragraphs.
117
  Return ONLY JSON:
118
  {{
119
  "executive_summary": "Clean narrative summary.",
@@ -143,45 +139,32 @@ with tab1:
143
  st.dataframe(pd.DataFrame(g_data.get('risk_landscape')), hide_index=True, use_container_width=True)
144
 
145
  st.subheader("3. Platform Strategy")
146
- st.dataframe(pd.DataFrame(g_data.get('platform_intelligence')), hide_index=True, use_container_width=True)
147
 
148
- st.success(f"**Conclusion:** {g_data.get('strategic_conclusion')}")
149
-
150
- # DOWNLOAD: λͺ¨λ°”일 ν˜Έν™˜μ„±μ„ μœ„ν•΄ Markdown μ‚¬μš© (λ‚΄μš©μ€ 전체 리포트 100% 동일)
151
- report_md = f"# OMNI-WATCH STRATEGIC REPORT: {keyword.upper()}\n\n"
152
- report_md += f"## 1. EXECUTIVE SUMMARY\n{g_data.get('executive_summary')}\n\n"
153
- report_md += f"## 2. STRATEGIC CONCLUSION\n{g_data.get('strategic_conclusion')}\n\n"
154
- report_md += "## 3. RISK LANDSCAPE\n"
155
- for item in g_data.get('risk_landscape', []):
156
- report_md += f"- **{item['Component']}**: {item['Findings']} (Risk: {item['Risk_Level']})\n"
157
-
158
- st.download_button(
159
- label="πŸ“₯ Download Report (.md)",
160
- data=report_md,
161
- file_name=f"Global_Intel_{datetime.now().strftime('%Y%m%d')}.md",
162
- mime="text/markdown"
163
- )
164
-
165
- # --- [Tab 2: Tactical Forensics] ---
166
  with tab2:
167
- st.header("National Forensics")
168
- target_geo = st.text_input("ISO Code (e.g., US)", "US").upper()
169
- if st.button("Analyze Nation"):
170
- with st.status(f"Scanning {target_geo}...", expanded=True):
171
- # 20+ Sources μˆ˜μ§‘ μœ μ§€
172
- news = fetch_extensive_news(f"{target_geo} social risk", geo=target_geo, limit=40, period="7d")
173
- news_titles = "\n".join([n['title'] for n in news])
174
-
175
- # ν”„λ‘¬ν”„νŠΈ: 4λŒ€ 핡심 ν•„λ“œ(Grid) μ™„λ²½ μœ μ§€
176
  system_prompt = f"""
177
- Identify Top 5 Risks for {target_geo} in English.
 
178
  Summary MUST be a clean narrative (300+ words). NO 'REF' tags.
179
  Return ONLY JSON:
180
  {{
181
  "risks": [
182
  {{
183
  "rank": 1, "title": "..", "score": 90,
184
- "summary": "Clean narrative analysis.",
185
  "forensic_grid": {{
186
  "Policy_Violation": "..",
187
  "Vulnerable_Groups": "..",
@@ -195,38 +178,25 @@ with tab2:
195
  res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}], response_format={"type": "json_object"})
196
  report_data = json.loads(res.choices[0].message.content).get('risks', [])
197
 
198
- full_report_md = f"# NATIONAL FORENSICS: {target_geo}\n\n"
199
 
200
  for i, r in enumerate(report_data):
201
- full_report_md += f"## RISK {r.get('rank')}: {r.get('title')} (Score: {r.get('score')})\n"
202
- full_report_md += f"{r.get('summary')}\n\n"
203
-
204
- with st.expander(f"🚩 {r.get('rank')}. {r.get('title')} (Score: {r.get('score')})", expanded=True):
205
  c1, c2 = st.columns([1, 4])
206
- with c1:
207
- # Forensicsμ—μ„œλŠ” κ²Œμ΄μ§€ 차트 μœ μ§€ (ν‚€ 쀑볡 λ°©μ§€ μ½”λ“œ 포함)
208
- st.plotly_chart(render_gauge(r.get('score'), "Index"), use_container_width=True, key=f"fg_{i}")
209
  with c2:
 
210
  st.markdown(r.get('summary').replace(". ", ".\n\n"))
211
-
212
- st.dataframe(pd.DataFrame(r.get('forensic_grid', {}).items(), columns=["Component", "Finding"]), hide_index=True, use_container_width=True)
213
-
214
- st.download_button(
215
- label="πŸ“₯ Download Forensics (.md)",
216
- data=full_report_md,
217
- file_name=f"National_Forensics_{target_geo}.md",
218
- mime="text/markdown"
219
- )
220
 
221
  st.divider()
222
- st.caption(f"Sources: {len(news)} articles analyzed.")
223
  st.dataframe(pd.DataFrame(news)[['title', 'source']], use_container_width=True)
224
 
225
  # --- [Tab 3: Velocity] ---
226
  with tab3:
227
  st.header("Risk Velocity")
228
- trend_key = st.text_input("Trend Topic", "Disinformation")
229
  if st.button("Check Trend"):
230
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
231
- fig = px.area(x=dates, y=[15, 30, 45, 80, 95, 88, 92], title=f"Trend: {trend_key}")
232
- st.plotly_chart(fig, use_container_width=True)
 
9
  import plotly.graph_objects as go
10
  from datetime import datetime, timedelta
11
 
12
+ # --- 1. Page Config ---
13
+ st.set_page_config(page_title="Omni-Watch Intelligence Master", page_icon="🚨", layout="wide")
14
 
15
  # --- 2. API Key Load ---
16
  api_key = os.environ.get("GROQ_API_KEY")
 
33
  "ME & Africa": ["IL", "SA", "AE", "TR"]
34
  }
35
 
36
+ # --- 4. Core Functions (Recency Optimized) ---
37
  def fetch_extensive_news(query, geo="US", limit=60, period="7d"):
38
+ # μ΅œμ‹  λ‰΄μŠ€ μš°μ„  μˆœμœ„λ₯Ό μœ„ν•΄ 검색어 μ‘°ν•© μ΅œμ ν™”
39
  time_filter = f" when:{period}"
40
  encoded = urllib.parse.quote(query + time_filter)
41
  url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl={geo}&ceid={geo}:en"
 
46
  return articles
47
 
48
  def render_gauge(score, title):
 
49
  fig = go.Figure(go.Indicator(
50
  mode = "gauge+number",
51
  value = score,
 
60
  fig.update_layout(height=180, margin=dict(l=10, r=10, t=40, b=10), paper_bgcolor="rgba(0,0,0,0)")
61
  return fig
62
 
63
+ # --- 5. 🚨 GLOBAL WAR ROOM (12h - Top 3 Numbers) ---
64
  st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
65
+ st.caption(f"Intelligence Baseline: {datetime.now().strftime('%H:%M:%S')} UTC")
66
 
67
+ if st.button("πŸ”„ Refresh War Room"):
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 High-Urgency Feeds..."):
72
+ # μ΅œμ‹  이슈 포착을 μœ„ν•΄ 검색어 κ°•ν™”
73
+ raw_news = fetch_extensive_news("breaking news OR emergency OR crisis", limit=40, period="12h")
74
+ news_context = "\n".join([f"EVENT: {n['title']}" for n in raw_news])
75
+ system_msg = """Identify TOP 3 actual critical incidents from the news titles. Return ONLY JSON: {"issues": [{"title": "..", "score": 85, "summary": ["..", "..", ".."], "link": ".."}]}"""
76
  try:
77
  res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}], response_format={"type": "json_object"})
78
  st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])[:3]
 
83
  for i, issue in enumerate(st.session_state.hot_issues):
84
  with cols[i]:
85
  with st.container(border=True):
 
86
  st.markdown(f"<h1 style='text-align: center; color: #FF4B4B; margin: 0;'>{issue.get('score', 50)}</h1>", unsafe_allow_html=True)
87
  st.markdown("<p style='text-align: center; color: gray; font-size: 0.8em;'>Severity Index</p>", unsafe_allow_html=True)
88
  st.error(f"**{issue.get('title')}**")
89
  for line in issue.get('summary', []): st.caption(f"β€’ {line}")
90
+ st.markdown(f"[πŸ”— Source Link]({issue.get('link')})")
91
 
92
  st.divider()
93
 
94
  # --- 6. Strategic Tabs ---
95
+ tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL SCAN", "πŸ” NATIONAL FORENSICS", "πŸ“ˆ TRENDS"])
96
 
97
+ # --- [Tab 1: Global Scan] ---
98
  with tab1:
99
+ st.header("Strategic Intelligence Briefing (SIB)")
100
+ keyword = st.text_input("Analysis Keyword", "Cyber Terrorism")
101
+ if st.button("Generate Strategic Report", type="primary"):
102
+ with st.status("Gathering 20+ Global Evidence Points...", expanded=True) as status:
103
  all_news = []
104
  for reg in REGION_MAP:
105
  for geo in REGION_MAP[reg][:2]:
106
+ all_news.extend(fetch_extensive_news(keyword, geo=geo, limit=8, period="7d"))
107
+ status.write(f"βœ… Aggregated {len(all_news)} sources. Synthesizing...")
 
108
 
109
  news_summary = "\n".join([n['title'] for n in all_news[:45]])
 
110
  global_prompt = f"""
111
+ Analyze '{keyword}' in English. Executive Summary MUST be a clean narrative (300+ words).
112
+ NO 'REF' tags. Focus on ACTUAL current news trends.
 
113
  Return ONLY JSON:
114
  {{
115
  "executive_summary": "Clean narrative summary.",
 
139
  st.dataframe(pd.DataFrame(g_data.get('risk_landscape')), hide_index=True, use_container_width=True)
140
 
141
  st.subheader("3. Platform Strategy")
142
+ st.table(pd.DataFrame(g_data.get('platform_intelligence')))
143
 
144
+ report_md = f"# OMNI-WATCH GLOBAL REPORT: {keyword.upper()}\n\n{g_data.get('executive_summary')}"
145
+ st.download_button("πŸ“₯ Download Report (.md)", data=report_md, file_name=f"Global_{keyword}.md")
146
+
147
+ # --- [Tab 2: National Forensics - RECENT NEWS FOCUS] ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  with tab2:
149
+ st.header("National Tactical Forensics")
150
+ target_geo = st.text_input("ISO Country Code (e.g., US, KR)", "KR").upper()
151
+ if st.button("Generate Recent Forensic Report"):
152
+ with st.status(f"Capturing ACTUAL recent news for {target_geo}...", expanded=True) as status:
153
+ # 🚨 둜직 μˆ˜μ •: λ‹¨μˆœνžˆ 'social risk'κ°€ μ•„λ‹ˆλΌ μ΅œμ‹  'breaking' 이슈λ₯Ό κ°•μ œλ‘œ κ°€μ Έμ˜΄
154
+ news = fetch_extensive_news(f"{target_geo} breaking news OR controversy OR crisis", geo=target_geo, limit=50, period="7d")
155
+ news_titles = "\n".join([f"NEWS_{i}: {n['title']}" for i, n in enumerate(news)])
156
+ status.write(f"βœ… Captured {len(news)} live headlines. Analyzing situational context...")
157
+
158
  system_prompt = f"""
159
+ Identify Top 5 ACTUAL RECENT Risks for {target_geo} based ONLY on the news headlines provided.
160
+ Do NOT use generic risks. Look for specific events mentioned in the news.
161
  Summary MUST be a clean narrative (300+ words). NO 'REF' tags.
162
  Return ONLY JSON:
163
  {{
164
  "risks": [
165
  {{
166
  "rank": 1, "title": "..", "score": 90,
167
+ "summary": "Specific narrative analysis of the recent event found in news.",
168
  "forensic_grid": {{
169
  "Policy_Violation": "..",
170
  "Vulnerable_Groups": "..",
 
178
  res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}], response_format={"type": "json_object"})
179
  report_data = json.loads(res.choices[0].message.content).get('risks', [])
180
 
181
+
182
 
183
  for i, r in enumerate(report_data):
184
+ with st.expander(f"🚩 RISK {r.get('rank')}: {r.get('title')} (Severity: {r.get('score')})", expanded=True):
 
 
 
185
  c1, c2 = st.columns([1, 4])
186
+ with c1: st.plotly_chart(render_gauge(r.get('score'), "Index"), use_container_width=True, key=f"fg_{i}")
 
 
187
  with c2:
188
+ st.markdown("**Intelligence Narrative:**")
189
  st.markdown(r.get('summary').replace(". ", ".\n\n"))
190
+ st.table(pd.DataFrame(r.get('forensic_grid', {}).items(), columns=["Component", "Finding"]))
 
 
 
 
 
 
 
 
191
 
192
  st.divider()
193
+ st.subheader(f"πŸ“° Actual Source Feed Used ({len(news)} Articles)")
194
  st.dataframe(pd.DataFrame(news)[['title', 'source']], use_container_width=True)
195
 
196
  # --- [Tab 3: Velocity] ---
197
  with tab3:
198
  st.header("Risk Velocity")
199
+ trend_key = st.text_input("Topic", "Election")
200
  if st.button("Check Trend"):
201
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
202
+ st.plotly_chart(px.area(x=dates, y=[10, 20, 40, 70, 95, 85, 90], title=f"Escalation Trend: {trend_key}"), use_container_width=True)