benjamin5607 commited on
Commit
deb2137
Β·
verified Β·
1 Parent(s): 8ab9bfc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -76
app.py CHANGED
@@ -9,7 +9,7 @@ import plotly.express as px
9
  from datetime import datetime, timedelta
10
  import base64
11
 
12
- # --- Page Config (FIXED) ---
13
  st.set_page_config(page_title="Omni-Watch War Room", page_icon="🚨", layout="wide")
14
 
15
  # --- API Key Load ---
@@ -27,7 +27,6 @@ CURRENT_MODEL = "llama-3.3-70b-versatile"
27
 
28
  # --- Helper Functions ---
29
  def fetch_google_news(query, geo="US", limit=15):
30
- # 'when:12h' filter for real-time freshness
31
  time_filter = " when:12h"
32
  encoded = urllib.parse.quote(query + time_filter)
33
  url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl={geo}&ceid={geo}:en"
@@ -52,76 +51,53 @@ st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
52
  st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}`")
53
 
54
  st.subheader("πŸ”₯ Global Breaking Incidents (Last 12 Hours)")
55
- st.caption("AI-monitored live feeds with 3-line strategic summaries for rapid decision making.")
56
 
57
  if st.button("πŸ”„ Refresh Live Intelligence"):
58
  if 'hot_issues' in st.session_state: del st.session_state.hot_issues
59
 
60
  if 'hot_issues' not in st.session_state:
61
- with st.spinner("Analyzing incidents and generating 3-line summaries..."):
62
  raw_news = fetch_google_news("breaking news risk security crisis controversy", limit=25)
63
  news_context = "\n".join([f"Event: {n['title']} | URL: {n['link']}" for n in raw_news])
64
 
65
  system_msg = """
66
  You are a Senior Strategic Intel Officer. Analyze news from the last 12 hours.
67
- Identify the 3 most dangerous ACTUAL events.
68
- For each, provide a 'three_line_summary':
69
- 1. Core incident description.
70
- 2. Platform/Policy risk impact.
71
- 3. Immediate tactical focus.
72
-
73
- Return ONLY a JSON object:
74
- {
75
- "issues": [
76
- {
77
- "event_title": "Specific Real-time Event Name",
78
- "severity": "CRITICAL/HIGH",
79
- "three_line_summary": ["Line 1", "Line 2", "Line 3"],
80
- "source_link": "Exact URL"
81
- }
82
- ]
83
- }
84
  """
85
- res = client.chat.completions.create(
86
- model=CURRENT_MODEL,
87
- messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}],
88
- response_format={"type": "json_object"}
89
- )
90
- st.session_state.hot_issues = json.loads(res.choices[0].message.content)['issues']
91
-
92
- # Display Live Event Cards with 3-Line Summary
 
 
93
 
 
94
  cols = st.columns(3)
95
  for i, issue in enumerate(st.session_state.hot_issues):
96
- with cols[i]:
97
  with st.container(border=True):
98
- st.error(f"**{issue['event_title']}**")
99
- st.markdown(f"**Threat Level:** `{issue['severity']}`")
100
-
101
- summary_html = "".join([f"<li>{line}</li>" for line in issue['three_line_summary']])
102
  st.markdown(f"<ul style='font-size: 0.85rem; padding-left: 15px;'>{summary_html}</ul>", unsafe_allow_html=True)
103
-
104
- st.markdown(f"[πŸ”— View Source]({issue['source_link']})")
105
 
106
  st.markdown("---")
107
 
108
  # --- Strategic Tabs ---
109
  tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL PROPAGATION", "πŸ” NATIONAL TOP 5 FORENSICS", "πŸ“ˆ RISK VELOCITY TREND"])
110
 
111
- # --- [Tab 1: Global Tracking] ---
112
- with tab1:
113
- st.subheader("Cross-Border Issue Propagation")
114
- keyword = st.text_input("Track Keyword Globally", "Cyber Warfare")
115
- if st.button("Execute Global Intelligence Scan"):
116
- st.info("Scanning global regional nodes...")
117
- st.plotly_chart(px.bar(x=["USA", "UK", "KR", "MY", "DE"], y=[85, 40, 92, 70, 30], title="Propagation Heatmap"))
118
-
119
- # --- [Tab 2: National Top 5 & PDF Download] ---
120
  with tab2:
121
  st.subheader("National Tactical Intelligence")
122
  c1, c2 = st.columns([1, 4])
123
  with c1:
124
- target_geo = st.text_input("Country Code (ISO)", "US").upper()
125
  btn_deep = st.button("Generate Tactical Report", type="primary")
126
 
127
  if btn_deep:
@@ -129,35 +105,31 @@ with tab2:
129
  news = fetch_google_news(f"{target_geo} risk social controversy", geo=target_geo, limit=30)
130
  news_titles = "\n".join([n['title'] for n in news])
131
 
 
132
  system_prompt = """
133
- Identify the TOP 5 most critical platform risks in JSON format.
134
- Include: rank, title, score, summary (300+ words), violation, demographics, tactical_action.
 
135
  """
136
- res = client.chat.completions.create(
137
- model=CURRENT_MODEL,
138
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}],
139
- response_format={"type": "json_object"}
140
- )
141
- report_data = json.loads(res.choices[0].message.content)['risks']
142
-
143
- st.markdown(create_download_link(report_data, f"{target_geo}_Intel.txt"), unsafe_allow_html=True)
144
-
145
-
146
- for r in report_data:
147
- with st.expander(f"🚩 RANK {r['rank']}: {r['title']} (Severity: {r['score']})"):
148
- st.markdown(f"**πŸ“ Intelligence Summary:** {r['summary']}")
149
- st.table(pd.DataFrame({
150
- "Category": ["Policy Breach", "Vulnerable Groups", "Platform Action"],
151
- "Insight": [r['violation'], r['demographics'], r['tactical_action']]
152
- }))
153
-
154
- # --- [Tab 3: Risk Velocity Trend] ---
155
- with tab3:
156
- st.subheader("πŸ“ˆ Risk Velocity & Forecast")
157
- trend_key = st.text_input("Keyword for Trend Analysis", "Election Misinformation")
158
- if st.button("Analyze Trend Velocity"):
159
- dates = [(datetime.now() - timedelta(hours=i*2)).strftime("%H:00") for i in range(6, -1, -1)]
160
- scores = [20, 25, 40, 60, 85, 95, 90]
161
- fig = px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity (Last 12h): {trend_key}")
162
- st.plotly_chart(fig, use_container_width=True)
163
- st.success(f"**AI Prediction:** Risk for '{trend_key}' is escalating. Immediate review required.")
 
9
  from datetime import datetime, timedelta
10
  import base64
11
 
12
+ # --- Page Config ---
13
  st.set_page_config(page_title="Omni-Watch War Room", page_icon="🚨", layout="wide")
14
 
15
  # --- API Key Load ---
 
27
 
28
  # --- Helper Functions ---
29
  def fetch_google_news(query, geo="US", limit=15):
 
30
  time_filter = " when:12h"
31
  encoded = urllib.parse.quote(query + time_filter)
32
  url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl={geo}&ceid={geo}:en"
 
51
  st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}`")
52
 
53
  st.subheader("πŸ”₯ Global Breaking Incidents (Last 12 Hours)")
 
54
 
55
  if st.button("πŸ”„ Refresh Live Intelligence"):
56
  if 'hot_issues' in st.session_state: del st.session_state.hot_issues
57
 
58
  if 'hot_issues' not in st.session_state:
59
+ with st.spinner("Analyzing incidents..."):
60
  raw_news = fetch_google_news("breaking news risk security crisis controversy", limit=25)
61
  news_context = "\n".join([f"Event: {n['title']} | URL: {n['link']}" for n in raw_news])
62
 
63
  system_msg = """
64
  You are a Senior Strategic Intel Officer. Analyze news from the last 12 hours.
65
+ Return ONLY a JSON object with this key: "issues".
66
+ Format: {"issues": [{"event_title": "...", "severity": "...", "three_line_summary": ["...", "...", "..."], "source_link": "..."}]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  """
68
+ try:
69
+ res = client.chat.completions.create(
70
+ model=CURRENT_MODEL,
71
+ messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}],
72
+ response_format={"type": "json_object"}
73
+ )
74
+ st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])
75
+ except Exception as e:
76
+ st.error(f"Error in War Room Analysis: {e}")
77
+ st.session_state.hot_issues = []
78
 
79
+ # Cards display
80
  cols = st.columns(3)
81
  for i, issue in enumerate(st.session_state.hot_issues):
82
+ with cols[i % 3]:
83
  with st.container(border=True):
84
+ st.error(f"**{issue.get('event_title', 'Unknown Event')}**")
85
+ st.markdown(f"**Level:** `{issue.get('severity', 'HIGH')}`")
86
+ summary = issue.get('three_line_summary', ["No summary available"])
87
+ summary_html = "".join([f"<li>{line}</li>" for line in summary])
88
  st.markdown(f"<ul style='font-size: 0.85rem; padding-left: 15px;'>{summary_html}</ul>", unsafe_allow_html=True)
89
+ st.markdown(f"[πŸ”— Source]({issue.get('source_link', '#')})")
 
90
 
91
  st.markdown("---")
92
 
93
  # --- Strategic Tabs ---
94
  tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL PROPAGATION", "πŸ” NATIONAL TOP 5 FORENSICS", "πŸ“ˆ RISK VELOCITY TREND"])
95
 
 
 
 
 
 
 
 
 
 
96
  with tab2:
97
  st.subheader("National Tactical Intelligence")
98
  c1, c2 = st.columns([1, 4])
99
  with c1:
100
+ target_geo = st.text_input("Country Code (ISO)", "KR").upper()
101
  btn_deep = st.button("Generate Tactical Report", type="primary")
102
 
103
  if btn_deep:
 
105
  news = fetch_google_news(f"{target_geo} risk social controversy", geo=target_geo, limit=30)
106
  news_titles = "\n".join([n['title'] for n in news])
107
 
108
+ # --- μˆ˜μ •λœ ν”„λ‘¬ν”„νŠΈμ™€ μ—λŸ¬ λ°©μ§€ 둜직 ---
109
  system_prompt = """
110
+ Identify the TOP 5 most critical platform risks in the country based on the news.
111
+ Return ONLY a valid JSON object with the root key "risks".
112
+ Format: {"risks": [{"rank": 1, "title": "...", "score": 90, "summary": "...", "violation": "...", "demographics": "...", "tactical_action": "..."}]}
113
  """
114
+ try:
115
+ res = client.chat.completions.create(
116
+ model=CURRENT_MODEL,
117
+ messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}],
118
+ response_format={"type": "json_object"}
119
+ )
120
+ raw_content = res.choices[0].message.content
121
+ report_data = json.loads(raw_content).get('risks', [])
122
+
123
+ if not report_data:
124
+ st.warning("AI did not return any specific risks for this search. Try a different country or broader keyword.")
125
+ else:
126
+ st.markdown(create_download_link(report_data, f"{target_geo}_Intel.txt"), unsafe_allow_html=True)
127
+ for r in report_data:
128
+ with st.expander(f"🚩 RANK {r.get('rank', '-')}: {r.get('title', 'No Title')} (Score: {r.get('score', 0)})"):
129
+ st.markdown(f"**πŸ“ Intelligence Summary:** {r.get('summary', 'No summary provided.')}")
130
+ st.table(pd.DataFrame({
131
+ "Category": ["Policy Breach", "Vulnerable Groups", "Platform Action"],
132
+ "Insight": [r.get('violation', 'N/A'), r.get('demographics', 'N/A'), r.get('tactical_action', 'N/A')]
133
+ }))
134
+ except Exception as e:
135
+ st.error(f"Analysis Failed: {e}")