Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -19,7 +19,7 @@ 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)
|
|
@@ -27,55 +27,61 @@ 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"],
|
| 32 |
-
"Americas": ["US", "
|
| 33 |
-
"ME & Africa": ["IL", "SA", "
|
| 34 |
}
|
| 35 |
|
| 36 |
# --- Helper Functions ---
|
| 37 |
-
def fetch_google_news(query, geo="US", limit=
|
| 38 |
-
|
|
|
|
|
|
|
| 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_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'
|
| 47 |
-
report_text += f"SEVERITY: {item.get('score'
|
| 48 |
report_text += f"SUMMARY: {item.get('summary')}\n"
|
| 49 |
-
report_text += f"POLICY: {item.get('violation')}\n"
|
| 50 |
-
report_text += f"
|
|
|
|
| 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"**
|
| 58 |
|
| 59 |
-
st.subheader("π₯
|
| 60 |
-
st.caption("AI-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
if 'hot_issues' not in st.session_state:
|
| 63 |
-
with st.spinner("
|
| 64 |
-
|
| 65 |
-
|
| 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
|
| 70 |
-
Identify the 3 most dangerous
|
| 71 |
Return ONLY a JSON object:
|
| 72 |
{
|
| 73 |
"issues": [
|
| 74 |
{
|
| 75 |
-
"event_title": "
|
| 76 |
"severity": "CRITICAL/HIGH",
|
| 77 |
-
"briefing": "
|
| 78 |
-
"source_link": "
|
| 79 |
}
|
| 80 |
]
|
| 81 |
}
|
|
@@ -87,67 +93,72 @@ if 'hot_issues' not in st.session_state:
|
|
| 87 |
)
|
| 88 |
st.session_state.hot_issues = json.loads(res.choices[0].message.content)['issues']
|
| 89 |
|
| 90 |
-
# Display
|
| 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"**
|
| 96 |
st.write(issue['briefing'])
|
| 97 |
-
st.markdown(f"[π
|
| 98 |
|
| 99 |
st.markdown("---")
|
| 100 |
|
| 101 |
-
# --- Tabs ---
|
| 102 |
-
tab1, tab2, tab3 = st.tabs(["π GLOBAL
|
| 103 |
|
| 104 |
# --- [Tab 1: Global Tracking] ---
|
| 105 |
with tab1:
|
| 106 |
-
st.subheader("
|
| 107 |
-
keyword = st.text_input("
|
| 108 |
-
if st.button("Execute Global Scan"):
|
| 109 |
-
#
|
| 110 |
-
st.info(
|
| 111 |
-
|
| 112 |
-
|
|
|
|
| 113 |
with tab2:
|
| 114 |
-
st.subheader("National
|
| 115 |
c1, c2 = st.columns([1, 4])
|
| 116 |
with c1:
|
| 117 |
-
target_geo = st.text_input("Country Code (ISO)", "
|
| 118 |
-
btn_deep = st.button("Generate
|
| 119 |
|
| 120 |
if btn_deep:
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
res = client.chat.completions.create(
|
| 126 |
model=CURRENT_MODEL,
|
| 127 |
-
messages=[{"role": "system", "content":
|
| 128 |
response_format={"type": "json_object"}
|
| 129 |
)
|
| 130 |
report_data = json.loads(res.choices[0].message.content)['risks']
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
| 143 |
with tab3:
|
| 144 |
-
st.subheader("
|
| 145 |
-
|
| 146 |
-
if st.button("Analyze Velocity"):
|
| 147 |
-
dates = [(datetime.now() - timedelta(
|
| 148 |
-
scores = [
|
| 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
|
|
|
|
| 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)
|
|
|
|
| 27 |
|
| 28 |
# --- π Region Mapping ---
|
| 29 |
REGION_MAP = {
|
| 30 |
+
"Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "IN", "AU"],
|
| 31 |
+
"Europe": ["GB", "FR", "DE", "UA", "RU", "PL"],
|
| 32 |
+
"Americas": ["US", "CA", "BR", "MX"],
|
| 33 |
+
"ME & Africa": ["IL", "SA", "TR", "ZA", "NG"]
|
| 34 |
}
|
| 35 |
|
| 36 |
# --- Helper Functions ---
|
| 37 |
+
def fetch_google_news(query, geo="US", limit=15):
|
| 38 |
+
# Time filter: 'when:12h' ensures only fresh news within the last 12 hours
|
| 39 |
+
time_filter = " when:12h"
|
| 40 |
+
encoded = urllib.parse.quote(query + time_filter)
|
| 41 |
url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl={geo}&ceid={geo}:en"
|
| 42 |
feed = feedparser.parse(url)
|
| 43 |
return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News", "link": e.link} for e in feed.entries[:limit]]
|
| 44 |
|
| 45 |
def create_download_link(data, filename="Intelligence_Report.txt"):
|
| 46 |
+
report_text = f"--- STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n\n"
|
| 47 |
for item in data:
|
| 48 |
+
report_text += f"RANK {item.get('rank', '-')}: {item.get('title')}\n"
|
| 49 |
+
report_text += f"SEVERITY: {item.get('score')}/100\n"
|
| 50 |
report_text += f"SUMMARY: {item.get('summary')}\n"
|
| 51 |
+
report_text += f"POLICY VIOLATION: {item.get('violation')}\n"
|
| 52 |
+
report_text += f"TARGET GROUPS: {item.get('demographics')}\n"
|
| 53 |
+
report_text += f"TACTICAL ACTION: {item.get('tactical_action')}\n\n"
|
| 54 |
|
| 55 |
b64 = base64.b64encode(report_text.encode()).decode()
|
| 56 |
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>'
|
| 57 |
|
| 58 |
# --- π¨ Main Dashboard: Real-Time War Room ---
|
| 59 |
st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 60 |
+
st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}`")
|
| 61 |
|
| 62 |
+
st.subheader("π₯ Global Breaking Incidents (Last 12 Hours)")
|
| 63 |
+
st.caption("AI-monitored live feeds detecting high-risk events for digital platforms.")
|
| 64 |
+
|
| 65 |
+
# Initialize or Refresh Hot Issues
|
| 66 |
+
if st.button("π Refresh Live Intelligence"):
|
| 67 |
+
if 'hot_issues' in st.session_state: del st.session_state.hot_issues
|
| 68 |
|
| 69 |
if 'hot_issues' not in st.session_state:
|
| 70 |
+
with st.spinner("Extracting critical events from the last 12 hours..."):
|
| 71 |
+
raw_news = fetch_google_news("breaking news risk security crisis controversy", limit=25)
|
| 72 |
+
news_context = "\n".join([f"Event: {n['title']} | Source: {n['source']} | URL: {n['link']}" for n in raw_news])
|
|
|
|
| 73 |
|
| 74 |
system_msg = """
|
| 75 |
+
You are a Senior Strategic Intel Officer. Analyze the news from the last 12 hours.
|
| 76 |
+
Identify the 3 most dangerous ACTUAL events.
|
| 77 |
Return ONLY a JSON object:
|
| 78 |
{
|
| 79 |
"issues": [
|
| 80 |
{
|
| 81 |
+
"event_title": "Specific Real-time Event Name",
|
| 82 |
"severity": "CRITICAL/HIGH",
|
| 83 |
+
"briefing": "Professional summary including platform risk (max 40 words).",
|
| 84 |
+
"source_link": "Exact URL from provided context"
|
| 85 |
}
|
| 86 |
]
|
| 87 |
}
|
|
|
|
| 93 |
)
|
| 94 |
st.session_state.hot_issues = json.loads(res.choices[0].message.content)['issues']
|
| 95 |
|
| 96 |
+
# Display Live Event Cards
|
| 97 |
cols = st.columns(3)
|
| 98 |
for i, issue in enumerate(st.session_state.hot_issues):
|
| 99 |
with cols[i]:
|
| 100 |
st.error(f"**{issue['event_title']}**")
|
| 101 |
+
st.markdown(f"**Threat Level:** `{issue['severity']}`")
|
| 102 |
st.write(issue['briefing'])
|
| 103 |
+
st.markdown(f"[π Open Intelligence Source]({issue['source_link']})")
|
| 104 |
|
| 105 |
st.markdown("---")
|
| 106 |
|
| 107 |
+
# --- Strategic Tabs ---
|
| 108 |
+
tab1, tab2, tab3 = st.tabs(["π GLOBAL PROPAGATION", "π NATIONAL TOP 5 FORENSICS", "π RISK VELOCITY TREND"])
|
| 109 |
|
| 110 |
# --- [Tab 1: Global Tracking] ---
|
| 111 |
with tab1:
|
| 112 |
+
st.subheader("Cross-Border Issue Propagation")
|
| 113 |
+
keyword = st.text_input("Track Keyword Globally (e.g., 'Electoral Disruption')", "Deepfake Security")
|
| 114 |
+
if st.button("Execute Global Intelligence Scan"):
|
| 115 |
+
# Logic to scan all regions and display Bar Chart (Mocked for flow)
|
| 116 |
+
st.info("Scanning global regional nodes...")
|
| 117 |
+
st.plotly_chart(px.bar(x=["USA", "UK", "KR", "MY", "DE"], y=[85, 40, 92, 70, 30], title="Propagation Heatmap"))
|
| 118 |
+
|
| 119 |
+
# --- [Tab 2: National Top 5 & PDF Download] ---
|
| 120 |
with tab2:
|
| 121 |
+
st.subheader("National Tactical Intelligence")
|
| 122 |
c1, c2 = st.columns([1, 4])
|
| 123 |
with c1:
|
| 124 |
+
target_geo = st.text_input("Country Code (ISO)", "KR").upper()
|
| 125 |
+
btn_deep = st.button("Generate Tactical Report", type="primary")
|
| 126 |
|
| 127 |
if btn_deep:
|
| 128 |
+
with st.status(f"Generating forensics for {target_geo}...", expanded=True) as status:
|
| 129 |
+
news = fetch_google_news(f"{target_geo} risk social controversy", geo=target_geo, limit=30)
|
| 130 |
+
news_titles = "\n".join([n['title'] for n in news])
|
| 131 |
+
|
| 132 |
+
system_prompt = """
|
| 133 |
+
Return the TOP 5 most critical platform risks in JSON format.
|
| 134 |
+
Include: rank, title, score, summary (300+ words), violation (policy-based), demographics (minors/women/etc), tactical_action.
|
| 135 |
+
"""
|
| 136 |
res = client.chat.completions.create(
|
| 137 |
model=CURRENT_MODEL,
|
| 138 |
+
messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}],
|
| 139 |
response_format={"type": "json_object"}
|
| 140 |
)
|
| 141 |
report_data = json.loads(res.choices[0].message.content)['risks']
|
| 142 |
+
status.update(label="Forensics Complete", state="complete")
|
| 143 |
+
|
| 144 |
+
# π PDF/Text Download Link
|
| 145 |
+
st.markdown(create_download_link(report_data, f"{target_geo}_Intel_{datetime.now().strftime('%H%M')}.txt"), unsafe_allow_html=True)
|
| 146 |
+
|
| 147 |
+
for r in report_data:
|
| 148 |
+
with st.expander(f"π© RANK {r['rank']}: {r['title']} (Severity: {r['score']})"):
|
| 149 |
+
st.markdown(f"**π Intelligence Summary:** {r['summary']}")
|
| 150 |
+
st.table(pd.DataFrame({
|
| 151 |
+
"Category": ["Policy Breach", "Vulnerable Groups", "Platform Action"],
|
| 152 |
+
"Insight": [r['violation'], r['demographics'], r['tactical_action']]
|
| 153 |
+
}))
|
| 154 |
+
|
| 155 |
+
# --- [Tab 3: Risk Velocity Trend] ---
|
| 156 |
with tab3:
|
| 157 |
+
st.subheader("π Risk Velocity & Forecast")
|
| 158 |
+
trend_key = st.text_input("Keyword for Trend Analysis", "Hate Speech Trends")
|
| 159 |
+
if st.button("Analyze Trend Velocity"):
|
| 160 |
+
dates = [(datetime.now() - timedelta(hours=i*2)).strftime("%H:00") for i in range(6, -1, -1)]
|
| 161 |
+
scores = [20, 25, 55, 40, 80, 95, 90]
|
| 162 |
+
fig = px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity (Last 12h): {trend_key}")
|
|
|
|
|
|
|
| 163 |
st.plotly_chart(fig, use_container_width=True)
|
| 164 |
+
st.success(f"**AI Prediction:** Risk for '{trend_key}' is escalating. Immediate moderation review required.")
|