benjamin5607 commited on
Commit
26cc62c
Β·
verified Β·
1 Parent(s): df3a179

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -92
app.py CHANGED
@@ -1,120 +1,116 @@
1
  import streamlit as st
2
  import feedparser
3
  import urllib.parse
4
- from groq import Groq # Groq μ „μš© 라이브러리
5
  import pandas as pd
6
  import json
7
  import time
8
  import os
9
  import plotly.express as px
10
- import random
11
 
12
  # --- Page Config ---
13
- st.set_page_config(page_title="Llama3 Risk Intelligence", page_icon="πŸ¦™", layout="wide")
14
 
15
- # --- 🌍 Global Monitor List ---
16
- MONITOR_LIST = {
17
- "South Korea": {"geo": "KR", "lang": "ko"}, "USA": {"geo": "US", "lang": "en"},
18
- "Japan": {"geo": "JP", "lang": "ja"}, "UK": {"geo": "GB", "lang": "en"},
19
- "France": {"geo": "FR", "lang": "fr"}, "Germany": {"geo": "DE", "lang": "de"},
20
- "India": {"geo": "IN", "lang": "en"}, "Malaysia": {"geo": "MY", "lang": "en"},
21
- "Vietnam": {"geo": "VN", "lang": "vi"}, "Ukraine": {"geo": "UA", "lang": "uk"}
22
- }
23
-
24
- # --- 1. API Key Load (Groq) ---
25
- # ν—ˆκΉ…νŽ˜μ΄μŠ€ Secrets에 'GROQ_API_KEY'둜 μ €μž₯ν•΄λ‘μ„Έμš”.
26
  api_key = os.environ.get("GROQ_API_KEY")
27
  if not api_key:
28
  try: api_key = st.secrets["GROQ_API_KEY"]
29
  except: pass
30
 
31
- # --- Helper: News Fetcher ---
32
- def fetch_google_news(query, geo="US", lang="en", limit=10):
 
 
 
 
 
 
 
 
 
 
 
 
33
  encoded = urllib.parse.quote(query)
34
  url = f"https://news.google.com/rss/search?q={encoded}&hl={lang}&gl={geo}&ceid={geo}:{lang}"
35
  feed = feedparser.parse(url)
36
  return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
37
 
38
  # --- UI ---
39
- st.title("πŸ¦™ Llama 3: Strategic Risk Intelligence")
40
- st.caption("Powered by Llama 3.1 70B (via Groq) | Zero-Cost Infrastructure")
41
 
42
- if not api_key:
43
- st.error("πŸ”‘ GROQ_API_KEY not found. Please set it in Settings.")
44
- st.stop()
 
 
45
 
46
- # Groq ν΄λΌμ΄μ–ΈνŠΈ μ΄ˆκΈ°ν™”
47
- client = Groq(api_key=api_key)
 
 
 
 
 
48
 
49
- tab_global, tab_deep = st.tabs(["🌐 Propagation Tracker", "πŸ“Š Policy & Vulnerability Analysis"])
50
-
51
- # --- [Tab 1: Global Keyword Tracker] ---
52
- with tab_global:
53
- search_keyword = st.text_input("Enter Issue Keyword", "Digital Harassment")
54
- if st.button("πŸ—ΊοΈ Analyze Global Propagation", type="primary"):
55
- results = []
56
- status_msg = st.empty()
57
- for name, conf in MONITOR_LIST.items():
58
- status_msg.text(f"Scanning {name} for '{search_keyword}'...")
59
- news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=5)
60
- if news:
61
- prompt = f"Assess the risk score (0-100) for '{search_keyword}' in {name} based on the headlines. RETURN ONLY THE INTEGER VALUE.\n{news[0]['title']}"
62
- try:
63
- res = client.chat.completions.create(
64
- model="llama-3.1-70b-versatile",
65
- messages=[{"role": "user", "content": prompt}],
66
- max_tokens=10
67
- )
68
- score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
69
- except: score = 50
70
- results.append({"Country": name, "Risk": score})
71
- status_msg.empty()
72
- st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))
73
-
74
- # --- [Tab 2: Deep Intelligence (Llama 3 Logic)] ---
75
- with tab_deep:
76
- col_d1, col_d2 = st.columns([1, 4])
77
- with col_d1:
78
- target_country = st.selectbox("Market", list(MONITOR_LIST.keys()))
79
- data_vol = st.slider("Intel Volume", 10, 60, 30)
80
- run_deep = st.button("πŸš€ Analyze Situation", use_container_width=True)
81
 
82
- if run_deep:
83
- conf = MONITOR_LIST[target_country]
84
- with st.status(f"Llama 3.1 70B is profiling {target_country}...", expanded=True):
85
- g_news = fetch_google_news(f"{target_country} controversy safety", limit=data_vol//2)
86
- l_news = fetch_google_news(target_country, geo=conf['geo'], lang=conf['lang'], limit=data_vol//2)
87
- feed_text = "\n".join([f"- {n['title']}" for n in g_news + l_news])
88
-
89
- system_prompt = f"""
90
- You are a Strategic Risk Intelligence Officer specializing in Llama 3 Policy Analysis.
91
- Target Market: {target_country}. OUTPUT MUST BE IN ENGLISH ONLY.
92
-
93
- Analyze the following news and provide a JSON report:
94
- 1. 'guideline_threats': Specific violations (Harassment, Dangerous Acts, Hate Speech, etc.) with WHY/HOW.
95
- 2. 'vulnerable_demographics': Risks to Minors, Gender-based issues, or Ethnic targeting.
96
- 3. 'propagation_mechanism': How it spreads (Viral, Bot, etc.)
97
- 4. 'visual_threat': Visual content or symbols to watch out for.
98
- 5. 'mitigation_strategy': Precise action for moderators.
99
- """
100
-
101
- # Llama 3 호좜
102
- res = client.chat.completions.create(
103
- model="llama-3.1-70b-versatile",
104
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": feed_text}],
105
- response_format={"type": "json_object"} # JSON λͺ¨λ“œ κ°•μ œ
106
- )
107
- report_data = json.loads(res.choices[0].message.content)
108
-
109
- st.markdown(f"## πŸ“‘ Llama 3 Strategic Report: {target_country}")
110
 
111
- # 상세 데이터 λ Œλ”λ§
112
- c1, c2 = st.columns(2)
113
- with c1:
114
- st.error(f"**🚫 Guideline Threats:**\n{report_data.get('guideline_threats')}")
115
- st.warning(f"**πŸ‘₯ Vulnerable Groups:**\n{report_data.get('vulnerable_demographics')}")
116
- with c2:
117
- st.info(f"**βš™οΈ Propagation:** {report_data.get('propagation_mechanism')}")
118
- st.info(f"**πŸ“Έ Visual Warning:** {report_data.get('visual_threat')}")
 
 
 
119
 
120
- st.success(f"**πŸ›‘οΈ Strategic Mitigation:** {report_data.get('mitigation_strategy')}")
 
 
 
 
 
1
  import streamlit as st
2
  import feedparser
3
  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="Llama3 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"]
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.")