benjamin5607 commited on
Commit
3a1444a
Β·
verified Β·
1 Parent(s): 23aad06

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -37
app.py CHANGED
@@ -4,14 +4,13 @@ import urllib.parse
4
  from groq import Groq
5
  import pandas as pd
6
  import json
7
- import time
8
  import os
9
  import plotly.express as px
10
 
11
  # --- Page Config ---
12
- st.set_page_config(page_title="Global Issue Intelligence Center", page_icon="πŸ“‘", layout="wide")
13
 
14
- # --- 🌍 API Key Load ---
15
  api_key = os.environ.get("GROQ_API_KEY")
16
  if not api_key:
17
  try: api_key = st.secrets["GROQ_API_KEY"]
@@ -21,19 +20,16 @@ if not api_key:
21
  st.error("πŸ”‘ GROQ_API_KEY Missing in Settings.")
22
  st.stop()
23
 
24
- # Groq ν΄λΌμ΄μ–ΈνŠΈ μ΄ˆκΈ°ν™”
25
  client = Groq(api_key=api_key)
26
-
27
- # μ΅œμ‹  λͺ¨λΈλͺ… μ •μ˜ (Llama 3.3 70B)
28
  CURRENT_MODEL = "llama-3.3-70b-versatile"
29
 
30
- # --- Monitoring Nations ---
31
- MONITOR_LIST = {
32
- "South Korea": {"geo": "KR", "lang": "ko"}, "USA": {"geo": "US", "lang": "en"},
33
- "Japan": {"geo": "JP", "lang": "ja"}, "UK": {"geo": "GB", "lang": "en"},
34
- "France": {"geo": "FR", "lang": "fr"}, "Germany": {"geo": "DE", "lang": "de"},
35
- "Malaysia": {"geo": "MY", "lang": "en"}, "India": {"geo": "IN", "lang": "en"},
36
- "Israel": {"geo": "IL", "lang": "he"}, "Brazil": {"geo": "BR", "lang": "pt"}
37
  }
38
 
39
  def fetch_google_news(query, geo="US", lang="en", limit=10):
@@ -42,84 +38,93 @@ def fetch_google_news(query, geo="US", lang="en", limit=10):
42
  feed = feedparser.parse(url)
43
  return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
44
 
45
- st.title("πŸ“‘ Omni-Watch: Global Intelligence (Llama 3.3)")
46
- st.caption("Strategic Intelligence for Policy & Risk Management")
47
  st.markdown("---")
48
 
49
  tab_search, tab_report = st.tabs(["🌐 Global Issue Tracking", "πŸ” National Deep-Dive"])
50
 
51
  # --- [Tab 1: Global Issue Tracking] ---
52
  with tab_search:
53
- st.subheader("Global Risk Propagation & Deep Intelligence")
54
  col_k1, col_k2 = st.columns([3, 1])
55
  with col_k1:
56
- search_keyword = st.text_input("Enter Issue Keyword", "Digital Misinformation")
 
57
  with col_k2:
58
  st.write("")
59
  run_global = st.button("πŸ—ΊοΈ Global Deep Scan", type="primary", use_container_width=True)
60
 
61
  if run_global:
 
 
 
 
 
62
  results = []
63
  all_captured_news = []
64
  progress = st.progress(0)
65
  status_msg = st.empty()
66
 
67
- for i, (name, conf) in enumerate(MONITOR_LIST.items()):
68
- status_msg.text(f"Extracting Intel from {name}...")
69
- news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=3)
70
 
71
  if news:
72
  titles = "\n".join([n['title'] for n in news])
73
- all_captured_news.append(f"--- {name} News ---\n{titles}")
74
 
75
  try:
76
  res = client.chat.completions.create(
77
  model=CURRENT_MODEL,
78
- messages=[{"role": "user", "content": f"Score 0-100 for '{search_keyword}' in {name}: {titles}. ONLY INTEGER."}],
79
  max_tokens=10
80
  )
81
  score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
82
  except: score = 50
83
- results.append({"Country": name, "Risk": score})
84
- progress.progress((i + 1) / len(MONITOR_LIST))
85
 
86
  status_msg.empty()
87
  df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
88
  st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"), use_container_width=True)
89
 
 
90
  st.divider()
91
- st.subheader(f"🧠 Llama 3.3 Global Intelligence Report")
92
-
93
- with st.spinner("Synthesizing Massive Data..."):
94
  combined_news = "\n\n".join(all_captured_news)
95
  global_res = client.chat.completions.create(
96
  model=CURRENT_MODEL,
97
- messages=[{"role": "system", "content": "You are a Global Strategic Intelligence Officer. Analyze issue propagation and demographic risks in 500+ words."}, {"role": "user", "content": combined_news}],
98
  max_tokens=3000
99
  )
100
- st.markdown(f"<div style='background-color: #e1f5fe; padding: 25px; border-radius: 10px; border-left: 5px solid #0288d1;'>{global_res.choices[0].message.content}</div>", unsafe_allow_html=True)
101
 
102
  # --- [Tab 2: National Deep-Dive] ---
103
  with tab_report:
 
104
  col_d1, col_d2 = st.columns([1, 4])
105
  with col_d1:
106
- target_country = st.selectbox("Market", list(MONITOR_LIST.keys()))
 
107
  data_vol = st.slider("Depth", 10, 60, 30)
108
  run_deep = st.button("πŸš€ Analyze Market", use_container_width=True)
109
 
110
  if run_deep:
111
- conf = MONITOR_LIST[target_country]
112
- with st.status(f"Llama 3.3 Deep-Dive: {target_country}...", expanded=True):
113
- news = fetch_google_news(f"{target_country} social controversy", limit=data_vol)
114
  feed_text = "\n".join([f"- {n['title']}" for n in news])
115
 
116
  deep_res = client.chat.completions.create(
117
  model=CURRENT_MODEL,
118
- messages=[{"role": "system", "content": "Analyze Community Guideline violations & demographics (Minors, Women, Race). Output JSON."}, {"role": "user", "content": feed_text}],
119
  response_format={"type": "json_object"}
120
  )
121
  data = json.loads(deep_res.choices[0].message.content)
122
 
123
- st.header(f"πŸ“‘ Intelligence Report: {target_country}")
124
- st.markdown(f"<div style='background-color: #f0f2f6; padding: 20px; border-radius: 10px;'>{data.get('executive_report', 'Processing...')}</div>", unsafe_allow_html=True)
125
- st.warning(f"**Policy & Demographics Risk:** {data.get('vulnerability_analysis', 'N/A')}")
 
 
 
4
  from groq import Groq
5
  import pandas as pd
6
  import json
 
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")
15
  if not api_key:
16
  try: api_key = st.secrets["GROQ_API_KEY"]
 
20
  st.error("πŸ”‘ GROQ_API_KEY Missing in Settings.")
21
  st.stop()
22
 
 
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
  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 = []
66
  progress = st.progress(0)
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)))
84
  except: score = 50
85
+ results.append({"Country": geo_code, "Risk": score})
86
+ progress.progress((i + 1) / len(target_countries))
87
 
88
  status_msg.empty()
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')}")