benjamin5607 commited on
Commit
e5ff858
Β·
verified Β·
1 Parent(s): deb2137

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -65
app.py CHANGED
@@ -9,10 +9,10 @@ import plotly.express as px
9
  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")
17
  if not api_key:
18
  try: api_key = st.secrets["GROQ_API_KEY"]
@@ -25,7 +25,15 @@ if not api_key:
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)
@@ -36,100 +44,126 @@ def fetch_google_news(query, geo="US", limit=15):
36
  def create_download_link(data, filename="Intelligence_Report.txt"):
37
  report_text = f"--- STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n\n"
38
  for item in data:
39
- report_text += f"RANK {item.get('rank', '-')}: {item.get('title')}\n"
40
- report_text += f"SEVERITY: {item.get('score')}/100\n"
41
- report_text += f"SUMMARY: {item.get('summary')}\n"
42
- report_text += f"POLICY VIOLATION: {item.get('violation')}\n"
43
- report_text += f"TARGET GROUPS: {item.get('demographics')}\n"
44
- report_text += f"TACTICAL ACTION: {item.get('tactical_action')}\n\n"
45
-
46
  b64 = base64.b64encode(report_text.encode()).decode()
47
  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>'
48
 
49
- # --- 🚨 Main Dashboard: Real-Time War Room ---
50
  st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
51
  st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}`")
52
 
53
  st.subheader("πŸ”₯ Global Breaking Incidents (Last 12 Hours)")
 
54
 
55
  if st.button("πŸ”„ Refresh Live Intelligence"):
56
  if 'hot_issues' in st.session_state: del st.session_state.hot_issues
57
 
58
  if 'hot_issues' not in st.session_state:
59
- with st.spinner("Analyzing incidents..."):
60
- raw_news = fetch_google_news("breaking news risk security crisis controversy", limit=25)
61
  news_context = "\n".join([f"Event: {n['title']} | URL: {n['link']}" for n in raw_news])
62
 
63
  system_msg = """
64
- You are a Senior Strategic Intel Officer. Analyze news from the last 12 hours.
65
- Return ONLY a JSON object with this key: "issues".
66
- Format: {"issues": [{"event_title": "...", "severity": "...", "three_line_summary": ["...", "...", "..."], "source_link": "..."}]}
67
  """
68
  try:
69
- res = client.chat.completions.create(
70
- model=CURRENT_MODEL,
71
- messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}],
72
- response_format={"type": "json_object"}
73
- )
74
  st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])
75
- except Exception as e:
76
- st.error(f"Error in War Room Analysis: {e}")
77
- st.session_state.hot_issues = []
78
 
79
- # Cards display
80
  cols = st.columns(3)
81
  for i, issue in enumerate(st.session_state.hot_issues):
82
  with cols[i % 3]:
83
  with st.container(border=True):
84
- st.error(f"**{issue.get('event_title', 'Unknown Event')}**")
85
- st.markdown(f"**Level:** `{issue.get('severity', 'HIGH')}`")
86
- summary = issue.get('three_line_summary', ["No summary available"])
87
- summary_html = "".join([f"<li>{line}</li>" for line in summary])
88
  st.markdown(f"<ul style='font-size: 0.85rem; padding-left: 15px;'>{summary_html}</ul>", unsafe_allow_html=True)
89
- st.markdown(f"[πŸ”— Source]({issue.get('source_link', '#')})")
90
 
91
  st.markdown("---")
92
 
93
- # --- Strategic Tabs ---
94
- tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL PROPAGATION", "πŸ” NATIONAL TOP 5 FORENSICS", "πŸ“ˆ RISK VELOCITY TREND"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
 
96
  with tab2:
97
- st.subheader("National Tactical Intelligence")
98
  c1, c2 = st.columns([1, 4])
99
  with c1:
100
- target_geo = st.text_input("Country Code (ISO)", "KR").upper()
101
- btn_deep = st.button("Generate Tactical Report", type="primary")
102
 
103
  if btn_deep:
104
  with st.status(f"Generating forensics for {target_geo}...", expanded=True):
105
- news = fetch_google_news(f"{target_geo} risk social controversy", geo=target_geo, limit=30)
106
  news_titles = "\n".join([n['title'] for n in news])
107
-
108
- # --- μˆ˜μ •λœ ν”„λ‘¬ν”„νŠΈμ™€ μ—λŸ¬ λ°©μ§€ 둜직 ---
109
- system_prompt = """
110
- Identify the TOP 5 most critical platform risks in the country based on the news.
111
- Return ONLY a valid JSON object with the root key "risks".
112
- Format: {"risks": [{"rank": 1, "title": "...", "score": 90, "summary": "...", "violation": "...", "demographics": "...", "tactical_action": "..."}]}
113
- """
114
- try:
115
- res = client.chat.completions.create(
116
- model=CURRENT_MODEL,
117
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}],
118
- response_format={"type": "json_object"}
119
- )
120
- raw_content = res.choices[0].message.content
121
- report_data = json.loads(raw_content).get('risks', [])
122
-
123
- if not report_data:
124
- st.warning("AI did not return any specific risks for this search. Try a different country or broader keyword.")
125
- else:
126
- st.markdown(create_download_link(report_data, f"{target_geo}_Intel.txt"), unsafe_allow_html=True)
127
- for r in report_data:
128
- with st.expander(f"🚩 RANK {r.get('rank', '-')}: {r.get('title', 'No Title')} (Score: {r.get('score', 0)})"):
129
- st.markdown(f"**πŸ“ Intelligence Summary:** {r.get('summary', 'No summary provided.')}")
130
- st.table(pd.DataFrame({
131
- "Category": ["Policy Breach", "Vulnerable Groups", "Platform Action"],
132
- "Insight": [r.get('violation', 'N/A'), r.get('demographics', 'N/A'), r.get('tactical_action', 'N/A')]
133
- }))
134
- except Exception as e:
135
- st.error(f"Analysis Failed: {e}")
 
9
  from datetime import datetime, timedelta
10
  import base64
11
 
12
+ # --- 1. Page Config ---
13
  st.set_page_config(page_title="Omni-Watch War Room", page_icon="🚨", layout="wide")
14
 
15
+ # --- 2. API Key Load ---
16
  api_key = os.environ.get("GROQ_API_KEY")
17
  if not api_key:
18
  try: api_key = st.secrets["GROQ_API_KEY"]
 
25
  client = Groq(api_key=api_key)
26
  CURRENT_MODEL = "llama-3.3-70b-versatile"
27
 
28
+ # --- 3. Region Mapping ---
29
+ REGION_MAP = {
30
+ "Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "IN", "AU", "SG"],
31
+ "Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL"],
32
+ "Americas": ["US", "CA", "BR", "MX", "AR", "CO"],
33
+ "ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
34
+ }
35
+
36
+ # --- 4. Helper Functions ---
37
  def fetch_google_news(query, geo="US", limit=15):
38
  time_filter = " when:12h"
39
  encoded = urllib.parse.quote(query + time_filter)
 
44
  def create_download_link(data, filename="Intelligence_Report.txt"):
45
  report_text = f"--- STRATEGIC INTELLIGENCE REPORT ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n\n"
46
  for item in data:
47
+ report_text += f"RANK {item.get('rank', '-')}: {item.get('title', 'N/A')}\n"
48
+ report_text += f"SEVERITY: {item.get('score', 0)}/100\n"
49
+ report_text += f"SUMMARY: {item.get('summary', 'N/A')}\n"
50
+ report_text += f"POLICY VIOLATION: {item.get('violation', 'N/A')}\n"
51
+ report_text += f"TARGET GROUPS: {item.get('demographics', 'N/A')}\n"
52
+ report_text += f"TACTICAL ACTION: {item.get('tactical_action', 'N/A')}\n\n"
 
53
  b64 = base64.b64encode(report_text.encode()).decode()
54
  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>'
55
 
56
+ # --- 5. 🚨 Main Dashboard: Real-Time War Room ---
57
  st.title("🚨 OMNI-WATCH: GLOBAL WAR ROOM")
58
  st.markdown(f"**Live Intelligence Analysis (UTC):** `{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}`")
59
 
60
  st.subheader("πŸ”₯ Global Breaking Incidents (Last 12 Hours)")
61
+ st.caption("AI-monitored live feeds with 3-line strategic summaries.")
62
 
63
  if st.button("πŸ”„ Refresh Live Intelligence"):
64
  if 'hot_issues' in st.session_state: del st.session_state.hot_issues
65
 
66
  if 'hot_issues' not in st.session_state:
67
+ with st.spinner("Analyzing incidents and generating 3-line summaries..."):
68
+ raw_news = fetch_google_news("breaking news risk security crisis controversy", limit=20)
69
  news_context = "\n".join([f"Event: {n['title']} | URL: {n['link']}" for n in raw_news])
70
 
71
  system_msg = """
72
+ Analyze news from the last 12 hours. Identify 3 most dangerous ACTUAL events.
73
+ Return ONLY JSON: {"issues": [{"event_title": "..", "severity": "..", "three_line_summary": ["line1", "line2", "line3"], "source_link": ".."}]}
 
74
  """
75
  try:
76
+ res = client.chat.completions.create(model=CURRENT_MODEL, messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": news_context}], response_format={"type": "json_object"})
 
 
 
 
77
  st.session_state.hot_issues = json.loads(res.choices[0].message.content).get('issues', [])
78
+ except: st.session_state.hot_issues = []
 
 
79
 
80
+ # Display Hot Issues
81
  cols = st.columns(3)
82
  for i, issue in enumerate(st.session_state.hot_issues):
83
  with cols[i % 3]:
84
  with st.container(border=True):
85
+ st.error(f"**{issue.get('event_title')}**")
86
+ st.markdown(f"**Threat Level:** `{issue.get('severity')}`")
87
+ summary_html = "".join([f"<li>{line}</li>" for line in issue.get('three_line_summary', [])])
 
88
  st.markdown(f"<ul style='font-size: 0.85rem; padding-left: 15px;'>{summary_html}</ul>", unsafe_allow_html=True)
89
+ st.markdown(f"[πŸ”— View Source]({issue.get('source_link')})")
90
 
91
  st.markdown("---")
92
 
93
+ # --- 6. Strategic Tabs ---
94
+ tab1, tab2, tab3 = st.tabs(["🌐 GLOBAL TRACKING & MARKET", "πŸ” NATIONAL TOP 5 FORENSICS", "πŸ“ˆ RISK VELOCITY TREND"])
95
+
96
+ # --- [Tab 1: Global Issue & Market Tracker] ---
97
+ with tab1:
98
+ st.subheader("Global Risk Propagation & Market Insight Scan")
99
+ col_k1, col_k2 = st.columns([3, 1])
100
+ with col_k1:
101
+ keyword = st.text_input("Enter Issue Keyword to Track", "Digital Propaganda")
102
+ selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
103
+ with col_k2:
104
+ st.write("")
105
+ run_global = st.button("πŸ—ΊοΈ Deep Global Scan", type="primary", use_container_width=True)
106
+
107
+ if run_global:
108
+ target_countries = []
109
+ for reg in selected_regions: target_countries.extend(REGION_MAP[reg])
110
+ results = []
111
+ all_news = []
112
+ progress = st.progress(0)
113
+ for i, geo in enumerate(target_countries):
114
+ news = fetch_google_news(keyword, geo=geo, limit=3)
115
+ if news:
116
+ all_news.extend(news)
117
+ results.append({"Country": geo, "Risk": 70}) # Mocking score for speed, AI can score here
118
+ progress.progress((i + 1) / len(target_countries))
119
+
120
+ st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))
121
+
122
+
123
+
124
+ with st.spinner("Analyzing Global Market Insights..."):
125
+ res = client.chat.completions.create(
126
+ model=CURRENT_MODEL,
127
+ messages=[{"role": "system", "content": "Analyze these news titles. Return JSON with 'market_insights' for TikTok, YT, Meta, X, and 'global_summary'."}],
128
+ response_format={"type": "json_object"}
129
+ )
130
+ g_data = json.loads(res.choices[0].message.content)
131
+ st.info(g_data.get('global_summary'))
132
+ st.table(pd.DataFrame(g_data.get('market_insights', {}).items(), columns=["Platform", "Insight"]))
133
 
134
+ # --- [Tab 2: National Top 5 & PDF Download] ---
135
  with tab2:
136
+ st.subheader("National Tactical Intelligence & Evidence Feed")
137
  c1, c2 = st.columns([1, 4])
138
  with c1:
139
+ target_geo = st.text_input("Country Code (ISO)", "US").upper()
140
+ btn_deep = st.button("Generate National Report", type="primary")
141
 
142
  if btn_deep:
143
  with st.status(f"Generating forensics for {target_geo}...", expanded=True):
144
+ news = fetch_google_news(f"{target_geo} social controversy risk", geo=target_geo, limit=25)
145
  news_titles = "\n".join([n['title'] for n in news])
146
+ res = client.chat.completions.create(
147
+ model=CURRENT_MODEL,
148
+ messages=[{"role": "system", "content": "Identify TOP 5 risks. Return JSON with 'risks' list containing rank, title, score, summary(300+ words), violation, demographics, tactical_action."}],
149
+ response_format={"type": "json_object"}
150
+ )
151
+ report_data = json.loads(res.choices[0].message.content).get('risks', [])
152
+
153
+ if report_data:
154
+ st.markdown(create_download_link(report_data, f"{target_geo}_Intel.txt"), unsafe_allow_html=True)
155
+ for r in report_data:
156
+ with st.expander(f"🚩 RANK {r.get('rank')}: {r.get('title')} (Score: {r.get('score')})"):
157
+ st.write(r.get('summary'))
158
+ st.table(pd.DataFrame({"Category": ["Policy", "Target", "Action"], "Insight": [r.get('violation'), r.get('demographics'), r.get('tactical_action')]}))
159
+ st.divider()
160
+ st.subheader("πŸ“° Evidence Feed")
161
+ st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']])
162
+
163
+ # --- [Tab 3: Risk Velocity Trend] ---
164
+ with tab3:
165
+ st.subheader("πŸ“ˆ Risk Velocity Trend")
166
+ trend_key = st.text_input("Trend Keyword", "AI Misinformation")
167
+ if st.button("Analyze Trend"):
168
+ fig = px.line(x=["10:00", "12:00", "14:00", "16:00", "18:00", "20:00"], y=[30, 45, 80, 70, 95, 90], title=f"Risk Score Velocity: {trend_key}")
169
+ st.plotly_chart(fig, use_container_width=True)