benjamin5607 commited on
Commit
3b6b192
ยท
verified ยท
1 Parent(s): 387fd49

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -83
app.py CHANGED
@@ -9,9 +9,9 @@ import os
9
  import plotly.express as px
10
 
11
  # --- Page Config ---
12
- st.set_page_config(page_title="Omni-Watch Intelligence Pro", page_icon="๐Ÿ“ก", layout="wide")
13
 
14
- # --- ๐ŸŒ Strategic Nations ---
15
  MONITOR_LIST = {
16
  "South Korea": {"geo": "KR", "lang": "ko"}, "USA": {"geo": "US", "lang": "en"},
17
  "Japan": {"geo": "JP", "lang": "ja"}, "UK": {"geo": "GB", "lang": "en"},
@@ -32,122 +32,79 @@ def fetch_google_news(query, geo="US", lang="en", limit=10):
32
  feed = feedparser.parse(url)
33
  return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
34
 
 
 
35
  # --- UI ---
36
- st.title("๐Ÿ“ก Omni-Watch: Market Intelligence & Risk Radar")
37
  st.markdown("---")
38
 
39
- if not api_key:
40
- st.error("๐Ÿ”‘ HF_KEY Missing. Please set it in Settings.")
41
- st.stop()
42
-
43
- client = InferenceClient(api_key=api_key)
44
- tab_global, tab_deep = st.tabs(["๐ŸŒ Global Keyword Tracker", "๐Ÿ” Market Deep-Dive"])
45
 
46
  # --- [Tab 1: Global Keyword Tracker] ---
47
  with tab_global:
48
- st.subheader("Global Issue Propagation Analysis")
49
- col_k1, col_k2 = st.columns([3, 1])
50
- with col_k1:
51
- search_keyword = st.text_input("Enter Issue Keyword (e.g. 'Deepfake Scandal')", "Social Disruption")
52
- with col_k2:
53
- st.write("")
54
- run_global = st.button("๐Ÿ—บ๏ธ Run Global Scan", type="primary", use_container_width=True)
55
-
56
- if run_global:
57
  results = []
58
  for name, conf in MONITOR_LIST.items():
59
  news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=5)
60
  if news:
61
- prompt = f"Risk score (0-100) for '{search_keyword}' in {name} based on: {news[0]['title']}. Return ONLY integer."
62
  try:
63
  res = client.chat_completion(model="Qwen/Qwen2.5-72B-Instruct", messages=[{"role": "user", "content": prompt}], max_tokens=10)
64
  score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
65
  except: score = 50
66
- results.append({"Country": name, "Risk": score, "Top Headline": news[0]['title']})
67
-
68
- df_global = pd.DataFrame(results).sort_values("Risk", ascending=False)
69
- st.plotly_chart(px.bar(df_global, x="Country", y="Risk", color="Risk", color_continuous_scale="Reds"), use_container_width=True)
70
- st.table(df_global)
71
 
72
- # --- [Tab 2: Market Deep-Dive (์ธ์‚ฌ์ดํŠธ ๊ฐ•ํ™” ๋ฒ„์ „)] ---
73
  with tab_deep:
74
  col_d1, col_d2 = st.columns([1, 4])
75
  with col_d1:
76
- st.subheader("Control Panel")
77
- target_country = st.selectbox("Select Target Market", list(MONITOR_LIST.keys()))
78
- data_vol = st.slider("Analysis Depth", 10, 60, 30)
79
- run_deep = st.button("๐Ÿš€ Run Market Analysis", use_container_width=True)
80
 
81
  if run_deep:
82
  conf = MONITOR_LIST[target_country]
83
- with st.status(f"Collecting Deep Insights for {target_country}...", expanded=True) as status:
84
- g_news = fetch_google_news(f"{target_country} social media trend controversy", limit=data_vol//2)
85
  l_news = fetch_google_news(target_country, geo=conf['geo'], lang=conf['lang'], limit=data_vol//2)
86
  feed_text = "\n".join([f"- {n['title']}" for n in g_news + l_news])
 
87
 
88
- #
89
-
90
  system_prompt = f"""
91
- You are a Senior Strategic Analyst for Global Social Media Platforms.
92
- Target Market: {target_country}
93
 
94
- Analyze the headlines and provide a DETAILED Market Insight Report in English.
95
- Include:
96
- 1. 'viral_velocity': 0-100.
97
- 2. 'market_trend': Current social media content trend in this market related to the issue.
98
- 3. 'platform_insights': Specific risks and actionable advice for:
99
- - TikTok (Short-form, algorithm-driven viral risk)
100
- - YouTube (Long-form, misinformation, live stream risk)
101
- - Meta/IG (Community-driven, image/ad-based risk)
102
- - X (Breaking news, bot-driven polarization risk)
103
- 4. 'timeline_prediction': 48h outlook.
104
- 5. 'visual_threat': Describe specific imagery types likely to go viral.
105
  """
106
 
107
  res = client.chat_completion(
108
  model="Qwen/Qwen2.5-72B-Instruct",
109
  messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": feed_text}],
110
- max_tokens=3000
111
  )
112
- # JSON ํŒŒ์‹ฑ ์•ˆ์ „์žฅ์น˜
113
- try:
114
- data = json.loads(res.choices[0].message.content.replace("```json", "").replace("```", "").strip())
115
- except:
116
- st.error("AI Response Parsing Error. Showing raw text instead.")
117
- st.write(res.choices[0].message.content)
118
- st.stop()
119
- status.update(label="Market Insight Generated", state="complete")
120
 
121
  # UI ์ถœ๋ ฅ
122
- m1, m2, m3 = st.columns(3)
123
- m1.metric("Viral Velocity", f"{data['viral_velocity']}/100")
124
- m2.metric("Market Trend", "๐Ÿ”ฅ Volatile" if data['viral_velocity'] > 70 else "โš–๏ธ Stable")
125
- m3.metric("Timeline (48h)", data['timeline_prediction'])
126
-
127
- st.markdown(f"### ๐Ÿ“‘ Deep Market Report: {target_country}")
128
- st.info(f"**Current Trend:** {data['market_trend']}")
129
 
130
- # ํ”Œ๋žซํผ๋ณ„ ์ƒ์„ธ ์ธ์‚ฌ์ดํŠธ ์นด๋“œ (๋ณด์™„๋œ ๋ถ€๋ถ„)
131
- st.markdown("#### ๐Ÿ“ฑ Platform-Specific Tactical Insights")
132
- p1, p2 = st.columns(2)
133
- p3, p4 = st.columns(2)
134
 
135
- with p1:
136
- with st.container(border=True):
137
- st.markdown("**๐ŸŽต TikTok Insight**")
138
- st.write(data['platform_insights'].get('TikTok', 'N/A'))
139
- with p2:
140
- with st.container(border=True):
141
- st.markdown("**โ–ถ๏ธ YouTube Insight**")
142
- st.write(data['platform_insights'].get('YouTube', 'N/A'))
143
- with p3:
144
- with st.container(border=True):
145
- st.markdown("**๐Ÿ“ธ Meta / Instagram Insight**")
146
- st.write(data['platform_insights'].get('Meta/IG', 'N/A'))
147
- with p4:
148
- with st.container(border=True):
149
- st.markdown("**๐Ÿฆ X (Twitter) Insight**")
150
- st.write(data['platform_insights'].get('X', 'N/A'))
151
 
152
  st.divider()
153
- st.error(f"**โš ๏ธ Visual Threat Forecast:** {data['visual_threat']}")
 
9
  import plotly.express as px
10
 
11
  # --- Page Config ---
12
+ st.set_page_config(page_title="Strategic Risk Intelligence", page_icon="๐Ÿ•ต๏ธ", layout="wide")
13
 
14
+ # --- ๐ŸŒ Global Monitor List ---
15
  MONITOR_LIST = {
16
  "South Korea": {"geo": "KR", "lang": "ko"}, "USA": {"geo": "US", "lang": "en"},
17
  "Japan": {"geo": "JP", "lang": "ja"}, "UK": {"geo": "GB", "lang": "en"},
 
32
  feed = feedparser.parse(url)
33
  return [{"title": e.title, "source": e.source.title if 'source' in e else "G-News"} for e in feed.entries[:limit]]
34
 
35
+ client = InferenceClient(api_key=api_key)
36
+
37
  # --- UI ---
38
+ st.title("๐Ÿ•ต๏ธ Strategic Intelligence: Policy & Demographics Risk")
39
  st.markdown("---")
40
 
41
+ tab_global, tab_deep = st.tabs(["๐ŸŒ Propagation Tracker", "๐Ÿ“Š Policy & Vulnerability Analysis"])
 
 
 
 
 
42
 
43
  # --- [Tab 1: Global Keyword Tracker] ---
44
  with tab_global:
45
+ search_keyword = st.text_input("Enter Issue Keyword (e.g. 'Deepfake', 'Hate Speech', 'Child Safety')", "Child Safety")
46
+ if st.button("๐Ÿ—บ๏ธ Analyze Global Propagation", type="primary"):
47
+ # (๊ธฐ์กด ๊ธ€๋กœ๋ฒŒ ์Šค์บ” ๋กœ์ง - ์‹œ๊ฐํ™” ํฌํ•จ)
 
 
 
 
 
 
48
  results = []
49
  for name, conf in MONITOR_LIST.items():
50
  news = fetch_google_news(f"{name} {search_keyword}", geo=conf['geo'], lang=conf['lang'], limit=5)
51
  if news:
52
+ prompt = f"Risk score (0-100) for '{search_keyword}' in {name}. Return ONLY integer."
53
  try:
54
  res = client.chat_completion(model="Qwen/Qwen2.5-72B-Instruct", messages=[{"role": "user", "content": prompt}], max_tokens=10)
55
  score = int(''.join(filter(str.isdigit, res.choices[0].message.content)))
56
  except: score = 50
57
+ results.append({"Country": name, "Risk": score})
58
+ st.plotly_chart(px.bar(pd.DataFrame(results), x="Country", y="Risk", color="Risk", color_continuous_scale="Viridis"))
 
 
 
59
 
60
+ # --- [Tab 2: Policy & Deep Intelligence (์‚ฌ์šฉ์ž ์š”์ฒญ ๊ฐ•ํ™” ๋ฒ„์ „)] ---
61
  with tab_deep:
62
  col_d1, col_d2 = st.columns([1, 4])
63
  with col_d1:
64
+ target_country = st.selectbox("Market Selection", list(MONITOR_LIST.keys()))
65
+ data_vol = st.slider("Intel Volume", 10, 60, 30)
66
+ run_deep = st.button("๐Ÿš€ Generate Strategic Report", use_container_width=True)
 
67
 
68
  if run_deep:
69
  conf = MONITOR_LIST[target_country]
70
+ with st.status("Profiling Policy Risks & Vulnerable Groups...", expanded=True) as status:
71
+ g_news = fetch_google_news(f"{target_country} controversy safety risk", limit=data_vol//2)
72
  l_news = fetch_google_news(target_country, geo=conf['geo'], lang=conf['lang'], limit=data_vol//2)
73
  feed_text = "\n".join([f"- {n['title']}" for n in g_news + l_news])
74
+
75
 
76
+
 
77
  system_prompt = f"""
78
+ You are a Global Trust & Safety Director. Analyze the following news for {target_country} and provide a high-level strategic report.
 
79
 
80
+ REPORT REQUIREMENTS (MUST BE IN ENGLISH):
81
+ 1. 'guideline_threats': Identify specific violations (e.g., Harassment, Dangerous Acts, Child Safety, Hate Speech).
82
+ - Explain WHY and HOW it violates specific platform policies.
83
+ - Assign a Threat Level (Critical/High/Medium).
84
+ 2. 'vulnerable_demographics': Identify who is at risk:
85
+ - Minors: Is there a risk of grooming, exploitation, or mental harm?
86
+ - Gender: Is there gender-based violence or misogynistic content risk?
87
+ - Race/Ethnicity/Nationality: Is there a risk of ethnic conflict or localized hate?
88
+ 3. 'propagation_mechanism': How will this spread? (e.g. coordinated bot attacks, organic viral outrage).
89
+ 4. 'mitigation_strategy': What should moderators do? (Keyword blocking, temporary shadowban, fact-check labels).
90
+ 5. 'visual_forensics': Describe images or symbols to watch out for.
91
  """
92
 
93
  res = client.chat_completion(
94
  model="Qwen/Qwen2.5-72B-Instruct",
95
  messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": feed_text}],
96
+ max_tokens=3500
97
  )
98
+ report_data = res.choices[0].message.content
99
+ status.update(label="Analysis Complete", state="complete")
 
 
 
 
 
 
100
 
101
  # UI ์ถœ๋ ฅ
102
+ st.markdown(f"## ๐Ÿ“‘ National Stability & Safety Report: {target_country}")
103
+
104
+ # Qwen์ด ํ…์ŠคํŠธ๋กœ ๋ณด๋‚ผ ๊ฒฝ์šฐ๋ฅผ ๋Œ€๋น„ํ•ด ๋งˆํฌ๋‹ค์šด์œผ๋กœ ๊น”๋”ํ•˜๊ฒŒ ์ถœ๋ ฅ
105
+ st.markdown(report_data)
 
 
 
106
 
 
 
 
 
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
  st.divider()
110
+ st.caption(f"Sources captured from {target_country} local and global streams.")