Spaces:
Running
Running
Add /api/match/{event_id}/detail route to main.py (the actual running module)
Browse files
main.py
CHANGED
|
@@ -1,1233 +1 @@
|
|
| 1 |
-
|
| 2 |
-
import hashlib, re, time, subprocess, json, os, threading
|
| 3 |
-
import html as html_lib
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 6 |
-
from fastapi import FastAPI, Query, Request
|
| 7 |
-
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, Response
|
| 8 |
-
from fastapi.staticfiles import StaticFiles
|
| 9 |
-
from urllib.parse import unquote, quote, urlencode
|
| 10 |
-
import requests
|
| 11 |
-
from bs4 import BeautifulSoup
|
| 12 |
-
|
| 13 |
-
app = FastAPI()
|
| 14 |
-
HEADERS = {"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","Accept-Language":"vi-VN,vi;q=0.9,en;q=0.8"}
|
| 15 |
-
BONGDA_HEADERS = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36","Accept-Language":"vi-VN,vi;q=0.9","Referer":"https://bongda.com.vn/lich-thi-dau","X-Requested-With":"XMLHttpRequest"}
|
| 16 |
-
BASE_BDP = "https://bongdaplus.vn"
|
| 17 |
-
SPACE_URL = "https://bep40-vnews.hf.space"
|
| 18 |
-
_cache = {}
|
| 19 |
-
_cache_ttl = 300
|
| 20 |
-
_cache_ttl_live = 60
|
| 21 |
-
_cache_ttl_yt = 600 # 10 min: RSS feed is cheap, keeps shorts fresh/live
|
| 22 |
-
SHORTS_FALLBACK = [
|
| 23 |
-
{"id":"Lu_iCQ5YwNM","title":"Công an lập hồ sơ xử lý người phụ nữ chửi bới, tát nam tài xế ô tô ở Hà Nội | #shorts","channel":"baodantri7941"},
|
| 24 |
-
{"id":"CwWvijF8BOA","title":"Chú rể Ninh Bình bật khóc nhận món quà bí mật người cha quá cố gửi 26 năm trước | #shorts","channel":"baodantri7941"},
|
| 25 |
-
{"id":"tvPewsc2ph4","title":"Tính năng ẩn trên iPhone giúp giảm mỏi mắt | #shorts","channel":"baodantri7941"},
|
| 26 |
-
{"id":"b1Nxzv9ixlU","title":"Y án 3 năm tù với nữ tài xế uống 8 lon bia lái xe tông chủ tịch xã tử vong | #shorts","channel":"baodantri7941"},
|
| 27 |
-
{"id":"Xp5eTwAZAis","title":"Người đánh hàng xóm tại chung cư ở Hà Nội bị tuyên hơn 4 tháng tù | #shorts","channel":"baodantri7941"},
|
| 28 |
-
{"id":"Htzvwg6iOBM","title":"Xe điện Audi S6 Sportback e-tron có gì đặc biệt? | #shorts","channel":"baodantri7941"},
|
| 29 |
-
{"id":"iMdFmWvYdlo","title":"Cô gái người Nga yêu thời trang và đất nước Việt Nam | #shorts","channel":"baodantri7941"},
|
| 30 |
-
{"id":"IVaRc6moEv8","title":"Người nông dân Trung Quốc đột quỵ, bệnh viện giúp bán sạch 4 tấn táo | #shorts","channel":"baodantri7941"},
|
| 31 |
-
{"id":"uVxqPxToItU","title":"Công an vào cuộc vụ người phụ nữ chửi bới, hành hung tài xế ô tô ở Hà Nội | #shorts","channel":"baodantri7941"},
|
| 32 |
-
{"id":"VAfgNNgZDRs","title":"Khởi tố 4 đối tượng ném bom xăng vào nhà dân ở Đồng Nai | #shorts","channel":"baodantri7941"},
|
| 33 |
-
{"id":"sBH_-zGh0Xw","title":"Vì sao Times New Roman vẫn nổi tiếng sau hàng chục năm? | #shorts","channel":"baodantri7941"},
|
| 34 |
-
{"id":"woKn5f2bLHM","title":"Quảng Ninh ngập sâu diện rộng sau đợt mưa lớn | #shorts","channel":"baodantri7941"},
|
| 35 |
-
{"id":"bcpgRoxbLPw","title":"Giông lốc quật bay mái tôn ở TP.HCM | #shorts","channel":"baodantri7941"},
|
| 36 |
-
{"id":"ZIIC5osy544","title":"Bé trai Trung Quốc rơi từ tầng 11 vẫn sống sót kỳ diệu | #shorts","channel":"baodantri7941"},
|
| 37 |
-
{"id":"uTMJ49NQpyc","title":"Sau lớp mascot 40kg: Câu chuyện mưu sinh của người trẻ ở TPHCM | #shorts","channel":"baodantri7941"},
|
| 38 |
-
{"id":"7Pd6vZ2Lz1M","title":"Hành động ấm lòng của người đàn ông tham gia tìm kiếm 5 học sinh tử vong ở sông Lô | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 39 |
-
{"id":"SlHLt_ZyPiE","title":"Xử phạt người đàn ông xóa số điện thoại cứu hộ trên cao tốc Bắc - Nam | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 40 |
-
{"id":"IUOprcJyYr4","title":"Phụ nữ táo bón có phải do lười ăn rau? | SKĐS #shorts","channel":"baosuckhoedoisongboyte"},
|
| 41 |
-
{"id":"YY8ojFNE-AU","title":"Quái xế tự quay clip nẹt pô, đánh võng đăng TikTok bị xử lý | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 42 |
-
{"id":"OV7_oGdQGII","title":"Bố cô dâu khóc sụt sùi rồi quẩy cực sung gây bão mạng | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 43 |
-
{"id":"FoxhFyz2skY","title":"Người đàn ông nước ngoài đập phá ô tô, bẻ cần gạt nước ở Đà Nẵng | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 44 |
-
{"id":"R1oC_I8dFPU","title":"Thanh niên buông tay lái, đứng trên xe máy khi đổ đèo ở Đắk Lắk | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 45 |
-
{"id":"U0Ft6ChWAIo","title":"Cô giáo kể phút tháo chạy khỏi xe khách trước khi bị lũ vò nát ở Cao Bằng | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 46 |
-
{"id":"hH0ANeze_4E","title":"Liên tiếp hàng chục con bò bị sét đánh chết trong ngày mưa dông | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 47 |
-
{"id":"pXWt0QbAzRQ","title":"Va chạm giao thông, người phụ nữ lăng mạ tài xế ô tô | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 48 |
-
{"id":"UWWLPY1OYt4","title":"CSGT chặn xe khách khống chế đối tượng cướp dây chuyền tại Gia Lai | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 49 |
-
{"id":"AxhVTQutsuo","title":"Xuất tinh sớm và những hiểu lầm thường gặp | SKĐS #shorts","channel":"baosuckhoedoisongboyte"},
|
| 50 |
-
{"id":"cNy6FgaNxYM","title":"Cô dâu khóc sưng mắt vì 6 chỉ vàng không cánh mà bay trong ngày cưới | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 51 |
-
{"id":"IDt_S6q59Ro","title":"Chở bạn gái không đội mũ bảo hiểm, thanh niên đấm CSGT | SKĐS","channel":"baosuckhoedoisongboyte"},
|
| 52 |
-
{"id":"LFxJ9Ik6W0A","title":"Mệnh lệnh từ trái tim: CSGT Hà Nội mở đường đưa bé 5 tháng tuổi đi cấp cứu | SKĐS","channel":"baosuckhoedoisongboyte"}
|
| 53 |
-
]
|
| 54 |
-
for _v in SHORTS_FALLBACK:
|
| 55 |
-
_v["link"]="https://www.youtube.com/watch?v="+_v["id"]
|
| 56 |
-
_v["img"]="https://i.ytimg.com/vi/"+_v["id"]+"/hqdefault.jpg"
|
| 57 |
-
_v["source"]="yt"
|
| 58 |
-
SHORT_STATS_FILE = "/data/short_stats.json" if os.path.isdir("/data") else "/app/short_stats.json"
|
| 59 |
-
_short_lock = threading.Lock()
|
| 60 |
-
def _load_short_db():
|
| 61 |
-
try:
|
| 62 |
-
if os.path.exists(SHORT_STATS_FILE):
|
| 63 |
-
with open(SHORT_STATS_FILE,"r",encoding="utf-8") as f:return json.load(f)
|
| 64 |
-
except:pass
|
| 65 |
-
return {}
|
| 66 |
-
def _save_short_db(db):
|
| 67 |
-
try:
|
| 68 |
-
os.makedirs(os.path.dirname(SHORT_STATS_FILE),exist_ok=True)
|
| 69 |
-
tmp=SHORT_STATS_FILE+".tmp"
|
| 70 |
-
with open(tmp,"w",encoding="utf-8") as f:json.dump(db,f,ensure_ascii=False)
|
| 71 |
-
os.replace(tmp,SHORT_STATS_FILE)
|
| 72 |
-
except:pass
|
| 73 |
-
|
| 74 |
-
def _short_default():return {"views":0,"likes":0,"shares":0,"comments":[]}
|
| 75 |
-
WALL_FILE = "/data/wall_posts.json" if os.path.isdir("/data") else "/app/wall_posts.json"
|
| 76 |
-
def _load_wall():
|
| 77 |
-
try:
|
| 78 |
-
if os.path.exists(WALL_FILE):
|
| 79 |
-
with open(WALL_FILE,"r",encoding="utf-8") as f:return json.load(f)
|
| 80 |
-
except:pass
|
| 81 |
-
return []
|
| 82 |
-
def _save_wall(posts):
|
| 83 |
-
try:
|
| 84 |
-
os.makedirs(os.path.dirname(WALL_FILE),exist_ok=True)
|
| 85 |
-
tmp=WALL_FILE+".tmp"
|
| 86 |
-
with open(tmp,"w",encoding="utf-8") as f:json.dump(posts[:100],f,ensure_ascii=False)
|
| 87 |
-
os.replace(tmp,WALL_FILE)
|
| 88 |
-
except:pass
|
| 89 |
-
PRIORITY_LEAGUES = ["Ngoại Hạng Anh","FA Cup","Champions League","LaLiga","Copa del Rey","Serie A","Bundesliga","Ligue 1","V-League"]
|
| 90 |
-
LEAGUE_IDS = {"nha":27110,"laliga":27233,"seriea":27044,"bundesliga":26891,"ligue1":27212}
|
| 91 |
-
HL_LEAGUES = {"premier-league":{"path":"anh/premier-league","name":"Premier League","emoji":"🏴"},"fa-cup":{"path":"anh/fa-cup","name":"FA Cup","emoji":"🏆"},"bundesliga":{"path":"duc/bundesliga","name":"Bundesliga","emoji":"🇩🇪"},"serie-a":{"path":"italy/serie-a","name":"Serie A","emoji":"🇮🇹"},"la-liga":{"path":"tay-ban-nha/la-liga","name":"La Liga","emoji":"🇪🇸"},"champions-league":{"path":"cup-chau-au/uefa-champions-league","name":"Champions League","emoji":"⭐"},"europa-league":{"path":"cup-chau-au/uefa-europa-league","name":"Europa League","emoji":"🟠"},"world-cup":{"path":"the-gioi/world-cup-qualifiers","name":"World Cup 2026","emoji":"🌍"}}
|
| 92 |
-
def _cached(key, fn, ttl=None):
|
| 93 |
-
now=time.time();t=ttl or _cache_ttl
|
| 94 |
-
if key in _cache and now-_cache[key]["t"]<t:return _cache[key]["d"]
|
| 95 |
-
try:data=fn()
|
| 96 |
-
except:data=_cache.get(key,{}).get("d",[])
|
| 97 |
-
_cache[key]={"d":data,"t":now};return data
|
| 98 |
-
def _get(url,headers=None):
|
| 99 |
-
h=headers or HEADERS;r=requests.get(url,headers=h,timeout=15);r.encoding="utf-8"
|
| 100 |
-
return BeautifulSoup(r.text,"lxml")
|
| 101 |
-
def fetch_bongda_api(endpoint):
|
| 102 |
-
try:
|
| 103 |
-
r=requests.get(f"https://bongda.com.vn{endpoint}",headers=BONGDA_HEADERS,timeout=10)
|
| 104 |
-
if r.status_code==200:
|
| 105 |
-
data=r.json()
|
| 106 |
-
if data.get("status")=="success":return data.get("html","")
|
| 107 |
-
return ""
|
| 108 |
-
except:return ""
|
| 109 |
-
def _parse_match_from_li(li, status_type="live"):
|
| 110 |
-
match_div=li.select_one("div.match")
|
| 111 |
-
if not match_div:return None
|
| 112 |
-
home_el=match_div.select_one(".home-team .name");away_el=match_div.select_one(".away-team .name")
|
| 113 |
-
if not home_el or not away_el:return None
|
| 114 |
-
status_el=match_div.select_one(".status a");league_el=li.find_previous("strong");time_el=match_div.select_one(".match-time")
|
| 115 |
-
home_logo=match_div.select_one(".home-team .logo img");away_logo=match_div.select_one(".away-team .logo img")
|
| 116 |
-
event_id=""
|
| 117 |
-
if status_el:
|
| 118 |
-
href=status_el.get("href","");m=re.search(r'/tran-dau/(\d+)/',href)
|
| 119 |
-
if m:event_id=m.group(1)
|
| 120 |
-
spans=status_el.find_all("span") if status_el else [];score="";minute=""
|
| 121 |
-
if len(spans)>=3:score=f"{spans[0].get_text(strip=True)} - {spans[2].get_text(strip=True)}"
|
| 122 |
-
if len(spans)>=4:minute=spans[3].get_text(strip=True)
|
| 123 |
-
if not score and status_el and status_el.select_one(".vs"):score="VS"
|
| 124 |
-
league=league_el.get_text(strip=True) if league_el else ""
|
| 125 |
-
return{"home":home_el.get_text(strip=True),"away":away_el.get_text(strip=True),"score":score or"VS","minute":minute,"league":league,"time":time_el.get_text(strip=True) if time_el else "","event_id":event_id,"home_logo":home_logo.get("src","") if home_logo else "","away_logo":away_logo.get("src","") if away_logo else "","status":status_type}
|
| 126 |
-
|
| 127 |
-
# ===== VIDEO PROXY =====
|
| 128 |
-
@app.get("/api/proxy/m3u8")
|
| 129 |
-
def proxy_m3u8(url: str = Query(...)):
|
| 130 |
-
try:
|
| 131 |
-
r = requests.get(url, headers=HEADERS, timeout=15)
|
| 132 |
-
if r.status_code != 200:return Response(status_code=502, content="upstream error")
|
| 133 |
-
lines = r.text.strip().split('\n');rewritten = []
|
| 134 |
-
for line in lines:
|
| 135 |
-
if line.startswith('#') or not line.strip():rewritten.append(line)
|
| 136 |
-
else:rewritten.append("/api/proxy/seg?url=" + quote(line.strip(), safe=""))
|
| 137 |
-
return Response(content='\n'.join(rewritten).encode('utf-8'),media_type="application/vnd.apple.mpegurl",headers={"Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=300"})
|
| 138 |
-
except:return Response(status_code=502, content="proxy error")
|
| 139 |
-
|
| 140 |
-
@app.get("/api/proxy/seg")
|
| 141 |
-
def proxy_segment(url: str = Query(...)):
|
| 142 |
-
try:
|
| 143 |
-
r = requests.get(url, headers=HEADERS, timeout=30)
|
| 144 |
-
if r.status_code != 200:return Response(status_code=502, content="upstream error")
|
| 145 |
-
data = r.content
|
| 146 |
-
if len(data) > 188 and data[0:4] == b'\x89PNG' and data[188] == 0x47:data = data[188:]
|
| 147 |
-
return Response(content=data,media_type="video/mp2t",headers={"Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=3600"})
|
| 148 |
-
except:return Response(status_code=502, content="proxy error")
|
| 149 |
-
|
| 150 |
-
@app.get("/api/proxy/video")
|
| 151 |
-
def proxy_video(url: str = Query(...), request: Request = None):
|
| 152 |
-
try:
|
| 153 |
-
req_headers = dict(HEADERS)
|
| 154 |
-
if request and request.headers.get("range"):req_headers["Range"] = request.headers["range"]
|
| 155 |
-
r = requests.get(url, headers=req_headers, timeout=30, stream=True)
|
| 156 |
-
resp_headers = {"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes","Content-Type":r.headers.get("Content-Type","video/mp4")}
|
| 157 |
-
if "Content-Range" in r.headers:resp_headers["Content-Range"] = r.headers["Content-Range"]
|
| 158 |
-
if "Content-Length" in r.headers:resp_headers["Content-Length"] = r.headers["Content-Length"]
|
| 159 |
-
return StreamingResponse(r.iter_content(chunk_size=256*1024),status_code=r.status_code,headers=resp_headers)
|
| 160 |
-
except:return Response(status_code=502, content="proxy error")
|
| 161 |
-
|
| 162 |
-
@app.get("/api/proxy/img")
|
| 163 |
-
def proxy_img(url: str = Query(...)):
|
| 164 |
-
"""Proxy images from sources that block hotlinking (DanTri CDN)."""
|
| 165 |
-
try:
|
| 166 |
-
r = requests.get(url, headers={**HEADERS, "Referer": "https://dantri.com.vn/"}, timeout=10)
|
| 167 |
-
if r.status_code != 200:return Response(status_code=502)
|
| 168 |
-
ct = r.headers.get("Content-Type", "image/jpeg")
|
| 169 |
-
return Response(content=r.content, media_type=ct, headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"})
|
| 170 |
-
except:return Response(status_code=502)
|
| 171 |
-
|
| 172 |
-
# ===== XEMLAIBONGDA HIGHLIGHTS =====
|
| 173 |
-
def _scrape_xemlaibongda_page(page_path, limit=20):
|
| 174 |
-
try:
|
| 175 |
-
url = f"https://xemlaibongda.top/{page_path}" if page_path else "https://xemlaibongda.top/"
|
| 176 |
-
r=requests.get(url,headers=HEADERS,timeout=15)
|
| 177 |
-
if r.status_code!=200:return[]
|
| 178 |
-
r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml");videos=[];seen=set()
|
| 179 |
-
for a in soup.find_all("a",href=True):
|
| 180 |
-
href=a.get("href","")
|
| 181 |
-
if"/video/" not in href:continue
|
| 182 |
-
if not href.startswith("http"):href="https://xemlaibongda.top"+href
|
| 183 |
-
if href in seen:continue
|
| 184 |
-
seen.add(href);slug=href.split("/video/")[-1].rstrip("/")
|
| 185 |
-
title=slug.replace("-"," ").title()
|
| 186 |
-
title=re.sub(r'\d{4}\s*\d{2}\s*\d{2}$','',title).strip()
|
| 187 |
-
title=re.sub(r'\s+V\s+',' vs ',title);title=re.sub(r'\s+Vs\s+',' vs ',title)
|
| 188 |
-
img=a.find("img") or (a.parent.find("img") if a.parent else None)
|
| 189 |
-
img_src=""
|
| 190 |
-
if img:img_src=img.get("data-src","") or img.get("src","") or img.get("data-lazy","")
|
| 191 |
-
if not img_src:img_src=f"https://img.refooty.com/thumbnail/{slug}.webp"
|
| 192 |
-
videos.append({"title":title,"link":href,"img":img_src,"source":"xemlaibongda"})
|
| 193 |
-
if len(videos)>=limit:break
|
| 194 |
-
return videos
|
| 195 |
-
except:return[]
|
| 196 |
-
|
| 197 |
-
def scrape_xemlaibongda():return _scrape_xemlaibongda_page("",20)
|
| 198 |
-
def scrape_highlights_by_league(league_key):
|
| 199 |
-
if league_key not in HL_LEAGUES:return[]
|
| 200 |
-
return _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"],20)
|
| 201 |
-
|
| 202 |
-
def scrape_all_league_highlights():
|
| 203 |
-
results = {}
|
| 204 |
-
def _fetch(key):return key, scrape_highlights_by_league(key)
|
| 205 |
-
with ThreadPoolExecutor(8) as ex:
|
| 206 |
-
futs = [ex.submit(_fetch, k) for k in HL_LEAGUES]
|
| 207 |
-
for f in as_completed(futs):
|
| 208 |
-
try:
|
| 209 |
-
key, vids = f.result()
|
| 210 |
-
if vids:results[key] = vids
|
| 211 |
-
except:pass
|
| 212 |
-
return results
|
| 213 |
-
|
| 214 |
-
def extract_xemlaibongda_video(url):
|
| 215 |
-
try:
|
| 216 |
-
r=requests.get(url,headers=HEADERS,timeout=15)
|
| 217 |
-
if r.status_code!=200:return None
|
| 218 |
-
r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml");video=soup.find("video")
|
| 219 |
-
if video:
|
| 220 |
-
src=video.get("src","");poster=video.get("poster","")
|
| 221 |
-
if not src:
|
| 222 |
-
source=video.find("source")
|
| 223 |
-
if source:src=source.get("src","")
|
| 224 |
-
if src:return{"src":src,"poster":poster,"type":"hls" if".m3u8" in src else"video"}
|
| 225 |
-
m3u8s=re.findall(r'(https?://[^\s"\'<>]+\.m3u8)',r.text)
|
| 226 |
-
if m3u8s:
|
| 227 |
-
og=soup.find("meta",property="og:image");poster=og.get("content","") if og else ""
|
| 228 |
-
return{"src":m3u8s[0],"poster":poster,"type":"hls"}
|
| 229 |
-
return None
|
| 230 |
-
except:return None
|
| 231 |
-
|
| 232 |
-
# ===== YOUTUBE SHORTS =====
|
| 233 |
-
# Permanent channel IDs (resolved from the @handles) used for the stable RSS feed.
|
| 234 |
-
_YT_CHANNEL_IDS={
|
| 235 |
-
"baodantri7941":"UCHZ_b_qC_k_ORdCkiPCpFsw",
|
| 236 |
-
"baosuckhoedoisongboyte":"UCD09NCZlzMj4yGvGkLbuBpw",
|
| 237 |
-
}
|
| 238 |
-
def _yt_rss_shorts(channel, count=24):
|
| 239 |
-
"""LIVE newest uploads via the YouTube RSS feed (stable from datacenter IPs, no API key).
|
| 240 |
-
Returns newest-first items. This is the primary, reliable source for the shorts slider."""
|
| 241 |
-
cid=_YT_CHANNEL_IDS.get(channel)
|
| 242 |
-
if not cid:return[]
|
| 243 |
-
try:
|
| 244 |
-
url=f"https://www.youtube.com/feeds/videos.xml?channel_id={cid}"
|
| 245 |
-
r=requests.get(url,headers={**HEADERS,"Accept-Language":"vi,en;q=0.8"},
|
| 246 |
-
cookies={"CONSENT":"YES+1"},timeout=15)
|
| 247 |
-
if r.status_code!=200 or not r.text:return[]
|
| 248 |
-
items=[]
|
| 249 |
-
# RSS is ordered newest-first; parse each <entry>.
|
| 250 |
-
for ent in re.findall(r"<entry>(.*?)</entry>",r.text,re.S):
|
| 251 |
-
mv=re.search(r"<yt:videoId>([A-Za-z0-9_-]{11})</yt:videoId>",ent)
|
| 252 |
-
if not mv:continue
|
| 253 |
-
vid=mv.group(1)
|
| 254 |
-
mt=re.search(r"<title>(.*?)</title>",ent,re.S)
|
| 255 |
-
title=html_lib.unescape(re.sub(r"\s+"," ",mt.group(1)).strip()) if mt else "YouTube Short"
|
| 256 |
-
items.append({"title":title,"link":f"https://www.youtube.com/watch?v={vid}",
|
| 257 |
-
"img":f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg","source":"yt","id":vid,"channel":channel})
|
| 258 |
-
if len(items)>=count:break
|
| 259 |
-
return items
|
| 260 |
-
except:return[]
|
| 261 |
-
def _yt_jina_page(handle, path):
|
| 262 |
-
"""Fetch a YouTube channel tab (videos/shorts) as markdown via r.jina.ai.
|
| 263 |
-
YouTube serves an EMPTY feeds/videos.xml to datacenter IPs, but the rendered
|
| 264 |
-
channel page through Jina returns the real newest videos (with Vietnamese titles
|
| 265 |
-
when X-Locale=vi-VN). This is the reliable source from the HF Space."""
|
| 266 |
-
u=f"https://www.youtube.com/@{handle}/{path}"
|
| 267 |
-
try:
|
| 268 |
-
r=requests.get("https://r.jina.ai/"+u,
|
| 269 |
-
headers={"User-Agent":"Mozilla/5.0","X-Return-Format":"markdown","X-Locale":"vi-VN"},
|
| 270 |
-
timeout=40)
|
| 271 |
-
if r.status_code!=200:return ""
|
| 272 |
-
return r.text
|
| 273 |
-
except:return ""
|
| 274 |
-
def _yt_jina_shorts(channel, count=24):
|
| 275 |
-
"""LIVE newest videos for a channel via Jina-rendered channel pages (works from the Space).
|
| 276 |
-
Pulls /videos then /shorts, newest-first, original Vietnamese titles."""
|
| 277 |
-
items=[];seen=set()
|
| 278 |
-
for path in ("videos","shorts"):
|
| 279 |
-
md=_yt_jina_page(channel,path)
|
| 280 |
-
if not md:continue
|
| 281 |
-
for m in re.finditer(r'\[([^\]\[]{8,160})\]\(https?://(?:www\.)?youtube\.com/(?:shorts/|watch\?v=)([A-Za-z0-9_-]{11})[^)]*\)',md):
|
| 282 |
-
title=html_lib.unescape(m.group(1)).strip().strip('"')
|
| 283 |
-
vid=m.group(2)
|
| 284 |
-
if vid in seen:continue
|
| 285 |
-
tl=title.lower()
|
| 286 |
-
if tl in ("home home","shorts shorts","image") or title.startswith("!") or title.startswith("Image"):continue
|
| 287 |
-
seen.add(vid)
|
| 288 |
-
items.append({"title":title,"link":f"https://www.youtube.com/watch?v={vid}",
|
| 289 |
-
"img":f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg","source":"yt","id":vid,"channel":channel})
|
| 290 |
-
if len(items)>=count:break
|
| 291 |
-
if len(items)>=count:break
|
| 292 |
-
return items
|
| 293 |
-
def _yt_channel_shorts(channel, count=24):
|
| 294 |
-
"""Live newest videos. Prefer Jina-rendered channel pages (reliable from datacenter IPs),
|
| 295 |
-
then the RSS feed, then a raw /shorts HTML scrape."""
|
| 296 |
-
items=_yt_jina_shorts(channel,count)
|
| 297 |
-
if items:return items
|
| 298 |
-
items=_yt_rss_shorts(channel,count)
|
| 299 |
-
if items:return items
|
| 300 |
-
# Fallback: HTML scrape of the shorts tab.
|
| 301 |
-
try:
|
| 302 |
-
url=f"https://www.youtube.com/@{channel}/shorts"
|
| 303 |
-
r=requests.get(url,headers={**HEADERS,"Accept-Language":"vi,en;q=0.8"},
|
| 304 |
-
cookies={"CONSENT":"YES+1"},timeout=15)
|
| 305 |
-
if r.status_code!=200:return[]
|
| 306 |
-
html=r.text
|
| 307 |
-
ids=[];items=[]
|
| 308 |
-
for m in re.finditer(r'"videoId":"([A-Za-z0-9_-]{11})"',html):
|
| 309 |
-
vid=m.group(1)
|
| 310 |
-
if vid in ids:continue
|
| 311 |
-
ids.append(vid)
|
| 312 |
-
snip=html[max(0,m.start()-900):m.start()+1600]
|
| 313 |
-
title=""
|
| 314 |
-
mt=re.search(r'"title":\{"runs":\[\{"text":"([^"]+)"',snip)
|
| 315 |
-
if not mt:mt=re.search(r'"accessibilityText":"([^"]+)"',snip)
|
| 316 |
-
if mt:title=html_lib.unescape(mt.group(1)).replace('\n',' ').strip()
|
| 317 |
-
if not title:title="YouTube Short"
|
| 318 |
-
items.append({"title":title,"link":f"https://www.youtube.com/watch?v={vid}","img":f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg","source":"yt","id":vid,"channel":channel})
|
| 319 |
-
if len(items)>=count:break
|
| 320 |
-
return items
|
| 321 |
-
except:return[]
|
| 322 |
-
# ----- Short vs normal-video classification -----
|
| 323 |
-
# A real YouTube Short responds 200 at /shorts/<id>; a normal (horizontal) video
|
| 324 |
-
# 3xx-redirects to /watch?v=<id>. We cache the result per id (it never changes).
|
| 325 |
-
_SHORT_KIND_CACHE={}
|
| 326 |
-
_SHORT_KIND_LOCK=threading.Lock()
|
| 327 |
-
def _classify_short(vid):
|
| 328 |
-
"""Return True if <vid> is a real vertical Short, False if it's a normal video.
|
| 329 |
-
Cached forever per id; network failures default to True (keep it in the shorts feed)."""
|
| 330 |
-
if not vid:return True
|
| 331 |
-
with _SHORT_KIND_LOCK:
|
| 332 |
-
if vid in _SHORT_KIND_CACHE:return _SHORT_KIND_CACHE[vid]
|
| 333 |
-
is_short=True
|
| 334 |
-
try:
|
| 335 |
-
r=requests.head(f"https://www.youtube.com/shorts/{vid}",
|
| 336 |
-
headers={**HEADERS,"Accept-Language":"vi,en;q=0.8"},
|
| 337 |
-
cookies={"CONSENT":"YES+1"},allow_redirects=False,timeout=4)
|
| 338 |
-
# 200 -> short ; 30x to /watch -> normal video
|
| 339 |
-
if r.status_code in (301,302,303,307,308):
|
| 340 |
-
loc=r.headers.get("Location","")
|
| 341 |
-
is_short = "/shorts/" in loc # redirect that stays in /shorts is still a short
|
| 342 |
-
if "/watch" in loc:is_short=False
|
| 343 |
-
elif r.status_code==200:
|
| 344 |
-
is_short=True
|
| 345 |
-
except:pass
|
| 346 |
-
with _SHORT_KIND_LOCK:_SHORT_KIND_CACHE[vid]=is_short
|
| 347 |
-
return is_short
|
| 348 |
-
def _classify_many(vids):
|
| 349 |
-
"""Classify a list of video ids in parallel; updates each dict's is_short in place."""
|
| 350 |
-
todo=[v for v in vids if v.get("id") and "is_short" not in v]
|
| 351 |
-
if not todo:return
|
| 352 |
-
with ThreadPoolExecutor(min(8,len(todo))) as ex:
|
| 353 |
-
futs={ex.submit(_classify_short,v["id"]):v for v in todo}
|
| 354 |
-
for f in as_completed(futs):
|
| 355 |
-
v=futs[f]
|
| 356 |
-
try:v["is_short"]=f.result()
|
| 357 |
-
except:v["is_short"]=True
|
| 358 |
-
def scrape_shorts():
|
| 359 |
-
"""Stable feed of Dân trí & SKĐS YouTube videos, each tagged is_short (true=short, false=normal).
|
| 360 |
-
Fast RSS scrape + static fallback so the slider never disappears."""
|
| 361 |
-
vids=[]
|
| 362 |
-
with ThreadPoolExecutor(2) as ex:
|
| 363 |
-
futs=[ex.submit(_yt_channel_shorts,ch,24) for ch in ["baodantri7941","baosuckhoedoisongboyte"]]
|
| 364 |
-
for f in as_completed(futs):
|
| 365 |
-
try:
|
| 366 |
-
r=f.result()
|
| 367 |
-
if r:vids.extend(r)
|
| 368 |
-
except:pass
|
| 369 |
-
merged=[];seen=set()
|
| 370 |
-
for v in vids+SHORTS_FALLBACK:
|
| 371 |
-
vid=v.get("id")
|
| 372 |
-
if not vid or vid in seen:continue
|
| 373 |
-
seen.add(vid);merged.append(v)
|
| 374 |
-
merged=merged[:40]
|
| 375 |
-
_classify_many(merged) # tag each with is_short
|
| 376 |
-
return merged
|
| 377 |
-
|
| 378 |
-
# ===== LIVESCORE =====
|
| 379 |
-
@app.get("/api/livescore/live")
|
| 380 |
-
def api_livescore_live():return JSONResponse({"html":_cached("ls_live",lambda:fetch_bongda_api("/api/fixtures/live"),ttl=_cache_ttl_live)})
|
| 381 |
-
@app.get("/api/livescore/incoming")
|
| 382 |
-
def api_livescore_incoming():return JSONResponse({"html":_cached("ls_incoming",lambda:fetch_bongda_api("/api/fixtures/incoming"),ttl=_cache_ttl_live)})
|
| 383 |
-
@app.get("/api/livescore/today")
|
| 384 |
-
def api_livescore_today():
|
| 385 |
-
today=datetime.now().strftime("%Y-%m-%d");return JSONResponse({"html":_cached("ls_today",lambda:fetch_bongda_api(f"/api/fixtures/get-by-date?date={today}"),ttl=_cache_ttl)})
|
| 386 |
-
@app.get("/api/livescore/results")
|
| 387 |
-
def api_livescore_results():
|
| 388 |
-
today=datetime.now().strftime("%Y-%m-%d");return JSONResponse({"html":_cached("ls_results",lambda:fetch_bongda_api(f"/api/fixtures/get-by-date?date={today}&status=finished"),ttl=_cache_ttl)})
|
| 389 |
-
@app.get("/api/livescore/standings/{league}")
|
| 390 |
-
def api_livescore_standings(league:str):
|
| 391 |
-
tid=LEAGUE_IDS.get(league,27110);return JSONResponse({"html":_cached(f"ls_bxh_{league}",lambda:fetch_bongda_api(f"/api/league-table/home?tournament_id={tid}&is_detail=True"),ttl=_cache_ttl)})
|
| 392 |
-
@app.get("/api/livescore/date/{date}")
|
| 393 |
-
def api_livescore_date(date:str):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/get-by-date?date={date}")})
|
| 394 |
-
@app.get("/api/match/{event_id}/commentaries")
|
| 395 |
-
def api_match_commentaries(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/commentaries?event_id={event_id}")})
|
| 396 |
-
@app.get("/api/match/{event_id}/stats")
|
| 397 |
-
def api_match_stats(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/event-standing/player-performance?event_id={event_id}")})
|
| 398 |
-
@app.get("/api/livescore/featured")
|
| 399 |
-
def api_livescore_featured():
|
| 400 |
-
def _f():
|
| 401 |
-
sources=[("/api/fixtures/live","live"),("/api/fixtures/get-by-date?date="+datetime.now().strftime("%Y-%m-%d"),"today"),("/api/fixtures/incoming","upcoming")]
|
| 402 |
-
for endpoint, stype in sources:
|
| 403 |
-
html=fetch_bongda_api(endpoint)
|
| 404 |
-
if not html or len(html)<100:continue
|
| 405 |
-
soup=BeautifulSoup(html,"lxml");all_matches=[]
|
| 406 |
-
for li in soup.select("li.match-detail"):
|
| 407 |
-
match=_parse_match_from_li(li, stype)
|
| 408 |
-
if not match or not match["event_id"]:continue
|
| 409 |
-
if stype=="today" and "KT" in match.get("minute",""):continue
|
| 410 |
-
all_matches.append(match)
|
| 411 |
-
if not all_matches:continue
|
| 412 |
-
for pl in PRIORITY_LEAGUES:
|
| 413 |
-
for match in all_matches:
|
| 414 |
-
if pl in match["league"]:return match
|
| 415 |
-
return all_matches[0]
|
| 416 |
-
return None
|
| 417 |
-
return JSONResponse(_cached("ls_featured",_f,ttl=30))
|
| 418 |
-
|
| 419 |
-
# ===== VIDEO APIs =====
|
| 420 |
-
@app.get("/api/shorts")
|
| 421 |
-
def api_shorts():return JSONResponse(_cached("yt_shorts_v3",scrape_shorts,ttl=_cache_ttl_yt))
|
| 422 |
-
@app.get("/api/short-stats")
|
| 423 |
-
def api_short_stats(ids:str=Query(default="")):
|
| 424 |
-
arr=[x for x in ids.split(",") if x]
|
| 425 |
-
with _short_lock:
|
| 426 |
-
db=_load_short_db();out={}
|
| 427 |
-
for vid in arr:
|
| 428 |
-
st=db.get(vid) or _short_default()
|
| 429 |
-
out[vid]={"views":int(st.get("views",0)),"likes":int(st.get("likes",0)),"shares":int(st.get("shares",0)),"comments":st.get("comments",[])[:80]}
|
| 430 |
-
return JSONResponse({"stats":out})
|
| 431 |
-
|
| 432 |
-
@app.post("/api/short-action")
|
| 433 |
-
async def api_short_action(request:Request):
|
| 434 |
-
try:body=await request.json()
|
| 435 |
-
except:body={}
|
| 436 |
-
vid=str(body.get("id","")).strip();action=str(body.get("action","")).strip();txt=str(body.get("text","")).strip()
|
| 437 |
-
if not vid:return JSONResponse({"error":"missing id"},status_code=400)
|
| 438 |
-
with _short_lock:
|
| 439 |
-
db=_load_short_db();st=db.get(vid) or _short_default()
|
| 440 |
-
if action=="view":st["views"]=int(st.get("views",0))+1
|
| 441 |
-
elif action=="like":st["likes"]=int(st.get("likes",0))+1
|
| 442 |
-
elif action=="share":st["shares"]=int(st.get("shares",0))+1
|
| 443 |
-
elif action=="comment" and txt:
|
| 444 |
-
comments=st.get("comments",[])
|
| 445 |
-
comments.insert(0,{"text":txt[:180],"ts":int(time.time())})
|
| 446 |
-
st["comments"]=comments[:80]
|
| 447 |
-
st["updated"]=int(time.time());db[vid]=st;_save_short_db(db)
|
| 448 |
-
out={"views":int(st.get("views",0)),"likes":int(st.get("likes",0)),"shares":int(st.get("shares",0)),"comments":st.get("comments",[])[:80]}
|
| 449 |
-
return JSONResponse({"stats":out})
|
| 450 |
-
|
| 451 |
-
@app.get("/api/highlights")
|
| 452 |
-
def api_highlights():return JSONResponse(_cached("xemlaibongda_hl",scrape_xemlaibongda,ttl=_cache_ttl))
|
| 453 |
-
@app.get("/api/highlights/leagues")
|
| 454 |
-
def api_highlights_leagues():return JSONResponse(_cached("hl_leagues",scrape_all_league_highlights,ttl=_cache_ttl))
|
| 455 |
-
@app.get("/api/highlights/{league}")
|
| 456 |
-
def api_highlights_league(league:str):
|
| 457 |
-
if league not in HL_LEAGUES:return JSONResponse({"error":"league not found"})
|
| 458 |
-
return JSONResponse(_cached(f"hl_{league}",lambda:scrape_highlights_by_league(league),ttl=_cache_ttl))
|
| 459 |
-
@app.get("/api/highlights_config")
|
| 460 |
-
def api_highlights_config():return JSONResponse(HL_LEAGUES)
|
| 461 |
-
@app.get("/api/video_url")
|
| 462 |
-
def api_video_url(url:str=Query(...)):
|
| 463 |
-
if "youtube.com" in url or "youtu.be" in url:
|
| 464 |
-
m=re.search(r'(?:v=|shorts/|youtu\.be/)([a-zA-Z0-9_-]{11})',url)
|
| 465 |
-
if m:vid=m.group(1);return JSONResponse({"src":f"https://www.youtube.com/embed/{vid}?autoplay=1&rel=0&enablejsapi=1","poster":f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg","type":"youtube"})
|
| 466 |
-
if "xemlaibongda.top" in url:
|
| 467 |
-
v=extract_xemlaibongda_video(url)
|
| 468 |
-
if v:
|
| 469 |
-
if v["type"]=="hls":v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="")
|
| 470 |
-
return JSONResponse(v)
|
| 471 |
-
if "bongdaplus.vn" in url:
|
| 472 |
-
try:
|
| 473 |
-
m=re.search(r'-(\d{6,})\.html',url)
|
| 474 |
-
if m:
|
| 475 |
-
r=requests.get(f"{BASE_BDP}/video-embed/{m.group(1)}.html",headers=HEADERS,timeout=10);r.encoding="utf-8"
|
| 476 |
-
soup=BeautifulSoup(r.text,"lxml");video=soup.select_one("video#videoPlayer")
|
| 477 |
-
if video:
|
| 478 |
-
source=video.find("source");src=source.get("src","") if source else "";poster=video.get("poster","")
|
| 479 |
-
if src:return JSONResponse({"src":"/api/proxy/video?url="+quote(src,safe=""),"poster":poster,"type":"video"})
|
| 480 |
-
except:pass
|
| 481 |
-
return JSONResponse({"error":"not found"})
|
| 482 |
-
@app.get("/api/bdp_videos")
|
| 483 |
-
def api_bdp_videos():
|
| 484 |
-
def _f():
|
| 485 |
-
try:
|
| 486 |
-
soup=_get(f"{BASE_BDP}/video");arts=[];seen=set()
|
| 487 |
-
for a in soup.find_all("a",href=True):
|
| 488 |
-
href=a.get("href","")
|
| 489 |
-
if"/video/" not in href or href in("/video/","/video/ban-thang-dep","/video/highlight"):continue
|
| 490 |
-
if not href.startswith("http"):href=BASE_BDP+href
|
| 491 |
-
if href in seen:continue
|
| 492 |
-
title=re.sub(r'^\d{2}:\d{2}','',a.get_text(strip=True)).strip()
|
| 493 |
-
if not title or len(title)<5:continue
|
| 494 |
-
img_tag=a.find("img") or(a.parent.find("img") if a.parent else None)
|
| 495 |
-
img=(img_tag.get("data-src") or img_tag.get("src","")) if img_tag else ""
|
| 496 |
-
seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bdp"})
|
| 497 |
-
return arts[:20]
|
| 498 |
-
except:return[]
|
| 499 |
-
return JSONResponse(_cached("bdp_videos",_f))
|
| 500 |
-
# ===== NEWS =====
|
| 501 |
-
def scrape_vne(cat_url):
|
| 502 |
-
try:
|
| 503 |
-
soup=_get(cat_url);arts=[]
|
| 504 |
-
for it in soup.select("article.item-news")[:15]:
|
| 505 |
-
a=it.select_one("h2.title-news a") or it.select_one("h3.title-news a")
|
| 506 |
-
if not a:continue
|
| 507 |
-
t=a.get("title","") or a.get_text(strip=True);lk=a.get("href","")
|
| 508 |
-
if not t or not lk:continue
|
| 509 |
-
im=it.find("img");img=(im.get("data-src") or im.get("src","")) if im else ""
|
| 510 |
-
if img and'blank'in img:
|
| 511 |
-
src=it.find("source")
|
| 512 |
-
if src:img=src.get("srcset","").split(",")[0].strip().split(" ")[0]
|
| 513 |
-
arts.append({"title":t,"link":lk,"img":img,"source":"vne"})
|
| 514 |
-
return arts
|
| 515 |
-
except:return[]
|
| 516 |
-
def scrape_vne_article(url):
|
| 517 |
-
try:
|
| 518 |
-
soup=_get(url);h1=soup.select_one("h1.title-detail");desc=soup.select_one("p.description")
|
| 519 |
-
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 520 |
-
cd=soup.select_one("article.fck_detail");body=[]
|
| 521 |
-
if cd:
|
| 522 |
-
for ch in cd.children:
|
| 523 |
-
if not hasattr(ch,'name') or not ch.name:continue
|
| 524 |
-
if ch.name=="p":t=ch.get_text(strip=True);(body.append({"type":"p","text":t}) if t else None)
|
| 525 |
-
elif ch.name=="figure":
|
| 526 |
-
im=ch.find("img")
|
| 527 |
-
if im:s=im.get("data-src") or im.get("src","");body.append({"type":"img","src":s})
|
| 528 |
-
elif ch.name in("h2","h3"):body.append({"type":"heading","text":ch.get_text(strip=True)})
|
| 529 |
-
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}
|
| 530 |
-
except:return None
|
| 531 |
-
def _scrape_dantri_homepage(cat_filter=None):
|
| 532 |
-
try:
|
| 533 |
-
soup=_get("https://dantri.com.vn/");arts=[];seen=set()
|
| 534 |
-
for a in soup.find_all("a",href=True):
|
| 535 |
-
href=a.get("href","");title=a.get("title","") or a.get_text(strip=True)
|
| 536 |
-
if not title or len(title)<15 or"javascript:" in href:continue
|
| 537 |
-
if not href.startswith("http"):href="https://dantri.com.vn"+href
|
| 538 |
-
if href in seen or not href.endswith(".htm"):continue
|
| 539 |
-
if cat_filter and f"/{cat_filter}/" not in href:continue
|
| 540 |
-
img_tag=a.find("img")
|
| 541 |
-
if not img_tag and a.parent:img_tag=a.parent.find("img")
|
| 542 |
-
img_src=""
|
| 543 |
-
if img_tag:img_src=img_tag.get("data-src","") or img_tag.get("src","")
|
| 544 |
-
if not img_src or "cdn" not in img_src:continue
|
| 545 |
-
proxied_img="/api/proxy/img?url="+quote(img_src,safe="")
|
| 546 |
-
seen.add(href);arts.append({"title":title,"link":href,"img":proxied_img,"source":"dantri"})
|
| 547 |
-
if len(arts)>=15:break
|
| 548 |
-
return arts
|
| 549 |
-
except:return[]
|
| 550 |
-
def scrape_dantri_hot():return _scrape_dantri_homepage()
|
| 551 |
-
def scrape_dantri_congnghe():
|
| 552 |
-
try:
|
| 553 |
-
soup=_get("https://dantri.com.vn/");arts=[];seen=set()
|
| 554 |
-
for a in soup.find_all("a",href=True):
|
| 555 |
-
href=a.get("href","");title=a.get("title","") or a.get_text(strip=True)
|
| 556 |
-
if not title or len(title)<15 or"javascript:" in href:continue
|
| 557 |
-
if not href.startswith("http"):href="https://dantri.com.vn"+href
|
| 558 |
-
if href in seen or not href.endswith(".htm"):continue
|
| 559 |
-
if"/cong-nghe/" not in href:continue
|
| 560 |
-
img_tag=a.find("img")
|
| 561 |
-
if not img_tag and a.parent:img_tag=a.parent.find("img")
|
| 562 |
-
img_src=""
|
| 563 |
-
if img_tag:img_src=img_tag.get("data-src","") or img_tag.get("src","")
|
| 564 |
-
if img_src and "cdn" in img_src:img_src="/api/proxy/img?url="+quote(img_src,safe="")
|
| 565 |
-
else:img_src=""
|
| 566 |
-
seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"dantri"})
|
| 567 |
-
if len(arts)>=15:break
|
| 568 |
-
return arts
|
| 569 |
-
except:return[]
|
| 570 |
-
|
| 571 |
-
# ===== JINA READER (for Cloudflare/SPA sites: vatvostudio, bongda, bongdaplus) =====
|
| 572 |
-
_JINA_CACHE={}
|
| 573 |
-
_JINA_LOCK=threading.Lock()
|
| 574 |
-
def _jina_md(url, ttl=600):
|
| 575 |
-
"""Fetch a page as markdown via r.jina.ai (bypasses Cloudflare/JS SPA). Cached."""
|
| 576 |
-
now=time.time()
|
| 577 |
-
with _JINA_LOCK:
|
| 578 |
-
c=_JINA_CACHE.get(url)
|
| 579 |
-
if c and now-c[0]<ttl:return c[1]
|
| 580 |
-
md=""
|
| 581 |
-
try:
|
| 582 |
-
r=requests.get("https://r.jina.ai/"+url,
|
| 583 |
-
headers={"Accept":"text/markdown","X-Return-Format":"markdown","User-Agent":"Mozilla/5.0"},timeout=30)
|
| 584 |
-
if r.status_code==200:md=r.text
|
| 585 |
-
except:pass
|
| 586 |
-
with _JINA_LOCK:_JINA_CACHE[url]=(now,md)
|
| 587 |
-
return md
|
| 588 |
-
|
| 589 |
-
def _jina_articles(md, host_re, require_id=True):
|
| 590 |
-
"""Parse markdown -> [{title,url,img}] for a given host regex.
|
| 591 |
-
Handles two markdown forms Jina emits:
|
| 592 |
-
[](URL) -> gives image + url (title often empty here)
|
| 593 |
-
[Plain Title](URL) -> gives title + url
|
| 594 |
-
Merge both by URL so each article has a title AND (when available) an image."""
|
| 595 |
-
titles={}; imgs={}; order=[]
|
| 596 |
-
def _ok(u):
|
| 597 |
-
u=u.split(' ')[0].strip()
|
| 598 |
-
if u.endswith(('.png','.jpg','.jpeg','.webp','.svg','.gif')):return None
|
| 599 |
-
if require_id and not re.search(r'-[a-z]?\d{4,}\.html', u):return None
|
| 600 |
-
if any(x in u for x in('/category/','/author/','/tag/','/page/')):return None
|
| 601 |
-
if not re.match('^'+host_re, u):return None
|
| 602 |
-
return u
|
| 603 |
-
# 1) image-wrapped links: [](URL "optional title")
|
| 604 |
-
for m in re.finditer(r'\[!\[[^\]]*\]\((https?://[^)\s]+)\)\]\(('+host_re+r'[^)\s]+)(?:\s+"[^"]*")?\)', md):
|
| 605 |
-
u=_ok(m.group(2))
|
| 606 |
-
if not u:continue
|
| 607 |
-
if u not in imgs:imgs[u]=m.group(1)
|
| 608 |
-
if u not in order:order.append(u)
|
| 609 |
-
# 2) plain text links: [Title](URL "optional title")
|
| 610 |
-
for m in re.finditer(r'(?<!!)\[([^\]\[]{15,140})\]\(('+host_re+r'[^)\s]+)(?:\s+"[^"]*")?\)', md):
|
| 611 |
-
title=m.group(1).strip().strip('"')
|
| 612 |
-
if title.startswith('!') or title.lower() in ('image','tin tức','trang chủ'):continue
|
| 613 |
-
u=_ok(m.group(2))
|
| 614 |
-
if not u:continue
|
| 615 |
-
if u not in titles:titles[u]=title
|
| 616 |
-
if u not in order:order.append(u)
|
| 617 |
-
out=[]
|
| 618 |
-
for u in order:
|
| 619 |
-
title=titles.get(u,'')
|
| 620 |
-
if not title or len(title)<15:continue
|
| 621 |
-
out.append({"title":title,"link":u,"img":imgs.get(u,"")})
|
| 622 |
-
return out
|
| 623 |
-
|
| 624 |
-
def scrape_vatvostudio():
|
| 625 |
-
"""Vat Vo Studio (vatvostudio.vn) - Cloudflare-protected WP tech/AI site via Jina. Newest first."""
|
| 626 |
-
md=_jina_md("https://vatvostudio.vn/")
|
| 627 |
-
arts=[]
|
| 628 |
-
for a in _jina_articles(md, r'https://vatvostudio\.vn/', require_id=False):
|
| 629 |
-
u=a["link"]
|
| 630 |
-
# real articles are /<slug>/ (one path segment, ends with /)
|
| 631 |
-
if not re.match(r'^https://vatvostudio\.vn/[a-z0-9\-]{8,}/?$', u):continue
|
| 632 |
-
a["source"]="vatvo";arts.append(a)
|
| 633 |
-
if len(arts)>=24:break
|
| 634 |
-
return arts
|
| 635 |
-
|
| 636 |
-
def scrape_bongda_jina(limit=30):
|
| 637 |
-
"""bongda.com.vn homepage articles (via Jina; site is JS-protected)."""
|
| 638 |
-
md=_jina_md("https://bongda.com.vn/")
|
| 639 |
-
arts=[a for a in _jina_articles(md, r'https://bongda\.com\.vn/')]
|
| 640 |
-
for a in arts:a["source"]="bongda";a.setdefault("img","")
|
| 641 |
-
return arts[:limit]
|
| 642 |
-
|
| 643 |
-
def scrape_bongdaplus_jina(limit=30):
|
| 644 |
-
"""bongdaplus.vn homepage articles (via Jina; site is a JS SPA)."""
|
| 645 |
-
md=_jina_md("https://bongdaplus.vn/")
|
| 646 |
-
arts=[a for a in _jina_articles(md, r'https://bongdaplus\.vn/')]
|
| 647 |
-
for a in arts:a["source"]="bongdaplus";a.setdefault("img","")
|
| 648 |
-
return arts[:limit]
|
| 649 |
-
|
| 650 |
-
def scrape_genk_ai():
|
| 651 |
-
"""Scrape AI articles from genk.vn - readable in-app"""
|
| 652 |
-
try:
|
| 653 |
-
r=requests.get("https://genk.vn/ai.chn",headers=HEADERS,timeout=15)
|
| 654 |
-
if r.status_code!=200:return[]
|
| 655 |
-
r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
|
| 656 |
-
articles=[];seen=set()
|
| 657 |
-
for a in soup.find_all("a",href=True):
|
| 658 |
-
href=a.get("href","")
|
| 659 |
-
if not href.endswith(".chn") or href=="/ai.chn":continue
|
| 660 |
-
if href.startswith("/"):href="https://genk.vn"+href
|
| 661 |
-
if href in seen or "genk.vn" not in href:continue
|
| 662 |
-
title=a.get("title","") or a.get_text(strip=True)
|
| 663 |
-
if not title or len(title)<20:continue
|
| 664 |
-
container=a.parent;img_src=""
|
| 665 |
-
for _ in range(6):
|
| 666 |
-
if container is None:break
|
| 667 |
-
for img in container.find_all("img"):
|
| 668 |
-
s=img.get("data-src","") or img.get("src","")
|
| 669 |
-
if s and "mediacdn" in s and "avatar" not in s and "logo" not in s:
|
| 670 |
-
img_src=s;break
|
| 671 |
-
if img_src:break
|
| 672 |
-
container=container.parent
|
| 673 |
-
seen.add(href)
|
| 674 |
-
if not img_src:
|
| 675 |
-
try:
|
| 676 |
-
og_r=requests.get(href,headers=HEADERS,timeout=8);og_r.encoding="utf-8"
|
| 677 |
-
og_soup=BeautifulSoup(og_r.text,"lxml");og_tag=og_soup.find("meta",property="og:image")
|
| 678 |
-
if og_tag:img_src=og_tag.get("content","")
|
| 679 |
-
except:pass
|
| 680 |
-
articles.append({"title":title,"link":href,"img":img_src,"source":"genk"})
|
| 681 |
-
if len(articles)>=30:break
|
| 682 |
-
return articles
|
| 683 |
-
except:return[]
|
| 684 |
-
|
| 685 |
-
def scrape_dantri_article(url):
|
| 686 |
-
try:
|
| 687 |
-
r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
|
| 688 |
-
for tag in soup.find_all(["script","style","nav","footer","aside"]):tag.decompose()
|
| 689 |
-
h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 690 |
-
if og_img and "cdnphoto.dantri" in og_img:og_img="/api/proxy/img?url="+quote(og_img,safe="")
|
| 691 |
-
content=soup.select_one("main") or soup.select_one("div.singular-content") or soup.select_one("article");body=[]
|
| 692 |
-
if content:
|
| 693 |
-
for el in content.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 694 |
-
if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None)
|
| 695 |
-
elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None)
|
| 696 |
-
elif el.name in("figure","img"):
|
| 697 |
-
im=el if el.name=="img" else el.find("img")
|
| 698 |
-
if im:
|
| 699 |
-
s=im.get("data-src") or im.get("src","")
|
| 700 |
-
if s and"base64" not in s:
|
| 701 |
-
if "cdnphoto.dantri" in s:s="/api/proxy/img?url="+quote(s,safe="")
|
| 702 |
-
body.append({"type":"img","src":s})
|
| 703 |
-
desc="";sapo=soup.select_one("h2.singular-sapo") or soup.select_one("h2[class*=sapo]")
|
| 704 |
-
if not sapo:
|
| 705 |
-
og_desc=soup.find("meta",property="og:description")
|
| 706 |
-
if og_desc:desc=og_desc.get("content","")
|
| 707 |
-
else:desc=sapo.get_text(strip=True)
|
| 708 |
-
return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"dantri","url":url}
|
| 709 |
-
except:return None
|
| 710 |
-
def scrape_bbc_vietnamese():
|
| 711 |
-
try:
|
| 712 |
-
r=requests.get("https://www.bbc.com/vietnamese",headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
|
| 713 |
-
soup=BeautifulSoup(r.text,"lxml");arts=[];seen=set()
|
| 714 |
-
for a in soup.select("a[href*='/vietnamese/']"):
|
| 715 |
-
href=a.get("href","")
|
| 716 |
-
if not href or href=="/vietnamese" or href.count("/")<3:continue
|
| 717 |
-
if not href.startswith("http"):href="https://www.bbc.com"+href
|
| 718 |
-
if href in seen:continue
|
| 719 |
-
title=a.get_text(strip=True)
|
| 720 |
-
if not title or len(title)<15 or any(x in title.lower() for x in["đăng nhập","trang chủ","bbc news"]):continue
|
| 721 |
-
img="";container=a.parent
|
| 722 |
-
for _ in range(3):
|
| 723 |
-
if container:
|
| 724 |
-
im=container.find("img")
|
| 725 |
-
if im:img=im.get("src","") or im.get("data-src","");break
|
| 726 |
-
container=container.parent
|
| 727 |
-
seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bbc"})
|
| 728 |
-
if len(arts)>=15:break
|
| 729 |
-
return arts
|
| 730 |
-
except:return[]
|
| 731 |
-
def scrape_bbc_article(url):
|
| 732 |
-
try:
|
| 733 |
-
r=requests.get(url,headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
|
| 734 |
-
soup=BeautifulSoup(r.text,"lxml");h1=soup.find("h1")
|
| 735 |
-
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 736 |
-
body=[]
|
| 737 |
-
for p in soup.select("[data-component='text-block'] p, article p, main p"):
|
| 738 |
-
t=p.get_text(strip=True)
|
| 739 |
-
if t and len(t)>20:body.append({"type":"p","text":t})
|
| 740 |
-
return{"title":h1.get_text(strip=True) if h1 else "","summary":"","og_image":og_img,"body":body,"source":"bbc","url":url}
|
| 741 |
-
except:return None
|
| 742 |
-
|
| 743 |
-
def scrape_ttvh_worldcup():
|
| 744 |
-
"""Scrape all World Cup 2026 articles from The Thao Van Hoa RSS."""
|
| 745 |
-
try:
|
| 746 |
-
r=requests.get("https://thethaovanhoa.vn/rss/world-cup-2026.rss",headers=HEADERS,timeout=15);r.encoding="utf-8"
|
| 747 |
-
soup=BeautifulSoup(r.text,"xml");arts=[];seen=set()
|
| 748 |
-
for it in soup.find_all("item"):
|
| 749 |
-
title=(it.find("title").get_text(strip=True) if it.find("title") else "")
|
| 750 |
-
link=(it.find("link").get_text(strip=True) if it.find("link") else "")
|
| 751 |
-
desc=(it.find("description").get_text(" ",strip=True) if it.find("description") else "")
|
| 752 |
-
img="";ds=BeautifulSoup(desc,"lxml");im=ds.find("img")
|
| 753 |
-
if im:img=im.get("src","") or im.get("data-src","")
|
| 754 |
-
if title and link and link not in seen:
|
| 755 |
-
seen.add(link);arts.append({"title":title,"link":link,"img":img,"source":"ttvh"})
|
| 756 |
-
if arts:return arts
|
| 757 |
-
except:pass
|
| 758 |
-
try:
|
| 759 |
-
soup=_get("https://thethaovanhoa.vn/world-cup-2026.htm");arts=[];seen=set()
|
| 760 |
-
for a in soup.find_all("a",href=True):
|
| 761 |
-
href=a.get("href","")
|
| 762 |
-
if not href.startswith("http"):href="https://thethaovanhoa.vn"+href
|
| 763 |
-
if href in seen or "thethaovanhoa.vn" not in href:continue
|
| 764 |
-
if not re.search(r"/[^/]+-\d{8,}\.htm",href):continue
|
| 765 |
-
title=a.get("title","") or a.get_text(" ",strip=True)
|
| 766 |
-
img=None;p=a
|
| 767 |
-
for _ in range(5):
|
| 768 |
-
if p is None:break
|
| 769 |
-
img=p.find("img")
|
| 770 |
-
if img:break
|
| 771 |
-
p=p.parent
|
| 772 |
-
img_src=""
|
| 773 |
-
if img:
|
| 774 |
-
img_src=img.get("data-src","") or img.get("src","") or img.get("data-original","") or img.get("data-thumb","")
|
| 775 |
-
if len(title)<15:title=img.get("alt","") or img.get("title","") or title
|
| 776 |
-
if not title or len(title)<15:continue
|
| 777 |
-
seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"ttvh"})
|
| 778 |
-
if len(arts)>=24:break
|
| 779 |
-
return arts
|
| 780 |
-
except:return[]
|
| 781 |
-
|
| 782 |
-
def scrape_ttvh_article(url):
|
| 783 |
-
try:
|
| 784 |
-
soup=_get(url);h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 785 |
-
og_title=soup.find("meta",property="og:title");fallback_title=og_title.get("content","") if og_title else ""
|
| 786 |
-
desc_el=soup.find("meta",property="og:description");desc=desc_el.get("content","") if desc_el else ""
|
| 787 |
-
cd=soup.select_one(".detail-content") or soup.select_one(".content-detail") or soup.select_one("article") or soup.select_one("main")
|
| 788 |
-
body=[]
|
| 789 |
-
if cd:
|
| 790 |
-
for el in cd.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 791 |
-
if el.name=="p":
|
| 792 |
-
t=el.get_text(strip=True)
|
| 793 |
-
if t and len(t)>20 and "Theo dõi" not in t:body.append({"type":"p","text":t})
|
| 794 |
-
elif el.name in ("h2","h3"):
|
| 795 |
-
t=el.get_text(strip=True)
|
| 796 |
-
if t:body.append({"type":"heading","text":t})
|
| 797 |
-
elif el.name in ("figure","img"):
|
| 798 |
-
im=el if el.name=="img" else el.find("img")
|
| 799 |
-
if im:
|
| 800 |
-
src=im.get("data-src") or im.get("src","") or im.get("data-original","")
|
| 801 |
-
if src and "base64" not in src:body.append({"type":"img","src":src})
|
| 802 |
-
if not body and desc:body=[{"type":"p","text":desc}]
|
| 803 |
-
return {"title":h1.get_text(strip=True) if h1 else fallback_title,"summary":desc,"og_image":og_img,"body":body,"source":"ttvh","url":url}
|
| 804 |
-
except:return None
|
| 805 |
-
|
| 806 |
-
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")}
|
| 807 |
-
@app.get("/api/homepage")
|
| 808 |
-
def api_homepage():
|
| 809 |
-
def _f():
|
| 810 |
-
articles=[]
|
| 811 |
-
with ThreadPoolExecutor(12) as ex:
|
| 812 |
-
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"]}
|
| 813 |
-
futs[ex.submit(scrape_bbc_vietnamese)]="BBC"
|
| 814 |
-
for f in as_completed(futs):
|
| 815 |
-
try:
|
| 816 |
-
for a in f.result():a["group"]=futs[f];articles.append(a)
|
| 817 |
-
except:pass
|
| 818 |
-
return articles
|
| 819 |
-
return JSONResponse(_cached("homepage",_f))
|
| 820 |
-
@app.get("/api/category/{cat_id}")
|
| 821 |
-
def api_category(cat_id:str):
|
| 822 |
-
def _f():
|
| 823 |
-
if cat_id=="bbc":return scrape_bbc_vietnamese()
|
| 824 |
-
if cat_id=="cong-nghe":return scrape_genk_ai()
|
| 825 |
-
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
|
| 826 |
-
return[]
|
| 827 |
-
return JSONResponse(_cached(f"cat_{cat_id}",_f))
|
| 828 |
-
@app.get("/api/categories")
|
| 829 |
-
def api_categories():
|
| 830 |
-
cats=[{"id":"bbc","name":"BBC Tiếng Việt","source":"bbc"},{"id":"cong-nghe","name":"Công Nghệ","source":"genk"}]
|
| 831 |
-
for k,(u,n) in VNE_CATS.items():cats.append({"id":k,"name":n,"source":"vne"})
|
| 832 |
-
return JSONResponse(cats)
|
| 833 |
-
@app.get("/api/dantri_hot")
|
| 834 |
-
def api_dantri_hot():return JSONResponse(_cached("dantri_hot",scrape_dantri_hot))
|
| 835 |
-
@app.get("/api/genk_ai")
|
| 836 |
-
def api_genk_ai():
|
| 837 |
-
def _ai_apps():
|
| 838 |
-
# vatvostudio.vn first (newest), then GenK AI — deduped by title
|
| 839 |
-
vatvo=_cached("vatvo_ai",scrape_vatvostudio,ttl=_cache_ttl)
|
| 840 |
-
genk=_cached("genk_ai",scrape_genk_ai,ttl=_cache_ttl)
|
| 841 |
-
out=[];seen=set()
|
| 842 |
-
for a in (vatvo or [])+(genk or []):
|
| 843 |
-
key=(a.get("title","") or "").strip().lower()
|
| 844 |
-
if not key or key in seen:continue
|
| 845 |
-
seen.add(key);out.append(a)
|
| 846 |
-
return out
|
| 847 |
-
return JSONResponse(_cached("ai_apps_merged",_ai_apps,ttl=_cache_ttl))
|
| 848 |
-
@app.get("/api/worldcup2026")
|
| 849 |
-
def api_worldcup2026():return JSONResponse(_cached("ttvh_worldcup",scrape_ttvh_worldcup,ttl=_cache_ttl))
|
| 850 |
-
def scrape_genk_article(url):
|
| 851 |
-
try:
|
| 852 |
-
r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
|
| 853 |
-
h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 854 |
-
og_title=soup.find("meta",property="og:title");fallback_title=og_title.get("content","") if og_title else ""
|
| 855 |
-
desc_el=soup.find("meta",property="og:description");desc=desc_el.get("content","") if desc_el else ""
|
| 856 |
-
cd=soup.select_one(".knc-content");body=[]
|
| 857 |
-
if cd:
|
| 858 |
-
for el in cd.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 859 |
-
if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None)
|
| 860 |
-
elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None)
|
| 861 |
-
elif el.name in("figure","img"):
|
| 862 |
-
im=el if el.name=="img" else el.find("img")
|
| 863 |
-
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)
|
| 864 |
-
return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"genk","url":url}
|
| 865 |
-
except:return None
|
| 866 |
-
|
| 867 |
-
@app.get("/api/article")
|
| 868 |
-
def api_article(url:str=Query(...)):
|
| 869 |
-
if"vnexpress.net" in url:data=scrape_vne_article(url)
|
| 870 |
-
elif"bbc.com" in url:data=scrape_bbc_article(url)
|
| 871 |
-
elif"dantri.com.vn" in url:data=scrape_dantri_article(url)
|
| 872 |
-
elif"genk.vn" in url:data=scrape_genk_article(url)
|
| 873 |
-
elif"thethaovanhoa.vn" in url:data=scrape_ttvh_article(url)
|
| 874 |
-
else:data=None
|
| 875 |
-
return JSONResponse(data if data else{"error":"not supported"})
|
| 876 |
-
def _web_context(topic):
|
| 877 |
-
"""Collect real web/news context for a topic."""
|
| 878 |
-
bits=[]
|
| 879 |
-
try:
|
| 880 |
-
rss="https://news.google.com/rss/search?q="+quote(topic)+"&hl=vi&gl=VN&ceid=VN:vi"
|
| 881 |
-
r=requests.get(rss,headers=HEADERS,timeout=12);r.encoding="utf-8"
|
| 882 |
-
soup=BeautifulSoup(r.text,"xml")
|
| 883 |
-
for it in soup.find_all("item")[:8]:
|
| 884 |
-
title=it.find("title").get_text(" ",strip=True) if it.find("title") else ""
|
| 885 |
-
src=it.find("source").get_text(" ",strip=True) if it.find("source") else ""
|
| 886 |
-
if title:bits.append((title+(" — "+src if src else ""))[:280])
|
| 887 |
-
except:pass
|
| 888 |
-
if bits:return "\n".join(bits)
|
| 889 |
-
try:
|
| 890 |
-
r=requests.get("https://html.duckduckgo.com/html/?q="+quote(topic),headers=HEADERS,timeout=12);r.encoding="utf-8"
|
| 891 |
-
soup=BeautifulSoup(r.text,"lxml")
|
| 892 |
-
for res in soup.select(".result")[:6]:
|
| 893 |
-
t=res.select_one(".result__title");sn=res.select_one(".result__snippet")
|
| 894 |
-
line=((t.get_text(" ",strip=True) if t else "")+" — "+(sn.get_text(" ",strip=True) if sn else "")).strip(" —")
|
| 895 |
-
if line:bits.append(line[:280])
|
| 896 |
-
except:pass
|
| 897 |
-
return "\n".join(bits)
|
| 898 |
-
|
| 899 |
-
def _jina_read(url):
|
| 900 |
-
try:
|
| 901 |
-
ju="https://r.jina.ai/http://"+url
|
| 902 |
-
r=requests.get(ju,headers=HEADERS,timeout=25);r.encoding="utf-8"
|
| 903 |
-
if r.status_code!=200 or not r.text:return None
|
| 904 |
-
lines=[x.rstrip() for x in r.text.splitlines()]
|
| 905 |
-
title="";img="";body=[];summary=""
|
| 906 |
-
for ln in lines[:40]:
|
| 907 |
-
if ln.startswith("Title:"):title=ln.replace("Title:","",1).strip()
|
| 908 |
-
elif ln.startswith("Image:"):img=ln.replace("Image:","",1).strip()
|
| 909 |
-
elif ln.startswith("Description:"):summary=ln.replace("Description:","",1).strip()
|
| 910 |
-
for ln in lines:
|
| 911 |
-
t=ln.strip()
|
| 912 |
-
if not t or t.startswith(("Title:","URL Source:","Published Time:","Markdown Content:","Image:","Description:")):continue
|
| 913 |
-
if len(t)>40:body.append({"type":"p","text":t})
|
| 914 |
-
if not body and summary:body=[{"type":"p","text":summary}]
|
| 915 |
-
return {"title":title or url,"summary":summary,"og_image":img,"body":body[:80],"source":"jina","url":url}
|
| 916 |
-
except:return None
|
| 917 |
-
|
| 918 |
-
def _scrape_generic_article(url):
|
| 919 |
-
try:
|
| 920 |
-
hdr={**HEADERS,"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}
|
| 921 |
-
r=requests.get(url,headers=hdr,timeout=15);r.encoding="utf-8"
|
| 922 |
-
ct=r.headers.get("content-type","").lower()
|
| 923 |
-
if r.status_code>=400 or "text/html" not in ct:
|
| 924 |
-
jr=_jina_read(url)
|
| 925 |
-
if jr:return jr
|
| 926 |
-
soup=BeautifulSoup(r.text,"lxml")
|
| 927 |
-
for tag in soup.find_all(["script","style","nav","footer","aside","form"]):tag.decompose()
|
| 928 |
-
h1=soup.find("h1")
|
| 929 |
-
ogt=soup.find("meta",property="og:title");title=h1.get_text(strip=True) if h1 else (ogt.get("content","") if ogt else "")
|
| 930 |
-
ogd=soup.find("meta",property="og:description");desc=ogd.get("content","") if ogd else ""
|
| 931 |
-
ogi=soup.find("meta",property="og:image");img=ogi.get("content","") if ogi else ""
|
| 932 |
-
main=soup.find("article") or soup.find("main") or soup.body
|
| 933 |
-
body=[]
|
| 934 |
-
if main:
|
| 935 |
-
for el in main.find_all(["p","h2","h3","figure","img"],recursive=True):
|
| 936 |
-
if el.name=="p":
|
| 937 |
-
t=el.get_text(" ",strip=True)
|
| 938 |
-
if t and len(t)>35:body.append({"type":"p","text":t})
|
| 939 |
-
elif el.name in ("h2","h3"):
|
| 940 |
-
t=el.get_text(" ",strip=True)
|
| 941 |
-
if t:body.append({"type":"heading","text":t})
|
| 942 |
-
elif el.name in ("figure","img"):
|
| 943 |
-
im=el if el.name=="img" else el.find("img")
|
| 944 |
-
if im:
|
| 945 |
-
src=im.get("data-src") or im.get("src","") or im.get("data-original","")
|
| 946 |
-
if src and "base64" not in src:body.append({"type":"img","src":src})
|
| 947 |
-
if not body:
|
| 948 |
-
jr=_jina_read(url)
|
| 949 |
-
if jr and jr.get("body"):return jr
|
| 950 |
-
if not body and desc:body=[{"type":"p","text":desc}]
|
| 951 |
-
return {"title":title or url,"summary":desc,"og_image":img,"body":body,"source":"generic","url":url}
|
| 952 |
-
except:
|
| 953 |
-
return _jina_read(url)
|
| 954 |
-
|
| 955 |
-
def _article_by_url(url):
|
| 956 |
-
if "vnexpress.net" in url:return scrape_vne_article(url)
|
| 957 |
-
if "bbc.com" in url:return scrape_bbc_article(url)
|
| 958 |
-
if "dantri.com.vn" in url:return scrape_dantri_article(url)
|
| 959 |
-
if "genk.vn" in url:return scrape_genk_article(url)
|
| 960 |
-
if "thethaovanhoa.vn" in url:return scrape_ttvh_article(url)
|
| 961 |
-
return _scrape_generic_article(url)
|
| 962 |
-
|
| 963 |
-
_QWEN_TEXT_MODELS=[m.strip() for m in os.environ.get(
|
| 964 |
-
"QWEN_TEXT_MODELS",
|
| 965 |
-
"Qwen/Qwen2.5-72B-Instruct,meta-llama/Llama-3.3-70B-Instruct,Qwen/Qwen2.5-7B-Instruct,meta-llama/Llama-3.1-8B-Instruct"
|
| 966 |
-
).split(",") if m.strip()]
|
| 967 |
-
_QWEN_WORKING=None # cache last-working model id
|
| 968 |
-
def _call_qwen(prompt, max_tokens=1800):
|
| 969 |
-
"""Summarize via HF router using FAST TEXT models (no vision needed for text summary).
|
| 970 |
-
Tries text models first (much faster than the VL model), VL only as last resort.
|
| 971 |
-
Returns None if no model is available (e.g. token lacks inference permission / credits)."""
|
| 972 |
-
global _QWEN_WORKING
|
| 973 |
-
token=os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN") or os.environ.get("VAISTUDIO")
|
| 974 |
-
if not token:return None
|
| 975 |
-
headers={"Authorization":"Bearer "+token,"Content-Type":"application/json"}
|
| 976 |
-
models=list(_QWEN_TEXT_MODELS)+["Qwen/Qwen2.5-VL-7B-Instruct"]
|
| 977 |
-
if _QWEN_WORKING and _QWEN_WORKING in models:
|
| 978 |
-
models=[_QWEN_WORKING]+[m for m in models if m!=_QWEN_WORKING]
|
| 979 |
-
last=None
|
| 980 |
-
for model in models:
|
| 981 |
-
try:
|
| 982 |
-
payload={"model":model,"messages":[{"role":"user","content":prompt}],"max_tokens":max_tokens,"temperature":0.7}
|
| 983 |
-
r=requests.post("https://router.huggingface.co/v1/chat/completions",headers=headers,json=payload,timeout=60)
|
| 984 |
-
if r.status_code>=300:
|
| 985 |
-
last=f"{model}:{r.status_code}";continue
|
| 986 |
-
j=r.json();out=j.get("choices",[{}])[0].get("message",{}).get("content")
|
| 987 |
-
if out and out.strip():
|
| 988 |
-
_QWEN_WORKING=model
|
| 989 |
-
return out
|
| 990 |
-
except Exception as e:
|
| 991 |
-
last=f"{model}:{type(e).__name__}";continue
|
| 992 |
-
if last:print("[_call_qwen] all models failed:",last)
|
| 993 |
-
return None
|
| 994 |
-
|
| 995 |
-
def _collect_article_text(data, limit=28000):
|
| 996 |
-
title=(data or {}).get("title","");summary=(data or {}).get("summary","")
|
| 997 |
-
parts=[]
|
| 998 |
-
if summary:parts.append(summary)
|
| 999 |
-
for b in (data or {}).get("body",[]):
|
| 1000 |
-
if b.get("type")=="heading":parts.append("## "+b.get("text","") )
|
| 1001 |
-
elif b.get("type")=="p":parts.append(b.get("text","") )
|
| 1002 |
-
text="\n".join([p.strip() for p in parts if p and p.strip()])
|
| 1003 |
-
return title,text[:limit]
|
| 1004 |
-
|
| 1005 |
-
def _ai_rewrite_article(data,tone="tu-nhien"):
|
| 1006 |
-
title,text=_collect_article_text(data)
|
| 1007 |
-
prompt=("Bạn là biên tập viên báo điện tử tiếng Việt. Hãy viết lại bài dưới đây bằng ngôn ngữ tự nhiên, mạch lạc, không cắt khúc, không bỏ ý quan trọng. "
|
| 1008 |
-
"Giữ đúng sự thật, không bịa, không thêm thông tin ngoài bài. Văn phong: "+tone+". "
|
| 1009 |
-
"Đầu ra gồm: tiêu đề hấp dẫn, đoạn sapo 2-3 câu, các đoạn nội dung ngắn dễ đọc, và 3 gạch đầu dòng điểm chính.\n\n"
|
| 1010 |
-
"TIÊU ĐỀ GỐC: "+title+"\n\nNỘI DUNG GỐC:\n"+text)
|
| 1011 |
-
out=_call_qwen(prompt,2200)
|
| 1012 |
-
if out and len(out)>300:return out.strip()
|
| 1013 |
-
# Fallback: complete non-truncated rewrite using full collected text chunks
|
| 1014 |
-
paras=[p.strip() for p in text.split("\n") if len(p.strip())>30]
|
| 1015 |
-
body="\n\n".join(paras[:18])
|
| 1016 |
-
bullets="\n".join(["• "+p[:220]+("..." if len(p)>220 else "") for p in paras[:5]])
|
| 1017 |
-
return ("Bản tin AI viết lại: "+title+"\n\n"+
|
| 1018 |
-
(paras[0] if paras else "")+"\n\n"+body+"\n\nĐiểm chính:\n"+bullets).strip()
|
| 1019 |
-
|
| 1020 |
-
def _image_for_topic(topic):
|
| 1021 |
-
return "https://image.pollinations.ai/prompt/"+quote("editorial illustration, Vietnamese news, "+topic,safe="")+"?width=1024&height=576&nologo=true"
|
| 1022 |
-
|
| 1023 |
-
def _topic_articles(topic,limit=5):
|
| 1024 |
-
items=[];seen=set()
|
| 1025 |
-
try:
|
| 1026 |
-
rss="https://news.google.com/rss/search?q="+quote(topic)+"&hl=vi&gl=VN&ceid=VN:vi"
|
| 1027 |
-
r=requests.get(rss,headers=HEADERS,timeout=12);r.encoding="utf-8"
|
| 1028 |
-
soup=BeautifulSoup(r.text,"xml")
|
| 1029 |
-
for it in soup.find_all("item")[:limit*3]:
|
| 1030 |
-
title=it.find("title").get_text(" ",strip=True) if it.find("title") else ""
|
| 1031 |
-
link=it.find("link").get_text(strip=True) if it.find("link") else ""
|
| 1032 |
-
src=it.find("source").get_text(" ",strip=True) if it.find("source") else ""
|
| 1033 |
-
if not title or not link or link in seen:continue
|
| 1034 |
-
seen.add(link);items.append({"title":title,"link":link,"source":src})
|
| 1035 |
-
if len(items)>=limit:break
|
| 1036 |
-
except:pass
|
| 1037 |
-
return items
|
| 1038 |
-
|
| 1039 |
-
def _topic_article_context(topic):
|
| 1040 |
-
"""Filter readable article sources by topic, then summarize actual article bodies."""
|
| 1041 |
-
raw_keys=[k.lower() for k in re.findall(r"[\wÀ-ỹ]+",topic) if len(k)>2]
|
| 1042 |
-
# Drop ultra-generic tokens; keep domain words such as giáo/dục, bóng/đá, world/cup.
|
| 1043 |
-
stop={"trong","năm","the","and","của","cho","với","một","các","những","hiện","nay"}
|
| 1044 |
-
keys=[k for k in raw_keys if k not in stop]
|
| 1045 |
-
candidates=[];seen=set()
|
| 1046 |
-
def add_items(items):
|
| 1047 |
-
for a in items or []:
|
| 1048 |
-
link=a.get("link","");title=a.get("title","")
|
| 1049 |
-
if not link or link in seen:continue
|
| 1050 |
-
seen.add(link);candidates.append(a)
|
| 1051 |
-
try:add_items(scrape_genk_ai())
|
| 1052 |
-
except:pass
|
| 1053 |
-
try:add_items(scrape_dantri_congnghe())
|
| 1054 |
-
except:pass
|
| 1055 |
-
try:add_items(scrape_ttvh_worldcup())
|
| 1056 |
-
except:pass
|
| 1057 |
-
# PRE-FILTER by TITLE first so we don't waste time scraping 40 irrelevant articles.
|
| 1058 |
-
# Only candidates whose title already matches a topic keyword get fully scraped.
|
| 1059 |
-
if keys:
|
| 1060 |
-
pref=[a for a in candidates if sum(1 for k in keys if k in (a.get("title","").lower()))>0]
|
| 1061 |
-
candidates=pref or candidates
|
| 1062 |
-
candidates=candidates[:12] # scrape at most 12 (was looping over 40 serially)
|
| 1063 |
-
# Scrape the shortlisted articles CONCURRENTLY (this is the main speed-up for
|
| 1064 |
-
# 'rewrite tong hop nguon tin tu hashtag'). Serial scraping of many articles via
|
| 1065 |
-
# Jina/HTTP was the real cause of the long wait, NOT the LLM call.
|
| 1066 |
-
from concurrent.futures import ThreadPoolExecutor as _TPE
|
| 1067 |
-
def _fetch(a):
|
| 1068 |
-
try:return a,_article_by_url(a.get("link",""))
|
| 1069 |
-
except Exception:return a,None
|
| 1070 |
-
fetched=[]
|
| 1071 |
-
with _TPE(max_workers=8) as ex:
|
| 1072 |
-
for a,data in ex.map(_fetch,candidates):
|
| 1073 |
-
fetched.append((a,data))
|
| 1074 |
-
scored=[];img=""
|
| 1075 |
-
for a,data in fetched:
|
| 1076 |
-
if not data or not data.get("body"):continue
|
| 1077 |
-
title=data.get("title") or a.get("title","")
|
| 1078 |
-
ps=[b.get("text","") for b in data.get("body",[]) if b.get("type")=="p" and len(b.get("text",""))>40]
|
| 1079 |
-
excerpt=" ".join(ps)[:1800] or data.get("summary","")
|
| 1080 |
-
hay=(title+" "+excerpt).lower()
|
| 1081 |
-
score=sum(1 for k in keys if k in hay)
|
| 1082 |
-
# Require topic relevance when we have meaningful keys.
|
| 1083 |
-
if keys and score==0:continue
|
| 1084 |
-
if len(keys)>=2 and score<2 and not any(" ".join(keys[i:i+2]) in hay for i in range(len(keys)-1)):continue
|
| 1085 |
-
scored.append((score,title,a.get("link",""),excerpt,data.get("og_image") or a.get("img","") or ""))
|
| 1086 |
-
scored=sorted(scored,key=lambda x:x[0],reverse=True)[:5]
|
| 1087 |
-
chunks=[];items=[]
|
| 1088 |
-
for score,title,link,excerpt,im in scored:
|
| 1089 |
-
if not img and im:img=im
|
| 1090 |
-
chunks.append("BÀI: "+title+"\nURL: "+link+"\nNỘI DUNG LỌC: "+excerpt)
|
| 1091 |
-
# Structured item per news: title + its own image + a SHORT clean description.
|
| 1092 |
-
# Take the first 1-2 real sentences of the article body (no URLs, no prompt text).
|
| 1093 |
-
desc=_short_desc(excerpt,260)
|
| 1094 |
-
ctitle=html_lib.unescape((title or "").replace("\n"," ")).strip()
|
| 1095 |
-
items.append({"title":ctitle,"img":im or "","desc":desc,"link":link})
|
| 1096 |
-
if chunks:return "\n\n".join(chunks),img,items
|
| 1097 |
-
return _web_context(topic),"",[]
|
| 1098 |
-
|
| 1099 |
-
def _short_desc(text,limit=260):
|
| 1100 |
-
"""First 1-2 clean sentences from an article excerpt (strip URLs / markdown / boilerplate)."""
|
| 1101 |
-
t=re.sub(r"https?://\S+","",text or "")
|
| 1102 |
-
t=re.sub(r"\[([^\]]*)\]\([^)]*\)",r"\1",t)
|
| 1103 |
-
t=re.sub(r"[#>*`_]+"," ",t)
|
| 1104 |
-
t=re.sub(r"\s+"," ",t).strip()
|
| 1105 |
-
if not t:return ""
|
| 1106 |
-
# cut at sentence boundary near the limit
|
| 1107 |
-
if len(t)<=limit:return t
|
| 1108 |
-
cut=t[:limit]
|
| 1109 |
-
p=max(cut.rfind(". "),cut.rfind("! "),cut.rfind("? "))
|
| 1110 |
-
return (cut[:p+1] if p>80 else cut).strip()
|
| 1111 |
-
|
| 1112 |
-
def _strip_prompt_leak(out,topic):
|
| 1113 |
-
"""Remove any leaked instruction/prompt phrases from the model output."""
|
| 1114 |
-
if not out:return out
|
| 1115 |
-
bad=["bạn là cây bút","bạn là biên tập","nhiệm vụ","vai trò","đầu ra gồm","theo yêu cầu",
|
| 1116 |
-
"dưới đây là","tôi sẽ","đây là bài","nguồn thực tế","không viết chung chung","chỉ dùng dữ kiện"]
|
| 1117 |
-
lines=[]
|
| 1118 |
-
for ln in out.splitlines():
|
| 1119 |
-
low=ln.strip().lower()
|
| 1120 |
-
if any(b in low for b in bad):continue
|
| 1121 |
-
lines.append(ln)
|
| 1122 |
-
return "\n".join(lines).strip()
|
| 1123 |
-
|
| 1124 |
-
def _topic_post_text(topic,ctx=None,items=None):
|
| 1125 |
-
if ctx is None:
|
| 1126 |
-
ctx,_,items=_topic_article_context(topic)
|
| 1127 |
-
prompt=("Bạn là cây bút báo điện tử tiếng Việt. Hãy lọc các thông tin thực tế trong những nguồn dưới đây để viết một bài tóm tắt theo chủ đề: "+topic+
|
| 1128 |
-
". Không viết chung chung. Chỉ dùng dữ kiện có trong nguồn; nếu nguồn khác nhau thì tổng hợp khách quan. "
|
| 1129 |
-
"Viết liền mạch thành đoạn văn, KHÔNG chèn URL, KHÔNG nhắc lại yêu cầu này.\n\nNGUỒN THỰC TẾ:\n"+ctx)
|
| 1130 |
-
out=_call_qwen(prompt,1800)
|
| 1131 |
-
out=_strip_prompt_leak(out,topic)
|
| 1132 |
-
if out and len(out)>300:return out.strip()
|
| 1133 |
-
# Fallback WITHOUT prompt/URL leakage: build a readable digest from the per-news items.
|
| 1134 |
-
if items:
|
| 1135 |
-
parts=["Tổng hợp tin nổi bật về \""+topic+"\":"]
|
| 1136 |
-
for it in items:
|
| 1137 |
-
t=it.get("title","").strip();d=it.get("desc","").strip()
|
| 1138 |
-
if not t:continue
|
| 1139 |
-
parts.append("• "+t+((" — "+d) if d else ""))
|
| 1140 |
-
return "\n\n".join(parts)
|
| 1141 |
-
if ctx:
|
| 1142 |
-
return "Tổng hợp tin nổi bật về \""+topic+"\". Các nguồn cho thấy chủ đề đang có nhiều diễn biến đáng chú ý."
|
| 1143 |
-
return "Chưa thu thập được dữ liệu đủ rõ cho chủ đề: "+topic
|
| 1144 |
-
|
| 1145 |
-
@app.get("/api/wall")
|
| 1146 |
-
def api_wall():return JSONResponse({"posts":_load_wall()[:50]})
|
| 1147 |
-
|
| 1148 |
-
@app.post("/api/rewrite_share")
|
| 1149 |
-
async def api_rewrite_share(request:Request):
|
| 1150 |
-
try:body=await request.json()
|
| 1151 |
-
except:body={}
|
| 1152 |
-
url=str(body.get("url","")).strip();tone=str(body.get("tone","tu-nhien")).strip()
|
| 1153 |
-
if not url:return JSONResponse({"error":"missing url"},status_code=400)
|
| 1154 |
-
data=_article_by_url(url)
|
| 1155 |
-
if not data or not data.get("title") or (not data.get("body") and not data.get("summary")):
|
| 1156 |
-
return JSONResponse({"error":"Không đọc được bài viết"},status_code=422)
|
| 1157 |
-
post={"id":hashlib.md5((url+str(time.time())).encode()).hexdigest()[:12],"url":url,"title":data.get("title",""),"img":data.get("og_image","") or "","text":_ai_rewrite_article(data,tone),"ts":int(time.time()),"source":data.get("source","")}
|
| 1158 |
-
posts=_load_wall();posts.insert(0,post);_save_wall(posts)
|
| 1159 |
-
return JSONResponse({"post":post})
|
| 1160 |
-
|
| 1161 |
-
@app.post("/api/topic_post")
|
| 1162 |
-
async def api_topic_post(request:Request):
|
| 1163 |
-
try:body=await request.json()
|
| 1164 |
-
except:body={}
|
| 1165 |
-
topic=str(body.get("topic","")).strip()
|
| 1166 |
-
if not topic:return JSONResponse({"error":"missing topic"},status_code=400)
|
| 1167 |
-
# Compute the aggregated context ONCE (was computed twice = double scraping work).
|
| 1168 |
-
ctx,ctx_img,items=_topic_article_context(topic)
|
| 1169 |
-
post={"id":hashlib.md5((topic+str(time.time())).encode()).hexdigest()[:12],"url":"","title":topic,
|
| 1170 |
-
"img":ctx_img or (items[0]["img"] if items and items[0].get("img") else "") or _image_for_topic(topic),
|
| 1171 |
-
"text":_topic_post_text(topic,ctx,items),
|
| 1172 |
-
"items":items, # per-news: each {title, img, desc} (no URLs shown)
|
| 1173 |
-
"ts":int(time.time()),"source":"ai-topic"}
|
| 1174 |
-
posts=_load_wall();posts.insert(0,post);_save_wall(posts)
|
| 1175 |
-
return JSONResponse({"post":post})
|
| 1176 |
-
|
| 1177 |
-
@app.post("/api/url_wall")
|
| 1178 |
-
async def api_url_wall(request:Request):
|
| 1179 |
-
try:body=await request.json()
|
| 1180 |
-
except:body={}
|
| 1181 |
-
url=str(body.get("url","")).strip()
|
| 1182 |
-
if not url:return JSONResponse({"error":"missing url"},status_code=400)
|
| 1183 |
-
data=_article_by_url(url)
|
| 1184 |
-
if not data or not data.get("title"):
|
| 1185 |
-
return JSONResponse({"error":"Không đọc được URL"},status_code=422)
|
| 1186 |
-
post={"id":hashlib.md5((url+str(time.time())).encode()).hexdigest()[:12],"url":url,"title":data.get("title",""),"img":data.get("og_image","") or "","text":_ai_rewrite_article(data,"ngan-gon-tu-nhien"),"ts":int(time.time()),"source":data.get("source","")}
|
| 1187 |
-
posts=_load_wall();posts.insert(0,post);_save_wall(posts)
|
| 1188 |
-
return JSONResponse({"post":post})
|
| 1189 |
-
|
| 1190 |
-
def _share_html(title,img,desc,store_key,store_val):
|
| 1191 |
-
"""A share landing page with REAL Open Graph tags (title/image/description) for
|
| 1192 |
-
social previews, that then opens the correct content inside the SPA."""
|
| 1193 |
-
import html as _h,json as _json
|
| 1194 |
-
t=_h.escape((title or "VNEWS").strip());d=_h.escape((desc or "Tin tức tổng hợp, bóng đá, video, AI.").strip()[:200])
|
| 1195 |
-
im=(img or "").strip() or "https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg"
|
| 1196 |
-
im_e=_h.escape(im,quote=True)
|
| 1197 |
-
val=_json.dumps(store_val) # safe JS string/obj literal
|
| 1198 |
-
script=(f'<script>try{{localStorage.setItem("{store_key}",{val});}}catch(e){{}}'
|
| 1199 |
-
f'location.replace("{SPACE_URL}/");</script>') if store_val else f'<script>location.replace("{SPACE_URL}/");</script>'
|
| 1200 |
-
return HTMLResponse(
|
| 1201 |
-
'<!DOCTYPE html><html lang="vi"><head><meta charset="utf-8">'
|
| 1202 |
-
'<meta name="viewport" content="width=device-width,initial-scale=1">'
|
| 1203 |
-
f'<title>{t}</title>'
|
| 1204 |
-
f'<meta name="description" content="{d}">'
|
| 1205 |
-
'<meta property="og:type" content="article">'
|
| 1206 |
-
f'<meta property="og:title" content="{t}">'
|
| 1207 |
-
f'<meta property="og:description" content="{d}">'
|
| 1208 |
-
f'<meta property="og:image" content="{im_e}">'
|
| 1209 |
-
'<meta name="twitter:card" content="summary_large_image">'
|
| 1210 |
-
f'<meta name="twitter:title" content="{t}">'
|
| 1211 |
-
f'<meta name="twitter:description" content="{d}">'
|
| 1212 |
-
f'<meta name="twitter:image" content="{im_e}">'
|
| 1213 |
-
f'</head><body style="background:#111;color:#fff;text-align:center;padding:40px;font-family:sans-serif">'
|
| 1214 |
-
f'<img src="{im_e}" style="max-width:320px;border-radius:10px"><h3>{t}</h3><p>{d}</p>'
|
| 1215 |
-
f'<p style="color:#888">⏳ Đang mở…</p>{script}</body></html>')
|
| 1216 |
-
|
| 1217 |
-
@app.get("/v")
|
| 1218 |
-
async def video_share(url:str=Query(default=""),title:str=Query(default="VNEWS Video"),img:str=Query(default=""),desc:str=Query(default=""),type:str=Query(default="highlights")):
|
| 1219 |
-
decoded_url=unquote(url)
|
| 1220 |
-
val={"url":decoded_url,"type":type} if decoded_url else None
|
| 1221 |
-
return _share_html(unquote(title),unquote(img),unquote(desc),"pending_video",val)
|
| 1222 |
-
|
| 1223 |
-
@app.get("/s")
|
| 1224 |
-
async def share_redirect(url:str=Query(default=""),title:str=Query(default="VNEWS"),img:str=Query(default=""),desc:str=Query(default=""),post:str=Query(default="")):
|
| 1225 |
-
# Sharing a saved wall/AI post by id, OR an external article url.
|
| 1226 |
-
if post:
|
| 1227 |
-
return _share_html(unquote(title),unquote(img),unquote(desc),"pending_post",unquote(post))
|
| 1228 |
-
decoded_url=unquote(url)
|
| 1229 |
-
return _share_html(unquote(title),unquote(img),unquote(desc),"pending_article",decoded_url if decoded_url else None)
|
| 1230 |
-
@app.get("/")
|
| 1231 |
-
async def index():
|
| 1232 |
-
with open("/app/static/index.html","r",encoding="utf-8") as f:return HTMLResponse(content=f.read())
|
| 1233 |
-
app.mount("/static",StaticFiles(directory="/app/static"),name="static")
|
|
|
|
| 1 |
+
see file /app/main.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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