Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -35,9 +35,6 @@ REGION_MAP = {
|
|
| 35 |
|
| 36 |
# --- 4. Helper Functions ---
|
| 37 |
def fetch_google_news(query, geo="US", limit=35, period="7d"):
|
| 38 |
-
"""
|
| 39 |
-
Fixed f-string syntax error: gl={geo} instead of gl=geo}
|
| 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"
|
|
@@ -55,27 +52,26 @@ def create_download_link(data, filename="Full_Strategic_Intel.txt"):
|
|
| 55 |
report_text = f"--- FULL STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n\n"
|
| 56 |
for item in data:
|
| 57 |
report_text += f"RANK {item.get('rank', '-')}: {item.get('title', 'N/A')}\n"
|
| 58 |
-
report_text += f"SCORE: {item.get('score', 0)}/100\n"
|
| 59 |
report_text += f"DETAILED ANALYSIS: {item.get('summary', 'N/A')}\n"
|
| 60 |
-
report_text += f"
|
| 61 |
report_text += f"TARGET DEMOGRAPHICS: {item.get('demographics', 'N/A')}\n"
|
| 62 |
report_text += f"SOCIAL IMPACT: {item.get('social_impact', 'N/A')}\n"
|
| 63 |
report_text += f"TACTICAL ACTION PLAN: {item.get('tactical_action', 'N/A')}\n\n"
|
| 64 |
b64 = base64.b64encode(report_text.encode()).decode()
|
| 65 |
-
return f'<a href="data:file/txt;base64,{b64}" download="{filename}"
|
| 66 |
|
| 67 |
# --- 5. π¨ Main Dashboard: WAR ROOM (12h Filter) ---
|
| 68 |
st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 69 |
-
st.markdown(f"**Live
|
| 70 |
|
| 71 |
-
if st.button("π Refresh War Room"):
|
| 72 |
if 'hot_issues' in st.session_state: del st.session_state.hot_issues
|
| 73 |
|
| 74 |
if 'hot_issues' not in st.session_state:
|
| 75 |
with st.spinner("Analyzing ultra-fresh 12-hour incidents..."):
|
| 76 |
-
raw_news = fetch_google_news("breaking news risk security crisis
|
| 77 |
-
news_context = "\n".join([f"Event: {n['title']}
|
| 78 |
-
system_msg = """Identify 3 most dangerous events from last 12h. Return ONLY JSON: {"issues": [{"event_title": "..", "severity": "..", "three_line_summary": ["..", "..", ".."], "source_link": ".."}]}"""
|
| 79 |
try:
|
| 80 |
res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}], response_format={"type": "json_object"})
|
| 81 |
st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])
|
|
@@ -94,12 +90,12 @@ st.markdown("---")
|
|
| 94 |
# --- 6. Strategic Tabs ---
|
| 95 |
tab1, tab2, tab3 = st.tabs(["π GLOBAL TRACKING & MARKET", "π NATIONAL TOP 5 FORENSICS", "π RISK VELOCITY TREND"])
|
| 96 |
|
| 97 |
-
# --- [Tab 1: Global & Market -
|
| 98 |
with tab1:
|
| 99 |
-
st.subheader("Global Risk Propagation & Strategic Market Insight")
|
| 100 |
col_k1, col_k2 = st.columns([3, 1])
|
| 101 |
with col_k1:
|
| 102 |
-
keyword = st.text_input("Enter Issue Keyword (7d Deep Scan)", "
|
| 103 |
selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
|
| 104 |
with col_k2:
|
| 105 |
st.write("")
|
|
@@ -119,75 +115,88 @@ with tab1:
|
|
| 119 |
|
| 120 |
st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))
|
| 121 |
|
| 122 |
-
|
|
|
|
|
|
|
| 123 |
news_summary = "\n".join([f"- {n['title']}" for n in all_news_tab1[:25]])
|
| 124 |
-
#
|
| 125 |
market_prompt = f"""
|
| 126 |
-
Analyze '{keyword}'
|
| 127 |
-
Return ONLY JSON:
|
| 128 |
{{
|
| 129 |
-
"global_summary": "Detailed narrative (300+ words) on propagation
|
| 130 |
-
"
|
| 131 |
-
"Target_Demographics": "
|
| 132 |
-
"Guideline_Violation": "
|
| 133 |
-
"Social_Impact": "
|
| 134 |
-
"
|
| 135 |
}},
|
| 136 |
"platform_analysis": {{
|
| 137 |
-
"TikTok": "
|
| 138 |
-
"YouTube": "
|
| 139 |
-
"Meta": "
|
| 140 |
-
"X": "
|
| 141 |
}}
|
| 142 |
}}
|
| 143 |
"""
|
| 144 |
try:
|
| 145 |
res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": market_prompt}, {"role": "user", "content": f"News:\n{news_summary}"}], response_format={"type": "json_object"})
|
| 146 |
g_data = json.loads(res.choices[0].message.content)
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
| 148 |
st.markdown("### π Risk Factor Breakdown")
|
| 149 |
-
st.table(pd.DataFrame(g_data.get('
|
|
|
|
| 150 |
st.markdown("### π± Platform Tactical Recommendations")
|
| 151 |
st.table(pd.DataFrame(g_data.get('platform_analysis', {{}}).items(), columns=["Platform", "Strategic Insight"]))
|
| 152 |
except Exception as e: st.error(f"Synthesis error: {e}")
|
| 153 |
|
| 154 |
-
# --- [Tab 2: National Forensics -
|
| 155 |
with tab2:
|
| 156 |
-
st.subheader("National Tactical Intelligence (
|
| 157 |
c1, c2 = st.columns([1, 4])
|
| 158 |
with c1:
|
| 159 |
target_geo = st.text_input("ISO Country Code", "US").upper()
|
| 160 |
btn_deep = st.button("Generate National Report", type="primary")
|
| 161 |
|
| 162 |
if btn_deep:
|
| 163 |
-
with st.status(f"Generating Deep-Dive for {target_geo}
|
| 164 |
-
news = fetch_google_news(f"{target_geo} social
|
| 165 |
news_context = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(news)])
|
| 166 |
|
|
|
|
|
|
|
|
|
|
| 167 |
system_prompt = f"""
|
| 168 |
-
|
| 169 |
-
Include: violation, demographics, social_impact, tactical_action.
|
| 170 |
Summary must be 300+ words citing REF IDs.
|
| 171 |
Return ONLY JSON:
|
| 172 |
{{
|
| 173 |
"risks": [
|
| 174 |
{{
|
| 175 |
"rank": 1, "title": "..", "score": 90, "summary": "..",
|
| 176 |
-
"violation": "
|
|
|
|
|
|
|
|
|
|
| 177 |
}}
|
| 178 |
]
|
| 179 |
}}
|
| 180 |
"""
|
| 181 |
try:
|
| 182 |
-
res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": f"Evidence
|
| 183 |
report_data = json.loads(res.choices[0].message.content).get('risks', [])
|
| 184 |
except: report_data = []
|
| 185 |
|
| 186 |
if report_data:
|
| 187 |
-
st.markdown(create_download_link(report_data, f"{target_geo}
|
| 188 |
for r in report_data:
|
| 189 |
with st.expander(f"π© RANK {r.get('rank')}: {r.get('title')} (Verified)"):
|
| 190 |
st.markdown(f"**Detailed Analysis:**\n{r.get('summary')}")
|
|
|
|
|
|
|
|
|
|
| 191 |
st.table(pd.DataFrame({
|
| 192 |
"Category": ["Violation", "Target Group", "Social Impact", "Tactical Action"],
|
| 193 |
"Intelligence": [r.get('violation'), r.get('demographics'), r.get('social_impact'), r.get('tactical_action')]
|
|
@@ -195,15 +204,12 @@ with tab2:
|
|
| 195 |
|
| 196 |
st.divider()
|
| 197 |
st.subheader("π° Evidence Feed (7-Day)")
|
| 198 |
-
|
| 199 |
-
if not df_news.empty:
|
| 200 |
-
st.dataframe(df_news[['source', 'title', 'link']], use_container_width=True)
|
| 201 |
|
| 202 |
-
# --- [Tab 3: Risk Velocity
|
| 203 |
with tab3:
|
| 204 |
st.subheader("π Risk Velocity Trend (Last 7 Days)")
|
| 205 |
-
trend_key = st.text_input("Trend Keyword", "
|
| 206 |
if st.button("Analyze Velocity"):
|
| 207 |
dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
|
| 208 |
-
|
| 209 |
-
st.plotly_chart(px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity: {trend_key}"), use_container_width=True)
|
|
|
|
| 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"
|
|
|
|
| 52 |
report_text = f"--- FULL STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\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"DETAILED ANALYSIS: {item.get('summary', 'N/A')}\n"
|
| 56 |
+
report_text += f"POLICY 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 PLAN: {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 Full Report (.txt)</button></a>'
|
| 62 |
|
| 63 |
# --- 5. π¨ Main Dashboard: WAR ROOM (12h Filter) ---
|
| 64 |
st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 65 |
+
st.markdown(f"**Live Analysis (UTC):** `{datetime.now().strftime('%H:%M:%S')}`")
|
| 66 |
|
| 67 |
+
if st.button("π Refresh War Room (12h Scan)"):
|
| 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 ultra-fresh 12-hour incidents..."):
|
| 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 dangerous ACTUAL events from last 12h. Return ONLY JSON: {"issues": [{"event_title": "..", "severity": "..", "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', [])
|
|
|
|
| 90 |
# --- 6. Strategic Tabs ---
|
| 91 |
tab1, tab2, tab3 = st.tabs(["π GLOBAL TRACKING & MARKET", "π NATIONAL TOP 5 FORENSICS", "π RISK VELOCITY TREND"])
|
| 92 |
|
| 93 |
+
# --- [Tab 1: Global & Market - FULL SPECTRUM] ---
|
| 94 |
with tab1:
|
| 95 |
+
st.subheader("Global Risk Propagation & Strategic Market Insight (7 Days)")
|
| 96 |
col_k1, col_k2 = st.columns([3, 1])
|
| 97 |
with col_k1:
|
| 98 |
+
keyword = st.text_input("Enter Issue Keyword (7d Deep Scan)", "Digital Extremism")
|
| 99 |
selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
|
| 100 |
with col_k2:
|
| 101 |
st.write("")
|
|
|
|
| 115 |
|
| 116 |
st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))
|
| 117 |
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
with st.spinner("Synthesizing Full Strategic Global Report..."):
|
| 121 |
news_summary = "\n".join([f"- {n['title']}" for n in all_news_tab1[:25]])
|
| 122 |
+
# ESCAPED BRACES {{ }} FOR JSON
|
| 123 |
market_prompt = f"""
|
| 124 |
+
Analyze '{keyword}' based on provided news. Return ONLY JSON:
|
|
|
|
| 125 |
{{
|
| 126 |
+
"global_summary": "Detailed narrative (300+ words) on propagation.",
|
| 127 |
+
"analysis_fields": {{
|
| 128 |
+
"Target_Demographics": "Who is at risk and why.",
|
| 129 |
+
"Guideline_Violation": "Specific policy breaches.",
|
| 130 |
+
"Social_Impact": "Societal and political consequences.",
|
| 131 |
+
"Primary_Tactical_Action": "Primary recommendation for platforms."
|
| 132 |
}},
|
| 133 |
"platform_analysis": {{
|
| 134 |
+
"TikTok": "Strategic recommendation...",
|
| 135 |
+
"YouTube": "Strategic recommendation...",
|
| 136 |
+
"Meta": "Strategic recommendation...",
|
| 137 |
+
"X": "Strategic recommendation..."
|
| 138 |
}}
|
| 139 |
}}
|
| 140 |
"""
|
| 141 |
try:
|
| 142 |
res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": market_prompt}, {"role": "user", "content": f"News:\n{news_summary}"}], response_format={"type": "json_object"})
|
| 143 |
g_data = json.loads(res.choices[0].message.content)
|
| 144 |
+
|
| 145 |
+
st.info(f"**π Global Strategic Summary:**\n\n{g_data.get('global_summary')}")
|
| 146 |
+
|
| 147 |
+
# Full Field Analysis for Tab 1
|
| 148 |
st.markdown("### π Risk Factor Breakdown")
|
| 149 |
+
st.table(pd.DataFrame(g_data.get('analysis_fields', {{}}).items(), columns=["Metric", "Intelligence Insight"]))
|
| 150 |
+
|
| 151 |
st.markdown("### π± Platform Tactical Recommendations")
|
| 152 |
st.table(pd.DataFrame(g_data.get('platform_analysis', {{}}).items(), columns=["Platform", "Strategic Insight"]))
|
| 153 |
except Exception as e: st.error(f"Synthesis error: {e}")
|
| 154 |
|
| 155 |
+
# --- [Tab 2: National Forensics - FULL SPECTRUM] ---
|
| 156 |
with tab2:
|
| 157 |
+
st.subheader("National Tactical Intelligence (7-Day Evidence)")
|
| 158 |
c1, c2 = st.columns([1, 4])
|
| 159 |
with c1:
|
| 160 |
target_geo = st.text_input("ISO Country Code", "US").upper()
|
| 161 |
btn_deep = st.button("Generate National Report", type="primary")
|
| 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 |
Summary must be 300+ words citing REF IDs.
|
| 174 |
Return ONLY JSON:
|
| 175 |
{{
|
| 176 |
"risks": [
|
| 177 |
{{
|
| 178 |
"rank": 1, "title": "..", "score": 90, "summary": "..",
|
| 179 |
+
"violation": "Specific guideline breach",
|
| 180 |
+
"demographics": "Vulnerable target groups",
|
| 181 |
+
"social_impact": "Societal/political consequences",
|
| 182 |
+
"tactical_action": "Platform-specific action plan"
|
| 183 |
}}
|
| 184 |
]
|
| 185 |
}}
|
| 186 |
"""
|
| 187 |
try:
|
| 188 |
+
res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": f"Evidence:\n{news_context}"}], response_format={"type": "json_object"})
|
| 189 |
report_data = json.loads(res.choices[0].message.content).get('risks', [])
|
| 190 |
except: report_data = []
|
| 191 |
|
| 192 |
if report_data:
|
| 193 |
+
st.markdown(create_download_link(report_data, f"{target_geo}_Full_Intel.txt"), unsafe_allow_html=True)
|
| 194 |
for r in report_data:
|
| 195 |
with st.expander(f"π© RANK {r.get('rank')}: {r.get('title')} (Verified)"):
|
| 196 |
st.markdown(f"**Detailed Analysis:**\n{r.get('summary')}")
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
|
| 200 |
st.table(pd.DataFrame({
|
| 201 |
"Category": ["Violation", "Target Group", "Social Impact", "Tactical Action"],
|
| 202 |
"Intelligence": [r.get('violation'), r.get('demographics'), r.get('social_impact'), r.get('tactical_action')]
|
|
|
|
| 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 Trend (Last 7 Days)")
|
| 212 |
+
trend_key = st.text_input("Trend Keyword", "Election Safety")
|
| 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, 45, 75, 85, 95, 92], markers=True, title=f"Risk Score Velocity: {trend_key}"), use_container_width=True)
|
|
|