Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,51 +6,62 @@ import pandas as pd
|
|
| 6 |
import json
|
| 7 |
import os
|
| 8 |
import plotly.express as px
|
| 9 |
-
import
|
| 10 |
|
| 11 |
# --- Page Config ---
|
| 12 |
st.set_page_config(page_title="Omni-Watch Intelligence Pro", page_icon="π‘", layout="wide")
|
| 13 |
|
| 14 |
# --- API Key Load ---
|
|
|
|
| 15 |
api_key = os.environ.get("GROQ_API_KEY")
|
| 16 |
if not api_key:
|
| 17 |
try: api_key = st.secrets["GROQ_API_KEY"]
|
| 18 |
except: pass
|
| 19 |
|
| 20 |
if not api_key:
|
| 21 |
-
st.error("π GROQ_API_KEY Missing.")
|
| 22 |
st.stop()
|
| 23 |
|
| 24 |
client = Groq(api_key=api_key)
|
| 25 |
CURRENT_MODEL = "llama-3.3-70b-versatile"
|
| 26 |
|
| 27 |
-
# --- π UN Geoscheme ---
|
| 28 |
REGION_MAP = {
|
| 29 |
-
"Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "TH", "IN", "ID", "PH", "AU"],
|
| 30 |
-
"Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL"],
|
| 31 |
-
"Americas": ["US", "CA", "BR", "MX", "AR", "CO", "VE"],
|
| 32 |
-
"
|
| 33 |
}
|
| 34 |
|
|
|
|
| 35 |
def fetch_google_news(query, geo="US", lang="en", limit=10):
|
| 36 |
encoded = urllib.parse.quote(query)
|
| 37 |
url = f"https://news.google.com/rss/search?q={encoded}&hl={lang}&gl={geo}&ceid={geo}:{lang}"
|
| 38 |
feed = feedparser.parse(url)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
st.markdown("---")
|
| 44 |
|
| 45 |
-
|
| 46 |
|
| 47 |
# --- [Tab 1: Global Issue Tracking] ---
|
| 48 |
-
with
|
| 49 |
-
st.subheader("Global Risk Propagation &
|
| 50 |
col_k1, col_k2 = st.columns([3, 1])
|
| 51 |
with col_k1:
|
| 52 |
-
search_keyword = st.text_input("Enter Issue Keyword", "
|
| 53 |
-
selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
|
| 54 |
with col_k2:
|
| 55 |
st.write("")
|
| 56 |
run_global = st.button("πΊοΈ Deep Global Scan", type="primary", use_container_width=True)
|
|
@@ -62,16 +73,18 @@ with tab_search:
|
|
| 62 |
results = []
|
| 63 |
all_captured_news = []
|
| 64 |
progress = st.progress(0)
|
|
|
|
| 65 |
|
| 66 |
for i, geo_code in enumerate(target_countries):
|
|
|
|
| 67 |
news = fetch_google_news(search_keyword, geo=geo_code, limit=3)
|
| 68 |
if news:
|
| 69 |
titles = "\n".join([n['title'] for n in news])
|
| 70 |
-
all_captured_news.extend(news)
|
| 71 |
try:
|
| 72 |
res = client.chat.completions.create(
|
| 73 |
model=CURRENT_MODEL,
|
| 74 |
-
messages=[{"role": "user", "content": f"
|
| 75 |
max_tokens=10
|
| 76 |
)
|
| 77 |
score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
|
|
@@ -79,55 +92,83 @@ with tab_search:
|
|
| 79 |
results.append({"Country": geo_code, "Risk": score})
|
| 80 |
progress.progress((i + 1) / len(target_countries))
|
| 81 |
|
|
|
|
| 82 |
df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
|
| 83 |
-
|
| 84 |
-
# π Visualization 1: Heatmap Bar Chart
|
| 85 |
-
st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk",
|
| 86 |
-
color_continuous_scale="Reds", text_auto=True,
|
| 87 |
-
title=f"Global Risk Concentration: {search_keyword}"), use_container_width=True)
|
| 88 |
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
{{
|
| 97 |
-
"
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
}}
|
|
|
|
| 102 |
"""
|
| 103 |
-
|
| 104 |
model=CURRENT_MODEL,
|
| 105 |
-
messages=[{"role": "system", "content":
|
| 106 |
response_format={"type": "json_object"}
|
| 107 |
)
|
| 108 |
-
data = json.loads(
|
| 109 |
-
|
| 110 |
-
# π Structured Report UI
|
| 111 |
-
st.markdown(f"### π Executive Intelligence: {search_keyword}")
|
| 112 |
-
st.info(data['summary'])
|
| 113 |
|
| 114 |
-
#
|
| 115 |
-
|
| 116 |
-
st.
|
| 117 |
-
|
| 118 |
-
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
-
# π« Guideline Violations
|
| 125 |
-
st.error(f"**Critical Policy Violations:** {', '.join(data['guidelines'])}")
|
| 126 |
-
|
| 127 |
-
# π° Evidence Feed (μ°Έκ³ λ΄μ€ κΈ°μ¬)
|
| 128 |
st.divider()
|
| 129 |
-
st.subheader("π°
|
| 130 |
-
st.dataframe(pd.DataFrame(
|
| 131 |
-
|
| 132 |
-
# --- [Tab 2: National Deep-Dive] ---
|
| 133 |
-
# (Tab 2λ μμ λμΌν κ΅¬μ‘°λ‘ μκ°ν λ° ν
μ΄λΈ λ‘μ§ μ μ©)
|
|
|
|
| 6 |
import json
|
| 7 |
import os
|
| 8 |
import plotly.express as px
|
| 9 |
+
import time
|
| 10 |
|
| 11 |
# --- Page Config ---
|
| 12 |
st.set_page_config(page_title="Omni-Watch Intelligence Pro", page_icon="π‘", layout="wide")
|
| 13 |
|
| 14 |
# --- API Key Load ---
|
| 15 |
+
# Hugging Face Secretsμ 'GROQ_API_KEY'λ₯Ό λ°λμ μ
λ ₯νμΈμ.
|
| 16 |
api_key = os.environ.get("GROQ_API_KEY")
|
| 17 |
if not api_key:
|
| 18 |
try: api_key = st.secrets["GROQ_API_KEY"]
|
| 19 |
except: pass
|
| 20 |
|
| 21 |
if not api_key:
|
| 22 |
+
st.error("π GROQ_API_KEY Missing. Please check your Secrets settings.")
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
| 26 |
CURRENT_MODEL = "llama-3.3-70b-versatile"
|
| 27 |
|
| 28 |
+
# --- π UN Geoscheme Data ---
|
| 29 |
REGION_MAP = {
|
| 30 |
+
"Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "TH", "IN", "ID", "PH", "AU", "SG"],
|
| 31 |
+
"Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL", "SE", "NO"],
|
| 32 |
+
"Americas": ["US", "CA", "BR", "MX", "AR", "CO", "CL", "VE"],
|
| 33 |
+
"Middle East & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR", "QA", "KE"]
|
| 34 |
}
|
| 35 |
|
| 36 |
+
# --- Helper: Google News RSS Fetcher ---
|
| 37 |
def fetch_google_news(query, geo="US", lang="en", limit=10):
|
| 38 |
encoded = urllib.parse.quote(query)
|
| 39 |
url = f"https://news.google.com/rss/search?q={encoded}&hl={lang}&gl={geo}&ceid={geo}:{lang}"
|
| 40 |
feed = feedparser.parse(url)
|
| 41 |
+
articles = []
|
| 42 |
+
for entry in feed.entries[:limit]:
|
| 43 |
+
articles.append({
|
| 44 |
+
"title": entry.title,
|
| 45 |
+
"link": entry.link,
|
| 46 |
+
"source": entry.source.title if 'source' in entry else "Google News",
|
| 47 |
+
"date": entry.published if 'published' in entry else "Recent"
|
| 48 |
+
})
|
| 49 |
+
return articles
|
| 50 |
+
|
| 51 |
+
# --- UI Setup ---
|
| 52 |
+
st.title("π‘ Omni-Watch: Universal Risk & Market Intelligence")
|
| 53 |
+
st.caption("Monitoring Global Propagation & National Risk Forensics with Llama 3.3 Intelligence")
|
| 54 |
st.markdown("---")
|
| 55 |
|
| 56 |
+
tab_global, tab_national = st.tabs(["π Global Issue Tracking", "π National Top 5 Risk Deep-Dive"])
|
| 57 |
|
| 58 |
# --- [Tab 1: Global Issue Tracking] ---
|
| 59 |
+
with tab_global:
|
| 60 |
+
st.subheader("Global Risk Propagation & Strategic Policy Report")
|
| 61 |
col_k1, col_k2 = st.columns([3, 1])
|
| 62 |
with col_k1:
|
| 63 |
+
search_keyword = st.text_input("Enter Issue Keyword to Analyze Globally", "Cyber Attacks")
|
| 64 |
+
selected_regions = st.multiselect("Select Target Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
|
| 65 |
with col_k2:
|
| 66 |
st.write("")
|
| 67 |
run_global = st.button("πΊοΈ Deep Global Scan", type="primary", use_container_width=True)
|
|
|
|
| 73 |
results = []
|
| 74 |
all_captured_news = []
|
| 75 |
progress = st.progress(0)
|
| 76 |
+
status_msg = st.empty()
|
| 77 |
|
| 78 |
for i, geo_code in enumerate(target_countries):
|
| 79 |
+
status_msg.text(f"Scanning {geo_code} for '{search_keyword}'...")
|
| 80 |
news = fetch_google_news(search_keyword, geo=geo_code, limit=3)
|
| 81 |
if news:
|
| 82 |
titles = "\n".join([n['title'] for n in news])
|
| 83 |
+
all_captured_news.extend(news)
|
| 84 |
try:
|
| 85 |
res = client.chat.completions.create(
|
| 86 |
model=CURRENT_MODEL,
|
| 87 |
+
messages=[{"role": "user", "content": f"Score 0-100 risk for '{search_keyword}' in {geo_code}: {titles}. ONLY INT."}],
|
| 88 |
max_tokens=10
|
| 89 |
)
|
| 90 |
score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
|
|
|
|
| 92 |
results.append({"Country": geo_code, "Risk": score})
|
| 93 |
progress.progress((i + 1) / len(target_countries))
|
| 94 |
|
| 95 |
+
status_msg.empty()
|
| 96 |
df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
|
| 97 |
+
st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds", title=f"Global Risk Heatmap: {search_keyword}"), use_container_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
st.divider()
|
| 100 |
+
st.subheader(f"π§ Llama 3.3 Global Intelligence Report")
|
| 101 |
+
with st.spinner("Synthesizing Strategic Policy Risks..."):
|
| 102 |
+
news_feed = "\n".join([n['title'] for n in all_captured_news[:20]])
|
| 103 |
+
global_prompt = f"""
|
| 104 |
+
Analyze the global propagation of '{search_keyword}'.
|
| 105 |
+
Structure your report with:
|
| 106 |
+
1. 'global_summary': Long professional report (300+ words).
|
| 107 |
+
2. 'market_insights': Table-ready data for TikTok, YouTube, Meta, X.
|
| 108 |
+
3. 'policy_risks': Violations of Community Guidelines and WHY.
|
| 109 |
+
4. 'demographics': Risks for Minors, Women, and Ethnic groups.
|
| 110 |
+
5. 'action_plan': Tactical moderation steps.
|
| 111 |
+
"""
|
| 112 |
+
res = client.chat.completions.create(
|
| 113 |
+
model=CURRENT_MODEL,
|
| 114 |
+
messages=[{"role": "system", "content": global_prompt}, {"role": "user", "content": news_feed}]
|
| 115 |
+
)
|
| 116 |
+
st.markdown(f"<div style='background-color: #e3f2fd; padding: 25px; border-radius: 10px; border-left: 5px solid #1976d2;'>{res.choices[0].message.content}</div>", unsafe_allow_html=True)
|
| 117 |
+
|
| 118 |
+
st.subheader("π° Reference News Feed")
|
| 119 |
+
st.dataframe(pd.DataFrame(all_captured_news)[['source', 'title', 'link']], use_container_width=True)
|
| 120 |
|
| 121 |
+
# --- [Tab 2: National Deep-Dive (Top 5 Risks)] ---
|
| 122 |
+
with tab_national:
|
| 123 |
+
st.subheader("Specific Country Top 5 Risk Intelligence")
|
| 124 |
+
col_d1, col_d2 = st.columns([1, 4])
|
| 125 |
+
with col_d1:
|
| 126 |
+
target_geo = st.text_input("Enter Country Code (ISO)", "KR").upper()
|
| 127 |
+
run_deep = st.button("π Analyze Market", use_container_width=True, type="primary")
|
| 128 |
+
|
| 129 |
+
if run_deep:
|
| 130 |
+
with st.status(f"Analytic Process for {target_geo}...", expanded=True) as status:
|
| 131 |
+
news = fetch_google_news(f"{target_geo} social controversy risk", geo=target_geo, limit=30)
|
| 132 |
+
news_titles = "\n".join([f"- {n['title']}" for n in news])
|
| 133 |
+
|
| 134 |
+
system_prompt = f"""
|
| 135 |
+
Identify the TOP 5 most critical social/platform risks in {target_geo}.
|
| 136 |
+
Return ONLY a JSON object:
|
| 137 |
{{
|
| 138 |
+
"risks": [
|
| 139 |
+
{{
|
| 140 |
+
"rank": 1,
|
| 141 |
+
"title": "Short title",
|
| 142 |
+
"score": 0-100,
|
| 143 |
+
"summary": "300+ word detailed report",
|
| 144 |
+
"violation": "Guideline breached & WHY",
|
| 145 |
+
"demographics": "Specific vulnerability (Minors, Women, etc.)",
|
| 146 |
+
"tactical_action": "Action for TikTok, YT, Meta"
|
| 147 |
+
}}
|
| 148 |
+
]
|
| 149 |
}}
|
| 150 |
+
Identify exactly 5 risks.
|
| 151 |
"""
|
| 152 |
+
res = client.chat.completions.create(
|
| 153 |
model=CURRENT_MODEL,
|
| 154 |
+
messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}],
|
| 155 |
response_format={"type": "json_object"}
|
| 156 |
)
|
| 157 |
+
data = json.loads(res.choices[0].message.content)
|
| 158 |
+
status.update(label="Analysis Complete", state="complete")
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
+
# π Visualization
|
| 161 |
+
df_risks = pd.DataFrame(data['risks'])
|
| 162 |
+
st.plotly_chart(px.bar(df_risks, x='score', y='title', orientation='h', color='score', color_continuous_scale='Reds', title=f"{target_geo} Top 5 Severity Map"), use_container_width=True)
|
|
|
|
|
|
|
| 163 |
|
| 164 |
+
for r in data['risks']:
|
| 165 |
+
with st.expander(f"π© Rank {r['rank']}: {r['title']} (Severity: {r['score']})", expanded=(r['rank']==1)):
|
| 166 |
+
st.markdown(f"**π Strategic Summary:** {r['summary']}")
|
| 167 |
+
st.table(pd.DataFrame({
|
| 168 |
+
"Category": ["Guideline Violation", "Target Demographics", "Tactical Action"],
|
| 169 |
+
"Analysis": [r['violation'], r['demographics'], r['tactical_action']]
|
| 170 |
+
}))
|
| 171 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
st.divider()
|
| 173 |
+
st.subheader("π° Evidence Feed")
|
| 174 |
+
st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
|
|
|
|
|
|
|
|
|