benjamin5607 commited on
Commit
231e179
Β·
verified Β·
1 Parent(s): 3fb7058

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -207
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="Global Risk Watch (Google Engine)", page_icon="πŸ“‘", layout="wide")
12
 
13
- # --- CSS ---
14
- st.markdown("""
15
- <style>
16
- div[data-testid="stMetricValue"] { font-size: 24px; }
17
- .risk-card { background-color: #f9f9f9; padding: 15px; border-radius: 10px; border: 1px solid #ddd; margin-bottom: 10px; }
18
- .report-box { background-color: #eef2f5; padding: 20px; border-radius: 10px; margin-top: 10px; }
19
- </style>
20
- """, unsafe_allow_html=True)
21
-
22
- # --- 🌍 Country & Language Config (Google News) ---
23
- # Format: "Country": {"code": "CountryCode", "lang": "LanguageCode"}
24
- # 예: KR (Country), ko (Language)
25
- GLOBAL_ZONES = {
26
- "🌏 Asia Pacific": {
27
- "South Korea": {"geo": "KR", "lang": "ko"},
28
- "Japan": {"geo": "JP", "lang": "ja"},
29
- "China": {"geo": "CN", "lang": "zh-CN"},
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
- # --- Helper: Google News RSS Fetcher ---
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
- # --- Sidebar ---
90
- with st.sidebar:
91
- st.header("πŸ“‘ Risk Command (G-News)")
92
- if api_key: st.success("πŸ” Key Loaded")
93
- else:
94
- st.warning("⚠️ No Key")
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
- # --- Main Logic ---
113
- st.title(f"🌍 Risk Radar: {country}")
 
114
 
115
- if not api_key: st.stop()
 
 
116
 
117
- if refresh_btn:
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
- df = pd.DataFrame(all_news)
150
-
151
- if df.empty:
152
- st.warning("No news found. Google News might be empty for this query.")
153
- st.stop()
154
-
155
- status_text.text(f"βœ… Mined {len(df)} articles via Google News RSS.")
156
- time.sleep(1)
157
- status_text.empty()
158
- progress_bar.empty()
159
-
160
- # [Step 2] AI Analysis (Force English)
161
- with st.spinner(f"🧠 Qwen-72B analyzing {len(df)} articles..."):
162
-
163
- news_feed = "\n".join([f"- [{row['stream']}] {row['title']} ({row['source']})" for i, row in df.iterrows()])
 
 
164
 
165
- system_prompt = f"""
166
- You are a Global Risk Analyst. Analyze the {len(df)} news headlines from TODAY ({country}).
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
- CRITICAL: OUTPUT MUST BE IN ENGLISH ONLY. Translate any local news titles in your analysis.
 
169
 
170
- OUTPUT FORMAT (Strict JSON):
171
- {{
172
- "viral_velocity": 0-100 (Integer),
173
- "top_risks": [
174
- {{
175
- "title": "Headline (English)",
176
- "risk_score": 0-100,
177
- "platform": "TikTok/YouTube/Meta",
178
- "violation": "Hate/Violence/Misinfo",
179
- "action": "Action (English)"
180
- }}
181
- ],
182
- "deep_report": {{
183
- "executive_summary": "Summary (English).",
184
- "local_vs_global": "Contrast (English).",
185
- "platform_strategy": {{ "Video": "Strategy (English)", "Text": "Strategy (English)" }},
186
- "critical_keywords": ["Tag1", "Tag2"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": news_feed}],
195
- max_tokens=2500, temperature=0.25
196
  )
197
- content = response.choices[0].message.content.replace("```json", "").replace("```", "").strip()
198
- data = json.loads(content)
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
- st.subheader("⚑ Top 3 Risks")
213
- cols = st.columns(3)
214
- for i, risk in enumerate(data['top_risks'][:3]):
215
- with cols[i]:
216
- score = risk['risk_score']
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
- st.divider()
225
- st.markdown("### πŸ“‘ Deep Intelligence")
226
- report = data['deep_report']
227
- t1, t2, t3, t4 = st.tabs(["Summary", "Local vs Global", "Strategy", "Feed"])
228
-
229
- with t1: st.info(report['executive_summary'])
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
- else:
238
- st.info("πŸ‘ˆ Select Country and Start Scan (Google Engine Active).")
 
 
 
 
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']}")