benjamin5607 commited on
Commit
2d6d3d4
Β·
verified Β·
1 Parent(s): 3b1954a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -59
app.py CHANGED
@@ -50,7 +50,7 @@ def render_gauge(score, title):
50
  mode = "gauge+number",
51
  value = score,
52
  domain = {'x': [0, 1], 'y': [0, 1]},
53
- title = {'text': title, 'font': {'size': 18}},
54
  gauge = {
55
  'axis': {'range': [0, 100], 'tickwidth': 1},
56
  'bar': {'color': "#FF4B4B"},
@@ -60,7 +60,7 @@ def render_gauge(score, title):
60
  {'range': [75, 100], 'color': "#ffebee"}],
61
  }
62
  ))
63
- fig.update_layout(height=220, margin=dict(l=20, r=20, t=50, b=20))
64
  return fig
65
 
66
  # --- 5. 🚨 GLOBAL WAR ROOM (12h Window - Fixed 5 Issues) ---
@@ -71,8 +71,8 @@ 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:
74
- with st.spinner("Analyzing fresh 12h security feeds..."):
75
- raw_news = fetch_extensive_news("breaking news crisis risk security", limit=30, period="12h")
76
  news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
77
  system_msg = """Identify TOP 5 critical incidents. Return ONLY JSON: {"issues": [{"title": "..", "score": 85, "summary": ["..", "..", ".."], "link": ".."}]}"""
78
  try:
@@ -85,83 +85,85 @@ if st.session_state.hot_issues:
85
  for i, issue in enumerate(st.session_state.hot_issues):
86
  with cols[i]:
87
  with st.container(border=True):
88
- st.plotly_chart(render_gauge(issue.get('score', 50), "Severity"), use_container_width=True)
89
  st.error(f"**{issue.get('title')}**")
90
  for line in issue.get('summary', []): st.caption(f"β€’ {line}")
91
  st.markdown(f"[πŸ”— Source]({issue.get('link')})")
92
 
93
  st.divider()
94
 
95
- # --- 6. Strategic Tabs (7d Window / Full Analytical Pillars) ---
96
- tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL TRACKING", "πŸ” NATIONAL FORENSICS", "πŸ“ˆ RISK VELOCITY"])
97
 
98
- # --- [Tab 1: Global Tracking] ---
99
  with tab1:
100
- st.header("Executive Strategic Global Tracking (7-Day Depth)")
101
- keyword = st.text_input("Analysis Keyword (Scan 20+ sources)", "Hybrid Warfare")
102
- if st.button("πŸ—ΊοΈ Run Full Spectrum Global Analysis", type="primary"):
103
- with st.status("Gathering Massive Evidence Base...", expanded=True) as status:
104
  all_news = []
105
  for reg in REGION_MAP:
106
  for geo in REGION_MAP[reg][:2]:
107
  all_news.extend(fetch_extensive_news(keyword, geo=geo, limit=6, period="7d"))
108
- status.write(f"βœ… Gathered {len(all_news)} articles. Synthesizing Report...")
109
 
110
-
111
-
112
- news_summary = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(all_news[:40])])
113
  global_prompt = f"""
114
- Analyze '{keyword}' in English using 30+ references.
115
  Return ONLY JSON:
116
  {{
117
- "global_summary": "300+ word detailed narrative citing REFs.",
118
- "analysis_grid": [
119
- {{"Category": "Target Demographics", "Insight": "..."}},
120
- {{"Category": "Policy Violation", "Insight": "..."}},
121
- {{"Category": "Social Impact", "Insight": "..."}},
122
- {{"Category": "Tactical Recommendation", "Insight": "..."}}
123
  ],
124
- "platform_matrix": [
125
- {{"Platform": "TikTok", "Risk": "...", "Action": "..."}},
126
- {{"Platform": "YouTube", "Risk": "...", "Action": "..."}},
127
- {{"Platform": "Meta", "Risk": "...", "Action": "..."}},
128
- {{"Platform": "X", "Risk": "...", "Action": "..."}}
129
- ]
 
130
  }}
131
  """
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"### 🌍 Executive Global Narrative\n{g_data.get('global_summary')}")
 
 
 
 
136
 
137
- c1, c2 = st.columns(2)
138
- with c1:
139
- st.subheader("πŸ” Analytical Factors")
140
- st.table(pd.DataFrame(g_data.get('analysis_grid')))
141
- with c2:
142
- st.subheader("πŸ“± Platform Strategy Matrix")
143
- st.table(pd.DataFrame(g_data.get('platform_matrix')))
144
-
145
- # --- [Tab 2: National Forensics] ---
146
  with tab2:
147
  st.header("National Tactical Forensic Deep-Dive")
148
  target_geo = st.text_input("ISO Country Code", "US").upper()
149
- if st.button("Execute Detailed Forensic Report"):
150
- with st.status(f"Scanning 20+ Sources for {target_geo}...", expanded=True):
151
- news = fetch_extensive_news(f"{target_geo} social controversy", geo=target_geo, limit=40, 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. Summary 300+ words citing REFs.
 
158
  Return ONLY JSON:
159
  {{
160
  "risks": [
161
  {{
162
  "rank": 1, "title": "..", "score": 90, "summary": "..",
163
- "pillars": {{
164
- "Violation": "..", "Demographics": "..", "Impact": "..", "Tactics": ".."
 
 
 
165
  }}
166
  }}
167
  ]
@@ -171,27 +173,24 @@ with tab2:
171
  report_data = json.loads(res.choices[0].message.content).get('risks', [])
172
 
173
  for r in report_data:
174
- with st.container(border=True):
175
  c1, c2 = st.columns([1, 4])
176
- with c1: st.plotly_chart(render_gauge(r.get('score'), "Risk Score"), use_container_width=True)
177
- with c2:
178
- st.subheader(f"🚩 Rank {r.get('rank')}: {r.get('title')}")
179
- st.write(r.get('summary'))
180
-
181
-
182
 
183
  st.markdown("**πŸ›‘οΈ Forensics Intelligence Grid**")
184
- st.table(pd.DataFrame(r.get('pillars', {}).items(), columns=["Pillar", "Insight"]))
 
185
 
186
  st.divider()
187
- st.subheader(f"πŸ“° Evidence Feed ({len(news)} Sources Captured)")
188
  st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
189
 
190
  # --- [Tab 3: Risk Velocity] ---
191
  with tab3:
192
- st.subheader("πŸ“ˆ Risk Velocity & Trend Forecasting")
193
- trend_key = st.text_input("Trend Keyword", "Election Safety")
194
  if st.button("Analyze Velocity"):
195
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
196
- fig = px.area(x=dates, y=[10, 30, 45, 80, 95, 88, 92], title=f"Threat Escallation Trend: {trend_key}")
197
  st.plotly_chart(fig, use_container_width=True)
 
50
  mode = "gauge+number",
51
  value = score,
52
  domain = {'x': [0, 1], 'y': [0, 1]},
53
+ title = {'text': title, 'font': {'size': 18}, 'color': "#FF4B4B"},
54
  gauge = {
55
  'axis': {'range': [0, 100], 'tickwidth': 1},
56
  'bar': {'color': "#FF4B4B"},
 
60
  {'range': [75, 100], 'color': "#ffebee"}],
61
  }
62
  ))
63
+ fig.update_layout(height=180, margin=dict(l=10, r=10, t=40, b=10), paper_bgcolor="rgba(0,0,0,0)")
64
  return fig
65
 
66
  # --- 5. 🚨 GLOBAL WAR ROOM (12h Window - Fixed 5 Issues) ---
 
71
  if 'hot_issues' in st.session_state: del st.session_state.hot_issues
72
 
73
  if 'hot_issues' not in st.session_state:
74
+ with st.spinner("Analyzing high-priority 12h feeds..."):
75
+ raw_news = fetch_extensive_news("breaking news crisis risk security", limit=35, period="12h")
76
  news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
77
  system_msg = """Identify TOP 5 critical incidents. Return ONLY JSON: {"issues": [{"title": "..", "score": 85, "summary": ["..", "..", ".."], "link": ".."}]}"""
78
  try:
 
85
  for i, issue in enumerate(st.session_state.hot_issues):
86
  with cols[i]:
87
  with st.container(border=True):
88
+ st.plotly_chart(render_gauge(issue.get('score', 50), "Severity Index"), use_container_width=True)
89
  st.error(f"**{issue.get('title')}**")
90
  for line in issue.get('summary', []): st.caption(f"β€’ {line}")
91
  st.markdown(f"[πŸ”— Source]({issue.get('link')})")
92
 
93
  st.divider()
94
 
95
+ # --- 6. Strategic Tabs ---
96
+ tab1, tab2, tab3 = st.tabs(["🌐 STRATEGIC GLOBAL SCAN", "πŸ” TACTICAL FORENSICS", "πŸ“ˆ RISK VELOCITY"])
97
 
98
+ # --- [Tab 1: Strategic Global Scan - Professional Format] ---
99
  with tab1:
100
+ st.header("Strategic Intelligence Briefing (SIB)")
101
+ keyword = st.text_input("Analysis Keyword (Scan 20+ sources)", "Cyber Terrorism")
102
+ if st.button("πŸ—ΊοΈ Generate Strategic Briefing", type="primary"):
103
+ with st.status("Aggregating Global Evidence (20+ Sources)...", expanded=True) as status:
104
  all_news = []
105
  for reg in REGION_MAP:
106
  for geo in REGION_MAP[reg][:2]:
107
  all_news.extend(fetch_extensive_news(keyword, geo=geo, limit=6, period="7d"))
108
+ status.write(f"βœ… Gathered {len(all_news)} articles. Synthesizing Final Report...")
109
 
110
+ news_summary = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(all_news[:45])])
 
 
111
  global_prompt = f"""
112
+ Analyze '{keyword}' in English using 30+ references. Follow STRICT Intelligence Format.
113
  Return ONLY JSON:
114
  {{
115
+ "executive_summary": "A high-level overview (300+ words) citing REFs.",
116
+ "risk_landscape": [
117
+ {{"Component": "Target Demographics", "Findings": "...", "Risk_Level": "High"}},
118
+ {{"Component": "Policy Violation", "Findings": "...", "Risk_Level": "Medium"}},
119
+ {{"Component": "Social Impact", "Findings": "...", "Risk_Level": "High"}},
120
+ {{"Component": "Tactical Mitigation", "Findings": "...", "Risk_Level": "Critical"}}
121
  ],
122
+ "platform_intelligence": [
123
+ {{"Platform": "TikTok", "Threat_Assessment": "...", "Counter_Strategy": "..."}},
124
+ {{"Platform": "YouTube", "Threat_Assessment": "...", "Counter_Strategy": "..."}},
125
+ {{"Platform": "Meta", "Threat_Assessment": "...", "Counter_Strategy": "..."}},
126
+ {{"Platform": "X", "Threat_Assessment": "...", "Counter_Strategy": "..."}}
127
+ ],
128
+ "strategic_conclusion": "Final command-level action point."
129
  }}
130
  """
131
  res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": global_prompt}, {"role": "user", "content": news_summary}], response_format={"type": "json_object"})
132
  g_data = json.loads(res.choices[0].message.content)
133
 
134
+ with st.container(border=True):
135
+ st.markdown(f"### πŸ“‘ 1. Executive Summary\n{g_data.get('executive_summary')}")
136
+
137
+ st.markdown("### πŸ“Š 2. Strategic Risk Landscape Matrix")
138
+ st.dataframe(pd.DataFrame(g_data.get('risk_landscape')), hide_index=True, use_container_width=True)
139
 
140
+ st.markdown("### πŸ“± 3. Platform Tactical Response Matrix")
141
+ st.table(pd.DataFrame(g_data.get('platform_intelligence')))
142
+
143
+ st.success(f"### πŸ’‘ 4. Strategic Conclusion\n{g_data.get('strategic_conclusion')}")
144
+
145
+ # --- [Tab 2: Tactical Forensics - Professional Format] ---
 
 
 
146
  with tab2:
147
  st.header("National Tactical Forensic Deep-Dive")
148
  target_geo = st.text_input("ISO Country Code", "US").upper()
149
+ if st.button("Generate National Forensic Report"):
150
+ with st.status(f"Capturing 20+ Source Evidence for {target_geo}...", expanded=True):
151
+ news = fetch_extensive_news(f"{target_geo} social risk", geo=target_geo, limit=40, period="7d")
152
  news_titles = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(news)])
153
 
 
 
154
  system_prompt = f"""
155
+ Identify Top 5 Risks for {target_geo} in English using 30+ references.
156
+ Summary 300+ words per risk citing REFs.
157
  Return ONLY JSON:
158
  {{
159
  "risks": [
160
  {{
161
  "rank": 1, "title": "..", "score": 90, "summary": "..",
162
+ "forensic_grid": {{
163
+ "Policy_Violation": "..",
164
+ "Vulnerable_Groups": "..",
165
+ "Social_Impact": "..",
166
+ "Tactical_Action": ".."
167
  }}
168
  }}
169
  ]
 
173
  report_data = json.loads(res.choices[0].message.content).get('risks', [])
174
 
175
  for r in report_data:
176
+ with st.expander(f"🚩 RISK {r.get('rank')}: {r.get('title')} (Severity: {r.get('score')})", expanded=True):
177
  c1, c2 = st.columns([1, 4])
178
+ with c1: st.plotly_chart(render_gauge(r.get('score'), "Risk Index"), use_container_width=True)
179
+ with c2: st.markdown(f"**Situational Analysis:**\n{r.get('summary')}")
 
 
 
 
180
 
181
  st.markdown("**πŸ›‘οΈ Forensics Intelligence Grid**")
182
+ grid_df = pd.DataFrame(r.get('forensic_grid', {}).items(), columns=["Analytical Component", "Intelligence Finding"])
183
+ st.table(grid_df)
184
 
185
  st.divider()
186
+ st.subheader(f"πŸ“° Source Evidence Feed ({len(news)} Articles)")
187
  st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
188
 
189
  # --- [Tab 3: Risk Velocity] ---
190
  with tab3:
191
+ st.subheader("πŸ“ˆ Risk Velocity & Trend Forecast")
192
+ trend_key = st.text_input("Trend Keyword", "Information War")
193
  if st.button("Analyze Velocity"):
194
  dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
195
+ fig = px.area(x=dates, y=[15, 30, 45, 80, 95, 88, 92], title=f"Risk Escalation Path: {trend_key}")
196
  st.plotly_chart(fig, use_container_width=True)