Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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=
|
| 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
|
| 75 |
-
raw_news = fetch_extensive_news("breaking news crisis risk security", limit=
|
| 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
|
| 96 |
-
tab1, tab2, tab3 = st.tabs(["π GLOBAL
|
| 97 |
|
| 98 |
-
# --- [Tab 1: Global
|
| 99 |
with tab1:
|
| 100 |
-
st.header("
|
| 101 |
-
keyword = st.text_input("Analysis Keyword (Scan 20+ sources)", "
|
| 102 |
-
if st.button("πΊοΈ
|
| 103 |
-
with st.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 |
-
"
|
| 118 |
-
"
|
| 119 |
-
{{"
|
| 120 |
-
{{"
|
| 121 |
-
{{"
|
| 122 |
-
{{"
|
| 123 |
],
|
| 124 |
-
"
|
| 125 |
-
{{"Platform": "TikTok", "
|
| 126 |
-
{{"Platform": "YouTube", "
|
| 127 |
-
{{"Platform": "Meta", "
|
| 128 |
-
{{"Platform": "X", "
|
| 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.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 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("
|
| 150 |
-
with st.status(f"
|
| 151 |
-
news = fetch_extensive_news(f"{target_geo} social
|
| 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 |
Return ONLY JSON:
|
| 159 |
{{
|
| 160 |
"risks": [
|
| 161 |
{{
|
| 162 |
"rank": 1, "title": "..", "score": 90, "summary": "..",
|
| 163 |
-
"
|
| 164 |
-
"
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 175 |
c1, c2 = st.columns([1, 4])
|
| 176 |
-
with c1: st.plotly_chart(render_gauge(r.get('score'), "Risk
|
| 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 |
-
|
|
|
|
| 185 |
|
| 186 |
st.divider()
|
| 187 |
-
st.subheader(f"π° Evidence Feed ({len(news)}
|
| 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
|
| 193 |
-
trend_key = st.text_input("Trend Keyword", "
|
| 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=[
|
| 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)
|