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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -91
app.py CHANGED
@@ -10,7 +10,7 @@ from datetime import datetime, timedelta
10
  import base64
11
 
12
  # --- Page Config ---
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,69 +19,55 @@ if not api_key:
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)
26
  CURRENT_MODEL = "llama-3.3-70b-versatile"
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,72 +79,19 @@ if 'hot_issues' not in st.session_state:
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.")
 
10
  import base64
11
 
12
  # --- Page Config ---
13
+ st.set_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.")
23
  st.stop()
24
 
25
  client = Groq(api_key=api_key)
26
  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
45
 
46
  if 'hot_issues' not in st.session_state:
47
+ with st.spinner("Analyzing incidents and generating 3-line summaries..."):
48
  raw_news = fetch_google_news("breaking news risk security crisis controversy", limit=25)
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 the news from the last 12 hours.
53
  Identify the 3 most dangerous ACTUAL events.
54
+ For each event, provide a 'three_line_summary' that covers:
55
+ 1. What happened.
56
+ 2. Why it is a risk to digital platforms/policy.
57
+ 3. Recommended immediate focus.
58
+
59
  Return ONLY a JSON object:
60
  {
61
  "issues": [
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
  ]
73
  }
 
79
  )
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.error(f"**{issue['event_title']}**")
87
  st.markdown(f"**Threat Level:** `{issue['severity']}`")
88
+
89
+ # 3쀄 μš”μ•½ 좜λ ₯ λΆ€λΆ„
90
+ summary_html = "".join([f"<li>{line}</li>" for line in issue['three_line_summary']])
91
+ st.markdown(f"<ul style='font-size: 0.9rem; padding-left: 20px;'>{summary_html}</ul>", unsafe_allow_html=True)
92
+
93
+ st.markdown(f"[πŸ”— View Source]({issue['source_link']})")
94
 
95
  st.markdown("---")
96
 
97
+ # --- (Tab 1, 2, 3 λ‘œμ§μ€ 이전과 λ™μΌν•˜κ²Œ μœ μ§€) ---