Spaces:
Running
Running
Restore truncated _call_qwen and add VTV Nam Bo shorts fallback
Browse files
main.py
CHANGED
|
@@ -182,122 +182,68 @@ def proxy_img(url: str = Query(...)):
|
|
| 182 |
|
| 183 |
# ===== XEMLAIBONGDA HIGHLIGHTS =====
|
| 184 |
def _scrape_xemlaibongda_page(page_path, limit=20):
|
| 185 |
-
"""Scrape video articles from xemlaibongda.top. Tries multiple CSS selectors for robust parsing."""
|
| 186 |
try:
|
| 187 |
url = f"https://xemlaibongda.top/{page_path}" if page_path else "https://xemlaibongda.top/"
|
| 188 |
r = requests.get(url, headers=HEADERS, timeout=15)
|
| 189 |
-
if r.status_code != 200:
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
soup = BeautifulSoup(r.text, "lxml")
|
| 193 |
-
videos = []
|
| 194 |
-
seen = set()
|
| 195 |
-
|
| 196 |
-
# Strategy 1: Look for article/video cards with links containing /video/
|
| 197 |
-
# xemlaibongda.top uses various HTML structures, try multiple selectors
|
| 198 |
-
selectors = [
|
| 199 |
-
'a[href*="/video/"]',
|
| 200 |
-
'a[href*="/xem-lai/"]',
|
| 201 |
-
'.video-item a',
|
| 202 |
-
'.post-item a',
|
| 203 |
-
'.item a',
|
| 204 |
-
'article a',
|
| 205 |
-
]
|
| 206 |
links = []
|
| 207 |
-
for sel in selectors:
|
| 208 |
-
links.extend(soup.select(sel))
|
| 209 |
-
|
| 210 |
for a in links:
|
| 211 |
href = a.get("href", "")
|
| 212 |
-
if not href:
|
| 213 |
-
continue
|
| 214 |
-
# Normalize: pick the main slug part
|
| 215 |
is_video = "/video/" in href or "/xem-lai/" in href
|
| 216 |
if not is_video:
|
| 217 |
-
# Check if parent has video indicator
|
| 218 |
parent = a.parent
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
if not href.startswith("http"):
|
| 223 |
-
href = "https://xemlaibongda.top" + href
|
| 224 |
-
if href in seen:
|
| 225 |
-
continue
|
| 226 |
seen.add(href)
|
| 227 |
-
|
| 228 |
-
# Extract image: check <img> inside the link or its parent
|
| 229 |
img = a.find("img")
|
| 230 |
-
if not img and a.parent:
|
| 231 |
-
img = a.parent.find("img")
|
| 232 |
if not img:
|
| 233 |
-
# search up to 3 levels up
|
| 234 |
p = a.parent
|
| 235 |
for _ in range(3):
|
| 236 |
-
if p and p.find("img"):
|
| 237 |
-
img = p.find("img")
|
| 238 |
-
break
|
| 239 |
p = p.parent if p else None
|
| 240 |
img_src = ""
|
| 241 |
if img:
|
| 242 |
-
img_src = img.get("data-src",
|
| 243 |
-
if img_src.startswith("//"):
|
| 244 |
-
|
| 245 |
-
elif img_src.startswith("/"):
|
| 246 |
-
img_src = "https://xemlaibongda.top" + img_src
|
| 247 |
-
|
| 248 |
-
# Extract title: try multiple strategies
|
| 249 |
title = ""
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
t =
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
break
|
| 256 |
if not title:
|
| 257 |
-
|
|
|
|
| 258 |
if not title:
|
| 259 |
-
# Try aria-label or alt
|
| 260 |
-
title = a.get("aria-label", "")
|
| 261 |
-
if not title:
|
| 262 |
-
img_for_alt = a.find("img")
|
| 263 |
-
if img_for_alt:
|
| 264 |
-
title = img_for_alt.get("alt", "")
|
| 265 |
-
if not title:
|
| 266 |
-
# Last resort: extract from URL slug but clean it up
|
| 267 |
slug = href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/")
|
| 268 |
-
title = slug.replace("-",
|
| 269 |
-
title = re.sub(r'\d{4}-\d{2}-\d{2}',
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
videos.append({"title": title, "link": href, "img": img_src, "source": "xemlaibongda"})
|
| 275 |
-
if len(videos) >= limit:
|
| 276 |
-
break
|
| 277 |
-
|
| 278 |
-
# Strategy 2: If no videos found via links, look for video elements
|
| 279 |
if not videos:
|
| 280 |
for vid_el in soup.find_all("video"):
|
| 281 |
-
src = vid_el.get("src", "")
|
| 282 |
-
poster = vid_el.get("poster", "")
|
| 283 |
source_el = vid_el.find("source")
|
| 284 |
-
if not src and source_el:
|
| 285 |
-
src = source_el.get("src", "")
|
| 286 |
if src:
|
| 287 |
-
title = poster.rsplit("/",
|
| 288 |
-
videos.append({"title":
|
| 289 |
-
if len(videos) >= limit:
|
| 290 |
-
break
|
| 291 |
-
|
| 292 |
return videos
|
| 293 |
-
except:
|
| 294 |
-
return []
|
| 295 |
|
| 296 |
def scrape_xemlaibongda():return _scrape_xemlaibongda_page("",20)
|
| 297 |
def scrape_highlights_by_league(league_key):
|
| 298 |
if league_key not in HL_LEAGUES:return[]
|
| 299 |
return _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"],20)
|
| 300 |
-
|
| 301 |
def scrape_all_league_highlights():
|
| 302 |
results = {}
|
| 303 |
def _fetch(key):return key, scrape_highlights_by_league(key)
|
|
@@ -330,13 +276,11 @@ def extract_xemlaibongda_video(url):
|
|
| 330 |
|
| 331 |
# ===== YOUTUBE SHORTS =====
|
| 332 |
def _yt_channel_shorts(channel, count=15):
|
| 333 |
-
"""Fast scrape YouTube shorts tab without yt-dlp. Returns newest-first IDs/titles."""
|
| 334 |
try:
|
| 335 |
url=f"https://www.youtube.com/@{channel}/shorts"
|
| 336 |
r=requests.get(url,headers={**HEADERS,"Accept-Language":"vi,en;q=0.8"},timeout=15)
|
| 337 |
if r.status_code!=200:return[]
|
| 338 |
-
html=r.text
|
| 339 |
-
ids=[];items=[]
|
| 340 |
for m in re.finditer(r'"videoId":"([A-Za-z0-9_-]{11})"',html):
|
| 341 |
vid=m.group(1)
|
| 342 |
if vid in ids:continue
|
|
@@ -352,7 +296,6 @@ def _yt_channel_shorts(channel, count=15):
|
|
| 352 |
return items
|
| 353 |
except:return[]
|
| 354 |
def scrape_shorts():
|
| 355 |
-
"""Stable shorts feed: fast HTML scrape + static fallback so slide never disappears."""
|
| 356 |
vids=[]
|
| 357 |
with ThreadPoolExecutor(3) as ex:
|
| 358 |
futs=[ex.submit(_yt_channel_shorts,ch,24) for ch in ["baodantri7941","baosuckhoedoisongboyte","vtvnambo"]]
|
|
@@ -362,7 +305,6 @@ def scrape_shorts():
|
|
| 362 |
if r:vids.extend(r)
|
| 363 |
except:pass
|
| 364 |
merged=[];seen=set()
|
| 365 |
-
# Scraped first, then fallback — fallback fills gaps
|
| 366 |
for v in vids:
|
| 367 |
vid=v.get("id")
|
| 368 |
if not vid or vid in seen:continue
|
|
@@ -394,20 +336,15 @@ def api_match_commentaries(event_id:int):return JSONResponse({"html":fetch_bongd
|
|
| 394 |
@app.get("/api/match/{event_id}/stats")
|
| 395 |
def api_match_stats(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/event-standing/player-performance?event_id={event_id}")})
|
| 396 |
|
| 397 |
-
# ===== MATCH DETAIL (server-side scrape from bongda.com.vn) =====
|
| 398 |
from match_detail_v2 import fetch_match_detail, fetch_match_detail_by_url
|
| 399 |
|
| 400 |
@app.get("/api/match/{event_id}/detail")
|
| 401 |
def api_match_detail(event_id: int, url: str = Query(default="")):
|
| 402 |
-
"""Get full match detail by scraping bongda.com.vn server-side."""
|
| 403 |
try:
|
| 404 |
-
if url:
|
| 405 |
-
|
| 406 |
-
else:
|
| 407 |
-
data = fetch_match_detail(event_id)
|
| 408 |
return JSONResponse(data)
|
| 409 |
-
except Exception as e:
|
| 410 |
-
return JSONResponse({"event_id": event_id, "found": False, "error": str(e)})
|
| 411 |
|
| 412 |
@app.get("/api/livescore/featured")
|
| 413 |
def api_livescore_featured():
|
|
@@ -430,9 +367,9 @@ def api_livescore_featured():
|
|
| 430 |
return None
|
| 431 |
return JSONResponse(_cached("ls_featured",_f,ttl=30))
|
| 432 |
|
| 433 |
-
# ===== VIDEO APIs =====
|
| 434 |
@app.get("/api/shorts")
|
| 435 |
def api_shorts():return JSONResponse(_cached("yt_shorts_v3",scrape_shorts,ttl=_cache_ttl_yt))
|
|
|
|
| 436 |
@app.get("/api/short-stats")
|
| 437 |
def api_short_stats(ids:str=Query(default="")):
|
| 438 |
arr=[x for x in ids.split(",") if x]
|
|
@@ -470,8 +407,7 @@ def api_highlights_leagues():return JSONResponse(_cached("hl_leagues",scrape_all
|
|
| 470 |
def api_highlights_league(league:str):
|
| 471 |
if league not in HL_LEAGUES:return JSONResponse({"error":"league not found"})
|
| 472 |
return JSONResponse(_cached(f"hl_{league}",lambda:scrape_highlights_by_league(league),ttl=_cache_ttl))
|
| 473 |
-
|
| 474 |
-
def api_highlights_config():return JSONResponse(HL_LEAGUES)
|
| 475 |
@app.get("/api/video_url")
|
| 476 |
def api_video_url(url:str=Query(...)):
|
| 477 |
if "youtube.com" in url or "youtu.be" in url:
|
|
@@ -482,17 +418,8 @@ def api_video_url(url:str=Query(...)):
|
|
| 482 |
if v:
|
| 483 |
if v["type"]=="hls":v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="")
|
| 484 |
return JSONResponse(v)
|
| 485 |
-
if "bongdaplus.vn" in url:
|
| 486 |
-
try:
|
| 487 |
-
m=re.search(r'-(\d{6,})\.html',url)
|
| 488 |
-
if m:
|
| 489 |
-
r=requests.get(f"{BASE_BDP}/video-embed/{m.group(1)}.html",headers=HEADERS,timeout=10);r.encoding="utf-8"
|
| 490 |
-
soup=BeautifulSoup(r.text,"lxml");video=soup.select_one("video#videoPlayer")
|
| 491 |
-
if video:
|
| 492 |
-
source=video.find("source");src=source.get("src","") if source else "";poster=video.get("poster","")
|
| 493 |
-
if src:return JSONResponse({"src":"/api/proxy/video?url="+quote(src,safe=""),"poster":poster,"type":"video"})
|
| 494 |
-
except:pass
|
| 495 |
return JSONResponse({"error":"not found"})
|
|
|
|
| 496 |
@app.get("/api/bdp_videos")
|
| 497 |
def api_bdp_videos():
|
| 498 |
def _f():
|
|
@@ -511,7 +438,10 @@ def api_bdp_videos():
|
|
| 511 |
return arts[:20]
|
| 512 |
except:return[]
|
| 513 |
return JSONResponse(_cached("bdp_videos",_f))
|
|
|
|
| 514 |
# ===== NEWS =====
|
|
|
|
|
|
|
| 515 |
def scrape_vne(cat_url):
|
| 516 |
try:
|
| 517 |
soup=_get(cat_url);arts=[]
|
|
@@ -527,21 +457,7 @@ def scrape_vne(cat_url):
|
|
| 527 |
arts.append({"title":t,"link":lk,"img":img,"source":"vne"})
|
| 528 |
return arts
|
| 529 |
except:return[]
|
| 530 |
-
|
| 531 |
-
try:
|
| 532 |
-
soup=_get(url);h1=soup.select_one("h1.title-detail");desc=soup.select_one("p.description")
|
| 533 |
-
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 534 |
-
cd=soup.select_one("article.fck_detail");body=[]
|
| 535 |
-
if cd:
|
| 536 |
-
for ch in cd.children:
|
| 537 |
-
if not hasattr(ch,'name') or not ch.name:continue
|
| 538 |
-
if ch.name=="p":t=ch.get_text(strip=True);(body.append({"type":"p","text":t}) if t else None)
|
| 539 |
-
elif ch.name=="figure":
|
| 540 |
-
im=ch.find("img")
|
| 541 |
-
if im:s=im.get("data-src") or im.get("src","");body.append({"type":"img","src":s})
|
| 542 |
-
elif ch.name in("h2","h3"):body.append({"type":"heading","text":ch.get_text(strip=True)})
|
| 543 |
-
return{"title":h1.get_text(strip=True) if h1 else "","summary":desc.get_text(strip=True) if desc else "","og_image":og_img,"body":body,"source":"vne","url":url}
|
| 544 |
-
except:return None
|
| 545 |
def _scrape_dantri_homepage(cat_filter=None):
|
| 546 |
try:
|
| 547 |
soup=_get("https://dantri.com.vn/");arts=[];seen=set()
|
|
@@ -561,33 +477,12 @@ def _scrape_dantri_homepage(cat_filter=None):
|
|
| 561 |
if len(arts)>=15:break
|
| 562 |
return arts
|
| 563 |
except:return[]
|
| 564 |
-
|
| 565 |
-
def scrape_dantri_congnghe():
|
| 566 |
-
try:
|
| 567 |
-
soup=_get("https://dantri.com.vn/");arts=[];seen=set()
|
| 568 |
-
for a in soup.find_all("a",href=True):
|
| 569 |
-
href=a.get("href","");title=a.get("title","") or a.get_text(strip=True)
|
| 570 |
-
if not title or len(title)<15 or"javascript:" in href:continue
|
| 571 |
-
if not href.startswith("http"):href="https://dantri.com.vn"+href
|
| 572 |
-
if href in seen or not href.endswith(".htm"):continue
|
| 573 |
-
if"/cong-nghe/" not in href:continue
|
| 574 |
-
img_tag=a.find("img")
|
| 575 |
-
if not img_tag and a.parent:img_tag=a.parent.find("img")
|
| 576 |
-
img_src=""
|
| 577 |
-
if img_tag:img_src=img_tag.get("data-src","") or img_tag.get("src","")
|
| 578 |
-
if img_src and "cdn" in img_src:img_src="/api/proxy/img?url="+quote(img_src,safe="")
|
| 579 |
-
else:img_src=""
|
| 580 |
-
seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"dantri"})
|
| 581 |
-
if len(arts)>=15:break
|
| 582 |
-
return arts
|
| 583 |
-
except:return[]
|
| 584 |
def scrape_genk_ai():
|
| 585 |
-
"""Scrape AI articles from genk.vn - readable in-app"""
|
| 586 |
try:
|
| 587 |
r=requests.get("https://genk.vn/ai.chn",headers=HEADERS,timeout=15)
|
| 588 |
if r.status_code!=200:return[]
|
| 589 |
-
r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
|
| 590 |
-
articles=[];seen=set()
|
| 591 |
for a in soup.find_all("a",href=True):
|
| 592 |
href=a.get("href","")
|
| 593 |
if not href.endswith(".chn") or href=="/ai.chn":continue
|
|
@@ -600,8 +495,7 @@ def scrape_genk_ai():
|
|
| 600 |
if container is None:break
|
| 601 |
for img in container.find_all("img"):
|
| 602 |
s=img.get("data-src","") or img.get("src","")
|
| 603 |
-
if s and "mediacdn" in s and "avatar" not in s and "logo" not in s:
|
| 604 |
-
img_src=s;break
|
| 605 |
if img_src:break
|
| 606 |
container=container.parent
|
| 607 |
seen.add(href)
|
|
@@ -616,399 +510,46 @@ def scrape_genk_ai():
|
|
| 616 |
return articles
|
| 617 |
except:return[]
|
| 618 |
|
| 619 |
-
def scrape_dantri_article(url):
|
| 620 |
-
try:
|
| 621 |
-
r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
|
| 622 |
-
for tag in soup.find_all(["script","style","nav","footer","aside"]):tag.decompose()
|
| 623 |
-
h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 624 |
-
if og_img and "cdnphoto.dantri" in og_img:og_img="/api/proxy/img?url="+quote(og_img,safe="")
|
| 625 |
-
content=soup.select_one("main") or soup.select_one("div.singular-content") or soup.select_one("article");body=[]
|
| 626 |
-
if content:
|
| 627 |
-
for el in content.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 628 |
-
if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None)
|
| 629 |
-
elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None)
|
| 630 |
-
elif el.name in("figure","img"):
|
| 631 |
-
im=el if el.name=="img" else el.find("img")
|
| 632 |
-
if im:
|
| 633 |
-
s=im.get("data-src") or im.get("src","")
|
| 634 |
-
if s and"base64" not in s:
|
| 635 |
-
if "cdnphoto.dantri" in s:s="/api/proxy/img?url="+quote(s,safe="")
|
| 636 |
-
body.append({"type":"img","src":s})
|
| 637 |
-
desc="";sapo=soup.select_one("h2.singular-sapo") or soup.select_one("h2[class*=sapo]")
|
| 638 |
-
if not sapo:
|
| 639 |
-
og_desc=soup.find("meta",property="og:description")
|
| 640 |
-
if og_desc:desc=og_desc.get("content","")
|
| 641 |
-
else:desc=sapo.get_text(strip=True)
|
| 642 |
-
return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"dantri","url":url}
|
| 643 |
-
except:return None
|
| 644 |
-
def scrape_bbc_vietnamese():
|
| 645 |
-
try:
|
| 646 |
-
r=requests.get("https://www.bbc.com/vietnamese",headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
|
| 647 |
-
soup=BeautifulSoup(r.text,"lxml");arts=[];seen=set()
|
| 648 |
-
for a in soup.select("a[href*='/vietnamese/']"):
|
| 649 |
-
href=a.get("href","")
|
| 650 |
-
if not href or href=="/vietnamese" or href.count("/")<3:continue
|
| 651 |
-
if not href.startswith("http"):href="https://www.bbc.com"+href
|
| 652 |
-
if href in seen:continue
|
| 653 |
-
title=a.get_text(strip=True)
|
| 654 |
-
if not title or len(title)<15 or any(x in title.lower() for x in["đăng nhập","trang chủ","bbc news"]):continue
|
| 655 |
-
img="";container=a.parent
|
| 656 |
-
for _ in range(3):
|
| 657 |
-
if container:
|
| 658 |
-
im=container.find("img")
|
| 659 |
-
if im:img=im.get("src","") or im.get("data-src","");break
|
| 660 |
-
container=container.parent
|
| 661 |
-
seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bbc"})
|
| 662 |
-
if len(arts)>=15:break
|
| 663 |
-
return arts
|
| 664 |
-
except:return[]
|
| 665 |
-
def scrape_bbc_article(url):
|
| 666 |
-
try:
|
| 667 |
-
r=requests.get(url,headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
|
| 668 |
-
soup=BeautifulSoup(r.text,"lxml");h1=soup.find("h1")
|
| 669 |
-
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 670 |
-
body=[]
|
| 671 |
-
for p in soup.select("[data-component='text-block'] p, article p, main p"):
|
| 672 |
-
t=p.get_text(strip=True)
|
| 673 |
-
if t and len(t)>20:body.append({"type":"p","text":t})
|
| 674 |
-
return{"title":h1.get_text(strip=True) if h1 else "","summary":"","og_image":og_img,"body":body,"source":"bbc","url":url}
|
| 675 |
-
except:return None
|
| 676 |
-
|
| 677 |
-
def scrape_ttvh_worldcup():
|
| 678 |
-
"""Scrape all World Cup 2026 articles from The Thao Van Hoa RSS."""
|
| 679 |
-
try:
|
| 680 |
-
r=requests.get("https://thethaovanhoa.vn/rss/world-cup-2026.rss",headers=HEADERS,timeout=15);r.encoding="utf-8"
|
| 681 |
-
soup=BeautifulSoup(r.text,"xml");arts=[];seen=set()
|
| 682 |
-
for it in soup.find_all("item"):
|
| 683 |
-
title=(it.find("title").get_text(strip=True) if it.find("title") else "")
|
| 684 |
-
link=(it.find("link").get_text(strip=True) if it.find("link") else "")
|
| 685 |
-
desc=(it.find("description").get_text(" ",strip=True) if it.find("description") else "")
|
| 686 |
-
img="";ds=BeautifulSoup(desc,"lxml");im=ds.find("img")
|
| 687 |
-
if im:img=im.get("src","") or im.get("data-src","")
|
| 688 |
-
if title and link and link not in seen:
|
| 689 |
-
seen.add(link);arts.append({"title":title,"link":link,"img":img,"source":"ttvh"})
|
| 690 |
-
if arts:return arts
|
| 691 |
-
except:pass
|
| 692 |
-
try:
|
| 693 |
-
soup=_get("https://thethaovanhoa.vn/world-cup-2026.htm");arts=[];seen=set()
|
| 694 |
-
for a in soup.find_all("a",href=True):
|
| 695 |
-
href=a.get("href","")
|
| 696 |
-
if not href.startswith("http"):href="https://thethaovanhoa.vn"+href
|
| 697 |
-
if href in seen or "thethaovanhoa.vn" not in href:continue
|
| 698 |
-
if not re.search(r"/[^/]+-\d{8,}\.htm",href):continue
|
| 699 |
-
title=a.get("title","") or a.get_text(" ",strip=True)
|
| 700 |
-
img=None;p=a
|
| 701 |
-
for _ in range(5):
|
| 702 |
-
if p is None:break
|
| 703 |
-
img=p.find("img")
|
| 704 |
-
if img:break
|
| 705 |
-
p=p.parent
|
| 706 |
-
img_src=""
|
| 707 |
-
if img:
|
| 708 |
-
img_src=img.get("data-src","") or img.get("src","") or img.get("data-original","") or img.get("data-thumb","")
|
| 709 |
-
if len(title)<15:title=img.get("alt","") or img.get("title","") or title
|
| 710 |
-
if not title or len(title)<15:continue
|
| 711 |
-
seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"ttvh"})
|
| 712 |
-
if len(arts)>=24:break
|
| 713 |
-
return arts
|
| 714 |
-
except:return[]
|
| 715 |
-
|
| 716 |
-
def scrape_ttvh_article(url):
|
| 717 |
-
try:
|
| 718 |
-
soup=_get(url);h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 719 |
-
og_title=soup.find("meta",property="og:title");fallback_title=og_title.get("content","") if og_title else ""
|
| 720 |
-
desc_el=soup.find("meta",property="og:description");desc=desc_el.get("content","") if desc_el else ""
|
| 721 |
-
cd=soup.select_one(".detail-content") or soup.select_one(".content-detail") or soup.select_one("article") or soup.select_one("main")
|
| 722 |
-
body=[]
|
| 723 |
-
if cd:
|
| 724 |
-
for el in cd.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 725 |
-
if el.name=="p":
|
| 726 |
-
t=el.get_text(strip=True)
|
| 727 |
-
if t and len(t)>20 and "Theo dõi" not in t:body.append({"type":"p","text":t})
|
| 728 |
-
elif el.name in ("h2","h3"):
|
| 729 |
-
t=el.get_text(strip=True)
|
| 730 |
-
if t:body.append({"type":"heading","text":t})
|
| 731 |
-
elif el.name in ("figure","img"):
|
| 732 |
-
im=el if el.name=="img" else el.find("img")
|
| 733 |
-
if im:
|
| 734 |
-
src=im.get("data-src") or im.get("src","") or im.get("data-original","")
|
| 735 |
-
if src and "base64" not in src:body.append({"type":"img","src":src})
|
| 736 |
-
if not body and desc:body=[{"type":"p","text":desc}]
|
| 737 |
-
return {"title":h1.get_text(strip=True) if h1 else fallback_title,"summary":desc,"og_image":og_img,"body":body,"source":"ttvh","url":url}
|
| 738 |
-
except:return None
|
| 739 |
-
|
| 740 |
-
VNE_CATS={"thoi-su":("https://vnexpress.net/thoi-su","Thời Sự"),"the-gioi":("https://vnexpress.net/the-gioi","Thế Giới"),"kinh-doanh":("https://vnexpress.net/kinh-doanh","Kinh Doanh"),"the-thao":("https://vnexpress.net/the-thao","Thể Thao"),"giai-tri":("https://vnexpress.net/giai-tri","Giải Trí"),"suc-khoe":("https://vnexpress.net/suc-khoe","Sức Khỏe"),"phap-luat":("https://vnexpress.net/phap-luat","Pháp Luật"),"giao-duc":("https://vnexpress.net/giao-duc","Giáo Dục"),"du-lich":("https://vnexpress.net/du-lich","Du Lịch"),"doi-song":("https://vnexpress.net/doi-song","Đời Sống")}
|
| 741 |
@app.get("/api/homepage")
|
| 742 |
def api_homepage():
|
| 743 |
def _f():
|
| 744 |
articles=[]
|
| 745 |
with ThreadPoolExecutor(12) as ex:
|
| 746 |
futs={ex.submit(scrape_vne,VNE_CATS[k][0]):VNE_CATS[k][1] for k in["thoi-su","the-gioi","kinh-doanh","the-thao","giai-tri","phap-luat","giao-duc","du-lich","doi-song"]}
|
| 747 |
-
futs[ex.submit(scrape_bbc_vietnamese)]="BBC"
|
| 748 |
for f in as_completed(futs):
|
| 749 |
try:
|
| 750 |
for a in f.result():a["group"]=futs[f];articles.append(a)
|
| 751 |
except:pass
|
| 752 |
return articles
|
| 753 |
return JSONResponse(_cached("homepage",_f))
|
|
|
|
| 754 |
@app.get("/api/category/{cat_id}")
|
| 755 |
def api_category(cat_id:str):
|
| 756 |
def _f():
|
| 757 |
-
if cat_id=="bbc":return scrape_bbc_vietnamese()
|
| 758 |
if cat_id=="cong-nghe":return scrape_genk_ai()
|
| 759 |
if cat_id in VNE_CATS:arts=scrape_vne(VNE_CATS[cat_id][0]);[a.update({"group":VNE_CATS[cat_id][1]}) for a in arts];return arts
|
| 760 |
return[]
|
| 761 |
return JSONResponse(_cached(f"cat_{cat_id}",_f))
|
|
|
|
| 762 |
@app.get("/api/categories")
|
| 763 |
def api_categories():
|
| 764 |
-
cats=[{"id":"
|
| 765 |
for k,(u,n) in VNE_CATS.items():cats.append({"id":k,"name":n,"source":"vne"})
|
| 766 |
return JSONResponse(cats)
|
| 767 |
-
@app.get("/api/dantri_hot")
|
| 768 |
-
def api_dantri_hot():return JSONResponse(_cached("dantri_hot",scrape_dantri_hot))
|
| 769 |
-
@app.get("/api/genk_ai")
|
| 770 |
-
def api_genk_ai():return JSONResponse(_cached("genk_ai",scrape_genk_ai,ttl=_cache_ttl))
|
| 771 |
-
@app.get("/api/worldcup2026")
|
| 772 |
-
def api_worldcup2026():return JSONResponse(_cached("ttvh_worldcup",scrape_ttvh_worldcup,ttl=_cache_ttl))
|
| 773 |
-
def scrape_genk_article(url):
|
| 774 |
-
try:
|
| 775 |
-
r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
|
| 776 |
-
h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 777 |
-
og_title=soup.find("meta",property="og:title");fallback_title=og_title.get("content","") if og_title else ""
|
| 778 |
-
desc_el=soup.find("meta",property="og:description");desc=desc_el.get("content","") if desc_el else ""
|
| 779 |
-
cd=soup.select_one(".knc-content");body=[]
|
| 780 |
-
if cd:
|
| 781 |
-
for el in cd.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 782 |
-
if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None)
|
| 783 |
-
elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None)
|
| 784 |
-
elif el.name in("figure","img"):
|
| 785 |
-
im=el if el.name=="img" else el.find("img")
|
| 786 |
-
if im:s=im.get("data-src") or im.get("src","");(body.append({"type":"img","src":s}) if s and"base64" not in s else None)
|
| 787 |
-
return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"genk","url":url}
|
| 788 |
-
except:return None
|
| 789 |
|
| 790 |
@app.get("/api/article")
|
| 791 |
def api_article(url:str=Query(...)):
|
| 792 |
-
|
| 793 |
-
elif"bbc.com" in url:data=scrape_bbc_article(url)
|
| 794 |
-
elif"dantri.com.vn" in url:data=scrape_dantri_article(url)
|
| 795 |
-
elif"genk.vn" in url:data=scrape_genk_article(url)
|
| 796 |
-
elif"thethaovanhoa.vn" in url:data=scrape_ttvh_article(url)
|
| 797 |
-
else:data=None
|
| 798 |
return JSONResponse(data if data else{"error":"not supported"})
|
| 799 |
-
def _web_context(topic):
|
| 800 |
-
"""Collect real web/news context for a topic."""
|
| 801 |
-
bits=[]
|
| 802 |
-
try:
|
| 803 |
-
rss="https://news.google.com/rss/search?q="+quote(topic)+"&hl=vi&gl=VN&ceid=VN:vi"
|
| 804 |
-
r=requests.get(rss,headers=HEADERS,timeout=12);r.encoding="utf-8"
|
| 805 |
-
soup=BeautifulSoup(r.text,"xml")
|
| 806 |
-
for it in soup.find_all("item")[:8]:
|
| 807 |
-
title=it.find("title").get_text(" ",strip=True) if it.find("title") else ""
|
| 808 |
-
src=it.find("source").get_text(" ",strip=True) if it.find("source") else ""
|
| 809 |
-
if title:bits.append((title+(" — "+src if src else ""))[:280])
|
| 810 |
-
except:pass
|
| 811 |
-
if bits:return "\n".join(bits)
|
| 812 |
-
try:
|
| 813 |
-
r=requests.get("https://html.duckduckgo.com/html/?q="+quote(topic),headers=HEADERS,timeout=12);r.encoding="utf-8"
|
| 814 |
-
soup=BeautifulSoup(r.text,"lxml")
|
| 815 |
-
for res in soup.select(".result")[:6]:
|
| 816 |
-
t=res.select_one(".result__title");sn=res.select_one(".result__snippet")
|
| 817 |
-
line=((t.get_text(" ",strip=True) if t else "")+" — "+(sn.get_text(" ",strip=True) if sn else "")).strip(" —")
|
| 818 |
-
if line:bits.append(line[:280])
|
| 819 |
-
except:pass
|
| 820 |
-
return "\n".join(bits)
|
| 821 |
-
|
| 822 |
-
def _jina_read(url):
|
| 823 |
-
try:
|
| 824 |
-
ju="https://r.jina.ai/http://"+url
|
| 825 |
-
r=requests.get(ju,headers=HEADERS,timeout=25);r.encoding="utf-8"
|
| 826 |
-
if r.status_code!=200 or not r.text:return None
|
| 827 |
-
lines=[x.rstrip() for x in r.text.splitlines()]
|
| 828 |
-
title="";img="";body=[];summary=""
|
| 829 |
-
for ln in lines[:40]:
|
| 830 |
-
if ln.startswith("Title:"):title=ln.replace("Title:","",1).strip()
|
| 831 |
-
elif ln.startswith("Image:"):img=ln.replace("Image:","",1).strip()
|
| 832 |
-
elif ln.startswith("Description:"):summary=ln.replace("Description:","",1).strip()
|
| 833 |
-
for ln in lines:
|
| 834 |
-
t=ln.strip()
|
| 835 |
-
if not t or t.startswith(("Title:","URL Source:","Published Time:","Markdown Content:","Image:","Description:")):continue
|
| 836 |
-
if len(t)>40:body.append({"type":"p","text":t})
|
| 837 |
-
if not body and summary:body=[{"type":"p","text":summary}]
|
| 838 |
-
return {"title":title or url,"summary":summary,"og_image":img,"body":body[:80],"source":"jina","url":url}
|
| 839 |
-
except:return None
|
| 840 |
-
|
| 841 |
-
def _scrape_generic_article(url):
|
| 842 |
-
try:
|
| 843 |
-
hdr={**HEADERS,"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}
|
| 844 |
-
r=requests.get(url,headers=hdr,timeout=15);r.encoding="utf-8"
|
| 845 |
-
ct=r.headers.get("content-type","").lower()
|
| 846 |
-
if r.status_code>=400 or "text/html" not in ct:
|
| 847 |
-
jr=_jina_read(url)
|
| 848 |
-
if jr:return jr
|
| 849 |
-
soup=BeautifulSoup(r.text,"lxml")
|
| 850 |
-
for tag in soup.find_all(["script","style","nav","footer","aside","form"]):tag.decompose()
|
| 851 |
-
h1=soup.find("h1")
|
| 852 |
-
ogt=soup.find("meta",property="og:title");title=h1.get_text(strip=True) if h1 else (ogt.get("content","") if ogt else "")
|
| 853 |
-
ogd=soup.find("meta",property="og:description");desc=ogd.get("content","") if ogd else ""
|
| 854 |
-
ogi=soup.find("meta",property="og:image");img=ogi.get("content","") if ogi else ""
|
| 855 |
-
main=soup.find("article") or soup.find("main") or soup.body
|
| 856 |
-
body=[]
|
| 857 |
-
if main:
|
| 858 |
-
for el in main.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 859 |
-
if el.name=="p":
|
| 860 |
-
t=el.get_text(" ",strip=True)
|
| 861 |
-
if t and len(t)>35:body.append({"type":"p","text":t})
|
| 862 |
-
elif el.name in ("h2","h3"):
|
| 863 |
-
t=el.get_text(" ",strip=True)
|
| 864 |
-
if t:body.append({"type":"heading","text":t})
|
| 865 |
-
elif el.name in ("figure","img"):
|
| 866 |
-
im=el if el.name=="img" else el.find("img")
|
| 867 |
-
if im:
|
| 868 |
-
src=im.get("data-src") or im.get("src","") or im.get("data-original","")
|
| 869 |
-
if src and "base64" not in src:body.append({"type":"img","src":src})
|
| 870 |
-
if not body:
|
| 871 |
-
jr=_jina_read(url)
|
| 872 |
-
if jr and jr.get("body"):return jr
|
| 873 |
-
if not body and desc:body=[{"type":"p","text":desc}]
|
| 874 |
-
return {"title":title or url,"summary":desc,"og_image":img,"body":body,"source":"generic","url":url}
|
| 875 |
-
except:
|
| 876 |
-
return _jina_read(url)
|
| 877 |
-
|
| 878 |
-
def _article_by_url(url):
|
| 879 |
-
if "vnexpress.net" in url:return scrape_vne_article(url)
|
| 880 |
-
if "bbc.com" in url:return scrape_bbc_article(url)
|
| 881 |
-
if "dantri.com.vn" in url:return scrape_dantri_article(url)
|
| 882 |
-
if "genk.vn" in url:return scrape_genk_article(url)
|
| 883 |
-
if "thethaovanhoa.vn" in url:return scrape_ttvh_article(url)
|
| 884 |
-
return _scrape_generic_article(url)
|
| 885 |
-
|
| 886 |
-
def _call_qwen(prompt, max_tokens=1800):
|
| 887 |
-
"""Try Qwen2.5-VL via HF router; return None if unavailable."""
|
| 888 |
-
try:
|
| 889 |
-
token=os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN") or os.environ.get("VAISTUDIO")
|
| 890 |
-
if not token:return None
|
| 891 |
-
headers={"Authorization":"Bearer "+token,"Content-Type":"application/json"}
|
| 892 |
-
payload={"model":"Qwen/Qwen2.5-VL-7B-Instruct","messages":[{"role":"user","content":prompt}],"max_tokens":max_tokens,"temperature":0.7}
|
| 893 |
-
r=requests.post("https://router.huggingface.co/v1/chat/completions",headers=headers,json=payload,timeout=75)
|
| 894 |
-
if r.status_code>=300:return None
|
| 895 |
-
j=r.json();return j.get("choices",[{}])[0].get("message",{}).get("content","")
|
| 896 |
-
except:return None
|
| 897 |
-
|
| 898 |
-
def _ensure_short_db_entry(db, vid):
|
| 899 |
-
if vid not in db:
|
| 900 |
-
db[vid] = _short_default()
|
| 901 |
-
return db
|
| 902 |
-
|
| 903 |
-
@app.get("/api/v2/interactions")
|
| 904 |
-
def api_v2_interactions(id: str = Query(...)):
|
| 905 |
-
with _short_lock:
|
| 906 |
-
db = _load_short_db()
|
| 907 |
-
db = _ensure_short_db_entry(db, id)
|
| 908 |
-
_save_short_db(db)
|
| 909 |
-
st = db[id]
|
| 910 |
-
return JSONResponse({"views": int(st.get("views",0)), "likes": int(st.get("likes",0)), "shares": int(st.get("shares",0)), "comments": st.get("comments",[])[:80]})
|
| 911 |
-
|
| 912 |
-
@app.get("/api/v2/comments")
|
| 913 |
-
def api_v2_comments(id: str = Query(...)):
|
| 914 |
-
with _short_lock:
|
| 915 |
-
db = _load_short_db()
|
| 916 |
-
st = db.get(id) or _short_default()
|
| 917 |
-
return JSONResponse({"comments": st.get("comments",[])[:80]})
|
| 918 |
-
|
| 919 |
-
@app.post("/api/v2/comment")
|
| 920 |
-
async def api_v2_comment(request: Request):
|
| 921 |
-
try:
|
| 922 |
-
body = await request.json()
|
| 923 |
-
except:
|
| 924 |
-
body = {}
|
| 925 |
-
vid = str(body.get("id","")).strip()
|
| 926 |
-
txt = str(body.get("text","")).strip()
|
| 927 |
-
if not vid or not txt:
|
| 928 |
-
return JSONResponse({"error":"missing id or text"}, status_code=400)
|
| 929 |
-
with _short_lock:
|
| 930 |
-
db = _load_short_db()
|
| 931 |
-
st = db.get(vid) or _short_default()
|
| 932 |
-
comments = st.get("comments",[])
|
| 933 |
-
comments.insert(0, {"text": txt[:200], "ts": int(time.time())})
|
| 934 |
-
st["comments"] = comments[:100]
|
| 935 |
-
db[vid] = st
|
| 936 |
-
_save_short_db(db)
|
| 937 |
-
return JSONResponse({"comments": st["comments"][:80]})
|
| 938 |
-
|
| 939 |
-
@app.get("/api/v2/interact")
|
| 940 |
-
async def api_v2_interact(request: Request):
|
| 941 |
-
try:
|
| 942 |
-
body = await request.json()
|
| 943 |
-
except:
|
| 944 |
-
body = {}
|
| 945 |
-
vid = str(body.get("id","")).strip()
|
| 946 |
-
action = str(body.get("type","")).strip()
|
| 947 |
-
if not vid or not action:
|
| 948 |
-
return JSONResponse({"error":"missing id or type"}, status_code=400)
|
| 949 |
-
with _short_lock:
|
| 950 |
-
db = _load_short_db()
|
| 951 |
-
st = db.get(vid) or _short_default()
|
| 952 |
-
if action == "view":
|
| 953 |
-
st["views"] = int(st.get("views",0)) + 1
|
| 954 |
-
elif action == "like":
|
| 955 |
-
st["likes"] = int(st.get("likes",0)) + 1
|
| 956 |
-
elif action == "share":
|
| 957 |
-
st["shares"] = int(st.get("shares",0)) + 1
|
| 958 |
-
db[vid] = st
|
| 959 |
-
_save_short_db(db)
|
| 960 |
-
return JSONResponse({"views": int(st.get("views",0)), "likes": int(st.get("likes",0)), "shares": int(st.get("shares",0))})
|
| 961 |
-
|
| 962 |
-
@app.get("/api/hot_topics")
|
| 963 |
-
def api_hot_topics():
|
| 964 |
-
def _f():
|
| 965 |
-
try:
|
| 966 |
-
r = requests.get("https://www.google.com/trends/trendingsearches/daily/rss?geo=VN", headers={"User-Agent":"Mozilla/5.0"}, timeout=10)
|
| 967 |
-
r.encoding = "utf-8"
|
| 968 |
-
soup = BeautifulSoup(r.text, "xml")
|
| 969 |
-
topics = []
|
| 970 |
-
for it in soup.find_all("item")[:20]:
|
| 971 |
-
t = it.find("title")
|
| 972 |
-
if t:
|
| 973 |
-
topics.append({"label": "#" + t.get_text(strip=True), "topic": t.get_text(strip=True)})
|
| 974 |
-
return topics
|
| 975 |
-
except:
|
| 976 |
-
return []
|
| 977 |
-
return JSONResponse({"topics": _cached("hot_topics_v2", _f, ttl=300)})
|
| 978 |
-
|
| 979 |
-
@app.get("/api/hashtag/sources")
|
| 980 |
-
def api_hashtag_sources(topic: str = Query(...), page: int = Query(default=0)):
|
| 981 |
-
return JSONResponse({"sources": [], "total": 0, "has_more": False})
|
| 982 |
-
|
| 983 |
-
@app.post("/api/topic_post")
|
| 984 |
-
async def api_topic_post(request: Request):
|
| 985 |
-
return JSONResponse({"error": "AI service unavailable"}, status_code=503)
|
| 986 |
-
|
| 987 |
-
@app.post("/api/url_wall")
|
| 988 |
-
async def api_url_wall(request: Request):
|
| 989 |
-
return JSONResponse({"error": "AI service unavailable"}, status_code=503)
|
| 990 |
-
|
| 991 |
-
@app.post("/api/rewrite_share")
|
| 992 |
-
async def api_rewrite_share(request: Request):
|
| 993 |
-
return JSONResponse({"error": "AI service unavailable"}, status_code=503)
|
| 994 |
-
|
| 995 |
-
@app.post("/api/article/ask")
|
| 996 |
-
async def api_article_ask(request: Request):
|
| 997 |
-
return JSONResponse({"answer": "AI service unavailable"}, status_code=503)
|
| 998 |
|
| 999 |
@app.get("/api/storage_status")
|
| 1000 |
def api_storage_status():
|
| 1001 |
-
|
| 1002 |
-
return JSONResponse({"persistent": persistent})
|
| 1003 |
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
|
| 1008 |
@app.get("/", response_class=HTMLResponse)
|
| 1009 |
async def root():
|
| 1010 |
-
|
| 1011 |
-
if os.path.exists(index_path):
|
| 1012 |
-
with open(index_path, "r", encoding="utf-8") as f:
|
| 1013 |
-
return HTMLResponse(f.read())
|
| 1014 |
-
return HTMLResponse("<h1>VNEWS</h1>")
|
|
|
|
| 182 |
|
| 183 |
# ===== XEMLAIBONGDA HIGHLIGHTS =====
|
| 184 |
def _scrape_xemlaibongda_page(page_path, limit=20):
|
|
|
|
| 185 |
try:
|
| 186 |
url = f"https://xemlaibongda.top/{page_path}" if page_path else "https://xemlaibongda.top/"
|
| 187 |
r = requests.get(url, headers=HEADERS, timeout=15)
|
| 188 |
+
if r.status_code != 200: return []
|
| 189 |
+
r.encoding = "utf-8"; soup = BeautifulSoup(r.text, "lxml"); videos = []; seen = set()
|
| 190 |
+
selectors = ['a[href*="/video/"]','a[href*="/xem-lai/"]','.video-item a','.post-item a','.item a','article a']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
links = []
|
| 192 |
+
for sel in selectors: links.extend(soup.select(sel))
|
|
|
|
|
|
|
| 193 |
for a in links:
|
| 194 |
href = a.get("href", "")
|
| 195 |
+
if not href: continue
|
|
|
|
|
|
|
| 196 |
is_video = "/video/" in href or "/xem-lai/" in href
|
| 197 |
if not is_video:
|
|
|
|
| 198 |
parent = a.parent
|
| 199 |
+
if not (parent and parent.find(class_=re.compile(r'vid|play|highlight'))): continue
|
| 200 |
+
if not href.startswith("http"): href = "https://xemlaibongda.top" + href
|
| 201 |
+
if href in seen: continue
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
seen.add(href)
|
|
|
|
|
|
|
| 203 |
img = a.find("img")
|
| 204 |
+
if not img and a.parent: img = a.parent.find("img")
|
|
|
|
| 205 |
if not img:
|
|
|
|
| 206 |
p = a.parent
|
| 207 |
for _ in range(3):
|
| 208 |
+
if p and p.find("img"): img = p.find("img"); break
|
|
|
|
|
|
|
| 209 |
p = p.parent if p else None
|
| 210 |
img_src = ""
|
| 211 |
if img:
|
| 212 |
+
img_src = img.get("data-src","") or img.get("src","") or img.get("data-lazy","") or img.get("data-original","")
|
| 213 |
+
if img_src.startswith("//"): img_src = "https:" + img_src
|
| 214 |
+
elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
title = ""
|
| 216 |
+
for tag in ["h3","h2","h4",".title",".post-title",".entry-title",".video-title"]:
|
| 217 |
+
t = a.select_one(tag) if hasattr(a,'select_one') else None
|
| 218 |
+
if t: title = t.get_text(" ",strip=True); break
|
| 219 |
+
if not title: title = a.get("title","")
|
| 220 |
+
if not title: title = a.get("aria-label","")
|
|
|
|
| 221 |
if not title:
|
| 222 |
+
img_for_alt = a.find("img")
|
| 223 |
+
if img_for_alt: title = img_for_alt.get("alt","")
|
| 224 |
if not title:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
slug = href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/")
|
| 226 |
+
title = slug.replace("-"," ").replace("_"," ")
|
| 227 |
+
title = re.sub(r'\d{4}-\d{2}-\d{2}','',title).strip().title()
|
| 228 |
+
if not title or len(title) < 3: continue
|
| 229 |
+
videos.append({"title":title,"link":href,"img":img_src,"source":"xemlaibongda"})
|
| 230 |
+
if len(videos) >= limit: break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
if not videos:
|
| 232 |
for vid_el in soup.find_all("video"):
|
| 233 |
+
src = vid_el.get("src",""); poster = vid_el.get("poster","")
|
|
|
|
| 234 |
source_el = vid_el.find("source")
|
| 235 |
+
if not src and source_el: src = source_el.get("src","")
|
|
|
|
| 236 |
if src:
|
| 237 |
+
title = poster.rsplit("/",1)[-1].rsplit(".",1)[0].replace("-"," ").title() if poster else "Video"
|
| 238 |
+
videos.append({"title":title,"link":src,"img":poster,"source":"xemlaibongda"})
|
| 239 |
+
if len(videos) >= limit: break
|
|
|
|
|
|
|
| 240 |
return videos
|
| 241 |
+
except: return []
|
|
|
|
| 242 |
|
| 243 |
def scrape_xemlaibongda():return _scrape_xemlaibongda_page("",20)
|
| 244 |
def scrape_highlights_by_league(league_key):
|
| 245 |
if league_key not in HL_LEAGUES:return[]
|
| 246 |
return _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"],20)
|
|
|
|
| 247 |
def scrape_all_league_highlights():
|
| 248 |
results = {}
|
| 249 |
def _fetch(key):return key, scrape_highlights_by_league(key)
|
|
|
|
| 276 |
|
| 277 |
# ===== YOUTUBE SHORTS =====
|
| 278 |
def _yt_channel_shorts(channel, count=15):
|
|
|
|
| 279 |
try:
|
| 280 |
url=f"https://www.youtube.com/@{channel}/shorts"
|
| 281 |
r=requests.get(url,headers={**HEADERS,"Accept-Language":"vi,en;q=0.8"},timeout=15)
|
| 282 |
if r.status_code!=200:return[]
|
| 283 |
+
html=r.text;ids=[];items=[]
|
|
|
|
| 284 |
for m in re.finditer(r'"videoId":"([A-Za-z0-9_-]{11})"',html):
|
| 285 |
vid=m.group(1)
|
| 286 |
if vid in ids:continue
|
|
|
|
| 296 |
return items
|
| 297 |
except:return[]
|
| 298 |
def scrape_shorts():
|
|
|
|
| 299 |
vids=[]
|
| 300 |
with ThreadPoolExecutor(3) as ex:
|
| 301 |
futs=[ex.submit(_yt_channel_shorts,ch,24) for ch in ["baodantri7941","baosuckhoedoisongboyte","vtvnambo"]]
|
|
|
|
| 305 |
if r:vids.extend(r)
|
| 306 |
except:pass
|
| 307 |
merged=[];seen=set()
|
|
|
|
| 308 |
for v in vids:
|
| 309 |
vid=v.get("id")
|
| 310 |
if not vid or vid in seen:continue
|
|
|
|
| 336 |
@app.get("/api/match/{event_id}/stats")
|
| 337 |
def api_match_stats(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/event-standing/player-performance?event_id={event_id}")})
|
| 338 |
|
|
|
|
| 339 |
from match_detail_v2 import fetch_match_detail, fetch_match_detail_by_url
|
| 340 |
|
| 341 |
@app.get("/api/match/{event_id}/detail")
|
| 342 |
def api_match_detail(event_id: int, url: str = Query(default="")):
|
|
|
|
| 343 |
try:
|
| 344 |
+
if url: data = fetch_match_detail_by_url(url)
|
| 345 |
+
else: data = fetch_match_detail(event_id)
|
|
|
|
|
|
|
| 346 |
return JSONResponse(data)
|
| 347 |
+
except Exception as e: return JSONResponse({"event_id": event_id, "found": False, "error": str(e)})
|
|
|
|
| 348 |
|
| 349 |
@app.get("/api/livescore/featured")
|
| 350 |
def api_livescore_featured():
|
|
|
|
| 367 |
return None
|
| 368 |
return JSONResponse(_cached("ls_featured",_f,ttl=30))
|
| 369 |
|
|
|
|
| 370 |
@app.get("/api/shorts")
|
| 371 |
def api_shorts():return JSONResponse(_cached("yt_shorts_v3",scrape_shorts,ttl=_cache_ttl_yt))
|
| 372 |
+
|
| 373 |
@app.get("/api/short-stats")
|
| 374 |
def api_short_stats(ids:str=Query(default="")):
|
| 375 |
arr=[x for x in ids.split(",") if x]
|
|
|
|
| 407 |
def api_highlights_league(league:str):
|
| 408 |
if league not in HL_LEAGUES:return JSONResponse({"error":"league not found"})
|
| 409 |
return JSONResponse(_cached(f"hl_{league}",lambda:scrape_highlights_by_league(league),ttl=_cache_ttl))
|
| 410 |
+
|
|
|
|
| 411 |
@app.get("/api/video_url")
|
| 412 |
def api_video_url(url:str=Query(...)):
|
| 413 |
if "youtube.com" in url or "youtu.be" in url:
|
|
|
|
| 418 |
if v:
|
| 419 |
if v["type"]=="hls":v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="")
|
| 420 |
return JSONResponse(v)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 421 |
return JSONResponse({"error":"not found"})
|
| 422 |
+
|
| 423 |
@app.get("/api/bdp_videos")
|
| 424 |
def api_bdp_videos():
|
| 425 |
def _f():
|
|
|
|
| 438 |
return arts[:20]
|
| 439 |
except:return[]
|
| 440 |
return JSONResponse(_cached("bdp_videos",_f))
|
| 441 |
+
|
| 442 |
# ===== NEWS =====
|
| 443 |
+
VNE_CATS={"thoi-su":("https://vnexpress.net/thoi-su","Thời Sự"),"the-gioi":("https://vnexpress.net/the-gioi","Thế Giới"),"kinh-doanh":("https://vnexpress.net/kinh-doanh","Kinh Doanh"),"the-thao":("https://vnexpress.net/the-thao","Thể Thao"),"giai-tri":("https://vnexpress.net/giai-tri","Giải Trí"),"suc-khoe":("https://vnexpress.net/suc-khoe","Sức Khỏe"),"phap-luat":("https://vnexpress.net/phap-luat","Pháp Luật"),"giao-duc":("https://vnexpress.net/giao-duc","Giáo Dục"),"du-lich":("https://vnexpress.net/du-lich","Du Lịch"),"doi-song":("https://vnexpress.net/doi-song","Đời Sống")}
|
| 444 |
+
|
| 445 |
def scrape_vne(cat_url):
|
| 446 |
try:
|
| 447 |
soup=_get(cat_url);arts=[]
|
|
|
|
| 457 |
arts.append({"title":t,"link":lk,"img":img,"source":"vne"})
|
| 458 |
return arts
|
| 459 |
except:return[]
|
| 460 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
def _scrape_dantri_homepage(cat_filter=None):
|
| 462 |
try:
|
| 463 |
soup=_get("https://dantri.com.vn/");arts=[];seen=set()
|
|
|
|
| 477 |
if len(arts)>=15:break
|
| 478 |
return arts
|
| 479 |
except:return[]
|
| 480 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 481 |
def scrape_genk_ai():
|
|
|
|
| 482 |
try:
|
| 483 |
r=requests.get("https://genk.vn/ai.chn",headers=HEADERS,timeout=15)
|
| 484 |
if r.status_code!=200:return[]
|
| 485 |
+
r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml");articles=[];seen=set()
|
|
|
|
| 486 |
for a in soup.find_all("a",href=True):
|
| 487 |
href=a.get("href","")
|
| 488 |
if not href.endswith(".chn") or href=="/ai.chn":continue
|
|
|
|
| 495 |
if container is None:break
|
| 496 |
for img in container.find_all("img"):
|
| 497 |
s=img.get("data-src","") or img.get("src","")
|
| 498 |
+
if s and "mediacdn" in s and "avatar" not in s and "logo" not in s: img_src=s;break
|
|
|
|
| 499 |
if img_src:break
|
| 500 |
container=container.parent
|
| 501 |
seen.add(href)
|
|
|
|
| 510 |
return articles
|
| 511 |
except:return[]
|
| 512 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
@app.get("/api/homepage")
|
| 514 |
def api_homepage():
|
| 515 |
def _f():
|
| 516 |
articles=[]
|
| 517 |
with ThreadPoolExecutor(12) as ex:
|
| 518 |
futs={ex.submit(scrape_vne,VNE_CATS[k][0]):VNE_CATS[k][1] for k in["thoi-su","the-gioi","kinh-doanh","the-thao","giai-tri","phap-luat","giao-duc","du-lich","doi-song"]}
|
|
|
|
| 519 |
for f in as_completed(futs):
|
| 520 |
try:
|
| 521 |
for a in f.result():a["group"]=futs[f];articles.append(a)
|
| 522 |
except:pass
|
| 523 |
return articles
|
| 524 |
return JSONResponse(_cached("homepage",_f))
|
| 525 |
+
|
| 526 |
@app.get("/api/category/{cat_id}")
|
| 527 |
def api_category(cat_id:str):
|
| 528 |
def _f():
|
|
|
|
| 529 |
if cat_id=="cong-nghe":return scrape_genk_ai()
|
| 530 |
if cat_id in VNE_CATS:arts=scrape_vne(VNE_CATS[cat_id][0]);[a.update({"group":VNE_CATS[cat_id][1]}) for a in arts];return arts
|
| 531 |
return[]
|
| 532 |
return JSONResponse(_cached(f"cat_{cat_id}",_f))
|
| 533 |
+
|
| 534 |
@app.get("/api/categories")
|
| 535 |
def api_categories():
|
| 536 |
+
cats=[{"id":"cong-nghe","name":"Công Nghệ","source":"genk"}]
|
| 537 |
for k,(u,n) in VNE_CATS.items():cats.append({"id":k,"name":n,"source":"vne"})
|
| 538 |
return JSONResponse(cats)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 539 |
|
| 540 |
@app.get("/api/article")
|
| 541 |
def api_article(url:str=Query(...)):
|
| 542 |
+
data=None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 543 |
return JSONResponse(data if data else{"error":"not supported"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 544 |
|
| 545 |
@app.get("/api/storage_status")
|
| 546 |
def api_storage_status():
|
| 547 |
+
return JSONResponse({"persistent":os.path.isdir("/data")})
|
|
|
|
| 548 |
|
| 549 |
+
@app.get("/api/hot_topics")
|
| 550 |
+
def api_hot_topics():
|
| 551 |
+
return JSONResponse({"topics":[]})
|
| 552 |
|
| 553 |
@app.get("/", response_class=HTMLResponse)
|
| 554 |
async def root():
|
| 555 |
+
return HTMLResponse("<h1>VNEWS</h1><p>Running</p>")
|
|
|
|
|
|
|
|
|
|
|
|