benjamin5607 commited on
Commit
9465fc2
ยท
verified ยท
1 Parent(s): 3a1444a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -53
app.py CHANGED
@@ -8,7 +8,7 @@ import os
8
  import plotly.express as px
9
 
10
  # --- Page Config ---
11
- st.set_page_config(page_title="Global Risk Radar: UN Scale", page_icon="๐Ÿ‡บ๐Ÿ‡ณ", layout="wide")
12
 
13
  # --- API Key Load ---
14
  api_key = os.environ.get("GROQ_API_KEY")
@@ -23,13 +23,12 @@ if not api_key:
23
  client = Groq(api_key=api_key)
24
  CURRENT_MODEL = "llama-3.3-70b-versatile"
25
 
26
- # --- ๐ŸŒ UN Nations Data (์ฃผ์š” ์ „๋žต ๊ตญ๊ฐ€ ์œ„์ฃผ ๊ธฐ๋ณธ์…‹ + ํ™•์žฅ ๊ฐ€๋Šฅ ๊ตฌ์กฐ) ---
27
- # ์‹ค์ „์—์„œ๋Š” pycountry ๊ฐ™์€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•ด 193๊ฐœ๊ตญ์„ ๋‹ค ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
28
  REGION_MAP = {
29
- "Asia": ["KR", "JP", "CN", "VN", "MY", "TH", "IN", "ID", "PH"],
30
- "Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL"],
31
- "Americas": ["US", "CA", "BR", "MX", "AR", "CO"],
32
- "Middle East/Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
33
  }
34
 
35
  def fetch_google_news(query, geo="US", lang="en", limit=10):
@@ -38,28 +37,26 @@ def fetch_google_news(query, geo="US", lang="en", limit=10):
38
  feed = feedparser.parse(url)
39
  return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
40
 
41
- st.title("๐Ÿ‡บ๐Ÿ‡ณ Omni-Watch: UN Scale Intelligence")
42
- st.caption("Monitoring Global Risks across all UN Member States")
43
  st.markdown("---")
44
 
45
- tab_search, tab_report = st.tabs(["๐ŸŒ Global Issue Tracking", "๐Ÿ” National Deep-Dive"])
46
 
47
- # --- [Tab 1: Global Issue Tracking] ---
48
  with tab_search:
49
- st.subheader("Global Risk Propagation (Select Regions)")
50
  col_k1, col_k2 = st.columns([3, 1])
51
  with col_k1:
52
- search_keyword = st.text_input("Enter Issue Keyword (e.g. 'Protest', 'Cyber Attack')", "Election Integrity")
53
- selected_regions = st.multiselect("Select Target Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
54
  with col_k2:
55
  st.write("")
56
  run_global = st.button("๐Ÿ—บ๏ธ Global Deep Scan", type="primary", use_container_width=True)
57
 
58
  if run_global:
59
- # ์„ ํƒ๋œ ๊ถŒ์—ญ์˜ ๋ชจ๋“  ๊ตญ๊ฐ€ ๋ฆฌ์ŠคํŠธ์—…
60
  target_countries = []
61
- for reg in selected_regions:
62
- target_countries.extend(REGION_MAP[reg])
63
 
64
  results = []
65
  all_captured_news = []
@@ -67,17 +64,15 @@ with tab_search:
67
  status_msg = st.empty()
68
 
69
  for i, geo_code in enumerate(target_countries):
70
- status_msg.text(f"Scanning {geo_code} for intelligence...")
71
  news = fetch_google_news(search_keyword, geo=geo_code, limit=3)
72
-
73
  if news:
74
  titles = "\n".join([n['title'] for n in news])
75
- all_captured_news.append(f"--- Country: {geo_code} ---\n{titles}")
76
-
77
  try:
78
  res = client.chat.completions.create(
79
  model=CURRENT_MODEL,
80
- messages=[{"role": "user", "content": f"Risk score (0-100) for '{search_keyword}' in {geo_code}: {titles}. ONLY INTEGER."}],
81
  max_tokens=10
82
  )
83
  score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
@@ -89,42 +84,34 @@ with tab_search:
89
  df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
90
  st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"), use_container_width=True)
91
 
92
- # [Global Deep Report]
93
  st.divider()
94
- st.subheader("๐Ÿง  Llama 3.3 Global Strategic Synthesis")
95
- with st.spinner("Analyzing Global Propagation..."):
 
 
 
96
  combined_news = "\n\n".join(all_captured_news)
 
 
 
 
 
 
 
 
 
 
 
 
97
  global_res = client.chat.completions.create(
98
  model=CURRENT_MODEL,
99
- messages=[{"role": "system", "content": "You are a UN Strategic Intelligence Officer. Analyze global risks and demographic impacts in 500+ words professional report."}, {"role": "user", "content": combined_news}],
100
- max_tokens=3000
101
  )
102
  st.markdown(f"<div style='background-color: #e3f2fd; padding: 25px; border-radius: 10px; border-left: 5px solid #1976d2;'>{global_res.choices[0].message.content}</div>", unsafe_allow_html=True)
103
 
104
- # --- [Tab 2: National Deep-Dive] ---
105
  with tab_report:
106
- st.subheader("Specific Country Intelligence Analysis")
107
- col_d1, col_d2 = st.columns([1, 4])
108
- with col_d1:
109
- # ์‚ฌ์šฉ์ž๊ฐ€ UN ๊ตญ๊ฐ€ ์ฝ”๋“œ๋ฅผ ์ง์ ‘ ์ž…๋ ฅํ•  ์ˆ˜๋„ ์žˆ๊ฒŒ ํ•จ
110
- target_geo = st.text_input("Enter ISO Country Code (e.g. KR, US, MY, UA)", "MY").upper()
111
- data_vol = st.slider("Depth", 10, 60, 30)
112
- run_deep = st.button("๐Ÿš€ Analyze Market", use_container_width=True)
113
-
114
- if run_deep:
115
- with st.status(f"Llama 3.3 Deep-Dive: {target_geo}...", expanded=True):
116
- news = fetch_google_news(f"{target_geo} social risk", geo=target_geo, limit=data_vol)
117
- feed_text = "\n".join([f"- {n['title']}" for n in news])
118
-
119
- deep_res = client.chat.completions.create(
120
- model=CURRENT_MODEL,
121
- messages=[{"role": "system", "content": "Analyze Community Guideline violations & demographics (Minors, Women, Race). Return JSON with 'risk_score', 'executive_report', 'vulnerability_analysis', 'action_plan'."}, {"role": "user", "content": feed_text}],
122
- response_format={"type": "json_object"}
123
- )
124
- data = json.loads(deep_res.choices[0].message.content)
125
-
126
- st.header(f"๐Ÿ“‘ National Intelligence Report: {target_geo}")
127
- st.metric("Risk Score", f"{data.get('risk_score')}/100")
128
- st.markdown(f"<div style='background-color: #f5f5f5; padding: 20px; border-radius: 10px;'>{data.get('executive_report')}</div>", unsafe_allow_html=True)
129
- st.error(f"**Vulnerability Analysis:** {data.get('vulnerability_analysis')}")
130
- st.success(f"**Tactical Action Plan:** {data.get('action_plan')}")
 
8
  import plotly.express as px
9
 
10
  # --- Page Config ---
11
+ st.set_page_config(page_title="Global Strategic Intelligence", page_icon="๐Ÿ‡บ๐Ÿ‡ณ", layout="wide")
12
 
13
  # --- API Key Load ---
14
  api_key = os.environ.get("GROQ_API_KEY")
 
23
  client = Groq(api_key=api_key)
24
  CURRENT_MODEL = "llama-3.3-70b-versatile"
25
 
26
+ # --- ๐ŸŒ UN Geoscheme Mapping ---
 
27
  REGION_MAP = {
28
+ "Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "TH", "IN", "ID", "PH", "AU", "SG"],
29
+ "Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL", "SE"],
30
+ "Americas": ["US", "CA", "BR", "MX", "AR", "CO", "CL", "VE"],
31
+ "ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR", "QA"]
32
  }
33
 
34
  def fetch_google_news(query, geo="US", lang="en", limit=10):
 
37
  feed = feedparser.parse(url)
38
  return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
39
 
40
+ st.title("๐Ÿ“ก Omni-Watch: Integrated Strategic Intelligence")
41
+ st.caption("Global Propagation Analysis & Policy Violation Forensics")
42
  st.markdown("---")
43
 
44
+ tab_search, tab_report = st.tabs(["๐ŸŒ Global Issue Tracking & Policy Report", "๐Ÿ” National Deep-Dive Analysis"])
45
 
46
+ # --- [Tab 1: Global Issue Tracking (์‚ฌ์šฉ์ž ์š”์ฒญ ๋ณด๊ฐ• ์™„๋ฃŒ)] ---
47
  with tab_search:
48
+ st.subheader("Global Risk Propagation & Strategic Policy Report")
49
  col_k1, col_k2 = st.columns([3, 1])
50
  with col_k1:
51
+ search_keyword = st.text_input("Enter Issue Keyword (e.g. 'Deepfake Violence', 'Hate Speech')", "Child Exploitation Risk")
52
+ selected_regions = st.multiselect("Select Regions to Scan", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
53
  with col_k2:
54
  st.write("")
55
  run_global = st.button("๐Ÿ—บ๏ธ Global Deep Scan", type="primary", use_container_width=True)
56
 
57
  if run_global:
 
58
  target_countries = []
59
+ for reg in selected_regions: target_countries.extend(REGION_MAP[reg])
 
60
 
61
  results = []
62
  all_captured_news = []
 
64
  status_msg = st.empty()
65
 
66
  for i, geo_code in enumerate(target_countries):
67
+ status_msg.text(f"Intercepting intel from {geo_code}...")
68
  news = fetch_google_news(search_keyword, geo=geo_code, limit=3)
 
69
  if news:
70
  titles = "\n".join([n['title'] for n in news])
71
+ all_captured_news.append(f"--- {geo_code} ---\n{titles}")
 
72
  try:
73
  res = client.chat.completions.create(
74
  model=CURRENT_MODEL,
75
+ messages=[{"role": "user", "content": f"Score 0-100 risk for '{search_keyword}' in {geo_code}. ONLY INT."}],
76
  max_tokens=10
77
  )
78
  score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
 
84
  df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
85
  st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"), use_container_width=True)
86
 
 
87
  st.divider()
88
+ st.subheader(f"๐Ÿง  Llama 3.3 Global Strategic Analysis: {search_keyword}")
89
+
90
+
91
+
92
+ with st.spinner("Synthesizing Global Intel & Policy Risks..."):
93
  combined_news = "\n\n".join(all_captured_news)
94
+ # ๊ธ€๋กœ๋ฒŒ ๋ฆฌํฌํŠธ์—๋„ ์ •์ฑ… ์œ„๋ฐ˜ ๊ทผ๊ฑฐ์™€ ์ทจ์•ฝ ๊ณ„์ธต ๋ถ„์„์„ ๊ฐ•ํ•˜๊ฒŒ ์ง€์‹œ
95
+ global_system_prompt = f"""
96
+ You are a UN Strategic Intelligence & Platform Safety Director.
97
+ Analyze the global propagation of '{search_keyword}'.
98
+
99
+ YOUR REPORT MUST INCLUDE:
100
+ 1. 'Global Narrative & Contagion': Detailed overview of the spread (300+ words).
101
+ 2. 'Community Guideline Threats': Explain specifically which policies (Hate Speech, Harassment, Child Safety, etc.) are being violated and WHY.
102
+ 3. 'Vulnerability Assessment': How this issue specifically harms Minors, Women, and Ethnic groups across borders.
103
+ 4. 'Platform-Specific Mitigation': Strategic advice for TikTok, YouTube, Meta, and X.
104
+ """
105
+
106
  global_res = client.chat.completions.create(
107
  model=CURRENT_MODEL,
108
+ messages=[{"role": "system", "content": global_system_prompt}, {"role": "user", "content": combined_news}],
109
+ max_tokens=4000
110
  )
111
  st.markdown(f"<div style='background-color: #e3f2fd; padding: 25px; border-radius: 10px; border-left: 5px solid #1976d2;'>{global_res.choices[0].message.content}</div>", unsafe_allow_html=True)
112
 
113
+ # --- [Tab 2: National Deep-Dive Analysis (๊ธฐ์กด ๊ธฐ๋Šฅ ์œ ์ง€)] ---
114
  with tab_report:
115
+ # ... (๊ธฐ์กด ๊ตญ๊ฐ€๋ณ„ ์‹ฌ์ธต ๋ถ„์„ ๋กœ์ง๊ณผ ๋™์ผํ•˜๊ฒŒ ์œ ์ง€) ...
116
+ st.subheader("Specific Market Policy Forensics")
117
+ # (์ฝ”๋“œ ์ค‘๋žต - Tab 1๊ณผ ์œ ์‚ฌํ•œ Deep-Dive UI ๊ตฌ์„ฑ)