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
|
| 14 |
|
| 15 |
# --- 2. API Key Load ---
|
| 16 |
api_key = os.environ.get("GROQ_API_KEY")
|
|
@@ -19,13 +19,13 @@ 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)
|
| 26 |
CURRENT_MODEL = "llama-3.3-70b-versatile"
|
| 27 |
|
| 28 |
-
# --- 3. Configuration
|
| 29 |
REGION_MAP = {
|
| 30 |
"Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "IN", "AU", "SG"],
|
| 31 |
"Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL"],
|
|
@@ -33,7 +33,7 @@ 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 |
time_filter = f" when:{period}"
|
| 39 |
encoded = urllib.parse.quote(query + time_filter)
|
|
@@ -49,29 +49,29 @@ def fetch_google_news(query, geo="US", limit=35, period="7d"):
|
|
| 49 |
return articles
|
| 50 |
|
| 51 |
def create_download_link(data, filename="Full_Strategic_Intel.txt"):
|
| 52 |
-
report_text = f"--- FULL STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d
|
| 53 |
for item in data:
|
| 54 |
report_text += f"RANK {item.get('rank', '-')}: {item.get('title', 'N/A')}\n"
|
| 55 |
-
report_text += f"
|
| 56 |
-
report_text += f"
|
| 57 |
report_text += f"TARGET DEMOGRAPHICS: {item.get('demographics', 'N/A')}\n"
|
| 58 |
report_text += f"SOCIAL IMPACT: {item.get('social_impact', 'N/A')}\n"
|
| 59 |
-
report_text += f"TACTICAL ACTION
|
| 60 |
b64 = base64.b64encode(report_text.encode()).decode()
|
| 61 |
-
return f'<a href="data:file/txt;base64,{b64}" download="{filename}"><button style="background-color:#FF4B4B; color:white; border:none; padding:10px 20px; border-radius:5px; cursor:pointer;">π₯ Download
|
| 62 |
|
| 63 |
-
# --- 5. π¨
|
| 64 |
st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 65 |
-
st.markdown(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("Analyzing
|
| 72 |
raw_news = fetch_google_news("breaking news risk security crisis", limit=20, period="12h")
|
| 73 |
news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
|
| 74 |
-
system_msg = """Identify 3 most
|
| 75 |
try:
|
| 76 |
res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}], response_format={"type": "json_object"})
|
| 77 |
st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])
|
|
@@ -85,131 +85,117 @@ for i, issue in enumerate(st.session_state.hot_issues):
|
|
| 85 |
for line in issue.get('three_line_summary', []): st.markdown(f"- {line}")
|
| 86 |
st.markdown(f"[π View Source]({issue.get('source_link')})")
|
| 87 |
|
| 88 |
-
st.
|
| 89 |
|
| 90 |
-
# --- 6. Strategic Tabs ---
|
| 91 |
-
tab1, tab2, tab3 = st.tabs(["π GLOBAL TRACKING & MARKET", "π NATIONAL
|
| 92 |
|
| 93 |
-
# --- [Tab 1: Global & Market
|
| 94 |
with tab1:
|
| 95 |
-
st.subheader("Global Risk Propagation &
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
st.write("")
|
| 102 |
-
run_global = st.button("πΊοΈ Run Global Scan", type="primary", use_container_width=True)
|
| 103 |
-
|
| 104 |
-
if run_global:
|
| 105 |
target_countries = []
|
| 106 |
for reg in selected_regions: target_countries.extend(REGION_MAP[reg])
|
| 107 |
-
results = []
|
| 108 |
-
all_news_tab1 = []
|
| 109 |
-
progress = st.progress(0)
|
| 110 |
-
for i, geo in enumerate(target_countries):
|
| 111 |
-
n_list = fetch_google_news(keyword, geo=geo, limit=5, period="7d")
|
| 112 |
-
all_news_tab1.extend(n_list)
|
| 113 |
-
results.append({"Country": geo, "Risk": min(len(n_list) * 20, 100)})
|
| 114 |
-
progress.progress((i + 1) / len(target_countries))
|
| 115 |
|
| 116 |
-
st.
|
|
|
|
|
|
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
-
with st.spinner("Synthesizing Full Strategic
|
| 121 |
-
news_summary = "\n".join([
|
| 122 |
-
#
|
| 123 |
-
|
| 124 |
-
Analyze '{keyword}' based on provided news. Return ONLY JSON:
|
| 125 |
{{
|
| 126 |
-
"global_summary": "
|
| 127 |
"analysis_fields": {{
|
| 128 |
-
"Target_Demographics": "
|
| 129 |
-
"Guideline_Violation": "
|
| 130 |
"Social_Impact": "Societal and political consequences.",
|
| 131 |
-
"
|
| 132 |
}},
|
| 133 |
"platform_analysis": {{
|
| 134 |
-
"TikTok": "
|
| 135 |
-
"YouTube": "
|
| 136 |
-
"Meta": "
|
| 137 |
-
"X": "
|
| 138 |
}}
|
| 139 |
}}
|
| 140 |
"""
|
| 141 |
try:
|
| 142 |
-
res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content":
|
| 143 |
g_data = json.loads(res.choices[0].message.content)
|
| 144 |
|
| 145 |
-
st.info(f"**π Global
|
| 146 |
|
| 147 |
-
#
|
| 148 |
-
st.markdown("### π Risk Factor Breakdown")
|
| 149 |
-
st.table(pd.DataFrame(g_data.get('analysis_fields', {
|
| 150 |
|
| 151 |
-
st.markdown("### π± Platform Tactical
|
| 152 |
-
st.table(pd.DataFrame(g_data.get('platform_analysis', {
|
| 153 |
-
except Exception as e: st.error(f"Synthesis
|
| 154 |
|
| 155 |
-
# --- [Tab 2: National Forensics -
|
| 156 |
with tab2:
|
| 157 |
-
st.subheader("National Tactical Intelligence (7-Day Evidence)")
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
if btn_deep:
|
| 164 |
-
with st.status(f"Generating Deep-Dive for {target_geo}...", expanded=True):
|
| 165 |
-
news = fetch_google_news(f"{target_geo} social controversy", geo=target_geo, limit=35, period="7d")
|
| 166 |
-
news_context = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(news)])
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
-
# ESCAPED BRACES {{ }} FOR JSON
|
| 171 |
system_prompt = f"""
|
| 172 |
Identify Top 5 Risks for {target_geo} in English.
|
| 173 |
-
|
| 174 |
Return ONLY JSON:
|
| 175 |
{{
|
| 176 |
"risks": [
|
| 177 |
{{
|
| 178 |
-
"rank": 1, "title": "..", "score": 90,
|
|
|
|
| 179 |
"violation": "Specific guideline breach",
|
| 180 |
-
"demographics": "
|
| 181 |
-
"social_impact": "
|
| 182 |
-
"tactical_action": "Platform
|
| 183 |
}}
|
| 184 |
]
|
| 185 |
}}
|
| 186 |
"""
|
| 187 |
try:
|
| 188 |
-
res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content":
|
| 189 |
report_data = json.loads(res.choices[0].message.content).get('risks', [])
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
st.
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
st.divider()
|
| 206 |
-
st.subheader("π° Evidence Feed (7-Day)")
|
| 207 |
-
st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
|
| 208 |
|
| 209 |
# --- [Tab 3: Risk Velocity] ---
|
| 210 |
with tab3:
|
| 211 |
-
st.subheader("π Risk Velocity
|
| 212 |
-
trend_key = st.text_input("Trend Keyword", "
|
| 213 |
if st.button("Analyze Velocity"):
|
| 214 |
dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
|
| 215 |
-
st.plotly_chart(px.line(x=dates, y=[15, 25,
|
|
|
|
| 10 |
import base64
|
| 11 |
|
| 12 |
# --- 1. Page Config ---
|
| 13 |
+
st.set_page_config(page_title="Omni-Watch Intelligence Center", 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 check your deployment settings.")
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
| 26 |
CURRENT_MODEL = "llama-3.3-70b-versatile"
|
| 27 |
|
| 28 |
+
# --- 3. Configuration ---
|
| 29 |
REGION_MAP = {
|
| 30 |
"Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "IN", "AU", "SG"],
|
| 31 |
"Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL"],
|
|
|
|
| 33 |
"ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
|
| 34 |
}
|
| 35 |
|
| 36 |
+
# --- 4. News Fetching Logic (Dual-Timeline) ---
|
| 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)
|
|
|
|
| 49 |
return articles
|
| 50 |
|
| 51 |
def create_download_link(data, filename="Full_Strategic_Intel.txt"):
|
| 52 |
+
report_text = f"--- FULL STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d')}) ---\n\n"
|
| 53 |
for item in data:
|
| 54 |
report_text += f"RANK {item.get('rank', '-')}: {item.get('title', 'N/A')}\n"
|
| 55 |
+
report_text += f"ANALYSIS: {item.get('summary', 'N/A')}\n"
|
| 56 |
+
report_text += f"GUIDELINE VIOLATION: {item.get('violation', 'N/A')}\n"
|
| 57 |
report_text += f"TARGET DEMOGRAPHICS: {item.get('demographics', 'N/A')}\n"
|
| 58 |
report_text += f"SOCIAL IMPACT: {item.get('social_impact', 'N/A')}\n"
|
| 59 |
+
report_text += f"TACTICAL ACTION: {item.get('tactical_action', 'N/A')}\n\n"
|
| 60 |
b64 = base64.b64encode(report_text.encode()).decode()
|
| 61 |
+
return f'<a href="data:file/txt;base64,{b64}" download="{filename}"><button style="background-color:#FF4B4B; color:white; border:none; padding:10px 20px; border-radius:5px; cursor:pointer;">π₯ Download Strategic Report</button></a>'
|
| 62 |
|
| 63 |
+
# --- 5. π¨ War Room (12-Hour Freshness) ---
|
| 64 |
st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 65 |
+
st.markdown(f"**Emergency Intelligence Feed (12h Window):** `{datetime.now().strftime('%H:%M:%S')} UTC`")
|
| 66 |
|
| 67 |
+
if st.button("π Refresh Dashboard"):
|
| 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 urgent feeds..."):
|
| 72 |
raw_news = fetch_google_news("breaking news risk security crisis", limit=20, period="12h")
|
| 73 |
news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
|
| 74 |
+
system_msg = """Identify 3 most critical events. Return ONLY JSON: {"issues": [{"event_title": "..", "three_line_summary": ["..", "..", ".."], "source_link": ".."}]}"""
|
| 75 |
try:
|
| 76 |
res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}], response_format={"type": "json_object"})
|
| 77 |
st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])
|
|
|
|
| 85 |
for line in issue.get('three_line_summary', []): st.markdown(f"- {line}")
|
| 86 |
st.markdown(f"[π View Source]({issue.get('source_link')})")
|
| 87 |
|
| 88 |
+
st.divider()
|
| 89 |
|
| 90 |
+
# --- 6. Strategic Tabs (7-Day Horizon) ---
|
| 91 |
+
tab1, tab2, tab3 = st.tabs(["π GLOBAL TRACKING & MARKET", "π NATIONAL DEEP-DIVE", "π RISK VELOCITY"])
|
| 92 |
|
| 93 |
+
# --- [Tab 1: Global Tracking & Full Market Insight] ---
|
| 94 |
with tab1:
|
| 95 |
+
st.subheader("Global Risk Propagation & Market Intelligence (7 Days)")
|
| 96 |
+
keyword = st.text_input("Deep Scan Keyword", "Digital Propaganda")
|
| 97 |
+
selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
|
| 98 |
+
|
| 99 |
+
if st.button("πΊοΈ Execute Global Analysis", type="primary"):
|
| 100 |
+
all_news_tab1 = []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
target_countries = []
|
| 102 |
for reg in selected_regions: target_countries.extend(REGION_MAP[reg])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
with st.spinner("Gathering global news nodes..."):
|
| 105 |
+
for geo in target_countries[:12]: # Balanced for API speed
|
| 106 |
+
all_news_tab1.extend(fetch_google_news(keyword, geo=geo, limit=5, period="7d"))
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
+
with st.spinner("Synthesizing Full-Spectrum Strategic Report..."):
|
| 111 |
+
news_summary = "\n".join([n['title'] for n in all_news_tab1[:30]])
|
| 112 |
+
# Double curly braces {{ }} for f-string JSON
|
| 113 |
+
global_prompt = f"""
|
| 114 |
+
Analyze '{keyword}' based on provided news. Return ONLY JSON in English:
|
| 115 |
{{
|
| 116 |
+
"global_summary": "300+ word narrative on propagation and threat level.",
|
| 117 |
"analysis_fields": {{
|
| 118 |
+
"Target_Demographics": "Detailed analysis of targeted groups.",
|
| 119 |
+
"Guideline_Violation": "Relevant community policy breaches.",
|
| 120 |
"Social_Impact": "Societal and political consequences.",
|
| 121 |
+
"Tactical_Action": "Global mitigation recommendation."
|
| 122 |
}},
|
| 123 |
"platform_analysis": {{
|
| 124 |
+
"TikTok": "Platform-specific risk insight.",
|
| 125 |
+
"YouTube": "Platform-specific risk insight.",
|
| 126 |
+
"Meta": "Platform-specific risk insight.",
|
| 127 |
+
"X": "Platform-specific risk insight."
|
| 128 |
}}
|
| 129 |
}}
|
| 130 |
"""
|
| 131 |
try:
|
| 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"**π Global Intelligence Narrative:**\n\n{g_data.get('global_summary')}")
|
| 136 |
|
| 137 |
+
# FULL SPECTRUM FIELDS IN TAB 1
|
| 138 |
+
st.markdown("### π Global Risk Factor Breakdown")
|
| 139 |
+
st.table(pd.DataFrame(g_data.get('analysis_fields', {}).items(), columns=["Metric", "Intelligence Insight"]))
|
| 140 |
|
| 141 |
+
st.markdown("### π± Platform-Specific Market Tactical Insights")
|
| 142 |
+
st.table(pd.DataFrame(g_data.get('platform_analysis', {}).items(), columns=["Platform", "Strategic Action"]))
|
| 143 |
+
except Exception as e: st.error(f"Synthesis failed: {e}")
|
| 144 |
|
| 145 |
+
# --- [Tab 2: National Forensics - EVERY FIELD INCLUDED] ---
|
| 146 |
with tab2:
|
| 147 |
+
st.subheader("National Tactical Intelligence (Verified 7-Day Evidence)")
|
| 148 |
+
target_geo = st.text_input("ISO Country Code (e.g., US, KR, GB)", "US").upper()
|
| 149 |
+
if st.button("Generate National Forensics Report"):
|
| 150 |
+
with st.status(f"Scanning Evidence for {target_geo}...", expanded=True):
|
| 151 |
+
news = fetch_google_news(f"{target_geo} social risk controversy", geo=target_geo, limit=30, 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.
|
| 158 |
+
For each risk, provide 300+ word summary citing REFs.
|
| 159 |
Return ONLY JSON:
|
| 160 |
{{
|
| 161 |
"risks": [
|
| 162 |
{{
|
| 163 |
+
"rank": 1, "title": "..", "score": 90,
|
| 164 |
+
"summary": "Deep analysis citing REFs",
|
| 165 |
"violation": "Specific guideline breach",
|
| 166 |
+
"demographics": "Targeted groups",
|
| 167 |
+
"social_impact": "Socio-political impact",
|
| 168 |
+
"tactical_action": "Platform mitigation steps"
|
| 169 |
}}
|
| 170 |
]
|
| 171 |
}}
|
| 172 |
"""
|
| 173 |
try:
|
| 174 |
+
res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}], response_format={"type": "json_object"})
|
| 175 |
report_data = json.loads(res.choices[0].message.content).get('risks', [])
|
| 176 |
+
|
| 177 |
+
if report_data:
|
| 178 |
+
st.markdown(create_download_link(report_data, f"{target_geo}_Deep_Intel.txt"), unsafe_allow_html=True)
|
| 179 |
+
for r in report_data:
|
| 180 |
+
with st.expander(f"π© RANK {r.get('rank')}: {r.get('title')} (Risk: {r.get('score')})"):
|
| 181 |
+
st.write(r.get('summary'))
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
st.table(pd.DataFrame({
|
| 186 |
+
"Category": ["Violation", "Target Group", "Social Impact", "Tactical Action"],
|
| 187 |
+
"Insight": [r.get('violation'), r.get('demographics'), r.get('social_impact'), r.get('tactical_action')]
|
| 188 |
+
}))
|
| 189 |
|
| 190 |
+
st.divider()
|
| 191 |
+
st.subheader("π° Underlying Evidence Feed")
|
| 192 |
+
st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
|
| 193 |
+
except Exception as e: st.error(f"Forensics error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
# --- [Tab 3: Risk Velocity] ---
|
| 196 |
with tab3:
|
| 197 |
+
st.subheader("π Risk Velocity & Forecast (Last 7 Days)")
|
| 198 |
+
trend_key = st.text_input("Trend Keyword", "AI Disinformation")
|
| 199 |
if st.button("Analyze Velocity"):
|
| 200 |
dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
|
| 201 |
+
st.plotly_chart(px.line(x=dates, y=[15, 25, 55, 70, 95, 90, 85], markers=True, title=f"Risk Score Velocity: {trend_key}"), use_container_width=True)
|