Spaces:
Sleeping
Sleeping
Update app.py
Browse files8 unmodified lines91011121314158 unmodified lines2425262728299 unmodified lines3940414243444546474849505152535455565 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761778 unmodified linesimport plotly.express as px# --- Page Config ---st.set_page_config(page_title="Global Issue Intelligence", page_icon="π‘", layout="wide")# --- π API Key Load ---api_key = os.environ.get("GROQ_API_KEY")8 unmodified lines# Groq ν΄λΌμ΄μΈνΈ μ΄κΈ°νclient = Groq(api_key=api_key)# --- Monitoring Nations ---MONITOR_LIST = {"South Korea": {"geo": "KR", "lang": "ko"}, "USA": {"geo": "US", "lang": "en"},9 unmodified linesfeed = feedparser.parse(url)return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]st.title("π‘ Omni-Watch: Global Issue Deep-Dive Center")st.caption("Strategic Intelligence for Community Guidelines & Risk Mitigation")st.markdown("---")tab_search, tab_report = st.tabs(["π Global Issue Tracking & Deep Report", "π National Deep-Dive Analysis"])# --- [Tab 1: Global Issue Tracking & Deep Report] ---with tab_search:st.subheader("Global Risk Propagation & Intelligence Analysis")col_k1, col_k2 = st.columns([3, 1])with col_k1:search_keyword = st.text_input("Enter Issue Keyword to Analyze Globally", "Cyber Attacks")with col_k2:st.write("")run_global = st.button("πΊοΈ Global Deep Scan", type="primary", use_container_width=True)5 unmodified linesstatus_msg = st.empty()for i, (name, conf) in enumerate(MONITOR_LIST.items()):status_msg.text(f"Extracting Intelligence from {name}...")news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=3)if news:titles = "\n".join([n['title'] for n in news])all_captured_news.append(f"--- {name} News ---\n{titles}")# μμ λ λΆλΆ: client.chat.completions.createtry:res = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "user", "content": f"Risk score (0-100) for '{search_keyword}' in {name} news: {titles}. Return ONLY the integer."}],max_tokens=10)score_text = res.choices[0].message.contentscore = int(''.join(filter(str.isdigit, score_text)))except: score = 50results.append({"Country": name, "Risk": score})progress.progress((i + 1) / len(MONITOR_LIST))status_msg.empty()df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)# μκ°νfig = px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds", title=f"Global Risk Heatmap: {search_keyword}")st.plotly_chart(fig, use_container_width=True)# [Global Deep-Dive Report Section]st.divider()st.subheader(f"π§ Llama 3 Global Intelligence Report: {search_keyword}")with st.spinner("Synthesizing Global Intelligence..."):combined_news = "\n\n".join(all_captured_news)global_system_prompt = f"""You are a Global Strategic Intelligence Officer. Analyze the propagation of '{search_keyword}' across multiple countries.Your report must be long, professional, and insightful.REQUIREMENTS (Output in English):1. 'Global Narrative': Detailed summary of how this issue is trending (300+ words).2. 'Contagion & Cross-Border Impact': How the issue flows between nations.3. 'Social Vulnerability Map': Identify risks to minors, women, and ethnic groups globally.4. 'Policy Recommendations': High-level moderation and guideline strategies."""# μμ λ λΆλΆ: client.chat.completions.createglobal_res = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "system", "content": global_system_prompt}, {"role": "user", "content": combined_news}],max_tokens=3000,temperature=0.3)global_report = global_res.choices[0].message.contentst.markdown(f"<div style='background-color: #e1f5fe; padding: 25px; border-radius: 10px; border-left: 5px solid #0288d1;'>{global_report}</div>", unsafe_allow_html=True)# --- [Tab 2: National Deep-Dive Analysis] ---with tab_report:col_d1, col_d2 = st.columns([1, 4])with col_d1:st.subheader("Target Selection")target_country = st.selectbox("Market", list(MONITOR_LIST.keys()))data_vol = st.slider("Intel Depth", 10, 60, 30)run_deep = st.button("π Analyze Market", use_container_width=True)if run_deep:conf = MONITOR_LIST[target_country]with st.status(f"Llama 3 Deep-Dive: {target_country}...", expanded=True):g_news = fetch_google_news(f"{target_country} social controversy", 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])deep_system_prompt = f"""Identify Community Guideline violations and risks for {target_country}.Structure your report as a JSON object:{{"risk_score": 0-100,"executive_report": "300+ word detailed English report","policy_impact": "Details on which guidelines are violated and why","vulnerability_analysis": "Risk assessment for minors, gender, and ethnicity","action_plan": "5 specific tactical steps"}}"""# μμ λ λΆλΆ: client.chat.completions.create + response_formatdeep_res = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "system", "content": deep_system_prompt}, {"role": "user", "content": feed_text}],response_format={"type": "json_object"})data = json.loads(deep_res.choices[0].message.content)# UI μΆλ ₯st.header(f"π National Intelligence: {target_country}")m1, m2 = st.columns([1, 4])m1.metric("Risk Score", f"{data['risk_score']}/100")st.subheader("π Executive Summary")st.markdown(f"<div style='background-color: #f0f2f6; padding: 20px; border-radius: 10px;'>{data['executive_report']}</div>", unsafe_allow_html=True)c_a, c_b = st.columns(2)with c_a:st.markdown("### π« Policy & Vulnerability")st.write(data['policy_impact'])st.warning(data['vulnerability_analysis'])with c_b:st.markdown("### π‘οΈ Tactical Action Plan")st.success(data['action_plan'])8 unmodified lines91011121314158 unmodified lines2425262728293031329 unmodified lines4243444546474849505152535455565758595 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241258 unmodified linesimport plotly.express as px# --- Page Config ---st.set_page_config(page_title="Global Issue Intelligence Center", page_icon="π‘", layout="wide")# --- π API Key Load ---api_key = os.environ.get("GROQ_API_KEY")8 unmodified lines# Groq ν΄λΌμ΄μΈνΈ μ΄κΈ°νclient = Groq(api_key=api_key)# μ΅μ λͺ¨λΈλͺ μ μ (Llama 3.3 70B)CURRENT_MODEL = "llama-3.3-70b-versatile"# --- Monitoring Nations ---MONITOR_LIST = {"South Korea": {"geo": "KR", "lang": "ko"}, "USA": {"geo": "US", "lang": "en"},9 unmodified linesfeed = feedparser.parse(url)return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]st.title("π‘ Omni-Watch: Global Intelligence (Llama 3.3)")st.caption("Strategic Intelligence for Policy & Risk Management")st.markdown("---")tab_search, tab_report = st.tabs(["π Global Issue Tracking", "π National Deep-Dive"])# --- [Tab 1: Global Issue Tracking] ---with tab_search:st.subheader("Global Risk Propagation & Deep Intelligence")col_k1, col_k2 = st.columns([3, 1])with col_k1:search_keyword = st.text_input("Enter Issue Keyword", "Digital Misinformation")with col_k2:st.write("")run_global = st.button("πΊοΈ Global Deep Scan", type="primary", use_container_width=True)5 unmodified linesstatus_msg = st.empty()for i, (name, conf) in enumerate(MONITOR_LIST.items()):status_msg.text(f"Extracting Intel from {name}...")news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=3)if news:titles = "\n".join([n['title'] for n in news])all_captured_news.append(f"--- {name} News ---\n{titles}")try:res = client.chat.completions.create(model=CURRENT_MODEL,messages=[{"role": "user", "content": f"Score 0-100 for '{search_keyword}' in {name}: {titles}. ONLY INTEGER."}],max_tokens=10)score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))except: score = 50results.append({"Country": name, "Risk": score})progress.progress((i + 1) / len(MONITOR_LIST))status_msg.empty()df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"), use_container_width=True)st.divider()st.subheader(f"π§ Llama 3.3 Global Intelligence Report")with st.spinner("Synthesizing Massive Data..."):combined_news = "\n\n".join(all_captured_news)global_res = client.chat.completions.create(model=CURRENT_MODEL,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}],max_tokens=3000)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)# --- [Tab 2: National Deep-Dive] ---with tab_report:col_d1, col_d2 = st.columns([1, 4])with col_d1:target_country = st.selectbox("Market", list(MONITOR_LIST.keys()))data_vol = st.slider("Depth", 10, 60, 30)run_deep = st.button("π Analyze Market", use_container_width=True)if run_deep:conf = MONITOR_LIST[target_country]with st.status(f"Llama 3.3 Deep-Dive: {target_country}...", expanded=True):news = fetch_google_news(f"{target_country} social controversy", limit=data_vol)feed_text = "\n".join([f"- {n['title']}" for n in news])deep_res = client.chat.completions.create(model=CURRENT_MODEL,messages=[{"role": "system", "content": "Analyze Community Guideline violations & demographics (Minors, Women, Race). Output JSON."}, {"role": "user", "content": feed_text}],response_format={"type": "json_object"})data = json.loads(deep_res.choices[0].message.content)st.header(f"π Intelligence Report: {target_country}")st.markdown(f"<div style='background-color: #f0f2f6; padding: 20px; border-radius: 10px;'>{data.get('executive_report', 'Processing...')}</div>", unsafe_allow_html=True)st.warning(f"**Policy & Demographics Risk:** {data.get('vulnerability_analysis', 'N/A')}")
app.py+31-83