bep40 commited on
Commit
ef816db
·
verified ·
1 Parent(s): cb4f838

Fix: og:image from slides, og:description from text, preserve SEO-friendly URL in canonical

Browse files
Files changed (1) hide show
  1. app_v2_entry.py +1820 -1
app_v2_entry.py CHANGED
@@ -1 +1,1820 @@
1
- # Will read the file with the read tool and upload it
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """VNEWS v2 Entry Point - with fast bongda proxy + rewrite endpoints + multilingual TTS"""
2
+ import sys, os
3
+ from main import app, HEADERS, BONGDA_HEADERS, fetch_bongda_api, HL_LEAGUES
4
+
5
+ try:
6
+ import ai_ext
7
+ except Exception as e:
8
+ print(f"[WARN] ai_ext import failed: {e}")
9
+
10
+ try:
11
+ import ai_patch
12
+ except Exception as e:
13
+ print(f"[WARN] ai_patch import failed: {e}")
14
+
15
+ from fastapi.responses import HTMLResponse, JSONResponse, FileResponse, Response
16
+ from fastapi.staticfiles import StaticFiles
17
+ from starlette.routing import Mount
18
+ from fastapi import Query, Request, UploadFile, File, Form
19
+ import requests as req
20
+ from bs4 import BeautifulSoup
21
+ import re, html as html_lib, json, threading, time, uuid
22
+ from concurrent.futures import ThreadPoolExecutor, as_completed
23
+ from urllib.parse import quote
24
+ import asyncio
25
+
26
+ HL_LEAGUES['friendly'] = {"path": "giai-khac/friendly", "name": "Giao hữu", "emoji": "🤝"}
27
+
28
+ STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
29
+ SPACE = "https://bep40-vnews.hf.space" # SEO URL base for share links
30
+ app.router.routes=[r for r in app.router.routes if not(getattr(r,'path',None)=='/' and hasattr(r,'methods') and 'GET' in getattr(r,'methods',set()))]
31
+ app.routes[:]=[r for r in app.routes if not isinstance(r, Mount)]
32
+ app.router.routes=[r for r in app.router.routes if not isinstance(r, Mount)]
33
+
34
+ def _clean(s): return re.sub(r"\s+"," ",html_lib.unescape(str(s or""))).strip()
35
+
36
+ # Cache for match details (5 min TTL)
37
+ _match_cache = {}
38
+
39
+ # === FAST BONGDA PROXY ENDPOINT ===
40
+ def _get_match_detail(event_id, slug=None):
41
+ headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept": "text/html", "Referer": "https://bongda.com.vn/"}
42
+ if slug:
43
+ url = f"https://bongda.com.vn/tran-dau/{event_id}/centre/{slug}"
44
+ else:
45
+ url = f"https://bongda.com.vn/tran-dau/{event_id}"
46
+ resp = req.get(url, headers=headers, timeout=15, allow_redirects=True)
47
+ if resp.status_code != 200:
48
+ return None
49
+ soup = BeautifulSoup(resp.text, 'html.parser')
50
+ result = {"event_id": event_id, "found": False, "sections": []}
51
+ info = {}
52
+ tel = soup.select_one('.teams')
53
+ if tel:
54
+ he = tel.select_one('.team.home')
55
+ if he:
56
+ p_tags = [p for p in he.select('p') if not p.get('class') or 'logo' not in p.get('class', [])]
57
+ if p_tags: info['home_team'] = _clean(p_tags[0].get_text())
58
+ lo = he.select_one('img')
59
+ if lo: info['home_logo'] = lo.get('src', '')
60
+ ae = tel.select_one('.team.away')
61
+ if ae:
62
+ p_tags = ae.select('p')
63
+ team_ps = [p for p in p_tags if not p.get('class') or 'logo' not in p.get('class', [])]
64
+ if team_ps: info['away_team'] = _clean(team_ps[-1].get_text())
65
+ lo = ae.select_one('img')
66
+ if lo: info['away_logo'] = lo.get('src', '')
67
+ sc = tel.select_one('.score')
68
+ if sc:
69
+ parts = [_clean(p.get_text()) for p in sc.select('p')]
70
+ if len(parts) >= 2: info['score'] = f"{parts[0]} - {parts[1]}"
71
+ lb = sc.select_one('.label')
72
+ if lb: info['status_label'] = _clean(lb.get_text())
73
+ if info.get('home_team') and info.get('away_team'):
74
+ result['info'] = info
75
+ result['found'] = True
76
+ result['sections'].append('info')
77
+ events = []
78
+ for ev in soup.select('.events .period .event'):
79
+ ev_cls = ' '.join(ev.get('class', []))
80
+ ev_data = {'team': 'home' if 'home' in ev_cls else 'away', 'period': '', 'type': 'unknown', 'time': '', 'players': ''}
81
+ parent = ev.parent
82
+ if parent:
83
+ h2 = parent.find('h2')
84
+ if h2: ev_data['period'] = _clean(h2.get_text())
85
+ if ev.select_one('[class*="goal"]'): ev_data['type'] = 'goal'
86
+ elif ev.select_one('[class*="redcard"]'): ev_data['type'] = 'redcard'
87
+ elif ev.select_one('[class*="yellowcard"]'): ev_data['type'] = 'yellowcard'
88
+ elif ev.select_one('[class*="substitution"]'): ev_data['type'] = 'substitution'
89
+ players_el = ev.select_one('.players')
90
+ if players_el:
91
+ pl_text = _clean(players_el.get_text(' ', strip=True))
92
+ m = re.match(r"(\d+)'(.*)", pl_text)
93
+ if m:
94
+ ev_data['time'] = f"{m.group(1)}'"
95
+ ev_data['players'] = m.group(2)
96
+ else:
97
+ ev_data['players'] = pl_text
98
+ events.append(ev_data)
99
+ if events:
100
+ result['events'] = events
101
+ result['sections'].append('events')
102
+ pred = soup.select_one('.prediction-card')
103
+ if pred:
104
+ team_info = pred.select_one('.team-info')
105
+ if team_info:
106
+ teams = team_info.select('.team')
107
+ pred_data = {}
108
+ if len(teams) >= 2:
109
+ pred_data['home_name'] = _clean(teams[0].select_one('.team-name').get_text()) if teams[0].select_one('.team-name') else ''
110
+ pred_data['away_name'] = _clean(teams[1].select_one('.team-name').get_text()) if teams[1].select_one('.team-name') else ''
111
+ divider = team_info.select_one('.divider')
112
+ if divider: pred_data['result'] = _clean(divider.get_text())
113
+ vc = pred.select_one('.vote-count')
114
+ if vc: pred_data['vote_count'] = _clean(vc.get_text())
115
+ result['prediction'] = pred_data
116
+ recent = []
117
+ ml = soup.select_one('.matches-list')
118
+ if ml:
119
+ for item in ml.select('.match-detail, .match-item, li'):
120
+ de = item.select_one('.date, .time')
121
+ le = item.select_one('.league')
122
+ he_item = item.select_one('.home, .team-home')
123
+ ae_item = item.select_one('.away, .team-away')
124
+ se = item.select_one('.score, .result')
125
+ if he_item or ae_item:
126
+ recent.append({'date': _clean(de.get_text()) if de else '', 'league': _clean(le.get_text()) if le else '', 'home': _clean(he_item.get_text()) if he_item else '', 'away': _clean(ae_item.get_text()) if ae_item else '', 'score': _clean(se.get_text()) if se else 'vs'})
127
+ if recent:
128
+ result['recent_matches'] = recent
129
+ result['sections'].append('recent')
130
+ try:
131
+ api_h = {"User-Agent": "Mozilla/5.0", "Accept": "application/json", "X-Requested-With": "XMLHttpRequest", "Referer": "https://bongda.com.vn/"}
132
+ ar = req.get(f"https://bongda.com.vn/api/fixtures/h2h-stats?event_id={event_id}", headers=api_h, timeout=10)
133
+ if ar.status_code == 200:
134
+ ad = ar.json()
135
+ if ad.get('status') == 'success' and ad.get('html'):
136
+ asp = BeautifulSoup(ad['html'], 'html.parser')
137
+ ast = {}
138
+ for row in asp.select('li, tr'):
139
+ cells = row.select('td, span, p')
140
+ if len(cells) >= 3:
141
+ lb = _clean(cells[0].get_text())
142
+ if lb: ast[lb] = {'home': _clean(cells[1].get_text()), 'away': _clean(cells[2].get_text())}
143
+ if ast:
144
+ result['h2h_stats_parsed'] = ast
145
+ result['sections'].append('h2h_stats')
146
+ except: pass
147
+ return result
148
+
149
+ @app.get('/api/proxy/bongda')
150
+ def proxy_bongda(event_id: int = Query(default=None), slug: str = Query(default=None)):
151
+ if event_id is None:
152
+ return JSONResponse({'error': 'event_id required'}, status_code=400)
153
+ cache_key = f"{event_id}_{slug}"
154
+ now = time.time()
155
+ cached = _match_cache.get(cache_key)
156
+ if cached and now - cached.get('_ts', 0) < 300:
157
+ return JSONResponse(cached)
158
+ try:
159
+ result = _get_match_detail(event_id, slug)
160
+ if result:
161
+ result['_ts'] = now
162
+ _match_cache[cache_key] = result
163
+ return JSONResponse(result)
164
+ except Exception as e:
165
+ err = {"event_id": event_id, "found": False, "error": str(e), "_ts": now}
166
+ _match_cache[cache_key] = err
167
+ return JSONResponse(err)
168
+ return JSONResponse({"event_id": event_id, "found": False})
169
+
170
+ @app.get('/api/match/{event_id}/detail')
171
+ def api_match_detail(event_id: int, url: str = Query(default=None)):
172
+ slug = None
173
+ if url:
174
+ m = re.match(r'.+/tran-dau/\d+/(?:centre|preview)/(.+)', url)
175
+ if m:
176
+ slug = m.group(1)
177
+ cache_key = f"{event_id}_{slug or ''}"
178
+ now = time.time()
179
+ cached = _match_cache.get(cache_key)
180
+ if cached and now - cached.get('_ts', 0) < 300:
181
+ return JSONResponse(cached)
182
+ try:
183
+ if not slug:
184
+ try:
185
+ home_r = req.get("https://bongda.com.vn/", headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
186
+ if home_r.status_code == 200:
187
+ home_soup = BeautifulSoup(home_r.text, 'html.parser')
188
+ for a in home_soup.select(f'a[href*="/tran-dau/{event_id}/"]'):
189
+ href = a.get('href', '')
190
+ m = re.match(r'/tran-dau/\d+/(?:centre|preview)/(.+)', href)
191
+ if m:
192
+ slug = m.group(1)
193
+ cache_key = f"{event_id}_{slug}"
194
+ break
195
+ except: pass
196
+ result = _get_match_detail(event_id, slug)
197
+ if result:
198
+ result['_ts'] = now
199
+ _match_cache[cache_key] = result
200
+ return JSONResponse(result)
201
+ except Exception as e:
202
+ err = {"event_id": event_id, "found": False, "error": str(e), "_ts": now}
203
+ _match_cache[cache_key] = err
204
+ return JSONResponse(err)
205
+ return JSONResponse({"event_id": event_id, "found": False})
206
+
207
+ _STOP=set('và của các những một được trong với cho tại sau trước khi không người việt nam hôm nay mới nhất nóng tin tức cập nhật theo từ đến là có thì này đã để'.split())
208
+
209
+ def _has_kw(topic,title):
210
+ tl=topic.lower();tt=(title or'').lower()
211
+ if tl in tt:return True
212
+ words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',tl) if len(w)>2 and w not in _STOP]
213
+ if not words:return True
214
+ return any(w in tt for w in words)
215
+
216
+ def _s_vnexpress(topic,limit=8):
217
+ items=[]
218
+ try:
219
+ r=req.get(f"https://timkiem.vnexpress.net/?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml')
220
+ for art in soup.select('article.item-news')[:limit]:
221
+ a=art.select_one('h2 a, h3 a')
222
+ if a and a.get('href'):
223
+ t=_clean(a.get('title','') or a.get_text(strip=True))
224
+ if _has_kw(topic,t):items.append({'title':t,'url':a['href'],'via':'VnExpress'})
225
+ except:pass
226
+ return items
227
+
228
+ def _s_dantri(topic,limit=8):
229
+ items=[]
230
+ try:
231
+ r=req.get(f"https://dantri.com.vn/tim-kiem/{quote(topic)}.htm",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml')
232
+ for a in soup.select('h3 a[href], .article-title a[href]')[:limit*2]:
233
+ t=_clean(a.get_text(strip=True));href=a.get('href','')
234
+ if t and len(t)>15 and _has_kw(topic,t):
235
+ if not href.startswith('http'):href='https://dantri.com.vn'+href
236
+ items.append({'title':t,'url':href,'via':'Dân Trí'})
237
+ if len(items)>=limit:break
238
+ except:pass
239
+ return items
240
+
241
+ def _s_vietnamnet(topic,limit=6):
242
+ items=[]
243
+ try:
244
+ r=req.get(f"https://vietnamnet.vn/tim-kiem?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml')
245
+ for a in soup.select('h3 a[href], .vnn-title a')[:limit*2]:
246
+ t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','')
247
+ if t and len(t)>15 and _has_kw(topic,t):
248
+ if not href.startswith('http'):href='https://vietnamnet.vn'+href
249
+ items.append({'title':t,'url':href,'via':'VietNamNet'})
250
+ if len(items)>=limit:break
251
+ except:pass
252
+ return items
253
+
254
+ def _s_bongda(topic,limit=5):
255
+ items=[]
256
+ try:
257
+ r=req.get(f"https://bongda.com.vn/tim-kiem.html?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=8);soup=BeautifulSoup(r.text,'lxml')
258
+ for a in soup.select('h3 a[href], .title a[href]')[:limit*2]:
259
+ t=_clean(a.get_text(strip=True));href=a.get('href','')
260
+ if t and len(t)>15 and _has_kw(topic,t):
261
+ if not href.startswith('http'):href='https://bongda.com.vn'+href
262
+ items.append({'title':t,'url':href,'via':'Bóng Đá'})
263
+ if len(items)>=limit:break
264
+ except:pass
265
+ return items
266
+
267
+ def _s_genk(topic,limit=5):
268
+ items=[]
269
+ try:
270
+ r=req.get(f"https://genk.vn/tim-kiem?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=8);soup=BeautifulSoup(r.text,'lxml')
271
+ for a in soup.select('a[href$=".chn"]')[:limit*3]:
272
+ t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','')
273
+ if t and len(t)>15 and _has_kw(topic,t):
274
+ if href.startswith('/'):href='https://genk.vn'+href
275
+ items.append({'title':t,'url':href,'via':'GenK'})
276
+ if len(items)>=limit:break
277
+ except:pass
278
+ return items
279
+
280
+ def _s_thanhnien(topic,limit=6):
281
+ items=[]
282
+ try:
283
+ r=req.get(f"https://thanhnien.vn/tim-kiem?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml')
284
+ for a in soup.select('h3 a[href], .box-title a')[:limit*2]:
285
+ t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','')
286
+ if t and len(t)>15 and _has_kw(topic,t):
287
+ if not href.startswith('http'):href='https://thanhnien.vn'+href
288
+ items.append({'title':t,'url':href,'via':'Thanh Niên'})
289
+ if len(items)>=limit:break
290
+ except:pass
291
+ return items
292
+
293
+ def _s_tuoitre(topic,limit=6):
294
+ items=[]
295
+ try:
296
+ r=req.get(f"https://tuoitre.vn/tim-kiem.htm?keywords={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml')
297
+ for a in soup.select('h3 a[href], .box-title-text a')[:limit*2]:
298
+ t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','')
299
+ if t and len(t)>15 and _has_kw(topic,t):
300
+ if not href.startswith('http'):href='https://tuoitre.vn'+href
301
+ items.append({'title':t,'url':href,'via':'Tuổi Trẻ'})
302
+ if len(items)>=limit:break
303
+ except:pass
304
+ return items
305
+
306
+ def _s_thethaovanhoa(topic,limit=5):
307
+ items=[]
308
+ try:
309
+ r=req.get(f"https://thethaovanhoa.vn/tim-kiem.htm?keyword={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=8);soup=BeautifulSoup(r.text,'lxml')
310
+ for a in soup.select('h3 a[href], .title a[href]')[:limit*2]:
311
+ t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','')
312
+ if t and len(t)>15 and _has_kw(topic,t):
313
+ if not href.startswith('http'):href='https://thethaovanhoa.vn'+href
314
+ items.append({'title':t,'url':href,'via':'TT&VH'})
315
+ if len(items)>=limit:break
316
+ except:pass
317
+ return items
318
+
319
+ def _search_all(topic,limit=36):
320
+ results={}
321
+ with ThreadPoolExecutor(8) as ex:
322
+ futs={ex.submit(_s_vnexpress,topic,8):'vne',ex.submit(_s_dantri,topic,8):'dt',ex.submit(_s_vietnamnet,topic,6):'vnn',ex.submit(_s_bongda,topic,5):'bd',ex.submit(_s_genk,topic,5):'gk',ex.submit(_s_thanhnien,topic,6):'tn',ex.submit(_s_tuoitre,topic,6):'tt',ex.submit(_s_thethaovanhoa,topic,5):'tvh'}
323
+ for f in as_completed(futs,timeout=14):
324
+ try:results[futs[f]]=f.result()
325
+ except:results[futs[f]]=[]
326
+ srcs=list(results.values());out=[];seen=set()
327
+ for i in range(max((len(s) for s in srcs),default=0)):
328
+ for s in srcs:
329
+ if i<len(s) and s[i].get('url') and s[i]['url'] not in seen:seen.add(s[i]['url']);out.append(s[i])
330
+ return out[:limit]
331
+
332
+ for _path in ['/api/article', '/api/hot_topics', '/api/categories', '/api/storage_status']:
333
+ app.router.routes=[r for r in app.router.routes if not(getattr(r,'path',None)==_path and 'GET' in getattr(r,'methods',set()))]
334
+
335
+ _article_cache = {}
336
+ _article_cache_ttl = 1800
337
+
338
+ _art_session = None
339
+ _art_lock = threading.Lock()
340
+ def _get_art_session():
341
+ global _art_session
342
+ if _art_session is None:
343
+ with _art_lock:
344
+ if _art_session is None:
345
+ _art_session = req.Session()
346
+ _art_session.headers.update({
347
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
348
+ "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8",
349
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
350
+ })
351
+ return _art_session
352
+
353
+ def _scrape_article_fast(url):
354
+ from urllib.parse import urlparse
355
+ domain = urlparse(url).netloc
356
+ sess = _get_art_session()
357
+ uas = [
358
+ {"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"},
359
+ {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},
360
+ ]
361
+ for ua in uas:
362
+ try:
363
+ r = sess.get(url, headers=ua, timeout=6, allow_redirects=True)
364
+ if not r or r.status_code != 200:
365
+ continue
366
+ r.encoding = 'utf-8'
367
+ soup = BeautifulSoup(r.text, 'lxml')
368
+ for tag in soup.find_all(['script','style','nav','footer','aside','form','noscript','iframe','.ads','.ad','.banner-ads','.fb-comments','.fb-root','.social-share','.related-news','.tag','.breadcrumb']):
369
+ tag.decompose()
370
+ title = summary = og_img = ""
371
+ ogt = soup.find('meta', property='og:title')
372
+ if ogt: title = ogt.get('content', '')
373
+ ogd = soup.find('meta', property='og:description') or soup.find('meta', attrs={'name': 'description'})
374
+ if ogd: summary = ogd.get('content', '')[:500]
375
+ ogi = soup.find('meta', property='og:image')
376
+ if ogi:
377
+ og_img = ogi.get('content', '')
378
+ if og_img.startswith('//'): og_img = 'https:' + og_img
379
+ h1 = soup.find('h1')
380
+ if not title and h1: title = h1.get_text(strip=True)[:200]
381
+ body = []
382
+ selectors = [
383
+ '.fck_detail', '.sidebar-1',
384
+ '.singular-content', '.dt__content', '.article-content', '.content-detail', '#divNewsContent',
385
+ '.content-detail', '.main-content-detail', '.box-content',
386
+ '.knc-content', '.article-body', '.detail-body',
387
+ '.article-detail', '.detail-content',
388
+ 'article', 'main', '.cms-body', '.article__body', '.post-content',
389
+ '.entry-content', '#content', '.article-text', '.story-body',
390
+ ]
391
+ for sel in selectors:
392
+ el = soup.select_one(sel)
393
+ if el and len(el.find_all('p')) >= 2:
394
+ seen_imgs = set()
395
+ for child in el.find_all(['p','h2','h3','figure','img'], recursive=True):
396
+ if child.name == 'p':
397
+ t = child.get_text(strip=True)
398
+ if t and len(t) > 15:
399
+ body.append({'type': 'p', 'text': t})
400
+ elif child.name in ('h2','h3'):
401
+ t = child.get_text(strip=True)
402
+ if t:
403
+ body.append({'type': 'heading', 'text': t})
404
+ elif child.name in ('figure','img'):
405
+ im = child if child.name == 'img' else child.find('img')
406
+ if im:
407
+ src = im.get('data-src') or im.get('src') or im.get('data-lazy') or ''
408
+ if src and 'base64' not in src and src not in seen_imgs:
409
+ seen_imgs.add(src)
410
+ if src.startswith('//'): src = 'https:' + src
411
+ body.append({'type': 'img', 'src': src})
412
+ if child.name == 'figure':
413
+ cap = child.find('figcaption')
414
+ if cap:
415
+ ct = cap.get_text(strip=True)
416
+ if ct: body.append({'type': 'p', 'text': ct})
417
+ if len(body) >= 2:
418
+ return {'title': _clean(title), 'summary': _clean(summary), 'og_image': og_img,
419
+ 'body': body[:50], 'source': domain, 'url': url}
420
+ if title and (summary or og_img):
421
+ fallback = []
422
+ if og_img: fallback.append({'type': 'img', 'src': og_img})
423
+ if summary: fallback.append({'type': 'p', 'text': summary})
424
+ if fallback:
425
+ return {'title': _clean(title), 'summary': _clean(summary), 'og_image': og_img,
426
+ 'body': fallback, 'source': domain, 'url': url, 'fallback': True}
427
+ if title:
428
+ return {'title': _clean(title), 'summary': '', 'og_image': '',
429
+ 'body': [{'type': 'p', 'text': 'Nội dung đang được tải...'}],
430
+ 'source': domain, 'url': url, 'fallback': True}
431
+ break
432
+ except Exception:
433
+ continue
434
+ return None
435
+
436
+ @app.get('/api/article')
437
+ def api_article_v2(url: str = Query(...)):
438
+ from urllib.parse import unquote
439
+ safe_url = unquote(url)
440
+ try:
441
+ now = time.time()
442
+ cached = _article_cache.get(safe_url)
443
+ if cached and now - cached['t'] < _article_cache_ttl:
444
+ resp = JSONResponse(cached['d'])
445
+ resp.headers["Cache-Control"] = "public, max-age=1800"
446
+ return resp
447
+ data = _scrape_article_fast(safe_url)
448
+ if data and data.get('body'):
449
+ _article_cache[safe_url] = {'d': data, 't': now}
450
+ resp = JSONResponse(data)
451
+ resp.headers["Cache-Control"] = "public, max-age=1800"
452
+ return resp
453
+ result = {'error': 'Không đọc được', 'url': safe_url}
454
+ resp = JSONResponse(result)
455
+ resp.headers["Cache-Control"] = "public, max-age=60"
456
+ return resp
457
+ except Exception as e:
458
+ return JSONResponse({'error': f'Server error: {str(e)[:100]}', 'url': safe_url}, status_code=200)
459
+
460
+ _hot_cache={'t':0,'d':[]}
461
+ def _get_hot_topics():
462
+ now=time.time()
463
+ if _hot_cache['d'] and now-_hot_cache['t']<600:return _hot_cache['d']
464
+ freq={};display={}
465
+ feeds=['https://vnexpress.net/rss/tin-moi-nhat.rss','https://dantri.com.vn/rss/home.rss','https://vietnamnet.vn/rss/tin-moi-nhat.rss','https://thanhnien.vn/rss/home.rss','https://tuoitre.vn/rss/tin-moi-nhat.rss','https://genk.vn/rss','https://vnexpress.net/rss/the-thao.rss','https://thethaovanhoa.vn/rss/tin-nong.rss']
466
+ for feed_url in feeds:
467
+ try:
468
+ r=req.get(feed_url,headers={'User-Agent':'Mozilla/5.0'},timeout=6);r.encoding='utf-8';soup=BeautifulSoup(r.text,'xml')
469
+ for item in soup.find_all('item')[:12]:
470
+ title=_clean(item.find('title').get_text() if item.find('title') else '')
471
+ if not title:continue
472
+ title=re.sub(r'\s*[-|].*$','',title);words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',title) if len(w)>2 and w.lower() not in _STOP]
473
+ if len(words)<2:continue
474
+ for n in(3,4,2):
475
+ for i in range(max(0,len(words)-n+1)):
476
+ phrase=' '.join(words[i:i+n])
477
+ if 8<=len(phrase)<=45:key=phrase.lower();freq[key]=freq.get(key,0)+1;display[key]=phrase
478
+ except:continue
479
+ ranked=sorted(freq.items(),key=lambda x:x[1],reverse=True);topics=[];seen=set()
480
+ for key,count in ranked:
481
+ is_dup=any(len(set(e.split())&set(key.split()))/max(len(set(e.split())),len(set(key.split())),1)>0.6 for e in seen)
482
+ if is_dup:continue
483
+ seen.add(key);topics.append({'label':'#'+re.sub(r'\s+','',display[key].title()),'topic':display[key],'count':count})
484
+ if len(topics)>=20:break
485
+ for kw in['World Cup 2026','Kinh tế Việt Nam','Bóng đá châu Âu','Công nghệ AI','Giá vàng','Thời tiết']:
486
+ if len(topics)>=24:break
487
+ if not any(kw.lower() in s for s in seen):topics.append({'label':'#'+re.sub(r'\s+','',kw.title()),'topic':kw,'count':0})
488
+ _hot_cache.update({'t':now,'d':topics[:24]});return topics[:24]
489
+
490
+ @app.get('/api/hot_topics')
491
+ def api_hot_topics():
492
+ resp = JSONResponse({'topics':_get_hot_topics()})
493
+ resp.headers["Cache-Control"] = "public, max-age=120"
494
+ return resp
495
+ @app.get('/')
496
+ async def serve_index():
497
+ p=os.path.join(STATIC_DIR,'index_v2.html')
498
+ if os.path.exists(p):return FileResponse(p,media_type='text/html')
499
+ return HTMLResponse('<h1>VNEWS</h1>')
500
+ @app.get('/api/hashtag/sources')
501
+ def _ht(topic:str=Query(...),page:int=Query(default=0)):
502
+ items=_search_all(topic,36);per_page=8;start=page*per_page;end=start+per_page
503
+ return JSONResponse({'sources':items[start:end],'topic':topic,'page':page,'has_more':end<len(items),'total':len(items)})
504
+ @app.get('/api/categories')
505
+ def _cat():return JSONResponse([])
506
+ @app.get('/api/storage_status')
507
+ def _st():return JSONResponse({'persistent':os.path.isdir('/data') and os.access('/data',os.W_OK)})
508
+ # ===== SHARE HELPERS: render content pages for shared links =====
509
+ def _render_slides_page(post, safe_title, safe_img, safe_url):
510
+ slides = post.get('slides', [])
511
+ # Get image from post.img or first slide's image
512
+ if not safe_img and slides and slides[0].get('image'):
513
+ safe_img = slides[0].get('image', '')
514
+ # Use text for description if available
515
+ description = _clean((post.get('text') or '')[:200]) or "Tin tức tóm tắt, AI rewrite, World Cup 2026"
516
+
517
+ # Build canonical URL preserving original query format if url was provided
518
+ if safe_url and safe_url != '/':
519
+ canonical_url = f"{SPACE}/s?url={quote(safe_url)}&title={quote(safe_title[:100])}"
520
+ else:
521
+ canonical_url = f"{SPACE}/s?post_id={post.get('id') or ''}"
522
+
523
+ h = f'''<!DOCTYPE html>
524
+ <html lang="vi">
525
+ <head>
526
+ <meta charset="utf-8">
527
+ <meta name="viewport" content="width=device-width,initial-scale=1">
528
+ <title>{_clean(safe_title)}</title>
529
+ <meta property="og:title" content="{_clean(safe_title)}">
530
+ <meta property="og:image" content="{_clean(safe_img)}">
531
+ <meta property="og:description" content="{description}">
532
+ <meta property="og:url" content="{canonical_url}">
533
+ <link rel="canonical" href="{canonical_url}">
534
+ <style>
535
+ *{{box-sizing:border-box;margin:0;padding:0}}body{{background:#111;color:#eee;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:12px}}
536
+ .slide-card{{background:#1a1a1a;border:1px solid #2a2a2a;border-radius:12px;padding:16px;margin-bottom:12px;max-width:600px;margin-left:auto;margin-right:auto}}
537
+ .slide-num{{color:#5cb87a;font-size:12px;font-weight:700;margin-bottom:6px}}
538
+ .slide-img{{width:100%;max-height:300px;object-fit:cover;border-radius:8px;margin-bottom:8px}}
539
+ .slide-text{{color:#ddd;font-size:14px;line-height:1.6;margin:0}}
540
+ </style>
541
+ </head>
542
+ <body>'''
543
+ for s in slides:
544
+ img_src = s.get('image', '')
545
+ if img_src and ('cdnphoto.dantri' in img_src or 'refooty' in img_src or 'vnexpress' in img_src or 'vcdn' in img_src):
546
+ img_tag = f'<img src="/api/proxy/img?url={quote(img_src, safe="")}" class="slide-img" loading="lazy" onerror="this.style.display=\'none\'">'
547
+ else:
548
+ img_tag = f'<img src="{_clean(img_src)}" class="slide-img" loading="lazy" onerror="this.style.display=\'none\'">' if img_src else ''
549
+ h += f'<div class="slide-card"><div class="slide-num">Slide {s.get("index",1)}/{len(slides)}</div>{img_tag}<p class="slide-text">{_clean(s.get("text",""))}</p></div>'
550
+ h += '</body></html>'
551
+ return HTMLResponse(h)
552
+
553
+ def _render_video_page(post, safe_title, safe_img, safe_url):
554
+ video_url = post.get('video', '')
555
+ # Use text for description if available
556
+ description = _clean((post.get('text') or '')[:200]) or "Tin tức tóm tắt, AI rewrite, World Cup 2026"
557
+
558
+ # Build canonical URL preserving original query format if url was provided
559
+ if safe_url and safe_url != '/':
560
+ canonical_url = f"{SPACE}/s?url={quote(safe_url)}&title={quote(safe_title[:100])}"
561
+ else:
562
+ canonical_url = f"{SPACE}/s?post_id={post.get('id') or ''}"
563
+
564
+ h = f'''<!DOCTYPE html>
565
+ <html lang="vi">
566
+ <head>
567
+ <meta charset="utf-8">
568
+ <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
569
+ <title>{_clean(safe_title)}</title>
570
+ <meta property="og:title" content="{_clean(safe_title)}">
571
+ <meta property="og:image" content="{_clean(safe_img)}">
572
+ <meta property="og:description" content="{description}">
573
+ <meta property="og:url" content="{canonical_url}">
574
+ <link rel="canonical" href="{canonical_url}">
575
+ <meta name="twitter:card" content="player">
576
+ <meta name="twitter:player" content="{video_url}">
577
+ <style>
578
+ *{{box-sizing:border-box;margin:0;padding:0}}body{{background:#111;color:#eee;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:0;overflow:hidden}}
579
+ .video-container{{width:100vw;height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;background:#000}}
580
+ video{{width:100%;height:100%;max-height:100vh;object-fit:contain;background:#000}}
581
+ .title-bar{{position:fixed;bottom:0;left:0;right:0;background:linear-gradient(transparent,rgba(0,0,0,.8));padding:40px 16px 16px;text-align:center}}
582
+ .title-text{{color:#fff;font-size:13px;line-height:1.4;max-width:600px;margin:0 auto}}
583
+ </style>
584
+ </head>
585
+ <body>
586
+ <div class="video-container">
587
+ <video src="{_clean(video_url)}" controls autoplay playsinline loop></video>
588
+ <div class="title-bar"><div class="title-text">{_clean(safe_title)}</div></div>
589
+ </div>
590
+ </body></html>'''
591
+ return HTMLResponse(h)
592
+
593
+ @app.get('/s/{slug}')
594
+ async def _sh_slug(slug: str, request: Request, url: str = '', title: str = '', img: str = ''):
595
+ """SEO-friendly share endpoint with slug in URL path.
596
+ Shows slide content when slug matches a wall post ID, otherwise redirects.
597
+ """
598
+ safe_title = _clean(title) if title else 'VNEWS - Tin tức'
599
+ safe_img = _clean(img) if img else ''
600
+ safe_url = _clean(url) if url else '/'
601
+
602
+ # Try to find post by slug (post ID)
603
+ post = None
604
+ try:
605
+ if slug and len(slug) > 5: # Likely a post ID
606
+ posts = _load_wall_posts()
607
+ for p in posts:
608
+ if p.get('id') == slug:
609
+ post = p
610
+ safe_title = p.get('title', safe_title) or safe_title
611
+ safe_img = p.get('img', safe_img) or safe_img
612
+ safe_url = p.get('url', safe_url) or safe_url
613
+ break
614
+ except:
615
+ pass
616
+
617
+ if post and post.get('slides'):
618
+ return _render_slides_page(post, safe_title, safe_img, safe_url)
619
+
620
+ if post and post.get('video'):
621
+ return _render_video_page(post, safe_title, safe_img, safe_url)
622
+
623
+ # Otherwise redirect
624
+ return HTMLResponse(f'''<!DOCTYPE html>
625
+ <html lang="vi">
626
+ <head>
627
+ <meta charset="utf-8">
628
+ <meta name="viewport" content="width=device-width,initial-scale=1">
629
+ <title>{_clean(safe_title)}</title>
630
+ <meta property="og:title" content="{_clean(safe_title)}">
631
+ <meta property="og:image" content="{_clean(safe_img)}">
632
+ <meta property="og:description" content="Tin tức tóm tắt, AI rewrite, World Cup 2026">
633
+ <meta property="og:url" content="{SPACE}/s/{slug}">
634
+ <link rel="canonical" href="{SPACE}/s/{slug}">
635
+ <meta http-equiv="refresh" content="0;url={safe_url}">
636
+ </head><body></body></html>''')
637
+
638
+ @app.get('/s')
639
+ async def _sh(url:str='',title:str='',img:str='',post_id:str=''):
640
+ safe_title = _clean(title) if title else 'VNEWS - Tin tức'
641
+ safe_img = _clean(img) if img else ''
642
+ safe_url = _clean(url) if url else '/'
643
+
644
+ # Try to find wall post by post_id or URL
645
+ post = None
646
+ try:
647
+ posts = _load_wall_posts()
648
+ for p in posts:
649
+ if post_id and p.get('id') == post_id:
650
+ post = p
651
+ safe_title = p.get('title', safe_title) or safe_title
652
+ safe_img = p.get('img', safe_img) or safe_img
653
+ safe_url = p.get('url', safe_url) or safe_url
654
+ break
655
+ if url and p.get('url') == url:
656
+ post = p
657
+ safe_title = p.get('title', safe_title) or safe_title
658
+ safe_img = p.get('img', safe_img) or safe_img
659
+ safe_url = p.get('url', safe_url) or safe_url
660
+ break
661
+ except:
662
+ pass
663
+
664
+ if post and post.get('slides'):
665
+ return _render_slides_page(post, safe_title, safe_img, safe_url)
666
+
667
+ if post and post.get('video'):
668
+ return _render_video_page(post, safe_title, safe_img, safe_url)
669
+
670
+ # Fallback: redirect to original URL
671
+ return HTMLResponse(f'''<!DOCTYPE html>
672
+ <html lang="vi">
673
+ <head>
674
+ <meta charset="utf-8">
675
+ <meta name="viewport" content="width=device-width,initial-scale=1">
676
+ <title>{safe_title}</title>
677
+ <meta property="og:title" content="{safe_title}">
678
+ <meta property="og:image" content="{safe_img}">
679
+ <meta property="og:description" content="Tin tức tóm tắt, AI rewrite, World Cup 2026">
680
+ <meta property="og:url" content="{SPACE}/s?url={quote(safe_url)}">
681
+ <link rel="canonical" href="{SPACE}/s?url={quote(safe_url)}">
682
+ <meta http-equiv="refresh" content="0;url={safe_url}">
683
+ </head><body></body></html>''')
684
+
685
+ from wc2026_scraper import scrape_summary,scrape_fixtures,scrape_standings,scrape_stats,scrape_wc_news,scrape_road_to_wc,get_wc2026_all,scrape_history,scrape_h2h,scrape_lineups,scrape_match_detail
686
+
687
+ _xlb_cache = {}
688
+ _xlb_lock = threading.Lock()
689
+
690
+ def _xlb_scrape(path):
691
+ url = f"https://xemlaibongda.top/{path}"
692
+ r = req.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}, timeout=15, allow_redirects=True)
693
+ if r.status_code != 200:
694
+ return []
695
+ soup = BeautifulSoup(r.text, 'lxml')
696
+ vids = []
697
+ seen = set()
698
+ for a in soup.select('a[href*="/video/"]'):
699
+ href = a.get('href', '')
700
+ if not href or href in seen:
701
+ continue
702
+ seen.add(href)
703
+ if not href.startswith('http'):
704
+ href = 'https://xemlaibongda.top' + href
705
+ img = a.select_one('img')
706
+ p = a.parent
707
+ for _ in range(4):
708
+ if img:
709
+ break
710
+ if p:
711
+ img = p.select_one('img')
712
+ p = p.parent
713
+ img_src = ''
714
+ if img:
715
+ img_src = img.get('data-src','') or img.get('src','') or img.get('data-lazy','') or img.get('data-original','')
716
+ if img_src.startswith('//'):
717
+ img_src = 'https:' + img_src
718
+ elif img_src.startswith('/'):
719
+ img_src = 'https://xemlaibongda.top' + img_src
720
+ title = ''
721
+ for sel in ['.title', 'h3', 'h2', '.name', '.post-title', '.entry-title', '.video-title']:
722
+ t = a.select_one(sel)
723
+ if t:
724
+ title = _clean(t.get_text())
725
+ break
726
+ if not title:
727
+ title = _clean(a.get('title',''))
728
+ if not title:
729
+ img_alt = a.select_one('img')
730
+ if img_alt:
731
+ title = _clean(img_alt.get('alt',''))
732
+ if not title:
733
+ parent = a.parent
734
+ if parent:
735
+ pt = _clean(parent.get_text(' ',strip=True))
736
+ if 5 < len(pt) < 120:
737
+ title = pt
738
+ if not title or len(title) < 3:
739
+ continue
740
+ vids.append({"link": href, "img": img_src, "title": title})
741
+ if len(vids) >= 30:
742
+ break
743
+ return vids
744
+
745
+ @app.get('/api/proxy/xlb')
746
+ def proxy_xlb(path: str = Query(default="")):
747
+ now = time.time()
748
+ cache_key = f"xlb:{path}"
749
+ with _xlb_lock:
750
+ cached = _xlb_cache.get(cache_key)
751
+ if cached and now - cached['t'] < 120:
752
+ return JSONResponse(cached['d'])
753
+ try:
754
+ vids = _xlb_scrape(path)
755
+ result = {"videos": vids, "count": len(vids)}
756
+ with _xlb_lock:
757
+ _xlb_cache[cache_key] = {'t': now, 'd': result}
758
+ return JSONResponse(result)
759
+ except Exception as e:
760
+ return JSONResponse({"videos": [], "count": 0, "error": str(e)}, status_code=500)
761
+
762
+ @app.get('/api/wc2026')
763
+ def _w():return JSONResponse(get_wc2026_all())
764
+ @app.get('/api/wc2026/fixtures')
765
+ def _wf():return JSONResponse(scrape_fixtures())
766
+ @app.get('/api/wc2026/standings')
767
+ def _ws():return JSONResponse(scrape_standings())
768
+ @app.get('/api/wc2026/stats')
769
+ def _wst():return JSONResponse(scrape_stats())
770
+ @app.get('/api/wc2026/history')
771
+ def _whi():return JSONResponse(scrape_history())
772
+ @app.get('/api/wc2026/news')
773
+ def _wn():return JSONResponse(scrape_wc_news())
774
+ @app.get('/api/wc2026/road')
775
+ def _wr():return JSONResponse(scrape_road_to_wc())
776
+ @app.get('/api/wc2026/h2h/{eid}')
777
+ def _wh2(eid:int):return JSONResponse(scrape_h2h(eid))
778
+ @app.get('/api/wc2026/lineups/{eid}')
779
+ def _wl(eid:int):return JSONResponse(scrape_lineups(eid))
780
+ @app.get('/api/wc2026/match/{eid}')
781
+ def _wm(eid:int):return JSONResponse(scrape_match_detail(eid))
782
+
783
+ DATA_DIR='/data' if os.path.isdir('/data') else os.path.join(os.path.dirname(os.path.abspath(__file__)),'data')
784
+ os.makedirs(DATA_DIR,exist_ok=True)
785
+ IF=os.path.join(DATA_DIR,'interactions_v2.json')
786
+ CF=os.path.join(DATA_DIR,'comments_v2.json')
787
+ WALL_FILE=os.path.join(DATA_DIR,'wall_posts.json')
788
+ WALL_VIDEO_DIR=os.path.join(DATA_DIR,'wall_videos')
789
+ os.makedirs(WALL_VIDEO_DIR,exist_ok=True)
790
+
791
+ _il=threading.Lock();_cl=threading.Lock();_wl_lock=threading.Lock()
792
+ def _lj(p):
793
+ try:
794
+ if os.path.exists(p):return json.load(open(p,'r',encoding='utf-8'))
795
+ except:pass
796
+ return{}
797
+ def _sj(p,d):
798
+ try:open(p+'.tmp','w',encoding='utf-8').write(json.dumps(d,ensure_ascii=False));os.replace(p+'.tmp',p)
799
+ except:pass
800
+
801
+ @app.post('/api/v2/interact')
802
+ async def _int(request:Request):
803
+ b=await request.json();v=str(b.get('id','')).strip();t=str(b.get('type','')).strip()
804
+ if not v or t not in('view','like'):return JSONResponse({'error':'x'},status_code=400)
805
+ with _il:db=_lj(IF);db.setdefault(v,{'views':0,'likes':0,'comments':0});db[v][t+'s']+=1;_sj(IF,db);return JSONResponse(db[v])
806
+
807
+ @app.get('/api/v2/interactions')
808
+ def _gi(id:str=Query(...)):
809
+ with _il:return JSONResponse(_lj(IF).get(id.strip(),{'views':0,'likes':0,'comments':0}))
810
+
811
+ @app.get('/api/v2/comments')
812
+ def _gc(id:str=Query(...)):
813
+ with _cl:return JSONResponse({'comments':_lj(CF).get(id.strip(),[])})
814
+
815
+ @app.post('/api/v2/comment')
816
+ async def _pc(request:Request):
817
+ b=await request.json();v=str(b.get('id','')).strip();tx=str(b.get('text','')).strip()[:500]
818
+ if not v or not tx:return JSONResponse({'error':'x'},status_code=400)
819
+ c={'text':tx,'time':time.strftime('%H:%M %d/%m',time.localtime()),'ts':int(time.time())}
820
+ with _cl:db=_lj(CF);db.setdefault(v,[]);db[v].append(c);db[v]=db[v][-200:];_sj(CF,db);cms=db[v]
821
+ with _il:idb=_lj(IF);idb.setdefault(v,{'views':0,'likes':0,'comments':0});idb[v]['comments']=len(cms);_sj(IF,idb)
822
+ return JSONResponse({'comments':cms})
823
+
824
+ def _load_wall_posts():
825
+ with _wl_lock:
826
+ return _lj(WALL_FILE)
827
+
828
+ def _save_wall_posts(posts):
829
+ with _wl_lock:
830
+ _sj(WALL_FILE, posts)
831
+
832
+ @app.get('/api/wall')
833
+ def api_wall():
834
+ posts = _load_wall_posts()
835
+ if not posts:
836
+ return JSONResponse({"posts": []})
837
+ return JSONResponse({"posts": posts})
838
+
839
+ @app.post('/api/wall')
840
+ async def api_wall_post(request: Request):
841
+ content_type = request.headers.get('content-type', '')
842
+ if 'multipart/form-data' in content_type:
843
+ try:
844
+ form = await request.form()
845
+ except Exception as e:
846
+ return JSONResponse({"error": f"Form parse error: {str(e)}"}, status_code=400)
847
+ title = form.get('title', 'Video mới') or 'Video mới'
848
+ text = form.get('text', '') or ''
849
+ source = form.get('source', 'vtv_recorder') or 'vtv_recorder'
850
+ video_file = form.get('video')
851
+ post_id = str(uuid.uuid4())[:12]
852
+ video_url = None
853
+ if video_file and hasattr(video_file, 'filename') and video_file.filename:
854
+ fname = video_file.filename.lower()
855
+ if fname.endswith('.mp4'):
856
+ ext = '.mp4'
857
+ elif fname.endswith('.webm'):
858
+ ext = '.webm'
859
+ else:
860
+ ext = '.webm'
861
+ video_filename = f"wall_{post_id}{ext}"
862
+ video_path = os.path.join(WALL_VIDEO_DIR, video_filename)
863
+ try:
864
+ content = await video_file.read()
865
+ if not content:
866
+ return JSONResponse({"error": "Empty video file"}, status_code=400)
867
+ with open(video_path, 'wb') as f:
868
+ f.write(content)
869
+ file_size_mb = len(content) / 1024 / 1024
870
+ if file_size_mb > 50:
871
+ os.remove(video_path)
872
+ return JSONResponse({"error": f"Video quá lớn ({file_size_mb:.1f}MB). Tối đa 50MB."}, status_code=400)
873
+ video_url = f"/api/wall/video/{video_filename}"
874
+ except Exception as e:
875
+ return JSONResponse({"error": f"Lỗi lưu video: {str(e)}"}, status_code=500)
876
+ post = {
877
+ "id": post_id,
878
+ "title": title[:200],
879
+ "text": text[:2000],
880
+ "source": source,
881
+ "video": video_url,
882
+ "img": None,
883
+ "images": [],
884
+ "created": int(time.time()),
885
+ "created_str": time.strftime('%H:%M %d/%m/%Y', time.localtime()),
886
+ }
887
+ posts = _load_wall_posts()
888
+ if not isinstance(posts, list):
889
+ posts = []
890
+ posts.insert(0, post)
891
+ posts = posts[:200]
892
+ _save_wall_posts(posts)
893
+ return JSONResponse({"post": post, "ok": True})
894
+ try:
895
+ body = await request.json()
896
+ except:
897
+ body = {}
898
+ title = body.get('title', 'Bài mới') or 'Bài mới'
899
+ text = body.get('text', '') or ''
900
+ img = body.get('img', None)
901
+ source = body.get('source', 'user') or 'user'
902
+ post_id = str(uuid.uuid4())[:12]
903
+ post = {
904
+ "id": post_id,
905
+ "title": title[:200],
906
+ "text": text[:2000],
907
+ "source": source,
908
+ "video": None,
909
+ "img": img,
910
+ "images": [],
911
+ "created": int(time.time()),
912
+ "created_str": time.strftime('%H:%M %d/%m/%Y', time.localtime()),
913
+ }
914
+ posts = _load_wall_posts()
915
+ if not isinstance(posts, list):
916
+ posts = []
917
+ posts.insert(0, post)
918
+ posts = posts[:200]
919
+ _save_wall_posts(posts)
920
+ return JSONResponse({"post": post, "ok": True})
921
+
922
+ @app.get('/api/wall/video/{filename}')
923
+ def api_wall_video(filename: str):
924
+ if '..' in filename or '/' in filename:
925
+ return Response(status_code=403)
926
+ video_path = os.path.join(WALL_VIDEO_DIR, filename)
927
+ if not os.path.exists(video_path):
928
+ return Response(status_code=404)
929
+ ext = os.path.splitext(filename)[1].lower()
930
+ media_type = 'video/mp4' if ext == '.mp4' else 'video/webm'
931
+ return FileResponse(video_path, media_type=media_type)
932
+
933
+ @app.delete('/api/wall/{post_id}')
934
+ def api_wall_delete(post_id: str):
935
+ posts = _load_wall_posts()
936
+ if not isinstance(posts, list):
937
+ return JSONResponse({"error": "No posts"}, status_code=404)
938
+ for i, p in enumerate(posts):
939
+ if p.get('id') == post_id:
940
+ if p.get('video'):
941
+ video_name = p['video'].split('/')[-1]
942
+ video_path = os.path.join(WALL_VIDEO_DIR, video_name)
943
+ if os.path.exists(video_path):
944
+ os.remove(video_path)
945
+ posts.pop(i)
946
+ _save_wall_posts(posts)
947
+ return JSONResponse({"ok": True})
948
+ return JSONResponse({"error": "Post not found"}, status_code=404)
949
+
950
+ # ===== LANGUAGE & EMOTION DETECTION =====
951
+ import random as _random2
952
+ from urllib.parse import quote as _quote2
953
+
954
+ _UA_RW = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept-Language': 'vi-VN,vi;q=0.9'}
955
+
956
+ # Unique character markers for language detection
957
+ _UNIQUE_CHARS = {
958
+ 'vietnamese': set('đăâêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềễểệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵý'),
959
+ 'spanish': set('ñáéíóúü¿¡'),
960
+ 'portuguese': set('ãõçáéíóúâêôà'),
961
+ }
962
+
963
+ _STOPWORDS = {
964
+ 'english': {'the', 'is', 'at', 'which', 'on', 'a', 'an', 'and', 'or', 'but', 'in', 'with', 'to', 'for', 'of', 'not', 'no', 'can', 'had', 'have', 'has', 'was', 'were', 'are', 'be', 'been', 'this', 'that', 'it', 'he', 'she', 'they', 'his', 'her', 'my', 'your', 'our', 'we', 'you', 'i'},
965
+ 'vietnamese': {'là', 'của', 'và', 'có', 'được', 'cho', 'kh��ng', 'với', 'này', 'đó', 'từ', 'trong', 'đã', 'sẽ', 'một', 'các', 'những', 'về', 'tại', 'người', 'năm', 'đến', 'ra', 'lại', 'như', 'khi', 'để', 'rất', 'cũng', 'mà', 'nếu', 'sau', 'trên', 'theo', 'vì', 'do', 'nên', 'thì', 'mình', 'tôi', 'bạn', 'anh', 'chị', 'em'},
966
+ 'portuguese': {'de', 'um', 'que', 'e', 'do', 'da', 'em', 'para', 'com', 'não', 'uma', 'os', 'no', 'se', 'na', 'por', 'mais', 'as', 'dos', 'como', 'mas', 'ao', 'ele', 'das', 'tem', 'seu', 'sua', 'ou', 'quando', 'muito', 'nos', 'já', 'eu', 'também', 'só', 'pelo', 'pela', 'até', 'isso', 'ela', 'entre', 'depois', 'sem', 'mesmo', 'aos', 'são', 'está', 'ter', 'ser', 'foi', 'era', 'há', 'estão', 'você', 'nós', 'eles', 'elas'},
967
+ 'spanish': {'de', 'que', 'el', 'en', 'y', 'a', 'los', 'del', 'se', 'las', 'por', 'un', 'para', 'con', 'no', 'una', 'su', 'al', 'es', 'lo', 'como', 'más', 'pero', 'sus', 'le', 'ya', 'o', 'fue', 'este', 'ha', 'si', 'porque', 'esta', 'son', 'entre', 'está', 'cuando', 'muy', 'sin', 'sobre', 'ser', 'también', 'me', 'hasta', 'hay', 'donde', 'han', 'quien', 'están', 'desde', 'todo', 'nos', 'durante', 'todos', 'uno', 'les', 'ni', 'contra', 'otros', 'fueron', 'ese', 'eso', 'ante', 'ellos', 'yo', 'tú', 'él', 'ella', 'nosotros', 'usted', 'ustedes'},
968
+ }
969
+
970
+ def detect_language(text):
971
+ """Detect language from text content using stopword + character analysis."""
972
+ if not text:
973
+ return 'vietnamese'
974
+ text_lower = text.lower()
975
+ text_chars = set(text_lower)
976
+
977
+ # Strong signal: Vietnamese unique characters
978
+ vn_chars = len(text_chars & _UNIQUE_CHARS['vietnamese'])
979
+ if vn_chars >= 2:
980
+ return 'vietnamese'
981
+
982
+ # Spanish unique chars (ñ, ¿, ¡)
983
+ es_chars = len(text_chars & _UNIQUE_CHARS['spanish'])
984
+ pt_chars = len(text_chars & _UNIQUE_CHARS['portuguese'])
985
+
986
+ # Stopword scoring
987
+ words = set(re.findall(r'\b\w+\b', text_lower))
988
+ scores = {}
989
+ for lang, stops in _STOPWORDS.items():
990
+ scores[lang] = len(words & stops) / max(len(stops), 1)
991
+
992
+ # Disambiguate Portuguese vs Spanish
993
+ pt_markers = {'não', 'pelo', 'pela', 'isso', 'há', 'estão', 'num', 'numa', 'tenho', 'posso', 'você', 'nós', 'eles', 'elas', 'também', 'muito', 'já', 'só', 'até', 'entre', 'depois', 'sem', 'mesmo', 'aos', 'serão'}
994
+ es_markers = {'pero', 'está', 'están', 'porque', 'también', 'hasta', 'donde', 'quien', 'fue', 'son', 'fueron', 'ese', 'eso', 'ante', 'ellos', 'ella', 'nosotros', 'usted', 'ustedes', 'tú', 'él', 'desde', 'todo', 'durante', 'todos', 'uno', 'les', 'ni', 'contra', 'otros', 'fueron'}
995
+
996
+ pt_overlap = len(words & pt_markers)
997
+ es_overlap = len(words & es_markers)
998
+
999
+ if scores.get('portuguese', 0) > 0 and pt_overlap > es_overlap:
1000
+ return 'portuguese'
1001
+ if scores.get('spanish', 0) > 0 and es_overlap > pt_overlap:
1002
+ return 'spanish'
1003
+ if scores.get('english', 0) > 0.15:
1004
+ return 'english'
1005
+
1006
+ best = max(scores, key=scores.get)
1007
+ return best if scores[best] > 0.05 else 'vietnamese'
1008
+
1009
+ # Emotion keyword-based detection
1010
+ _EMOTION_KEYWORDS = {
1011
+ 'happy': {
1012
+ 'en': ['happy', 'joy', 'wonderful', 'great', 'amazing', 'fantastic', 'love', 'excellent', 'beautiful', 'glad', 'delighted', 'pleased', 'cheerful', 'celebrate', 'victory', 'win', 'success'],
1013
+ 'pt': ['feliz', 'alegria', 'maravilhoso', 'ótimo', 'incrível', 'fantástico', 'amor', 'excelente', 'lindo', 'contente', 'encantado', 'vitória', 'sucesso'],
1014
+ 'es': ['feliz', 'alegria', 'maravilloso', 'genial', 'increíble', 'fantástico', 'amor', 'excelente', 'hermoso', 'contento', 'encantado', 'victoria', 'éxito'],
1015
+ 'vi': ['vui', 'hạnh phúc', 'tuyệt vời', 'tuyệt', 'ý nghĩa', 'đẹp', 'thích', 'yêu', 'vui vẻ', 'hân hoan', 'phấn khích', 'chiến thắng', 'thành công'],
1016
+ },
1017
+ 'sad': {
1018
+ 'en': ['sad', 'unhappy', 'terrible', 'awful', 'horrible', 'miserable', 'depressed', 'grief', 'sorrow', 'tragic', 'unfortunate', 'painful', 'death', 'die', 'kill'],
1019
+ 'pt': ['triste', 'infeliz', 'terrível', 'horrível', 'miserável', 'deprimido', 'dor', 'trágico', 'infelizmente', 'penoso', 'morte', 'morrer'],
1020
+ 'es': ['triste', 'infeliz', 'terrible', 'horrible', 'miserable', 'deprimido', 'dolor', 'trágico', 'desafortunado', 'penoso', 'muerte', 'morir'],
1021
+ 'vi': ['buồn', 'không vui', 'tồi tệ', 'kinh khủng', 'đau khổ', 'đau buồn', 'bi thương', 'khốn nạn', 'đau đớn', 'thảm họa', 'chết', 'mất'],
1022
+ },
1023
+ 'excited': {
1024
+ 'en': ['excited', 'thrilling', 'amazing', 'wow', 'incredible', 'unbelievable', 'awesome', 'exhilarating', 'electrifying', 'breathtaking', 'breakthrough', 'record'],
1025
+ 'pt': ['animado', 'emocionante', 'incrível', 'impressionante', 'sensacional', 'eletrizante', 'empolgante', 'recorde'],
1026
+ 'es': ['emocionante', 'increíble', 'impresionante', 'sensacional', 'electrizante', 'emocionado', 'entusiasmado', 'récord'],
1027
+ 'vi': ['hào hứng', 'phấn khích', 'thú vị', 'tuyệt cú mèo', 'đỉnh cao', 'ngoạn mục', 'sục sôi', 'kỷ lục', 'đột phá'],
1028
+ },
1029
+ 'humorous': {
1030
+ 'en': ['funny', 'hilarious', 'joke', 'laugh', 'comedy', 'humor', 'amusing', 'witty', 'sarcastic', 'ironic', 'ridiculous', 'absurd', 'lol', 'haha'],
1031
+ 'pt': ['engraçado', 'hilário', 'piada', 'rir', 'comédia', 'humor', 'divertido', 'irônico', 'ridículo', 'absurdo', 'kkk'],
1032
+ 'es': ['gracioso', 'hilarante', 'broma', 'risa', 'comedia', 'humor', 'divertido', 'irónico', 'ridículo', 'absurdo', 'jaja'],
1033
+ 'vi': ['hài hước', 'buồn cười', 'đùa', 'cười', 'hài', 'vui nhộn', 'hóm hỉnh', 'mỉa mai', 'lố bịch', 'vô lý', 'haha'],
1034
+ },
1035
+ 'serious': {
1036
+ 'en': ['serious', 'critical', 'important', 'urgent', 'severe', 'grave', 'significant', 'crucial', 'vital', 'essential', 'alarming', 'concerning', 'crisis', 'war', 'conflict'],
1037
+ 'pt': ['sério', 'crítico', 'importante', 'urgente', 'grave', 'significativo', 'crucial', 'vital', 'essencial', 'preocupante', 'crise', 'guerra', 'conflito'],
1038
+ 'es': ['serio', 'crítico', 'importante', 'urgente', 'grave', 'significativo', 'crucial', 'vital', 'esencial', 'preocupante', 'crisis', 'guerra', 'conflicto'],
1039
+ 'vi': ['nghiêm trọng', 'quan trọng', 'khẩn cấp', 'nghiêm túc', 'đáng kể', 'thiết yếu', 'cần thiết', 'báo động', 'lo ngại', 'khủng hoảng', 'chiến tranh', 'xung đột'],
1040
+ },
1041
+ }
1042
+
1043
+ def detect_emotion(text, language='vietnamese'):
1044
+ """Detect emotion from text using keyword matching."""
1045
+ if not text:
1046
+ return 'neutral'
1047
+ text_lower = text.lower()
1048
+
1049
+ scores = {}
1050
+ for emotion, lang_keywords in _EMOTION_KEYWORDS.items():
1051
+ keywords = lang_keywords.get(language, lang_keywords.get('en', []))
1052
+ score = sum(1 for kw in keywords if kw in text_lower)
1053
+ scores[emotion] = score
1054
+
1055
+ if max(scores.values()) == 0:
1056
+ return 'neutral'
1057
+
1058
+ return max(scores, key=scores.get)
1059
+
1060
+ def detect_language_and_emotion(title, text):
1061
+ """Detect both language and emotion from article content."""
1062
+ combined = f"{title} {text}"
1063
+ lang = detect_language(combined)
1064
+ emotion = detect_emotion(combined, lang)
1065
+ return lang, emotion
1066
+
1067
+ # Voice selection based on language and emotion (using MultilingualNeural voices)
1068
+ VOICE_BY_LANG_EMOTION = {
1069
+ 'vietnamese': {
1070
+ 'happy': ('vi-VN-HoaiMyNeural', 'vui'),
1071
+ 'sad': ('vi-VN-NamMinhNeural', 'buồn'),
1072
+ 'excited': ('vi-VN-HoaiMyNeural', 'hào hứng'),
1073
+ 'humorous': ('vi-VN-HoaiMyNeural', 'vui'),
1074
+ 'serious': ('vi-VN-NamMinhNeural', 'nghiêm túc'),
1075
+ 'neutral': ('vi-VN-HoaiMyNeural', 'trung_tinh'),
1076
+ },
1077
+ 'portuguese': {
1078
+ 'happy': ('pt-BR-ThalitaMultilingualNeural', 'feliz'),
1079
+ 'sad': ('pt-BR-ThalitaMultilingualNeural', 'triste'),
1080
+ 'excited': ('pt-BR-ThalitaMultilingualNeural', 'animado'),
1081
+ 'humorous': ('pt-BR-ThalitaMultilingualNeural', 'engraçado'),
1082
+ 'serious': ('pt-BR-ThalitaMultilingualNeural', 'sério'),
1083
+ 'neutral': ('pt-BR-ThalitaMultilingualNeural', 'neutro'),
1084
+ },
1085
+ 'english': {
1086
+ 'happy': ('en-US-AndrewMultilingualNeural', 'happy'),
1087
+ 'sad': ('en-AU-WilliamMultilingualNeural', 'sad'),
1088
+ 'excited': ('en-US-AndrewMultilingualNeural', 'excited'),
1089
+ 'humorous': ('en-US-AndrewMultilingualNeural', 'funny'),
1090
+ 'serious': ('en-AU-WilliamMultilingualNeural', 'serious'),
1091
+ 'neutral': ('en-US-AndrewMultilingualNeural', 'neutral'),
1092
+ },
1093
+ 'french': {
1094
+ 'happy': ('fr-FR-VivienneMultilingualNeural', 'heureux'),
1095
+ 'sad': ('fr-FR-RemyMultilingualNeural', 'triste'),
1096
+ 'excited': ('fr-FR-VivienneMultilingualNeural', 'excité'),
1097
+ 'humorous': ('fr-FR-VivienneMultilingualNeural', 'drôle'),
1098
+ 'serious': ('fr-FR-RemyMultilingualNeural', 'sérieux'),
1099
+ 'neutral': ('fr-FR-VivienneMultilingualNeural', 'neutre'),
1100
+ },
1101
+ 'german': {
1102
+ 'happy': ('de-DE-SeraphinaMultilingualNeural', 'glücklich'),
1103
+ 'sad': ('de-DE-FlorianMultilingualNeural', 'traurig'),
1104
+ 'excited': ('de-DE-SeraphinaMultilingualNeural', 'aufgeregt'),
1105
+ 'humorous': ('de-DE-SeraphinaMultilingualNeural', 'lustig'),
1106
+ 'serious': ('de-DE-FlorianMultilingualNeural', 'ernst'),
1107
+ 'neutral': ('de-DE-SeraphinaMultilingualNeural', 'neutral'),
1108
+ },
1109
+ 'korean': {
1110
+ 'happy': ('ko-KR-HyunsuMultilingualNeural', '행복'),
1111
+ 'sad': ('ko-KR-HyunsuMultilingualNeural', '슬픔'),
1112
+ 'excited': ('ko-KR-HyunsuMultilingualNeural', '흥분'),
1113
+ 'humorous': ('ko-KR-HyunsuMultilingualNeural', '유쾌'),
1114
+ 'serious': ('ko-KR-HyunsuMultilingualNeural', '진지'),
1115
+ 'neutral': ('ko-KR-HyunsuMultilingualNeural', '중립'),
1116
+ },
1117
+ 'italian': {
1118
+ 'happy': ('it-IT-GiuseppeMultilingualNeural', 'felice'),
1119
+ 'sad': ('it-IT-GiuseppeMultilingualNeural', 'triste'),
1120
+ 'excited': ('it-IT-GiuseppeMultilingualNeural', 'emozionato'),
1121
+ 'humorous': ('it-IT-GiuseppeMultilingualNeural', 'divertente'),
1122
+ 'serious': ('it-IT-GiuseppeMultilingualNeural', 'serio'),
1123
+ 'neutral': ('it-IT-GiuseppeMultilingualNeural', 'neutro'),
1124
+ },
1125
+ }
1126
+
1127
+ # All valid voice IDs (new MultilingualNeural format)
1128
+ VALID_VOICES = {
1129
+ 'vi-VN-HoaiMyNeural', 'vi-VN-NamMinhNeural',
1130
+ 'en-US-AndrewMultilingualNeural', 'en-AU-WilliamMultilingualNeural',
1131
+ 'pt-BR-ThalitaMultilingualNeural',
1132
+ 'fr-FR-VivienneMultilingualNeural', 'fr-FR-RemyMultilingualNeural',
1133
+ 'de-DE-SeraphinaMultilingualNeural', 'de-DE-FlorianMultilingualNeural',
1134
+ 'ko-KR-HyunsuMultilingualNeural',
1135
+ 'it-IT-GiuseppeMultilingualNeural',
1136
+ }
1137
+
1138
+ def get_voice_for_content(title, text, preferred_voice=None):
1139
+ """Get appropriate voice based on content language and emotion."""
1140
+ # Accept the new MultilingualNeural voices directly
1141
+ if preferred_voice and preferred_voice in VALID_VOICES:
1142
+ return preferred_voice
1143
+
1144
+ # Also accept old shorthand voice IDs and map them to new format
1145
+ old_voice_map = {
1146
+ 'hoaimy': 'vi-VN-HoaiMyNeural',
1147
+ 'namminh': 'vi-VN-NamMinhNeural',
1148
+ 'andrew': 'en-US-AndrewMultilingualNeural',
1149
+ 'jenny': 'en-US-AndrewMultilingualNeural',
1150
+ 'thalita': 'pt-BR-ThalitaMultilingualNeural',
1151
+ 'pt_thalita': 'pt-BR-ThalitaMultilingualNeural',
1152
+ 'pt_francisco': 'pt-BR-ThalitaMultilingualNeural',
1153
+ 'ela': 'en-US-AndrewMultilingualNeural',
1154
+ 'es_carlos': 'en-US-AndrewMultilingualNeural',
1155
+ 'denise': 'fr-FR-VivienneMultilingualNeural',
1156
+ 'katja': 'de-DE-SeraphinaMultilingualNeural',
1157
+ 'nanami': 'en-US-AndrewMultilingualNeural',
1158
+ 'sunhee': 'ko-KR-HyunsuMultilingualNeural',
1159
+ 'xiaochen': 'en-US-AndrewMultilingualNeural',
1160
+ }
1161
+ if preferred_voice and preferred_voice in old_voice_map:
1162
+ return old_voice_map[preferred_voice]
1163
+
1164
+ lang, emotion = detect_language_and_emotion(title, text)
1165
+ lang_map = VOICE_BY_LANG_EMOTION.get(lang, VOICE_BY_LANG_EMOTION['vietnamese'])
1166
+ voice, _ = lang_map.get(emotion, lang_map['neutral'])
1167
+ return voice
1168
+
1169
+
1170
+ def _is_relevant_image(img_url, title, text):
1171
+ """Check if an image is relevant to the article content."""
1172
+ if not img_url:
1173
+ return False
1174
+ skip_patterns = ['pixel', 'analytics', 'tracking', '1x1.gif', 'spacer.gif',
1175
+ 'logo', 'icon', 'avatar', 'emoji', 'smiley', 'sprite',
1176
+ 'advertisement', 'ad-banner', 'sponsored', 'banner-ads']
1177
+ img_lower = img_url.lower()
1178
+ for p in skip_patterns:
1179
+ if p in img_lower:
1180
+ return False
1181
+ if not any(img_lower.endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.webp', '.gif']):
1182
+ return False
1183
+ return True
1184
+
1185
+
1186
+ def _filter_relevant_images(images, title, text, max_images=8):
1187
+ """Filter and rank images by relevance to article content."""
1188
+ if not images:
1189
+ return []
1190
+ seen = set()
1191
+ relevant = []
1192
+ for img in images:
1193
+ if img in seen:
1194
+ continue
1195
+ seen.add(img)
1196
+ if _is_relevant_image(img, title, text):
1197
+ relevant.append(img)
1198
+ return relevant[:max_images]
1199
+
1200
+
1201
+ def _scrape_article_for_rewrite(url):
1202
+ """Scrape article: extract title, paragraphs, RELEVANT images, OG image."""
1203
+ try:
1204
+ r = req.get(url, headers=_UA_RW, timeout=15, allow_redirects=True)
1205
+ r.encoding = 'utf-8'
1206
+ soup = BeautifulSoup(r.text, 'lxml')
1207
+ for tag in soup.find_all(['script', 'style', 'nav', 'footer', 'aside', 'form']):
1208
+ tag.decompose()
1209
+ h1 = soup.find('h1')
1210
+ ogt = soup.find('meta', property='og:title')
1211
+ title = (h1.get_text(strip=True) if h1 else '') or (ogt.get('content', '') if ogt else '')
1212
+ ogi = soup.find('meta', property='og:image')
1213
+ og_img = ogi.get('content', '') if ogi else ''
1214
+ if og_img and og_img.startswith('//'):
1215
+ og_img = 'https:' + og_img
1216
+ block = None
1217
+ for sel in ['article', '.singular-content', '.detail-content', '.fck_detail', '.content-detail', '.knc-content', 'main', '.cms-body', '.article__body']:
1218
+ el = soup.select_one(sel)
1219
+ if el and len(el.find_all('p')) >= 2:
1220
+ block = el
1221
+ break
1222
+ if not block:
1223
+ block = soup.body or soup
1224
+ paragraphs = []
1225
+ all_images = []
1226
+ seen_imgs = set()
1227
+ if og_img and og_img not in seen_imgs:
1228
+ all_images.append(og_img)
1229
+ seen_imgs.add(og_img)
1230
+ for el in block.find_all(['p', 'h2', 'h3', 'figure', 'img'], recursive=True):
1231
+ if el.name == 'p':
1232
+ t = _clean(el.get_text(strip=True))
1233
+ if t and len(t) > 40:
1234
+ paragraphs.append(t)
1235
+ elif el.name in ('figure', 'img'):
1236
+ im = el if el.name == 'img' else el.find('img')
1237
+ if im:
1238
+ src = im.get('data-src') or im.get('src') or im.get('data-original') or ''
1239
+ if src and 'base64' not in src:
1240
+ if src.startswith('//'):
1241
+ src = 'https:' + src
1242
+ if src not in seen_imgs:
1243
+ all_images.append(src)
1244
+ seen_imgs.add(src)
1245
+ # Filter to relevant images only
1246
+ relevant_images = _filter_relevant_images(all_images, title, ' '.join(paragraphs[:5]))
1247
+ return {'title': _clean(title), 'paragraphs': paragraphs, 'images': relevant_images, 'og_img': og_img}
1248
+ except Exception:
1249
+ return None
1250
+
1251
+
1252
+ def _extract_key_points_rw(paragraphs, max_points=5):
1253
+ r"""Extract key points from paragraphs - extracts ALL sentences, not just first one.
1254
+
1255
+ Fixes: Original regex `^(.+?[.!?])\s` only captured first sentence per paragraph.
1256
+ Now splits on all sentence boundaries and takes valid sentences until max_points.
1257
+ """
1258
+ points = []
1259
+
1260
+ for p in paragraphs:
1261
+ if len(points) >= max_points:
1262
+ break
1263
+
1264
+ p = _clean(p)
1265
+ if not p:
1266
+ continue
1267
+
1268
+ # Split paragraph into sentences using Vietnamese + English punctuation
1269
+ sentences = re.split(r'(?<=[.!?])\s+(?=[A-ZÀ-Ỹ0-9])', p)
1270
+ sentences = [s.strip() for s in sentences if s.strip()]
1271
+
1272
+ for sentence in sentences:
1273
+ if len(points) >= max_points:
1274
+ break
1275
+
1276
+ # Clean sentence - remove extra whitespace
1277
+ sentence = _clean(sentence)
1278
+
1279
+ if len(sentence) < 30:
1280
+ continue
1281
+
1282
+ # Check for duplicates
1283
+ if any(sentence[:60] in existing for existing in points):
1284
+ continue
1285
+
1286
+ # Ensure sentence ends with punctuation
1287
+ if not sentence.endswith(('.', '!', '?')):
1288
+ sentence = sentence + '.'
1289
+
1290
+ points.append(sentence)
1291
+
1292
+ # If no valid sentences found, take chunks from raw text
1293
+ if not points:
1294
+ raw = '\n'.join(paragraphs)
1295
+ for i in range(0, min(len(raw), max_points * 300), 280):
1296
+ chunk = _clean(raw[i:i+280])
1297
+ if len(chunk) >= 30 and chunk not in points:
1298
+ points.append(chunk + ('.' if not chunk.endswith('.') else ''))
1299
+ if len(points) >= max_points:
1300
+ break
1301
+
1302
+ return points
1303
+
1304
+
1305
+ @app.post("/api/rewrite_slide")
1306
+ async def api_rewrite_slide(request: Request):
1307
+ """Fast rewrite as SLIDES - no AI needed, instant response."""
1308
+ body = await request.json()
1309
+ url = _clean(body.get("url", ""))
1310
+ context = body.get("context", "")
1311
+ preferred_voice = body.get("voice", "") # Accept custom voice selection
1312
+ if not url and not context:
1313
+ return JSONResponse({"error": "Cần URL hoặc nội dung"}, status_code=400)
1314
+ data = None
1315
+ if url and url.startswith("http"):
1316
+ data = _scrape_article_for_rewrite(url)
1317
+ if not data and context:
1318
+ paragraphs = [_clean(p) for p in context.split('\n') if len(_clean(p)) > 40]
1319
+ data = {'title': paragraphs[0][:80] if paragraphs else 'Bài viết', 'paragraphs': paragraphs, 'images': [], 'og_img': ''}
1320
+ if not data or not data.get('paragraphs'):
1321
+ return JSONResponse({"error": "Không đọc được bài viết"}, status_code=422)
1322
+ points = _extract_key_points_rw(data['paragraphs'], max_points=12)
1323
+ if not points:
1324
+ return JSONResponse({"error": "Không tìm được ý chính"}, status_code=422)
1325
+ images = data.get('images', [])
1326
+ slides = []
1327
+ for i, point in enumerate(points):
1328
+ img = images[i] if i < len(images) else (images[-1] if images else '')
1329
+ if img and 'cdnphoto.dantri' in img:
1330
+ img = '/api/proxy/img?url=' + _quote2(img, safe='')
1331
+ slides.append({'text': point, 'image': img, 'index': i + 1})
1332
+ summary_text = '\n\n'.join([f"• {s['text']}" for s in slides])
1333
+
1334
+ # Auto-detect language and emotion
1335
+ lang, emotion = detect_language_and_emotion(data['title'], summary_text)
1336
+ # Use preferred voice if provided, otherwise auto-detect
1337
+ voice = preferred_voice if preferred_voice else get_voice_for_content(data['title'], summary_text)
1338
+
1339
+ post = {
1340
+ "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)),
1341
+ "title": data['title'],
1342
+ "text": summary_text,
1343
+ "img": images[0] if images else '',
1344
+ "url": url,
1345
+ "kind": "slide_summary",
1346
+ "slides": slides,
1347
+ "images": images[:10],
1348
+ "video": "",
1349
+ "voice": voice,
1350
+ "emotion": emotion,
1351
+ "language": lang,
1352
+ "ts": int(time.time())
1353
+ }
1354
+ posts = _load_wall_posts()
1355
+ posts.insert(0, post)
1356
+ _save_wall_posts(posts)
1357
+ return JSONResponse({"post": post, "slides": slides})
1358
+
1359
+
1360
+ @app.post("/api/rewrite_share")
1361
+ async def api_rewrite_share(request: Request):
1362
+ """Rewrite article and post to Tường AI with SLIDES + AI text."""
1363
+ body = await request.json()
1364
+ url = _clean(body.get("url", ""))
1365
+ ctx = _clean(body.get("context", ""))
1366
+ preferred_voice = body.get("voice", "") # Accept custom voice selection
1367
+ if not url and not ctx:
1368
+ return JSONResponse({"error": "Cần URL hoặc nội dung"}, status_code=400)
1369
+ data = None
1370
+ if url and url.startswith("http"):
1371
+ data = _scrape_article_for_rewrite(url)
1372
+ if not data and ctx:
1373
+ paragraphs = [_clean(p) for p in ctx.split('\n') if len(_clean(p)) > 40]
1374
+ data = {'title': paragraphs[0][:80] if paragraphs else 'Bài viết', 'paragraphs': paragraphs, 'images': [], 'og_img': ''}
1375
+ if not data or not data.get('paragraphs'):
1376
+ return JSONResponse({"error": "Không đọc được bài viết"}, status_code=422)
1377
+ raw_text = '\n'.join(data['paragraphs'])
1378
+ if len(raw_text) < 50:
1379
+ raw_text = ctx[:14000]
1380
+ if len(raw_text) < 50:
1381
+ return JSONResponse({"error": "Bài viết quá ngắn"}, status_code=422)
1382
+ domain = ''
1383
+ try:
1384
+ from urllib.parse import urlparse
1385
+ domain = urlparse(url).netloc.replace('www.', '')
1386
+ except:
1387
+ pass
1388
+
1389
+ # Generate AI summary text
1390
+ ai_text = None
1391
+ try:
1392
+ import ai_ext
1393
+ if hasattr(ai_ext, 'qwen_generate'):
1394
+ prompt = f'Tóm tắt đăng Tường AI:\nTiêu đề: {data["title"]}\n{raw_text[:14000]}\n\n4-6 ý chính. Cuối ghi nguồn.'
1395
+ ai_text = await ai_ext.qwen_generate(prompt, max_tokens=1000)
1396
+ except Exception:
1397
+ pass
1398
+ if not ai_text or len(ai_text) < 80:
1399
+ key_pts = _extract_key_points_rw(data['paragraphs'], max_points=12)
1400
+ if key_pts:
1401
+ ai_text = '\n\n'.join([f"• {p}" for p in key_pts])
1402
+ else:
1403
+ ai_text = f"Tóm tắt: {data['title']}\n\n{raw_text[:1200]}\n\nNguồn: {domain}"
1404
+
1405
+ # Build slides from key points (FIX: include slides in rewrite_share too!)
1406
+ points = _extract_key_points_rw(data['paragraphs'], max_points=12)
1407
+ images = data.get('images', [])
1408
+ slides = []
1409
+ for i, point in enumerate(points):
1410
+ img = images[i] if i < len(images) else (images[-1] if images else '')
1411
+ if img and 'cdnphoto.dantri' in img:
1412
+ img = '/api/proxy/img?url=' + _quote2(img, safe='')
1413
+ slides.append({'text': point, 'image': img, 'index': i + 1})
1414
+
1415
+ # Auto-detect language and emotion
1416
+ lang, emotion = detect_language_and_emotion(data['title'], ai_text)
1417
+ # Use preferred voice if provided, otherwise auto-detect
1418
+ voice = preferred_voice if preferred_voice else get_voice_for_content(data['title'], ai_text)
1419
+
1420
+ post = {
1421
+ "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)),
1422
+ "title": data['title'],
1423
+ "text": ai_text,
1424
+ "img": images[0] if images else '',
1425
+ "url": url,
1426
+ "kind": "rewrite",
1427
+ "slides": slides,
1428
+ "images": images[:10],
1429
+ "video": "",
1430
+ "voice": voice,
1431
+ "emotion": emotion,
1432
+ "language": lang,
1433
+ "ts": int(time.time())
1434
+ }
1435
+ posts = _load_wall_posts()
1436
+ posts.insert(0, post)
1437
+ _save_wall_posts(posts)
1438
+ return JSONResponse({"post": post, "slides": slides})
1439
+
1440
+
1441
+ @app.post("/api/url_wall")
1442
+ async def api_url_wall(request: Request):
1443
+ """Submit URL to add to Tường AI."""
1444
+ body = await request.json()
1445
+ url = _clean(body.get("url", ""))
1446
+ if not url or not url.startswith('http'):
1447
+ return JSONResponse({"error": "URL không hợp lệ"}, status_code=400)
1448
+ # Reuse rewrite_share logic
1449
+ req._body = json.dumps({"url": url}).encode()
1450
+ return await api_rewrite_share(request)
1451
+
1452
+
1453
+ def _bg():
1454
+ time.sleep(15)
1455
+ while True:
1456
+ try:get_wc2026_all()
1457
+ except:pass
1458
+ time.sleep(90)
1459
+ threading.Thread(target=_bg,daemon=True).start()
1460
+
1461
+ # ===== AUTO SCHEDULER: rewrite AI + short at 7/13/19 VN time =====
1462
+ _AUTO_SCHEDULE_TIMES = [(7, '07:00'), (13, '13:00'), (19, '19:00')]
1463
+ _AUTO_LOG = os.path.join(DATA_DIR, 'auto_rewrite_log.json')
1464
+
1465
+ def _load_auto_log():
1466
+ try:
1467
+ if os.path.exists(_AUTO_LOG):
1468
+ with open(_AUTO_LOG, 'r') as f:
1469
+ return json.load(f)
1470
+ except: pass
1471
+ return {}
1472
+
1473
+ def _save_auto_log(log):
1474
+ try:
1475
+ tmp = _AUTO_LOG + '.tmp'
1476
+ with open(tmp, 'w') as f:
1477
+ json.dump(log, f)
1478
+ os.replace(tmp, _AUTO_LOG)
1479
+ except: pass
1480
+
1481
+ async def _auto_fetch_short(post_id):
1482
+ """Try to auto-generate a short for a post."""
1483
+ try:
1484
+ import httpx
1485
+ async with httpx.AsyncClient(timeout=180) as cl:
1486
+ r = await cl.post(
1487
+ f"http://localhost:7860/api/ai/short/{post_id}",
1488
+ json={"voice":"vi-VN-HoaiMyNeural","emotion":"neutral","speed":1.2},
1489
+ headers={"Content-Type":"application/json"}
1490
+ )
1491
+ if r.status_code < 300:
1492
+ sj = r.json()
1493
+ if sj.get('video'):
1494
+ posts = _load_wall_posts()
1495
+ for p in posts:
1496
+ if p.get('id') == post_id:
1497
+ p['video'] = sj['video']
1498
+ break
1499
+ _save_wall_posts(posts)
1500
+ return True
1501
+ except: pass
1502
+ return False
1503
+
1504
+ async def _auto_rewrite_one(topic, slot_label, used_urls=None, post_index=0):
1505
+ """Rewrite one topic: find articles, summarize, post to wall, trigger short.
1506
+ used_urls: shared set to avoid duplicate articles across topics.
1507
+ post_index: 0-based index to create multiple posts per topic (0,1,2 = up to 3 posts)."""
1508
+ from urllib.parse import quote as _q
1509
+ # Get MORE items to support 1-3 posts per topic
1510
+ items = _search_all(topic, limit=12)
1511
+ # Skip URLs already used by another topic
1512
+ if used_urls is not None:
1513
+ filtered = [it for it in items if it.get('url') not in used_urls]
1514
+ if filtered:
1515
+ items = filtered
1516
+ if not items or post_index >= len(items):
1517
+ return False
1518
+
1519
+ # Get article at post_index (0,1,2 for multiple posts)
1520
+ item = items[post_index] # post_index allows multiple articles per topic
1521
+ url = item.get('url', '')
1522
+ title = item.get('title', topic)
1523
+ if url and used_urls is not None:
1524
+ used_urls.add(url)
1525
+ if not url.startswith('http'):
1526
+ return False
1527
+
1528
+ data = _scrape_article_for_rewrite(url)
1529
+ if not data or not data.get('paragraphs'):
1530
+ return False
1531
+
1532
+ raw_text = '\n'.join(data['paragraphs'])
1533
+ ai_text = None
1534
+
1535
+ # Try AI generation
1536
+ try:
1537
+ import ai_ext
1538
+ prompt = f"Tóm tắt tin tức (tự động {slot_label}):\nTiêu đề: {data['title']}\n{raw_text[:10000]}\n\n4-6 ý chính dạng bullet. Cuối ghi nguồn."
1539
+ ai_text = await ai_ext.qwen_generate(prompt, max_tokens=1000)
1540
+ except: pass
1541
+
1542
+ if not ai_text or len(ai_text) < 80:
1543
+ pts = data['paragraphs'][:6]
1544
+ ai_text = '\n\n'.join([f"• {p[:300]}" for p in pts])
1545
+ via = item.get('via', '') or urlparse(url).netloc.replace('www.', '')
1546
+ ai_text += f"\n\nNguồn tham khảo: {via}"
1547
+
1548
+ # Build slides
1549
+ images = data.get('images', [])
1550
+ pts = data['paragraphs'][:10]
1551
+ slides = []
1552
+ for i, p in enumerate(pts[:8]):
1553
+ img = images[i] if i < len(images) else (images[-1] if images else data.get('og_img', ''))
1554
+ slides.append({'text': p[:300], 'image': img, 'index': i + 1})
1555
+
1556
+ post_id = str(int(time.time() * 1000)) + str(_random2.randint(100, 999))
1557
+ post = {
1558
+ "id": post_id, "title": data.get('title', title)[:200],
1559
+ "text": ai_text, "img": images[0] if images else data.get('og_img', ''),
1560
+ "url": url, "kind": "auto_rewrite", "slides": slides,
1561
+ "images": images[:10], "video": "",
1562
+ "voice": "vi-VN-HoaiMyNeural", "emotion": "neutral",
1563
+ "language": "vietnamese", "ts": int(time.time()),
1564
+ "auto_scheduled": True, "slot": slot_label,
1565
+ }
1566
+
1567
+ posts = _load_wall_posts()
1568
+ posts.insert(0, post)
1569
+ _save_wall_posts(posts)
1570
+
1571
+ # Trigger short generation async
1572
+ threading.Thread(target=lambda: asyncio.run(_auto_fetch_short(post_id)), daemon=True).start()
1573
+ return True
1574
+
1575
+ async def _do_scheduled_run(slot_label):
1576
+ """Main scheduled run: 1-3 posts from 3 different HOT topics (3-9 total), no duplicates."""
1577
+ print(f"[auto] Starting scheduled rewrite for {slot_label}")
1578
+
1579
+ # Get top hot topics, skip duplicates
1580
+ all_topics = _get_hot_topics()
1581
+ seen_topics = set()
1582
+ unique_topics = []
1583
+ for t in all_topics:
1584
+ kw = t.get('topic', '').lower().strip()
1585
+ if kw and len(kw) > 5 and kw not in seen_topics:
1586
+ is_dup = False
1587
+ for s in seen_topics:
1588
+ # Check if one topic is substring of another
1589
+ if kw in s or s in kw:
1590
+ is_dup = True
1591
+ break
1592
+ if not is_dup:
1593
+ seen_topics.add(kw)
1594
+ unique_topics.append(t)
1595
+ if len(unique_topics) >= 3:
1596
+ break
1597
+
1598
+ job_topics = [t['topic'] for t in unique_topics[:3] if t.get('topic')]
1599
+ if not job_topics:
1600
+ print(f"[auto] No hot topics found, skipping")
1601
+ return
1602
+
1603
+ print(f"[auto] Running 3 topics: {job_topics}")
1604
+
1605
+ # Track used URLs to avoid cross-topic duplicates
1606
+ _used_urls = set()
1607
+ results = []
1608
+
1609
+ # Process each topic, create 1-3 posts per topic
1610
+ for jt in job_topics:
1611
+ for post_idx in range(3): # Try up to 3 posts per topic
1612
+ try:
1613
+ ok = await asyncio.wait_for(_auto_rewrite_one(jt, slot_label, _used_urls, post_idx), timeout=120)
1614
+ if ok:
1615
+ results.append((jt, post_idx, True))
1616
+ print(f"[auto] Created post {post_idx+1} for '{jt}'")
1617
+ else:
1618
+ # No more articles for this topic
1619
+ break
1620
+ except Exception as e:
1621
+ print(f"[auto] Error on '{jt}' post {post_idx}: {e}")
1622
+ results.append((jt, post_idx, False))
1623
+ await asyncio.sleep(1) # Small delay between posts
1624
+
1625
+ # Ensure at least 3 posts total (fallback if needed)
1626
+ successful_posts = sum(1 for _, _, ok in results if ok)
1627
+ print(f"[auto] Done {slot_label}: {successful_posts} posts created")
1628
+
1629
+ # Log
1630
+ from datetime import datetime, timezone, timedelta
1631
+ VN_TZ_SCHED = timezone(timedelta(hours=7))
1632
+ today_str = datetime.now(VN_TZ_SCHED).strftime('%Y-%m-%d')
1633
+ log = _load_auto_log()
1634
+ if today_str not in log: log[today_str] = {}
1635
+ log[today_str][slot_label] = {
1636
+ 'time': datetime.now(VN_TZ_SCHED).strftime('%H:%M:%S'),
1637
+ 'count': successful_posts,
1638
+ 'total': len(job_topics),
1639
+ }
1640
+ _save_auto_log(log)
1641
+
1642
+ def _scheduler_loop():
1643
+ """Check every 60s; trigger at 7:00, 13:00, 19:00 VN time.
1644
+ On startup, check for any missed slots today and run them immediately."""
1645
+ time.sleep(35)
1646
+ from datetime import datetime, timezone, timedelta
1647
+ VN_TZ_SCHED = timezone(timedelta(hours=7))
1648
+
1649
+ _last_run_date = ""
1650
+ _last_run_slots = set()
1651
+
1652
+ # On startup: check log for missed slots today
1653
+ try:
1654
+ start_now = datetime.now(VN_TZ_SCHED)
1655
+ today_str = start_now.strftime('%Y-%m-%d')
1656
+ current_hour = start_now.hour
1657
+ current_minute = start_now.minute
1658
+ log = _load_auto_log()
1659
+ today_log = log.get(today_str, {})
1660
+ for h, label in _AUTO_SCHEDULE_TIMES:
1661
+ # Run if slot is past (either strictly earlier hour, or same hour but window has passed)
1662
+ should_run = False
1663
+ if h < current_hour:
1664
+ should_run = True
1665
+ elif h == current_hour and current_minute > 10:
1666
+ should_run = True
1667
+ if should_run and label not in today_log:
1668
+ print(f"[auto] Detected missed slot {label} (h={h} < now={current_hour}:{current_minute}), running catch-up now")
1669
+ _run_scheduled_sync(label)
1670
+ _last_run_slots.add(label)
1671
+ except Exception as e:
1672
+ print(f"[auto] Catch-up check error: {e}")
1673
+
1674
+ while True:
1675
+ try:
1676
+ now = datetime.now(VN_TZ_SCHED)
1677
+ today = now.strftime('%Y-%m-%d')
1678
+ hour = now.hour
1679
+ minute = now.minute
1680
+
1681
+ if today != _last_run_date:
1682
+ _last_run_date = today
1683
+ _last_run_slots = set()
1684
+
1685
+ slot = None
1686
+ for h, label in _AUTO_SCHEDULE_TIMES:
1687
+ if hour == h and 0 <= minute < 5:
1688
+ slot = label
1689
+ break
1690
+
1691
+ if slot and slot not in _last_run_slots:
1692
+ _last_run_slots.add(slot)
1693
+ _run_scheduled_sync(slot)
1694
+ except Exception as e:
1695
+ print(f"[auto] Loop error: {e}")
1696
+
1697
+ time.sleep(60)
1698
+
1699
+ threading.Thread(target=_scheduler_loop, daemon=True, name='auto-rewrite-scheduler').start()
1700
+
1701
+ @app.get('/api/debug/auto_schedule')
1702
+ async def debug_auto_schedule(slot: str = '07:00'):
1703
+ """Manually trigger auto scheduler for debugging."""
1704
+ try:
1705
+ # Check if we can access the data directory
1706
+ log = _load_auto_log()
1707
+ topics = _get_hot_topics()[:3]
1708
+ job_topics = [t['topic'] for t in topics if t.get('topic')]
1709
+ return JSONResponse({
1710
+ "slot": slot,
1711
+ "log": log,
1712
+ "hot_topics": job_topics,
1713
+ "wall_posts_count": len(_load_wall_posts()),
1714
+ "data_dir_writable": os.access(DATA_DIR, os.W_OK) if os.path.isdir(DATA_DIR) else False,
1715
+ "data_dir_exists": os.path.isdir(DATA_DIR),
1716
+ })
1717
+ except Exception as e:
1718
+ return JSONResponse({"error": str(e)}, status_code=500)
1719
+
1720
+ def _run_scheduled_sync(slot):
1721
+ """Run _do_scheduled_run in a separate event loop (for background thread)."""
1722
+ loop = asyncio.new_event_loop()
1723
+ asyncio.set_event_loop(loop)
1724
+ try:
1725
+ loop.run_until_complete(_do_scheduled_run(slot))
1726
+ except Exception as e:
1727
+ print(f"[auto] Background run error: {e}")
1728
+ finally:
1729
+ loop.close()
1730
+
1731
+ @app.get('/api/debug/trigger_auto')
1732
+ async def debug_trigger_auto(slot: str = '19:00'):
1733
+ """Trigger _do_scheduled_run in background thread (non-blocking)."""
1734
+ threading.Thread(target=_run_scheduled_sync, args=(slot,), daemon=True).start()
1735
+ return JSONResponse({"status": "started", "slot": slot})
1736
+
1737
+ # ===== SHORTS RSS PROXY ENDPOINT =====
1738
+ @app.get("/api/shorts/rss")
1739
+ def shorts_rss():
1740
+ """Get shorts from YouTube RSS feeds server-side"""
1741
+ import xml.etree.ElementTree as ET
1742
+ import html as html_lib2
1743
+ import re as re2
1744
+
1745
+ YOUTUBE_CHANNELS = {
1746
+ "baodantri7941": "UC_x5TKhOgd6GhYvv5z4I3jg",
1747
+ "baosuckhoedoisongboyte": "UCBsY5fXTQLkF_JnH9kLkL4g",
1748
+ }
1749
+
1750
+ shorts = []
1751
+ seen = set()
1752
+
1753
+ for handle, channel_id in YOUTUBE_CHANNELS.items():
1754
+ try:
1755
+ rss_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}"
1756
+ r = req.get(rss_url, headers=HEADERS, timeout=15)
1757
+ if r.status_code != 200:
1758
+ continue
1759
+
1760
+ root = ET.fromstring(r.text)
1761
+ ns = {
1762
+ 'atom': 'http://www.w3.org/2005/Atom',
1763
+ 'yt': 'http://www.youtube.com/xml/schemas/2015',
1764
+ 'media': 'http://search.yahoo.com/mrss/'
1765
+ }
1766
+
1767
+ for entry in root.findall('atom:entry', ns)[:30]:
1768
+ title_el = entry.find('atom:title', ns)
1769
+ title = html_lib2.unescape(title_el.text) if title_el is not None and title_el.text else ''
1770
+
1771
+ link_el = entry.find('atom:link', ns)
1772
+ link = link_el.get('href', '') if link_el is not None else ''
1773
+
1774
+ vid_el = entry.find('yt:videoId', ns)
1775
+ vid = vid_el.text if vid_el is not None else ''
1776
+
1777
+ if not vid or vid in seen:
1778
+ continue
1779
+
1780
+ # Check if it's a short
1781
+ is_short = '#shorts' in title.lower() or '#short' in title.lower() or '/shorts/' in link
1782
+
1783
+ if not is_short:
1784
+ desc_el = entry.find('media:description', ns)
1785
+ if desc_el is not None and desc_el.text:
1786
+ if '#shorts' in desc_el.text.lower():
1787
+ is_short = True
1788
+
1789
+ if not is_short:
1790
+ continue
1791
+
1792
+ seen.add(vid)
1793
+
1794
+ # Get thumbnail
1795
+ thumb = f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg"
1796
+ media_group = entry.find('media:group', ns)
1797
+ if media_group is not None:
1798
+ thumb_el = media_group.find('media:thumbnail', ns)
1799
+ if thumb_el is not None:
1800
+ thumb = thumb_el.get('url', thumb)
1801
+
1802
+ shorts.append({
1803
+ 'id': vid,
1804
+ 'title': title.replace('#shorts', '').replace('#short', '').strip()[:120],
1805
+ 'img': thumb,
1806
+ 'link': f'https://www.youtube.com/shorts/{vid}',
1807
+ 'channel': handle,
1808
+ 'source': 'yt'
1809
+ })
1810
+
1811
+ if len(shorts) >= 40:
1812
+ break
1813
+
1814
+ except Exception as e:
1815
+ print(f"RSS error for {handle}: {e}")
1816
+ continue
1817
+
1818
+ return {"shorts": shorts, "count": len(shorts)}
1819
+
1820
+ app.mount('/static',StaticFiles(directory=STATIC_DIR),name='vnews_static')