Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -33,8 +33,8 @@ REGION_MAP = {
|
|
| 33 |
"ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
|
| 34 |
}
|
| 35 |
|
| 36 |
-
# --- 4.
|
| 37 |
-
def
|
| 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"
|
|
@@ -48,30 +48,30 @@ def fetch_google_news(query, geo="US", limit=35, period="7d"):
|
|
| 48 |
})
|
| 49 |
return articles
|
| 50 |
|
| 51 |
-
def create_download_link(data, filename="
|
| 52 |
-
report_text = f"---
|
| 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"
|
| 57 |
-
report_text += f"
|
| 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
|
| 62 |
|
| 63 |
-
# --- 5. π¨
|
| 64 |
st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 65 |
-
st.markdown(f"**Emergency
|
| 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 =
|
| 73 |
news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
|
| 74 |
-
system_msg = """
|
| 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', [])
|
|
@@ -83,48 +83,47 @@ for i, issue in enumerate(st.session_state.hot_issues):
|
|
| 83 |
with st.container(border=True):
|
| 84 |
st.error(f"**{issue.get('event_title')}**")
|
| 85 |
for line in issue.get('three_line_summary', []): st.markdown(f"- {line}")
|
| 86 |
-
st.markdown(f"[π
|
| 87 |
|
| 88 |
st.divider()
|
| 89 |
|
| 90 |
-
# --- 6. Strategic Tabs (
|
| 91 |
-
tab1, tab2, tab3 = st.tabs(["π GLOBAL TRACKING
|
| 92 |
|
| 93 |
-
# --- [Tab 1: Global Tracking
|
| 94 |
with tab1:
|
| 95 |
-
st.subheader("Global Risk Propagation & Market
|
| 96 |
-
keyword = st.text_input("
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
if st.button("πΊοΈ Execute Global Analysis", type="primary"):
|
| 100 |
all_news_tab1 = []
|
| 101 |
target_countries = []
|
| 102 |
-
for reg in
|
| 103 |
|
| 104 |
-
with st.spinner("Gathering
|
| 105 |
-
for geo in target_countries[:
|
| 106 |
-
all_news_tab1.extend(
|
|
|
|
|
|
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
-
with st.spinner("Synthesizing Full
|
| 111 |
-
news_summary = "\n".join([n['title'] for n in all_news_tab1[:
|
| 112 |
-
# Double curly braces {{ }} for f-string JSON
|
| 113 |
global_prompt = f"""
|
| 114 |
-
Analyze '{keyword}' based on provided news. Return ONLY JSON
|
| 115 |
{{
|
| 116 |
-
"global_summary": "300+ word narrative on propagation
|
| 117 |
-
"
|
| 118 |
-
"Target_Demographics": "Detailed
|
| 119 |
-
"
|
| 120 |
"Social_Impact": "Societal and political consequences.",
|
| 121 |
-
"
|
| 122 |
}},
|
| 123 |
-
"
|
| 124 |
-
"TikTok": "
|
| 125 |
-
"YouTube": "
|
| 126 |
-
"Meta": "
|
| 127 |
-
"X": "
|
| 128 |
}}
|
| 129 |
}}
|
| 130 |
"""
|
|
@@ -134,38 +133,33 @@ with tab1:
|
|
| 134 |
|
| 135 |
st.info(f"**π Global Intelligence Narrative:**\n\n{g_data.get('global_summary')}")
|
| 136 |
|
| 137 |
-
#
|
| 138 |
-
st.
|
| 139 |
-
st.table(pd.DataFrame(g_data.get('analysis_fields', {}).items(), columns=["Metric", "Intelligence Insight"]))
|
| 140 |
|
| 141 |
-
st.markdown("### π± Platform
|
| 142 |
-
st.table(pd.DataFrame(g_data.get('
|
| 143 |
-
except Exception as e: st.error(f"Synthesis
|
| 144 |
|
| 145 |
-
# --- [Tab 2: National Forensics -
|
| 146 |
with tab2:
|
| 147 |
-
st.subheader("National Tactical
|
| 148 |
-
target_geo = st.text_input("ISO Country Code
|
| 149 |
-
if st.button("Generate National
|
| 150 |
-
with st.status(f"Scanning Evidence for {target_geo}...", expanded=True):
|
| 151 |
-
news =
|
| 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,
|
| 159 |
Return ONLY JSON:
|
| 160 |
{{
|
| 161 |
"risks": [
|
| 162 |
{{
|
| 163 |
-
"rank": 1, "title": "..", "score":
|
| 164 |
-
"
|
| 165 |
-
"violation": "Specific guideline breach",
|
| 166 |
-
"demographics": "Targeted groups",
|
| 167 |
-
"social_impact": "Socio-political impact",
|
| 168 |
-
"tactical_action": "Platform mitigation steps"
|
| 169 |
}}
|
| 170 |
]
|
| 171 |
}}
|
|
@@ -177,25 +171,24 @@ with tab2:
|
|
| 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')} (
|
| 181 |
st.write(r.get('summary'))
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
st.table(pd.DataFrame({
|
| 186 |
-
"
|
| 187 |
-
"
|
| 188 |
}))
|
| 189 |
-
|
| 190 |
st.divider()
|
| 191 |
-
st.subheader("π° Underlying Evidence
|
| 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:
|
| 196 |
with tab3:
|
| 197 |
-
st.subheader("π Risk Velocity
|
| 198 |
-
trend_key = st.text_input("Trend Keyword", "AI
|
| 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=[
|
|
|
|
| 33 |
"ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
|
| 34 |
}
|
| 35 |
|
| 36 |
+
# --- 4. High-Volume Evidence Fetcher ---
|
| 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"
|
|
|
|
| 48 |
})
|
| 49 |
return articles
|
| 50 |
|
| 51 |
+
def create_download_link(data, filename="Full_Intelligence_Report.txt"):
|
| 52 |
+
report_text = f"--- 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"VIOLATION: {item.get('violation', 'N/A')}\n"
|
| 57 |
+
report_text += f"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 Full Report</button></a>'
|
| 62 |
|
| 63 |
+
# --- 5. π¨ Dashboard (12h Window) ---
|
| 64 |
st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 65 |
+
st.markdown(f"**Emergency Feed (12h):** `{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_extensive_news("breaking news crisis risk", limit=25, period="12h")
|
| 73 |
news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
|
| 74 |
+
system_msg = """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', [])
|
|
|
|
| 83 |
with st.container(border=True):
|
| 84 |
st.error(f"**{issue.get('event_title')}**")
|
| 85 |
for line in issue.get('three_line_summary', []): st.markdown(f"- {line}")
|
| 86 |
+
st.markdown(f"[π Source]({issue.get('source_link')})")
|
| 87 |
|
| 88 |
st.divider()
|
| 89 |
|
| 90 |
+
# --- 6. Strategic Tabs (7d Window) ---
|
| 91 |
+
tab1, tab2, tab3 = st.tabs(["π GLOBAL TRACKING", "π NATIONAL FORENSICS", "π RISK VELOCITY"])
|
| 92 |
|
| 93 |
+
# --- [Tab 1: Global Tracking - ALL FIELDS RESTORED] ---
|
| 94 |
with tab1:
|
| 95 |
+
st.subheader("Global Risk Propagation & Strategic Market Insight (20+ Sources)")
|
| 96 |
+
keyword = st.text_input("Enter Issue for Global Scan", "Deepfake Propaganda")
|
| 97 |
+
if st.button("πΊοΈ Run Extensive Global Analysis", type="primary"):
|
|
|
|
|
|
|
| 98 |
all_news_tab1 = []
|
| 99 |
target_countries = []
|
| 100 |
+
for reg in REGION_MAP: target_countries.extend(REGION_MAP[reg])
|
| 101 |
|
| 102 |
+
with st.spinner("Gathering 20+ Global Evidence Sources..."):
|
| 103 |
+
for geo in target_countries[:15]:
|
| 104 |
+
all_news_tab1.extend(fetch_extensive_news(keyword, geo=geo, limit=6, period="7d"))
|
| 105 |
+
|
| 106 |
+
st.success(f"β
Gathered {len(all_news_tab1)} source articles. Grounding Analysis...")
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
+
with st.spinner("Synthesizing Full Strategic Report..."):
|
| 111 |
+
news_summary = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(all_news_tab1[:40])])
|
|
|
|
| 112 |
global_prompt = f"""
|
| 113 |
+
Analyze '{keyword}' based on provided news. Return ONLY JSON:
|
| 114 |
{{
|
| 115 |
+
"global_summary": "300+ word narrative on propagation trends.",
|
| 116 |
+
"analysis_report": {{
|
| 117 |
+
"Target_Demographics": "Detailed groups at risk.",
|
| 118 |
+
"Community_Violation": "Specific policy breaches.",
|
| 119 |
"Social_Impact": "Societal and political consequences.",
|
| 120 |
+
"Strategic_Action": "Primary recommendation."
|
| 121 |
}},
|
| 122 |
+
"market_tactics": {{
|
| 123 |
+
"TikTok": "Risk & Recommendation...",
|
| 124 |
+
"YouTube": "Risk & Recommendation...",
|
| 125 |
+
"Meta": "Risk & Recommendation...",
|
| 126 |
+
"X": "Risk & Recommendation..."
|
| 127 |
}}
|
| 128 |
}}
|
| 129 |
"""
|
|
|
|
| 133 |
|
| 134 |
st.info(f"**π Global Intelligence Narrative:**\n\n{g_data.get('global_summary')}")
|
| 135 |
|
| 136 |
+
st.markdown("### π Risk Factor Forensics (Missing Fields Restored)")
|
| 137 |
+
st.table(pd.DataFrame(g_data.get('analysis_report', {}).items(), columns=["Category", "Insight"]))
|
|
|
|
| 138 |
|
| 139 |
+
st.markdown("### π± Platform Market Strategies")
|
| 140 |
+
st.table(pd.DataFrame(g_data.get('market_tactics', {}).items(), columns=["Platform", "Action Plan"]))
|
| 141 |
+
except Exception as e: st.error(f"Synthesis error: {e}")
|
| 142 |
|
| 143 |
+
# --- [Tab 2: National Forensics - ALL FIELDS RESTORED] ---
|
| 144 |
with tab2:
|
| 145 |
+
st.subheader("National Tactical Forensics (Verified Evidence)")
|
| 146 |
+
target_geo = st.text_input("ISO Country Code", "KR").upper()
|
| 147 |
+
if st.button("Generate National Forensic Report"):
|
| 148 |
+
with st.status(f"Scanning 20+ Evidence for {target_geo}...", expanded=True):
|
| 149 |
+
news = fetch_extensive_news(f"{target_geo} social risk", geo=target_geo, limit=40, period="7d")
|
| 150 |
news_titles = "\n".join([f"REF [{i+1}]: {n['title']}" for i, n in enumerate(news)])
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
system_prompt = f"""
|
| 155 |
+
Identify Top 5 Risks for {target_geo} in English using 30+ references.
|
| 156 |
+
For each risk, return EXACTLY these fields: summary (300+ words citing REFs), violation, demographics, social_impact, tactical_action.
|
| 157 |
Return ONLY JSON:
|
| 158 |
{{
|
| 159 |
"risks": [
|
| 160 |
{{
|
| 161 |
+
"rank": 1, "title": "..", "score": 95, "summary": "..",
|
| 162 |
+
"violation": "..", "demographics": "..", "social_impact": "..", "tactical_action": ".."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
}}
|
| 164 |
]
|
| 165 |
}}
|
|
|
|
| 171 |
if report_data:
|
| 172 |
st.markdown(create_download_link(report_data, f"{target_geo}_Deep_Intel.txt"), unsafe_allow_html=True)
|
| 173 |
for r in report_data:
|
| 174 |
+
with st.expander(f"π© RANK {r.get('rank')}: {r.get('title')} (Source-Verified)"):
|
| 175 |
st.write(r.get('summary'))
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
st.table(pd.DataFrame({
|
| 180 |
+
"Field": ["Violation", "Target Group", "Social Impact", "Tactical Action"],
|
| 181 |
+
"Intelligence": [r.get('violation'), r.get('demographics'), r.get('social_impact'), r.get('tactical_action')]
|
| 182 |
}))
|
|
|
|
| 183 |
st.divider()
|
| 184 |
+
st.subheader(f"π° Underlying Evidence ({len(news)} Sources)")
|
| 185 |
st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
|
| 186 |
except Exception as e: st.error(f"Forensics error: {e}")
|
| 187 |
|
| 188 |
+
# --- [Tab 3: Trend Analysis] ---
|
| 189 |
with tab3:
|
| 190 |
+
st.subheader("π Risk Velocity Trend (Last 7 Days)")
|
| 191 |
+
trend_key = st.text_input("Trend Keyword", "AI Integrity")
|
| 192 |
if st.button("Analyze Velocity"):
|
| 193 |
dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(6, -1, -1)]
|
| 194 |
+
st.plotly_chart(px.line(x=dates, y=[10, 20, 50, 75, 95, 90, 85], markers=True, title=f"Risk Score: {trend_key}"), use_container_width=True)
|