Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,14 +4,13 @@ import urllib.parse
|
|
| 4 |
from groq import Groq
|
| 5 |
import pandas as pd
|
| 6 |
import json
|
| 7 |
-
import time
|
| 8 |
import os
|
| 9 |
import plotly.express as px
|
| 10 |
|
| 11 |
# --- Page Config ---
|
| 12 |
-
st.set_page_config(page_title="Global
|
| 13 |
|
| 14 |
-
# ---
|
| 15 |
api_key = os.environ.get("GROQ_API_KEY")
|
| 16 |
if not api_key:
|
| 17 |
try: api_key = st.secrets["GROQ_API_KEY"]
|
|
@@ -21,19 +20,16 @@ if not api_key:
|
|
| 21 |
st.error("π GROQ_API_KEY Missing in Settings.")
|
| 22 |
st.stop()
|
| 23 |
|
| 24 |
-
# Groq ν΄λΌμ΄μΈνΈ μ΄κΈ°ν
|
| 25 |
client = Groq(api_key=api_key)
|
| 26 |
-
|
| 27 |
-
# μ΅μ λͺ¨λΈλͺ
μ μ (Llama 3.3 70B)
|
| 28 |
CURRENT_MODEL = "llama-3.3-70b-versatile"
|
| 29 |
|
| 30 |
-
# ---
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
"
|
| 34 |
-
"
|
| 35 |
-
"
|
| 36 |
-
"
|
| 37 |
}
|
| 38 |
|
| 39 |
def fetch_google_news(query, geo="US", lang="en", limit=10):
|
|
@@ -42,84 +38,93 @@ def fetch_google_news(query, geo="US", lang="en", limit=10):
|
|
| 42 |
feed = feedparser.parse(url)
|
| 43 |
return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
|
| 44 |
|
| 45 |
-
st.title("
|
| 46 |
-
st.caption("
|
| 47 |
st.markdown("---")
|
| 48 |
|
| 49 |
tab_search, tab_report = st.tabs(["π Global Issue Tracking", "π National Deep-Dive"])
|
| 50 |
|
| 51 |
# --- [Tab 1: Global Issue Tracking] ---
|
| 52 |
with tab_search:
|
| 53 |
-
st.subheader("Global Risk Propagation
|
| 54 |
col_k1, col_k2 = st.columns([3, 1])
|
| 55 |
with col_k1:
|
| 56 |
-
search_keyword = st.text_input("Enter Issue Keyword", "
|
|
|
|
| 57 |
with col_k2:
|
| 58 |
st.write("")
|
| 59 |
run_global = st.button("πΊοΈ Global Deep Scan", type="primary", use_container_width=True)
|
| 60 |
|
| 61 |
if run_global:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
results = []
|
| 63 |
all_captured_news = []
|
| 64 |
progress = st.progress(0)
|
| 65 |
status_msg = st.empty()
|
| 66 |
|
| 67 |
-
for i,
|
| 68 |
-
status_msg.text(f"
|
| 69 |
-
news = fetch_google_news(
|
| 70 |
|
| 71 |
if news:
|
| 72 |
titles = "\n".join([n['title'] for n in news])
|
| 73 |
-
all_captured_news.append(f"--- {
|
| 74 |
|
| 75 |
try:
|
| 76 |
res = client.chat.completions.create(
|
| 77 |
model=CURRENT_MODEL,
|
| 78 |
-
messages=[{"role": "user", "content": f"
|
| 79 |
max_tokens=10
|
| 80 |
)
|
| 81 |
score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
|
| 82 |
except: score = 50
|
| 83 |
-
results.append({"Country":
|
| 84 |
-
progress.progress((i + 1) / len(
|
| 85 |
|
| 86 |
status_msg.empty()
|
| 87 |
df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
|
| 88 |
st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"), use_container_width=True)
|
| 89 |
|
|
|
|
| 90 |
st.divider()
|
| 91 |
-
st.subheader(
|
| 92 |
-
|
| 93 |
-
with st.spinner("Synthesizing Massive Data..."):
|
| 94 |
combined_news = "\n\n".join(all_captured_news)
|
| 95 |
global_res = client.chat.completions.create(
|
| 96 |
model=CURRENT_MODEL,
|
| 97 |
-
messages=[{"role": "system", "content": "You are a
|
| 98 |
max_tokens=3000
|
| 99 |
)
|
| 100 |
-
st.markdown(f"<div style='background-color: #
|
| 101 |
|
| 102 |
# --- [Tab 2: National Deep-Dive] ---
|
| 103 |
with tab_report:
|
|
|
|
| 104 |
col_d1, col_d2 = st.columns([1, 4])
|
| 105 |
with col_d1:
|
| 106 |
-
|
|
|
|
| 107 |
data_vol = st.slider("Depth", 10, 60, 30)
|
| 108 |
run_deep = st.button("π Analyze Market", use_container_width=True)
|
| 109 |
|
| 110 |
if run_deep:
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
news = fetch_google_news(f"{target_country} social controversy", limit=data_vol)
|
| 114 |
feed_text = "\n".join([f"- {n['title']}" for n in news])
|
| 115 |
|
| 116 |
deep_res = client.chat.completions.create(
|
| 117 |
model=CURRENT_MODEL,
|
| 118 |
-
messages=[{"role": "system", "content": "Analyze Community Guideline violations & demographics (Minors, Women, Race).
|
| 119 |
response_format={"type": "json_object"}
|
| 120 |
)
|
| 121 |
data = json.loads(deep_res.choices[0].message.content)
|
| 122 |
|
| 123 |
-
st.header(f"π Intelligence Report: {
|
| 124 |
-
st.
|
| 125 |
-
st.
|
|
|
|
|
|
|
|
|
| 4 |
from groq import Groq
|
| 5 |
import pandas as pd
|
| 6 |
import json
|
|
|
|
| 7 |
import os
|
| 8 |
import plotly.express as px
|
| 9 |
|
| 10 |
# --- Page Config ---
|
| 11 |
+
st.set_page_config(page_title="Global Risk Radar: UN Scale", page_icon="πΊπ³", layout="wide")
|
| 12 |
|
| 13 |
+
# --- API Key Load ---
|
| 14 |
api_key = os.environ.get("GROQ_API_KEY")
|
| 15 |
if not api_key:
|
| 16 |
try: api_key = st.secrets["GROQ_API_KEY"]
|
|
|
|
| 20 |
st.error("π GROQ_API_KEY Missing in Settings.")
|
| 21 |
st.stop()
|
| 22 |
|
|
|
|
| 23 |
client = Groq(api_key=api_key)
|
|
|
|
|
|
|
| 24 |
CURRENT_MODEL = "llama-3.3-70b-versatile"
|
| 25 |
|
| 26 |
+
# --- π UN Nations Data (μ£Όμ μ λ΅ κ΅κ° μμ£Ό κΈ°λ³Έμ
+ νμ₯ κ°λ₯ ꡬ쑰) ---
|
| 27 |
+
# μ€μ μμλ pycountry κ°μ λΌμ΄λΈλ¬λ¦¬λ₯Ό μ¬μ©ν΄ 193κ°κ΅μ λ€ λΆλ¬μ¬ μ μμ΅λλ€.
|
| 28 |
+
REGION_MAP = {
|
| 29 |
+
"Asia": ["KR", "JP", "CN", "VN", "MY", "TH", "IN", "ID", "PH"],
|
| 30 |
+
"Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL"],
|
| 31 |
+
"Americas": ["US", "CA", "BR", "MX", "AR", "CO"],
|
| 32 |
+
"Middle East/Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
|
| 33 |
}
|
| 34 |
|
| 35 |
def fetch_google_news(query, geo="US", lang="en", limit=10):
|
|
|
|
| 38 |
feed = feedparser.parse(url)
|
| 39 |
return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
|
| 40 |
|
| 41 |
+
st.title("πΊπ³ Omni-Watch: UN Scale Intelligence")
|
| 42 |
+
st.caption("Monitoring Global Risks across all UN Member States")
|
| 43 |
st.markdown("---")
|
| 44 |
|
| 45 |
tab_search, tab_report = st.tabs(["π Global Issue Tracking", "π National Deep-Dive"])
|
| 46 |
|
| 47 |
# --- [Tab 1: Global Issue Tracking] ---
|
| 48 |
with tab_search:
|
| 49 |
+
st.subheader("Global Risk Propagation (Select Regions)")
|
| 50 |
col_k1, col_k2 = st.columns([3, 1])
|
| 51 |
with col_k1:
|
| 52 |
+
search_keyword = st.text_input("Enter Issue Keyword (e.g. 'Protest', 'Cyber Attack')", "Election Integrity")
|
| 53 |
+
selected_regions = st.multiselect("Select Target Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
|
| 54 |
with col_k2:
|
| 55 |
st.write("")
|
| 56 |
run_global = st.button("πΊοΈ Global Deep Scan", type="primary", use_container_width=True)
|
| 57 |
|
| 58 |
if run_global:
|
| 59 |
+
# μ νλ κΆμμ λͺ¨λ κ΅κ° 리μ€νΈμ
|
| 60 |
+
target_countries = []
|
| 61 |
+
for reg in selected_regions:
|
| 62 |
+
target_countries.extend(REGION_MAP[reg])
|
| 63 |
+
|
| 64 |
results = []
|
| 65 |
all_captured_news = []
|
| 66 |
progress = st.progress(0)
|
| 67 |
status_msg = st.empty()
|
| 68 |
|
| 69 |
+
for i, geo_code in enumerate(target_countries):
|
| 70 |
+
status_msg.text(f"Scanning {geo_code} for intelligence...")
|
| 71 |
+
news = fetch_google_news(search_keyword, geo=geo_code, limit=3)
|
| 72 |
|
| 73 |
if news:
|
| 74 |
titles = "\n".join([n['title'] for n in news])
|
| 75 |
+
all_captured_news.append(f"--- Country: {geo_code} ---\n{titles}")
|
| 76 |
|
| 77 |
try:
|
| 78 |
res = client.chat.completions.create(
|
| 79 |
model=CURRENT_MODEL,
|
| 80 |
+
messages=[{"role": "user", "content": f"Risk score (0-100) for '{search_keyword}' in {geo_code}: {titles}. ONLY INTEGER."}],
|
| 81 |
max_tokens=10
|
| 82 |
)
|
| 83 |
score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
|
| 84 |
except: score = 50
|
| 85 |
+
results.append({"Country": geo_code, "Risk": score})
|
| 86 |
+
progress.progress((i + 1) / len(target_countries))
|
| 87 |
|
| 88 |
status_msg.empty()
|
| 89 |
df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
|
| 90 |
st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"), use_container_width=True)
|
| 91 |
|
| 92 |
+
# [Global Deep Report]
|
| 93 |
st.divider()
|
| 94 |
+
st.subheader("π§ Llama 3.3 Global Strategic Synthesis")
|
| 95 |
+
with st.spinner("Analyzing Global Propagation..."):
|
|
|
|
| 96 |
combined_news = "\n\n".join(all_captured_news)
|
| 97 |
global_res = client.chat.completions.create(
|
| 98 |
model=CURRENT_MODEL,
|
| 99 |
+
messages=[{"role": "system", "content": "You are a UN Strategic Intelligence Officer. Analyze global risks and demographic impacts in 500+ words professional report."}, {"role": "user", "content": combined_news}],
|
| 100 |
max_tokens=3000
|
| 101 |
)
|
| 102 |
+
st.markdown(f"<div style='background-color: #e3f2fd; padding: 25px; border-radius: 10px; border-left: 5px solid #1976d2;'>{global_res.choices[0].message.content}</div>", unsafe_allow_html=True)
|
| 103 |
|
| 104 |
# --- [Tab 2: National Deep-Dive] ---
|
| 105 |
with tab_report:
|
| 106 |
+
st.subheader("Specific Country Intelligence Analysis")
|
| 107 |
col_d1, col_d2 = st.columns([1, 4])
|
| 108 |
with col_d1:
|
| 109 |
+
# μ¬μ©μκ° UN κ΅κ° μ½λλ₯Ό μ§μ μ
λ ₯ν μλ μκ² ν¨
|
| 110 |
+
target_geo = st.text_input("Enter ISO Country Code (e.g. KR, US, MY, UA)", "MY").upper()
|
| 111 |
data_vol = st.slider("Depth", 10, 60, 30)
|
| 112 |
run_deep = st.button("π Analyze Market", use_container_width=True)
|
| 113 |
|
| 114 |
if run_deep:
|
| 115 |
+
with st.status(f"Llama 3.3 Deep-Dive: {target_geo}...", expanded=True):
|
| 116 |
+
news = fetch_google_news(f"{target_geo} social risk", geo=target_geo, limit=data_vol)
|
|
|
|
| 117 |
feed_text = "\n".join([f"- {n['title']}" for n in news])
|
| 118 |
|
| 119 |
deep_res = client.chat.completions.create(
|
| 120 |
model=CURRENT_MODEL,
|
| 121 |
+
messages=[{"role": "system", "content": "Analyze Community Guideline violations & demographics (Minors, Women, Race). Return JSON with 'risk_score', 'executive_report', 'vulnerability_analysis', 'action_plan'."}, {"role": "user", "content": feed_text}],
|
| 122 |
response_format={"type": "json_object"}
|
| 123 |
)
|
| 124 |
data = json.loads(deep_res.choices[0].message.content)
|
| 125 |
|
| 126 |
+
st.header(f"π National Intelligence Report: {target_geo}")
|
| 127 |
+
st.metric("Risk Score", f"{data.get('risk_score')}/100")
|
| 128 |
+
st.markdown(f"<div style='background-color: #f5f5f5; padding: 20px; border-radius: 10px;'>{data.get('executive_report')}</div>", unsafe_allow_html=True)
|
| 129 |
+
st.error(f"**Vulnerability Analysis:** {data.get('vulnerability_analysis')}")
|
| 130 |
+
st.success(f"**Tactical Action Plan:** {data.get('action_plan')}")
|