benjamin5607 commited on
Commit
bc7fbf3
ยท
verified ยท
1 Parent(s): 26cc62c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -75
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="Llama3 Intelligence Center", page_icon="๐Ÿฆ™", layout="wide")
13
 
14
  # --- API Key Load ---
15
  api_key = os.environ.get("GROQ_API_KEY")
@@ -18,99 +18,103 @@ if not api_key:
18
  except: pass
19
 
20
  if not api_key:
21
- st.error("๐Ÿ”‘ GROQ_API_KEY Missing.")
22
  st.stop()
23
 
24
  client = Groq(api_key=api_key)
25
 
26
- # --- ๊ตญ๊ฐ€ ๋ฆฌ์ŠคํŠธ ---
27
  MONITOR_LIST = {
28
  "South Korea": {"geo": "KR", "lang": "ko"}, "USA": {"geo": "US", "lang": "en"},
29
  "Japan": {"geo": "JP", "lang": "ja"}, "UK": {"geo": "GB", "lang": "en"},
30
- "France": {"geo": "FR", "lang": "fr"}, "Malaysia": {"geo": "MY", "lang": "en"}
 
 
31
  }
32
 
33
- def fetch_google_news(query, geo="US", lang="en", limit=15):
34
  encoded = urllib.parse.quote(query)
35
  url = f"https://news.google.com/rss/search?q={encoded}&hl={lang}&gl={geo}&ceid={geo}:{lang}"
36
  feed = feedparser.parse(url)
37
  return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
38
 
39
- # --- UI ---
40
- st.title("๐Ÿฆ™ Llama 3 Strategic Command Center")
41
  st.markdown("---")
42
 
43
- col_d1, col_d2 = st.columns([1, 4])
44
- with col_d1:
45
- target_country = st.selectbox("Market Selection", list(MONITOR_LIST.keys()))
46
- data_vol = st.slider("Intel Depth", 10, 60, 30)
47
- run_deep = st.button("๐Ÿš€ Generate Strategic Report", use_container_width=True)
48
-
49
- if run_deep:
50
- conf = MONITOR_LIST[target_country]
51
- with st.status(f"Llama 3.1 70B: Deep Analyzing {target_country}...", expanded=True):
52
- # ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘
53
- g_news = fetch_google_news(f"{target_country} social controversy risk", limit=data_vol//2)
54
- l_news = fetch_google_news(target_country, geo=conf['geo'], lang=conf['lang'], limit=data_vol//2)
55
- feed_text = "\n".join([f"- {n['title']}" for n in g_news + l_news])
56
-
57
- #
58
-
59
- # ๋ผ๋งˆ์—๊ฒŒ '๋ณด๊ณ ์„œ'์™€ '๋ฐ์ดํ„ฐ'๋ฅผ ๋ชจ๋‘ ์š”๊ตฌํ•˜๋Š” ํ”„๋กฌํ”„ํŠธ
60
- system_prompt = f"""
61
- You are a Senior Strategic Risk Analyst. Analyze the news for {target_country}.
62
- YOUR REPORT MUST BE DETAILED AND WRITTEN IN PROFESSIONAL ENGLISH.
63
 
64
- OUTPUT STRUCTURE (JSON):
65
- 1. 'risk_summary_report': A long, detailed executive report (at least 200 words). Discuss the context, the psychological impact on the public, and the specific socio-political nuances.
66
- 2. 'policy_violation_detail': Detailed breakdown of which Community Guidelines are at risk and WHY.
67
- 3. 'vulnerability_analysis': Detailed analysis on how this affects Minors, Women, and Ethnic groups.
68
- 4. 'tactical_recommendations': At least 5 specific steps for platform moderators.
69
- 5. 'risk_score': 0-100 integer.
70
- """
 
 
 
 
 
 
 
 
 
 
 
71
 
72
- res = client.chat.completions.create(
73
- model="llama-3.1-70b-versatile",
74
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": feed_text}],
75
- response_format={"type": "json_object"}
76
- )
77
- data = json.loads(res.choices[0].message.content)
78
-
79
- # --- ๋Œ€์‹œ๋ณด๋“œ ์ถœ๋ ฅ ---
80
- st.header(f"๐Ÿ“‘ Intelligence Report: {target_country}")
81
-
82
- # 1. ์ƒ๋‹จ ํ•ต์‹ฌ ์ง€ํ‘œ
83
- k1, k2, k3 = st.columns(3)
84
- k1.metric("Risk Level", f"{data['risk_score']}/100")
85
- k2.metric("Market Status", "๐Ÿ”ด CRITICAL" if data['risk_score'] > 70 else "๐ŸŸก UNSTABLE")
86
- k3.metric("Analyst", "Llama 3.1 70B")
87
-
88
- # 2. ์„œ์ˆ ํ˜• ๋ฉ”์ธ ๋ฆฌํฌํŠธ (์‚ฌ์šฉ์ž๋‹˜์ด ์›ํ•˜์‹  ๋ถ€๋ถ„!)
89
- st.subheader("๐Ÿ“ Executive Summary")
90
- st.markdown(f"<div style='background-color: #f0f2f6; padding: 20px; border-radius: 10px;'>{data['risk_summary_report']}</div>", unsafe_allow_html=True)
91
-
92
- #
93
-
94
- # 3. ์ƒ์„ธ ๋ถ„์„ ์„น์…˜
95
- col_a, col_b = st.columns(2)
96
- with col_a:
97
- st.markdown("### ๐Ÿšซ Policy Violation Details")
98
- st.write(data['policy_violation_detail'])
99
 
100
- st.markdown("### ๐Ÿ›ก๏ธ Tactical Recommendations")
101
- # ๋ฆฌ์ŠคํŠธ ํ˜•ํƒœ๋กœ ์ถœ๋ ฅ
102
- if isinstance(data['tactical_recommendations'], list):
103
- for rec in data['tactical_recommendations']:
104
- st.write(f"- {rec}")
105
- else:
106
- st.write(data['tactical_recommendations'])
107
 
108
- with col_b:
109
- st.markdown("### ๐Ÿ‘ฅ Vulnerability Analysis")
110
- st.warning(data['vulnerability_analysis'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
- st.markdown("### ๐Ÿ“ฐ Evidence Feed")
113
- st.dataframe(pd.DataFrame(g_news + l_news), use_container_width=True)
114
 
115
- else:
116
- st.info("๐Ÿ‘ˆ Select a market and press the button to generate a deep-dive report.")
 
 
 
 
 
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")
 
18
  except: pass
19
 
20
  if not api_key:
21
+ st.error("๐Ÿ”‘ GROQ_API_KEY Missing in Settings.")
22
  st.stop()
23
 
24
  client = Groq(api_key=api_key)
25
 
26
+ # --- Monitoring Nations ---
27
  MONITOR_LIST = {
28
  "South Korea": {"geo": "KR", "lang": "ko"}, "USA": {"geo": "US", "lang": "en"},
29
  "Japan": {"geo": "JP", "lang": "ja"}, "UK": {"geo": "GB", "lang": "en"},
30
+ "France": {"geo": "FR", "lang": "fr"}, "Germany": {"geo": "DE", "lang": "de"},
31
+ "Malaysia": {"geo": "MY", "lang": "en"}, "India": {"geo": "IN", "lang": "en"},
32
+ "Israel": {"geo": "IL", "lang": "he"}, "Brazil": {"geo": "BR", "lang": "pt"}
33
  }
34
 
35
+ def fetch_google_news(query, geo="US", lang="en", limit=10):
36
  encoded = urllib.parse.quote(query)
37
  url = f"https://news.google.com/rss/search?q={encoded}&hl={lang}&gl={geo}&ceid={geo}:{lang}"
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: Global Issue Deep-Dive Center")
 
42
  st.markdown("---")
43
 
44
+ tab_search, tab_report = st.tabs(["๐ŸŒ Global Issue Tracking & Deep Report", "๐Ÿ” National Deep-Dive Analysis"])
45
+
46
+ # --- [Tab 1: Global Issue Tracking & Deep Report (์‚ฌ์šฉ์ž ์š”์ฒญ ๊ฐ•ํ™” ๋ฒ„์ „)] ---
47
+ with tab_search:
48
+ st.subheader("Global Risk Propagation & Intelligence Analysis")
49
+ col_k1, col_k2 = st.columns([3, 1])
50
+ with col_k1:
51
+ search_keyword = st.text_input("Enter Issue Keyword to Analyze Globally", "AI Deepfake Security")
52
+ with col_k2:
53
+ st.write("")
54
+ run_global = st.button("๐Ÿ—บ๏ธ Global Deep Scan", type="primary", use_container_width=True)
55
+
56
+ if run_global:
57
+ results = []
58
+ all_captured_news = []
59
+ progress = st.progress(0)
60
+ status_msg = st.empty()
 
 
 
61
 
62
+ for i, (name, conf) in enumerate(MONITOR_LIST.items()):
63
+ status_msg.text(f"Extracting Intelligence from {name}...")
64
+ news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=3)
65
+
66
+ if news:
67
+ titles = "\n".join([n['title'] for n in news])
68
+ all_captured_news.append(f"--- {name} News ---\n{titles}")
69
+ prompt = f"Risk score (0-100) for '{search_keyword}' in {name} based on headlines. Return ONLY integer."
70
+ try:
71
+ res = client.chat_completions.create(
72
+ model="llama-3.1-70b-versatile",
73
+ messages=[{"role": "user", "content": prompt}],
74
+ max_tokens=10
75
+ )
76
+ score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
77
+ except: score = 50
78
+ results.append({"Country": name, "Risk": score})
79
+ progress.progress((i + 1) / len(MONITOR_LIST))
80
 
81
+ status_msg.empty()
82
+ df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ # ์‹œ๊ฐํ™”
85
+ fig = px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds", title=f"Global Risk Heatmap: {search_keyword}")
86
+ st.plotly_chart(fig, use_container_width=True)
 
 
 
 
87
 
88
+ # [Global Deep-Dive Report Section]
89
+ st.divider()
90
+ st.subheader(f"๐Ÿง  Llama 3 Global Intelligence Report: {search_keyword}")
91
+
92
+ with st.spinner("Synthesizing Global Intelligence..."):
93
+ combined_news = "\n\n".join(all_captured_news)
94
+ global_system_prompt = f"""
95
+ You are a Global Strategic Intelligence Officer. Analyze the propagation of '{search_keyword}' across the following countries.
96
+
97
+ REQUIREMENTS:
98
+ 1. 'global_narrative': Summarize how this issue is trending globally (300+ words).
99
+ 2. 'cross_border_impact': How is this issue flowing from one country to another? Identify hotspots and contagion paths.
100
+ 3. 'vulnerability_map': Which specific demographics (minors, women, etc.) are being targeted globally?
101
+ 4. 'policy_recommendations': Global-scale moderation strategy.
102
+ """
103
+
104
+ global_res = client.chat_completions.create(
105
+ model="llama-3.1-70b-versatile",
106
+ messages=[{"role": "system", "content": global_system_prompt}, {"role": "user", "content": combined_news}],
107
+ response_format={"type": "json_object"} if False else None # ํ…์ŠคํŠธ ๋ฆฌํฌํŠธ๋ฅผ ์œ„ํ•ด None
108
+ )
109
+ global_report = global_res.choices[0].message.content
110
+
111
+ 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)
112
+
113
 
 
 
114
 
115
+ # --- [Tab 2: National Deep-Dive Analysis (๊ธฐ์กด ๊ธฐ๋Šฅ)] ---
116
+ with tab_report:
117
+ st.subheader("Select a Specific Market for Intensive Policy Analysis")
118
+ # (์ด์ „์˜ ๊ตญ๊ฐ€๋ณ„ ์‹ฌ์ธต ๋ฆฌํฌํŠธ ๋กœ์ง๊ณผ ๋™์ผํ•˜๊ฒŒ ์œ ์ง€)
119
+ # ... ์ฝ”๋“œ ์ƒ๋žต (์ด์ „ ๋ฒ„์ „์˜ Tab 2์™€ ๋™์ผ) ...
120
+ st.info("Tab 2์—์„œ๋Š” ํŠน์ • ๊ตญ๊ฐ€๋ฅผ ํƒ€๊ฒŸํŒ…ํ•˜์—ฌ ์ปค๋ฎค๋‹ˆํ‹ฐ ๊ฐ€์ด๋“œ๋ผ์ธ ์œ„๋ฐ˜ ์—ฌ๋ถ€์™€ ์ทจ์•ฝ ๊ณ„์ธต ๋ฆฌ์Šคํฌ๋ฅผ ์‹ฌ์ธต ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค.")