Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import feedparser
|
| 3 |
import urllib.parse
|
| 4 |
-
from groq import Groq
|
| 5 |
import pandas as pd
|
| 6 |
import json
|
| 7 |
import os
|
|
@@ -23,7 +23,15 @@ if not api_key:
|
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
# --- 3. Configuration ---
|
| 29 |
REGION_MAP = {
|
|
@@ -34,6 +42,31 @@ REGION_MAP = {
|
|
| 34 |
}
|
| 35 |
|
| 36 |
# --- 4. Core Functions ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
|
@@ -59,7 +92,7 @@ def render_gauge(score, title):
|
|
| 59 |
fig.update_layout(height=180, margin=dict(l=10, r=10, t=40, b=10), paper_bgcolor="rgba(0,0,0,0)")
|
| 60 |
return fig
|
| 61 |
|
| 62 |
-
# --- 5. 🚨 GLOBAL WAR ROOM
|
| 63 |
st.title("🚨 OMNI-WATCH: T&S WAR ROOM")
|
| 64 |
st.caption(f"Policy Risk Monitoring: {datetime.now().strftime('%H:%M:%S')} UTC")
|
| 65 |
|
|
@@ -69,23 +102,31 @@ if st.button("🔄 Refresh"):
|
|
| 69 |
if 'hot_issues' not in st.session_state:
|
| 70 |
with st.spinner("Scanning for Community Standard Violations..."):
|
| 71 |
raw_news = fetch_extensive_news("violence OR hate speech OR disinformation OR scandal OR protest", limit=40, period="12h")
|
| 72 |
-
news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
|
| 73 |
-
|
| 74 |
-
# 🚨 PROMPT UPDATE: 첫 줄에 반드시 'Event Summary' 포함
|
| 75 |
-
system_msg = """
|
| 76 |
-
Identify TOP 3 incidents with highest 'Trust & Safety' risk.
|
| 77 |
-
The 'summary' array MUST follow this order:
|
| 78 |
-
1. "Event: [Brief but clear summary of what happened]"
|
| 79 |
-
2. "Violation: [Specific Community Guideline breached]"
|
| 80 |
-
3. "Risk: [Potential offline harm]"
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
if st.session_state.hot_issues:
|
| 91 |
cols = st.columns(3)
|
|
@@ -114,56 +155,62 @@ with tab1:
|
|
| 114 |
for geo in REGION_MAP[reg][:2]:
|
| 115 |
all_news.extend(fetch_extensive_news(keyword, geo=geo, limit=6, period="7d"))
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
# --- [Tab 2: Tactical Forensics] ---
|
| 169 |
with tab2:
|
|
@@ -172,54 +219,61 @@ with tab2:
|
|
| 172 |
if st.button("Analyze Violations"):
|
| 173 |
with st.status(f"Scanning {target_geo} for Policy Breaches (20+ Sources)...", expanded=True):
|
| 174 |
news = fetch_extensive_news(f"{target_geo} controversy OR scandal OR protest OR violence", geo=target_geo, limit=40, period="7d")
|
| 175 |
-
news_titles = "\n".join([n['title'] for n in news])
|
| 176 |
-
|
| 177 |
-
# 🚨 PROMPT UPDATE: 서머리에 '사건 개요' 필수 포함
|
| 178 |
-
system_prompt = f"""
|
| 179 |
-
Analyze Top 5 Risks in {target_geo} strictly through a 'Community Guidelines' lens.
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
}}
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
full_report_md = f"# NATIONAL T&S FORENSICS: {target_geo}\n\n"
|
| 203 |
-
|
| 204 |
-
for i, r in enumerate(report_data):
|
| 205 |
-
full_report_md += f"## {r.get('rank')}. {r.get('title')} (Risk: {r.get('score')})\n"
|
| 206 |
-
full_report_md += f"{r.get('summary')}\n\n"
|
| 207 |
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
with c1:
|
| 211 |
-
st.plotly_chart(render_gauge(r.get('score'), "Risk Index"), use_container_width=True, key=f"fg_{i}")
|
| 212 |
-
with c2:
|
| 213 |
-
st.markdown("**Incident & Policy Analysis:**")
|
| 214 |
-
st.markdown(r.get('summary').replace(". ", ".\n\n"))
|
| 215 |
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
# --- [Tab 3: Velocity] ---
|
| 225 |
with tab3:
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import feedparser
|
| 3 |
import urllib.parse
|
| 4 |
+
from groq import Groq, RateLimitError # 에러 핸들링을 위해 추가
|
| 5 |
import pandas as pd
|
| 6 |
import json
|
| 7 |
import os
|
|
|
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
| 26 |
+
|
| 27 |
+
# 🚨 [NEW] Robust Model List (Fallback Strategy)
|
| 28 |
+
# 1순위 모델이 막히면 2순위, 3순위로 자동 전환하여 분석을 수행합니다.
|
| 29 |
+
MODEL_HIERARCHY = [
|
| 30 |
+
"llama-3.3-70b-versatile", # Best Quality
|
| 31 |
+
"llama3-70b-8192", # High Quality
|
| 32 |
+
"mixtral-8x7b-32768", # Good Alternative
|
| 33 |
+
"llama3-8b-8192" # Fast & Light (Emergency Backup)
|
| 34 |
+
]
|
| 35 |
|
| 36 |
# --- 3. Configuration ---
|
| 37 |
REGION_MAP = {
|
|
|
|
| 42 |
}
|
| 43 |
|
| 44 |
# --- 4. Core Functions ---
|
| 45 |
+
# [NEW] Smart AI Request Function (Auto-Switching)
|
| 46 |
+
def get_ai_response(system_msg, user_content, json_mode=True):
|
| 47 |
+
for model in MODEL_HIERARCHY:
|
| 48 |
+
try:
|
| 49 |
+
kwargs = {
|
| 50 |
+
"model": model,
|
| 51 |
+
"messages": [{"role": "system", "content": system_msg}, {"role": "user", "content": user_content}],
|
| 52 |
+
}
|
| 53 |
+
if json_mode:
|
| 54 |
+
kwargs["response_format"] = {"type": "json_object"}
|
| 55 |
+
|
| 56 |
+
res = client.chat.completions.create(**kwargs)
|
| 57 |
+
return res # 성공하면 반환
|
| 58 |
+
except RateLimitError:
|
| 59 |
+
# 한도 초과 시 다음 모델로 조용히 넘어감
|
| 60 |
+
continue
|
| 61 |
+
except Exception as e:
|
| 62 |
+
# 다른 에러는 즉시 보고
|
| 63 |
+
st.error(f"⚠️ Error with model {model}: {e}")
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
# 모든 모델이 실패했을 경우
|
| 67 |
+
st.error("🚨 All AI models are currently rate-limited or unavailable. Please try again in a few minutes.")
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
def fetch_extensive_news(query, geo="US", limit=60, period="7d"):
|
| 71 |
time_filter = f" when:{period}"
|
| 72 |
encoded = urllib.parse.quote(query + time_filter)
|
|
|
|
| 92 |
fig.update_layout(height=180, margin=dict(l=10, r=10, t=40, b=10), paper_bgcolor="rgba(0,0,0,0)")
|
| 93 |
return fig
|
| 94 |
|
| 95 |
+
# --- 5. 🚨 GLOBAL WAR ROOM ---
|
| 96 |
st.title("🚨 OMNI-WATCH: T&S WAR ROOM")
|
| 97 |
st.caption(f"Policy Risk Monitoring: {datetime.now().strftime('%H:%M:%S')} UTC")
|
| 98 |
|
|
|
|
| 102 |
if 'hot_issues' not in st.session_state:
|
| 103 |
with st.spinner("Scanning for Community Standard Violations..."):
|
| 104 |
raw_news = fetch_extensive_news("violence OR hate speech OR disinformation OR scandal OR protest", limit=40, period="12h")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
+
if not raw_news:
|
| 107 |
+
st.warning("No critical incidents in the last 12h.")
|
| 108 |
+
st.session_state.hot_issues = []
|
| 109 |
+
else:
|
| 110 |
+
news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
|
| 111 |
+
|
| 112 |
+
system_msg = """
|
| 113 |
+
Identify TOP 3 incidents with highest 'Trust & Safety' risk.
|
| 114 |
+
The 'summary' array MUST follow this order:
|
| 115 |
+
1. "Event: [Brief summary]"
|
| 116 |
+
2. "Violation: [Specific Guideline breached]"
|
| 117 |
+
3. "Risk: [Offline harm]"
|
| 118 |
+
|
| 119 |
+
Return ONLY JSON:
|
| 120 |
+
{"issues": [{"title": "Short Title", "score": 85, "summary": ["Event: ...", "Violation: ...", "Risk: ..."], "link": ".."}]}
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
# [NEW] Use Smart Wrapper
|
| 124 |
+
res = get_ai_response(system_msg, news_context)
|
| 125 |
+
if res:
|
| 126 |
+
try:
|
| 127 |
+
st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])[:3]
|
| 128 |
+
except:
|
| 129 |
+
st.session_state.hot_issues = []
|
| 130 |
|
| 131 |
if st.session_state.hot_issues:
|
| 132 |
cols = st.columns(3)
|
|
|
|
| 155 |
for geo in REGION_MAP[reg][:2]:
|
| 156 |
all_news.extend(fetch_extensive_news(keyword, geo=geo, limit=6, period="7d"))
|
| 157 |
|
| 158 |
+
if not all_news:
|
| 159 |
+
st.error("No news found for this keyword.")
|
| 160 |
+
else:
|
| 161 |
+
news_summary = "\n".join([n['title'] for n in all_news[:45]])
|
| 162 |
+
|
| 163 |
+
global_prompt = f"""
|
| 164 |
+
Analyze '{keyword}' focusing on 'Community Guidelines' and 'Social Impact'.
|
| 165 |
+
|
| 166 |
+
1. Executive Summary: Start with a clear **Event Summary** of what happened. Then, analyze the systemic policy risks and societal harm. (300+ words).
|
| 167 |
+
2. Risk Landscape: Map findings to specific violations.
|
| 168 |
+
|
| 169 |
+
Return ONLY JSON:
|
| 170 |
+
{{
|
| 171 |
+
"executive_summary": "Start with [The Event], then move to [Policy Analysis].",
|
| 172 |
+
"risk_landscape": [
|
| 173 |
+
{{"Component": "Primary Violation", "Findings": "...", "Risk_Level": "High"}},
|
| 174 |
+
{{"Component": "Vulnerable Target", "Findings": "...", "Risk_Level": "Critical"}},
|
| 175 |
+
{{"Component": "Offline Harm", "Findings": "...", "Risk_Level": "High"}},
|
| 176 |
+
{{"Component": "Enforcement Gap", "Findings": "...", "Risk_Level": "Medium"}}
|
| 177 |
+
],
|
| 178 |
+
"platform_intelligence": [
|
| 179 |
+
{{"Platform": "TikTok", "Assessment": "...", "Strategy": "..."}},
|
| 180 |
+
{{"Platform": "YouTube", "Assessment": "...", "Strategy": "..."}},
|
| 181 |
+
{{"Platform": "Meta", "Assessment": "...", "Strategy": "..."}},
|
| 182 |
+
{{"Platform": "X", "Assessment": "...", "Strategy": "..."}}
|
| 183 |
+
],
|
| 184 |
+
"strategic_conclusion": "Final Trust & Safety recommendation."
|
| 185 |
+
}}
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
# [NEW] Use Smart Wrapper
|
| 189 |
+
res = get_ai_response(global_prompt, news_summary)
|
| 190 |
+
|
| 191 |
+
if res:
|
| 192 |
+
g_data = json.loads(res.choices[0].message.content)
|
| 193 |
+
|
| 194 |
+
with st.container(border=True):
|
| 195 |
+
st.subheader("1. Policy Impact Executive Summary")
|
| 196 |
+
st.markdown(g_data.get('executive_summary').replace(". ", ".\n\n"))
|
| 197 |
+
|
| 198 |
+
st.subheader("2. Guideline Violation Matrix")
|
| 199 |
+
st.dataframe(pd.DataFrame(g_data.get('risk_landscape')), hide_index=True, use_container_width=True)
|
| 200 |
+
|
| 201 |
+
st.subheader("3. Platform Enforcement Strategy")
|
| 202 |
+
st.table(pd.DataFrame(g_data.get('platform_intelligence')))
|
| 203 |
+
|
| 204 |
+
st.success(f"**T&S Recommendation:** {g_data.get('strategic_conclusion')}")
|
| 205 |
+
|
| 206 |
+
# DOWNLOAD
|
| 207 |
+
report_md = f"# OMNI-WATCH POLICY REPORT: {keyword.upper()}\n\n"
|
| 208 |
+
report_md += f"## 1. EXECUTIVE SUMMARY\n{g_data.get('executive_summary')}\n\n"
|
| 209 |
+
report_md += "## 2. VIOLATION LANDSCAPE\n"
|
| 210 |
+
for item in g_data.get('risk_landscape', []):
|
| 211 |
+
report_md += f"- **{item['Component']}**: {item['Findings']} ({item['Risk_Level']})\n"
|
| 212 |
+
|
| 213 |
+
st.download_button("📥 Download Policy Report (.md)", report_md, f"Policy_Intel_{keyword}.md")
|
| 214 |
|
| 215 |
# --- [Tab 2: Tactical Forensics] ---
|
| 216 |
with tab2:
|
|
|
|
| 219 |
if st.button("Analyze Violations"):
|
| 220 |
with st.status(f"Scanning {target_geo} for Policy Breaches (20+ Sources)...", expanded=True):
|
| 221 |
news = fetch_extensive_news(f"{target_geo} controversy OR scandal OR protest OR violence", geo=target_geo, limit=40, period="7d")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
+
if not news:
|
| 224 |
+
st.error(f"No recent controversy news found for {target_geo}.")
|
| 225 |
+
else:
|
| 226 |
+
news_titles = "\n".join([n['title'] for n in news])
|
| 227 |
+
|
| 228 |
+
system_prompt = f"""
|
| 229 |
+
Analyze Top 5 Risks in {target_geo} strictly through a 'Community Guidelines' lens.
|
| 230 |
+
|
| 231 |
+
Summary MUST start with **"The Incident:"** (What happened) followed by **"Policy Analysis:"** (Why it violates rules).
|
| 232 |
+
|
| 233 |
+
Return ONLY JSON:
|
| 234 |
+
{{
|
| 235 |
+
"risks": [
|
| 236 |
+
{{
|
| 237 |
+
"rank": 1, "title": "Event Title", "score": 90,
|
| 238 |
+
"summary": "1. The Incident: ... \n2. Policy Analysis: ...",
|
| 239 |
+
"forensic_grid": {{
|
| 240 |
+
"Guideline_Breached": "e.g. Dangerous Organizations Policy",
|
| 241 |
+
"Victim_Demographics": "e.g. Teenagers / Ethnic Minorities",
|
| 242 |
+
"Societal_Impact": "e.g. Incitement to Violence",
|
| 243 |
+
"Enforcement_Action": "e.g. Geo-blocking / Account Ban"
|
| 244 |
+
}}
|
| 245 |
}}
|
| 246 |
+
]
|
| 247 |
+
}}
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
# [NEW] Use Smart Wrapper
|
| 251 |
+
res = get_ai_response(system_prompt, news_titles)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
+
if res:
|
| 254 |
+
report_data = json.loads(res.choices[0].message.content).get('risks', [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
+
full_report_md = f"# NATIONAL T&S FORENSICS: {target_geo}\n\n"
|
| 257 |
+
|
| 258 |
+
for i, r in enumerate(report_data):
|
| 259 |
+
full_report_md += f"## {r.get('rank')}. {r.get('title')} (Risk: {r.get('score')})\n"
|
| 260 |
+
full_report_md += f"{r.get('summary')}\n\n"
|
| 261 |
+
|
| 262 |
+
with st.expander(f"🚩 RISK {r.get('rank')}: {r.get('title')} (Score: {r.get('score')})", expanded=True):
|
| 263 |
+
c1, c2 = st.columns([1, 4])
|
| 264 |
+
with c1:
|
| 265 |
+
st.plotly_chart(render_gauge(r.get('score'), "Risk Index"), use_container_width=True, key=f"fg_{i}")
|
| 266 |
+
with c2:
|
| 267 |
+
st.markdown("**Incident & Policy Analysis:**")
|
| 268 |
+
st.markdown(r.get('summary').replace(". ", ".\n\n"))
|
| 269 |
+
|
| 270 |
+
st.table(pd.DataFrame(r.get('forensic_grid', {}).items(), columns=["T&S Component", "Assessment"]))
|
| 271 |
+
|
| 272 |
+
st.download_button("📥 Download Forensic Report (.md)", full_report_md, f"T&S_Forensics_{target_geo}.md")
|
| 273 |
+
|
| 274 |
+
st.divider()
|
| 275 |
+
st.caption(f"Evidence Base: {len(news)} articles")
|
| 276 |
+
st.dataframe(pd.DataFrame(news)[['title', 'source']], use_container_width=True)
|
| 277 |
|
| 278 |
# --- [Tab 3: Velocity] ---
|
| 279 |
with tab3:
|