Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,233 +6,151 @@ import pandas as pd
|
|
| 6 |
import json
|
| 7 |
import time
|
| 8 |
import os
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# --- Page Config ---
|
| 11 |
-
st.set_page_config(page_title="
|
| 12 |
|
| 13 |
-
# ---
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
""",
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
"
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
"India": {"geo": "IN", "lang": "en"},
|
| 31 |
-
"Indonesia": {"geo": "ID", "lang": "id"},
|
| 32 |
-
"Vietnam": {"geo": "VN", "lang": "vi"},
|
| 33 |
-
"Thailand": {"geo": "TH", "lang": "th"},
|
| 34 |
-
"Philippines": {"geo": "PH", "lang": "en"},
|
| 35 |
-
"Malaysia": {"geo": "MY", "lang": "en"}, # λ§λ μ΄μμ μΆκ°
|
| 36 |
-
"Australia": {"geo": "AU", "lang": "en"}
|
| 37 |
-
},
|
| 38 |
-
"π° Europe": {
|
| 39 |
-
"United Kingdom": {"geo": "GB", "lang": "en"},
|
| 40 |
-
"France": {"geo": "FR", "lang": "fr"},
|
| 41 |
-
"Germany": {"geo": "DE", "lang": "de"},
|
| 42 |
-
"Italy": {"geo": "IT", "lang": "it"},
|
| 43 |
-
"Spain": {"geo": "ES", "lang": "es"},
|
| 44 |
-
"Russia": {"geo": "RU", "lang": "ru"},
|
| 45 |
-
"Ukraine": {"geo": "UA", "lang": "uk"},
|
| 46 |
-
"Netherlands": {"geo": "NL", "lang": "nl"}
|
| 47 |
-
},
|
| 48 |
-
"π½ Americas": {
|
| 49 |
-
"USA": {"geo": "US", "lang": "en"},
|
| 50 |
-
"Canada": {"geo": "CA", "lang": "en"},
|
| 51 |
-
"Mexico": {"geo": "MX", "lang": "es"},
|
| 52 |
-
"Brazil": {"geo": "BR", "lang": "pt"},
|
| 53 |
-
"Argentina": {"geo": "AR", "lang": "es"}
|
| 54 |
-
},
|
| 55 |
-
"π ME & Africa": {
|
| 56 |
-
"Israel": {"geo": "IL", "lang": "he"},
|
| 57 |
-
"Saudi Arabia": {"geo": "SA", "lang": "ar"},
|
| 58 |
-
"UAE": {"geo": "AE", "lang": "ar"},
|
| 59 |
-
"South Africa": {"geo": "ZA", "lang": "en"},
|
| 60 |
-
"Turkey": {"geo": "TR", "lang": "tr"}
|
| 61 |
-
}
|
| 62 |
}
|
| 63 |
|
| 64 |
-
# ---
|
| 65 |
-
def fetch_google_news(query, geo="US", lang="en", limit=10):
|
| 66 |
-
# Google News RSS URL Builder
|
| 67 |
-
# hl=Language, gl=Country, ceid=Country:Language
|
| 68 |
-
encoded_query = urllib.parse.quote(query)
|
| 69 |
-
rss_url = f"https://news.google.com/rss/search?q={encoded_query}&hl={lang}&gl={geo}&ceid={geo}:{lang}"
|
| 70 |
-
|
| 71 |
-
feed = feedparser.parse(rss_url)
|
| 72 |
-
articles = []
|
| 73 |
-
|
| 74 |
-
for entry in feed.entries[:limit]:
|
| 75 |
-
articles.append({
|
| 76 |
-
"title": entry.title,
|
| 77 |
-
"link": entry.link,
|
| 78 |
-
"source": entry.source.title if 'source' in entry else "Google News",
|
| 79 |
-
"date": entry.published if 'published' in entry else "Recent"
|
| 80 |
-
})
|
| 81 |
-
return articles
|
| 82 |
-
|
| 83 |
-
# --- 1. API Key ---
|
| 84 |
api_key = os.environ.get("HF_KEY")
|
| 85 |
if not api_key:
|
| 86 |
try: api_key = st.secrets["HF_KEY"]
|
| 87 |
except: pass
|
| 88 |
|
| 89 |
-
# ---
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
api_key = st.text_input("HF Token", type="password")
|
| 96 |
-
|
| 97 |
-
st.subheader("Target")
|
| 98 |
-
zone = st.selectbox("Region", list(GLOBAL_ZONES.keys()))
|
| 99 |
-
country = st.selectbox("Country", list(GLOBAL_ZONES[zone].keys()))
|
| 100 |
-
|
| 101 |
-
# Target Config
|
| 102 |
-
target_conf = GLOBAL_ZONES[zone][country]
|
| 103 |
-
|
| 104 |
-
st.markdown("---")
|
| 105 |
-
st.subheader("βοΈ Config")
|
| 106 |
-
# κ΅¬κΈ λ΄μ€λ μ°¨λ¨μ΄ κ±°μ μμ΄μ μ¬λΌμ΄λ κΈ°λ³Έκ°μ λμ¬λ λ©λλ€.
|
| 107 |
-
data_vol = st.slider("Data Volume", 10, 60, 30, 10)
|
| 108 |
-
st.info("Engine: Google News RSS (No Rate Limit)")
|
| 109 |
-
|
| 110 |
-
refresh_btn = st.button("π Start Scan", type="primary", use_container_width=True)
|
| 111 |
|
| 112 |
-
# ---
|
| 113 |
-
st.title(
|
|
|
|
| 114 |
|
| 115 |
-
if not api_key:
|
|
|
|
|
|
|
| 116 |
|
| 117 |
-
|
| 118 |
-
client = InferenceClient(api_key=api_key)
|
| 119 |
-
|
| 120 |
-
status_text = st.empty()
|
| 121 |
-
progress_bar = st.progress(0)
|
| 122 |
-
all_news = []
|
| 123 |
-
split_vol = data_vol // 2
|
| 124 |
-
|
| 125 |
-
try:
|
| 126 |
-
# 1. Global Stream (English / US Perspective)
|
| 127 |
-
status_text.text(f"π‘ Fetching Global News (English)...")
|
| 128 |
-
# κ²μμ΄: "Country Name crisis"
|
| 129 |
-
global_articles = fetch_google_news(f"{country} controversy crisis", geo="US", lang="en", limit=split_vol)
|
| 130 |
-
for r in global_articles:
|
| 131 |
-
r['stream'] = 'Global π'
|
| 132 |
-
all_news.append(r)
|
| 133 |
-
progress_bar.progress(50)
|
| 134 |
-
|
| 135 |
-
# 2. Local Stream (Native Language Perspective)
|
| 136 |
-
status_text.text(f"π‘ Fetching Local News ({target_conf['lang']})...")
|
| 137 |
-
# κ²μμ΄: "Country Name" (νμ§ λ΄μ€μμλ κ΅κ°λͺ
μ΄λ μ¬ν μ΄μ ν€μλ)
|
| 138 |
-
# νμ§μ΄ λ΄μ€λ₯Ό κ°μ Έμ€κΈ° μν΄ geo/lang μ€μ λ³κ²½
|
| 139 |
-
local_articles = fetch_google_news(f"{country}", geo=target_conf['geo'], lang=target_conf['lang'], limit=split_vol)
|
| 140 |
-
for r in local_articles:
|
| 141 |
-
r['stream'] = 'Local π '
|
| 142 |
-
all_news.append(r)
|
| 143 |
-
progress_bar.progress(100)
|
| 144 |
-
|
| 145 |
-
except Exception as e:
|
| 146 |
-
st.error(f"News Fetch Error: {e}")
|
| 147 |
-
st.stop()
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
-
|
|
|
|
| 169 |
|
| 170 |
-
|
| 171 |
-
{
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
}}
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
try:
|
| 192 |
-
response = client.chat_completion(
|
| 193 |
model="Qwen/Qwen2.5-72B-Instruct",
|
| 194 |
-
messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content":
|
| 195 |
-
max_tokens=2500
|
| 196 |
)
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
except Exception as e:
|
| 201 |
-
st.error(f"AI Analysis Failed: {e}")
|
| 202 |
-
st.stop()
|
| 203 |
-
|
| 204 |
-
# --- [UI Render] ---
|
| 205 |
-
|
| 206 |
-
kpi1, kpi2, kpi3 = st.columns(3)
|
| 207 |
-
vel = data.get('viral_velocity', 50)
|
| 208 |
-
kpi1.metric("Viral Velocity", f"{vel}/100", "Critical" if vel > 80 else "Normal")
|
| 209 |
-
kpi2.metric("Mined Data", f"{len(df)}")
|
| 210 |
-
kpi3.metric("Top Risk", data['top_risks'][0]['violation'])
|
| 211 |
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
color = "#ff4b4b" if score >= 80 else "#ffa500" if score >= 50 else "#4caf50"
|
| 218 |
-
with st.container(border=True):
|
| 219 |
-
st.markdown(f"<h3 style='color:{color}'>{score}</h3>", unsafe_allow_html=True)
|
| 220 |
-
st.markdown(f"**{risk['title']}**")
|
| 221 |
-
st.caption(f"{risk['platform']} | {risk['violation']}")
|
| 222 |
-
st.markdown(f"π‘οΈ {risk['action']}")
|
| 223 |
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
with t2: st.success(report['local_vs_global'])
|
| 231 |
-
with t3:
|
| 232 |
-
c1, c2 = st.columns(2)
|
| 233 |
-
c1.warning(f"**π¬ Video:** {report['platform_strategy'].get('Video')}")
|
| 234 |
-
c2.warning(f"**π¬ Text:** {report['platform_strategy'].get('Text')}")
|
| 235 |
-
with t4: st.dataframe(df[['stream', 'title', 'source']], use_container_width=True)
|
| 236 |
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import json
|
| 7 |
import time
|
| 8 |
import os
|
| 9 |
+
import plotly.express as px
|
| 10 |
+
import random
|
| 11 |
|
| 12 |
# --- Page Config ---
|
| 13 |
+
st.set_page_config(page_title="Omni-Watch Intelligence", page_icon="π‘", layout="wide")
|
| 14 |
|
| 15 |
+
# --- π Global Strategic Nations (UN Core) ---
|
| 16 |
+
MONITOR_LIST = {
|
| 17 |
+
"South Korea": {"geo": "KR", "lang": "ko"},
|
| 18 |
+
"USA": {"geo": "US", "lang": "en"},
|
| 19 |
+
"Japan": {"geo": "JP", "lang": "ja"},
|
| 20 |
+
"UK": {"geo": "GB", "lang": "en"},
|
| 21 |
+
"France": {"geo": "FR", "lang": "fr"},
|
| 22 |
+
"Germany": {"geo": "DE", "lang": "de"},
|
| 23 |
+
"Israel": {"geo": "IL", "lang": "he"},
|
| 24 |
+
"Saudi Arabia": {"geo": "SA", "lang": "ar"},
|
| 25 |
+
"Brazil": {"geo": "BR", "lang": "pt"},
|
| 26 |
+
"India": {"geo": "IN", "lang": "en"},
|
| 27 |
+
"Malaysia": {"geo": "MY", "lang": "en"},
|
| 28 |
+
"Vietnam": {"geo": "VN", "lang": "vi"},
|
| 29 |
+
"Ukraine": {"geo": "UA", "lang": "uk"},
|
| 30 |
+
"Russia": {"geo": "RU", "lang": "ru"},
|
| 31 |
+
"Turkey": {"geo": "TR", "lang": "tr"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
}
|
| 33 |
|
| 34 |
+
# --- 1. API Key Auto-Load ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
api_key = os.environ.get("HF_KEY")
|
| 36 |
if not api_key:
|
| 37 |
try: api_key = st.secrets["HF_KEY"]
|
| 38 |
except: pass
|
| 39 |
|
| 40 |
+
# --- Helper: News Fetcher ---
|
| 41 |
+
def fetch_google_news(query, geo="US", lang="en", limit=10):
|
| 42 |
+
encoded = urllib.parse.quote(query)
|
| 43 |
+
url = f"https://news.google.com/rss/search?q={encoded}&hl={lang}&gl={geo}&ceid={geo}:{lang}"
|
| 44 |
+
feed = feedparser.parse(url)
|
| 45 |
+
return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
# --- UI Layout ---
|
| 48 |
+
st.title("π‘ Omni-Watch: Global Strategic Intelligence")
|
| 49 |
+
st.caption("Integrated Risk Monitoring: Options A(Timeline), B(Contagion), C(Visual Prediction) + Keyword Tracker")
|
| 50 |
|
| 51 |
+
if not api_key:
|
| 52 |
+
st.error("π HF_KEY Missing. Please set it in Environment Variables or Secrets.")
|
| 53 |
+
st.stop()
|
| 54 |
|
| 55 |
+
client = InferenceClient(api_key=api_key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
# ν ꡬμ±
|
| 58 |
+
tab_global, tab_deep = st.tabs(["π Global Keyword Tracker", "π National Deep-Dive"])
|
| 59 |
+
|
| 60 |
+
# --- [Tab 1: Global Keyword Tracker] ---
|
| 61 |
+
with tab_global:
|
| 62 |
+
st.subheader("Global Risk Propagation Analysis")
|
| 63 |
+
col_k1, col_k2 = st.columns([3, 1])
|
| 64 |
+
with col_k1:
|
| 65 |
+
search_keyword = st.text_input("Enter Issue Keyword", "Political Protest")
|
| 66 |
+
with col_k2:
|
| 67 |
+
st.write("") # Padding
|
| 68 |
+
run_global = st.button("πΊοΈ Global Scan", type="primary", use_container_width=True)
|
| 69 |
+
|
| 70 |
+
if run_global:
|
| 71 |
+
results = []
|
| 72 |
+
progress = st.progress(0)
|
| 73 |
+
status_msg = st.empty()
|
| 74 |
|
| 75 |
+
for i, (name, conf) in enumerate(MONITOR_LIST.items()):
|
| 76 |
+
status_msg.text(f"Scanning {name}...")
|
| 77 |
+
news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=5)
|
| 78 |
+
|
| 79 |
+
if news:
|
| 80 |
+
titles = "\n".join([n['title'] for n in news])
|
| 81 |
+
prompt = f"Based on these headlines about '{search_keyword}' in {name}, provide a risk score (0-100). Return ONLY the integer value.\n{titles}"
|
| 82 |
+
try:
|
| 83 |
+
res = client.chat_completion(model="Qwen/Qwen2.5-72B-Instruct", messages=[{"role": "user", "content": prompt}], max_tokens=10)
|
| 84 |
+
score_str = ''.join(filter(str.isdigit, res.choices[0].message.content))
|
| 85 |
+
score = int(score_str) if score_str else 50
|
| 86 |
+
except: score = 50
|
| 87 |
+
results.append({"Country": name, "Risk": score, "Sample": news[0]['title']})
|
| 88 |
+
progress.progress((i + 1) / len(MONITOR_LIST))
|
| 89 |
|
| 90 |
+
status_msg.empty()
|
| 91 |
+
df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
|
| 92 |
|
| 93 |
+
# Visualization
|
| 94 |
+
fig = px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds", title=f"Global Threat Map: {search_keyword}")
|
| 95 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 96 |
+
st.table(df_global)
|
| 97 |
+
|
| 98 |
+
# --- [Tab 2: National Deep-Dive] ---
|
| 99 |
+
with tab_deep:
|
| 100 |
+
col_d1, col_d2 = st.columns([1, 4])
|
| 101 |
+
with col_d1:
|
| 102 |
+
st.subheader("Control Panel")
|
| 103 |
+
target_country = st.selectbox("Select Target", list(MONITOR_LIST.keys()))
|
| 104 |
+
data_vol = st.slider("Data Depth", 10, 60, 30)
|
| 105 |
+
run_deep = st.button("π Run Deep Analysis", use_container_width=True)
|
| 106 |
+
|
| 107 |
+
if run_deep:
|
| 108 |
+
conf = MONITOR_LIST[target_country]
|
| 109 |
+
with st.status(f"Analytic Process for {target_country}...", expanded=True) as status:
|
| 110 |
+
st.write("π‘ Collecting Dual-Stream Intel...")
|
| 111 |
+
g_news = fetch_google_news(f"{target_country} crisis", limit=data_vol//2)
|
| 112 |
+
l_news = fetch_google_news(target_country, geo=conf['geo'], lang=conf['lang'], limit=data_vol//2)
|
| 113 |
+
|
| 114 |
+
combined = g_news + l_news
|
| 115 |
+
feed_text = "\n".join([f"- {n['title']}" for n in combined])
|
| 116 |
+
|
| 117 |
+
st.write("π§ Generating Multidimensional Report...")
|
| 118 |
+
system_prompt = f"""
|
| 119 |
+
You are a Strategic Risk Intelligence Officer. Analyze {target_country}.
|
| 120 |
+
Required Output (English Only, JSON):
|
| 121 |
+
{{
|
| 122 |
+
"viral_velocity": 0-100,
|
| 123 |
+
"trend_prediction": "Option A: 48h outlook (Rising/Stable/Declining)",
|
| 124 |
+
"contagion_risk": "Option B: Risk of spreading to neighboring countries",
|
| 125 |
+
"visual_threat_forecast": "Option C: Describe types of graphic/violent imagery likely to circulate",
|
| 126 |
+
"top_risks": [{{"title": "...", "risk_score": 0-100, "platform": "...", "violation": "...", "action": "..."}}],
|
| 127 |
+
"summary": "Full summary (3-4 sentences)"
|
| 128 |
}}
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
res = client.chat_completion(
|
|
|
|
|
|
|
| 132 |
model="Qwen/Qwen2.5-72B-Instruct",
|
| 133 |
+
messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": feed_text}],
|
| 134 |
+
max_tokens=2500
|
| 135 |
)
|
| 136 |
+
data = json.loads(res.choices[0].message.content.replace("```json", "").replace("```", "").strip())
|
| 137 |
+
status.update(label="Analysis Complete", state="complete")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
# UI Display
|
| 140 |
+
k1, k2, k3 = st.columns(3)
|
| 141 |
+
k1.metric("Viral Velocity", f"{data['viral_velocity']}/100")
|
| 142 |
+
k2.metric("Trend (Option A)", data['trend_prediction'])
|
| 143 |
+
k3.metric("Contagion (Option B)", "High" if "High" in data['contagion_risk'] else "Low/Med")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
+
st.subheader("β‘ Top Priority Threats")
|
| 146 |
+
cols = st.columns(3)
|
| 147 |
+
for i, r in enumerate(data['top_risks'][:3]):
|
| 148 |
+
with cols[i]:
|
| 149 |
+
st.info(f"**{r['title']}**\n\nScore: {r['risk_score']} | {r['platform']}")
|
| 150 |
+
st.caption(f"Action: {r['action']}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
st.divider()
|
| 153 |
+
st.markdown("### π Strategic Intelligence Report")
|
| 154 |
+
st.write(f"**Summary:** {data['summary']}")
|
| 155 |
+
st.warning(f"**πΈ Visual Threat Forecast (Option C):** {data['visual_threat_forecast']}")
|
| 156 |
+
st.error(f"**πΊοΈ Contagion Risk (Option B):** {data['contagion_risk']}")
|