benjamin5607 commited on
Commit
23aad06
Β·
verified Β·
1 Parent(s): 8c6d44d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -83
app.py CHANGED
@@ -9,7 +9,7 @@ import os
9
  import plotly.express as px
10
 
11
  # --- Page Config ---
12
- st.set_page_config(page_title="Global Issue Intelligence", page_icon="πŸ“‘", layout="wide")
13
 
14
  # --- 🌍 API Key Load ---
15
  api_key = os.environ.get("GROQ_API_KEY")
@@ -24,6 +24,9 @@ if not api_key:
24
  # Groq ν΄λΌμ΄μ–ΈνŠΈ μ΄ˆκΈ°ν™”
25
  client = Groq(api_key=api_key)
26
 
 
 
 
27
  # --- Monitoring Nations ---
28
  MONITOR_LIST = {
29
  "South Korea": {"geo": "KR", "lang": "ko"}, "USA": {"geo": "US", "lang": "en"},
@@ -39,18 +42,18 @@ def fetch_google_news(query, geo="US", lang="en", limit=10):
39
  feed = feedparser.parse(url)
40
  return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
41
 
42
- st.title("πŸ“‘ Omni-Watch: Global Issue Deep-Dive Center")
43
- st.caption("Strategic Intelligence for Community Guidelines & Risk Mitigation")
44
  st.markdown("---")
45
 
46
- tab_search, tab_report = st.tabs(["🌐 Global Issue Tracking & Deep Report", "πŸ” National Deep-Dive Analysis"])
47
 
48
- # --- [Tab 1: Global Issue Tracking & Deep Report] ---
49
  with tab_search:
50
- st.subheader("Global Risk Propagation & Intelligence Analysis")
51
  col_k1, col_k2 = st.columns([3, 1])
52
  with col_k1:
53
- search_keyword = st.text_input("Enter Issue Keyword to Analyze Globally", "Cyber Attacks")
54
  with col_k2:
55
  st.write("")
56
  run_global = st.button("πŸ—ΊοΈ Global Deep Scan", type="primary", use_container_width=True)
@@ -62,116 +65,61 @@ with tab_search:
62
  status_msg = st.empty()
63
 
64
  for i, (name, conf) in enumerate(MONITOR_LIST.items()):
65
- status_msg.text(f"Extracting Intelligence from {name}...")
66
  news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=3)
67
 
68
  if news:
69
  titles = "\n".join([n['title'] for n in news])
70
  all_captured_news.append(f"--- {name} News ---\n{titles}")
71
 
72
- # μˆ˜μ •λœ λΆ€λΆ„: client.chat.completions.create
73
  try:
74
  res = client.chat.completions.create(
75
- model="llama-3.3-70b-versatile",
76
- messages=[{"role": "user", "content": f"Risk score (0-100) for '{search_keyword}' in {name} news: {titles}. Return ONLY the integer."}],
77
  max_tokens=10
78
  )
79
- score_text = res.choices[0].message.content
80
- score = int(''.join(filter(str.isdigit, score_text)))
81
  except: score = 50
82
  results.append({"Country": name, "Risk": score})
83
  progress.progress((i + 1) / len(MONITOR_LIST))
84
 
85
  status_msg.empty()
86
  df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
87
-
88
- # μ‹œκ°ν™”
89
- fig = px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds", title=f"Global Risk Heatmap: {search_keyword}")
90
- st.plotly_chart(fig, use_container_width=True)
91
 
92
- # [Global Deep-Dive Report Section]
93
  st.divider()
94
- st.subheader(f"🧠 Llama 3 Global Intelligence Report: {search_keyword}")
95
-
96
-
97
 
98
- with st.spinner("Synthesizing Global Intelligence..."):
99
  combined_news = "\n\n".join(all_captured_news)
100
- global_system_prompt = f"""
101
- You are a Global Strategic Intelligence Officer. Analyze the propagation of '{search_keyword}' across multiple countries.
102
- Your report must be long, professional, and insightful.
103
-
104
- REQUIREMENTS (Output in English):
105
- 1. 'Global Narrative': Detailed summary of how this issue is trending (300+ words).
106
- 2. 'Contagion & Cross-Border Impact': How the issue flows between nations.
107
- 3. 'Social Vulnerability Map': Identify risks to minors, women, and ethnic groups globally.
108
- 4. 'Policy Recommendations': High-level moderation and guideline strategies.
109
- """
110
-
111
- # μˆ˜μ •λœ λΆ€λΆ„: client.chat.completions.create
112
  global_res = client.chat.completions.create(
113
- model="llama-3.3-70b-versatile",
114
- messages=[{"role": "system", "content": global_system_prompt}, {"role": "user", "content": combined_news}],
115
- max_tokens=3000,
116
- temperature=0.3
117
  )
118
- global_report = global_res.choices[0].message.content
119
-
120
- st.markdown(f"<div style='background-color: #e1f5fe; padding: 25px; border-radius: 10px; border-left: 5px solid #0288d1;'>{global_report}</div>", unsafe_allow_html=True)
121
 
122
- # --- [Tab 2: National Deep-Dive Analysis] ---
123
  with tab_report:
124
  col_d1, col_d2 = st.columns([1, 4])
125
  with col_d1:
126
- st.subheader("Target Selection")
127
  target_country = st.selectbox("Market", list(MONITOR_LIST.keys()))
128
- data_vol = st.slider("Intel Depth", 10, 60, 30)
129
  run_deep = st.button("πŸš€ Analyze Market", use_container_width=True)
130
 
131
  if run_deep:
132
  conf = MONITOR_LIST[target_country]
133
- with st.status(f"Llama 3 Deep-Dive: {target_country}...", expanded=True):
134
- g_news = fetch_google_news(f"{target_country} social controversy", limit=data_vol//2)
135
- l_news = fetch_google_news(target_country, geo=conf['geo'], lang=conf['lang'], limit=data_vol//2)
136
- feed_text = "\n".join([f"- {n['title']}" for n in g_news + l_news])
137
 
138
-
139
-
140
- deep_system_prompt = f"""
141
- Identify Community Guideline violations and risks for {target_country}.
142
- Structure your report as a JSON object:
143
- {{
144
- "risk_score": 0-100,
145
- "executive_report": "300+ word detailed English report",
146
- "policy_impact": "Details on which guidelines are violated and why",
147
- "vulnerability_analysis": "Risk assessment for minors, gender, and ethnicity",
148
- "action_plan": "5 specific tactical steps"
149
- }}
150
- """
151
-
152
- # μˆ˜μ •λœ λΆ€λΆ„: client.chat.completions.create + response_format
153
  deep_res = client.chat.completions.create(
154
- model="llama-3.3-70b-versatile",
155
- messages=[{"role": "system", "content": deep_system_prompt}, {"role": "user", "content": feed_text}],
156
  response_format={"type": "json_object"}
157
  )
158
  data = json.loads(deep_res.choices[0].message.content)
159
 
160
- # UI 좜λ ₯
161
- st.header(f"πŸ“‘ National Intelligence: {target_country}")
162
- m1, m2 = st.columns([1, 4])
163
- m1.metric("Risk Score", f"{data['risk_score']}/100")
164
-
165
- st.subheader("πŸ“ Executive Summary")
166
- st.markdown(f"<div style='background-color: #f0f2f6; padding: 20px; border-radius: 10px;'>{data['executive_report']}</div>", unsafe_allow_html=True)
167
-
168
-
169
-
170
- c_a, c_b = st.columns(2)
171
- with c_a:
172
- st.markdown("### 🚫 Policy & Vulnerability")
173
- st.write(data['policy_impact'])
174
- st.warning(data['vulnerability_analysis'])
175
- with c_b:
176
- st.markdown("### πŸ›‘οΈ Tactical Action Plan")
177
- st.success(data['action_plan'])
 
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")
 
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"},
 
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)
 
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')}")