Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
| 13 |
-
st.set_page_config(page_title="Omni-Watch
|
| 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 (
|
| 64 |
st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 65 |
-
st.caption(f"
|
| 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("
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 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:
|
| 99 |
with tab1:
|
| 100 |
-
st.header("Strategic Briefing (SIB)")
|
| 101 |
-
keyword = st.text_input("Keyword", "Cyber
|
| 102 |
-
if st.button("Generate Report", type="primary"):
|
| 103 |
-
with st.status("
|
| 104 |
all_news = []
|
| 105 |
for reg in REGION_MAP:
|
| 106 |
for geo in REGION_MAP[reg][:2]:
|
| 107 |
-
|
| 108 |
-
|
| 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 |
-
|
| 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.
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 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)", "
|
| 169 |
-
if st.button("
|
| 170 |
-
with st.status(f"
|
| 171 |
-
#
|
| 172 |
-
news = fetch_extensive_news(f"{target_geo}
|
| 173 |
-
news_titles = "\n".join([n['title'] for n in news])
|
| 174 |
-
|
| 175 |
-
|
| 176 |
system_prompt = f"""
|
| 177 |
-
Identify Top 5 Risks for {target_geo}
|
|
|
|
| 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": "
|
| 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 |
-
|
| 199 |
|
| 200 |
for i, r in enumerate(report_data):
|
| 201 |
-
|
| 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.
|
| 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("
|
| 229 |
if st.button("Check Trend"):
|
| 230 |
dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
|
| 231 |
-
|
| 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)
|
|
|