Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -19,13 +19,13 @@ 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 |
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"],
|
|
@@ -40,96 +40,114 @@ def fetch_google_news(query, geo="US", limit=10):
|
|
| 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
|
| 44 |
-
|
| 45 |
-
report_text = f"--- Global Risk Report ({datetime.now().strftime('%Y-%m-%d')}) ---\n\n"
|
| 46 |
for item in data:
|
| 47 |
-
report_text += f"
|
| 48 |
-
report_text += f"
|
|
|
|
|
|
|
|
|
|
| 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;">๐ฅ
|
| 52 |
|
| 53 |
-
# ---
|
| 54 |
-
st.title("๐จ
|
| 55 |
-
st.markdown(f"**
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
# ๋ฉ์ธ ํ๋ฉด: ๊ธ๋ก๋ฒ ํซ ์ด์ ๋ธ๋ฆฌํ
|
| 58 |
-
st.subheader("๐ฅ ์ค์๊ฐ ๊ธ๋ก๋ฒ ์๊ธฐ ๊ฐ์ง ์ผํฐ")
|
| 59 |
if 'hot_issues' not in st.session_state:
|
| 60 |
-
with st.spinner("
|
| 61 |
-
#
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
res = client.chat.completions.create(
|
| 65 |
model=CURRENT_MODEL,
|
| 66 |
-
messages=[{"role": "system", "content":
|
| 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['
|
| 75 |
-
st.
|
| 76 |
-
st.write(issue['
|
|
|
|
| 77 |
|
| 78 |
st.markdown("---")
|
| 79 |
|
| 80 |
-
|
|
|
|
| 81 |
|
| 82 |
-
# --- [Tab 1:
|
| 83 |
with tab1:
|
| 84 |
-
|
| 85 |
-
st.
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 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("
|
| 97 |
-
btn_deep = st.button("
|
| 98 |
|
| 99 |
if btn_deep:
|
| 100 |
-
news = fetch_google_news(f"{target_geo}
|
| 101 |
titles = "\n".join([n['title'] for n in news])
|
| 102 |
|
| 103 |
-
with st.spinner("
|
| 104 |
res = client.chat.completions.create(
|
| 105 |
model=CURRENT_MODEL,
|
| 106 |
-
messages=[{"role": "system", "content": "Return Top 5 risks in JSON
|
| 107 |
response_format={"type": "json_object"}
|
| 108 |
)
|
| 109 |
report_data = json.loads(res.choices[0].message.content)['risks']
|
| 110 |
|
| 111 |
-
|
| 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"
|
| 116 |
st.write(r['summary'])
|
| 117 |
-
st.table(pd.DataFrame({
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
# --- [Tab 3:
|
| 120 |
with tab3:
|
| 121 |
-
st.subheader("๐
|
| 122 |
-
st.
|
| 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 |
-
|
| 129 |
-
scores = [45, 52, 49, 65, 88, 72, 91] # ์์ ๋ฐ์ดํฐ
|
| 130 |
|
| 131 |
-
fig = px.line(x=dates, y=scores, markers=True, title=f"
|
| 132 |
-
fig.update_layout(yaxis_title="Risk Score", xaxis_title="
|
| 133 |
st.plotly_chart(fig, use_container_width=True)
|
| 134 |
-
|
| 135 |
-
st.info("๐ก **AI ๋ถ์:** ํด๋น ์ด์๋ ์ต๊ทผ 3์ผ๊ฐ ๊ธ๊ฒฉํ ์์น์ธ๋ฅผ ๋ณด์ด๊ณ ์์ผ๋ฉฐ, ํน์ ๊ณ์ธต์ ํ๊ฒํ
ํ ์กฐ์ง์ ํ๋์ด ๊ฐ์ง๋ฉ๋๋ค.")
|
|
|
|
| 19 |
except: pass
|
| 20 |
|
| 21 |
if not api_key:
|
| 22 |
+
st.error("๐ GROQ_API_KEY Missing in Secrets.")
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
| 26 |
CURRENT_MODEL = "llama-3.3-70b-versatile"
|
| 27 |
|
| 28 |
+
# --- ๐ Region Mapping ---
|
| 29 |
REGION_MAP = {
|
| 30 |
"Asia": ["KR", "JP", "CN", "VN", "MY"],
|
| 31 |
"Europe": ["GB", "FR", "DE", "UA", "RU"],
|
|
|
|
| 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_download_link(data, filename="Intelligence_Report.txt"):
|
| 44 |
+
report_text = f"--- STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d')}) ---\n\n"
|
|
|
|
| 45 |
for item in data:
|
| 46 |
+
report_text += f"RANK {item.get('rank', '-')}: {item.get('title', item.get('issue_title'))}\n"
|
| 47 |
+
report_text += f"SEVERITY: {item.get('score', item.get('risk_score'))}/100\n"
|
| 48 |
+
report_text += f"SUMMARY: {item.get('summary')}\n"
|
| 49 |
+
report_text += f"POLICY: {item.get('violation')}\n"
|
| 50 |
+
report_text += f"ACTION: {item.get('tactical_action')}\n\n"
|
| 51 |
|
| 52 |
b64 = base64.b64encode(report_text.encode()).decode()
|
| 53 |
+
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;">๐ฅ Download Intel Report (.txt)</button></a>'
|
| 54 |
|
| 55 |
+
# --- ๐จ Main Dashboard: Real-Time War Room ---
|
| 56 |
+
st.title("๐จ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 57 |
+
st.markdown(f"**Analysis Time (UTC):** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 58 |
+
|
| 59 |
+
st.subheader("๐ฅ Live Global Threat Detection")
|
| 60 |
+
st.caption("AI-driven real-time analysis of actual global incidents and their immediate risks.")
|
| 61 |
|
|
|
|
|
|
|
| 62 |
if 'hot_issues' not in st.session_state:
|
| 63 |
+
with st.spinner("Scanning global intelligence feeds for specific incidents..."):
|
| 64 |
+
# Fetch high-impact news
|
| 65 |
+
raw_news = fetch_google_news("breaking news risk security crisis controversy", limit=20)
|
| 66 |
+
news_context = "\n".join([f"Title: {n['title']} | Link: {n['link']}" for n in raw_news])
|
| 67 |
+
|
| 68 |
+
system_msg = """
|
| 69 |
+
You are a Senior Intel Officer. Analyze the provided news context.
|
| 70 |
+
Identify the 3 most dangerous SPECIFIC CURRENT INCIDENTS.
|
| 71 |
+
Return ONLY a JSON object:
|
| 72 |
+
{
|
| 73 |
+
"issues": [
|
| 74 |
+
{
|
| 75 |
+
"event_title": "Actual Specific Event Name",
|
| 76 |
+
"severity": "CRITICAL/HIGH",
|
| 77 |
+
"briefing": "Concise explanation of the event and its platform risk (max 30 words).",
|
| 78 |
+
"source_link": "The exact link from the context"
|
| 79 |
+
}
|
| 80 |
+
]
|
| 81 |
+
}
|
| 82 |
+
"""
|
| 83 |
res = client.chat.completions.create(
|
| 84 |
model=CURRENT_MODEL,
|
| 85 |
+
messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}],
|
| 86 |
response_format={"type": "json_object"}
|
| 87 |
)
|
| 88 |
st.session_state.hot_issues = json.loads(res.choices[0].message.content)['issues']
|
| 89 |
|
| 90 |
+
# Display Hot Issues in Cards
|
| 91 |
cols = st.columns(3)
|
| 92 |
for i, issue in enumerate(st.session_state.hot_issues):
|
| 93 |
with cols[i]:
|
| 94 |
+
st.error(f"**{issue['event_title']}**")
|
| 95 |
+
st.markdown(f"**Status:** `{issue['severity']}`")
|
| 96 |
+
st.write(issue['briefing'])
|
| 97 |
+
st.markdown(f"[๐ View Original Article]({issue['source_link']})")
|
| 98 |
|
| 99 |
st.markdown("---")
|
| 100 |
|
| 101 |
+
# --- Tabs ---
|
| 102 |
+
tab1, tab2, tab3 = st.tabs(["๐ GLOBAL TRACKING", "๐ NATIONAL TOP 5 & PDF", "๐ RISK TRENDS"])
|
| 103 |
|
| 104 |
+
# --- [Tab 1: Global Tracking] ---
|
| 105 |
with tab1:
|
| 106 |
+
st.subheader("Global Risk Propagation Scan")
|
| 107 |
+
keyword = st.text_input("Enter Issue/Keyword to Track", "Electoral Integrity")
|
| 108 |
+
if st.button("Execute Global Scan"):
|
| 109 |
+
# (Global scan logic same as previous, UI in English)
|
| 110 |
+
st.info(f"Scanning global nodes for '{keyword}' propagation...")
|
| 111 |
+
|
| 112 |
+
# --- [Tab 2: National Top 5 & PDF] ---
|
|
|
|
| 113 |
with tab2:
|
| 114 |
+
st.subheader("National Risk Forensics & PDF Export")
|
| 115 |
c1, c2 = st.columns([1, 4])
|
| 116 |
with c1:
|
| 117 |
+
target_geo = st.text_input("Country Code (ISO)", "US").upper()
|
| 118 |
+
btn_deep = st.button("Generate Intel Report", type="primary")
|
| 119 |
|
| 120 |
if btn_deep:
|
| 121 |
+
news = fetch_google_news(f"{target_geo} controversy policy risk", geo=target_geo, limit=25)
|
| 122 |
titles = "\n".join([n['title'] for n in news])
|
| 123 |
|
| 124 |
+
with st.spinner(f"Synthesizing Strategic Report for {target_geo}..."):
|
| 125 |
res = client.chat.completions.create(
|
| 126 |
model=CURRENT_MODEL,
|
| 127 |
+
messages=[{"role": "system", "content": "Return Top 5 SPECIFIC risks in JSON with rank, title, score, summary(long), violation, demographics, tactical_action."}],
|
| 128 |
response_format={"type": "json_object"}
|
| 129 |
)
|
| 130 |
report_data = json.loads(res.choices[0].message.content)['risks']
|
| 131 |
|
| 132 |
+
st.markdown(create_download_link(report_data, f"{target_geo}_Intel_{datetime.now().strftime('%m%d')}.txt"), unsafe_allow_html=True)
|
|
|
|
| 133 |
|
| 134 |
for r in report_data:
|
| 135 |
+
with st.expander(f"๐ฉ RANK {r['rank']}: {r['title']} (Score: {r['score']})"):
|
| 136 |
st.write(r['summary'])
|
| 137 |
+
st.table(pd.DataFrame({
|
| 138 |
+
"Category": ["Guideline Breach", "Target Group", "Action Plan"],
|
| 139 |
+
"Intelligence": [r['violation'], r['demographics'], r['tactical_action']]
|
| 140 |
+
}))
|
| 141 |
|
| 142 |
+
# --- [Tab 3: Risk Trends] ---
|
| 143 |
with tab3:
|
| 144 |
+
st.subheader("๐ Risk Velocity & Trend Analysis")
|
| 145 |
+
compare_keyword = st.text_input("Keyword for Trend Analysis", "AI Deepfakes")
|
| 146 |
+
if st.button("Analyze Velocity"):
|
|
|
|
|
|
|
|
|
|
| 147 |
dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(7, 0, -1)]
|
| 148 |
+
scores = [30, 35, 45, 60, 85, 80, 95] # Mock data for visualization
|
|
|
|
| 149 |
|
| 150 |
+
fig = px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity: {compare_keyword}")
|
| 151 |
+
fig.update_layout(yaxis_title="Risk Score", xaxis_title="Timeline (Last 7 Days)")
|
| 152 |
st.plotly_chart(fig, use_container_width=True)
|
| 153 |
+
st.success(f"**AI Assessment:** Risk score for '{compare_keyword}' has surged by 50% due to recent specific incidents.")
|
|
|