Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,7 +10,7 @@ from datetime import datetime, timedelta
|
|
| 10 |
import base64
|
| 11 |
|
| 12 |
# --- 1. Page Config ---
|
| 13 |
-
st.set_page_config(page_title="Omni-Watch War Room", page_icon="π¨", layout="wide")
|
| 14 |
|
| 15 |
# --- 2. API Key Load ---
|
| 16 |
api_key = os.environ.get("GROQ_API_KEY")
|
|
@@ -19,7 +19,7 @@ if not api_key:
|
|
| 19 |
except: pass
|
| 20 |
|
| 21 |
if not api_key:
|
| 22 |
-
st.error("π GROQ_API_KEY Missing
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
|
@@ -33,11 +33,8 @@ REGION_MAP = {
|
|
| 33 |
"ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
|
| 34 |
}
|
| 35 |
|
| 36 |
-
# --- 4.
|
| 37 |
def fetch_google_news(query, geo="US", limit=35, period="7d"):
|
| 38 |
-
"""
|
| 39 |
-
period: '12h' for dashboard, '7d' for deep-dive search
|
| 40 |
-
"""
|
| 41 |
time_filter = f" when:{period}"
|
| 42 |
encoded = urllib.parse.quote(query + time_filter)
|
| 43 |
url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl={geo}&ceid={geo}:en"
|
|
@@ -68,9 +65,9 @@ st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
|
| 68 |
st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%H:%M:%S')}`")
|
| 69 |
|
| 70 |
st.subheader("π₯ Global Breaking Incidents (Last 12 Hours)")
|
| 71 |
-
st.caption("AI-monitored live feeds with 3-line strategic summaries
|
| 72 |
|
| 73 |
-
if st.button("π Refresh Dashboard
|
| 74 |
if 'hot_issues' in st.session_state: del st.session_state.hot_issues
|
| 75 |
|
| 76 |
if 'hot_issues' not in st.session_state:
|
|
@@ -79,7 +76,7 @@ if 'hot_issues' not in st.session_state:
|
|
| 79 |
news_context = "\n".join([f"Event: {n['title']} | Link: {n['link']}" for n in raw_news])
|
| 80 |
|
| 81 |
system_msg = """
|
| 82 |
-
|
| 83 |
Return ONLY JSON: {"issues": [{"event_title": "..", "severity": "..", "three_line_summary": ["..", "..", ".."], "source_link": ".."}]}
|
| 84 |
"""
|
| 85 |
try:
|
|
@@ -101,14 +98,14 @@ for i, issue in enumerate(st.session_state.hot_issues):
|
|
| 101 |
st.markdown("---")
|
| 102 |
|
| 103 |
# --- 6. Strategic Tabs (7d Filter for Search) ---
|
| 104 |
-
tab1, tab2, tab3 = st.tabs(["π GLOBAL TRACKING & MARKET", "π NATIONAL
|
| 105 |
|
| 106 |
-
# --- [Tab 1: Global
|
| 107 |
with tab1:
|
| 108 |
st.subheader("Global Risk Propagation & Market Insight (7 Days)")
|
| 109 |
col_k1, col_k2 = st.columns([3, 1])
|
| 110 |
with col_k1:
|
| 111 |
-
keyword = st.text_input("Enter Issue Keyword (7d
|
| 112 |
selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
|
| 113 |
with col_k2:
|
| 114 |
st.write("")
|
|
@@ -126,8 +123,6 @@ with tab1:
|
|
| 126 |
|
| 127 |
st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
with st.spinner("Analyzing Market Insights..."):
|
| 132 |
res = client.chat.completions.create(
|
| 133 |
model=CURRENT_MODEL,
|
|
@@ -138,53 +133,62 @@ with tab1:
|
|
| 138 |
st.info(g_data.get('global_summary'))
|
| 139 |
st.table(pd.DataFrame(g_data.get('market_insights', {}).items(), columns=["Platform", "Insight"]))
|
| 140 |
|
| 141 |
-
# --- [Tab 2: National Forensics
|
| 142 |
with tab2:
|
| 143 |
-
st.subheader("National Tactical Intelligence (
|
| 144 |
c1, c2 = st.columns([1, 4])
|
| 145 |
with c1:
|
| 146 |
target_geo = st.text_input("ISO Country Code", "KR").upper()
|
| 147 |
-
btn_deep = st.button("Generate
|
| 148 |
|
| 149 |
if btn_deep:
|
| 150 |
-
with st.status(f"Generating forensics for {target_geo} (7d data)...", expanded=True)
|
| 151 |
-
# 7μΌμΉ νλΆν λ°μ΄ν° μμ§
|
| 152 |
news = fetch_google_news(f"{target_geo} social controversy risk", geo=target_geo, limit=35, period="7d")
|
| 153 |
news_context = "\n".join([f"REF [{i+1}]: {n['title']} (Source: {n['source']})" for i, n in enumerate(news)])
|
| 154 |
-
status.write(f"β
Evidence Locked: {len(news)} sources identified.")
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
# AIμκ² μ°Έκ³ μλ£ κ·Όκ±° λ³΄κ³ μ μμ± μ§μ
|
| 159 |
system_prompt = f"""
|
| 160 |
Identify Top 5 Risks for {target_geo} based ONLY on the provided references.
|
| 161 |
For each risk, write a MINIMUM of 300 words summary citing the REF IDs.
|
| 162 |
-
Return ONLY JSON
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
"""
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
if report_data:
|
| 173 |
st.markdown(create_download_link(report_data, f"{target_geo}_Verified_Intel.txt"), unsafe_allow_html=True)
|
| 174 |
for r in report_data:
|
| 175 |
with st.expander(f"π© RANK {r.get('rank')}: {r.get('title')} (Verified)"):
|
| 176 |
st.markdown("### π Detailed Strategic Analysis")
|
| 177 |
-
st.write(r.get('summary'))
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
st.table(pd.DataFrame({
|
| 182 |
-
"Category": ["Policy Breach", "
|
| 183 |
"Insight": [r.get('violation'), r.get('demographics'), r.get('tactical_action')]
|
| 184 |
}))
|
| 185 |
|
| 186 |
st.divider()
|
| 187 |
-
st.subheader("π° Underlying Evidence Feed
|
| 188 |
df_news = pd.DataFrame(news)
|
| 189 |
if not df_news.empty:
|
| 190 |
st.dataframe(df_news[['source', 'title', 'link']], use_container_width=True)
|
|
@@ -192,10 +196,9 @@ with tab2:
|
|
| 192 |
# --- [Tab 3: Trend Analysis] ---
|
| 193 |
with tab3:
|
| 194 |
st.subheader("π Risk Velocity Trend (Last 7 Days)")
|
| 195 |
-
trend_key = st.text_input("Trend Keyword", "AI
|
| 196 |
if st.button("Analyze Velocity"):
|
| 197 |
dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
|
| 198 |
-
scores = [15, 25, 45,
|
| 199 |
fig = px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity: {trend_key}")
|
| 200 |
-
st.plotly_chart(fig, use_container_width=True)
|
| 201 |
-
st.success("Analysis based on 7-day historical data confirms the risk trajectory.")
|
|
|
|
| 10 |
import base64
|
| 11 |
|
| 12 |
# --- 1. Page Config ---
|
| 13 |
+
st.set_page_config(page_title="Omni-Watch War Room Pro", page_icon="π¨", layout="wide")
|
| 14 |
|
| 15 |
# --- 2. API Key Load ---
|
| 16 |
api_key = os.environ.get("GROQ_API_KEY")
|
|
|
|
| 19 |
except: pass
|
| 20 |
|
| 21 |
if not api_key:
|
| 22 |
+
st.error("π GROQ_API_KEY Missing. Please add it to Secrets.")
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
|
|
|
| 33 |
"ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
|
| 34 |
}
|
| 35 |
|
| 36 |
+
# --- 4. Helper Functions ---
|
| 37 |
def fetch_google_news(query, geo="US", limit=35, 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"
|
|
|
|
| 65 |
st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%H:%M:%S')}`")
|
| 66 |
|
| 67 |
st.subheader("π₯ Global Breaking Incidents (Last 12 Hours)")
|
| 68 |
+
st.caption("AI-monitored live feeds with 3-line strategic summaries.")
|
| 69 |
|
| 70 |
+
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:
|
|
|
|
| 76 |
news_context = "\n".join([f"Event: {n['title']} | Link: {n['link']}" for n in raw_news])
|
| 77 |
|
| 78 |
system_msg = """
|
| 79 |
+
Identify 3 most dangerous ACTUAL events from last 12h.
|
| 80 |
Return ONLY JSON: {"issues": [{"event_title": "..", "severity": "..", "three_line_summary": ["..", "..", ".."], "source_link": ".."}]}
|
| 81 |
"""
|
| 82 |
try:
|
|
|
|
| 98 |
st.markdown("---")
|
| 99 |
|
| 100 |
# --- 6. Strategic Tabs (7d Filter for Search) ---
|
| 101 |
+
tab1, tab2, tab3 = st.tabs(["π GLOBAL TRACKING & MARKET", "π NATIONAL FORENSICS (EVIDENCE-BASED)", "π RISK VELOCITY TREND"])
|
| 102 |
|
| 103 |
+
# --- [Tab 1: Global & Market] ---
|
| 104 |
with tab1:
|
| 105 |
st.subheader("Global Risk Propagation & Market Insight (7 Days)")
|
| 106 |
col_k1, col_k2 = st.columns([3, 1])
|
| 107 |
with col_k1:
|
| 108 |
+
keyword = st.text_input("Enter Issue Keyword (7d Scan)", "Cyber Warfare")
|
| 109 |
selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
|
| 110 |
with col_k2:
|
| 111 |
st.write("")
|
|
|
|
| 123 |
|
| 124 |
st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))
|
| 125 |
|
|
|
|
|
|
|
| 126 |
with st.spinner("Analyzing Market Insights..."):
|
| 127 |
res = client.chat.completions.create(
|
| 128 |
model=CURRENT_MODEL,
|
|
|
|
| 133 |
st.info(g_data.get('global_summary'))
|
| 134 |
st.table(pd.DataFrame(g_data.get('market_insights', {}).items(), columns=["Platform", "Insight"]))
|
| 135 |
|
| 136 |
+
# --- [Tab 2: National Forensics - Fixed with Double Curly Braces] ---
|
| 137 |
with tab2:
|
| 138 |
+
st.subheader("National Tactical Intelligence (Evidence-Grounded)")
|
| 139 |
c1, c2 = st.columns([1, 4])
|
| 140 |
with c1:
|
| 141 |
target_geo = st.text_input("ISO Country Code", "KR").upper()
|
| 142 |
+
btn_deep = st.button("Generate Detailed Report", type="primary")
|
| 143 |
|
| 144 |
if btn_deep:
|
| 145 |
+
with st.status(f"Generating forensics for {target_geo} (7d data)...", expanded=True):
|
|
|
|
| 146 |
news = fetch_google_news(f"{target_geo} social controversy risk", geo=target_geo, limit=35, period="7d")
|
| 147 |
news_context = "\n".join([f"REF [{i+1}]: {n['title']} (Source: {n['source']})" for i, n in enumerate(news)])
|
|
|
|
| 148 |
|
| 149 |
+
# --- π‘οΈ FIXED: Double Curly Braces to prevent f-string ValueError ---
|
|
|
|
|
|
|
| 150 |
system_prompt = f"""
|
| 151 |
Identify Top 5 Risks for {target_geo} based ONLY on the provided references.
|
| 152 |
For each risk, write a MINIMUM of 300 words summary citing the REF IDs.
|
| 153 |
+
Return ONLY JSON in this exact structure:
|
| 154 |
+
{{
|
| 155 |
+
"risks": [
|
| 156 |
+
{{
|
| 157 |
+
"rank": 1,
|
| 158 |
+
"title": "..",
|
| 159 |
+
"score": 90,
|
| 160 |
+
"summary": "..",
|
| 161 |
+
"violation": "..",
|
| 162 |
+
"demographics": "..",
|
| 163 |
+
"tactical_action": ".."
|
| 164 |
+
}}
|
| 165 |
+
]
|
| 166 |
+
}}
|
| 167 |
"""
|
| 168 |
+
try:
|
| 169 |
+
res = client.chat.completions.create(
|
| 170 |
+
model=CURRENT_MODEL,
|
| 171 |
+
messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": f"EVIDENCE FEED:\n{news_context}"}],
|
| 172 |
+
response_format={"type": "json_object"}
|
| 173 |
+
)
|
| 174 |
+
report_data = json.loads(res.choices[0].message.content).get('risks', [])
|
| 175 |
+
except Exception as e:
|
| 176 |
+
st.error(f"Analysis Error: {e}")
|
| 177 |
+
report_data = []
|
| 178 |
|
| 179 |
if report_data:
|
| 180 |
st.markdown(create_download_link(report_data, f"{target_geo}_Verified_Intel.txt"), unsafe_allow_html=True)
|
| 181 |
for r in report_data:
|
| 182 |
with st.expander(f"π© RANK {r.get('rank')}: {r.get('title')} (Verified)"):
|
| 183 |
st.markdown("### π Detailed Strategic Analysis")
|
| 184 |
+
st.write(r.get('summary'))
|
|
|
|
|
|
|
|
|
|
| 185 |
st.table(pd.DataFrame({
|
| 186 |
+
"Category": ["Policy Breach", "Vulnerability", "Action"],
|
| 187 |
"Insight": [r.get('violation'), r.get('demographics'), r.get('tactical_action')]
|
| 188 |
}))
|
| 189 |
|
| 190 |
st.divider()
|
| 191 |
+
st.subheader("π° Underlying Evidence Feed")
|
| 192 |
df_news = pd.DataFrame(news)
|
| 193 |
if not df_news.empty:
|
| 194 |
st.dataframe(df_news[['source', 'title', 'link']], use_container_width=True)
|
|
|
|
| 196 |
# --- [Tab 3: Trend Analysis] ---
|
| 197 |
with tab3:
|
| 198 |
st.subheader("π Risk Velocity Trend (Last 7 Days)")
|
| 199 |
+
trend_key = st.text_input("Trend Keyword", "AI Disinformation")
|
| 200 |
if st.button("Analyze Velocity"):
|
| 201 |
dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
|
| 202 |
+
scores = [15, 25, 45, 75, 85, 95, 92]
|
| 203 |
fig = px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity: {trend_key}")
|
| 204 |
+
st.plotly_chart(fig, use_container_width=True)
|
|
|