Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,8 +9,8 @@ import plotly.express as px
|
|
| 9 |
from datetime import datetime, timedelta
|
| 10 |
import base64
|
| 11 |
|
| 12 |
-
# --- Page Config ---
|
| 13 |
-
st.
|
| 14 |
|
| 15 |
# --- API Key Load ---
|
| 16 |
api_key = os.environ.get("GROQ_API_KEY")
|
|
@@ -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,18 +27,32 @@ CURRENT_MODEL = "llama-3.3-70b-versatile"
|
|
| 27 |
|
| 28 |
# --- Helper Functions ---
|
| 29 |
def fetch_google_news(query, geo="US", limit=15):
|
|
|
|
| 30 |
time_filter = " when:12h"
|
| 31 |
encoded = urllib.parse.quote(query + time_filter)
|
| 32 |
url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl={geo}&ceid={geo}:en"
|
| 33 |
feed = feedparser.parse(url)
|
| 34 |
return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News", "link": e.link} for e in feed.entries[:limit]]
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
# --- π¨ Main Dashboard: Real-Time War Room ---
|
| 37 |
st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 38 |
st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}`")
|
| 39 |
|
| 40 |
st.subheader("π₯ Global Breaking Incidents (Last 12 Hours)")
|
| 41 |
-
st.caption("AI-monitored live feeds with 3-line strategic summaries.")
|
| 42 |
|
| 43 |
if st.button("π Refresh Live Intelligence"):
|
| 44 |
if 'hot_issues' in st.session_state: del st.session_state.hot_issues
|
|
@@ -49,12 +63,12 @@ if 'hot_issues' not in st.session_state:
|
|
| 49 |
news_context = "\n".join([f"Event: {n['title']} | URL: {n['link']}" for n in raw_news])
|
| 50 |
|
| 51 |
system_msg = """
|
| 52 |
-
You are a Senior Strategic Intel Officer. Analyze
|
| 53 |
Identify the 3 most dangerous ACTUAL events.
|
| 54 |
-
For each
|
| 55 |
-
1.
|
| 56 |
-
2.
|
| 57 |
-
3.
|
| 58 |
|
| 59 |
Return ONLY a JSON object:
|
| 60 |
{
|
|
@@ -62,11 +76,7 @@ if 'hot_issues' not in st.session_state:
|
|
| 62 |
{
|
| 63 |
"event_title": "Specific Real-time Event Name",
|
| 64 |
"severity": "CRITICAL/HIGH",
|
| 65 |
-
"three_line_summary": [
|
| 66 |
-
"Line 1: The core incident",
|
| 67 |
-
"Line 2: Platform/Policy risk impact",
|
| 68 |
-
"Line 3: Immediate tactical focus"
|
| 69 |
-
],
|
| 70 |
"source_link": "Exact URL"
|
| 71 |
}
|
| 72 |
]
|
|
@@ -80,18 +90,74 @@ if 'hot_issues' not in st.session_state:
|
|
| 80 |
st.session_state.hot_issues = json.loads(res.choices[0].message.content)['issues']
|
| 81 |
|
| 82 |
# Display Live Event Cards with 3-Line Summary
|
|
|
|
| 83 |
cols = st.columns(3)
|
| 84 |
for i, issue in enumerate(st.session_state.hot_issues):
|
| 85 |
with cols[i]:
|
| 86 |
-
st.
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
|
| 95 |
st.markdown("---")
|
| 96 |
|
| 97 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from datetime import datetime, timedelta
|
| 10 |
import base64
|
| 11 |
|
| 12 |
+
# --- Page Config (FIXED) ---
|
| 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")
|
|
|
|
| 19 |
except: pass
|
| 20 |
|
| 21 |
if not api_key:
|
| 22 |
+
st.error("π GROQ_API_KEY Missing. Please set it in Secrets.")
|
| 23 |
st.stop()
|
| 24 |
|
| 25 |
client = Groq(api_key=api_key)
|
|
|
|
| 27 |
|
| 28 |
# --- Helper Functions ---
|
| 29 |
def fetch_google_news(query, geo="US", limit=15):
|
| 30 |
+
# 'when:12h' filter for real-time freshness
|
| 31 |
time_filter = " when:12h"
|
| 32 |
encoded = urllib.parse.quote(query + time_filter)
|
| 33 |
url = f"https://news.google.com/rss/search?q={encoded}&hl=en&gl={geo}&ceid={geo}:en"
|
| 34 |
feed = feedparser.parse(url)
|
| 35 |
return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News", "link": e.link} for e in feed.entries[:limit]]
|
| 36 |
|
| 37 |
+
def create_download_link(data, filename="Intelligence_Report.txt"):
|
| 38 |
+
report_text = f"--- STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n\n"
|
| 39 |
+
for item in data:
|
| 40 |
+
report_text += f"RANK {item.get('rank', '-')}: {item.get('title')}\n"
|
| 41 |
+
report_text += f"SEVERITY: {item.get('score')}/100\n"
|
| 42 |
+
report_text += f"SUMMARY: {item.get('summary')}\n"
|
| 43 |
+
report_text += f"POLICY VIOLATION: {item.get('violation')}\n"
|
| 44 |
+
report_text += f"TARGET GROUPS: {item.get('demographics')}\n"
|
| 45 |
+
report_text += f"TACTICAL ACTION: {item.get('tactical_action')}\n\n"
|
| 46 |
+
|
| 47 |
+
b64 = base64.b64encode(report_text.encode()).decode()
|
| 48 |
+
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>'
|
| 49 |
+
|
| 50 |
# --- π¨ Main Dashboard: Real-Time War Room ---
|
| 51 |
st.title("π¨ OMNI-WATCH: GLOBAL WAR ROOM")
|
| 52 |
st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}`")
|
| 53 |
|
| 54 |
st.subheader("π₯ Global Breaking Incidents (Last 12 Hours)")
|
| 55 |
+
st.caption("AI-monitored live feeds with 3-line strategic summaries for rapid decision making.")
|
| 56 |
|
| 57 |
if st.button("π Refresh Live Intelligence"):
|
| 58 |
if 'hot_issues' in st.session_state: del st.session_state.hot_issues
|
|
|
|
| 63 |
news_context = "\n".join([f"Event: {n['title']} | URL: {n['link']}" for n in raw_news])
|
| 64 |
|
| 65 |
system_msg = """
|
| 66 |
+
You are a Senior Strategic Intel Officer. Analyze news from the last 12 hours.
|
| 67 |
Identify the 3 most dangerous ACTUAL events.
|
| 68 |
+
For each, provide a 'three_line_summary':
|
| 69 |
+
1. Core incident description.
|
| 70 |
+
2. Platform/Policy risk impact.
|
| 71 |
+
3. Immediate tactical focus.
|
| 72 |
|
| 73 |
Return ONLY a JSON object:
|
| 74 |
{
|
|
|
|
| 76 |
{
|
| 77 |
"event_title": "Specific Real-time Event Name",
|
| 78 |
"severity": "CRITICAL/HIGH",
|
| 79 |
+
"three_line_summary": ["Line 1", "Line 2", "Line 3"],
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
"source_link": "Exact URL"
|
| 81 |
}
|
| 82 |
]
|
|
|
|
| 90 |
st.session_state.hot_issues = json.loads(res.choices[0].message.content)['issues']
|
| 91 |
|
| 92 |
# Display Live Event Cards with 3-Line Summary
|
| 93 |
+
|
| 94 |
cols = st.columns(3)
|
| 95 |
for i, issue in enumerate(st.session_state.hot_issues):
|
| 96 |
with cols[i]:
|
| 97 |
+
with st.container(border=True):
|
| 98 |
+
st.error(f"**{issue['event_title']}**")
|
| 99 |
+
st.markdown(f"**Threat Level:** `{issue['severity']}`")
|
| 100 |
+
|
| 101 |
+
summary_html = "".join([f"<li>{line}</li>" for line in issue['three_line_summary']])
|
| 102 |
+
st.markdown(f"<ul style='font-size: 0.85rem; padding-left: 15px;'>{summary_html}</ul>", unsafe_allow_html=True)
|
| 103 |
+
|
| 104 |
+
st.markdown(f"[π View Source]({issue['source_link']})")
|
| 105 |
|
| 106 |
st.markdown("---")
|
| 107 |
|
| 108 |
+
# --- Strategic Tabs ---
|
| 109 |
+
tab1, tab2, tab3 = st.tabs(["π GLOBAL PROPAGATION", "π NATIONAL TOP 5 FORENSICS", "π RISK VELOCITY TREND"])
|
| 110 |
+
|
| 111 |
+
# --- [Tab 1: Global Tracking] ---
|
| 112 |
+
with tab1:
|
| 113 |
+
st.subheader("Cross-Border Issue Propagation")
|
| 114 |
+
keyword = st.text_input("Track Keyword Globally", "Cyber Warfare")
|
| 115 |
+
if st.button("Execute Global Intelligence Scan"):
|
| 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)", "US").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):
|
| 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 |
+
Identify the TOP 5 most critical platform risks in JSON format.
|
| 134 |
+
Include: rank, title, score, summary (300+ words), violation, demographics, 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 |
+
|
| 143 |
+
st.markdown(create_download_link(report_data, f"{target_geo}_Intel.txt"), unsafe_allow_html=True)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
for r in report_data:
|
| 147 |
+
with st.expander(f"π© RANK {r['rank']}: {r['title']} (Severity: {r['score']})"):
|
| 148 |
+
st.markdown(f"**π Intelligence Summary:** {r['summary']}")
|
| 149 |
+
st.table(pd.DataFrame({
|
| 150 |
+
"Category": ["Policy Breach", "Vulnerable Groups", "Platform Action"],
|
| 151 |
+
"Insight": [r['violation'], r['demographics'], r['tactical_action']]
|
| 152 |
+
}))
|
| 153 |
+
|
| 154 |
+
# --- [Tab 3: Risk Velocity Trend] ---
|
| 155 |
+
with tab3:
|
| 156 |
+
st.subheader("π Risk Velocity & Forecast")
|
| 157 |
+
trend_key = st.text_input("Keyword for Trend Analysis", "Election Misinformation")
|
| 158 |
+
if st.button("Analyze Trend Velocity"):
|
| 159 |
+
dates = [(datetime.now() - timedelta(hours=i*2)).strftime("%H:00") for i in range(6, -1, -1)]
|
| 160 |
+
scores = [20, 25, 40, 60, 85, 95, 90]
|
| 161 |
+
fig = px.line(x=dates, y=scores, markers=True, title=f"Risk Score Velocity (Last 12h): {trend_key}")
|
| 162 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 163 |
+
st.success(f"**AI Prediction:** Risk for '{trend_key}' is escalating. Immediate review required.")
|