Spaces:
Running
Running
fix: /api/article supports BDP + 24h (scrape any article for in-app reading)
Browse files
main.py
CHANGED
|
@@ -13,112 +13,74 @@ HEADERS = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/5
|
|
| 13 |
BASE_BDP = "https://bongdaplus.vn"
|
| 14 |
BASE_24H = "https://www.24h.com.vn"
|
| 15 |
SPACE_URL = "https://bep40-vnews.hf.space"
|
| 16 |
-
|
| 17 |
_DATA_DIR = "/data" if os.path.isdir("/data") else "."
|
| 18 |
DB_PATH = os.path.join(_DATA_DIR, "db.json")
|
| 19 |
SHARE_PATH = os.path.join(_DATA_DIR, "shares.json")
|
| 20 |
_db_lock = threading.Lock()
|
| 21 |
_share_lock = threading.Lock()
|
| 22 |
-
|
| 23 |
def _load_json(path, default):
|
| 24 |
try:
|
| 25 |
with open(path,"r") as f: return json.load(f)
|
| 26 |
except: return default
|
| 27 |
-
|
| 28 |
def _save_json(path, data):
|
| 29 |
try:
|
| 30 |
with open(path,"w") as f: json.dump(data, f, ensure_ascii=False)
|
| 31 |
except: pass
|
| 32 |
-
|
| 33 |
def db_inc(category, aid):
|
| 34 |
with _db_lock:
|
| 35 |
db = _load_json(DB_PATH, {"views":{},"shares":{},"comments":{}})
|
| 36 |
db[category][aid] = db[category].get(aid, 0) + 1
|
| 37 |
-
_save_json(DB_PATH, db)
|
| 38 |
-
return db[category][aid]
|
| 39 |
-
|
| 40 |
def db_add_comment(aid, name, text):
|
| 41 |
with _db_lock:
|
| 42 |
db = _load_json(DB_PATH, {"views":{},"shares":{},"comments":{}})
|
| 43 |
if aid not in db["comments"]: db["comments"][aid] = []
|
| 44 |
db["comments"][aid].append({"n":name,"t":text,"d":time.strftime("%d/%m %H:%M")})
|
| 45 |
-
_save_json(DB_PATH, db)
|
| 46 |
-
return db["comments"][aid]
|
| 47 |
-
|
| 48 |
def db_get(aid):
|
| 49 |
db = _load_json(DB_PATH, {"views":{},"shares":{},"comments":{}})
|
| 50 |
return {"views":db["views"].get(aid,0),"shares":db["shares"].get(aid,0),"comments":db["comments"].get(aid,[])}
|
| 51 |
-
|
| 52 |
def _slug(title):
|
| 53 |
s = unicodedata.normalize('NFKD', title.lower())
|
| 54 |
s = ''.join(c for c in s if not unicodedata.combining(c))
|
| 55 |
-
s = re.sub(r'[^a-z0-9\s-]','',s)
|
| 56 |
-
s = re.sub(r'[\s]+','-',s.strip())
|
| 57 |
return re.sub(r'-+','-',s).strip('-')[:60]
|
| 58 |
-
|
| 59 |
-
def _hash(url):
|
| 60 |
-
return hashlib.md5(url.encode()).hexdigest()[:12]
|
| 61 |
-
|
| 62 |
def register_share(url, title, img=""):
|
| 63 |
-
h = _hash(url)
|
| 64 |
-
sl = _slug(title)
|
| 65 |
with _share_lock:
|
| 66 |
-
db = _load_json(SHARE_PATH, {})
|
| 67 |
-
db[h] = {"url":url,"title":title,"img":img,"slug":sl}
|
| 68 |
-
_save_json(SHARE_PATH, db)
|
| 69 |
return sl, h
|
| 70 |
-
|
| 71 |
def get_share(h):
|
| 72 |
-
db = _load_json(SHARE_PATH, {})
|
| 73 |
-
return db.get(h)
|
| 74 |
|
| 75 |
@app.post("/api/view")
|
| 76 |
-
def api_view(aid:str=Body(...,embed=True)):
|
| 77 |
-
return JSONResponse({"views": db_inc("views", aid)})
|
| 78 |
-
|
| 79 |
@app.post("/api/share_inc")
|
| 80 |
-
def api_share_inc(aid:str=Body(...,embed=True)):
|
| 81 |
-
return JSONResponse({"shares": db_inc("shares", aid)})
|
| 82 |
-
|
| 83 |
@app.post("/api/comment")
|
| 84 |
-
def api_comment(aid:str=Body(...), name:str=Body(...), text:str=Body(...)):
|
| 85 |
-
return JSONResponse({"comments": db_add_comment(aid, name, text)})
|
| 86 |
-
|
| 87 |
@app.get("/api/stats/{aid}")
|
| 88 |
-
def api_stats(aid:str):
|
| 89 |
-
return JSONResponse(db_get(aid))
|
| 90 |
-
|
| 91 |
@app.post("/api/register_share")
|
| 92 |
def api_register_share(url:str=Body(...), title:str=Body(...), img:str=Body("")):
|
| 93 |
-
sl, h = register_share(url, title, img)
|
| 94 |
-
db_inc("shares", _hash(url))
|
| 95 |
return JSONResponse({"slug":sl,"hash":h,"share_url":f"{SPACE_URL}/#/{sl}/{h}","social_url":f"{SPACE_URL}/s/{sl}/{h}"})
|
| 96 |
|
| 97 |
-
# SEO share page: crawlers see og:image, users get redirected to VNEWS article reader
|
| 98 |
@app.get("/s/{slug}/{hash_id}")
|
| 99 |
async def share_page(slug:str, hash_id:str):
|
| 100 |
info = get_share(hash_id)
|
| 101 |
-
if not info:
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
return HTMLResponse(f'''<!DOCTYPE html><html><head><meta charset="utf-8">
|
| 110 |
-
<title>{title}</title>
|
| 111 |
-
<meta property="og:title" content="{title}">
|
| 112 |
-
<meta property="og:image" content="{img}">
|
| 113 |
-
<meta property="og:url" content="{hash_url}">
|
| 114 |
-
<meta property="og:type" content="article">
|
| 115 |
-
<meta property="og:site_name" content="VNEWS">
|
| 116 |
-
<meta name="twitter:card" content="summary_large_image">
|
| 117 |
-
<meta name="twitter:title" content="{title}">
|
| 118 |
-
<meta name="twitter:image" content="{img}">
|
| 119 |
</head><body><script>localStorage.setItem('pending_article','{escaped_url}');window.location.replace('{SPACE_URL}');</script></body></html>''')
|
| 120 |
|
| 121 |
-
# Scrapers
|
| 122 |
_cache={}; _cache_ttl=300
|
| 123 |
def _cached(key,fn):
|
| 124 |
now=time.time()
|
|
@@ -126,7 +88,6 @@ def _cached(key,fn):
|
|
| 126 |
try:data=fn()
|
| 127 |
except:data=_cache.get(key,{}).get("d",[])
|
| 128 |
_cache[key]={"d":data,"t":now};return data
|
| 129 |
-
|
| 130 |
def _get(url,headers=None):
|
| 131 |
h=headers or HEADERS;r=requests.get(url,headers=h,timeout=15);r.encoding="utf-8"
|
| 132 |
return BeautifulSoup(r.text,"lxml")
|
|
@@ -164,6 +125,53 @@ def scrape_vne_article(url):
|
|
| 164 |
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}
|
| 165 |
except:return None
|
| 166 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
def scrape_bdp(url):
|
| 168 |
try:
|
| 169 |
soup=_get(url);arts=[];seen=set()
|
|
@@ -179,7 +187,6 @@ def scrape_bdp(url):
|
|
| 179 |
seen.add(lk);arts.append({"title":t,"link":lk,"img":img,"source":"bdp","summary":""})
|
| 180 |
return arts[:15]
|
| 181 |
except:return[]
|
| 182 |
-
|
| 183 |
def scrape_bdp_videos():
|
| 184 |
try:
|
| 185 |
soup=_get(f"{BASE_BDP}/video");arts=[];seen=set()
|
|
@@ -195,7 +202,6 @@ def scrape_bdp_videos():
|
|
| 195 |
seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bdp"})
|
| 196 |
return arts[:20]
|
| 197 |
except:return[]
|
| 198 |
-
|
| 199 |
def scrape_24h_highlights():
|
| 200 |
try:
|
| 201 |
soup=_get(f"{BASE_24H}/video-highlight-c953.html");arts=[];seen=set()
|
|
@@ -218,7 +224,6 @@ def scrape_24h_highlights():
|
|
| 218 |
with ThreadPoolExecutor(5) as ex:list(ex.map(_og,need))
|
| 219 |
return arts[:30]
|
| 220 |
except:return[]
|
| 221 |
-
|
| 222 |
def scrape_24h_shorts():
|
| 223 |
try:
|
| 224 |
r=requests.get(f"{BASE_24H}/video/video-tin-tuc-cvd769.html",headers=HEADERS,timeout=15);r.encoding="utf-8"
|
|
@@ -250,7 +255,6 @@ def scrape_24h_shorts():
|
|
| 250 |
seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"24h-shorts"})
|
| 251 |
return arts[:20]
|
| 252 |
except:return[]
|
| 253 |
-
|
| 254 |
def scrape_bbc_vietnamese():
|
| 255 |
try:
|
| 256 |
bbc_h={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB,en;q=0.9"}
|
|
@@ -273,19 +277,6 @@ def scrape_bbc_vietnamese():
|
|
| 273 |
if len(arts)>=15:break
|
| 274 |
return arts
|
| 275 |
except:return[]
|
| 276 |
-
|
| 277 |
-
def scrape_bbc_article(url):
|
| 278 |
-
try:
|
| 279 |
-
r=requests.get(url,headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
|
| 280 |
-
soup=BeautifulSoup(r.text,"lxml");h1=soup.find("h1")
|
| 281 |
-
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 282 |
-
body=[]
|
| 283 |
-
for p in soup.select("[data-component='text-block'] p, article p, main p"):
|
| 284 |
-
t=p.get_text(strip=True)
|
| 285 |
-
if t and len(t)>20:body.append({"type":"p","text":t})
|
| 286 |
-
return{"title":h1.get_text(strip=True) if h1 else "","summary":"","og_image":og_img,"body":body,"source":"bbc","url":url}
|
| 287 |
-
except:return None
|
| 288 |
-
|
| 289 |
def extract_video_url(article_url):
|
| 290 |
try:
|
| 291 |
r=requests.get(article_url,headers={**HEADERS,"Referer":"https://www.24h.com.vn/"},timeout=10);r.encoding="utf-8"
|
|
@@ -321,7 +312,6 @@ def extract_video_url(article_url):
|
|
| 321 |
if len(parts)>1:return{"src":parts[0],"poster":poster,"all_parts":parts}
|
| 322 |
return{"src":primary[0],"poster":poster}
|
| 323 |
except:return None
|
| 324 |
-
|
| 325 |
def extract_bdp_video(url):
|
| 326 |
try:
|
| 327 |
m=re.search(r'-(\d{6,})\.html',url)
|
|
@@ -333,6 +323,7 @@ def extract_bdp_video(url):
|
|
| 333 |
return{"src":source.get("src","") if source else "","poster":video.get("poster","")}
|
| 334 |
except:return None
|
| 335 |
|
|
|
|
| 336 |
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"),"cong-nghe":("https://vnexpress.net/so-hoa","Công Nghệ"),"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")}
|
| 337 |
BDP_CATS={"ngoai-hang-anh":("https://bongdaplus.vn/ngoai-hang-anh","Ngoại Hạng Anh"),"la-liga":("https://bongdaplus.vn/la-liga","La Liga"),"champions-league":("https://bongdaplus.vn/champions-league-cup-c1","Champions League"),"bong-da-vn":("https://bongdaplus.vn/bong-da-viet-nam","Bóng Đá VN")}
|
| 338 |
|
|
@@ -352,7 +343,6 @@ def api_homepage():
|
|
| 352 |
except:pass
|
| 353 |
return articles
|
| 354 |
return JSONResponse(_cached("homepage",_f))
|
| 355 |
-
|
| 356 |
@app.get("/api/category/{cat_id}")
|
| 357 |
def api_category(cat_id:str):
|
| 358 |
def _f():
|
|
@@ -361,14 +351,12 @@ def api_category(cat_id:str):
|
|
| 361 |
if cat_id in BDP_CATS:arts=scrape_bdp(BDP_CATS[cat_id][0]);[a.update({"group":BDP_CATS[cat_id][1]}) for a in arts];return arts
|
| 362 |
return[]
|
| 363 |
return JSONResponse(_cached(f"cat_{cat_id}",_f))
|
| 364 |
-
|
| 365 |
@app.get("/api/categories")
|
| 366 |
def api_categories():
|
| 367 |
cats=[{"id":"bbc","name":"BBC Tiếng Việt","source":"bbc"}]
|
| 368 |
for k,(u,n) in VNE_CATS.items():cats.append({"id":k,"name":n,"source":"vne"})
|
| 369 |
for k,(u,n) in BDP_CATS.items():cats.append({"id":k,"name":n,"source":"bdp"})
|
| 370 |
return JSONResponse(cats)
|
| 371 |
-
|
| 372 |
@app.get("/api/highlights")
|
| 373 |
def api_highlights():return JSONResponse(_cached("highlights",scrape_24h_highlights))
|
| 374 |
@app.get("/api/shorts")
|
|
@@ -381,15 +369,17 @@ def api_video_url(url:str=Query(...)):
|
|
| 381 |
elif"bongdaplus.vn" in url:v=extract_bdp_video(url)
|
| 382 |
else:v=None
|
| 383 |
return JSONResponse(v if v else{"error":"not found"})
|
|
|
|
|
|
|
| 384 |
@app.get("/api/article")
|
| 385 |
def api_article(url:str=Query(...)):
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
|
|
|
|
|
|
| 390 |
|
| 391 |
@app.get("/")
|
| 392 |
-
async def index():
|
| 393 |
-
return FileResponse("/app/static/index.html")
|
| 394 |
-
|
| 395 |
app.mount("/static",StaticFiles(directory="/app/static"),name="static")
|
|
|
|
| 13 |
BASE_BDP = "https://bongdaplus.vn"
|
| 14 |
BASE_24H = "https://www.24h.com.vn"
|
| 15 |
SPACE_URL = "https://bep40-vnews.hf.space"
|
|
|
|
| 16 |
_DATA_DIR = "/data" if os.path.isdir("/data") else "."
|
| 17 |
DB_PATH = os.path.join(_DATA_DIR, "db.json")
|
| 18 |
SHARE_PATH = os.path.join(_DATA_DIR, "shares.json")
|
| 19 |
_db_lock = threading.Lock()
|
| 20 |
_share_lock = threading.Lock()
|
|
|
|
| 21 |
def _load_json(path, default):
|
| 22 |
try:
|
| 23 |
with open(path,"r") as f: return json.load(f)
|
| 24 |
except: return default
|
|
|
|
| 25 |
def _save_json(path, data):
|
| 26 |
try:
|
| 27 |
with open(path,"w") as f: json.dump(data, f, ensure_ascii=False)
|
| 28 |
except: pass
|
|
|
|
| 29 |
def db_inc(category, aid):
|
| 30 |
with _db_lock:
|
| 31 |
db = _load_json(DB_PATH, {"views":{},"shares":{},"comments":{}})
|
| 32 |
db[category][aid] = db[category].get(aid, 0) + 1
|
| 33 |
+
_save_json(DB_PATH, db); return db[category][aid]
|
|
|
|
|
|
|
| 34 |
def db_add_comment(aid, name, text):
|
| 35 |
with _db_lock:
|
| 36 |
db = _load_json(DB_PATH, {"views":{},"shares":{},"comments":{}})
|
| 37 |
if aid not in db["comments"]: db["comments"][aid] = []
|
| 38 |
db["comments"][aid].append({"n":name,"t":text,"d":time.strftime("%d/%m %H:%M")})
|
| 39 |
+
_save_json(DB_PATH, db); return db["comments"][aid]
|
|
|
|
|
|
|
| 40 |
def db_get(aid):
|
| 41 |
db = _load_json(DB_PATH, {"views":{},"shares":{},"comments":{}})
|
| 42 |
return {"views":db["views"].get(aid,0),"shares":db["shares"].get(aid,0),"comments":db["comments"].get(aid,[])}
|
|
|
|
| 43 |
def _slug(title):
|
| 44 |
s = unicodedata.normalize('NFKD', title.lower())
|
| 45 |
s = ''.join(c for c in s if not unicodedata.combining(c))
|
| 46 |
+
s = re.sub(r'[^a-z0-9\s-]','',s); s = re.sub(r'[\s]+','-',s.strip())
|
|
|
|
| 47 |
return re.sub(r'-+','-',s).strip('-')[:60]
|
| 48 |
+
def _hash(url): return hashlib.md5(url.encode()).hexdigest()[:12]
|
|
|
|
|
|
|
|
|
|
| 49 |
def register_share(url, title, img=""):
|
| 50 |
+
h = _hash(url); sl = _slug(title)
|
|
|
|
| 51 |
with _share_lock:
|
| 52 |
+
db = _load_json(SHARE_PATH, {}); db[h] = {"url":url,"title":title,"img":img,"slug":sl}; _save_json(SHARE_PATH, db)
|
|
|
|
|
|
|
| 53 |
return sl, h
|
|
|
|
| 54 |
def get_share(h):
|
| 55 |
+
db = _load_json(SHARE_PATH, {}); return db.get(h)
|
|
|
|
| 56 |
|
| 57 |
@app.post("/api/view")
|
| 58 |
+
def api_view(aid:str=Body(...,embed=True)): return JSONResponse({"views": db_inc("views", aid)})
|
|
|
|
|
|
|
| 59 |
@app.post("/api/share_inc")
|
| 60 |
+
def api_share_inc(aid:str=Body(...,embed=True)): return JSONResponse({"shares": db_inc("shares", aid)})
|
|
|
|
|
|
|
| 61 |
@app.post("/api/comment")
|
| 62 |
+
def api_comment(aid:str=Body(...), name:str=Body(...), text:str=Body(...)): return JSONResponse({"comments": db_add_comment(aid, name, text)})
|
|
|
|
|
|
|
| 63 |
@app.get("/api/stats/{aid}")
|
| 64 |
+
def api_stats(aid:str): return JSONResponse(db_get(aid))
|
|
|
|
|
|
|
| 65 |
@app.post("/api/register_share")
|
| 66 |
def api_register_share(url:str=Body(...), title:str=Body(...), img:str=Body("")):
|
| 67 |
+
sl, h = register_share(url, title, img); db_inc("shares", _hash(url))
|
|
|
|
| 68 |
return JSONResponse({"slug":sl,"hash":h,"share_url":f"{SPACE_URL}/#/{sl}/{h}","social_url":f"{SPACE_URL}/s/{sl}/{h}"})
|
| 69 |
|
|
|
|
| 70 |
@app.get("/s/{slug}/{hash_id}")
|
| 71 |
async def share_page(slug:str, hash_id:str):
|
| 72 |
info = get_share(hash_id)
|
| 73 |
+
if not info: return HTMLResponse(f'<meta http-equiv="refresh" content="0;url={SPACE_URL}">')
|
| 74 |
+
title=info["title"]; url=info["url"]; img=info.get("img") or "https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg"
|
| 75 |
+
escaped_url = url.replace("\\","\\\\").replace("'","\\'")
|
| 76 |
+
return HTMLResponse(f'''<!DOCTYPE html><html><head><meta charset="utf-8"><title>{title}</title>
|
| 77 |
+
<meta property="og:title" content="{title}"><meta property="og:image" content="{img}">
|
| 78 |
+
<meta property="og:url" content="{SPACE_URL}/#/{slug}/{hash_id}"><meta property="og:type" content="article">
|
| 79 |
+
<meta property="og:site_name" content="VNEWS"><meta name="twitter:card" content="summary_large_image">
|
| 80 |
+
<meta name="twitter:title" content="{title}"><meta name="twitter:image" content="{img}">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
</head><body><script>localStorage.setItem('pending_article','{escaped_url}');window.location.replace('{SPACE_URL}');</script></body></html>''')
|
| 82 |
|
| 83 |
+
# ═══ Scrapers ═══
|
| 84 |
_cache={}; _cache_ttl=300
|
| 85 |
def _cached(key,fn):
|
| 86 |
now=time.time()
|
|
|
|
| 88 |
try:data=fn()
|
| 89 |
except:data=_cache.get(key,{}).get("d",[])
|
| 90 |
_cache[key]={"d":data,"t":now};return data
|
|
|
|
| 91 |
def _get(url,headers=None):
|
| 92 |
h=headers or HEADERS;r=requests.get(url,headers=h,timeout=15);r.encoding="utf-8"
|
| 93 |
return BeautifulSoup(r.text,"lxml")
|
|
|
|
| 125 |
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}
|
| 126 |
except:return None
|
| 127 |
|
| 128 |
+
def scrape_bdp_article(url):
|
| 129 |
+
try:
|
| 130 |
+
soup=_get(url);h1=soup.select_one(".lead-title h1") or soup.select_one("h1")
|
| 131 |
+
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 132 |
+
se=soup.select_one("div.summary");body=[]
|
| 133 |
+
cd=soup.select_one("div.content#postContent") or soup.select_one("div.content")
|
| 134 |
+
if cd:
|
| 135 |
+
for ch in cd.children:
|
| 136 |
+
if not hasattr(ch,'name') or not ch.name:continue
|
| 137 |
+
if ch.name=="p":
|
| 138 |
+
im=ch.find("img")
|
| 139 |
+
if im:s=im.get("src") or im.get("data-src","");(body.append({"type":"img","src":s,"alt":""}) if s else None)
|
| 140 |
+
t=ch.get_text(strip=True);(body.append({"type":"p","text":t}) if t else None)
|
| 141 |
+
elif ch.name in("h2","h3"):body.append({"type":"heading","text":ch.get_text(strip=True)})
|
| 142 |
+
return{"title":h1.get_text(strip=True) if h1 else "","summary":se.get_text(strip=True) if se else "","og_image":og_img,"body":body,"source":"bdp","url":url}
|
| 143 |
+
except:return None
|
| 144 |
+
|
| 145 |
+
def scrape_24h_article(url):
|
| 146 |
+
try:
|
| 147 |
+
r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8"
|
| 148 |
+
soup=BeautifulSoup(r.text,"lxml");h1=soup.select_one("h1")
|
| 149 |
+
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 150 |
+
desc=soup.find("meta",property="og:description");summary=desc.get("content","")[:200] if desc else ""
|
| 151 |
+
body=[]
|
| 152 |
+
for sel in["div.the-article-body","div.nws-mainContent","div.nwsCt","div.detail-content"]:
|
| 153 |
+
cd=soup.select_one(sel)
|
| 154 |
+
if cd:
|
| 155 |
+
for ch in cd.children:
|
| 156 |
+
if not hasattr(ch,'name') or not ch.name:continue
|
| 157 |
+
if ch.name=="p":t=ch.get_text(strip=True);(body.append({"type":"p","text":t}) if t else None)
|
| 158 |
+
elif ch.name in("h2","h3"):body.append({"type":"heading","text":ch.get_text(strip=True)})
|
| 159 |
+
break
|
| 160 |
+
return{"title":h1.get_text(strip=True) if h1 else "","summary":summary,"og_image":og_img,"body":body,"source":"24h","url":url}
|
| 161 |
+
except:return None
|
| 162 |
+
|
| 163 |
+
def scrape_bbc_article(url):
|
| 164 |
+
try:
|
| 165 |
+
r=requests.get(url,headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
|
| 166 |
+
soup=BeautifulSoup(r.text,"lxml");h1=soup.find("h1")
|
| 167 |
+
og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
|
| 168 |
+
body=[]
|
| 169 |
+
for p in soup.select("[data-component='text-block'] p, article p, main p"):
|
| 170 |
+
t=p.get_text(strip=True)
|
| 171 |
+
if t and len(t)>20:body.append({"type":"p","text":t})
|
| 172 |
+
return{"title":h1.get_text(strip=True) if h1 else "","summary":"","og_image":og_img,"body":body,"source":"bbc","url":url}
|
| 173 |
+
except:return None
|
| 174 |
+
|
| 175 |
def scrape_bdp(url):
|
| 176 |
try:
|
| 177 |
soup=_get(url);arts=[];seen=set()
|
|
|
|
| 187 |
seen.add(lk);arts.append({"title":t,"link":lk,"img":img,"source":"bdp","summary":""})
|
| 188 |
return arts[:15]
|
| 189 |
except:return[]
|
|
|
|
| 190 |
def scrape_bdp_videos():
|
| 191 |
try:
|
| 192 |
soup=_get(f"{BASE_BDP}/video");arts=[];seen=set()
|
|
|
|
| 202 |
seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bdp"})
|
| 203 |
return arts[:20]
|
| 204 |
except:return[]
|
|
|
|
| 205 |
def scrape_24h_highlights():
|
| 206 |
try:
|
| 207 |
soup=_get(f"{BASE_24H}/video-highlight-c953.html");arts=[];seen=set()
|
|
|
|
| 224 |
with ThreadPoolExecutor(5) as ex:list(ex.map(_og,need))
|
| 225 |
return arts[:30]
|
| 226 |
except:return[]
|
|
|
|
| 227 |
def scrape_24h_shorts():
|
| 228 |
try:
|
| 229 |
r=requests.get(f"{BASE_24H}/video/video-tin-tuc-cvd769.html",headers=HEADERS,timeout=15);r.encoding="utf-8"
|
|
|
|
| 255 |
seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"24h-shorts"})
|
| 256 |
return arts[:20]
|
| 257 |
except:return[]
|
|
|
|
| 258 |
def scrape_bbc_vietnamese():
|
| 259 |
try:
|
| 260 |
bbc_h={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB,en;q=0.9"}
|
|
|
|
| 277 |
if len(arts)>=15:break
|
| 278 |
return arts
|
| 279 |
except:return[]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
def extract_video_url(article_url):
|
| 281 |
try:
|
| 282 |
r=requests.get(article_url,headers={**HEADERS,"Referer":"https://www.24h.com.vn/"},timeout=10);r.encoding="utf-8"
|
|
|
|
| 312 |
if len(parts)>1:return{"src":parts[0],"poster":poster,"all_parts":parts}
|
| 313 |
return{"src":primary[0],"poster":poster}
|
| 314 |
except:return None
|
|
|
|
| 315 |
def extract_bdp_video(url):
|
| 316 |
try:
|
| 317 |
m=re.search(r'-(\d{6,})\.html',url)
|
|
|
|
| 323 |
return{"src":source.get("src","") if source else "","poster":video.get("poster","")}
|
| 324 |
except:return None
|
| 325 |
|
| 326 |
+
# ═══ API Routes ═══
|
| 327 |
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"),"cong-nghe":("https://vnexpress.net/so-hoa","Công Nghệ"),"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")}
|
| 328 |
BDP_CATS={"ngoai-hang-anh":("https://bongdaplus.vn/ngoai-hang-anh","Ngoại Hạng Anh"),"la-liga":("https://bongdaplus.vn/la-liga","La Liga"),"champions-league":("https://bongdaplus.vn/champions-league-cup-c1","Champions League"),"bong-da-vn":("https://bongdaplus.vn/bong-da-viet-nam","Bóng Đá VN")}
|
| 329 |
|
|
|
|
| 343 |
except:pass
|
| 344 |
return articles
|
| 345 |
return JSONResponse(_cached("homepage",_f))
|
|
|
|
| 346 |
@app.get("/api/category/{cat_id}")
|
| 347 |
def api_category(cat_id:str):
|
| 348 |
def _f():
|
|
|
|
| 351 |
if cat_id in BDP_CATS:arts=scrape_bdp(BDP_CATS[cat_id][0]);[a.update({"group":BDP_CATS[cat_id][1]}) for a in arts];return arts
|
| 352 |
return[]
|
| 353 |
return JSONResponse(_cached(f"cat_{cat_id}",_f))
|
|
|
|
| 354 |
@app.get("/api/categories")
|
| 355 |
def api_categories():
|
| 356 |
cats=[{"id":"bbc","name":"BBC Tiếng Việt","source":"bbc"}]
|
| 357 |
for k,(u,n) in VNE_CATS.items():cats.append({"id":k,"name":n,"source":"vne"})
|
| 358 |
for k,(u,n) in BDP_CATS.items():cats.append({"id":k,"name":n,"source":"bdp"})
|
| 359 |
return JSONResponse(cats)
|
|
|
|
| 360 |
@app.get("/api/highlights")
|
| 361 |
def api_highlights():return JSONResponse(_cached("highlights",scrape_24h_highlights))
|
| 362 |
@app.get("/api/shorts")
|
|
|
|
| 369 |
elif"bongdaplus.vn" in url:v=extract_bdp_video(url)
|
| 370 |
else:v=None
|
| 371 |
return JSONResponse(v if v else{"error":"not found"})
|
| 372 |
+
|
| 373 |
+
# ★ FIX: /api/article now supports ALL sources (VNE, BBC, BDP, 24h)
|
| 374 |
@app.get("/api/article")
|
| 375 |
def api_article(url:str=Query(...)):
|
| 376 |
+
data=None
|
| 377 |
+
if "vnexpress.net" in url: data=scrape_vne_article(url)
|
| 378 |
+
elif "bbc.com" in url: data=scrape_bbc_article(url)
|
| 379 |
+
elif "bongdaplus.vn" in url: data=scrape_bdp_article(url)
|
| 380 |
+
elif "24h.com.vn" in url: data=scrape_24h_article(url)
|
| 381 |
+
return JSONResponse(data if data else {"error":"not supported"})
|
| 382 |
|
| 383 |
@app.get("/")
|
| 384 |
+
async def index(): return FileResponse("/app/static/index.html")
|
|
|
|
|
|
|
| 385 |
app.mount("/static",StaticFiles(directory="/app/static"),name="static")
|