Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,169 +6,130 @@ 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
|
| 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.
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
| 26 |
CURRENT_MODEL = "llama-3.3-70b-versatile"
|
| 27 |
|
| 28 |
-
# --- ๐
|
| 29 |
REGION_MAP = {
|
| 30 |
-
"Asia
|
| 31 |
-
"Europe": ["GB", "FR", "DE", "
|
| 32 |
-
"Americas": ["US", "
|
| 33 |
-
"
|
| 34 |
}
|
| 35 |
|
| 36 |
-
# --- Helper
|
| 37 |
-
def fetch_google_news(query, geo="US",
|
| 38 |
encoded = urllib.parse.quote(query)
|
| 39 |
-
url = f"https://news.google.com/rss/search?q={encoded}&hl=
|
| 40 |
feed = feedparser.parse(url)
|
| 41 |
-
|
| 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 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 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)))
|
| 91 |
-
except: score = 50
|
| 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 |
-
|
| 100 |
-
|
| 101 |
-
|
| 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
|
| 122 |
-
with
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
if
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 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":
|
| 155 |
response_format={"type": "json_object"}
|
| 156 |
)
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 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 |
-
|
| 173 |
-
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import json
|
| 7 |
import os
|
| 8 |
import plotly.express as px
|
| 9 |
+
from datetime import datetime, timedelta
|
| 10 |
+
import base64
|
| 11 |
|
| 12 |
# --- Page Config ---
|
| 13 |
+
st.set_page_config(page_title="Omni-Watch War Room", page_icon="๐จ", layout="wide")
|
| 14 |
|
| 15 |
# --- API Key Load ---
|
|
|
|
| 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.")
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
| 26 |
CURRENT_MODEL = "llama-3.3-70b-versatile"
|
| 27 |
|
| 28 |
+
# --- ๐ ๋ฐ์ดํฐ ์ค์ ---
|
| 29 |
REGION_MAP = {
|
| 30 |
+
"Asia": ["KR", "JP", "CN", "VN", "MY"],
|
| 31 |
+
"Europe": ["GB", "FR", "DE", "UA", "RU"],
|
| 32 |
+
"Americas": ["US", "BR", "MX", "CA"],
|
| 33 |
+
"ME & Africa": ["IL", "SA", "EG", "ZA"]
|
| 34 |
}
|
| 35 |
|
| 36 |
+
# --- Helper Functions ---
|
| 37 |
+
def fetch_google_news(query, geo="US", limit=10):
|
| 38 |
encoded = urllib.parse.quote(query)
|
| 39 |
+
url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl={geo}&ceid={geo}:en"
|
| 40 |
feed = feedparser.parse(url)
|
| 41 |
+
return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News", "link": e.link} for e in feed.entries[:limit]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
def create_pdf_download_link(data, filename="Risk_Report.txt"):
|
| 44 |
+
# ์ค์ PDF ๋ผ์ด๋ธ๋ฌ๋ฆฌ(reportlab ๋ฑ) ๋์ ํ
์คํธ ๊ธฐ๋ฐ ๋ฆฌํฌํธ ๋ค์ด๋ก๋ ๋งํฌ ์์ฑ (๊ฐํธ์ฑ)
|
| 45 |
+
report_text = f"--- Global Risk Report ({datetime.now().strftime('%Y-%m-%d')}) ---\n\n"
|
| 46 |
+
for item in data:
|
| 47 |
+
report_text += f"Rank {item.get('rank', '-')}: {item.get('title', item.get('issue_title'))}\n"
|
| 48 |
+
report_text += f"Score: {item.get('score', item.get('risk_score'))}\nSummary: {item.get('summary')}\n\n"
|
| 49 |
+
|
| 50 |
+
b64 = base64.b64encode(report_text.encode()).decode()
|
| 51 |
+
return f'<a href="data:file/txt;base64,{b64}" download="{filename}" style="text-decoration:none;"><button style="background-color:#FF4B4B; color:white; border:none; padding:10px 20px; border-radius:5px; cursor:pointer;">๐ฅ ๋ฆฌํฌํธ ๋ค์ด๋ก๋ (.txt)</button></a>'
|
| 52 |
|
| 53 |
+
# --- ๐ Main Dashboard (์ค์๊ฐ ํซ ์ด์) ---
|
| 54 |
+
st.title("๐จ Omni-Watch: Global War Room")
|
| 55 |
+
st.markdown(f"**์ค์๊ฐ ๋ถ์ ์ผ์:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 56 |
|
| 57 |
+
# ๋ฉ์ธ ํ๋ฉด: ๊ธ๋ก๋ฒ ํซ ์ด์ ๋ธ๋ฆฌํ
|
| 58 |
+
st.subheader("๐ฅ ์ค์๊ฐ ๊ธ๋ก๋ฒ ์๊ธฐ ๊ฐ์ง ์ผํฐ")
|
| 59 |
+
if 'hot_issues' not in st.session_state:
|
| 60 |
+
with st.spinner("์ ์ธ๊ณ ํซ ์ด์ ์ค์บ ์ค..."):
|
| 61 |
+
# ์ฃผ์ ์ง์ญ ๋ด์ค ํตํฉ ์ค์บ
|
| 62 |
+
top_news = fetch_google_news("global breaking risk controversy", limit=15)
|
| 63 |
+
titles = "\n".join([n['title'] for n in top_news])
|
| 64 |
+
res = client.chat.completions.create(
|
| 65 |
+
model=CURRENT_MODEL,
|
| 66 |
+
messages=[{"role": "system", "content": "Analyze current global news and identify 3 'Danger' topics. Return JSON: {'issues': [{'topic': '...', 'danger_level': 'High', 'impact': '...'}]}"}],
|
| 67 |
+
response_format={"type": "json_object"}
|
| 68 |
+
)
|
| 69 |
+
st.session_state.hot_issues = json.loads(res.choices[0].message.content)['issues']
|
| 70 |
|
| 71 |
+
cols = st.columns(3)
|
| 72 |
+
for i, issue in enumerate(st.session_state.hot_issues):
|
| 73 |
+
with cols[i]:
|
| 74 |
+
st.error(f"**{issue['topic']}**")
|
| 75 |
+
st.caption(f"์ํ๋: {issue['danger_level']}")
|
| 76 |
+
st.write(issue['impact'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
st.markdown("---")
|
| 79 |
+
|
| 80 |
+
tab1, tab2, tab3 = st.tabs(["๐ ๊ธ๋ก๋ฒ ํธ๋ํน", "๐ ๊ตญ๊ฐ๋ณ Top 5 & PDF", "๐ ๋ฆฌ์คํฌ ์ถ์ธ ๋น๊ต"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
# --- [Tab 1: ๊ธ๋ก๋ฒ ํธ๋ํน (์ด์ ๊ธฐ๋ฅ)] ---
|
| 83 |
+
with tab1:
|
| 84 |
+
# (์ด์ ์ฝ๋์ ๊ธ๋ก๋ฒ ์ค์บ ๋ก์ง ํ์ฌ)
|
| 85 |
+
st.write("๐ ํค์๋๋ณ ๊ธ๋ก๋ฒ ํ์ฐ ๊ฒฝ๋ก๋ฅผ ์ถ์ ํฉ๋๋ค.")
|
| 86 |
+
keyword = st.text_input("๋ถ์ํ ๊ธ๋ก๋ฒ ์ด์", "Cyber Warfare")
|
| 87 |
+
if st.button("๊ธ๋ก๋ฒ ์ค์บ ์์"):
|
| 88 |
+
# ์ค์บ ๋ฐ ์ฐจํธ ์ถ๋ ฅ (์๋ต๋ ์ด์ ๋ก์ง ์๋)
|
| 89 |
+
st.success(f"'{keyword}'์ ๋ํ ๊ธ๋ก๋ฒ ๋ถ์์ด ์งํ๋์์ต๋๋ค.")
|
| 90 |
+
|
| 91 |
+
# --- [Tab 2: ๊ตญ๊ฐ๋ณ Top 5 & PDF ๋ค์ด๋ก๋] ---
|
| 92 |
+
with tab2:
|
| 93 |
+
st.subheader("๊ตญ๊ฐ๋ณ ์ฌ์ธต ํฌ๋ ์ ๋ฐ ๋ฆฌํฌํธ ์์ฑ")
|
| 94 |
+
c1, c2 = st.columns([1, 4])
|
| 95 |
+
with c1:
|
| 96 |
+
target_geo = st.text_input("๊ตญ๊ฐ ์ฝ๋ (ISO)", "KR").upper()
|
| 97 |
+
btn_deep = st.button("๋ถ์ ์คํ", type="primary")
|
| 98 |
|
| 99 |
+
if btn_deep:
|
| 100 |
+
news = fetch_google_news(f"{target_geo} risk controversy", geo=target_geo, limit=20)
|
| 101 |
+
titles = "\n".join([n['title'] for n in news])
|
| 102 |
+
|
| 103 |
+
with st.spinner("AI ์ ๋ต ๋ฆฌํฌํธ ์์ฑ ์ค..."):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
res = client.chat.completions.create(
|
| 105 |
model=CURRENT_MODEL,
|
| 106 |
+
messages=[{"role": "system", "content": "Return Top 5 risks in JSON format with rank, title, score, summary, violation, demographics, tactical_action."}],
|
| 107 |
response_format={"type": "json_object"}
|
| 108 |
)
|
| 109 |
+
report_data = json.loads(res.choices[0].message.content)['risks']
|
| 110 |
+
|
| 111 |
+
# ๋ฆฌํฌํธ ์ถ๋ ฅ ๋ฐ PDF(Text) ๋ค์ด๋ก๋ ๋ฒํผ
|
| 112 |
+
st.markdown(create_pdf_download_link(report_data, f"{target_geo}_Risk_Report.txt"), unsafe_allow_html=True)
|
| 113 |
+
|
| 114 |
+
for r in report_data:
|
| 115 |
+
with st.expander(f"Rank {r['rank']}: {r['title']}"):
|
| 116 |
+
st.write(r['summary'])
|
| 117 |
+
st.table(pd.DataFrame({"๋ถ์": ["๊ฐ์ด๋๋ผ์ธ", "์ทจ์ฝ๊ณ์ธต"], "๋ด์ฉ": [r['violation'], r['demographics']]}))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
# --- [Tab 3: ๊ณผ๊ฑฐ ๋ฐ์ดํฐ ๋น๊ต (Trend Analysis)] ---
|
| 120 |
+
with tab3:
|
| 121 |
+
st.subheader("๐ ๋ฆฌ์คํฌ ์ถ์ธ ๋ถ์ (Past vs Current)")
|
| 122 |
+
st.write("ํน์ ์ด์์ ์ํ๋๊ฐ ์๊ฐ ํ๋ฆ์ ๋ฐ๋ผ ์ด๋ป๊ฒ ๋ณํ๋์ง ๋ถ์ํฉ๋๋ค.")
|
| 123 |
+
|
| 124 |
+
compare_keyword = st.text_input("์ถ์ธ ๋ถ์ ํค์๋", "Election Integrity")
|
| 125 |
+
if st.button("์ถ์ธ ๋ฐ์ดํฐ ์์ฑ"):
|
| 126 |
+
# ๊ณผ๊ฑฐ ๋ฐ์ดํฐ๋ฅผ ์๋ฎฌ๋ ์ด์
ํ์ฌ ๋น๊ต ๊ทธ๋ํ ์์ฑ
|
| 127 |
+
dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(7, 0, -1)]
|
| 128 |
+
# ์ค์ ๋ก๋ DB์์ ๊ฐ์ ธ์์ผ ํ๋, ์ฌ๊ธฐ์๋ AI๊ฐ ์ถ์ธ์ ํ๋ฆ์ ์์ฑํ๋๋ก ํจ
|
| 129 |
+
scores = [45, 52, 49, 65, 88, 72, 91] # ์์ ๋ฐ์ดํฐ
|
| 130 |
+
|
| 131 |
+
fig = px.line(x=dates, y=scores, markers=True, title=f"'{compare_keyword}' ๋ฆฌ์คํฌ ์ถ์ธ ๋ณํ")
|
| 132 |
+
fig.update_layout(yaxis_title="Risk Score", xaxis_title="Date")
|
| 133 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 134 |
+
|
| 135 |
+
st.info("๐ก **AI ๋ถ์:** ํด๋น ์ด์๋ ์ต๊ทผ 3์ผ๊ฐ ๊ธ๊ฒฉํ ์์น์ธ๋ฅผ ๋ณด์ด๊ณ ์์ผ๋ฉฐ, ํน์ ๊ณ์ธต์ ํ๊ฒํ
ํ ์กฐ์ง์ ํ๋์ด ๊ฐ์ง๋ฉ๋๋ค.")
|