bep40 commited on
Commit
4d8e550
·
verified ·
1 Parent(s): 833b482

Restore from 8a81274 + apply: shorts @baodantri7941+@baosuckhoedoisongboyte, genk AI 30 articles+OG fallback, homepage genk_ai replaces cong-nghe

Browse files
Files changed (1) hide show
  1. main.py +512 -1
main.py CHANGED
@@ -1 +1,512 @@
1
- Tôi cần thay thế hàm _yt_playlist scrape_fpt_shorts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """VNEWS - FastAPI backend with livescore + xemlaibongda highlights + YouTube FPT shorts"""
2
+ import hashlib, re, time, subprocess, json
3
+ from datetime import datetime
4
+ from concurrent.futures import ThreadPoolExecutor, as_completed
5
+ from fastapi import FastAPI, Query, Request
6
+ from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, Response
7
+ from fastapi.staticfiles import StaticFiles
8
+ from urllib.parse import unquote, quote, urlencode
9
+ import requests
10
+ from bs4 import BeautifulSoup
11
+
12
+ app = FastAPI()
13
+ 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"}
14
+ 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"}
15
+ BASE_BDP = "https://bongdaplus.vn"
16
+ SPACE_URL = "https://bep40-vnews.hf.space"
17
+ _cache = {}
18
+ _cache_ttl = 300
19
+ _cache_ttl_live = 60
20
+ _cache_ttl_yt = 1800
21
+ PRIORITY_LEAGUES = ["Ngoại Hạng Anh","FA Cup","Champions League","LaLiga","Copa del Rey","Serie A","Bundesliga","Ligue 1","V-League"]
22
+ LEAGUE_IDS = {"nha":27110,"laliga":27233,"seriea":27044,"bundesliga":26891,"ligue1":27212}
23
+ 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":"🌍"}}
24
+ def _cached(key, fn, ttl=None):
25
+ now=time.time();t=ttl or _cache_ttl
26
+ if key in _cache and now-_cache[key]["t"]<t:return _cache[key]["d"]
27
+ try:data=fn()
28
+ except:data=_cache.get(key,{}).get("d",[])
29
+ _cache[key]={"d":data,"t":now};return data
30
+ def _get(url,headers=None):
31
+ h=headers or HEADERS;r=requests.get(url,headers=h,timeout=15);r.encoding="utf-8"
32
+ return BeautifulSoup(r.text,"lxml")
33
+ def fetch_bongda_api(endpoint):
34
+ try:
35
+ r=requests.get(f"https://bongda.com.vn{endpoint}",headers=BONGDA_HEADERS,timeout=10)
36
+ if r.status_code==200:
37
+ data=r.json()
38
+ if data.get("status")=="success":return data.get("html","")
39
+ return ""
40
+ except:return ""
41
+ def _parse_match_from_li(li, status_type="live"):
42
+ match_div=li.select_one("div.match")
43
+ if not match_div:return None
44
+ home_el=match_div.select_one(".home-team .name");away_el=match_div.select_one(".away-team .name")
45
+ if not home_el or not away_el:return None
46
+ status_el=match_div.select_one(".status a");league_el=li.find_previous("strong");time_el=match_div.select_one(".match-time")
47
+ home_logo=match_div.select_one(".home-team .logo img");away_logo=match_div.select_one(".away-team .logo img")
48
+ event_id=""
49
+ if status_el:
50
+ href=status_el.get("href","");m=re.search(r'/tran-dau/(\d+)/',href)
51
+ if m:event_id=m.group(1)
52
+ spans=status_el.find_all("span") if status_el else [];score="";minute=""
53
+ if len(spans)>=3:score=f"{spans[0].get_text(strip=True)} - {spans[2].get_text(strip=True)}"
54
+ if len(spans)>=4:minute=spans[3].get_text(strip=True)
55
+ if not score and status_el and status_el.select_one(".vs"):score="VS"
56
+ league=league_el.get_text(strip=True) if league_el else ""
57
+ 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}
58
+
59
+ # ===== VIDEO PROXY =====
60
+ @app.get("/api/proxy/m3u8")
61
+ def proxy_m3u8(url: str = Query(...)):
62
+ try:
63
+ r = requests.get(url, headers=HEADERS, timeout=15)
64
+ if r.status_code != 200:return Response(status_code=502, content="upstream error")
65
+ lines = r.text.strip().split('\n');rewritten = []
66
+ for line in lines:
67
+ if line.startswith('#') or not line.strip():rewritten.append(line)
68
+ else:rewritten.append("/api/proxy/seg?url=" + quote(line.strip(), safe=""))
69
+ 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"})
70
+ except:return Response(status_code=502, content="proxy error")
71
+
72
+ @app.get("/api/proxy/seg")
73
+ def proxy_segment(url: str = Query(...)):
74
+ try:
75
+ r = requests.get(url, headers=HEADERS, timeout=30)
76
+ if r.status_code != 200:return Response(status_code=502, content="upstream error")
77
+ data = r.content
78
+ if len(data) > 188 and data[0:4] == b'\x89PNG' and data[188] == 0x47:data = data[188:]
79
+ return Response(content=data,media_type="video/mp2t",headers={"Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=3600"})
80
+ except:return Response(status_code=502, content="proxy error")
81
+
82
+ @app.get("/api/proxy/video")
83
+ def proxy_video(url: str = Query(...), request: Request = None):
84
+ try:
85
+ req_headers = dict(HEADERS)
86
+ if request and request.headers.get("range"):req_headers["Range"] = request.headers["range"]
87
+ r = requests.get(url, headers=req_headers, timeout=30, stream=True)
88
+ resp_headers = {"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes","Content-Type":r.headers.get("Content-Type","video/mp4")}
89
+ if "Content-Range" in r.headers:resp_headers["Content-Range"] = r.headers["Content-Range"]
90
+ if "Content-Length" in r.headers:resp_headers["Content-Length"] = r.headers["Content-Length"]
91
+ return StreamingResponse(r.iter_content(chunk_size=256*1024),status_code=r.status_code,headers=resp_headers)
92
+ except:return Response(status_code=502, content="proxy error")
93
+
94
+ @app.get("/api/proxy/img")
95
+ def proxy_img(url: str = Query(...)):
96
+ """Proxy images from sources that block hotlinking (DanTri CDN)."""
97
+ try:
98
+ r = requests.get(url, headers={**HEADERS, "Referer": "https://dantri.com.vn/"}, timeout=10)
99
+ if r.status_code != 200:return Response(status_code=502)
100
+ ct = r.headers.get("Content-Type", "image/jpeg")
101
+ return Response(content=r.content, media_type=ct, headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"})
102
+ except:return Response(status_code=502)
103
+
104
+ # ===== XEMLAIBONGDA HIGHLIGHTS =====
105
+ def _scrape_xemlaibongda_page(page_path, limit=20):
106
+ try:
107
+ url = f"https://xemlaibongda.top/{page_path}" if page_path else "https://xemlaibongda.top/"
108
+ r=requests.get(url,headers=HEADERS,timeout=15)
109
+ if r.status_code!=200:return[]
110
+ r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml");videos=[];seen=set()
111
+ for a in soup.find_all("a",href=True):
112
+ href=a.get("href","")
113
+ if"/video/" not in href:continue
114
+ if not href.startswith("http"):href="https://xemlaibongda.top"+href
115
+ if href in seen:continue
116
+ seen.add(href);slug=href.split("/video/")[-1].rstrip("/")
117
+ title=slug.replace("-"," ").title()
118
+ title=re.sub(r'\d{4}\s*\d{2}\s*\d{2}$','',title).strip()
119
+ title=re.sub(r'\s+V\s+',' vs ',title);title=re.sub(r'\s+Vs\s+',' vs ',title)
120
+ img=a.find("img") or (a.parent.find("img") if a.parent else None)
121
+ img_src=""
122
+ if img:img_src=img.get("data-src","") or img.get("src","") or img.get("data-lazy","")
123
+ if not img_src:img_src=f"https://img.refooty.com/thumbnail/{slug}.webp"
124
+ videos.append({"title":title,"link":href,"img":img_src,"source":"xemlaibongda"})
125
+ if len(videos)>=limit:break
126
+ return videos
127
+ except:return[]
128
+
129
+ def scrape_xemlaibongda():return _scrape_xemlaibongda_page("",20)
130
+ def scrape_highlights_by_league(league_key):
131
+ if league_key not in HL_LEAGUES:return[]
132
+ return _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"],20)
133
+
134
+ def scrape_all_league_highlights():
135
+ results = {}
136
+ def _fetch(key):return key, scrape_highlights_by_league(key)
137
+ with ThreadPoolExecutor(8) as ex:
138
+ futs = [ex.submit(_fetch, k) for k in HL_LEAGUES]
139
+ for f in as_completed(futs):
140
+ try:
141
+ key, vids = f.result()
142
+ if vids:results[key] = vids
143
+ except:pass
144
+ return results
145
+
146
+ def extract_xemlaibongda_video(url):
147
+ try:
148
+ r=requests.get(url,headers=HEADERS,timeout=15)
149
+ if r.status_code!=200:return None
150
+ r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml");video=soup.find("video")
151
+ if video:
152
+ src=video.get("src","");poster=video.get("poster","")
153
+ if not src:
154
+ source=video.find("source")
155
+ if source:src=source.get("src","")
156
+ if src:return{"src":src,"poster":poster,"type":"hls" if".m3u8" in src else"video"}
157
+ m3u8s=re.findall(r'(https?://[^\s"\'<>]+\.m3u8)',r.text)
158
+ if m3u8s:
159
+ og=soup.find("meta",property="og:image");poster=og.get("content","") if og else ""
160
+ return{"src":m3u8s[0],"poster":poster,"type":"hls"}
161
+ return None
162
+ except:return None
163
+
164
+ # ===== YOUTUBE SHORTS =====
165
+ def _yt_channel_shorts(channel, count=15):
166
+ try:
167
+ result=subprocess.run(["yt-dlp","--flat-playlist","--dump-json","--no-download","--playlist-end",str(count),f"https://www.youtube.com/@{channel}/shorts"],capture_output=True,text=True,timeout=60)
168
+ videos=[]
169
+ for line in result.stdout.strip().split('\n'):
170
+ if not line:continue
171
+ try:
172
+ info=json.loads(line);vid=info.get("id","");title=info.get("title","")
173
+ if not vid or not title:continue
174
+ videos.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})
175
+ except:pass
176
+ return videos
177
+ except:return[]
178
+ def scrape_shorts():
179
+ """Fetch shorts from multiple channels"""
180
+ vids=[]
181
+ with ThreadPoolExecutor(2) as ex:
182
+ futs=[ex.submit(_yt_channel_shorts,ch,10) for ch in ["baodantri7941","baosuckhoedoisongboyte"]]
183
+ for f in as_completed(futs):
184
+ try:vids.extend(f.result())
185
+ except:pass
186
+ return vids[:20]
187
+
188
+ # ===== LIVESCORE =====
189
+ @app.get("/api/livescore/live")
190
+ def api_livescore_live():return JSONResponse({"html":_cached("ls_live",lambda:fetch_bongda_api("/api/fixtures/live"),ttl=_cache_ttl_live)})
191
+ @app.get("/api/livescore/incoming")
192
+ def api_livescore_incoming():return JSONResponse({"html":_cached("ls_incoming",lambda:fetch_bongda_api("/api/fixtures/incoming"),ttl=_cache_ttl_live)})
193
+ @app.get("/api/livescore/today")
194
+ def api_livescore_today():
195
+ 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)})
196
+ @app.get("/api/livescore/results")
197
+ def api_livescore_results():
198
+ 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)})
199
+ @app.get("/api/livescore/standings/{league}")
200
+ def api_livescore_standings(league:str):
201
+ 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)})
202
+ @app.get("/api/livescore/date/{date}")
203
+ def api_livescore_date(date:str):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/get-by-date?date={date}")})
204
+ @app.get("/api/match/{event_id}/commentaries")
205
+ def api_match_commentaries(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/commentaries?event_id={event_id}")})
206
+ @app.get("/api/match/{event_id}/stats")
207
+ def api_match_stats(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/event-standing/player-performance?event_id={event_id}")})
208
+ @app.get("/api/livescore/featured")
209
+ def api_livescore_featured():
210
+ def _f():
211
+ sources=[("/api/fixtures/live","live"),("/api/fixtures/get-by-date?date="+datetime.now().strftime("%Y-%m-%d"),"today"),("/api/fixtures/incoming","upcoming")]
212
+ for endpoint, stype in sources:
213
+ html=fetch_bongda_api(endpoint)
214
+ if not html or len(html)<100:continue
215
+ soup=BeautifulSoup(html,"lxml");all_matches=[]
216
+ for li in soup.select("li.match-detail"):
217
+ match=_parse_match_from_li(li, stype)
218
+ if not match or not match["event_id"]:continue
219
+ if stype=="today" and "KT" in match.get("minute",""):continue
220
+ all_matches.append(match)
221
+ if not all_matches:continue
222
+ for pl in PRIORITY_LEAGUES:
223
+ for match in all_matches:
224
+ if pl in match["league"]:return match
225
+ return all_matches[0]
226
+ return None
227
+ return JSONResponse(_cached("ls_featured",_f,ttl=30))
228
+
229
+ # ===== VIDEO APIs =====
230
+ @app.get("/api/shorts")
231
+ def api_shorts():return JSONResponse(_cached("yt_shorts",scrape_shorts,ttl=_cache_ttl_yt))
232
+ @app.get("/api/highlights")
233
+ def api_highlights():return JSONResponse(_cached("xemlaibongda_hl",scrape_xemlaibongda,ttl=_cache_ttl))
234
+ @app.get("/api/highlights/leagues")
235
+ def api_highlights_leagues():return JSONResponse(_cached("hl_leagues",scrape_all_league_highlights,ttl=_cache_ttl))
236
+ @app.get("/api/highlights/{league}")
237
+ def api_highlights_league(league:str):
238
+ if league not in HL_LEAGUES:return JSONResponse({"error":"league not found"})
239
+ return JSONResponse(_cached(f"hl_{league}",lambda:scrape_highlights_by_league(league),ttl=_cache_ttl))
240
+ @app.get("/api/highlights_config")
241
+ def api_highlights_config():return JSONResponse(HL_LEAGUES)
242
+ @app.get("/api/video_url")
243
+ def api_video_url(url:str=Query(...)):
244
+ if "youtube.com" in url or "youtu.be" in url:
245
+ m=re.search(r'(?:v=|shorts/|youtu\.be/)([a-zA-Z0-9_-]{11})',url)
246
+ 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"})
247
+ if "xemlaibongda.top" in url:
248
+ v=extract_xemlaibongda_video(url)
249
+ if v:
250
+ if v["type"]=="hls":v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="")
251
+ return JSONResponse(v)
252
+ if "bongdaplus.vn" in url:
253
+ try:
254
+ m=re.search(r'-(\d{6,})\.html',url)
255
+ if m:
256
+ r=requests.get(f"{BASE_BDP}/video-embed/{m.group(1)}.html",headers=HEADERS,timeout=10);r.encoding="utf-8"
257
+ soup=BeautifulSoup(r.text,"lxml");video=soup.select_one("video#videoPlayer")
258
+ if video:
259
+ source=video.find("source");src=source.get("src","") if source else "";poster=video.get("poster","")
260
+ if src:return JSONResponse({"src":"/api/proxy/video?url="+quote(src,safe=""),"poster":poster,"type":"video"})
261
+ except:pass
262
+ return JSONResponse({"error":"not found"})
263
+ @app.get("/api/bdp_videos")
264
+ def api_bdp_videos():
265
+ def _f():
266
+ try:
267
+ soup=_get(f"{BASE_BDP}/video");arts=[];seen=set()
268
+ for a in soup.find_all("a",href=True):
269
+ href=a.get("href","")
270
+ if"/video/" not in href or href in("/video/","/video/ban-thang-dep","/video/highlight"):continue
271
+ if not href.startswith("http"):href=BASE_BDP+href
272
+ if href in seen:continue
273
+ title=re.sub(r'^\d{2}:\d{2}','',a.get_text(strip=True)).strip()
274
+ if not title or len(title)<5:continue
275
+ img_tag=a.find("img") or(a.parent.find("img") if a.parent else None)
276
+ img=(img_tag.get("data-src") or img_tag.get("src","")) if img_tag else ""
277
+ seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bdp"})
278
+ return arts[:20]
279
+ except:return[]
280
+ return JSONResponse(_cached("bdp_videos",_f))
281
+ # ===== NEWS =====
282
+ def scrape_vne(cat_url):
283
+ try:
284
+ soup=_get(cat_url);arts=[]
285
+ for it in soup.select("article.item-news")[:15]:
286
+ a=it.select_one("h2.title-news a") or it.select_one("h3.title-news a")
287
+ if not a:continue
288
+ t=a.get("title","") or a.get_text(strip=True);lk=a.get("href","")
289
+ if not t or not lk:continue
290
+ im=it.find("img");img=(im.get("data-src") or im.get("src","")) if im else ""
291
+ if img and'blank'in img:
292
+ src=it.find("source")
293
+ if src:img=src.get("srcset","").split(",")[0].strip().split(" ")[0]
294
+ arts.append({"title":t,"link":lk,"img":img,"source":"vne"})
295
+ return arts
296
+ except:return[]
297
+ def scrape_vne_article(url):
298
+ try:
299
+ soup=_get(url);h1=soup.select_one("h1.title-detail");desc=soup.select_one("p.description")
300
+ og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
301
+ cd=soup.select_one("article.fck_detail");body=[]
302
+ if cd:
303
+ for ch in cd.children:
304
+ if not hasattr(ch,'name') or not ch.name:continue
305
+ if ch.name=="p":t=ch.get_text(strip=True);(body.append({"type":"p","text":t}) if t else None)
306
+ elif ch.name=="figure":
307
+ im=ch.find("img")
308
+ if im:s=im.get("data-src") or im.get("src","");body.append({"type":"img","src":s})
309
+ elif ch.name in("h2","h3"):body.append({"type":"heading","text":ch.get_text(strip=True)})
310
+ 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}
311
+ except:return None
312
+ def _scrape_dantri_homepage(cat_filter=None):
313
+ try:
314
+ soup=_get("https://dantri.com.vn/");arts=[];seen=set()
315
+ for a in soup.find_all("a",href=True):
316
+ href=a.get("href","");title=a.get("title","") or a.get_text(strip=True)
317
+ if not title or len(title)<15 or"javascript:" in href:continue
318
+ if not href.startswith("http"):href="https://dantri.com.vn"+href
319
+ if href in seen or not href.endswith(".htm"):continue
320
+ if cat_filter and f"/{cat_filter}/" not in href:continue
321
+ img_tag=a.find("img")
322
+ if not img_tag and a.parent:img_tag=a.parent.find("img")
323
+ img_src=""
324
+ if img_tag:img_src=img_tag.get("data-src","") or img_tag.get("src","")
325
+ if not img_src or "cdn" not in img_src:continue
326
+ proxied_img="/api/proxy/img?url="+quote(img_src,safe="")
327
+ seen.add(href);arts.append({"title":title,"link":href,"img":proxied_img,"source":"dantri"})
328
+ if len(arts)>=15:break
329
+ return arts
330
+ except:return[]
331
+ def scrape_dantri_hot():return _scrape_dantri_homepage()
332
+ def scrape_dantri_congnghe():
333
+ try:
334
+ soup=_get("https://dantri.com.vn/");arts=[];seen=set()
335
+ for a in soup.find_all("a",href=True):
336
+ href=a.get("href","");title=a.get("title","") or a.get_text(strip=True)
337
+ if not title or len(title)<15 or"javascript:" in href:continue
338
+ if not href.startswith("http"):href="https://dantri.com.vn"+href
339
+ if href in seen or not href.endswith(".htm"):continue
340
+ if"/cong-nghe/" not in href:continue
341
+ img_tag=a.find("img")
342
+ if not img_tag and a.parent:img_tag=a.parent.find("img")
343
+ img_src=""
344
+ if img_tag:img_src=img_tag.get("data-src","") or img_tag.get("src","")
345
+ if img_src and "cdn" in img_src:img_src="/api/proxy/img?url="+quote(img_src,safe="")
346
+ else:img_src=""
347
+ seen.add(href);arts.append({"title":title,"link":href,"img":img_src,"source":"dantri"})
348
+ if len(arts)>=15:break
349
+ return arts
350
+ except:return[]
351
+ def scrape_genk_ai():
352
+ """Scrape AI articles from genk.vn - readable in-app"""
353
+ try:
354
+ r=requests.get("https://genk.vn/ai.chn",headers=HEADERS,timeout=15)
355
+ if r.status_code!=200:return[]
356
+ r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
357
+ articles=[];seen=set()
358
+ for a in soup.find_all("a",href=True):
359
+ href=a.get("href","")
360
+ if not href.endswith(".chn") or href=="/ai.chn":continue
361
+ if href.startswith("/"):href="https://genk.vn"+href
362
+ if href in seen or "genk.vn" not in href:continue
363
+ title=a.get("title","") or a.get_text(strip=True)
364
+ if not title or len(title)<20:continue
365
+ container=a.parent;img_src=""
366
+ for _ in range(6):
367
+ if container is None:break
368
+ for img in container.find_all("img"):
369
+ s=img.get("data-src","") or img.get("src","")
370
+ if s and "mediacdn" in s and "avatar" not in s and "logo" not in s:
371
+ img_src=s;break
372
+ if img_src:break
373
+ container=container.parent
374
+ seen.add(href)
375
+ if not img_src:
376
+ try:
377
+ og_r=requests.get(href,headers=HEADERS,timeout=8);og_r.encoding="utf-8"
378
+ og_soup=BeautifulSoup(og_r.text,"lxml");og_tag=og_soup.find("meta",property="og:image")
379
+ if og_tag:img_src=og_tag.get("content","")
380
+ except:pass
381
+ articles.append({"title":title,"link":href,"img":img_src,"source":"genk"})
382
+ if len(articles)>=30:break
383
+ return articles
384
+ except:return[]
385
+
386
+ def scrape_dantri_article(url):
387
+ try:
388
+ r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
389
+ for tag in soup.find_all(["script","style","nav","footer","aside"]):tag.decompose()
390
+ h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
391
+ if og_img and "cdnphoto.dantri" in og_img:og_img="/api/proxy/img?url="+quote(og_img,safe="")
392
+ content=soup.select_one("main") or soup.select_one("div.singular-content") or soup.select_one("article");body=[]
393
+ if content:
394
+ for el in content.find_all(["p","h2","h3","figure","img"],recursive=True):
395
+ if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None)
396
+ elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None)
397
+ elif el.name in("figure","img"):
398
+ im=el if el.name=="img" else el.find("img")
399
+ if im:
400
+ s=im.get("data-src") or im.get("src","")
401
+ if s and"base64" not in s:
402
+ if "cdnphoto.dantri" in s:s="/api/proxy/img?url="+quote(s,safe="")
403
+ body.append({"type":"img","src":s})
404
+ desc="";sapo=soup.select_one("h2.singular-sapo") or soup.select_one("h2[class*=sapo]")
405
+ if not sapo:
406
+ og_desc=soup.find("meta",property="og:description")
407
+ if og_desc:desc=og_desc.get("content","")
408
+ else:desc=sapo.get_text(strip=True)
409
+ return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"dantri","url":url}
410
+ except:return None
411
+ def scrape_bbc_vietnamese():
412
+ try:
413
+ r=requests.get("https://www.bbc.com/vietnamese",headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
414
+ soup=BeautifulSoup(r.text,"lxml");arts=[];seen=set()
415
+ for a in soup.select("a[href*='/vietnamese/']"):
416
+ href=a.get("href","")
417
+ if not href or href=="/vietnamese" or href.count("/")<3:continue
418
+ if not href.startswith("http"):href="https://www.bbc.com"+href
419
+ if href in seen:continue
420
+ title=a.get_text(strip=True)
421
+ if not title or len(title)<15 or any(x in title.lower() for x in["đăng nhập","trang chủ","bbc news"]):continue
422
+ img="";container=a.parent
423
+ for _ in range(3):
424
+ if container:
425
+ im=container.find("img")
426
+ if im:img=im.get("src","") or im.get("data-src","");break
427
+ container=container.parent
428
+ seen.add(href);arts.append({"title":title,"link":href,"img":img,"source":"bbc"})
429
+ if len(arts)>=15:break
430
+ return arts
431
+ except:return[]
432
+ def scrape_bbc_article(url):
433
+ try:
434
+ r=requests.get(url,headers={"User-Agent":"Mozilla/5.0","Accept-Language":"en-GB"},timeout=15);r.encoding="utf-8"
435
+ soup=BeautifulSoup(r.text,"lxml");h1=soup.find("h1")
436
+ og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
437
+ body=[]
438
+ for p in soup.select("[data-component='text-block'] p, article p, main p"):
439
+ t=p.get_text(strip=True)
440
+ if t and len(t)>20:body.append({"type":"p","text":t})
441
+ return{"title":h1.get_text(strip=True) if h1 else "","summary":"","og_image":og_img,"body":body,"source":"bbc","url":url}
442
+ except:return None
443
+ VNE_CATS={"thoi-su":("https://vnexpress.net/thoi-su","Thời Sự"),"the-gioi":("https://vnexpress.net/the-gioi","Thế Giới"),"kinh-doanh":("https://vnexpress.net/kinh-doanh","Kinh Doanh"),"the-thao":("https://vnexpress.net/the-thao","Thể Thao"),"giai-tri":("https://vnexpress.net/giai-tri","Giải Trí"),"suc-khoe":("https://vnexpress.net/suc-khoe","Sức Khỏe"),"phap-luat":("https://vnexpress.net/phap-luat","Pháp Luật"),"giao-duc":("https://vnexpress.net/giao-duc","Giáo Dục"),"du-lich":("https://vnexpress.net/du-lich","Du Lịch"),"doi-song":("https://vnexpress.net/doi-song","Đời Sống")}
444
+ @app.get("/api/homepage")
445
+ def api_homepage():
446
+ def _f():
447
+ articles=[]
448
+ with ThreadPoolExecutor(12) as ex:
449
+ 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"]}
450
+ futs[ex.submit(scrape_bbc_vietnamese)]="BBC"
451
+ futs[ex.submit(scrape_genk_ai)]="Công Nghệ"
452
+ for f in as_completed(futs):
453
+ try:
454
+ for a in f.result():a["group"]=futs[f];articles.append(a)
455
+ except:pass
456
+ return articles
457
+ return JSONResponse(_cached("homepage",_f))
458
+ @app.get("/api/category/{cat_id}")
459
+ def api_category(cat_id:str):
460
+ def _f():
461
+ if cat_id=="bbc":return scrape_bbc_vietnamese()
462
+ if cat_id=="cong-nghe":return scrape_genk_ai()
463
+ 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
464
+ return[]
465
+ return JSONResponse(_cached(f"cat_{cat_id}",_f))
466
+ @app.get("/api/categories")
467
+ def api_categories():
468
+ cats=[{"id":"bbc","name":"BBC Tiếng Việt","source":"bbc"},{"id":"cong-nghe","name":"Công Nghệ","source":"genk"}]
469
+ for k,(u,n) in VNE_CATS.items():cats.append({"id":k,"name":n,"source":"vne"})
470
+ return JSONResponse(cats)
471
+ @app.get("/api/dantri_hot")
472
+ def api_dantri_hot():return JSONResponse(_cached("dantri_hot",scrape_dantri_hot))
473
+ @app.get("/api/genk_ai")
474
+ def api_genk_ai():return JSONResponse(_cached("genk_ai",scrape_genk_ai,ttl=_cache_ttl))
475
+ def scrape_genk_article(url):
476
+ try:
477
+ r=requests.get(url,headers=HEADERS,timeout=15);r.encoding="utf-8";soup=BeautifulSoup(r.text,"lxml")
478
+ h1=soup.find("h1");og=soup.find("meta",property="og:image");og_img=og.get("content","") if og else ""
479
+ desc_el=soup.find("meta",property="og:description");desc=desc_el.get("content","") if desc_el else ""
480
+ cd=soup.select_one(".knc-content");body=[]
481
+ if cd:
482
+ for el in cd.find_all(["p","h2","h3","figure","img"],recursive=True):
483
+ if el.name=="p":t=el.get_text(strip=True);(body.append({"type":"p","text":t}) if t and len(t)>15 else None)
484
+ elif el.name in("h2","h3"):t=el.get_text(strip=True);(body.append({"type":"heading","text":t}) if t else None)
485
+ elif el.name in("figure","img"):
486
+ im=el if el.name=="img" else el.find("img")
487
+ 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)
488
+ return{"title":h1.get_text(strip=True) if h1 else "","summary":desc,"og_image":og_img,"body":body,"source":"genk","url":url}
489
+ except:return None
490
+
491
+ @app.get("/api/article")
492
+ def api_article(url:str=Query(...)):
493
+ if"vnexpress.net" in url:data=scrape_vne_article(url)
494
+ elif"bbc.com" in url:data=scrape_bbc_article(url)
495
+ elif"dantri.com.vn" in url:data=scrape_dantri_article(url)
496
+ elif"genk.vn" in url:data=scrape_genk_article(url)
497
+ else:data=None
498
+ return JSONResponse(data if data else{"error":"not supported"})
499
+ @app.get("/v")
500
+ async def video_share(url:str=Query(default=""),title:str=Query(default="VNEWS Video"),img:str=Query(default=""),type:str=Query(default="highlights")):
501
+ decoded_url=unquote(url);decoded_title=unquote(title)
502
+ redirect_script=f'<script>localStorage.setItem("pending_video",JSON.stringify({{"url":"{decoded_url}","type":"{type}"}}));location.href="{SPACE_URL}";</script>' if decoded_url else f'<script>location.href="{SPACE_URL}";</script>'
503
+ return HTMLResponse(f'<!DOCTYPE html><html><head><meta charset="utf-8"><title>{decoded_title}</title></head><body style="background:#111;color:#fff;text-align:center;padding:40px"><p>⏳</p>{redirect_script}</body></html>')
504
+ @app.get("/s")
505
+ async def share_redirect(url:str=Query(default=""),title:str=Query(default="VNEWS"),img:str=Query(default="")):
506
+ decoded_url=unquote(url)
507
+ redirect_script=f'<script>localStorage.setItem("pending_article","{decoded_url}");location.href="{SPACE_URL}";</script>' if decoded_url else f'<script>location.href="{SPACE_URL}";</script>'
508
+ return HTMLResponse(f'<!DOCTYPE html><html><head><meta charset="utf-8"><title>{unquote(title)}</title></head><body>{redirect_script}</body></html>')
509
+ @app.get("/")
510
+ async def index():
511
+ with open("/app/static/index.html","r",encoding="utf-8") as f:return HTMLResponse(content=f.read())
512
+ app.mount("/static",StaticFiles(directory="/app/static"),name="static")