bep40 commited on
Commit
58565b4
·
verified ·
1 Parent(s): ba24ffc

Update app_v2_entry.py - add app_v2_patch import to start auto scheduler

Browse files
Files changed (1) hide show
  1. app_v2_entry.py +8 -1864
app_v2_entry.py CHANGED
@@ -1,4 +1,4 @@
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
 
@@ -12,6 +12,12 @@ try:
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
@@ -29,1866 +35,4 @@ 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 url matches a wall post, 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 URL first (most reliable)
603
- post = None
604
- try:
605
- if url:
606
- posts = _load_wall_posts()
607
- for p in posts:
608
- if p.get('url') == url and p.get('slides'):
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
- # Fallback: any matching URL
615
- if not post and url:
616
- for p in posts:
617
- if p.get('url') == url:
618
- post = p
619
- safe_title = p.get('title', safe_title) or safe_title
620
- safe_img = p.get('img', safe_img) or safe_img
621
- safe_url = p.get('url', safe_url) or safe_url
622
- break
623
- except:
624
- pass
625
-
626
- if post and post.get('slides'):
627
- return _render_slides_page(post, safe_title, safe_img, safe_url)
628
-
629
- if post and post.get('video'):
630
- return _render_video_page(post, safe_title, safe_img, safe_url)
631
-
632
- # Otherwise redirect
633
- return HTMLResponse(f'''<!DOCTYPE html>
634
- <html lang="vi">
635
- <head>
636
- <meta charset="utf-8">
637
- <meta name="viewport" content="width=device-width,initial-scale=1">
638
- <title>{_clean(safe_title)}</title>
639
- <meta property="og:title" content="{_clean(safe_title)}">
640
- <meta property="og:image" content="{_clean(safe_img)}">
641
- <meta property="og:description" content="Tin tức tóm tắt, AI rewrite, World Cup 2026">
642
- <meta property="og:url" content="{SPACE}/s/{slug}">
643
- <link rel="canonical" href="{SPACE}/s/{slug}">
644
- <meta http-equiv="refresh" content="0;url={safe_url}">
645
- </head><body></body></html>''')
646
-
647
-
648
-
649
- @app.get('/api/proxy/img')
650
- def proxy_img(url: str = Query(default=""), max_size: int = Query(default=1200)):
651
- """Proxy image from blocked CDN to public URL."""
652
- from urllib.parse import unquote
653
- safe_url = unquote(url)
654
- import requests as _req
655
- try:
656
- r = _req.get(safe_url, timeout=10, headers={"User-Agent": "Mozilla/5.0"})
657
- if r.status_code == 200 and r.content:
658
- return Response(r.content, media_type=r.headers.get("content-type", "image/jpeg"))
659
- except Exception as e:
660
- pass
661
- return Response(status_code=502)
662
- @app.get('/s')
663
- async def _sh(url:str='',title:str='',img:str='',post_id:str=''):
664
- safe_title = _clean(title) if title else 'VNEWS - Tin tức'
665
- safe_img = _clean(img) if img else ''
666
- safe_url = _clean(url) if url else '/'
667
-
668
- # Try to find wall post by post_id or URL (prioritize posts with slides/video)
669
- post = None
670
- try:
671
- posts = _load_wall_posts()
672
- if post_id:
673
- for p in posts:
674
- if p.get('id') == post_id:
675
- post = p
676
- safe_title = p.get('title', safe_title) or safe_title
677
- safe_img = p.get('img', safe_img) or safe_img
678
- safe_url = p.get('url', safe_url) or safe_url
679
- break
680
- elif url:
681
- # Find matching URL - prioritize posts with slides or video
682
- for p in posts:
683
- if p.get('url') == url and p.get('slides'):
684
- post = p
685
- safe_title = p.get('title', safe_title) or safe_title
686
- safe_img = p.get('img', safe_img) or safe_img
687
- safe_url = p.get('url', safe_url) or safe_url
688
- break
689
- if not post:
690
- # Fallback: find any matching URL
691
- for p in posts:
692
- if p.get('url') == url:
693
- post = p
694
- safe_title = p.get('title', safe_title) or safe_title
695
- safe_img = p.get('img', safe_img) or safe_img
696
- safe_url = p.get('url', safe_url) or safe_url
697
- break
698
- except:
699
- pass
700
-
701
- if post and post.get('slides'):
702
- return _render_slides_page(post, safe_title, safe_img, safe_url)
703
-
704
- if post and post.get('video'):
705
- return _render_video_page(post, safe_title, safe_img, safe_url)
706
-
707
- # Fallback: redirect to original URL
708
- # Fetch og:image for better rich preview
709
- if url and not safe_img:
710
- try:
711
- art = _scrape_article_fast(url)
712
- if art and art.get('og_image'):
713
- safe_img = art.get('og_image', '')
714
- if art and art.get('title'):
715
- safe_title = art.get('title', safe_title)
716
- except:
717
- pass
718
-
719
- return HTMLResponse(f'''<!DOCTYPE html>
720
- <html lang="vi">
721
- <head>
722
- <meta charset="utf-8">
723
- <meta name="viewport" content="width=device-width,initial-scale=1">
724
- <title>{safe_title}</title>
725
- <meta property="og:title" content="{safe_title}">
726
- <meta property="og:image" content="{safe_img}">
727
- <meta property="og:description" content="Tin tức tóm tắt, AI rewrite, World Cup 2026">
728
- <meta property="og:url" content="{SPACE}/s?url={quote(safe_url)}">
729
- <link rel="canonical" href="{SPACE}/s?url={quote(safe_url)}">
730
- <meta http-equiv="refresh" content="0;url={safe_url}">
731
- </head><body></body></html>''')
732
-
733
- 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
734
-
735
- _xlb_cache = {}
736
- _xlb_lock = threading.Lock()
737
-
738
- def _xlb_scrape(path):
739
- url = f"https://xemlaibongda.top/{path}"
740
- r = req.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}, timeout=15, allow_redirects=True)
741
- if r.status_code != 200:
742
- return []
743
- soup = BeautifulSoup(r.text, 'lxml')
744
- vids = []
745
- seen = set()
746
- for a in soup.select('a[href*="/video/"]'):
747
- href = a.get('href', '')
748
- if not href or href in seen:
749
- continue
750
- seen.add(href)
751
- if not href.startswith('http'):
752
- href = 'https://xemlaibongda.top' + href
753
- img = a.select_one('img')
754
- p = a.parent
755
- for _ in range(4):
756
- if img:
757
- break
758
- if p:
759
- img = p.select_one('img')
760
- p = p.parent
761
- img_src = ''
762
- if img:
763
- img_src = img.get('data-src','') or img.get('src','') or img.get('data-lazy','') or img.get('data-original','')
764
- if img_src.startswith('//'):
765
- img_src = 'https:' + img_src
766
- elif img_src.startswith('/'):
767
- img_src = 'https://xemlaibongda.top' + img_src
768
- title = ''
769
- for sel in ['.title', 'h3', 'h2', '.name', '.post-title', '.entry-title', '.video-title']:
770
- t = a.select_one(sel)
771
- if t:
772
- title = _clean(t.get_text())
773
- break
774
- if not title:
775
- title = _clean(a.get('title',''))
776
- if not title:
777
- img_alt = a.select_one('img')
778
- if img_alt:
779
- title = _clean(img_alt.get('alt',''))
780
- if not title:
781
- parent = a.parent
782
- if parent:
783
- pt = _clean(parent.get_text(' ',strip=True))
784
- if 5 < len(pt) < 120:
785
- title = pt
786
- if not title or len(title) < 3:
787
- continue
788
- vids.append({"link": href, "img": img_src, "title": title})
789
- if len(vids) >= 30:
790
- break
791
- return vids
792
-
793
- @app.get('/api/proxy/xlb')
794
- def proxy_xlb(path: str = Query(default="")):
795
- now = time.time()
796
- cache_key = f"xlb:{path}"
797
- with _xlb_lock:
798
- cached = _xlb_cache.get(cache_key)
799
- if cached and now - cached['t'] < 120:
800
- return JSONResponse(cached['d'])
801
- try:
802
- vids = _xlb_scrape(path)
803
- result = {"videos": vids, "count": len(vids)}
804
- with _xlb_lock:
805
- _xlb_cache[cache_key] = {'t': now, 'd': result}
806
- return JSONResponse(result)
807
- except Exception as e:
808
- return JSONResponse({"videos": [], "count": 0, "error": str(e)}, status_code=500)
809
-
810
- @app.get('/api/wc2026')
811
- def _w():return JSONResponse(get_wc2026_all())
812
- @app.get('/api/wc2026/fixtures')
813
- def _wf():return JSONResponse(scrape_fixtures())
814
- @app.get('/api/wc2026/standings')
815
- def _ws():return JSONResponse(scrape_standings())
816
- @app.get('/api/wc2026/stats')
817
- def _wst():return JSONResponse(scrape_stats())
818
- @app.get('/api/wc2026/history')
819
- def _whi():return JSONResponse(scrape_history())
820
- @app.get('/api/wc2026/news')
821
- def _wn():return JSONResponse(scrape_wc_news())
822
- @app.get('/api/wc2026/road')
823
- def _wr():return JSONResponse(scrape_road_to_wc())
824
- @app.get('/api/wc2026/h2h/{eid}')
825
- def _wh2(eid:int):return JSONResponse(scrape_h2h(eid))
826
- @app.get('/api/wc2026/lineups/{eid}')
827
- def _wl(eid:int):return JSONResponse(scrape_lineups(eid))
828
- @app.get('/api/wc2026/match/{eid}')
829
- def _wm(eid:int):return JSONResponse(scrape_match_detail(eid))
830
-
831
- DATA_DIR='/data' if os.path.isdir('/data') else os.path.join(os.path.dirname(os.path.abspath(__file__)),'data')
832
- os.makedirs(DATA_DIR,exist_ok=True)
833
- IF=os.path.join(DATA_DIR,'interactions_v2.json')
834
- CF=os.path.join(DATA_DIR,'comments_v2.json')
835
- WALL_FILE=os.path.join(DATA_DIR,'wall_posts.json')
836
- WALL_VIDEO_DIR=os.path.join(DATA_DIR,'wall_videos')
837
- os.makedirs(WALL_VIDEO_DIR,exist_ok=True)
838
-
839
- _il=threading.Lock();_cl=threading.Lock();_wl_lock=threading.Lock()
840
- def _lj(p):
841
- try:
842
- if os.path.exists(p):return json.load(open(p,'r',encoding='utf-8'))
843
- except:pass
844
- return [] # Return empty list instead of dict for wall posts
845
- def _sj(p,d):
846
- try:open(p+'.tmp','w',encoding='utf-8').write(json.dumps(d,ensure_ascii=False));os.replace(p+'.tmp',p)
847
- except:pass
848
-
849
- @app.post('/api/v2/interact')
850
- async def _int(request:Request):
851
- b=await request.json();v=str(b.get('id','')).strip();t=str(b.get('type','')).strip()
852
- if not v or t not in('view','like'):return JSONResponse({'error':'x'},status_code=400)
853
- 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])
854
-
855
- @app.get('/api/v2/interactions')
856
- def _gi(id:str=Query(...)):
857
- with _il:return JSONResponse(_lj(IF).get(id.strip(),{'views':0,'likes':0,'comments':0}))
858
-
859
- @app.get('/api/v2/comments')
860
- def _gc(id:str=Query(...)):
861
- with _cl:return JSONResponse({'comments':_lj(CF).get(id.strip(),[])})
862
-
863
- @app.post('/api/v2/comment')
864
- async def _pc(request:Request):
865
- b=await request.json();v=str(b.get('id','')).strip();tx=str(b.get('text','')).strip()[:500]
866
- if not v or not tx:return JSONResponse({'error':'x'},status_code=400)
867
- c={'text':tx,'time':time.strftime('%H:%M %d/%m',time.localtime()),'ts':int(time.time())}
868
- with _cl:db=_lj(CF);db.setdefault(v,[]);db[v].append(c);db[v]=db[v][-200:];_sj(CF,db);cms=db[v]
869
- with _il:idb=_lj(IF);idb.setdefault(v,{'views':0,'likes':0,'comments':0});idb[v]['comments']=len(cms);_sj(IF,idb)
870
- return JSONResponse({'comments':cms})
871
-
872
- def _load_wall_posts():
873
- with _wl_lock:
874
- return _lj(WALL_FILE)
875
-
876
- def _save_wall_posts(posts):
877
- with _wl_lock:
878
- _sj(WALL_FILE, posts)
879
-
880
- @app.get('/api/wall')
881
- def api_wall():
882
- posts = _load_wall_posts()
883
- if not posts:
884
- return JSONResponse({"posts": []})
885
- return JSONResponse({"posts": posts})
886
-
887
- @app.post('/api/wall')
888
- async def api_wall_post(request: Request):
889
- content_type = request.headers.get('content-type', '')
890
- if 'multipart/form-data' in content_type:
891
- try:
892
- form = await request.form()
893
- except Exception as e:
894
- return JSONResponse({"error": f"Form parse error: {str(e)}"}, status_code=400)
895
- title = form.get('title', 'Video mới') or 'Video mới'
896
- text = form.get('text', '') or ''
897
- source = form.get('source', 'vtv_recorder') or 'vtv_recorder'
898
- video_file = form.get('video')
899
- post_id = str(uuid.uuid4())[:12]
900
- video_url = None
901
- if video_file and hasattr(video_file, 'filename') and video_file.filename:
902
- fname = video_file.filename.lower()
903
- if fname.endswith('.mp4'):
904
- ext = '.mp4'
905
- elif fname.endswith('.webm'):
906
- ext = '.webm'
907
- else:
908
- ext = '.webm'
909
- video_filename = f"wall_{post_id}{ext}"
910
- video_path = os.path.join(WALL_VIDEO_DIR, video_filename)
911
- try:
912
- content = await video_file.read()
913
- if not content:
914
- return JSONResponse({"error": "Empty video file"}, status_code=400)
915
- with open(video_path, 'wb') as f:
916
- f.write(content)
917
- file_size_mb = len(content) / 1024 / 1024
918
- if file_size_mb > 50:
919
- os.remove(video_path)
920
- return JSONResponse({"error": f"Video quá lớn ({file_size_mb:.1f}MB). Tối đa 50MB."}, status_code=400)
921
- video_url = f"/api/wall/video/{video_filename}"
922
- except Exception as e:
923
- return JSONResponse({"error": f"Lỗi lưu video: {str(e)}"}, status_code=500)
924
- post = {
925
- "id": post_id,
926
- "title": title[:200],
927
- "text": text[:2000],
928
- "source": source,
929
- "video": video_url,
930
- "img": None,
931
- "images": [],
932
- "created": int(time.time()),
933
- "created_str": time.strftime('%H:%M %d/%m/%Y', time.localtime()),
934
- }
935
- posts = _load_wall_posts()
936
- if not isinstance(posts, list):
937
- posts = []
938
- posts.insert(0, post)
939
- posts = posts[:200]
940
- _save_wall_posts(posts)
941
- return JSONResponse({"post": post, "ok": True})
942
- try:
943
- body = await request.json()
944
- except:
945
- body = {}
946
- title = body.get('title', 'Bài mới') or 'Bài mới'
947
- text = body.get('text', '') or ''
948
- img = body.get('img', None)
949
- source = body.get('source', 'user') or 'user'
950
- post_id = str(uuid.uuid4())[:12]
951
- post = {
952
- "id": post_id,
953
- "title": title[:200],
954
- "text": text[:2000],
955
- "source": source,
956
- "video": None,
957
- "img": img,
958
- "images": [],
959
- "created": int(time.time()),
960
- "created_str": time.strftime('%H:%M %d/%m/%Y', time.localtime()),
961
- }
962
- posts = _load_wall_posts()
963
- if not isinstance(posts, list):
964
- posts = []
965
- posts.insert(0, post)
966
- posts = posts[:200]
967
- _save_wall_posts(posts)
968
- return JSONResponse({"post": post, "ok": True})
969
-
970
- @app.get('/api/wall/video/{filename}')
971
- def api_wall_video(filename: str):
972
- if '..' in filename or '/' in filename:
973
- return Response(status_code=403)
974
- video_path = os.path.join(WALL_VIDEO_DIR, filename)
975
- if not os.path.exists(video_path):
976
- return Response(status_code=404)
977
- ext = os.path.splitext(filename)[1].lower()
978
- media_type = 'video/mp4' if ext == '.mp4' else 'video/webm'
979
- return FileResponse(video_path, media_type=media_type)
980
-
981
- @app.delete('/api/wall/{post_id}')
982
- def api_wall_delete(post_id: str):
983
- posts = _load_wall_posts()
984
- if not isinstance(posts, list):
985
- return JSONResponse({"error": "No posts"}, status_code=404)
986
- for i, p in enumerate(posts):
987
- if p.get('id') == post_id:
988
- if p.get('video'):
989
- video_name = p['video'].split('/')[-1]
990
- video_path = os.path.join(WALL_VIDEO_DIR, video_name)
991
- if os.path.exists(video_path):
992
- os.remove(video_path)
993
- posts.pop(i)
994
- _save_wall_posts(posts)
995
- return JSONResponse({"ok": True})
996
- return JSONResponse({"error": "Post not found"}, status_code=404)
997
-
998
- # ===== LANGUAGE & EMOTION DETECTION =====
999
- import random as _random2
1000
- from urllib.parse import quote as _quote2
1001
-
1002
- _UA_RW = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept-Language': 'vi-VN,vi;q=0.9'}
1003
-
1004
- # Unique character markers for language detection
1005
- _UNIQUE_CHARS = {
1006
- 'vietnamese': set('đăâêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềễểệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵý'),
1007
- 'spanish': set('ñáéíóúü¿¡'),
1008
- 'portuguese': set('ãõçáéíóúâêôà'),
1009
- }
1010
-
1011
- _STOPWORDS = {
1012
- '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'},
1013
- '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'},
1014
- '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'},
1015
- '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'},
1016
- }
1017
-
1018
- def detect_language(text):
1019
- """Detect language from text content using stopword + character analysis."""
1020
- if not text:
1021
- return 'vietnamese'
1022
- text_lower = text.lower()
1023
- text_chars = set(text_lower)
1024
-
1025
- # Strong signal: Vietnamese unique characters
1026
- vn_chars = len(text_chars & _UNIQUE_CHARS['vietnamese'])
1027
- if vn_chars >= 2:
1028
- return 'vietnamese'
1029
-
1030
- # Spanish unique chars (ñ, ¿, ¡)
1031
- es_chars = len(text_chars & _UNIQUE_CHARS['spanish'])
1032
- pt_chars = len(text_chars & _UNIQUE_CHARS['portuguese'])
1033
-
1034
- # Stopword scoring
1035
- words = set(re.findall(r'\b\w+\b', text_lower))
1036
- scores = {}
1037
- for lang, stops in _STOPWORDS.items():
1038
- scores[lang] = len(words & stops) / max(len(stops), 1)
1039
-
1040
- # Disambiguate Portuguese vs Spanish
1041
- 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'}
1042
- 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'}
1043
-
1044
- pt_overlap = len(words & pt_markers)
1045
- es_overlap = len(words & es_markers)
1046
-
1047
- if scores.get('portuguese', 0) > 0 and pt_overlap > es_overlap:
1048
- return 'portuguese'
1049
- if scores.get('spanish', 0) > 0 and es_overlap > pt_overlap:
1050
- return 'spanish'
1051
- if scores.get('english', 0) > 0.15:
1052
- return 'english'
1053
-
1054
- best = max(scores, key=scores.get)
1055
- return best if scores[best] > 0.05 else 'vietnamese'
1056
-
1057
- # Emotion keyword-based detection
1058
- _EMOTION_KEYWORDS = {
1059
- 'happy': {
1060
- 'en': ['happy', 'joy', 'wonderful', 'great', 'amazing', 'fantastic', 'love', 'excellent', 'beautiful', 'glad', 'delighted', 'pleased', 'cheerful', 'celebrate', 'victory', 'win', 'success'],
1061
- 'pt': ['feliz', 'alegria', 'maravilhoso', 'ótimo', 'incrível', 'fantástico', 'amor', 'excelente', 'lindo', 'contente', 'encantado', 'vitória', 'sucesso'],
1062
- 'es': ['feliz', 'alegria', 'maravilloso', 'genial', 'increíble', 'fantástico', 'amor', 'excelente', 'hermoso', 'contento', 'encantado', 'victoria', 'éxito'],
1063
- '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'],
1064
- },
1065
- 'sad': {
1066
- 'en': ['sad', 'unhappy', 'terrible', 'awful', 'horrible', 'miserable', 'depressed', 'grief', 'sorrow', 'tragic', 'unfortunate', 'painful', 'death', 'die', 'kill'],
1067
- 'pt': ['triste', 'infeliz', 'terrível', 'horrível', 'miserável', 'deprimido', 'dor', 'trágico', 'infelizmente', 'penoso', 'morte', 'morrer'],
1068
- 'es': ['triste', 'infeliz', 'terrible', 'horrible', 'miserable', 'deprimido', 'dolor', 'trágico', 'desafortunado', 'penoso', 'muerte', 'morir'],
1069
- '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'],
1070
- },
1071
- 'excited': {
1072
- 'en': ['excited', 'thrilling', 'amazing', 'wow', 'incredible', 'unbelievable', 'awesome', 'exhilarating', 'electrifying', 'breathtaking', 'breakthrough', 'record'],
1073
- 'pt': ['animado', 'emocionante', 'incrível', 'impressionante', 'sensacional', 'eletrizante', 'empolgante', 'recorde'],
1074
- 'es': ['emocionante', 'increíble', 'impresionante', 'sensacional', 'electrizante', 'emocionado', 'entusiasmado', 'récord'],
1075
- '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á'],
1076
- },
1077
- 'humorous': {
1078
- 'en': ['funny', 'hilarious', 'joke', 'laugh', 'comedy', 'humor', 'amusing', 'witty', 'sarcastic', 'ironic', 'ridiculous', 'absurd', 'lol', 'haha'],
1079
- 'pt': ['engraçado', 'hilário', 'piada', 'rir', 'comédia', 'humor', 'divertido', 'irônico', 'ridículo', 'absurdo', 'kkk'],
1080
- 'es': ['gracioso', 'hilarante', 'broma', 'risa', 'comedia', 'humor', 'divertido', 'irónico', 'ridículo', 'absurdo', 'jaja'],
1081
- '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'],
1082
- },
1083
- 'serious': {
1084
- 'en': ['serious', 'critical', 'important', 'urgent', 'severe', 'grave', 'significant', 'crucial', 'vital', 'essential', 'alarming', 'concerning', 'crisis', 'war', 'conflict'],
1085
- 'pt': ['sério', 'crítico', 'importante', 'urgente', 'grave', 'significativo', 'crucial', 'vital', 'essencial', 'preocupante', 'crise', 'guerra', 'conflito'],
1086
- 'es': ['serio', 'crítico', 'importante', 'urgente', 'grave', 'significativo', 'crucial', 'vital', 'esencial', 'preocupante', 'crisis', 'guerra', 'conflicto'],
1087
- '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'],
1088
- },
1089
- }
1090
-
1091
- def detect_emotion(text, language='vietnamese'):
1092
- """Detect emotion from text using keyword matching."""
1093
- if not text:
1094
- return 'neutral'
1095
- text_lower = text.lower()
1096
-
1097
- scores = {}
1098
- for emotion, lang_keywords in _EMOTION_KEYWORDS.items():
1099
- keywords = lang_keywords.get(language, lang_keywords.get('en', []))
1100
- score = sum(1 for kw in keywords if kw in text_lower)
1101
- scores[emotion] = score
1102
-
1103
- if max(scores.values()) == 0:
1104
- return 'neutral'
1105
-
1106
- return max(scores, key=scores.get)
1107
-
1108
- def detect_language_and_emotion(title, text):
1109
- """Detect both language and emotion from article content."""
1110
- combined = f"{title} {text}"
1111
- lang = detect_language(combined)
1112
- emotion = detect_emotion(combined, lang)
1113
- return lang, emotion
1114
-
1115
- # Voice selection based on language and emotion (using MultilingualNeural voices)
1116
- VOICE_BY_LANG_EMOTION = {
1117
- 'vietnamese': {
1118
- 'happy': ('vi-VN-HoaiMyNeural', 'vui'),
1119
- 'sad': ('vi-VN-NamMinhNeural', 'buồn'),
1120
- 'excited': ('vi-VN-HoaiMyNeural', 'hào hứng'),
1121
- 'humorous': ('vi-VN-HoaiMyNeural', 'vui'),
1122
- 'serious': ('vi-VN-NamMinhNeural', 'nghiêm túc'),
1123
- 'neutral': ('vi-VN-HoaiMyNeural', 'trung_tinh'),
1124
- },
1125
- 'portuguese': {
1126
- 'happy': ('pt-BR-ThalitaMultilingualNeural', 'feliz'),
1127
- 'sad': ('pt-BR-ThalitaMultilingualNeural', 'triste'),
1128
- 'excited': ('pt-BR-ThalitaMultilingualNeural', 'animado'),
1129
- 'humorous': ('pt-BR-ThalitaMultilingualNeural', 'engraçado'),
1130
- 'serious': ('pt-BR-ThalitaMultilingualNeural', 'sério'),
1131
- 'neutral': ('pt-BR-ThalitaMultilingualNeural', 'neutro'),
1132
- },
1133
- 'english': {
1134
- 'happy': ('en-US-AndrewMultilingualNeural', 'happy'),
1135
- 'sad': ('en-AU-WilliamMultilingualNeural', 'sad'),
1136
- 'excited': ('en-US-AndrewMultilingualNeural', 'excited'),
1137
- 'humorous': ('en-US-AndrewMultilingualNeural', 'funny'),
1138
- 'serious': ('en-AU-WilliamMultilingualNeural', 'serious'),
1139
- 'neutral': ('en-US-AndrewMultilingualNeural', 'neutral'),
1140
- },
1141
- 'french': {
1142
- 'happy': ('fr-FR-VivienneMultilingualNeural', 'heureux'),
1143
- 'sad': ('fr-FR-RemyMultilingualNeural', 'triste'),
1144
- 'excited': ('fr-FR-VivienneMultilingualNeural', 'excité'),
1145
- 'humorous': ('fr-FR-VivienneMultilingualNeural', 'drôle'),
1146
- 'serious': ('fr-FR-RemyMultilingualNeural', 'sérieux'),
1147
- 'neutral': ('fr-FR-VivienneMultilingualNeural', 'neutre'),
1148
- },
1149
- 'german': {
1150
- 'happy': ('de-DE-SeraphinaMultilingualNeural', 'glücklich'),
1151
- 'sad': ('de-DE-FlorianMultilingualNeural', 'traurig'),
1152
- 'excited': ('de-DE-SeraphinaMultilingualNeural', 'aufgeregt'),
1153
- 'humorous': ('de-DE-SeraphinaMultilingualNeural', 'lustig'),
1154
- 'serious': ('de-DE-FlorianMultilingualNeural', 'ernst'),
1155
- 'neutral': ('de-DE-SeraphinaMultilingualNeural', 'neutral'),
1156
- },
1157
- 'korean': {
1158
- 'happy': ('ko-KR-HyunsuMultilingualNeural', '행복'),
1159
- 'sad': ('ko-KR-HyunsuMultilingualNeural', '슬픔'),
1160
- 'excited': ('ko-KR-HyunsuMultilingualNeural', '흥분'),
1161
- 'humorous': ('ko-KR-HyunsuMultilingualNeural', '유쾌'),
1162
- 'serious': ('ko-KR-HyunsuMultilingualNeural', '진지'),
1163
- 'neutral': ('ko-KR-HyunsuMultilingualNeural', '중립'),
1164
- },
1165
- 'italian': {
1166
- 'happy': ('it-IT-GiuseppeMultilingualNeural', 'felice'),
1167
- 'sad': ('it-IT-GiuseppeMultilingualNeural', 'triste'),
1168
- 'excited': ('it-IT-GiuseppeMultilingualNeural', 'emozionato'),
1169
- 'humorous': ('it-IT-GiuseppeMultilingualNeural', 'divertente'),
1170
- 'serious': ('it-IT-GiuseppeMultilingualNeural', 'serio'),
1171
- 'neutral': ('it-IT-GiuseppeMultilingualNeural', 'neutro'),
1172
- },
1173
- }
1174
-
1175
- # All valid voice IDs (new MultilingualNeural format)
1176
- VALID_VOICES = {
1177
- 'vi-VN-HoaiMyNeural', 'vi-VN-NamMinhNeural',
1178
- 'en-US-AndrewMultilingualNeural', 'en-AU-WilliamMultilingualNeural',
1179
- 'pt-BR-ThalitaMultilingualNeural',
1180
- 'fr-FR-VivienneMultilingualNeural', 'fr-FR-RemyMultilingualNeural',
1181
- 'de-DE-SeraphinaMultilingualNeural', 'de-DE-FlorianMultilingualNeural',
1182
- 'ko-KR-HyunsuMultilingualNeural',
1183
- 'it-IT-GiuseppeMultilingualNeural',
1184
- }
1185
-
1186
- def get_voice_for_content(title, text, preferred_voice=None):
1187
- """Get appropriate voice based on content language and emotion."""
1188
- # Accept the new MultilingualNeural voices directly
1189
- if preferred_voice and preferred_voice in VALID_VOICES:
1190
- return preferred_voice
1191
-
1192
- # Also accept old shorthand voice IDs and map them to new format
1193
- old_voice_map = {
1194
- 'hoaimy': 'vi-VN-HoaiMyNeural',
1195
- 'namminh': 'vi-VN-NamMinhNeural',
1196
- 'andrew': 'en-US-AndrewMultilingualNeural',
1197
- 'jenny': 'en-US-AndrewMultilingualNeural',
1198
- 'thalita': 'pt-BR-ThalitaMultilingualNeural',
1199
- 'pt_thalita': 'pt-BR-ThalitaMultilingualNeural',
1200
- 'pt_francisco': 'pt-BR-ThalitaMultilingualNeural',
1201
- 'ela': 'en-US-AndrewMultilingualNeural',
1202
- 'es_carlos': 'en-US-AndrewMultilingualNeural',
1203
- 'denise': 'fr-FR-VivienneMultilingualNeural',
1204
- 'katja': 'de-DE-SeraphinaMultilingualNeural',
1205
- 'nanami': 'en-US-AndrewMultilingualNeural',
1206
- 'sunhee': 'ko-KR-HyunsuMultilingualNeural',
1207
- 'xiaochen': 'en-US-AndrewMultilingualNeural',
1208
- }
1209
- if preferred_voice and preferred_voice in old_voice_map:
1210
- return old_voice_map[preferred_voice]
1211
-
1212
- lang, emotion = detect_language_and_emotion(title, text)
1213
- lang_map = VOICE_BY_LANG_EMOTION.get(lang, VOICE_BY_LANG_EMOTION['vietnamese'])
1214
- voice, _ = lang_map.get(emotion, lang_map['neutral'])
1215
- return voice
1216
-
1217
-
1218
- def _is_relevant_image(img_url, title, text):
1219
- """Check if an image is relevant to the article content."""
1220
- if not img_url:
1221
- return False
1222
- skip_patterns = ['pixel', 'analytics', 'tracking', '1x1.gif', 'spacer.gif',
1223
- 'logo', 'icon', 'avatar', 'emoji', 'smiley', 'sprite',
1224
- 'advertisement', 'ad-banner', 'sponsored', 'banner-ads']
1225
- img_lower = img_url.lower()
1226
- for p in skip_patterns:
1227
- if p in img_lower:
1228
- return False
1229
- if not any(img_lower.endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.webp', '.gif']):
1230
- return False
1231
- return True
1232
-
1233
-
1234
- def _filter_relevant_images(images, title, text, max_images=8):
1235
- """Filter and rank images by relevance to article content."""
1236
- if not images:
1237
- return []
1238
- seen = set()
1239
- relevant = []
1240
- for img in images:
1241
- if img in seen:
1242
- continue
1243
- seen.add(img)
1244
- if _is_relevant_image(img, title, text):
1245
- relevant.append(img)
1246
- return relevant[:max_images]
1247
-
1248
-
1249
- def _scrape_article_for_rewrite(url):
1250
- """Scrape article: extract title, paragraphs, RELEVANT images, OG image."""
1251
- try:
1252
- r = req.get(url, headers=_UA_RW, timeout=15, allow_redirects=True)
1253
- r.encoding = 'utf-8'
1254
- soup = BeautifulSoup(r.text, 'lxml')
1255
- for tag in soup.find_all(['script', 'style', 'nav', 'footer', 'aside', 'form']):
1256
- tag.decompose()
1257
- h1 = soup.find('h1')
1258
- ogt = soup.find('meta', property='og:title')
1259
- title = (h1.get_text(strip=True) if h1 else '') or (ogt.get('content', '') if ogt else '')
1260
- ogi = soup.find('meta', property='og:image')
1261
- og_img = ogi.get('content', '') if ogi else ''
1262
- if og_img and og_img.startswith('//'):
1263
- og_img = 'https:' + og_img
1264
- block = None
1265
- for sel in ['article', '.singular-content', '.detail-content', '.fck_detail', '.content-detail', '.knc-content', 'main', '.cms-body', '.article__body', '#content', '.content', 'section', '[class*="content"]', '[class*="detail"]', '[class*="article"]']:
1266
- el = soup.select_one(sel)
1267
- if el and len(el.find_all('p')) >= 2:
1268
- block = el
1269
- break
1270
- if not block:
1271
- block = soup.body or soup
1272
- paragraphs = []
1273
- all_images = []
1274
- seen_imgs = set()
1275
- if og_img and og_img not in seen_imgs:
1276
- all_images.append(og_img)
1277
- seen_imgs.add(og_img)
1278
- for el in block.find_all(['p', 'h2', 'h3', 'figure', 'img'], recursive=True):
1279
- if el.name == 'p':
1280
- t = _clean(el.get_text(strip=True))
1281
- if t and len(t) > 40:
1282
- paragraphs.append(t)
1283
- elif el.name in ('figure', 'img'):
1284
- im = el if el.name == 'img' else el.find('img')
1285
- if im:
1286
- src = im.get('data-src') or im.get('src') or im.get('data-original') or ''
1287
- if src and 'base64' not in src:
1288
- if src.startswith('//'):
1289
- src = 'https:' + src
1290
- if src not in seen_imgs:
1291
- all_images.append(src)
1292
- seen_imgs.add(src)
1293
- # FALLBACK: if no paragraph block found, grab all <p> in body with decent length
1294
- if not paragraphs:
1295
- for p in soup.find_all('p'):
1296
- t = _clean(p.get_text(strip=True))
1297
- if t and len(t) > 40:
1298
- paragraphs.append(t)
1299
- if len(paragraphs) >= 12:
1300
- break
1301
- # FALLBACK: if still empty, use og:description or title so we always have content
1302
- if not paragraphs:
1303
- og_desc = ''
1304
- ogd = soup.find('meta', property='og:description')
1305
- if ogd:
1306
- og_desc = _clean(ogd.get('content', ''))
1307
- if og_desc and len(og_desc) > 40:
1308
- paragraphs = [og_desc]
1309
- elif title and len(title) > 20:
1310
- paragraphs = [title]
1311
- # Filter to relevant images only
1312
- relevant_images = _filter_relevant_images(all_images, title, ' '.join(paragraphs[:5]))
1313
- return {'title': _clean(title), 'paragraphs': paragraphs, 'images': relevant_images, 'og_img': og_img}
1314
- except Exception:
1315
- return None
1316
-
1317
-
1318
- def _extract_key_points_rw(paragraphs, max_points=5):
1319
- r"""Extract key points from paragraphs - extracts ALL sentences, not just first one.
1320
-
1321
- Fixes: Original regex `^(.+?[.!?])\s` only captured first sentence per paragraph.
1322
- Now splits on all sentence boundaries and takes valid sentences until max_points.
1323
- """
1324
- points = []
1325
-
1326
- for p in paragraphs:
1327
- if len(points) >= max_points:
1328
- break
1329
-
1330
- p = _clean(p)
1331
- if not p:
1332
- continue
1333
-
1334
- # Split paragraph into sentences using Vietnamese + English punctuation
1335
- sentences = re.split(r'(?<=[.!?])\s+(?=[A-ZÀ-Ỹ0-9])', p)
1336
- sentences = [s.strip() for s in sentences if s.strip()]
1337
-
1338
- for sentence in sentences:
1339
- if len(points) >= max_points:
1340
- break
1341
-
1342
- # Clean sentence - remove extra whitespace
1343
- sentence = _clean(sentence)
1344
-
1345
- if len(sentence) < 30:
1346
- continue
1347
-
1348
- # Check for duplicates
1349
- if any(sentence[:60] in existing for existing in points):
1350
- continue
1351
-
1352
- # Ensure sentence ends with punctuation
1353
- if not sentence.endswith(('.', '!', '?')):
1354
- sentence = sentence + '.'
1355
-
1356
- points.append(sentence)
1357
-
1358
- # If no valid sentences found, take chunks from raw text
1359
- if not points:
1360
- raw = '\n'.join(paragraphs)
1361
- for i in range(0, min(len(raw), max_points * 300), 280):
1362
- chunk = _clean(raw[i:i+280])
1363
- if len(chunk) >= 30 and chunk not in points:
1364
- points.append(chunk + ('.' if not chunk.endswith('.') else ''))
1365
- if len(points) >= max_points:
1366
- break
1367
-
1368
- return points
1369
-
1370
-
1371
- @app.post("/api/rewrite_slide")
1372
- async def api_rewrite_slide(request: Request):
1373
- """Fast rewrite as SLIDES - no AI needed, instant response."""
1374
- body = await request.json()
1375
- url = _clean(body.get("url", ""))
1376
- context = body.get("context", "")
1377
- preferred_voice = body.get("voice", "") # Accept custom voice selection
1378
- if not url and not context:
1379
- return JSONResponse({"error": "Cần URL hoặc nội dung"}, status_code=400)
1380
- data = None
1381
- if url and url.startswith("http"):
1382
- data = _scrape_article_for_rewrite(url)
1383
- if not data and context:
1384
- paragraphs = [_clean(p) for p in context.split('\n') if len(_clean(p)) > 40]
1385
- data = {'title': paragraphs[0][:80] if paragraphs else 'Bài viết', 'paragraphs': paragraphs, 'images': [], 'og_img': ''}
1386
- if not data or not data.get('paragraphs'):
1387
- return JSONResponse({"error": "Không đọc được bài viết"}, status_code=422)
1388
- points = _extract_key_points_rw(data['paragraphs'], max_points=12)
1389
- if not points:
1390
- return JSONResponse({"error": "Không tìm được ý chính"}, status_code=422)
1391
- images = data.get('images', [])
1392
- slides = []
1393
- for i, point in enumerate(points):
1394
- img = images[i] if i < len(images) else (images[-1] if images else '')
1395
- if img and 'cdnphoto.dantri' in img:
1396
- img = '/api/proxy/img?url=' + _quote2(img, safe='')
1397
- slides.append({'text': point, 'image': img, 'index': i + 1})
1398
- summary_text = '\n\n'.join([f"• {s['text']}" for s in slides])
1399
-
1400
- # Auto-detect language and emotion
1401
- lang, emotion = detect_language_and_emotion(data['title'], summary_text)
1402
- # Use preferred voice if provided, otherwise auto-detect
1403
- voice = preferred_voice if preferred_voice else get_voice_for_content(data['title'], summary_text)
1404
-
1405
- post = {
1406
- "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)),
1407
- "title": data['title'],
1408
- "text": summary_text,
1409
- "img": images[0] if images else '',
1410
- "url": url,
1411
- "kind": "slide_summary",
1412
- "slides": slides,
1413
- "images": images[:10],
1414
- "video": "",
1415
- "voice": voice,
1416
- "emotion": emotion,
1417
- "language": lang,
1418
- "ts": int(time.time())
1419
- }
1420
- posts = _load_wall_posts()
1421
- posts.insert(0, post)
1422
- _save_wall_posts(posts)
1423
- return JSONResponse({"post": post, "slides": slides})
1424
-
1425
-
1426
- @app.post("/api/rewrite_share")
1427
- async def api_rewrite_share(request: Request):
1428
- """Rewrite article and post to Tường AI with SLIDES + AI text."""
1429
- body = await request.json()
1430
- url = _clean(body.get("url", ""))
1431
- ctx = _clean(body.get("context", ""))
1432
- preferred_voice = body.get("voice", "") # Accept custom voice selection
1433
- if not url and not ctx:
1434
- return JSONResponse({"error": "Cần URL hoặc nội dung"}, status_code=400)
1435
- data = None
1436
- if url and url.startswith("http"):
1437
- data = _scrape_article_for_rewrite(url)
1438
- if not data and ctx:
1439
- paragraphs = [_clean(p) for p in ctx.split('\n') if len(_clean(p)) > 40]
1440
- data = {'title': paragraphs[0][:80] if paragraphs else 'Bài viết', 'paragraphs': paragraphs, 'images': [], 'og_img': ''}
1441
- if not data or not data.get('paragraphs'):
1442
- return JSONResponse({"error": "Không đọc được bài viết"}, status_code=422)
1443
- raw_text = '\n'.join(data['paragraphs'])
1444
- if len(raw_text) < 50:
1445
- raw_text = ctx[:14000]
1446
- if len(raw_text) < 50:
1447
- return JSONResponse({"error": "Bài viết quá ngắn"}, status_code=422)
1448
- domain = ''
1449
- try:
1450
- from urllib.parse import urlparse
1451
- domain = urlparse(url).netloc.replace('www.', '')
1452
- except:
1453
- pass
1454
-
1455
- # Generate AI summary text
1456
- ai_text = None
1457
- try:
1458
- import ai_ext
1459
- if hasattr(ai_ext, 'qwen_generate'):
1460
- 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.'
1461
- ai_text = await ai_ext.qwen_generate(prompt, max_tokens=1000)
1462
- except Exception:
1463
- pass
1464
- if not ai_text or len(ai_text) < 80:
1465
- key_pts = _extract_key_points_rw(data['paragraphs'], max_points=12)
1466
- if key_pts:
1467
- ai_text = '\n\n'.join([f"• {p}" for p in key_pts])
1468
- else:
1469
- ai_text = f"Tóm tắt: {data['title']}\n\n{raw_text[:1200]}\n\nNguồn: {domain}"
1470
-
1471
- # Build slides from key points (FIX: include slides in rewrite_share too!)
1472
- points = _extract_key_points_rw(data['paragraphs'], max_points=12)
1473
- # FINAL FALLBACK: if still no points (e.g. Dantri edge cases), build from ai_text/title
1474
- if not points:
1475
- if ai_text and len(ai_text) > 40:
1476
- # split ai_text into sentences/chunks
1477
- chunks = [c.strip() for c in re.split(r'[.\n]+', ai_text) if len(c.strip()) > 30]
1478
- points = chunks[:12] if chunks else [ai_text[:280]]
1479
- elif data.get('title'):
1480
- points = [data['title']]
1481
- images = data.get('images', [])
1482
- slides = []
1483
- for i, point in enumerate(points):
1484
- img = images[i] if i < len(images) else (images[-1] if images else '')
1485
- if img and 'cdnphoto.dantri' in img:
1486
- img = '/api/proxy/img?url=' + _quote2(img, safe='')
1487
- slides.append({'text': point, 'image': img, 'index': i + 1})
1488
-
1489
- # Auto-detect language and emotion
1490
- lang, emotion = detect_language_and_emotion(data['title'], ai_text)
1491
- # Use preferred voice if provided, otherwise auto-detect
1492
- voice = preferred_voice if preferred_voice else get_voice_for_content(data['title'], ai_text)
1493
-
1494
- post = {
1495
- "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)),
1496
- "title": data['title'],
1497
- "text": ai_text,
1498
- "img": images[0] if images else '',
1499
- "url": url,
1500
- "kind": "rewrite",
1501
- "slides": slides,
1502
- "images": images[:10],
1503
- "video": "",
1504
- "voice": voice,
1505
- "emotion": emotion,
1506
- "language": lang,
1507
- "ts": int(time.time())
1508
- }
1509
- posts = _load_wall_posts()
1510
- posts.insert(0, post)
1511
- _save_wall_posts(posts)
1512
- return JSONResponse({"post": post, "slides": slides})
1513
-
1514
-
1515
- @app.post("/api/url_wall")
1516
- async def api_url_wall(request: Request):
1517
- """Submit URL to add to Tường AI."""
1518
- body = await request.json()
1519
- url = _clean(body.get("url", ""))
1520
- if not url or not url.startswith('http'):
1521
- return JSONResponse({"error": "URL không hợp lệ"}, status_code=400)
1522
- # Reuse rewrite_share logic
1523
- req._body = json.dumps({"url": url}).encode()
1524
- return await api_rewrite_share(request)
1525
-
1526
-
1527
- def _bg():
1528
- time.sleep(15)
1529
- while True:
1530
- try:get_wc2026_all()
1531
- except:pass
1532
- time.sleep(90)
1533
- threading.Thread(target=_bg,daemon=True).start()
1534
-
1535
- # ===== AUTO SCHEDULER: rewrite AI + short at 7/13/19 VN time =====
1536
- _AUTO_SCHEDULE_TIMES = [(7, '07:00'), (13, '13:00'), (19, '19:00')]
1537
- _AUTO_LOG = os.path.join(DATA_DIR, 'auto_rewrite_log.json')
1538
-
1539
- def _load_auto_log():
1540
- try:
1541
- if os.path.exists(_AUTO_LOG):
1542
- with open(_AUTO_LOG, 'r') as f:
1543
- return json.load(f)
1544
- except: pass
1545
- return {}
1546
-
1547
- def _save_auto_log(log):
1548
- try:
1549
- tmp = _AUTO_LOG + '.tmp'
1550
- with open(tmp, 'w') as f:
1551
- json.dump(log, f)
1552
- os.replace(tmp, _AUTO_LOG)
1553
- except: pass
1554
-
1555
- async def _auto_fetch_short(post_id):
1556
- """Try to auto-generate a short for a post."""
1557
- try:
1558
- import httpx
1559
- async with httpx.AsyncClient(timeout=180) as cl:
1560
- r = await cl.post(
1561
- f"http://localhost:7860/api/ai/short/{post_id}",
1562
- json={"voice":"vi-VN-HoaiMyNeural","emotion":"neutral","speed":1.2},
1563
- headers={"Content-Type":"application/json"}
1564
- )
1565
- if r.status_code < 300:
1566
- sj = r.json()
1567
- if sj.get('video'):
1568
- posts = _load_wall_posts()
1569
- for p in posts:
1570
- if p.get('id') == post_id:
1571
- p['video'] = sj['video']
1572
- break
1573
- _save_wall_posts(posts)
1574
- return True
1575
- except: pass
1576
- return False
1577
-
1578
- async def _auto_rewrite_one(topic, slot_label, used_urls=None, post_index=0):
1579
- """Rewrite one topic: find articles, summarize, post to wall, trigger short.
1580
- used_urls: shared set to avoid duplicate articles across topics.
1581
- post_index: 0-based index to create multiple posts per topic (0,1,2 = up to 3 posts)."""
1582
- from urllib.parse import quote as _q
1583
- # Get MORE items to support 1-3 posts per topic
1584
- items = _search_all(topic, limit=12)
1585
- # Skip URLs already used by another topic
1586
- if used_urls is not None:
1587
- filtered = [it for it in items if it.get('url') not in used_urls]
1588
- if filtered:
1589
- items = filtered
1590
- if not items or post_index >= len(items):
1591
- return False
1592
-
1593
- # Get article at post_index (0,1,2 for multiple posts)
1594
- item = items[post_index] # post_index allows multiple articles per topic
1595
- url = item.get('url', '')
1596
- title = item.get('title', topic)
1597
- if url and used_urls is not None:
1598
- used_urls.add(url)
1599
- if not url.startswith('http'):
1600
- return False
1601
-
1602
- data = _scrape_article_for_rewrite(url)
1603
- if not data or not data.get('paragraphs'):
1604
- return False
1605
-
1606
- raw_text = '\n'.join(data['paragraphs'])
1607
- ai_text = None
1608
-
1609
- # Try AI generation
1610
- try:
1611
- import ai_ext
1612
- 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."
1613
- ai_text = await ai_ext.qwen_generate(prompt, max_tokens=1000)
1614
- except: pass
1615
-
1616
- if not ai_text or len(ai_text) < 80:
1617
- pts = data['paragraphs'][:6]
1618
- ai_text = '\n\n'.join([f"• {p[:300]}" for p in pts])
1619
- via = item.get('via', '') or urlparse(url).netloc.replace('www.', '')
1620
- ai_text += f"\n\nNguồn tham khảo: {via}"
1621
-
1622
- # Build slides
1623
- images = data.get('images', [])
1624
- pts = data['paragraphs'][:10]
1625
- slides = []
1626
- for i, p in enumerate(pts[:8]):
1627
- img = images[i] if i < len(images) else (images[-1] if images else data.get('og_img', ''))
1628
- slides.append({'text': p[:300], 'image': img, 'index': i + 1})
1629
-
1630
- post_id = str(int(time.time() * 1000)) + str(_random2.randint(100, 999))
1631
- post = {
1632
- "id": post_id, "title": data.get('title', title)[:200],
1633
- "text": ai_text, "img": images[0] if images else data.get('og_img', ''),
1634
- "url": url, "kind": "auto_rewrite", "slides": slides,
1635
- "images": images[:10], "video": "",
1636
- "voice": "vi-VN-HoaiMyNeural", "emotion": "neutral",
1637
- "language": "vietnamese", "ts": int(time.time()),
1638
- "auto_scheduled": True, "slot": slot_label,
1639
- }
1640
-
1641
- posts = _load_wall_posts()
1642
- posts.insert(0, post)
1643
- _save_wall_posts(posts)
1644
-
1645
- # Trigger short generation async
1646
- threading.Thread(target=lambda: asyncio.run(_auto_fetch_short(post_id)), daemon=True).start()
1647
- return True
1648
-
1649
- async def _do_scheduled_run(slot_label):
1650
- """Main scheduled run: 1-3 posts from 3 different HOT topics (3-9 total), no duplicates."""
1651
- print(f"[auto] Starting scheduled rewrite for {slot_label}")
1652
-
1653
- # Get top hot topics, skip duplicates
1654
- all_topics = _get_hot_topics()
1655
- seen_topics = set()
1656
- unique_topics = []
1657
- for t in all_topics:
1658
- kw = t.get('topic', '').lower().strip()
1659
- if kw and len(kw) > 5 and kw not in seen_topics:
1660
- is_dup = False
1661
- for s in seen_topics:
1662
- # Check if one topic is substring of another
1663
- if kw in s or s in kw:
1664
- is_dup = True
1665
- break
1666
- if not is_dup:
1667
- seen_topics.add(kw)
1668
- unique_topics.append(t)
1669
- if len(unique_topics) >= 3:
1670
- break
1671
-
1672
- job_topics = [t['topic'] for t in unique_topics[:3] if t.get('topic')]
1673
- if not job_topics:
1674
- print(f"[auto] No hot topics found, skipping")
1675
- return
1676
-
1677
- print(f"[auto] Running 3 topics: {job_topics}")
1678
-
1679
- # Track used URLs to avoid cross-topic duplicates
1680
- _used_urls = set()
1681
- results = []
1682
-
1683
- # Process each topic, create 1-3 posts per topic
1684
- for jt in job_topics:
1685
- for post_idx in range(3): # Try up to 3 posts per topic
1686
- try:
1687
- ok = await asyncio.wait_for(_auto_rewrite_one(jt, slot_label, _used_urls, post_idx), timeout=120)
1688
- if ok:
1689
- results.append((jt, post_idx, True))
1690
- print(f"[auto] Created post {post_idx+1} for '{jt}'")
1691
- else:
1692
- # No more articles for this topic
1693
- break
1694
- except Exception as e:
1695
- print(f"[auto] Error on '{jt}' post {post_idx}: {e}")
1696
- results.append((jt, post_idx, False))
1697
- await asyncio.sleep(1) # Small delay between posts
1698
-
1699
- # Ensure at least 3 posts total (fallback if needed)
1700
- successful_posts = sum(1 for _, _, ok in results if ok)
1701
- print(f"[auto] Done {slot_label}: {successful_posts} posts created")
1702
-
1703
- # Log
1704
- from datetime import datetime, timezone, timedelta
1705
- VN_TZ_SCHED = timezone(timedelta(hours=7))
1706
- today_str = datetime.now(VN_TZ_SCHED).strftime('%Y-%m-%d')
1707
- log = _load_auto_log()
1708
- if today_str not in log: log[today_str] = {}
1709
- log[today_str][slot_label] = {
1710
- 'time': datetime.now(VN_TZ_SCHED).strftime('%H:%M:%S'),
1711
- 'count': successful_posts,
1712
- 'total': len(job_topics),
1713
- }
1714
- _save_auto_log(log)
1715
-
1716
- def _scheduler_loop():
1717
- """Check every 60s; trigger at 7:00, 13:00, 19:00 VN time.
1718
- On startup, check for any missed slots today and run them immediately."""
1719
- time.sleep(35)
1720
- from datetime import datetime, timezone, timedelta
1721
- VN_TZ_SCHED = timezone(timedelta(hours=7))
1722
-
1723
- _last_run_date = ""
1724
- _last_run_slots = set()
1725
-
1726
- # On startup: check log for missed slots today
1727
- try:
1728
- start_now = datetime.now(VN_TZ_SCHED)
1729
- today_str = start_now.strftime('%Y-%m-%d')
1730
- current_hour = start_now.hour
1731
- current_minute = start_now.minute
1732
- log = _load_auto_log()
1733
- today_log = log.get(today_str, {})
1734
- for h, label in _AUTO_SCHEDULE_TIMES:
1735
- # Run if slot is past (either strictly earlier hour, or same hour but window has passed)
1736
- should_run = False
1737
- if h < current_hour:
1738
- should_run = True
1739
- elif h == current_hour and current_minute > 10:
1740
- should_run = True
1741
- if should_run and label not in today_log:
1742
- print(f"[auto] Detected missed slot {label} (h={h} < now={current_hour}:{current_minute}), running catch-up now")
1743
- _run_scheduled_sync(label)
1744
- _last_run_slots.add(label)
1745
- except Exception as e:
1746
- print(f"[auto] Catch-up check error: {e}")
1747
-
1748
- while True:
1749
- try:
1750
- now = datetime.now(VN_TZ_SCHED)
1751
- today = now.strftime('%Y-%m-%d')
1752
- hour = now.hour
1753
- minute = now.minute
1754
-
1755
- if today != _last_run_date:
1756
- _last_run_date = today
1757
- _last_run_slots = set()
1758
-
1759
- slot = None
1760
- for h, label in _AUTO_SCHEDULE_TIMES:
1761
- if hour == h and 0 <= minute < 5:
1762
- slot = label
1763
- break
1764
-
1765
- if slot and slot not in _last_run_slots:
1766
- _last_run_slots.add(slot)
1767
- _run_scheduled_sync(slot)
1768
- except Exception as e:
1769
- print(f"[auto] Loop error: {e}")
1770
-
1771
- time.sleep(60)
1772
-
1773
- threading.Thread(target=_scheduler_loop, daemon=True, name='auto-rewrite-scheduler').start()
1774
-
1775
- @app.get('/api/debug/auto_schedule')
1776
- async def debug_auto_schedule(slot: str = '07:00'):
1777
- """Manually trigger auto scheduler for debugging."""
1778
- try:
1779
- # Check if we can access the data directory
1780
- log = _load_auto_log()
1781
- topics = _get_hot_topics()[:3]
1782
- job_topics = [t['topic'] for t in topics if t.get('topic')]
1783
- return JSONResponse({
1784
- "slot": slot,
1785
- "log": log,
1786
- "hot_topics": job_topics,
1787
- "wall_posts_count": len(_load_wall_posts()),
1788
- "data_dir_writable": os.access(DATA_DIR, os.W_OK) if os.path.isdir(DATA_DIR) else False,
1789
- "data_dir_exists": os.path.isdir(DATA_DIR),
1790
- })
1791
- except Exception as e:
1792
- return JSONResponse({"error": str(e)}, status_code=500)
1793
-
1794
- def _run_scheduled_sync(slot):
1795
- """Run _do_scheduled_run in a separate event loop (for background thread)."""
1796
- loop = asyncio.new_event_loop()
1797
- asyncio.set_event_loop(loop)
1798
- try:
1799
- loop.run_until_complete(_do_scheduled_run(slot))
1800
- except Exception as e:
1801
- print(f"[auto] Background run error: {e}")
1802
- finally:
1803
- loop.close()
1804
-
1805
- @app.get('/api/debug/trigger_auto')
1806
- async def debug_trigger_auto(slot: str = '19:00'):
1807
- """Trigger _do_scheduled_run in background thread (non-blocking)."""
1808
- threading.Thread(target=_run_scheduled_sync, args=(slot,), daemon=True).start()
1809
- return JSONResponse({"status": "started", "slot": slot})
1810
-
1811
- # ===== SHORTS RSS PROXY ENDPOINT =====
1812
- @app.get("/api/shorts/rss")
1813
- def shorts_rss():
1814
- """Get shorts from YouTube RSS feeds server-side"""
1815
- import xml.etree.ElementTree as ET
1816
- import html as html_lib2
1817
- import re as re2
1818
-
1819
- YOUTUBE_CHANNELS = {
1820
- "baodantri7941": "UC_x5TKhOgd6GhYvv5z4I3jg",
1821
- "baosuckhoedoisongboyte": "UCBsY5fXTQLkF_JnH9kLkL4g",
1822
- }
1823
-
1824
- shorts = []
1825
- seen = set()
1826
-
1827
- for handle, channel_id in YOUTUBE_CHANNELS.items():
1828
- try:
1829
- rss_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}"
1830
- r = req.get(rss_url, headers=HEADERS, timeout=15)
1831
- if r.status_code != 200:
1832
- continue
1833
-
1834
- root = ET.fromstring(r.text)
1835
- ns = {
1836
- 'atom': 'http://www.w3.org/2005/Atom',
1837
- 'yt': 'http://www.youtube.com/xml/schemas/2015',
1838
- 'media': 'http://search.yahoo.com/mrss/'
1839
- }
1840
-
1841
- for entry in root.findall('atom:entry', ns)[:30]:
1842
- title_el = entry.find('atom:title', ns)
1843
- title = html_lib2.unescape(title_el.text) if title_el is not None and title_el.text else ''
1844
-
1845
- link_el = entry.find('atom:link', ns)
1846
- link = link_el.get('href', '') if link_el is not None else ''
1847
-
1848
- vid_el = entry.find('yt:videoId', ns)
1849
- vid = vid_el.text if vid_el is not None else ''
1850
-
1851
- if not vid or vid in seen:
1852
- continue
1853
-
1854
- # Check if it's a short
1855
- is_short = '#shorts' in title.lower() or '#short' in title.lower() or '/shorts/' in link
1856
-
1857
- if not is_short:
1858
- desc_el = entry.find('media:description', ns)
1859
- if desc_el is not None and desc_el.text:
1860
- if '#shorts' in desc_el.text.lower():
1861
- is_short = True
1862
-
1863
- if not is_short:
1864
- continue
1865
-
1866
- seen.add(vid)
1867
-
1868
- # Get thumbnail
1869
- thumb = f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg"
1870
- media_group = entry.find('media:group', ns)
1871
- if media_group is not None:
1872
- thumb_el = media_group.find('media:thumbnail', ns)
1873
- if thumb_el is not None:
1874
- thumb = thumb_el.get('url', thumb)
1875
-
1876
- shorts.append({
1877
- 'id': vid,
1878
- 'title': title.replace('#shorts', '').replace('#short', '').strip()[:120],
1879
- 'img': thumb,
1880
- 'link': f'https://www.youtube.com/shorts/{vid}',
1881
- 'channel': handle,
1882
- 'source': 'yt'
1883
- })
1884
-
1885
- if len(shorts) >= 40:
1886
- break
1887
-
1888
- except Exception as e:
1889
- print(f"RSS error for {handle}: {e}")
1890
- continue
1891
-
1892
- return {"shorts": shorts, "count": len(shorts)}
1893
-
1894
- app.mount('/static',StaticFiles(directory=STATIC_DIR),name='vnews_static')
 
1
+ """VNEWS v2 Entry Point - with fast bongda proxy + rewrite endpoints + multilingual TTS + Auto Scheduler"""
2
  import sys, os
3
  from main import app, HEADERS, BONGDA_HEADERS, fetch_bongda_api, HL_LEAGUES
4
 
 
12
  except Exception as e:
13
  print(f"[WARN] ai_patch import failed: {e}")
14
 
15
+ # Start auto scheduler (7:00, 13:00, 19:00 VN time)
16
+ try:
17
+ import app_v2_patch
18
+ except Exception as e:
19
+ print(f"[WARN] app_v2_patch import failed: {e}")
20
+
21
  from fastapi.responses import HTMLResponse, JSONResponse, FileResponse, Response
22
  from fastapi.staticfiles import StaticFiles
23
  from starlette.routing import Mount
 
35
  SPACE = "https://bep40-vnews.hf.space" # SEO URL base for share links
36
  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()))]
37
  app.routes[:]=[r for r in app.routes if not isinstance(r, Mount)]
38
+ app.router.routes=[r for r in app.router.routes if not isinstance(r, Mount)]