benjamin5607 commited on
Commit
42eb666
Β·
verified Β·
1 Parent(s): 3cc37d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -65
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 in Secrets.")
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", "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_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
  }
@@ -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 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.")
 
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.")