benjamin5607 commited on
Commit
2edfdfa
Β·
verified Β·
1 Parent(s): 06690f0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -57
app.py CHANGED
@@ -6,51 +6,62 @@ import pandas as pd
6
  import json
7
  import os
8
  import plotly.express as px
9
- import plotly.graph_objects as go
10
 
11
  # --- Page Config ---
12
  st.set_page_config(page_title="Omni-Watch Intelligence Pro", 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
  CURRENT_MODEL = "llama-3.3-70b-versatile"
26
 
27
- # --- 🌍 UN Geoscheme ---
28
  REGION_MAP = {
29
- "Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "TH", "IN", "ID", "PH", "AU"],
30
- "Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL"],
31
- "Americas": ["US", "CA", "BR", "MX", "AR", "CO", "VE"],
32
- "ME & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR"]
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", "link": e.link} for e in feed.entries[:limit]]
40
-
41
- st.title("πŸ“‘ Omni-Watch: Market & Policy Intelligence Pro")
42
- st.caption("Universal Global Issue Tracker with Advanced Visualization & Evidence Feed")
 
 
 
 
 
 
 
 
 
43
  st.markdown("---")
44
 
45
- tab_search, tab_deep = st.tabs(["🌐 Global Issue Tracking", "πŸ” National Deep-Dive"])
46
 
47
  # --- [Tab 1: Global Issue Tracking] ---
48
- with tab_search:
49
- st.subheader("Global Risk Propagation & Market Insight Scan")
50
  col_k1, col_k2 = st.columns([3, 1])
51
  with col_k1:
52
- search_keyword = st.text_input("Enter Issue Keyword", "Deepfake Misinformation")
53
- selected_regions = st.multiselect("Select Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
54
  with col_k2:
55
  st.write("")
56
  run_global = st.button("πŸ—ΊοΈ Deep Global Scan", type="primary", use_container_width=True)
@@ -62,16 +73,18 @@ with tab_search:
62
  results = []
63
  all_captured_news = []
64
  progress = st.progress(0)
 
65
 
66
  for i, geo_code in enumerate(target_countries):
 
67
  news = fetch_google_news(search_keyword, geo=geo_code, limit=3)
68
  if news:
69
  titles = "\n".join([n['title'] for n in news])
70
- all_captured_news.extend(news) # λ‰΄μŠ€ μˆ˜μ§‘
71
  try:
72
  res = client.chat.completions.create(
73
  model=CURRENT_MODEL,
74
- messages=[{"role": "user", "content": f"Risk score (0-100) for '{search_keyword}' in {geo_code}: {titles}. ONLY INT."}],
75
  max_tokens=10
76
  )
77
  score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
@@ -79,55 +92,83 @@ with tab_search:
79
  results.append({"Country": geo_code, "Risk": score})
80
  progress.progress((i + 1) / len(target_countries))
81
 
 
82
  df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
83
-
84
- # πŸ“Š Visualization 1: Heatmap Bar Chart
85
- st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk",
86
- color_continuous_scale="Reds", text_auto=True,
87
- title=f"Global Risk Concentration: {search_keyword}"), use_container_width=True)
88
 
89
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
- # 🧠 Intelligence Report Generation
92
- with st.spinner("Synthesizing Strategic Report..."):
93
- news_summary = "\n".join([n['title'] for n in all_captured_news[:20]])
94
- global_system_prompt = f"""
95
- Analyze '{search_keyword}' and return a JSON object:
 
 
 
 
 
 
 
 
 
 
 
96
  {{
97
- "summary": "300+ words report",
98
- "market_table": {{"TikTok": "insight", "YouTube": "insight", "Meta": "insight", "X": "insight"}},
99
- "demographics": {{"Minors": "risk", "Women": "risk", "Ethnic": "risk"}},
100
- "guidelines": ["violation 1", "violation 2"]
 
 
 
 
 
 
 
101
  }}
 
102
  """
103
- global_res = client.chat.completions.create(
104
  model=CURRENT_MODEL,
105
- messages=[{"role": "system", "content": global_system_prompt}, {"role": "user", "content": news_summary}],
106
  response_format={"type": "json_object"}
107
  )
108
- data = json.loads(global_res.choices[0].message.content)
109
-
110
- # πŸ“„ Structured Report UI
111
- st.markdown(f"### πŸ“‘ Executive Intelligence: {search_keyword}")
112
- st.info(data['summary'])
113
 
114
- # πŸ“± Market Insights Table
115
- st.markdown("#### πŸ“± Platform-Specific Tactics")
116
- st.table(pd.DataFrame(data['market_table'].items(), columns=["Platform", "Strategic Insight"]))
117
-
118
-
119
 
120
- # πŸ‘₯ Demographic Vulnerability Table
121
- st.markdown("#### πŸ‘₯ Vulnerability Assessment")
122
- st.table(pd.DataFrame(data['demographics'].items(), columns=["Target Group", "Risk Analysis"]))
 
 
 
 
123
 
124
- # 🚫 Guideline Violations
125
- st.error(f"**Critical Policy Violations:** {', '.join(data['guidelines'])}")
126
-
127
- # πŸ“° Evidence Feed (μ°Έκ³  λ‰΄μŠ€ 기사)
128
  st.divider()
129
- st.subheader("πŸ“° Reference Evidence Feed")
130
- st.dataframe(pd.DataFrame(all_captured_news)[['source', 'title', 'link']], use_container_width=True)
131
-
132
- # --- [Tab 2: National Deep-Dive] ---
133
- # (Tab 2도 μœ„μ™€ λ™μΌν•œ ꡬ쑰둜 μ‹œκ°ν™” 및 ν…Œμ΄λΈ” 둜직 적용)
 
6
  import json
7
  import os
8
  import plotly.express as px
9
+ import time
10
 
11
  # --- Page Config ---
12
  st.set_page_config(page_title="Omni-Watch Intelligence Pro", page_icon="πŸ“‘", layout="wide")
13
 
14
  # --- API Key Load ---
15
+ # Hugging Face Secrets에 'GROQ_API_KEY'λ₯Ό λ°˜λ“œμ‹œ μž…λ ₯ν•˜μ„Έμš”.
16
  api_key = os.environ.get("GROQ_API_KEY")
17
  if not api_key:
18
  try: api_key = st.secrets["GROQ_API_KEY"]
19
  except: pass
20
 
21
  if not api_key:
22
+ st.error("πŸ”‘ GROQ_API_KEY Missing. Please check your Secrets settings.")
23
  st.stop()
24
 
25
  client = Groq(api_key=api_key)
26
  CURRENT_MODEL = "llama-3.3-70b-versatile"
27
 
28
+ # --- 🌍 UN Geoscheme Data ---
29
  REGION_MAP = {
30
+ "Asia & Pacific": ["KR", "JP", "CN", "VN", "MY", "TH", "IN", "ID", "PH", "AU", "SG"],
31
+ "Europe": ["GB", "FR", "DE", "IT", "ES", "UA", "RU", "PL", "NL", "SE", "NO"],
32
+ "Americas": ["US", "CA", "BR", "MX", "AR", "CO", "CL", "VE"],
33
+ "Middle East & Africa": ["IL", "SA", "AE", "EG", "ZA", "NG", "TR", "QA", "KE"]
34
  }
35
 
36
+ # --- Helper: Google News RSS Fetcher ---
37
  def fetch_google_news(query, geo="US", lang="en", limit=10):
38
  encoded = urllib.parse.quote(query)
39
  url = f"https://news.google.com/rss/search?q={encoded}&hl={lang}&gl={geo}&ceid={geo}:{lang}"
40
  feed = feedparser.parse(url)
41
+ articles = []
42
+ for entry in feed.entries[:limit]:
43
+ articles.append({
44
+ "title": entry.title,
45
+ "link": entry.link,
46
+ "source": entry.source.title if 'source' in entry else "Google News",
47
+ "date": entry.published if 'published' in entry else "Recent"
48
+ })
49
+ return articles
50
+
51
+ # --- UI Setup ---
52
+ st.title("πŸ“‘ Omni-Watch: Universal Risk & Market Intelligence")
53
+ st.caption("Monitoring Global Propagation & National Risk Forensics with Llama 3.3 Intelligence")
54
  st.markdown("---")
55
 
56
+ tab_global, tab_national = st.tabs(["🌐 Global Issue Tracking", "πŸ” National Top 5 Risk Deep-Dive"])
57
 
58
  # --- [Tab 1: Global Issue Tracking] ---
59
+ with tab_global:
60
+ st.subheader("Global Risk Propagation & Strategic Policy Report")
61
  col_k1, col_k2 = st.columns([3, 1])
62
  with col_k1:
63
+ search_keyword = st.text_input("Enter Issue Keyword to Analyze Globally", "Cyber Attacks")
64
+ selected_regions = st.multiselect("Select Target Regions", list(REGION_MAP.keys()), default=list(REGION_MAP.keys()))
65
  with col_k2:
66
  st.write("")
67
  run_global = st.button("πŸ—ΊοΈ Deep Global Scan", type="primary", use_container_width=True)
 
73
  results = []
74
  all_captured_news = []
75
  progress = st.progress(0)
76
+ status_msg = st.empty()
77
 
78
  for i, geo_code in enumerate(target_countries):
79
+ status_msg.text(f"Scanning {geo_code} for '{search_keyword}'...")
80
  news = fetch_google_news(search_keyword, geo=geo_code, limit=3)
81
  if news:
82
  titles = "\n".join([n['title'] for n in news])
83
+ all_captured_news.extend(news)
84
  try:
85
  res = client.chat.completions.create(
86
  model=CURRENT_MODEL,
87
+ messages=[{"role": "user", "content": f"Score 0-100 risk for '{search_keyword}' in {geo_code}: {titles}. ONLY INT."}],
88
  max_tokens=10
89
  )
90
  score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
 
92
  results.append({"Country": geo_code, "Risk": score})
93
  progress.progress((i + 1) / len(target_countries))
94
 
95
+ status_msg.empty()
96
  df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
97
+ st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds", title=f"Global Risk Heatmap: {search_keyword}"), use_container_width=True)
 
 
 
 
98
 
99
+ st.divider()
100
+ st.subheader(f"🧠 Llama 3.3 Global Intelligence Report")
101
+ with st.spinner("Synthesizing Strategic Policy Risks..."):
102
+ news_feed = "\n".join([n['title'] for n in all_captured_news[:20]])
103
+ global_prompt = f"""
104
+ Analyze the global propagation of '{search_keyword}'.
105
+ Structure your report with:
106
+ 1. 'global_summary': Long professional report (300+ words).
107
+ 2. 'market_insights': Table-ready data for TikTok, YouTube, Meta, X.
108
+ 3. 'policy_risks': Violations of Community Guidelines and WHY.
109
+ 4. 'demographics': Risks for Minors, Women, and Ethnic groups.
110
+ 5. 'action_plan': Tactical moderation steps.
111
+ """
112
+ res = client.chat.completions.create(
113
+ model=CURRENT_MODEL,
114
+ messages=[{"role": "system", "content": global_prompt}, {"role": "user", "content": news_feed}]
115
+ )
116
+ st.markdown(f"<div style='background-color: #e3f2fd; padding: 25px; border-radius: 10px; border-left: 5px solid #1976d2;'>{res.choices[0].message.content}</div>", unsafe_allow_html=True)
117
+
118
+ st.subheader("πŸ“° Reference News Feed")
119
+ st.dataframe(pd.DataFrame(all_captured_news)[['source', 'title', 'link']], use_container_width=True)
120
 
121
+ # --- [Tab 2: National Deep-Dive (Top 5 Risks)] ---
122
+ with tab_national:
123
+ st.subheader("Specific Country Top 5 Risk Intelligence")
124
+ col_d1, col_d2 = st.columns([1, 4])
125
+ with col_d1:
126
+ target_geo = st.text_input("Enter Country Code (ISO)", "KR").upper()
127
+ run_deep = st.button("πŸš€ Analyze Market", use_container_width=True, type="primary")
128
+
129
+ if run_deep:
130
+ with st.status(f"Analytic Process for {target_geo}...", expanded=True) as status:
131
+ news = fetch_google_news(f"{target_geo} social controversy risk", geo=target_geo, limit=30)
132
+ news_titles = "\n".join([f"- {n['title']}" for n in news])
133
+
134
+ system_prompt = f"""
135
+ Identify the TOP 5 most critical social/platform risks in {target_geo}.
136
+ Return ONLY a JSON object:
137
  {{
138
+ "risks": [
139
+ {{
140
+ "rank": 1,
141
+ "title": "Short title",
142
+ "score": 0-100,
143
+ "summary": "300+ word detailed report",
144
+ "violation": "Guideline breached & WHY",
145
+ "demographics": "Specific vulnerability (Minors, Women, etc.)",
146
+ "tactical_action": "Action for TikTok, YT, Meta"
147
+ }}
148
+ ]
149
  }}
150
+ Identify exactly 5 risks.
151
  """
152
+ res = client.chat.completions.create(
153
  model=CURRENT_MODEL,
154
+ messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": news_titles}],
155
  response_format={"type": "json_object"}
156
  )
157
+ data = json.loads(res.choices[0].message.content)
158
+ status.update(label="Analysis Complete", state="complete")
 
 
 
159
 
160
+ # πŸ“Š Visualization
161
+ df_risks = pd.DataFrame(data['risks'])
162
+ st.plotly_chart(px.bar(df_risks, x='score', y='title', orientation='h', color='score', color_continuous_scale='Reds', title=f"{target_geo} Top 5 Severity Map"), use_container_width=True)
 
 
163
 
164
+ for r in data['risks']:
165
+ with st.expander(f"🚩 Rank {r['rank']}: {r['title']} (Severity: {r['score']})", expanded=(r['rank']==1)):
166
+ st.markdown(f"**πŸ“ Strategic Summary:** {r['summary']}")
167
+ st.table(pd.DataFrame({
168
+ "Category": ["Guideline Violation", "Target Demographics", "Tactical Action"],
169
+ "Analysis": [r['violation'], r['demographics'], r['tactical_action']]
170
+ }))
171
 
 
 
 
 
172
  st.divider()
173
+ st.subheader("πŸ“° Evidence Feed")
174
+ st.dataframe(pd.DataFrame(news)[['source', 'title', 'link']], use_container_width=True)