benjamin5607 commited on
Commit
adfef13
ยท
verified ยท
1 Parent(s): 2edfdfa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -134
app.py CHANGED
@@ -6,169 +6,130 @@ import pandas as pd
6
  import json
7
  import os
8
  import plotly.express as px
9
- import time
 
10
 
11
  # --- Page Config ---
12
- st.set_page_config(page_title="Omni-Watch Intelligence Pro", page_icon="๐Ÿ“ก", layout="wide")
13
 
14
  # --- API Key Load ---
15
- # Hugging Face Secrets์— 'GROQ_API_KEY'๋ฅผ ๋ฐ˜๋“œ์‹œ ์ž…๋ ฅํ•˜์„ธ์š”.
16
  api_key = os.environ.get("GROQ_API_KEY")
17
  if not api_key:
18
  try: api_key = st.secrets["GROQ_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
- # --- ๐ŸŒ UN Geoscheme Data ---
29
  REGION_MAP = {
30
- "Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "TH", "IN", "ID", "PH", "AU", "SG"],
31
- "Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL", "SE", "NO"],
32
- "Americas": ["US", "CA", "BR", "MX", "AR", "CO", "CL", "VE"],
33
- "Middle East & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR", "QA", "KE"]
34
  }
35
 
36
- # --- Helper: Google News RSS Fetcher ---
37
- def fetch_google_news(query, geo="US", lang="en", limit=10):
38
  encoded = urllib.parse.quote(query)
39
- url = f"https://news.google.com/rss/search?q={encoded}&hl={lang}&gl={geo}&ceid={geo}:{lang}"
40
  feed = feedparser.parse(url)
41
- articles = []
42
- for entry in feed.entries[:limit]:
43
- articles.append({
44
- "title": entry.title,
45
- "link": entry.link,
46
- "source": entry.source.title if 'source' in entry else "Google News",
47
- "date": entry.published if 'published' in entry else "Recent"
48
- })
49
- return articles
50
 
51
- # --- UI Setup ---
52
- st.title("๐Ÿ“ก Omni-Watch: Universal Risk & Market Intelligence")
53
- st.caption("Monitoring Global Propagation & National Risk Forensics with Llama 3.3 Intelligence")
54
- st.markdown("---")
 
 
 
 
 
55
 
56
- tab_global, tab_national = st.tabs(["๐ŸŒ Global Issue Tracking", "๐Ÿ” National Top 5 Risk Deep-Dive"])
 
 
57
 
58
- # --- [Tab 1: Global Issue Tracking] ---
59
- with tab_global:
60
- st.subheader("Global Risk Propagation & Strategic Policy Report")
61
- col_k1, col_k2 = st.columns([3, 1])
62
- with col_k1:
63
- search_keyword = st.text_input("Enter Issue Keyword to Analyze Globally", "Cyber Attacks")
64
- selected_regions = st.multiselect("Select Target Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
65
- with col_k2:
66
- st.write("")
67
- run_global = st.button("๐Ÿ—บ๏ธ Deep Global Scan", type="primary", use_container_width=True)
 
 
 
68
 
69
- if run_global:
70
- target_countries = []
71
- for reg in selected_regions: target_countries.extend(REGION_MAP[reg])
72
-
73
- results = []
74
- all_captured_news = []
75
- progress = st.progress(0)
76
- status_msg = st.empty()
77
-
78
- for i, geo_code in enumerate(target_countries):
79
- status_msg.text(f"Scanning {geo_code} for '{search_keyword}'...")
80
- news = fetch_google_news(search_keyword, geo=geo_code, limit=3)
81
- if news:
82
- titles = "\n".join([n['title'] for n in news])
83
- all_captured_news.extend(news)
84
- try:
85
- res = client.chat.completions.create(
86
- model=CURRENT_MODEL,
87
- messages=[{"role": "user", "content": f"Score 0-100 risk for '{search_keyword}' in {geo_code}: {titles}. ONLY INT."}],
88
- max_tokens=10
89
- )
90
- score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
91
- except: score = 50
92
- results.append({"Country": geo_code, "Risk": score})
93
- progress.progress((i + 1) / len(target_countries))
94
-
95
- status_msg.empty()
96
- df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
97
- st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds", title=f"Global Risk Heatmap: {search_keyword}"), use_container_width=True)
98
 
99
- st.divider()
100
- st.subheader(f"๐Ÿง  Llama 3.3 Global Intelligence Report")
101
- with st.spinner("Synthesizing Strategic Policy Risks..."):
102
- news_feed = "\n".join([n['title'] for n in all_captured_news[:20]])
103
- global_prompt = f"""
104
- Analyze the global propagation of '{search_keyword}'.
105
- Structure your report with:
106
- 1. 'global_summary': Long professional report (300+ words).
107
- 2. 'market_insights': Table-ready data for TikTok, YouTube, Meta, X.
108
- 3. 'policy_risks': Violations of Community Guidelines and WHY.
109
- 4. 'demographics': Risks for Minors, Women, and Ethnic groups.
110
- 5. 'action_plan': Tactical moderation steps.
111
- """
112
- res = client.chat.completions.create(
113
- model=CURRENT_MODEL,
114
- messages=[{"role": "system", "content": global_prompt}, {"role": "user", "content": news_feed}]
115
- )
116
- st.markdown(f"<div style='background-color: #e3f2fd; padding: 25px; border-radius: 10px; border-left: 5px solid #1976d2;'>{res.choices[0].message.content}</div>", unsafe_allow_html=True)
117
-
118
- st.subheader("๐Ÿ“ฐ Reference News Feed")
119
- st.dataframe(pd.DataFrame(all_captured_news)[['source', 'title', 'link']], use_container_width=True)
120
 
121
- # --- [Tab 2: National Deep-Dive (Top 5 Risks)] ---
122
- with tab_national:
123
- st.subheader("Specific Country Top 5 Risk Intelligence")
124
- col_d1, col_d2 = st.columns([1, 4])
125
- with col_d1:
126
- target_geo = st.text_input("Enter Country Code (ISO)", "KR").upper()
127
- run_deep = st.button("๐Ÿš€ Analyze Market", use_container_width=True, type="primary")
 
 
 
 
 
 
 
 
 
128
 
129
- if run_deep:
130
- with st.status(f"Analytic Process for {target_geo}...", expanded=True) as status:
131
- news = fetch_google_news(f"{target_geo} social controversy risk", geo=target_geo, limit=30)
132
- news_titles = "\n".join([f"- {n['title']}" for n in news])
133
-
134
- system_prompt = f"""
135
- Identify the TOP 5 most critical social/platform risks in {target_geo}.
136
- Return ONLY a JSON object:
137
- {{
138
- "risks": [
139
- {{
140
- "rank": 1,
141
- "title": "Short title",
142
- "score": 0-100,
143
- "summary": "300+ word detailed report",
144
- "violation": "Guideline breached & WHY",
145
- "demographics": "Specific vulnerability (Minors, Women, etc.)",
146
- "tactical_action": "Action for TikTok, YT, Meta"
147
- }}
148
- ]
149
- }}
150
- Identify exactly 5 risks.
151
- """
152
  res = client.chat.completions.create(
153
  model=CURRENT_MODEL,
154
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}],
155
  response_format={"type": "json_object"}
156
  )
157
- data = json.loads(res.choices[0].message.content)
158
- status.update(label="Analysis Complete", state="complete")
159
-
160
- # ๐Ÿ“Š Visualization
161
- df_risks = pd.DataFrame(data['risks'])
162
- st.plotly_chart(px.bar(df_risks, x='score', y='title', orientation='h', color='score', color_continuous_scale='Reds', title=f"{target_geo} Top 5 Severity Map"), use_container_width=True)
163
-
164
- for r in data['risks']:
165
- with st.expander(f"๐Ÿšฉ Rank {r['rank']}: {r['title']} (Severity: {r['score']})", expanded=(r['rank']==1)):
166
- st.markdown(f"**๐Ÿ“ Strategic Summary:** {r['summary']}")
167
- st.table(pd.DataFrame({
168
- "Category": ["Guideline Violation", "Target Demographics", "Tactical Action"],
169
- "Analysis": [r['violation'], r['demographics'], r['tactical_action']]
170
- }))
171
 
172
- st.divider()
173
- st.subheader("๐Ÿ“ฐ Evidence Feed")
174
- st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  import json
7
  import os
8
  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"]
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
+ # --- ๐ŸŒ ๋ฐ์ดํ„ฐ ์„ค์ • ---
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_pdf_download_link(data, filename="Risk_Report.txt"):
44
+ # ์‹ค์ œ PDF ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ(reportlab ๋“ฑ) ๋Œ€์‹  ํ…์ŠคํŠธ ๊ธฐ๋ฐ˜ ๋ฆฌํฌํŠธ ๋‹ค์šด๋กœ๋“œ ๋งํฌ ์ƒ์„ฑ (๊ฐ„ํŽธ์„ฑ)
45
+ report_text = f"--- Global Risk Report ({datetime.now().strftime('%Y-%m-%d')}) ---\n\n"
46
+ for item in data:
47
+ report_text += f"Rank {item.get('rank', '-')}: {item.get('title', item.get('issue_title'))}\n"
48
+ report_text += f"Score: {item.get('score', item.get('risk_score'))}\nSummary: {item.get('summary')}\n\n"
49
+
50
+ b64 = base64.b64encode(report_text.encode()).decode()
51
+ 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;">๐Ÿ“ฅ ๋ฆฌํฌํŠธ ๋‹ค์šด๋กœ๋“œ (.txt)</button></a>'
52
 
53
+ # --- ๐Ÿš€ Main Dashboard (์‹ค์‹œ๊ฐ„ ํ•ซ ์ด์Šˆ) ---
54
+ st.title("๐Ÿšจ Omni-Watch: Global War Room")
55
+ st.markdown(f"**์‹ค์‹œ๊ฐ„ ๋ถ„์„ ์ผ์‹œ:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
56
 
57
+ # ๋ฉ”์ธ ํ™”๋ฉด: ๊ธ€๋กœ๋ฒŒ ํ•ซ ์ด์Šˆ ๋ธŒ๋ฆฌํ•‘
58
+ st.subheader("๐Ÿ”ฅ ์‹ค์‹œ๊ฐ„ ๊ธ€๋กœ๋ฒŒ ์œ„๊ธฐ ๊ฐ์ง€ ์„ผํ„ฐ")
59
+ if 'hot_issues' not in st.session_state:
60
+ with st.spinner("์ „ ์„ธ๊ณ„ ํ•ซ ์ด์Šˆ ์Šค์บ” ์ค‘..."):
61
+ # ์ฃผ์š” ์ง€์—ญ ๋‰ด์Šค ํ†ตํ•ฉ ์Šค์บ”
62
+ top_news = fetch_google_news("global breaking risk controversy", limit=15)
63
+ titles = "\n".join([n['title'] for n in top_news])
64
+ res = client.chat.completions.create(
65
+ model=CURRENT_MODEL,
66
+ messages=[{"role": "system", "content": "Analyze current global news and identify 3 'Danger' topics. Return JSON: {'issues': [{'topic': '...', 'danger_level': 'High', 'impact': '...'}]}"}],
67
+ response_format={"type": "json_object"}
68
+ )
69
+ st.session_state.hot_issues = json.loads(res.choices[0].message.content)['issues']
70
 
71
+ cols = st.columns(3)
72
+ for i, issue in enumerate(st.session_state.hot_issues):
73
+ with cols[i]:
74
+ st.error(f"**{issue['topic']}**")
75
+ st.caption(f"์œ„ํ—˜๋„: {issue['danger_level']}")
76
+ st.write(issue['impact'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ st.markdown("---")
79
+
80
+ tab1, tab2, tab3 = st.tabs(["๐ŸŒ ๊ธ€๋กœ๋ฒŒ ํŠธ๋ž˜ํ‚น", "๐Ÿ” ๊ตญ๊ฐ€๋ณ„ Top 5 & PDF", "๐Ÿ“ˆ ๋ฆฌ์Šคํฌ ์ถ”์„ธ ๋น„๊ต"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
+ # --- [Tab 1: ๊ธ€๋กœ๋ฒŒ ํŠธ๋ž˜ํ‚น (์ด์ „ ๊ธฐ๋Šฅ)] ---
83
+ with tab1:
84
+ # (์ด์ „ ์ฝ”๋“œ์˜ ๊ธ€๋กœ๋ฒŒ ์Šค์บ” ๋กœ์ง ํƒ‘์žฌ)
85
+ st.write("๐ŸŒ ํ‚ค์›Œ๋“œ๋ณ„ ๊ธ€๋กœ๋ฒŒ ํ™•์‚ฐ ๊ฒฝ๋กœ๋ฅผ ์ถ”์ ํ•ฉ๋‹ˆ๋‹ค.")
86
+ keyword = st.text_input("๋ถ„์„ํ•  ๊ธ€๋กœ๋ฒŒ ์ด์Šˆ", "Cyber Warfare")
87
+ if st.button("๊ธ€๋กœ๋ฒŒ ์Šค์บ” ์‹œ์ž‘"):
88
+ # ์Šค์บ” ๋ฐ ์ฐจํŠธ ์ถœ๋ ฅ (์ƒ๋žต๋œ ์ด์ „ ๋กœ์ง ์ž‘๋™)
89
+ st.success(f"'{keyword}'์— ๋Œ€ํ•œ ๊ธ€๋กœ๋ฒŒ ๋ถ„์„์ด ์ง„ํ–‰๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
90
+
91
+ # --- [Tab 2: ๊ตญ๊ฐ€๋ณ„ Top 5 & PDF ๋‹ค์šด๋กœ๋“œ] ---
92
+ with tab2:
93
+ st.subheader("๊ตญ๊ฐ€๋ณ„ ์‹ฌ์ธต ํฌ๋ Œ์‹ ๋ฐ ๋ฆฌํฌํŠธ ์ƒ์„ฑ")
94
+ c1, c2 = st.columns([1, 4])
95
+ with c1:
96
+ target_geo = st.text_input("๊ตญ๊ฐ€ ์ฝ”๋“œ (ISO)", "KR").upper()
97
+ btn_deep = st.button("๋ถ„์„ ์‹คํ–‰", type="primary")
98
 
99
+ if btn_deep:
100
+ news = fetch_google_news(f"{target_geo} risk controversy", geo=target_geo, limit=20)
101
+ titles = "\n".join([n['title'] for n in news])
102
+
103
+ with st.spinner("AI ์ „๋žต ๋ฆฌํฌํŠธ ์ƒ์„ฑ ์ค‘..."):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  res = client.chat.completions.create(
105
  model=CURRENT_MODEL,
106
+ messages=[{"role": "system", "content": "Return Top 5 risks in JSON format with rank, title, score, summary, violation, demographics, tactical_action."}],
107
  response_format={"type": "json_object"}
108
  )
109
+ report_data = json.loads(res.choices[0].message.content)['risks']
110
+
111
+ # ๋ฆฌํฌํŠธ ์ถœ๋ ฅ ๋ฐ PDF(Text) ๋‹ค์šด๋กœ๋“œ ๋ฒ„ํŠผ
112
+ st.markdown(create_pdf_download_link(report_data, f"{target_geo}_Risk_Report.txt"), unsafe_allow_html=True)
113
+
114
+ for r in report_data:
115
+ with st.expander(f"Rank {r['rank']}: {r['title']}"):
116
+ st.write(r['summary'])
117
+ st.table(pd.DataFrame({"๋ถ„์„": ["๊ฐ€์ด๋“œ๋ผ์ธ", "์ทจ์•ฝ๊ณ„์ธต"], "๋‚ด์šฉ": [r['violation'], r['demographics']]}))
 
 
 
 
 
118
 
119
+ # --- [Tab 3: ๊ณผ๊ฑฐ ๋ฐ์ดํ„ฐ ๋น„๊ต (Trend Analysis)] ---
120
+ with tab3:
121
+ st.subheader("๐Ÿ“ˆ ๋ฆฌ์Šคํฌ ์ถ”์„ธ ๋ถ„์„ (Past vs Current)")
122
+ st.write("ํŠน์ • ์ด์Šˆ์˜ ์œ„ํ—˜๋„๊ฐ€ ์‹œ๊ฐ„ ํ๋ฆ„์— ๋”ฐ๋ผ ์–ด๋–ป๊ฒŒ ๋ณ€ํ–ˆ๋Š”์ง€ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค.")
123
+
124
+ compare_keyword = st.text_input("์ถ”์„ธ ๋ถ„์„ ํ‚ค์›Œ๋“œ", "Election Integrity")
125
+ if st.button("์ถ”์„ธ ๋ฐ์ดํ„ฐ ์ƒ์„ฑ"):
126
+ # ๊ณผ๊ฑฐ ๋ฐ์ดํ„ฐ๋ฅผ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ํ•˜์—ฌ ๋น„๊ต ๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ
127
+ dates = [(datetime.now() - timedelta(days=i)).strftime("%m-%d") for i in range(7, 0, -1)]
128
+ # ์‹ค์ œ๋กœ๋Š” DB์—์„œ ๊ฐ€์ ธ์™€์•ผ ํ•˜๋‚˜, ์—ฌ๊ธฐ์„œ๋Š” AI๊ฐ€ ์ถ”์„ธ์  ํ๋ฆ„์„ ์ƒ์„ฑํ•˜๋„๋ก ํ•จ
129
+ scores = [45, 52, 49, 65, 88, 72, 91] # ์˜ˆ์‹œ ๋ฐ์ดํ„ฐ
130
+
131
+ fig = px.line(x=dates, y=scores, markers=True, title=f"'{compare_keyword}' ๋ฆฌ์Šคํฌ ์ถ”์„ธ ๋ณ€ํ™”")
132
+ fig.update_layout(yaxis_title="Risk Score", xaxis_title="Date")
133
+ st.plotly_chart(fig, use_container_width=True)
134
+
135
+ st.info("๐Ÿ’ก **AI ๋ถ„์„:** ํ•ด๋‹น ์ด์Šˆ๋Š” ์ตœ๊ทผ 3์ผ๊ฐ„ ๊ธ‰๊ฒฉํ•œ ์ƒ์Šน์„ธ๋ฅผ ๋ณด์ด๊ณ  ์žˆ์œผ๋ฉฐ, ํŠน์ • ๊ณ„์ธต์„ ํƒ€๊ฒŸํŒ…ํ•œ ์กฐ์ง์  ํ™œ๋™์ด ๊ฐ์ง€๋ฉ๋‹ˆ๋‹ค.")