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, RateLimitError
|
| 5 |
import pandas as pd
|
| 6 |
import json
|
| 7 |
import os
|
|
@@ -19,18 +19,18 @@ if not api_key:
|
|
| 19 |
except: pass
|
| 20 |
|
| 21 |
if not api_key:
|
| 22 |
-
st.error("π GROQ_API_KEY Missing.")
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
| 26 |
|
| 27 |
-
# π¨ [
|
| 28 |
-
#
|
| 29 |
MODEL_HIERARCHY = [
|
| 30 |
-
"llama-3.3-70b-versatile",
|
| 31 |
-
"
|
| 32 |
-
"mixtral-8x7b-32768",
|
| 33 |
-
"
|
| 34 |
]
|
| 35 |
|
| 36 |
# --- 3. Configuration ---
|
|
@@ -42,7 +42,8 @@ REGION_MAP = {
|
|
| 42 |
}
|
| 43 |
|
| 44 |
# --- 4. Core Functions ---
|
| 45 |
-
|
|
|
|
| 46 |
def get_ai_response(system_msg, user_content, json_mode=True):
|
| 47 |
for model in MODEL_HIERARCHY:
|
| 48 |
try:
|
|
@@ -54,17 +55,17 @@ def get_ai_response(system_msg, user_content, json_mode=True):
|
|
| 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 |
-
|
|
|
|
|
|
|
| 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"):
|
|
@@ -78,6 +79,7 @@ def fetch_extensive_news(query, geo="US", limit=60, period="7d"):
|
|
| 78 |
return articles
|
| 79 |
|
| 80 |
def render_gauge(score, title):
|
|
|
|
| 81 |
fig = go.Figure(go.Indicator(
|
| 82 |
mode = "gauge+number",
|
| 83 |
value = score,
|
|
@@ -92,7 +94,7 @@ def render_gauge(score, title):
|
|
| 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 |
|
|
@@ -100,27 +102,28 @@ if st.button("π Refresh"):
|
|
| 100 |
if 'hot_issues' in st.session_state: del st.session_state.hot_issues
|
| 101 |
|
| 102 |
if 'hot_issues' not in st.session_state:
|
| 103 |
-
with st.spinner("Scanning
|
|
|
|
| 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: [
|
| 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:
|
|
@@ -133,6 +136,7 @@ if st.session_state.hot_issues:
|
|
| 133 |
for i, issue in enumerate(st.session_state.hot_issues):
|
| 134 |
with cols[i]:
|
| 135 |
with st.container(border=True):
|
|
|
|
| 136 |
st.markdown(f"<h1 style='text-align: center; color: #FF4B4B; margin: 0;'>{issue.get('score', 50)}</h1>", unsafe_allow_html=True)
|
| 137 |
st.markdown("<p style='text-align: center; color: gray; font-size: 0.8em;'>Safety Risk Index</p>", unsafe_allow_html=True)
|
| 138 |
st.error(f"**{issue.get('title')}**")
|
|
@@ -160,6 +164,7 @@ with tab1:
|
|
| 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 |
|
|
@@ -168,7 +173,7 @@ with tab1:
|
|
| 168 |
|
| 169 |
Return ONLY JSON:
|
| 170 |
{{
|
| 171 |
-
"executive_summary": "Start with [The
|
| 172 |
"risk_landscape": [
|
| 173 |
{{"Component": "Primary Violation", "Findings": "...", "Risk_Level": "High"}},
|
| 174 |
{{"Component": "Vulnerable Target", "Findings": "...", "Risk_Level": "Critical"}},
|
|
@@ -185,7 +190,6 @@ with tab1:
|
|
| 185 |
}}
|
| 186 |
"""
|
| 187 |
|
| 188 |
-
# [NEW] Use Smart Wrapper
|
| 189 |
res = get_ai_response(global_prompt, news_summary)
|
| 190 |
|
| 191 |
if res:
|
|
@@ -193,6 +197,7 @@ with tab1:
|
|
| 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")
|
|
@@ -203,7 +208,7 @@ with tab1:
|
|
| 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"
|
|
@@ -218,6 +223,7 @@ with tab2:
|
|
| 218 |
target_geo = st.text_input("ISO Code", "US").upper()
|
| 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:
|
|
@@ -225,6 +231,7 @@ with tab2:
|
|
| 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 |
|
|
@@ -247,7 +254,6 @@ with tab2:
|
|
| 247 |
}}
|
| 248 |
"""
|
| 249 |
|
| 250 |
-
# [NEW] Use Smart Wrapper
|
| 251 |
res = get_ai_response(system_prompt, news_titles)
|
| 252 |
|
| 253 |
if res:
|
|
@@ -262,6 +268,7 @@ with tab2:
|
|
| 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:**")
|
|
|
|
| 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
|
|
|
|
| 19 |
except: pass
|
| 20 |
|
| 21 |
if not api_key:
|
| 22 |
+
st.error("π GROQ_API_KEY Missing. Please check your deployment settings.")
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
| 26 |
|
| 27 |
+
# π¨ [CRITICAL] Robust Model Hierarchy (Auto-Switching)
|
| 28 |
+
# 429 μλ¬λ 400(λͺ¨λΈ μ’
λ£) μλ¬ λ°μ μ, μλμΌλ‘ λ€μ μμ λͺ¨λΈλ‘ μ ννμ¬ μ€λ¨ μμ΄ λΆμν©λλ€.
|
| 29 |
MODEL_HIERARCHY = [
|
| 30 |
+
"llama-3.3-70b-versatile", # 1μμ: μ΅μ SOTA λͺ¨λΈ
|
| 31 |
+
"llama-3.1-70b-versatile", # 2μμ: κ³ μ±λ₯ λ°±μ
|
| 32 |
+
"mixtral-8x7b-32768", # 3μμ: μμ μ± μμ£Ό
|
| 33 |
+
"llama-3.1-8b-instant" # 4μμ: μ΄κ³ μ λΉμμ©
|
| 34 |
]
|
| 35 |
|
| 36 |
# --- 3. Configuration ---
|
|
|
|
| 42 |
}
|
| 43 |
|
| 44 |
# --- 4. Core Functions ---
|
| 45 |
+
|
| 46 |
+
# [Smart AI Wrapper] μλ¬ νΈλ€λ§ λ° λͺ¨λΈ μλ μ ν λ‘μ§
|
| 47 |
def get_ai_response(system_msg, user_content, json_mode=True):
|
| 48 |
for model in MODEL_HIERARCHY:
|
| 49 |
try:
|
|
|
|
| 55 |
kwargs["response_format"] = {"type": "json_object"}
|
| 56 |
|
| 57 |
res = client.chat.completions.create(**kwargs)
|
| 58 |
+
return res
|
| 59 |
except RateLimitError:
|
| 60 |
+
continue # νλ μ΄κ³Ό μ λ€μ λͺ¨λΈ μλ
|
|
|
|
| 61 |
except Exception as e:
|
| 62 |
+
# λͺ¨λΈ μ’
λ£(400)λ μ°Ύμ μ μμ(404) μλ¬ μμλ λ€μ λͺ¨λΈ μλ
|
| 63 |
+
if "model_decommissioned" in str(e) or "404" in str(e) or "400" in str(e):
|
| 64 |
+
continue
|
| 65 |
+
st.error(f"β οΈ Error with {model}: {e}") # κ·Έ μΈ μΉλͺ
μ μλ¬λ μΆλ ₯
|
| 66 |
return None
|
| 67 |
|
| 68 |
+
st.error("π¨ All AI models are currently unavailable. Please check API Status.")
|
|
|
|
| 69 |
return None
|
| 70 |
|
| 71 |
def fetch_extensive_news(query, geo="US", limit=60, period="7d"):
|
|
|
|
| 79 |
return articles
|
| 80 |
|
| 81 |
def render_gauge(score, title):
|
| 82 |
+
# μμΈ λΆμμ© κ²μ΄μ§ μ°¨νΈ (μλ£Έ λ―Έμ¬μ©)
|
| 83 |
fig = go.Figure(go.Indicator(
|
| 84 |
mode = "gauge+number",
|
| 85 |
value = score,
|
|
|
|
| 94 |
fig.update_layout(height=180, margin=dict(l=10, r=10, t=40, b=10), paper_bgcolor="rgba(0,0,0,0)")
|
| 95 |
return fig
|
| 96 |
|
| 97 |
+
# --- 5. π¨ GLOBAL WAR ROOM (Policy Focused, Numeric Only) ---
|
| 98 |
st.title("π¨ OMNI-WATCH: T&S WAR ROOM")
|
| 99 |
st.caption(f"Policy Risk Monitoring: {datetime.now().strftime('%H:%M:%S')} UTC")
|
| 100 |
|
|
|
|
| 102 |
if 'hot_issues' in st.session_state: del st.session_state.hot_issues
|
| 103 |
|
| 104 |
if 'hot_issues' not in st.session_state:
|
| 105 |
+
with st.spinner("Scanning 12h Global Feeds for Violations..."):
|
| 106 |
+
# κ²μμ΄: T&S μλ° κ°λ₯μ±μ΄ λμ ν€μλ
|
| 107 |
raw_news = fetch_extensive_news("violence OR hate speech OR disinformation OR scandal OR protest", limit=40, period="12h")
|
| 108 |
|
| 109 |
if not raw_news:
|
| 110 |
+
st.warning("No critical incidents found in the last 12h.")
|
| 111 |
st.session_state.hot_issues = []
|
| 112 |
else:
|
| 113 |
news_context = "\n".join([f"Event: {n['title']}" for n in raw_news])
|
| 114 |
|
| 115 |
+
# PROMPT: μ¬κ±΄ κ°μμ μλ° μ¬νμ λͺ
νν ꡬλΆ
|
| 116 |
system_msg = """
|
| 117 |
Identify TOP 3 incidents with highest 'Trust & Safety' risk.
|
| 118 |
The 'summary' array MUST follow this order:
|
| 119 |
+
1. "Event: [Brief summary of what happened]"
|
| 120 |
+
2. "Violation: [Specific Community Guideline breached]"
|
| 121 |
+
3. "Risk: [Potential offline harm]"
|
| 122 |
|
| 123 |
Return ONLY JSON:
|
| 124 |
{"issues": [{"title": "Short Title", "score": 85, "summary": ["Event: ...", "Violation: ...", "Risk: ..."], "link": ".."}]}
|
| 125 |
"""
|
| 126 |
|
|
|
|
| 127 |
res = get_ai_response(system_msg, news_context)
|
| 128 |
if res:
|
| 129 |
try:
|
|
|
|
| 136 |
for i, issue in enumerate(st.session_state.hot_issues):
|
| 137 |
with cols[i]:
|
| 138 |
with st.container(border=True):
|
| 139 |
+
# UI: κ²μ΄μ§ λμ ν° μ«μ μ¬μ© (λͺ¨λ°μΌ κ°λ
μ±)
|
| 140 |
st.markdown(f"<h1 style='text-align: center; color: #FF4B4B; margin: 0;'>{issue.get('score', 50)}</h1>", unsafe_allow_html=True)
|
| 141 |
st.markdown("<p style='text-align: center; color: gray; font-size: 0.8em;'>Safety Risk Index</p>", unsafe_allow_html=True)
|
| 142 |
st.error(f"**{issue.get('title')}**")
|
|
|
|
| 164 |
else:
|
| 165 |
news_summary = "\n".join([n['title'] for n in all_news[:45]])
|
| 166 |
|
| 167 |
+
# PROMPT: μ¬κ±΄ κ°μ(Summary) νμ ν¬ν¨
|
| 168 |
global_prompt = f"""
|
| 169 |
Analyze '{keyword}' focusing on 'Community Guidelines' and 'Social Impact'.
|
| 170 |
|
|
|
|
| 173 |
|
| 174 |
Return ONLY JSON:
|
| 175 |
{{
|
| 176 |
+
"executive_summary": "Start with [The Incident Details], then move to [Policy Analysis].",
|
| 177 |
"risk_landscape": [
|
| 178 |
{{"Component": "Primary Violation", "Findings": "...", "Risk_Level": "High"}},
|
| 179 |
{{"Component": "Vulnerable Target", "Findings": "...", "Risk_Level": "Critical"}},
|
|
|
|
| 190 |
}}
|
| 191 |
"""
|
| 192 |
|
|
|
|
| 193 |
res = get_ai_response(global_prompt, news_summary)
|
| 194 |
|
| 195 |
if res:
|
|
|
|
| 197 |
|
| 198 |
with st.container(border=True):
|
| 199 |
st.subheader("1. Policy Impact Executive Summary")
|
| 200 |
+
# κ°λ
μ±μ μν μ€λ°κΏ μ²λ¦¬
|
| 201 |
st.markdown(g_data.get('executive_summary').replace(". ", ".\n\n"))
|
| 202 |
|
| 203 |
st.subheader("2. Guideline Violation Matrix")
|
|
|
|
| 208 |
|
| 209 |
st.success(f"**T&S Recommendation:** {g_data.get('strategic_conclusion')}")
|
| 210 |
|
| 211 |
+
# DOWNLOAD: Markdown Format (λͺ¨λ°μΌ νΈν)
|
| 212 |
report_md = f"# OMNI-WATCH POLICY REPORT: {keyword.upper()}\n\n"
|
| 213 |
report_md += f"## 1. EXECUTIVE SUMMARY\n{g_data.get('executive_summary')}\n\n"
|
| 214 |
report_md += "## 2. VIOLATION LANDSCAPE\n"
|
|
|
|
| 223 |
target_geo = st.text_input("ISO Code", "US").upper()
|
| 224 |
if st.button("Analyze Violations"):
|
| 225 |
with st.status(f"Scanning {target_geo} for Policy Breaches (20+ Sources)...", expanded=True):
|
| 226 |
+
# κ²μμ΄ μ΅μ ν: μ€μ μ¬κ±΄/μ¬κ³ μμ£Ό
|
| 227 |
news = fetch_extensive_news(f"{target_geo} controversy OR scandal OR protest OR violence", geo=target_geo, limit=40, period="7d")
|
| 228 |
|
| 229 |
if not news:
|
|
|
|
| 231 |
else:
|
| 232 |
news_titles = "\n".join([n['title'] for n in news])
|
| 233 |
|
| 234 |
+
# PROMPT: Incident -> Policy Analysis ꡬ쑰 κ°μ
|
| 235 |
system_prompt = f"""
|
| 236 |
Analyze Top 5 Risks in {target_geo} strictly through a 'Community Guidelines' lens.
|
| 237 |
|
|
|
|
| 254 |
}}
|
| 255 |
"""
|
| 256 |
|
|
|
|
| 257 |
res = get_ai_response(system_prompt, news_titles)
|
| 258 |
|
| 259 |
if res:
|
|
|
|
| 268 |
with st.expander(f"π© RISK {r.get('rank')}: {r.get('title')} (Score: {r.get('score')})", expanded=True):
|
| 269 |
c1, c2 = st.columns([1, 4])
|
| 270 |
with c1:
|
| 271 |
+
# μμΈ λΆμ νμμλ κ²μ΄μ§ μ°¨νΈ μ¬μ© (Key μ€λ³΅ λ°©μ§ μ μ©)
|
| 272 |
st.plotly_chart(render_gauge(r.get('score'), "Risk Index"), use_container_width=True, key=f"fg_{i}")
|
| 273 |
with c2:
|
| 274 |
st.markdown("**Incident & Policy Analysis:**")
|