Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314154 unmodified lines2021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110import streamlit as stimport feedparserimport urllib.parsefrom huggingface_hub import InferenceClientimport pandas as pdimport jsonimport timeimport osimport plotly.express as px# --- Page Config ---st.set_page_config(page_title="Strategic Risk Intelligence", page_icon="๐ต๏ธ", layout="wide")# --- ๐ Global Monitor List ---MONITOR_LIST = {4 unmodified lines"Vietnam": {"geo": "VN", "lang": "vi"}, "Ukraine": {"geo": "UA", "lang": "uk"}}# --- API Load ---api_key = os.environ.get("HF_KEY")if not api_key:try: api_key = st.secrets["HF_KEY"]except: passdef fetch_google_news(query, geo="US", lang="en", limit=10):encoded = urllib.parse.quote(query)url = f"https://news.google.com/rss/search?q={encoded}&hl={lang}&gl={geo}&ceid={geo}:{lang}"feed = feedparser.parse(url)return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]client = InferenceClient(api_key=api_key)# --- UI ---st.title("๐ต๏ธ Strategic Intelligence: Policy & Demographics Risk")st.markdown("---")tab_global, tab_deep = st.tabs(["๐ Propagation Tracker", "๐ Policy & Vulnerability Analysis"])# --- [Tab 1: Global Keyword Tracker] ---with tab_global:search_keyword = st.text_input("Enter Issue Keyword (e.g. 'Deepfake', 'Hate Speech', 'Child Safety')", "Child Safety")if st.button("๐บ๏ธ Analyze Global Propagation", type="primary"):# (๊ธฐ์กด ๊ธ๋ก๋ฒ ์ค์บ ๋ก์ง - ์๊ฐํ ํฌํจ)results = []for name, conf in MONITOR_LIST.items():news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=5)if news:prompt = f"Risk score (0-100) for '{search_keyword}' in {name}. Return ONLY integer."try:res = client.chat_completion(model="Qwen/Qwen2.5-72B-Instruct", messages=[{"role": "user", "content": prompt}], max_tokens=10)score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))except: score = 50results.append({"Country": name, "Risk": score})st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Viridis"))# --- [Tab 2: Policy & Deep Intelligence (์ฌ์ฉ์ ์์ฒญ ๊ฐํ ๋ฒ์ )] ---with tab_deep:col_d1, col_d2 = st.columns([1, 4])with col_d1:target_country = st.selectbox("Market Selection", list(MONITOR_LIST.keys()))data_vol = st.slider("Intel Volume", 10, 60, 30)run_deep = st.button("๐ Generate Strategic Report", use_container_width=True)if run_deep:conf = MONITOR_LIST[target_country]with st.status("Profiling Policy Risks & Vulnerable Groups...", expanded=True) as status:g_news = fetch_google_news(f"{target_country} controversy safety risk", limit=data_vol//2)l_news = fetch_google_news(target_country, geo=conf['geo'], lang=conf['lang'], limit=data_vol//2)feed_text = "\n".join([f"- {n['title']}" for n in g_news + l_news])system_prompt = f"""You are a Global Trust & Safety Director. Analyze the following news for {target_country} and provide a high-level strategic report.REPORT REQUIREMENTS (MUST BE IN ENGLISH):1. 'guideline_threats': Identify specific violations (e.g., Harassment, Dangerous Acts, Child Safety, Hate Speech).- Explain WHY and HOW it violates specific platform policies.- Assign a Threat Level (Critical/High/Medium).2. 'vulnerable_demographics': Identify who is at risk:- Minors: Is there a risk of grooming, exploitation, or mental harm?- Gender: Is there gender-based violence or misogynistic content risk?- Race/Ethnicity/Nationality: Is there a risk of ethnic conflict or localized hate?3. 'propagation_mechanism': How will this spread? (e.g. coordinated bot attacks, organic viral outrage).4. 'mitigation_strategy': What should moderators do? (Keyword blocking, temporary shadowban, fact-check labels).5. 'visual_forensics': Describe images or symbols to watch out for."""res = client.chat_completion(model="Qwen/Qwen2.5-72B-Instruct",messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": feed_text}],max_tokens=3500)report_data = res.choices[0].message.contentstatus.update(label="Analysis Complete", state="complete")# UI ์ถ๋ ฅst.markdown(f"## ๐ National Stability & Safety Report: {target_country}")# Qwen์ด ํ ์คํธ๋ก ๋ณด๋ผ ๊ฒฝ์ฐ๋ฅผ ๋๋นํด ๋งํฌ๋ค์ด์ผ๋ก ๊น๋ํ๊ฒ ์ถ๋ ฅst.markdown(report_data)st.divider()st.caption(f"Sources captured from {target_country} local and global streams.")123456789101112131415164 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import streamlit as stimport feedparserimport urllib.parsefrom groq import Groq # Groq ์ ์ฉ ๋ผ์ด๋ธ๋ฌ๋ฆฌimport pandas as pdimport jsonimport timeimport osimport plotly.express as pximport random# --- Page Config ---st.set_page_config(page_title="Llama3 Risk Intelligence", page_icon="๐ฆ", layout="wide")# --- ๐ Global Monitor List ---MONITOR_LIST = {4 unmodified lines"Vietnam": {"geo": "VN", "lang": "vi"}, "Ukraine": {"geo": "UA", "lang": "uk"}}# --- 1. API Key Load (Groq) ---# ํ๊น ํ์ด์ค Secrets์ 'GROQ_API_KEY'๋ก ์ ์ฅํด๋์ธ์.api_key = os.environ.get("GROQ_API_KEY")if not api_key:try: api_key = st.secrets["GROQ_API_KEY"]except: pass# --- Helper: News Fetcher ---def fetch_google_news(query, geo="US", lang="en", limit=10):encoded = urllib.parse.quote(query)url = f"https://news.google.com/rss/search?q={encoded}&hl={lang}&gl={geo}&ceid={geo}:{lang}"feed = feedparser.parse(url)return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]# --- UI ---st.title("๐ฆ Llama 3: Strategic Risk Intelligence")st.caption("Powered by Llama 3.1 70B (via Groq) | Zero-Cost Infrastructure")if not api_key:st.error("๐ GROQ_API_KEY not found. Please set it in Settings.")st.stop()# Groq ํด๋ผ์ด์ธํธ ์ด๊ธฐํclient = Groq(api_key=api_key)tab_global, tab_deep = st.tabs(["๐ Propagation Tracker", "๐ Policy & Vulnerability Analysis"])# --- [Tab 1: Global Keyword Tracker] ---with tab_global:search_keyword = st.text_input("Enter Issue Keyword", "Digital Harassment")if st.button("๐บ๏ธ Analyze Global Propagation", type="primary"):results = []status_msg = st.empty()for name, conf in MONITOR_LIST.items():status_msg.text(f"Scanning {name} for '{search_keyword}'...")news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=5)if news: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']}"try:res = client.chat.completions.create(model="llama-3.1-70b-versatile",messages=[{"role": "user", "content": prompt}],max_tokens=10)score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))except: score = 50results.append({"Country": name, "Risk": score})status_msg.empty()st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"))# --- [Tab 2: Deep Intelligence (Llama 3 Logic)] ---with tab_deep:col_d1, col_d2 = st.columns([1, 4])with col_d1:target_country = st.selectbox("Market", list(MONITOR_LIST.keys()))data_vol = st.slider("Intel Volume", 10, 60, 30)run_deep = st.button("๐ Analyze Situation", use_container_width=True)if run_deep:conf = MONITOR_LIST[target_country]with st.status(f"Llama 3.1 70B is profiling {target_country}...", expanded=True):g_news = fetch_google_news(f"{target_country} controversy safety", limit=data_vol//2)l_news = fetch_google_news(target_country, geo=conf['geo'], lang=conf['lang'], limit=data_vol//2)feed_text = "\n".join([f"- {n['title']}" for n in g_news + l_news])system_prompt = f"""You are a Strategic Risk Intelligence Officer specializing in Llama 3 Policy Analysis.Target Market: {target_country}. OUTPUT MUST BE IN ENGLISH ONLY.Analyze the following news and provide a JSON report:1. 'guideline_threats': Specific violations (Harassment, Dangerous Acts, Hate Speech, etc.) with WHY/HOW.2. 'vulnerable_demographics': Risks to Minors, Gender-based issues, or Ethnic targeting.3. 'propagation_mechanism': How it spreads (Viral, Bot, etc.)4. 'visual_threat': Visual content or symbols to watch out for.5. 'mitigation_strategy': Precise action for moderators."""# Llama 3 ํธ์ถres = client.chat.completions.create(model="llama-3.1-70b-versatile",messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": feed_text}],response_format={"type": "json_object"} # JSON ๋ชจ๋ ๊ฐ์ )report_data = json.loads(res.choices[0].message.content)st.markdown(f"## ๐ Llama 3 Strategic Report: {target_country}")# ์์ธ ๋ฐ์ดํฐ ๋ ๋๋งc1, c2 = st.columns(2)with c1:st.error(f"**๐ซ Guideline Threats:**\n{report_data.get('guideline_threats')}")st.warning(f"**๐ฅ Vulnerable Groups:**\n{report_data.get('vulnerable_demographics')}")with c2:st.info(f"**โ๏ธ Propagation:** {report_data.get('propagation_mechanism')}")st.info(f"**๐ธ Visual Warning:** {report_data.get('visual_threat')}")st.success(f"**๐ก๏ธ Strategic Mitigation:** {report_data.get('mitigation_strategy')}")
app.py+56-46