Restore version 98c133a

#21
This view is limited to 50 files because it contains too many changes. See the raw diff here.
.dockerignore DELETED
File without changes
.gitignore DELETED
@@ -1,6 +0,0 @@
1
- __pycache__/
2
- *.pyc
3
- data/
4
- .data
5
- .huggingface/
6
- .restart_trigger
 
 
 
 
 
 
 
.rebuild ADDED
@@ -0,0 +1 @@
 
 
1
+ rebuilt at 2026-06-18T09:24:34.973630
.restart_trigger ADDED
@@ -0,0 +1 @@
 
 
1
+ # restart trigger
CHANGELOG.md CHANGED
@@ -1,16 +1,36 @@
1
- # FPT Play Stream Selector Update
2
 
3
- Added FPT Play channel with stream selector UI similar to VTV6:
4
 
5
- - New tab "FPT" (orange themed) in the channel tabs
6
- - Stream selector with 4 sources:
7
- 1. 🌐 Web FPT Play (iframe)
8
- 2. 📡 HLS Proxy (via /api/proxy/m3u8)
9
- 3. 🔗 HLS Direct
10
- 4. 📺 HD1.xemtv.net (iframe from LINK 1)
11
- - Backend vtv_api.py now returns stream_selectors for fpt-the-thao channel
12
- - Frontend handles stream switching automatically when FPT tab is active
 
 
13
 
14
- ## Changes
15
- - `static/vtv_init.js`: Added FPT tab + stream selector UI logic
16
- - `vtv_api.py`: Added FPT Play endpoint responses with stream_selectors data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VNEWS v5 - Match Detail Fix
2
 
3
+ ## Changes
4
 
5
+ ### 1. match_detail_v2.py Rewrote event parser with correct selectors
6
+ - Parse `.events > .period > .event` structure (not old `.timeline`)
7
+ - Extract event type from SVG icons in `.event-type` (goal/redcard/yellowcard/substitution)
8
+ - Parse player names from `.players > div` elements
9
+ - For goals: extract scorer + assist names
10
+ - For substitutions: extract player_out player_in
11
+ - For cards: extract player name
12
+ - Normalize time format: `45' +2` `45+2'`
13
+ - Fetch H2H stats from `/api/fixtures/h2h-stats` API
14
+ - Parse prediction card, recent matches, H2H standings
15
 
16
+ ### 2. static/match_detail.js — Complete rewrite with 2-tab layout
17
+ - **Tab "Thống kê"**: H2H stats comparison, prediction vote, recent match results
18
+ - **Tab "Diễn biến"**: Detailed timeline with:
19
+ - ⚽ BÀN THẮNG — scorer name + assist
20
+ - 🟥 THỺ ĐỎ — player name
21
+ - 🟨 THỺ VÀNG — player name
22
+ - ↔️ THAY ĐỔI — player_out → player_in
23
+ - Period grouping (H1, H2) with visual headers
24
+ - Team badges (HOME/AWAY) per event
25
+ - Color-coded event icons
26
+
27
+ ### 3. app_v2_entry.py — Updated
28
+ - Module cache clearing for fresh match_detail_v2 import on each API call
29
+ - Single clean import for both `/detail` and `/live` endpoints
30
+ - Removed duplicate inline scraping code
31
+
32
+ ### 4. _run.py — Fixed import
33
+ - Changed `import match_detail` to `import match_detail_v2`
34
+
35
+ ### 5. Dockerfile — Cache busting
36
+ - Added `RUN date > /app/.build_timestamp` to force Docker rebuild
Dockerfile CHANGED
@@ -2,47 +2,14 @@ FROM python:3.12-slim
2
 
3
  WORKDIR /app
4
 
5
- RUN echo "[BUILD] step1: apt-get update+install ffmpeg + Vietnamese fonts" && \
6
- apt-get update && apt-get install -y --no-install-recommends \
7
- ffmpeg \
8
- fonts-dejavu-core \
9
- fonts-noto \
10
- fonts-noto-cjk \
11
- fonts-noto-color-emoji \
12
- fonts-liberation \
13
- fonts-freefont-ttf \
14
- libfreetype6 \
15
- && rm -rf /var/lib/apt/lists/* && \
16
- echo "[BUILD] step1 done"
17
-
18
- RUN echo "[BUILD] step2: pip base pkgs (bs4/lxml)" && \
19
- pip install --no-cache-dir "beautifulsoup4>=4.12" lxml && \
20
- echo "[BUILD] step2 done"
21
-
22
- RUN echo "[BUILD] step3: pip main pkgs" && \
23
- pip install --no-cache-dir fastapi uvicorn requests beautifulsoup4 jinja2 yt-dlp huggingface_hub gTTS pillow edge-tts python-dateutil httpx pycryptodome && \
24
- echo "[BUILD] step3 done"
25
 
26
  COPY requirements.txt .
27
- RUN echo "[BUILD] step4: pip requirements.txt" && \
28
- pip install --no-cache-dir -r requirements.txt || true && \
29
- echo "[BUILD] step4 done"
30
 
31
  COPY . .
32
  EXPOSE 7860
33
 
34
- RUN echo "[BUILD] step5: setup Vietnamese font symlink" && \
35
- mkdir -p /usr/share/fonts/truetype/vn && \
36
- # Prefer Noto Sans for Vietnamese - it has full diacritic support
37
- if [ -f /usr/share/fonts/truetype/noto/NotoSans-Regular.ttf ]; then \
38
- ln -sf /usr/share/fonts/truetype/noto/NotoSans-Regular.ttf /usr/share/fonts/truetype/vn/VNFont.ttf; \
39
- elif [ -f /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf ]; then \
40
- ln -sf /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf /usr/share/fonts/truetype/vn/VNFont.ttf; \
41
- ln -sf /usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf /usr/share/fonts/truetype/vn/VNFont-Bold.ttf; \
42
- fi; \
43
- fc-cache -f -v || true; \
44
- date > /app/.build_done && \
45
- echo "[BUILD] step5 done"
46
-
47
- CMD ["uvicorn", "_run:app", "--host", "0.0.0.0", "--port", "7860"]
48
- # v3.0-vn-font-fix-short-video-2026-07-19
 
2
 
3
  WORKDIR /app
4
 
5
+ RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg fonts-dejavu-core && rm -rf /var/lib/apt/lists/*
6
+ RUN pip install --no-cache-dir "beautifulsoup4>=4.12" lxml
7
+ RUN pip install --no-cache-dir fastapi uvicorn requests beautifulsoup4 jinja2 yt-dlp huggingface_hub gTTS pillow edge-tts python-dateutil httpx
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  COPY requirements.txt .
10
+ RUN pip install --no-cache-dir -r requirements.txt || true
 
 
11
 
12
  COPY . .
13
  EXPOSE 7860
14
 
15
+ CMD ["uvicorn", "_run:app", "--host", "0.0.0.0", "--port", "7860", "--reload"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -9,50 +9,17 @@ tags:
9
  - ml-intern
10
  ---
11
 
12
- # VNEWS - Tin Tức Việt Nam
13
-
14
- **v18 - FIXED VTV2/VTV3/VTV6/VTV9 stream hanging**
15
-
16
- ## 🔧 Changes in v18 (2026-07-06)
17
- - **VTV2, VTV3, VTV6, VTV9**: Skip expired ssaimh CDN token → immediately fall through to sv2.xemtivitop.com
18
- - **15+ extraction patterns** for m3u8 URL (up from 5), including: file:, src=, source:, player.src(), hls.loadSource(), href=, `<source src>`, url:, window.location, iframe follow (3 levels deep), base64 decode
19
- - **Backup CDN** `tv.mediacdn.vn` for VTV2/VTV3/VTV6/VTV9
20
- - **Fast timeout** 5s for CDN, 12s for PHP endpoints (was 15s each = 60s+ total)
21
- - **sv2.xemtivitop.com** re-prioritized to check BEFORE xemtv.us
22
- - **Iframe chain following**: if a PHP page returns an iframe → follow it up to 3 levels to find the m3u8
23
-
24
- ## Features:
25
- - 📰 News from VnExpress (10 categories) + GenK AI
26
- - ⚽ Livescore from bongda.com.vn (live, today, upcoming, results, standings)
27
- - 🎬 Football highlights from xemlaibongda.top (8 leagues)
28
- - 📺 VTV live channels (VTV1→VTV10, VTV Prime)
29
- - Priority: ssaimh CDN → sv2.xemtivitop.com → xemtv.us → xemtivitop blogspot → FPTPlay → VTVGo → mediacdn → xemtv.net
30
- - 🏆 World Cup 2026 (news, fixtures, standings, stats, highlights)
31
- - 🤖 AI article writing + TTS (multilingual, emotion-aware)
32
- - 🔍 Topic search (8 news sources)
33
- - 🎤 TTS: voice selector + emotion selector + speed control
34
-
35
- ## 🎬 Short AI — Video từ link (scrap YouTube / TikTok / tin tức)
36
-
37
- Short creator có chế độ **"🔗 Video từ link"**: dán link video YouTube / TikTok /
38
- VnExpress / Dân trí / Znews / 24h... → bấm "Lấy video" để xem trước → tạo short
39
- chạy video + ảnh đã chọn bù phần còn thiếu nếu video ngắn hơn giọng đọc.
40
-
41
- ### 🔑 Cài cookies cho YouTube (bỏ chặn "Sign in to confirm you're not a bot")
42
- YouTube đôi khi chặn IP datacenter. Cách khắc phục bằng cookies:
43
-
44
- 1. Cài extension trình duyệt **"Get cookies.txt LOCALLY"** (Chrome/Edge) hoặc
45
- **"cookies.txt"** (Firefox).
46
- 2. Mở `https://www.youtube.com` (đã đăng nhập) → bấm extension → **Export** → ra file `cookies.txt` (định dạng Netscape).
47
- 3. Đưa cookies vào Space bằng **một trong hai cách**:
48
- - **Cách A (khuyến nghị):** Vào Settings của Space
49
- `huggingface.co/spaces/bep40/VNEWS/settings` → **Variables and secrets** →
50
- tạo secret tên **`YT_COOKIES`**, giá trị = toàn bộ nội dung file `cookies.txt`.
51
- - **Cách B:** đặt file `cookies.txt` vào thư mục gốc repo `VNEWS/` và commit
52
- (chú ý: cookies sẽ công khai nếu repo public — ưu tiên Cách A).
53
- 4. Rebuild Space (mỗi lần đổi secret phải **Restart** Space).
54
-
55
- Backend tự đọc `YT_COOKIES` (secret) hoặc `/app/cookies.txt`, ghi thành file tạm
56
- và truyền cho yt-dlp qua `cookiefile`. Không cần sửa code.
57
-
58
- > Lưu ý: cookies có hạn (thường vài tuần). Khi hết hạn, export lại và cập nhật secret.
 
9
  - ml-intern
10
  ---
11
 
12
+ # bep40/vnews
13
+ <!-- build: 2026-06-12T06:45:00 -->
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+ <!-- rebuild: v6.5-final-1781173463 -->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
RESTART_TRIGGER.md DELETED
@@ -1,7 +0,0 @@
1
- trigger rebuild v20260827fptwall
2
-
3
- - FPT wall cards now use .wall-thumb 100% width/height (16:9), identical to Short AI cards
4
- - FPT player opens a scrollable vertical feed interleaving FPT Play + Short AI videos, newest-first
5
- - 16:9 <-> 9:16 ratio toggle (🖥️/📺) works on football highlight slides and Tường AI slide player
6
- - Cache-busting: app_v2.js?v=20260827fptwall
7
- - FORCE REBUILD: this commit retriggers the Space container with the latest static/app_v2.js
 
 
 
 
 
 
 
 
_run.py CHANGED
@@ -1 +1 @@
1
- from app_v2_entry import app # v5-stable inline bongda proxy
 
1
+ from app_v2_entry import app # v5-stable inline bongda proxy
ai_ext.py CHANGED
@@ -13,16 +13,7 @@ from bs4 import BeautifulSoup
13
  from fastapi import Request, Query
14
  from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
15
 
16
- # Try to import main app, but don't fail if it doesn't exist
17
- try:
18
- from main import app
19
- except ImportError:
20
- # Create a minimal FastAPI app for standalone testing
21
- try:
22
- from fastapi import FastAPI
23
- app = FastAPI()
24
- except Exception:
25
- app = None
26
 
27
  # Import wall store from main.py so we read/write the SAME file
28
  try:
@@ -50,10 +41,6 @@ except ImportError:
50
  def _web_context(topic):
51
  return ""
52
 
53
- # ai_ext alias for backward compatibility
54
- _load_ai_wall = _load_wall
55
- _save_ai_wall = _save_wall
56
-
57
  try:
58
  from huggingface_hub import AsyncInferenceClient
59
  except Exception:
@@ -73,260 +60,1078 @@ except Exception:
73
 
74
 
75
  def _hf_token():
76
- for k in ("HF_TOKEN", "HUGGINGFACE_HUB_API_TOKEN", "HUGGING_FACE_HUB_TOKEN", "HF_API_TOKEN"):
77
  v = os.getenv(k, "").strip()
78
  if v:
79
  return v
80
  return ""
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  def _clean_text(s: str) -> str:
84
- """Clean text for processing."""
85
  s = html_lib.unescape(s or "")
86
- s = re.sub(r"\s+", " ", s)
87
- return s.strip()
88
-
89
 
90
- def _domain(url: str) -> str:
91
- """Extract domain from URL."""
92
  try:
93
- return urlparse(url or "").netloc.replace("www.", "")
94
  except Exception:
95
  return ""
96
 
 
 
97
 
98
- async def qwen_generate(prompt: str, image_url: str = None, max_tokens: int = 1200) -> str:
99
- """Generate text using Llama/Qwen models via Hugging Face Inference API.
100
-
101
- Prioritizes Llama-3.3-70B for better creative/opinion writing.
102
- """
103
- token = _hf_token()
104
- errors = []
105
-
106
- # Try HF router API with multiple models - Llama FIRST for opinion writing
107
- if token:
108
- models = [
109
- os.getenv("QWEN_VL_MODEL", ""),
110
- "meta-llama/Llama-3.3-70B-Instruct", # FIRST - best for opinion/analysis
111
- "Qwen/Qwen2.5-VL-7B-Instruct",
112
- "Qwen/Qwen2.5-72B-Instruct",
113
- ]
114
- # Deduplicate while preserving order
115
- seen = set()
116
- models = [m for m in models if m and m not in seen and not seen.add(m)]
117
-
118
- headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
119
-
120
- for model in models:
121
- try:
122
- is_vl = "VL" in model and image_url
123
- if is_vl:
124
- user_content = [
125
- {"type": "image_url", "image_url": {"url": image_url}},
126
- {"type": "text", "text": prompt}
127
- ]
128
- else:
129
- user_content = prompt
130
-
131
- payload = {
132
- "model": model,
133
- "messages": [
134
- {"role": "system", "content": "Bạn là nhà báo phản biện chuyên nghiệp. Luôn viết theo quan điểm cá nhân, phân tích sâu, không sao chép nguyên văn nguồn tin."},
135
- {"role": "user", "content": user_content},
136
- ],
137
- "max_tokens": min(int(max_tokens or 2000), 2500),
138
- "temperature": 0.75,
139
- "top_p": 0.9,
140
- }
141
-
142
- r = requests.post(
143
- "https://router.huggingface.co/v1/chat/completions",
144
- headers=headers,
145
- json=payload,
146
- timeout=95
147
- )
148
-
149
- if r.status_code >= 300:
150
- errors.append(f"{model}: HTTP {r.status_code}")
151
- continue
152
-
153
- j = r.json()
154
- txt = (j.get("choices", [{}])[0].get("message", {}).get("content") or "").strip()
155
-
156
- if txt:
157
- return txt
158
-
159
- errors.append(f"{model}: empty response")
160
-
161
- except Exception as e:
162
- errors.append(f"{model}: {type(e).__name__}")
163
-
164
- # Fallback: extractive summary from prompt
165
- LAST_QWEN_ERROR = errors[-3:] if errors else "unknown error"
166
- return _fallback_summary_from_prompt(prompt, max_units=6)
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
- def _fallback_summary_from_prompt(prompt: str, max_units: int = 6) -> str:
170
- """Generate a simple fallback summary when AI is unavailable."""
171
- text = prompt or ""
172
- for marker in ["Nội dung nguồn:", "Nội dung bài:", "Nội dung gốc:", "Nội dung:", "Nguồn/bối c���nh internet:"]:
173
- if marker in text:
174
- text = text.split(marker, 1)[1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  break
176
- text = re.sub(r"https?://\S+", "", text)
177
- text = re.sub(r"\s+", " ", text).strip()
178
-
179
- # Split into sentences
180
- sentences = re.split(r"(?<=[.!?])\s+(?=[A-ZÀ-Ỹ0-9])", text)
181
- units = []
182
- for s in sentences:
183
- s = _clean_text(s)
184
- if len(s) >= 30:
185
- units.append(s)
186
-
187
- if units:
188
- result_units = units[:max_units]
189
- return "\n".join("• " + u for u in result_units)
190
- if text:
191
- chunks = []
192
- for i in range(0, min(len(text), max_units * 300), 280):
193
- chunk = _clean_text(text[i:i+300])
194
- if chunk and chunk not in chunks:
195
- chunks.append(chunk)
196
- if len(chunks) >= max_units:
197
- break
198
- if chunks:
199
- return "\n".join("• " + c for c in chunks)
200
- return "• Không có đủ nội dung để tóm tắt."
201
-
202
- # ===== URL scraping & article processing =====
203
- 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"}
204
 
205
- try:
206
- _shorts_base = "/data" if os.path.isdir("/data") else os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
207
- except Exception:
208
- _shorts_base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
209
- SHORTS_DIR = os.path.join(_shorts_base, "ai_shorts")
210
- os.makedirs(SHORTS_DIR, exist_ok=True)
211
 
212
- import random as _random2
213
- from datetime import datetime, timezone, timedelta
214
- _VN_TZ = timezone(timedelta(hours=7))
 
 
 
 
 
 
 
 
 
 
215
 
 
 
 
 
 
 
 
 
216
 
217
- def _safe_name(filename: str) -> str:
218
- """Sanitize filename."""
219
- return re.sub(r"[^a-zA-Z0-9_.-]", "_", filename)[:120]
 
 
220
 
 
 
 
221
 
222
- def pollinations_image_url(topic: str) -> str:
223
- """Generate a placeholder image URL via Pollinations."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  try:
225
- return "https://image.pollinations.ai/prompt/" + quote("Vietnamese editorial illustration, " + topic, safe="") + "?width=1024&height=576&nologo=true"
 
 
 
 
 
 
 
 
 
 
 
226
  except Exception:
227
- return ""
 
 
 
 
 
 
 
228
 
229
 
230
- def _download_image(url: str, fallback_title: str, out_path: str) -> str:
231
- """Download an image from URL or create a placeholder."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  if url:
 
 
 
 
 
233
  try:
234
- r = requests.get(url, headers=HEADERS, timeout=15)
235
- if r.status_code == 200 and len(r.content) > 1200:
236
- os.makedirs(os.path.dirname(out_path), exist_ok=True)
237
  with open(out_path, "wb") as f:
238
  f.write(r.content)
 
 
239
  return out_path
240
  except Exception:
241
  pass
242
- # Fallback: create a placeholder image
243
  try:
244
- from PIL import Image, ImageDraw, ImageFont
245
- img = Image.new("RGB", (1080, 760), (24, 24, 24))
246
- draw = ImageDraw.Draw(img)
247
- try:
248
- font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 48)
249
- except Exception:
250
- font = None
251
- text = (fallback_title or "VNEWS")[:40]
252
- try:
253
- bbox = draw.textbbox((0, 0), text, font=font)
254
- tw = bbox[2] - bbox[0]
255
- except Exception:
256
- tw = len(text) * 24
257
- draw.text(((1080 - tw) // 2, 330), text, fill=(255, 255, 255), font=font)
258
- os.makedirs(os.path.dirname(out_path), exist_ok=True)
259
- img.save(out_path, quality=90)
260
- return out_path
261
  except Exception:
 
 
 
262
  return out_path
 
263
 
264
 
265
- def scrape_any_url(url: str) -> dict:
266
- """Scrape article content from any URL."""
267
- if not url or not url.startswith("http"):
268
- return {"title": "", "text": "", "summary": "", "image": "", "og_image": "", "via": ""}
269
- try:
270
- r = requests.get(url, headers=HEADERS, timeout=15, allow_redirects=True)
271
- if r.status_code != 200 or not r.text:
272
- return {"title": "", "text": "", "summary": "", "image": "", "og_image": "", "via": _domain(url)}
273
- r.encoding = "utf-8"
274
- soup = BeautifulSoup(r.text, "lxml")
275
- for tag in soup.find_all(["script", "style", "nav", "footer", "aside", "form", "noscript", "iframe", ".ads", ".ad", ".banner-ads", ".fb-comments", ".fb-root", ".social-share", ".related-news", ".breadcrumb"]):
276
- tag.decompose()
277
- title = ""
278
- ogt = soup.find("meta", property="og:title")
279
- if ogt:
280
- title = ogt.get("content", "")
281
- h1 = soup.find("h1")
282
- if not title and h1:
283
- title = h1.get_text(strip=True)
284
- if not title:
285
- t = soup.find("title")
 
 
 
 
 
 
 
 
286
  if t:
287
- title = t.get_text(strip=True)
288
- og_image = ""
289
- ogi = soup.find("meta", property="og:image")
290
- if ogi:
291
- og_image = ogi.get("content", "")
292
- if og_image.startswith("//"):
293
- og_image = "https:" + og_image
294
- summary = ""
295
- ogd = soup.find("meta", property="og:description") or soup.find("meta", attrs={"name": "description"})
296
- if ogd:
297
- summary = ogd.get("content", "")[:500]
298
- body_text = []
299
- for sel in ["article", ".singular-content", ".detail-content", ".fck_detail", ".content-detail", ".knc-content", "main", ".cms-body", ".article__body", ".post-content", ".entry-content"]:
300
- el = soup.select_one(sel)
301
- if el and len(el.find_all("p")) >= 2:
302
- for p in el.find_all("p"):
303
- t = _clean_text(p.get_text(strip=True))
304
- if t and len(t) > 30:
305
- body_text.append(t)
306
- break
307
- if not body_text and soup.body:
308
- for p in soup.body.find_all("p"):
309
- t = _clean_text(p.get_text(strip=True))
310
- if t and len(t) > 30:
311
- body_text.append(t)
312
- text = "\n".join(body_text)
313
- return {"title": _clean_text(title), "text": text, "summary": _clean_text(summary), "image": og_image, "og_image": og_image, "via": _domain(url), "url": url}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  except Exception as e:
315
- return {"title": "", "text": "", "summary": "", "image": "", "og_image": "", "via": _domain(url)}
 
316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
 
318
- def make_post(title: str, text: str, img: str, url: str, kind: str = "auto", sources: list = None) -> dict:
319
- """Create a wall post dict."""
320
- import random as _r2
321
- now = int(time.time() * 1000)
322
  return {
323
- "id": str(now) + str(_r2.randint(100, 999)),
324
- "title": (title or "Bài viết")[:200],
325
- "text": (text or "")[:5000],
326
- "img": img or "",
327
- "url": url or "",
328
- "kind": kind or "auto",
329
- "sources": sources or [],
330
- "created": now,
331
- "created_str": datetime.now(_VN_TZ).strftime("%H:%M %d/%m/%Y"),
332
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  from fastapi import Request, Query
14
  from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
15
 
16
+ from main import app
 
 
 
 
 
 
 
 
 
17
 
18
  # Import wall store from main.py so we read/write the SAME file
19
  try:
 
41
  def _web_context(topic):
42
  return ""
43
 
 
 
 
 
44
  try:
45
  from huggingface_hub import AsyncInferenceClient
46
  except Exception:
 
60
 
61
 
62
  def _hf_token():
63
+ for k in ("HF_TOKEN", "HUGGINGFACEHUB_API_TOKEN", "HUGGING_FACE_HUB_TOKEN", "HF_API_TOKEN"):
64
  v = os.getenv(k, "").strip()
65
  if v:
66
  return v
67
  return ""
68
 
69
+ HF_TOKEN = _hf_token()
70
+ QWEN_VL_MODEL = os.getenv("QWEN_VL_MODEL", "Qwen/Qwen2.5-VL-7B-Instruct")
71
+ # Fast TEXT models for summaries that don't need vision (much faster than the VL model).
72
+ QWEN_TEXT_MODELS = [m.strip() for m in os.getenv(
73
+ "QWEN_TEXT_MODELS",
74
+ "Qwen/Qwen2.5-72B-Instruct,meta-llama/Llama-3.3-70B-Instruct,Qwen/Qwen2.5-7B-Instruct"
75
+ ).split(",") if m.strip()]
76
+ _WORKING_MODEL_TEXT = None # cached last-working text model
77
+ _WORKING_MODEL_VL = None # cached last-working vision model
78
+ DATA_DIR = "/data" if os.path.isdir("/data") else "/app/data"
79
+ SHORTS_DIR = os.path.join(DATA_DIR, "ai_shorts")
80
+ HEADERS = {
81
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
82
+ "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8"
83
+ }
84
+ LAST_QWEN_ERROR = ""
85
+
86
+ # ===== TTS VOICE CONFIG =====
87
+ # Multilingual neural voices grouped by country/language
88
+ # Format: key -> {id, gender, name, country, lang, flag}
89
+ TTS_VOICES = {
90
+ # === VIETNAM (edge-tts) ===
91
+ "hoaimy": {"id": "vi-VN-HoaiMyNeural", "gender": "female", "name": "Hoài My", "country": "Việt Nam", "lang": "vi", "flag": "🇻🇳", "engine": "edge"},
92
+ "namminh": {"id": "vi-VN-NamMinhNeural", "gender": "male", "name": "Nam Minh", "country": "Việt Nam", "lang": "vi", "flag": "🇻🇳", "engine": "edge"},
93
+ # === gTTS (Google, tiếng Việt cơ bản) ===
94
+ "gtts_vi": {"id": "gtts", "gender": "female", "name": "gTTS Google", "country": "Việt Nam", "lang": "vi", "flag": "🇻🇳", "engine": "gtts"},
95
+ # === MULTILINGUAL (đa ngôn ngữ — đọc được tiếng Việt + nhiều thứ tiếng) ===
96
+ "en_au_william": {"id": "en-AU-WilliamMultilingualNeural", "gender": "male", "name": "William (Đa NN)", "country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
97
+ "en_us_andrew": {"id": "en-US-AndrewMultilingualNeural", "gender": "male", "name": "Andrew (Đa NN)", "country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
98
+ "en_us_ava": {"id": "en-US-AvaMultilingualNeural", "gender": "female", "name": "Ava (Đa NN)", "country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
99
+ "en_us_brian": {"id": "en-US-BrianMultilingualNeural", "gender": "male", "name": "Brian (Đa NN)", "country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
100
+ "en_us_emma": {"id": "en-US-EmmaMultilingualNeural", "gender": "female", "name": "Emma (Đa NN)", "country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
101
+ "fr_vivienne": {"id": "fr-FR-VivienneMultilingualNeural","gender": "female", "name": "Vivienne (Đa NN)","country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
102
+ "fr_remy": {"id": "fr-FR-RemyMultilingualNeural", "gender": "male", "name": "Rémy (Đa NN)", "country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
103
+ "de_seraphina": {"id": "de-DE-SeraphinaMultilingualNeural","gender": "female","name": "Seraphina (Đa NN)","country": "Đa ngôn ngữ","lang": "multi", "flag": "🌐", "engine": "edge"},
104
+ "de_florian": {"id": "de-DE-FlorianMultilingualNeural", "gender": "male", "name": "Florian (Đa NN)", "country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
105
+ "it_giuseppe": {"id": "it-IT-GiuseppeMultilingualNeural","gender": "male", "name": "Giuseppe (Đa NN)","country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
106
+ "ko_hyunsu": {"id": "ko-KR-HyunsuMultilingualNeural", "gender": "male", "name": "Hyunsu (Đa NN)", "country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
107
+ "pt_thalita": {"id": "pt-BR-ThalitaMultilingualNeural", "gender": "female", "name": "Thalita (Đa NN)", "country": "Đa ngôn ngữ", "lang": "multi", "flag": "🌐", "engine": "edge"},
108
+ }
109
+ TTS_DEFAULT_VOICE = "hoaimy"
110
+ TTS_DEFAULT_SPEED = 1.2 # 1.2x speed for faster reading
111
+
112
+ # Topic -> voice mapping (auto-detect based on topic keywords)
113
+ TOPIC_VOICE_MAP = {
114
+ # Sports -> male voice
115
+ "bóng đá": "namminh", "thể thao": "namminh", "world cup": "namminh",
116
+ "premier league": "namminh", "champions league": "namminh", "la liga": "namminh",
117
+ "serie a": "namminh", "bundesliga": "namminh", "v-league": "namminh",
118
+ "tennis": "namminh", "olympic": "namminh", "f1": "namminh", "moto": "namminh",
119
+ # Lifestyle/Health/Entertainment -> female voice
120
+ "sức khỏe": "hoaimy", "làm đẹp": "hoaimy", "giải trí": "hoaimy",
121
+ "âm nhạc": "hoaimy", "phim": "hoaimy", "thời trang": "hoaimy",
122
+ "ẩm thực": "hoaimy", "du lịch": "hoaimy", "gia đình": "hoaimy",
123
+ "tình yêu": "hoaimy", "hôn nhân": "hoaimy", "mẹ và bé": "hoaimy",
124
+ # Tech/Science -> male voice
125
+ "công nghệ": "namminh", "ai": "namminh", "robot": "namminh",
126
+ "khoa học": "namminh", "vũ trụ": "namminh", "điện thoại": "namminh",
127
+ "laptop": "namminh", "game": "namminh",
128
+ # News/Politics/Economy -> male voice
129
+ "chính trị": "namminh", "kinh tế": "namminh", "tài chính": "namminh",
130
+ "chứng khoán": "namminh", "ngân hàng": "namminh", "thị trường": "namminh",
131
+ "xã hội": "namminh", "pháp luật": "namminh", "giáo dục": "namminh",
132
+ }
133
+
134
+
135
+ def _detect_voice_for_topic(title: str, text: str) -> str:
136
+ """Auto-detect the best voice based on topic keywords."""
137
+ combined = (title + " " + text[:500]).lower()
138
+ for keyword, voice_id in TOPIC_VOICE_MAP.items():
139
+ if keyword in combined:
140
+ return voice_id
141
+ return TTS_DEFAULT_VOICE
142
+
143
 
144
+ # ===== EMOTION (CẢM XÚC) FOR TTS =====
145
+ # edge-tts does NOT support Azure express-as styles, so emotion is simulated
146
+ # with pitch + rate(speed multiplier) + volume. Each preset is a delta.
147
+ # rate_mul multiplies the user/auto speed; pitch is absolute Hz; volume is percent.
148
+ EMOTION_PRESETS = {
149
+ "vui": {"label": "Vui tươi", "emoji": "😊", "rate_mul": 1.06, "pitch": "+15Hz", "volume": "+6%"},
150
+ "hao_hung": {"label": "Hào hứng", "emoji": "🔥", "rate_mul": 1.12, "pitch": "+24Hz", "volume": "+12%"},
151
+ "nghiem": {"label": "Nghiêm túc", "emoji": "📰", "rate_mul": 1.00, "pitch": "-3Hz", "volume": "+0%"},
152
+ "tram": {"label": "Trầm ấm", "emoji": "🌙", "rate_mul": 0.94, "pitch": "-10Hz", "volume": "+0%"},
153
+ "buon": {"label": "Buồn/Xúc động", "emoji": "💧", "rate_mul": 0.88, "pitch": "-18Hz", "volume": "-4%"},
154
+ "trung_tinh":{"label": "Trung tính", "emoji": "🎙️", "rate_mul": 1.00, "pitch": "+0Hz", "volume": "+0%"},
155
+ }
156
+ EMOTION_DEFAULT = "trung_tinh"
157
+
158
+ # Topic keyword -> emotion. Checked in order; first match wins.
159
+ TOPIC_EMOTION_MAP = {
160
+ # Sports / wins -> excited
161
+ "chiến thắng": "hao_hung", "vô địch": "hao_hung", "world cup": "hao_hung",
162
+ "bóng đá": "hao_hung", "thể thao": "hao_hung", "ghi bàn": "hao_hung",
163
+ "champions league": "hao_hung", "premier league": "hao_hung", "chung kết": "hao_hung",
164
+ "olympic": "hao_hung", "kỷ lục": "hao_hung",
165
+ # Entertainment / lifestyle / good news -> cheerful
166
+ "giải trí": "vui", "âm nhạc": "vui", "phim": "vui", "lễ hội": "vui",
167
+ "du lịch": "vui", "ẩm thực": "vui", "thời trang": "vui", "ra mắt": "vui",
168
+ "khai trương": "vui", "tin vui": "vui", "hạnh phúc": "vui",
169
+ # Sad / accidents / loss -> sad
170
+ "tai nạn": "buon", "qua đời": "buon", "tử vong": "buon", "thiệt mạng": "buon",
171
+ "động đất": "buon", "lũ lụt": "buon", "thiên tai": "buon", "cháy": "buon",
172
+ "tang lễ": "buon", "mất tích": "buon", "thương tâm": "buon",
173
+ # Health / science / calm -> calm warm
174
+ "sức khỏe": "tram", "y tế": "tram", "bệnh": "tram", "dinh dưỡng": "tram",
175
+ "tâm lý": "tram", "thiền": "tram", "giấc ngủ": "tram",
176
+ # News / politics / economy / law -> serious
177
+ "chính trị": "nghiem", "kinh tế": "nghiem", "tài chính": "nghiem",
178
+ "chứng khoán": "nghiem", "pháp luật": "nghiem", "tòa án": "nghiem",
179
+ "ngân hàng": "nghiem", "thị trường": "nghiem", "lạm phát": "nghiem",
180
+ "công nghệ": "nghiem", "ai": "nghiem", "khoa học": "nghiem", "giáo dục": "nghiem",
181
+ }
182
+
183
+
184
+ def _detect_emotion_for_topic(title: str, text: str) -> str:
185
+ """Auto-detect emotion (cảm xúc) from topic/content keywords."""
186
+ combined = (title + " " + text[:600]).lower()
187
+ for keyword, emo in TOPIC_EMOTION_MAP.items():
188
+ if keyword in combined:
189
+ return emo
190
+ return EMOTION_DEFAULT
191
+
192
+
193
+ def _detect_voice_emotion(title: str, text: str) -> tuple:
194
+ """Return (voice_id, emotion_id) auto-chosen for the article's topic."""
195
+ return _detect_voice_for_topic(title, text), _detect_emotion_for_topic(title, text)
196
+
197
+
198
+ # ===== TEXT HELPERS =====
199
  def _clean_text(s: str) -> str:
 
200
  s = html_lib.unescape(s or "")
201
+ return re.sub(r"\s+", " ", s).strip()
 
 
202
 
203
+ def _domain(u):
 
204
  try:
205
+ return urlparse(u).netloc.replace("www.", "")
206
  except Exception:
207
  return ""
208
 
209
+ def _safe_name(s):
210
+ return re.sub(r"[^a-zA-Z0-9_-]+", "_", str(s))[:80]
211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
+ # ===== CLEAN AI OUTPUT =====
214
+ def _clean_ai_output(text: str) -> str:
215
+ """Remove markdown artifacts, instruction leakage, and aggressively dedup content."""
216
+ if not text:
217
+ return ""
218
+ # Remove markdown headings, bold, italic, horizontal rules
219
+ text = re.sub(r'^#{1,6}\s+', '', text, flags=re.MULTILINE)
220
+ text = re.sub(r'\*\*([^*]+)\*\*', r'\1', text)
221
+ text = re.sub(r'\*([^*]+)\*', r'\1', text)
222
+ text = re.sub(r'^---+\s*$', '', text, flags=re.MULTILINE)
223
+ text = re.sub(r'^[-*_]{3,}\s*$', '', text, flags=re.MULTILINE)
224
+ # Remove common AI instruction leakage phrases (entire line)
225
+ leakage = [
226
+ r'Dưới đây là', r'Theo yêu cầu', r'Tôi sẽ viết', r'Tôi sẽ tóm tắt',
227
+ r'Đây là bài', r'Đây là nội dung', r'Bài viết sau đây',
228
+ r'Nội dung (tóm tắt|chính)', r'Nhiệm vụ', r'Vai trò', r'Tôi là',
229
+ r'Dựa trên.*tôi sẽ', r'Hãy', r'Bạn cần', r'Đọc bài viết',
230
+ r'Tôi xin', r'Xin chào', r'Trân trọng', r'Kính thưa',
231
+ r'Dựa trên.*dưới đây', r'Sau đây là', r'Dưới đây là bài',
232
+ ]
233
+ for phrase in leakage:
234
+ text = re.sub(r'^' + phrase + r'[^\n]*\n?', '', text, flags=re.MULTILINE | re.IGNORECASE)
235
+ text = re.sub(r'\n{3,}', '\n\n', text)
236
+ # --- Aggressive dedup: split into sentences, remove any that repeats ---
237
+ # Normalize: collapse whitespace, strip
238
+ def _norm(s):
239
+ return re.sub(r'\s+', ' ', s.strip().lower())
240
+
241
+ # Split by sentence-ending punctuation (keep delimiters)
242
+ raw_parts = re.split(r'(?<=[.!?])\s+', text.strip())
243
+ seen_sentences = set()
244
+ unique_parts = []
245
+ for part in raw_parts:
246
+ n = _norm(part)
247
+ # Skip near-duplicate: if >70% of an existing seen sentence matches
248
+ is_dup = False
249
+ if n:
250
+ if n in seen_sentences:
251
+ is_dup = True
252
+ else:
253
+ partial = re.sub(r'\W+', '', n)
254
+ for seen in seen_sentences:
255
+ seen_clean = re.sub(r'\W+', '', seen)
256
+ # Check substring match for very similar sentences
257
+ if partial and seen_clean and (
258
+ partial in seen_clean or seen_clean in partial
259
+ ):
260
+ shorter = min(len(partial), len(seen_clean))
261
+ longer = max(len(partial), len(seen_clean))
262
+ if shorter > 20 and shorter / longer > 0.75:
263
+ is_dup = True
264
+ break
265
+ if is_dup:
266
+ continue
267
+ if n:
268
+ seen_sentences.add(n)
269
+ unique_parts.append(part)
270
+
271
+ result = ' '.join(unique_parts).strip()
272
+ # Final pass: remove any remaining consecutive duplicate lines
273
+ lines = result.split('\n')
274
+ final_lines = []
275
+ prev_line = ""
276
+ for line in lines:
277
+ stripped = line.strip()
278
+ if stripped and stripped == prev_line:
279
+ continue
280
+ final_lines.append(line)
281
+ prev_line = stripped
282
+ result = '\n'.join(final_lines).strip()
283
+ return result
284
+
285
+
286
+ # ===== EXTRACT ALL IMAGES FROM ARTICLE =====
287
+ def _extract_all_images(soup, base_url: str) -> List[Dict]:
288
+ """Extract ALL content images from an article page using multi-strategy approach."""
289
+ images = []
290
+ seen_urls = set()
291
+ skip_patterns = [
292
+ "avatar", "icon", "logo", "button", "banner-ad", "tracking",
293
+ "beacon", "pixel", "1x1", "spacer", "emoji", "sprite", "placeholder",
294
+ "advertisement", "ads", "widget", "sidebar", "footer-logo",
295
+ ]
296
+
297
+ def _add_image(src: str, alt: str = "", source_tag: str = "img"):
298
+ if not src or src.startswith("data:"):
299
+ return
300
+ abs_url = urljoin(base_url, src.strip())
301
+ if abs_url in seen_urls:
302
+ return
303
+ # Skip non-content images by URL pattern
304
+ if any(p in abs_url.lower() for p in skip_patterns):
305
+ return
306
+ # Skip very small images (likely icons)
307
+ try:
308
+ parsed = urlparse(abs_url)
309
+ path = parsed.path.lower()
310
+ if any(path.endswith(ext) for ext in ['.svg', '.ico', '.gif']):
311
+ return
312
+ except Exception:
313
+ pass
314
+ seen_urls.add(abs_url)
315
+ images.append({"url": abs_url, "alt": alt, "source": source_tag})
316
+
317
+ # Strategy 1: Standard <img> tags with all lazy-load attributes
318
+ for img in soup.find_all("img"):
319
+ src = (img.get("src") or img.get("data-src") or img.get("data-lazy-src") or
320
+ img.get("data-original") or img.get("data-srcset", "").split(",")[0].strip().split(" ")[0])
321
+ _add_image(src, alt=img.get("alt", ""), source_tag="img")
322
+
323
+ # Strategy 2: srcset on <img>
324
+ for img in soup.find_all("img", srcset=True):
325
+ for part in img["srcset"].split(","):
326
+ part = part.strip()
327
+ if part:
328
+ _add_image(part.split(" ")[0], alt=img.get("alt", ""), source_tag="srcset")
329
+
330
+ # Strategy 3: <picture> with <source>
331
+ for picture in soup.find_all("picture"):
332
+ for source in picture.find_all("source"):
333
+ srcset = source.get("srcset", "")
334
+ for part in srcset.split(","):
335
+ part = part.strip()
336
+ if part:
337
+ _add_image(part.split(" ")[0], source_tag="picture/srcset")
338
+ fallback_img = picture.find("img")
339
+ if fallback_img:
340
+ _add_image(
341
+ fallback_img.get("src") or fallback_img.get("data-src"),
342
+ alt=fallback_img.get("alt", ""),
343
+ source_tag="picture/img"
344
+ )
345
+
346
+ # Strategy 4: WordPress CMS patterns
347
+ for img in soup.find_all("img", class_=re.compile(r"wp-image|size-large|size-full|aligncenter")):
348
+ _add_image(img.get("data-src") or img.get("src"),
349
+ alt=img.get("alt", ""), source_tag="wp-image")
350
+
351
+ # Strategy 5: Background images in style attributes
352
+ for tag in soup.find_all(style=re.compile(r"background-image")):
353
+ for m in re.findall(r'url\(["\']?(.*?)["\']?\)', tag.get("style", "")):
354
+ _add_image(m, source_tag="background-style")
355
+
356
+ # Strategy 6: og:image (featured/hero image)
357
+ og_image = soup.find("meta", property="og:image")
358
+ if og_image and og_image.get("content"):
359
+ _add_image(og_image["content"], source_tag="og:image")
360
 
361
+ # Strategy 7: twitter:image
362
+ tw_image = soup.find("meta", attrs={"name": "twitter:image"})
363
+ if tw_image and tw_image.get("content"):
364
+ _add_image(tw_image["content"], source_tag="twitter:image")
365
+
366
+ # Strategy 8: <figure> with <figcaption>
367
+ for figure in soup.find_all("figure"):
368
+ img = figure.find("img")
369
+ if img:
370
+ src = img.get("data-src") or img.get("src")
371
+ figcaption = figure.find("figcaption")
372
+ alt = figcaption.get_text(strip=True) if figcaption else img.get("alt", "")
373
+ _add_image(src, alt=alt, source_tag="figure")
374
+
375
+ # Strategy 9: <a> tags linking to images
376
+ for a in soup.find_all("a", href=True):
377
+ href = a["href"]
378
+ if any(href.lower().endswith(ext) for ext in [".jpg", ".jpeg", ".png", ".webp", ".gif"]):
379
+ _add_image(href, alt=a.get_text(strip=True)[:80], source_tag="link")
380
+
381
+ return images
382
+
383
+
384
+ # ===== JINA READER =====
385
+ def _reader_url(target_url: str) -> str:
386
+ safe = quote(target_url, safe=":/?#[]@!$&'()*+,;=%")
387
+ return "https://r.jina.ai/http://" + safe
388
+
389
+ def jina_reader_markdown(url: str) -> str:
390
+ jr = _reader_url(url)
391
+ r = requests.get(jr, headers={"Accept": "text/markdown,text/plain,*/*", "X-Return-Format": "markdown", "User-Agent": "Mozilla/5.0"}, timeout=35)
392
+ r.raise_for_status()
393
+ return r.text or ""
394
+
395
+ def _parse_jina_markdown(md: str, url: str):
396
+ lines = [x.rstrip() for x in (md or "").splitlines()]
397
+ title = ""; first_image = ""; all_images = []; content_lines = []; in_content = False
398
+ for ln in lines:
399
+ if ln.startswith("Title:") and not title:
400
+ title = _clean_text(ln.replace("Title:", "", 1)); continue
401
+ if ln.startswith("URL Source:"):
402
+ continue
403
+ if ln.startswith("Markdown Content:"):
404
+ in_content = True; continue
405
+ # Extract ALL images from markdown ![alt](url)
406
+ for mimg in re.finditer(r'!\[[^\]]*\]\((https?://[^)]+)\)', ln):
407
+ img_url = mimg.group(1)
408
+ if img_url not in all_images:
409
+ all_images.append(img_url)
410
+ if not first_image:
411
+ first_image = img_url
412
+ if in_content or (title and not ln.startswith("Title:")):
413
+ if ln.strip():
414
+ content_lines.append(ln)
415
+ text = "\n".join(content_lines)
416
+ text = re.sub(r'!\[[^\]]*\]\([^)]+\)', '', text)
417
+ paras = []
418
+ for part in re.split(r'\n{2,}|\n(?=#{1,3}\s)', text):
419
+ t = _clean_text(re.sub(r'^#{1,6}\s*', '', part))
420
+ if len(t) >= 40:
421
+ paras.append(t)
422
+ if len(paras) >= 35:
423
  break
424
+ if not title and paras:
425
+ title = paras[0][:90]
426
+ return {"url": url, "title": title or url, "summary": paras[0] if paras else "",
427
+ "text": "\n".join(paras), "image": first_image,
428
+ "images": all_images, "via": "jina"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
 
 
 
 
 
 
 
430
 
431
+ # ===== WEB SCRAPE (with full image extraction) =====
432
+ def _best_content_block(soup):
433
+ best, best_score = None, 0
434
+ for el in soup.find_all(["article", "main", "section", "div"]):
435
+ ps = el.find_all("p")
436
+ txt = " ".join(p.get_text(" ", strip=True) for p in ps)
437
+ score = len(ps) * 100 + len(txt)
438
+ cls = " ".join(el.get("class", []))
439
+ if any(k in cls.lower() for k in ["content", "article", "detail", "body", "post", "entry"]):
440
+ score += 800
441
+ if score > best_score:
442
+ best, best_score = el, score
443
+ return best
444
 
445
+ def scrape_any_url_direct(url: str):
446
+ r = requests.get(url, headers=HEADERS, timeout=18)
447
+ if r.status_code in {401, 403, 406, 409, 429, 451, 503}:
448
+ raise RuntimeError(f"blocked status {r.status_code}")
449
+ r.encoding = "utf-8"
450
+ soup = BeautifulSoup(r.text, "lxml")
451
+ for tag in soup.find_all(["script", "style", "nav", "footer", "aside", "form", "noscript"]):
452
+ tag.decompose()
453
 
454
+ # Title
455
+ title = soup.find("h1").get_text(" ", strip=True) if soup.find("h1") else ""
456
+ if not title:
457
+ ogt = soup.find("meta", property="og:title") or soup.find("meta", attrs={"name": "title"})
458
+ title = ogt.get("content", "") if ogt else (soup.title.get_text(strip=True) if soup.title else "")
459
 
460
+ # Summary
461
+ desc_tag = soup.find("meta", property="og:description") or soup.find("meta", attrs={"name": "description"})
462
+ summary = desc_tag.get("content", "") if desc_tag else ""
463
 
464
+ # Featured image (og:image)
465
+ img_tag = soup.find("meta", property="og:image") or soup.find("meta", attrs={"name": "twitter:image"})
466
+ image = img_tag.get("content", "") if img_tag else ""
467
+ if image and image.startswith("//"):
468
+ image = "https:" + image
469
+
470
+ # Extract ALL images from the article
471
+ all_images = _extract_all_images(soup, url)
472
+ image_urls = [img["url"] for img in all_images]
473
+
474
+ # Ensure featured image is first
475
+ if image and image not in image_urls:
476
+ image_urls.insert(0, image)
477
+ elif image in image_urls:
478
+ image_urls.remove(image)
479
+ image_urls.insert(0, image)
480
+
481
+ # Content paragraphs
482
+ block = _best_content_block(soup) or soup
483
+ paras, seen_p = [], set()
484
+ for p in block.find_all("p"):
485
+ t = _clean_text(p.get_text(" ", strip=True))
486
+ if len(t) >= 40 and t not in seen_p:
487
+ seen_p.add(t)
488
+ paras.append(t)
489
+ if len(paras) >= 35:
490
+ break
491
+
492
+ if not title and paras:
493
+ title = paras[0][:90]
494
+
495
+ return {
496
+ "url": url, "title": title or url, "summary": paras[0] if paras else "",
497
+ "text": "\n".join(paras), "image": image_urls[0] if image_urls else "",
498
+ "images": image_urls, "via": _domain(url)
499
+ }
500
+
501
+ def scrape_any_url(url: str):
502
+ """Try direct scrape first, fall back to Jina Reader."""
503
+ data = scrape_any_url_direct(url)
504
+ raw_text = (data.get("summary", "") + "\n" + data.get("text", "")).strip()
505
+ if len(raw_text) >= 120:
506
+ return data
507
  try:
508
+ md = jina_reader_markdown(url)
509
+ if md:
510
+ jr = _parse_jina_markdown(md, url)
511
+ if jr.get("text"):
512
+ if data.get("title") and data["title"] != url:
513
+ jr["title"] = data["title"]
514
+ if data.get("image"):
515
+ jr["image"] = data["image"]
516
+ if data.get("images"):
517
+ jr["images"] = data["images"]
518
+ jr["via"] = data.get("via", _domain(url)) + " + jina"
519
+ return jr
520
  except Exception:
521
+ pass
522
+ return data
523
+
524
+
525
+ # ===== POLLINATIONS IMAGE =====
526
+ def pollinations_image_url(topic: str) -> str:
527
+ prompt = "editorial illustration, Vietnamese news, " + topic
528
+ return "https://image.pollinations.ai/prompt/" + quote(prompt, safe="") + "?width=1024&height=576&nologo=true"
529
 
530
 
531
+ @app.get("/api/ai/probe")
532
+ async def api_ai_probe():
533
+ """Diagnostic: test which chat models actually work on this token + their latency."""
534
+ import time as _t
535
+ tok = _hf_token()
536
+ out = []
537
+ extra = os.getenv("PROBE_MODELS", "").split(",")
538
+ cand = [m.strip() for m in extra if m.strip()] + [
539
+ "Qwen/Qwen2.5-VL-7B-Instruct", "Qwen/Qwen2.5-VL-3B-Instruct", "Qwen/Qwen2-VL-7B-Instruct",
540
+ "Qwen/Qwen2.5-VL-72B-Instruct", "Qwen/Qwen3-8B", "Qwen/Qwen3-4B", "Qwen/Qwen3-32B",
541
+ "Qwen/Qwen2.5-7B-Instruct-1M", "meta-llama/Llama-3.2-3B-Instruct"]
542
+ seen = set()
543
+ for m in cand:
544
+ if not m or m in seen:
545
+ continue
546
+ seen.add(m)
547
+ t0 = _t.time()
548
+ try:
549
+ c = AsyncInferenceClient(provider="auto", api_key=tok, timeout=40)
550
+ r = await c.chat_completion(model=m, messages=[{"role": "user", "content": "Trả lời đúng 1 từ: xin chào"}], max_tokens=10)
551
+ out.append({"model": m, "ok": True, "sec": round(_t.time() - t0, 1), "txt": (r.choices[0].message.content or "")[:30]})
552
+ except Exception as e:
553
+ out.append({"model": m, "ok": False, "sec": round(_t.time() - t0, 1), "err": (type(e).__name__ + ": " + str(e))[-300:]})
554
+ return JSONResponse({"results": out})
555
+
556
+
557
+ # ===== QWEN AI (strict, concise) =====
558
+ async def qwen_generate(prompt: str, image_url: Optional[str] = None, max_tokens: int = 500, image_urls: Optional[List[str]] = None):
559
+ global LAST_QWEN_ERROR, HF_TOKEN
560
+ HF_TOKEN = _hf_token()
561
+ if not HF_TOKEN:
562
+ LAST_QWEN_ERROR = "Không tìm thấy token"
563
+ return None
564
+ if not AsyncInferenceClient:
565
+ LAST_QWEN_ERROR = "Thiếu huggingface_hub"
566
+ return None
567
+ errors = []; models = []
568
+ has_images = bool(image_urls) or bool(image_url)
569
+ if has_images:
570
+ # Vision needed -> VL models
571
+ candidate = [QWEN_VL_MODEL, "Qwen/Qwen2.5-VL-7B-Instruct", "Qwen/Qwen2.5-VL-3B-Instruct"]
572
+ else:
573
+ # Text-only summary -> FAST text models first, VL only as last resort.
574
+ candidate = QWEN_TEXT_MODELS + [QWEN_VL_MODEL]
575
+ # Use the last-known-working model first to avoid wasting time on unavailable models.
576
+ global _WORKING_MODEL_TEXT, _WORKING_MODEL_VL
577
+ cached_ok = _WORKING_MODEL_VL if has_images else _WORKING_MODEL_TEXT
578
+ if cached_ok and cached_ok in candidate:
579
+ candidate = [cached_ok] + [m for m in candidate if m != cached_ok]
580
+ for m in candidate:
581
+ if m and m not in models:
582
+ models.append(m)
583
+ for model in models:
584
+ try:
585
+ client = AsyncInferenceClient(provider="auto", api_key=HF_TOKEN, timeout=60)
586
+ content = []
587
+ # Collect all images: image_urls list takes priority, fall back to single image_url
588
+ all_img_urls = []
589
+ if image_urls:
590
+ all_img_urls = image_urls[:6] # max 6 images to avoid context overflow
591
+ elif image_url:
592
+ all_img_urls = [image_url]
593
+ for img_u in all_img_urls:
594
+ if img_u and img_u.startswith("http"):
595
+ content.append({"type": "image_url", "image_url": {"url": img_u}})
596
+ content.append({"type": "text", "text": prompt})
597
+ messages = [
598
+ {"role": "system", "content": (
599
+ "Bạn là biên tập viên báo điện tử tiếng Việt. "
600
+ "NHIỆM VỤ: Chỉ TÓM TẮT nội dung, KHÔNG viết lại bài đầy đủ. "
601
+ "QUY TẮC CỨNG: "
602
+ "(1) KHÔNG lặp lại bất kỳ nội dung nào — mỗi ý chỉ xuất hiện ĐÚNG 1 LẦN. "
603
+ "(2) Nếu 2 câu diễn đạt cùng 1 ý → bỏ cây thứ 2. "
604
+ "(3) KHÔNG dùng Markdown (##, **, ---, *). "
605
+ "(4) KHÔNG viết 'Dưới đây là', 'Tôi sẽ', 'Theo yêu cầu', 'Nhiệm vụ', 'Vai trò', 'Đây là bài tóm tắt'. "
606
+ "(5) KHÔNG bịa thông tin ngoài nguồn. "
607
+ "(6) Chỉ viết ĐOẠN VĂN THUẦN, không bullet points. "
608
+ "(7) Tối đa 200 từ. Ngắn gọn, súc tích."
609
+ )},
610
+ {"role": "user", "content": content}
611
+ ]
612
+ resp = await client.chat_completion(model=model, messages=messages, max_tokens=max_tokens, temperature=0.3, top_p=0.8)
613
+ txt = (resp.choices[0].message.content or "").strip()
614
+ if txt:
615
+ LAST_QWEN_ERROR = ""
616
+ if has_images: _WORKING_MODEL_VL = model
617
+ else: _WORKING_MODEL_TEXT = model
618
+ return txt
619
+ except Exception as e:
620
+ errors.append(f"{model}: {type(e).__name__}: {str(e)[:220]}")
621
+ LAST_QWEN_ERROR = " | ".join(errors) or "Qwen không trả nội dung."
622
+ print("[qwen errors]", LAST_QWEN_ERROR)
623
+ return None
624
+
625
+
626
+ # ===== TTS GENERATION =====
627
+ async def _generate_tts_edge(text: str, voice_id: str, speed: float, out_path: str, emotion: str = None):
628
+ """Generate TTS using edge-tts (or gTTS if engine=gtts) with voice, speed & emotion control.
629
+
630
+ Emotion (cảm xúc) is simulated via pitch + rate + volume (edge-tts has no express-as).
631
+ """
632
+ vcfg = TTS_VOICES.get(voice_id, TTS_VOICES[TTS_DEFAULT_VOICE])
633
+ # gTTS engine (no voice/speed/emotion control)
634
+ if vcfg.get("engine") == "gtts":
635
+ _generate_tts_gtts(text, out_path)
636
+ return
637
+ if edge_tts is None:
638
+ raise RuntimeError("edge-tts chưa cài đặt")
639
+ voice = vcfg["id"]
640
+ emo = EMOTION_PRESETS.get(emotion or EMOTION_DEFAULT, EMOTION_PRESETS[EMOTION_DEFAULT])
641
+ # Apply emotion rate multiplier on top of base speed
642
+ eff_speed = speed * emo.get("rate_mul", 1.0)
643
+ pct = int(round((eff_speed - 1.0) * 100))
644
+ rate = f"+{pct}%" if pct >= 0 else f"{pct}%"
645
+ pitch = emo.get("pitch", "+0Hz")
646
+ volume = emo.get("volume", "+0%")
647
+ communicate = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch, volume=volume)
648
+ await communicate.save(out_path)
649
+
650
+ def _generate_tts_gtts(text: str, out_path: str):
651
+ """Fallback TTS using gTTS (no voice/speed control)."""
652
+ if gTTS is None:
653
+ raise RuntimeError("gTTS chưa cài đặt")
654
+ gTTS(text, lang="vi").save(out_path)
655
+
656
+
657
+ # ===== SHORT VIDEO GENERATION (multi-segment: each key point with its own image) =====
658
+ def _download_image(url, fallback_topic, out_path):
659
+ """Download an image (un-proxying our own /api/proxy/img). Falls back to generated image."""
660
  if url:
661
+ u = url
662
+ m = re.search(r'/api/proxy/img\?url=(.+)$', u)
663
+ if m:
664
+ from urllib.parse import unquote
665
+ u = unquote(m.group(1))
666
  try:
667
+ r = requests.get(u, headers={**HEADERS, "Referer": "https://dantri.com.vn/"}, timeout=15)
668
+ if r.status_code == 200 and len(r.content) > 1000:
 
669
  with open(out_path, "wb") as f:
670
  f.write(r.content)
671
+ if Image:
672
+ Image.open(out_path).verify()
673
  return out_path
674
  except Exception:
675
  pass
676
+ gen = pollinations_image_url(fallback_topic)
677
  try:
678
+ r = requests.get(gen, headers=HEADERS, timeout=25)
679
+ if r.status_code == 200 and len(r.content) > 1000:
680
+ with open(out_path, "wb") as f:
681
+ f.write(r.content)
682
+ return out_path
 
 
 
 
 
 
 
 
 
 
 
 
683
  except Exception:
684
+ pass
685
+ if Image:
686
+ Image.new("RGB", (1080, 980), (30, 55, 42)).save(out_path)
687
  return out_path
688
+ raise RuntimeError("Không tạo được ảnh")
689
 
690
 
691
+ def _split_keypoint_sentences(text, max_points=6):
692
+ """Split summary text into key points: prefer bullet markers, else sentences."""
693
+ text = _clean_text(text)
694
+ parts = re.split(r'\s*•\s*', text)
695
+ good = [p.strip() for p in parts if len(p.strip()) > 20]
696
+ if len(good) >= 2:
697
+ # Explicit bullet points: keep each one as-is (never merge).
698
+ return good[:max_points]
699
+ # Fallback: split into sentences and merge orphan short fragments.
700
+ pts = [p.strip() for p in re.split(r'(?<=[.!?])\s+', text) if len(p.strip()) > 20]
701
+ out = []
702
+ for p in pts:
703
+ if out and len(p) < 40:
704
+ out[-1] = (out[-1] + " " + p).strip()
705
+ else:
706
+ out.append(p)
707
+ return out[:max_points] if out else ([text] if text else [])
708
+
709
+
710
+ def _build_keypoints(post, max_points=6):
711
+ """Return [{text, image}] pairing each key point with its own image."""
712
+ slides = post.get("slides") or []
713
+ images = post.get("images") or ([post.get("img")] if post.get("img") else [])
714
+ images = [i for i in images if i]
715
+ if slides:
716
+ kps = []
717
+ for i, s in enumerate(slides[:max_points]):
718
+ t = _clean_text(s.get("text", ""))
719
+ img = s.get("image") or (images[i] if i < len(images) else (images[-1] if images else ""))
720
  if t:
721
+ kps.append({"text": t, "image": img})
722
+ if kps:
723
+ return kps
724
+ points = _split_keypoint_sentences(post.get("text", ""), max_points)
725
+ kps = []
726
+ for i, t in enumerate(points):
727
+ img = images[i] if i < len(images) else (images[-1] if images else "")
728
+ kps.append({"text": t, "image": img})
729
+ if not kps:
730
+ kps = [{"text": _clean_text(post.get("title", "")) or "VNEWS", "image": images[0] if images else ""}]
731
+ return kps
732
+
733
+
734
+ def _wrap_text(draw, text, font, max_w):
735
+ words = text.split()
736
+ lines, cur = [], ""
737
+ for w in words:
738
+ test = (cur + " " + w).strip()
739
+ if draw.textlength(test, font=font) <= max_w:
740
+ cur = test
741
+ else:
742
+ if cur:
743
+ lines.append(cur)
744
+ cur = w
745
+ if cur:
746
+ lines.append(cur)
747
+ return lines
748
+
749
+
750
+ def _make_segment_frame(title, point_text, img_path, idx, total, out_path):
751
+ """Render a 1080x1920 vertical frame: image on top, key point text below."""
752
+ if Image is None:
753
+ raise RuntimeError("Pillow chưa sẵn sàng")
754
+ W, H = 1080, 1920
755
+ IMG_H = 980
756
+ bg = Image.new("RGB", (W, H), (12, 14, 18))
757
+ try:
758
+ im = Image.open(img_path).convert("RGB")
759
+ tr = W / IMG_H
760
+ ir = im.width / im.height
761
+ if ir > tr:
762
+ nh = IMG_H; nw = int(nh * ir)
763
+ else:
764
+ nw = W; nh = int(nw / ir)
765
+ im = im.resize((nw, nh))
766
+ left = (nw - W) // 2; top = (nh - IMG_H) // 2
767
+ im = im.crop((left, top, left + W, top + IMG_H))
768
+ bg.paste(im, (0, 0))
769
+ except Exception:
770
+ pass
771
+ draw = ImageDraw.Draw(bg)
772
+ draw.rectangle((0, IMG_H, W, H), fill=(12, 14, 18))
773
+ try:
774
+ f_label = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 34)
775
+ f_title = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 46)
776
+ f_point = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 52)
777
+ except Exception:
778
+ f_label = f_title = f_point = ImageFont.load_default()
779
+ draw.text((54, IMG_H + 24), "VNEWS · Tường AI", fill=(92, 184, 122), font=f_label)
780
+ cnt = f"{idx + 1}/{total}"
781
+ draw.text((W - 54 - draw.textlength(cnt, font=f_label), IMG_H + 24), cnt, fill=(240, 192, 64), font=f_label)
782
+ y = IMG_H + 86
783
+ for ln in _wrap_text(draw, _clean_text(title), f_title, W - 108)[:2]:
784
+ draw.text((54, y), ln, fill=(255, 255, 255), font=f_title)
785
+ y += 56
786
+ y += 16
787
+ for ln in _wrap_text(draw, _clean_text(point_text), f_point, W - 108)[:11]:
788
+ draw.text((54, y), ln, fill=(225, 230, 235), font=f_point)
789
+ y += 64
790
+ bg.save(out_path, quality=92)
791
+ return out_path
792
+
793
+
794
+ def _ffmpeg_bin():
795
+ return os.environ.get("FFMPEG_BIN", "ffmpeg")
796
+
797
+
798
+ def _audio_duration(path):
799
+ try:
800
+ out = subprocess.run([_ffmpeg_bin(), "-i", path], capture_output=True, text=True, timeout=30).stderr
801
+ m = re.search(r"Duration:\s*(\d+):(\d+):(\d+\.\d+)", out)
802
+ if m:
803
+ h, mi, s = m.groups()
804
+ return int(h) * 3600 + int(mi) * 60 + float(s)
805
+ except Exception:
806
+ pass
807
+ return 0.0
808
+
809
+
810
+ async def _generate_short_video(post, post_id: str, voice_id: str = None, speed: float = None, emotion: str = None) -> str:
811
+ """Generate a multi-segment MP4 short: each key point shown with its OWN image + narration."""
812
+ try:
813
+ os.makedirs(SHORTS_DIR, exist_ok=True)
814
+ out_mp4 = os.path.join(SHORTS_DIR, _safe_name(post_id) + ".mp4")
815
+ if os.path.exists(out_mp4) and voice_id is None and speed is None and emotion is None:
816
+ return "/api/ai/short-file/" + post_id
817
+
818
+ work = os.path.join(SHORTS_DIR, _safe_name(post_id) + "_work")
819
+ os.makedirs(work, exist_ok=True)
820
+
821
+ title = _clean_text(post.get("title", "")) or "VNEWS"
822
+ kps = _build_keypoints(post)
823
+
824
+ # Resolve voice + emotion (auto from topic, or from post, or explicit args)
825
+ auto_voice, auto_emotion = _detect_voice_emotion(post.get("title", ""), post.get("text", ""))
826
+ if voice_id is None:
827
+ voice_id = post.get("voice") or auto_voice
828
+ if emotion is None:
829
+ emotion = post.get("emotion") or auto_emotion
830
+ if speed is None:
831
+ speed = TTS_DEFAULT_SPEED
832
+ vcfg = TTS_VOICES.get(voice_id, TTS_VOICES[TTS_DEFAULT_VOICE])
833
+
834
+ seg_files = []
835
+ ff = _ffmpeg_bin()
836
+ for i, kp in enumerate(kps):
837
+ img_path = os.path.join(work, f"img{i}.jpg")
838
+ frame_path = os.path.join(work, f"frame{i}.jpg")
839
+ audio_path = os.path.join(work, f"voice{i}.mp3")
840
+ seg_mp4 = os.path.join(work, f"seg{i}.mp4")
841
+ _download_image(kp.get("image", ""), title, img_path)
842
+ _make_segment_frame(title, kp["text"], img_path, i, len(kps), frame_path)
843
+ narration = (title + ". " + kp["text"]) if i == 0 else kp["text"]
844
+ try:
845
+ await _generate_tts_edge(narration, voice_id, speed, audio_path, emotion=emotion)
846
+ except Exception as e:
847
+ print(f"[TTS edge-tts error] {e}, falling back to gTTS")
848
+ if gTTS:
849
+ _generate_tts_gtts(narration, audio_path)
850
+ else:
851
+ return ""
852
+ dur = _audio_duration(audio_path)
853
+ if dur < 1.0:
854
+ dur = 2.0
855
+ cmd = [ff, "-y", "-loop", "1", "-i", frame_path, "-i", audio_path,
856
+ "-c:v", "libx264", "-tune", "stillimage", "-pix_fmt", "yuv420p",
857
+ "-t", f"{dur + 0.4:.2f}", "-c:a", "aac", "-b:a", "128k", "-ar", "44100",
858
+ "-vf", "scale=1080:1920", "-r", "25", seg_mp4]
859
+ subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180)
860
+ seg_files.append(seg_mp4)
861
+
862
+ if not seg_files:
863
+ return ""
864
+ if len(seg_files) == 1:
865
+ os.replace(seg_files[0], out_mp4)
866
+ return "/api/ai/short-file/" + post_id
867
+
868
+ listfile = os.path.join(work, "concat.txt")
869
+ with open(listfile, "w", encoding="utf-8") as f:
870
+ f.write("\n".join(f"file '{s}'" for s in seg_files))
871
+ cmd = [ff, "-y", "-f", "concat", "-safe", "0", "-i", listfile,
872
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", out_mp4]
873
+ subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300)
874
+ return "/api/ai/short-file/" + post_id
875
  except Exception as e:
876
+ print(f"[short video error] {e}")
877
+ return ""
878
 
879
+ import threading as _threading
880
+ def _spawn_background_video(post):
881
+ """Generate the short video in a BACKGROUND thread so the rewrite/topic endpoint
882
+ can return immediately. When done, persist the video URL onto the wall post.
883
+ This is the main fix for 'rewrite tu cac nguon tin qua lau' — the user gets the
884
+ text post instantly; the video appears shortly after (or via the 'Tao Video' button)."""
885
+ pid = post.get("id")
886
+ if not pid:
887
+ return
888
+ def _run():
889
+ try:
890
+ loop = asyncio.new_event_loop()
891
+ asyncio.set_event_loop(loop)
892
+ video_url = loop.run_until_complete(_generate_short_video(post, pid))
893
+ loop.close()
894
+ if video_url:
895
+ posts = _load_wall()
896
+ for i, p in enumerate(posts):
897
+ if str(p.get("id")) == str(pid):
898
+ posts[i]["video"] = video_url
899
+ break
900
+ _save_wall(posts)
901
+ print(f"[bg-video] done {pid} -> {video_url}")
902
+ except Exception as e:
903
+ print(f"[bg-video] error {pid}: {e}")
904
+ _threading.Thread(target=_run, daemon=True).start()
905
 
906
+ # ===== MAKE POST =====
907
+ def make_post(title, text, image, source_url, kind, sources=None, images=None, voice=None, emotion=None):
908
+ # Auto-pick voice + emotion from the article topic when not provided
909
+ auto_voice, auto_emotion = _detect_voice_emotion(title or "", text or "")
910
  return {
911
+ "id": str(int(time.time() * 1000)) + str(random.randint(100, 999)),
912
+ "title": title, "text": text, "img": image, "url": source_url,
913
+ "kind": kind, "sources": sources or [], "video": "",
914
+ "images": images or [], "ts": int(time.time()),
915
+ "voice": voice or auto_voice,
916
+ "emotion": emotion or auto_emotion,
 
 
 
917
  }
918
+
919
+
920
+ # ===== SHARED PROMPT BUILDER =====
921
+ def _build_rewrite_prompt(title: str, raw: str, images: List[str] = None) -> str:
922
+ image_info = ""
923
+ if images:
924
+ num = len(images)
925
+ if num == 1:
926
+ image_info = "\n\nBài viết có 1 ảnh minh họa. Hãy tham khảo ảnh để hiểu ngữ cảnh (nếu phù hợp)."
927
+ else:
928
+ image_info = f"\n\nBài viết có {num} ảnh minh họa. Hãy tham khảo tất cả ảnh để hiểu ngữ cảnh và bổ sung thông tin cho bài viết (nếu phù hợp)."
929
+
930
+ return f"""Tóm tắt bài viết sau thành bài TÓM TẮT đăng Tường AI.
931
+
932
+ QUY TẮC BẮT BUỘC:
933
+ 1. Chỉ viết TÓM TẮT các ý chính. KHÔNG sao chép nguyên văn từ bài gốc.
934
+ 2. KHÔNG lặp lại bất kỳ nội dung nào. Mỗi thông tin chỉ xuất hiện ĐÚNG 1 LẦN.
935
+ 3. Nếu 2 câu nói cùng 1 ý → chỉ giữ 1 câu, bỏ cây còn lại.
936
+ 4. KHÔNG dùng Markdown (##, **, ---, *).
937
+ 5. KHÔNG viết "Dưới đây là", "Tôi sẽ", "Theo yêu cầu", "Nhiệm vụ", "Vai trò", "Đây là bài tóm tắt".
938
+ 6. Viết thành ĐOẠN VĂN THUẦN, mạch lạc, dễ đọc. Không dùng bullet points.
939
+ 7. Giữ sự thật, KHÔNG bịa thông tin.
940
+ 8. Tối đa 200 từ. Ngắn gọn, đủ ý.{image_info}
941
+
942
+ Tiêu đề gốc: {title}
943
+
944
+ Nội dung gốc:
945
+ {raw[:14000]}"""
946
+
947
+
948
+ def _build_topic_prompt(topic: str, ctx: str) -> str:
949
+ return f"""Viết bài TÓM TẮT NGẮN GỌN về chủ đề: "{topic}".
950
+
951
+ QUY TẮC BẮT BUỘC:
952
+ 1. Chỉ viết TÓM TẮT các ý chính từ nguồn. KHÔNG sao chép nguyên văn.
953
+ 2. KHÔNG lặp lại bất kỳ nội dung nào. Mỗi thông tin chỉ xuất hiện ĐÚNG 1 LẦN.
954
+ 3. Nếu 2 câu nói cùng 1 ý → chỉ giữ 1 câu.
955
+ 4. KHÔNG dùng Markdown (##, **, ---, *).
956
+ 5. KHÔNG viết "Dưới đây là", "Tôi sẽ", "Theo yêu cầu", "Nhiệm vụ", "Vai trò".
957
+ 6. Viết thành ĐOẠN VĂN THUẦN, mạch lạc. Không dùng bullet points.
958
+ 7. Giữ sự thật, KHÔNG bịa.
959
+ 8. Tối đa 200 từ. Ngắn gọn, đủ ý.
960
+
961
+ Nguồn thực tế:
962
+ {ctx[:12000]}"""
963
+
964
+
965
+ # ===== WRITE ENDPOINTS =====
966
+ @app.post("/api/rewrite_share")
967
+ async def api_rewrite_share(request: Request):
968
+ body = await request.json()
969
+ url = _clean_text(body.get("url", ""))
970
+ if not url.startswith("http"):
971
+ return JSONResponse({"error": "missing url"}, status_code=400)
972
+ try:
973
+ data = scrape_any_url(url)
974
+ except Exception as e:
975
+ return JSONResponse({"error": "Không đọc được bài viết: " + str(e)[:180]}, status_code=422)
976
+ raw = (data.get("summary", "") + "\n" + data.get("text", "")).strip()
977
+ if len(raw) < 60:
978
+ return JSONResponse({"error": "Bài viết quá ngắn để tóm tắt"}, status_code=422)
979
+
980
+ images = data.get("images", [])
981
+ prompt = _build_rewrite_prompt(data.get("title", ""), raw, images)
982
+ # Text-only summary for SPEED (images are kept on the post for display + short video).
983
+ text = await qwen_generate(prompt, max_tokens=500)
984
+ if not text:
985
+ return JSONResponse({"error": "Qwen2.5-VL chưa sẵn sàng: " + LAST_QWEN_ERROR}, status_code=503)
986
+ text = _clean_ai_output(text)
987
+ post = make_post(data.get("title") or "Bài viết", text,
988
+ images[0] if images else data.get("image", ""),
989
+ url, "rewrite", images=images)
990
+
991
+ # Save post and return IMMEDIATELY; generate the short video in the background
992
+ # (so rewrite is fast). Video appears on the wall when ready / via 'Tao Video' button.
993
+ posts = _load_wall()
994
+ posts.insert(0, post)
995
+ _save_wall(posts)
996
+ _spawn_background_video(post)
997
+ return JSONResponse({"post": post})
998
+
999
+
1000
+ @app.post("/api/url_wall")
1001
+ async def api_url_wall(request: Request):
1002
+ body = await request.json()
1003
+ url = _clean_text(body.get("url", ""))
1004
+ if not url.startswith("http"):
1005
+ return JSONResponse({"error": "missing url"}, status_code=400)
1006
+ try:
1007
+ data = scrape_any_url(url)
1008
+ except Exception as e:
1009
+ return JSONResponse({"error": "Không scrape được URL: " + str(e)[:180]}, status_code=422)
1010
+ raw = (data.get("summary", "") + "\n" + data.get("text", "")).strip()
1011
+ if len(raw) < 60:
1012
+ return JSONResponse({"error": "URL không có đủ nội dung"}, status_code=422)
1013
+
1014
+ images = data.get("images", [])
1015
+ prompt = _build_rewrite_prompt(data.get("title", ""), raw, images)
1016
+ # Text-only summary for SPEED (images are kept on the post for display + short video).
1017
+ text = await qwen_generate(prompt, max_tokens=500)
1018
+ if not text:
1019
+ return JSONResponse({"error": "Qwen2.5-VL chưa sẵn sàng: " + LAST_QWEN_ERROR}, status_code=503)
1020
+ text = _clean_ai_output(text)
1021
+ post = make_post(data.get("title") or "Bài viết", text,
1022
+ images[0] if images else data.get("image", ""),
1023
+ url, "url", images=images)
1024
+
1025
+ posts = _load_wall()
1026
+ posts.insert(0, post)
1027
+ _save_wall(posts)
1028
+ _spawn_background_video(post)
1029
+ return JSONResponse({"post": post})
1030
+
1031
+
1032
+ @app.post("/api/topic_post")
1033
+ async def api_topic_post(request: Request):
1034
+ body = await request.json()
1035
+ topic = _clean_text(body.get("topic", ""))
1036
+ if not topic:
1037
+ return JSONResponse({"error": "missing topic"}, status_code=400)
1038
+
1039
+ ctx = _web_context(topic)
1040
+ if not ctx:
1041
+ return JSONResponse({"error": "Không lấy được dữ liệu cho chủ đề này"}, status_code=422)
1042
+
1043
+ image = pollinations_image_url(topic)
1044
+ prompt = _build_topic_prompt(topic, ctx)
1045
+ # NOTE: do NOT pass the decorative pollinations image to the VL model — feeding an
1046
+ # image makes Qwen2.5-VL much slower (it must download+process it) with no benefit for
1047
+ # a text summary. We keep the image only for display on the post. This is a major
1048
+ # speed-up for 'rewrite tong hop'. (Text-only inference is several times faster.)
1049
+ text = await qwen_generate(prompt, max_tokens=500)
1050
+ if not text:
1051
+ return JSONResponse({"error": "Qwen2.5-VL chưa sẵn sàng: " + LAST_QWEN_ERROR}, status_code=503)
1052
+ text = _clean_ai_output(text)
1053
+ post = make_post(topic, text, image, "", "topic")
1054
+
1055
+ posts = _load_wall()
1056
+ posts.insert(0, post)
1057
+ _save_wall(posts)
1058
+ _spawn_background_video(post)
1059
+ return JSONResponse({"post": post})
1060
+
1061
+
1062
+ # ===== WALL ENDPOINTS =====
1063
+ @app.get("/api/ai_wall")
1064
+ def api_ai_wall():
1065
+ return JSONResponse({"posts": _load_wall()[:80]})
1066
+
1067
+ @app.get("/api/wall")
1068
+ def api_wall():
1069
+ return JSONResponse({"posts": _load_wall()[:80]})
1070
+
1071
+
1072
+ # ===== SHORT VIDEO ENDPOINT (with voice + speed params) =====
1073
+ @app.post("/api/ai/short/{post_id}")
1074
+ async def api_ai_short(post_id: str, voice: str = Query(default=None), speed: float = Query(default=None), emotion: str = Query(default=None)):
1075
+ """Generate (or retrieve cached) short video for a wall post.
1076
+
1077
+ Query params:
1078
+ - voice: 'hoaimy' (female) | 'namminh' (male) | auto-detect if not specified
1079
+ - speed: float (default 1.2), e.g. 1.0=normal, 1.2=fast, 0.8=slow
1080
+ - emotion: 'vui'|'hao_hung'|'nghiem'|'tram'|'buon'|'trung_tinh' | auto by topic
1081
+ """
1082
+ posts = _load_wall()
1083
+ post = next((p for p in posts if str(p.get("id")) == str(post_id)), None)
1084
+ if not post:
1085
+ return JSONResponse({"error": "post not found"}, status_code=404)
1086
+
1087
+ os.makedirs(SHORTS_DIR, exist_ok=True)
1088
+ out_mp4 = os.path.join(SHORTS_DIR, _safe_name(post_id) + ".mp4")
1089
+
1090
+ # If cached and no custom voice/speed/emotion requested, return cached
1091
+ if os.path.exists(out_mp4) and voice is None and speed is None and emotion is None:
1092
+ video_url = "/api/ai/short-file/" + post_id
1093
+ for i, p in enumerate(posts):
1094
+ if str(p.get("id")) == str(post_id):
1095
+ posts[i]["video"] = video_url
1096
+ break
1097
+ _save_wall(posts)
1098
+ return JSONResponse({"video": video_url})
1099
+
1100
+ # Validate params
1101
+ if voice is not None and voice not in TTS_VOICES:
1102
+ return JSONResponse({"error": f"voice không hợp lệ. Chọn: {list(TTS_VOICES.keys())}"}, status_code=400)
1103
+ if emotion is not None and emotion not in EMOTION_PRESETS:
1104
+ return JSONResponse({"error": f"emotion không hợp lệ. Chọn: {list(EMOTION_PRESETS.keys())}"}, status_code=400)
1105
+
1106
+ video_url = await _generate_short_video(post, post_id, voice_id=voice, speed=speed, emotion=emotion)
1107
+ if video_url:
1108
+ for i, p in enumerate(posts):
1109
+ if str(p.get("id")) == str(post_id):
1110
+ posts[i]["video"] = video_url
1111
+ if voice:
1112
+ posts[i]["voice"] = voice
1113
+ if emotion:
1114
+ posts[i]["emotion"] = emotion
1115
+ break
1116
+ _save_wall(posts)
1117
+ return JSONResponse({"video": video_url})
1118
+ return JSONResponse({"error": "Không tạo được shorts"}, status_code=500)
1119
+
1120
+
1121
+ @app.get("/api/ai/short-file/{post_id}")
1122
+ def api_ai_short_file(post_id: str):
1123
+ path = os.path.join(SHORTS_DIR, _safe_name(post_id) + ".mp4")
1124
+ if not os.path.exists(path):
1125
+ return JSONResponse({"error": "not found"}, status_code=404)
1126
+ return FileResponse(path, media_type="video/mp4", filename=f"vnews-ai-{post_id}.mp4")
1127
+
1128
+
1129
+ @app.get("/api/ai/status")
1130
+ def api_ai_status():
1131
+ return JSONResponse({
1132
+ "has_token": bool(_hf_token()),
1133
+ "client_imported": AsyncInferenceClient is not None,
1134
+ "last_error": LAST_QWEN_ERROR,
1135
+ "working_text_model": _WORKING_MODEL_TEXT,
1136
+ "working_vl_model": _WORKING_MODEL_VL,
1137
+ })
ai_patch.py CHANGED
@@ -6,7 +6,6 @@ import json
6
  import html as html_lib
7
  import subprocess
8
  import requests
9
- import hashlib
10
  import ai_ext as base
11
  from ai_ext import app
12
  from fastapi import Request
@@ -42,17 +41,17 @@ def _similar(a, b):
42
  return len(ta & tb) / max(1, min(len(ta), len(tb))) >= 0.72
43
 
44
 
45
- def _dedupe_units(units, max_units=25):
46
- """Deduplicate units - only skip exact matches to ensure all bullet points are read."""
47
  out, seen = [], set()
48
  for u in units:
49
  u = _clean(re.sub(r"^[-•*\d\.\)\s]+", "", u))
50
  if len(u) < 18:
51
  continue
52
  nu = _norm(u)
53
- # Only skip exact matches, NOT similar content (to avoid skipping valid bullet points)
54
  if nu in seen:
55
  continue
 
 
56
  seen.add(nu)
57
  out.append(u)
58
  if len(out) >= max_units:
@@ -60,7 +59,7 @@ def _dedupe_units(units, max_units=25):
60
  return out
61
 
62
 
63
- def _postprocess_ai_text(text, max_units=20):
64
  text = _clean(text)
65
  if not text:
66
  return text
@@ -79,9 +78,10 @@ def _postprocess_ai_text(text, max_units=20):
79
  raw_lines.append(line)
80
  units = []
81
  for line in raw_lines:
82
- # KEEP FULL bullet point - don't truncate or split into segments
83
- if len(line) >= 18:
84
- units.append(_clean(re.sub(r"^[-•*\d\.\)\s]+", "", line)))
 
85
  units = _dedupe_units(units, max_units=max_units)
86
  if not units:
87
  return text[:900]
@@ -268,7 +268,7 @@ async def qwen_generate_resilient(prompt: str, image_url=None, max_tokens: int =
268
  errors.append("missing HF_TOKEN")
269
  base.LAST_QWEN_ERROR = " | ".join(errors[-6:]) or "Qwen unavailable; used extractive fallback"
270
  print("[qwen resilient fallback]", base.LAST_QWEN_ERROR)
271
- return _fallback_summary_from_prompt(prompt, max_units=12)
272
 
273
 
274
  if not hasattr(base, "_original_qwen_generate"):
@@ -321,30 +321,12 @@ Yêu cầu bắt buộc:
321
 
322
  Nội dung bài:
323
  {art['raw'][:14000]}"""
324
- text = await base.qwen_generate(prompt, image_url=art.get('image') or None, max_tokens=1500)
325
- text = _postprocess_ai_text(text, max_units=20)
326
  src = [art['source']]
327
  if 'Nguồn tham khảo:' not in text:
328
  text += "\n\n" + _source_line(src)
329
  post = base.make_post(art['title'], text, art.get('image') or base.pollinations_image_url(art['title']), art.get('url') or '', 'topic_article', sources=src)
330
-
331
- # Generate slides for this post so they persist after page reload
332
- try:
333
- page_data = _scrape_article_images(art.get('url', ''))
334
- if page_data and page_data.get('paragraphs'):
335
- key_points = _extract_key_points_for_slides(page_data['paragraphs'], max_points=12)
336
- if key_points:
337
- relevant_imgs = page_data.get('images', [])
338
- if not relevant_imgs and page_data.get('og_img'):
339
- relevant_imgs = [page_data['og_img']]
340
- slides = []
341
- for i, point in enumerate(key_points):
342
- img = relevant_imgs[i] if i < len(relevant_imgs) else (relevant_imgs[-1] if relevant_imgs else '')
343
- slides.append({'text': point, 'image': img, 'index': i + 1})
344
- post['slides'] = slides
345
- except Exception:
346
- pass
347
-
348
  new_posts.append(post)
349
  posts = new_posts + posts
350
  base._save_ai_wall(posts)
@@ -365,142 +347,14 @@ async def compat_url_wall(request: Request):
365
  if len(raw) < 120:
366
  return JSONResponse({'error': 'URL không có đủ nội dung để tóm tắt'}, status_code=422)
367
  prompt = _make_summary_prompt(data.get('title', ''), raw, data.get('via', '') or base._domain(url))
368
- text = await base.qwen_generate(prompt, image_url=data.get('image') or None, max_tokens=1500)
369
- text = _postprocess_ai_text(text, max_units=20)
370
  src = [{'title': data.get('title'), 'url': url, 'excerpt': raw[:500], 'via': data.get('via') or base._domain(url)}]
371
  if 'Nguồn tham khảo:' not in text:
372
  text += "\n\n" + _source_line(src)
373
  post = base.make_post(data.get('title') or 'Bài viết', text, data.get('image') or '', url, 'url', sources=src)
374
-
375
- # Generate slides so they persist after page reload
376
- slides = []
377
- try:
378
- page_data = _scrape_article_images(url)
379
- if page_data and page_data.get('paragraphs'):
380
- key_points = _extract_key_points_for_slides(page_data['paragraphs'], max_points=12)
381
- if key_points:
382
- relevant_imgs = page_data.get('images', [])
383
- if not relevant_imgs and page_data.get('og_img'):
384
- relevant_imgs = [page_data['og_img']]
385
- for i, point in enumerate(key_points):
386
- img = relevant_imgs[i] if i < len(relevant_imgs) else (relevant_imgs[-1] if relevant_imgs else '')
387
- slides.append({'text': point, 'image': img, 'index': i + 1})
388
- except Exception:
389
- pass
390
- post['slides'] = slides
391
-
392
  posts = base._load_ai_wall(); posts.insert(0, post); base._save_ai_wall(posts)
393
- return JSONResponse({'post': post, 'slides': slides})
394
-
395
-
396
- def _is_relevant_image(img_url, title, text):
397
- """Check if an image is relevant to the article content."""
398
- if not img_url:
399
- return False
400
- skip_patterns = ['pixel', 'analytics', 'tracking', '1x1.gif', 'spacer.gif',
401
- 'logo', 'icon', 'avatar', 'emoji', 'smiley', 'sprite',
402
- 'advertisement', 'ad-banner', 'sponsored', 'banner-ads']
403
- img_lower = img_url.lower()
404
- for p in skip_patterns:
405
- if p in img_lower:
406
- return False
407
- if not any(img_lower.endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.webp', '.gif']):
408
- return False
409
- return True
410
-
411
-
412
- def _filter_relevant_images(images, title, text, max_images=8):
413
- """Filter and rank images by relevance to article content."""
414
- if not images:
415
- return []
416
- seen = set()
417
- relevant = []
418
- for img in images:
419
- if img in seen:
420
- continue
421
- seen.add(img)
422
- if _is_relevant_image(img, title, text):
423
- relevant.append(img)
424
- return relevant[:max_images]
425
-
426
-
427
- def _extract_key_points_for_slides(paragraphs, max_points=12):
428
- """Extract key points from paragraphs for slides - extracts ALL sentences, not just first one."""
429
- points = []
430
- for p in paragraphs:
431
- if len(points) >= max_points:
432
- break
433
- p = _clean(p)
434
- if not p:
435
- continue
436
- # Split paragraph into sentences using Vietnamese + English punctuation - GET ALL SENTENCES
437
- sentences = re.split(r'(?<=[.!?])\s+(?=[A-ZÀ-Ỹ0-9])', p)
438
- sentences = [s.strip() for s in sentences if s.strip()]
439
-
440
- for sentence in sentences:
441
- if len(points) >= max_points:
442
- break
443
- sentence = _clean(sentence)
444
- if len(sentence) < 30:
445
- continue
446
- if any(sentence[:60] in existing for existing in points):
447
- continue
448
- if not sentence.endswith(('.', '!', '?')):
449
- sentence = sentence + '.'
450
- points.append(sentence)
451
- return points
452
-
453
-
454
- def _scrape_article_images(url):
455
- """Scrape article page and return only relevant images."""
456
- try:
457
- headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
458
- "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8"}
459
- r = requests.get(url, headers=headers, timeout=15, allow_redirects=True)
460
- r.encoding = 'utf-8'
461
- soup = BeautifulSoup(r.text, 'lxml')
462
- for tag in soup.find_all(['script', 'style', 'nav', 'footer', 'aside', 'form']):
463
- tag.decompose()
464
- h1 = soup.find('h1')
465
- ogt = soup.find('meta', property='og:title')
466
- title = (h1.get_text(strip=True) if h1 else '') or (ogt.get('content', '') if ogt else '')
467
- ogi = soup.find('meta', property='og:image')
468
- og_img = ogi.get('content', '') if ogi else ''
469
- if og_img and og_img.startswith('//'):
470
- og_img = 'https:' + og_img
471
- block = None
472
- for sel in ['article', '.singular-content', '.detail-content', '.fck_detail', '.content-detail', '.knc-content', 'main', '.cms-body', '.article__body']:
473
- el = soup.select_one(sel)
474
- if el and len(el.find_all('p')) >= 2:
475
- block = el
476
- break
477
- if not block:
478
- block = soup.body or soup
479
- paragraphs = []
480
- all_images = []
481
- seen_imgs = set()
482
- if og_img and og_img not in seen_imgs:
483
- all_images.append(og_img)
484
- seen_imgs.add(og_img)
485
- for el in block.find_all(['p', 'h2', 'h3', 'figure', 'img'], recursive=True):
486
- if el.name == 'p':
487
- t = _clean(el.get_text(strip=True))
488
- if t and len(t) > 40:
489
- paragraphs.append(t)
490
- elif el.name in ('figure', 'img'):
491
- im = el if el.name == 'img' else el.find('img')
492
- if im:
493
- src = im.get('data-src') or im.get('src') or im.get('data-original') or ''
494
- if src and 'base64' not in src:
495
- if src.startswith('//'):
496
- src = 'https:' + src
497
- if src not in seen_imgs:
498
- all_images.append(src)
499
- seen_imgs.add(src)
500
- relevant_images = _filter_relevant_images(all_images, title, ' '.join(paragraphs[:5]))
501
- return {'title': _clean(title), 'paragraphs': paragraphs, 'images': relevant_images, 'og_img': og_img}
502
- except Exception:
503
- return None
504
 
505
 
506
  @app.post('/api/rewrite_share')
@@ -517,56 +371,40 @@ async def compat_rewrite_share(request: Request):
517
  if len(raw) < 120:
518
  return JSONResponse({'error': 'Bài viết không đủ nội dung để tóm tắt'}, status_code=422)
519
  prompt = _make_summary_prompt(data.get('title', ''), raw, data.get('via', '') or base._domain(url))
520
- text = await base.qwen_generate(prompt, image_url=data.get('image') or None, max_tokens=1500)
521
- text = _postprocess_ai_text(text, max_units=20)
522
  src = [{'title': data.get('title'), 'url': url, 'excerpt': raw[:500], 'via': data.get('via') or base._domain(url)}]
523
  if 'Nguồn tham khảo:' not in text:
524
  text += "\n\n" + _source_line(src)
525
  post = base.make_post(data.get('title') or 'Bài viết', text, data.get('image') or '', url, 'summary', sources=src)
526
-
527
- # Generate slides with relevant images only
528
- slides = []
529
- page_data = _scrape_article_images(url)
530
- if page_data and page_data.get('paragraphs'):
531
- key_points = _extract_key_points_for_slides(page_data['paragraphs'], max_points=12)
532
- if key_points:
533
- relevant_imgs = page_data.get('images', [])
534
- if not relevant_imgs and page_data.get('og_img'):
535
- relevant_imgs = [page_data['og_img']]
536
- for i, point in enumerate(key_points):
537
- img = relevant_imgs[i] if i < len(relevant_imgs) else (relevant_imgs[-1] if relevant_imgs else '')
538
- slides.append({'text': point, 'image': img, 'index': i + 1})
539
-
540
- # FIX: Save slides into post so they persist after page reload
541
- post['slides'] = slides
542
  posts = base._load_ai_wall(); posts.insert(0, post); base._save_ai_wall(posts)
543
-
544
- return JSONResponse({'post': post, 'slides': slides})
545
 
546
 
547
  def _emotion_script(text, emotion):
548
- """Prepend emotion-appropriate prefix to text based on emotion type.
549
-
550
- NOTE: Prefix is NOT added to avoid cluttering Short AI speech.
551
- The emotion is still used for voice selection but content is read cleanly.
552
- """
553
  text = _clean(text)
554
- # REMOVED: No prefix added to keep content clean and natural
 
 
 
 
 
 
 
555
  return text
556
 
557
 
558
  def _tts_script_smart(post, emotion):
559
- raw = base._short_script(post) if hasattr(base, '_short_script') else _clean(post.get('text', '') or post.get('title', ''))
560
  raw = re.sub(r"^[•\-\*]\s*", "", raw, flags=re.M)
561
  raw = re.sub(r"\s*\n\s*", ". ", raw)
562
  raw = re.sub(r"([\.\!\?])\s*", r"\1\n", raw)
563
  raw = re.sub(r"\n{2,}", "\n", raw).strip()
564
- # REMOVED: _emotion_script call - read content cleanly without prefix
565
- # INCREASED to 3000 to read full content of all bullet points
566
- if len(raw) > 3000:
567
- raw = raw[:3000]
568
  cut = max(raw.rfind("."), raw.rfind("!"), raw.rfind("?"))
569
- if cut > 700:
570
  raw = raw[:cut + 1]
571
  return raw
572
 
@@ -681,7 +519,7 @@ def _make_short_frame_full(post, img_path, out_path):
681
 
682
 
683
 
684
- def _summary_segments_from_post(post, max_segments=25):
685
  raw = _clean(post.get('text') or post.get('title') or '')
686
  raw = re.sub(r'^Bản tin AI viết lại:\s*', '', raw, flags=re.I)
687
  raw = re.sub(r'Nguồn tham khảo:.*$', '', raw, flags=re.I|re.S).strip()
@@ -692,7 +530,7 @@ def _summary_segments_from_post(post, max_segments=25):
692
  low=ln.lower()
693
  if low.startswith(('điểm chính','tiêu đề','sapo','nguồn tham khảo')): continue
694
  if len(ln)>=18: lines.append(ln)
695
- if len(lines)<3:
696
  lines=[]
697
  for s in re.split(r'(?<=[\.\!\?])\s+', raw):
698
  s=_clean(s)
@@ -744,8 +582,7 @@ def _make_scene_frame(post, segment, idx, total, img_path, out_path, emotion='ne
744
  draw.rounded_rectangle((48,834,260,880), radius=20, fill=(28,70,45))
745
  draw.text((66,842),f'Đoạn {idx+1}/{total}',fill=(235,235,235),font=font_small)
746
  y=940; maxw=W-96
747
- # INCREASED from 12 to 18 for full content display - each key point can span multiple lines
748
- for ln in _wrap_text_px(draw, segment, font_seg, maxw, 18):
749
  draw.text((48,y),ln,fill=(255,255,255),font=font_seg)
750
  y+=74
751
  if y>1500: break
@@ -757,11 +594,10 @@ def _make_scene_frame(post, segment, idx, total, img_path, out_path, emotion='ne
757
  bg.save(out_path, quality=92)
758
 
759
 
760
- def _estimate_audio_duration(path, fallback=15.0):
761
- """Estimate audio duration with 15s minimum per segment for complete bullet reading."""
762
  try:
763
  pr=subprocess.run(['ffprobe','-v','error','-show_entries','format=duration','-of','default=noprint_wrappers=1:no_key=1',path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20)
764
- return max(12.0, float((pr.stdout or b'').decode().strip() or fallback))
765
  except Exception:
766
  return fallback
767
 
@@ -774,7 +610,7 @@ async def patched_ai_short(post_id: str, request: Request):
774
  body = {}
775
  voice = str(body.get('voice', 'nu')).strip().lower()
776
  emotion = str(body.get('emotion', 'neutral')).strip().lower()
777
- speed = float(body.get('speed', 1.0) or 1.0)
778
  speed = max(0.85, min(1.35, speed))
779
 
780
  posts = base._load_ai_wall()
@@ -782,7 +618,7 @@ async def patched_ai_short(post_id: str, request: Request):
782
  if not post:
783
  return JSONResponse({'error': 'post not found'}, status_code=404)
784
 
785
- segments = _summary_segments_from_post(post, max_segments=25)
786
  seg_hash = hashlib.md5(('|'.join(segments)+voice+emotion+str(speed)).encode('utf-8')).hexdigest()[:8]
787
  os.makedirs(base.SHORTS_DIR, exist_ok=True)
788
  suffix = f"_{voice}_{emotion}_{str(speed).replace('.', 'p')}_{seg_hash}_scenes_nosub"
@@ -805,63 +641,11 @@ async def patched_ai_short(post_id: str, request: Request):
805
  try:
806
  base._download_image(post.get('img'), post.get('title', 'AI news'), img)
807
  edge_voice = {
808
- # Vietnamese
809
- 'vi-vn-hoaimyneural': 'vi-VN-HoaiMyNeural',
810
- 'vi-vn-namminhneural': 'vi-VN-NamMinhNeural',
811
- 'hoaimy': 'vi-VN-HoaiMyNeural',
812
- 'namminh': 'vi-VN-NamMinhNeural',
813
  'nam': 'vi-VN-NamMinhNeural',
814
  'male': 'vi-VN-NamMinhNeural',
815
  'nu': 'vi-VN-HoaiMyNeural',
816
  'female': 'vi-VN-HoaiMyNeural',
817
  'mien-nam': 'vi-VN-HoaiMyNeural',
818
- # English - Multilingual
819
- 'en-us-andrewmultilingualneural': 'en-US-AndrewMultilingualNeural',
820
- 'en-au-williammultilingualneural': 'en-AU-WilliamMultilingualNeural',
821
- 'andrew': 'en-US-AndrewMultilingualNeural',
822
- 'en_andrew': 'en-US-AndrewMultilingualNeural',
823
- 'jenny': 'en-US-AndrewMultilingualNeural',
824
- 'en_jenny': 'en-US-AndrewMultilingualNeural',
825
- # Portuguese - Multilingual (ONLY Thalita)
826
- 'pt-br-thalitamultilingualneural': 'pt-BR-ThalitaMultilingualNeural',
827
- 'thalita': 'pt-BR-ThalitaMultilingualNeural',
828
- 'pt_thalita': 'pt-BR-ThalitaMultilingualNeural',
829
- 'pt_br_thalita': 'pt-BR-ThalitaMultilingualNeural',
830
- 'pt': 'pt-BR-ThalitaMultilingualNeural',
831
- 'pt_francisco': 'pt-BR-ThalitaMultilingualNeural',
832
- # French - Multilingual
833
- 'fr-fr-viviennemultilingualneural': 'fr-FR-VivienneMultilingualNeural',
834
- 'fr-fr-remymultilingualneural': 'fr-FR-RemyMultilingualNeural',
835
- 'denise': 'fr-FR-VivienneMultilingualNeural',
836
- 'fr': 'fr-FR-VivienneMultilingualNeural',
837
- 'fr_denise': 'fr-FR-VivienneMultilingualNeural',
838
- # German - Multilingual
839
- 'de-de-seraphinamultilingualneural': 'de-DE-SeraphinaMultilingualNeural',
840
- 'de-de-florianmultilingualneural': 'de-DE-FlorianMultilingualNeural',
841
- 'katja': 'de-DE-SeraphinaMultilingualNeural',
842
- 'de': 'de-DE-SeraphinaMultilingualNeural',
843
- 'de_katja': 'de-DE-SeraphinaMultilingualNeural',
844
- # Korean - Multilingual (Hyunsu, NOT SunHee)
845
- 'ko-kr-hyusumultilingualneural': 'ko-KR-HyunsuMultilingualNeural',
846
- 'ko-kr-hyunsuneural': 'ko-KR-HyunsuMultilingualNeural',
847
- 'sunhee': 'ko-KR-HyunsuMultilingualNeural',
848
- 'ko': 'ko-KR-HyunsuMultilingualNeural',
849
- 'ko_sunhee': 'ko-KR-HyunsuMultilingualNeural',
850
- # Italian - Multilingual
851
- 'it-it-giuseppemultilingualneural': 'it-IT-GiuseppeMultilingualNeural',
852
- # Spanish (keep for backward compat)
853
- 'ela': 'en-US-AndrewMultilingualNeural',
854
- 'es_ela': 'en-US-AndrewMultilingualNeural',
855
- 'es': 'en-US-AndrewMultilingualNeural',
856
- 'es_carlos': 'en-US-AndrewMultilingualNeural',
857
- # Japanese (keep for backward compat)
858
- 'nanami': 'en-US-AndrewMultilingualNeural',
859
- 'ja': 'en-US-AndrewMultilingualNeural',
860
- 'ja_nanami': 'en-US-AndrewMultilingualNeural',
861
- # Chinese (keep for backward compat)
862
- 'xiaochen': 'en-US-AndrewMultilingualNeural',
863
- 'zh': 'en-US-AndrewMultilingualNeural',
864
- 'zh_xiaochen': 'en-US-AndrewMultilingualNeural',
865
  }.get(voice, 'vi-VN-HoaiMyNeural')
866
  part_files=[]
867
  for idx, seg in enumerate(segments):
@@ -874,13 +658,13 @@ async def patched_ai_short(post_id: str, request: Request):
874
  try:
875
  subprocess.run(['python','-m','edge_tts','--voice',edge_voice,'--text',spoken,'--write-media',aud], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
876
  except Exception:
877
- tld='com.vn' if voice in ('nu','female','mien-nam','hoaimy') else 'com'
878
  try:
879
  base.gTTS(spoken, lang='vi', tld=tld, slow=False).save(aud)
880
  except TypeError:
881
  base.gTTS(spoken, lang='vi', slow=False).save(aud)
882
  subprocess.run(['ffmpeg','-y','-i',aud,'-filter:a',f'atempo={speed}','-vn',aud_fast], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=90)
883
- dur=_estimate_audio_duration(aud_fast, fallback=15.0)+0.35
884
  subprocess.run(['ffmpeg','-y','-loop','1','-t',str(dur),'-i',frame,'-i',aud_fast,'-shortest','-c:v','libx264','-tune','stillimage','-pix_fmt','yuv420p','-c:a','aac','-b:a','128k',part], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=150)
885
  part_files.append(part)
886
  concat=os.path.join(work,'concat.txt')
@@ -915,3 +699,53 @@ def api_ai_shorts():
915
 
916
 
917
  app.router.routes = [r for r in app.router.routes if not (getattr(r, 'path', None) == '/' and 'GET' in getattr(r, 'methods', set()))]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  import html as html_lib
7
  import subprocess
8
  import requests
 
9
  import ai_ext as base
10
  from ai_ext import app
11
  from fastapi import Request
 
41
  return len(ta & tb) / max(1, min(len(ta), len(tb))) >= 0.72
42
 
43
 
44
+ def _dedupe_units(units, max_units=7):
 
45
  out, seen = [], set()
46
  for u in units:
47
  u = _clean(re.sub(r"^[-•*\d\.\)\s]+", "", u))
48
  if len(u) < 18:
49
  continue
50
  nu = _norm(u)
 
51
  if nu in seen:
52
  continue
53
+ if any(_similar(u, old) for old in out):
54
+ continue
55
  seen.add(nu)
56
  out.append(u)
57
  if len(out) >= max_units:
 
59
  return out
60
 
61
 
62
+ def _postprocess_ai_text(text, max_units=7):
63
  text = _clean(text)
64
  if not text:
65
  return text
 
78
  raw_lines.append(line)
79
  units = []
80
  for line in raw_lines:
81
+ if len(line) > 260:
82
+ units.extend(re.split(r"(?<=[\.\!\?])\s+(?=[A-ZÀ-Ỹ0-9])", line))
83
+ else:
84
+ units.append(line)
85
  units = _dedupe_units(units, max_units=max_units)
86
  if not units:
87
  return text[:900]
 
268
  errors.append("missing HF_TOKEN")
269
  base.LAST_QWEN_ERROR = " | ".join(errors[-6:]) or "Qwen unavailable; used extractive fallback"
270
  print("[qwen resilient fallback]", base.LAST_QWEN_ERROR)
271
+ return _fallback_summary_from_prompt(prompt, max_units=6)
272
 
273
 
274
  if not hasattr(base, "_original_qwen_generate"):
 
321
 
322
  Nội dung bài:
323
  {art['raw'][:14000]}"""
324
+ text = await base.qwen_generate(prompt, image_url=art.get('image') or None, max_tokens=900)
325
+ text = _postprocess_ai_text(text, max_units=6)
326
  src = [art['source']]
327
  if 'Nguồn tham khảo:' not in text:
328
  text += "\n\n" + _source_line(src)
329
  post = base.make_post(art['title'], text, art.get('image') or base.pollinations_image_url(art['title']), art.get('url') or '', 'topic_article', sources=src)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  new_posts.append(post)
331
  posts = new_posts + posts
332
  base._save_ai_wall(posts)
 
347
  if len(raw) < 120:
348
  return JSONResponse({'error': 'URL không có đủ nội dung để tóm tắt'}, status_code=422)
349
  prompt = _make_summary_prompt(data.get('title', ''), raw, data.get('via', '') or base._domain(url))
350
+ text = await base.qwen_generate(prompt, image_url=data.get('image') or None, max_tokens=850)
351
+ text = _postprocess_ai_text(text, max_units=6)
352
  src = [{'title': data.get('title'), 'url': url, 'excerpt': raw[:500], 'via': data.get('via') or base._domain(url)}]
353
  if 'Nguồn tham khảo:' not in text:
354
  text += "\n\n" + _source_line(src)
355
  post = base.make_post(data.get('title') or 'Bài viết', text, data.get('image') or '', url, 'url', sources=src)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  posts = base._load_ai_wall(); posts.insert(0, post); base._save_ai_wall(posts)
357
+ return JSONResponse({'post': post})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
 
359
 
360
  @app.post('/api/rewrite_share')
 
371
  if len(raw) < 120:
372
  return JSONResponse({'error': 'Bài viết không đủ nội dung để tóm tắt'}, status_code=422)
373
  prompt = _make_summary_prompt(data.get('title', ''), raw, data.get('via', '') or base._domain(url))
374
+ text = await base.qwen_generate(prompt, image_url=data.get('image') or None, max_tokens=850)
375
+ text = _postprocess_ai_text(text, max_units=6)
376
  src = [{'title': data.get('title'), 'url': url, 'excerpt': raw[:500], 'via': data.get('via') or base._domain(url)}]
377
  if 'Nguồn tham khảo:' not in text:
378
  text += "\n\n" + _source_line(src)
379
  post = base.make_post(data.get('title') or 'Bài viết', text, data.get('image') or '', url, 'summary', sources=src)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
  posts = base._load_ai_wall(); posts.insert(0, post); base._save_ai_wall(posts)
381
+ return JSONResponse({'post': post})
 
382
 
383
 
384
  def _emotion_script(text, emotion):
 
 
 
 
 
385
  text = _clean(text)
386
+ if emotion == 'urgent':
387
+ return 'Tin nhanh. ' + text
388
+ if emotion == 'warm':
389
+ return 'Câu chuyện đáng chú ý. ' + text
390
+ if emotion == 'serious':
391
+ return 'Bản tin nghiêm túc. ' + text
392
+ if emotion == 'energetic':
393
+ return 'Cập nhật nổi bật. ' + text
394
  return text
395
 
396
 
397
  def _tts_script_smart(post, emotion):
398
+ raw = base._short_script(post)
399
  raw = re.sub(r"^[•\-\*]\s*", "", raw, flags=re.M)
400
  raw = re.sub(r"\s*\n\s*", ". ", raw)
401
  raw = re.sub(r"([\.\!\?])\s*", r"\1\n", raw)
402
  raw = re.sub(r"\n{2,}", "\n", raw).strip()
403
+ raw = _emotion_script(raw, emotion)
404
+ if len(raw) > 1000:
405
+ raw = raw[:1000]
 
406
  cut = max(raw.rfind("."), raw.rfind("!"), raw.rfind("?"))
407
+ if cut > 350:
408
  raw = raw[:cut + 1]
409
  return raw
410
 
 
519
 
520
 
521
 
522
+ def _summary_segments_from_post(post, max_segments=7):
523
  raw = _clean(post.get('text') or post.get('title') or '')
524
  raw = re.sub(r'^Bản tin AI viết lại:\s*', '', raw, flags=re.I)
525
  raw = re.sub(r'Nguồn tham khảo:.*$', '', raw, flags=re.I|re.S).strip()
 
530
  low=ln.lower()
531
  if low.startswith(('điểm chính','tiêu đề','sapo','nguồn tham khảo')): continue
532
  if len(ln)>=18: lines.append(ln)
533
+ if len(lines)<2:
534
  lines=[]
535
  for s in re.split(r'(?<=[\.\!\?])\s+', raw):
536
  s=_clean(s)
 
582
  draw.rounded_rectangle((48,834,260,880), radius=20, fill=(28,70,45))
583
  draw.text((66,842),f'Đoạn {idx+1}/{total}',fill=(235,235,235),font=font_small)
584
  y=940; maxw=W-96
585
+ for ln in _wrap_text_px(draw, segment, font_seg, maxw, 8):
 
586
  draw.text((48,y),ln,fill=(255,255,255),font=font_seg)
587
  y+=74
588
  if y>1500: break
 
594
  bg.save(out_path, quality=92)
595
 
596
 
597
+ def _estimate_audio_duration(path, fallback=4.0):
 
598
  try:
599
  pr=subprocess.run(['ffprobe','-v','error','-show_entries','format=duration','-of','default=noprint_wrappers=1:no_key=1',path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20)
600
+ return max(1.5, float((pr.stdout or b'').decode().strip() or fallback))
601
  except Exception:
602
  return fallback
603
 
 
610
  body = {}
611
  voice = str(body.get('voice', 'nu')).strip().lower()
612
  emotion = str(body.get('emotion', 'neutral')).strip().lower()
613
+ speed = float(body.get('speed', 1.2) or 1.2)
614
  speed = max(0.85, min(1.35, speed))
615
 
616
  posts = base._load_ai_wall()
 
618
  if not post:
619
  return JSONResponse({'error': 'post not found'}, status_code=404)
620
 
621
+ segments = _summary_segments_from_post(post, max_segments=7)
622
  seg_hash = hashlib.md5(('|'.join(segments)+voice+emotion+str(speed)).encode('utf-8')).hexdigest()[:8]
623
  os.makedirs(base.SHORTS_DIR, exist_ok=True)
624
  suffix = f"_{voice}_{emotion}_{str(speed).replace('.', 'p')}_{seg_hash}_scenes_nosub"
 
641
  try:
642
  base._download_image(post.get('img'), post.get('title', 'AI news'), img)
643
  edge_voice = {
 
 
 
 
 
644
  'nam': 'vi-VN-NamMinhNeural',
645
  'male': 'vi-VN-NamMinhNeural',
646
  'nu': 'vi-VN-HoaiMyNeural',
647
  'female': 'vi-VN-HoaiMyNeural',
648
  'mien-nam': 'vi-VN-HoaiMyNeural',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
649
  }.get(voice, 'vi-VN-HoaiMyNeural')
650
  part_files=[]
651
  for idx, seg in enumerate(segments):
 
658
  try:
659
  subprocess.run(['python','-m','edge_tts','--voice',edge_voice,'--text',spoken,'--write-media',aud], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
660
  except Exception:
661
+ tld='com.vn' if voice in ('nu','female','mien-nam') else 'com'
662
  try:
663
  base.gTTS(spoken, lang='vi', tld=tld, slow=False).save(aud)
664
  except TypeError:
665
  base.gTTS(spoken, lang='vi', slow=False).save(aud)
666
  subprocess.run(['ffmpeg','-y','-i',aud,'-filter:a',f'atempo={speed}','-vn',aud_fast], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=90)
667
+ dur=_estimate_audio_duration(aud_fast, fallback=4.0)+0.35
668
  subprocess.run(['ffmpeg','-y','-loop','1','-t',str(dur),'-i',frame,'-i',aud_fast,'-shortest','-c:v','libx264','-tune','stillimage','-pix_fmt','yuv420p','-c:a','aac','-b:a','128k',part], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=150)
669
  part_files.append(part)
670
  concat=os.path.join(work,'concat.txt')
 
699
 
700
 
701
  app.router.routes = [r for r in app.router.routes if not (getattr(r, 'path', None) == '/' and 'GET' in getattr(r, 'methods', set()))]
702
+
703
+ PATCH_INJECT = r'''
704
+ <style>
705
+ .ai-wall-patched{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}
706
+ .ai-wall-card{flex:0 0 250px;background:#141414;border:1px solid #2b2b2b;border-radius:10px;padding:8px}
707
+ .ai-wall-img{width:100%;aspect-ratio:16/9;background:#222;border-radius:8px;overflow:hidden;margin-bottom:6px}
708
+ .ai-wall-img img{width:100%;height:100%;object-fit:cover}
709
+ .ai-wall-title{font-size:12px;color:#5cb87a;font-weight:800;line-height:1.3;margin-bottom:4px}
710
+ .ai-wall-text{font-size:11px;color:#bbb;line-height:1.45;white-space:pre-wrap;display:-webkit-box;-webkit-line-clamp:5;-webkit-box-orient:vertical;overflow:hidden}
711
+ .ai-wall-actions{display:flex;gap:6px;margin-top:8px}
712
+ .ai-wall-actions button,.ai-wall-actions select{flex:1;border:1px solid #333;background:#222;color:#ddd;border-radius:14px;padding:6px 8px;font-size:10px;min-width:0}
713
+ .ai-wall-actions button.primary{background:#2d8659;border-color:#2d8659;color:#fff}
714
+ .ai-short-card{flex:0 0 145px}
715
+ .ai-short-video{width:100%;aspect-ratio:9/16;background:#000;border-radius:8px;overflow:hidden}
716
+ .ai-short-video video{width:100%;height:100%;object-fit:cover}
717
+ .ai-short-progress{position:fixed;inset:0;background:rgba(0,0,0,.78);z-index:99999;display:none;align-items:center;justify-content:center;padding:20px}
718
+ .ai-short-progress.active{display:flex}
719
+ .ai-short-box{max-width:420px;width:100%;background:#141414;border:2px solid #2d8659;border-radius:14px;padding:18px;color:#eee;box-shadow:0 0 30px rgba(45,134,89,.35)}
720
+ .ai-short-box h3{color:#5cb87a;margin-bottom:10px}
721
+ .ai-short-step{font-size:13px;line-height:1.55;color:#ccc}
722
+ .ai-short-spinner{width:34px;height:34px;border:4px solid #333;border-top-color:#5cb87a;border-radius:50%;animation:spin 1s linear infinite;margin:10px auto}
723
+ @keyframes spin{to{transform:rotate(360deg)}}
724
+ </style>
725
+ <div id="ai-short-progress" class="ai-short-progress"><div class="ai-short-box"><h3>🎬 Đang tạo Short AI</h3><div class="ai-short-spinner"></div><div class="ai-short-step" id="ai-short-step">Đang chuẩn bị...</div></div></div>
726
+ <script>
727
+ (function(){
728
+ function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));}
729
+ let patchedWall=[];let aiShorts=[];
730
+ function showProgress(msg){let box=document.getElementById('ai-short-progress');let st=document.getElementById('ai-short-step');if(st)st.innerHTML=msg;if(box)box.classList.add('active');}
731
+ function hideProgress(){document.getElementById('ai-short-progress')?.classList.remove('active');}
732
+ function updateAiLabels(){document.querySelectorAll('.ai-compose-title').forEach(e=>e.textContent='🤖 Tường AI: lọc từng bài theo chủ đề, tóm tắt nội dung bài');document.querySelectorAll('button').forEach(b=>{if((b.textContent||'').includes('AI viết lại'))b.textContent='🤖 Tóm tắt AI & đăng tường';});}
733
+ async function loadPatchedWall(){try{const r=await fetch('/api/ai_wall');const j=await r.json();patchedWall=j.posts||[];renderPatchedWall();updateAiLabels();}catch(e){}try{const r2=await fetch('/api/ai_shorts');const j2=await r2.json();aiShorts=j2.posts||[];renderAiShorts();}catch(e){}}
734
+ function renderAiShorts(){const home=document.getElementById('view-home');if(!home)return;document.getElementById('ai-shorts-patched')?.remove();if(!aiShorts.length)return;let wrap=document.createElement('div');wrap.id='ai-shorts-patched';wrap.className='ai-wall-patched';let h='<div class="slider-header"><span class="slider-label">🎬 Short AI</span><span class="slider-note">Video đã tạo</span></div><div class="slider-track">';aiShorts.slice(0,30).forEach((p,i)=>{h+=`<div class="ai-short-card" onclick="aiReadShortPatched(${i})"><div class="ai-short-video"><video src="${p.video}" muted playsinline preload="metadata"></video></div><div class="slider-title">${esc(p.title)}</div></div>`});h+='</div>';wrap.innerHTML=h;let wall=document.getElementById('ai-wall-patched');if(wall)wall.after(wrap);else home.prepend(wrap);}
735
+ function renderPatchedWall(){const home=document.getElementById('view-home');if(!home)return;document.getElementById('ai-wall-patched')?.remove();if(!patchedWall.length)return;let wrap=document.createElement('div');wrap.id='ai-wall-patched';wrap.className='ai-wall-patched';let h='<div class="slider-header"><span class="slider-label">🧱 Tường AI</span><span class="slider-note">Mỗi nguồn = một bài tóm tắt</span></div><div class="slider-track">';patchedWall.slice(0,30).forEach((p,i)=>{h+=`<div class="ai-wall-card"><div class="ai-wall-img">${p.img?`<img src="${p.img}">`:''}</div><div class="ai-wall-title">${esc(p.title)}</div><div class="ai-wall-text">${esc(p.text)}</div><div class="ai-wall-actions"><button onclick="aiReadWallPatched(${i})">Xem</button><button class="primary" onclick="aiMakeShortPatched(${i})">Shorts</button></div></div>`});h+='</div>';wrap.innerHTML=h;let after=document.querySelector('.ai-compose');if(after)after.after(wrap);else home.prepend(wrap);}
736
+ window.aiReadShortPatched=function(i){const p=aiShorts[i];if(!p)return;showView('view-article');let h=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="article-view"><span class="badge badge-ai">Short AI</span><h1 class="article-title">${esc(p.title)}</h1><video class="article-img" src="${p.video}" controls playsinline autoplay></video><p class="article-p" style="white-space:pre-wrap">${esc(p.text||'')}</p><div class="article-actions"><button onclick="window.open('${p.video}','_blank')">⬇ Mở video</button>${p.url?`<button onclick="window.open('${p.url}','_blank')">🔗 Nguồn</button>`:''}</div></div>`;document.getElementById('view-article').innerHTML=h;window.scrollTo(0,0)};
737
+ window.aiReadWallPatched=function(i){const p=patchedWall[i];if(!p)return;showView('view-article');let sources='';if(p.sources&&p.sources.length){sources='<div class="article-summary"><b>Nguồn tham khảo:</b><br>'+p.sources.slice(0,5).map(s=>`• ${esc(s.title||s.url||'Nguồn')} ${s.url?`(${esc(new URL(s.url).hostname.replace('www.',''))})`:''}`).join('<br>')+'</div>'}let voiceBox=`<div class="article-actions"><select id="ai-short-voice"><option value="nu">Giọng nữ Việt</option><option value="nam">Giọng nam Việt</option><option value="mien-nam">Giọng miền Nam</option></select><select id="ai-short-emotion"><option value="neutral">Trung tính</option><option value="urgent">Tin nhanh</option><option value="warm">Ấm áp</option><option value="serious">Nghiêm túc</option><option value="energetic">Sôi nổi</option></select><button onclick="aiMakeShortPatched(${i})">🎬 Tạo video shorts</button></div>`;let h=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="article-view"><span class="badge badge-ai">AI</span><h1 class="article-title">${esc(p.title)}</h1>${p.img?`<img class="article-img" src="${p.img}">`:''}${sources}<p class="article-p" style="white-space:pre-wrap">${esc(p.text)}</p>${p.video?`<video class="article-img" src="${p.video}" controls playsinline></video>`:''}<div class="article-actions">${p.url?`<button onclick="window.open('${p.url}','_blank')">🔗 Nguồn</button>`:''}</div>${voiceBox}</div>`;document.getElementById('view-article').innerHTML=h;window.scrollTo(0,0)};
738
+ window.aiMakeShortPatched=async function(i){const p=patchedWall[i];if(!p)return;let voice=document.getElementById('ai-short-voice')?.value||'nu';let emotion=document.getElementById('ai-short-emotion')?.value||'neutral';let voiceName={nu:'Giọng nữ Việt',nam:'Giọng nam Việt','mien-nam':'Giọng miền Nam'}[voice]||voice;let emotionName={neutral:'Trung tính',urgent:'Tin nhanh',warm:'Ấm áp',serious:'Nghiêm túc',energetic:'Sôi nổi'}[emotion]||emotion;let ok=confirm(`Quy trình tạo short AI:\n\n1) Dùng ảnh đại diện của bài hoặc tạo ảnh minh họa nếu thiếu.\n2) Rút gọn nội dung tóm tắt thành kịch bản đọc ngắn.\n3) Tự ngắt câu theo dấu câu và xuống dòng hợp lý.\n4) Tạo giọng đọc tiếng Việt: ${voiceName}.\n5) Áp dụng cảm xúc/kịch bản: ${emotionName}.\n6) Tăng tốc giọng đọc 1.2 lần.\n7) Mỗi đoạn tóm tắt sẽ là một cảnh ri��ng theo thời lượng đọc.\n8) Không thêm phụ đề; video chỉ có chữ cảnh và giọng đọc.\n9) Sau khi xong, video xuất hiện ở slide "Short AI".\n\nQuá trình có thể mất 1-3 phút. Bạn muốn bắt đầu?`);if(!ok)return;try{showProgress(`Bước 1/5: Chuẩn bị ảnh và căn chữ full width...<br>Bước 2/5: Tạo kịch bản, tự ngắt câu/xuống dòng...<br>Bước 3/5: Tạo giọng đọc ${voiceName}, cảm xúc ${emotionName}.<br>Bước 4/5: Tăng tốc 1.2x và ghép từng cảnh riêng, không phụ đề.<br>Bước 5/5: Lưu vào slide "Short AI".`);const r=await fetch('/api/ai/short/'+p.id,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice,emotion,speed:1.2})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');p.video=j.video;hideProgress();alert('Hoàn tất: video shorts đã được tạo và thêm vào slide "Short AI".');aiReadWallPatched(i);loadPatchedWall();}catch(e){hideProgress();alert('Không tạo được shorts: '+e.message)}};
739
+ window.createTopicPost=function(){let inp=document.getElementById('ai-topic-input');let topic=(inp&&inp.value||'').trim();if(!topic)return alert('Nhập chủ đề trước');fetch('/api/topic_post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({topic})}).then(r=>r.json().then(j=>({ok:r.ok,j}))).then(({ok,j})=>{if(ok&&(j.posts||j.post)){let arr=j.posts||[j.post];patchedWall=arr.concat(patchedWall.filter(x=>!arr.find(y=>y.id===x.id)));renderPatchedWall();if(inp)inp.value='';alert(`Đã lọc và tóm tắt ${arr.length} bài viết theo chủ đề lên Tường AI`);}else alert(j.error||'Lỗi tạo bài')}).catch(e=>alert(e.message||'Lỗi tạo bài'));};
740
+ window.createUrlPost=function(){let inp=document.getElementById('ai-url-input');let url=(inp&&inp.value||'').trim();if(!url)return alert('Dán URL trước');if(!/^https?:\/\//i.test(url))return alert('URL cần bắt đầu bằng http:// hoặc https://');fetch('/api/url_wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})}).then(r=>r.json().then(j=>({ok:r.ok,j}))).then(({ok,j})=>{if(ok&&j.post){patchedWall=[j.post].concat(patchedWall.filter(x=>x.id!==j.post.id));renderPatchedWall();if(inp)inp.value='';alert('Đã tóm tắt URL và đăng lên Tường AI');}else alert(j.error||'Lỗi URL')}).catch(e=>alert(e.message||'Lỗi URL'));};
741
+ window.rewriteCurrentArticle=function(){if(!window._currentArticle&&typeof _currentArticle!=='undefined')window._currentArticle=_currentArticle;let cur=window._currentArticle||_currentArticle;if(!cur)return;let btn=document.querySelector('.article-actions button.primary');if(btn){btn.textContent='Đang tóm tắt...';btn.disabled=true}fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url:cur.url})}).then(r=>r.json().then(j=>({ok:r.ok,j}))).then(({ok,j})=>{if(ok&&j.post){document.getElementById('rewrite-result').innerHTML=`<div class="rewrite-box"><div class="rewrite-title">Đã tóm tắt và đăng Tường AI</div><div class="rewrite-text">${esc(j.post.text||'')}</div></div>`;patchedWall=[j.post].concat(patchedWall.filter(x=>x.id!==j.post.id));renderPatchedWall();alert('Đã tóm tắt lên Tường AI');}else alert(j.error||'Không tóm tắt được')}).catch(e=>alert(e.message||'Lỗi tóm tắt')).finally(()=>{if(btn){btn.textContent='🤖 Tóm tắt AI & đăng tường';btn.disabled=false}})};
742
+ setTimeout(loadPatchedWall,1500);setInterval(updateAiLabels,2000);
743
+ })();
744
+ </script>
745
+ '''
746
+
747
+ @app.get('/')
748
+ async def index_patched():
749
+ with open('/app/static/index.html','r',encoding='utf-8') as f:
750
+ html=f.read()
751
+ return HTMLResponse(html.replace('</body>', PATCH_INJECT+'\n</body>'))
ai_runtime_final6.py CHANGED
@@ -1,849 +1,394 @@
1
- """Final6: robust topic synthesis, stable shorts, hot topic hashtags.
2
-
3
- This runtime intentionally overrides only the topic/shorts/root endpoints from the restored app.
4
- """
5
- import re, time, json, os, threading, html as html_lib
6
- from urllib.parse import quote, urlparse, parse_qs, unquote
7
- import requests
8
- from bs4 import BeautifulSoup
9
  import ai_runtime_final5 as f5
10
- from ai_runtime_final5 import app, rt, HTMLResponse, JSONResponse, Request, Query
 
11
 
12
- _PATCH={('/api/topic_post','POST'),('/api/shorts','GET'),('/api/hot_topics','GET'),('/api/topic_sources','GET'),('/','GET')}
13
- app.router.routes=[r for r in app.router.routes if not any(getattr(r,'path',None)==p and m in getattr(r,'methods',set()) for p,m in _PATCH)]
 
 
 
 
 
 
14
 
15
- _TOPIC_CACHE={}
16
- _HOT_CACHE={"t":0,"d":[]}
17
- _SHORTS_CACHE_FINAL6={"t":0,"d":[]}
18
- _TRANSLATE_CACHE_PATH="/data/title_vi_cache.json" if os.path.isdir('/data') else "/app/data/title_vi_cache.json"
19
- _translate_lock=threading.Lock()
20
- YOUTUBE_HANDLES=["baodantri7941","baosuckhoedoisongboyte"]
21
- UA={"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,en;q=0.8"}
22
- STOP_WORDS=set('và của các những một được trong với cho tại sau trước khi không người việt nam hôm nay mới nhất nóng tin tức cập nhật'.split())
23
- TRUSTED_SITES=['vnexpress.net','dantri.com.vn','vietnamnet.vn','tuoitre.vn','thanhnien.vn','laodong.vn','vov.vn','vtv.vn','genk.vn','cafef.vn','thethaovanhoa.vn']
24
 
25
- def clean(s):return re.sub(r"\s+"," ",html_lib.unescape(str(s or ""))).strip()
26
  def _domain(u):
27
- try:return urlparse(u or '').netloc.replace('www.','')
28
- except Exception:return ''
29
-
30
- def _load_title_cache():
31
- try:
32
- if os.path.exists(_TRANSLATE_CACHE_PATH):
33
- with open(_TRANSLATE_CACHE_PATH,'r',encoding='utf-8') as f:return json.load(f)
34
- except Exception:pass
35
- return {}
36
- def _save_title_cache(db):
37
- try:
38
- os.makedirs(os.path.dirname(_TRANSLATE_CACHE_PATH),exist_ok=True);tmp=_TRANSLATE_CACHE_PATH+'.tmp'
39
- with open(tmp,'w',encoding='utf-8') as f:json.dump(db,f,ensure_ascii=False)
40
- os.replace(tmp,_TRANSLATE_CACHE_PATH)
41
- except Exception:pass
42
-
43
- def _looks_vietnamese(s):
44
- s=s or ''
45
- if re.search(r'[àáạảãâầấậẩẫăằắặẳẵèéẹẻẽêềếệểễìíịỉĩòóọỏõôồốộổỗơờớợởỡùúụủũưừứựửữỳýỵỷỹđ]',s,re.I):return True
46
- low=' '+s.lower()+' '
47
- return any(w in low for w in [' và ',' của ',' người ',' tại ',' trong ',' với ',' không ',' được ',' công an ',' bệnh viện ',' học sinh ',' tài xế ',' bóng đá ',' tin tức ',' sức khỏe '])
48
- def _translate_title_vi(title):
49
- title=clean(title)
50
- if not title or _looks_vietnamese(title):return title
51
- with _translate_lock:
52
- db=_load_title_cache()
53
- if title in db:return db[title]
54
- vi=title
55
- try:
56
- r=requests.get('https://translate.googleapis.com/translate_a/single',params={'client':'gtx','sl':'auto','tl':'vi','dt':'t','q':title},headers=UA,timeout=8)
57
- if r.status_code==200:
58
- data=r.json();vi=''.join(part[0] for part in data[0] if part and part[0]).strip() or title
59
- except Exception:pass
60
- vi=clean(vi)
61
- with _translate_lock:
62
- db=_load_title_cache();db[title]=vi;_save_title_cache(db)
63
- return vi
64
 
65
- # ===== Hot topics / hashtags =====
66
- def _keywords_from_title(title):
67
- title=clean(re.sub(r'\s+-\s+.*$','',title))
68
- words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',title) if len(w)>2 and w.lower() not in STOP_WORDS]
69
- phrases=[]
70
- for n in (4,3,2):
71
- for i in range(0,max(0,len(words)-n+1)):
72
- ph=' '.join(words[i:i+n]).strip()
73
- if len(ph)>=8:phrases.append(ph)
74
- if words:phrases.append(' '.join(words[:5]))
75
- return phrases[:4]
76
-
77
- def _hot_topics():
78
- now=time.time()
79
- if _HOT_CACHE['d'] and now-_HOT_CACHE['t']<900:return _HOT_CACHE['d']
80
- topics=[];seen=set()
81
- feeds=[
82
- 'https://news.google.com/rss?hl=vi&gl=VN&ceid=VN:vi',
83
- 'https://news.google.com/rss/headlines/section/topic/NATION?hl=vi&gl=VN&ceid=VN:vi',
84
- 'https://news.google.com/rss/headlines/section/topic/BUSINESS?hl=vi&gl=VN&ceid=VN:vi',
85
- 'https://news.google.com/rss/headlines/section/topic/SPORTS?hl=vi&gl=VN&ceid=VN:vi',
86
- 'https://news.google.com/rss/headlines/section/topic/TECHNOLOGY?hl=vi&gl=VN&ceid=VN:vi'
87
- ]
88
- for feed in feeds:
89
- try:
90
- r=requests.get(feed,headers=UA,timeout=10);r.encoding='utf-8'
91
- soup=BeautifulSoup(r.text,'xml')
92
- for it in soup.find_all('item')[:15]:
93
- title=clean(it.find('title').get_text(' ',strip=True) if it.find('title') else '')
94
- for kw in _keywords_from_title(title):
95
- key=kw.lower()
96
- if key not in seen and len(kw)<=60:
97
- seen.add(key);topics.append({'label':'#'+re.sub(r'\s+','',kw.title()),'topic':kw})
98
- if len(topics)>=24:break
99
- if len(topics)>=24:break
100
- except Exception:pass
101
- if len(topics)>=24:break
102
- for kw in ['AI trong giáo dục','World Cup 2026','kinh tế Việt Nam','biến đổi khí hậu','giá vàng','bóng đá Việt Nam','an ninh mạng','xe điện','sức khỏe tinh thần','thị trường chứng khoán']:
103
- if kw.lower() not in seen:topics.append({'label':'#'+re.sub(r'\s+','',kw.title()),'topic':kw})
104
- _HOT_CACHE.update({'t':now,'d':topics[:24]})
105
- return _HOT_CACHE['d']
106
- @app.get('/api/hot_topics')
107
- def api_hot_topics():return JSONResponse({'topics':_hot_topics()})
108
-
109
- # ===== Topic web research =====
110
- def _unwrap_ddg_href(href):
111
- if not href:return ''
112
- if href.startswith('//duckduckgo.com/l/?') or 'duckduckgo.com/l/?' in href:
113
- qs=parse_qs(urlparse('https:'+href if href.startswith('//') else href).query)
114
- return unquote(qs.get('uddg',[''])[0])
115
- return href
116
-
117
- def _ddg_search(query, limit=10):
118
- items=[];seen=set()
119
  try:
120
- url='https://html.duckduckgo.com/html/?q='+quote(query)
121
- r=requests.get(url,headers=UA,timeout=14);r.encoding='utf-8'
122
- soup=BeautifulSoup(r.text,'lxml')
123
- for res in soup.select('.result'):
124
- a=res.select_one('.result__title a') or res.find('a',href=True)
125
- if not a:continue
126
- link=_unwrap_ddg_href(a.get('href',''));title=clean(a.get_text(' ',strip=True));snippet=clean((res.select_one('.result__snippet') or res).get_text(' ',strip=True))
127
- if not link.startswith('http') or link in seen:continue
128
- if any(bad in link for bad in ['duckduckgo.com','youtube.com','facebook.com','tiktok.com','twitter.com','x.com']):continue
129
- seen.add(link);items.append({'title':title,'url':link,'source':_domain(link),'snippet':snippet})
130
- if len(items)>=limit:break
131
- except Exception:pass
132
- return items
133
 
134
- def _google_news_items(topic, limit=8):
135
- items=[];seen=set()
136
  try:
137
- rss='https://news.google.com/rss/search?q='+quote(topic)+'&hl=vi&gl=VN&ceid=VN:vi'
138
- r=requests.get(rss,headers=UA,timeout=12);r.encoding='utf-8'
139
- soup=BeautifulSoup(r.text,'xml')
140
- for it in soup.find_all('item')[:limit*2]:
141
- title=clean(it.find('title').get_text(' ',strip=True) if it.find('title') else '')
142
- link=clean(it.find('link').get_text(strip=True) if it.find('link') else '')
143
- src=clean(it.find('source').get_text(' ',strip=True) if it.find('source') else _domain(link))
144
- if title and link and link not in seen:
145
- seen.add(link);items.append({'title':title,'url':link,'source':src,'snippet':''})
146
- if len(items)>=limit:break
147
- except Exception:pass
148
- return items
149
-
150
- def _candidate_urls(topic):
151
- seen=set();items=[]
152
- queries=[topic+' tin tức Việt Nam', topic+' phân tích bối cảnh', topic+' site:vnexpress.net OR site:dantri.com.vn OR site:vietnamnet.vn']
153
- for q in queries:
154
- for it in _ddg_search(q,8):
155
- if it['url'] not in seen:
156
- seen.add(it['url']);items.append(it)
157
- if len(items)>=12:break
158
- for site in TRUSTED_SITES[:8]:
159
- for it in _ddg_search(f'{topic} site:{site}',3):
160
- if it['url'] not in seen:
161
- seen.add(it['url']);items.append(it)
162
- for it in _google_news_items(topic,8):
163
- if it['url'] not in seen:
164
- seen.add(it['url']);items.append(it)
165
- return items[:24]
166
 
167
- def _extract_article_text_bs(url, max_chars=9000):
168
  try:
169
- r=requests.get(url,headers=UA,timeout=16,allow_redirects=True)
170
- if r.status_code>=400:return ''
171
- r.encoding='utf-8';soup=BeautifulSoup(r.text,'lxml')
172
- for tag in soup.find_all(['script','style','nav','footer','aside','form','noscript','iframe','svg']):tag.decompose()
173
- candidates=[]
174
- for sel in ['article','main','.article-content','.detail-content','.singular-content','.fck_detail','.content-detail','.entry-content','.story-body','.knc-content']:
175
- el=soup.select_one(sel)
176
- if el:candidates.append(el)
177
- if not candidates:candidates=[soup.body or soup]
178
- best=max(candidates,key=lambda el:len(el.find_all('p')) if el else 0)
179
- ps=[]
180
- for el in best.find_all(['p','h2','h3'],recursive=True):
181
- t=clean(el.get_text(' ',strip=True))
182
- if len(t)>45 and not any(x in t.lower() for x in ['đăng ký nhận tin','theo dõi chúng tôi','chuyên mục','xem thêm','tin liên quan','advertisement']):ps.append(t)
183
- if sum(len(x) for x in ps)>max_chars:break
184
- return '\n'.join(ps)[:max_chars]
185
- except Exception:return ''
186
 
187
- def _jina_read_text(url, max_chars=9000):
188
  try:
189
- ju='https://r.jina.ai/http://'+url
190
- r=requests.get(ju,headers=UA,timeout=28);r.encoding='utf-8'
191
- if r.status_code!=200 or not r.text:return ''
192
- lines=[]
193
- for ln in r.text.splitlines():
194
- t=clean(ln)
195
- if not t or t.startswith(('Title:','URL Source:','Published Time:','Markdown Content:','Image:','Description:')):continue
196
- if len(t)>45:lines.append(t)
197
- if sum(len(x) for x in lines)>max_chars:break
198
- return '\n'.join(lines)[:max_chars]
199
- except Exception:return ''
200
-
201
- def _scrape_article_text(url, max_chars=9000):
202
- text=_extract_article_text_bs(url,max_chars)
203
- if len(text)<350:text=_jina_read_text(url,max_chars)
204
- return text
205
 
206
- def _score_relevance(topic, title, text, snippet=''):
207
- keys=[w.lower() for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',topic) if len(w)>2 and w.lower() not in STOP_WORDS]
208
- hay=(title+' '+snippet+' '+text[:2500]).lower()
209
- if not keys:return 1
210
- return sum(1 for k in keys if k in hay)
 
 
 
 
 
 
 
 
211
 
212
- def _web_research_context(topic):
213
- now=time.time();key=topic.lower().strip()
214
- if key in _TOPIC_CACHE and now-_TOPIC_CACHE[key]['t']<900:return _TOPIC_CACHE[key]['d']
215
- items=_candidate_urls(topic)
216
- crawled=[]
217
- for it in items:
218
- text=_scrape_article_text(it['url'],9000)
219
- rel=_score_relevance(topic,it.get('title',''),text,it.get('snippet',''))
220
- if text and len(text)>300 and rel>0:
221
- crawled.append({**it,'text':text,'rel':rel})
222
- elif it.get('snippet') and rel>0:
223
- crawled.append({**it,'text':it['snippet'],'rel':rel,'snippet_only':True})
224
- crawled=sorted(crawled,key=lambda x:(x.get('rel',0),len(x.get('text',''))),reverse=True)[:6]
225
- blocks=[];sources=[]
226
- for it in crawled:
227
- label='ĐOẠN MÔ TẢ TỪ KẾT QUẢ TÌM KIẾM' if it.get('snippet_only') else 'NỘI DUNG BÀI VIẾT ĐÃ CRAWL'
228
- blocks.append(f"NGUỒN: {it['source']}\nTIÊU ĐỀ: {it['title']}\n{label}:\n{it['text'][:8500]}")
229
- sources.append({'title':it['title'],'url':it['url'],'via':it['source']})
230
- data={'context':'\n\n---\n\n'.join(blocks),'sources':sources[:8],'count':len(blocks)}
231
- _TOPIC_CACHE[key]={'t':now,'d':data}
232
- return data
233
 
234
  def _topic_image(topic):
235
- try:return f5.base.pollinations_image_url(topic)
236
- except Exception:return 'https://image.pollinations.ai/prompt/'+quote('Vietnamese editorial illustration, '+topic)+'?width=1024&height=576&nologo=true'
237
-
238
- @app.get('/api/topic_sources')
239
- def api_topic_sources(topic:str=Query(...)):
240
- data=_web_research_context(clean(topic))
241
- return JSONResponse({'count':data.get('count',0),'sources':data.get('sources',[]),'has_context':bool(data.get('context'))})
242
 
243
- @app.post('/api/topic_post')
244
- async def topic_post_synthesis(request:Request):
245
- body=await request.json();topic=clean(body.get('topic',''))
246
- if not topic:return JSONResponse({'error':'missing topic'},status_code=400)
247
- img=_topic_image(topic);research=_web_research_context(topic);context=research.get('context','');sources=research.get('sources',[])
248
- if not context or research.get('count',0)==0:
249
- return JSONResponse({'error':'Không tìm/crawl được đủ nội dung về chủ đề này. Hãy thử chủ đề cụ thể hơn hoặc dùng hashtag gợi ý.'},status_code=422)
250
- prompt=f"""Bạn biên tập viên VNEWS. Người dùng chọn chủ đề: "{topic}".
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
 
252
- Dưới đây NỘI DUNG các bài viết/đoạn mô tả đã crawl từ internet. Hãy đọc hiểu và TỔNG HỢP thành MỘT BÀI VIẾT HOÀN CHỈNH. Tuyệt đối không bê nguyên văn, không xếp danh sách tiêu đề thành bài viết, không viết kiểu trả lời chat.
 
 
253
 
254
- DỮ LIỆU CRAWL:
255
- {context[:30000]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
 
257
- Yêu cầu bắt buộc:
258
- - Viết bằng tiếng Việt, văn phong báo điện tử/tạp chí.
259
- - Tiêu đề mới, rõ, hấp dẫn.
260
- - Sapo 2-3 câu nêu vấn đề chính.
261
- - 5-8 đoạn nội dung tổng hợp: bối cảnh, diễn biến/khái niệm, phân tích, tác động, điểm cần lưu ý.
262
- - Dùng thông tin từ nội dung đã crawl để tổng hợp ý; nếu chỉ có mô tả tìm kiếm thì viết thận trọng.
263
- - KHÔNG liệt kê các tiêu đề nguồn. KHÔNG mở đầu bằng "Dưới đây là" hay "Tôi sẽ".
264
- - Cuối bài thêm mục "Nguồn tham khảo" gồm tên nguồn ngắn gọn.
265
- """
266
- text=await f5.base.qwen_generate(prompt,image_url=img,max_tokens=2800)
267
- if not text or len(text)<500:
268
- parts=[]
269
- for block in context.split('---'):
270
- body=block.split('NỘI DUNG BÀI VIẾT ĐÃ CRAWL:')[-1].split('ĐOẠN MÔ TẢ TỪ KẾT QUẢ TÌM KIẾM:')[-1].strip()
271
- if len(body)>120:parts.append(body)
272
- joined='\n\n'.join(parts)[:8500]
273
- text=(f"{topic}: những điểm chính cần biết\n\n{topic} đang thu hút sự chú ý vì liên quan đến nhiều khía cạnh thực tế. Tổng hợp từ các nội dung thu thập được, có thể nhìn vấn đề qua bối cảnh, tác động và những điểm cần theo dõi.\n\n"+joined+"\n\nNguồn tham khảo: "+', '.join(sorted({s.get('via','') for s in sources if s.get('via')})))
274
- post=f5.base.make_post(topic,text,img,'','topic_web_synthesis',sources=[s for s in sources if s.get('url')]);post['images']=[img]
275
- posts=f5.base._load_ai_wall();posts.insert(0,post);f5.base._save_ai_wall(posts)
276
- return JSONResponse({'post':post})
277
 
278
- # ===== Stable newest Dantri/SKDS Shorts =====
279
- def _yt_ytdlp(handle,count=30):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  try:
281
- import yt_dlp
282
- urls=[f'https://www.youtube.com/@{handle}/shorts',f'https://www.youtube.com/@{handle}/videos']
283
- out=[];seen=set();opts={'quiet':True,'extract_flat':True,'skip_download':True,'playlistend':count,'ignoreerrors':True,'no_warnings':True,'extractor_args':{'youtube':{'player_client':['web']}}}
284
- for url in urls:
285
- with yt_dlp.YoutubeDL(opts) as ydl:info=ydl.extract_info(url,download=False)
286
- for e in (info or {}).get('entries') or []:
287
- vid=e.get('id') or ''
288
- if not re.match(r'^[A-Za-z0-9_-]{11}$',vid) or vid in seen:continue
289
- title=e.get('title') or 'YouTube Short'
290
- if url.endswith('/videos') and '#short' not in title.lower() and 'shorts' not in title.lower():continue
291
- seen.add(vid);out.append({'title':title,'link':'https://www.youtube.com/watch?v='+vid,'img':'https://i.ytimg.com/vi/'+vid+'/hqdefault.jpg','source':'yt','id':vid,'channel':handle})
292
- if len(out)>=count:break
293
- if len(out)>=count:break
294
- return out
295
- except Exception:return []
296
- def _yt_html(handle,count=30):
297
- out=[];seen=set()
298
- for suffix in ['shorts','videos']:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  try:
300
- r=requests.get(f'https://www.youtube.com/@{handle}/{suffix}',headers=UA,timeout=15);html=r.text
301
- for m in re.finditer(r'"videoId":"([A-Za-z0-9_-]{11})"',html):
302
- vid=m.group(1)
303
- if vid in seen:continue
304
- snip=html[max(0,m.start()-1200):m.start()+2200];title='YouTube Short'
305
- mt=re.search(r'"title":\{"runs":\[\{"text":"([^"]+)"',snip) or re.search(r'"accessibilityText":"([^"]+)"',snip)
306
- if mt:title=clean(mt.group(1).replace('\\n',' '))
307
- if suffix=='videos' and '#short' not in title.lower() and 'shorts' not in title.lower():continue
308
- seen.add(vid);out.append({'title':title,'link':'https://www.youtube.com/watch?v='+vid,'img':'https://i.ytimg.com/vi/'+vid+'/hqdefault.jpg','source':'yt','id':vid,'channel':handle})
309
- if len(out)>=count:break
310
- except Exception:pass
311
- if len(out)>=count:break
312
- return out[:count]
313
- def _fallback_shorts():
314
- try:return f5._fallback_shorts()
315
- except Exception:return []
316
- @app.get('/api/shorts')
317
- def api_shorts_final6(refresh:int=Query(default=0)):
318
- now=time.time()
319
- if not refresh and _SHORTS_CACHE_FINAL6['d'] and now-_SHORTS_CACHE_FINAL6['t']<600:return JSONResponse(_SHORTS_CACHE_FINAL6['d'])
320
- raw=[]
321
- for h in YOUTUBE_HANDLES:raw.extend(_yt_ytdlp(h,30) or _yt_html(h,30))
322
- raw.extend(_fallback_shorts())
323
- seen=set();out=[]
324
- for v in raw:
325
- vid=v.get('id') or ''
326
- if not vid:
327
- m=re.search(r'(?:v=|shorts/|youtu\.be/)([A-Za-z0-9_-]{11})',v.get('link',''));vid=m.group(1) if m else ''
328
- title=_translate_title_vi(v.get('title') or 'YouTube Short');key=vid or re.sub(r'\W+','',title.lower())[:80]
329
- if not key or key in seen:continue
330
- seen.add(key);item=dict(v);item['id']=vid;item['title']=title
331
- if vid:item['link']='https://www.youtube.com/watch?v='+vid;item['img']='https://i.ytimg.com/vi/'+vid+'/hqdefault.jpg'
332
- item['source']='yt';out.append(item)
333
- if len(out)>=40:break
334
- _SHORTS_CACHE_FINAL6.update({'t':now,'d':out})
335
- return JSONResponse(out)
336
 
337
- FINAL6_INJECT=r'''
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  <style>
339
- #ai-topic-input-final3,.topic-final3,#ai-topic-input-final4,.topic-final4{display:none!important}.topic-final5{display:flex!important}.ai-wall-topic-live{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}.hot-topic-row{display:flex;gap:6px;overflow-x:auto;padding:4px 0}.hot-chip{flex:0 0 auto;background:#222;border:1px solid #333;color:#ddd;border-radius:16px;padding:5px 10px;font-size:11px;cursor:pointer}.hot-chip:active{transform:scale(.96)}.topic-source-note{font-size:10px;color:#777;margin-top:4px;line-height:1.3}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
  </style>
341
  <script>
342
  (function(){
343
  function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));}
344
- let liveTopicWall=[];
345
- async function ensureHotTopics(){let inp=document.getElementById('ai-topic-input-final5');if(!inp||document.getElementById('hot-topic-row-final6'))return;let row=document.createElement('div');row.id='hot-topic-row-final6';row.className='hot-topic-row';row.innerHTML='<span style="color:#777;font-size:11px;padding:5px 0">Đang tải từ khóa nóng...</span>';inp.insertAdjacentElement('afterend',row);let note=document.createElement('div');note.id='topic-source-note';note.className='topic-source-note';note.textContent='AI sẽ tìm nhiều nguồn, crawl nội dung bài viết rồi tổng hợp thành bài mới.';row.insertAdjacentElement('afterend',note);let j=await fetch('/api/hot_topics').then(r=>r.json()).catch(()=>({topics:[]}));let topics=j.topics||[];row.innerHTML=topics.slice(0,18).map(t=>`<button class="hot-chip" onclick="document.getElementById('ai-topic-input-final5').value='${esc(t.topic).replace(/'/g,'\\\'')}';document.getElementById('ai-topic-input-final5').focus();">${esc(t.label)}</button>`).join('')||'';}
346
- async function ensureNewsShortsHome(){if(!document.getElementById('view-home')?.classList.contains('active'))return;let labels=[...document.querySelectorAll('.slider-wrap .slider-label')];let wraps=labels.filter(l=>/shorts|short /i.test(l.textContent||'')&&!/short ai/i.test(l.textContent||'')).map(l=>l.closest('.slider-wrap')).filter(Boolean);wraps.forEach((w,i)=>{if(i>0)w.remove();});let w=wraps[0];if(w){let seen=new Set();[...w.querySelectorAll('.slider-item')].forEach(it=>{let img=it.querySelector('img')?.src||'';let tt=(it.querySelector('.slider-title')?.textContent||'').trim().toLowerCase();let k=img||tt;if(k&&seen.has(k))it.remove();else if(k)seen.add(k);});if(w.querySelectorAll('.slider-item').length>=6)return;w.remove();}let sh=await fetch('/api/shorts?refresh=1').then(r=>r.json()).catch(()=>[]);if(!sh.length)return;let wrap=document.createElement('div');wrap.className='slider-wrap';wrap.id='shorts-final6-stable';let h='<div class="slider-header"><span class="slider-label">📱 Shorts Dân trí & SKĐS</span><span class="slider-note">Mới nhất</span></div><div class="slider-track">';sh.slice(0,30).forEach((a,i)=>{h+=`<div class="slider-item shorts-item" onclick="openTikTok('shorts',${i})"><div class="slider-thumb shorts-thumb">${a.img?`<img src="${esc(a.img)}">`:''}<div class="card-play">▶</div></div><div class="slider-title">${esc(a.title)}</div></div>`});h+='</div>';wrap.innerHTML=h;let comp=document.querySelector('.ai-compose')||document.getElementById('view-home').firstChild;if(comp)comp.after(wrap);else document.getElementById('view-home').prepend(wrap);}
347
- function renderLiveTopicWall(){let home=document.getElementById('view-home');if(!home||!liveTopicWall.length)return;document.getElementById('ai-wall-topic-live')?.remove();let wrap=document.createElement('div');wrap.id='ai-wall-topic-live';wrap.className='ai-wall-topic-live';let h='<div class="slider-header"><span class="slider-label">🧱 Tường AI mới</span><span class="slider-note">Tổng hợp từ web</span></div><div class="slider-track">';liveTopicWall.slice(0,20).forEach((p,i)=>{h+=`<div class="wall-item"><div class="wall-thumb">${p.img?`<img src="${esc(p.img)}">`:''}</div><div class="wall-title">${esc(p.title)}</div><div class="wall-text">${esc(p.text)}</div><div class="wall-actions"><button class="primary" onclick="readLiveTopicWall(${i})">Xem</button></div></div>`});h+='</div>';wrap.innerHTML=h;let comp=document.querySelector('.ai-compose');if(comp)comp.after(wrap);else home.prepend(wrap);}
348
- window.readLiveTopicWall=function(i){let p=liveTopicWall[i];if(!p)return;showView('view-article');let imgs=(p.images||[]).filter(Boolean);let gal=imgs.length?'<div class="ai-wall-gallery">'+imgs.slice(0,12).map(u=>`<img src="${esc(u)}" loading="lazy">`).join('')+'</div>':(p.img?`<img class="article-img" src="${esc(p.img)}">`:'');document.getElementById('view-article').innerHTML=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="article-view"><span class="badge badge-ai">AI</span><h1 class="article-title">${esc(p.title)}</h1>${gal}<p class="article-p" style="white-space:pre-wrap">${esc(p.text)}</p><div class="article-actions"><button onclick="shareAI?shareAI(${JSON.stringify(p).replace(/"/g,'&quot;')},false):navigator.clipboard.writeText(location.href)">📤 Chia sẻ</button></div></div>`;window.scrollTo(0,0)};
349
- window.createTopicPostFinal5=async function(){let inp=document.getElementById('ai-topic-input-final5');let topic=(inp&&inp.value||'').trim();if(!topic)return alert('Nhập chủ đề trước');let btn=document.getElementById('ai-topic-btn-final5');if(btn){btn.disabled=true;btn.textContent='Đang tìm nguồn...'}try{let src=await fetch('/api/topic_sources?topic='+encodeURIComponent(topic)).then(r=>r.json()).catch(()=>null);if(btn&&src)btn.textContent='Đã tìm '+(src.count||0)+' nguồn, đang tổng hợp...';let r=await fetch('/api/topic_post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({topic})});let j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');liveTopicWall.unshift(j.post);if(inp)inp.value='';renderLiveTopicWall();readLiveTopicWall(0);alert('Đã tạo bài tổng hợp từ nội dung web và đăng lên Tường AI.');}catch(e){alert(e.message)}finally{if(btn){btn.disabled=false;btn.textContent='✨ Tạo bài tổng hợp từ web bằng Qwen'}}};
350
- setInterval(()=>{document.querySelectorAll('#ai-topic-input-final3,.topic-final3,#ai-topic-input-final4,.topic-final4').forEach(e=>(e.closest('.topic-final3,.topic-final4,.ai-compose-row')||e).remove());let b=document.getElementById('ai-topic-btn-final5');if(b){b.style.display='block';b.textContent='✨ Tạo bài tổng hợp từ web bằng Qwen';}ensureHotTopics();ensureNewsShortsHome();},1200);setTimeout(()=>{ensureHotTopics();ensureNewsShortsHome();},1200);
351
  })();
352
  </script>
353
  '''
354
 
355
- @app.get('/')
356
- async def index_final6():
357
- html=f5.f4.f3.f2.f1._load_index_html()
358
- body=getattr(rt.old,'PATCH_INJECT','')+f5.f4.f3.f2.f1.FINAL_INJECT+f5.f4.f3.FINAL3_INJECT+f5.f4.FINAL4_INJECT+f5.FINAL5_INJECT+FINAL6_INJECT
359
- return HTMLResponse(html.replace('</body>',body+'\n</body>') if '</body>' in html else html+body)
360
-
361
-
362
- # ===== FINAL6B: Vietnam hot hashtags + reliable VN RSS/source retrieval =====
363
- VN_RSS_FEEDS = [
364
- ('VnExpress Thời sự','https://vnexpress.net/rss/thoi-su.rss'),
365
- ('VnExpress Thế giới','https://vnexpress.net/rss/the-gioi.rss'),
366
- ('VnExpress Kinh doanh','https://vnexpress.net/rss/kinh-doanh.rss'),
367
- ('VnExpress Công nghệ','https://vnexpress.net/rss/so-hoa.rss'),
368
- ('VnExpress Thể thao','https://vnexpress.net/rss/the-thao.rss'),
369
- ('VnExpress Giải trí','https://vnexpress.net/rss/giai-tri.rss'),
370
- ('VnExpress Sức khỏe','https://vnexpress.net/rss/suc-khoe.rss'),
371
- ('VnExpress Giáo dục','https://vnexpress.net/rss/giao-duc.rss'),
372
- ('Dân trí Xã hội','https://dantri.com.vn/rss/xa-hoi.rss'),
373
- ('Dân trí Thế giới','https://dantri.com.vn/rss/the-gioi.rss'),
374
- ('Dân trí Kinh doanh','https://dantri.com.vn/rss/kinh-doanh.rss'),
375
- ('Dân trí Sức khỏe','https://dantri.com.vn/rss/suc-khoe.rss'),
376
- ('Dân trí Thể thao','https://dantri.com.vn/rss/the-thao.rss'),
377
- ('Dân trí Công nghệ','https://dantri.com.vn/rss/suc-manh-so.rss'),
378
- ('Vietnamnet Thời sự','https://vietnamnet.vn/thoi-su.rss'),
379
- ('Vietnamnet Kinh doanh','https://vietnamnet.vn/kinh-doanh.rss'),
380
- ('Vietnamnet Công nghệ','https://vietnamnet.vn/cong-nghe.rss'),
381
- ('Vietnamnet Thể thao','https://vietnamnet.vn/the-thao.rss'),
382
- ]
383
-
384
- def _fetch_rss_items(feed_name, feed_url, max_items=15):
385
- items=[]
386
- try:
387
- r=requests.get(feed_url,headers=UA,timeout=10);r.encoding='utf-8'
388
- soup=BeautifulSoup(r.text,'xml')
389
- for it in soup.find_all('item')[:max_items]:
390
- title=clean(it.find('title').get_text(' ',strip=True) if it.find('title') else '')
391
- link=clean(it.find('link').get_text(strip=True) if it.find('link') else '')
392
- desc=it.find('description').get_text(' ',strip=True) if it.find('description') else ''
393
- desc_txt=clean(BeautifulSoup(desc,'lxml').get_text(' ',strip=True))
394
- if title and link:
395
- items.append({'title':title,'url':link,'source':feed_name,'snippet':desc_txt})
396
- except Exception:pass
397
- return items
398
-
399
- def _vn_rss_pool():
400
- now=time.time();key='vn_rss_pool'
401
- if key in _TOPIC_CACHE and now-_TOPIC_CACHE[key]['t']<600:return _TOPIC_CACHE[key]['d']
402
- pool=[];seen=set()
403
- for name,url in VN_RSS_FEEDS:
404
- for it in _fetch_rss_items(name,url,12):
405
- if it['url'] not in seen:
406
- seen.add(it['url']);pool.append(it)
407
- _TOPIC_CACHE[key]={'t':now,'d':pool}
408
- return pool
409
-
410
- def _topic_tokens(topic):
411
- toks=[w.lower() for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',topic or '') if len(w)>1]
412
- return [t for t in toks if t not in STOP_WORDS]
413
-
414
- def _score_topic_item(topic,item):
415
- toks=_topic_tokens(topic)
416
- hay=(item.get('title','')+' '+item.get('snippet','')+' '+item.get('source','')).lower()
417
- if not toks:return 0
418
- score=0
419
- for t in toks:
420
- if t in hay:score+=2 if len(t)>3 else 1
421
- phrase=topic.lower().strip()
422
- if phrase and phrase in hay:score+=8
423
- return score
424
-
425
- # Override: hashtags must be Việt Nam-focused, using VN news RSS directly.
426
- def _hot_topics():
427
- now=time.time()
428
- if _HOT_CACHE['d'] and now-_HOT_CACHE['t']<600:return _HOT_CACHE['d']
429
- pool=_vn_rss_pool()
430
- freq={};display={}
431
- for it in pool[:180]:
432
- title=re.sub(r'\s+-\s+.*$','',it.get('title',''))
433
- # Extract compact Vietnamese hot phrases from current VN headlines.
434
- kws=[]
435
- # quoted/name phrases first
436
- for m in re.findall(r'([A-ZĐÀ-Ỹ][A-Za-zÀ-ỹ0-9]+(?:\s+[A-ZĐÀ-ỸA-Za-zÀ-ỹ0-9][A-Za-zÀ-ỹ0-9]+){1,4})',title):
437
- if len(m)>=6:kws.append(m)
438
- kws += _keywords_from_title(title)
439
- for kw in kws[:5]:
440
- kw=clean(kw)
441
- words=[w for w in kw.split() if w.lower() not in STOP_WORDS]
442
- if len(words)<2:continue
443
- kw=' '.join(words[:5])
444
- if len(kw)<6 or len(kw)>55:continue
445
- key=kw.lower()
446
- freq[key]=freq.get(key,0)+1
447
- display[key]=kw
448
- ranked=sorted(freq.items(),key=lambda x:x[1],reverse=True)
449
- topics=[];seen=set()
450
- for key,_ in ranked:
451
- kw=display[key]
452
- if key in seen:continue
453
- seen.add(key)
454
- label='#'+re.sub(r'\s+','',kw.title())
455
- topics.append({'label':label,'topic':kw})
456
- if len(topics)>=24:break
457
- # VN fallback, not generic global.
458
- for kw in ['Giá vàng trong nước','Bão và mưa lũ','Bóng đá Việt Nam','Kinh tế Việt Nam','AI tại Việt Nam','Giá xăng dầu','Thị trường chứng khoán Việt Nam','Tuyển Việt Nam','Sức khỏe cộng đồng','An ninh mạng Việt Nam']:
459
- if kw.lower() not in seen:topics.append({'label':'#'+re.sub(r'\s+','',kw.title()),'topic':kw})
460
- _HOT_CACHE.update({'t':now,'d':topics[:24]})
461
- return _HOT_CACHE['d']
462
-
463
- def _candidate_urls(topic):
464
- seen=set();items=[]
465
- # 1) VN RSS pool relevance is most reliable and has direct URLs.
466
- scored=[]
467
- for it in _vn_rss_pool():
468
- sc=_score_topic_item(topic,it)
469
- if sc>0:scored.append((sc,it))
470
- for sc,it in sorted(scored,key=lambda x:x[0],reverse=True)[:12]:
471
- if it['url'] not in seen:
472
- seen.add(it['url']);items.append(it)
473
- # 2) Search trusted web if RSS not enough.
474
- queries=[topic+' Việt Nam tin tức',topic+' phân tích Việt Nam',topic+' mới nhất']
475
- for q in queries:
476
- for it in _ddg_search(q,8):
477
- if it['url'] not in seen:
478
- seen.add(it['url']);items.append(it)
479
- if len(items)>=14:break
480
- # 3) Google News as supplemental titles/direct links.
481
- for it in _google_news_items(topic,10):
482
- if it['url'] not in seen:
483
- seen.add(it['url']);items.append(it)
484
- return items[:24]
485
-
486
- def _web_research_context(topic):
487
- now=time.time();key='ctx2:'+topic.lower().strip()
488
- if key in _TOPIC_CACHE and now-_TOPIC_CACHE[key]['t']<900:return _TOPIC_CACHE[key]['d']
489
- items=_candidate_urls(topic)
490
- crawled=[]
491
- for it in items:
492
- text=_scrape_article_text(it['url'],9000)
493
- rel=_score_relevance(topic,it.get('title',''),text,it.get('snippet','')) or _score_topic_item(topic,it)
494
- # If RSS item has good snippet, keep it even when full text blocks.
495
- if text and len(text)>300 and rel>0:
496
- crawled.append({**it,'text':text,'rel':rel})
497
- elif it.get('snippet') and len(it['snippet'])>120 and rel>0:
498
- crawled.append({**it,'text':it['snippet'],'rel':rel,'snippet_only':True})
499
- crawled=sorted(crawled,key=lambda x:(x.get('rel',0),len(x.get('text',''))),reverse=True)[:7]
500
- blocks=[];sources=[]
501
- for it in crawled:
502
- label='ĐOẠN MÔ TẢ TỪ RSS/TÌM KIẾM' if it.get('snippet_only') else 'NỘI DUNG BÀI VIẾT ĐÃ CRAWL'
503
- blocks.append(f"NGUỒN: {it['source']}\nTIÊU ĐỀ: {it['title']}\n{label}:\n{it['text'][:8500]}")
504
- sources.append({'title':it['title'],'url':it['url'],'via':it['source']})
505
- data={'context':'\n\n---\n\n'.join(blocks),'sources':sources[:8],'count':len(blocks)}
506
- _TOPIC_CACHE[key]={'t':now,'d':data}
507
- return data
508
-
509
-
510
- # ===== FINAL6C: FAST topic generation (RSS cache first, no slow full-page crawling) =====
511
- import asyncio
512
- _FAST_TOPIC_CACHE={}
513
- FAST_RSS_FEEDS=[
514
- ('VnExpress','https://vnexpress.net/rss/tin-moi-nhat.rss'),
515
- ('VnExpress Thời sự','https://vnexpress.net/rss/thoi-su.rss'),
516
- ('VnExpress Thế giới','https://vnexpress.net/rss/the-gioi.rss'),
517
- ('VnExpress Kinh doanh','https://vnexpress.net/rss/kinh-doanh.rss'),
518
- ('VnExpress Công nghệ','https://vnexpress.net/rss/so-hoa.rss'),
519
- ('VnExpress Thể thao','https://vnexpress.net/rss/the-thao.rss'),
520
- ('Dân trí','https://dantri.com.vn/rss/home.rss'),
521
- ('Dân trí Xã hội','https://dantri.com.vn/rss/xa-hoi.rss'),
522
- ('Dân trí Kinh doanh','https://dantri.com.vn/rss/kinh-doanh.rss'),
523
- ('Dân trí Thể thao','https://dantri.com.vn/rss/the-thao.rss'),
524
- ('Dân trí Công nghệ','https://dantri.com.vn/rss/suc-manh-so.rss'),
525
- ('Vietnamnet','https://vietnamnet.vn/rss/tin-moi-nhat.rss'),
526
- ('Vietnamnet Thời sự','https://vietnamnet.vn/thoi-su.rss'),
527
- ('Vietnamnet Kinh doanh','https://vietnamnet.vn/kinh-doanh.rss'),
528
- ('Vietnamnet Công nghệ','https://vietnamnet.vn/cong-nghe.rss'),
529
- ('Vietnamnet Thể thao','https://vietnamnet.vn/the-thao.rss'),
530
- ]
531
-
532
- def _fast_fetch_rss(feed_name, feed_url, max_items=20):
533
- items=[]
534
- try:
535
- r=requests.get(feed_url,headers=UA,timeout=6);r.encoding='utf-8'
536
- soup=BeautifulSoup(r.text,'xml')
537
- for it in soup.find_all('item')[:max_items]:
538
- title=clean(it.find('title').get_text(' ',strip=True) if it.find('title') else '')
539
- link=clean(it.find('link').get_text(strip=True) if it.find('link') else '')
540
- desc_raw=it.find('description').get_text(' ',strip=True) if it.find('description') else ''
541
- desc=clean(BeautifulSoup(desc_raw,'lxml').get_text(' ',strip=True))
542
- if title and link:
543
- items.append({'title':title,'url':link,'source':feed_name,'snippet':desc})
544
- except Exception:pass
545
- return items
546
-
547
- def _fast_rss_pool():
548
- now=time.time();key='fast_rss_pool'
549
- if key in _FAST_TOPIC_CACHE and now-_FAST_TOPIC_CACHE[key]['t']<600:return _FAST_TOPIC_CACHE[key]['d']
550
- pool=[];seen=set()
551
- # Sequential with short timeouts is predictable; RSS is small.
552
- for name,url in FAST_RSS_FEEDS:
553
- for it in _fast_fetch_rss(name,url,16):
554
- if it['url'] not in seen:
555
- seen.add(it['url']);pool.append(it)
556
- _FAST_TOPIC_CACHE[key]={'t':now,'d':pool}
557
- return pool
558
-
559
- def _fast_topic_tokens(topic):
560
- toks=[w.lower() for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',topic or '') if len(w)>1]
561
- return [t for t in toks if t not in STOP_WORDS]
562
-
563
- def _fast_score(topic,item):
564
- toks=_fast_topic_tokens(topic)
565
- hay=(item.get('title','')+' '+item.get('snippet','')+' '+item.get('source','')).lower()
566
- if not toks:return 0
567
- score=0
568
- for t in toks:
569
- if t in hay:score+=3 if len(t)>3 else 1
570
- phrase=topic.lower().strip()
571
- if phrase and phrase in hay:score+=12
572
- return score
573
-
574
- def _fast_sources(topic, limit=8):
575
- pool=_fast_rss_pool()
576
- scored=[]
577
- for it in pool:
578
- sc=_fast_score(topic,it)
579
- if sc>0:scored.append((sc,it))
580
- scored=sorted(scored,key=lambda x:(x[0],len(x[1].get('snippet',''))),reverse=True)
581
- out=[];seen=set()
582
- for sc,it in scored:
583
- if it['url'] in seen:continue
584
- seen.add(it['url']);out.append({**it,'score':sc})
585
- if len(out)>=limit:break
586
- # If topic too narrow and no match, use top latest from VN RSS as weak context instead of slow crawling.
587
- if not out:
588
- out=pool[:min(limit,8)]
589
- return out
590
-
591
- def _fast_context(topic):
592
- now=time.time();key='fast_ctx:'+topic.lower().strip()
593
- if key in _FAST_TOPIC_CACHE and now-_FAST_TOPIC_CACHE[key]['t']<600:return _FAST_TOPIC_CACHE[key]['d']
594
- sources=_fast_sources(topic,8)
595
- blocks=[];src=[]
596
- for it in sources:
597
- text=(it.get('snippet') or '').strip()
598
- # Use title + RSS description only: fast and reliable.
599
- blocks.append(f"NGUỒN: {it.get('source','')}\nTIÊU ĐỀ: {it.get('title','')}\nTÓM TẮT RSS:\n{text}")
600
- src.append({'title':it.get('title',''),'url':it.get('url',''),'via':it.get('source','')})
601
- data={'context':'\n\n---\n\n'.join(blocks),'sources':src,'count':len(blocks)}
602
- _FAST_TOPIC_CACHE[key]={'t':now,'d':data}
603
- return data
604
-
605
- def _fallback_fast_article(topic, sources):
606
- lines=[]
607
- for s in sources[:7]:
608
- title=s.get('title','')
609
- if title:lines.append(title)
610
- body='\n'.join('• '+x for x in lines[:7])
611
- vias=', '.join(sorted({s.get('via','') for s in sources if s.get('via')}))
612
- return (f"{topic}: những điểm đáng chú ý\n\n"
613
- f"{topic} đang là chủ đề được quan tâm trong dòng tin tức hiện nay. Dựa trên các nguồn tin mới nhất, có thể tổng hợp nhanh một số điểm nổi bật để người đọc nắm bối cảnh và theo dõi tiếp diễn biến.\n\n"
614
- f"Các nguồn tin liên quan cho thấy chủ đề này gắn với những diễn biến sau:\n{body}\n\n"
615
- f"Nhìn chung, đây là vấn đề cần được theo dõi theo nhiều góc độ: bối cảnh, tác động thực tế, phản ứng của các bên liên quan và những thông tin cập nhật tiếp theo. Người đọc nên đối chiếu thêm các nguồn chính thống khi cần quyết định hoặc đánh giá chi tiết.\n\n"
616
- f"Nguồn tham khảo: {vias}")
617
-
618
- # Remove previous slow topic routes and register fast versions last.
619
- app.router.routes=[r for r in app.router.routes if not any(getattr(r,'path',None)==p and m in getattr(r,'methods',set()) for p,m in {('/api/topic_post','POST'),('/api/topic_sources','GET')})]
620
-
621
- @app.get('/api/topic_sources')
622
- def api_topic_sources_fast(topic:str=Query(...)):
623
- data=_fast_context(clean(topic))
624
- return JSONResponse({'count':data.get('count',0),'sources':data.get('sources',[]),'has_context':bool(data.get('context')),'mode':'fast_rss'})
625
-
626
- @app.post('/api/topic_post')
627
- async def topic_post_fast(request:Request):
628
- body=await request.json();topic=clean(body.get('topic',''))
629
- if not topic:return JSONResponse({'error':'missing topic'},status_code=400)
630
- img=_topic_image(topic)
631
- research=_fast_context(topic);context=research.get('context','');sources=research.get('sources',[])
632
- prompt=f"""Bạn là biên tập viên VNEWS. Hãy viết MỘT BÀI VIẾT HOÀN CHỈNH bằng tiếng Việt về chủ đề: {topic}
633
-
634
- Dữ liệu nhanh từ RSS nguồn Việt Nam:
635
- {context[:12000]}
636
-
637
- Yêu cầu:
638
- - Không liệt kê tiêu đề nguồn thành bài viết.
639
- - Tổng hợp thành bài báo/tạp chí hoàn chỉnh.
640
- - Có tiêu đề mới, sapo 2-3 câu, 4-6 đoạn phân tích/bối cảnh/tác động.
641
- - Diễn đạt lại, không sao chép nguyên văn.
642
- - Nếu dữ liệu ít, viết thận trọng và nêu các điểm cần theo dõi.
643
- - Cuối bài có mục Nguồn tham khảo.
644
- """
645
- text=None
646
- try:
647
- text=await asyncio.wait_for(f5.base.qwen_generate(prompt,image_url=img,max_tokens=1300),timeout=28)
648
- except Exception:
649
- text=None
650
- if not text or len(text)<350:
651
- text=_fallback_fast_article(topic,sources)
652
- post=f5.base.make_post(topic,text,img,'','topic_fast_rss',sources=[s for s in sources if s.get('url')])
653
- post['images']=[img]
654
- posts=f5.base._load_ai_wall();posts.insert(0,post);f5.base._save_ai_wall(posts)
655
- return JSONResponse({'post':post,'mode':'fast_rss','sources_count':len(sources)})
656
-
657
-
658
- # ===== FINAL6D: FAST HOME LOAD =====
659
- _FAST_HOME_CACHE={"t":0,"d":[]}
660
- _FAST_DT_CACHE={"t":0,"d":[]}
661
- _FAST_VNEGO_CACHE={"t":0,"d":[]}
662
- _FAST_HL_CACHE={"t":0,"d":[]}
663
-
664
- def _rss_articles_fast(feed_url, group, source='vne', limit=6):
665
- out=[]
666
- try:
667
- r=requests.get(feed_url,headers=UA,timeout=4);r.encoding='utf-8'
668
- soup=BeautifulSoup(r.text,'xml')
669
- for it in soup.find_all('item')[:limit*2]:
670
- title=clean(it.find('title').get_text(' ',strip=True) if it.find('title') else '')
671
- link=clean(it.find('link').get_text(strip=True) if it.find('link') else '')
672
- desc_raw=it.find('description').get_text(' ',strip=True) if it.find('description') else ''
673
- ds=BeautifulSoup(desc_raw,'lxml')
674
- im=ds.find('img'); img=im.get('src','') if im else ''
675
- desc=clean(ds.get_text(' ',strip=True))[:160]
676
- if title and link:
677
- out.append({'title':title,'link':link,'img':img,'summary':desc,'source':source,'group':group})
678
- if len(out)>=limit:break
679
- except Exception:pass
680
- return out
681
-
682
- def _fast_homepage():
683
- now=time.time()
684
- if _FAST_HOME_CACHE['d'] and now-_FAST_HOME_CACHE['t']<600:return _FAST_HOME_CACHE['d']
685
- feeds=[('Thời Sự','https://vnexpress.net/rss/thoi-su.rss'),('Thế Giới','https://vnexpress.net/rss/the-gioi.rss'),('Kinh Doanh','https://vnexpress.net/rss/kinh-doanh.rss'),('Công Nghệ','https://vnexpress.net/rss/so-hoa.rss'),('Thể Thao','https://vnexpress.net/rss/the-thao.rss'),('Giải Trí','https://vnexpress.net/rss/giai-tri.rss'),('Sức Khỏe','https://vnexpress.net/rss/suc-khoe.rss'),('Giáo Dục','https://vnexpress.net/rss/giao-duc.rss'),('Pháp Luật','https://vnexpress.net/rss/phap-luat.rss'),('Du Lịch','https://vnexpress.net/rss/du-lich.rss')]
686
- arts=[]
687
- try:
688
- from concurrent.futures import ThreadPoolExecutor, as_completed
689
- with ThreadPoolExecutor(max_workers=6) as ex:
690
- futs=[ex.submit(_rss_articles_fast,u,g,'vne',6) for g,u in feeds]
691
- for f in as_completed(futs,timeout=7):
692
- try:arts.extend(f.result() or [])
693
- except Exception:pass
694
- except Exception:
695
- for g,u in feeds[:5]:arts.extend(_rss_articles_fast(u,g,'vne',4))
696
- if arts:_FAST_HOME_CACHE.update({'t':now,'d':arts})
697
- return _FAST_HOME_CACHE['d'] or arts
698
-
699
- def _fast_dantri_hot():
700
- now=time.time()
701
- if _FAST_DT_CACHE['d'] and now-_FAST_DT_CACHE['t']<900:return _FAST_DT_CACHE['d']
702
- data=_rss_articles_fast('https://dantri.com.vn/rss/home.rss','Tin Nổi Bật','dantri',12)
703
- if data:_FAST_DT_CACHE.update({'t':now,'d':data})
704
- return data
705
-
706
- def _fast_vnego():
707
- now=time.time()
708
- if _FAST_VNEGO_CACHE['d'] and now-_FAST_VNEGO_CACHE['t']<900:return _FAST_VNEGO_CACHE['d']
709
- out=[]
710
- try:
711
- r=requests.get('https://vnexpress.net/vne-go',headers=UA,timeout=4);r.encoding='utf-8'
712
- soup=BeautifulSoup(r.text,'lxml');seen=set()
713
- for a in soup.find_all('a',href=True):
714
- href=a.get('href','');title=clean(a.get('title','') or a.get_text(' ',strip=True))
715
- if not title or len(title)<8 or not href.startswith('http') or href in seen:continue
716
- if '/vne-go' not in href and '/video/' not in href:continue
717
- seen.add(href);img='';im=a.find('img') or (a.parent.find('img') if a.parent else None)
718
- if im:img=im.get('data-src') or im.get('src','')
719
- out.append({'title':title,'link':href,'img':img,'source':'vne-video'})
720
- if len(out)>=10:break
721
- except Exception:pass
722
- _FAST_VNEGO_CACHE.update({'t':now,'d':out})
723
- return out
724
-
725
- def _fast_highlights():
726
- now=time.time()
727
- if _FAST_HL_CACHE['d'] and now-_FAST_HL_CACHE['t']<900:return _FAST_HL_CACHE['d']
728
- _FAST_HL_CACHE.update({'t':now,'d':[]})
729
- return []
730
-
731
- for _p in ['/api/homepage','/api/dantri_hot','/api/vne_video','/api/highlights']:
732
- app.router.routes=[r for r in app.router.routes if not (getattr(r,'path',None)==_p and 'GET' in getattr(r,'methods',set()))]
733
- @app.get('/api/homepage')
734
- def api_homepage_fast():return JSONResponse(_fast_homepage())
735
- @app.get('/api/dantri_hot')
736
- def api_dantri_hot_fast():return JSONResponse(_fast_dantri_hot())
737
- @app.get('/api/vne_video')
738
- def api_vne_video_fast():return JSONResponse(_fast_vnego())
739
- @app.get('/api/highlights')
740
- def api_highlights_fast():return JSONResponse(_fast_highlights())
741
-
742
- FINAL6_FAST_HOME_INJECT = """
743
  <script>
744
  (function(){
745
- const oldFetch=window.fetch;
746
- window.__allowShortRefresh=false;
747
- window.fetch=function(url,opts){try{let u=String(url||'');if(u.includes('/api/shorts?refresh=1')&&!window.__allowShortRefresh)url='/api/shorts';}catch(e){}return oldFetch.call(this,url,opts)};
748
- setTimeout(()=>{window.__allowShortRefresh=true;},7000);
749
  })();
750
  </script>
751
- """
752
- app.router.routes=[r for r in app.router.routes if not (getattr(r,'path',None)=='/' and 'GET' in getattr(r,'methods',set()))]
753
- @app.get('/')
754
- async def index_final6_fast_home():
755
- html=f5.f4.f3.f2.f1._load_index_html()
756
- body=getattr(rt.old,'PATCH_INJECT','')+f5.f4.f3.f2.f1.FINAL_INJECT+f5.f4.f3.FINAL3_INJECT+f5.f4.FINAL4_INJECT+f5.FINAL5_INJECT+FINAL6_INJECT+FINAL6_FAST_HOME_INJECT
757
- return HTMLResponse(html.replace('</body>',body+'\n</body>') if '</body>' in html else html+body)
758
-
759
-
760
- # ===== FINAL6E: SHOW SOURCE CONTENTS IN TOPIC ARTICLE =====
761
- def _extract_source_details_from_context(context, sources):
762
- details=[]
763
- # Map source urls by title for URL/via enrichment
764
- src_by_title={clean(s.get('title','')):s for s in (sources or [])}
765
- for block in (context or '').split('---'):
766
- block=block.strip()
767
- if not block:continue
768
- via='';title='';content=''
769
- m=re.search(r'NGUỒN:\s*(.*)',block)
770
- if m:via=clean(m.group(1))
771
- m=re.search(r'TIÊU ĐỀ:\s*(.*)',block)
772
- if m:title=clean(m.group(1))
773
- if 'NỘI DUNG BÀI VIẾT ĐÃ CRAWL:' in block:
774
- content=block.split('NỘI DUNG BÀI VIẾT ĐÃ CRAWL:',1)[1]
775
- elif 'TÓM TẮT RSS:' in block:
776
- content=block.split('TÓM TẮT RSS:',1)[1]
777
- elif 'ĐOẠN MÔ TẢ' in block:
778
- content=re.split(r'ĐOẠN MÔ TẢ[^:]*:',block,1)[-1]
779
- content=clean(content)
780
- if not title and not content:continue
781
- s=src_by_title.get(title,{})
782
- details.append({'title':title or s.get('title','Nguồn tham khảo'),'url':s.get('url',''),'via':via or s.get('via',''),'content':content[:1800]})
783
- if len(details)>=8:break
784
- return details
785
-
786
- # Remove prior topic endpoint and register one that stores source_details in post.
787
- app.router.routes=[r for r in app.router.routes if not (getattr(r,'path',None)=='/api/topic_post' and 'POST' in getattr(r,'methods',set()))]
788
-
789
- @app.post('/api/topic_post')
790
- async def topic_post_with_source_contents(request:Request):
791
- body=await request.json();topic=clean(body.get('topic',''))
792
- if not topic:return JSONResponse({'error':'missing topic'},status_code=400)
793
- img=_topic_image(topic)
794
- research=_fast_context(topic) if '_fast_context' in globals() else _web_research_context(topic)
795
- context=research.get('context','');sources=research.get('sources',[])
796
- details=_extract_source_details_from_context(context,sources)
797
- if not context or not details:
798
- return JSONResponse({'error':'Không tìm/crawl được đủ nội dung về chủ đề này. Hãy thử chủ đề cụ thể hơn hoặc dùng hashtag gợi ý.'},status_code=422)
799
- source_brief='\n\n'.join([f"[{i+1}] {d.get('title','')} ({d.get('via','')})\n{d.get('content','')[:1400]}" for i,d in enumerate(details)])
800
- prompt=f"""Bạn là biên tập viên VNEWS. Hãy viết MỘT BÀI VIẾT HOÀN CHỈNH bằng tiếng Việt về chủ đề: {topic}
801
-
802
- Dưới đây là nội dung từng nguồn đã thu thập. Hãy tổng hợp ý chính, không sao chép nguyên văn, không biến các tiêu đề thành danh sách.
803
-
804
- NỘI DUNG NGUỒN:
805
- {source_brief[:18000]}
806
-
807
- Yêu cầu:
808
- - Tiêu đề mới, rõ, hấp dẫn.
809
- - Sapo 2-3 câu.
810
- - 5-8 đoạn phân tích/bối cảnh/tác động/điểm cần lưu ý.
811
- - Không dùng câu "Dưới đây là" hoặc "Tôi sẽ".
812
- - Cuối bài có mục "Nguồn tham khảo" nêu tên nguồn.
813
- """
814
- text=None
815
- try:
816
- import asyncio
817
- text=await asyncio.wait_for(f5.base.qwen_generate(prompt,image_url=img,max_tokens=1700),timeout=35)
818
- except Exception:
819
- text=None
820
- if not text or len(text)<350:
821
- bullets='\n'.join([f"• {d['title']}: {d.get('content','')[:320]}" for d in details[:6]])
822
- vias=', '.join(sorted({d.get('via','') for d in details if d.get('via')}))
823
- text=(f"{topic}: tổng hợp những điểm đáng chú ý\n\n"
824
- f"{topic} đang được nhiều nguồn tin đề cập với các góc nhìn khác nhau. Dưới đây là phần tổng hợp nhanh từ những nội dung đã thu thập được.\n\n"
825
- f"{bullets}\n\n"
826
- f"Nhìn chung, chủ đề này cần được theo dõi thêm ở các khía cạnh: bối cảnh, tác động thực tế, phản ứng của các bên liên quan và các diễn biến mới trong thời gian tới.\n\n"
827
- f"Nguồn tham khảo: {vias}")
828
- post=f5.base.make_post(topic,text,img,'','topic_fast_rss_with_sources',sources=[s for s in sources if s.get('url')])
829
- post['images']=[img]
830
- post['source_details']=details
831
- posts=f5.base._load_ai_wall();posts.insert(0,post);f5.base._save_ai_wall(posts)
832
- return JSONResponse({'post':post,'mode':'fast_rss_with_source_details','sources_count':len(details)})
833
 
834
- FINAL6E_INJECT = """
835
  <style>
836
- .source-detail-box{margin-top:14px;background:#151515;border:1px solid #2b2b2b;border-radius:10px;padding:10px}.source-detail-box h3{font-size:14px;color:#5cb87a;margin-bottom:8px}.source-detail-item{background:#202020;border-radius:8px;padding:9px;margin:7px 0}.source-detail-title{font-size:12px;font-weight:700;color:#eee;line-height:1.35}.source-detail-meta{font-size:10px;color:#888;margin:3px 0}.source-detail-content{font-size:12px;color:#bbb;line-height:1.5;white-space:pre-wrap;max-height:220px;overflow:auto}.source-detail-item a{color:#5cb87a;font-size:11px;text-decoration:none}
 
837
  </style>
838
  <script>
839
  (function(){
840
- function escE(s){return String(s||'').replace(/[&<>\"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',"'":'&#39;'}[m]));}
841
- window.__topicWallE=[];
842
- function sourceDetailsHtml(p){let arr=p.source_details||[];if(!arr.length)return '';let h='<div class="source-detail-box"><h3>📚 Nội dung từng nguồn đã dùng</h3>';arr.forEach((s,i)=>{h+=`<div class="source-detail-item"><div class="source-detail-title">${i+1}. ${escE(s.title)}</div><div class="source-detail-meta">${escE(s.via||'Nguồn')}</div><div class="source-detail-content">${escE(s.content||'')}</div>${s.url?`<a href="${escE(s.url)}" target="_blank">Mở nguồn gốc</a>`:''}</div>`});h+='</div>';return h;}
843
- function renderTopicWallE(){let home=document.getElementById('view-home');if(!home||!window.__topicWallE.length)return;document.getElementById('ai-wall-topic-live')?.remove();let wrap=document.createElement('div');wrap.id='ai-wall-topic-live';wrap.className='ai-wall-topic-live';let h='<div class="slider-header"><span class="slider-label">🧱 Tường AI mới</span><span class="slider-note">Tổng hợp từ web</span></div><div class="slider-track">';window.__topicWallE.slice(0,20).forEach((p,i)=>{h+=`<div class="wall-item"><div class="wall-thumb">${p.img?`<img src="${escE(p.img)}">`:''}</div><div class="wall-title">${escE(p.title)}</div><div class="wall-text">${escE(p.text)}</div><div class="wall-actions"><button class="primary" onclick="readTopicWallE(${i})">Xem</button></div></div>`});h+='</div>';wrap.innerHTML=h;let comp=document.querySelector('.ai-compose');if(comp)comp.after(wrap);else home.prepend(wrap);}
844
- window.readTopicWallE=function(i){let p=window.__topicWallE[i];if(!p)return;showView('view-article');let imgs=(p.images||[]).filter(Boolean);let gal=imgs.length?'<div class="ai-wall-gallery">'+imgs.slice(0,12).map(u=>`<img src="${escE(u)}" loading="lazy">`).join('')+'</div>':(p.img?`<img class="article-img" src="${escE(p.img)}">`:'');let srcDetails=sourceDetailsHtml(p);document.getElementById('view-article').innerHTML=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="article-view"><span class="badge badge-ai">AI</span><h1 class="article-title">${escE(p.title)}</h1>${gal}<p class="article-p" style="white-space:pre-wrap">${escE(p.text)}</p>${srcDetails}<div class="article-actions"><button onclick="shareAI?shareAI(${JSON.stringify(p).replace(/"/g,'&quot;')},false):navigator.clipboard.writeText(location.href)">📤 Chia sẻ</button></div></div>`;window.scrollTo(0,0)};
845
- window.createTopicPostFinal5=async function(){let inp=document.getElementById('ai-topic-input-final5');let topic=(inp&&inp.value||'').trim();if(!topic)return alert('Nhập chủ đề trước');let btn=document.getElementById('ai-topic-btn-final5');if(btn){btn.disabled=true;btn.textContent='Đang tìm nguồn...'}try{let src=await fetch('/api/topic_sources?topic='+encodeURIComponent(topic)).then(r=>r.json()).catch(()=>null);if(btn&&src)btn.textContent='Đã tìm '+(src.count||0)+' nguồn, đang tổng hợp...';let r=await fetch('/api/topic_post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({topic})});let j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');window.__topicWallE.unshift(j.post);if(inp)inp.value='';renderTopicWallE();readTopicWallE(0);alert('Đã tạo bài tổng hợp từ nội dung web và đăng lên Tường AI.');}catch(e){alert(e.message)}finally{if(btn){btn.disabled=false;btn.textContent='✨ Tạo bài tổng hợp từ web bằng Qwen'}}};
846
- setInterval(()=>{document.querySelectorAll('#ai-topic-input-final3,.topic-final3,#ai-topic-input-final4,.topic-final4').forEach(e=>(e.closest('.topic-final3,.topic-final4,.ai-compose-row')||e).remove());let b=document.getElementById('ai-topic-btn-final5');if(b){b.style.display='block';b.textContent='✨ Tạo bài tổng hợp từ web bằng Qwen';}},1200);
 
 
 
 
 
 
 
847
  })();
848
  </script>
849
  '''
 
 
 
 
 
 
 
 
 
 
1
+ """Final6 runtime: fast homepage, fast shorts, Qwen topic with source details, hashtag sources, rewrite auto-title."""
2
+ import os, re, time, json, hashlib, asyncio, threading, requests
3
+ from urllib.parse import urlparse, quote
 
 
 
 
 
4
  import ai_runtime_final5 as f5
5
+ from ai_runtime_final5 import app, base, rt, HTMLResponse, JSONResponse, Request, Query
6
+ import html as html_lib
7
 
8
+ SPACE_URL = "https://bep40-vnews.hf.space"
9
+ SHORT_CHANNELS = ["baodantri7941", "baosuckhoedoisongboyte"]
10
+ YOUTUBE_HANDLES = SHORT_CHANNELS
11
+ DATA_DIR = "/data" if os.path.isdir("/data") else "/app/data"
12
+ os.makedirs(DATA_DIR, exist_ok=True)
13
+ SHORTS_CACHE = {"t": 0, "d": []}
14
+ AI_INTERACTIONS_FILE = os.path.join(DATA_DIR, "ai_interactions.json")
15
+ SHORT_COMMENTS_FILE = os.path.join(DATA_DIR, "short_comments.json")
16
 
17
+ def clean(s):
18
+ return re.sub(r"\s+", " ", html_lib.unescape(s or "")).strip()
 
 
 
 
 
 
 
19
 
 
20
  def _domain(u):
21
+ try: return urlparse(u or '').netloc.replace('www.', '')
22
+ except: return ''
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ def _lj(p, d):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  try:
26
+ if os.path.exists(p): return json.load(open(p, 'r', encoding='utf-8'))
27
+ except: pass
28
+ return d
 
 
 
 
 
 
 
 
 
 
29
 
30
+ def _sj(p, d):
 
31
  try:
32
+ os.makedirs(os.path.dirname(p), exist_ok=True)
33
+ open(p + '.tmp', 'w', encoding='utf-8').write(json.dumps(d, ensure_ascii=False))
34
+ os.replace(p + '.tmp', p)
35
+ except: pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ def _yt_ytdlp(handle, count=20):
38
  try:
39
+ import yt_dlp
40
+ url = f"https://www.youtube.com/@{handle}/shorts"
41
+ opts = {'quiet': True, 'extract_flat': True, 'skip_download': True, 'playlist-end': count, 'ignoreerrors': True, 'no_warnings': True}
42
+ with yt_dlp.YoutubeDL(opts) as ydl:
43
+ info = ydl.extract_info(url, download=False)
44
+ out = []
45
+ for e in (info or {}).get('entries') or []:
46
+ vid = e.get('id') or ''
47
+ if not re.match(r'^[A-Za-z0-9_-]{11}$', vid): continue
48
+ title = e.get('title') or 'YouTube Short'
49
+ out.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': handle})
50
+ return out
51
+ except: return []
 
 
 
 
52
 
53
+ def _yt_html(handle, count=20):
54
  try:
55
+ r = requests.get(f"https://www.youtube.com/@{handle}/shorts", headers=getattr(base, 'HEADERS', {}), timeout=15)
56
+ ids = []; out = []
57
+ for m in re.finditer(r'"videoId":"([A-Za-z0-9_-]{11})"', r.text):
58
+ vid = m.group(1)
59
+ if vid in ids: continue
60
+ ids.append(vid)
61
+ snip = r.text[max(0, m.start()-1000):m.start()+1800]
62
+ title = 'YouTube Short'
63
+ mt = re.search(r'"title":\{"runs":\[\{"text":"([^"]+)"', snip) or re.search(r'"accessibilityText":"([^"]+)"', snip)
64
+ if mt: title = clean(mt.group(1).replace('\\n', ' '))
65
+ out.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': handle})
66
+ if len(out) >= count: break
67
+ return out
68
+ except: return []
 
 
69
 
70
+ def _fallback_shorts():
71
+ out = []; seen = set()
72
+ hard = [
73
+ ('Lu_iCQ5YwNM', 'Công an lập hồ sơ xử lý người phụ nữ chửi bới, tát tài xế ô tô | Dân trí', 'baodantri7941'),
74
+ ('CwWvijF8BOA', 'Chú rể bật khóc nhận món quà bí mật người cha quá cố gửi 26 năm trước | Dân trí', 'baodantri7941'),
75
+ ('7Pd6vZ2Lz1M', 'Hành động ấm lòng trong tìm kiếm học sinh tử vong ở sông Lô | SKĐS', 'baosuckhoedoisongboyte'),
76
+ ('SlHLt_ZyPiE', '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', 'baosuckhoedoisongboyte'),
77
+ ]
78
+ for vid, title, ch in hard:
79
+ if vid not in seen:
80
+ seen.add(vid)
81
+ out.append({'id': vid, 'title': title, 'channel': ch, 'link': f'https://www.youtube.com/watch?v={vid}', 'img': f'https://i.ytimg.com/vi/{vid}/hqdefault.jpg', 'source': 'yt'})
82
+ return out
83
 
84
+ def _fresh_shorts():
85
+ items = []; seen = set()
86
+ for ch in YOUTUBE_HANDLES:
87
+ got = _yt_ytdlp(ch, 24) or _yt_html(ch, 24)
88
+ for v in got:
89
+ if v['id'] not in seen:
90
+ seen.add(v['id']); items.append(v)
91
+ for v in _fallback_shorts():
92
+ if v['id'] not in seen:
93
+ seen.add(v['id']); items.append(v)
94
+ return items[:50]
 
 
 
 
 
 
 
 
 
 
95
 
96
  def _topic_image(topic):
97
+ try: return base.pollinations_image_url(topic)
98
+ except: return "https://image.pollinations.ai/prompt/" + quote("Vietnamese news editorial illustration " + topic) + "?width=1024&height=576&nologo=true"
 
 
 
 
 
99
 
100
+ def _web_research_context(topic, limit=5):
101
+ try:
102
+ ctx, sources = base.web_context(topic, limit=limit)
103
+ return {"context": ctx or "", "sources": sources or []}
104
+ except:
105
+ return {"context": "", "sources": []}
106
+
107
+ def _fast_context(topic, limit=5):
108
+ return _web_research_context(topic, limit)
109
+
110
+ def _extract_source_details_from_context(ctx, sources):
111
+ """Extract detailed source info from web context for source_details field."""
112
+ details = []
113
+ if not ctx or not sources:
114
+ return details
115
+ # Parse sources from context
116
+ for s in sources[:8]:
117
+ url = s.get('url', '')
118
+ if not url: continue
119
+ details.append({
120
+ 'title': s.get('title', ''),
121
+ 'url': url,
122
+ 'via': s.get('via', _domain(url)),
123
+ 'content': s.get('excerpt', s.get('description', ''))
124
+ })
125
+ return details
126
 
127
+ _bg_home = {"t": 0, "d": []}
128
+ _bg_shorts = {"t": 0, "d": []}
129
+ _bg_lock = False
130
 
131
+ def _bg():
132
+ global _bg_lock
133
+ if _bg_lock: return
134
+ _bg_lock = True
135
+ try:
136
+ # Fast homepage: just return empty, let frontend handle it
137
+ _bg_home.update({"t": time.time(), "d": []})
138
+ # Shorts
139
+ raw = []
140
+ for h in YOUTUBE_HANDLES:
141
+ raw.extend(_yt_ytdlp(h, 20) or _yt_html(h, 20))
142
+ raw.extend(_fallback_shorts())
143
+ seen = set()
144
+ out = [v for v in raw if v.get('id') and v['id'] not in seen and not seen.add(v['id'])]
145
+ if out: _bg_shorts.update({"t": time.time(), "d": out[:40]})
146
+ except: pass
147
+ finally: _bg_lock = False
148
+
149
+ @app.on_event("startup")
150
+ async def _s():
151
+ threading.Thread(target=_bg, daemon=True).start()
152
+ threading.Thread(target=lambda: [time.sleep(600) or _bg() for _ in iter(int, 1)], daemon=True).start()
153
+
154
+ # Remove endpoints to override
155
+ app.router.routes = [r for r in app.router.routes if not (
156
+ getattr(r, 'path', None) in ('/api/homepage', '/api/shorts', '/api/ai_wall', '/api/topic_post', '/api/article/ask', '/api/topic/rewrite', '/api/rewrite_share', '/api/url_wall', '/api/short/comments', '/api/short/comment', '/api/storage_status', '/') and
157
+ any(m in getattr(r, 'methods', set()) for m in ('GET', 'POST'))
158
+ )]
159
 
160
+ @app.get('/api/homepage')
161
+ def _h():
162
+ n = time.time()
163
+ if _bg_home['d']:
164
+ if n - _bg_home['t'] > 300: threading.Thread(target=_bg, daemon=True).start()
165
+ return JSONResponse(_bg_home['d'])
166
+ threading.Thread(target=_bg, daemon=True).start()
167
+ return JSONResponse([])
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
+ @app.get('/api/shorts')
170
+ def _sh(refresh: int = Query(default=0)):
171
+ n = time.time()
172
+ if _bg_shorts['d'] and (not refresh or n - _bg_shorts['t'] < 120):
173
+ if n - _bg_shorts['t'] > 600: threading.Thread(target=_bg, daemon=True).start()
174
+ return JSONResponse(_bg_shorts['d'])
175
+ data = _fresh_shorts()
176
+ _bg_shorts.update({'t': n, 'd': data})
177
+ return JSONResponse(data)
178
+
179
+ @app.get('/api/ai_wall')
180
+ def _w():
181
+ n = int(time.time())
182
+ return JSONResponse({'posts': [p for p in f5.base._load_ai_wall() if n - int(p.get('ts') or 0) < 86400], 'persistent': os.path.isdir('/data')})
183
+
184
+ @app.get('/api/storage_status')
185
+ def _st():
186
+ return JSONResponse({'persistent': os.path.isdir('/data')})
187
+
188
+ @app.get('/api/short/comments')
189
+ def _gc(id: str = Query(...)):
190
+ return JSONResponse({'comments': _lj(SHORT_COMMENTS_FILE, {}).get(id, [])})
191
+
192
+ @app.post('/api/short/comment')
193
+ async def _pc(request: Request):
194
+ b = await request.json()
195
+ v = str(b.get('id', '')).strip()
196
+ t = clean(b.get('text', ''))
197
+ if not v or not t: return JSONResponse({'error': 'missing'}, status_code=400)
198
+ db = _lj(SHORT_COMMENTS_FILE, {})
199
+ c = db.get(v, [])
200
+ c.insert(0, {'text': t[:300], 'ts': int(time.time())})
201
+ db[v] = c[:100]
202
+ _sj(SHORT_COMMENTS_FILE, db)
203
+ return JSONResponse({'comments': db[v]})
204
+
205
+ @app.post('/api/article/ask')
206
+ async def _ask(request: Request):
207
+ b = await request.json()
208
+ q = clean(b.get('question', ''))
209
+ ctx = clean(b.get('context', ''))
210
+ url = clean(b.get('url', ''))
211
+ if not q: return JSONResponse({'error': 'missing question'}, status_code=400)
212
+ title = ''; raw = ''
213
+ if url:
214
+ try:
215
+ d = f5.base.scrape_any_url(url)
216
+ title = d.get('title', '')
217
+ raw = (d.get('summary', '') + '\n' + d.get('text', '')).strip()
218
+ except: pass
219
+ if not raw: raw = ctx[:12000]
220
+ ans = await f5.base.qwen_generate(
221
+ f'Bạn là VNEWS AI. Nội dung: "{title}"\n{raw[:9000]}\n\nHỏi: "{q}"\n\nTrả lời tự nhiên bằng tiếng Việt.',
222
+ max_tokens=1200)
223
+ return JSONResponse({'answer': ans or 'Chưa trả lời được.', 'title': title})
224
+
225
+ @app.post('/api/rewrite_share')
226
+ @app.post('/api/url_wall')
227
+ async def _rw(request: Request):
228
+ b = await request.json()
229
+ url = clean(b.get('url', ''))
230
+ ctx = clean(b.get('context', ''))
231
+ if not url.startswith('http'): return JSONResponse({'error': 'URL không hợp lệ'}, status_code=400)
232
  try:
233
+ d = f5.base.scrape_any_url(url)
234
+ title = d.get('title', '')
235
+ raw = (d.get('summary', '') + '\n' + d.get('text', '')).strip()
236
+ img = d.get('image') or ''
237
+ except:
238
+ title = ''; raw = ctx[:14000]; img = ''
239
+ if len(raw) < 50: return JSONResponse({'error': 'Không đọc được bài'}, status_code=422)
240
+ text = None
241
+ try:
242
+ text = await asyncio.wait_for(f5.base.qwen_generate(
243
+ f'Tóm tắt đăng Tường AI:\nTiêu đề: {title}\n{raw[:14000]}\n\n4-6 ý chính. Cuối ghi nguồn.',
244
+ image_url=img or None, max_tokens=1000), timeout=30)
245
+ except: pass
246
+ if not text or len(text) < 80:
247
+ text = f"Tóm tắt: {title}\n\n{raw[:1200]}\n\nNguồn: {_domain(url)}"
248
+ post = f5.base.make_post(title or 'Bài viết', text, img, url, 'rewrite',
249
+ sources=[{'title': title, 'url': url, 'via': _domain(url)}])
250
+ ps = f5.base._load_ai_wall(); ps.insert(0, post); f5.base._save_ai_wall(ps)
251
+ return JSONResponse({'post': post})
252
+
253
+ @app.post('/api/topic/rewrite')
254
+ async def _tr(request: Request):
255
+ b = await request.json()
256
+ pid = str(b.get('post_id', '')).strip()
257
+ if not pid: return JSONResponse({'error': 'missing post_id'}, status_code=400)
258
+ ps = f5.base._load_ai_wall()
259
+ p = next((x for x in ps if str(x.get('id')) == pid), None)
260
+ if not p: return JSONResponse({'error': 'Bài không tồn tại'}, status_code=404)
261
+ urls = list(dict.fromkeys(
262
+ [s['url'] for s in (p.get('source_details') or []) if s.get('url')] +
263
+ [s['url'] for s in (p.get('sources') or []) if s.get('url')]
264
+ ))[:5]
265
+ parts = []
266
+ for u in urls:
267
  try:
268
+ d = f5.base.scrape_any_url(u)
269
+ t = d.get('title', '')
270
+ r = (d.get('summary', '') + '\n' + d.get('text', '')).strip()
271
+ if r and len(r) > 150:
272
+ parts.append(f"[{_domain(u)}] {t}\n{r}")
273
+ except: pass
274
+ ac = '\n---\n'.join(parts) if parts else (p.get('text') or '')
275
+ title = p.get('title', '')
276
+ text = None
277
+ try:
278
+ text = await asyncio.wait_for(f5.base.qwen_generate(
279
+ f'Viết lại:\nChủ đề: {title}\n{ac[:16000]}\n\nTiêu đề mới + 4-6 ý + nguồn.',
280
+ image_url=p.get('img'), max_tokens=1200), timeout=35)
281
+ except: pass
282
+ if not text or len(text) < 100:
283
+ text = f"Tóm tắt: {title}\n\n{ac[:1500]}\n\nNguồn: VNEWS AI"
284
+ np = f5.base.make_post('Rewrite: ' + title, text, p.get('img', ''), '', 'rewrite_topic', sources=p.get('sources', []))
285
+ np['images'] = p.get('images', [])
286
+ all_p = f5.base._load_ai_wall(); all_p.insert(0, np); f5.base._save_ai_wall(all_p)
287
+ return JSONResponse({'post': np})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
 
289
+ @app.post('/api/topic_post')
290
+ async def _tp(request: Request):
291
+ b = await request.json()
292
+ topic = clean(b.get('topic', ''))
293
+ if not topic: return JSONResponse({'error': 'missing topic'}, status_code=400)
294
+ img = _topic_image(topic)
295
+ research = _fast_context(topic)
296
+ ctx = research.get('context', '')
297
+ src = research.get('sources', [])
298
+ det = _extract_source_details_from_context(ctx, src)
299
+ if not ctx or not src:
300
+ return JSONResponse({'error': 'Không tìm được nội dung.'}, status_code=422)
301
+ sb = '\n\n'.join([f"[{i+1}] {d.get('title', '')} ({d.get('via', '')})\n{d.get('content', '')[:1400]}" for i, d in enumerate(det)]) if det else ctx[:18000]
302
+ text = None
303
+ try:
304
+ text = await asyncio.wait_for(f5.base.qwen_generate(
305
+ f'Viết bài tiếng Việt VỀ: "{topic}"\nNGUỒN:\n{sb[:18000]}\nCHỈ viết về "{topic}". 5-8 đoạn. Cuối có nguồn.',
306
+ image_url=img, max_tokens=1700), timeout=35)
307
+ except: pass
308
+ if not text or len(text) < 300:
309
+ text = f"{topic}: tổng hợp\n\n" + '\n'.join([f"• {d['title']}: {d.get('content', '')[:300]}" for d in (det or [])[:6]]) + "\n\nNguồn: " + ', '.join(sorted({d.get('via', '') for d in (det or []) if d.get('via')}))
310
+ post = f5.base.make_post(topic, text, img, '', 'topic_focused', sources=[s for s in src if s.get('url')])
311
+ post['images'] = [img]; post['source_details'] = det
312
+ ps = f5.base._load_ai_wall(); ps.insert(0, post); f5.base._save_ai_wall(ps)
313
+ return JSONResponse({'post': post})
314
+
315
+ FINAL6_INJECT = r'''
316
  <style>
317
+ /* Livescore */
318
+ .ls-content{max-height:480px;overflow-y:auto;padding:0 6px 8px;font-size:12px;color:#ddd}
319
+ .ls-content ul{list-style:none;padding:0;margin:0}
320
+ .ls-content .title-content{display:flex;gap:6px;align-items:center;background:#222;border-radius:4px;margin:4px 0;padding:5px 8px}
321
+ .ls-content .title-content img{width:18px;height:18px}
322
+ .ls-content .title-content strong{font-size:11px;color:#ccc}
323
+ .ls-content .match-detail{padding:6px;border-bottom:1px solid #262626;cursor:pointer}
324
+ .ls-content .match-detail:hover{background:#1a2a1f}
325
+ .ls-content .match{display:flex;flex-wrap:wrap;align-items:center;gap:4px}
326
+ .ls-content .datetime{width:100%;font-size:9px;color:#888}
327
+ .ls-content .teams{display:flex;width:100%;align-items:center;gap:4px}
328
+ .ls-content .team{flex:1;display:flex;align-items:center;gap:4px;min-width:0}
329
+ .ls-content .team .name{font-size:11px;color:#ddd;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
330
+ .ls-content .team .logo img{width:18px;height:18px}
331
+ .ls-content .home-team{justify-content:flex-end;text-align:right}
332
+ .ls-content .status{flex:0 0 54px;text-align:center}
333
+ .ls-content .status a{color:#fff;text-decoration:none;font-weight:800;font-size:12px}
334
+ .ls-content .status .label{font-size:8px;color:#888;display:block}
335
+ .ls-content .status .label.live{color:#e74c3c}
336
+ .ls-content .info,.ls-content .btns{display:none}
337
  </style>
338
  <script>
339
  (function(){
340
  function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));}
341
+ // Block slow YouTube refresh on first load
342
+ var _origFetch=window.fetch,_allowRefresh=false;
343
+ window.fetch=function(url,opts){try{if(String(url).indexOf('/api/shorts?refresh=1')>-1&&!_allowRefresh)url='/api/shorts';}catch(e){}return _origFetch.call(this,url,opts);};
344
+ setTimeout(function(){_allowRefresh=true;},8000);
 
 
 
345
  })();
346
  </script>
347
  '''
348
 
349
+ FINAL6_FAST_HOME_INJECT = r'''
350
+ <style>
351
+ .storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 4px}
352
+ </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
  <script>
354
  (function(){
355
+ fetch('/api/storage_status').then(function(r){return r.json()}).then(function(j){
356
+ if(!j.persistent){var h=document.getElementById('view-home');if(h){var w=document.createElement('div');w.className='storage-warn';w.innerHTML='⚠️ <b>Persistent Storage chưa bật.</b> Bật: Space Settings → Persistent Storage → Small.';h.prepend(w);}}
357
+ });
 
358
  })();
359
  </script>
360
+ '''
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
362
+ FINAL6E_INJECT = r'''
363
  <style>
364
+ /* Kill ALL duplicate slides/walls from old layers */
365
+ #ai-short-home,.ai-short-home,.ai-short-card-final,[id*="ai-shorts-patched"]{display:none!important}
366
  </style>
367
  <script>
368
  (function(){
369
+ // Kill old renderers
370
+ window.renderTopicWallE=function(){};
371
+ window.renderAIShortHome=function(){};
372
+ window.renderAIShorts7=function(){};
373
+ window.renderPatchedWall=function(){};
374
+ window.renderAiShorts=function(){};
375
+ window.renderWall=function(){};
376
+ window.renderAIShorts=function(){};
377
+ window.loadPatchedWall=function(){};
378
+ window.refreshFinalWall3=function(){};
379
+ // Remove duplicate slides
380
+ setInterval(function(){
381
+ document.querySelectorAll('#ai-short-home,.ai-short-home,[id*="ai-shorts-patched"]').forEach(function(el){el.remove()});
382
+ },2000);
383
  })();
384
  </script>
385
  '''
386
+
387
+ @app.get('/')
388
+ async def _index():
389
+ html = f5.f4.f3.f2.f1._load_index_html()
390
+ body = ''
391
+ body += getattr(rt.old, 'PATCH_INJECT', '')
392
+ body += f5.f4.f3.f2.f1.FINAL_INJECT + f5.f4.f3.FINAL3_INJECT + f5.f4.FINAL4_INJECT + f5.FINAL5_INJECT
393
+ body += FINAL6_INJECT + FINAL6_FAST_HOME_INJECT + FINAL6E_INJECT
394
+ return HTMLResponse(html.replace('</body>', body + '\n</body>') if '</body>' in html else html + body)
ai_runtime_fix.py DELETED
@@ -1,394 +0,0 @@
1
- """VNEWS Short Video Fix - standalone module with clean registration.
2
- This module MUST be imported LAST to register /api/ai/short endpoints.
3
- FIX v1: No route filtering issues - registers endpoints unconditionally.
4
- FIX v2: SSE inline endpoint for auto homepage updates
5
- """
6
- import os
7
- import re
8
- import time
9
- import json
10
- import sys
11
- import logging
12
- import asyncio
13
- import hashlib
14
- import subprocess
15
- import requests
16
- from datetime import datetime, timezone, timedelta
17
- from urllib.parse import urlparse
18
- from fastapi import Request, Query
19
- from fastapi.responses import JSONResponse, FileResponse
20
-
21
- # Import dependencies
22
- try:
23
- import ai_ext as base
24
- except ImportError:
25
- import ai_runtime_final6 as base
26
-
27
- # Try to import app from various sources
28
- try:
29
- from app_v2_entry import app
30
- except ImportError:
31
- try:
32
- from main import app
33
- except ImportError:
34
- from ai_runtime_final6 import app
35
-
36
- _log = logging.getLogger("short_fix")
37
- _log.setLevel(logging.INFO)
38
- if not _log.handlers:
39
- _log.addHandler(logging.StreamHandler(sys.stderr))
40
-
41
- DATA_DIR = "/data" if os.path.isdir("/data") else "/app/data"
42
- os.makedirs(DATA_DIR, exist_ok=True)
43
- SHORTS_DIR = os.path.join(DATA_DIR, "ai_shorts")
44
- os.makedirs(SHORTS_DIR, exist_ok=True)
45
-
46
- # ===== VIETNAMESE FONT DETECTION =====
47
- _VN_FONT_REG = None
48
- _VN_FONT_BOLD = None
49
-
50
- def _get_vn_fonts():
51
- """Find Vietnamese-supporting fonts."""
52
- global _VN_FONT_REG, _VN_FONT_BOLD
53
- if _VN_FONT_REG is not None:
54
- return _VN_FONT_REG, _VN_FONT_BOLD
55
-
56
- try:
57
- from PIL import ImageFont
58
- except Exception:
59
- _log.error("PIL not available!")
60
- return None, None
61
-
62
- # Priority: Noto > DejaVu > Liberation
63
- reg_paths = [
64
- "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
65
- "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
66
- "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
67
- "/usr/share/fonts/truetype/freefont/FreeSans.ttf",
68
- ]
69
- bold_paths = [
70
- "/usr/share/fonts/truetype/noto/NotoSans-Bold.ttf",
71
- "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
72
- "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
73
- "/usr/share/fonts/truetype/freefont/FreeSans.ttf",
74
- ]
75
-
76
- for path in reg_paths:
77
- if os.path.exists(path):
78
- try:
79
- _VN_FONT_REG = ImageFont.truetype(path, 40)
80
- _log.info(f"Found regular font: {path}")
81
- break
82
- except:
83
- continue
84
-
85
- for path in bold_paths:
86
- if os.path.exists(path):
87
- try:
88
- _VN_FONT_BOLD = ImageFont.truetype(path, 52)
89
- _log.info(f"Found bold font: {path}")
90
- break
91
- except:
92
- continue
93
-
94
- if _VN_FONT_REG is None:
95
- _VN_FONT_REG = ImageFont.load_default()
96
- if _VN_FONT_BOLD is None:
97
- _VN_FONT_BOLD = _VN_FONT_REG
98
-
99
- return _VN_FONT_REG, _VN_FONT_BOLD
100
-
101
-
102
- def _clean(s):
103
- import html as html_lib
104
- return re.sub(r"\s+", " ", html_lib.unescape(str(s or ""))).strip()
105
-
106
-
107
- # ===== ROBUST TEXT SEGMENTATION =====
108
- def _split_into_segments(text, max_segments=10, min_len=30):
109
- """Split text into segments - multi strategy."""
110
- text = _clean(text)
111
- if not text:
112
- return []
113
-
114
- # Strategy 1: bullet points
115
- lines = text.split('\n')
116
- segmented = []
117
- for line in lines:
118
- line = _clean(line)
119
- line_bare = re.sub(r'^[•\-\*\d\.\)\s]+', '', line).strip()
120
- if len(line_bare) > min_len:
121
- segmented.append(line_bare)
122
- elif len(line) > min_len:
123
- segmented.append(line)
124
-
125
- # Strategy 2: sentences (Vietnamese)
126
- if len(segmented) < 2:
127
- sents = re.split(r'(?<=[.!?])\s+(?=[A-Z0-9À-ỸĐ])', text)
128
- segmented = [s for s in sents if len(_clean(s)) > min_len]
129
-
130
- # Strategy 3: character chunks
131
- if not segmented:
132
- words = text.split()
133
- for i in range(0, min(len(words), max_segments * 20), 20):
134
- chunk = ' '.join(words[i:i+20])
135
- if len(chunk) > min_len:
136
- segmented.append(chunk)
137
-
138
- # Strategy 4: fallback
139
- if not segmented:
140
- segmented = [text[:300]]
141
-
142
- return segmented[:max_segments]
143
-
144
-
145
- # ===== SHORT VIDEO GENERATOR =====
146
- def _gen_short_core(post, work_dir):
147
- """Core short generation - returns video path or None."""
148
- post_id = post.get('id', '')
149
- text = post.get('text', '') or post.get('title', '')
150
-
151
- if not post_id or len(text) < 100:
152
- _log.error(f"Invalid post: id={post_id}, text_len={len(text)}")
153
- return None
154
-
155
- segments = _split_into_segments(text, max_segments=10, min_len=30)
156
- if not segments:
157
- _log.error("No segments generated")
158
- return None
159
-
160
- _log.info(f"Generating short: {len(segments)} segments")
161
-
162
- seg_hash = hashlib.md5(('|'.join(segments) + 'nu').encode()).hexdigest()[:8]
163
- suffix = f"_nu_{seg_hash}"
164
- out_mp4 = os.path.join(work_dir, f"{post_id}{suffix}.mp4")
165
-
166
- if os.path.exists(out_mp4):
167
- _log.info(f"Already exists: {out_mp4}")
168
- return out_mp4
169
-
170
- # Check dependencies
171
- try:
172
- subprocess.run(['ffmpeg', '-version'], capture_output=True, timeout=5)
173
- except Exception as e:
174
- _log.error(f"ffmpeg missing: {e}")
175
- return None
176
-
177
- # Download image
178
- img_path = os.path.join(work_dir, 'bg.jpg')
179
- downloaded = False
180
- try:
181
- img_url = post.get('img', '')
182
- if img_url and img_url.startswith('http'):
183
- r = requests.get(img_url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=12)
184
- if r.status_code == 200:
185
- with open(img_path, 'wb') as f:
186
- f.write(r.content)
187
- downloaded = True
188
- except Exception as e:
189
- _log.warning(f"Image download: {e}")
190
-
191
- try:
192
- from PIL import Image, ImageDraw
193
- has_pil = True
194
- except:
195
- has_pil = False
196
- _log.warning("PIL not available")
197
-
198
- try:
199
- from gtts import gTTS
200
- has_tts = True
201
- except:
202
- has_tts = False
203
- _log.warning("gTTS not available")
204
-
205
- parts = []
206
-
207
- for i, seg in enumerate(segments[:10]):
208
- frame = os.path.join(work_dir, f'frame_{i}.jpg')
209
- audio = os.path.join(work_dir, f'audio_{i}.mp3')
210
- part = os.path.join(work_dir, f'part_{i}.mp4')
211
-
212
- # Create frame
213
- try:
214
- if has_pil:
215
- _make_frame(post, seg, img_path, downloaded, frame)
216
- else:
217
- subprocess.run(['ffmpeg', '-y', '-f', 'lavfi', '-i',
218
- 'color=c=black:s=1080x1920:d=1', '-frames:v', '1', frame],
219
- capture_output=True, timeout=20)
220
- except Exception as e:
221
- _log.error(f"Frame error: {e}")
222
- continue
223
-
224
- # Create audio
225
- if has_tts:
226
- try:
227
- tts = _clean(seg)[:300]
228
- gTTS(tts, lang='vi', slow=False).save(audio)
229
- except Exception as e:
230
- _log.warning(f"TTS error: {e}")
231
- audio = None
232
-
233
- # Combine
234
- dur = 10
235
- try:
236
- cmd = ['ffmpeg', '-y', '-loop', '1', '-t', str(dur), '-i', frame]
237
- if has_tts and os.path.exists(audio):
238
- cmd += ['-i', audio, '-shortest']
239
- else:
240
- cmd += ['-f', 'lavfi', '-i', 'anullsrc', '-shortest']
241
- cmd += ['-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p',
242
- '-c:a', 'aac', '-b:a', '128k', part]
243
- subprocess.run(cmd, capture_output=True, timeout=120)
244
- if os.path.exists(part) and os.path.getsize(part) > 5000:
245
- parts.append(part)
246
- except Exception as e:
247
- _log.error(f"Part combine error: {e}")
248
-
249
- if not parts:
250
- _log.error("No video parts created!")
251
- return None
252
-
253
- # Concatenate
254
- try:
255
- concat = os.path.join(work_dir, 'list.txt')
256
- with open(concat, 'w') as f:
257
- for p in parts:
258
- f.write(f"file '{p}'\n")
259
- subprocess.run(['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat, '-c', 'copy', out_mp4],
260
- capture_output=True, timeout=180)
261
- _log.info(f"Short created: {out_mp4}")
262
- return out_mp4
263
- except Exception as e:
264
- _log.error(f"Concat error: {e}")
265
- return None
266
-
267
-
268
- def _make_frame(post, text, img_path, downloaded, out_path):
269
- """Create video frame with Vietnamese font."""
270
- from PIL import Image, ImageDraw
271
- _get_vn_fonts()
272
-
273
- W, H = 1080, 1920
274
- bg = Image.new('RGB', (W, H), (15, 23, 38))
275
- d = ImageDraw.Draw(bg)
276
-
277
- # Background image
278
- if downloaded and os.path.exists(img_path):
279
- try:
280
- im = Image.open(img_path).convert('RGB')
281
- im = im.resize((W, 760))
282
- bg.paste(im, (0, 0))
283
- except:
284
- pass
285
-
286
- # Title
287
- d.rectangle([0, 0, W, 100], fill=(25, 118, 210))
288
- ttl = post.get('title', '')[:50]
289
- if _VN_FONT_BOLD:
290
- d.text((W//2, 50), ttl, fill='white', font=_VN_FONT_BOLD, anchor='mm')
291
-
292
- # Content
293
- y = 150
294
- for ln in _wrap_text(d, text[:200], _VN_FONT_REG, 80, 920, 10):
295
- d.text((80, y), ln, fill='white', font=_VN_FONT_REG)
296
- y += 55
297
-
298
- bg.save(out_path, quality=85)
299
-
300
-
301
- def _wrap_text(draw, text, font, x, max_w, max_lines):
302
- """Word wrap text."""
303
- words = text.split()
304
- lines = []
305
- cur = []
306
- for w in words:
307
- test = ' '.join(cur + [w])
308
- try:
309
- w_px = draw.textbbox((0, 0), test, font=font)[2]
310
- except:
311
- w_px = len(test) * 22
312
- if w_px <= max_w:
313
- cur.append(w)
314
- else:
315
- if cur:
316
- lines.append(' '.join(cur))
317
- cur = [w]
318
- if len(lines) >= max_lines:
319
- break
320
- if cur and len(lines) < max_lines:
321
- lines.append(' '.join(cur))
322
- return lines
323
-
324
-
325
- def _gen_short_sync(post) -> str:
326
- """Sync wrapper - returns video URL."""
327
- work = os.path.join(SHORTS_DIR, f"work_{post.get('id', int(time.time()))}")
328
- os.makedirs(work, exist_ok=True)
329
- result = _gen_short_core(post, work)
330
- if result:
331
- # Update wall
332
- try:
333
- wall = base._load_ai_wall()
334
- for i, p in enumerate(wall):
335
- if str(p.get('id')) == str(post.get('id')):
336
- p['video'] = f'/api/ai/short-file/{post.get("id")}_nu_{hashlib.md5(str(post).encode()).hexdigest()[:8]}'
337
- wall[i] = p
338
- break
339
- base._save_ai_wall(wall)
340
- # Notify SSE for auto-update
341
- try:
342
- from auto_update_sse import notify_new_short
343
- notify_new_short(post)
344
- except:
345
- pass
346
- except Exception as e:
347
- _log.warning(f"Wall update: {e}")
348
- return result
349
- return ''
350
-
351
-
352
- # ===== REGISTER ENDPOINTS - MUST BE AT MODULE LEVEL =====
353
- @app.post('/api/ai/short/{post_id}')
354
- async def api_short_generate(post_id: str, request: Request):
355
- _log.info(f"POST /api/ai/short/{post_id}")
356
- wall = base._load_ai_wall()
357
- post = next((p for p in wall if str(p.get('id')) == str(post_id)), None)
358
- if not post:
359
- return JSONResponse({'error': 'Post not found in wall'}, status_code=404)
360
-
361
- if post.get('video'):
362
- return JSONResponse({'post': post, 'video': post['video'], 'status': 'done'})
363
-
364
- loop = asyncio.get_event_loop()
365
- result = await loop.run_in_executor(None, _gen_short_sync, post)
366
-
367
- if result:
368
- # Get the video URL from wall (updated in _gen_short_sync)
369
- wall = base._load_ai_wall()
370
- post = next((p for p in wall if str(p.get('id')) == str(post_id)), post)
371
- return JSONResponse({'post': post, 'video': post.get('video'), 'status': 'done'})
372
- return JSONResponse({'error': 'Video generation failed'}, status_code=500)
373
-
374
-
375
- @app.get('/api/ai/short-file/{file_id:path}')
376
- async def api_short_file(file_id: str):
377
- safe = re.sub(r'[^\w\-.]', '_', file_id)[:100]
378
- for fname in os.listdir(SHORTS_DIR) if os.path.isdir(SHORTS_DIR) else []:
379
- if fname.endswith('.mp4') and safe in fname:
380
- return FileResponse(os.path.join(SHORTS_DIR, fname), media_type='video/mp4')
381
- return JSONResponse({'error': 'Not found'}, status_code=404)
382
-
383
-
384
- # ===== SSE ENDPOINT FOR AUTO-UPDATE =====
385
- try:
386
- from auto_update_sse import sse_events as _sse_handler
387
- app.add_api_route('/api/events', _sse_handler, methods=['GET'])
388
- _log.info("SSE endpoint registered at /api/events")
389
- except Exception as e:
390
- _log.warning(f"SSE route not loaded: {e}")
391
-
392
-
393
- # Log startup
394
- _log.info("Short video endpoints registered")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ai_runtime_patch_final.py DELETED
@@ -1,78 +0,0 @@
1
- """Final patch: homepage fix + AI topics at top + SSE auto-update"""
2
- import re, json, time
3
- from fastapi.responses import HTMLResponse, JSONResponse
4
- from fastapi import Query
5
-
6
- # Import chain - must be after ai_runtime_final6
7
- try:
8
- import ai_runtime_final6 as f6
9
- from ai_runtime_final6 import app, f5
10
- from main import rt
11
- except Exception as e:
12
- print(f"[ERROR] f6 import: {e}")
13
- f6 = None
14
- f5 = None
15
- rt = None
16
-
17
- PATCH_CSS_JS = r'''
18
- <style>
19
- .short-cmt-panel{position:fixed;bottom:0;left:0;right:0;max-height:55vh;background:#181818;border-radius:16px 16px 0 0;z-index:99999;padding:14px;display:none;overflow-y:auto}.short-cmt-panel.active{display:block}.short-cmt-panel textarea{width:100%;background:#222;border:1px solid #444;color:#eee;border-radius:10px;padding:9px;margin:6px 0;min-height:60px}.short-cmt-panel button{background:#2d8659;border:0;color:#fff;border-radius:10px;padding:8px 12px;margin:4px}.cmt-item{background:#222;border-radius:8px;padding:7px;margin:5px 0;color:#ccc;font-size:12px}
20
- .storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 0}
21
- button[onclick*="rewriteCurrentArticle"]{display:none!important}
22
- #ai-short-home,.ai-short-home,.ai-short-card-final{display:none!important}
23
- </style>
24
- <div id="short-cmt-panel" class="short-cmt-panel"></div>
25
- <script>
26
- (function(){
27
- function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));}
28
- fetch('/api/storage_status').then(r=>r.json()).then(j=>{if(!j.persistent){let h=document.getElementById('view-home');if(h){let w=document.createElement('div');w.className='storage-warn';w.innerHTML='⚠️ Persistent Storage chưa bật. Bật: Space Settings → Persistent Storage → Small.';h.prepend(w);}}});
29
-
30
- // ===== AI HOT TOPICS PREPEND =====
31
- const AI_HOT_TOPICS = ['Công nghệ AI', 'World Cup 2026', 'Kinh tế Việt Nam', 'Bóng đá châu Âu'];
32
- async function ensureHotTopics(){let inp=document.getElementById('ai-topic-input-final5');if(!inp||document.getElementById('hot-topic-row-ai'))return;let row=document.createElement('div');row.id='hot-topic-row-ai';row.style.cssText='display:flex;gap:6px;overflow-x:auto;padding:4px 0;margin:6px 0';let topics=[];try{let j=await fetch('/api/hot_topics').then(r=>r.json()).catch(()=>({topics:[]}));topics=j.topics||[];}catch(e){topics=[];}AI_HOT_TOPICS.forEach(ai=>{if(!topics.find(t=>(t.topic||'').toLowerCase()===ai.toLowerCase())){topics.unshift({label:'#'+ai.replace(/\s+/g,''),topic:ai,count:0});}});row.innerHTML=topics.slice(0,14).map(t=>`<button class="hot-chip" style="flex:0 0 auto;background:#222;border:1px solid #333;color:#ddd;border-radius:16px;padding:5px 10px;font-size:11px;cursor:pointer" onclick="document.getElementById('ai-topic-input-final5').value='${esc(t.topic).replace(/'/g,'\\''}';document.getElementById('ai-topic-input-final5').focus();searchTopic('${esc(t.topic).replace(/'/g,'\\''}')">${esc(t.label)}</button>`).join('');inp.insertAdjacentElement('afterend',row);}
33
-
34
- // ===== SSE AUTO UPDATE =====
35
- let _sseSource=null;
36
- function connectSSE(){try{_sseSource=new EventSource('/api/events');_sseSource.onmessage=e=>{try{const d=JSON.parse(e.data);if(d.type==='new_post'||d.type==='new_short'){fetch('/api/ai_wall').then(r=>r.json()).then(j=>{_wallPosts=j.posts||[];if(typeof renderShortAISlide==='function')renderShortAISlide();const track=document.getElementById('ai-wall-track');if(track)_wallPosts.length?track.innerHTML=_wallPosts.slice(0,20).map((p,i)=>makeWallItem(p,i)).join(''):null;});}}catch{}};_sseSource.onerror=()=>setTimeout(connectSSE,5000);}catch(e){}}
37
- let _lastWallLen=0;
38
- setInterval(()=>{fetch('/api/ai_wall').then(r=>r.json()).then(j=>{const w=j.posts||[];if(w.length!==_lastWallLen){_lastWallLen=w.length;_wallPosts=w;const track=document.getElementById('ai-wall-track');if(track)w.length?track.innerHTML=w.slice(0,20).map((p,i)=>makeWallItem(p,i)).join(''):null;if(typeof renderShortAISlide==='function')renderShortAISlide();}}).catch(()=>{});},30000);
39
- connectSSE();
40
-
41
- // ===== Short AI slide =====
42
- async function renderShortAISlide(){let home=document.getElementById('view-home');if(!home)return;document.getElementById('short-ai-final-slide')?.remove();let wall=(await fetch('/api/ai_wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];let vids=wall.filter(p=>p.video);if(!vids.length)return;let wrap=document.createElement('div');wrap.id='short-ai-final-slide';wrap.className='slider-wrap';wrap.innerHTML='<div class="slider-header"><span class="slider-label">🎬 Short AI</span></div><div class="slider-track">'+vids.slice(0,30).map((p,i)=>`<div class="slider-item shorts-item" onclick="openAIShortFeed(${i})"><div class="slider-thumb shorts-thumb"><video src="${p.video}" muted preload="metadata" style="width:100%;height:100%;object-fit:cover"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`).join('')+'</div>';let comp=home.querySelector('.ai-compose');(comp&&comp.nextSibling?comp.parentNode.insertBefore(wrap,comp.nextSibling):home.prepend(wrap));}
43
- setTimeout(renderShortAISlide,2500);
44
-
45
- setInterval(ensureHotTopics,2000);
46
- })();
47
- </script>
48
- '''
49
-
50
- # Register route if possible
51
- if f6 and app:
52
- try:
53
- # Remove duplicate / route to avoid conflict
54
- original_routes = [r for r in app.router.routes if not (getattr(r,'path',None)=='/' and 'GET' in getattr(r,'methods',set()))]
55
- app.router.routes = original_routes
56
-
57
- @app.get('/')
58
- async def patch_homepage():
59
- html = f5.f4.f3.f2.f1._load_index_html() if f5 else "<html><body></body></html>"
60
- body = ""
61
- if hasattr(rt,'old') and hasattr(rt.old,'PATCH_INJECT'):
62
- body += getattr(rt.old,'PATCH_INJECT','')
63
- if f5:
64
- body += getattr(f5.f4.f3.f2.f1,'FINAL_INJECT','') if hasattr(f5,'f4') else ''
65
- body += getattr(f5.f4.f3,'FINAL3_INJECT','') if hasattr(f5,'f4') else ''
66
- body += getattr(f5.f4,'FINAL4_INJECT','') if hasattr(f5,'f4') else ''
67
- body += getattr(f5,'FINAL5_INJECT','') if hasattr(f5,'f4') else ''
68
- body += getattr(f6,'FINAL6_INJECT','') if f6 else ''
69
- body += getattr(f6,'FINAL6_FAST_HOME_INJECT','') if f6 else ''
70
- body += getattr(f6,'FINAL6E_INJECT','') if f6 else ''
71
- body += PATCH_CSS_JS
72
- if '</body>' in html:
73
- html = html.replace('</body>', body + '\n</body>')
74
- else:
75
- html = html + body
76
- return HTMLResponse(html)
77
- except Exception as e:
78
- print(f"[ERROR] register route: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ai_short_v2.py DELETED
@@ -1,2083 +0,0 @@
1
- """VNEWS Short AI v2 — Short creator with TikTok background music, uploaded audio,
2
- uploaded video/image background, and 'recreate from designed slides' (image-only,
3
- reusing previous short audio, NO text overlays) mode.
4
-
5
- Registered by app_v2_entry.py (import ai_short_v2). Uses the SAME wall store
6
- (WALL_FILE) as the wall endpoints so posts created by the designer survive and
7
- can be re-shorted purely from designed images.
8
- """
9
- import os
10
- import re
11
- import json
12
- import time
13
- import uuid
14
- import hashlib
15
- import subprocess
16
- import threading
17
-
18
- import requests
19
- from urllib.parse import quote as urllib_quote
20
- from fastapi import Request, UploadFile, File, Query
21
- from fastapi.responses import JSONResponse, FileResponse, Response, StreamingResponse
22
-
23
- try:
24
- import yt_dlp
25
- except Exception: # pragma: no cover
26
- yt_dlp = None
27
-
28
- try:
29
- from PIL import Image, ImageDraw, ImageFont
30
- except Exception: # pragma: no cover
31
- Image = ImageDraw = ImageFont = None
32
-
33
- try:
34
- from main import app
35
- except Exception: # pragma: no cover
36
- from fastapi import FastAPI
37
- app = FastAPI()
38
-
39
- DATA_DIR = "/data" if os.path.isdir("/data") else os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
40
- WALL_FILE = os.path.join(DATA_DIR, "wall_posts.json")
41
- SHORTS_DIR = os.path.join(DATA_DIR, "ai_shorts")
42
- UPLOAD_DIR = os.path.join(DATA_DIR, "short_uploads")
43
- WALL_IMG_DIR = os.path.join(DATA_DIR, "wall_imgs")
44
- os.makedirs(SHORTS_DIR, exist_ok=True)
45
- os.makedirs(UPLOAD_DIR, exist_ok=True)
46
-
47
- _wl_lock = threading.Lock()
48
-
49
- UA_HEADERS = {
50
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
51
- "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
52
- "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8",
53
- }
54
-
55
- # ---------------------------------------------------------------------------
56
- # Video scraping (YouTube / TikTok / news sites) via yt-dlp + oEmbed fallback
57
- # ---------------------------------------------------------------------------
58
- _SCRAPE_CACHE = {} # url -> {ok, ...} (in-memory, TTL 30 min)
59
- _SCRAPE_TTL = 30 * 60
60
-
61
- YTDLP_OPTS = {
62
- "format": "best[height<=720][ext=mp4]/best[height<=720]/best",
63
- "quiet": True,
64
- "no_warnings": True,
65
- "noplaylist": True,
66
- "socket_timeout": 30,
67
- "retries": 5,
68
- "fragment_retries": 5,
69
- "ignoreerrors": False,
70
- "extractor_args": {"youtube": {"player_client": ["tv", "ios", "mweb"]}},
71
- "http_headers": UA_HEADERS,
72
- }
73
-
74
-
75
- # ---------------------------------------------------------------------------
76
- # YouTube cookies (bypasses the "Sign in to confirm you're not a bot" block).
77
- # Sources, in priority order:
78
- # 1. YT_COOKIES env var (HF Space secret — raw Netscape-format cookies.txt)
79
- # 2. /app/cookies.txt (a cookies.txt file baked into the repo/runtime)
80
- # yt-dlp reads a Netscape cookies.txt via the 'cookiefile' option.
81
- # ---------------------------------------------------------------------------
82
- _cookie_file = None
83
-
84
-
85
- def _ensure_cookies():
86
- """Materialise a cookies.txt (Netscape format) for yt-dlp if any cookie
87
- source is available. Returns the cookiefile path or None."""
88
- global _cookie_file
89
- if _cookie_file and os.path.exists(_cookie_file):
90
- return _cookie_file
91
- content = None
92
- # 1. HF Space secret YT_COOKIES (raw cookies.txt content)
93
- secret = os.environ.get("YT_COOKIES", "").strip()
94
- if secret and ("# Netscape" in secret or "#HTTP" in secret or "youtube.com" in secret or "\tTRUE" in secret):
95
- content = secret
96
- # 2. baked-in file
97
- if not content:
98
- for p in ("/app/cookies.txt", "cookies.txt"):
99
- if os.path.exists(p):
100
- content = open(p, encoding="utf-8", errors="ignore").read()
101
- break
102
- if not content:
103
- _cookie_file = None
104
- return None
105
- try:
106
- path = os.path.join(DATA_DIR, "yt_cookies.txt")
107
- os.makedirs(os.path.dirname(path), exist_ok=True)
108
- with open(path, "w", encoding="utf-8") as f:
109
- f.write(content)
110
- _cookie_file = path
111
- return path
112
- except Exception:
113
- return None
114
-
115
-
116
- def _ytdlp_opts():
117
- """YTDLP opts + cookiefile (only when cookies are available)."""
118
- opts = dict(YTDLP_OPTS)
119
- cf = _ensure_cookies()
120
- if cf:
121
- opts["cookiefile"] = cf
122
- # also add "cookiesfrombrowser" fallback? No — datacenter IPs can't read
123
- # a local browser. cookiefile is the reliable path.
124
- return opts
125
-
126
-
127
- def _oembed_probe(url):
128
- """Cheap metadata fallback for TikTok/Facebook/Instagram/YouTube (no direct URL)."""
129
- try:
130
- host = (re.sub(r"^https?://", "", url).split("/")[0] or "").lower()
131
- api = None
132
- if "tiktok" in host:
133
- api = "https://www.tiktok.com/oembed?url=" + urllib_quote(url, safe="")
134
- elif "facebook" in host or "fb.watch" in host:
135
- api = "https://www.facebook.com/plugins/video/oembed.json?url=" + urllib_quote(url, safe="")
136
- elif "youtube.com" in host or "youtu.be" in host:
137
- api = "https://www.youtube.com/oembed?url=" + urllib_quote(url, safe="") + "&format=json"
138
- if not api:
139
- return None
140
- # Facebook oEmbed often times out from datacenter IPs; use a shorter timeout
141
- _timeout = 8 if ("facebook" in host or "fb.watch" in host) else 12
142
- j = {}
143
- try:
144
- r = requests.get(api, headers=UA_HEADERS, timeout=_timeout)
145
- if r.status_code == 200:
146
- j = r.json() or {}
147
- except Exception:
148
- j = {}
149
- # YouTube: youtube.com/oembed is often SNI-blocked from datacenter IPs.
150
- # Fall back to _yt_meta (noembed.com cascade) which reliably returns
151
- # title+thumbnail+description from restricted networks.
152
- yt_meta = None
153
- if "youtube.com" in host or "youtu.be" in host:
154
- yt_meta = _yt_meta(url)
155
- title = ((j.get("title") or "") or (yt_meta or {}).get("title") or "").strip()[:200]
156
- thumb = ((j.get("thumbnail_url") or "") or (yt_meta or {}).get("thumbnail") or "").strip()
157
- desc = (yt_meta or {}).get("description") or ""
158
- if "youtube.com" in host or "youtu.be" in host:
159
- if not desc:
160
- desc = (yt_meta or {}).get("description") or ""
161
- embed_url = _oembed_embed_url(url)
162
- # oEmbed providers (notably TikTok short links like vm.tiktok.com) don't
163
- # expose the video ID in the URL, but the `html` field contains the
164
- # canonical <iframe src> — parse it so short links still embed.
165
- if not embed_url:
166
- try:
167
- m_html = re.search(r'<iframe[^>]+src="([^"]+)"', ((j or {}).get("html") or ""))
168
- if m_html:
169
- embed_url = m_html.group(1).replace("&amp;", "&")
170
- if "?" in embed_url and "autoplay" not in embed_url:
171
- embed_url += "&autoplay=1&rel=0"
172
- except Exception:
173
- pass
174
- return {
175
- "ok": True,
176
- "title": title[:200],
177
- "thumbnail": thumb,
178
- "duration": None,
179
- "extractor": "oembed",
180
- "direct_url": None,
181
- "previewable": False, # no direct streamable URL from oEmbed alone
182
- "embed_url": embed_url,
183
- "description": desc[:2000],
184
- "note": "Có thể lấy được thông tin, nhưng không tải được video trực tiếp từ link này.",
185
- }
186
- except Exception:
187
- return None
188
-
189
-
190
- def _yt_meta(url):
191
- """Fetch YouTube video metadata (title/description/thumbnail).
192
-
193
- Cascades over several providers so at least title+thumbnail always come
194
- back even from datacenter IPs where www.youtube.com is SNI-blocked:
195
- 1. noembed.com — reliable title+thumb (works from restricted IPs)
196
- 2. youtube oEmbed — title + thumbnail_url
197
- 3. watch page og:tags — title + description + thumbnail (best-effort)
198
- Description is best-effort (YT oEmbed has no description field); when
199
- unavailable the caller falls back to the title. Returns dict or None."""
200
- try:
201
- vid = _yt_id_from_url(url)
202
- if not vid:
203
- return None
204
- out = {"video_id": vid, "title": "", "description": "", "thumbnail": ""}
205
- watch = f"https://www.youtube.com/watch?v={vid}"
206
-
207
- # 1) noembed (title+thumb, no desc)
208
- try:
209
- r = requests.get(f"https://noembed.com/embed?url={urllib_quote(watch, safe='')}",
210
- headers=UA_HEADERS, timeout=15)
211
- if r.status_code == 200:
212
- j = r.json() or {}
213
- out["title"] = (j.get("title") or "").strip()[:250]
214
- out["thumbnail"] = (j.get("thumbnail_url") or "").strip()
215
- except Exception:
216
- pass
217
-
218
- # 2) youtube oEmbed (title+thumb)
219
- if not out["title"]:
220
- try:
221
- r2 = requests.get(f"https://www.youtube.com/oembed?url={urllib_quote(watch, safe='')}&format=json",
222
- headers=UA_HEADERS, timeout=15)
223
- if r2.status_code == 200:
224
- j2 = r2.json() or {}
225
- out["title"] = (j2.get("title") or "").strip()[:250]
226
- out["thumbnail"] = (j2.get("thumbnail_url") or "").strip()
227
- except Exception:
228
- pass
229
-
230
- # 3) watch page og:tags (title + description + thumb, best-effort)
231
- try:
232
- r3 = requests.get(watch, headers=UA_HEADERS, timeout=20)
233
- if r3.status_code == 200:
234
- h3 = r3.text
235
- def _og(prop):
236
- mm = re.search(r'<meta[^>]+property="og:' + prop + r'"[^>]+content="([^"]*)"', h3) or \
237
- re.search(r'<meta[^>]+content="([^"]*)"[^>]+property="og:' + prop + r'"', h3)
238
- return mm.group(1).strip() if mm else ""
239
- def _nm(name):
240
- mm = re.search(r'<meta[^>]+name="' + name + r'"[^>]+content="([^"]*)"', h3)
241
- return mm.group(1).strip() if mm else ""
242
- if not out["title"]:
243
- out["title"] = _og("title") or _nm("title")
244
- out["description"] = _og("description") or _nm("description")
245
- if not out["thumbnail"]:
246
- out["thumbnail"] = _og("image") or ""
247
- if out["thumbnail"].startswith("//"):
248
- out["thumbnail"] = "https:" + out["thumbnail"]
249
- except Exception:
250
- pass
251
-
252
- # 4) r.jina.ai reader proxy — server-side fetch that renders the watch
253
- # page and returns Title/Description/Thumbnail lines as markdown.
254
- # Requires the Space origin in the Origin header (CORS check). Works
255
- # from datacenter IPs where youtube.com is SNI-blocked.
256
- if not out["description"] or not out["title"]:
257
- try:
258
- _hdrs = dict(UA_HEADERS)
259
- _hdrs["Origin"] = "https://bep40-vnews.hf.space"
260
- r4 = requests.get(f"https://r.jina.ai/{watch}", headers=_hdrs, timeout=30)
261
- if r4.status_code == 200:
262
- h4 = r4.text
263
- _tm = re.search(r'(?:^|\n)Title:\s*(.+)', h4)
264
- _dm = re.search(r'(?:^|\n)Description:\s*(.+)', h4, re.S)
265
- _im = re.search(r'(?:^|\n)Thumbnail:\s*(\S+)', h4)
266
- if _tm:
267
- out["title"] = _tm.group(1).strip()[:250]
268
- if _dm:
269
- out["description"] = _dm.group(1).strip()[:2000]
270
- if _im:
271
- th = _im.group(1).strip()
272
- if th.startswith("//"):
273
- th = "https:" + th
274
- out["thumbnail"] = th
275
- except Exception:
276
- pass
277
-
278
- if not out["title"] and not out["description"]:
279
- return None
280
- return {
281
- "video_id": vid,
282
- "title": (out["title"] or "").strip()[:250],
283
- "description": (out["description"] or "").strip()[:2000],
284
- "thumbnail": out["thumbnail"],
285
- }
286
- except Exception:
287
- return None
288
-
289
-
290
- def _yt_id_from_url(url):
291
- m = re.search(r'(?:youtube\.com/(?:embed|watch)\?v=|youtu\.be/|youtube-nocookie\.com/embed/)([a-zA-Z0-9_-]{11})', (url or ""))
292
- return m.group(1) if m else ""
293
-
294
-
295
- def _is_known_social(url):
296
- """True for platforms whose content is embeddable via oEmbed iframes."""
297
- try:
298
- host = (re.sub(r"^https?://", "", url or "").split("/")[0] or "").lower()
299
- return any(k in host for k in ("tiktok", "facebook", "fb.watch", "instagram", "youtube", "youtu.be", "vimeo", "twitter", "x.com"))
300
- except Exception:
301
- return False
302
-
303
-
304
- def _oembed_embed_url(url):
305
- """Derive a browser-embeddable iframe URL for social video links.
306
-
307
- Used as a Short HOT fallback when the direct media cannot be downloaded:
308
- the post is still created, and the TikTok-style feed renders it as an
309
- oEmbed iframe slide (exactly like the football video slides on YouTube)
310
- while the title/description/thumb come from the oEmbed metadata.
311
- """
312
- try:
313
- host = (re.sub(r"^https?://", "", url).split("/")[0] or "").lower()
314
- u = (url or "").strip()
315
- if "tiktok" in host:
316
- m = re.search(r"/(?:video|@[\w.\-]+/video|embed/v2)/(\d+)", u)
317
- if m:
318
- return f"https://www.tiktok.com/embed/v2/{m.group(1)}"
319
- return ""
320
- if "facebook" in host or "fb.watch" in host or "fb.gg" in host:
321
- return "https://www.facebook.com/plugins/video.php?href=" + urllib_quote(u, safe="") + "&show_text=0"
322
- if "instagram" in host:
323
- m = re.search(r"/p/([\w\-]+)/?", u)
324
- if m:
325
- return f"https://www.instagram.com/p/{m.group(1)}/embed/"
326
- if "youtube.com" in host or "youtu.be" in host:
327
- m = re.search(r"(?:v=|shorts/|embed/|youtu\.be/)([a-zA-Z0-9_-]{11})", u)
328
- if m:
329
- return f"https://www.youtube.com/embed/{m.group(1)}?autoplay=1&rel=0"
330
- if "x.com" in host or "twitter" in host:
331
- m = re.search(r"/status/(\d+)", u)
332
- if m:
333
- return f"https://platform.twitter.com/embed/Tweet.html?id={m.group(1)}&dnt=true"
334
- if "vimeo" in host:
335
- m = re.search(r"/(\d+)$", u)
336
- if m:
337
- return f"https://player.vimeo.com/video/{m.group(1)}"
338
- except Exception:
339
- pass
340
- return ""
341
-
342
-
343
- def _is_real_http(u):
344
- """True if a candidate URL is a real http(s) media URL (not a JS template)."""
345
- u = (u or "").strip()
346
- if not re.match(r"^https?://", u):
347
- return False
348
- if "'" in u or '"' in u or "+" in u or u.count("(") > 0:
349
- return False
350
- return True
351
-
352
-
353
- def _scrape_page_html(url):
354
- """Fallback scraper for news sites (24h, dantri, znews...): parse the article
355
- HTML for og:video / <video>/<source> / m3u8|mp4 regex inside JS configs
356
- (e.g. 24h 'playlistConf' blob). Returns info dict or None."""
357
- try:
358
- r = requests.get(url, headers=UA_HEADERS, timeout=25)
359
- if r.status_code != 200:
360
- return None
361
- r.encoding = "utf-8"
362
- html = r.text
363
- except Exception:
364
- return None
365
- title = ""
366
- mt = re.search(r'<meta[^>]+property="og:title"[^>]+content="([^"]+)"', html) or \
367
- re.search(r'<meta[^>]+content="([^"]+)"[^>]+property="og:title"', html) or \
368
- re.search(r"<title[^>]*>([^<]+)</title>", html)
369
- if mt:
370
- title = re.sub(r"\s+", " ", mt.group(1)).strip()[:250]
371
-
372
- # 1) og:video
373
- cands = []
374
- for pat in (r'property="og:video[^"]*"\s+content="([^"]+)"',
375
- r'content="([^"]+)"\s+property="og:video[^"]*"'):
376
- cands += re.findall(pat, html)
377
- # 2) <video>/<source> tags
378
- cands += re.findall(r'<source[^>]+src="([^"]+)"', html)
379
- cands += re.findall(r"<source[^>]+src='([^']+)'", html)
380
- cands += re.findall(r'<video[^>]+src="([^"]+)"', html)
381
- # 3) raw .mp4/.m3u8 URLs in the page (incl. JS playlistConf src:"...")
382
- cands += re.findall(r'https?://[^"\'\s<>\\]+?\.(?:m3u8|mp4)[^"\'\s<>\\]*', html)
383
- # 4) src: "..." inside JS (m3u8/mp4)
384
- cands += re.findall(r'src\s*:\s*["\']([^"\']+?\.(?:m3u8|mp4)[^"\']*)["\']', html)
385
-
386
- # 5) YouTube iframe embeds (e.g. bongdaplus.vn video pages embed highlights)
387
- for yt_iframe_src in re.findall(r'<iframe[^>]+src="([^"]*(?:youtube\.com/embed|youtu\.be/|youtube-nocookie\.com/embed)[^"]*)"[^>]*>', html, re.I):
388
- yt_iframe_src = yt_iframe_src.strip()
389
- if yt_iframe_src.startswith("//"): yt_iframe_src = "https:" + yt_iframe_src
390
- yt_id = re.search(r'(?:embed/|youtu\.be/|v=)([a-zA-Z0-9_-]{11})', yt_iframe_src)
391
- if yt_id:
392
- cands.append(f"https://www.youtube.com/embed/{yt_id.group(1)}?autoplay=1&rel=0&enablejsapi=1")
393
- else:
394
- cands.append(yt_iframe_src)
395
-
396
- # 6) YouTube embed URLs in JS strings (src: "https://youtube.com/embed/...")
397
- for yt_js in re.findall(r'src\s*:\s*["\']([^"\']*(?:youtube\.com/embed|youtu\.be/)[^"\']*)["\']', html, re.I):
398
- yt_js = yt_js.strip()
399
- if yt_js.startswith("//"): yt_js = "https:" + yt_js
400
- cands.append(yt_js)
401
-
402
- # normalize relative URLs + dedupe + prefer 720p m3u8 then mp4
403
- from urllib.parse import urljoin
404
- seen = set()
405
- good = []
406
- for c in cands:
407
- c = c.strip().strip('"').strip("'")
408
- if not c or not _is_real_http(c) and not c.startswith("/"):
409
- continue
410
- if c.startswith("/"):
411
- c = urljoin(url, c)
412
- if not c.startswith("http"):
413
- continue
414
- if c in seen:
415
- continue
416
- seen.add(c)
417
- good.append(c)
418
- if not good:
419
- return None
420
-
421
- # score: prefer m3u8 720p > m3u8 > mp4 720p > mp4
422
- def score(c):
423
- s = 0
424
- if "720p" in c or "720" in c:
425
- s += 20
426
- if ".m3u8" in c:
427
- s += 10
428
- if "1080" in c:
429
- s += 18
430
- if "480" in c:
431
- s += 8
432
- return s
433
- good.sort(key=score, reverse=True)
434
- direct = good[0]
435
-
436
- thumb = ""
437
- mt2 = re.search(r'<meta[^>]+property="og:image[^"]*"\s+content="([^"]+)"', html) or \
438
- re.search(r'<meta[^>]+content="([^"]+)"[^>]+property="og:image[^"]*"', html)
439
- if mt2:
440
- thumb = mt2.group(1).strip()
441
-
442
- is_hls = ".m3u8" in direct.lower()
443
- is_youtube = "youtube.com/embed" in direct.lower() or "youtu.be" in direct.lower() or "youtube-nocookie" in direct.lower()
444
- return {
445
- "ok": True,
446
- "url": url,
447
- "title": title,
448
- "duration": None,
449
- "thumbnail": thumb,
450
- "direct_url": direct,
451
- "extractor": "youtube" if is_youtube else "html-page",
452
- "previewable": True,
453
- "is_hls": is_hls,
454
- "note": "",
455
- }
456
-
457
-
458
- def _resolve_media_url(url):
459
- """Fetch the body of a media URL using the right headers (referer for news CDNs)."""
460
- HDRS = dict(UA_HEADERS)
461
- host = (re.sub(r"^https?://", "", url).split("/")[0] or "").lower()
462
- if "vnecdn" in host or "vnexpress" in host:
463
- HDRS["Referer"] = "https://vnexpress.net/"
464
- elif "cdn.24h" in host or "24h.com.vn" in host:
465
- HDRS["Referer"] = "https://www.24h.com.vn/"
466
- return HDRS
467
-
468
-
469
- def _scrape_video_info(url):
470
- """Extract direct video URL + metadata for a user-pasted link.
471
-
472
- Returns dict with keys: ok, url (original), title, duration, thumbnail,
473
- direct_url (proxy-able), extractor, previewable, note.
474
- """
475
- try:
476
- now = time.time()
477
- cached = _SCRAPE_CACHE.get(url)
478
- if cached and now - cached.get("_t", 0) < _SCRAPE_TTL:
479
- return cached
480
- except Exception:
481
- pass
482
-
483
- # Early-detect social/video platforms that yt-dlp handles slowly or not at all.
484
- # Facebook URLs block datacenter IPs → yt-dlp hangs for 15s+; skip it and
485
- # go straight to oEmbed metadata-only fallback.
486
- _host_l = (re.sub(r"^https?://", "", url).split("/")[0] or "").lower()
487
- _is_facebook = "facebook" in _host_l or "fb.watch" in _host_l
488
-
489
- out = None
490
- if yt_dlp is not None and not _is_facebook:
491
- try:
492
- with yt_dlp.YoutubeDL(_ytdlp_opts()) as ydl:
493
- info = ydl.extract_info(url, download=False)
494
- # pick best direct (non-m3u8) progressive URL
495
- direct = None
496
- if info:
497
- direct = info.get("url") or ""
498
- for f in info.get("formats") or []:
499
- proto = (f.get("protocol") or "")
500
- if f.get("url") and proto not in ("m3u8_native", "m3u8"):
501
- direct = f.get("url")
502
- break
503
- dur = info.get("duration") if info else None
504
- try:
505
- dur = float(dur) if dur is not None else None
506
- except Exception:
507
- dur = None
508
- extractor = (info.get("extractor_key") or info.get("extractor") or "generic") if info else "generic"
509
- is_hls = bool(direct) and ".m3u8" in direct.lower()
510
- # If yt-dlp returned a bogus JS template URL ('+d+' etc.), treat as
511
- # a scrape failure -> fall through to the HTML page parser.
512
- yt_bad = not _is_real_http(direct)
513
- out = {
514
- "ok": not yt_bad,
515
- "url": url,
516
- "title": (info.get("title") or "").strip()[:250] if info else "",
517
- "duration": dur,
518
- "thumbnail": (info.get("thumbnail") or "").strip() or "" if not yt_bad else "",
519
- "direct_url": direct or "",
520
- "extractor": extractor,
521
- "previewable": bool(direct) and not yt_bad,
522
- "is_hls": is_hls,
523
- "note": "",
524
- }
525
- except Exception as e:
526
- if getattr(e, "args", None):
527
- msg = str(e.args[0]) if isinstance(e.args[0], str) else str(e)
528
- else:
529
- msg = str(e)
530
- # split real error after '[xxx] '
531
- m = re.search(r"\]\s*(.+)$", msg)
532
- err = m.group(1) if m else msg[:200]
533
- out = {"ok": False, "url": url, "error": err[:200]}
534
-
535
- # YouTube-specific fallback: if yt-dlp fails (SSL/EOF, rate-limit),
536
- # extract video ID and return the embed iframe URL + thumbnail.
537
- # The frontend renders YouTube embed URLs as iframes.
538
- yt_id_match = re.search(r'(?:youtube\.com/(?:embed|watch)\?v=|youtu\.be/|youtube-nocookie\.com/embed/)([a-zA-Z0-9_-]{11})', url)
539
- if yt_id_match:
540
- yt_id = yt_id_match.group(1)
541
- out = {
542
- "ok": True,
543
- "url": url,
544
- "title": f"YouTube video {yt_id}",
545
- "duration": None,
546
- "thumbnail": f"https://i.ytimg.com/vi/{yt_id}/hqdefault.jpg",
547
- "direct_url": f"https://www.youtube.com/embed/{yt_id}?autoplay=1&rel=0&enablejsapi=1",
548
- "extractor": "youtube-fallback",
549
- "previewable": True,
550
- "is_hls": False,
551
- "note": "yt-dlp failed, using YouTube embed directly",
552
- }
553
-
554
- # YouTube enrichment: grab the watch-page meta tags (title/description/
555
- # thumbnail). yt-dlp often gives a title + mp4 URL but NO description, and
556
- # the fallback path gives a bare 'YouTube video {id}' — the og: tags from
557
- # the watch page fix both. Only fills gaps; keeps the existing direct_url.
558
- if "youtube.com" in _host_l or "youtu.be" in _host_l:
559
- _meta = _yt_meta(url)
560
- if _meta:
561
- if not out or not out.get("ok") or not (out.get("title") or "").strip() or "YouTube video" in (out.get("title") or ""):
562
- out_title = _meta.get("title") or ""
563
- else:
564
- out_title = (out.get("title") or "")
565
- desc = _meta.get("description") or ""
566
- thumb = _meta.get("thumbnail") or (out or {}).get("thumbnail", "")
567
- if not out:
568
- out = {"ok": True, "url": url}
569
- out["title"] = out_title or _meta.get("title") or (out.get("title") or "")
570
- out["description"] = desc
571
- if thumb:
572
- out["thumbnail"] = thumb
573
-
574
- # If yt-dlp failed / gave a bad URL, try parsing the article HTML directly
575
- # (handles 24h.com.vn JS configs, dantri, znews, some vnexpress pages).
576
- if not out or not out.get("ok") or not out.get("direct_url"):
577
- page = _scrape_page_html(url)
578
- if page:
579
- # keep yt-dlp title/duration for social sites, take media from page
580
- base = {"ok": True, "url": url,
581
- "title": page.get("title") or (out or {}).get("title", ""),
582
- "duration": (out or {}).get("duration") if (out or {}).get("direct_url") else page.get("duration"),
583
- "thumbnail": page.get("thumbnail") or (out or {}).get("thumbnail", ""),
584
- "direct_url": page.get("direct_url"),
585
- "extractor": page.get("extractor") or "html-page",
586
- "previewable": True,
587
- "is_hls": page.get("is_hls", False),
588
- "note": page.get("note", ""),
589
- }
590
- out = base
591
-
592
- # metadata-only fallback (oEmbed) — lets the user at least see title/thumb
593
- if not out or not out.get("ok"):
594
- probe = _oembed_probe(url)
595
- if probe:
596
- probe["url"] = url
597
- out = probe
598
-
599
- if not out:
600
- out = {"ok": False, "url": url, "error": "Không lấy được thông tin video từ link này."}
601
- if "is_hls" not in out:
602
- out["is_hls"] = bool(out.get("direct_url", "")) and ".m3u8" in (out.get("direct_url", "") or "").lower()
603
- try:
604
- out["_t"] = time.time()
605
- _SCRAPE_CACHE[url] = out
606
- if len(_SCRAPE_CACHE) > 200:
607
- for k in list(_SCRAPE_CACHE)[:50]:
608
- _SCRAPE_CACHE.pop(k, None)
609
- except Exception:
610
- pass
611
- return out
612
-
613
-
614
- def _load_wall_posts():
615
- try:
616
- with _wl_lock:
617
- if os.path.exists(WALL_FILE):
618
- with open(WALL_FILE, "r", encoding="utf-8") as f:
619
- return json.load(f) or []
620
- except Exception:
621
- pass
622
- return []
623
-
624
-
625
- def _save_wall_posts(posts):
626
- try:
627
- with _wl_lock:
628
- tmp = WALL_FILE + ".tmp"
629
- with open(tmp, "w", encoding="utf-8") as f:
630
- json.dump(posts, f, ensure_ascii=False)
631
- os.replace(tmp, WALL_FILE)
632
- except Exception:
633
- pass
634
-
635
-
636
- def _clean(s):
637
- s = re.sub(r"[ \t]+", " ", s or "")
638
- s = re.sub(r"\n{3,}", "\n\n", s)
639
- return s.strip()
640
-
641
-
642
- def _safe_name(name):
643
- return re.sub(r"[^a-zA-Z0-9_.-]", "_", name)[:120]
644
-
645
-
646
- # =========================================================================
647
- # TikTok / background MUSIC list — royalty-free tracks with verified direct
648
- # mp3 URLs (incompetech CC-BY 4.0, Pixabay, Archive.org).
649
- # =========================================================================
650
- MUSIC_LIST = [
651
- {"id": "none", "name": "🚫 Không có nhạc nền", "url": ""},
652
- {"id": "carefree", "name": "🎵 Carefree (Joyful)", "url": "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Carefree.mp3"},
653
- {"id": "wholesome", "name": "🎵 Wholesome (Warm)", "url": "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Wholesome.mp3"},
654
- {"id": "fluffing", "name": "🎵 Fluffing a Duck (Quirky)", "url": "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Fluffing%20a%20Duck.mp3"},
655
- {"id": "loping", "name": "🎵 Loping Sting (Short)", "url": "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Loping%20Sting.mp3"},
656
- {"id": "modern", "name": "🎵 Modern Vibes (Electronic)", "url": "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Modern%20Vibes.mp3"},
657
- {"id": "cheezee", "name": "🎵 Chee Zee Jungle (Upbeat)", "url": "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Chee%20Zee%20Jungle.mp3"},
658
- {"id": "constance", "name": "🎵 Constance (Cinematic)", "url": "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Constance.mp3"},
659
- {"id": "edm", "name": "🎵 EDM Detection Mode (Energetic)", "url": "https://incompetech.com/music/royalty-free/mp3-royaltyfree/EDM%20Detection%20Mode.mp3"},
660
- {"id": "spyglass", "name": "🎵 Spy Glass (Mystery)", "url": "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Spy%20Glass.mp3"},
661
- {"id": "raving", "name": "🎵 Raving Energy (Dance)", "url": "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Raving%20Energy.mp3"},
662
- {"id": "pixabay", "name": "🎵 Pixabay Sunset Vibes", "url": "https://cdn.pixabay.com/download/audio/2022/05/27/audio_1808fbf07a.mp3"},
663
- ]
664
-
665
- MUSIC_BY_ID = {m["id"]: m for m in MUSIC_LIST}
666
-
667
-
668
- # =========================================================================
669
- # local URL resolution (uploaded files / wall images) + remote fetch
670
- # =========================================================================
671
- def _fetch_bytes(url):
672
- """Fetch image/audio/video bytes from a URL. Handles local /api/ URLs."""
673
- if not url:
674
- return None
675
- if url.startswith("/api/ai-short/upload/"):
676
- p = os.path.join(UPLOAD_DIR, os.path.basename(url.rstrip("/")))
677
- if os.path.exists(p):
678
- with open(p, "rb") as f:
679
- return f.read()
680
- return None
681
- if url.startswith("/api/wall/img/"):
682
- p = os.path.join(WALL_IMG_DIR, os.path.basename(url.rstrip("/")))
683
- if os.path.exists(p):
684
- with open(p, "rb") as f:
685
- return f.read()
686
- return None
687
- try:
688
- r = requests.get(url, headers=UA_HEADERS, timeout=30)
689
- if r.status_code == 200 and len(r.content) > 900:
690
- return r.content
691
- except Exception:
692
- pass
693
- return None
694
-
695
-
696
- def _download_to_file(url, dst, max_mb=400):
697
- """Stream a remote file (video) to disk without loading it into RAM.
698
- Returns True on success. Handles same-origin /api/ URLs by copy.
699
- If the URL is an HLS playlist (.m3u8), downloads+decrypts all segments
700
- via _download_hls_to_ts (handles AES-128 encryption from news CDNs).
701
- YouTube URLs are downloaded via yt-dlp."""
702
- try:
703
- # YouTube embed / watch URLs → use yt-dlp to fetch best MP4
704
- yt_match = re.search(r'youtube\.com/(?:embed|watch)\?v=([a-zA-Z0-9_-]{11})|youtu\.be/([a-zA-Z0-9_-]{11})', (url or ""))
705
- if yt_dlp is not None and yt_match:
706
- yt_id = yt_match.group(1) or yt_match.group(2)
707
- tmp_out = dst + ".yt.mp4"
708
- cf = _ensure_cookies()
709
- ytdlp_args = ["yt-dlp", "-f", "best[ext=mp4][height<=720]/best[ext=mp4]/best",
710
- "--no-playlist", "--remux-video", "mp4", "-o", tmp_out,
711
- "--timeout", "30", "--no-warnings"]
712
- if cf:
713
- ytdlp_args += ["--cookiefile", cf]
714
- # use the video ID to construct the canonical watch URL
715
- ytdlp_args.append(f"https://www.youtube.com/watch?v={yt_id}")
716
- try:
717
- subprocess.run(ytdlp_args, check=True, stdout=subprocess.PIPE,
718
- stderr=subprocess.PIPE, timeout=180)
719
- if os.path.exists(tmp_out) and os.path.getsize(tmp_out) > 0:
720
- os.rename(tmp_out, dst)
721
- return True
722
- except Exception:
723
- pass
724
- return False
725
-
726
- # HLS playlists need segment-wise download + AES decryption
727
- if ".m3u8" in (url or "").lower():
728
- return _download_hls_to_ts(url, dst, max_mb=max_mb)
729
- if url.startswith("/api/ai-short/upload/"):
730
- p = os.path.join(UPLOAD_DIR, os.path.basename(url.rstrip("/")))
731
- if os.path.exists(p):
732
- with open(p, "rb") as f, open(dst, "wb") as g:
733
- g.write(f.read())
734
- return True
735
- return False
736
- if url.startswith("/api/wall/img/"):
737
- p = os.path.join(WALL_IMG_DIR, os.path.basename(url.rstrip("/")))
738
- if os.path.exists(p):
739
- with open(p, "rb") as f, open(dst, "wb") as g:
740
- g.write(f.read())
741
- return True
742
- return False
743
- with requests.get(url, headers=UA_HEADERS, timeout=60, stream=True,
744
- allow_redirects=True) as r:
745
- if r.status_code != 200:
746
- return False
747
- total = 0
748
- with open(dst, "wb") as f:
749
- for chunk in r.iter_content(chunk_size=256 * 1024):
750
- if not chunk:
751
- continue
752
- f.write(chunk)
753
- total += len(chunk)
754
- if total > max_mb * 1024 * 1024:
755
- return False
756
- return os.path.exists(dst) and os.path.getsize(dst) > 900
757
- except Exception:
758
- return False
759
-
760
-
761
- def _download_hls_to_ts(m3u8_url, dst, max_mb=400):
762
- """Download an HLS stream (incl. AES-128 encrypted) to a single .ts file,
763
- decrypting segments in Python. Returns True on success.
764
-
765
- Avoids relying on ffmpeg's network HLS demuxer (which can be fragile on
766
- news CDNs like vnecdn/24h that require referer + AES-128 keys)."""
767
- try:
768
- from urllib.parse import urljoin, urlparse
769
- try:
770
- from Crypto.Cipher import AES
771
- except Exception:
772
- AES = None
773
- HDRS = _resolve_media_url(m3u8_url)
774
- r = requests.get(m3u8_url, headers=HDRS, timeout=30)
775
- if r.status_code != 200:
776
- return False
777
- text = r.text
778
- if "#EXTM3U" not in text:
779
- # Not actually HLS — write raw bytes
780
- with open(dst, "wb") as f:
781
- f.write(r.content)
782
- return os.path.exists(dst) and os.path.getsize(dst) > 900
783
- # master playlist? pick a variant (prefer 720)
784
- if "#EXT-X-STREAM-INF" in text:
785
- ch = re.findall(r'#EXT-X-STREAM-INF[^\n]*\n([^\n]+)', text)
786
- variants = [v.strip() for v in ch if v.strip()]
787
- # pick one containing 720, else first
788
- chosen = next((v for v in variants if "720" in v), variants[0] if variants else None)
789
- if chosen:
790
- if not chosen.startswith("http"):
791
- chosen = urljoin(m3u8_url, chosen)
792
- return _download_hls_to_ts(chosen, dst, max_mb=max_mb)
793
-
794
- key = None
795
- key_uri = None
796
- km = re.search(r'#EXT-X-KEY:METHOD=AES-128,URI="([^"]+)"', text)
797
- if km:
798
- key_uri = km.group(1)
799
- if not key_uri.startswith("http"):
800
- key_uri = urljoin(m3u8_url, key_uri)
801
- kr = requests.get(key_uri, headers=HDRS, timeout=20)
802
- if kr.status_code == 200:
803
- key = kr.content
804
- use_aes = key is not None and AES is not None
805
-
806
- # media sequence drives the AES-CBC IV
807
- seq = 0
808
- mm = re.search(r'#EXT-X-MEDIA-SEQUENCE:\s*(\d+)', text)
809
- if mm:
810
- seq = int(mm.group(1))
811
- keyfm = re.search(r'#EXT-X-KEY:METHOD=AES-128,.*?IV=0x([0-9A-Fa-f]+)', text)
812
- explicit_iv = keyfm.group(1) if keyfm else None
813
-
814
- segs = [l.strip() for l in text.splitlines()
815
- if l.strip() and not l.startswith("#")]
816
- total = 0
817
- with open(dst, "wb") as out:
818
- for i, s in enumerate(segs):
819
- if not s.startswith("http"):
820
- s = urljoin(m3u8_url, s)
821
- sr = requests.get(s, headers=HDRS, timeout=60)
822
- if sr.status_code != 200:
823
- return False
824
- data = sr.content
825
- sr.close()
826
- if use_aes:
827
- # AES-128-CBC decrypt the ENTIRE segment with one call so
828
- # PKCS7 + CBC chaining stay correct (segment is self-contained).
829
- if explicit_iv:
830
- iv = bytes.fromhex(explicit_iv)
831
- else:
832
- iv = (seq + i).to_bytes(16, "big")
833
- data = AES.new(key, AES.MODE_CBC, iv).decrypt(data)
834
- out.write(data)
835
- total += len(data)
836
- if total > max_mb * 1024 * 1024:
837
- return False
838
- return os.path.exists(dst) and os.path.getsize(dst) > 900
839
- except Exception:
840
- return False
841
-
842
-
843
- def _probe_duration(path, fallback=15.0):
844
- try:
845
- pr = subprocess.run(
846
- ["ffprobe", "-v", "error", "-show_entries", "format=duration",
847
- "-of", "default=noprint_wrappers=1:no_key=1", path],
848
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30)
849
- return max(1.0, float((pr.stdout or b"").decode().strip() or fallback))
850
- except Exception:
851
- return fallback
852
-
853
-
854
- def _probe_has_audio(path):
855
- try:
856
- pr = subprocess.run(
857
- ["ffprobe", "-v", "error", "-select_streams", "a", "-show_entries",
858
- "stream=index", "-of", "csv=p=0", path],
859
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30)
860
- return bool((pr.stdout or b"").decode().strip())
861
- except Exception:
862
- return False
863
-
864
-
865
- def _first_frame(video_path, thumb_path, t=0.5):
866
- """Extract a thumbnail frame from a video at time t seconds.
867
- Returns the served URL path or empty string."""
868
- try:
869
- os.makedirs(os.path.dirname(thumb_path), exist_ok=True)
870
- subprocess.run(
871
- ["ffmpeg", "-y", "-ss", str(t), "-i", video_path,
872
- "-frames:v", "1", "-q:v", "3", thumb_path],
873
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
874
- if os.path.exists(thumb_path) and os.path.getsize(thumb_path) > 500:
875
- return f"/api/wall/img/{os.path.basename(thumb_path)}"
876
- except Exception:
877
- pass
878
- return ""
879
-
880
-
881
- # =========================================================================
882
- # Image helpers
883
- # =========================================================================
884
- def _wrap_text_px(draw, text, font, max_width, max_lines):
885
- words = _clean(text).split()
886
- lines, cur = [], ""
887
- for w in words:
888
- test = (cur + " " + w).strip()
889
- try:
890
- width = draw.textbbox((0, 0), test, font=font)[2]
891
- except Exception:
892
- width = len(test) * 20
893
- if width <= max_width:
894
- cur = test
895
- else:
896
- if cur:
897
- lines.append(cur)
898
- cur = w
899
- if len(lines) >= max_lines:
900
- break
901
- if cur and len(lines) < max_lines:
902
- lines.append(cur)
903
- return lines
904
-
905
-
906
- def _cover_resize(img, w, h):
907
- """Center-crop + resize to exactly (w, h)."""
908
- rw, rh = w / h, img.width / img.height
909
- if rw > rh: # image too tall -> crop bottom/top
910
- nh = int(img.width / rw)
911
- top = max(0, (img.height - nh) // 2)
912
- img = img.crop((0, top, img.width, top + nh))
913
- else: # image too wide -> crop left/right
914
- nw = int(img.height * rw)
915
- left = max(0, (img.width - nw) // 2)
916
- img = img.crop((left, 0, left + nw, img.height))
917
- return img.resize((w, h))
918
-
919
-
920
- def _frame_from_image(image_bytes, out_path, seg_idx=0, seg_total=1):
921
- """Full-bleed designed image background + tiny progress chip. NO text."""
922
- W, H = 1080, 1920
923
- bg = Image.new("RGB", (W, H), (10, 10, 10))
924
- try:
925
- im = Image.open(io_bytes(image_bytes)).convert("RGB")
926
- bg = _cover_resize(im, W, H)
927
- except Exception:
928
- pass
929
- draw = ImageDraw.Draw(bg)
930
- try:
931
- font_small = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 26)
932
- except Exception:
933
- font_small = None
934
- if seg_total > 1:
935
- chip = f"{seg_idx + 1}/{seg_total}"
936
- try:
937
- tw = draw.textbbox((0, 0), chip, font=font_small)[2]
938
- except Exception:
939
- tw = len(chip) * 14
940
- draw.rounded_rectangle((W - 40 - tw - 24, 34, W - 22, 74), radius=18, fill=(0, 0, 0))
941
- draw.text((W - 40 - tw - 10, 40), chip, fill=(255, 255, 255), font=font_small)
942
- bg.save(out_path, quality=92)
943
-
944
-
945
- def _frame_with_text(image_bytes, out_path, segment, title, seg_idx=0, seg_total=1):
946
- """Designed image bg + centered key point + footer title (default design)."""
947
- W, H = 1080, 1920
948
- bg = Image.new("RGB", (W, H), (10, 10, 10))
949
- try:
950
- im = Image.open(io_bytes(image_bytes)).convert("RGB")
951
- cover = _cover_resize(im, W, H)
952
- bg = Image.blend(cover, Image.new("RGB", (W, H), (0, 0, 0)), 0.45)
953
- except Exception:
954
- pass
955
- draw = ImageDraw.Draw(bg)
956
- try:
957
- font_brand = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 34)
958
- font_small = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 28)
959
- font_seg = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 56)
960
- font_title = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 32)
961
- except Exception:
962
- font_brand = font_small = font_seg = font_title = None
963
- draw.rectangle((0, 620, W, H), fill=(12, 12, 12))
964
- y = 700
965
- dot_x, dot_y = 48, 762
966
- for i in range(max(1, seg_total)):
967
- fill = (92, 184, 122) if i == seg_idx else (70, 70, 70)
968
- draw.rounded_rectangle((dot_x + i * 38, dot_y, dot_x + i * 38 + 24, dot_y + 10), radius=5, fill=fill)
969
- draw.text((48, 800), "VNEWS AI SHORT", fill=(110, 231, 143), font=font_brand)
970
- draw.rounded_rectangle((48, 854, 260, 900), radius=20, fill=(28, 70, 45))
971
- draw.text((66, 862), f"Đoạn {seg_idx + 1}/{max(1, seg_total)}", fill=(235, 235, 235), font=font_small)
972
- y = 960
973
- maxw = W - 96
974
- for ln in _wrap_text_px(draw, segment, font_seg, maxw, 16):
975
- draw.text((48, y), ln, fill=(255, 255, 255), font=font_seg)
976
- y += 72
977
- if y > 1560:
978
- break
979
- y2 = 1700
980
- draw.line((48, y2 - 24, W - 48, y2 - 24), fill=(70, 70, 70), width=2)
981
- for ln in _wrap_text_px(draw, title, font_title, maxw, 3):
982
- draw.text((48, y2), ln, fill=(220, 220, 220), font=font_title)
983
- y2 += 44
984
- bg.save(out_path, quality=92)
985
-
986
-
987
- def io_bytes(b):
988
- import io
989
- return io.BytesIO(b)
990
-
991
-
992
- def _tts_one(text, voice, speed, out_path):
993
- """Generate one TTS segment (edge-tts with gTTS fallback), speed-adjusted.
994
- Returns the final file path or None on failure."""
995
- edge_voice = {
996
- "vi-vn-hoaimyneural": "vi-VN-HoaiMyNeural", "vi-vn-namminhneural": "vi-VN-NamMinhNeural",
997
- "hoaimy": "vi-VN-HoaiMyNeural", "namminh": "vi-VN-NamMinhNeural", "nam": "vi-VN-NamMinhNeural",
998
- "male": "vi-VN-NamMinhNeural", "nu": "vi-VN-HoaiMyNeural", "female": "vi-VN-HoaiMyNeural",
999
- "mien-nam": "vi-VN-HoaiMyNeural",
1000
- "en-us-andrewmultilingualneural": "en-US-AndrewMultilingualNeural",
1001
- "en-au-williammultilingualneural": "en-AU-WilliamMultilingualNeural",
1002
- "andrew": "en-US-AndrewMultilingualNeural", "en_andrew": "en-US-AndrewMultilingualNeural",
1003
- "jenny": "en-US-AndrewMultilingualNeural", "en_jenny": "en-US-AndrewMultilingualNeural",
1004
- "pt-br-thalitamultilingualneural": "pt-BR-ThalitaMultilingualNeural",
1005
- "thalita": "pt-BR-ThalitaMultilingualNeural", "pt": "pt-BR-ThalitaMultilingualNeural",
1006
- "fr-fr-viviennemultilingualneural": "fr-FR-VivienneMultilingualNeural",
1007
- "fr-fr-remymultilingualneural": "fr-FR-RemyMultilingualNeural",
1008
- "denise": "fr-FR-VivienneMultilingualNeural", "fr": "fr-FR-VivienneMultilingualNeural",
1009
- "de-de-seraphinamultilingualneural": "de-DE-SeraphinaMultilingualNeural",
1010
- "de-de-florianmultilingualneural": "de-DE-FlorianMultilingualNeural",
1011
- "katja": "de-DE-SeraphinaMultilingualNeural", "de": "de-DE-SeraphinaMultilingualNeural",
1012
- "ko-kr-hyusumultilingualneural": "ko-KR-HyunsuMultilingualNeural",
1013
- "ko-kr-hyunsuneural": "ko-KR-HyunsuMultilingualNeural", "sunhee": "ko-KR-HyunsuMultilingualNeural",
1014
- "ko": "ko-KR-HyunsuMultilingualNeural",
1015
- "it-it-giuseppemultilingualneural": "it-IT-GiuseppeMultilingualNeural",
1016
- "ela": "en-US-AndrewMultilingualNeural", "es": "en-US-AndrewMultilingualNeural",
1017
- }.get(voice.lower(), voice)
1018
- aud = out_path
1019
- aud_fast = re.sub(r"\.mp3$", "_fast.mp3", out_path)
1020
- try:
1021
- subprocess.run(
1022
- ["python", "-m", "edge_tts", "--voice", edge_voice, "--text", text,
1023
- "--write-media", aud],
1024
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
1025
- except Exception:
1026
- aud = None
1027
- try:
1028
- from gtts import gTTS
1029
- tld = "com.vn" if voice.lower() in ("nu", "female", "mien-nam", "hoaimy") else "com"
1030
- try:
1031
- gTTS(text, lang="vi", tld=tld, slow=False).save(aud)
1032
- except TypeError:
1033
- gTTS(text, lang="vi", slow=False).save(aud)
1034
- except Exception:
1035
- pass
1036
- if aud and os.path.exists(aud) and os.path.getsize(aud) > 900:
1037
- try:
1038
- subprocess.run(["ffmpeg", "-y", "-i", aud, "-filter:a", f"atempo={speed}", "-vn", aud_fast],
1039
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=90)
1040
- if os.path.exists(aud_fast) and os.path.getsize(aud_fast) > 900:
1041
- return aud_fast
1042
- except Exception:
1043
- pass
1044
- return aud
1045
- return None
1046
-
1047
-
1048
- def _concat_audio(paths, out_path, pad=0.3):
1049
- """Concatenate audio files into one track (m4a/aac)."""
1050
- if not paths:
1051
- return None
1052
- lst = os.path.join(os.path.dirname(out_path), "_alist.txt")
1053
- with open(lst, "w", encoding="utf-8") as f:
1054
- for p in paths:
1055
- f.write("file '" + p.replace("'", "'\\''") + "'\n")
1056
- subprocess.run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", lst,
1057
- "-c:a", "aac", "-b:a", "128k", out_path],
1058
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=240)
1059
- return out_path if os.path.exists(out_path) and os.path.getsize(out_path) > 900 else None
1060
-
1061
-
1062
- def _assemble_video_short(work, video_path, video_dur, img_paths, segs,
1063
- reuse_audio_path, video_audio_path, voice, speed,
1064
- music_path, out_mp4, fallback_title):
1065
- """New video-first short assembly.
1066
-
1067
- Timeline: scraped/uploaded video plays first (up to min(video_dur, voice)),
1068
- then the designed/selected images fill the remainder of the voice duration
1069
- (or until the video covers the whole short). The voice track is
1070
- continuous TTS narration of the segments (or reused previous short audio).
1071
-
1072
- Returns (out_mp4, total_dur) or raises on failure.
1073
- """
1074
- # ---------- 1. narration track (continuous) ----------
1075
- narr = None
1076
- if reuse_audio_path and os.path.exists(reuse_audio_path):
1077
- narr = os.path.join(work, "narr.m4a")
1078
- subprocess.run(["ffmpeg", "-y", "-i", reuse_audio_path,
1079
- "-c:a", "aac", "-b:a", "128k", narr],
1080
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180)
1081
- narr = narr if os.path.exists(narr) and os.path.getsize(narr) > 900 else None
1082
- else:
1083
- voice_parts = []
1084
- for i, seg in enumerate(segs):
1085
- vf = _tts_one(seg, voice, speed, os.path.join(work, f"vf_{i:02d}.mp3"))
1086
- if vf:
1087
- voice_parts.append(vf)
1088
- if voice_parts:
1089
- narr = _concat_audio(voice_parts, os.path.join(work, "narr.m4a"))
1090
- if narr and os.path.exists(narr):
1091
- # small tail silence so the last word isn't cut
1092
- tail = os.path.join(work, "narr_tail.m4a")
1093
- subprocess.run(["ffmpeg", "-y", "-i", narr, "-af", "apad=pad_dur=0.6",
1094
- "-c:a", "aac", "-b:a", "128k", tail],
1095
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
1096
- if os.path.exists(tail) and os.path.getsize(tail) > 900:
1097
- narr = tail
1098
-
1099
- narr_dur = _probe_duration(narr, fallback=0.0) if narr else 0.0
1100
- total_dur = narr_dur
1101
- if total_dur < 1.0:
1102
- # no voice -> short is driven by video length (or music overlays later)
1103
- total_dur = max(1.0, video_dur)
1104
-
1105
- # ---------- 2. split timeline ----------
1106
- # When video is longer than narration (e.g. scraped YouTube video in HOT mode),
1107
- # let the video play at its full length and fill remaining time with images.
1108
- # When narration is longer, video plays first then images fill the remainder.
1109
- if video_dur > 0 and narr_dur < video_dur:
1110
- # Video is longer than narration → video plays first at full length,
1111
- # then images fill any remaining narration time (usually minimal).
1112
- use_video = video_dur
1113
- total_dur = max(use_video, narr_dur)
1114
- img_dur = total_dur - use_video
1115
- else:
1116
- use_video = max(0.0, min(video_dur, total_dur))
1117
- img_dur = total_dur - use_video
1118
- imgs = img_paths or []
1119
- # image durations: split remaining time across available images (min 1.2s,
1120
- # repeat cyclically if the voice is longer than all images)
1121
- img_plan = []
1122
- if img_dur > 0.5 and imgs:
1123
- per = max(1.2, min(8.0, img_dur / len(imgs)))
1124
- remaining = img_dur
1125
- i = 0
1126
- while remaining > 0.3:
1127
- img_plan.append((imgs[i % len(imgs)], min(per, remaining)))
1128
- remaining -= per
1129
- i += 1
1130
-
1131
- # ---------- 3. build ffmpeg command ----------
1132
- cmd = ["ffmpeg", "-y"]
1133
- # video input first (index 0)
1134
- cmd += ["-i", video_path]
1135
- # image loop inputs
1136
- for idx, (_, dur) in enumerate(img_plan):
1137
- cmd += ["-framerate", "25", "-loop", "1", "-t", str(max(0.4, dur)), "-i", img_plan[idx][0]]
1138
- # narration + optional video audio inputs
1139
- audio_inputs = []
1140
- narr_idx = None
1141
- va_idx = None
1142
- if narr:
1143
- narr_idx = 1 + len(img_plan)
1144
- cmd += ["-i", narr]
1145
- audio_inputs.append(narr_idx)
1146
- if video_audio_path and os.path.exists(video_audio_path):
1147
- va_idx = 1 + len(img_plan) + (1 if narr_idx is not None else 0)
1148
- cmd += ["-i", video_audio_path]
1149
- audio_inputs.append(va_idx)
1150
-
1151
- # filter graph
1152
- fc = []
1153
- # video inputs: [0:v] = scraped video, [k:v] = images
1154
- vlabels = []
1155
- # video: trim to use_video, scale/crop to 1080x1920 portrait, normalize fps
1156
- fc.append(
1157
- f"[0:v]trim=duration={use_video:.3f},setpts=PTS-STARTPTS,"
1158
- f"scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,"
1159
- f"fps=25,format=yuv420p[v0]"
1160
- )
1161
- vlabels.append("[v0]")
1162
- for idx, (_, dur) in enumerate(img_plan):
1163
- lab = f"v{idx + 1}"
1164
- fc.append(
1165
- f"[{1 + idx}:v]trim=duration={dur:.3f},setpts=PTS-STARTPTS,"
1166
- f"scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,"
1167
- f"fps=25,format=yuv420p[{lab}]"
1168
- )
1169
- vlabels.append(f"[{lab}]")
1170
- if len(vlabels) > 1:
1171
- concat_in = "".join(vlabels)
1172
- fc.append(f"{concat_in}concat=n={len(vlabels)}:v=1:a=0[vout]")
1173
- vmap = "[vout]"
1174
- else:
1175
- vmap = "[v0]"
1176
-
1177
- # audio graph
1178
- if audio_inputs:
1179
- amix_sources = []
1180
- if narr_idx is not None:
1181
- fc.append(f"[{narr_idx}:a]aresample=44100,atrim=duration={total_dur:.3f},asetpts=PTS-STARTPTS[n]")
1182
- amix_sources.append("[n]")
1183
- if va_idx is not None:
1184
- fc.append(f"[{va_idx}:a]aresample=44100,volume=0.85,atrim=duration={use_video:.3f},asetpts=PTS-STARTPTS[xva]")
1185
- amix_sources.append("[xva]")
1186
- fc.append(f"{''.join(amix_sources)}amix=inputs={len(amix_sources)}:duration=first:dropout_transition=0:normalize=0[aout]")
1187
- amap = "[aout]"
1188
- else:
1189
- amap = None
1190
-
1191
- fc_str = ";".join(fc)
1192
- cmd += ["-filter_complex", fc_str]
1193
- cmd += ["-map", vmap]
1194
- if amap:
1195
- cmd += ["-map", amap, "-c:a", "aac", "-b:a", "160k"]
1196
- else:
1197
- cmd += ["-an"]
1198
- cmd += ["-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
1199
- "-pix_fmt", "yuv420p", "-movflags", "+faststart",
1200
- "-t", f"{total_dur:.3f}", "-shortest", out_mp4]
1201
- subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=600)
1202
- return out_mp4, total_dur
1203
-
1204
-
1205
- def _segments_from_post(post, max_segments=25):
1206
- raw = _clean(post.get("text") or post.get("title") or "")
1207
- raw = re.sub(r"^Bản tin AI viết lại:\s*", "", raw, flags=re.I)
1208
- raw = re.sub(r"Nguồn tham khảo:.*$", "", raw, flags=re.I | re.S).strip()
1209
- lines = []
1210
- for ln in raw.splitlines():
1211
- ln = _clean(re.sub(r"^[•\-\*\d\.\)\s]+", "", ln))
1212
- if not ln:
1213
- continue
1214
- low = ln.lower()
1215
- if low.startswith(("điểm chính", "tiêu đề", "sapo", "nguồn tham khảo")):
1216
- continue
1217
- if len(ln) >= 18:
1218
- lines.append(ln)
1219
- if len(lines) < 3:
1220
- lines = []
1221
- for s in re.split(r"(?<=[\.\!\?])\s+", raw):
1222
- s = _clean(s)
1223
- if len(s) >= 25:
1224
- lines.append(s)
1225
- seen = set()
1226
- out = []
1227
- for u in lines[: max_segments * 3]:
1228
- nu = re.sub(r"[^\wÀ-ỹ\s]", "", u.lower())
1229
- if nu in seen:
1230
- continue
1231
- seen.add(nu)
1232
- out.append(u)
1233
- if len(out) >= max_segments:
1234
- break
1235
- return out[:max_segments] if out else [post.get("title", "Bản tin VNEWS")]
1236
-
1237
-
1238
- def _find_previous_short(post_id):
1239
- """Find the most recent short mp4 for this post (prior generation)."""
1240
- prefix = _safe_name(post_id)
1241
- best, best_mtime = None, 0
1242
- try:
1243
- for f in os.listdir(SHORTS_DIR):
1244
- # current naming: <post_id>v2_<...>.mp4
1245
- if f.startswith(prefix + "v2_") and f.endswith(".mp4"):
1246
- p = os.path.join(SHORTS_DIR, f)
1247
- mt = os.path.getmtime(p)
1248
- if mt > best_mtime:
1249
- best, best_mtime = p, mt
1250
- except Exception:
1251
- pass
1252
- # also legacy patched files: <post_id>_<voice>_..._scenes_nosub.mp4
1253
- if not best:
1254
- try:
1255
- for f in os.listdir(SHORTS_DIR):
1256
- if f.startswith(prefix + "_") and f.endswith("_scenes_nosub.mp4"):
1257
- p = os.path.join(SHORTS_DIR, f)
1258
- mt = os.path.getmtime(p)
1259
- if mt > best_mtime:
1260
- best, best_mtime = p, mt
1261
- except Exception:
1262
- pass
1263
- return best
1264
-
1265
-
1266
- # =========================================================================
1267
- # Endpoints
1268
- # =========================================================================
1269
- @app.get("/api/ai-short/music")
1270
- def api_short_music_list():
1271
- return JSONResponse({"music": MUSIC_LIST})
1272
-
1273
-
1274
- @app.get("/api/ai-short/music/stream")
1275
- def api_short_music_stream(url: str = Query(...)):
1276
- """Proxy một track nhạc nền với CORS headers để trình duyệt phát trước khi chọn."""
1277
- try:
1278
- r = requests.get(url, headers=UA_HEADERS, timeout=30,
1279
- stream=True, allow_redirects=True)
1280
- if r.status_code != 200:
1281
- return Response(status_code=502)
1282
- return Response(
1283
- content=r.content,
1284
- media_type="audio/mpeg",
1285
- headers={
1286
- "Cache-Control": "public, max-age=86400",
1287
- "Access-Control-Allow-Origin": "*",
1288
- "Accept-Ranges": "bytes",
1289
- "Content-Disposition": "inline",
1290
- },
1291
- )
1292
- except Exception:
1293
- return Response(status_code=502)
1294
-
1295
-
1296
- @app.post("/api/ai-short/upload")
1297
- async def api_short_upload(file: UploadFile = File(...)):
1298
- """Upload audio/video/image used as short background."""
1299
- try:
1300
- if not file or not hasattr(file, "filename"):
1301
- return JSONResponse({"error": "Thiếu file"}, status_code=400)
1302
- fname = file.filename or ""
1303
- ext = os.path.splitext(fname)[1].lower()
1304
- if ext not in (".mp3", ".wav", ".m4a", ".aac", ".ogg",
1305
- ".mp4", ".webm", ".mov",
1306
- ".jpg", ".jpeg", ".png", ".webp"):
1307
- return JSONResponse({"error": "Định dạng file không hỗ trợ"}, status_code=400)
1308
- content = await file.read()
1309
- if not content:
1310
- return JSONResponse({"error": "File rỗng"}, status_code=400)
1311
- if len(content) > 60 * 1024 * 1024:
1312
- return JSONResponse({"error": "File quá lớn (>60MB)"}, status_code=400)
1313
- fuid = str(uuid.uuid4())[:12]
1314
- out_name = f"su_{fuid}{ext}"
1315
- with open(os.path.join(UPLOAD_DIR, out_name), "wb") as f:
1316
- f.write(content)
1317
- kind = ("audio" if ext in (".mp3", ".wav", ".m4a", ".aac", ".ogg")
1318
- else ("video" if ext in (".mp4", ".webm", ".mov") else "image"))
1319
- return JSONResponse({"ok": True, "url": f"/api/ai-short/upload/{out_name}", "kind": kind})
1320
- except Exception as e:
1321
- return JSONResponse({"error": f"Lỗi upload: {str(e)[:150]}"}, status_code=500)
1322
-
1323
-
1324
- @app.get("/api/ai-short/upload/{fname}")
1325
- def api_short_upload_file(fname: str):
1326
- if ".." in fname or "/" in fname:
1327
- return JSONResponse({"error": "bad name"}, status_code=400)
1328
- p = os.path.join(UPLOAD_DIR, fname)
1329
- if not os.path.exists(p):
1330
- return JSONResponse({"error": "not found"}, status_code=404)
1331
- ext = os.path.splitext(fname)[1].lower()
1332
- mt = {
1333
- ".mp3": "audio/mpeg", ".wav": "audio/wav", ".m4a": "audio/mp4",
1334
- ".aac": "audio/aac", ".ogg": "audio/ogg",
1335
- ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime",
1336
- ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png",
1337
- ".webp": "image/webp",
1338
- }.get(ext, "application/octet-stream")
1339
- return FileResponse(p, media_type=mt)
1340
-
1341
-
1342
- @app.get("/api/ai-short/scrape")
1343
- def api_scrape_video(url: str = Query(...)):
1344
- """Scrap video info from any link (YouTube/TikTok/news...).
1345
-
1346
- Returns direct media URL + duration + thumbnail so the frontend can
1347
- show a preview before generating the short.
1348
- """
1349
- if not url or not re.match(r"^https?://", url):
1350
- return JSONResponse({"error": "Link không hợp lệ"}, status_code=400)
1351
- info = _scrape_video_info(url.strip())
1352
- if not info.get("ok"):
1353
- return JSONResponse({"error": info.get("error", "Không lấy được video")}, status_code=422)
1354
- # strip cache-internal key before returning to the client
1355
- info = {k: v for k, v in info.items() if k != "_t"}
1356
- return JSONResponse(info)
1357
-
1358
-
1359
- @app.get("/api/ai-short/scrape/preview")
1360
- def api_scrape_video_preview(url: str = Query(...), request: Request = None):
1361
- """Stream the scraped video (or its direct mp4) so the browser can play
1362
- it inside the short creator modal. Range-capable proxy.
1363
- """
1364
- if not url or not re.match(r"^https?://", url):
1365
- return JSONResponse({"error": "Link không hợp lệ"}, status_code=400)
1366
- req_headers = dict(UA_HEADERS)
1367
- if request and request.headers.get("range"):
1368
- req_headers["Range"] = request.headers["range"]
1369
- try:
1370
- r = requests.get(url, headers=req_headers, timeout=30, stream=True,
1371
- allow_redirects=True)
1372
- except Exception:
1373
- return JSONResponse({"error": "Không tải được video" }, status_code=502)
1374
- if r.status_code >= 400:
1375
- return JSONResponse({"error": "Lỗi nguồn video"}, status_code=502)
1376
- resp_headers = {
1377
- "Access-Control-Allow-Origin": "*",
1378
- "Accept-Ranges": "bytes",
1379
- "Content-Type": r.headers.get("Content-Type", "video/mp4"),
1380
- }
1381
- if "Content-Range" in r.headers:
1382
- resp_headers["Content-Range"] = r.headers["Content-Range"]
1383
- if "Content-Length" in r.headers:
1384
- resp_headers["Content-Length"] = r.headers["Content-Length"]
1385
- if "Cache-Control" in r.headers:
1386
- resp_headers["Cache-Control"] = r.headers["Cache-Control"]
1387
- else:
1388
- resp_headers["Cache-Control"] = "public, max-age=3600"
1389
-
1390
- def gen():
1391
- try:
1392
- yield from r.iter_content(chunk_size=256 * 1024)
1393
- finally:
1394
- r.close()
1395
-
1396
- return StreamingResponse(gen(), status_code=r.status_code, headers=resp_headers)
1397
-
1398
-
1399
- @app.get("/api/ai-short/scrape/hls")
1400
- def api_scrape_video_hls(url: str = Query(...)):
1401
- """Proxy an HLS master/media playlist and rewrite segment + key URIs to
1402
- same-origin proxy routes so the browser (hls.js) can play AES-128 HLS
1403
- from news CDNs (vnexpress/24h) without CORS errors."""
1404
- if not url or not re.match(r"^https?://", url):
1405
- return JSONResponse({"error": "Link không hợp lệ"}, status_code=400)
1406
- try:
1407
- HDRS = _resolve_media_url(url)
1408
- r = requests.get(url, headers=HDRS, timeout=25)
1409
- if r.status_code != 200:
1410
- return JSONResponse({"error": "Lỗi nguồn HLS"}, status_code=502)
1411
- text = r.text
1412
- if "#EXTM3U" not in text:
1413
- # not a playlist; pass through as binary
1414
- return Response(content=r.content,
1415
- media_type=r.headers.get("Content-Type", "video/mp4"),
1416
- headers={"Access-Control-Allow-Origin": "*"})
1417
- from urllib.parse import urljoin, quote
1418
- out_lines = []
1419
- for line in text.splitlines():
1420
- s = line.strip()
1421
- if s.startswith("#"):
1422
- # rewrite #EXT-X-KEY URI to same-origin key proxy
1423
- if "#EXT-X-KEY" in s and "URI=" in s:
1424
- m = re.search(r'URI="([^"]+)"', s)
1425
- if m:
1426
- ku = m.group(1)
1427
- if not ku.startswith("http"):
1428
- ku = urljoin(url, ku)
1429
- s2 = s.replace(m.group(0), 'URI="/api/ai-short/scrape/key?url=' + urllib_quote(ku, safe="") + '"')
1430
- out_lines.append(s2)
1431
- continue
1432
- out_lines.append(s)
1433
- elif s.startswith("http"): # absolute segment URI
1434
- out_lines.append("/api/ai-short/scrape/seg?url=" + urllib_quote(s, safe=""))
1435
- elif s: # relative segment URI
1436
- out_lines.append("/api/ai-short/scrape/seg?url=" + urllib_quote(urljoin(url, s), safe=""))
1437
- return Response(content="\n".join(out_lines).encode("utf-8"),
1438
- media_type="application/vnd.apple.mpegurl",
1439
- headers={"Access-Control-Allow-Origin": "*",
1440
- "Cache-Control": "public, max-age=300"})
1441
- except Exception:
1442
- return JSONResponse({"error": "Lỗi proxy HLS"}, status_code=502)
1443
-
1444
-
1445
- @app.get("/api/ai-short/scrape/seg")
1446
- def api_scrape_video_seg(url: str = Query(...)):
1447
- """Stream a single HLS segment (.ts) with proper referer headers."""
1448
- if not url or not re.match(r"^https?://", url):
1449
- return JSONResponse({"error": "Link không hợp lệ"}, status_code=400)
1450
- try:
1451
- HDRS = _resolve_media_url(url)
1452
- r = requests.get(url, headers=HDRS, timeout=60, stream=True)
1453
- if r.status_code != 200:
1454
- return JSONResponse({"error": "Lỗi segment"}, status_code=502)
1455
- return StreamingResponse(r.iter_content(chunk_size=256 * 1024),
1456
- media_type="video/mp2t",
1457
- headers={"Access-Control-Allow-Origin": "*",
1458
- "Cache-Control": "public, max-age=3600"})
1459
- except Exception:
1460
- return JSONResponse({"error": "Lỗi segment"}, status_code=502)
1461
-
1462
-
1463
- @app.get("/api/ai-short/scrape/key")
1464
- def api_scrape_video_key(url: str = Query(...)):
1465
- """Proxy the AES-128 key URI for HLS playlists."""
1466
- if not url or not re.match(r"^https?://", url):
1467
- return JSONResponse({"error": "Link không hợp lệ"}, status_code=400)
1468
- try:
1469
- HDRS = _resolve_media_url(url)
1470
- r = requests.get(url, headers=HDRS, timeout=20)
1471
- if r.status_code != 200:
1472
- return JSONResponse({"error": "Lỗi key"}, status_code=502)
1473
- return Response(content=r.content, media_type="application/octet-stream",
1474
- headers={"Access-Control-Allow-Origin": "*",
1475
- "Cache-Control": "public, max-age=3600"})
1476
- except Exception:
1477
- return JSONResponse({"error": "Lỗi key"}, status_code=502)
1478
-
1479
-
1480
- @app.post("/api/ai-short")
1481
- async def api_short_generate(request: Request):
1482
- """Generate a Short AI video.
1483
-
1484
- JSON body:
1485
- post_id (str) wall post id (required)
1486
- use_slides (bool) one scene per designed slide; image = designed slide
1487
- image; NO text overlays; narration = audio of previous
1488
- short if available, else TTS of slide text (audio only).
1489
- images (list[str]) custom background image URLs (replaces default)
1490
- audio_music (str) music id from MUSIC_LIST ('' -> none)
1491
- audio_url (str) custom audio URL (uploaded /api/ai-short/upload/...)
1492
- voice/emotion/speed — TTS controls
1493
- """
1494
- try:
1495
- body = await request.json()
1496
- except Exception:
1497
- body = {}
1498
- post_id = _clean(str(body.get("post_id", "")))
1499
- create_new = bool(body.get("create_new"))
1500
- posts = _load_wall_posts()
1501
- if not isinstance(posts, list):
1502
- posts = []
1503
- post = None
1504
- if create_new:
1505
- # "Thêm Short HOT" from the homepage: no source wall post. Create a
1506
- # brand-new post now; the generated video is attached to it and it is
1507
- # posted to the AI wall. Retention: if generation fails, the draft is
1508
- # removed again so no empty post stays on the wall.
1509
- import uuid as _uuid
1510
- new_id = str(_uuid.uuid4())[:12]
1511
- hot_title = _clean(str(body.get("title", "")))[:200]
1512
- hot_text = _clean(str(body.get("text", "")))[:2000]
1513
- hot_imgs = [str(x) for x in (body.get("images") or []) if str(x).strip()][:10]
1514
- post = {
1515
- "id": new_id,
1516
- "title": hot_title or "Short HOT",
1517
- "text": hot_text,
1518
- "source": "hot_short",
1519
- "kind": "hot_short",
1520
- "video": None,
1521
- "img": hot_imgs[0] if hot_imgs else None,
1522
- "images": hot_imgs,
1523
- "url": _clean(str(body.get("url", ""))),
1524
- "voice": _clean(str(body.get("voice", ""))),
1525
- "emotion": _clean(str(body.get("emotion", ""))),
1526
- "language": _clean(str(body.get("language", "vi"))),
1527
- "created": int(time.time()),
1528
- "created_str": time.strftime('%H:%M %d/%m/%Y', time.localtime()),
1529
- }
1530
- posts.insert(0, post)
1531
- post_id = new_id
1532
- else:
1533
- if not post_id:
1534
- return JSONResponse({"error": "Thiếu post_id"}, status_code=400)
1535
- post = next((p for p in posts if str(p.get("id")) == str(post_id)), None)
1536
- if not post:
1537
- return JSONResponse({"error": "Không tìm thấy bài viết"}, status_code=404)
1538
-
1539
- use_slides = bool(body.get("use_slides"))
1540
- reuse_audio = body.get("reuse_audio")
1541
- if reuse_audio is None:
1542
- # default: when recreating from slides, reuse the previous short's audio
1543
- reuse_audio = use_slides
1544
- custom_images = [str(x) for x in (body.get("images") or []) if str(x).strip()]
1545
- fixed_image = _clean(str(body.get("fixed_image", ""))) # 1 ảnh cố định cho nhiều slide
1546
- raw_indices = body.get("slide_indices") or []
1547
- slide_indices = []
1548
- for v in raw_indices:
1549
- try:
1550
- slide_indices.append(int(v))
1551
- except Exception:
1552
- pass
1553
- video_url = _clean(str(body.get("video_url", "")))
1554
- video_muted = bool(body.get("video_muted"))
1555
- # oEmbed fallback for Short HOT: passed by the frontend when the scraped
1556
- # link has metadata but the direct media download failed (e.g. TikTok/
1557
- # Facebook/Instagram which block datacenter IPs). The short is then saved
1558
- # as an embeddable slide (like the football video slides) with the
1559
- # metadata auto-filled from oEmbed.
1560
- embed_url = _clean(str(body.get("embed_url", "")))
1561
- embed_title = _clean(str(body.get("embed_title", "")))[:250]
1562
- embed_thumb = _clean(str(body.get("embed_thumb", "")))
1563
- embed_desc = _clean(str(body.get("embed_desc", "")))[:5000]
1564
- try:
1565
- video_dur = float(body.get("video_dur")) if body.get("video_dur") is not None else None
1566
- except Exception:
1567
- video_dur = None
1568
- scrape_mode = bool(body.get("scrape_mode"))
1569
- audio_music = _clean(str(body.get("audio_music", "")))
1570
- audio_url = _clean(str(body.get("audio_url", "")))
1571
- voice = _clean(str(body.get("voice", "vi-VN-HoaiMyNeural")))
1572
- emotion = _clean(str(body.get("emotion", "neutral")))
1573
- try:
1574
- speed = max(0.85, min(1.35, float(body.get("speed", 1.0) or 1.0)))
1575
- except Exception:
1576
- speed = 1.0
1577
-
1578
- os.makedirs(SHORTS_DIR, exist_ok=True)
1579
-
1580
- # ---------- scene images ----------
1581
- scene_images = []
1582
- slide_texts = []
1583
- if use_slides:
1584
- slides = post.get("slides") or []
1585
- if not slides:
1586
- return JSONResponse({"error": "Bài chưa có ảnh slide thiết kế. Hãy chọn '🎨 Thiết kế ảnh' trước."}, status_code=400)
1587
- # optional per-slide selection from the recreate modal
1588
- if slide_indices:
1589
- slides = [s for i, s in enumerate(slides) if i in slide_indices]
1590
- if not slides:
1591
- return JSONResponse({"error": "Slide đã chọn không hợp lệ."}, status_code=400)
1592
- for s in slides:
1593
- im = (s.get("image") or "").strip()
1594
- if im:
1595
- scene_images.append(im)
1596
- slide_texts.append(_clean(s.get("text", "")))
1597
- # fixed_image: 1 ảnh do người dùng chọn (trong danh sách rewrite hoặc upload)
1598
- # thay thế toàn bộ ảnh slide -> dùng ảnh này cho N slide (sau dedupe = 1 scene)
1599
- if fixed_image:
1600
- scene_images = [fixed_image]
1601
- slide_texts = [slide_texts[0] if slide_texts else ""]
1602
- # dedupe identical designed images globally: if the same image appears
1603
- # in multiple slides (e.g. only 1 slide was designed, others share the
1604
- # fallback cover), collapse to one scene so the slide isn't repeated
1605
- deduped = []
1606
- seen_imgs = set()
1607
- for im in scene_images:
1608
- if im not in seen_imgs:
1609
- seen_imgs.add(im)
1610
- deduped.append(im)
1611
- scene_images = deduped
1612
- if not scene_images:
1613
- return JSONResponse({"error": "Các slide chưa có ảnh đã thiết kế."}, status_code=400)
1614
- # align slide_texts to the deduped scenes (keep first text per image group)
1615
- if slide_texts and len(slide_texts) > len(scene_images):
1616
- grouped = []
1617
- seen = set()
1618
- for idx, s in enumerate(slides):
1619
- im = (s.get("image") or "").strip()
1620
- if not im or im in seen:
1621
- continue
1622
- seen.add(im)
1623
- grouped.append(slide_texts[idx] if idx < len(slide_texts) else "")
1624
- if grouped:
1625
- slide_texts = grouped
1626
- else:
1627
- slide_texts = slide_texts[:len(scene_images)]
1628
- else:
1629
- # fixed_image (chosen from rewrite list) replaces the bg for the short
1630
- if fixed_image:
1631
- scene_images = [fixed_image]
1632
- else:
1633
- for im in custom_images:
1634
- scene_images.append(im)
1635
- if not scene_images:
1636
- scene_images = [(x or "").strip() for x in (post.get("images") or []) if (x or "").strip()]
1637
- if not scene_images:
1638
- slides = post.get("slides") or []
1639
- for s in slides:
1640
- im = (s.get("image") or "").strip()
1641
- if im:
1642
- scene_images.append(im)
1643
- if not scene_images and post.get("img"):
1644
- scene_images = [post.get("img")]
1645
- # video-only (scraped/uploaded) short: video is the background, so
1646
- # images are OPTIONAL. Let the video-first assembler handle it.
1647
- if not scene_images and not video_url:
1648
- # Short HOT oEmbed fallback: no direct media AND no background
1649
- # image -> still create the embeddable slide with the oEmbed
1650
- # thumbnail as the visual (if any), so the wall/feed can show it.
1651
- if embed_url:
1652
- pass
1653
- else:
1654
- # AUTO oEmbed FALLBACK: the frontend couldn't get a video
1655
- # (or even embed metadata) from the link — derive the
1656
- # embed iframe URL from the source link itself (cheap, no
1657
- # network) and enrich with oEmbed metadata if available.
1658
- src_url = _clean(str(body.get("url", "")) or post.get("url") or "")
1659
- if src_url and (_is_known_social(src_url) or body.get("allow_oembed_fallback")):
1660
- embed_url = _oembed_embed_url(src_url)
1661
- _probe3 = _oembed_probe(src_url)
1662
- if _probe3:
1663
- embed_url = _probe3.get("embed_url") or embed_url
1664
- embed_title = _probe3.get("title") or embed_title
1665
- embed_thumb = _probe3.get("thumbnail") or embed_thumb
1666
- embed_desc = _probe3.get("description") or embed_desc
1667
- if not embed_url:
1668
- return JSONResponse({"error": "Bài viết không có ảnh nền"}, status_code=400)
1669
- segs0 = _segments_from_post(post)
1670
- if len(scene_images) > len(segs0):
1671
- scene_images = scene_images[:max(1, len(segs0))]
1672
-
1673
- # ---------- Short HOT oEmbed shortcut ----------
1674
- # When the source link is oEmbed-only (TikTok/FB/IG block datacenter IPs,
1675
- # or the scrape returned no direct media URL), save the post as an
1676
- # embeddable slide right away with the auto-fetched title/desc/thumb.
1677
- if not video_url and embed_url:
1678
- # Don't trust the client for metadata: when the post has a source URL
1679
- # and we still lack a thumbnail/title at save time (e.g. an older page
1680
- # cached in the browser didn't send embed_thumb), probe oEmbed NOW so
1681
- # the wall post always gets its thumbnail + title.
1682
- _src_url = _clean(str(body.get("url", "")) or post.get("url") or "")
1683
- if (not embed_thumb or not embed_title) and _src_url:
1684
- _probe_save = _oembed_probe(_src_url)
1685
- if _probe_save:
1686
- embed_title = embed_title or _probe_save.get("title") or ""
1687
- embed_thumb = embed_thumb or _probe_save.get("thumbnail") or ""
1688
- embed_desc = embed_desc or _probe_save.get("description") or ""
1689
- post["video"] = embed_url
1690
- post["embed_oembed"] = True
1691
- post["title"] = embed_title or post.get("title") or "Short HOT"
1692
- post["text"] = embed_desc or post.get("text") or embed_title or ""
1693
- post["description"] = embed_desc or ""
1694
- if embed_thumb:
1695
- post["img"] = embed_thumb
1696
- post["images"] = [embed_thumb] + [x for x in (post.get("images") or []) if x != embed_thumb]
1697
- post["short_thumb"] = embed_thumb
1698
- else:
1699
- post["short_thumb"] = post.get("img")
1700
- post["extractor"] = "oembed"
1701
- _save_wall_posts(posts)
1702
- return JSONResponse({"video": embed_url, "oembed": True, "post": post})
1703
-
1704
- # ---------- naming / cache ----------
1705
- scene_key = "slides" if use_slides else "norm"
1706
- sel_key = ("s" + "".join(str(i) for i in slide_indices)) if slide_indices else ""
1707
- vid_key = hashlib.md5(video_url.encode("utf-8")).hexdigest()[:8] if video_url else ""
1708
- img_key = hashlib.md5("|".join(scene_images).encode("utf-8")).hexdigest()[:8]
1709
- mus_key = audio_music or "nomus"
1710
- aud_key = hashlib.md5(audio_url.encode("utf-8")).hexdigest()[:8] if audio_url else "none"
1711
- suffix = f"v2_{scene_key}_{'v'+vid_key if vid_key else ''}{sel_key}{img_key}_{mus_key}_{aud_key}_{voice}_{emotion}_{str(speed).replace('.', 'p')}"
1712
- out_mp4 = os.path.join(SHORTS_DIR, _safe_name(post_id + suffix) + ".mp4")
1713
- out_url = "/api/ai/short-file/" + post_id + suffix
1714
-
1715
- if os.path.exists(out_mp4):
1716
- post["video"] = out_url
1717
- post["short_voice"] = voice
1718
- post["short_emotion"] = emotion
1719
- post["short_speed"] = speed
1720
- post["short_music"] = audio_music
1721
- post["short_audio_url"] = audio_url
1722
- post["short_use_slides"] = use_slides
1723
- post["short_images"] = scene_images
1724
- _save_wall_posts(posts)
1725
- return JSONResponse({"video": out_url, "voice": voice, "emotion": emotion,
1726
- "speed": speed, "music": audio_music, "use_slides": use_slides,
1727
- "post": post})
1728
-
1729
- work = os.path.join(SHORTS_DIR, _safe_name(post_id + suffix))
1730
- os.makedirs(work, exist_ok=True)
1731
-
1732
- # ---------- download scene images ----------
1733
- local_imgs = []
1734
- for i, im_url in enumerate(scene_images):
1735
- dst = os.path.join(work, f"scene_{i:02d}.jpg")
1736
- data = _fetch_bytes(im_url)
1737
- if data:
1738
- with open(dst, "wb") as f:
1739
- f.write(data)
1740
- local_imgs.append(dst)
1741
- if not local_imgs:
1742
- img = Image.new("RGB", (1080, 1920), (24, 24, 24))
1743
- img.save(os.path.join(work, "scene_00.jpg"), quality=90)
1744
- local_imgs = [os.path.join(work, "scene_00.jpg")]
1745
-
1746
- # ---------- uploaded/scraped video background ----------
1747
- video_audio_path = None
1748
- using_video_first = False # video plays as-is (video-first assembly), images fill tail
1749
- if video_url:
1750
- vid_local = os.path.join(work, "bg_video.mp4")
1751
- dl_ok = _download_to_file(video_url, vid_local)
1752
- if not dl_ok:
1753
- # ---- Short HOT oEmbed fallback: can't download the media -> save
1754
- # the post as an embeddable slide with auto title/desc/thumb from
1755
- # the scrape metadata. The feed renders it as an iframe slide,
1756
- # exactly like the football video slides on YouTube.
1757
- fb_embed = embed_url or _oembed_embed_url(_clean(str(body.get("url", "")) or post.get("url") or ""))
1758
- fb_title = embed_title or post.get("title") or ""
1759
- fb_thumb = embed_thumb or post.get("img") or ""
1760
- fb_desc = embed_desc or ""
1761
- if not fb_title or not fb_thumb or not fb_desc:
1762
- _probe2 = _oembed_probe(_clean(str(body.get("url", "")) or post.get("url") or ""))
1763
- if _probe2:
1764
- fb_embed = fb_embed or _probe2.get("embed_url") or ""
1765
- fb_title = fb_title or _probe2.get("title") or ""
1766
- fb_thumb = fb_thumb or _probe2.get("thumbnail") or ""
1767
- fb_desc = fb_desc or (_probe2.get("description") or "")
1768
- if fb_embed:
1769
- post["video"] = fb_embed
1770
- post["embed_oembed"] = True
1771
- post["title"] = fb_title or post.get("title") or "Short HOT"
1772
- post["text"] = fb_desc or post.get("text") or fb_title or ""
1773
- post["description"] = fb_desc or ""
1774
- if fb_thumb:
1775
- post["img"] = fb_thumb
1776
- post["images"] = [fb_thumb] + [x for x in (post.get("images") or []) if x != fb_thumb]
1777
- post["short_thumb"] = fb_thumb
1778
- else:
1779
- post["short_thumb"] = post.get("img")
1780
- post["short_video_url"] = video_url
1781
- post["extractor"] = "oembed"
1782
- _save_wall_posts(posts)
1783
- return JSONResponse({"video": fb_embed, "oembed": True, "post": post})
1784
- return JSONResponse({"error": "Không tải được video từ link. Link đã hết hạn hoặc nguồn chặn."}, status_code=422)
1785
- try:
1786
- vdur = _probe_duration(vid_local, fallback=6.0)
1787
- except Exception:
1788
- vdur = 6.0
1789
- if video_dur and video_dur > 0:
1790
- vdur = float(video_dur)
1791
- # extract video's own audio (used as narration track)
1792
- vaudio = os.path.join(work, "vaudio.m4a")
1793
- subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", vid_local, "-vn",
1794
- "-c:a", "aac", "-b:a", "128k", vaudio],
1795
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180)
1796
- if os.path.exists(vaudio) and os.path.getsize(vaudio) > 900:
1797
- video_audio_path = vaudio
1798
-
1799
- # --- NEW: video-first mode (scraped video or muted uploaded video)
1800
- # Video plays first; designed/selected images fill the rest if the
1801
- # video is shorter than the voice. No per-frame mosaic.
1802
- using_video_first = scrape_mode or video_muted
1803
- if not using_video_first:
1804
- # legacy uploaded-video mode: extract up to N frames as the
1805
- # moving-background scenes
1806
- n_frames = max(1, min(5, len(local_imgs) if len(local_imgs) >= 1 else 5))
1807
- frame_imgs = []
1808
- for i in range(n_frames):
1809
- t = vdur * (i + 0.5) / n_frames
1810
- fimg = os.path.join(work, f"vc_{i:02d}.jpg")
1811
- subprocess.run(["ffmpeg", "-y", "-v", "error", "-ss", str(t), "-i", vid_local,
1812
- "-frames:v", "1", "-q:v", "3", fimg],
1813
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
1814
- if os.path.exists(fimg) and os.path.getsize(fimg) > 1200:
1815
- frame_imgs.append(fimg)
1816
- if frame_imgs:
1817
- local_imgs = frame_imgs
1818
-
1819
- # ---------- narration plan ----------
1820
- reuse_audio_path = None
1821
- if reuse_audio:
1822
- prev = _find_previous_short(post_id)
1823
- if prev:
1824
- try:
1825
- prev_audio = os.path.join(work, "prev_audio.m4a")
1826
- subprocess.run(["ffmpeg", "-y", "-i", prev, "-vn", "-acodec", "aac", "-b:a", "128k", prev_audio],
1827
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180)
1828
- if os.path.exists(prev_audio) and os.path.getsize(prev_audio) > 900:
1829
- reuse_audio_path = prev_audio
1830
- except Exception:
1831
- reuse_audio_path = None
1832
- if video_audio_path and not reuse_audio_path and not video_muted and not using_video_first:
1833
- # uploaded/scraped video has its own audio -> use it instead of TTS
1834
- # (only in legacy mosaic mode; video-first mode keeps video audio as a
1835
- # background layer mixed with the TTS narration)
1836
- reuse_audio_path = video_audio_path
1837
- segs = slide_texts if (use_slides and slide_texts) else _segments_from_post(post)
1838
- while len(segs) < len(local_imgs):
1839
- segs.append(segs[-1] if segs else post.get("title", "Bản tin VNEWS"))
1840
-
1841
- # ---------- NEW: video-first short assembly ----------
1842
- if using_video_first:
1843
- # images for the tail: designed slides first, then post images
1844
- tail_imgs = list(local_imgs) if (local_imgs and not (use_slides and fixed_image)) else local_imgs
1845
- # if user chose a fixed image -> only that image for the tail
1846
- if fixed_image:
1847
- fimg = os.path.join(work, "fixed_tail.jpg")
1848
- data = _fetch_bytes(fixed_image)
1849
- if data:
1850
- with open(fimg, "wb") as f:
1851
- f.write(data)
1852
- tail_imgs = [fimg] if os.path.getsize(fimg) > 1200 else (tail_imgs or [])
1853
- # ensure at least the post image exists as tail
1854
- if not tail_imgs:
1855
- fallback_img = os.path.join(work, "scene_00.jpg")
1856
- if os.path.exists(fallback_img):
1857
- tail_imgs = [fallback_img]
1858
- # TTS segments: for video-first, use per-slide texts if slides,
1859
- # else the whole article as segments (each read out)
1860
- tts_segs = slide_texts if (use_slides and slide_texts) else _segments_from_post(post)
1861
- if not tts_segs:
1862
- tts_segs = [post.get("title", "Bản tin VNEWS")]
1863
- try:
1864
- out_mp4, _total = _assemble_video_short(
1865
- work, vid_local, vdur,
1866
- tail_imgs, tts_segs,
1867
- reuse_audio_path,
1868
- (video_audio_path if not video_muted else None),
1869
- voice, speed,
1870
- None, out_mp4, post.get("title", ""),
1871
- )
1872
- # music overlay handled by the shared block below
1873
- music_url = ""
1874
- if audio_url:
1875
- music_url = audio_url
1876
- elif audio_music and audio_music in MUSIC_BY_ID:
1877
- music_url = MUSIC_BY_ID[audio_music].get("url", "")
1878
- if music_url:
1879
- music_path = os.path.join(work, "music.mp3")
1880
- data = _fetch_bytes(music_url)
1881
- if data:
1882
- with open(music_path, "wb") as f:
1883
- f.write(data)
1884
- if os.path.exists(music_path) and os.path.getsize(music_path) > 900:
1885
- muxed = os.path.join(work, "muxed.mp4")
1886
- vid_dur2 = _probe_duration(out_mp4, fallback=30.0)
1887
- if _probe_has_audio(out_mp4):
1888
- fc = (
1889
- f"[1:a]volume=0.5,aloop=loop=-1:size=2e9,atrim=duration={vid_dur2}[m];"
1890
- f"[0:a][m]amix=inputs=2:duration=first:dropout_transition=0:normalize=0[aout]"
1891
- )
1892
- cmd = ["ffmpeg", "-y", "-i", out_mp4, "-i", music_path,
1893
- "-filter_complex", fc, "-map", "0:v", "-map", "[aout]",
1894
- "-c:v", "copy", "-c:a", "aac", "-b:a", "160k", "-shortest", muxed]
1895
- else:
1896
- fc = f"[1:a]volume=0.55,aloop=loop=-1:size=2e9,atrim=duration={vid_dur2}[a]"
1897
- cmd = ["ffmpeg", "-y", "-i", out_mp4, "-i", music_path,
1898
- "-filter_complex", fc, "-map", "0:v", "-map", "[a]",
1899
- "-c:v", "copy", "-c:a", "aac", "-b:a", "160k", "-shortest", muxed]
1900
- subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=240)
1901
- os.replace(muxed, out_mp4)
1902
- post["video"] = out_url
1903
- post["short_thumb"] = _first_frame(out_mp4, os.path.join(WALL_IMG_DIR, _safe_name(post_id + suffix + "_thumb") + ".jpg"))
1904
- post["short_voice"] = voice
1905
- post["short_emotion"] = emotion
1906
- post["short_speed"] = speed
1907
- post["short_music"] = audio_music
1908
- post["short_audio_url"] = audio_url
1909
- post["short_use_slides"] = use_slides
1910
- post["short_images"] = scene_images
1911
- post["short_video_url"] = video_url
1912
- post["short_video_muted"] = video_muted
1913
- _save_wall_posts(posts)
1914
- return JSONResponse({"video": out_url, "voice": voice, "emotion": emotion,
1915
- "speed": speed, "music": audio_music, "use_slides": use_slides,
1916
- "post": post})
1917
- except Exception as e:
1918
- if create_new:
1919
- _load_wall_posts() # ensure fresh list
1920
- posts2 = [p for p in _load_wall_posts() if str(p.get("id")) != str(post_id)]
1921
- _save_wall_posts(posts2)
1922
- return JSONResponse({"error": "Không tạo được shorts: " + str(e)[:220]}, status_code=500)
1923
-
1924
- # ---------- frame rendering ----------
1925
- frames = []
1926
- for idx in range(len(local_imgs)):
1927
- frame = os.path.join(work, f"frame_{idx:02d}.jpg")
1928
- with open(local_imgs[idx], "rb") as f:
1929
- data = f.read()
1930
- if use_slides:
1931
- _frame_from_image(data, frame, seg_idx=idx, seg_total=len(local_imgs))
1932
- else:
1933
- _frame_with_text(data, frame, segs[idx], post.get("title", ""), seg_idx=idx, seg_total=len(local_imgs))
1934
- frames.append(frame)
1935
-
1936
- part_files = []
1937
- try:
1938
- if reuse_audio_path:
1939
- # ---------- reuse previous short audio ----------
1940
- total_dur = _probe_duration(reuse_audio_path, fallback=30.0)
1941
- per = max(2.2, min(8.0, total_dur / max(1, len(frames))))
1942
- for idx, frame in enumerate(frames):
1943
- part = os.path.join(work, f"part_{idx:02d}.mp4")
1944
- subprocess.run(
1945
- ["ffmpeg", "-y", "-loop", "1", "-t", str(per), "-i", frame,
1946
- "-c:v", "libx264", "-tune", "stillimage", "-pix_fmt", "yuv420p", "-an", part],
1947
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=150)
1948
- part_files.append(part)
1949
- concat = os.path.join(work, "concat.txt")
1950
- with open(concat, "w", encoding="utf-8") as f:
1951
- for p in part_files:
1952
- f.write("file '" + p.replace("'", "'\\''") + "'\n")
1953
- subprocess.run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", concat, "-c", "copy", out_mp4],
1954
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=240)
1955
- # mux previous audio (trim to video length)
1956
- vid_dur = _probe_duration(out_mp4, fallback=total_dur)
1957
- with_audio = os.path.join(work, "with_audio.mp4")
1958
- subprocess.run(
1959
- ["ffmpeg", "-y", "-i", out_mp4, "-i", reuse_audio_path,
1960
- "-filter_complex", f"[1:a]atrim=duration={vid_dur}[a]",
1961
- "-map", "0:v", "-map", "[a]", "-c:v", "copy", "-c:a", "aac",
1962
- "-b:a", "128k", "-shortest", with_audio],
1963
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=240)
1964
- os.replace(with_audio, out_mp4)
1965
- else:
1966
- # ---------- fresh TTS narration ----------
1967
- edge_voice = {
1968
- "vi-vn-hoaimyneural": "vi-VN-HoaiMyNeural", "vi-vn-namminhneural": "vi-VN-NamMinhNeural",
1969
- "hoaimy": "vi-VN-HoaiMyNeural", "namminh": "vi-VN-NamMinhNeural", "nam": "vi-VN-NamMinhNeural",
1970
- "male": "vi-VN-NamMinhNeural", "nu": "vi-VN-HoaiMyNeural", "female": "vi-VN-HoaiMyNeural",
1971
- "mien-nam": "vi-VN-HoaiMyNeural",
1972
- "en-us-andrewmultilingualneural": "en-US-AndrewMultilingualNeural",
1973
- "en-au-williammultilingualneural": "en-AU-WilliamMultilingualNeural",
1974
- "andrew": "en-US-AndrewMultilingualNeural", "en_andrew": "en-US-AndrewMultilingualNeural",
1975
- "jenny": "en-US-AndrewMultilingualNeural", "en_jenny": "en-US-AndrewMultilingualNeural",
1976
- "pt-br-thalitamultilingualneural": "pt-BR-ThalitaMultilingualNeural",
1977
- "thalita": "pt-BR-ThalitaMultilingualNeural", "pt": "pt-BR-ThalitaMultilingualNeural",
1978
- "fr-fr-viviennemultilingualneural": "fr-FR-VivienneMultilingualNeural",
1979
- "fr-fr-remymultilingualneural": "fr-FR-RemyMultilingualNeural",
1980
- "denise": "fr-FR-VivienneMultilingualNeural", "fr": "fr-FR-VivienneMultilingualNeural",
1981
- "de-de-seraphinamultilingualneural": "de-DE-SeraphinaMultilingualNeural",
1982
- "de-de-florianmultilingualneural": "de-DE-FlorianMultilingualNeural",
1983
- "katja": "de-DE-SeraphinaMultilingualNeural", "de": "de-DE-SeraphinaMultilingualNeural",
1984
- "ko-kr-hyusumultilingualneural": "ko-KR-HyunsuMultilingualNeural",
1985
- "ko-kr-hyunsuneural": "ko-KR-HyunsuMultilingualNeural", "sunhee": "ko-KR-HyunsuMultilingualNeural",
1986
- "ko": "ko-KR-HyunsuMultilingualNeural",
1987
- "it-it-giuseppemultilingualneural": "it-IT-GiuseppeMultilingualNeural",
1988
- "ela": "en-US-AndrewMultilingualNeural", "es": "en-US-AndrewMultilingualNeural",
1989
- }.get(voice.lower(), voice)
1990
- for idx, frame in enumerate(frames):
1991
- aud = os.path.join(work, f"voice_{idx:02d}.mp3")
1992
- aud_fast = os.path.join(work, f"voice_{idx:02d}_fast.mp3")
1993
- part = os.path.join(work, f"part_{idx:02d}.mp4")
1994
- spoken = segs[idx] if idx < len(segs) else post.get("title", "Bản tin VNEWS")
1995
- try:
1996
- subprocess.run(
1997
- ["python", "-m", "edge_tts", "--voice", edge_voice, "--text", spoken,
1998
- "--write-media", aud],
1999
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
2000
- except Exception:
2001
- aud = None
2002
- try:
2003
- from gtts import gTTS
2004
- tld = "com.vn" if voice.lower() in ("nu", "female", "mien-nam", "hoaimy") else "com"
2005
- try:
2006
- gTTS(spoken, lang="vi", tld=tld, slow=False).save(aud)
2007
- except TypeError:
2008
- gTTS(spoken, lang="vi", slow=False).save(aud)
2009
- except Exception:
2010
- pass
2011
- if aud and os.path.exists(aud) and os.path.getsize(aud) > 900:
2012
- subprocess.run(["ffmpeg", "-y", "-i", aud, "-filter:a", f"atempo={speed}", "-vn", aud_fast],
2013
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=90)
2014
- dur = _probe_duration(aud_fast, fallback=15.0) + 0.35
2015
- subprocess.run(
2016
- ["ffmpeg", "-y", "-loop", "1", "-t", str(dur), "-i", frame, "-i", aud_fast,
2017
- "-shortest", "-c:v", "libx264", "-tune", "stillimage", "-pix_fmt", "yuv420p",
2018
- "-c:a", "aac", "-b:a", "128k", part],
2019
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=150)
2020
- else:
2021
- subprocess.run(
2022
- ["ffmpeg", "-y", "-loop", "1", "-t", "4", "-i", frame,
2023
- "-c:v", "libx264", "-tune", "stillimage", "-pix_fmt", "yuv420p", "-an", part],
2024
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
2025
- part_files.append(part)
2026
- concat = os.path.join(work, "concat.txt")
2027
- with open(concat, "w", encoding="utf-8") as f:
2028
- for p in part_files:
2029
- f.write("file '" + p.replace("'", "'\\''") + "'\n")
2030
- subprocess.run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", concat, "-c", "copy", out_mp4],
2031
- check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=240)
2032
-
2033
- # ---------- background music overlay ----------
2034
- music_url = ""
2035
- if audio_url:
2036
- music_url = audio_url
2037
- elif audio_music and audio_music in MUSIC_BY_ID:
2038
- music_url = MUSIC_BY_ID[audio_music].get("url", "")
2039
- if music_url:
2040
- music_path = os.path.join(work, "music.mp3")
2041
- data = _fetch_bytes(music_url)
2042
- if data:
2043
- with open(music_path, "wb") as f:
2044
- f.write(data)
2045
- if os.path.exists(music_path) and os.path.getsize(music_path) > 900:
2046
- muxed = os.path.join(work, "muxed.mp4")
2047
- vid_dur = _probe_duration(out_mp4, fallback=30.0)
2048
- if _probe_has_audio(out_mp4):
2049
- # narration at full volume + music at 0.5, no amix downscale (normalize=0)
2050
- fc = (
2051
- f"[1:a]volume=0.5,aloop=loop=-1:size=2e9,atrim=duration={vid_dur}[m];"
2052
- f"[0:a][m]amix=inputs=2:duration=first:dropout_transition=0:normalize=0[aout]"
2053
- )
2054
- cmd = ["ffmpeg", "-y", "-i", out_mp4, "-i", music_path,
2055
- "-filter_complex", fc, "-map", "0:v", "-map", "[aout]",
2056
- "-c:v", "copy", "-c:a", "aac", "-b:a", "160k", "-shortest", muxed]
2057
- else:
2058
- fc = f"[1:a]volume=0.55,aloop=loop=-1:size=2e9,atrim=duration={vid_dur}[a]"
2059
- cmd = ["ffmpeg", "-y", "-i", out_mp4, "-i", music_path,
2060
- "-filter_complex", fc, "-map", "0:v", "-map", "[a]",
2061
- "-c:v", "copy", "-c:a", "aac", "-b:a", "160k", "-shortest", muxed]
2062
- subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=240)
2063
- os.replace(muxed, out_mp4)
2064
-
2065
- except Exception as e:
2066
- if create_new:
2067
- posts2 = [p for p in _load_wall_posts() if str(p.get("id")) != str(post_id)]
2068
- _save_wall_posts(posts2)
2069
- return JSONResponse({"error": "Không tạo được shorts: " + str(e)[:220]}, status_code=500)
2070
-
2071
- post["video"] = out_url
2072
- post["short_thumb"] = _first_frame(out_mp4, os.path.join(WALL_IMG_DIR, _safe_name(post_id + suffix + "_thumb") + ".jpg"))
2073
- post["short_voice"] = voice
2074
- post["short_emotion"] = emotion
2075
- post["short_speed"] = speed
2076
- post["short_music"] = audio_music
2077
- post["short_audio_url"] = audio_url
2078
- post["short_use_slides"] = use_slides
2079
- post["short_images"] = scene_images
2080
-
2081
- return JSONResponse({"video": out_url, "voice": voice, "emotion": emotion,
2082
- "speed": speed, "music": audio_music, "use_slides": use_slides,
2083
- "post": post})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app_v2.js DELETED
The diff for this file is too large to render. See raw diff
 
app_v2_entry.py CHANGED
The diff for this file is too large to render. See raw diff
 
app_v2_entry.py.gitigignore DELETED
@@ -1,3 +0,0 @@
1
- .pyc
2
- __pycache__/
3
- *.pyc
 
 
 
 
app_v2_entry_hot.py DELETED
@@ -1,24 +0,0 @@
1
- """Hot topics patch - makes AI topics always visible at top of HOT list."""
2
- # This file is imported by app_v2_entry.py
3
-
4
- # AI topics to prepend to hot topics
5
- AI_HOT_TOPICS = [
6
- {'label': '#Công nghệ AI', 'topic': 'Công nghệ AI', 'count': 0},
7
- {'label': '#World Cup 2026', 'topic': 'World Cup 2026', 'count': 0},
8
- {'label': '#Kinh tế Việt Nam', 'topic': 'Kinh tế Việt Nam', 'count': 0},
9
- {'label': '#Bóng đá châu Âu', 'topic': 'Bóng đá châu Âu', 'count': 0},
10
- {'label': '#Giá vàng', 'topic': 'Giá vàng', 'count': 0},
11
- {'label': '#Thời tiết', 'topic': 'Thời tiết', 'count': 0},
12
- ]
13
-
14
- def prepend_ai_hot_topics(topics):
15
- """Prepend AI topics to hot topics list, ensuring they're always visible."""
16
- if not topics:
17
- return AI_HOT_TOPICS[:]
18
- # Remove duplicates that already exist
19
- existing_topics = [t.get('topic', '').lower() for t in topics]
20
- result = []
21
- for ai_topic in AI_HOT_TOPICS:
22
- if ai_topic.get('topic', '').lower() not in existing_topics:
23
- result.append(ai_topic)
24
- return result + topics
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app_v2_patch.py DELETED
@@ -1,111 +0,0 @@
1
- """VNEWS v2 Patch - auto scheduler + status endpoints + keep-alive.
2
- This is imported by app_v2_entry.py to add auto posting functionality.
3
- FIX v2: Catch-up scheduler + keep-alive to prevent Space sleep
4
- """
5
- import sys, os, threading, json, time, logging
6
- from datetime import datetime, timezone, timedelta
7
- from fastapi import Request
8
- from fastapi.responses import JSONResponse
9
- import requests as _req
10
-
11
- VN_TZ = timezone(timedelta(hours=7))
12
- LOG = logging.getLogger("app_v2_patch")
13
- LOG.setLevel(logging.INFO)
14
- if not LOG.handlers:
15
- ch = logging.StreamHandler()
16
- ch.setFormatter(logging.Formatter('%(asctime)s [app_v2_patch] %(levelname)s: %(message)s'))
17
- LOG.addHandler(ch)
18
-
19
- # ===== Keep-alive: prevent Space from sleeping =====
20
- # HF Spaces sleep after ~30 min of inactivity on free tier
21
- # This thread pings the Space every 10 minutes to keep it alive
22
- SPACE_URL = "https://bep40-vnews.hf.space"
23
-
24
- def _keep_alive_loop():
25
- """Ping the Space every 10 minutes to prevent sleep."""
26
- LOG.info(f"🔄 Keep-alive thread started - ping {SPACE_URL} every 10 min")
27
- while True:
28
- try:
29
- time.sleep(600) # 10 minutes
30
- _req.get(f"{SPACE_URL}/api/scheduler/status",
31
- headers={"User-Agent": "VNEWS-KeepAlive/1.0"},
32
- timeout=15)
33
- LOG.debug("Keep-alive ping OK")
34
- except Exception as e:
35
- LOG.warning(f"Keep-alive ping failed (Space may be sleeping): {e}")
36
-
37
- # Start keep-alive in background
38
- try:
39
- _ka_thread = threading.Thread(target=_keep_alive_loop, daemon=True, name="keep-alive")
40
- _ka_thread.start()
41
- LOG.info("🔄 Keep-alive started - Space will stay awake")
42
- except Exception as e:
43
- LOG.warning(f"Keep-alive start failed: {e}")
44
-
45
- # ===== Start auto scheduler =====
46
- try:
47
- import auto_scheduler as _as
48
- _as.start_auto_scheduler()
49
- LOG.info("[auto_scheduler] Started successfully - will post at 7:00, 13:00, 19:00 VN time (with catch-up)")
50
- except Exception as e:
51
- LOG.error(f"[auto_scheduler] Start failed: {e}")
52
-
53
- def register_scheduler_endpoints(app):
54
- """Register scheduler status/trigger endpoints on the FastAPI app."""
55
-
56
- @app.get('/api/scheduler/status')
57
- def scheduler_status():
58
- running = any(t.name == 'auto-scheduler' and t.is_alive() for t in threading.enumerate())
59
- keep_alive = any(t.name == 'keep-alive' and t.is_alive() for t in threading.enumerate())
60
-
61
- # Load state to show which slots ran today
62
- today_str = datetime.now(VN_TZ).strftime('%Y-%m-%d')
63
- state = {}
64
- try:
65
- state_file = '/data/scheduler_state.json' if os.path.isdir('/data') else None
66
- if state_file and os.path.exists(state_file):
67
- state = json.load(open(state_file, 'r'))
68
- except:
69
- pass
70
-
71
- ran_today = state.get(today_str, {}) if state else {}
72
-
73
- return JSONResponse({
74
- "running": running,
75
- "keep_alive": keep_alive,
76
- "schedule": "7:00, 13:00, 19:00 VN time",
77
- "today": today_str,
78
- "slots_ran_today": ran_today,
79
- "catch_up_enabled": True,
80
- "next_run": "7:00, 13:00, or 19:00 VN time (whichever is next)"
81
- })
82
-
83
- @app.post('/api/scheduler/trigger')
84
- async def scheduler_trigger():
85
- try:
86
- import auto_scheduler as _as2
87
- _as2._run_scheduled_posting()
88
- return JSONResponse({"ok": True, "message": "Scheduled posting triggered manually"})
89
- except Exception as e:
90
- return JSONResponse({"ok": False, "error": str(e)}, status_code=500)
91
-
92
- @app.get('/api/scheduler/force')
93
- def scheduler_force():
94
- """Force-run all missed slots immediately. Useful after deploy."""
95
- try:
96
- import auto_scheduler as _as2
97
- _as2._check_missed_slots()
98
- return JSONResponse({"ok": True, "message": "Missed slots check triggered"})
99
- except Exception as e:
100
- return JSONResponse({"ok": False, "error": str(e)}, status_code=500)
101
-
102
- return app
103
-
104
-
105
- # Auto-register on the main app from app_v2_entry
106
- try:
107
- from main import app
108
- register_scheduler_endpoints(app)
109
- LOG.info("[app_v2_patch] Scheduler endpoints registered: /api/scheduler/status, /api/scheduler/trigger, /api/scheduler/force")
110
- except Exception as e:
111
- LOG.error(f"[app_v2_patch] Could not register endpoints: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
auto_scheduler.py DELETED
@@ -1,396 +0,0 @@
1
- """VNEWS Auto Scheduler - tự động đăng 3 bài rewrite AI + shorts từ 3 chủ đề HOT
2
- Vào các khung giờ: 7:00, 13:00, 19:00 (giờ Việt Nam)
3
- Mỗi bài: Rewrite AI từ nguồn báo + short video tự động
4
- FIX v7: Giữ nguyên tiêu đề gốc từng bài viết + thêm "Tin tóm tắt VNEWS 7h sáng/13h trưa/19h tối" ở đầu text
5
- """
6
- import os, re, json, time, threading, asyncio, logging, random, hashlib, html as html_lib
7
- from datetime import datetime, timezone, timedelta, date
8
- from urllib.parse import quote
9
- import requests
10
- from bs4 import BeautifulSoup
11
-
12
- # Import storage for persistent data
13
- from storage import load_wall_posts, save_wall_posts, DATA_DIR
14
-
15
- VN_TZ = timezone(timedelta(hours=7))
16
- LOG = logging.getLogger("auto_scheduler")
17
- LOG.setLevel(logging.INFO)
18
- if not LOG.handlers:
19
- ch = logging.StreamHandler()
20
- ch.setFormatter(logging.Formatter('%(asctime)s [%(name)s] %(levelname)s: %(message)s'))
21
- LOG.addHandler(ch)
22
-
23
- SCHEDULE_TIMES = [(7, 0), (13, 0), (19, 0)]
24
- SCHEDULE_LABELS = {t: f"{t[0]:02d}:{t[1]:02d}" for t in SCHEDULE_TIMES}
25
-
26
- os.makedirs(DATA_DIR, exist_ok=True)
27
- SCHEDULE_STATE_FILE = os.path.join(DATA_DIR, 'scheduler_state.json')
28
-
29
- def _load_state():
30
- try:
31
- if os.path.exists(SCHEDULE_STATE_FILE):
32
- with open(SCHEDULE_STATE_FILE, 'r') as f: return json.load(f)
33
- except: pass
34
- return {}
35
-
36
- def _save_state(state):
37
- try:
38
- tmp = SCHEDULE_STATE_FILE + '.tmp'
39
- with open(tmp, 'w') as f: json.dump(state, f, ensure_ascii=False)
40
- os.replace(tmp, SCHEDULE_STATE_FILE)
41
- except Exception as e: LOG.warning(f"Cannot save state: {e}")
42
-
43
- _STOP = set('và của các những một được trong với cho tại sau trước khi không người vietnam hôm nay mới nhất nóng tin tức cập nhật theo từ đến là có thì này đã để'.split())
44
-
45
- def _clean(s):
46
- s = html_lib.unescape(s or "")
47
- # FIX: Remove malformed HTML artifacts (truncated tags without closing >)
48
- s = s.replace('<a href=" src="', '').replace("<a href=' src='", '')
49
- s = s.replace('<a href=" src=', '').replace("<a href=' src=", '')
50
- s = re.sub(r'<[^>]+>', '', s) # Remove all HTML tags
51
- return re.sub(r"\s+", " ", s).strip()
52
-
53
- def _get_hot_topics():
54
- freq = {}; display = {}
55
- feeds = [
56
- 'https://vnexpress.net/rss/tin-moi-nhat.rss',
57
- 'https://dantri.com.vn/rss/home.rss',
58
- 'https://vietnamnet.vn/rss/tin-moi-nhat.rss',
59
- 'https://thanhnien.vn/rss/home.rss',
60
- 'https://tuoitre.vn/rss/tin-moi-nhat.rss',
61
- 'https://genk.vn/rss',
62
- 'https://vnexpress.net/rss/the-thao.rss',
63
- 'https://thethaovanhoa.vn/rss/tin-nong.rss',
64
- 'https://vnexpress.net/rss/kinh-doanh.rss',
65
- 'https://dantri.com.vn/rss/the-gioi.rss',
66
- ]
67
- for feed_url in feeds:
68
- try:
69
- r = requests.get(feed_url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=6)
70
- r.encoding = 'utf-8'
71
- soup = BeautifulSoup(r.text, 'xml')
72
- for item in soup.find_all('item')[:12]:
73
- title = _clean(item.find('title').get_text() if item.find('title') else '')
74
- if not title: continue
75
- title = re.sub(r'\s*[-|].*$', '', title)
76
- words = [w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+', title) if len(w) > 2 and w.lower() not in _STOP]
77
- if len(words) < 2: continue
78
- for n in (3, 4, 2):
79
- for i in range(max(0, len(words) - n + 1)):
80
- phrase = ' '.join(words[i:i + n])
81
- if 8 <= len(phrase) <= 45:
82
- key = phrase.lower()
83
- freq[key] = freq.get(key, 0) + 1
84
- display[key] = phrase
85
- except: continue
86
- ranked = sorted(freq.items(), key=lambda x: x[1], reverse=True)
87
- topics = []; seen = set()
88
- for key, count in ranked:
89
- kw = display[key]
90
- is_dup = any(len(set(e.split()) & set(key.split())) / max(len(set(e.split())), len(set(key.split())), 1) > 0.6 for e in seen)
91
- if is_dup: continue
92
- seen.add(key)
93
- topics.append({'label': '#' + re.sub(r'\s+', '', kw.title()), 'topic': kw, 'count': count})
94
- if len(topics) >= 20: break
95
- for kw in ['World Cup 2026', 'Kinh tế Việt Nam', 'Bóng đá châu Âu', 'Công nghệ AI', 'Giá vàng', 'Thời tiết']:
96
- if len(topics) >= 24: break
97
- if not any(kw.lower() in s for s in seen):
98
- topics.append({'label': '#' + re.sub(r'\s+', '', kw.title()), 'topic': kw, 'count': 0})
99
- return topics[:24]
100
-
101
- _ai_ext = None; _ai_patch = None
102
- def _get_ai_ext():
103
- global _ai_ext
104
- if _ai_ext is None: import ai_ext as m; _ai_ext = m
105
- return _ai_ext
106
- def _get_ai_patch():
107
- global _ai_patch
108
- if _ai_patch is None: import ai_patch as m; _ai_patch = m
109
- return _ai_patch
110
-
111
- _RSS_FEEDS = [
112
- ('https://vnexpress.net/rss/tin-moi-nhat.rss', 'VnExpress'),
113
- ('https://dantri.com.vn/rss/home.rss', 'Dân Trí'),
114
- ('https://vietnamnet.vn/rss/tin-moi-nhat.rss', 'VietNamNet'),
115
- ('https://thanhnien.vn/rss/home.rss', 'Thanh Niên'),
116
- ('https://tuoitre.vn/rss/tin-moi-nhat.rss', 'Tuổi Trẻ'),
117
- ('https://genk.vn/rss', 'GenK'),
118
- ('https://vnexpress.net/rss/the-thao.rss', 'VnExpress'),
119
- ('https://thethaovanhoa.vn/rss/tin-nong.rss', 'TT&VH'),
120
- ('https://vnexpress.net/rss/kinh-doanh.rss', 'VnExpress'),
121
- ('https://dantri.com.vn/rss/the-gioi.rss', 'Dân Trí'),
122
- ]
123
-
124
- def _search_articles_by_topic(topic, limit=4):
125
- all_articles = []; seen_urls = set()
126
- topic_lower = topic.lower()
127
- topic_words = set(re.findall(r'[A-Za-zÀ-ỹ0-9]+', topic_lower))
128
- for feed_url, source in _RSS_FEEDS:
129
- try:
130
- r = requests.get(feed_url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=6)
131
- r.encoding = 'utf-8'
132
- soup = BeautifulSoup(r.text, 'xml')
133
- for item in soup.find_all('item')[:8]:
134
- title = _clean(item.find('title').get_text() if item.find('title') else '')
135
- link = _clean(item.find('link').get_text() if item.find('link') else '')
136
- desc = _clean(item.find('description').get_text() if item.find('description') else '')
137
- if not title or not link or link in seen_urls: continue
138
- seen_urls.add(link)
139
- title_words = set(re.findall(r'[A-Za-zÀ-ỹ0-9]+', title.lower()))
140
- overlap = len(topic_words & title_words) if topic_words else 0
141
- exact_match = topic_lower in title.lower() or topic_lower in desc.lower()
142
- if exact_match or overlap >= 2:
143
- img = ''
144
- encl = item.find('enclosure')
145
- if encl: img = encl.get('url', '')
146
- if not img:
147
- try:
148
- art_r = requests.get(link, headers={'User-Agent': 'Mozilla/5.0'}, timeout=4)
149
- art_r.encoding = 'utf-8'
150
- art_soup = BeautifulSoup(art_r.text, 'lxml')
151
- ogi = art_soup.find('meta', property='og:image')
152
- if ogi: img = ogi.get('content', '')
153
- except: pass
154
- all_articles.append({'title': title, 'url': link, 'raw': desc or title, 'image': img, 'via': source, 'source': {'title': title, 'url': link, 'excerpt': (desc or title)[:700], 'via': source}})
155
- if len(all_articles) >= limit: break
156
- except: continue
157
- return all_articles[:limit]
158
-
159
- async def _create_ai_post(topic):
160
- ai_ext = _get_ai_ext(); ai_patch = _get_ai_patch()
161
- articles = _search_articles_by_topic(topic, limit=4)
162
- if not articles:
163
- LOG.warning(f"No articles for topic: {topic}. Fallback.")
164
- return await _create_fallback_post(topic, ai_ext, ai_patch)
165
- posts = []
166
- # Get schedule time label for text intro (7h sáng, 13h trưa, 19h tối)
167
- now = datetime.now(VN_TZ)
168
- hour = now.hour
169
- time_label = "7h sáng" if hour == 7 else ("13h trưa" if hour == 13 else "19h tối")
170
- text_intro = f"Tin tóm tắt VNEWS {time_label}"
171
- wall = ai_ext._load_ai_wall()
172
- if not isinstance(wall, list): wall = []
173
- for art in articles:
174
- try:
175
- prompt = ai_patch._make_summary_prompt(art.get('title', topic), art.get('raw', ''), art.get('via', ''))
176
- text = await ai_ext.qwen_generate(prompt, image_url=art.get('image'), max_tokens=1500)
177
- text = ai_patch._postprocess_ai_text(text, max_units=20)
178
- src = [art.get('source', {'title': art.get('title', topic), 'url': art.get('url', ''), 'via': art.get('via', '')})]
179
- # Prepend time label intro to text (giữ nguyên title là tiêu đề gốc của bài báo)
180
- if text and not text.startswith(text_intro):
181
- text = f"{text_intro}\n\n{text}"
182
- if 'Nguồn tham khảo:' not in (text or ''):
183
- text = (text or '') + "\n\n" + ai_patch._source_line(src)
184
- img = art.get('image') or ai_ext.pollination_image_url(art.get('title', topic))
185
- # Dùng art.get('title') GIỮ NGUYÊN tiêu đề gốc từ bài báo
186
- post = ai_ext.make_post(art.get('title', topic), text, img, art.get('url', ''), 'auto_scheduled', sources=src)
187
- try:
188
- page_data = ai_patch._scrape_article_images(art.get('url', ''))
189
- if page_data and page_data.get('paragraphs'):
190
- kp = ai_patch._extract_key_points_for_slides(page_data['paragraphs'], max_points=8)
191
- if kp:
192
- imgs = page_data.get('images', [])
193
- if not imgs and page_data.get('og_img'): imgs = [page_data['og_img']]
194
- slides = []
195
- for i, pt in enumerate(kp):
196
- slides.append({'text': pt, 'image': imgs[i] if i < len(imgs) else (imgs[-1] if imgs else ''), 'index': i + 1})
197
- post['slides'] = slides
198
- except: pass
199
- posts.append(post)
200
- except Exception as e:
201
- LOG.error(f"Error post: {e}")
202
- if not posts: return await _create_fallback_post(topic, ai_ext, ai_patch)
203
- wall = posts + wall
204
- ai_ext._save_ai_wall(wall)
205
- for post in posts:
206
- try: _try_generate_short(post)
207
- except: pass
208
- return posts
209
-
210
- async def _create_fallback_post(topic, ai_ext, ai_patch):
211
- LOG.info(f"Fallback: {topic}")
212
- try:
213
- # Still add time label to fallback posts
214
- now = datetime.now(VN_TZ)
215
- hour = now.hour
216
- time_label = "7h sáng" if hour == 7 else ("13h trưa" if hour == 13 else "19h tối")
217
- text_intro = f"Tin tóm tắt VNEWS {time_label}"
218
- text = f"{text_intro}\n\n• {topic} đang là chủ đề nóng hôm nay.\n• Theo dõi VNEWS để cập nhật tin tức mới nhất."
219
- img = ai_ext.pollination_image_url(topic)
220
- post = ai_ext.make_post(topic, text, img, '', 'auto_scheduled', sources=[])
221
- wall = ai_ext._load_ai_wall()
222
- if not isinstance(wall, list): wall = []
223
- wall = [post] + wall
224
- ai_ext._save_ai_wall(wall)
225
- LOG.info(f"Fallback saved: {topic}")
226
- return [post]
227
- except Exception as e:
228
- LOG.error(f"Fallback failed: {e}")
229
- return []
230
-
231
- def _try_generate_short(post):
232
- post_id = post.get('id', '')
233
- if not post_id: return
234
- try:
235
- ai_ext = _get_ai_ext(); ai_patch = _get_ai_patch()
236
- if ai_ext.gTTS is None: return
237
- segments = ai_patch._summary_segments_from_post(post, max_segments=15)
238
- if not segments: return
239
- seg_hash = hashlib.md5(('|'.join(segments) + 'nu' + 'neutral' + '1.0').encode('utf-8')).hexdigest()[:8]
240
- suffix = f"_nu_neutral_1p0_{seg_hash}_scenes_nosub"
241
- out_mp4 = os.path.join(ai_ext.SHORTS_DIR, ai_ext._safe_name(post_id + suffix) + '.mp4')
242
- if os.path.exists(out_mp4):
243
- post['video'] = '/api/ai/short-file/' + post_id + suffix
244
- wall = ai_ext._load_ai_wall()
245
- for i, p in enumerate(wall):
246
- if p.get('id') == post_id: wall[i] = post; break
247
- ai_ext._save_ai_wall(wall); return
248
- threading.Thread(target=lambda: _generate_short_worker(post, segments, post_id, suffix, out_mp4), daemon=True).start()
249
- except Exception as e: LOG.warning(f"Short init: {e}")
250
-
251
- def _generate_short_worker(post, segments, post_id, suffix, out_mp4):
252
- import subprocess
253
- try:
254
- ai_ext = _get_ai_ext(); ai_patch = _get_ai_patch()
255
- work = os.path.join(ai_ext.SHORTS_DIR, ai_ext._safe_name(post_id + suffix))
256
- os.makedirs(work, exist_ok=True)
257
- img = os.path.join(work, 'image.jpg')
258
- ai_ext._download_image(post.get('img'), post.get('title', 'AI news'), img)
259
- part_files = []
260
- for idx, seg in enumerate(segments[:10]):
261
- frame = os.path.join(work, f'frame_{idx:02d}.jpg')
262
- aud = os.path.join(work, f'voice_{idx:02d}.mp3')
263
- aud_fast = os.path.join(work, f'voice_{idx:02d}_fast.mp3')
264
- part = os.path.join(work, f'part_{idx:02d}.mp4')
265
- try: ai_patch._make_scene_frame(post, seg, idx, min(len(segments), 10), img, frame, emotion='neutral')
266
- except:
267
- if not os.path.exists(img): continue
268
- from PIL import Image
269
- Image.new('RGB', (1080, 1920), (14, 14, 14)).save(frame, quality=85)
270
- tts_text = re.sub(r'^[•\-\*\d\.\)\s]+', '', seg).strip()
271
- try: ai_ext.gTTS(tts_text, lang='vi', slow=False).save(aud)
272
- except:
273
- try: ai_ext.gTTS(tts_text, lang='vi', tld='com.vn', slow=False).save(aud)
274
- except: continue
275
- subprocess.run(['ffmpeg', '-y', '-i', aud, '-filter:a', 'atempo=1.0', '-vn', aud_fast], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=90)
276
- dur = 12.0
277
- try:
278
- pr = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:no_key=1', aud_fast], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20)
279
- dur = max(8.0, float((pr.stdout or b'').decode().strip() or 12.0)) + 0.5
280
- except: pass
281
- subprocess.run(['ffmpeg', '-y', '-loop', '1', '-t', str(dur), '-i', frame, '-i', aud_fast, '-shortest', '-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '128k', part], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=150)
282
- part_files.append(part)
283
- if part_files:
284
- concat = os.path.join(work, 'concat.txt')
285
- with open(concat, 'w', encoding='utf-8') as f:
286
- for p in part_files: f.write("file '" + p.replace("'", "'\\''") + "'\n")
287
- subprocess.run(['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat, '-c', 'copy', out_mp4], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180)
288
- post['video'] = '/api/ai/short-file/' + post_id + suffix
289
- post['short_voice'] = 'nu'; post['short_emotion'] = 'neutral'; post['short_speed'] = 1.0
290
- post['short_segments'] = segments; post['short_subtitles'] = False
291
- wall = ai_ext._load_ai_wall()
292
- for i, p in enumerate(wall):
293
- if p.get('id') == post_id: wall[i] = post; break
294
- ai_ext._save_ai_wall(wall)
295
- LOG.info(f"Short: {post_id}")
296
- except Exception as e: LOG.warning(f"Short fail: {e}")
297
-
298
- def _run_async(coro):
299
- """Run async coroutine safely regardless of current event loop state."""
300
- try:
301
- loop = asyncio.get_running_loop()
302
- except RuntimeError:
303
- return asyncio.run(coro)
304
- import concurrent.futures
305
- with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
306
- return pool.submit(asyncio.run, coro).result(timeout=300)
307
-
308
- def _run_scheduled_posting():
309
- LOG.info("=" * 50)
310
- LOG.info("Scheduler triggered at %s", datetime.now(VN_TZ).strftime('%H:%M %d/%m/%Y'))
311
- LOG.info("=" * 50)
312
- try:
313
- hot_topics = _get_hot_topics()
314
- if not hot_topics:
315
- LOG.warning("No hot topics"); return
316
- selected = []; seen_labels = set()
317
- for t in hot_topics:
318
- label = t.get('label', '')
319
- if label and label not in seen_labels:
320
- seen_labels.add(label); selected.append(t['topic'])
321
- if len(selected) >= 3: break
322
- if len(selected) < 3:
323
- selected = ['Thời sự Việt Nam', 'Kinh tế Việt Nam', 'Thể thao']
324
- LOG.info(f"Topics: {selected}")
325
- async def _do_all():
326
- results = []
327
- for topic in selected:
328
- try:
329
- posts = await _create_ai_post(topic)
330
- results.append({'topic': topic, 'posts': len(posts) if posts else 0})
331
- LOG.info(f"{'✓' if posts else '✗'} {topic}: {len(posts) if posts else 0} posts")
332
- except Exception as e:
333
- LOG.error(f"Error {topic}: {e}")
334
- results.append({'topic': topic, 'posts': 0})
335
- return results
336
- results = _run_async(_do_all())
337
- LOG.info(f"Done: {len(results)} topics")
338
- for r in results: LOG.info(f" • {r['topic']}: {r['posts']} bài")
339
- except Exception as e:
340
- LOG.error(f"Scheduler error: {e}", exc_info=True)
341
-
342
- def _check_missed_slots():
343
- try:
344
- state = _load_state()
345
- today_str = datetime.now(VN_TZ).strftime('%Y-%m-%d')
346
- now = datetime.now(VN_TZ); cur_mins = now.hour * 60 + now.minute
347
- ran = state.get(today_str, {})
348
- for s in SCHEDULE_TIMES:
349
- lbl = SCHEDULE_LABELS[s]; sm = s[0] * 60 + s[1]
350
- if ran.get(lbl): continue
351
- if cur_mins >= sm:
352
- LOG.info(f"Catch-up: {lbl}")
353
- _run_scheduled_posting()
354
- if today_str not in state: state[today_str] = {}
355
- state[today_str][lbl] = True; _save_state(state)
356
- except Exception as e: LOG.error(f"Catch-up: {e}")
357
-
358
- def _scheduler_loop():
359
- LOG.info("Scheduler started")
360
- LOG.info(f"Schedule: {', '.join(f'{h:02d}:{m:02d}' for h,m in SCHEDULE_TIMES)} VN")
361
- state = _load_state(); today_str = datetime.now(VN_TZ).strftime('%Y-%m-%d')
362
- ran = state.get(today_str, {})
363
- now = datetime.now(VN_TZ); cur_mins = now.hour * 60 + now.minute
364
- for s in SCHEDULE_TIMES:
365
- lbl = SCHEDULE_LABELS[s]; sm = s[0] * 60 + s[1]
366
- if ran.get(lbl): LOG.info(f" ✓ {lbl} done"); continue
367
- if cur_mins >= sm:
368
- LOG.info(f" → {lbl} missed! Catch-up")
369
- _run_scheduled_posting()
370
- if today_str not in state: state[today_str] = {}
371
- state[today_str][lbl] = True; _save_state(state)
372
- else: LOG.info(f" ⏩ {lbl} upcoming")
373
- while True:
374
- try:
375
- now = datetime.now(VN_TZ)
376
- ck = (now.hour, now.minute)
377
- state = _load_state(); today_str = now.strftime('%Y-%m-%d')
378
- ran = state.get(today_str, {})
379
- for s in SCHEDULE_TIMES:
380
- lbl = SCHEDULE_LABELS[s]
381
- if ck == s and not ran.get(lbl):
382
- LOG.info(f"On-time: {lbl}")
383
- _run_scheduled_posting()
384
- if today_str not in state: state[today_str] = {}
385
- state[today_str][lbl] = True; _save_state(state)
386
- break
387
- time.sleep(60)
388
- except Exception as e:
389
- LOG.error(f"Loop: {e}")
390
- time.sleep(60)
391
-
392
- def start_auto_scheduler():
393
- t = threading.Thread(target=_scheduler_loop, daemon=True, name="auto-scheduler")
394
- t.start()
395
- LOG.info("Auto scheduler started")
396
- return t
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
auto_update_sse.py DELETED
@@ -1,55 +0,0 @@
1
- """Auto-update SSE endpoint for VNEWS - pushes updates when new posts/shorts published."""
2
- import asyncio
3
- import json
4
- import time
5
- from fastapi import Request
6
- from fastapi.responses import StreamingResponse
7
-
8
- # Connected clients queue
9
- _clients = []
10
- _lock = asyncio.Lock()
11
-
12
- async def _notify_clients(event_type: str, data: dict):
13
- """Send notification to all SSE clients."""
14
- if not _clients:
15
- return
16
- msg = f"data: {json.dumps({'type': event_type, 'data': data, 'ts': int(time.time())})}\n\n"
17
- async with _lock:
18
- dead = []
19
- for q in _clients:
20
- try:
21
- await q.put_nowait(msg)
22
- except asyncio.QueueFull:
23
- pass
24
- except:
25
- dead.append(q)
26
- for q in dead:
27
- if q in _clients:
28
- _clients.remove(q)
29
-
30
- # Public functions to call from other modules
31
- notify_new_post = lambda post: asyncio.create_task(_notify_clients("new_post", post)) if post else None
32
- notify_new_short = lambda post: asyncio.create_task(_notify_clients("new_short", post)) if post else None
33
-
34
- async def sse_events(request: Request):
35
- """SSE endpoint for real-time updates on homepage."""
36
- q = asyncio.Queue(maxsize=10)
37
- _clients.append(q)
38
-
39
- async def event_generator():
40
- try:
41
- # Send initial connection message
42
- yield "data: {\"type\":\"connected\",\"ts\":null}\n\n"
43
- while not await request.is_disconnected():
44
- try:
45
- msg = await asyncio.wait_for(q.get(), timeout=25.0)
46
- yield msg
47
- except asyncio.TimeoutError:
48
- yield ":keepalive\n\n"
49
- except:
50
- pass
51
- finally:
52
- if q in _clients:
53
- _clients.remove(q)
54
-
55
- return StreamingResponse(event_generator(), media_type="text/event-stream")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdp_full.html DELETED
@@ -1,1250 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <title>Hull City vs MU: Quỷ Đỏ vào hang bắt hổ - Bongdaplus.vn</title>
5
-
6
-
7
- <meta name="MobileOptimized" content="100" />
8
- <meta name="viewport" content="width=device-width, initial-scale=1" />
9
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
10
- <meta http-equiv="content-language" content="vi" />
11
- <meta http-equiv="refresh" content="300" />
12
- <meta property="fb:pages" content="1738672379699789" />
13
- <meta property="dable:item_id" content="2015111202028" />
14
- <meta property="og:image" itemprop="thumbnailUrl" content="https://bongdaplus.vn/img/logo-daily.png" />
15
- <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
16
- <link href="/favicon.svg" rel="icon" sizes="any" type="image/svg+xml" />
17
- <link href="/apple-touch-icon.png" rel="apple-touch-icon" />
18
- <!--iPhone icons-->
19
- <link href="/logo-57.png" rel="apple-touch-icon-precomposed" sizes="57x57" />
20
- <link href="/logo-114.png" rel="apple-touch-icon-precomposed" sizes="114x114" />
21
- <!--iPad icons-->
22
- <link href="/logo-72.png" rel="apple-touch-icon-precomposed" sizes="72x72" />
23
- <link href="/logo-114.png" rel="apple-touch-icon-precomposed" sizes="114x114" />
24
- <!--Android icon-->
25
- <link href="/logo-114.png" rel="apple-touch-icon-precomposed" sizes="1x1" />
26
- <!--Symbian icon-->
27
- <link href="/logo-57.png" rel="nokia-touch-icon" sizes="57x57" />
28
- <link rel="preconnect" href="https://fonts.googleapis.com">
29
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
30
- <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700;1,800&display=swap" rel="stylesheet">
31
- <link href="https://fonts.googleapis.com/css2?family=Noto+Serif:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
32
- <link href="/css/premium.css?id=0000&amp;v=ivL0rSTnUIBx45p3hw7UIAzbXjyQ9rgPVSyjqPglN_o" rel="stylesheet">
33
-
34
- <script async src="https://www.googletagmanager.com/gtag/js?id=UA-20374657-1"></script>
35
- <script>
36
- window.dataLayer = window.dataLayer || [];
37
- function gtag() { dataLayer.push(arguments); }
38
- gtag('js', new Date());
39
-
40
- gtag('config', 'UA-20374657-1');
41
- </script>
42
- <!-- Google tag (gtag.js) -->
43
- <script async src="https://www.googletagmanager.com/gtag/js?id=G-Y1DBNQWMVW"></script>
44
- <script>
45
- window.dataLayer = window.dataLayer || [];
46
- function gtag() { dataLayer.push(arguments); }
47
- gtag('js', new Date());
48
-
49
- gtag('config', 'G-Y1DBNQWMVW');
50
- </script>
51
-
52
- <script async src="https://static.amcdn.vn/tka/cdn.js" type="text/javascript"></script>
53
- <script>var arfAsync = arfAsync || [];</script>
54
- <script id="arf-core-js" onerror="window.arferrorload=true;" src="//media1.admicro.vn/cms/Arf.min.js" async></script>
55
- <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3619133031508264" crossorigin="anonymous"></script>
56
- </head>
57
- <body>
58
- <script type="application/ld+json">
59
- {
60
- "@context": "https://schema.org",
61
- "@type": "Organization",
62
- "name": "TẠP CHÍ ĐIỆN TỬ BÓNG ĐÁ - BONGDAPLUS",
63
- "url": "https://bongdaplus.vn",
64
- "logo": "https://bongdaplus.vn/img/logo.png",
65
- "contactPoint": {
66
- "@type": "ContactPoint",
67
- "telephone": "(84.24)35541188",
68
- "contactType": "customer service",
69
- "areaServed": "VN",
70
- "availableLanguage": "Vietnamese"
71
- },
72
- "sameAs": [
73
- "https://www.facebook.com/baobongda",
74
- "https://www.youtube.com/channel/UCvDYMBE6GipX2VGacqOU2_Q",
75
- "https://bongdaplus.vn",
76
- "https://www.pinterest.com/bongdaplus",
77
- "https://soundcloud.com/baobongda"
78
- ]
79
- }
80
- </script>
81
- <header>
82
- <center><div id="ADMTOP" class="banner admob" banner-adpos="top"></div></center>
83
-
84
- <div class="cont-wrap">
85
- <div class="mmnu-nav">
86
- <button class="ico mnu-sch mmnu-trigger hide-w"></button>
87
- <button class="ico menubar mmnu-trigger hide-m"></button>
88
- <button class="ico close mmnu-closer hide"></button>
89
- </div>
90
- <a class="logo" href="/"></a>
91
- <button class="ico bell hide-w hide"></button>
92
-
93
- <div class="authen-nav dropper">
94
- <a class="member">
95
- <span class="avatar">
96
- </span>
97
- </a>
98
- <div class="drop-down rgt">
99
- <ul class="lst">
100
-
101
- <li><a href="#" data-showpaner="#loginview">Đăng nhập</a></li>
102
- <li><a href="https://member.bongdaplus.vn/Identity/Account/Register?returnUrl=%2F" target="_blank">Tạo tài khoản</a></li>
103
-
104
-
105
- </ul>
106
- </div>
107
- </div>
108
- </div>
109
- </header>
110
- <input type="hidden" id="catrefid" value="video" />
111
- <input type="hidden" id="objectid" value="98267" />
112
- <input type="hidden" id="objecttype" value="1" />
113
- <input type="hidden" id="parentid" value="0" />
114
- <input type="hidden" id="commentnum" value="0" />
115
- <img src="/imgthumbnail/98267/1/1" alt="" height="0" width="0" />
116
-
117
- <main>
118
- <div class="nav-menu">
119
- <div class="menu-bar">
120
- <div class="cont-wrap">
121
- <div class="menu-side">
122
- <ul class="bar-w">
123
- <li><a class="ico home" href="/"></a></li>
124
- <li><a title="AFF Cup" href="/aff-cup">AFF Cup</a></li>
125
- <li class="popover">
126
- <a title="Việt Nam" href="/bong-da-viet-nam">Việt Nam</a>
127
- <div class="drop-down">
128
- <ul class="lst">
129
- <li><a title="V-League" href="/v-league">V-League</a></li>
130
- <li><a title="Hạng Nhất" href="/hang-nhat-quoc-gia">Hạng Nhất</a></li>
131
- <li><a title="Cúp Quốc gia" href="/cup-quoc-gia">Cúp Quốc gia</a></li>
132
- <li><a title="ĐTQG" href="/doi-tuyen-quoc-gia-viet-nam">ĐTQG</a></li>
133
- <li><a title="Bóng đá Nữ" href="/bong-da-nu-viet-nam">Bóng đá Nữ</a></li>
134
- <li><a title="U17 Quốc gia" href="/u17-viet-nam">U17 Quốc gia</a></li>
135
- <li><a title="U19 Quốc Gia" href="/u19-viet-nam">U19 Quốc Gia</a></li>
136
- <li><a title="U21 Quốc Gia" href="/u21-viet-nam">U21 Quốc Gia</a></li>
137
- <li><a title="Các đội tuyển trẻ" href="/cac-doi-tuyen-tre-viet-nam">Các đội tuyển trẻ</a></li>
138
- <li><a title="Futsal" href="/futsal">Futsal</a></li>
139
- <li><a title="Phong trào" href="/bong-da-phong-trao">Phong trào</a></li>
140
- <li><a title="Đơn vị Kết nghĩa" href="/ket-nghia-anh-em">Đơn vị Kết nghĩa</a></li>
141
- </ul>
142
- </div>
143
- </li>
144
- <li class="popover">
145
- <a title="Chuyển nhượng" href="/tin-chuyen-nhuong">Chuyển nhượng</a>
146
- <div class="drop-down">
147
- <ul class="lst">
148
- <li><a title="Tin chuyển nhượng Ngoại Hạng Anh" href="/tin-chuyen-nhuong-ngoai-hang-anh">Tin chuyển nhượng Ngoại Hạng Anh</a></li>
149
- <li><a title="Tin chuyển nhượng V-league" href="/tin-chuyen-nhuong-v-league">Tin chuyển nhượng V-league</a></li>
150
- </ul>
151
- </div>
152
- </li>
153
- <li><a title="Champions League" href="/champions-league-cup-c1">Champions League</a></li>
154
- <li class="popover">
155
- <a title="Tây Ban Nha" href="/bong-da-tay-ban-nha">Tây Ban Nha</a>
156
- <div class="drop-down">
157
- <ul class="lst">
158
- <li><a title="VĐQG Tây Ban Nha" href="/la-liga">VĐQG Tây Ban Nha</a></li>
159
- <li><a title="Cúp Nhà Vua" href="/cup-nha-vua-tay-ban-nha">Cúp Nhà Vua</a></li>
160
- <li><a title="Đội tuyển TBN" href="/doi-tuyen-tay-ban-nha">Đội tuyển TBN</a></li>
161
- </ul>
162
- </div>
163
- </li>
164
- <li class="popover">
165
- <a title="Pháp" href="/bong-da-phap">Pháp</a>
166
- <div class="drop-down">
167
- <ul class="lst">
168
- <li><a title="VĐQG Pháp" href="/ligue-1">VĐQG Pháp</a></li>
169
- <li><a title="Cúp Quốc gia Pháp" href="/cup-quoc-gia-phap">Cúp Quốc gia Pháp</a></li>
170
- <li><a title="Đội tuyển Pháp" href="/doi-tuyen-phap">Đội tuyển Pháp</a></li>
171
- </ul>
172
- </div>
173
- </li>
174
- <li class="popover">
175
- <a title="Italia" href="/bong-da-y">Italia</a>
176
- <div class="drop-down">
177
- <ul class="lst">
178
- <li><a title="VĐQG Italia" href="/serie-a">VĐQG Italia</a></li>
179
- <li><a title="Coppa Italia" href="/coppa-italia">Coppa Italia</a></li>
180
- <li><a title="Đội tuyển Italia" href="/doi-tuyen-y">Đội tuyển Italia</a></li>
181
- </ul>
182
- </div>
183
- </li>
184
- <li class="popover">
185
- <a title="Thể thao" href="/the-thao">Thể thao</a>
186
- <div class="drop-down">
187
- <ul class="lst">
188
- <li><a title="eSports" href="/esports">eSports</a></li>
189
- <li><a title="Tennis" href="/tennis">Tennis</a></li>
190
- <li><a title="Pickleball" href="/pickleball">Pickleball</a></li>
191
- <li><a title="MMA" href="/mma">MMA</a></li>
192
- <li><a title="Đua xe F1" href="/dua-xe-f1">Đua xe F1</a></li>
193
- <li><a title="Bóng rổ" href="/bong-ro">Bóng rổ</a></li>
194
- <li><a title="Olympic 2028" href="/olympic">Olympic 2028</a></li>
195
- </ul>
196
- </div>
197
- </li>
198
- <li><a title="Nhận định bóng đá" href="/nhan-dinh-bong-da-tags">Nhận định</a></li>
199
- <li><a title="Multimedia" href="/video">Multimedia</a></li>
200
- <li class="hide"><a title="Bongdaplus Premium" href="/premium">Premium <i class="ico crown"></i></a></li>
201
- </ul>
202
- </div>
203
- <div class="menu-nav">
204
- <a class="ico home hide-w" href="/"></a>
205
- <ul class="nav">
206
- <li class="hide-m"><i class="sepr"></i></li>
207
- <li><a href="/tin-moi">Mới nhất</a></li>
208
- <li class="hide-w"><a title="Bongdaplus Premium" href="/premium">Premium <i class="ico crown"></i></a></li>
209
- <li><a title="Anh" href="/bong-da-anh">Bóng đá Anh</a></li>
210
- <li class="hide-w"><a title="AFF Cup" href="/aff-cup">AFF Cup</a></li>
211
- <li class="hide-w"><a title="Việt Nam" href="/bong-da-viet-nam">Việt Nam</a></li>
212
- <li class="hide-w"><a title="Chuyển nhượng" href="/tin-chuyen-nhuong">Chuyển nhượng</a></li>
213
- <li class="hide-w"><a title="Champions League" href="/champions-league-cup-c1">Champions League</a></li>
214
- <li class="hide-w"><a title="Tây Ban Nha" href="/bong-da-tay-ban-nha">Tây Ban Nha</a></li>
215
- <li class="hide-w"><a title="Pháp" href="/bong-da-phap">Pháp</a></li>
216
- <li class="hide-w"><a title="Italia" href="/bong-da-y">Italia</a></li>
217
- <li class="hide-w"><a title="Thể thao" href="/the-thao">Thể thao</a></li>
218
- <li class="hide-w"><a title="Nhận định" href="/nhan-dinh-bong-da-tags">Nhận định</a></li>
219
- <li class="hide-w"><a title="Thế giới" href="/the-gioi">Thế giới</a></li>
220
- <li class="hide-w"><a title="Multimedia" href="/video">Multimedia</a></li>
221
- <li class="hide-w"><a title="Bóng đá Cuộc sống" href="/bong-da-cuoc-song">Bóng đá Cuộc sống</a></li>
222
- </ul>
223
- <div class="srch-bar hide-m">
224
- <button class="ico close"></button>
225
- <form class="srch-form" action="/tim-kiem">
226
- <input class="pattern toggler" name="q" type="text" placeholder="Nhập nội dung cần tìm" />
227
- </form>
228
- </div>
229
- </div>
230
- </div>
231
- </div>
232
- <div class="clr"></div>
233
- </div>
234
- <div class="mob-menu">
235
- <div class="mmnu-cap">
236
- <button class="ico close" data-action="hide"></button>
237
- <a class="logo" href="/"></a>
238
- </div>
239
- <form class="mmnu-sch " action="/tim-kiem">
240
- <input type="text" name="q">
241
- <button class="ico search" type="submit"></button>
242
- </form>
243
- <div class="mmnu-lst">
244
- <div class="menu-row">
245
- <ul class="bar">
246
- <li class="exp">
247
- <a class="major" title="Tin mới nhất" href="/tin-moi"><span class="ico blinkr"></span> Mới nhất</a>
248
- </li>
249
- <li>
250
- <ul class="lst">
251
- <li><a class="fst" title="Nh���n định Bóng đá" href="/nhan-dinh-bong-da-tags">Nhận định</a></li>
252
- </ul>
253
- </li>
254
- <li>
255
- <ul class="lst">
256
- <li><a class="fst" title="Lịch thi đấu bóng đá" href="/lich-thi-dau-bong-da">Lịch thi đấu</a></li>
257
- </ul>
258
- </li>
259
- <li class="exp"></li>
260
- <li class="exp"><a class="major" title="Bóng đá Plus Premium" href="/premium">Bóng đá Premium <i class="ico crown"></i></a></li>
261
- <li>
262
- <ul class="lst">
263
- <li><a class="fst" title="Bóng đá Việt Nam" href="/bong-da-viet-nam">Bóng đá Việt Nam</a></li>
264
- <li><a title="Đội tuyển Việt Nam" href="/doi-tuyen-quoc-gia-viet-nam">Đội tuyển Việt Nam</a></li>
265
- <li><a title="V.League" href="/v-league">V.League</a></li>
266
- <li><a title="Hạng Nhất" href="/hang-nhat-viet-nam">Hạng Nhất</a></li>
267
- <li><a title="Cúp Quốc gia" href="/cup-quoc-gia-viet-nam">Cúp Quốc gia</a></li>
268
- <li><a title="Bóng đá nữ" href="/bong-da-nu-viet-nam">Bóng đá nữ</a></li>
269
- <li><a title="Futsal" href="/futsal">Futsal</a></li>
270
- <li><a title="Phong trào" href="/bong-da-phong-trao">Bóng đá Phong trào</a></li>
271
- <li><a title="Chuyển nhượng V.League" href="/tin-chuyen-nhuong-v-league">Chuyển nhượng</a></li>
272
- </ul>
273
- </li>
274
- <li>
275
- <ul class="lst">
276
- <li><a class="fst" title="Bóng đá Anh" href="/bong-da-anh">Bóng đá Anh</a></li>
277
- <li><a title="Đội tuyển Anh" href="/doi-tuyen-anh">Đội tuyển Anh</a></li>
278
- <li><a title="Ngoại hạng Anh" href="/ngoai-hang-anh">Ngoại hạng Anh</a></li>
279
- <li><a title="FA Cup" href="/fa-cup">FA Cup</a></li>
280
- <li><a title="League Cup" href="/cup-lien-doan-anh">League Cup</a></li>
281
- </ul>
282
- <div class="clx"></div>
283
- <ul class="lst">
284
- <li><a class="fst" title="Tây Ban nha" href="/bong-da-tay-ban-nha">Tây Ban nha</a></li>
285
- <li><a title="Đội tuyển TBN" href="/doi-tuyen-tay-ban-nha">Đội tuyển TBN</a></li>
286
- <li><a title="La Liga" href="/la-liga">La Liga</a></li>
287
- <li><a title="Cúp Nhà Vua" href="/cup-nha-vua-tay-ban-nha">Cúp Nhà Vua</a></li>
288
- </ul>
289
- </li>
290
- <li class="exp"></li>
291
- <li>
292
- <ul class="lst">
293
- <li><a class="fst" title="Bóng đá Pháp" href="/bong-da-phap">Bóng đá Pháp</a></li>
294
- <li><a title="Đội tuyển Pháp" href="/doi-tuyen-phap">Đội tuyển Pháp</a></li>
295
- <li><a title="Ligue 1" href="/ligue-1">Ligue 1</a></li>
296
- <li><a title="Cúp QG Pháp" href="/cup-quoc-gia-phap">Cúp QG Pháp</a></li>
297
- <li><a title="Cúp Liên đoàn Pháp" href="/cup-lien-doan-phap-tags">Cúp Liên đoàn Pháp</a></li>
298
- </ul>
299
- </li>
300
- <li>
301
- <ul class="lst">
302
- <li><a class="fst" href="#">Bóng đá Khu vực</a></li>
303
- <li><a title="Asian Cup" href="/asian-cup">Asian Cup</a></li>
304
- <li><a title="Asian Games" href="/asian-games">Asian Games</a></li>
305
- <li><a title="AFF Cup" href="/aff-cup">AFF Cup</a></li>
306
- <li><a title="SEA Games" href="/sea-games">SEA Games</a></li>
307
- </ul>
308
- </li>
309
- <li class="exp"></li>
310
- <li>
311
- <ul class="lst">
312
- <li><a class="fst" title="Bóng đá Italia" href="/bong-da-y">Bóng đá Italia</a></li>
313
- <li><a title="Đội tuyển Italia" href="/doi-tuyen-y">Đội tuyển Italia</a></li>
314
- <li><a title="Serie A" href="/serie-a">Serie A</a></li>
315
- <li><a title="Coppa Italia" href="/coppa-italia">Coppa Italia</a></li>
316
- </ul>
317
- </li>
318
- <li>
319
- <ul class="lst">
320
- <li><a class="fst" title="Bóng đá Đức" href="/bong-da-duc">Bóng đá Đức</a></li>
321
- <li><a title="Đội tuyển Đức" href="/doi-tuyen-duc">Đội tuyển Đức</a></li>
322
- <li><a title="Bundesliga" href="/bundesliga">Bundesliga</a></li>
323
- <li><a title="Cúp QG Đức" href="/cup-quoc-gia-duc">Cúp QG Đức</a></li>
324
- </ul>
325
- </li>
326
- <li class="exp"></li>
327
- <li>
328
- <ul class="lst">
329
- <li><a class="fst" href="#">Nội dung Đặc biệt</a></li>
330
- <li><a title="Big Story" href="/emagazine">Big Story</a></li>
331
- <li><a title="X-File" href="/x-file">X-File</a></li>
332
- <li><a title="Infographic" href="/infographic">Infographic</a></li>
333
- <li><a title="Interactive" href="/interactive">Interactive</a></li>
334
- </ul>
335
- </li>
336
- <li>
337
- <ul class="lst">
338
- <li><a class="fst" href="#">Giải đấu CLB</a></li>
339
- <li><a title="Champions Leage" href="/champions-league-cup-c1">Champions League</a></li>
340
- <li><a title="Europa League" href="/europa-league">Europa League</a></li>
341
- <li><a title="Club World Cup" href="/fifa-club-world-cup-tags">Club World Cup</a></li>
342
- <li><a title="Europa Conference League" href="/europa-conference-league">Europa Conf League</a></li>
343
- </ul>
344
- </li>
345
- <li class="exp"></li>
346
- <li>
347
- <ul class="lst">
348
- <li><a class="fst" href="#">Chuyên đề</a></li>
349
- <li><a title="Tin chuyển nhượng" href="/tin-chuyen-nhuong">Chuyển nhượng</a></li>
350
- <li><a title="Hậu trường bóng đá" href="/hau-truong-bong-da">Hậu trường</a></li>
351
- <li><a title="Điểm tin" href="/diem-tin">Điểm tin</a></li>
352
- <li><a title="Showbiz Ngôi sao" href="/ngoi-sao-showbiz">Showbiz Ngôi sao</a></li>
353
- <li><a title="Góc check var" href="/goc-check-var">Góc check var</a></li>
354
- <li><a title="Công nghệ" href="/cong-nghe">Công nghệ</a></li>
355
- <li><a title="Thông tin Thị trường" href="/thi-truong">Thị trường</a></li>
356
- <li><a title="Bóng đá & Cuộc sống" href="/bong-da-cuoc-song">Bóng đá & Cuộc sống</a></li>
357
- </ul>
358
- </li>
359
- <li>
360
- <ul class="lst">
361
- <li><a class="fst" href="#">Đội tuyển</a></li>
362
- <li><a title="World Cup nữ 2028" href="/world-cup-nu-2023-tags">World Cup nữ 2028</a></li>
363
- <li><a title="World Cup" href="/world-cup">World Cup 2026</a></li>
364
- <li><a title="European Championship 2028" href="/euro-cup-chau-au">EURO 2028</a></li>
365
- <li><a title="Nations League" href="/nations-league">Nations League</a></li>
366
- <li><a title="Copa America" href="/copa-america">Copa America</a></li>
367
- <li><a title="CAN" href="/can">CAN</a></li>
368
- <li><a title="Olympic 2028" href="/olympic">Olympic 2028</a></li>
369
- </ul>
370
- </li>
371
- <li class="exp"></li>
372
- <li>
373
- <ul class="lst">
374
- <li><a class="fst" title="Multimedia" href="/video">Multimedia</a></li>
375
- </ul>
376
- </li>
377
- <li>
378
- <ul class="lst">
379
- <li>&nbsp;</li>
380
- </ul>
381
- </li>
382
- <li class="exp"></li>
383
- <li>
384
- <ul class="lst">
385
- <li><a class="fst" href="/lich-thi-dau-bong-da">Lịch thi đấu</a></li>
386
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-viet-nam" title="Lịch thi đấu V.League">V.League</a></li>
387
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-anh" title="Lịch thi đấu Ngoại hạng Anh">Ngoại hạng Anh</a></li>
388
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-phap" title="Lịch thi đấu Ligue 1 Pháp">Ligue 1</a></li>
389
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-tay-ban-nha" title="Lịch thi đấu La Liga Tây Ban Nha">La Liga</a></li>
390
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-duc" title="Lịch thi đấu Bundesliga Đức">Bundesliga</a></li>
391
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-y" title="Lịch thi đấu Serie A Italia">Serie A</a></li>
392
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?champions-league-cup-c1" title="Lịch thi đấu Champions League">Champions League</a></li>
393
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?europa-league" title="Lịch thi đấu Europa League">Europa League</a></li>
394
- </ul>
395
- </li>
396
- <li>
397
- <ul class="lst">
398
- <li><a class="fst" href="/bang-xep-hang-bong-da">Bảng xếp hạng</a></li>
399
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-viet-nam" title="Bảng xếp hạng V.League">V.League</a></li>
400
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-anh" title="Bảng xếp hạng Ngoại hạng Anh">Ngoại hạng Anh</a></li>
401
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-phap" title="Bảng xếp hạng Ligue 1 Pháp">Ligue 1</a></li>
402
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-tay-ban-nha" title="Bảng xếp hạng La Liga Tây Ban Nha">La Liga</a></li>
403
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-duc" title="Bảng xếp hạng Bundesliga Đức">Bundesliga</a></li>
404
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-y" title="Bảng xếp hạng Serie A Italia">Serie A</a></li>
405
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?champions-league-cup-c1" title="Bảng xếp hạng Champions League">Champions League</a></li>
406
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?europa-league" title="Bảng xếp hạng Europa League">Europa League</a></li>
407
- </ul>
408
- </li>
409
- <li class="exp"></li>
410
- <li><a class="caption" href="https://phui.bongdaplus.vn" target="_blank">Bóng đá phủi</a></li>
411
- <li><a class="caption" href="/tennis">Tennis</a></li>
412
- <li><a class="caption" href="/esports">Esports</a></li>
413
- <li><a class="caption" href="/the-thao">Thể thao +</a></li>
414
- </ul>
415
- </div>
416
- </div>
417
- <div class="mmnu-end tx-cen">
418
- <p>Theo dõi thông tin</p>
419
- <ul class="bar social-lnk">
420
- <li class="hide-m">Theo dõi thông tin</li>
421
- <li><a class="ico vff-lnk" target="_blank" href="https://vff.org.vn/" style="background-size:28px;opacity:1;" rel="nofollow"></a></li>
422
- <li><a class="ico fb-lnk" target="_blank" href="https://www.facebook.com/BaoBongDa/" style="background-size:28px;opacity:1;"></a></li>
423
- <li><a class="ico yt-lnk" target="_blank" href="https://www.youtube.com/channel/UCF0VFBZu-5SRJXMV_FMysEA" style="background-size:28px;opacity:1;"></a></li>
424
- </ul>
425
- </div>
426
- </div>
427
- <div class="mega-menu">
428
- <div class="cont-wrap">
429
- <div class="menu-row">
430
- <ul class="bar">
431
- <li><a class="caption" title="Tin mới nhất" href="/tin-moi">Mới nhất</a></li>
432
- <li>
433
- <ul class="lst">
434
- <li><a class="fst" title="Bóng đá Việt Nam" href="/bong-da-viet-nam">Bóng đá Việt Nam</a></li>
435
- <li><a title="Đội tuyển Việt Nam" href="/doi-tuyen-quoc-gia-viet-nam">Đội tuyển Việt Nam</a></li>
436
- <li><a title="V.League" href="/v-league">V.League</a></li>
437
- <li><a title="Hạng Nhất" href="/hang-nhat-viet-nam">Hạng Nhất</a></li>
438
- <li><a title="Cúp Quốc gia" href="/cup-quoc-gia-viet-nam">Cúp Quốc gia</a></li>
439
- <li><a title="Cúp châu Á" href="/asian-cup">Cúp châu Á</a></li>
440
- <li><a title="Bóng đá nữ" href="/bong-da-nu-viet-nam">Bóng đá nữ</a></li>
441
- <li><a title="Futsal" href="/futsal">Futsal</a></li>
442
- <li><a title="Phong trào" href="/bong-da-phong-trao">Phong trào</a></li>
443
- <li><a title="Chuyển nhượng V.League" href="/tin-chuyen-nhuong-v-league">Chuyển nhượng V.League</a></li>
444
- <li><a title="Tin khác" href="/tin-khac">Tin khác</a></li>
445
- </ul>
446
- </li>
447
-
448
- <li>
449
- <ul class="lst">
450
- <li><a class="fst" title="Bóng đá Anh" href="/bong-da-anh">Bóng đá Anh</a></li>
451
- <li><a title="Đội tuyển Anh" href="/doi-tuyen-anh">Đội tuyển Anh</a></li>
452
- <li><a title="Ngoại hạng Anh" href="/ngoai-hang-anh">Ngoại hạng Anh</a></li>
453
- <li><a title="FA Cup" href="/fa-cup">FA Cup</a></li>
454
- <li><a title="League Cup" href="/cup-lien-doan-anh">League Cup</a></li>
455
- </ul>
456
- <div class="clx"></div>
457
- <ul class="lst">
458
- <li><a class="fst" href="#">Giải đấu CLB</a></li>
459
- <li><a title="Champions Leage" href="/champions-league-cup-c1">Champions League</a></li>
460
- <li><a title="Europa League" href="/europa-league">Europa League</a></li>
461
- <li><a title="Club World Cup" href="/fifa-club-world-cup-tags">Club World Cup</a></li>
462
- <li><a title="Europa Conference League" href="/europa-conference-league">Europa Conference League</a></li>
463
- </ul>
464
- </li>
465
-
466
- <li>
467
- <ul class="lst">
468
- <li><a class="fst" title="Bóng đá Italia" href="/bong-da-y">Bóng đá Italia</a></li>
469
- <li><a title="Đội tuyển Italia" href="/doi-tuyen-y">Đội tuyển Italia</a></li>
470
- <li><a title="Serie A" href="/serie-a">Serie A</a></li>
471
- <li><a title="Coppa Italia" href="/coppa-italia">Coppa Italia</a></li>
472
- </ul>
473
- <div class="clx"></div>
474
- <ul class="lst">
475
- <li><a class="fst" href="#">Đội tuyển</a></li>
476
- <li><a title="World Cup nữ 2028" href="/world-cup-nu-2023-tags">World Cup nữ 2028</a></li>
477
- <li><a title="World Cup" href="/world-cup">World Cup 2026</a></li>
478
- <li><a title="European Championship 2028" href="/euro-cup-chau-au">EURO 2028</a></li>
479
- <li><a title="Nations League" href="/nations-league">Nations League</a></li>
480
- <li><a title="Copa America" href="/copa-america">Copa America</a></li>
481
- <li><a title="CAN" href="/can">CAN</a></li>
482
- <li><a title="Olympic" href="/olympic">Olympic 2028</a></li>
483
- </ul>
484
- </li>
485
-
486
- <li>
487
- <ul class="lst">
488
- <li><a class="fst" title="Bóng đá Pháp" href="/bong-da-phap">Bóng đá Pháp</a></li>
489
- <li><a title="Đội tuyển Pháp" href="/doi-tuyen-phap">Đội tuyển Pháp</a></li>
490
- <li><a title="Ligue 1" href="/ligue-1">Ligue 1</a></li>
491
- <li><a title="Cúp QG Pháp" href="/cup-quoc-gia-phap">Cúp QG Pháp</a></li>
492
- <li><a title="Cúp Liên đoàn Pháp" href="/cup-lien-doan-phap-tags">Cúp Liên đoàn Pháp</a></li>
493
- </ul>
494
- <div class="clx"></div>
495
- <ul class="lst">
496
- <li><a class="fst" href="#">Khu vực</a></li>
497
- <li><a title="Asian Cup" href="/asian-cup">Asian Cup</a></li>
498
- <li><a title="Asian Games" href="/asian-games">Asian Games</a></li>
499
- <li><a title="AFF Cup" href="/aff-cup">AFF Cup</a></li>
500
- <li><a title="SEA Games" href="/sea-games">SEA Games</a></li>
501
- </ul>
502
- </li>
503
-
504
- <li>
505
- <ul class="lst">
506
- <li><a class="fst" title="Tây Ban nha" href="/bong-da-tay-ban-nha">Tây Ban nha</a></li>
507
- <li><a title="Đội tuyển TBN" href="/doi-tuyen-tay-ban-nha">Đội tuyển TBN</a></li>
508
- <li><a title="La Liga" href="/la-liga">La Liga</a></li>
509
- <li><a title="Cúp Nhà Vua" href="/cup-nha-vua-tay-ban-nha">Cúp Nhà Vua</a></li>
510
- </ul>
511
- <div class="clx"></div>
512
- <ul class="lst">
513
- <li><a class="fst" href="#">Chuyên đề</a></li>
514
- <li><a title="Tin chuyển nhượng" href="/tin-chuyen-nhuong">Chuyển nhượng</a></li>
515
- <li><a title="Hậu trường bóng đá" href="/hau-truong-bong-da">Hậu trường</a></li>
516
- <li><a title="Điểm tin" href="/diem-tin">Điểm tin</a></li>
517
- <li><a title="Showbiz Ngôi sao" href="/ngoi-sao-showbiz">Showbiz Ngôi sao</a></li>
518
- <li><a title="Góc check var" href="/goc-check-var">Góc check var</a></li>
519
- <li><a title="Công nghệ" href="/cong-nghe">Công nghệ</a></li>
520
- <li><a title="Thông tin Thị trường" href="/thi-truong">Thị trường</a></li>
521
- </ul>
522
- </li>
523
-
524
- <li>
525
- <ul class="lst">
526
- <li><a class="fst" title="Bóng đá Đức" href="/bong-da-duc">Bóng đá Đức</a></li>
527
- <li><a title="Đội tuyển Đức" href="/doi-tuyen-duc">Đội tuyển Đức</a></li>
528
- <li><a title="Bundesliga" href="/bundesliga">Bundesliga</a></li>
529
- <li><a title="Cúp QG Đức" href="/cup-quoc-gia-duc">Cúp QG Đức</a></li>
530
- </ul>
531
- <div class="clx"></div>
532
- <ul class="lst">
533
- <li><a class="fst" href="#">Đặc biệt</a></li>
534
- <li><a title="Big Story" href="/emagazine">Big Story</a></li>
535
- <li><a title="X-File" href="/x-file">X-File</a></li>
536
- <li><a title="Infographic" href="/infographic">Infographic</a></li>
537
- <li><a title="Interactive" href="/interactive">Interactive</a></li>
538
- </ul>
539
- </li>
540
- </ul>
541
- </div>
542
-
543
- <div class="menu-row">
544
- <ul class="bar">
545
- <li>&nbsp;</li>
546
- <li><a title="Tin chuyển nhượng" href="/tin-chuyen-nhuong">Tin chuyển nhượng</a></li>
547
- <li><a title="Bóng đá & Cuộc sống" href="/bong-da-cuoc-song">Bóng đá & Cuộc sống</a></li>
548
- <li><a title="Thông tin Thị trường" href="/thi-truong">Thông tin Thị trường</a></li>
549
- <li><a title="Tin tức Công nghệ" href="/cong-nghe">Công nghệ</a></li>
550
- <li><a title="Tin tức Xe auto bike" href="/xe-co">Xe auto</a></li>
551
- </ul>
552
- </div>
553
-
554
- <div class="menu-row">
555
- <ul class="bar">
556
- <li>&nbsp;</li>
557
- <li><a class="caption" title="Nhận định Bóng đá" href="/nhan-dinh-bong-da-tags">Nhận định</a></li>
558
- <li><a class="caption" title="Tư vấn Bóng đá" href="/soi-keo-bong-da">Tư vấn</a></li>
559
- <li><a class="caption" title="Multimedia" href="/video">Multimedia</a></li>
560
- <li><a class="caption" title="Youtube" target="_blank" href="https://www.youtube.com/channel/UCF0VFBZu-5SRJXMV_FMysEA">Youtube</a></li>
561
- <li><a class="caption" title="Facebook fanpage" target="_blank" href="https://www.facebook.com/BaoBongDa">FB Fanpage</a></li>
562
- <li>
563
- <a class="caption" title="Premium" href="/premium">Premium <i class="ico crown"></i></a>
564
- </li>
565
- </ul>
566
- </div>
567
-
568
- <div class="menu-row">
569
- <ul class="bar">
570
- <li><a class="caption" href="/lich-thi-dau-bong-da">Lịch thi đấu</a></li>
571
- <li>
572
- <ul class="lst">
573
- <li><a class="fst" href="/lich-thi-dau-bong-da">Lịch thi đấu hôm nay</a></li>
574
- <li><a href="/lich-thi-dau-bong-da?bong-da-viet-nam" title="Lịch thi đấu V.League">V.League</a></li>
575
- <li><a href="/lich-thi-dau-bong-da?bong-da-anh" title="Lịch thi đấu Ngoại hạng Anh">Ngoại hạng Anh</a></li>
576
- <li><a href="/lich-thi-dau-bong-da?bong-da-phap" title="Lịch thi đấu Ligue 1 Pháp">Ligue 1</a></li>
577
- <li><a href="/lich-thi-dau-bong-da?bong-da-tay-ban-nha" title="Lịch thi đấu La Liga Tây Ban Nha">La Liga</a></li>
578
- <li><a href="/lich-thi-dau-bong-da?bong-da-duc" title="Lịch thi đấu Bundesliga Đức">Bundesliga</a></li>
579
- <li><a href="/lich-thi-dau-bong-da?bong-da-y" title="Lịch thi đấu Serie A Italia">Serie A</a></li>
580
- <li><a href="/lich-thi-dau-bong-da?champions-league-cup-c1" title="Lịch thi đấu Champions League">Champions League</a></li>
581
- <li><a href="/lich-thi-dau-bong-da?europa-league" title="Lịch thi đấu Europa League">Europa League</a></li>
582
- </ul>
583
- </li>
584
-
585
- <li>
586
- <ul class="lst">
587
- <li><a class="fst" href="/ket-qua-bong-da">Kết quả mới nhất</a></li>
588
- <li><a href="/lich-thi-dau-bong-da?bong-da-viet-nam" title="Kết quả V.League">V.League</a></li>
589
- <li><a href="/lich-thi-dau-bong-da?bong-da-anh" title="Kết quả Ngoại hạng Anh">Ngoại hạng Anh</a></li>
590
- <li><a href="/lich-thi-dau-bong-da?bong-da-phap" title="Kết quả Ligue 1 Pháp">Ligue 1</a></li>
591
- <li><a href="/lich-thi-dau-bong-da?bong-da-tay-ban-nha" title="Kết quả La Liga Tây Ban Nha">La Liga</a></li>
592
- <li><a href="/lich-thi-dau-bong-da?bong-da-duc" title="Kết quả Bundesliga Đức">Bundesliga</a></li>
593
- <li><a href="/lich-thi-dau-bong-da?bong-da-y" title="Kết quả Serie A Italia">Serie A</a></li>
594
- <li><a href="/lich-thi-dau-bong-da?champions-league-cup-c1" title="Kết quả Champions League">Champions League</a></li>
595
- <li><a href="/lich-thi-dau-bong-da?europa-league" title="Kết quả Europa League">Europa League</a></li>
596
- </ul>
597
- </li>
598
-
599
- <li>
600
- <ul class="lst">
601
- <li><a class="fst" href="#">Bảng xếp hạng</a></li>
602
- <li><a href="/bang-xep-hang-bong-da?bong-da-viet-nam" title="Bảng xếp hạng V.League">V.League</a></li>
603
- <li><a href="/bang-xep-hang-bong-da?bong-da-anh" title="Bảng xếp hạng Ngoại hạng Anh">Ngoại hạng Anh</a></li>
604
- <li><a href="/bang-xep-hang-bong-da?bong-da-phap" title="Bảng xếp hạng Ligue 1 Pháp">Ligue 1</a></li>
605
- <li><a href="/bang-xep-hang-bong-da?bong-da-tay-ban-nha" title="Bảng xếp hạng La Liga Tây Ban Nha">La Liga</a></li>
606
- <li><a href="/bang-xep-hang-bong-da?bong-da-duc" title="Bảng xếp hạng Bundesliga Đức">Bundesliga</a></li>
607
- <li><a href="/bang-xep-hang-bong-da?bong-da-y" title="Bảng xếp hạng Serie A Italia">Serie A</a></li>
608
- <li><a href="/bang-xep-hang-bong-da?champions-league-cup-c1" title="Bảng xếp hạng Champions League">Champions League</a></li>
609
- <li><a href="/bang-xep-hang-bong-da?europa-league" title="Bảng xếp hạng Europa League">Europa League</a></li>
610
- </ul>
611
- </li>
612
-
613
- <li>
614
- <ul class="lst">
615
- <li><a class="caption" href="https://phui.bongdaplus.vn" target="_blank">Bóng đá phủi</a></li>
616
- <li><a class="caption" href="/tennis">Tennis</a></li>
617
- </ul>
618
- </li>
619
- <li>
620
- <ul class="lst">
621
- <li><a class="caption" href="/esports">Esports</a></li>
622
- <li><a class="caption" href="/the-thao">Thể thao +</a></li>
623
- </ul>
624
- </li>
625
-
626
- <li>
627
- <ul class="lst">
628
- <li>
629
- <div class="copyr">
630
- <div class="splt hide-w"></div>
631
- <p><b class="allcap">Tạp chí Bóng Đá</b></p>
632
- <p>Giấy phép số 48/GP-BTTTT cấp ngày 05/02/2020</p>
633
- <p>&nbsp;</p>
634
- <p>
635
- Tổng biên tập:<br /> <b>Vũ Khắc Sơn</b><br />
636
- Phó tổng biên tập:<br /> <b>Nguyễn Hà Thanh</b>
637
- </p>
638
- <p>&nbsp;</p>
639
- <p>
640
- <a class="contact-showr" href="#">Thông tin tòa soạn</a><br />
641
- <a class="contact-showr" href="#">Liên hệ quảng cáo</a>
642
- </p>
643
- <p>Liên đoàn BĐVN <a href="https://vff.org.vn/" target="_blank" rel="nofollow"><img alt="VFF" src="/img/logo_Vff.png" style="width:28px;" /></a></p>
644
- </div>
645
- </li>
646
- </ul>
647
- </li>
648
- </ul>
649
- </div>
650
- </div>
651
- </div>
652
- <div class="menu-tags hide-w">
653
- <div class="today"></div>
654
- <div class="mtags">
655
- <a title="#HighlightBóngđá" href="/video/highlight">#HighlightBóngđá</a>
656
- <a title="#PremierLeague" href="/ngoai-hang-anh">#PremierLeague</a>
657
- <a title="#V.League" href="/v-league">#V.League</a>
658
- </div>
659
- </div>
660
-
661
- <div id="fxtSlideCover" class="fixt-strm" style="margin-bottom:5px;">
662
- <div class="cont-wrap">
663
- <a class="brand" href="https://admin.giaminhmedia.vn/www/delivery/cl.php?bannerid=1411&zoneid=328&sig=8300d1283663cec85d90499507ffd94240954967132167c0f302d7388b8f9bb5&dest=http%3A%2F%2Fadmin.giaminhmedia.vn%2Fwww%2Funiscore.php" target="_blank" rel="nofollow" style="margin-left:5px;">
664
- <img alt="" src="https://bongdaplus.vn/img/logouniscore-tiny.png">
665
- </a>
666
- <ul id="fxtSlide" class="nav"></ul>
667
- </div>
668
- </div>
669
-
670
- <div class="clz"></div>
671
- <div id="ADTOP" class="banner adweb admob" banner-adpos="top"></div>
672
-
673
- <section class="bread-crums">
674
- <div class="clz"></div>
675
- <div class="cont-wrap">
676
- <div class="chain-navs">
677
- <a href="/video">Multimedia</a>&raquo;
678
- </div>
679
- </div>
680
- </section>
681
-
682
- <section class="media-box">
683
- <div class="clz"></div>
684
- <div class="cont-wrap video-box">
685
- <div class="row">
686
- <div class="col m12 w8 clip-box">
687
- <div class="play-box rbox">
688
- <iframe id="ytbFrBpl" class="play-frame" src="https://www.youtube.com/embed/Qokb_8w6p0s?si=QNKAZIYxNrtn2hSN" cid="UCmn1v6lrIDZghUfbxXaorUw" vnum="0" class="latestVideoEmbed" title="Bongdaplus trên Youtube" frameborder="0" allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe>
689
- </div>
690
- </div>
691
-
692
- <div class="col m12 w4 clip-cont">
693
- <div class="ovrscrl">
694
- <div class="clip-info">
695
- <h1 class="title">Hull City vs MU: Quỷ Đỏ vào hang bắt hổ</h1>
696
- <p class="desc">
697
- Mùa giải Premier League 2026/27 của MU sẽ mở màn bằng chuyến làm khách đầy thử thách trước tân binh Hull City tại sân MKM. Cuộc đối đầu Hull City vs MU là màn chạm trán đáng chú ý khi “Đàn Hổ” đang tràn đầy khí thế, trong khi Quỷ đỏ không được phép sảy chân nếu muốn sớm tạo đà cho cuộc đua vô địch.
698
- </p>
699
-
700
- <div>08:07 - 22/08/2026</div>
701
- <div class="editor"></div>
702
- <div class="hash-tags">
703
- <b>Tags:</b>
704
- <a href="/video/hull-city-vs-mu-tags">Hull City vs MU</a>
705
- <a href="/video/nhan-dinh-hull-city-vs-mu-tags">nh&#x1EAD;n &#x111;&#x1ECB;nh Hull City vs MU</a>
706
- <a href="/video/premier-league-tags">Premier League</a>
707
- <a href="/video/mu-tags">MU</a>
708
- </div>
709
- <style>
710
- .emobar .emo:not(:empty) {
711
- background-position: left 10px top 50%;
712
- padding: 0 13px 0 36px;
713
- }
714
- .emobar .emo {
715
- border-radius: 16px;
716
- background-color: #d7d3d3;
717
- background-size: auto 18px;
718
- cursor: pointer;
719
- margin: 0 3px;
720
- padding: 0 16px;
721
- line-height: 32px;
722
- height: 32px;
723
- }
724
- .emopicked {
725
- border: solid 1px #767676;
726
- }
727
- </style>
728
- <div class="emobar tx-cen">
729
- <div class="clx"></div>
730
- <a class="emo like" onclick="btnNewsEmotion_click(1)" id="btnEmo1"> <span id="numemo1"></span></a>
731
- <a class="emo heart" onclick="btnNewsEmotion_click(2)" id="btnEmo2"> <span id="numemo2"></span></a>
732
- <a class="emo star" onclick="btnNewsEmotion_click(4)" id="btnEmo4"> <span id="numemo4"></span></a>
733
- <a class="emo comment" id="ncmt" href="#commenting" data-action="comment" data-act-only="true"></a>
734
- </div>
735
- </div>
736
- </div>
737
- </div>
738
- </div>
739
- </div>
740
-
741
- <div class="clx"></div>
742
- <div class="cont-view">
743
-
744
-
745
-
746
-
747
- <style>
748
- .btnlikedislikecmt {
749
- border-radius: 9px;
750
- border: solid 1px #767676;
751
- background-color: #cecece;
752
- }
753
-
754
- sup {
755
- padding: 3px;
756
- position: initial;
757
- vertical-align: initial;
758
- }
759
-
760
- .TopComment {
761
- border: solid 1px #fdd835;
762
- }
763
-
764
- .TopComment .info .member {
765
- color: red;
766
- }
767
-
768
- .TopComment .info .avatar {
769
- border: solid 1px red;
770
- }
771
-
772
- .comment .summ .replyat {
773
- /*color: #1b5e20;*/
774
- display: inline-block;
775
- margin: 0 8px 0 0;
776
- font-weight: bold;
777
- /* text-decoration: underline; */
778
- }
779
- </style>
780
- <div id="postComment" class="comm-zone">
781
- <a class="anchor" name="#comments"></a>
782
- <div class="clz"></div>
783
- <div class="xcap">Bình luận</div>
784
- <div class="clz"></div>
785
- <div class="comm-post ">
786
- <div id="formcomment" class="comm-form">
787
- <label class="txt-fld">
788
- <textarea id="txtcomment_0" name="txtcomment_0" maxlength="1000" placeholder="Hãy chia sẻ suy nghĩ của bạn..." onclick="showcommentloginform();"></textarea>
789
- </label>
790
- <div class="actions">
791
- <button id="btnComment" class="btn btn-send base" onclick="btnComment_click(0,0)">Gửi</button>
792
- </div>
793
- <center><div class="cmterr"></div></center>
794
- </div>
795
- </div>
796
- <div class="clz"></div>
797
- <div class="comm-frame">
798
- <div id="NewsComments"></div>
799
- <div class="clz"></div>
800
- <div class="cat-news">
801
- <div id="btnloadviewmore" class="view-more hide"><a onclick="loadviewmorecomment();">Xem thêm</a></div>
802
- </div>
803
- <div class="clz"></div>
804
- </div>
805
- </div>
806
- </div>
807
- <div class="clz"></div>
808
- </section>
809
-
810
-
811
-
812
-
813
-
814
- <div class="clx"></div>
815
- <center><div id="ADHOT" class="banner adweb admob" banner-adpos="hot"></div></center>
816
- <div class="clx"></div>
817
-
818
-
819
- <section class="cat-news">
820
- <div class="cont-wrap">
821
- <div class="capt-cover">
822
- <div class="caption">Video mới nhất</div>
823
- <button class="more-lnk"></button>
824
- </div>
825
- <div class="row flex">
826
- <div class="col m12 w3">
827
- <div class="news">
828
- <a class="thumb" href="/video/du-doan-ty-so-hull-mu-than-rua-ali-33-chon-doi-nao-982702608.html"><img alt="Dự đoán tỷ số Hull vs MU: Thần Rùa Ali 33 chọn đội nào?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/18/80/Anh-chu-480-x-270.jpg" /></a>
829
- <a class="title" href="/video/du-doan-ty-so-hull-mu-than-rua-ali-33-chon-doi-nao-982702608.html">Dự đoán tỷ số Hull vs MU: Thần Rùa Ali 33 chọn đội nào?</a>
830
- <span class="info">
831
- 43 ph&#xFA;t tr&#x1B0;&#x1EDB;c
832
- </span>
833
- <span class="info">
834
- </span>
835
- </div>
836
- </div>
837
- <div class="col m12 w3">
838
- <div class="news">
839
- <a class="thumb" href="/video/hull-city-vs-mu-quy-do-vao-hang-bat-ho-982672608.html"><img alt="Hull City vs MU: Quỷ Đỏ vào hang bắt hổ" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/18/13/ThumbHullvsMU-up.jpg" /></a>
840
- <a class="title" href="/video/hull-city-vs-mu-quy-do-vao-hang-bat-ho-982672608.html">Hull City vs MU: Quỷ Đỏ vào hang bắt hổ</a>
841
- <span class="info">
842
- 44 ph&#xFA;t tr&#x1B0;&#x1EDB;c
843
- </span>
844
- <span class="info">
845
- </span>
846
- </div>
847
- </div>
848
- <div class="col m12 w3">
849
- <div class="news">
850
- <a class="thumb" href="/video/du-doan-ty-so-brentford-vs-tottenham-premier-league-2026-27-than-rua-ali-33-chon-doi-nao-982862608.html"><img alt="Dự đoán tỷ số Brentford vs Tottenham: Thần Rùa Ali 33 chọn đội nào?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/19/80/Brentford-vs-Tottenham-480-x-270-moi.jpg" /></a>
851
- <a class="title" href="/video/du-doan-ty-so-brentford-vs-tottenham-premier-league-2026-27-than-rua-ali-33-chon-doi-nao-982862608.html">Dự đoán tỷ số Brentford vs Tottenham: Thần Rùa Ali 33 chọn đội nào?</a>
852
- <span class="info">
853
- 44 ph&#xFA;t tr&#x1B0;&#x1EDB;c
854
- </span>
855
- <span class="info">
856
- </span>
857
- </div>
858
- </div>
859
- <div class="col m12 w3">
860
- <div class="news">
861
- <a class="thumb" href="/video/brentford-vs-tottenham-de-zerbi-vuot-ai-gtech-982822608.html"><img alt="Brentford vs Tottenham: De Zerbi vượt ải Gtech" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/19/13/Brenfort-vs-Tottenham.jpg" /></a>
862
- <a class="title" href="/video/brentford-vs-tottenham-de-zerbi-vuot-ai-gtech-982822608.html">Brentford vs Tottenham: De Zerbi vượt ải Gtech</a>
863
- <span class="info">
864
- 45 ph&#xFA;t tr&#x1B0;&#x1EDB;c
865
- </span>
866
- <span class="info">
867
- </span>
868
- </div>
869
- </div>
870
- <div class="col m12 w3">
871
- <div class="news">
872
- <a class="thumb" href="/video/du-doan-ty-so-arsenal-vs-coventry-than-rua-ali-33-chon-doi-nao-982612608.html"><img alt="Dự đoán tỷ số Arsenal vs Coventry: Thần Rùa Ali 33 chọn đội nào?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/17/0/thumblai.jpg" /></a>
873
- <a class="title" href="/video/du-doan-ty-so-arsenal-vs-coventry-than-rua-ali-33-chon-doi-nao-982612608.html">Dự đoán tỷ số Arsenal vs Coventry: Thần Rùa Ali 33 chọn đội nào?</a>
874
- <span class="info">
875
- 09 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
876
- </span>
877
- <span class="info">
878
- </span>
879
- </div>
880
- </div>
881
- <div class="col m12 w3">
882
- <div class="news">
883
- <a class="thumb" href="/video/arsenal-vs-coventry-nha-vua-mo-man-bang-mot-chien-thang-982662608.html"><img alt="Arsenal vs Coventry: Nhà vua mở màn bằng một chiến thắng?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/18/13/ThumbArsenalvsCoventry-up.jpg" /></a>
884
- <a class="title" href="/video/arsenal-vs-coventry-nha-vua-mo-man-bang-mot-chien-thang-982662608.html">Arsenal vs Coventry: Nhà vua mở màn bằng một chiến thắng?</a>
885
- <span class="info">
886
- 09 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
887
- </span>
888
- <span class="info">
889
- </span>
890
- </div>
891
- </div>
892
- <div class="col m12 w3">
893
- <div class="news">
894
- <a class="thumb" href="/video/truc-tuyen-truoc-tran-arsenal-vs-coventry-hull-vs-mu-983222608.html"><img alt="Trực tuyến trước trận Arsenal vs Coventry, Hull vs MU" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/truc-tuyen-truoc-tran-Arsenal-vs-Coventry.jpg" /></a>
895
- <a class="title" href="/video/truc-tuyen-truoc-tran-arsenal-vs-coventry-hull-vs-mu-983222608.html">Trực tuyến trước trận Arsenal vs Coventry, Hull vs MU</a>
896
- <span class="info">
897
- 11 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
898
- </span>
899
- <span class="info">
900
- </span>
901
- </div>
902
- </div>
903
- <div class="col m12 w3">
904
- <div class="news">
905
- <a class="thumb" href="/video/dt-thai-lan-tap-cach-san-rajamangala-40km-hlv-anthony-hudson-chot-luon-doi-hinh-dau-viet-nam-983202608.html"><img alt=" ĐT Thái Lan tập cách sân Rajamangala 40km, HLV Anthony Hudson chốt luôn đội hình đấu Việt Nam" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/80/HLV-Thai-Lan-chot-doi-hinh.jpg" /></a>
906
- <a class="title" href="/video/dt-thai-lan-tap-cach-san-rajamangala-40km-hlv-anthony-hudson-chot-luon-doi-hinh-dau-viet-nam-983202608.html"> ĐT Thái Lan tập cách sân Rajamangala 40km, HLV Anthony Hudson chốt luôn đội hình đấu Việt Nam</a>
907
- <span class="info">
908
- 13 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
909
- </span>
910
- <span class="info">
911
- </span>
912
- </div>
913
- </div>
914
- <div class="col m12 w3">
915
- <div class="news">
916
- <a class="thumb" href="/video/tro-lai-san-tung-vo-dich-aff-cup-2024-dt-viet-nam-quyet-lam-nen-lich-su-983212608.html"><img alt=" Trở lại sân từng vô địch AFF Cup 2024, ĐT Việt Nam quyết làm nên lịch sử" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/80/Viet-Nam-tap-2-1-8.jpg" /></a>
917
- <a class="title" href="/video/tro-lai-san-tung-vo-dich-aff-cup-2024-dt-viet-nam-quyet-lam-nen-lich-su-983212608.html"> Trở lại sân từng vô địch AFF Cup 2024, ĐT Việt Nam quyết làm nên lịch sử</a>
918
- <span class="info">
919
- 14 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
920
- </span>
921
- <span class="info">
922
- </span>
923
- </div>
924
- </div>
925
- <div class="col m12 w3">
926
- <div class="news">
927
- <a class="thumb" href="/video/vong-1-premier-league-2026-27-lieu-co-cu-soc-983112608.html"><img alt="Nhận định Premier League vòng 1: Liệu có cú sốc?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/thumbvong1-480.jpg" /></a>
928
- <a class="title" href="/video/vong-1-premier-league-2026-27-lieu-co-cu-soc-983112608.html">Nhận định Premier League vòng 1: Liệu có cú sốc?</a>
929
- <span class="info">
930
- 14 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
931
- </span>
932
- <span class="info">
933
- </span>
934
- </div>
935
- </div>
936
- <div class="col m12 w3">
937
- <div class="news">
938
- <a class="thumb" href="/video/ronaldinho-gay-soc-46-tuoi-van-tro-lai-san-co-khoac-ao-clb-serie-c-983192608.html"><img alt="Ronaldinho gây sốc: 46 tuổi vẫn trở lại sân cỏ, khoác áo CLB Serie C" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/26/Ronaldinho480.jpg" /></a>
939
- <a class="title" href="/video/ronaldinho-gay-soc-46-tuoi-van-tro-lai-san-co-khoac-ao-clb-serie-c-983192608.html">Ronaldinho gây sốc: 46 tuổi vẫn trở lại sân cỏ, khoác áo CLB Serie C</a>
940
- <span class="info">
941
- 14 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
942
- </span>
943
- <span class="info">
944
- </span>
945
- </div>
946
- </div>
947
- <div class="col m12 w3">
948
- <div class="news">
949
- <a class="thumb" href="/video/arsenal-no-bom-tan-51-trieu-bang-de-va-hang-thu-983122608.html"><img alt="Arsenal nổ bom tấn 51 triệu bảng để vá hàng thủ" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/26/Konsa480.jpg" /></a>
950
- <a class="title" href="/video/arsenal-no-bom-tan-51-trieu-bang-de-va-hang-thu-983122608.html">Arsenal nổ bom tấn 51 triệu bảng để vá hàng thủ</a>
951
- <span class="info">
952
- 14 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
953
- </span>
954
- <span class="info">
955
- </span>
956
- </div>
957
- </div>
958
- <div class="col m12 w3">
959
- <div class="news">
960
- <a class="thumb" href="/video/truc-tuyen-hop-bao-viet-nam-hlv-kim-sang-sik-noi-gi-khi-pho-chu-tich-thai-lan-mia-mai-dan-nhap-tich-983182608.html"><img alt="Trực tuyến họp báo Việt Nam: HLV Kim Sang Sik nói gì khi Phó Chủ tịch Thái Lan mỉa mai dàn nhập tịch" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/anhliveVN.jpg" /></a>
961
- <a class="title" href="/video/truc-tuyen-hop-bao-viet-nam-hlv-kim-sang-sik-noi-gi-khi-pho-chu-tich-thai-lan-mia-mai-dan-nhap-tich-983182608.html">Trực tuyến họp báo Việt Nam: HLV Kim Sang Sik nói gì khi Phó Chủ tịch Thái Lan mỉa mai dàn nhập tịch</a>
962
- <span class="info">
963
- 16 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
964
- </span>
965
- <span class="info">
966
- </span>
967
- </div>
968
- </div>
969
- <div class="col m12 w3">
970
- <div class="news">
971
- <a class="thumb" href="/video/truc-tuyen-thai-lan-hop-bao-hlv-thach-dau-dt-viet-nam-983162608.html"><img alt=" Trực tuyến Thái Lan họp báo: HLV Anthony Hudson thách đấu ĐT Việt Nam" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/anhlivesua-480.jpg" /></a>
972
- <a class="title" href="/video/truc-tuyen-thai-lan-hop-bao-hlv-thach-dau-dt-viet-nam-983162608.html"> Trực tuyến Thái Lan họp báo: HLV Anthony Hudson thách đấu ĐT Việt Nam</a>
973
- <span class="info">
974
- 18 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
975
- </span>
976
- <span class="info">
977
- </span>
978
- </div>
979
- </div>
980
- <div class="col m12 w3">
981
- <div class="news">
982
- <a class="thumb" href="/video/ban-tin-21-8-dt-viet-nam-chiu-thong-ke-cuc-xau-truoc-chung-ket-thai-lan-choi-chieu-nhu-indo-983152608.html"><img alt="Bản tin 21/8: ĐT Việt Nam chịu thống kê cực xấu trước chung kết, Thái Lan chơi chiêu như Indo" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/Thumb-tin-nong-21-8-480-up.jpg" /></a>
983
- <a class="title" href="/video/ban-tin-21-8-dt-viet-nam-chiu-thong-ke-cuc-xau-truoc-chung-ket-thai-lan-choi-chieu-nhu-indo-983152608.html">Bản tin 21/8: ĐT Việt Nam chịu thống kê cực xấu trước chung kết, Thái Lan chơi chiêu như Indo</a>
984
- <span class="info">
985
- 18 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
986
- </span>
987
- <span class="info">
988
- </span>
989
- </div>
990
- </div>
991
- <div class="col m12 w3">
992
- <div class="news">
993
- <a class="thumb" href="/video/thai-lan-khoa-cdv-viet-nam-chi-3-000-ve-cho-tran-chung-ket-tai-rajamangala-983142608.html"><img alt="Thái Lan 'khóa' CĐV Việt Nam: Chỉ 3.000 vé cho trận chung kết tại Rajamangala" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/26/cdv.jpg" /></a>
994
- <a class="title" href="/video/thai-lan-khoa-cdv-viet-nam-chi-3-000-ve-cho-tran-chung-ket-tai-rajamangala-983142608.html">Thái Lan 'khóa' CĐV Việt Nam: Chỉ 3.000 vé cho trận chung kết tại Rajamangala</a>
995
- <span class="info">
996
- 20 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
997
- </span>
998
- <span class="info">
999
- </span>
1000
- </div>
1001
- </div>
1002
- <div class="col m12 w3">
1003
- <div class="news">
1004
- <a class="thumb" href="/video/truoc-tran-thai-lan-vs-viet-nam-svd-rajamagala-vang-tanh-hon-chua-ba-danh-983132608.html"><img alt="Trước trận Thái Lan vs Việt Nam: SVĐ Rajamagala vắng tanh hơn chùa Bà Đanh" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/livethumbYT-480.jpg" /></a>
1005
- <a class="title" href="/video/truoc-tran-thai-lan-vs-viet-nam-svd-rajamagala-vang-tanh-hon-chua-ba-danh-983132608.html">Trước trận Thái Lan vs Việt Nam: SVĐ Rajamagala vắng tanh hơn chùa Bà Đanh</a>
1006
- <span class="info">
1007
- 22 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
1008
- </span>
1009
- <span class="info">
1010
- </span>
1011
- </div>
1012
- </div>
1013
- <div class="col m12 w3">
1014
- <div class="news">
1015
- <a class="thumb" href="/video/du-doan-ty-so-thai-lan-vs-viet-nam-than-rua-ali-33-chon-doi-nao-983092608.html"><img alt="Dự đoán tỷ số Thái Lan vs Việt Nam: Thần Rùa Ali 33 chọn đội nào?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/20/80/ThumbRuaThaivsVietnam-480.jpg" /></a>
1016
- <a class="title" href="/video/du-doan-ty-so-thai-lan-vs-viet-nam-than-rua-ali-33-chon-doi-nao-983092608.html">Dự đoán tỷ số Thái Lan vs Việt Nam: Thần Rùa Ali 33 chọn đội nào?</a>
1017
- <span class="info">
1018
- 19:18 ng&#xE0;y 20/08/2026
1019
- </span>
1020
- <span class="info">
1021
- </span>
1022
- </div>
1023
- </div>
1024
- <div class="col m12 w3">
1025
- <div class="news">
1026
- <a class="thumb" href="/video/truyen-thong-anh-dac-biet-chu-y-den-ngoi-no-cua-dt-viet-nam-983072608.html"><img alt="Truyền thông Anh đặc biệt chú ý đến 'ngòi nổ' của ĐT Việt Nam" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/20/26/xuan-son.jpg" /></a>
1027
- <a class="title" href="/video/truyen-thong-anh-dac-biet-chu-y-den-ngoi-no-cua-dt-viet-nam-983072608.html">Truyền thông Anh đặc biệt chú ý đến 'ngòi nổ' của ĐT Việt Nam</a>
1028
- <span class="info">
1029
- 19:18 ng&#xE0;y 20/08/2026
1030
- </span>
1031
- <span class="info">
1032
- </span>
1033
- </div>
1034
- </div>
1035
- <div class="col m12 w3">
1036
- <div class="news">
1037
- <a class="thumb" href="/video/dt-viet-nam-co-mat-tai-thai-lan-ao-trang-van-chua-bi-thay-kim-vut-het-983082608.html"><img alt="ĐT Việt Nam có mặt tại Thái Lan, áo trắng vẫn chưa bị thầy Kim bỏ hết" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/20/26/Kim-Sang-Sik.jpg" /></a>
1038
- <a class="title" href="/video/dt-viet-nam-co-mat-tai-thai-lan-ao-trang-van-chua-bi-thay-kim-vut-het-983082608.html">ĐT Việt Nam có mặt tại Thái Lan, áo trắng vẫn chưa bị thầy Kim bỏ hết</a>
1039
- <span class="info">
1040
- 17:32 ng&#xE0;y 20/08/2026
1041
- </span>
1042
- <span class="info">
1043
- </span>
1044
- </div>
1045
- </div>
1046
- </div>
1047
- </div>
1048
- <div class="clz"></div>
1049
- </section>
1050
-
1051
-
1052
-
1053
- <div class="clx"></div>
1054
- <center><div id="ADBOT" class="banner adweb admob" banner-adpos="footer"></div></center>
1055
- </main>
1056
-
1057
- <style>
1058
- .iframpanel {
1059
- width: 100%;
1060
- max-width: 500px;
1061
- height: 560px;
1062
- overflow: hidden;
1063
- }
1064
-
1065
- </style>
1066
- <div class="paner-wrap">
1067
- <div class="over-layer hide"></div>
1068
- <div id="loginview" class="login-box paner hide iframpanel">
1069
- <div class="pan-capt">
1070
- <i class="pan-close" data-action="hide"></i>
1071
- </div>
1072
-
1073
-
1074
- <iframe src="https://member.bongdaplus.vn/Identity/Account/Login?ReturnUrl=%2FHome%2FLoginFromBongdaplus" frameborder="0" style="overflow:hidden;height:100%;width:100%"></iframe>
1075
-
1076
- </div>
1077
- <div id="commentloginview" class="login-box paner hide iframpanel">
1078
-
1079
-
1080
- <iframe src="https://member.bongdaplus.vn/Identity/Account/Login?ReturnUrl=%2FHome%2FCommentLoginFromBongdaplus" frameborder="0" style="overflow:hidden;height:100%;width:100%"></iframe>
1081
-
1082
- </div>
1083
- </div>
1084
- <input type="hidden" id="txtFullname" value="" />
1085
- <input type="hidden" id="txtUserid" value="" />
1086
-
1087
-
1088
-
1089
-
1090
-
1091
-
1092
- <center><div id="ADFT" class="banner adweb admob" banner-adpos="footer"></div></center>
1093
- <footer>
1094
- <div class="cont-wrap">
1095
- <div class="row">
1096
- <div class="col m12 w3">
1097
- <div class="caption">Tạp chí điện tử Bóng đá</div>
1098
- </div>
1099
- <div class="col m12 w6">
1100
- <p>Giấy phép số 48/GP-BTTTT cấp ngày 05/02/2020</p>
1101
- <p>Tổng biên tập: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <b>Vũ Khắc Sơn</b></p>
1102
- <p>Phó tổng biên tập: &nbsp; &nbsp;<b>Nguyễn Hà Thanh</b></p>
1103
- <div class="hide-w">
1104
- <p>Địa chỉ: &nbsp;<b>Tầng 6, Tòa nhà Licogi 13 Tower, 164 đường Khuất Duy Tiến, phường Thanh Xuân, Thành phố Hà Nội</b></p>
1105
- <p>Văn phòng giao dịch: <b>Tầng 5-6-7, toà nhà LĐBĐVN, số 18 Lý Văn Phức, phường Ô Chợ Dừa, Hà Nội</b></p>
1106
- <p>Điện thoại: <b>(84.24) 3554 1188 - (84.24) 3554 1199</b></p>
1107
- <p>
1108
- Email: &nbsp; &nbsp; <a href="mailto:toasoan@bongdaplus.vn"><b>toasoan@bongdaplus.vn</b></a> |
1109
- <a href="mailto:vanphong@bongdaplus.vn"><b>vanphong@bongdaplus.vn</b></a>
1110
- </p>
1111
- <div class="spl"></div>
1112
- <p class="caption">Liên hệ quảng cáo</p>
1113
- <p>Hotline: &nbsp;<b>0903 203 412</b></p>
1114
- <p>Email: &nbsp; &nbsp;<a href="mailto:tien.nguyen@giaminhmedia.vn"><b>tien.nguyen@giaminhmedia.vn</b></a></p>
1115
- </div>
1116
- </div>
1117
- <div class="col m12 w3">
1118
- <ul class="bar social-lnk rgt-w">
1119
- <li class="hide-m">Theo dõi thông tin</li>
1120
- <li><a class="ico vff-lnk" href="https://vff.org.vn/" target="_blank" rel="nofollow"></a></li>
1121
- <li><a class="ico fb-lnk" href="https://www.facebook.com/BaoBongDa/"></a></li>
1122
- <li><a class="ico yt-lnk" href="https://www.youtube.com/channel/UCvDYMBE6GipX2VGacqOU2_Q"></a></li>
1123
- </ul>
1124
- </div>
1125
- </div>
1126
- <div class="foot-menu">
1127
- <ul class="bar hide-m">
1128
- <li><a href="#" data-showpaner="#contactview">Thông tin tòa soạn</a></li>
1129
- <li><a href="#" data-showpaner="#advertview">Liên hệ quảng cáo</a></li>
1130
- </ul>
1131
- <div class="copy-rgt">
1132
- Bản quyền &copy;2011 Bongdaplus.vn. Chỉ được phát hành lại thông tin khi
1133
- có sự đồng ý bằng văn bản của Tạp chí điện tử Bóng đá
1134
- </div>
1135
- <div class="clx hide-m"></div>
1136
- </div>
1137
- </div>
1138
- </footer>
1139
-
1140
- <div class="paner-wrap">
1141
- <div class="over-layer hide"></div>
1142
- <div id="contactview" class="contact-box paner hide">
1143
- <div class="pan-capt">
1144
- <div class="pan-title">Thông tin Toà soạn</div>
1145
- <i class="pan-close" data-action="hide"></i>
1146
- </div>
1147
- <div class="pan-cont">
1148
- <div class="xcap lead tx-prime tx-cen">Tạp chí Điện tử Bóng Đá</div>
1149
- <div class="row">
1150
- <div class="col w3 tx-base tx-rgt">Tổng biên tập:</div>
1151
- <div class="col w9"><b>Vũ Khắc Sơn</b></div>
1152
- <div class="clx"></div>
1153
- <div class="col w3 tx-base tx-rgt">Phó Tổng biên tập:</div>
1154
- <div class="col w9">
1155
- <b>Nguyễn Hà Thanh</b>
1156
- </div>
1157
- </div>
1158
- <div class="splt"></div>
1159
- <div class="row">
1160
- <div class="col w3 tx-base tx-rgt">Địa chỉ:</div>
1161
- <div class="col w9"><b>Tầng 6, Tòa nhà Licogi 13 Tower, 164 đường Khuất Duy Tiến, phường Thanh Xuân, Thành phố Hà Nội</b></div>
1162
- <div class="col w3 tx-base tx-rgt">Văn phòng giao dịch:</div>
1163
- <div class="col w9"><b>Tầng 5-6-7, toà nhà LĐBĐVN, số 18 Lý Văn Phức, phường Ô Chợ Dừa, Hà Nội</b></div>
1164
- <div class="col w3 tx-base tx-rgt">Tel:</div>
1165
- <div class="col w9"><b>(84.24) 3554 1188 - (84.24) 3554 1199</b></div>
1166
- <div class="col w3 tx-base tx-rgt">Fax:</div>
1167
- <div class="col w9"><b>(84.24) 3553 9898</b></div>
1168
- <div class="col w3 tx-base tx-rgt">Email:</div>
1169
- <div class="col w9">
1170
- <a href="mailto:toasoan@bongdaplus.vn"><b>toasoan@bongdaplus.vn</b></a>
1171
- <a href="mailto:vanphong@bongdaplus.vn"><b>vanphong@bongdaplus.vn</b></a>
1172
- </div>
1173
- </div>
1174
- </div>
1175
- </div>
1176
-
1177
- <div id="advertview" class="contact-box paner hide">
1178
- <div class="pan-capt">
1179
- <div class="pan-title">Thông tin Liên hệ</div>
1180
- <i class="pan-close" data-action="hide"></i>
1181
- </div>
1182
- <div class="pan-cont">
1183
- <div class="xcap lead tx-prime tx-cen">Tạp chí Điện tử Bóng Đá</div>
1184
- <div class="row">
1185
- <div class="col w4 tx-base tx-rgt">Hotline:</div>
1186
- <div class="col w8"><b>0903 203 412</b></div>
1187
- <div class="col w4 tx-base tx-rgt">Email:</div>
1188
- <div class="col w8"><a href="mailto:tien.nguyen@giaminhmedia.vn"><b>tien.nguyen@giaminhmedia.vn</b></a></div>
1189
- </div>
1190
- <p class="tx-base">Địa chỉ liên hệ:</p>
1191
- <b>Tầng 6, Tòa nhà Licogi 13 Tower, 164 đường Khuất Duy Tiến, phường Thanh Xuân, Thành phố Hà Nội</b>
1192
- <p class="tx-base">Văn phòng giao dịch:</p>
1193
- <b>Tầng 5-6-7, toà nhà LĐBĐVN, số 18 Lý Văn Phức, phường Ô Chợ Dừa, Hà Nội</b>
1194
- </div>
1195
- </div>
1196
-
1197
-
1198
- <div id="loginview" class="login-box paner hide">
1199
- <div class="pan-capt">
1200
- <div class="pan-title">Đăng nhập</div>
1201
- <i class="pan-close" data-action="hide"></i>
1202
- </div>
1203
- <div class="pan-cont">
1204
- <form class="soc-auth" action="#">
1205
- <button><i class="ico gg-color"></i>Google</button>
1206
- <button><i class="ico fb-color"></i>Facebook</button>
1207
- </form>
1208
- <div class="clx"></div>
1209
- <div class="splt"><span>hoặc</span></div>
1210
- <form class="loginer" action="//member.bongdaplus.vn/Identity/Account/Login?ReturnUrl=/" method="post">
1211
- <p>Email:</p>
1212
- <label class="txt-fld" for="email">
1213
- <input id="email" name="Input.Email" type="email" />
1214
- <span>Nhập địa chỉ email của bạn</span>
1215
- </label>
1216
- <label class="err-fld hide" for="email">Địa chỉ email không được để trống</label>
1217
- <p>Mật khẩu:</p>
1218
- <label class="txt-fld" for="passw">
1219
- <input id="passw" name="Input.Password" type="password" data-required="Mật khẩu không được để trống" />
1220
- <span>Nhập mật khẩu của bạn</span>
1221
- </label>
1222
- <label class="err-fld hide" for="passw">Mật khẩu không được để trống</label>
1223
- <p class="ft-sm tx-rgt"><a class="fg-psw" href="#" data-action="hide" data-showpaner="#forgetview">Quên mật khẩu?</a></p>
1224
- <label class="rdo-fld" for="persist">
1225
- <input id="persist" name="Input.RememberMe" type="checkbox" />
1226
- Ghi nhớ thông tin đăng nhập
1227
- </label>
1228
- <br>
1229
- <div class="fld-box">
1230
- <button class="btn major" type="submit">Đăng nhập</button>
1231
- </div>
1232
- <p class="ft-sm tx-cen">
1233
- Bạn chưa có tài khoản?
1234
- <a class="act-now" href="#" data-action="hide" data-showpaner="#registview">Đăng ký ngay</a>
1235
- </p>
1236
- </form>
1237
- </div>
1238
- </div>
1239
- </div>
1240
-
1241
- <script src="/lib/jquery/dist/jquery.min.js"></script>
1242
- <script src="/js/js_cookie.min.js?v=0H3Nuz3aug3afVbUlsu12Puxva3CP4EhJtPExqs54Vg"></script>
1243
- <script src="/js/bongdaplus.js?v=gIIX1pYQ8DB66N40YPyoHGaBgBFoHkPMMCARX4L6NdA"></script>
1244
- <script src="/js/premium.js?v=mbXB8QoXMl1zoEFSeE6z-mwQTb0ot7C8zj_F8JqsvNc"></script>
1245
-
1246
- <script>var _ad_info_code = 'mda/video';</script>
1247
- <script src="/js/advloader.js?v=dvvR0ygTjyYzNcQmQ_dI5bwYeX2Ww0nBjBBmCt9DWjQ"></script>
1248
-
1249
- </body>
1250
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdp_page.html DELETED
@@ -1,1250 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <title>Hull City vs MU: Quỷ Đỏ vào hang bắt hổ - Bongdaplus.vn</title>
5
-
6
-
7
- <meta name="MobileOptimized" content="100" />
8
- <meta name="viewport" content="width=device-width, initial-scale=1" />
9
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
10
- <meta http-equiv="content-language" content="vi" />
11
- <meta http-equiv="refresh" content="300" />
12
- <meta property="fb:pages" content="1738672379699789" />
13
- <meta property="dable:item_id" content="2015111202028" />
14
- <meta property="og:image" itemprop="thumbnailUrl" content="https://bongdaplus.vn/img/logo-daily.png" />
15
- <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
16
- <link href="/favicon.svg" rel="icon" sizes="any" type="image/svg+xml" />
17
- <link href="/apple-touch-icon.png" rel="apple-touch-icon" />
18
- <!--iPhone icons-->
19
- <link href="/logo-57.png" rel="apple-touch-icon-precomposed" sizes="57x57" />
20
- <link href="/logo-114.png" rel="apple-touch-icon-precomposed" sizes="114x114" />
21
- <!--iPad icons-->
22
- <link href="/logo-72.png" rel="apple-touch-icon-precomposed" sizes="72x72" />
23
- <link href="/logo-114.png" rel="apple-touch-icon-precomposed" sizes="114x114" />
24
- <!--Android icon-->
25
- <link href="/logo-114.png" rel="apple-touch-icon-precomposed" sizes="1x1" />
26
- <!--Symbian icon-->
27
- <link href="/logo-57.png" rel="nokia-touch-icon" sizes="57x57" />
28
- <link rel="preconnect" href="https://fonts.googleapis.com">
29
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
30
- <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700;1,800&display=swap" rel="stylesheet">
31
- <link href="https://fonts.googleapis.com/css2?family=Noto+Serif:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
32
- <link href="/css/premium.css?id=0000&amp;v=ivL0rSTnUIBx45p3hw7UIAzbXjyQ9rgPVSyjqPglN_o" rel="stylesheet">
33
-
34
- <script async src="https://www.googletagmanager.com/gtag/js?id=UA-20374657-1"></script>
35
- <script>
36
- window.dataLayer = window.dataLayer || [];
37
- function gtag() { dataLayer.push(arguments); }
38
- gtag('js', new Date());
39
-
40
- gtag('config', 'UA-20374657-1');
41
- </script>
42
- <!-- Google tag (gtag.js) -->
43
- <script async src="https://www.googletagmanager.com/gtag/js?id=G-Y1DBNQWMVW"></script>
44
- <script>
45
- window.dataLayer = window.dataLayer || [];
46
- function gtag() { dataLayer.push(arguments); }
47
- gtag('js', new Date());
48
-
49
- gtag('config', 'G-Y1DBNQWMVW');
50
- </script>
51
-
52
- <script async src="https://static.amcdn.vn/tka/cdn.js" type="text/javascript"></script>
53
- <script>var arfAsync = arfAsync || [];</script>
54
- <script id="arf-core-js" onerror="window.arferrorload=true;" src="//media1.admicro.vn/cms/Arf.min.js" async></script>
55
- <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3619133031508264" crossorigin="anonymous"></script>
56
- </head>
57
- <body>
58
- <script type="application/ld+json">
59
- {
60
- "@context": "https://schema.org",
61
- "@type": "Organization",
62
- "name": "TẠP CHÍ ĐIỆN TỬ BÓNG ĐÁ - BONGDAPLUS",
63
- "url": "https://bongdaplus.vn",
64
- "logo": "https://bongdaplus.vn/img/logo.png",
65
- "contactPoint": {
66
- "@type": "ContactPoint",
67
- "telephone": "(84.24)35541188",
68
- "contactType": "customer service",
69
- "areaServed": "VN",
70
- "availableLanguage": "Vietnamese"
71
- },
72
- "sameAs": [
73
- "https://www.facebook.com/baobongda",
74
- "https://www.youtube.com/channel/UCvDYMBE6GipX2VGacqOU2_Q",
75
- "https://bongdaplus.vn",
76
- "https://www.pinterest.com/bongdaplus",
77
- "https://soundcloud.com/baobongda"
78
- ]
79
- }
80
- </script>
81
- <header>
82
- <center><div id="ADMTOP" class="banner admob" banner-adpos="top"></div></center>
83
-
84
- <div class="cont-wrap">
85
- <div class="mmnu-nav">
86
- <button class="ico mnu-sch mmnu-trigger hide-w"></button>
87
- <button class="ico menubar mmnu-trigger hide-m"></button>
88
- <button class="ico close mmnu-closer hide"></button>
89
- </div>
90
- <a class="logo" href="/"></a>
91
- <button class="ico bell hide-w hide"></button>
92
-
93
- <div class="authen-nav dropper">
94
- <a class="member">
95
- <span class="avatar">
96
- </span>
97
- </a>
98
- <div class="drop-down rgt">
99
- <ul class="lst">
100
-
101
- <li><a href="#" data-showpaner="#loginview">Đăng nhập</a></li>
102
- <li><a href="https://member.bongdaplus.vn/Identity/Account/Register?returnUrl=%2F" target="_blank">Tạo tài khoản</a></li>
103
-
104
-
105
- </ul>
106
- </div>
107
- </div>
108
- </div>
109
- </header>
110
- <input type="hidden" id="catrefid" value="video" />
111
- <input type="hidden" id="objectid" value="98267" />
112
- <input type="hidden" id="objecttype" value="1" />
113
- <input type="hidden" id="parentid" value="0" />
114
- <input type="hidden" id="commentnum" value="0" />
115
- <img src="/imgthumbnail/98267/1/1" alt="" height="0" width="0" />
116
-
117
- <main>
118
- <div class="nav-menu">
119
- <div class="menu-bar">
120
- <div class="cont-wrap">
121
- <div class="menu-side">
122
- <ul class="bar-w">
123
- <li><a class="ico home" href="/"></a></li>
124
- <li><a title="AFF Cup" href="/aff-cup">AFF Cup</a></li>
125
- <li class="popover">
126
- <a title="Việt Nam" href="/bong-da-viet-nam">Việt Nam</a>
127
- <div class="drop-down">
128
- <ul class="lst">
129
- <li><a title="V-League" href="/v-league">V-League</a></li>
130
- <li><a title="Hạng Nhất" href="/hang-nhat-quoc-gia">Hạng Nhất</a></li>
131
- <li><a title="Cúp Quốc gia" href="/cup-quoc-gia">Cúp Quốc gia</a></li>
132
- <li><a title="ĐTQG" href="/doi-tuyen-quoc-gia-viet-nam">ĐTQG</a></li>
133
- <li><a title="Bóng đá Nữ" href="/bong-da-nu-viet-nam">Bóng đá Nữ</a></li>
134
- <li><a title="U17 Quốc gia" href="/u17-viet-nam">U17 Quốc gia</a></li>
135
- <li><a title="U19 Quốc Gia" href="/u19-viet-nam">U19 Quốc Gia</a></li>
136
- <li><a title="U21 Quốc Gia" href="/u21-viet-nam">U21 Quốc Gia</a></li>
137
- <li><a title="Các đội tuyển trẻ" href="/cac-doi-tuyen-tre-viet-nam">Các đội tuyển trẻ</a></li>
138
- <li><a title="Futsal" href="/futsal">Futsal</a></li>
139
- <li><a title="Phong trào" href="/bong-da-phong-trao">Phong trào</a></li>
140
- <li><a title="Đơn vị Kết nghĩa" href="/ket-nghia-anh-em">Đơn vị Kết nghĩa</a></li>
141
- </ul>
142
- </div>
143
- </li>
144
- <li class="popover">
145
- <a title="Chuyển nhượng" href="/tin-chuyen-nhuong">Chuyển nhượng</a>
146
- <div class="drop-down">
147
- <ul class="lst">
148
- <li><a title="Tin chuyển nhượng Ngoại Hạng Anh" href="/tin-chuyen-nhuong-ngoai-hang-anh">Tin chuyển nhượng Ngoại Hạng Anh</a></li>
149
- <li><a title="Tin chuyển nhượng V-league" href="/tin-chuyen-nhuong-v-league">Tin chuyển nhượng V-league</a></li>
150
- </ul>
151
- </div>
152
- </li>
153
- <li><a title="Champions League" href="/champions-league-cup-c1">Champions League</a></li>
154
- <li class="popover">
155
- <a title="Tây Ban Nha" href="/bong-da-tay-ban-nha">Tây Ban Nha</a>
156
- <div class="drop-down">
157
- <ul class="lst">
158
- <li><a title="VĐQG Tây Ban Nha" href="/la-liga">VĐQG Tây Ban Nha</a></li>
159
- <li><a title="Cúp Nhà Vua" href="/cup-nha-vua-tay-ban-nha">Cúp Nhà Vua</a></li>
160
- <li><a title="Đội tuyển TBN" href="/doi-tuyen-tay-ban-nha">Đội tuyển TBN</a></li>
161
- </ul>
162
- </div>
163
- </li>
164
- <li class="popover">
165
- <a title="Pháp" href="/bong-da-phap">Pháp</a>
166
- <div class="drop-down">
167
- <ul class="lst">
168
- <li><a title="VĐQG Pháp" href="/ligue-1">VĐQG Pháp</a></li>
169
- <li><a title="Cúp Quốc gia Pháp" href="/cup-quoc-gia-phap">Cúp Quốc gia Pháp</a></li>
170
- <li><a title="Đội tuyển Pháp" href="/doi-tuyen-phap">Đội tuyển Pháp</a></li>
171
- </ul>
172
- </div>
173
- </li>
174
- <li class="popover">
175
- <a title="Italia" href="/bong-da-y">Italia</a>
176
- <div class="drop-down">
177
- <ul class="lst">
178
- <li><a title="VĐQG Italia" href="/serie-a">VĐQG Italia</a></li>
179
- <li><a title="Coppa Italia" href="/coppa-italia">Coppa Italia</a></li>
180
- <li><a title="Đội tuyển Italia" href="/doi-tuyen-y">Đội tuyển Italia</a></li>
181
- </ul>
182
- </div>
183
- </li>
184
- <li class="popover">
185
- <a title="Thể thao" href="/the-thao">Thể thao</a>
186
- <div class="drop-down">
187
- <ul class="lst">
188
- <li><a title="eSports" href="/esports">eSports</a></li>
189
- <li><a title="Tennis" href="/tennis">Tennis</a></li>
190
- <li><a title="Pickleball" href="/pickleball">Pickleball</a></li>
191
- <li><a title="MMA" href="/mma">MMA</a></li>
192
- <li><a title="Đua xe F1" href="/dua-xe-f1">Đua xe F1</a></li>
193
- <li><a title="Bóng rổ" href="/bong-ro">Bóng rổ</a></li>
194
- <li><a title="Olympic 2028" href="/olympic">Olympic 2028</a></li>
195
- </ul>
196
- </div>
197
- </li>
198
- <li><a title="Nhận định bóng đá" href="/nhan-dinh-bong-da-tags">Nhận định</a></li>
199
- <li><a title="Multimedia" href="/video">Multimedia</a></li>
200
- <li class="hide"><a title="Bongdaplus Premium" href="/premium">Premium <i class="ico crown"></i></a></li>
201
- </ul>
202
- </div>
203
- <div class="menu-nav">
204
- <a class="ico home hide-w" href="/"></a>
205
- <ul class="nav">
206
- <li class="hide-m"><i class="sepr"></i></li>
207
- <li><a href="/tin-moi">Mới nhất</a></li>
208
- <li class="hide-w"><a title="Bongdaplus Premium" href="/premium">Premium <i class="ico crown"></i></a></li>
209
- <li><a title="Anh" href="/bong-da-anh">Bóng đá Anh</a></li>
210
- <li class="hide-w"><a title="AFF Cup" href="/aff-cup">AFF Cup</a></li>
211
- <li class="hide-w"><a title="Việt Nam" href="/bong-da-viet-nam">Việt Nam</a></li>
212
- <li class="hide-w"><a title="Chuyển nhượng" href="/tin-chuyen-nhuong">Chuyển nhượng</a></li>
213
- <li class="hide-w"><a title="Champions League" href="/champions-league-cup-c1">Champions League</a></li>
214
- <li class="hide-w"><a title="Tây Ban Nha" href="/bong-da-tay-ban-nha">Tây Ban Nha</a></li>
215
- <li class="hide-w"><a title="Pháp" href="/bong-da-phap">Pháp</a></li>
216
- <li class="hide-w"><a title="Italia" href="/bong-da-y">Italia</a></li>
217
- <li class="hide-w"><a title="Thể thao" href="/the-thao">Thể thao</a></li>
218
- <li class="hide-w"><a title="Nhận định" href="/nhan-dinh-bong-da-tags">Nhận định</a></li>
219
- <li class="hide-w"><a title="Thế giới" href="/the-gioi">Thế giới</a></li>
220
- <li class="hide-w"><a title="Multimedia" href="/video">Multimedia</a></li>
221
- <li class="hide-w"><a title="Bóng đá Cuộc sống" href="/bong-da-cuoc-song">Bóng đá Cuộc sống</a></li>
222
- </ul>
223
- <div class="srch-bar hide-m">
224
- <button class="ico close"></button>
225
- <form class="srch-form" action="/tim-kiem">
226
- <input class="pattern toggler" name="q" type="text" placeholder="Nhập nội dung cần tìm" />
227
- </form>
228
- </div>
229
- </div>
230
- </div>
231
- </div>
232
- <div class="clr"></div>
233
- </div>
234
- <div class="mob-menu">
235
- <div class="mmnu-cap">
236
- <button class="ico close" data-action="hide"></button>
237
- <a class="logo" href="/"></a>
238
- </div>
239
- <form class="mmnu-sch " action="/tim-kiem">
240
- <input type="text" name="q">
241
- <button class="ico search" type="submit"></button>
242
- </form>
243
- <div class="mmnu-lst">
244
- <div class="menu-row">
245
- <ul class="bar">
246
- <li class="exp">
247
- <a class="major" title="Tin mới nhất" href="/tin-moi"><span class="ico blinkr"></span> Mới nhất</a>
248
- </li>
249
- <li>
250
- <ul class="lst">
251
- <li><a class="fst" title="Nh���n định Bóng đá" href="/nhan-dinh-bong-da-tags">Nhận định</a></li>
252
- </ul>
253
- </li>
254
- <li>
255
- <ul class="lst">
256
- <li><a class="fst" title="Lịch thi đấu bóng đá" href="/lich-thi-dau-bong-da">Lịch thi đấu</a></li>
257
- </ul>
258
- </li>
259
- <li class="exp"></li>
260
- <li class="exp"><a class="major" title="Bóng đá Plus Premium" href="/premium">Bóng đá Premium <i class="ico crown"></i></a></li>
261
- <li>
262
- <ul class="lst">
263
- <li><a class="fst" title="Bóng đá Việt Nam" href="/bong-da-viet-nam">Bóng đá Việt Nam</a></li>
264
- <li><a title="Đội tuyển Việt Nam" href="/doi-tuyen-quoc-gia-viet-nam">Đội tuyển Việt Nam</a></li>
265
- <li><a title="V.League" href="/v-league">V.League</a></li>
266
- <li><a title="Hạng Nhất" href="/hang-nhat-viet-nam">Hạng Nhất</a></li>
267
- <li><a title="Cúp Quốc gia" href="/cup-quoc-gia-viet-nam">Cúp Quốc gia</a></li>
268
- <li><a title="Bóng đá nữ" href="/bong-da-nu-viet-nam">Bóng đá nữ</a></li>
269
- <li><a title="Futsal" href="/futsal">Futsal</a></li>
270
- <li><a title="Phong trào" href="/bong-da-phong-trao">Bóng đá Phong trào</a></li>
271
- <li><a title="Chuyển nhượng V.League" href="/tin-chuyen-nhuong-v-league">Chuyển nhượng</a></li>
272
- </ul>
273
- </li>
274
- <li>
275
- <ul class="lst">
276
- <li><a class="fst" title="Bóng đá Anh" href="/bong-da-anh">Bóng đá Anh</a></li>
277
- <li><a title="Đội tuyển Anh" href="/doi-tuyen-anh">Đội tuyển Anh</a></li>
278
- <li><a title="Ngoại hạng Anh" href="/ngoai-hang-anh">Ngoại hạng Anh</a></li>
279
- <li><a title="FA Cup" href="/fa-cup">FA Cup</a></li>
280
- <li><a title="League Cup" href="/cup-lien-doan-anh">League Cup</a></li>
281
- </ul>
282
- <div class="clx"></div>
283
- <ul class="lst">
284
- <li><a class="fst" title="Tây Ban nha" href="/bong-da-tay-ban-nha">Tây Ban nha</a></li>
285
- <li><a title="Đội tuyển TBN" href="/doi-tuyen-tay-ban-nha">Đội tuyển TBN</a></li>
286
- <li><a title="La Liga" href="/la-liga">La Liga</a></li>
287
- <li><a title="Cúp Nhà Vua" href="/cup-nha-vua-tay-ban-nha">Cúp Nhà Vua</a></li>
288
- </ul>
289
- </li>
290
- <li class="exp"></li>
291
- <li>
292
- <ul class="lst">
293
- <li><a class="fst" title="Bóng đá Pháp" href="/bong-da-phap">Bóng đá Pháp</a></li>
294
- <li><a title="Đội tuyển Pháp" href="/doi-tuyen-phap">Đội tuyển Pháp</a></li>
295
- <li><a title="Ligue 1" href="/ligue-1">Ligue 1</a></li>
296
- <li><a title="Cúp QG Pháp" href="/cup-quoc-gia-phap">Cúp QG Pháp</a></li>
297
- <li><a title="Cúp Liên đoàn Pháp" href="/cup-lien-doan-phap-tags">Cúp Liên đoàn Pháp</a></li>
298
- </ul>
299
- </li>
300
- <li>
301
- <ul class="lst">
302
- <li><a class="fst" href="#">Bóng đá Khu vực</a></li>
303
- <li><a title="Asian Cup" href="/asian-cup">Asian Cup</a></li>
304
- <li><a title="Asian Games" href="/asian-games">Asian Games</a></li>
305
- <li><a title="AFF Cup" href="/aff-cup">AFF Cup</a></li>
306
- <li><a title="SEA Games" href="/sea-games">SEA Games</a></li>
307
- </ul>
308
- </li>
309
- <li class="exp"></li>
310
- <li>
311
- <ul class="lst">
312
- <li><a class="fst" title="Bóng đá Italia" href="/bong-da-y">Bóng đá Italia</a></li>
313
- <li><a title="Đội tuyển Italia" href="/doi-tuyen-y">Đội tuyển Italia</a></li>
314
- <li><a title="Serie A" href="/serie-a">Serie A</a></li>
315
- <li><a title="Coppa Italia" href="/coppa-italia">Coppa Italia</a></li>
316
- </ul>
317
- </li>
318
- <li>
319
- <ul class="lst">
320
- <li><a class="fst" title="Bóng đá Đức" href="/bong-da-duc">Bóng đá Đức</a></li>
321
- <li><a title="Đội tuyển Đức" href="/doi-tuyen-duc">Đội tuyển Đức</a></li>
322
- <li><a title="Bundesliga" href="/bundesliga">Bundesliga</a></li>
323
- <li><a title="Cúp QG Đức" href="/cup-quoc-gia-duc">Cúp QG Đức</a></li>
324
- </ul>
325
- </li>
326
- <li class="exp"></li>
327
- <li>
328
- <ul class="lst">
329
- <li><a class="fst" href="#">Nội dung Đặc biệt</a></li>
330
- <li><a title="Big Story" href="/emagazine">Big Story</a></li>
331
- <li><a title="X-File" href="/x-file">X-File</a></li>
332
- <li><a title="Infographic" href="/infographic">Infographic</a></li>
333
- <li><a title="Interactive" href="/interactive">Interactive</a></li>
334
- </ul>
335
- </li>
336
- <li>
337
- <ul class="lst">
338
- <li><a class="fst" href="#">Giải đấu CLB</a></li>
339
- <li><a title="Champions Leage" href="/champions-league-cup-c1">Champions League</a></li>
340
- <li><a title="Europa League" href="/europa-league">Europa League</a></li>
341
- <li><a title="Club World Cup" href="/fifa-club-world-cup-tags">Club World Cup</a></li>
342
- <li><a title="Europa Conference League" href="/europa-conference-league">Europa Conf League</a></li>
343
- </ul>
344
- </li>
345
- <li class="exp"></li>
346
- <li>
347
- <ul class="lst">
348
- <li><a class="fst" href="#">Chuyên đề</a></li>
349
- <li><a title="Tin chuyển nhượng" href="/tin-chuyen-nhuong">Chuyển nhượng</a></li>
350
- <li><a title="Hậu trường bóng đá" href="/hau-truong-bong-da">Hậu trường</a></li>
351
- <li><a title="Điểm tin" href="/diem-tin">Điểm tin</a></li>
352
- <li><a title="Showbiz Ngôi sao" href="/ngoi-sao-showbiz">Showbiz Ngôi sao</a></li>
353
- <li><a title="Góc check var" href="/goc-check-var">Góc check var</a></li>
354
- <li><a title="Công nghệ" href="/cong-nghe">Công nghệ</a></li>
355
- <li><a title="Thông tin Thị trường" href="/thi-truong">Thị trường</a></li>
356
- <li><a title="Bóng đá & Cuộc sống" href="/bong-da-cuoc-song">Bóng đá & Cuộc sống</a></li>
357
- </ul>
358
- </li>
359
- <li>
360
- <ul class="lst">
361
- <li><a class="fst" href="#">Đội tuyển</a></li>
362
- <li><a title="World Cup nữ 2028" href="/world-cup-nu-2023-tags">World Cup nữ 2028</a></li>
363
- <li><a title="World Cup" href="/world-cup">World Cup 2026</a></li>
364
- <li><a title="European Championship 2028" href="/euro-cup-chau-au">EURO 2028</a></li>
365
- <li><a title="Nations League" href="/nations-league">Nations League</a></li>
366
- <li><a title="Copa America" href="/copa-america">Copa America</a></li>
367
- <li><a title="CAN" href="/can">CAN</a></li>
368
- <li><a title="Olympic 2028" href="/olympic">Olympic 2028</a></li>
369
- </ul>
370
- </li>
371
- <li class="exp"></li>
372
- <li>
373
- <ul class="lst">
374
- <li><a class="fst" title="Multimedia" href="/video">Multimedia</a></li>
375
- </ul>
376
- </li>
377
- <li>
378
- <ul class="lst">
379
- <li>&nbsp;</li>
380
- </ul>
381
- </li>
382
- <li class="exp"></li>
383
- <li>
384
- <ul class="lst">
385
- <li><a class="fst" href="/lich-thi-dau-bong-da">Lịch thi đấu</a></li>
386
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-viet-nam" title="Lịch thi đấu V.League">V.League</a></li>
387
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-anh" title="Lịch thi đấu Ngoại hạng Anh">Ngoại hạng Anh</a></li>
388
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-phap" title="Lịch thi đấu Ligue 1 Pháp">Ligue 1</a></li>
389
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-tay-ban-nha" title="Lịch thi đấu La Liga Tây Ban Nha">La Liga</a></li>
390
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-duc" title="Lịch thi đấu Bundesliga Đức">Bundesliga</a></li>
391
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?bong-da-y" title="Lịch thi đấu Serie A Italia">Serie A</a></li>
392
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?champions-league-cup-c1" title="Lịch thi đấu Champions League">Champions League</a></li>
393
- <li class="hide-m"><a href="/lich-thi-dau-bong-da?europa-league" title="Lịch thi đấu Europa League">Europa League</a></li>
394
- </ul>
395
- </li>
396
- <li>
397
- <ul class="lst">
398
- <li><a class="fst" href="/bang-xep-hang-bong-da">Bảng xếp hạng</a></li>
399
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-viet-nam" title="Bảng xếp hạng V.League">V.League</a></li>
400
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-anh" title="Bảng xếp hạng Ngoại hạng Anh">Ngoại hạng Anh</a></li>
401
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-phap" title="Bảng xếp hạng Ligue 1 Pháp">Ligue 1</a></li>
402
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-tay-ban-nha" title="Bảng xếp hạng La Liga Tây Ban Nha">La Liga</a></li>
403
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-duc" title="Bảng xếp hạng Bundesliga Đức">Bundesliga</a></li>
404
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?bong-da-y" title="Bảng xếp hạng Serie A Italia">Serie A</a></li>
405
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?champions-league-cup-c1" title="Bảng xếp hạng Champions League">Champions League</a></li>
406
- <li class="hide-m"><a href="/bang-xep-hang-bong-da?europa-league" title="Bảng xếp hạng Europa League">Europa League</a></li>
407
- </ul>
408
- </li>
409
- <li class="exp"></li>
410
- <li><a class="caption" href="https://phui.bongdaplus.vn" target="_blank">Bóng đá phủi</a></li>
411
- <li><a class="caption" href="/tennis">Tennis</a></li>
412
- <li><a class="caption" href="/esports">Esports</a></li>
413
- <li><a class="caption" href="/the-thao">Thể thao +</a></li>
414
- </ul>
415
- </div>
416
- </div>
417
- <div class="mmnu-end tx-cen">
418
- <p>Theo dõi thông tin</p>
419
- <ul class="bar social-lnk">
420
- <li class="hide-m">Theo dõi thông tin</li>
421
- <li><a class="ico vff-lnk" target="_blank" href="https://vff.org.vn/" style="background-size:28px;opacity:1;" rel="nofollow"></a></li>
422
- <li><a class="ico fb-lnk" target="_blank" href="https://www.facebook.com/BaoBongDa/" style="background-size:28px;opacity:1;"></a></li>
423
- <li><a class="ico yt-lnk" target="_blank" href="https://www.youtube.com/channel/UCF0VFBZu-5SRJXMV_FMysEA" style="background-size:28px;opacity:1;"></a></li>
424
- </ul>
425
- </div>
426
- </div>
427
- <div class="mega-menu">
428
- <div class="cont-wrap">
429
- <div class="menu-row">
430
- <ul class="bar">
431
- <li><a class="caption" title="Tin mới nhất" href="/tin-moi">Mới nhất</a></li>
432
- <li>
433
- <ul class="lst">
434
- <li><a class="fst" title="Bóng đá Việt Nam" href="/bong-da-viet-nam">Bóng đá Việt Nam</a></li>
435
- <li><a title="Đội tuyển Việt Nam" href="/doi-tuyen-quoc-gia-viet-nam">Đội tuyển Việt Nam</a></li>
436
- <li><a title="V.League" href="/v-league">V.League</a></li>
437
- <li><a title="Hạng Nhất" href="/hang-nhat-viet-nam">Hạng Nhất</a></li>
438
- <li><a title="Cúp Quốc gia" href="/cup-quoc-gia-viet-nam">Cúp Quốc gia</a></li>
439
- <li><a title="Cúp châu Á" href="/asian-cup">Cúp châu Á</a></li>
440
- <li><a title="Bóng đá nữ" href="/bong-da-nu-viet-nam">Bóng đá nữ</a></li>
441
- <li><a title="Futsal" href="/futsal">Futsal</a></li>
442
- <li><a title="Phong trào" href="/bong-da-phong-trao">Phong trào</a></li>
443
- <li><a title="Chuyển nhượng V.League" href="/tin-chuyen-nhuong-v-league">Chuyển nhượng V.League</a></li>
444
- <li><a title="Tin khác" href="/tin-khac">Tin khác</a></li>
445
- </ul>
446
- </li>
447
-
448
- <li>
449
- <ul class="lst">
450
- <li><a class="fst" title="Bóng đá Anh" href="/bong-da-anh">Bóng đá Anh</a></li>
451
- <li><a title="Đội tuyển Anh" href="/doi-tuyen-anh">Đội tuyển Anh</a></li>
452
- <li><a title="Ngoại hạng Anh" href="/ngoai-hang-anh">Ngoại hạng Anh</a></li>
453
- <li><a title="FA Cup" href="/fa-cup">FA Cup</a></li>
454
- <li><a title="League Cup" href="/cup-lien-doan-anh">League Cup</a></li>
455
- </ul>
456
- <div class="clx"></div>
457
- <ul class="lst">
458
- <li><a class="fst" href="#">Giải đấu CLB</a></li>
459
- <li><a title="Champions Leage" href="/champions-league-cup-c1">Champions League</a></li>
460
- <li><a title="Europa League" href="/europa-league">Europa League</a></li>
461
- <li><a title="Club World Cup" href="/fifa-club-world-cup-tags">Club World Cup</a></li>
462
- <li><a title="Europa Conference League" href="/europa-conference-league">Europa Conference League</a></li>
463
- </ul>
464
- </li>
465
-
466
- <li>
467
- <ul class="lst">
468
- <li><a class="fst" title="Bóng đá Italia" href="/bong-da-y">Bóng đá Italia</a></li>
469
- <li><a title="Đội tuyển Italia" href="/doi-tuyen-y">Đội tuyển Italia</a></li>
470
- <li><a title="Serie A" href="/serie-a">Serie A</a></li>
471
- <li><a title="Coppa Italia" href="/coppa-italia">Coppa Italia</a></li>
472
- </ul>
473
- <div class="clx"></div>
474
- <ul class="lst">
475
- <li><a class="fst" href="#">Đội tuyển</a></li>
476
- <li><a title="World Cup nữ 2028" href="/world-cup-nu-2023-tags">World Cup nữ 2028</a></li>
477
- <li><a title="World Cup" href="/world-cup">World Cup 2026</a></li>
478
- <li><a title="European Championship 2028" href="/euro-cup-chau-au">EURO 2028</a></li>
479
- <li><a title="Nations League" href="/nations-league">Nations League</a></li>
480
- <li><a title="Copa America" href="/copa-america">Copa America</a></li>
481
- <li><a title="CAN" href="/can">CAN</a></li>
482
- <li><a title="Olympic" href="/olympic">Olympic 2028</a></li>
483
- </ul>
484
- </li>
485
-
486
- <li>
487
- <ul class="lst">
488
- <li><a class="fst" title="Bóng đá Pháp" href="/bong-da-phap">Bóng đá Pháp</a></li>
489
- <li><a title="Đội tuyển Pháp" href="/doi-tuyen-phap">Đội tuyển Pháp</a></li>
490
- <li><a title="Ligue 1" href="/ligue-1">Ligue 1</a></li>
491
- <li><a title="Cúp QG Pháp" href="/cup-quoc-gia-phap">Cúp QG Pháp</a></li>
492
- <li><a title="Cúp Liên đoàn Pháp" href="/cup-lien-doan-phap-tags">Cúp Liên đoàn Pháp</a></li>
493
- </ul>
494
- <div class="clx"></div>
495
- <ul class="lst">
496
- <li><a class="fst" href="#">Khu vực</a></li>
497
- <li><a title="Asian Cup" href="/asian-cup">Asian Cup</a></li>
498
- <li><a title="Asian Games" href="/asian-games">Asian Games</a></li>
499
- <li><a title="AFF Cup" href="/aff-cup">AFF Cup</a></li>
500
- <li><a title="SEA Games" href="/sea-games">SEA Games</a></li>
501
- </ul>
502
- </li>
503
-
504
- <li>
505
- <ul class="lst">
506
- <li><a class="fst" title="Tây Ban nha" href="/bong-da-tay-ban-nha">Tây Ban nha</a></li>
507
- <li><a title="Đội tuyển TBN" href="/doi-tuyen-tay-ban-nha">Đội tuyển TBN</a></li>
508
- <li><a title="La Liga" href="/la-liga">La Liga</a></li>
509
- <li><a title="Cúp Nhà Vua" href="/cup-nha-vua-tay-ban-nha">Cúp Nhà Vua</a></li>
510
- </ul>
511
- <div class="clx"></div>
512
- <ul class="lst">
513
- <li><a class="fst" href="#">Chuyên đề</a></li>
514
- <li><a title="Tin chuyển nhượng" href="/tin-chuyen-nhuong">Chuyển nhượng</a></li>
515
- <li><a title="Hậu trường bóng đá" href="/hau-truong-bong-da">Hậu trường</a></li>
516
- <li><a title="Điểm tin" href="/diem-tin">Điểm tin</a></li>
517
- <li><a title="Showbiz Ngôi sao" href="/ngoi-sao-showbiz">Showbiz Ngôi sao</a></li>
518
- <li><a title="Góc check var" href="/goc-check-var">Góc check var</a></li>
519
- <li><a title="Công nghệ" href="/cong-nghe">Công nghệ</a></li>
520
- <li><a title="Thông tin Thị trường" href="/thi-truong">Thị trường</a></li>
521
- </ul>
522
- </li>
523
-
524
- <li>
525
- <ul class="lst">
526
- <li><a class="fst" title="Bóng đá Đức" href="/bong-da-duc">Bóng đá Đức</a></li>
527
- <li><a title="Đội tuyển Đức" href="/doi-tuyen-duc">Đội tuyển Đức</a></li>
528
- <li><a title="Bundesliga" href="/bundesliga">Bundesliga</a></li>
529
- <li><a title="Cúp QG Đức" href="/cup-quoc-gia-duc">Cúp QG Đức</a></li>
530
- </ul>
531
- <div class="clx"></div>
532
- <ul class="lst">
533
- <li><a class="fst" href="#">Đặc biệt</a></li>
534
- <li><a title="Big Story" href="/emagazine">Big Story</a></li>
535
- <li><a title="X-File" href="/x-file">X-File</a></li>
536
- <li><a title="Infographic" href="/infographic">Infographic</a></li>
537
- <li><a title="Interactive" href="/interactive">Interactive</a></li>
538
- </ul>
539
- </li>
540
- </ul>
541
- </div>
542
-
543
- <div class="menu-row">
544
- <ul class="bar">
545
- <li>&nbsp;</li>
546
- <li><a title="Tin chuyển nhượng" href="/tin-chuyen-nhuong">Tin chuyển nhượng</a></li>
547
- <li><a title="Bóng đá & Cuộc sống" href="/bong-da-cuoc-song">Bóng đá & Cuộc sống</a></li>
548
- <li><a title="Thông tin Thị trường" href="/thi-truong">Thông tin Thị trường</a></li>
549
- <li><a title="Tin tức Công nghệ" href="/cong-nghe">Công nghệ</a></li>
550
- <li><a title="Tin tức Xe auto bike" href="/xe-co">Xe auto</a></li>
551
- </ul>
552
- </div>
553
-
554
- <div class="menu-row">
555
- <ul class="bar">
556
- <li>&nbsp;</li>
557
- <li><a class="caption" title="Nhận định Bóng đá" href="/nhan-dinh-bong-da-tags">Nhận định</a></li>
558
- <li><a class="caption" title="Tư vấn Bóng đá" href="/soi-keo-bong-da">Tư vấn</a></li>
559
- <li><a class="caption" title="Multimedia" href="/video">Multimedia</a></li>
560
- <li><a class="caption" title="Youtube" target="_blank" href="https://www.youtube.com/channel/UCF0VFBZu-5SRJXMV_FMysEA">Youtube</a></li>
561
- <li><a class="caption" title="Facebook fanpage" target="_blank" href="https://www.facebook.com/BaoBongDa">FB Fanpage</a></li>
562
- <li>
563
- <a class="caption" title="Premium" href="/premium">Premium <i class="ico crown"></i></a>
564
- </li>
565
- </ul>
566
- </div>
567
-
568
- <div class="menu-row">
569
- <ul class="bar">
570
- <li><a class="caption" href="/lich-thi-dau-bong-da">Lịch thi đấu</a></li>
571
- <li>
572
- <ul class="lst">
573
- <li><a class="fst" href="/lich-thi-dau-bong-da">Lịch thi đấu hôm nay</a></li>
574
- <li><a href="/lich-thi-dau-bong-da?bong-da-viet-nam" title="Lịch thi đấu V.League">V.League</a></li>
575
- <li><a href="/lich-thi-dau-bong-da?bong-da-anh" title="Lịch thi đấu Ngoại hạng Anh">Ngoại hạng Anh</a></li>
576
- <li><a href="/lich-thi-dau-bong-da?bong-da-phap" title="Lịch thi đấu Ligue 1 Pháp">Ligue 1</a></li>
577
- <li><a href="/lich-thi-dau-bong-da?bong-da-tay-ban-nha" title="Lịch thi đấu La Liga Tây Ban Nha">La Liga</a></li>
578
- <li><a href="/lich-thi-dau-bong-da?bong-da-duc" title="Lịch thi đấu Bundesliga Đức">Bundesliga</a></li>
579
- <li><a href="/lich-thi-dau-bong-da?bong-da-y" title="Lịch thi đấu Serie A Italia">Serie A</a></li>
580
- <li><a href="/lich-thi-dau-bong-da?champions-league-cup-c1" title="Lịch thi đấu Champions League">Champions League</a></li>
581
- <li><a href="/lich-thi-dau-bong-da?europa-league" title="Lịch thi đấu Europa League">Europa League</a></li>
582
- </ul>
583
- </li>
584
-
585
- <li>
586
- <ul class="lst">
587
- <li><a class="fst" href="/ket-qua-bong-da">Kết quả mới nhất</a></li>
588
- <li><a href="/lich-thi-dau-bong-da?bong-da-viet-nam" title="Kết quả V.League">V.League</a></li>
589
- <li><a href="/lich-thi-dau-bong-da?bong-da-anh" title="Kết quả Ngoại hạng Anh">Ngoại hạng Anh</a></li>
590
- <li><a href="/lich-thi-dau-bong-da?bong-da-phap" title="Kết quả Ligue 1 Pháp">Ligue 1</a></li>
591
- <li><a href="/lich-thi-dau-bong-da?bong-da-tay-ban-nha" title="Kết quả La Liga Tây Ban Nha">La Liga</a></li>
592
- <li><a href="/lich-thi-dau-bong-da?bong-da-duc" title="Kết quả Bundesliga Đức">Bundesliga</a></li>
593
- <li><a href="/lich-thi-dau-bong-da?bong-da-y" title="Kết quả Serie A Italia">Serie A</a></li>
594
- <li><a href="/lich-thi-dau-bong-da?champions-league-cup-c1" title="Kết quả Champions League">Champions League</a></li>
595
- <li><a href="/lich-thi-dau-bong-da?europa-league" title="Kết quả Europa League">Europa League</a></li>
596
- </ul>
597
- </li>
598
-
599
- <li>
600
- <ul class="lst">
601
- <li><a class="fst" href="#">Bảng xếp hạng</a></li>
602
- <li><a href="/bang-xep-hang-bong-da?bong-da-viet-nam" title="Bảng xếp hạng V.League">V.League</a></li>
603
- <li><a href="/bang-xep-hang-bong-da?bong-da-anh" title="Bảng xếp hạng Ngoại hạng Anh">Ngoại hạng Anh</a></li>
604
- <li><a href="/bang-xep-hang-bong-da?bong-da-phap" title="Bảng xếp hạng Ligue 1 Pháp">Ligue 1</a></li>
605
- <li><a href="/bang-xep-hang-bong-da?bong-da-tay-ban-nha" title="Bảng xếp hạng La Liga Tây Ban Nha">La Liga</a></li>
606
- <li><a href="/bang-xep-hang-bong-da?bong-da-duc" title="Bảng xếp hạng Bundesliga Đức">Bundesliga</a></li>
607
- <li><a href="/bang-xep-hang-bong-da?bong-da-y" title="Bảng xếp hạng Serie A Italia">Serie A</a></li>
608
- <li><a href="/bang-xep-hang-bong-da?champions-league-cup-c1" title="Bảng xếp hạng Champions League">Champions League</a></li>
609
- <li><a href="/bang-xep-hang-bong-da?europa-league" title="Bảng xếp hạng Europa League">Europa League</a></li>
610
- </ul>
611
- </li>
612
-
613
- <li>
614
- <ul class="lst">
615
- <li><a class="caption" href="https://phui.bongdaplus.vn" target="_blank">Bóng đá phủi</a></li>
616
- <li><a class="caption" href="/tennis">Tennis</a></li>
617
- </ul>
618
- </li>
619
- <li>
620
- <ul class="lst">
621
- <li><a class="caption" href="/esports">Esports</a></li>
622
- <li><a class="caption" href="/the-thao">Thể thao +</a></li>
623
- </ul>
624
- </li>
625
-
626
- <li>
627
- <ul class="lst">
628
- <li>
629
- <div class="copyr">
630
- <div class="splt hide-w"></div>
631
- <p><b class="allcap">Tạp chí Bóng Đá</b></p>
632
- <p>Giấy phép số 48/GP-BTTTT cấp ngày 05/02/2020</p>
633
- <p>&nbsp;</p>
634
- <p>
635
- Tổng biên tập:<br /> <b>Vũ Khắc Sơn</b><br />
636
- Phó tổng biên tập:<br /> <b>Nguyễn Hà Thanh</b>
637
- </p>
638
- <p>&nbsp;</p>
639
- <p>
640
- <a class="contact-showr" href="#">Thông tin tòa soạn</a><br />
641
- <a class="contact-showr" href="#">Liên hệ quảng cáo</a>
642
- </p>
643
- <p>Liên đoàn BĐVN <a href="https://vff.org.vn/" target="_blank" rel="nofollow"><img alt="VFF" src="/img/logo_Vff.png" style="width:28px;" /></a></p>
644
- </div>
645
- </li>
646
- </ul>
647
- </li>
648
- </ul>
649
- </div>
650
- </div>
651
- </div>
652
- <div class="menu-tags hide-w">
653
- <div class="today"></div>
654
- <div class="mtags">
655
- <a title="#HighlightBóngđá" href="/video/highlight">#HighlightBóngđá</a>
656
- <a title="#PremierLeague" href="/ngoai-hang-anh">#PremierLeague</a>
657
- <a title="#V.League" href="/v-league">#V.League</a>
658
- </div>
659
- </div>
660
-
661
- <div id="fxtSlideCover" class="fixt-strm" style="margin-bottom:5px;">
662
- <div class="cont-wrap">
663
- <a class="brand" href="https://admin.giaminhmedia.vn/www/delivery/cl.php?bannerid=1411&zoneid=328&sig=8300d1283663cec85d90499507ffd94240954967132167c0f302d7388b8f9bb5&dest=http%3A%2F%2Fadmin.giaminhmedia.vn%2Fwww%2Funiscore.php" target="_blank" rel="nofollow" style="margin-left:5px;">
664
- <img alt="" src="https://bongdaplus.vn/img/logouniscore-tiny.png">
665
- </a>
666
- <ul id="fxtSlide" class="nav"></ul>
667
- </div>
668
- </div>
669
-
670
- <div class="clz"></div>
671
- <div id="ADTOP" class="banner adweb admob" banner-adpos="top"></div>
672
-
673
- <section class="bread-crums">
674
- <div class="clz"></div>
675
- <div class="cont-wrap">
676
- <div class="chain-navs">
677
- <a href="/video">Multimedia</a>&raquo;
678
- </div>
679
- </div>
680
- </section>
681
-
682
- <section class="media-box">
683
- <div class="clz"></div>
684
- <div class="cont-wrap video-box">
685
- <div class="row">
686
- <div class="col m12 w8 clip-box">
687
- <div class="play-box rbox">
688
- <iframe id="ytbFrBpl" class="play-frame" src="https://www.youtube.com/embed/Qokb_8w6p0s?si=QNKAZIYxNrtn2hSN" cid="UCmn1v6lrIDZghUfbxXaorUw" vnum="0" class="latestVideoEmbed" title="Bongdaplus trên Youtube" frameborder="0" allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe>
689
- </div>
690
- </div>
691
-
692
- <div class="col m12 w4 clip-cont">
693
- <div class="ovrscrl">
694
- <div class="clip-info">
695
- <h1 class="title">Hull City vs MU: Quỷ Đỏ vào hang bắt hổ</h1>
696
- <p class="desc">
697
- Mùa giải Premier League 2026/27 của MU sẽ mở màn bằng chuyến làm khách đầy thử thách trước tân binh Hull City tại sân MKM. Cuộc đối đầu Hull City vs MU là màn chạm trán đáng chú ý khi “Đàn Hổ” đang tràn đầy khí thế, trong khi Quỷ đỏ không được phép sảy chân nếu muốn sớm tạo đà cho cuộc đua vô địch.
698
- </p>
699
-
700
- <div>08:07 - 22/08/2026</div>
701
- <div class="editor"></div>
702
- <div class="hash-tags">
703
- <b>Tags:</b>
704
- <a href="/video/hull-city-vs-mu-tags">Hull City vs MU</a>
705
- <a href="/video/nhan-dinh-hull-city-vs-mu-tags">nh&#x1EAD;n &#x111;&#x1ECB;nh Hull City vs MU</a>
706
- <a href="/video/premier-league-tags">Premier League</a>
707
- <a href="/video/mu-tags">MU</a>
708
- </div>
709
- <style>
710
- .emobar .emo:not(:empty) {
711
- background-position: left 10px top 50%;
712
- padding: 0 13px 0 36px;
713
- }
714
- .emobar .emo {
715
- border-radius: 16px;
716
- background-color: #d7d3d3;
717
- background-size: auto 18px;
718
- cursor: pointer;
719
- margin: 0 3px;
720
- padding: 0 16px;
721
- line-height: 32px;
722
- height: 32px;
723
- }
724
- .emopicked {
725
- border: solid 1px #767676;
726
- }
727
- </style>
728
- <div class="emobar tx-cen">
729
- <div class="clx"></div>
730
- <a class="emo like" onclick="btnNewsEmotion_click(1)" id="btnEmo1"> <span id="numemo1"></span></a>
731
- <a class="emo heart" onclick="btnNewsEmotion_click(2)" id="btnEmo2"> <span id="numemo2"></span></a>
732
- <a class="emo star" onclick="btnNewsEmotion_click(4)" id="btnEmo4"> <span id="numemo4"></span></a>
733
- <a class="emo comment" id="ncmt" href="#commenting" data-action="comment" data-act-only="true"></a>
734
- </div>
735
- </div>
736
- </div>
737
- </div>
738
- </div>
739
- </div>
740
-
741
- <div class="clx"></div>
742
- <div class="cont-view">
743
-
744
-
745
-
746
-
747
- <style>
748
- .btnlikedislikecmt {
749
- border-radius: 9px;
750
- border: solid 1px #767676;
751
- background-color: #cecece;
752
- }
753
-
754
- sup {
755
- padding: 3px;
756
- position: initial;
757
- vertical-align: initial;
758
- }
759
-
760
- .TopComment {
761
- border: solid 1px #fdd835;
762
- }
763
-
764
- .TopComment .info .member {
765
- color: red;
766
- }
767
-
768
- .TopComment .info .avatar {
769
- border: solid 1px red;
770
- }
771
-
772
- .comment .summ .replyat {
773
- /*color: #1b5e20;*/
774
- display: inline-block;
775
- margin: 0 8px 0 0;
776
- font-weight: bold;
777
- /* text-decoration: underline; */
778
- }
779
- </style>
780
- <div id="postComment" class="comm-zone">
781
- <a class="anchor" name="#comments"></a>
782
- <div class="clz"></div>
783
- <div class="xcap">Bình luận</div>
784
- <div class="clz"></div>
785
- <div class="comm-post ">
786
- <div id="formcomment" class="comm-form">
787
- <label class="txt-fld">
788
- <textarea id="txtcomment_0" name="txtcomment_0" maxlength="1000" placeholder="Hãy chia sẻ suy nghĩ của bạn..." onclick="showcommentloginform();"></textarea>
789
- </label>
790
- <div class="actions">
791
- <button id="btnComment" class="btn btn-send base" onclick="btnComment_click(0,0)">Gửi</button>
792
- </div>
793
- <center><div class="cmterr"></div></center>
794
- </div>
795
- </div>
796
- <div class="clz"></div>
797
- <div class="comm-frame">
798
- <div id="NewsComments"></div>
799
- <div class="clz"></div>
800
- <div class="cat-news">
801
- <div id="btnloadviewmore" class="view-more hide"><a onclick="loadviewmorecomment();">Xem thêm</a></div>
802
- </div>
803
- <div class="clz"></div>
804
- </div>
805
- </div>
806
- </div>
807
- <div class="clz"></div>
808
- </section>
809
-
810
-
811
-
812
-
813
-
814
- <div class="clx"></div>
815
- <center><div id="ADHOT" class="banner adweb admob" banner-adpos="hot"></div></center>
816
- <div class="clx"></div>
817
-
818
-
819
- <section class="cat-news">
820
- <div class="cont-wrap">
821
- <div class="capt-cover">
822
- <div class="caption">Video mới nhất</div>
823
- <button class="more-lnk"></button>
824
- </div>
825
- <div class="row flex">
826
- <div class="col m12 w3">
827
- <div class="news">
828
- <a class="thumb" href="/video/du-doan-ty-so-hull-mu-than-rua-ali-33-chon-doi-nao-982702608.html"><img alt="Dự đoán tỷ số Hull vs MU: Thần Rùa Ali 33 chọn đội nào?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/18/80/Anh-chu-480-x-270.jpg" /></a>
829
- <a class="title" href="/video/du-doan-ty-so-hull-mu-than-rua-ali-33-chon-doi-nao-982702608.html">Dự đoán tỷ số Hull vs MU: Thần Rùa Ali 33 chọn đội nào?</a>
830
- <span class="info">
831
- 42 ph&#xFA;t tr&#x1B0;&#x1EDB;c
832
- </span>
833
- <span class="info">
834
- </span>
835
- </div>
836
- </div>
837
- <div class="col m12 w3">
838
- <div class="news">
839
- <a class="thumb" href="/video/hull-city-vs-mu-quy-do-vao-hang-bat-ho-982672608.html"><img alt="Hull City vs MU: Quỷ Đỏ vào hang bắt hổ" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/18/13/ThumbHullvsMU-up.jpg" /></a>
840
- <a class="title" href="/video/hull-city-vs-mu-quy-do-vao-hang-bat-ho-982672608.html">Hull City vs MU: Quỷ Đỏ vào hang bắt hổ</a>
841
- <span class="info">
842
- 43 ph&#xFA;t tr&#x1B0;&#x1EDB;c
843
- </span>
844
- <span class="info">
845
- </span>
846
- </div>
847
- </div>
848
- <div class="col m12 w3">
849
- <div class="news">
850
- <a class="thumb" href="/video/du-doan-ty-so-brentford-vs-tottenham-premier-league-2026-27-than-rua-ali-33-chon-doi-nao-982862608.html"><img alt="Dự đoán tỷ số Brentford vs Tottenham: Thần Rùa Ali 33 chọn đội nào?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/19/80/Brentford-vs-Tottenham-480-x-270-moi.jpg" /></a>
851
- <a class="title" href="/video/du-doan-ty-so-brentford-vs-tottenham-premier-league-2026-27-than-rua-ali-33-chon-doi-nao-982862608.html">Dự đoán tỷ số Brentford vs Tottenham: Thần Rùa Ali 33 chọn đội nào?</a>
852
- <span class="info">
853
- 43 ph&#xFA;t tr&#x1B0;&#x1EDB;c
854
- </span>
855
- <span class="info">
856
- </span>
857
- </div>
858
- </div>
859
- <div class="col m12 w3">
860
- <div class="news">
861
- <a class="thumb" href="/video/brentford-vs-tottenham-de-zerbi-vuot-ai-gtech-982822608.html"><img alt="Brentford vs Tottenham: De Zerbi vượt ải Gtech" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/19/13/Brenfort-vs-Tottenham.jpg" /></a>
862
- <a class="title" href="/video/brentford-vs-tottenham-de-zerbi-vuot-ai-gtech-982822608.html">Brentford vs Tottenham: De Zerbi vượt ải Gtech</a>
863
- <span class="info">
864
- 43 ph&#xFA;t tr&#x1B0;&#x1EDB;c
865
- </span>
866
- <span class="info">
867
- </span>
868
- </div>
869
- </div>
870
- <div class="col m12 w3">
871
- <div class="news">
872
- <a class="thumb" href="/video/du-doan-ty-so-arsenal-vs-coventry-than-rua-ali-33-chon-doi-nao-982612608.html"><img alt="Dự đoán tỷ số Arsenal vs Coventry: Thần Rùa Ali 33 chọn đội nào?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/17/0/thumblai.jpg" /></a>
873
- <a class="title" href="/video/du-doan-ty-so-arsenal-vs-coventry-than-rua-ali-33-chon-doi-nao-982612608.html">Dự đoán tỷ số Arsenal vs Coventry: Thần Rùa Ali 33 chọn đội nào?</a>
874
- <span class="info">
875
- 09 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
876
- </span>
877
- <span class="info">
878
- </span>
879
- </div>
880
- </div>
881
- <div class="col m12 w3">
882
- <div class="news">
883
- <a class="thumb" href="/video/arsenal-vs-coventry-nha-vua-mo-man-bang-mot-chien-thang-982662608.html"><img alt="Arsenal vs Coventry: Nhà vua mở màn bằng một chiến thắng?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/18/13/ThumbArsenalvsCoventry-up.jpg" /></a>
884
- <a class="title" href="/video/arsenal-vs-coventry-nha-vua-mo-man-bang-mot-chien-thang-982662608.html">Arsenal vs Coventry: Nhà vua mở màn bằng một chiến thắng?</a>
885
- <span class="info">
886
- 09 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
887
- </span>
888
- <span class="info">
889
- </span>
890
- </div>
891
- </div>
892
- <div class="col m12 w3">
893
- <div class="news">
894
- <a class="thumb" href="/video/truc-tuyen-truoc-tran-arsenal-vs-coventry-hull-vs-mu-983222608.html"><img alt="Trực tuyến trước trận Arsenal vs Coventry, Hull vs MU" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/truc-tuyen-truoc-tran-Arsenal-vs-Coventry.jpg" /></a>
895
- <a class="title" href="/video/truc-tuyen-truoc-tran-arsenal-vs-coventry-hull-vs-mu-983222608.html">Trực tuyến trước trận Arsenal vs Coventry, Hull vs MU</a>
896
- <span class="info">
897
- 11 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
898
- </span>
899
- <span class="info">
900
- </span>
901
- </div>
902
- </div>
903
- <div class="col m12 w3">
904
- <div class="news">
905
- <a class="thumb" href="/video/dt-thai-lan-tap-cach-san-rajamangala-40km-hlv-anthony-hudson-chot-luon-doi-hinh-dau-viet-nam-983202608.html"><img alt=" ĐT Thái Lan tập cách sân Rajamangala 40km, HLV Anthony Hudson chốt luôn đội hình đấu Việt Nam" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/80/HLV-Thai-Lan-chot-doi-hinh.jpg" /></a>
906
- <a class="title" href="/video/dt-thai-lan-tap-cach-san-rajamangala-40km-hlv-anthony-hudson-chot-luon-doi-hinh-dau-viet-nam-983202608.html"> ĐT Thái Lan tập cách sân Rajamangala 40km, HLV Anthony Hudson chốt luôn đội hình đấu Việt Nam</a>
907
- <span class="info">
908
- 13 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
909
- </span>
910
- <span class="info">
911
- </span>
912
- </div>
913
- </div>
914
- <div class="col m12 w3">
915
- <div class="news">
916
- <a class="thumb" href="/video/tro-lai-san-tung-vo-dich-aff-cup-2024-dt-viet-nam-quyet-lam-nen-lich-su-983212608.html"><img alt=" Trở lại sân từng vô địch AFF Cup 2024, ĐT Việt Nam quyết làm nên lịch sử" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/80/Viet-Nam-tap-2-1-8.jpg" /></a>
917
- <a class="title" href="/video/tro-lai-san-tung-vo-dich-aff-cup-2024-dt-viet-nam-quyet-lam-nen-lich-su-983212608.html"> Trở lại sân từng vô địch AFF Cup 2024, ĐT Việt Nam quyết làm nên lịch sử</a>
918
- <span class="info">
919
- 14 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
920
- </span>
921
- <span class="info">
922
- </span>
923
- </div>
924
- </div>
925
- <div class="col m12 w3">
926
- <div class="news">
927
- <a class="thumb" href="/video/vong-1-premier-league-2026-27-lieu-co-cu-soc-983112608.html"><img alt="Nhận định Premier League vòng 1: Liệu có cú sốc?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/thumbvong1-480.jpg" /></a>
928
- <a class="title" href="/video/vong-1-premier-league-2026-27-lieu-co-cu-soc-983112608.html">Nhận định Premier League vòng 1: Liệu có cú sốc?</a>
929
- <span class="info">
930
- 14 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
931
- </span>
932
- <span class="info">
933
- </span>
934
- </div>
935
- </div>
936
- <div class="col m12 w3">
937
- <div class="news">
938
- <a class="thumb" href="/video/ronaldinho-gay-soc-46-tuoi-van-tro-lai-san-co-khoac-ao-clb-serie-c-983192608.html"><img alt="Ronaldinho gây sốc: 46 tuổi vẫn trở lại sân cỏ, khoác áo CLB Serie C" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/26/Ronaldinho480.jpg" /></a>
939
- <a class="title" href="/video/ronaldinho-gay-soc-46-tuoi-van-tro-lai-san-co-khoac-ao-clb-serie-c-983192608.html">Ronaldinho gây sốc: 46 tuổi vẫn trở lại sân cỏ, khoác áo CLB Serie C</a>
940
- <span class="info">
941
- 14 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
942
- </span>
943
- <span class="info">
944
- </span>
945
- </div>
946
- </div>
947
- <div class="col m12 w3">
948
- <div class="news">
949
- <a class="thumb" href="/video/arsenal-no-bom-tan-51-trieu-bang-de-va-hang-thu-983122608.html"><img alt="Arsenal nổ bom tấn 51 triệu bảng để vá hàng thủ" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/26/Konsa480.jpg" /></a>
950
- <a class="title" href="/video/arsenal-no-bom-tan-51-trieu-bang-de-va-hang-thu-983122608.html">Arsenal nổ bom tấn 51 triệu bảng để vá hàng thủ</a>
951
- <span class="info">
952
- 14 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
953
- </span>
954
- <span class="info">
955
- </span>
956
- </div>
957
- </div>
958
- <div class="col m12 w3">
959
- <div class="news">
960
- <a class="thumb" href="/video/truc-tuyen-hop-bao-viet-nam-hlv-kim-sang-sik-noi-gi-khi-pho-chu-tich-thai-lan-mia-mai-dan-nhap-tich-983182608.html"><img alt="Trực tuyến họp báo Việt Nam: HLV Kim Sang Sik nói gì khi Phó Chủ tịch Thái Lan mỉa mai dàn nhập tịch" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/anhliveVN.jpg" /></a>
961
- <a class="title" href="/video/truc-tuyen-hop-bao-viet-nam-hlv-kim-sang-sik-noi-gi-khi-pho-chu-tich-thai-lan-mia-mai-dan-nhap-tich-983182608.html">Trực tuyến họp báo Việt Nam: HLV Kim Sang Sik nói gì khi Phó Chủ tịch Thái Lan mỉa mai dàn nhập tịch</a>
962
- <span class="info">
963
- 16 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
964
- </span>
965
- <span class="info">
966
- </span>
967
- </div>
968
- </div>
969
- <div class="col m12 w3">
970
- <div class="news">
971
- <a class="thumb" href="/video/truc-tuyen-thai-lan-hop-bao-hlv-thach-dau-dt-viet-nam-983162608.html"><img alt=" Trực tuyến Thái Lan họp báo: HLV Anthony Hudson thách đấu ĐT Việt Nam" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/anhlivesua-480.jpg" /></a>
972
- <a class="title" href="/video/truc-tuyen-thai-lan-hop-bao-hlv-thach-dau-dt-viet-nam-983162608.html"> Trực tuyến Thái Lan họp báo: HLV Anthony Hudson thách đấu ĐT Việt Nam</a>
973
- <span class="info">
974
- 18 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
975
- </span>
976
- <span class="info">
977
- </span>
978
- </div>
979
- </div>
980
- <div class="col m12 w3">
981
- <div class="news">
982
- <a class="thumb" href="/video/ban-tin-21-8-dt-viet-nam-chiu-thong-ke-cuc-xau-truoc-chung-ket-thai-lan-choi-chieu-nhu-indo-983152608.html"><img alt="Bản tin 21/8: ĐT Việt Nam chịu thống kê cực xấu trước chung kết, Thái Lan chơi chiêu như Indo" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/Thumb-tin-nong-21-8-480-up.jpg" /></a>
983
- <a class="title" href="/video/ban-tin-21-8-dt-viet-nam-chiu-thong-ke-cuc-xau-truoc-chung-ket-thai-lan-choi-chieu-nhu-indo-983152608.html">Bản tin 21/8: ĐT Việt Nam chịu thống kê cực xấu trước chung kết, Thái Lan chơi chiêu như Indo</a>
984
- <span class="info">
985
- 18 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
986
- </span>
987
- <span class="info">
988
- </span>
989
- </div>
990
- </div>
991
- <div class="col m12 w3">
992
- <div class="news">
993
- <a class="thumb" href="/video/thai-lan-khoa-cdv-viet-nam-chi-3-000-ve-cho-tran-chung-ket-tai-rajamangala-983142608.html"><img alt="Thái Lan 'khóa' CĐV Việt Nam: Chỉ 3.000 vé cho trận chung kết tại Rajamangala" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/26/cdv.jpg" /></a>
994
- <a class="title" href="/video/thai-lan-khoa-cdv-viet-nam-chi-3-000-ve-cho-tran-chung-ket-tai-rajamangala-983142608.html">Thái Lan 'khóa' CĐV Việt Nam: Chỉ 3.000 vé cho trận chung kết tại Rajamangala</a>
995
- <span class="info">
996
- 20 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
997
- </span>
998
- <span class="info">
999
- </span>
1000
- </div>
1001
- </div>
1002
- <div class="col m12 w3">
1003
- <div class="news">
1004
- <a class="thumb" href="/video/truoc-tran-thai-lan-vs-viet-nam-svd-rajamagala-vang-tanh-hon-chua-ba-danh-983132608.html"><img alt="Trước trận Thái Lan vs Việt Nam: SVĐ Rajamagala vắng tanh hơn chùa Bà Đanh" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/livethumbYT-480.jpg" /></a>
1005
- <a class="title" href="/video/truoc-tran-thai-lan-vs-viet-nam-svd-rajamagala-vang-tanh-hon-chua-ba-danh-983132608.html">Trước trận Thái Lan vs Việt Nam: SVĐ Rajamagala vắng tanh hơn chùa Bà Đanh</a>
1006
- <span class="info">
1007
- 21 gi&#x1EDD; tr&#x1B0;&#x1EDB;c
1008
- </span>
1009
- <span class="info">
1010
- </span>
1011
- </div>
1012
- </div>
1013
- <div class="col m12 w3">
1014
- <div class="news">
1015
- <a class="thumb" href="/video/du-doan-ty-so-thai-lan-vs-viet-nam-than-rua-ali-33-chon-doi-nao-983092608.html"><img alt="Dự đoán tỷ số Thái Lan vs Việt Nam: Thần Rùa Ali 33 chọn đội nào?" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/20/80/ThumbRuaThaivsVietnam-480.jpg" /></a>
1016
- <a class="title" href="/video/du-doan-ty-so-thai-lan-vs-viet-nam-than-rua-ali-33-chon-doi-nao-983092608.html">Dự đoán tỷ số Thái Lan vs Việt Nam: Thần Rùa Ali 33 chọn đội nào?</a>
1017
- <span class="info">
1018
- 19:18 ng&#xE0;y 20/08/2026
1019
- </span>
1020
- <span class="info">
1021
- </span>
1022
- </div>
1023
- </div>
1024
- <div class="col m12 w3">
1025
- <div class="news">
1026
- <a class="thumb" href="/video/truyen-thong-anh-dac-biet-chu-y-den-ngoi-no-cua-dt-viet-nam-983072608.html"><img alt="Truyền thông Anh đặc biệt chú ý đến 'ngòi nổ' của ĐT Việt Nam" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/20/26/xuan-son.jpg" /></a>
1027
- <a class="title" href="/video/truyen-thong-anh-dac-biet-chu-y-den-ngoi-no-cua-dt-viet-nam-983072608.html">Truyền thông Anh đặc biệt chú ý đến 'ngòi nổ' của ĐT Việt Nam</a>
1028
- <span class="info">
1029
- 19:18 ng&#xE0;y 20/08/2026
1030
- </span>
1031
- <span class="info">
1032
- </span>
1033
- </div>
1034
- </div>
1035
- <div class="col m12 w3">
1036
- <div class="news">
1037
- <a class="thumb" href="/video/dt-viet-nam-co-mat-tai-thai-lan-ao-trang-van-chua-bi-thay-kim-vut-het-983082608.html"><img alt="ĐT Việt Nam có mặt tại Thái Lan, áo trắng vẫn chưa bị thầy Kim bỏ hết" src="https://cdn.bongdaplus.vn/assets/Media/2026/08/20/26/Kim-Sang-Sik.jpg" /></a>
1038
- <a class="title" href="/video/dt-viet-nam-co-mat-tai-thai-lan-ao-trang-van-chua-bi-thay-kim-vut-het-983082608.html">ĐT Việt Nam có mặt tại Thái Lan, áo trắng vẫn chưa bị thầy Kim bỏ hết</a>
1039
- <span class="info">
1040
- 17:32 ng&#xE0;y 20/08/2026
1041
- </span>
1042
- <span class="info">
1043
- </span>
1044
- </div>
1045
- </div>
1046
- </div>
1047
- </div>
1048
- <div class="clz"></div>
1049
- </section>
1050
-
1051
-
1052
-
1053
- <div class="clx"></div>
1054
- <center><div id="ADBOT" class="banner adweb admob" banner-adpos="footer"></div></center>
1055
- </main>
1056
-
1057
- <style>
1058
- .iframpanel {
1059
- width: 100%;
1060
- max-width: 500px;
1061
- height: 560px;
1062
- overflow: hidden;
1063
- }
1064
-
1065
- </style>
1066
- <div class="paner-wrap">
1067
- <div class="over-layer hide"></div>
1068
- <div id="loginview" class="login-box paner hide iframpanel">
1069
- <div class="pan-capt">
1070
- <i class="pan-close" data-action="hide"></i>
1071
- </div>
1072
-
1073
-
1074
- <iframe src="https://member.bongdaplus.vn/Identity/Account/Login?ReturnUrl=%2FHome%2FLoginFromBongdaplus" frameborder="0" style="overflow:hidden;height:100%;width:100%"></iframe>
1075
-
1076
- </div>
1077
- <div id="commentloginview" class="login-box paner hide iframpanel">
1078
-
1079
-
1080
- <iframe src="https://member.bongdaplus.vn/Identity/Account/Login?ReturnUrl=%2FHome%2FCommentLoginFromBongdaplus" frameborder="0" style="overflow:hidden;height:100%;width:100%"></iframe>
1081
-
1082
- </div>
1083
- </div>
1084
- <input type="hidden" id="txtFullname" value="" />
1085
- <input type="hidden" id="txtUserid" value="" />
1086
-
1087
-
1088
-
1089
-
1090
-
1091
-
1092
- <center><div id="ADFT" class="banner adweb admob" banner-adpos="footer"></div></center>
1093
- <footer>
1094
- <div class="cont-wrap">
1095
- <div class="row">
1096
- <div class="col m12 w3">
1097
- <div class="caption">Tạp chí điện tử Bóng đá</div>
1098
- </div>
1099
- <div class="col m12 w6">
1100
- <p>Giấy phép số 48/GP-BTTTT cấp ngày 05/02/2020</p>
1101
- <p>Tổng biên tập: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <b>Vũ Khắc Sơn</b></p>
1102
- <p>Phó tổng biên tập: &nbsp; &nbsp;<b>Nguyễn Hà Thanh</b></p>
1103
- <div class="hide-w">
1104
- <p>Địa chỉ: &nbsp;<b>Tầng 6, Tòa nhà Licogi 13 Tower, 164 đường Khuất Duy Tiến, phường Thanh Xuân, Thành phố Hà Nội</b></p>
1105
- <p>Văn phòng giao dịch: <b>Tầng 5-6-7, toà nhà LĐBĐVN, số 18 Lý Văn Phức, phường Ô Chợ Dừa, Hà Nội</b></p>
1106
- <p>Điện thoại: <b>(84.24) 3554 1188 - (84.24) 3554 1199</b></p>
1107
- <p>
1108
- Email: &nbsp; &nbsp; <a href="mailto:toasoan@bongdaplus.vn"><b>toasoan@bongdaplus.vn</b></a> |
1109
- <a href="mailto:vanphong@bongdaplus.vn"><b>vanphong@bongdaplus.vn</b></a>
1110
- </p>
1111
- <div class="spl"></div>
1112
- <p class="caption">Liên hệ quảng cáo</p>
1113
- <p>Hotline: &nbsp;<b>0903 203 412</b></p>
1114
- <p>Email: &nbsp; &nbsp;<a href="mailto:tien.nguyen@giaminhmedia.vn"><b>tien.nguyen@giaminhmedia.vn</b></a></p>
1115
- </div>
1116
- </div>
1117
- <div class="col m12 w3">
1118
- <ul class="bar social-lnk rgt-w">
1119
- <li class="hide-m">Theo dõi thông tin</li>
1120
- <li><a class="ico vff-lnk" href="https://vff.org.vn/" target="_blank" rel="nofollow"></a></li>
1121
- <li><a class="ico fb-lnk" href="https://www.facebook.com/BaoBongDa/"></a></li>
1122
- <li><a class="ico yt-lnk" href="https://www.youtube.com/channel/UCvDYMBE6GipX2VGacqOU2_Q"></a></li>
1123
- </ul>
1124
- </div>
1125
- </div>
1126
- <div class="foot-menu">
1127
- <ul class="bar hide-m">
1128
- <li><a href="#" data-showpaner="#contactview">Thông tin tòa soạn</a></li>
1129
- <li><a href="#" data-showpaner="#advertview">Liên hệ quảng cáo</a></li>
1130
- </ul>
1131
- <div class="copy-rgt">
1132
- Bản quyền &copy;2011 Bongdaplus.vn. Chỉ được phát hành lại thông tin khi
1133
- có sự đồng ý bằng văn bản của Tạp chí điện tử Bóng đá
1134
- </div>
1135
- <div class="clx hide-m"></div>
1136
- </div>
1137
- </div>
1138
- </footer>
1139
-
1140
- <div class="paner-wrap">
1141
- <div class="over-layer hide"></div>
1142
- <div id="contactview" class="contact-box paner hide">
1143
- <div class="pan-capt">
1144
- <div class="pan-title">Thông tin Toà soạn</div>
1145
- <i class="pan-close" data-action="hide"></i>
1146
- </div>
1147
- <div class="pan-cont">
1148
- <div class="xcap lead tx-prime tx-cen">Tạp chí Điện tử Bóng Đá</div>
1149
- <div class="row">
1150
- <div class="col w3 tx-base tx-rgt">Tổng biên tập:</div>
1151
- <div class="col w9"><b>Vũ Khắc Sơn</b></div>
1152
- <div class="clx"></div>
1153
- <div class="col w3 tx-base tx-rgt">Phó Tổng biên tập:</div>
1154
- <div class="col w9">
1155
- <b>Nguyễn Hà Thanh</b>
1156
- </div>
1157
- </div>
1158
- <div class="splt"></div>
1159
- <div class="row">
1160
- <div class="col w3 tx-base tx-rgt">Địa chỉ:</div>
1161
- <div class="col w9"><b>Tầng 6, Tòa nhà Licogi 13 Tower, 164 đường Khuất Duy Tiến, phường Thanh Xuân, Thành phố Hà Nội</b></div>
1162
- <div class="col w3 tx-base tx-rgt">Văn phòng giao dịch:</div>
1163
- <div class="col w9"><b>Tầng 5-6-7, toà nhà LĐBĐVN, số 18 Lý Văn Phức, phường Ô Chợ Dừa, Hà Nội</b></div>
1164
- <div class="col w3 tx-base tx-rgt">Tel:</div>
1165
- <div class="col w9"><b>(84.24) 3554 1188 - (84.24) 3554 1199</b></div>
1166
- <div class="col w3 tx-base tx-rgt">Fax:</div>
1167
- <div class="col w9"><b>(84.24) 3553 9898</b></div>
1168
- <div class="col w3 tx-base tx-rgt">Email:</div>
1169
- <div class="col w9">
1170
- <a href="mailto:toasoan@bongdaplus.vn"><b>toasoan@bongdaplus.vn</b></a>
1171
- <a href="mailto:vanphong@bongdaplus.vn"><b>vanphong@bongdaplus.vn</b></a>
1172
- </div>
1173
- </div>
1174
- </div>
1175
- </div>
1176
-
1177
- <div id="advertview" class="contact-box paner hide">
1178
- <div class="pan-capt">
1179
- <div class="pan-title">Thông tin Liên hệ</div>
1180
- <i class="pan-close" data-action="hide"></i>
1181
- </div>
1182
- <div class="pan-cont">
1183
- <div class="xcap lead tx-prime tx-cen">Tạp chí Điện tử Bóng Đá</div>
1184
- <div class="row">
1185
- <div class="col w4 tx-base tx-rgt">Hotline:</div>
1186
- <div class="col w8"><b>0903 203 412</b></div>
1187
- <div class="col w4 tx-base tx-rgt">Email:</div>
1188
- <div class="col w8"><a href="mailto:tien.nguyen@giaminhmedia.vn"><b>tien.nguyen@giaminhmedia.vn</b></a></div>
1189
- </div>
1190
- <p class="tx-base">Địa chỉ liên hệ:</p>
1191
- <b>Tầng 6, Tòa nhà Licogi 13 Tower, 164 đường Khuất Duy Tiến, phường Thanh Xuân, Thành phố Hà Nội</b>
1192
- <p class="tx-base">Văn phòng giao dịch:</p>
1193
- <b>Tầng 5-6-7, toà nhà LĐBĐVN, số 18 Lý Văn Phức, phường Ô Chợ Dừa, Hà Nội</b>
1194
- </div>
1195
- </div>
1196
-
1197
-
1198
- <div id="loginview" class="login-box paner hide">
1199
- <div class="pan-capt">
1200
- <div class="pan-title">Đăng nhập</div>
1201
- <i class="pan-close" data-action="hide"></i>
1202
- </div>
1203
- <div class="pan-cont">
1204
- <form class="soc-auth" action="#">
1205
- <button><i class="ico gg-color"></i>Google</button>
1206
- <button><i class="ico fb-color"></i>Facebook</button>
1207
- </form>
1208
- <div class="clx"></div>
1209
- <div class="splt"><span>hoặc</span></div>
1210
- <form class="loginer" action="//member.bongdaplus.vn/Identity/Account/Login?ReturnUrl=/" method="post">
1211
- <p>Email:</p>
1212
- <label class="txt-fld" for="email">
1213
- <input id="email" name="Input.Email" type="email" />
1214
- <span>Nhập địa chỉ email của bạn</span>
1215
- </label>
1216
- <label class="err-fld hide" for="email">Địa chỉ email không được để trống</label>
1217
- <p>Mật khẩu:</p>
1218
- <label class="txt-fld" for="passw">
1219
- <input id="passw" name="Input.Password" type="password" data-required="Mật khẩu không được để trống" />
1220
- <span>Nhập mật khẩu của bạn</span>
1221
- </label>
1222
- <label class="err-fld hide" for="passw">Mật khẩu không được để trống</label>
1223
- <p class="ft-sm tx-rgt"><a class="fg-psw" href="#" data-action="hide" data-showpaner="#forgetview">Quên mật khẩu?</a></p>
1224
- <label class="rdo-fld" for="persist">
1225
- <input id="persist" name="Input.RememberMe" type="checkbox" />
1226
- Ghi nhớ thông tin đăng nhập
1227
- </label>
1228
- <br>
1229
- <div class="fld-box">
1230
- <button class="btn major" type="submit">Đăng nhập</button>
1231
- </div>
1232
- <p class="ft-sm tx-cen">
1233
- Bạn chưa có tài khoản?
1234
- <a class="act-now" href="#" data-action="hide" data-showpaner="#registview">Đăng ký ngay</a>
1235
- </p>
1236
- </form>
1237
- </div>
1238
- </div>
1239
- </div>
1240
-
1241
- <script src="/lib/jquery/dist/jquery.min.js"></script>
1242
- <script src="/js/js_cookie.min.js?v=0H3Nuz3aug3afVbUlsu12Puxva3CP4EhJtPExqs54Vg"></script>
1243
- <script src="/js/bongdaplus.js?v=gIIX1pYQ8DB66N40YPyoHGaBgBFoHkPMMCARX4L6NdA"></script>
1244
- <script src="/js/premium.js?v=mbXB8QoXMl1zoEFSeE6z-mwQTb0ot7C8zj_F8JqsvNc"></script>
1245
-
1246
- <script>var _ad_info_code = 'mda/video';</script>
1247
- <script src="/js/advloader.js?v=dvvR0ygTjyYzNcQmQ_dI5bwYeX2Ww0nBjBBmCt9DWjQ"></script>
1248
-
1249
- </body>
1250
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
embed.html DELETED
@@ -1,56 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta name="viewport" content="width=device-width" />
5
- <title>EmbedVideo - Bongdaplus.vn </title>
6
-
7
- <link href="/css/video-js.css" rel="stylesheet">
8
- <link href="/css/style.css" rel="stylesheet">
9
- <link href="/css/player.css?new=43666246" rel="stylesheet">
10
- <script src="https://imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
11
- <script src="/js/video.min.js"></script>
12
- <!-- Google tag (gtag.js) -->
13
- <script async src="https://www.googletagmanager.com/gtag/js?id=G-EDHD2H8E9T"></script>
14
- <script>window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-EDHD2H8E9T');</script>
15
- </head>
16
- <body class="vjs-fullscreen">
17
-
18
- <div class="">
19
- <video id="videoPlayer" class="video-js" preload="auto" width="100%" height="100%" poster="https://cdn.bongdaplus.vn/assets/Media/2026/08/18/13/ThumbHullvsMU-up.jpg" controls disablePictureInPicture>
20
- <source src="https://cdn.bongdaplus.vn/assets//Media/2026/08/18/13/thumbhullvsmu-up.jpg" type="video/mp4">
21
- </video>
22
- <script>
23
- var adpath = 'mob/'; var cat = 127, evt = 0;
24
- if (window.matchMedia('(min-width: 1023px)').matches || (window.parent.Detect && !window.parent.Detect.isMob())) {
25
- adpath = 'web/';
26
- }
27
- adpath += 'mda';
28
- document.write('<script src="/adscripts/' + adpath + '/vast.js?new=' + (new Date()).getTime() + '"></' + 'script>');
29
- </script>
30
-
31
- <script>
32
- var vdo = videojs('videoPlayer', { autoplay: true });
33
- vdo.relatedCarousel([{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/18/80/Anh-chu-480-x-270.jpg', vdoref: '/video/du-doan-ty-so-hull-mu-than-rua-ali-33-chon-doi-nao-982702608.html', title: 'Dự đoán tỷ số Hull vs MU: Thần Rùa Ali 33 chọn đội nào?', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/18/13/ThumbHullvsMU-up.jpg', vdoref: '/video/hull-city-vs-mu-quy-do-vao-hang-bat-ho-982672608.html', title: 'Hull City vs MU: Quỷ Đỏ vào hang bắt hổ', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/19/80/Brentford-vs-Tottenham-480-x-270-moi.jpg', vdoref: '/video/du-doan-ty-so-brentford-vs-tottenham-premier-league-2026-27-than-rua-ali-33-chon-doi-nao-982862608.html', title: 'Dự đoán tỷ số Brentford vs Tottenham: Thần Rùa Ali 33 chọn đội nào?', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/19/13/Brenfort-vs-Tottenham.jpg', vdoref: '/video/brentford-vs-tottenham-de-zerbi-vuot-ai-gtech-982822608.html', title: 'Brentford vs Tottenham: De Zerbi vượt ải Gtech', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/17/0/thumblai.jpg', vdoref: '/video/du-doan-ty-so-arsenal-vs-coventry-than-rua-ali-33-chon-doi-nao-982612608.html', title: 'Dự đoán tỷ số Arsenal vs Coventry: Thần Rùa Ali 33 chọn đội nào?', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/18/13/ThumbArsenalvsCoventry-up.jpg', vdoref: '/video/arsenal-vs-coventry-nha-vua-mo-man-bang-mot-chien-thang-982662608.html', title: 'Arsenal vs Coventry: Nhà vua mở màn bằng một chiến thắng?', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/truc-tuyen-truoc-tran-Arsenal-vs-Coventry.jpg', vdoref: '/video/truc-tuyen-truoc-tran-arsenal-vs-coventry-hull-vs-mu-983222608.html', title: 'Trực tuyến trước trận Arsenal vs Coventry, Hull vs MU', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/80/HLV-Thai-Lan-chot-doi-hinh.jpg', vdoref: '/video/dt-thai-lan-tap-cach-san-rajamangala-40km-hlv-anthony-hudson-chot-luon-doi-hinh-dau-viet-nam-983202608.html', title: ' ĐT Thái Lan tập cách sân Rajamangala 40km, HLV Anthony Hudson chốt luôn đội hình đấu Việt Nam', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/80/Viet-Nam-tap-2-1-8.jpg', vdoref: '/video/tro-lai-san-tung-vo-dich-aff-cup-2024-dt-viet-nam-quyet-lam-nen-lich-su-983212608.html', title: ' Trở lại sân từng vô địch AFF Cup 2024, ĐT Việt Nam quyết làm nên lịch sử', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/thumbvong1-480.jpg', vdoref: '/video/vong-1-premier-league-2026-27-lieu-co-cu-soc-983112608.html', title: 'Nhận định Premier League vòng 1: Liệu có cú sốc?', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/26/Ronaldinho480.jpg', vdoref: '/video/ronaldinho-gay-soc-46-tuoi-van-tro-lai-san-co-khoac-ao-clb-serie-c-983192608.html', title: 'Ronaldinho gây sốc: 46 tuổi vẫn trở lại sân cỏ, khoác áo CLB Serie C', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/26/Konsa480.jpg', vdoref: '/video/arsenal-no-bom-tan-51-trieu-bang-de-va-hang-thu-983122608.html', title: 'Arsenal nổ bom tấn 51 triệu bảng để vá hàng thủ', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/anhliveVN.jpg', vdoref: '/video/truc-tuyen-hop-bao-viet-nam-hlv-kim-sang-sik-noi-gi-khi-pho-chu-tich-thai-lan-mia-mai-dan-nhap-tich-983182608.html', title: 'Trực tuyến họp báo Việt Nam: HLV Kim Sang Sik nói gì khi Phó Chủ tịch Thái Lan mỉa mai dàn nhập tịch', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/anhlivesua-480.jpg', vdoref: '/video/truc-tuyen-thai-lan-hop-bao-hlv-thach-dau-dt-viet-nam-983162608.html', title: ' Trực tuyến Thái Lan họp báo: HLV Anthony Hudson thách đấu ĐT Việt Nam', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/Thumb-tin-nong-21-8-480-up.jpg', vdoref: '/video/ban-tin-21-8-dt-viet-nam-chiu-thong-ke-cuc-xau-truoc-chung-ket-thai-lan-choi-chieu-nhu-indo-983152608.html', title: 'Bản tin 218: ĐT Việt Nam chịu thống kê cực xấu trước chung kết, Thái Lan chơi chiêu như Indo', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/26/cdv.jpg', vdoref: '/video/thai-lan-khoa-cdv-viet-nam-chi-3-000-ve-cho-tran-chung-ket-tai-rajamangala-983142608.html', title: 'Thái Lan khóa CĐV Việt Nam: Chỉ 3.000 vé cho trận chung kết tại Rajamangala', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/21/13/livethumbYT-480.jpg', vdoref: '/video/truoc-tran-thai-lan-vs-viet-nam-svd-rajamagala-vang-tanh-hon-chua-ba-danh-983132608.html', title: 'Trước trận Thái Lan vs Việt Nam: SVĐ Rajamagala vắng tanh hơn chùa Bà Đanh', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/20/80/ThumbRuaThaivsVietnam-480.jpg', vdoref: '/video/du-doan-ty-so-thai-lan-vs-viet-nam-than-rua-ali-33-chon-doi-nao-983092608.html', title: 'Dự đoán tỷ số Thái Lan vs Việt Nam: Thần Rùa Ali 33 chọn đội nào?', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/20/26/xuan-son.jpg', vdoref: '/video/truyen-thong-anh-dac-biet-chu-y-den-ngoi-no-cua-dt-viet-nam-983072608.html', title: 'Truyền thông Anh đặc biệt chú ý đến ngòi nổ của ĐT Việt Nam', target: '_parent' },{ poster: 'https://cdn.bongdaplus.vn/assets/Media/2026/08/20/26/Kim-Sang-Sik.jpg', vdoref: '/video/dt-viet-nam-co-mat-tai-thai-lan-ao-trang-van-chua-bi-thay-kim-vut-het-983082608.html', title: 'ĐT Việt Nam có mặt tại Thái Lan, áo trắng vẫn chưa bị thầy Kim bỏ hết', target: '_parent' }]);
34
-
35
- var vst = window['vast'] || '';
36
- if (vst) {
37
- vst = vst.replace('[yo_page_url]', window.parent.location.href);
38
- vdo.adsVastClient(vst);
39
- }
40
- vdo.ready(function () { vdo.play(); }); var counter = 0;
41
- if (window.parent.location.href.indexOf('.vn/video/') < 0) {
42
- window.addEventListener("click", function () {
43
- if (!counter) {
44
- var img = document.createElement("img");
45
- img.src = "/imgthumbnail/98267/1/1";
46
- img.width = 0;
47
- img.height = 0;
48
- document.body.appendChild(img);
49
- counter++;
50
- }
51
- });
52
- }
53
- </script>
54
- </div>
55
- </body>
56
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
headers.txt DELETED
@@ -1,9 +0,0 @@
1
- HTTP/2 200
2
- strict-transport-security: max-age=31536000; includeSubDomains; preload
3
- set-cookie: BongdaplusView_98267_1=1; expires=Sat, 22 Aug 2026 02:21:27 GMT; path=/
4
- x-frame-options: SAMEORIGIN
5
- x-xss-protection: 1; mode=block
6
- x-content-type-options: nosniff
7
- x-powered-by: ASP.NET
8
- date: Sat, 22 Aug 2026 01:51:27 GMT
9
-
 
 
 
 
 
 
 
 
 
 
index_v2.html DELETED
@@ -1,98 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="vi">
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
6
- <title>VNEWS - Tin Tức Việt Nam</title>
7
- <meta name="description" content="Tin tức tổng hợp, bóng đá trực tiếp, video highlight, AI tóm tắt.">
8
- <meta property="og:title" content="VNEWS - Tin Tức Việt Nam">
9
- <meta property="og:image" content="https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg">
10
- <link rel="canonical" href="https://bep40-vnews.hf.space">
11
- <link rel="stylesheet" href="/static/wc2026.css"><link rel="stylesheet" href="/static/fm_fix.css">
12
- <script src="https://cdn.jsdelivr.net/npm/hls.js@1/dist/hls.min.js"></script>
13
- <style>
14
- *{box-sizing:border-box;margin:0;padding:0}body{background:#111;color:#eee;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;overflow-x:hidden}.header{background:linear-gradient(135deg,#0d1117,#1a3a2a 50%,#8b7500);padding:12px;text-align:center}.header h1{font-size:18px;color:#fff}.header p{font-size:10px;color:#aaa}.cats{display:flex;overflow-x:auto;background:#1a1a1a;border-bottom:1px solid #333;padding:0 4px;position:sticky;top:0;z-index:50;scrollbar-width:none}.cats::-webkit-scrollbar{display:none}.cat{padding:9px 11px;color:#888;font-size:11px;white-space:nowrap;border-bottom:2px solid transparent;cursor:pointer;flex-shrink:0}.cat.active{color:#5cb87a;border-bottom-color:#5cb87a;font-weight:700}.view{display:none}.view.active{display:block}.loading{text-align:center;padding:30px;color:#777;font-size:12px}.slider-wrap{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}.slider-header{padding:7px 10px;display:flex;align-items:center;justify-content:space-between}.slider-label{color:#f0c040;font-size:13px;font-weight:800}.slider-note{font-size:10px;color:#777}.slider-track{display:flex;overflow-x:auto;gap:8px;padding:4px 10px 10px;scrollbar-width:none}.slider-track::-webkit-scrollbar{display:none}.slider-item{flex:0 0 160px;cursor:pointer}.slider-thumb{position:relative;width:100%;aspect-ratio:16/9;border-radius:6px;overflow:hidden;background:#333}.slider-thumb img,.slider-thumb video{width:100%;height:100%;object-fit:cover}.slider-title{font-size:10px;color:#ccc;margin-top:3px;line-height:1.2;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.card-play{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:30px;height:30px;border-radius:50%;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px}.grid{display:grid;grid-template-columns:repeat(2,1fr);gap:6px;padding:6px 4px}@media(min-width:650px){.grid{grid-template-columns:repeat(3,1fr)}}.card{background:#1a1a1a;border:1px solid #222;border-radius:8px;overflow:hidden;cursor:pointer}.card-img{position:relative;aspect-ratio:16/9;background:#333}.card-img img{width:100%;height:100%;object-fit:cover}.card-body{padding:6px 8px}.card-title{font-size:11px;line-height:1.35;color:#eee;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.badge{font-size:8px;padding:1px 5px;border-radius:3px;font-weight:700;display:inline-block;margin-bottom:2px;color:#fff}.badge-vne{background:#c0392b}.badge-genk{background:#6a1b9a}.badge-ai{background:#2d8659}.badge-wc{background:#0b6bcb}.section-title{font-size:13px;font-weight:800;color:#5cb87a;margin:8px 0 4px;padding-left:8px;border-left:3px solid #5cb87a}.back-btn{background:#111;color:#fff;border:none;padding:10px;font-size:12px;width:100%;position:sticky;top:0;z-index:60;cursor:pointer}.article-view{padding:12px 8px 40px;max-width:760px;margin:0 auto}.article-title{font-size:18px;font-weight:800;line-height:1.3;margin-bottom:8px}.article-summary{background:#1a2a1f;border-left:3px solid #2d8659;padding:10px;margin-bottom:14px;color:#ccc;font-size:13px}.article-p{font-size:14px;line-height:1.7;color:#ccc;margin-bottom:10px}.article-img{width:100%;border-radius:6px;margin:10px 0}.article-h2{font-size:16px;margin:16px 0 8px;color:#eee}.article-actions{display:flex;gap:8px;flex-wrap:wrap;border-top:1px solid #333;margin-top:16px;padding-top:10px}.article-actions button{background:#1a1a1a;border:1px solid #333;color:#ccc;padding:7px 12px;border-radius:14px;font-size:11px;cursor:pointer}.article-actions button.primary{background:#2d8659;border-color:#2d8659;color:#fff}.article-ai-ask{margin-top:12px;background:#141414;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.article-ai-ask textarea{width:100%;min-height:60px;background:#222;border:1px solid #444;color:#eee;border-radius:10px;padding:9px;font-size:12px}.article-ai-ask button{background:#2d8659;border:0;color:#fff;border-radius:10px;padding:8px 12px;margin-top:6px;font-size:11px;cursor:pointer}.article-ai-answer{white-space:pre-wrap;color:#ccc;font-size:13px;line-height:1.55;margin-top:8px}.tiktok-container{width:100%;height:80vh;max-height:680px;min-height:400px;background:#000}.tiktok-feed{height:100%;overflow-y:scroll;scroll-snap-type:y mandatory;scrollbar-width:none}.tiktok-feed::-webkit-scrollbar{display:none}.tiktok-slide{height:80vh;max-height:680px;min-height:400px;scroll-snap-align:start;position:relative;background:#000;display:flex;align-items:center;justify-content:center}.tiktok-slide video{width:100%;height:100%;object-fit:cover;border:none}.tiktok-slide iframe{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:177.78vh;min-width:100%;height:100%;border:none;pointer-events:none;max-width:none}.tiktok-slide.ratio-wide video{width:100%;height:100%;object-fit:contain}.tiktok-slide.ratio-wide iframe{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:calc(100vw - 1px);height:56.25vw;max-width:100vw;max-height:100%;border:none;pointer-events:none}.tiktok-bottom{position:absolute;bottom:0;left:0;right:60px;padding:12px 10px 16px;background:linear-gradient(transparent,rgba(0,0,0,.85));z-index:3}.tiktok-title{font-size:12px;color:#fff}.tiktok-counter{position:absolute;top:8px;left:8px;background:rgba(0,0,0,.5);font-size:9px;padding:2px 7px;border-radius:8px;color:#fff;z-index:4}.tiktok-right{position:absolute;right:8px;bottom:100px;display:flex;flex-direction:column;align-items:center;gap:14px;z-index:5}.tiktok-right-btn{display:flex;flex-direction:column;align-items:center;gap:2px;background:none;border:0;color:#fff;cursor:pointer;font-size:10px}.tiktok-right-btn .icon{width:42px;height:42px;border-radius:50%;background:rgba(255,255,255,.12);display:flex;align-items:center;justify-content:center;font-size:20px}.tiktok-right-btn .count{font-size:10px;color:#ddd}.inline-comments{position:absolute;bottom:0;left:0;right:0;max-height:60%;min-height:140px;background:rgba(18,18,18,.95);border-radius:14px 14px 0 0;z-index:10;overflow:clip;display:flex;flex-direction:column}.inline-cmt-header{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid #333;color:#5cb87a;font-size:12px;font-weight:700;flex-shrink:0}.inline-cmt-header button{background:none;border:0;color:#fff;font-size:16px;cursor:pointer}.inline-cmt-list{flex:1 1 auto;overflow-y:auto;padding:6px 10px;max-height:140px;min-height:40px}.inline-cmt-item{background:#222;border-radius:8px;padding:6px 8px;margin:4px 0;color:#ccc;font-size:11px;line-height:1.3}.inline-cmt-time{font-size:9px;color:#777;margin-right:6px}.inline-cmt-input{display:flex;gap:6px;padding:8px 10px;border-top:1px solid #333;flex-shrink:0;position:sticky;bottom:0;background:rgba(18,18,18,.98)}.inline-cmt-input input{flex:1;background:#222;border:1px solid #444;color:#eee;border-radius:16px;padding:7px 12px;font-size:11px;min-height:32px}.inline-cmt-input button{background:#2d8659;border:0;color:#fff;border-radius:16px;padding:7px 12px;font-size:11px;cursor:pointer;min-height:32px}.wc2026-section{margin:6px 4px;background:linear-gradient(135deg,#0d1117,#1a1a3a);border:1px solid #1a3a5a;border-radius:10px;overflow:hidden}.wc-header{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;background:linear-gradient(90deg,#0b2e4a,#1a3a5a)}.wc-header h2{font-size:15px;color:#fff;margin:0}.wc-live-badge{font-size:10px;color:#e74c3c;font-weight:700;animation:wc-pulse 1.5s infinite}@keyframes wc-pulse{0%,100%{opacity:1}50%{opacity:.4}}.wc-tabs{display:flex;gap:4px;padding:8px 10px;overflow-x:auto;scrollbar-width:none}.wc-tabs::-webkit-scrollbar{display:none}.wc-tab{padding:5px 10px;background:#1a2a3a;border:1px solid #2a3a4a;border-radius:12px;color:#8ab4d8;font-size:10px;cursor:pointer;white-space:nowrap;flex-shrink:0}.wc-tab.active{background:#0b6bcb;border-color:#0b6bcb;color:#fff;font-weight:700}.wc-content{padding:8px 10px;max-height:500px;overflow-y:auto}.wc-news-grid{display:flex;flex-direction:column;gap:8px}.wc-news-item{display:flex;gap:8px;padding:8px;background:#1a2030;border-radius:8px;cursor:pointer}.wc-news-item:active{opacity:.8}.wc-news-img{flex:0 0 70px;aspect-ratio:16/9;border-radius:6px;overflow:hidden;background:#222}.wc-news-img img{width:100%;height:100%;object-fit:cover}.wc-news-text{flex:1;min-width:0}.wc-news-title{font-size:11px;font-weight:700;color:#eee;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.wc-news-via{font-size:9px;color:#6a9fca;margin-top:2px}.ls-section{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}.ls-header{padding:7px 10px;display:flex;align-items:center;justify-content:space-between}.ls-header h3{color:#f0c040;font-size:13px;font-weight:800}.ls-tabs{display:flex;gap:4px;padding:0 10px 8px;overflow-x:auto;scrollbar-width:none}.ls-tabs::-webkit-scrollbar{display:none}.ls-tab{padding:4px 10px;background:#222;border:1px solid #333;border-radius:12px;color:#999;font-size:10px;white-space:nowrap;cursor:pointer;flex-shrink:0}.ls-tab.active{background:#2d8659;border-color:#2d8659;color:#fff;font-weight:700}.ls-content{max-height:420px;overflow-y:auto;padding:0 6px 8px;font-size:12px;color:#ddd}.ls-content ul{list-style:none;padding:0;margin:0}.ls-content .title-content{display:flex;gap:6px;align-items:center;background:#222;border-radius:4px;margin:4px 0;padding:5px 8px}.ls-content .title-content img{width:18px;height:18px}.ls-content .title-content strong{font-size:11px;color:#ccc}.ls-content .match-detail{padding:6px;border-bottom:1px solid #262626;cursor:pointer}.ls-content .match-detail:hover{background:#1a2a1f}.ls-content .match{display:flex;flex-wrap:wrap;align-items:center;gap:4px}.ls-content .datetime{width:100%;font-size:9px;color:#888}.ls-content .teams{display:flex;width:100%;align-items:center;gap:4px}.ls-content .team{flex:1;display:flex;align-items:center;gap:4px;min-width:0;text-decoration:none}.ls-content .team .name{font-size:11px;color:#ddd;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ls-content .team .logo img{width:18px;height:18px}.ls-content .home-team{justify-content:flex-end;text-align:right}.ls-content .status{flex:0 0 54px;text-align:center}.ls-content .status a{color:#fff;text-decoration:none;font-weight:800;font-size:12px}.ls-content .status .label{font-size:8px;color:#888;display:block}.ls-content .status .label.live{color:#e74c3c}.ls-content .info,.ls-content .btns{display:none}.ls-content table{width:100%;border-collapse:collapse;font-size:11px;color:#ccc}.ls-content table th{background:#222;color:#999;padding:5px 4px;font-size:10px;border-bottom:1px solid #333}.ls-content table td{padding:4px 3px;border-bottom:1px solid #1a1a1a}.ls-content table .team-name{display:flex;align-items:center;gap:4px}.ls-content table .team-name img{width:16px;height:16px}.ls-content table .pts{font-weight:800;color:#f0c040}.match-overlay{position:fixed;inset:0;background:#111;z-index:9999;display:none;flex-direction:column;overflow:auto}.match-overlay.active{display:flex}.mo-header{padding:10px;background:#1a1a1a;display:flex;justify-content:space-between;align-items:center;position:sticky;top:0;z-index:1}.mo-header h3{font-size:13px;color:#eee}.mo-close{background:none;border:0;color:#fff;font-size:22px;cursor:pointer}.mo-tabs{display:flex;gap:4px;padding:8px 10px;background:#1a1a1a;overflow-x:auto}.mo-tab{padding:5px 12px;background:#222;border:1px solid #333;border-radius:10px;color:#999;font-size:10px;cursor:pointer;white-space:nowrap}.mo-tab.active{background:#2d8659;color:#fff}.mo-body{padding:8px;overflow-x:auto;font-size:12px;color:#ddd}.mo-body ul{list-style:none;padding:0;margin:0}.mo-body li{padding:5px 0;border-bottom:1px solid #222}.featured-match{margin:6px 4px;background:linear-gradient(135deg,#1a2a1f,#0d1117);border:1px solid #2d8659;border-radius:10px;padding:12px;cursor:pointer}.fm-league{text-align:center;color:#5cb87a;font-size:9px;font-weight:700;text-transform:uppercase}.fm-teams{display:flex;align-items:center;justify-content:center;gap:10px;margin-top:6px}.fm-team{flex:1;display:flex;flex-direction:column;align-items:center;gap:4px}.fm-team img{width:32px;height:32px;object-fit:contain}.fm-team span{font-size:10px;color:#ccc;text-align:center}.fm-score{font-size:22px;font-weight:900;min-width:60px;text-align:center;color:#fff}.fm-status{text-align:center;margin-top:6px;font-size:9px;color:#e74c3c;font-weight:700}.fm-status.upcoming{color:#f0c040}.ai-compose{margin:6px 4px;background:#141414;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.ai-compose-title{font-size:13px;font-weight:800;color:#5cb87a;margin-bottom:8px}.ai-compose-row{display:flex;gap:6px;margin-top:6px}.ai-compose input{flex:1;background:#222;border:1px solid #333;color:#eee;border-radius:18px;padding:9px 12px;font-size:12px;min-width:0}.ai-compose button{background:#2d8659;border:0;color:#fff;border-radius:18px;padding:9px 12px;font-size:11px;font-weight:700;cursor:pointer;white-space:nowrap}.ai-compose button.secondary{background:#333}.ai-compose button.hot-short-btn{background:linear-gradient(135deg,#8b1a5a,#c0392b);border:1px solid #e07050;color:#fff;box-shadow:0 0 10px rgba(192,57,43,.4);animation:hot-pulse 2s infinite}@keyframes hot-pulse{0%,100%{box-shadow:0 0 6px rgba(192,57,43,.35)}50%{box-shadow:0 0 16px rgba(192,57,43,.75)}}.hot-topic-row{display:flex;gap:6px;overflow-x:auto;padding:4px 0;scrollbar-width:none}.hot-topic-row::-webkit-scrollbar{display:none}.hot-chip{flex:0 0 auto;background:#222;border:1px solid #333;color:#ddd;border-radius:16px;padding:5px 10px;font-size:11px;cursor:pointer;white-space:nowrap}.hot-chip:active{transform:scale(.96)}.hashtag-sources{margin:8px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.hashtag-sources h3{font-size:13px;color:#5cb87a;margin-bottom:8px}.hashtag-src-item{display:flex;gap:8px;padding:8px;background:#202020;border-radius:8px;margin:6px 0;cursor:pointer}.hashtag-src-item:active{opacity:.8}.hashtag-src-img{flex:0 0 80px;aspect-ratio:16/9;background:#333;border-radius:6px;overflow:hidden}.hashtag-src-img img{width:100%;height:100%;object-fit:cover}.hashtag-src-text{flex:1;min-width:0}.hashtag-src-title{font-size:12px;font-weight:700;color:#eee;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.hashtag-src-via{font-size:10px;color:#888;margin-top:2px}.hashtag-rewrite-btn{width:100%;margin-top:8px;background:#2d8659;border:0;color:#fff;padding:9px;border-radius:10px;font-size:12px;font-weight:700;cursor:pointer}.hashtag-load-more{width:100%;margin-top:8px;background:#222;border:1px solid #333;color:#ccc;padding:9px;border-radius:10px;font-size:12px;cursor:pointer}.hashtag-loading{display:flex;align-items:center;gap:8px;padding:12px;color:#888;font-size:12px}.hashtag-spinner{width:16px;height:16px;border:2px solid #333;border-top-color:#5cb87a;border-radius:50%;animation:ht-spin .8s linear infinite}@keyframes ht-spin{to{transform:rotate(360deg)}}.wall-item{flex:0 0 260px;background:#141414;border:1px solid #2b2b2b;border-radius:10px;padding:8px}.wall-item-new{animation:wall-flash 1.8s ease-out}@keyframes wall-flash{0%{border-color:#f0c040;box-shadow:0 0 18px rgba(240,192,64,.35)}30%{border-color:#f0c040;box-shadow:0 0 12px rgba(240,192,64,.2)}100%{border-color:#2b2b2b;box-shadow:none}}.wall-thumb{width:100%;aspect-ratio:16/9;border-radius:8px;background:#222;overflow:hidden;margin-bottom:6px;position:relative}.wall-thumb img{width:100%;height:100%;object-fit:cover}.wall-video-badge{position:absolute;top:4px;right:4px;background:rgba(45,134,89,.9);color:#fff;font-size:10px;padding:2px 6px;border-radius:6px;font-weight:700}.wall-title{font-size:12px;color:#5cb87a;font-weight:800;line-height:1.3;margin-bottom:4px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.wall-text{font-size:11px;color:#bbb;line-height:1.4;white-space:pre-wrap;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}.wall-actions{display:flex;gap:6px;margin-top:8px}.wall-actions button{flex:1;border:1px solid #333;background:#222;color:#ddd;border-radius:14px;padding:6px 8px;font-size:10px;cursor:pointer}.wall-actions button.primary{background:#2d8659;border-color:#2d8659;color:#fff}.wall-actions button.wall-btn-design{background:#1a3a5a;border-color:#3a5a7a;color:#fff;font-weight:700}#progress-toast{position:fixed;bottom:70px;left:50%;transform:translateX(-50%);background:#2d8659;color:#fff;padding:10px 20px;border-radius:20px;font-size:12px;z-index:99998;box-shadow:0 4px 12px rgba(0,0,0,.4);display:none;white-space:nowrap}.storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 4px}
15
- .hl-load-more:hover{background:#2a2a2a !important}
16
- .slider-wrap{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}
17
- .slider-track{display:flex;overflow-x:auto;gap:8px;padding:4px 10px 10px;scrollbar-width:none}
18
- .slider-track::-webkit-scrollbar{display:none}
19
- .slider-item{flex:0 0 160px;cursor:pointer}
20
- .slider-thumb{position:relative;width:100%;aspect-ratio:16/9;border-radius:6px;overflow:hidden;background:#333}
21
- .slider-thumb img,.slider-thumb video{width:100%;height:100%;object-fit:cover}
22
- .card-play{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:30px;height:30px;border-radius:50%;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px}
23
- .slider-title{font-size:10px;color:#ccc;margin-top:3px;line-height:1.2;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
24
- .ls-section-header{padding:8px 10px;font-size:11px;font-weight:700;color:#5cb87a;border-bottom:1px solid #2a2a2a}
25
- .ls-section-header.upcoming{color:#f0c040}
26
- .ls-section-header.finished{color:#e74c3c}
27
- .ls-section-header.yesterday{color:#8ab4f0}
28
- .ls-section-header.older{color:#888}
29
- .hl-load-more{margin:4px 8px 8px;background:#222;border:1px solid #333;color:#ccc;padding:6px 12px;border-radius:8px;font-size:11px;cursor:pointer;width:calc(100% - 16px);display:block}
30
- .hl-load-more:hover{background:#2a2a2a}
31
- </style>
32
- </head>
33
- <body>
34
- <div class="header"><h1>📰 VNEWS</h1><p>Tin tức · Bóng đá LIVE · Highlight · AI · World Cup 2026</p></div>
35
- <div class="cats" id="cat-bar"></div>
36
- <div id="home-hl-section"></div>
37
- <div id="view-home" class="view active"><div class="loading">Đang tải...</div></div>
38
- <div id="view-cat" class="view"></div>
39
- <div id="view-video" class="view"></div>
40
- <div id="view-tiktok" class="view"></div>
41
- <div id="view-article" class="view"></div>
42
- <div class="match-overlay" id="match-overlay">
43
- <div class="mo-header"><h3 id="mo-title">Chi tiết trận đấu</h3><button class="mo-close" onclick="closeMatch()">✕</button></div>
44
- <div class="mo-tabs"><span class="mo-tab active" onclick="loadMatchTab('detail')">📋 Chi tiết</span><span class="mo-tab" onclick="loadMatchTab('comm')">Diễn biến</span><span class="mo-tab" onclick="loadMatchTab('stats')">Thống kê</span></div>
45
- <div class="mo-body" id="mo-body"><div class="loading">Đang tải...</div></div>
46
- </div>
47
- <div id="progress-toast"></div>
48
- <script>
49
- var _cats=[],_hlLeagueData={},_currentArticle=null;window._currentEventId='';
50
- function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]))}
51
- function showView(id){document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.getElementById(id)?.classList.add('active')}
52
- function switchCat(id){document.querySelectorAll('.cat').forEach(c=>c.classList.remove('active'));document.querySelector('[data-cat="'+id+'"]')?.classList.add('active');document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.querySelectorAll('video').forEach(v=>{v.pause();if(v._hls){v._hls.destroy();v._hls=null}});document.querySelectorAll('iframe[data-yt-src]').forEach(f=>{f.src=''});if(id==='home')document.getElementById('view-home').classList.add('active');else if(id==='news-all'){document.getElementById('view-cat').classList.add('active');loadNewsTab()}else{document.getElementById('view-cat').classList.add('active');loadCat(id)}}
53
- function toast(msg){let t=document.getElementById('progress-toast');if(t){t.textContent=msg;t.style.display='block';setTimeout(()=>{t.style.display='none'},3500)}}
54
- function doShare(title,url,img,postId){
55
- var shareUrl;
56
- if(postId){
57
- shareUrl = SPACE+'/s?post_id='+encodeURIComponent(postId)+'&title='+encodeURIComponent(title);
58
- } else {
59
- shareUrl = SPACE+'/s?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title)+'&img='+encodeURIComponent(img||'');
60
- }
61
- // Use clipboard API first (modern, works on Chrome mobile 85+)
62
- if(navigator.clipboard && navigator.clipboard.writeText){
63
- navigator.clipboard.writeText(shareUrl).then(function(){
64
- toast('📋 Đã sao chép link!');
65
- try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){}
66
- }).catch(function(){
67
- try{
68
- var ta=document.createElement('textarea');ta.value=shareUrl;ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='-9999px';ta.style.opacity='0';
69
- document.body.appendChild(ta);ta.select();ta.setSelectionRange(0,99999);
70
- if(document.execCommand('copy')){toast('📋 Đã sao chép link!');}else{prompt('📋 Sao chép link:', shareUrl);}
71
- document.body.removeChild(ta);
72
- }catch(e){prompt('📋 Sao chép link:', shareUrl);}
73
- try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){}
74
- });
75
- } else {
76
- try{
77
- var ta=document.createElement('textarea');ta.value=shareUrl;ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='-9999px';ta.style.opacity='0';
78
- document.body.appendChild(ta);ta.select();ta.setSelectionRange(0,99999);
79
- if(document.execCommand('copy')){toast('📋 Đã sao chép link!');}else{prompt('📋 Sao chép link:', shareUrl);}
80
- document.body.removeChild(ta);
81
- }catch(e){prompt('📋 Sao chép link:', shareUrl);}
82
- try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){}
83
- }
84
- }
85
- async function init(){_cats=await fetch('/api/categories').then(r=>r.json()).catch(()=>[]);let bar='<div class="cat active" data-cat="home">🏠</div><div class="cat" data-cat="news-all">📰 Tin tức</div>';_cats.forEach(c=>{bar+='<div class="cat" data-cat="'+c.id+'">'+c.name+'</div>'});document.getElementById('cat-bar').innerHTML=bar;document.querySelectorAll('.cat').forEach(t=>{t.onclick=()=>switchCat(t.dataset.cat)});}
86
- var SPACE=location.origin;
87
- </script>
88
- <script src="/static/app_v2.js?v=20260827fptwall"></script>
89
- <script src="/static/designer_v2.js?v=20260817fix1"></script>
90
- <script src="/static/yt_live.js"></script>
91
- <script src="/static/vtv_init.js"></script>
92
- <script src="/static/hot_multi.js?v=1"></script>
93
- <script src="/static/wc2026_v2.js"></script>
94
- <script src="/static/live_mode.js"></script>
95
- <script src="/static/match_detail_v6.js"></script>
96
- <script>init();loadHome();</script>
97
- </body>
98
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
logs_route.py DELETED
@@ -1,106 +0,0 @@
1
- """Independent logs page for VNEWS Space.
2
- Serves /logs (HTML) and /logs.txt (raw) so build/runtime errors are visible
3
- even when the Hugging Face build-logs tab is stuck/unavailable.
4
- Mounted from _run.py.
5
- """
6
- import os
7
- import time
8
- import json
9
- import subprocess
10
- from fastapi import Request
11
- from fastapi.responses import HTMLResponse, PlainTextResponse
12
-
13
- try:
14
- from app_v2_entry import app
15
- except Exception:
16
- from main import app
17
-
18
- BUILD_DONE = "/app/.build_done"
19
- DATA_DIR = '/data' if os.path.isdir('/data') else os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
20
-
21
-
22
- def _collect():
23
- lines = []
24
- lines.append("=== VNEWS LOGS ===")
25
- lines.append("generated: " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
26
- lines.append("")
27
- # Build marker
28
- if os.path.exists(BUILD_DONE):
29
- lines.append("[BUILD] .build_done exists -> container started OK")
30
- try:
31
- lines.append("[BUILD] built at: " + open(BUILD_DONE).read().strip())
32
- except Exception:
33
- pass
34
- else:
35
- lines.append("[BUILD] WARNING: .build_done MISSING -> uvicorn started before build finished?")
36
- lines.append("")
37
-
38
- # Space status from HF runtime file
39
- try:
40
- import json as _j
41
- mj = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.huggingface', 'main.json')
42
- if os.path.exists(mj):
43
- lines.append("[RUNTIME] .huggingface/main.json present")
44
- else:
45
- lines.append("[RUNTIME] .huggingface/main.json NOT found")
46
- except Exception as e:
47
- lines.append("[RUNTIME] error: " + str(e))
48
- lines.append("")
49
-
50
- # Data dir contents
51
- lines.append("[DATA] dir=" + DATA_DIR)
52
- try:
53
- if os.path.isdir(DATA_DIR):
54
- for f in sorted(os.listdir(DATA_DIR)):
55
- p = os.path.join(DATA_DIR, f)
56
- lines.append(" - %s (%d bytes)" % (f, os.path.getsize(p)))
57
- else:
58
- lines.append(" (data dir missing)")
59
- except Exception as e:
60
- lines.append(" error: " + str(e))
61
- lines.append("")
62
-
63
- # Recent container logs (stdout) if captured
64
- log_paths = ["/tmp/vnews_stdout.log", os.path.join(DATA_DIR, "app.log")]
65
- for lp in log_paths:
66
- if os.path.exists(lp):
67
- lines.append("[STDOUT] tail of " + lp + ":")
68
- try:
69
- with open(lp, "r", errors="replace") as fh:
70
- tail = fh.read().splitlines()[-50:]
71
- for l in tail:
72
- lines.append(" " + l)
73
- except Exception as e:
74
- lines.append(" read error: " + str(e))
75
- lines.append("")
76
-
77
- # Environment hints
78
- lines.append("[ENV] HF_SPACE: " + os.environ.get("HF_SPACE", "?"))
79
- lines.append("[ENV] SPACE_ID: " + os.environ.get("SPACE_ID", "?"))
80
- lines.append("[ENV] CUDA/CPU: " + ("gpu" if os.environ.get("CUDA_VISIBLE_DEVICES") else "cpu"))
81
- lines.append("")
82
- lines.append("=== END ===")
83
- return "\n".join(lines)
84
-
85
-
86
- @app.get("/logs")
87
- def logs_page(request: Request):
88
- txt = _collect()
89
- html = (
90
- "<!DOCTYPE html><html lang='vi'><head><meta charset='utf-8'>"
91
- "<meta name='viewport' content='width=device-width,initial-scale=1'>"
92
- "<title>VNEWS Logs</title>"
93
- "<style>body{background:#0d1117;color:#c9d1d9;font-family:monospace;padding:16px}"
94
- "pre{white-space:pre-wrap;word-break:break-word;font-size:13px;line-height:1.5}"
95
- "a{color:#58a6ff}</style></head><body>"
96
- "<h2>VNEWS — Build & Runtime Logs</h2>"
97
- "<p><a href='/logs.txt'>📄 raw text</a> · refresh để cập nhật</p>"
98
- "<pre>" + txt.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") + "</pre>"
99
- "</body></html>"
100
- )
101
- return HTMLResponse(html)
102
-
103
-
104
- @app.get("/logs.txt")
105
- def logs_raw(request: Request):
106
- return PlainTextResponse(_collect())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main.py CHANGED
@@ -1,7 +1,7 @@
1
- """VNEWS - FastAPI backend with livescore + xemlaibongda highlights + VTV channels"""
2
  import re, time, subprocess, json, os, threading
3
  import html as html_lib
4
- from datetime import datetime, timezone, timedelta, date
5
  from collections import defaultdict
6
 
7
  VN_TZ = timezone(timedelta(hours=7))
@@ -14,29 +14,38 @@ from bs4 import BeautifulSoup
14
 
15
  app = FastAPI()
16
 
 
 
17
  # ===== WORLD CUP 2026 SCRAPER =====
18
  from wc2026_scraper import get_wc2026_all, scrape_fixtures, scrape_standings, scrape_stats, scrape_wc_news
19
 
20
  # ===== RATE LIMITING =====
21
- _rate_limit_data = defaultdict(list)
22
  _rate_limit_lock = threading.Lock()
23
- RATE_LIMIT_MAX = 60
24
- RATE_LIMIT_WINDOW = 60
25
 
26
  def _check_rate_limit(ip: str) -> bool:
 
27
  with _rate_limit_lock:
28
  now = time.time()
 
29
  _rate_limit_data[ip] = [t for t in _rate_limit_data[ip] if now - t < RATE_LIMIT_WINDOW]
30
- if len(_rate_limit_data[ip]) >= RATE_LIMIT_MAX: return False
 
31
  _rate_limit_data[ip].append(now)
32
  return True
33
 
34
  @app.middleware("http")
35
  async def rate_limit_middleware(request: Request, call_next):
 
 
36
  if request.url.path.startswith("/api/"):
37
  ip = request.client.host
38
- if not _check_rate_limit(ip): return JSONResponse({"error": "rate limit exceeded"}, status_code=429)
39
- return await call_next(request)
 
 
40
 
41
  # ===== VTV CHANNELS API =====
42
  from vtv_api import router as vtv_router
@@ -50,8 +59,65 @@ _cache_ttl = 300
50
  _cache_ttl_live = 60
51
  _cache_ttl_yt = 1800
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  PRIORITY_LEAGUES = ["Ngoại Hạng Anh","FA Cup","Champions League","LaLiga","Copa del Rey","Serie A","Bundesliga","Ligue 1","V-League"]
54
- LEAGUE_IDS = {"nha":36781,"laliga":38843,"seriea":36072,"bundesliga":40040,"ligue1":37298}
55
  HL_LEAGUES = {
56
  "premier-league":{"path":"anh/premier-league","name":"Premier League","emoji":"🏴󠁧󠁢󠁥󠁮󠁧󠁿"},
57
  "fa-cup":{"path":"anh/fa-cup","name":"FA Cup","emoji":"🏆"},
@@ -69,17 +135,8 @@ def _cached(key, fn, ttl=None):
69
  except: data=_cache.get(key,{}).get("d",[])
70
  _cache[key]={"d":data,"t":now}; return data
71
  def _get(url, headers=None):
72
- h=headers or HEADERS
73
- for attempt in range(3):
74
- try:
75
- r=requests.get(url, headers=h, timeout=15)
76
- r.encoding="utf-8"
77
- return BeautifulSoup(r.text,"lxml")
78
- except Exception:
79
- if attempt < 2:
80
- time.sleep(0.5 * (attempt + 1))
81
- else:
82
- raise
83
  def fetch_bongda_api(endpoint):
84
  try:
85
  r=requests.get(f"https://bongda.com.vn{endpoint}", headers=BONGDA_HEADERS, timeout=10)
@@ -145,345 +202,315 @@ def proxy_video(url: str = Query(...), request: Request = None):
145
  @app.get("/api/proxy/img")
146
  def proxy_img(url: str = Query(...)):
147
  try:
148
- from urllib.parse import urlparse
149
- _u = urlparse(url); _host = _u.netloc.lower()
150
- _referer = "https://dantri.com.vn/"
151
- if "refooty" in _host or "xemlaibongda" in _host: _referer = "https://xemlaibongda.top/"
152
- elif "ytimg" in _host or "youtube" in _host: _referer = "https://www.youtube.com/"
153
- elif "vncecdn" in _host or "vnexpress" in _host: _referer = "https://vnexpress.net/"
154
- r = requests.get(url, headers={**HEADERS, "Referer": _referer}, timeout=10)
155
  if r.status_code != 200: return Response(status_code=502)
156
- return Response(content=r.content, media_type=r.headers.get("Content-Type", "image/jpeg"), headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"})
 
157
  except: return Response(status_code=502)
158
 
159
  # ===== XEMLAIBONGDA HIGHLIGHTS =====
160
  def _scrape_xemlaibongda_page(page_path, limit=20):
 
 
 
 
161
  try:
162
  url = f"https://xemlaibongda.top/{page_path}" if page_path else "https://xemlaibongda.top/"
163
- r = requests.get(url, headers=HEADERS, timeout=8)
164
- if r.status_code != 200: return []
 
165
  r.encoding = "utf-8"
166
  soup = BeautifulSoup(r.text, "lxml")
167
- videos = []; seen = set()
 
 
168
  for a in soup.find_all("a", href=True):
169
  href = a.get("href", "")
170
- if "/video/" not in href and "/xem-lai/" not in href: continue
171
- if not href.startswith("http"): href = "https://xemlaibongda.top" + href
 
 
 
 
 
172
  clean_href = href.split("?")[0].split("#")[0]
173
- if clean_href in seen: continue
 
174
  seen.add(clean_href)
 
 
175
  img_src = ""
176
  img = a.find("img")
177
- if not img and a.parent: img = a.parent.find("img")
 
178
  if not img:
179
  p = a.parent
180
  for _ in range(4):
181
- if p and p.find("img"): img = p.find("img"); break
182
- p = p.parent if p else None
183
- if img:
184
- img_src = (img.get("data-src", "") or img.get("src", "") or img.get("data-lazy", "") or img.get("data-original", "") or img.get("data-thumb", "") or img.get("data-image", ""))
185
- if img_src.startswith("//"): img_src = "https:" + img_src
186
- elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src
187
- if not img_src:
188
- p = a.parent
189
- for _ in range(5):
190
- if p is None: break
191
- style = p.get("style", "")
192
- bg_match = re.search(r'url\(["\']?(.*?)["\']?\)', style)
193
- if bg_match:
194
- img_src = bg_match.group(1)
195
- if img_src.startswith("//"): img_src = "https:" + img_src
196
- elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src
197
  break
198
  p = p.parent if p else None
 
 
 
 
 
 
 
 
 
 
199
  title = ""
 
200
  for attr in ["title", "aria-label"]:
201
  val = a.get(attr, "")
202
- if val and len(val) >= 5: title = val; break
 
 
 
 
203
  if not title:
204
  for selector in ["h3", "h2", "h4", ".title", ".video-title", "strong"]:
205
  try:
206
  el = a.select_one(selector)
207
- if el: t = el.get_text(strip=True)
208
- if t and len(t) >= 5: title = t; break
209
- except: pass
 
 
 
 
 
 
210
  if not title:
211
  text = a.get_text(strip=True)
212
- if text and len(text) >= 5: title = text[:100]
 
 
 
213
  if not title or len(title) < 3:
214
  slug = clean_href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/")
215
  title = slug.replace("-", " ").replace("_", " ").title()
216
  title = re.sub(r'\d{4}-\d{2}-\d{2}', '', title).strip()
217
- if not title or len(title) < 3: continue
 
 
 
 
218
  if not img_src:
219
  slug = clean_href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/")
220
  img_src = f"https://xemlaibongda.top/uploads/thumb/{slug}.jpg"
221
- videos.append({"title": title[:100], "link": clean_href, "img": img_src, "source": "xemlaibongda", "published": _video_published(img_src, clean_href)})
222
- if len(videos) >= limit: break
 
 
 
 
 
 
 
 
 
223
  return videos
224
  except Exception as e:
225
- print(f"[xemlaibongda] Error: {e}"); return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
 
227
  def scrape_xemlaibongda(): return _scrape_xemlaibongda_page("", 20)
228
  def scrape_highlights_by_league(league_key):
229
  if league_key not in HL_LEAGUES: return []
230
- # Try bongdaplus.vn first (reliable from HF Spaces), fallback from there
231
- bp_vids = scrape_bongdaplus_by_league(league_key, 20)
232
- if bp_vids: return bp_vids
233
- # Fallback: xemlaibongda.top (may be slow/unreachable)
234
- vids = _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"], 20)
235
- if vids: return vids
236
- # Ultimate fallback: bongdaplus.vn general video feed, only for primary home league
237
- if league_key == "premier-league":
238
- return scrape_bongdaplus_videos(20)
239
- return []
240
  def scrape_all_league_highlights():
241
  results = {}
242
  def _fetch(key): return key, scrape_highlights_by_league(key)
243
  with ThreadPoolExecutor(8) as ex:
244
  futs = [ex.submit(_fetch, k) for k in HL_LEAGUES]
245
- for f in as_completed(futs, timeout=20):
246
- try: key, vids = f.result()
247
- except: continue
248
- if vids: results[key] = vids
249
- if not results:
250
- fb = scrape_bongdaplus_videos(20)
251
- if fb:
252
- results["premier-league"] = fb
253
- # The league sub-pages resolve to the SAME content from this server (the
254
- # football sites serve one generic list regardless of league path). Return
255
- # the unique videos once per league (deduped against the global set) and
256
- # enrich with the general bongdaplus feed so the homepage slider gets a
257
- # genuinely bigger, duplicate-free list instead of 8x the same 10 clips.
258
- global_seen = set()
259
- seen_per_league = {}
260
- enriched = {}
261
- try:
262
- extra = scrape_bongdaplus_videos(40)
263
- except Exception:
264
- extra = []
265
- for key, vids in list(results.items()):
266
- uniq = []
267
- fresh = []
268
- for v in vids:
269
- link = (v or {}).get("link", "")
270
- if not link or link in seen_per_league.get(key, set()): continue
271
- seen_per_league.setdefault(key, set()).add(link)
272
- if link in global_seen:
273
- fresh.append(v) # duplicate across leagues — will dedupe
274
- continue
275
- global_seen.add(link)
276
- uniq.append(v)
277
- # league-local unique list
278
- if uniq:
279
- results[key] = uniq
280
- # still add across-league dupes to each league so per-league feeds
281
- # are non-empty, but ONLY if the league has < 10 unique videos
282
- if len(uniq) < 10:
283
- for v in fresh:
284
- link = (v or {}).get("link", "")
285
- if link in seen_per_league.get(key, set()): continue
286
- seen_per_league[key].add(link)
287
- uniq.append(v)
288
- results[key] = uniq
289
- # enrich league with global feed leftovers when it's still thin
290
- if len(uniq) < 10:
291
- for v in extra:
292
- link = (v or {}).get("link", "")
293
- if not link or link in seen_per_league.get(key, set()): continue
294
- seen_per_league[key].add(link)
295
- uniq.append(v)
296
- results[key] = uniq
297
- return results
298
-
299
- BDP_HL = "https://bongdaplus.vn/video"
300
- def _video_published(img_src, link=""):
301
- """Best-effort publish date from image URL (bongdaplus stores dates as
302
- /Media/YYYY/MM/DD/) or from a dated slug. Returns 'YYYY-MM-DD' or ''."""
303
- try:
304
- if img_src:
305
- m = re.search(r"/Media/(\d{4})/(\d{2})/(\d{2})/", img_src)
306
- if m:
307
- return "%s-%s-%s" % (m.group(1), m.group(2), m.group(3))
308
- if link:
309
- m2 = re.search(r"/(\d{4})/(\d{2})/(\d{2})/", link)
310
- if m2:
311
- return "%s-%s-%s" % (m2.group(1), m2.group(2), m2.group(3))
312
- except Exception:
313
- pass
314
- return ""
315
-
316
- def scrape_bongdaplus_videos(limit=20):
317
- """Scrape football highlight/clip videos from bongdaplus.vn/video (reachable from HF Spaces)."""
318
- try:
319
- r = requests.get(BDP_HL, headers=HEADERS, timeout=15)
320
- if r.status_code != 200: return []
321
- r.encoding = "utf-8"
322
- soup = BeautifulSoup(r.text, "lxml")
323
- videos = []; seen = set()
324
- for a in soup.find_all("a", href=True):
325
- href = a.get("href","")
326
- if "/video/" not in href or not href.endswith(".html"): continue
327
- if not href.startswith("http"): href = "https://bongdaplus.vn" + href
328
- link = href.split("?")[0].split("#")[0]
329
- if link in seen: continue
330
- seen.add(link)
331
- img_src = ""
332
- img = a.find("img")
333
- if img:
334
- img_src = img.get("data-src","") or img.get("src","") or ""
335
- title = ""
336
- t = a.get("title","") or ""
337
- if t and len(t)>=5: title = t
338
- if not title:
339
- img_alt = img.get("alt","") if img else ""
340
- if img_alt and len(img_alt)>=5: title = img_alt
341
- if not title:
342
- txt = a.get_text(strip=True)
343
- if txt and len(txt)>=5: title = txt
344
- title = re.sub(r'^(VIDEO\s*:\s*|VIDEO\s+)', '', title, flags=re.I).strip()
345
- if not title or len(title)<5: continue
346
- if img_src and img_src.startswith("//"): img_src = "https:" + img_src
347
- videos.append({"title": title[:100], "link": link, "img": img_src, "source": "bongdaplus", "published": _video_published(img_src, link)})
348
- if len(videos) >= limit: break
349
- return videos
350
- except Exception as e:
351
- print(f"[bongdaplus] Error: {e}"); return []
352
-
353
- # Bongdaplus.vn league-specific video URLs (used as fallback when xemlaibongda.top fails)
354
- BDP_LEAGUE_URLS = {
355
- "premier-league": "https://bongdaplus.vn/video/premier-league",
356
- "la-liga": "https://bongdaplus.vn/video/la-liga",
357
- "serie-a": "https://bongdaplus.vn/video/serie-a",
358
- "bundesliga": "https://bongdaplus.vn/video/bundesliga",
359
- "champions-league": "https://bongdaplus.vn/video/champions-league",
360
- "fa-cup": "https://bongdaplus.vn/video/fa-cup",
361
- "europa-league": "https://bongdaplus.vn/video/europa-league",
362
- "world-cup": "https://bongdaplus.vn/video/world-cup",
363
- }
364
- def scrape_bongdaplus_by_league(league_key, limit=20):
365
- """Scrape bongdaplus.vn video page for a specific league."""
366
- url = BDP_LEAGUE_URLS.get(league_key)
367
- if not url: return []
368
- try:
369
- r = requests.get(url, headers=HEADERS, timeout=15)
370
- if r.status_code != 200: return []
371
- r.encoding = "utf-8"
372
- soup = BeautifulSoup(r.text, "lxml")
373
- videos = []; seen = set()
374
- for a in soup.find_all("a", href=True):
375
- href = a.get("href","")
376
- if "/video/" not in href or not href.endswith(".html"): continue
377
- if not href.startswith("http"): href = "https://bongdaplus.vn" + href
378
- link = href.split("?")[0].split("#")[0]
379
- if link in seen: continue
380
- seen.add(link)
381
- img_src = ""
382
- img = a.find("img")
383
- if img:
384
- img_src = img.get("data-src","") or img.get("src","") or ""
385
- title = ""
386
- t = a.get("title","") or ""
387
- if t and len(t)>=5: title = t
388
- if not title:
389
- img_alt = img.get("alt","") if img else ""
390
- if img_alt and len(img_alt)>=5: title = img_alt
391
- if not title:
392
- txt = a.get_text(strip=True)
393
- if txt and len(txt)>=5: title = txt
394
- title = re.sub(r'^(VIDEO\s*:\s*|VIDEO\s+)', '', title, flags=re.I).strip()
395
- if not title or len(title)<5: continue
396
- if img_src and img_src.startswith("//"): img_src = "https:" + img_src
397
- videos.append({"title": title[:100], "link": link, "img": img_src, "source": "bongdaplus", "published": _video_published(img_src, link)})
398
- if len(videos) >= limit: break
399
- return videos
400
- except Exception as e:
401
- print(f"[bongdaplus:{league_key}] Error: {e}"); return []
402
-
403
- def extract_bongdaplus_video(url):
404
- """Extract direct MP4 from bongdaplus.vn video detail via its embed page.
405
-
406
- The embed page (/video-embed/{id}.html) sometimes only has a JPG placeholder
407
- as <source>. In that case, fall back to the main video page
408
- (/video/{slug}.html) which contains a YouTube iframe with the actual
409
- highlight.
410
- """
411
- try:
412
- m = re.search(r'/video/(?:[^/]+-)?(\d+)\.html', url)
413
- if not m:
414
- return None
415
- vid = m.group(1)
416
- embed = f"https://bongdaplus.vn/video-embed/{vid}.html"
417
- r = requests.get(embed, headers=HEADERS, timeout=15)
418
- if r.status_code != 200: return None
419
- r.encoding = "utf-8"
420
- soup = BeautifulSoup(r.text, "lxml")
421
- video = soup.find("video")
422
- src = ""
423
- poster = ""
424
- if video:
425
- src = video.get("src","")
426
- poster = video.get("poster","")
427
- if not src:
428
- src_el = soup.find("source")
429
- if src_el: src = src_el.get("src","")
430
- if not src: return None
431
- src = src.split("?")[0].split("#")[0]
432
- # Only accept real media; placeholder .jpg/jpeg/png means video not available
433
- if not re.search(r'\.(mp4|m3u8|webm)$', src, re.I):
434
- # The embed source is a JPG placeholder — fall back to the main video
435
- # page and look for a YouTube iframe (actual highlight video).
436
  try:
437
- r2 = requests.get(url, headers=HEADERS, timeout=15)
438
- if r2.status_code == 200:
439
- soup2 = BeautifulSoup(r2.text, "lxml")
440
- yt_iframe = soup2.find("iframe", src=re.compile(r"youtube\.com/embed|youtube-nocookie\.com/embed"))
441
- if yt_iframe:
442
- yt_src = yt_iframe.get("src","").strip()
443
- if yt_src.startswith("//"): yt_src = "https:" + yt_src
444
- yt_id = re.search(r'/(?:embed|v)/([a-zA-Z0-9_-]{11})', yt_src)
445
- if yt_id:
446
- poster = poster or ""
447
- if not poster:
448
- og = soup2.find("meta", property="og:image")
449
- if og: poster = og.get("content","")
450
- if not poster:
451
- og = soup.find("meta", property="og:image")
452
- if og: poster = og.get("content","")
453
- return {"src": f"https://www.youtube.com/embed/{yt_id.group(1)}?autoplay=1&rel=0&enablejsapi=1", "poster": poster or yt_src, "type": "youtube"}
454
- except Exception:
455
- pass
456
- return None
457
- if not poster:
458
- og = soup.find("meta",property="og:image")
459
- if og: poster = og.get("content","")
460
- return {"src": src, "poster": poster, "type": "video"}
461
- except Exception:
462
- return None
463
 
464
  def extract_xemlaibongda_video(url):
465
  try:
466
  r=requests.get(url, headers=HEADERS, timeout=15)
467
  if r.status_code!=200: return None
468
- r.encoding="utf-8"; soup=BeautifulSoup(r.text,"lxml")
469
- og=soup.find("meta",property="og:image")
470
- og_poster=og.get("content","") if og else ""
471
- if og_poster.startswith("//"): og_poster="https:"+og_poster
472
- video=soup.find("video")
473
  if video:
474
  src=video.get("src",""); poster=video.get("poster","")
475
  if not src:
476
  source=video.find("source")
477
  if source: src=source.get("src","")
478
- if not poster: poster=og_poster
479
  if src: return{"src":src,"poster":poster,"type":"hls" if".m3u8" in src else"video"}
480
  m3u8s=re.findall(r'(https?://[^\s"\'<>]+\.m3u8)',r.text)
481
- if m3u8s: return{"src":m3u8s[0],"poster":og_poster,"type":"hls"}
482
- yt_iframe = soup.find("iframe", src=re.compile(r"youtube\.com/embed|youtube-nocookie\.com/embed"))
483
- if yt_iframe: return{"src":yt_iframe.get("src",""),"poster":og_poster,"type":"youtube"}
484
  return None
485
  except: return None
486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487
  # ===== LIVESCORE =====
488
  @app.get("/api/livescore/live")
489
  def api_livescore_live(): return JSONResponse({"html":_cached("ls_live",lambda:fetch_bongda_api("/api/fixtures/live"),ttl=_cache_ttl_live)})
@@ -497,207 +524,9 @@ def api_livescore_results():
497
  today=datetime.now(VN_TZ).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)})
498
  @app.get("/api/livescore/standings/{league}")
499
  def api_livescore_standings(league:str):
500
- tid=LEAGUE_IDS.get(league,36781);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)})
501
  @app.get("/api/livescore/date/{date}")
502
  def api_livescore_date(date:str):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/get-by-date?date={date}")})
503
-
504
- def _compute_updates7d():
505
- from datetime import date as _date
506
- today = _date.today()
507
- all_html = []
508
- # Past 7 days (results)
509
- for i in range(7, 0, -1):
510
- d = (today - timedelta(days=i)).strftime("%Y-%m-%d")
511
- html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}&status=finished")
512
- if html and len(html) > 50:
513
- soup = BeautifulSoup(html, "lxml")
514
- day_label = (today - timedelta(days=i)).strftime("%d/%m")
515
- for match in soup.select(".match-detail"):
516
- dt = soup.new_tag("div", **{"class": "datetime"})
517
- dt.string = f"📅 {day_label}"
518
- match.insert(0, dt)
519
- all_html.append(str(soup))
520
- # Next 7 days (upcoming)
521
- for i in range(7):
522
- d = (today + timedelta(days=i)).strftime("%Y-%m-%d")
523
- html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}")
524
- if html and len(html) > 50:
525
- soup = BeautifulSoup(html, "lxml")
526
- day_label = (today + timedelta(days=i)).strftime("%d/%m")
527
- for match in soup.select(".match-detail"):
528
- dt = soup.new_tag("div", **{"class": "datetime"})
529
- dt.string = f"📅 {day_label}"
530
- match.insert(0, dt)
531
- all_html.append(str(soup))
532
- combined = "<div class='updates7d'>" + "".join(all_html) + "</div>"
533
- return combined if all_html else ""
534
-
535
- _updates7d_cache = {"t": 0, "d": "", "busy": False}
536
- _updates7d_lock = threading.Lock()
537
- def _start_updates7d_refresh():
538
- def _run():
539
- try:
540
- with _updates7d_lock:
541
- if _updates7d_cache["busy"]: return
542
- _updates7d_cache["busy"] = True
543
- data = _compute_updates7d()
544
- with _updates7d_lock:
545
- if data:
546
- _updates7d_cache["t"] = time.time()
547
- _updates7d_cache["d"] = data
548
- _updates7d_cache["busy"] = False
549
- except Exception:
550
- with _updates7d_lock:
551
- _updates7d_cache["busy"] = False
552
- th = threading.Thread(target=_run, daemon=True)
553
- th.start()
554
-
555
- @app.get("/api/livescore/updates7d")
556
- def api_livescore_updates7d():
557
- """Aggregate matches. Never blocks synchronously — returns cached value instantly
558
- and refreshes in a background thread. Pre-warmed at startup."""
559
- now = time.time()
560
- with _updates7d_lock:
561
- fresh = _updates7d_cache["d"] and (now - _updates7d_cache["t"] < _cache_ttl)
562
- stale = _updates7d_cache["d"]
563
- if not fresh:
564
- _start_updates7d_refresh()
565
- return JSONResponse({"html": stale or "", "cached": bool(stale)})
566
-
567
- # ===== LIVESCORE RECENT (prioritized: upcoming → just-finished today → yesterday → older) =====
568
- def _compute_recent():
569
- """Compute recent livescore with priority: upcoming → just-finished today → yesterday → older."""
570
- from datetime import date as _date
571
- today = _date.today()
572
- all_html = []
573
-
574
- # Helper to extract match details with date label
575
- def _extract_matches(date_str, day_label, status_param=""):
576
- url_path = f"/api/fixtures/get-by-date?date={date_str}"
577
- if status_param:
578
- url_path += f"&status={status_param}"
579
- html = fetch_bongda_api(url_path)
580
- if not html or len(html) <= 50:
581
- return
582
- soup = BeautifulSoup(html, "lxml")
583
- for match in soup.select(".match-detail"):
584
- dt = soup.new_tag("div", **{"class": "datetime section-date"})
585
- dt.string = f"📅 {day_label}"
586
- match.insert(0, dt)
587
- all_html.append(str(soup))
588
-
589
- # 1) Trận sắp tới (hôm nay + ngày mai)
590
- upcoming_html = []
591
- for offset in [0, 1]:
592
- d = (today + timedelta(days=offset)).strftime("%Y-%m-%d")
593
- day_label = (today + timedelta(days=offset)).strftime("%d/%m")
594
- html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}")
595
- if html and len(html) > 50:
596
- soup = BeautifulSoup(html, "lxml")
597
- for match in soup.select(".match-detail"):
598
- dt = soup.new_tag("div", **{"class": "datetime section-date"})
599
- dt.string = f"📅 {day_label}"
600
- match.insert(0, dt)
601
- upcoming_html.append(str(soup))
602
- if upcoming_html:
603
- all_html.append("<div class='ls-section-header upcoming'><span>⏰ Trận sắp tới</span></div><div class='ls-section-body upcoming'>" + "".join(upcoming_html) + "</div>")
604
-
605
- # 2) Vừa kết thúc hôm nay
606
- today_str = today.strftime("%Y-%m-%d")
607
- finished_today = fetch_bongda_api(f"/api/fixtures/get-by-date?date={today_str}&status=finished")
608
- if finished_today and len(finished_today) > 50:
609
- soup = BeautifulSoup(finished_today, "lxml")
610
- for match in soup.select(".match-detail"):
611
- dt = soup.new_tag("div", **{"class": "datetime section-date"})
612
- dt.string = f"📅 {today.strftime('%d/%m')}"
613
- match.insert(0, dt)
614
- all_html.append("<div class='ls-section-header finished'><span>✅ Vừa kết thúc</span></div><div class='ls-section-body finished'>" + str(soup) + "</div>")
615
-
616
- # 3) Hôm qua
617
- yesterday = today - timedelta(days=1)
618
- d = yesterday.strftime("%Y-%m-%d")
619
- html_yesterday = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}&status=finished")
620
- if html_yesterday and len(html_yesterday) > 50:
621
- soup = BeautifulSoup(html_yesterday, "lxml")
622
- for match in soup.select(".match-detail"):
623
- dt = soup.new_tag("div", **{"class": "datetime section-date"})
624
- dt.string = f"📅 {yesterday.strftime('%d/%m')}"
625
- match.insert(0, dt)
626
- all_html.append("<div class='ls-section-header yesterday'><span>📅 Hôm qua</span></div><div class='ls-section-body yesterday'>" + str(soup) + "</div>")
627
-
628
- # 4) Các ngày cũ hơn (2 ngày trước → 6 ngày trước)
629
- older_html = []
630
- for i in range(2, 7):
631
- d = (today - timedelta(days=i)).strftime("%Y-%m-%d")
632
- day_label = (today - timedelta(days=i)).strftime("%d/%m")
633
- html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}&status=finished")
634
- if html and len(html) > 50:
635
- soup = BeautifulSoup(html, "lxml")
636
- for match in soup.select(".match-detail"):
637
- dt = soup.new_tag("div", **{"class": "datetime section-date"})
638
- dt.string = f"📅 {day_label}"
639
- match.insert(0, dt)
640
- older_html.append(str(soup))
641
- if older_html:
642
- all_html.append("<div class='ls-section-header older'><span>🗓️ Kết quả trước</span></div><div class='ls-section-body older'>" + "".join(older_html) + "</div>")
643
-
644
- combined = "<div class='updates7d'>" + "".join(all_html) + "</div>"
645
- return combined if all_html else ""
646
-
647
- _recent_cache = {"t": 0, "d": "", "busy": False}
648
- _recent_lock = threading.Lock()
649
- def _start_recent_refresh():
650
- def _run():
651
- try:
652
- with _recent_lock:
653
- if _recent_cache["busy"]: return
654
- _recent_cache["busy"] = True
655
- data = _compute_recent()
656
- with _recent_lock:
657
- if data:
658
- _recent_cache["t"] = time.time()
659
- _recent_cache["d"] = data
660
- _recent_cache["busy"] = False
661
- except Exception:
662
- with _recent_lock:
663
- _recent_cache["busy"] = False
664
- th = threading.Thread(target=_run, daemon=True)
665
- th.start()
666
-
667
- @app.get("/api/livescore/recent")
668
- def api_livescore_recent():
669
- """Recent matches with new priority: upcoming today/tomorrow → finished today → yesterday → older."""
670
- now = time.time()
671
- with _recent_lock:
672
- fresh = _recent_cache["d"] and (now - _recent_cache["t"] < _cache_ttl)
673
- stale = _recent_cache["d"]
674
- if not fresh:
675
- _start_recent_refresh()
676
- return JSONResponse({"html": stale or "", "cached": bool(stale)})
677
-
678
- def _warm_recent():
679
- def _warm():
680
- try:
681
- time.sleep(3)
682
- _start_recent_refresh()
683
- except Exception:
684
- pass
685
- th = threading.Thread(target=_warm, daemon=True)
686
- th.start()
687
- _warm_recent()
688
-
689
- def _warm_updates7d():
690
- # Lightweight startup pre-warm so the first user request is instant.
691
- def _warm():
692
- try:
693
- time.sleep(3)
694
- _start_updates7d_refresh()
695
- except Exception:
696
- pass
697
- th = threading.Thread(target=_warm, daemon=True)
698
- th.start()
699
- _warm_updates7d()
700
-
701
  @app.get("/api/match/{event_id}/commentaries")
702
  def api_match_commentaries(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/commentaries?event_id={event_id}")})
703
  @app.get("/api/match/{event_id}/stats")
@@ -734,8 +563,43 @@ def api_livescore_featured():
734
  return None
735
  return JSONResponse(_cached("ls_featured",_f,ttl=30))
736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
737
  @app.get("/api/highlights")
738
- def api_highlights(): return JSONResponse(_cached("xemlaibongda_hl",lambda: scrape_bongdaplus_videos(20) or scrape_xemlaibongda(),ttl=_cache_ttl))
739
  @app.get("/api/highlights/leagues")
740
  def api_highlights_leagues(): return JSONResponse(_cached("hl_leagues",scrape_all_league_highlights,ttl=_cache_ttl))
741
  @app.get("/api/highlights/{league}")
@@ -743,49 +607,8 @@ def api_highlights_league(league:str):
743
  if league not in HL_LEAGUES: return JSONResponse({"error":"league not found"})
744
  return JSONResponse(_cached(f"hl_{league}",lambda:scrape_highlights_by_league(league),ttl=_cache_ttl))
745
 
746
- @app.get("/api/highlights/{league}/page")
747
- def api_highlights_league_page(league:str, page:int=Query(default=0, ge=0), limit:int=Query(default=15, ge=5, le=40)):
748
- """Paginated league highlights for 'Xem thêm' load-more. Supports 'all' to fetch every league aggregated."""
749
- if league == "all":
750
- all_vids = []
751
- with ThreadPoolExecutor(8) as ex:
752
- futs = {ex.submit(scrape_highlights_by_league, k): k for k in HL_LEAGUES}
753
- for f in as_completed(futs, timeout=20):
754
- try:
755
- all_vids.extend(f.result())
756
- except: pass
757
- # The league sub-pages resolve to the same content from this server,
758
- # so dedupe by link — the slider/feed must not show 8x the same 10
759
- # videos. If dedup leaves few unique items, enrich from the general
760
- # bongdaplus video feed to add genuinely different videos.
761
- seen = set(); uniq = []
762
- for v in all_vids:
763
- link = (v or {}).get("link", "")
764
- if not link or link in seen: continue
765
- seen.add(link); uniq.append(v)
766
- if len(uniq) < 20:
767
- try:
768
- extra = scrape_bongdaplus_videos(40)
769
- for v in extra:
770
- link = (v or {}).get("link", "")
771
- if not link or link in seen: continue
772
- seen.add(link); uniq.append(v)
773
- except Exception:
774
- pass
775
- all_vids = uniq
776
- start = page * limit
777
- end = start + limit
778
- paged = all_vids[start:end]
779
- return JSONResponse({"videos": paged, "league": "all", "page": page, "has_more": end < len(all_vids), "total": len(all_vids)})
780
- if league not in HL_LEAGUES: return JSONResponse({"error":"league not found"})
781
- all_vids = scrape_highlights_by_league(league)
782
- start = page * limit
783
- end = start + limit
784
- paged = all_vids[start:end]
785
- return JSONResponse({"videos": paged, "league": league, "page": page, "has_more": end < len(all_vids), "total": len(all_vids)})
786
-
787
  @app.get("/api/video_url")
788
- def api_video_url(url:str=Query(...), img:str=Query(default="")):
789
  if "youtube.com" in url or "youtu.be" in url:
790
  m=re.search(r'(?:v=|shorts/|youtu\.be/)([a-zA-Z0-9_-]{11})',url)
791
  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"})
@@ -793,147 +616,69 @@ def api_video_url(url:str=Query(...), img:str=Query(default="")):
793
  v=extract_xemlaibongda_video(url)
794
  if v:
795
  if v["type"]=="hls": v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="")
796
- if not v.get("poster") and img: v["poster"] = img
797
- return JSONResponse(v)
798
- if "bongdaplus.vn" in url and "/video/" in url:
799
- v=extract_bongdaplus_video(url)
800
- if v:
801
- if not v.get("poster") and img: v["poster"] = img
802
  return JSONResponse(v)
803
  return JSONResponse({"error":"not found"})
804
 
805
- # ===== FPT PLAY (YouTube channel) API =====
806
- # The datacenter cannot reach youtube.com directly, so this endpoint keeps a
807
- # persisted list of the channel's latest videos. The frontend (running in the
808
- # user's browser, which CAN reach YouTube) periodically fetches the channel via
809
- # r.jina.ai, then POSTs the result here so the slide auto-updates when the
810
- # channel uploads — exactly like "Thêm Short HOT" but fully automatic.
811
- FPT_FILE = "/data/fpt_play_videos.json"
812
- FPT_CHANNEL_URL = "https://www.youtube.com/@fptbongdaofficial"
813
- FPT_CACHE_TTL = 600 # 10 min
814
-
815
- def _fpt_load():
816
- try:
817
- if os.path.exists(FPT_FILE):
818
- with open(FPT_FILE, encoding="utf-8") as f:
819
- j = json.load(f)
820
- if isinstance(j, list):
821
- return j
822
- except Exception:
823
- pass
824
- return []
825
-
826
- def _fpt_save(videos):
827
- try:
828
- with open(FPT_FILE, "w", encoding="utf-8") as f:
829
- json.dump(videos, f, ensure_ascii=False)
830
- except Exception:
831
- pass
832
-
833
- def _fpt_try_server_fetch():
834
- """Server-side attempt (jina proxy with our Origin). Usually blocked from
835
- the datacenter, but harmless to try once so the slide works even without
836
- a client push."""
837
- try:
838
- _hdrs = dict(HEADERS)
839
- _hdrs["Origin"] = "https://bep40-vnews.hf.space"
840
- r = requests.get("https://r.jina.ai/" + FPT_CHANNEL_URL + "/videos",
841
- headers=_hdrs, timeout=40)
842
- if r.status_code != 200:
843
- return []
844
- txt = r.text
845
- out = []
846
- seen = set()
847
- # jina markdown lists entries as "1. Title - url" or link lines with yt ids
848
- for m in re.finditer(r"https?://(?:www\.)?youtube\.com/watch\?v=([a-zA-Z0-9_-]{11})", txt):
849
- vid = m.group(1)
850
- if vid in seen: continue
851
- seen.add(vid)
852
- out.append({
853
- "id": vid,
854
- "title": "",
855
- "link": "https://youtu.be/" + vid,
856
- "img": "https://i.ytimg.com/vi/%s/hqdefault.jpg" % vid,
857
- "source": "fptplay",
858
- "published": "",
859
- })
860
- return out
861
- except Exception:
862
- return []
863
-
864
- @app.get("/api/fptplay/videos")
865
- def api_fptplay_videos():
866
- vids = _fpt_load()
867
- if not vids:
868
- vids = _fpt_try_server_fetch()
869
- if vids: _fpt_save(vids)
870
- return JSONResponse({"channel": FPT_CHANNEL_URL, "videos": vids, "updated": int(time.time())})
871
-
872
- @app.post("/api/fptplay/update")
873
- async def api_fptplay_update(request: Request):
874
- try:
875
- body = await request.json()
876
- except Exception:
877
- body = {}
878
- incoming = body.get("videos") or []
879
- if not isinstance(incoming, list) or not incoming:
880
- return JSONResponse({"ok": True, "videos": _fpt_load()})
881
- seen = set()
882
- merged = []
883
- for v in _fpt_load():
884
- vid = (v or {}).get("id", "")
885
- if vid and vid in seen: continue
886
- if vid: seen.add(vid)
887
- merged.append(v)
888
- added = 0
889
- for v in incoming:
890
- vid = (v or {}).get("id", "") or ""
891
- if not vid or vid in seen: continue
892
- seen.add(vid)
893
- # keep user-friendly fields, always normalize the watch link
894
- merged.append({
895
- "id": vid,
896
- "title": (v.get("title") or "").strip()[:200],
897
- "link": (v.get("link") or "https://youtu.be/" + vid),
898
- "img": (v.get("img") or "https://i.ytimg.com/vi/%s/hqdefault.jpg" % vid),
899
- "source": "fptplay",
900
- "published": (v.get("published") or "")[:10],
901
- })
902
- added += 1
903
- # newest first
904
- merged.sort(key=lambda x: (x.get("published") or ""), reverse=True)
905
- _fpt_save(merged[:50])
906
- return JSONResponse({"ok": True, "added": added, "videos": merged[:50]})
907
-
908
  # ===== WORLD CUP 2026 API =====
909
- _wc_request_times = []; _wc_rate_limit_lock = threading.Lock()
910
- _WC_RATE_LIMIT = 10
 
 
 
911
  def _wc_rate_limit():
 
912
  global _wc_request_times
913
  with _wc_rate_limit_lock:
914
  now = time.time()
 
915
  _wc_request_times = [t for t in _wc_request_times if now - t < 60]
916
- if len(_wc_request_times) >= _WC_RATE_LIMIT: return False
 
917
  _wc_request_times.append(now)
918
  return True
919
 
920
  @app.get("/api/wc2026")
921
  def api_wc2026():
 
922
  return JSONResponse(_cached("wc2026", get_wc2026_all, ttl=_cache_ttl))
923
 
924
  @app.get("/api/wc2026/{tab}")
925
  def api_wc2026_tab(tab: str):
 
926
  valid_tabs = ["news", "fixtures", "standings", "stats", "highlights"]
927
- if tab not in valid_tabs: return JSONResponse({"error": "invalid tab"}, status_code=400)
 
 
928
  def _fetch_tab():
929
- if tab == "highlights": return scrape_highlights_by_league("world-cup")
930
- elif tab == "news": return scrape_wc_news()
931
- elif tab == "fixtures": return scrape_fixtures()
932
- elif tab == "standings": return scrape_standings()
933
- elif tab == "stats": return scrape_stats()
 
 
 
 
 
934
  return []
 
935
  return JSONResponse(_cached(f"wc2026_{tab}", _fetch_tab, ttl=_cache_ttl))
936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
937
  @app.get("/api/bdp_videos")
938
  def api_bdp_videos():
939
  def _f():
@@ -970,8 +715,7 @@ def scrape_vne(cat_url):
970
  if src: img=src.get("srcset","").split(",")[0].strip().split(" ")[0]
971
  arts.append({"title":t,"link":lk,"img":img,"source":"vne"})
972
  return arts
973
- except Exception:
974
- return []
975
 
976
  def scrape_genk_ai():
977
  try:
@@ -991,7 +735,8 @@ def scrape_genk_ai():
991
  for img in container.find_all("img"):
992
  s=img.get("data-src","") or img.get("src","")
993
  if s and "mediacdn" in s and "avatar" not in s and "logo" not in s: img_src=s; break
994
- if img_src: break; container=container.parent
 
995
  seen.add(href)
996
  if not img_src:
997
  try:
@@ -1034,73 +779,9 @@ def api_categories():
1034
  for k,(u,n) in VNE_CATS.items(): cats.append({"id":k,"name":n,"source":"vne"})
1035
  return JSONResponse(cats)
1036
 
1037
- @app.get("/api/proxy/xlb")
1038
- def api_xlb(path: str = Query(default=""), limit: int = Query(default=20)):
1039
- # Try xemlaibongda.top first (fast timeout), fallback to bongdaplus.vn
1040
- videos = _do_xlb_scrape_xlb(path, limit)
1041
- if not videos:
1042
- videos = _do_xlb_scrape_bdp(limit)
1043
- if not videos:
1044
- return JSONResponse({"videos": [], "error": "No videos available"})
1045
- return JSONResponse({"videos": videos})
1046
-
1047
- def _do_xlb_scrape_xlb(path, limit):
1048
- try:
1049
- url = f"https://xemlaibongda.top/{path}" if path else "https://xemlaibongda.top/"
1050
- r = requests.get(url, headers=HEADERS, timeout=8)
1051
- if r.status_code != 200: return []
1052
- r.encoding = "utf-8"
1053
- soup = BeautifulSoup(r.text, "lxml")
1054
- videos, seen = [], set()
1055
- for a in soup.find_all("a", href=True):
1056
- href = a.get("href", "")
1057
- if "/video/" not in href and "/xem-lai/" not in href: continue
1058
- if not href.startswith("http"): href = "https://xemlaibongda.top" + href
1059
- clean = href.split("?")[0].split("#")[0]
1060
- if clean in seen: continue
1061
- seen.add(clean)
1062
- img_src = ""
1063
- img = a.find("img") or (a.parent.find("img") if a.parent else None)
1064
- if not img:
1065
- p = a.parent
1066
- for _ in range(5):
1067
- if p and p.find("img"): img = p.find("img"); break
1068
- p = p.parent if p else None
1069
- if img:
1070
- img_src = (img.get("data-src", "") or img.get("src", "") or img.get("data-lazy", "") or img.get("data-original", ""))
1071
- if img_src.startswith("//"): img_src = "https:" + img_src
1072
- elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src
1073
- title = a.find("h3")
1074
- if not title: title = a.find("h2")
1075
- if not title: title = a.find("strong")
1076
- t = title.get_text(strip=True) if title else ""
1077
- if not t:
1078
- slug = clean.split("/video/")[-1].rstrip("/")
1079
- t = slug.replace("-", " ").title()
1080
- videos.append({"title": t[:100], "link": clean, "img": img_src, "source": "xemlaibongda", "published": _video_published(img_src, clean)})
1081
- if len(videos) >= limit: break
1082
- return videos
1083
- except Exception:
1084
- return []
1085
-
1086
- def _do_xlb_scrape_bdp(limit):
1087
- """Fallback: scrape bongdaplus.vn videos for the xlb endpoint."""
1088
- try:
1089
- return scrape_bongdaplus_videos(limit)
1090
- except Exception:
1091
- return []
1092
-
1093
  @app.get("/api/article")
1094
  def api_article(url:str=Query(...)):
1095
- try:
1096
- r2 = requests.get(url, headers=HEADERS, timeout=10)
1097
- if r2.status_code == 200:
1098
- r2.encoding = "utf-8"
1099
- soup = BeautifulSoup(r2.text, "lxml")
1100
- og = soup.find("meta", property="og:image")
1101
- return JSONResponse({"og_image": og.get("content", "") if og else ""})
1102
- except: pass
1103
- return JSONResponse({"og_image": ""})
1104
 
1105
  @app.get("/api/storage_status")
1106
  def api_storage_status():
@@ -1112,4 +793,5 @@ def api_hot_topics():
1112
 
1113
  @app.get("/", response_class=HTMLResponse)
1114
  async def root():
1115
- return HTMLResponse("<h1>VNEWS v17</h1><p>VTV Digital CDN ssaimh · No shorts Dantri/SKDS · Homepage full content</p>")
 
 
1
+ """VNEWS - FastAPI backend with livescore + xemlaibongda highlights + YouTube VTV shorts"""
2
  import re, time, subprocess, json, os, threading
3
  import html as html_lib
4
+ from datetime import datetime, timezone, timedelta
5
  from collections import defaultdict
6
 
7
  VN_TZ = timezone(timedelta(hours=7))
 
14
 
15
  app = FastAPI()
16
 
17
+ # ===== RATE LIMITING =====app = FastAPI()
18
+
19
  # ===== WORLD CUP 2026 SCRAPER =====
20
  from wc2026_scraper import get_wc2026_all, scrape_fixtures, scrape_standings, scrape_stats, scrape_wc_news
21
 
22
  # ===== RATE LIMITING =====
23
+ _rate_limit_data = defaultdict(list) # {ip: [timestamp1, timestamp2, ...]}
24
  _rate_limit_lock = threading.Lock()
25
+ RATE_LIMIT_MAX = 60 # Max requests per minute per IP
26
+ RATE_LIMIT_WINDOW = 60 # seconds
27
 
28
  def _check_rate_limit(ip: str) -> bool:
29
+ """Kiểm tra rate limit, return True nếu OK, False nếu bị limit"""
30
  with _rate_limit_lock:
31
  now = time.time()
32
+ # Xóa các request cũ
33
  _rate_limit_data[ip] = [t for t in _rate_limit_data[ip] if now - t < RATE_LIMIT_WINDOW]
34
+ if len(_rate_limit_data[ip]) >= RATE_LIMIT_MAX:
35
+ return False
36
  _rate_limit_data[ip].append(now)
37
  return True
38
 
39
  @app.middleware("http")
40
  async def rate_limit_middleware(request: Request, call_next):
41
+ """Middleware để kiểm tra rate limit"""
42
+ # Chỉ rate limit API endpoints
43
  if request.url.path.startswith("/api/"):
44
  ip = request.client.host
45
+ if not _check_rate_limit(ip):
46
+ return JSONResponse({"error": "rate limit exceeded"}, status_code=429)
47
+ response = await call_next(request)
48
+ return response
49
 
50
  # ===== VTV CHANNELS API =====
51
  from vtv_api import router as vtv_router
 
59
  _cache_ttl_live = 60
60
  _cache_ttl_yt = 1800
61
 
62
+ # ===== VTV NAM BO SHORTS FALLBACK =====
63
+ SHORTS_FALLBACK = [
64
+ {"id":"nqlLH6chLRo","title":"Tin nóng VTV Nam Bộ | #shorts","channel":"vtvnambo"},
65
+ {"id":"E7Kq0v3hG6w","title":"VTV Nam Bộ - Tin tức miền Nam | #shorts","channel":"vtvnambo"},
66
+ {"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","channel":"baodantri7941"},
67
+ {"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","channel":"baodantri7941"},
68
+ {"id":"tvPewsc2ph4","title":"Tính năng ẩn trên iPhone giúp giảm mỏi mắt","channel":"baodantri7941"},
69
+ {"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","channel":"baodantri7941"},
70
+ {"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ù","channel":"baodantri7941"},
71
+ {"id":"Htzvwg6iOBM","title":"Xe điện Audi S6 Sportback e-tron có gì đặc biệt?","channel":"baodantri7941"},
72
+ {"id":"iMdFmWvYdlo","title":"Cô gái người Nga yêu thời trang và đất nước Việt Nam","channel":"baodantri7941"},
73
+ {"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","channel":"baodantri7941"},
74
+ {"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","channel":"baodantri7941"},
75
+ {"id":"VAfgNNgZDRs","title":"Khởi tố 4 đối tượng ném bom xăng vào nhà dân ở Đồng Nai","channel":"baodantri7941"},
76
+ {"id":"sBH_-zGh0Xw","title":"Vì sao Times New Roman vẫn nổi tiếng sau hàng chục năm?","channel":"baodantri7941"},
77
+ {"id":"woKn5f2bLHM","title":"Quảng Ninh ngập sâu diện rộng sau đợt mưa lớn","channel":"baodantri7941"},
78
+ {"id":"bcpgRoxbLPw","title":"Giông lốc quật bay mái tôn ở TP.HCM","channel":"baodantri7941"},
79
+ {"id":"ZIIC5osy544","title":"Bé trai Trung Quốc rơi từ tầng 11 vẫn sống sót kỳ diệu","channel":"baodantri7941"},
80
+ {"id":"uTMJ49NQpyc","title":"Sau lớp mascot 40kg Câu chuyện mưu sinh của người trẻ ở TPHCM","channel":"baodantri7941"},
81
+ {"id":"7Pd6vZ2Lz1M","title":"Hành động ấm lòng của người đàn ông tìm kiếm 5 học sinh tử vong ở sông Lô","channel":"baosuckhoedoisongboyte"},
82
+ {"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","channel":"baosuckhoedoisongboyte"},
83
+ {"id":"IUOprcJyYr4","title":"Phụ nữ táo bón có phải do lười ăn rau?","channel":"baosuckhoedoisongboyte"},
84
+ {"id":"YY8ojFNE-AU","title":"Quái xế tự quay clip nẹt pô đánh võng đăng TikTok bị xử lý","channel":"baosuckhoedoisongboyte"},
85
+ {"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","channel":"baosuckhoedoisongboyte"},
86
+ {"id":"FoxhFyz2skY","title":"Người đàn ông nước ngoài đập phá ô tô bẻ cần gạt nước ở Đà Nẵng","channel":"baosuckhoedoisongboyte"},
87
+ {"id":"R1oC_I8dFPU","title":"Thanh niên buông tay lái đứng trên xe máy khi đổ đèo ở Đắk Lắk","channel":"baosuckhoedoisongboyte"},
88
+ {"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","channel":"baosuckhoedoisongboyte"},
89
+ {"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","channel":"baosuckhoedoisongboyte"},
90
+ {"id":"pXWt0QbAzRQ","title":"Va chạm giao thông người phụ nữ lăng mạ tài xế ô tô","channel":"baosuckhoedoisongboyte"},
91
+ {"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","channel":"baosuckhoedoisongboyte"},
92
+ {"id":"AxhVTQutsuo","title":"Xuất tinh sớm và những hiểu lầm thường gặp","channel":"baosuckhoedoisongboyte"},
93
+ {"id":"cNy6FgaNxYM","title":"Cô dâu khóc sưng mắt vì 6 chỉ vàng không cánh mày bay trong ngày cưới","channel":"baosuckhoedoisongboyte"},
94
+ {"id":"IDt_S6q59Ro","title":"Chở bạn gái không đội mũ bảo hiểm thanh niên đấm CSGT","channel":"baosuckhoedoisongboyte"},
95
+ {"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","channel":"baosuckhoedoisongboyte"},
96
+ ]
97
+ for _v in SHORTS_FALLBACK:
98
+ _v.setdefault("link", "https://www.youtube.com/watch?v="+_v["id"])
99
+ _v.setdefault("img", "https://i.ytimg.com/vi/"+_v["id"]+"/hqdefault.jpg")
100
+ _v.setdefault("source", "yt")
101
+
102
+ SHORT_STATS_FILE = "/data/short_stats.json" if os.path.isdir("/data") else "/app/short_stats.json"
103
+ _short_lock = threading.Lock()
104
+ def _load_short_db():
105
+ try:
106
+ if os.path.exists(SHORT_STATS_FILE):
107
+ with open(SHORT_STATS_FILE,"r",encoding="utf-8") as f: return json.load(f)
108
+ except: pass
109
+ return {}
110
+ def _save_short_db(db):
111
+ try:
112
+ os.makedirs(os.path.dirname(SHORT_STATS_FILE), exist_ok=True)
113
+ tmp = SHORT_STATS_FILE + ".tmp"
114
+ with open(tmp,"w",encoding="utf-8") as f: json.dump(db, f, ensure_ascii=False)
115
+ os.replace(tmp, SHORT_STATS_FILE)
116
+ except: pass
117
+ def _short_default(): return {"views":0,"likes":0,"shares":0,"comments":[]}
118
+
119
  PRIORITY_LEAGUES = ["Ngoại Hạng Anh","FA Cup","Champions League","LaLiga","Copa del Rey","Serie A","Bundesliga","Ligue 1","V-League"]
120
+ LEAGUE_IDS = {"nha":27110,"laliga":27233,"seriea":27044,"bundesliga":26891,"ligue1":27212}
121
  HL_LEAGUES = {
122
  "premier-league":{"path":"anh/premier-league","name":"Premier League","emoji":"🏴󠁧󠁢󠁥󠁮󠁧󠁿"},
123
  "fa-cup":{"path":"anh/fa-cup","name":"FA Cup","emoji":"🏆"},
 
135
  except: data=_cache.get(key,{}).get("d",[])
136
  _cache[key]={"d":data,"t":now}; return data
137
  def _get(url, headers=None):
138
+ h=headers or HEADERS; r=requests.get(url, headers=h, timeout=15); r.encoding="utf-8"
139
+ return BeautifulSoup(r.text,"lxml")
 
 
 
 
 
 
 
 
 
140
  def fetch_bongda_api(endpoint):
141
  try:
142
  r=requests.get(f"https://bongda.com.vn{endpoint}", headers=BONGDA_HEADERS, timeout=10)
 
202
  @app.get("/api/proxy/img")
203
  def proxy_img(url: str = Query(...)):
204
  try:
205
+ r = requests.get(url, headers={**HEADERS, "Referer": "https://dantri.com.vn/"}, timeout=10)
 
 
 
 
 
 
206
  if r.status_code != 200: return Response(status_code=502)
207
+ ct = r.headers.get("Content-Type", "image/jpeg")
208
+ return Response(content=r.content, media_type=ct, headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"})
209
  except: return Response(status_code=502)
210
 
211
  # ===== XEMLAIBONGDA HIGHLIGHTS =====
212
  def _scrape_xemlaibongda_page(page_path, limit=20):
213
+ """
214
+ Scrape video từ xemlaibongda.top - Simple & Reliable
215
+ Dùng logic cũ đã test, không fetch từng trang (tránh timeout)
216
+ """
217
  try:
218
  url = f"https://xemlaibongda.top/{page_path}" if page_path else "https://xemlaibongda.top/"
219
+ r = requests.get(url, headers=HEADERS, timeout=15)
220
+ if r.status_code != 200:
221
+ return []
222
  r.encoding = "utf-8"
223
  soup = BeautifulSoup(r.text, "lxml")
224
+ videos = []
225
+ seen = set()
226
+
227
  for a in soup.find_all("a", href=True):
228
  href = a.get("href", "")
229
+ if "/video/" not in href and "/xem-lai/" not in href:
230
+ continue
231
+
232
+ if not href.startswith("http"):
233
+ href = "https://xemlaibongda.top" + href
234
+
235
+ # Bỏ query params
236
  clean_href = href.split("?")[0].split("#")[0]
237
+ if clean_href in seen:
238
+ continue
239
  seen.add(clean_href)
240
+
241
+ # ===== Lấy THUMBNAIL =====
242
  img_src = ""
243
  img = a.find("img")
244
+ if not img and a.parent:
245
+ img = a.parent.find("img")
246
  if not img:
247
  p = a.parent
248
  for _ in range(4):
249
+ if p and p.find("img"):
250
+ img = p.find("img")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  break
252
  p = p.parent if p else None
253
+
254
+ if img:
255
+ img_src = (img.get("data-src", "") or img.get("src", "") or
256
+ img.get("data-lazy", "") or img.get("data-original", ""))
257
+ if img_src.startswith("//"):
258
+ img_src = "https:" + img_src
259
+ elif img_src.startswith("/"):
260
+ img_src = "https://xemlaibongda.top" + img_src
261
+
262
+ # ===== Lấy TITLE =====
263
  title = ""
264
+ # Thử attribute
265
  for attr in ["title", "aria-label"]:
266
  val = a.get(attr, "")
267
+ if val and len(val) >= 5:
268
+ title = val
269
+ break
270
+
271
+ # Thử các selector
272
  if not title:
273
  for selector in ["h3", "h2", "h4", ".title", ".video-title", "strong"]:
274
  try:
275
  el = a.select_one(selector)
276
+ if el:
277
+ t = el.get_text(strip=True)
278
+ if len(t) >= 5:
279
+ title = t
280
+ break
281
+ except:
282
+ pass
283
+
284
+ # Thử text content
285
  if not title:
286
  text = a.get_text(strip=True)
287
+ if text and len(text) >= 5:
288
+ title = text[:100]
289
+
290
+ # Fallback: tạo title từ slug
291
  if not title or len(title) < 3:
292
  slug = clean_href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/")
293
  title = slug.replace("-", " ").replace("_", " ").title()
294
  title = re.sub(r'\d{4}-\d{2}-\d{2}', '', title).strip()
295
+
296
+ if not title or len(title) < 3:
297
+ continue
298
+
299
+ # Fallback thumbnail từ slug
300
  if not img_src:
301
  slug = clean_href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/")
302
  img_src = f"https://xemlaibongda.top/uploads/thumb/{slug}.jpg"
303
+
304
+ videos.append({
305
+ "title": title[:100],
306
+ "link": clean_href,
307
+ "img": img_src,
308
+ "source": "xemlaibongda"
309
+ })
310
+
311
+ if len(videos) >= limit:
312
+ break
313
+
314
  return videos
315
  except Exception as e:
316
+ print(f"[xemlaibongda] Error: {e}")
317
+ return []
318
+
319
+ def _extract_img_src(a_tag):
320
+ """Extract image URL từ thẻ <a> và parent elements"""
321
+ img = a_tag.find("img")
322
+ if not img and a_tag.parent:
323
+ img = a_tag.parent.find("img")
324
+ if not img:
325
+ p = a_tag.parent
326
+ for _ in range(5): # Tìm sâu hơn
327
+ if p and p.find("img"):
328
+ img = p.find("img")
329
+ break
330
+ p = p.parent if p else None
331
+
332
+ if not img:
333
+ return ""
334
+
335
+ # Thử tất cả các attribute có thể chứa img URL
336
+ attrs = ["data-src", "src", "data-lazy", "data-original", "data-srcset", "data-thumb", "data-image"]
337
+ for attr in attrs:
338
+ val = img.get(attr, "")
339
+ if val:
340
+ if attr == "data-srcset":
341
+ val = val.split(",")[0].strip().split(" ")[0]
342
+ break
343
+ else:
344
+ val = ""
345
+
346
+ # Thử background-image từ style
347
+ if not val:
348
+ style = img.get("style", "") or img.get("data-bg", "")
349
+ bg_match = re.search(r'url\(["\']?(.*?)["\']?\)', style)
350
+ if bg_match:
351
+ val = bg_match.group(1)
352
+
353
+ # Normalize URL
354
+ if val.startswith("//"):
355
+ val = "https:" + val
356
+ elif val.startswith("/"):
357
+ val = "https://xemlaibongda.top" + val
358
+
359
+ return val
360
+
361
+ def _extract_title(a_tag, href):
362
+ """Extract title từ thẻ <a> và child/parent elements"""
363
+ title = ""
364
+
365
+ # 1. Thử các selector phổ biến cho title
366
+ title_selectors = [
367
+ "h3", "h2", "h4", "h5",
368
+ ".title", ".post-title", ".entry-title", ".video-title",
369
+ ".card-title", ".item-title", ".news-title",
370
+ "span.title", "strong", "b",
371
+ ".name", ".caption"
372
+ ]
373
+ for tag in title_selectors:
374
+ try:
375
+ t = a_tag.select_one(tag) if hasattr(a_tag, 'select_one') else None
376
+ if t:
377
+ title = t.get_text(" ", strip=True)
378
+ if len(title) >= 3:
379
+ return title
380
+ except:
381
+ pass
382
+
383
+ # 2. Thử attribute của <a>
384
+ for attr in ["title", "aria-label", "data-title"]:
385
+ val = a_tag.get(attr, "")
386
+ if val and len(val) >= 3:
387
+ return val
388
+
389
+ # 3. Thử alt text của img
390
+ img = a_tag.find("img")
391
+ if img:
392
+ alt = img.get("alt", "")
393
+ if alt and len(alt) >= 3:
394
+ return alt
395
+
396
+ # 4. Thử text content của <a> (loại bỏ quá dài)
397
+ text = a_tag.get_text(" ", strip=True)
398
+ if text and len(text) >= 3:
399
+ # Lấy dòng đầu tiên nếu có nhiều dòng
400
+ lines = [l.strip() for l in text.split("\n") if l.strip()]
401
+ if lines:
402
+ first_line = lines[0]
403
+ if len(first_line) >= 3:
404
+ return first_line[:100]
405
+
406
+ # 5. Fallback: tạo title từ slug
407
+ slug = href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/")
408
+ title = slug.replace("-", " ").replace("_", " ")
409
+ title = re.sub(r'\d{4}-\d{2}-\d{2}', '', title).strip()
410
+ if title:
411
+ return title.title()
412
+
413
+ return ""
414
 
415
  def scrape_xemlaibongda(): return _scrape_xemlaibongda_page("", 20)
416
  def scrape_highlights_by_league(league_key):
417
  if league_key not in HL_LEAGUES: return []
418
+ return _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"], 20)
 
 
 
 
 
 
 
 
 
419
  def scrape_all_league_highlights():
420
  results = {}
421
  def _fetch(key): return key, scrape_highlights_by_league(key)
422
  with ThreadPoolExecutor(8) as ex:
423
  futs = [ex.submit(_fetch, k) for k in HL_LEAGUES]
424
+ for f in as_completed(futs, timeout=25):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  try:
426
+ key, vids = f.result()
427
+ if vids: results[key] = vids
428
+ except: pass
429
+ return results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
430
 
431
  def extract_xemlaibongda_video(url):
432
  try:
433
  r=requests.get(url, headers=HEADERS, timeout=15)
434
  if r.status_code!=200: return None
435
+ r.encoding="utf-8"; soup=BeautifulSoup(r.text,"lxml"); video=soup.find("video")
 
 
 
 
436
  if video:
437
  src=video.get("src",""); poster=video.get("poster","")
438
  if not src:
439
  source=video.find("source")
440
  if source: src=source.get("src","")
 
441
  if src: return{"src":src,"poster":poster,"type":"hls" if".m3u8" in src else"video"}
442
  m3u8s=re.findall(r'(https?://[^\s"\'<>]+\.m3u8)',r.text)
443
+ if m3u8s:
444
+ og=soup.find("meta",property="og:image"); poster=og.get("content","") if og else ""
445
+ return{"src":m3u8s[0],"poster":poster,"type":"hls"}
446
  return None
447
  except: return None
448
 
449
+ # ===== YOUTUBE SHORTS SCRAPING =====
450
+ def _yt_channel_shorts_requests(channel, count=15):
451
+ try:
452
+ url=f"https://www.youtube.com/@{channel}/shorts"
453
+ r=requests.get(url, headers={**HEADERS,"Accept-Language":"vi,en;q=0.8"}, timeout=15)
454
+ if r.status_code!=200: return []
455
+ html=r.text; ids=[]; items=[]
456
+ for m in re.finditer(r'"videoId":"([A-Za-z0-9_-]{11})"',html):
457
+ vid=m.group(1)
458
+ if vid in ids: continue
459
+ ids.append(vid)
460
+ snip=html[max(0,m.start()-900):m.start()+1600]
461
+ title=""
462
+ mt=re.search(r'"title":\{"runs":\[\{"text":"([^"]+)"',snip)
463
+ if not mt: mt=re.search(r'"accessibilityText":"([^"]+)"',snip)
464
+ if mt: title=html_lib.unescape(mt.group(1)).replace('\n',' ').strip()
465
+ if not title: title="YouTube Short"
466
+ 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})
467
+ if len(items)>=count: break
468
+ return items
469
+ except: return []
470
+
471
+ def scrape_shorts():
472
+ vids=[]
473
+ with ThreadPoolExecutor(3) as ex:
474
+ futs=[ex.submit(_yt_channel_shorts_requests,ch,24) for ch in ["baodantri7941","baosuckhoedoisongboyte","vtvnambo"]]
475
+ for f in as_completed(futs):
476
+ try:
477
+ r=f.result()
478
+ if r: vids.extend(r)
479
+ except: pass
480
+ merged=[]; seen=set()
481
+ for v in vids:
482
+ vid=v.get("id")
483
+ if not vid or vid in seen: continue
484
+ seen.add(vid); merged.append(v)
485
+ for v in SHORTS_FALLBACK:
486
+ vid=v.get("id")
487
+ if not vid or vid in seen: continue
488
+ seen.add(vid); merged.append(v)
489
+ return merged[:60]
490
+
491
+ # ===== VTV NAM BO & WC SHORTS - using yt-dlp =====
492
+ from yt_scraper import get_vtvnambo_shorts, get_wc_related_shorts
493
+
494
+ @app.get("/api/shorts/vtvnamo")
495
+ def api_shorts_vtvnamo(count: int = Query(default=50, le=100)):
496
+ items = get_vtvnambo_shorts(count)
497
+ if not items:
498
+ items = [v for v in SHORTS_FALLBACK if v.get("channel") == "vtvnambo"]
499
+ nql = [v for v in items if v.get("id") == "nqlLH6chLRo"]
500
+ rest = [v for v in items if v.get("id") != "nqlLH6chLRo"]
501
+ items = nql + rest
502
+ return JSONResponse(items)
503
+
504
+ @app.get("/api/shorts/wc")
505
+ def api_shorts_wc(count: int = Query(default=50, le=100)):
506
+ items = get_wc_related_shorts(count)
507
+ if not items:
508
+ items = [v for v in SHORTS_FALLBACK if v.get("channel") == "vtvnambo"]
509
+ nql = [v for v in items if v.get("id") == "nqlLH6chLRo"]
510
+ rest = [v for v in items if v.get("id") != "nqlLH6chLRo"]
511
+ items = nql + rest
512
+ return JSONResponse(items)
513
+
514
  # ===== LIVESCORE =====
515
  @app.get("/api/livescore/live")
516
  def api_livescore_live(): return JSONResponse({"html":_cached("ls_live",lambda:fetch_bongda_api("/api/fixtures/live"),ttl=_cache_ttl_live)})
 
524
  today=datetime.now(VN_TZ).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)})
525
  @app.get("/api/livescore/standings/{league}")
526
  def api_livescore_standings(league:str):
527
+ 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)})
528
  @app.get("/api/livescore/date/{date}")
529
  def api_livescore_date(date:str):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/get-by-date?date={date}")})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
530
  @app.get("/api/match/{event_id}/commentaries")
531
  def api_match_commentaries(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/commentaries?event_id={event_id}")})
532
  @app.get("/api/match/{event_id}/stats")
 
563
  return None
564
  return JSONResponse(_cached("ls_featured",_f,ttl=30))
565
 
566
+ @app.get("/api/shorts")
567
+ def api_shorts(channel: str = Query(default="")):
568
+ if channel == "vtvnambo": return api_shorts_vtvnamo()
569
+ if channel == "wc": return api_shorts_wc()
570
+ return JSONResponse(_cached("yt_shorts_v3",scrape_shorts,ttl=_cache_ttl_yt))
571
+
572
+ @app.get("/api/short-stats")
573
+ def api_short_stats(ids:str=Query(default="")):
574
+ arr=[x for x in ids.split(",") if x]
575
+ with _short_lock:
576
+ db=_load_short_db();out={}
577
+ for vid in arr:
578
+ st=db.get(vid) or _short_default()
579
+ 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]}
580
+ return JSONResponse({"stats":out})
581
+
582
+ @app.post("/api/short-action")
583
+ async def api_short_action(request:Request):
584
+ try: body=await request.json()
585
+ except: body={}
586
+ vid=str(body.get("id","")).strip(); action=str(body.get("action","")).strip(); txt=str(body.get("text","")).strip()
587
+ if not vid: return JSONResponse({"error":"missing id"},status_code=400)
588
+ with _short_lock:
589
+ db=_load_short_db(); st=db.get(vid) or _short_default()
590
+ if action=="view": st["views"]=int(st.get("views",0))+1
591
+ elif action=="like": st["likes"]=int(st.get("likes",0))+1
592
+ elif action=="share": st["shares"]=int(st.get("shares",0))+1
593
+ elif action=="comment" and txt:
594
+ comments=st.get("comments",[])
595
+ comments.insert(0,{"text":txt[:180],"ts":int(time.time())})
596
+ st["comments"]=comments[:80]
597
+ st["updated"]=int(time.time()); db[vid]=st; _save_short_db(db)
598
+ out={"views":int(st.get("views",0)),"likes":int(st.get("likes",0)),"shares":int(st.get("shares",0)),"comments":st.get("comments",[])[:80]}
599
+ return JSONResponse({"stats":out})
600
+
601
  @app.get("/api/highlights")
602
+ def api_highlights(): return JSONResponse(_cached("xemlaibongda_hl",scrape_xemlaibongda,ttl=_cache_ttl))
603
  @app.get("/api/highlights/leagues")
604
  def api_highlights_leagues(): return JSONResponse(_cached("hl_leagues",scrape_all_league_highlights,ttl=_cache_ttl))
605
  @app.get("/api/highlights/{league}")
 
607
  if league not in HL_LEAGUES: return JSONResponse({"error":"league not found"})
608
  return JSONResponse(_cached(f"hl_{league}",lambda:scrape_highlights_by_league(league),ttl=_cache_ttl))
609
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610
  @app.get("/api/video_url")
611
+ def api_video_url(url:str=Query(...)):
612
  if "youtube.com" in url or "youtu.be" in url:
613
  m=re.search(r'(?:v=|shorts/|youtu\.be/)([a-zA-Z0-9_-]{11})',url)
614
  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"})
 
616
  v=extract_xemlaibongda_video(url)
617
  if v:
618
  if v["type"]=="hls": v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="")
 
 
 
 
 
 
619
  return JSONResponse(v)
620
  return JSONResponse({"error":"not found"})
621
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
622
  # ===== WORLD CUP 2026 API =====
623
+ # Rate limiting cho WC API
624
+ _wc_request_times = []
625
+ _wc_rate_limit_lock = threading.Lock()
626
+ _WC_RATE_LIMIT = 10 # Max 10 requests per minute
627
+
628
  def _wc_rate_limit():
629
+ """Kiểm tra rate limit cho WC API"""
630
  global _wc_request_times
631
  with _wc_rate_limit_lock:
632
  now = time.time()
633
+ # Xóa các request cũ hơn 60 giây
634
  _wc_request_times = [t for t in _wc_request_times if now - t < 60]
635
+ if len(_wc_request_times) >= _WC_RATE_LIMIT:
636
+ return False
637
  _wc_request_times.append(now)
638
  return True
639
 
640
  @app.get("/api/wc2026")
641
  def api_wc2026():
642
+ """Trả về tất cả dữ liệu World Cup 2026"""
643
  return JSONResponse(_cached("wc2026", get_wc2026_all, ttl=_cache_ttl))
644
 
645
  @app.get("/api/wc2026/{tab}")
646
  def api_wc2026_tab(tab: str):
647
+ """Trả về từng tab của World Cup"""
648
  valid_tabs = ["news", "fixtures", "standings", "stats", "highlights"]
649
+ if tab not in valid_tabs:
650
+ return JSONResponse({"error": "invalid tab"}, status_code=400)
651
+
652
  def _fetch_tab():
653
+ if tab == "highlights":
654
+ return scrape_highlights_by_league("world-cup")
655
+ elif tab == "news":
656
+ return scrape_wc_news()
657
+ elif tab == "fixtures":
658
+ return scrape_fixtures()
659
+ elif tab == "standings":
660
+ return scrape_standings()
661
+ elif tab == "stats":
662
+ return scrape_stats()
663
  return []
664
+
665
  return JSONResponse(_cached(f"wc2026_{tab}", _fetch_tab, ttl=_cache_ttl))
666
 
667
+ # Note: WC functions (scrape_wc_news, scrape_fixtures, scrape_stats, scrape_standings)
668
+ # are imported from wc2026_scraper.py at the top of this file
669
+
670
+ @app.get("/api/video_url")
671
+ def api_video_url(url:str=Query(...)):
672
+ if "youtube.com" in url or "youtu.be" in url:
673
+ m=re.search(r'(?:v=|shorts/|youtu\.be/)([a-zA-Z0-9_-]{11})',url)
674
+ 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"})
675
+ if "xemlaibongda.top" in url:
676
+ v=extract_xemlaibongda_video(url)
677
+ if v:
678
+ if v["type"]=="hls": v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="")
679
+ return JSONResponse(v)
680
+ return JSONResponse({"error":"not found"})
681
+
682
  @app.get("/api/bdp_videos")
683
  def api_bdp_videos():
684
  def _f():
 
715
  if src: img=src.get("srcset","").split(",")[0].strip().split(" ")[0]
716
  arts.append({"title":t,"link":lk,"img":img,"source":"vne"})
717
  return arts
718
+ except: return []
 
719
 
720
  def scrape_genk_ai():
721
  try:
 
735
  for img in container.find_all("img"):
736
  s=img.get("data-src","") or img.get("src","")
737
  if s and "mediacdn" in s and "avatar" not in s and "logo" not in s: img_src=s; break
738
+ if img_src: break
739
+ container=container.parent
740
  seen.add(href)
741
  if not img_src:
742
  try:
 
779
  for k,(u,n) in VNE_CATS.items(): cats.append({"id":k,"name":n,"source":"vne"})
780
  return JSONResponse(cats)
781
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
782
  @app.get("/api/article")
783
  def api_article(url:str=Query(...)):
784
+ return JSONResponse({"error":"not supported"})
 
 
 
 
 
 
 
 
785
 
786
  @app.get("/api/storage_status")
787
  def api_storage_status():
 
793
 
794
  @app.get("/", response_class=HTMLResponse)
795
  async def root():
796
+ return HTMLResponse("<h1>VNEWS</h1><p>Running</p>")
797
+ # v14 rebuild 2026-06-18T12:21:41.503230
patch_ai_hot.py DELETED
@@ -1,55 +0,0 @@
1
- """PATCH AI: prepend AI topics to hot list + homepage route fix"""
2
- import re, json, time
3
- from fastapi.responses import HTMLResponse
4
-
5
- # Import at runtime to avoid circular
6
- try:
7
- from main import app, rt
8
- import ai_runtime_final6 as f6
9
- from ai_runtime_final6 import f5
10
- except:
11
- f6, f5, rt = None, None, None
12
-
13
- # Patch hot_topics to prepend AI topics
14
- if f6 and hasattr(f6, '_HOT_CACHE') and hasattr(f6, '_hot_topics'):
15
- _orig_hot = f6._hot_topics
16
- def _hot_topics_patched():
17
- topics = _orig_hot()
18
- # Prepend AI topics to front
19
- for ai in ['Công nghệ AI', 'World Cup 2026', 'Kinh tế Việt Nam']:
20
- if not any(ai.lower() == t.get('topic','').lower() for t in topics):
21
- topics.insert(0, {'label': f'#{ai.replace(" ", "")}', 'topic': ai, 'count': 0})
22
- return topics[:24]
23
- f6._hot_topics = f6._HOT_CACHE['d'] = _hot_topics_patched()
24
- f6._HOT_CACHE['t'] = time.time()
25
-
26
- PATCH_INJECT = r'''
27
- <script>
28
- const AI_HOT_TOPICS = ['Công nghệ AI', 'World Cup 2026', 'Kinh tế Việt Nam', 'Bóng đá châu Âu'];
29
- async function ensureHotTopics(){let i=document.getElementById('ai-topic-input-final5');if(!i||document.getElementById('ai-hot-row'))return;let r=document.createElement('div');r.id='ai-hot-row';r.style.cssText='display:flex;gap:6px;overflow-x:auto;padding:4px 0;margin:6px 0';let t=[];try{let j=await fetch('/api/hot_topics').then(r=>r.json()).catch(()=>({topics:[]}));t=j.topics||[];}catch(e){}AI_HOT_TOPICS.forEach(ai=>{if(!t.find(x=>(x.topic||'').toLowerCase()===ai.toLowerCase())){t.unshift({label:'#'+ai.replace(/\s+/g,''),topic:ai});}});r.innerHTML=t.slice(0,14).map(x=>`<button class="hot-chip" style="flex:0 0 auto;background:#222;border:1px solid #333;color:#ddd;border-radius:16px;padding:5px 10px;font-size:11px;cursor:pointer" onclick="document.getElementById('ai-topic-input-final5').value='${x.topic.replace(/'/g,'\\''}';document.getElementById('ai-topic-input-final5').focus();searchTopic('${x.topic.replace(/'/g,'\\''}')">${x.label}</button>`).join('');i.insertAdjacentElement('afterend',r);}
30
- setInterval(ensureHotTopics,1500);
31
- </script>
32
- '''
33
-
34
- # Register homepage route
35
- if app and f5 and f6:
36
- # Remove old / route
37
- app.router.routes = [r for r in app.router.routes if not (getattr(r,'path',None)=='/' and 'GET' in getattr(r,'methods',set()))]
38
-
39
- @app.get('/')
40
- async def patch_homepage():
41
- html = f5.f4.f3.f2.f1._load_index_html() if f5 else "<html><body></body></html>"
42
- body = (getattr(rt.old,'PATCH_INJECT','') if hasattr(rt,'old') else '') + \
43
- (getattr(f5.f4.f3.f2.f1,'FINAL_INJECT','') if f5 else '') + \
44
- (getattr(f5.f4.f3,'FINAL3_INJECT','') if f5 else '') + \
45
- (getattr(f5.f4,'FINAL4_INJECT','') if f5 else '') + \
46
- (getattr(f5,'FINAL5_INJECT','') if f5 else '') + \
47
- (getattr(f6,'FINAL6_INJECT','') or '') + \
48
- (getattr(f6,'FINAL6_FAST_HOME_INJECT','') or '') + \
49
- (getattr(f6,'FINAL6E_INJECT','') or '') + \
50
- PATCH_INJECT
51
- if '</body>' in html:
52
- html = html.replace('</body>', body + '\n</body>')
53
- else:
54
- html += body
55
- return HTMLResponse(html)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
rebuild3.md DELETED
@@ -1 +0,0 @@
1
- rebuild
 
 
rebuild_trigger.txt DELETED
@@ -1 +0,0 @@
1
- rebuild: Fri Aug 28 11:15:45 UTC 2026
 
 
requirements.txt CHANGED
@@ -11,6 +11,3 @@ pillow
11
  edge-tts
12
  python-dateutil
13
  httpx
14
- python-multipart
15
- pycryptodome
16
- # trigger rebuild 1784359130
 
11
  edge-tts
12
  python-dateutil
13
  httpx
 
 
 
restart.txt DELETED
@@ -1 +0,0 @@
1
- rebuild 1787553359
 
 
restart2.md DELETED
@@ -1 +0,0 @@
1
- restart with _run.py fix
 
 
restart_trigger.md DELETED
@@ -1,14 +0,0 @@
1
- # VNEWS Space Restart Trigger
2
-
3
- ## Version: v20260822d
4
-
5
- ### All fixes applied:
6
- 1. **Scrolling fix**: `-webkit-overflow-scrolling: touch` + `scroll-behavior: smooth` on `.tiktok-feed`
7
- 2. **Thumbnail fix**: `.yt-thumb-wrap` with background image for YouTube iframes, YouTube hqdefault fallback
8
- 3. **Lazy loading**: IntersectionObserver to unload slides far from viewport
9
- 4. **SHORT HOT video looping**: Video plays at full duration instead of being trimmed to narration length
10
- 5. **CSS consistency**: Same poster/thumbnail styling for all TikTok slides
11
- 6. **Homepage loading**: Retry logic for `scrape_vne`, bongdaplus.vn as primary source, faster xemlaibongda timeout
12
- 7. **YouTube SSL error**: Increased yt-dlp retries (5), socket_timeout 30s, YouTube embed fallback
13
-
14
- Last restart: 20260822d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
rewrite_fix_v2.js DELETED
@@ -1,2 +0,0 @@
1
- // No-op - all functionality built into app_v2.js
2
- (function(){})();
 
 
 
rewrite_slide.py CHANGED
@@ -84,36 +84,17 @@ def _scrape_article_full(url):
84
  return None
85
 
86
 
87
- def _ensure_complete_sentence(text):
88
- """Ensure text ends with complete sentence ending."""
89
- text = _clean(text)
90
- if not text:
91
- return text
92
- # Find last complete sentence ending
93
- for end_char in ['.', '!', '?']:
94
- last_pos = text.rfind(end_char)
95
- if last_pos > len(text) * 0.5: # Keep if ending is in latter half
96
- return text[:last_pos + 1].strip()
97
- return text
98
-
99
  def _extract_key_points(paragraphs, max_points=5):
100
- """Extract key points: take first COMPLETE sentence of each significant paragraph."""
101
  points = []
102
  for p in paragraphs:
103
  if len(points) >= max_points: break
104
- # Find ALL sentence endings and take the first complete sentence
105
- # that ends with . ! or ?
106
- sentences = re.split(r'(?<=[.!?])\s+', p)
107
- sentence = ""
108
- for s in sentences:
109
- s = _clean(s)
110
- if len(s) >= 30 and re.search(r'[.!?]$', s):
111
- sentence = s
112
- break
113
-
114
- # If no complete sentence found, take first sentence and ensure it ends
115
- if not sentence and sentences:
116
- sentence = _ensure_complete_sentence(sentences[0])
117
 
118
  # Skip if too short or duplicate
119
  if len(sentence) < 30: continue
 
84
  return None
85
 
86
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  def _extract_key_points(paragraphs, max_points=5):
88
+ """Extract key points: take first sentence of each significant paragraph."""
89
  points = []
90
  for p in paragraphs:
91
  if len(points) >= max_points: break
92
+ # Take first complete sentence (ends with . ! ?)
93
+ m = re.match(r'^(.+?[.!?])\s', p)
94
+ if m:
95
+ sentence = m.group(1)
96
+ else:
97
+ sentence = p[:150] + ('.' if not p.endswith('.') else '')
 
 
 
 
 
 
 
98
 
99
  # Skip if too short or duplicate
100
  if len(sentence) < 30: continue
runtime.txt CHANGED
@@ -0,0 +1 @@
 
 
1
+ python-3.12.x
shorts_cache.py DELETED
@@ -1,86 +0,0 @@
1
- """
2
- VNEWS Shorts Runtime Cache - External Updater Module
3
- GitHub Actions fetches YouTube shorts via yt-dlp -> POST to /api/shorts/update
4
- Space saves to RAM cache + persistent file if /data available
5
- """
6
- import os
7
- import json
8
- import time
9
- import threading
10
-
11
- # Runtime cache (RAM)
12
- _shorts_runtime_cache = None
13
- _shorts_cache_ts = 0
14
- _shorts_cache_lock = threading.Lock()
15
-
16
- # Secret for authenticating update requests
17
- SHORTS_UPDATE_SECRET = os.environ.get("SHORTS_UPDATE_SECRET", "vnews-shorts-2026")
18
-
19
- # Paths
20
- SHORTS_CACHE_FILE = "/data/shorts_runtime_cache.json" if os.path.isdir("/data") else "/app/shorts_runtime_cache.json"
21
-
22
-
23
- def get_runtime_cache():
24
- """Get cached shorts (from RAM or file fallback)"""
25
- global _shorts_runtime_cache, _shorts_cache_ts
26
- with _shorts_cache_lock:
27
- if _shorts_runtime_cache is not None:
28
- age = time.time() - _shorts_cache_ts
29
- if age < 7200: # 2h fresh
30
- return _shorts_runtime_cache
31
-
32
- # Try file fallback
33
- try:
34
- if os.path.exists(SHORTS_CACHE_FILE):
35
- with open(SHORTS_CACHE_FILE, "r", encoding="utf-8") as f:
36
- data = json.load(f)
37
- age = time.time() - data.get("ts", 0)
38
- if age < 86400: # 24h stale limit
39
- items = data.get("items", [])
40
- with _shorts_cache_lock:
41
- _shorts_runtime_cache = items
42
- _shorts_cache_ts = data.get("ts", time.time())
43
- return items
44
- except Exception as e:
45
- print(f"[cache] read error: {e}")
46
-
47
- return None
48
-
49
-
50
- def set_runtime_cache(items):
51
- """Update runtime cache from external data"""
52
- global _shorts_runtime_cache, _shorts_cache_ts
53
- ts = time.time()
54
- with _shorts_cache_lock:
55
- _shorts_runtime_cache = items
56
- _shorts_cache_ts = ts
57
-
58
- # Also write to file (persistent if /data mounted)
59
- try:
60
- os.makedirs(os.path.dirname(SHORTS_CACHE_FILE), exist_ok=True)
61
- payload = {"items": items, "ts": ts, "count": len(items)}
62
- with open(SHORTS_CACHE_FILE, "w", encoding="utf-8") as f:
63
- json.dump(payload, f, ensure_ascii=False, indent=2)
64
- print(f"[cache] saved {len(items)} shorts to {SHORTS_CACHE_FILE}")
65
- except Exception as e:
66
- print(f"[cache] write skipped: {e}")
67
-
68
- return len(items)
69
-
70
-
71
- def get_cache_status():
72
- """Return status dict for the cache"""
73
- cache = None
74
- with _shorts_cache_lock:
75
- if _shorts_runtime_cache is not None:
76
- cache = _shorts_runtime_cache
77
- age = int(time.time() - _shorts_cache_ts)
78
- else:
79
- age = -1
80
- return {
81
- "cached": cache is not None,
82
- "count": len(cache) if cache else 0,
83
- "age_seconds": age,
84
- "has_persistent": os.path.isdir("/data"),
85
- "cache_file_exists": os.path.exists(SHORTS_CACHE_FILE),
86
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shorts_rss_proxy.py DELETED
@@ -1,114 +0,0 @@
1
- """
2
- YouTube RSS Proxy - Fetches YouTube channel RSS feeds server-side
3
- Avoids CORS issues when client tries to fetch YouTube directly
4
- """
5
- import requests as req
6
- from fastapi import Query
7
- from fastapi.responses import Response
8
-
9
- HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
10
-
11
- YOUTUBE_CHANNELS = {
12
- "baodantri7941": "UC_x5TKhOgd6GhYvv5z4I3jg",
13
- "baosuckhoedoisongboyte": "UCBsY5fXTQLkF_JnH9kLkL4g",
14
- }
15
-
16
- def setup_rss_proxy(app):
17
- """Add RSS proxy endpoints to the FastAPI app"""
18
-
19
- @app.get("/api/proxy/rss")
20
- def proxy_rss(url: str = Query(...)):
21
- """Proxy YouTube RSS feed to avoid CORS"""
22
- try:
23
- r = req.get(url, headers=HEADERS, timeout=15)
24
- if r.status_code == 200:
25
- return Response(
26
- content=r.content,
27
- media_type="application/xml",
28
- headers={"Access-Control-Allow-Origin": "*"}
29
- )
30
- return Response(status_code=r.status_code)
31
- except Exception as e:
32
- return Response(status_code=502, content=str(e))
33
-
34
- @app.get("/api/shorts/rss")
35
- def shorts_via_rss():
36
- """Get shorts from YouTube RSS feeds server-side"""
37
- import xml.etree.ElementTree as ET
38
- import html as html_lib
39
- import re
40
-
41
- shorts = []
42
- seen = set()
43
-
44
- for handle, channel_id in YOUTUBE_CHANNELS.items():
45
- try:
46
- rss_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}"
47
- r = req.get(rss_url, headers=HEADERS, timeout=15)
48
- if r.status_code != 200:
49
- continue
50
-
51
- root = ET.fromstring(r.text)
52
- ns = {
53
- 'atom': 'http://www.w3.org/2005/Atom',
54
- 'yt': 'http://www.youtube.com/xml/schemas/2015',
55
- 'media': 'http://search.yahoo.com/mrss/'
56
- }
57
-
58
- for entry in root.findall('atom:entry', ns)[:30]:
59
- title_el = entry.find('atom:title', ns)
60
- title = html_lib.unescape(title_el.text) if title_el is not None and title_el.text else ''
61
-
62
- link_el = entry.find('atom:link', ns)
63
- link = link_el.get('href', '') if link_el is not None else ''
64
-
65
- vid_el = entry.find('yt:videoId', ns)
66
- vid = vid_el.text if vid_el is not None else ''
67
-
68
- if not vid:
69
- m = re.search(r'(?:v=|shorts/)([A-Za-z0-9_-]{11})', link)
70
- if m:
71
- vid = m.group(1)
72
-
73
- if not vid or vid in seen:
74
- continue
75
-
76
- # Check if it's a short
77
- is_short = '#shorts' in title.lower() or '#short' in title.lower() or '/shorts/' in link
78
-
79
- if not is_short:
80
- desc_el = entry.find('media:description', ns)
81
- if desc_el is not None and desc_el.text:
82
- if '#shorts' in desc_el.text.lower():
83
- is_short = True
84
-
85
- if not is_short:
86
- continue
87
-
88
- seen.add(vid)
89
-
90
- # Get thumbnail
91
- thumb = f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg"
92
- media_group = entry.find('media:group', ns)
93
- if media_group is not None:
94
- thumb_el = media_group.find('media:thumbnail', ns)
95
- if thumb_el is not None:
96
- thumb = thumb_el.get('url', thumb)
97
-
98
- shorts.append({
99
- 'id': vid,
100
- 'title': title.replace('#shorts', '').replace('#short', '').strip()[:120],
101
- 'img': thumb,
102
- 'link': f'https://www.youtube.com/shorts/{vid}',
103
- 'channel': handle,
104
- 'source': 'yt'
105
- })
106
-
107
- if len(shorts) >= 40:
108
- break
109
-
110
- except Exception as e:
111
- print(f"RSS error for {handle}: {e}")
112
- continue
113
-
114
- return {"shorts": shorts, "count": len(shorts)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/app_v2.js CHANGED
The diff for this file is too large to render. See raw diff
 
static/app_v2_shorts_fix.js DELETED
@@ -1,2 +0,0 @@
1
- // No-op - all functionality built into app_v2.js
2
- (function(){})();
 
 
 
static/designer_v2.js DELETED
@@ -1,903 +0,0 @@
1
- /* =========================================================================
2
- * designer_v2.js — Slide Designer nâng cấp cho VNEWS
3
- * - Nhiều hiệu ứng độc đáo (gradient, blur, neon, top-banner, lower-third,
4
- * card, corner-frame, stars, vignette, split, spotlight, diagonal, solid)
5
- * - Bộ lọc màu (grayscale, sepia, saturate, warm, cool, invert)
6
- * - Chữ phát sáng (neon/glow)
7
- * - Vị trí chữ (trên/giữa/dưới)
8
- * - Chọn 1 / nhiều / TẤT CẢ slide trong modal sửa ảnh
9
- * - Đăng lên Tường AI là bài dạng slide gồm CÁC SLIDE ĐÃ CHỌN
10
- *
11
- * 2026-08-12 FIX (2 lỗi báo cáo):
12
- * - Bug 1: upload ảnh preview + nút "Áp dụng ảnh". _dsHandleBgFile được gắn
13
- * trực tiếp làm listener 'change' nên nhận Event object, `input.files`
14
- * undefined -> upload im lặng không làm gì. Giờ đọc evt.target.files.
15
- * Nút "Áp dụng ảnh này cho TẤT CẢ slide đã chọn" luôn hiển thị.
16
- * - Bug 2: chọn 1 ảnh rewrite áp dụng cho nhiều slide. Danh sách ảnh dùng
17
- * data-index + delegated click (hết fragile inline onclick với URL thô).
18
- *
19
- * 2026-08-13 FIX (lỗi báo cáo tiếp):
20
- * - Bug 3: "dùng 1 ảnh cho nhiều slide" vẫn chỉ áp dụng cho slide đầu.
21
- * Giờ có _dsAppliedImg (ảnh đã áp dụng ở cấp thiết kế): khi chọn ảnh bất kỳ
22
- * (rewrite / upload / URL) sẽ áp dụng cho TẤT CẢ slide đã chọn NGAY LẬP TỨC;
23
- * khi đổi lựa chọn slide (chọn thêm / bỏ chọn / chọn tất cả) ảnh đó vẫn được
24
- * áp dụng tự động cho các slide mới được chọn; khi lưu, mọi slide được chọn
25
- * đều dùng ảnh đó.
26
- * - Bug 4: ảnh preview hiển thị đúng tỉ lệ nhưng sau khi tạo ảnh xong hiển thị
27
- * sai tỉ lệ + ảnh nền không định vị chính xác như preview. Preview và khi
28
- * lưu giờ render Ở CÙNG một hàm `_dsRenderSlide(canvas, opts, cb)` (cùng
29
- * resolution, cùng cover-fit, cùng filter, cùng text) nên file tạo ra khớp
30
- * TUYỆT ĐỐI với preview. Ảnh trên Tường/slide viewer giữ đúng tỉ lệ khung
31
- * (ko cắt xén bằng object-fit:cover nữa).
32
- * - Thêm MÀU NỀN + nhiều ẢNH NỀN MẪU khi chọn "Nền đều (phủ màu tối)" —
33
- * dải màu nền (solid color swatches) và bộ ảnh nền mẫu (gradient mờ) để
34
- * người dùng tạo ảnh nền trơn thay vì chỉ phủ màu tối.
35
- * ========================================================================= */
36
-
37
- /* ---------------- state ---------------- */
38
- let _dsState = {
39
- postIdx: -1, // index into _wallPosts
40
- selected: [], // array of selected slide indices (into p.slides)
41
- };
42
-
43
- /* per-slide image override map: {si: imageUrl} set by the rewrite image list */
44
- let _dsImgMap = {};
45
-
46
- /* srcs backing the rewrite image list (Bug 2 fix: index-based, no inline onclick) */
47
- let _dsRewriteImgSrcs = [];
48
-
49
- /* designer-level "applied image": the image the user picked (rewrite / upload /
50
- URL). Applied to ALL selected slides, including slides selected LATER.
51
- Bug 3 fix: keeps "1 ảnh cho nhiều slide" working when selection changes. */
52
- let _dsAppliedImg = '';
53
-
54
- /* solid-color background for the 'solid' layout (map because _dsOptions reads it) */
55
- let _dsBgColor = '';
56
- /* sample background image (proxied URL) for the 'solid' layout */
57
- let _dsBgSample = '';
58
-
59
- /* ---------------- ratio / layout helpers ---------------- */
60
- function designerGetRatioV2(){
61
- const v = document.getElementById('ds-ratio')?.value || '3:4';
62
- const m = v.split(':');
63
- return m.length === 2 ? {w: parseInt(m[0]), h: parseInt(m[1])} : {w:3,h:4};
64
- }
65
- function designerGetLayoutV2(){ return document.getElementById('ds-layout')?.value || 'solid'; }
66
- function designerGetFilterV2(){ return document.getElementById('ds-filter')?.value || 'none'; }
67
- function designerGetGlowV2(){ return document.getElementById('ds-glow')?.value || 'none'; }
68
- function designerGetPosV2(){ return document.getElementById('ds-pos')?.value || 'middle'; }
69
-
70
- /* ---------------- open modal (override) ---------------- */
71
- function openSlideDesigner(idx){
72
- const p = _wallPosts[idx]; if(!p || !p.slides || !p.slides.length) return;
73
- _dsState.postIdx = idx;
74
- // default: chỉ slide đầu tiên (slide 1 = ảnh đại diện bài đăng tường).
75
- // Người dùng có thể chọn thêm bằng checkbox hoặc "Chọn tất cả".
76
- _dsState.selected = p.slides.length ? [0] : [];
77
- _dsBgDataUrl = null; // reset uploaded bg between opens
78
- _dsTextColor = '#ffffff';
79
- _dsImgMode = 'rewrite'; // default: use rewrite image
80
- _dsImgMap = {}; // reset per-slide image overrides
81
- _dsRewriteImgSrcs = [];
82
- _dsAppliedImg = ''; // reset designer-level applied image
83
- _buildDesignerModal(p);
84
- }
85
-
86
- function _buildDesignerModal(p){
87
- const overlay = document.createElement('div');
88
- overlay.id = 'slide-designer-overlay';
89
- overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.94);z-index:99999;display:flex;align-items:center;justify-content:center;padding:12px;overflow-y:auto';
90
- let h='<div style="background:#16161a;border:2px solid #5cb87a;border-radius:16px;padding:18px;max-width:780px;width:100%;max-height:94vh;overflow-y:auto">';
91
- h+='<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px"><h3 style="color:#5cb87a;margin:0;font-size:16px">🎨 Thiết kế ảnh slide</h3><button onclick="document.getElementById(\'slide-designer-overlay\').remove()" style="background:none;border:0;color:#fff;font-size:24px;cursor:pointer">✕</button></div>';
92
-
93
- /* ---- 1. Chọn slide (1 / nhiều / tất cả) ---- */
94
- h+='<div style="margin-bottom:10px"><label style="color:#888;font-size:11px;display:block;margin-bottom:6px">📌 Chọn slide để chỉnh sửa & đăng lên Tường AI:</label>';
95
- h+='<div style="margin-bottom:8px;display:flex;gap:8px;flex-wrap:wrap">';
96
- h+='<button id="ds-sel-all" style="background:#2d8659;border:0;color:#fff;padding:6px 12px;border-radius:8px;font-size:11px;cursor:pointer">✅ Chọn tất cả</button>';
97
- h+='<button id="ds-sel-none" style="background:#333;border:0;color:#ddd;padding:6px 12px;border-radius:8px;font-size:11px;cursor:pointer">🚫 Bỏ chọn</button>';
98
- h+='</div><div id="ds-slide-list" style="display:flex;flex-wrap:wrap;gap:8px">';
99
- p.slides.forEach((s,i)=>{
100
- const preview = s.image ? `<img src="${_proxyImg(s.image)}" style="width:100%;height:54px;object-fit:cover;border-radius:6px;margin-bottom:4px" onerror="this.style.display='none'">` : `<div style="width:100%;height:54px;background:#222;border-radius:6px;margin-bottom:4px;display:flex;align-items:center;justify-content:center;color:#555;font-size:20px">🖼️</div>`;
101
- const isSel = _dsState.selected.includes(i);
102
- h+=`<label data-idx="${i}" class="ds-slide-chip" style="width:110px;border:2px solid #2d8659;background:#1e2621;border-radius:10px;padding:6px;cursor:pointer;text-align:center">
103
- <input type="checkbox" class="ds-slide-chk" data-idx="${i}"${isSel?' checked':''} style="accent-color:#5cb87a;width:14px;height:14px">
104
- ${preview}
105
- <div style="color:#eee;font-size:10px;line-height:1.3;height:32px;overflow:hidden">Slide ${s.index||i+1}: ${(s.text||'').slice(0,34)}</div>
106
- </label>`;
107
- });
108
- h+='</div></div>';
109
-
110
- /* ---- 2. Nội dung từng slide đã chọn ---- */
111
- h+='<div style="margin-bottom:10px"><label style="color:#888;font-size:11px;display:block;margin-bottom:4px">✏️ Nội dung từng slide:</label><div id="ds-texts"></div></div>';
112
-
113
- /* ---- 3. Cấu hình thiết kế ---- */
114
- h+='<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px">';
115
- h+='<div><label style="color:#888;font-size:11px;display:block;margin-bottom:4px">Tỉ lệ cắt ảnh:</label><select id="ds-ratio" style="width:100%;background:#222;border:1px solid #333;color:#eee;border-radius:8px;padding:8px;font-size:12px"><option value="3:4">📱 3:4 (dọc)</option><option value="1:1">📐 1:1 (vuông)</option><option value="4:3">🖥️ 4:3 (ngang)</option><option value="16:9">🎞️ 16:9 (rộng)</option></select></div>';
116
- h+='<div><label style="color:#888;font-size:11px;display:block;margin-bottom:4px">Vị trí chữ:</label><select id="ds-pos" style="width:100%;background:#222;border:1px solid #333;color:#eee;border-radius:8px;padding:8px;font-size:12px"><option value="middle">⬅️ Giữa</option><option value="top">⬆️ Trên</option><option value="bottom">⬇️ Dưới</option></select></div>';
117
- h+='<div style="grid-column:1/3"><label style="color:#888;font-size:11px;display:block;margin-bottom:4px">✨ Hiệu ứng nền:</label><select id="ds-layout" style="width:100%;background:#222;border:1px solid #333;color:#eee;border-radius:8px;padding:8px;font-size:12px">';
118
- h+='<option value="solid">🎨 Nền đều (phủ màu tối)</option>';
119
- h+='<option value="gradient">🌈 Gradient (đổ màu)</option>';
120
- h+='<option value="vignette">🌙 Vignette (viền tối dần)</option>';
121
- h+='<option value="blur">🌀 Làm mờ hậu cảnh</option>';
122
- h+='<option value="split">✂️ Chia đôi (trên mờ, dưới rõ)</option>';
123
- h+='<option value="spotlight">🎯 Spotlight (ánh sáng giữa)</option>';
124
- h+='<option value="diagonal">↘️ Đường chéo</option>';
125
- h+='<option value="neon">💡 Neon (nền tối + chữ phát sáng)</option>';
126
- h+='<option value="top-banner">🏷️ Banner trên cùng</option>';
127
- h+='<option value="lower-third">📺 Lower-third (chữ dưới)</option>';
128
- h+='<option value="card">🃏 Card bo góc</option>';
129
- h+='<option value="corner">🖼️ Khung viền góc</option>';
130
- h+='<option value="stars">🌠 Nền sao lấp lánh</option>';
131
- h+='</select></div>';
132
- h+='<div><label style="color:#888;font-size:11px;display:block;margin-bottom:4px">🎚️ Bộ lọc màu:</label><select id="ds-filter" style="width:100%;background:#222;border:1px solid #333;color:#eee;border-radius:8px;padding:8px;font-size:12px"><option value="none">Nguyên bản</option><option value="grayscale">⚪ Đen trắng</option><option value="sepia">🟤 Sepia</option><option value="saturate">🎨 Bão hòa mạnh</option><option value="warm">🔥 Ấm áp</option><option value="cool">❄️ Mát lạnh</option><option value="invert">🔁 Đảo màu</option><option value="noir">🖤 Noir tương phản</option></select></div>';
133
- h+='<div><label style="color:#888;font-size:11px;display:block;margin-bottom:4px">💡 Phát sáng chữ:</label><select id="ds-glow" style="width:100%;background:#222;border:1px solid #333;color:#eee;border-radius:8px;padding:8px;font-size:12px"><option value="none">Tắt</option><option value="white">✨ Tỏa trắng</option><option value="color">🌈 Tỏa màu chữ</option><option value="neon">💡 Neon mạnh</option></select></div>';
134
- h+='</div>';
135
-
136
- /* ---- 3b. Màu nền + ảnh nền mẫu (chỉ hiển thị khi chọn "Nền đều/solid") ---- */
137
- h+='<div id="ds-bg-solid-wrap" style="display:none;margin-bottom:10px;padding:10px;background:#1e2621;border:1px solid #2d8659;border-radius:10px">';
138
- h+='<div style="color:#888;font-size:11px;display:block;margin-bottom:6px">🎨 Màu nền (nền trơn):</div><div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px" id="ds-bg-colors">';
139
- ['#0f172a','#1e293b','#334155','#1a1a2e','#16213e','#0f3460','#202040','#2d3436','#2c2c54','#3d1e1e','#4a1e3d','#1e3d2f','#3a2e1e','#111827','#0b0b1a','#233329'].forEach(c=>{h+=`<button class="ds-bgcolor-btn" data-color="${c}" style="width:30px;height:30px;border-radius:8px;border:2px solid #333;background:${c};cursor:pointer;padding:0" title="${c}"></button>`;});
140
- h+='</div>';
141
- h+='<div style="color:#888;font-size:11px;display:block;margin-bottom:6px">🖼️ Hoặc chọn ẢNH NỀN MẪU:</div><div style="display:flex;flex-wrap:wrap;gap:6px" id="ds-bg-samples">';
142
- _DS_BG_SAMPLES.forEach((b,bi)=>{h+=`<button type="button" class="ds-bgsample-btn" data-bi="${bi}" style="width:52px;height:68px;border-radius:8px;border:2px solid #333;background:#222;background-image:url('${_dsImageSrc(b)}');background-size:cover;background-position:center;cursor:pointer;padding:0;position:relative"><span style="position:absolute;right:3px;top:3px;font-size:9px;line-height:1;color:#fff;text-shadow:0 0 3px #000">🖼️</span></button>`;});
143
- h+='</div>';
144
- h+='<div style="color:#666;font-size:9px;margin-top:6px">Chọn màu nền hoặc ảnh nền mẫu — ảnh nền mẫu sẽ được phủ mờ để chữ dễ đọc. Nếu không chọn, dùng màu tối mặc định.</div>';
145
- h+='</div>';
146
-
147
- /* ---- 4. Màu chữ + nền ---- */
148
- h+='<div style="margin-bottom:10px"><label style="color:#888;font-size:11px;display:block;margin-bottom:4px">🎨 Màu chữ:</label><div style="display:flex;gap:6px;flex-wrap:wrap" id="ds-colors">';
149
- ['#ffffff','#000000','#ff4444','#44ff44','#4444ff','#ffff00','#ff00ff','#00ffff','#ff8800','#88ff00','#ffd700','#ff69b4'].forEach(c=>{h+=`<button class="ds-color-btn" data-color="${c}" style="width:26px;height:26px;border-radius:50%;border:2px solid ${c==='#ffffff'?'#888':'#333'};background:${c};cursor:pointer;padding:0"></button>`;});
150
- h+='</div></div>';
151
-
152
- /* ---- 5. Ảnh nền (source buttons + URL/upload) ---- */
153
- h+='<div style="margin-bottom:6px"><label style="color:#888;font-size:11px;display:block;margin-bottom:4px">🖼️ Ảnh nền:</label>';
154
- h+='<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:6px">';
155
- h+='<button id="ds-img-src-rewrite" class="ds-img-src-btn" style="background:#2d8659;border:0;color:#fff;padding:6px 10px;border-radius:8px;font-size:10px;cursor:pointer">📰 Ảnh từ bài rewrite</button>';
156
- h+='<button id="ds-img-src-custom" class="ds-img-src-btn" style="background:#333;border:0;color:#ccc;padding:6px 10px;border-radius:8px;font-size:10px;cursor:pointer">🖼️ Ảnh riêng (URL/upload)</button>';
157
- h+='<button id="ds-img-src-none" class="ds-img-src-btn" style="background:#333;border:0;color:#ccc;padding:6px 10px;border-radius:8px;font-size:10px;cursor:pointer">🚫 Không ảnh (nền trơn)</button>';
158
- h+='</div>';
159
- /* URL + upload panel (only the URL/upload inputs collapse; apply button stays visible) */
160
- h+='<div id="ds-custom-img-url-wrap" style="display:none">';
161
- h+='<input id="ds-bg-url" type="text" placeholder="https://... (URL ảnh)" style="width:100%;background:#222;border:1px solid #333;color:#eee;border-radius:8px;padding:8px;font-size:12px;margin-bottom:6px">';
162
- h+='<input type="file" id="ds-bg-file" accept="image/*" style="font-size:11px;color:#888">';
163
- h+='</div>';
164
- /* "Áp dụng ảnh này cho TẤT CẢ slide đã chọn" — ALWAYS visible (Bug 1 fix) */
165
- h+='<div style="display:flex;gap:6px;margin-top:6px;flex-wrap:wrap;align-items:center"><button id="ds-apply-img-btn" style="background:#2d8659;border:0;color:#fff;padding:6px 12px;border-radius:8px;font-size:10px;cursor:pointer">📌 Áp dụng ảnh này cho TẤT CẢ slide đã chọn</button><span id="ds-apply-img-hint" style="color:#5cb87a;font-size:9px;line-height:1.6">✓ Áp dụng để dùng 1 ảnh cho nhiều slide</span></div>';
166
- h+='<div style="color:#888;font-size:10px">Ảnh tải lên/URL nhập từ ngoài (hoặc chọn từ danh sách dưới) sẽ thay thế ảnh bài rewrite và áp dụng cho TẤT CẢ slide đã chọn.</div>';
167
- h+='<div id="ds-rewrite-imgs" style="margin-top:8px;display:none"><label style="color:#888;font-size:10px;display:block;margin-bottom:4px">📋 Danh sách ảnh từ bài rewrite (bấm để chọn ảnh):</label><div id="ds-rewrite-list" style="display:flex;flex-wrap:wrap;gap:6px"></div></div>';
168
- h+='</div>';
169
-
170
- h+='<div style="margin-top:14px;display:flex;gap:8px;justify-content:center;flex-wrap:wrap"><button id="ds-preview-btn" style="background:#2d8659;border:0;color:#fff;padding:10px 18px;border-radius:10px;font-size:12px;font-weight:700;cursor:pointer">👁 Xem trước</button><button id="ds-save-btn" style="background:#1a3a5a;border:1px solid #3a5a7b;color:#fff;padding:10px 18px;border-radius:10px;font-size:12px;font-weight:700;cursor:pointer">📤 Lưu & Đăng lên Tường AI ('+p.slides.length+' slide)</button></div>';
171
- h+='<div id="ds-preview-area" style="margin-top:12px;text-align:center;display:none"></div>';
172
- h+='<div id="ds-status" style="color:#888;font-size:11px;margin-top:8px;text-align:center"></div>';
173
- overlay.innerHTML=h; document.body.appendChild(overlay);
174
-
175
- /* button label update fn */
176
- window._dsUpdateSaveLabel = function(){
177
- const n = _dsState.selected.length;
178
- const b = document.getElementById('ds-save-btn');
179
- if(b) b.textContent = '📤 Lưu & Đăng lên Tường AI ('+n+' slide)';
180
- };
181
-
182
- /* ---- slide selection wiring ---- */
183
- overlay.querySelectorAll('.ds-slide-chk').forEach(chk=>{
184
- chk.addEventListener('change', _dsSyncSelection);
185
- });
186
- document.getElementById('ds-sel-all').addEventListener('click', ()=>{ _setAllSelected(true); });
187
- document.getElementById('ds-sel-none').addEventListener('click', ()=>{ _setAllSelected(false); });
188
- document.getElementById('ds-slide-list').addEventListener('click', e=>{
189
- const lbl = e.target.closest('.ds-slide-chip');
190
- if(!lbl) return;
191
- const chk = lbl.querySelector('.ds-slide-chk');
192
- if(e.target === chk) return;
193
- chk.checked = !chk.checked; _dsSyncSelection();
194
- });
195
-
196
- /* ---- inputs wiring ---- */
197
- document.getElementById('ds-preview-btn').addEventListener('click', _dsPreview);
198
- document.getElementById('ds-save-btn').addEventListener('click', ()=>_dsSave(p));
199
- ['ds-texts','ds-ratio','ds-layout','ds-filter','ds-glow','ds-pos'].forEach(id=>{
200
- ['change','input'].forEach(evt=>{
201
- const el=document.getElementById(id); if(el) el.addEventListener(evt, ()=>_dsDebounce(_dsPreview, 150));
202
- });
203
- });
204
- // URL input: as user types a custom image URL, live-preview + apply to selected
205
- const bgUrlInput=document.getElementById('ds-bg-url');
206
- if(bgUrlInput){
207
- bgUrlInput.addEventListener('input', ()=>{
208
- const v=bgUrlInput.value.trim();
209
- if(v && v.length>8){
210
- _dsSetImgMode('custom');
211
- const proxied=_dsImageSrc(v);
212
- _dsAppliedImg = proxied; // Bug 3: applies to current + future selections
213
- const sel=_dsState.selected;
214
- if(sel.length){ sel.forEach(si=>{ _dsImgMap[si]=proxied; }); }
215
- else { _dsImgMap[0]=proxied; }
216
- }
217
- _dsDebounce(_dsPreview,150);
218
- });
219
- }
220
- // Bug 1 fix: pass through the event; _dsHandleBgFile reads evt.target.files
221
- document.getElementById('ds-bg-file').addEventListener('change', _dsHandleBgFile);
222
- ['ds-img-src-rewrite','ds-img-src-custom','ds-img-src-none'].forEach(id=>{
223
- const b=document.getElementById(id);
224
- if(b) b.addEventListener('click', ()=>{
225
- _dsSetImgMode(id==='ds-img-src-rewrite'?'rewrite':id==='ds-img-src-custom'?'custom':'none');
226
- });
227
- });
228
- /* "Áp dụng ảnh này cho TẤT CẢ slide đã chọn" — always-visible apply button */
229
- const applyBtn=document.getElementById('ds-apply-img-btn');
230
- if(applyBtn){
231
- applyBtn.addEventListener('click', function(){
232
- let chosen = _dsBgDataUrl || (document.getElementById('ds-bg-url')?.value||'');
233
- if(!chosen){ toast('⚠️ Chọn ảnh (tải lên hoặc nhập URL) trước khi áp dụng'); return; }
234
- _dsSetImgMode('custom');
235
- let proxied = _dsImageSrc(chosen);
236
- _dsAppliedImg = proxied; // Bug 3 fix
237
- dsApplyImgToSelected(proxied);
238
- });
239
- }
240
- // Toggle the "nền trơn" (solid) color + sample-image panel when layout changes
241
- const layoutSel=document.getElementById('ds-layout');
242
- if(layoutSel){
243
- const toggleSolidPanel=()=>{
244
- const wrap=document.getElementById('ds-bg-solid-wrap');
245
- if(wrap) wrap.style.display = layoutSel.value==='solid' ? 'block' : 'none';
246
- };
247
- layoutSel.addEventListener('change', toggleSolidPanel);
248
- layoutSel.addEventListener('input', toggleSolidPanel);
249
- toggleSolidPanel();
250
- }
251
- // Solid background color swatches
252
- const bgColorBox=document.getElementById('ds-bg-colors');
253
- if(bgColorBox){
254
- bgColorBox.addEventListener('click', e=>{
255
- const b=e.target.closest('.ds-bgcolor-btn'); if(!b) return;
256
- document.querySelectorAll('#ds-bg-colors .ds-bgcolor-btn').forEach(x=>x.style.borderColor='#333');
257
- b.style.borderColor='#fff';
258
- _dsBgColor = b.dataset.color;
259
- _dsBgSample = ''; // color takes precedence over sample image
260
- document.querySelectorAll('#ds-bg-samples .ds-bgsample-btn').forEach(x=>x.style.borderColor='#333');
261
- _dsStatus('🎨 Đã chọn màu nền: '+_dsBgColor);
262
- _dsDebounce(_dsPreview, 150);
263
- });
264
- }
265
- // Sample background images (only for solid layout)
266
- const bgSampleBox=document.getElementById('ds-bg-samples');
267
- if(bgSampleBox){
268
- bgSampleBox.addEventListener('click', e=>{
269
- const b=e.target.closest('.ds-bgsample-btn'); if(!b) return;
270
- const bi=parseInt(b.dataset.bi,10);
271
- const src=_DS_BG_SAMPLES[bi];
272
- if(!src) return;
273
- document.querySelectorAll('#ds-bg-samples .ds-bgsample-btn').forEach(x=>x.style.borderColor='#333');
274
- b.style.borderColor='#ffd700';
275
- _dsBgSample = _dsImageSrc(src);
276
- _dsBgColor = ''; // sample image takes precedence over color
277
- document.querySelectorAll('#ds-bg-colors .ds-bgcolor-btn').forEach(x=>x.style.borderColor='#333');
278
- _dsStatus('🖼️ Đã chọn ảnh nền mẫu');
279
- _dsDebounce(_dsPreview, 150);
280
- });
281
- }
282
- _syncImgModeBtns();
283
- _dsRefreshRewriteImgs(p);
284
- document.getElementById('ds-colors').addEventListener('click', e=>{
285
- const b = e.target.closest('.ds-color-btn'); if(!b) return;
286
- overlay.querySelectorAll('.ds-color-btn').forEach(x=>x.style.borderColor='#333');
287
- b.style.borderColor='#fff';
288
- _dsTextColor = b.dataset.color;
289
- _dsDebounce(_dsPreview, 150);
290
- });
291
-
292
- _dsRefreshTexts(p);
293
- _dsUpdateSaveLabel();
294
- _dsPreview();
295
- }
296
-
297
- /* ---------------- selection sync ---------------- */
298
- function _setAllSelected(on){
299
- _dsState.selected = [];
300
- document.querySelectorAll('#ds-slide-list .ds-slide-chk').forEach(chk=>{ chk.checked = on; if(on) _dsState.selected.push(parseInt(chk.dataset.idx)); });
301
- // Bug 3 fix: if an image was already applied at designer level, push it to
302
- // every slide that is (now) selected so "1 ảnh cho nhiều slide" also covers
303
- // slides selected AFTER the image was picked.
304
- if(on && _dsAppliedImg){
305
- _dsState.selected.forEach(si=>{ _dsImgMap[si] = _dsAppliedImg; });
306
- }
307
- const p = _wallPosts[_dsState.postIdx];
308
- if(p) _dsRefreshTexts(p);
309
- _dsUpdateSaveLabel();
310
- _dsDebounce(_dsPreview, 150);
311
- }
312
- function _dsSyncSelection(){
313
- _dsState.selected = [];
314
- document.querySelectorAll('#ds-slide-list .ds-slide-chk:checked').forEach(chk=>{ _dsState.selected.push(parseInt(chk.dataset.idx)); });
315
- // Bug 3 fix: same propagation for checkbox changes.
316
- if(_dsAppliedImg){
317
- _dsState.selected.forEach(si=>{ if(!_dsImgMap[si]) _dsImgMap[si] = _dsAppliedImg; });
318
- }
319
- const p = _wallPosts[_dsState.postIdx];
320
- if(p) _dsRefreshTexts(p);
321
- _dsUpdateSaveLabel();
322
- _dsDebounce(_dsPreview, 150);
323
- }
324
-
325
- /* ---------------- per-slide text areas ---------------- */
326
- function _dsRefreshTexts(p){
327
- const box = document.getElementById('ds-texts'); if(!box) return;
328
- if(!_dsState.selected.length){ box.innerHTML='<div style="color:#888;font-size:11px;padding:6px">Chưa chọn slide nào.</div>'; return; }
329
- let h='<div style="display:flex;flex-direction:column;gap:6px">';
330
- _dsState.selected.forEach((si, k)=>{
331
- const s = p.slides[si];
332
- h+=`<textarea data-sivec="${k}" data-sidx="${si}" style="width:100%;min-height:44px;background:#222;border:1px solid #333;color:#eee;border-radius:8px;padding:8px;font-size:13px;resize:vertical">${esc(s.text||'')}</textarea>`;
333
- });
334
- h+='</div>';
335
- box.innerHTML=h;
336
- box.querySelectorAll('textarea').forEach(ta=>{
337
- ta.addEventListener('input', ()=>{ _dsDebounce(_dsPreview, 200); });
338
- });
339
- }
340
-
341
- /* ---------------- bg file ---------------- */
342
- let _dsBgDataUrl = null;
343
- let _dsTextColor = '#ffffff';
344
- let _dsImgMode = 'rewrite'; // 'rewrite' | 'custom' | 'none'
345
- /* Bug 1 fix: this is bound as a 'change' listener, so the first arg is the
346
- Event. Read the <input> from evt.target.files (previously input.files was
347
- undefined, so the upload silently did nothing and the preview/apply button
348
- never saw the image). */
349
- function _dsHandleBgFile(evt){
350
- const input = evt && evt.target ? evt.target : evt;
351
- const file = (input && input.files && input.files[0]) ? input.files[0] : null;
352
- if(!file) return;
353
- _dsSetImgMode('custom'); // show the custom-img URL/upload panel
354
- const reader=new FileReader();
355
- reader.onload=function(e){
356
- _dsBgDataUrl=e.target.result;
357
- _dsImgMode='custom';
358
- _syncImgModeBtns();
359
- _dsStatus('✅ Đã chọn ảnh: '+(file.name||'').slice(0,30) + (file.size? ' ('+Math.round(file.size/1024)+'KB)':''));
360
- // Auto-apply uploaded image to ALL currently selected slides so the upload
361
- // has an immediate, visible effect (preview + save will use it for every slide).
362
- _dsAppliedImg = _dsBgDataUrl; // Bug 3 fix: applies to future selections too
363
- const sel=_dsState.selected;
364
- if(sel.length){ sel.forEach(si=>{ _dsImgMap[si]=_dsBgDataUrl; }); }
365
- else { _dsImgMap[0]=_dsBgDataUrl; }
366
- _dsDebounce(_dsPreview,150);
367
- };
368
- reader.readAsDataURL(file);
369
- }
370
- /* Show a transient status line in the designer footer. */
371
- function _dsStatus(msg){
372
- const s=document.getElementById('ds-status'); if(s) s.textContent=msg;
373
- }
374
- function _syncImgModeBtns(){
375
- ['ds-img-src-rewrite','ds-img-src-custom','ds-img-src-none'].forEach(id=>{
376
- const b=document.getElementById(id);
377
- if(!b) return;
378
- const on = (id==='ds-img-src-rewrite' && _dsImgMode==='rewrite') ||
379
- (id==='ds-img-src-custom' && _dsImgMode==='custom') ||
380
- (id==='ds-img-src-none' && _dsImgMode==='none');
381
- b.style.background = on ? '#2d8659' : '#333';
382
- b.style.color = on ? '#fff' : '#ccc';
383
- });
384
- const wrap=document.getElementById('ds-custom-img-url-wrap');
385
- if(wrap) wrap.style.display = _dsImgMode==='custom' ? 'block' : 'none';
386
- }
387
- function _dsSetImgMode(m){
388
- _dsImgMode = m;
389
- _syncImgModeBtns();
390
- _dsDebounce(_dsPreview, 150);
391
- }
392
-
393
- /* Build a list of available rewrite images (post.img + each slide.image)
394
- and render them so the user can pick 1 image to apply to the selected slides.
395
- Bug 2 fix: uses data-index + a delegated click handler (no fragile inline
396
- onclick embedding the raw URL, which broke on URLs containing quotes). */
397
- function _dsRefreshRewriteImgs(p){
398
- const box = document.getElementById('ds-rewrite-list');
399
- if(!box) return;
400
- const imgs = [];
401
- const seen = new Set();
402
- // post-level image first
403
- if(p.img && typeof p.img === 'string' && p.img.length){
404
- const key = p.img.startsWith('/api/') ? p.img : _dsImageSrc(p.img);
405
- if(!seen.has(key)){ seen.add(key); imgs.push({src: key, label: 'Ảnh bài (đại diện)'}); }
406
- }
407
- // then per-slide images
408
- if(Array.isArray(p.slides)){
409
- p.slides.forEach((s, i)=>{
410
- const raw = s.image || s.img || '';
411
- if(raw && typeof raw === 'string' && raw.length){
412
- const key = raw.startsWith('/api/') ? raw : _dsImageSrc(raw);
413
- if(!seen.has(key)){ seen.add(key); imgs.push({src: key, label: `Slide ${s.index||i+1}`}); }
414
- }
415
- });
416
- }
417
- if(!imgs.length){
418
- box.innerHTML = '<div style="color:#666;font-size:10px">Không có ảnh rewrite nào.</div>';
419
- const wrap = document.getElementById('ds-rewrite-imgs');
420
- if(wrap) wrap.style.display = 'none';
421
- return;
422
- }
423
- const wrap = document.getElementById('ds-rewrite-imgs');
424
- if(wrap) wrap.style.display = 'block';
425
- _dsRewriteImgSrcs = imgs.map(x=>x.src); // index -> src
426
- let h='';
427
- imgs.forEach((img, idx)=>{
428
- h += '<div style="display:flex;flex-direction:column;align-items:center;gap:2px">'
429
- + '<img src="'+esc(img.src)+'" data-ds-rw="'+idx+'" style="width:48px;height:48px;object-fit:cover;border-radius:6px;border:2px solid #2d8659;cursor:pointer" '
430
- + 'onerror="this.style.display=\'none\'">'
431
- + '<div style="color:#aaa;font-size:8px;text-align:center">'+img.label+'</div>'
432
- + '</div>';
433
- });
434
- box.innerHTML = h;
435
- // Bug 2 fix: delegated click handler (event delegation, URL-safe)
436
- box.onclick = function(e){
437
- const im = e.target.closest('img[data-ds-rw]');
438
- if(!im) return;
439
- const idx = parseInt(im.getAttribute('data-ds-rw'), 10);
440
- const src = _dsRewriteImgSrcs[idx];
441
- if(src) dsApplyImgToSelected(src);
442
- };
443
- }
444
-
445
- /* Apply a chosen image src to ALL selected slides (or the current preview slide). */
446
- function dsApplyImgToSelected(imgSrc){
447
- _dsAppliedImg = imgSrc; // Bug 3 fix: remember at designer level (future selections too)
448
- const sel = _dsState.selected;
449
- if(sel.length){
450
- sel.forEach(si=>{ _dsImgMap[si] = imgSrc; });
451
- }else{
452
- _dsImgMap[0] = imgSrc;
453
- }
454
- _dsImgMode = 'custom'; // visually marks we are using a chosen image
455
- _syncImgModeBtns();
456
- _dsStatus('✅ Đã áp dụng ảnh cho '+(sel.length? sel.length+' slide đã chọn':'slide hiện tại'));
457
- // refresh preview immediately (selected slide 0 is what we preview)
458
- const p=_wallPosts[_dsState.postIdx];
459
- if(p && sel.length){ _dsOptions(p, sel[0]); }
460
- _dsPreview();
461
- }
462
-
463
- function _dsDebounce(fn,d){ clearTimeout(fn._t); fn._t=setTimeout(fn,d); }
464
-
465
- /* ---------------- get design options ---------------- */
466
- function _dsOptions(p, si){
467
- const s = p.slides[si];
468
- const ta = document.querySelector(`#ds-texts textarea[data-sidx="${si}"]`);
469
- const text = ta ? ta.value : (s.text||'');
470
- const bgInput = document.getElementById('ds-bg-url')?.value||'';
471
- // Per-slide image override: when user picks an image from the rewrite list,
472
- // it is stored in _dsImgMap[si] and applied to that specific slide.
473
- let bgUrl = '';
474
- // Solid layout + user picked a SAMPLE background image -> use it as the
475
- // background photo (dark overlay for readability) instead of a flat color.
476
- const isSolid = designerGetLayoutV2()==='solid';
477
- const useSample = isSolid && _dsBgSample && !_dsAppliedImg;
478
- if(useSample) bgUrl = _dsBgSample;
479
- // Bug 3 fix: designer-level applied image wins for every selected slide.
480
- // Applied when the user picked an image (rewrite picker / upload / URL /
481
- // "Áp dụng" button) — even for slides selected AFTER the image was picked.
482
- if(!bgUrl && _dsAppliedImg) bgUrl = _dsAppliedImg;
483
- if(!bgUrl && _dsImgMap[si]) bgUrl = _dsImgMap[si];
484
- if(!bgUrl){
485
- if(_dsImgMode === 'custom'){
486
- bgUrl = _dsBgDataUrl || bgInput || '';
487
- } else if(_dsImgMode === 'rewrite'){
488
- bgUrl = s.image || p.img || '';
489
- } // none -> ''
490
- }
491
- return {
492
- si, s, text, bgUrl,
493
- ratio: designerGetRatioV2(),
494
- layout: isSolid ? 'solid' : designerGetLayoutV2(),
495
- filter: designerGetFilterV2(),
496
- glow: designerGetGlowV2(),
497
- pos: designerGetPosV2(),
498
- color: _dsTextColor,
499
- bgColor: _dsBgColor, // solid-layout background color ('' = default dark)
500
- bgSample: useSample ? _dsBgSample : '', // 'sample' mode: img passed to draw
501
- };
502
- }
503
-
504
- /* ---------------- drawing core ---------------- */
505
- function _dsImageSrc(url){
506
- if(!url) return '';
507
- if(url.startsWith('/api/') || url.startsWith('data:')) return url;
508
- return '/api/proxy/img?url='+encodeURIComponent(url);
509
- }
510
- /* Only tag crossOrigin=anonymous for proxied EXTERNAL images.
511
- Setting it on data: URLs or local /api/ paths can cause silent onload
512
- failures (black preview) in some browser/CORS configurations. */
513
- function _dsMakeImg(url){
514
- const img=new Image();
515
- if(url && !url.startsWith('data:') && !url.startsWith('/api/')) img.crossOrigin='anonymous';
516
- return img;
517
- }
518
-
519
- /* Sample background images for the "Nền đều (solid)" layout — abstract
520
- gradients that look good with white text. Served through the /api/proxy/img
521
- endpoint (same-origin, no crossOrigin needed — _dsMakeImg handles that).
522
- Keyed for the modal background swatches and for _dsDrawLayout. */
523
- const _DS_BG_SAMPLES = [
524
- 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=900&q=60', // sơn hùng vĩ (núi)
525
- 'https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=900&q=60', // sương mù rừng
526
- 'https://images.unsplash.com/photo-1462331940025-496dfbfc7564?w=900&q=60', // vũ trụ
527
- 'https://images.unsplash.com/photo-1469474968028-56623f02e42e?w=900&q=60', // núi rừng
528
- 'https://images.unsplash.com/photo-1499002238440-d264edd596ec?w=900&q=60', // hoàng hôn
529
- 'https://images.unsplash.com/photo-1448375240586-882707db888b?w=900&q=60', // rừng tối
530
- 'https://images.unsplash.com/photo-1519681393784-d120267933ba?w=900&q=60', // trời sao
531
- 'https://images.unsplash.com/photo-1518173946687-a4c8892bbd9f?w=900&q=60', // biển đêm
532
- 'https://images.unsplash.com/photo-1497436072909-60f360e1d4b1?w=900&q=60', // đồng cỏ
533
- ];
534
-
535
- /* draw bg image with cover-fit + color filter */
536
- function _dsDrawBg(ctx, W, H, bgUrl, filter, blur){
537
- ctx.save();
538
- ctx.fillStyle='#111'; ctx.fillRect(0,0,W,H);
539
- // filter string
540
- let f='';
541
- if(filter==='grayscale') f='grayscale(1)';
542
- else if(filter==='sepia') f='sepia(0.85)';
543
- else if(filter==='saturate') f='saturate(2.4)';
544
- else if(filter==='warm') f='sepia(0.45) saturate(1.5) hue-rotate(-15deg)';
545
- else if(filter==='cool') f='saturate(1.2) hue-rotate(15deg) brightness(1.05)';
546
- else if(filter==='invert') f='invert(1)';
547
- else if(filter==='noir') f='grayscale(1) contrast(1.6) brightness(0.9)';
548
- if(blur) f=(f?f+' ':'')+'blur('+blur+'px)';
549
- ctx.filter = f;
550
- if(bgUrl){
551
- const img = new Image(); img.crossOrigin='anonymous';
552
- // Note: async path handled by caller via onload; this fn is synchronous draw of already-loaded img
553
- }
554
- ctx.restore();
555
- }
556
-
557
- /* ---------------- layout effects (with loaded bg image) ---------------- */
558
- function _dsDrawLayout(ctx, W, H, opts, img){
559
- const { layout, filter, bgUrl, bgColor } = opts;
560
- // base: solid layout can use the chosen background color (no image needed)
561
- let baseColor = '#141414';
562
- if(layout==='solid' && !img && bgColor) baseColor = bgColor;
563
- ctx.fillStyle = baseColor; ctx.fillRect(0,0,W,H);
564
- // draw bg image cover-fit if present & loaded
565
- if(img){
566
- const blur = layout==='blur' ? Math.max(6, Math.round(W/90)) : 0;
567
- ctx.save();
568
- let f='';
569
- if(filter==='grayscale') f='grayscale(1)';
570
- else if(filter==='sepia') f='sepia(0.85)';
571
- else if(filter==='saturate') f='saturate(2.4)';
572
- else if(filter==='warm') f='sepia(0.45) saturate(1.5) hue-rotate(-15deg)';
573
- else if(filter==='cool') f='saturate(1.2) hue-rotate(15deg) brightness(1.05)';
574
- else if(filter==='invert') f='invert(1)';
575
- else if(filter==='noir') f='grayscale(1) contrast(1.6) brightness(0.9)';
576
- if(blur) f=(f?f+' ':'')+'blur('+blur+'px)';
577
- ctx.filter = f;
578
- const iw=img.naturalWidth||1, ih=img.naturalHeight||1;
579
- const scale=Math.max(W/iw, H/ih);
580
- const dw=iw*scale, dh=ih*scale;
581
- const dx=(W-dw)/2, dy=(H-dh)/2;
582
- ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh);
583
- ctx.filter='none';
584
- ctx.restore();
585
- }
586
- // overlay per layout
587
- if(layout==='gradient'){
588
- const g=ctx.createLinearGradient(0,0,W,H);
589
- g.addColorStop(0,'rgba(50,20,90,0.75)'); g.addColorStop(0.5,'rgba(20,60,120,0.6)'); g.addColorStop(1,'rgba(120,30,60,0.75)');
590
- ctx.fillStyle=g; ctx.fillRect(0,0,W,H);
591
- }
592
- else if(layout==='vignette'){
593
- const g=ctx.createRadialGradient(W/2,H/2,0,W/2,H/2,Math.max(W,H)*0.62);
594
- g.addColorStop(0,'rgba(0,0,0,0)'); g.addColorStop(1,'rgba(0,0,0,0.78)');
595
- ctx.fillStyle=g; ctx.fillRect(0,0,W,H);
596
- }
597
- else if(layout==='split'){
598
- const g=ctx.createLinearGradient(0,0,0,H);
599
- g.addColorStop(0,'rgba(0,0,0,0.85)'); g.addColorStop(0.5,'rgba(0,0,0,0.15)'); g.addColorStop(1,'rgba(0,0,0,0.85)');
600
- ctx.fillStyle=g; ctx.fillRect(0,0,W,H);
601
- }
602
- else if(layout==='spotlight'){
603
- ctx.fillStyle='rgba(0,0,0,0.72)'; ctx.fillRect(0,0,W,H);
604
- const cx=W/2, cy=H*0.45, r=Math.max(W,H)*0.4;
605
- const g=ctx.createRadialGradient(cx,cy,0,cx,cy,r);
606
- g.addColorStop(0,'rgba(255,255,255,0.45)'); g.addColorStop(0.6,'rgba(255,255,255,0.12)'); g.addColorStop(1,'rgba(0,0,0,0.9)');
607
- ctx.fillStyle=g; ctx.fillRect(0,0,W,H);
608
- }
609
- else if(layout==='diagonal'){
610
- ctx.fillStyle='rgba(0,0,0,0.55)'; ctx.fillRect(0,0,W,H);
611
- ctx.fillStyle='rgba(0,0,0,0.8)';
612
- ctx.beginPath(); ctx.moveTo(0,0); ctx.lineTo(W*0.9,0); ctx.lineTo(0,H*0.9); ctx.closePath(); ctx.fill();
613
- }
614
- else if(layout==='neon'){
615
- ctx.fillStyle='rgba(10,10,30,0.85)'; ctx.fillRect(0,0,W,H);
616
- ctx.strokeStyle='rgba(80,220,255,0.5)'; ctx.lineWidth=Math.max(2,W/300);
617
- ctx.strokeRect(W*0.03,H*0.03,W*0.94,H*0.94);
618
- }
619
- else if(layout==='top-banner'){
620
- ctx.fillStyle='rgba(0,0,0,0)';
621
- const g=ctx.createLinearGradient(0,0,0,H*0.5);
622
- g.addColorStop(0,'rgba(0,0,0,0.8)'); g.addColorStop(1,'rgba(0,0,0,0)');
623
- ctx.fillStyle=g; ctx.fillRect(0,0,W,H*0.5);
624
- }
625
- else if(layout==='lower-third'){
626
- const g=ctx.createLinearGradient(0,H*0.55,0,H);
627
- g.addColorStop(0,'rgba(0,0,0,0)'); g.addColorStop(1,'rgba(0,0,0,0.82)');
628
- ctx.fillStyle=g; ctx.fillRect(0,H*0.55,W,H*0.45);
629
- }
630
- else if(layout==='card'){
631
- ctx.fillStyle='rgba(0,0,0,0.35)'; ctx.fillRect(0,0,W,H);
632
- // rounded card
633
- const pad=Math.round(W*0.04);
634
- ctx.fillStyle='rgba(0,0,0,0.65)';
635
- _dsRoundRect(ctx, pad, H*0.16, W-2*pad, H*0.68, Math.round(W*0.05));
636
- ctx.fill();
637
- ctx.strokeStyle='rgba(255,255,255,0.25)'; ctx.lineWidth=Math.max(2,W/400); _dsRoundRect(ctx,pad,H*0.16,W-2*pad,H*0.68,Math.round(W*0.05)); ctx.stroke();
638
- }
639
- else if(layout==='corner'){
640
- ctx.fillStyle='rgba(0,0,0,0.3)'; ctx.fillRect(0,0,W,H);
641
- ctx.strokeStyle='rgba(255,215,0,0.9)'; ctx.lineWidth=Math.max(4,W/160);
642
- const L=Math.round(W*0.18), c=Math.round(W*0.04);
643
- [[0,c],[c,0],[W,c],[W-c,0],[0,H-c],[c,H],[W,H-c],[W-c,H]].forEach(([x,y],i)=>{
644
- const top = y===0 || y===c; const left = x===0 || x===c;
645
- ctx.beginPath();
646
- if(i<4){ // top corners
647
- if(top && left){ ctx.moveTo(x,y+L); ctx.lineTo(x,y); ctx.lineTo(x+L,y); }
648
- else if(top){ ctx.moveTo(x,y+L); ctx.lineTo(x,y); ctx.lineTo(x-L,y); }
649
- else { ctx.moveTo(x-L,y); ctx.lineTo(x,y); ctx.lineTo(x,y+L); }
650
- } else { // bottom corners
651
- if(left){ ctx.moveTo(x,y-L); ctx.lineTo(x,y); ctx.lineTo(x+L,y); }
652
- else { ctx.moveTo(x-L,y); ctx.lineTo(x,y); ctx.lineTo(x,y-L); }
653
- }
654
- ctx.stroke();
655
- });
656
- }
657
- else if(layout==='stars'){
658
- ctx.fillStyle='rgba(8,8,30,0.82)'; ctx.fillRect(0,0,W,H);
659
- const n=Math.round(W*H/18000);
660
- for(let i=0;i<n;i++){
661
- const x=Math.random()*W, y=Math.random()*H, r=Math.random()*Math.max(1,W/300)+0.5;
662
- ctx.fillStyle=`rgba(255,255,255,${0.4+Math.random()*0.6})`;
663
- ctx.beginPath(); ctx.arc(x,y,r,0,Math.PI*2); ctx.fill();
664
- }
665
- }
666
- else { // solid
667
- if(img && bgUrl){
668
- // sample background photo (or user image) -> dark overlay so text is readable
669
- ctx.fillStyle='rgba(0,0,0,0.45)'; ctx.fillRect(0,0,W,H);
670
- } else if(bgColor){
671
- // chosen solid color with a subtle gradient + soft vignette for depth
672
- const g=ctx.createLinearGradient(0,0,W,H);
673
- g.addColorStop(0, bgColor);
674
- g.addColorStop(1, _dsShadeColor(bgColor, -0.25));
675
- ctx.fillStyle=g; ctx.fillRect(0,0,W,H);
676
- const vg=ctx.createRadialGradient(W/2,H/2,0,W/2,H/2,Math.max(W,H)*0.66);
677
- vg.addColorStop(0,'rgba(0,0,0,0)'); vg.addColorStop(1,'rgba(0,0,0,0.42)');
678
- ctx.fillStyle=vg; ctx.fillRect(0,0,W,H);
679
- } else {
680
- ctx.fillStyle='rgba(0,0,0,0.6)'; ctx.fillRect(0,0,W,H);
681
- }
682
- }
683
- }
684
-
685
- /* Darken (n<0) or lighten (n>0) a hex color by n*100% (for solid bg gradient). */
686
- function _dsShadeColor(hex, n){
687
- try{
688
- hex=String(hex||'').replace('#','');
689
- if(hex.length===3) hex=hex.split('').map(c=>c+c).join('');
690
- if(hex.length!==6) return hex;
691
- const num=parseInt(hex,16);
692
- let r=(num>>16)&255, g=(num>>8)&255, b=num&255;
693
- const t = n<0 ? 0 : 255;
694
- const p = Math.abs(n);
695
- r=Math.round((t-r)*p)+r; g=Math.round((t-g)*p)+g; b=Math.round((t-b)*p)+b;
696
- return '#'+((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);
697
- }catch(e){ return hex; }
698
- }
699
-
700
- function _dsRoundRect(ctx,x,y,w,h,r){
701
- ctx.beginPath();
702
- ctx.moveTo(x+r,y);
703
- ctx.arcTo(x+w,y,x+w,y+h,r);
704
- ctx.arcTo(x+w,y+h,x,y+h,r);
705
- ctx.arcTo(x,y+h,x,y,r);
706
- ctx.arcTo(x,y,x+w,y,r);
707
- ctx.closePath();
708
- }
709
-
710
- /* ---------------- text drawing ---------------- */
711
- function _dsDrawText(ctx, W, H, opts, baseFontScale){
712
- const { text, pos, glow, color } = opts;
713
- if(!text || !text.trim()) return;
714
- const base = Math.max(28, Math.round(W*baseFontScale));
715
- const fs = Math.min(base, Math.round(W*0.09));
716
- ctx.font = 'bold '+fs+'px "Segoe UI","Arial","Noto Sans",sans-serif';
717
- ctx.textAlign='center';
718
- // split lines
719
- const lines=[]; let line='';
720
- const maxW=Math.round(W*0.82);
721
- text.split(' ').forEach(w=>{
722
- const test = line? line+' '+w : w;
723
- if(ctx.measureText(test).width>maxW && line){ lines.push(line.trim()); line=w; } else { line=test; }
724
- });
725
- if(line) lines.push(line.trim());
726
- const lh=Math.round(fs*1.25);
727
- const blockH=lines.length*lh;
728
- let y;
729
- if(pos==='top') y=Math.round(H*0.14)+lh/2;
730
- else if(pos==='bottom') y=Math.round(H*0.88)-blockH+lh/2;
731
- else y=Math.round(H/2)-blockH/2+lh/2;
732
- // glow
733
- if(glow==='white'){ ctx.shadowColor='rgba(255,255,255,0.95)'; ctx.shadowBlur=Math.max(8,fs*0.5); }
734
- else if(glow==='color'){ ctx.shadowColor=color; ctx.shadowBlur=Math.max(10,fs*0.6); }
735
- else if(glow==='neon'){ ctx.shadowColor='#00ffff'; ctx.shadowBlur=Math.max(16,fs*0.9); }
736
- ctx.fillStyle=color;
737
- // subtle stroke for legibility at top/bottom
738
- if(pos==='top'||pos==='bottom'){ ctx.strokeStyle='rgba(0,0,0,0.6)'; ctx.lineWidth=Math.max(2,fs*0.12); ctx.strokeText(textLine(text),W/2,y); }
739
- lines.forEach((l,li)=>{ ctx.fillText(l, W/2, y+li*lh); });
740
- ctx.shadowBlur=0;
741
- }
742
- function textLine(t){ return t; }
743
-
744
- /* ---------------- compute final canvas size for a design ---------------- */
745
- function _dsFinalSize(opts){
746
- const r=opts.ratio;
747
- const w = (r.w>=r.h) ? 1800 : 1350;
748
- const h = Math.round(w*r.h/r.w);
749
- return { w, h };
750
- }
751
-
752
- /* Shared renderer (Bug 4 fix): renders a slide onto `canvas` using the SAME
753
- code path and SAME resolution for BOTH preview and final save, so the
754
- published image is pixel-identical to what the user saw in the preview —
755
- same cover-fit, same filter, same text placement, same background. */
756
- function _dsRenderSlide(canvas, opts, done){
757
- const ctx = canvas.getContext('2d');
758
- const bgUrl = _dsImageSrc(opts.bgUrl);
759
- function draw(img){
760
- _dsDrawLayout(ctx, canvas.width, canvas.height, opts, img||null);
761
- _dsDrawText(ctx, canvas.width, canvas.height, opts, 0.052);
762
- if(done) done(img||null);
763
- }
764
- if(bgUrl){
765
- const img=_dsMakeImg(bgUrl);
766
- img.onload=function(){ draw(img); };
767
- img.onerror=function(){ console.warn('[designer] bg image failed to load:', bgUrl); draw(null); };
768
- img.src=bgUrl;
769
- } else {
770
- draw(null);
771
- }
772
- }
773
-
774
- /* ---------------- preview ---------------- */
775
- function _dsPreview(){
776
- const p=_wallPosts[_dsState.postIdx]; if(!p) return;
777
- const area=document.getElementById('ds-preview-area'); if(!area) return;
778
- const sel=_dsState.selected;
779
- if(!sel.length){ area.style.display='block'; area.innerHTML='<div style="color:#888;font-size:12px">Chưa chọn slide nào để xem trước.</div>'; return; }
780
- area.style.display='block';
781
- area.innerHTML='<div style="color:#888;font-size:12px">⏳ Đang tạo xem trước...</div>';
782
- // display-scale: cap visible width at 300px, keep aspect ratio per slide
783
- const dispW=Math.min(300, Math.floor((Math.max(document.documentElement.clientWidth||540, document.body.clientWidth||540))*0.5));
784
- const cans=[];
785
- sel.forEach((si, k)=>{
786
- const opts=_dsOptions(p, si);
787
- const { w, h }=_dsFinalSize(opts);
788
- const canvas=document.createElement('canvas');
789
- canvas.width=w; canvas.height=h;
790
- canvas.style.width=dispW+'px'; canvas.style.height='auto';
791
- canvas.style.borderRadius='12px'; canvas.style.boxShadow='0 8px 24px rgba(0,0,0,.5)'; canvas.style.display='block'; canvas.style.margin='0 auto 14px auto';
792
- cans.push({opts, canvas});
793
- });
794
- let remaining=cans.length;
795
- function allDone(){
796
- if(--remaining>0) return;
797
- let out='';
798
- if(cans.length>1) out+='<div style="color:#888;font-size:10px;margin-bottom:8px">Xem trước '+(cans.length)+' slide đã chọn (cuộn xuống để xem hết):</div>';
799
- area.innerHTML=out;
800
- cans.forEach((c,k)=>{
801
- if(k>0) area.appendChild(document.createElement('br'));
802
- area.appendChild(c.canvas);
803
- });
804
- }
805
- cans.forEach(c=>{ _dsRenderSlide(c.canvas, c.opts, allDone); });
806
- }
807
-
808
- /* ---------------- save: render + upload each selected slide, then post ---------------- */
809
- async function _dsSave(p){
810
- const statusEl=document.getElementById('ds-status'); if(statusEl) statusEl.textContent='⏳ Đang tạo ảnh các slide...';
811
- const sel=_dsState.selected;
812
- if(!sel.length){ if(statusEl) statusEl.textContent='⚠️ Chưa chọn slide nào để đăng.'; return; }
813
- const saveBtn=document.getElementById('ds-save-btn'); if(saveBtn){ saveBtn.disabled=true; saveBtn.textContent='⏳ Đang xử lý...'; }
814
-
815
- const uploaded = []; // {si, url}
816
- try{
817
- // render each selected slide at final resolution
818
- for(let k=0;k<sel.length;k++){
819
- const si=sel[k];
820
- if(statusEl) statusEl.textContent=`⏳ Đang tạo ảnh slide ${k+1}/${sel.length}... (${p.slides.length} slide trong bài)`;
821
- const opts=_dsOptions(p, si);
822
- const { w: FINAL_W, h: FINAL_H }=_dsFinalSize(opts);
823
- const canvas=document.createElement('canvas'); canvas.width=FINAL_W; canvas.height=FINAL_H;
824
- // Shared render path (Bug 4 fix) — identical to preview.
825
- const url = await new Promise((resolve)=>{
826
- _dsRenderSlide(canvas, opts, function(){
827
- // Nén JPEG thay PNG: dung lượng rất nhỏ (thường 5-10x nhỏ hơn),
828
- // ảnh tải nhanh hơn nhiều trên Tường AI. Chất lượng 0.82 giữ chữ sắc nét.
829
- canvas.toBlob(async function(blob){
830
- const fd=new FormData();
831
- fd.append('file', blob, 'slide_'+(si+1)+'.jpg');
832
- fd.append('post_id', p.id||'');
833
- try{
834
- const r=await fetch('/api/wall/img',{method:'POST',body:fd});
835
- const j=await r.json();
836
- if(!r.ok || j.error) throw new Error(j.error||'Lỗi upload');
837
- resolve(j.url);
838
- }catch(e){ resolve({error:e.message}); }
839
- },'image/jpeg', 0.82);
840
- });
841
- });
842
- if(url && url.error) throw new Error(url.error);
843
- uploaded.push({si, url});
844
- // update slide image live
845
- if(p.slides[si]) p.slides[si].image = url;
846
- }
847
-
848
- if(statusEl) statusEl.textContent='⏳ Đang đăng lên Tường AI...';
849
-
850
- // build updated slides array (keep unselected unchanged)
851
- const newSlides = p.slides.map((s,i)=>{
852
- const up = uploaded.find(u=>u.si===i);
853
- // ensure text edits are applied too
854
- const ta = document.querySelector(`#ds-texts textarea[data-sidx="${i}"]`);
855
- return {
856
- text: ta ? ta.value : (s.text||''),
857
- image: up ? up.url : (s.image||''),
858
- index: s.index || (i+1),
859
- };
860
- });
861
-
862
- // pick selected slides only -> the wall post is a SLIDE-IMAGE post of selected slides
863
- const selSlides = newSlides.filter((_,i)=> sel.includes(i));
864
-
865
- const post = {
866
- id: p.id,
867
- title: p.title||'',
868
- text: selSlides.map(s=>'• '+s.text).join('\n\n'),
869
- img: selSlides[0] ? selSlides[0].image : p.img||'',
870
- url: p.url||'',
871
- slides: selSlides, // <-- bài đăng bao gồm chỉ các slide đã chọn
872
- images: selSlides.map(s=>s.image),
873
- kind: p.kind||'slide_summary',
874
- video: p.video||'',
875
- voice: p.voice||'',
876
- emotion: p.emotion||'',
877
- language: p.language||'',
878
- ts: p.ts||Math.floor(Date.now()/1000),
879
- };
880
-
881
- const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)});
882
- const wj=await wr.json();
883
- if(wr.ok && wj.post){
884
- prependWallPost(wj.post);
885
- toast('✅ Đã đăng bài slide lên Tường AI ('+selSlides.length+' slide)!');
886
- } else {
887
- toast('✅ Đã lưu ảnh slide!');
888
- }
889
- document.getElementById('slide-designer-overlay').remove();
890
- }catch(e){
891
- if(statusEl) statusEl.textContent='❌ '+e.message;
892
- toast('❌ '+e.message);
893
- if(saveBtn){ saveBtn.disabled=false; saveBtn.textContent='📤 Lưu & Đăng lên Tường AI ('+sel.length+' slide)'; }
894
- }
895
- }
896
-
897
- /* keep old helper names harmless for any other caller */
898
- function updateDesignerText(){}
899
- function designerGetRatio(){ return designerGetRatioV2(); }
900
- function designerGetLayout(){ return designerGetLayoutV2(); }
901
- function designerDebounce(fn,d){ _dsDebounce(fn,d); }
902
- function handleDesignerBgFile(){}
903
- function previewDesignerSlide(){ _dsPreview(); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/fm_fix.css CHANGED
@@ -168,250 +168,3 @@
168
  min-width:100%!important;max-width:none!important;max-height:none!important;
169
  object-fit:cover!important;
170
  }
171
-
172
- /* ============================================================
173
- BXH / BÅNG XẼP HẠNG (standing league table) FIX
174
- Bongda returns div-based Tailwind rows (.ranking-table .leaderboard
175
- .leaderboard-item / .head / .team / .copy). The old CSS only styled
176
- <table> so the standings rendered broken. Style the divs directly.
177
- ============================================================ */
178
- #ls-content .ranking-table,
179
- #ls-content .leaderboard{display:block!important;width:100%!important}
180
- #ls-content .ranking-table .head,
181
- #ls-content .leaderboard .head{display:flex!important;width:100%!important;background:#222!important;border-bottom:1px solid #333!important;padding:5px 0!important;font-size:10px!important;color:#999!important}
182
- #ls-content .ranking-table .head .team,
183
- #ls-content .leaderboard .head .team{flex:1 1 auto!important;min-width:0!important}
184
- #ls-content .ranking-table .head .team span,
185
- #ls-content .leaderboard .head .team span{display:inline-block!important;width:18px!important;text-align:center!important;color:#888!important}
186
- #ls-content .ranking-table .head .team .link,
187
- #ls-content .leaderboard .head .team .link{font-size:10px!important;color:#999!important;font-weight:700!important}
188
- #ls-content .ranking-table .head .copy,
189
- #ls-content .leaderboard .head .copy{display:flex!important;gap:2px!important;align-items:center!important;justify-content:flex-end!important;min-width:0!important}
190
- #ls-content .ranking-table .head .copy p,
191
- #ls-content .leaderboard .head .copy p{font-size:9px!important;color:#888!important;min-width:16px!important;text-align:center!important;margin:0!important}
192
- #ls-content .ranking-table .head .copy p.form,
193
- #ls-content .leaderboard .head .copy p.form{display:none!important}
194
- #ls-content .ranking-table .leaderboard-item,
195
- #ls-content .ranking-table #team_,
196
- #ls-content .leaderboard .leaderboard-item{
197
- display:table!important;width:100%!important;table-layout:fixed!important;
198
- border-collapse:collapse!important;border-bottom:1px solid #1a1a1a!important;
199
- font-size:11px!important;color:#ccc!important;background:transparent!important
200
- }
201
- #ls-content .ranking-table .leaderboard-item>div.team,
202
- #ls-content .ranking-table .leaderboard-item>.team,
203
- #ls-content .leaderboard .leaderboard-item .team{
204
- display:table-cell!important;vertical-align:middle!important;
205
- padding:5px 4px!important;text-align:left!important;min-width:0!important
206
- }
207
- #ls-content .ranking-table .leaderboard-item>div.team span,
208
- #ls-content .ranking-table .leaderboard-item>.team span{
209
- display:inline-block!important;width:18px!important;min-width:18px!important;
210
- text-align:center!important;font-size:10px!important;color:#888!important;font-weight:600!important
211
- }
212
- #ls-content .ranking-table .leaderboard-item>div.team a.link,
213
- #ls-content .ranking-table .leaderboard-item>.team a.link{
214
- display:inline-flex!important;align-items:center!important;gap:4px!important;
215
- min-width:0!important;font-size:11px!important;color:#ccc!important;text-decoration:none!important
216
- }
217
- #ls-content .ranking-table .leaderboard-item>div.team a.link img,
218
- #ls-content .ranking-table .leaderboard-item>.team a.link img{width:16px!important;height:16px!important;object-fit:contain!important;flex:0 0 auto!important}
219
- #ls-content .ranking-table .leaderboard-item>div.team a.link p,
220
- #ls-content .ranking-table .leaderboard-item>.team a.link p{
221
- font-size:11px!important;color:#ccc!important;margin:0!important;
222
- white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important
223
- }
224
- #ls-content .ranking-table .leaderboard-item>div.copy,
225
- #ls-content .ranking-table .leaderboard-item>.copy,
226
- #ls-content .leaderboard .leaderboard-item .copy{
227
- display:table-cell!important;vertical-align:middle!important;
228
- padding:5px 2px!important;text-align:center!important;white-space:nowrap!important
229
- }
230
- #ls-content .ranking-table .leaderboard-item>div.copy p,
231
- #ls-content .ranking-table .leaderboard-item>.copy p{
232
- display:inline-block!important;min-width:22px!important;text-align:center!important;
233
- font-size:11px!important;color:#ccc!important;margin:0 1px!important
234
- }
235
- #ls-content .ranking-table .leaderboard-item>div.copy p strong,
236
- #ls-content .ranking-table .leaderboard-item>.copy p strong{
237
- display:inline-block!important;min-width:22px!important;text-align:center!important;
238
- font-weight:800!important;color:#f0c040!important;font-size:12px!important
239
- }
240
- #ls-content .ranking-table .leaderboard-item>div.copy p.form,
241
- #ls-content .ranking-table .leaderboard-item>.copy p.form{display:inline-flex!important;flex-wrap:nowrap!important}
242
- #ls-content .ranking-table .leaderboard-item>div.copy p.form span,
243
- #ls-content .ranking-table .leaderboard-item>.copy p.form span{
244
- display:inline-block!important;min-width:14px!important;height:14px!important;
245
- line-height:14px!important;text-align:center!important;font-size:9px!important;
246
- border-radius:2px!important;margin:0 1px!important;color:#fff!important
247
- }
248
- #ls-content .ranking-table .leaderboard-item>div.copy p.form span.bg-green,
249
- #ls-content .ranking-table .leaderboard-item>.copy p.form span.bg-green{background:#2d8659!important}
250
- #ls-content .ranking-table .leaderboard-item>div.copy p.form span.bg-gray-5,
251
- #ls-content .ranking-table .leaderboard-item>.copy p.form span.bg-gray-5,
252
- #ls-content .leaderboard .leaderboard-item .copy p.form span.bg-gray-5,
253
- #ls-content .ranking-table .leaderboard-item .copy p.form span.bg-gray-5{background:#555!important;color:#ccc!important}
254
- #ls-content .ranking-table .leaderboard-item>div.copy p.form span.bg-red,
255
- #ls-content .ranking-table .leaderboard-item>.copy p.form span.bg-red{background:#c0392b!important}
256
- /* hide the bongda left accent bar that floats absolutely */
257
- #ls-content .ranking-table .leaderboard-item>div[class*="w-["],
258
- #ls-content .ranking-table .leaderboard-item div.relative{display:none!important}
259
- /* top row = champion accent can stay, but clean layout */
260
- #ls-content .leaderboard-item{margin:0!important}
261
- #ls-content .rank-table{width:100%!important;overflow-x:auto!important}
262
- /* fallback generic so ANY div-based standings table gets readable */
263
- #ls-content .team .name,#ls-content .team .logo{font-size:11px!important;color:#ccc!important}
264
- #ls-content .copy p{font-size:11px!important;color:#ccc!important}
265
- /* injected BXH header + row layout (see _decorateStandings in app_v2.js) */
266
- #ls-content .ls-bxh-head{
267
- display:flex!important;width:100%!important;align-items:center!important;gap:4px!important;
268
- background:#222!important;border-bottom:1px solid #333!important;
269
- padding:5px 2px!important;position:sticky!important;top:0!important;z-index:2!important
270
- }
271
- #ls-content .ls-bxh-head .team{flex:1!important;min-width:0!important;display:flex!important;align-items:center!important;gap:4px!important}
272
- #ls-content .ls-bxh-head .team span{display:inline-block!important;width:18px!important;min-width:18px!important;text-align:center!important;color:#888!important;font-size:10px!important;font-weight:700!important}
273
- #ls-content .ls-bxh-head .team p{font-size:10px!important;color:#999!important;font-weight:700!important;margin:0!important;text-transform:uppercase!important}
274
- #ls-content .ls-bxh-head .copy{display:flex!important;align-items:center!important;gap:2px!important;white-space:nowrap!important}
275
- #ls-content .ls-bxh-head .copy p{display:inline-block!important;min-width:20px!important;text-align:center!important;font-size:9px!important;color:#888!important;font-weight:700!important;margin:0!important}
276
- #ls-content .leaderboard-item{display:flex!important;width:100%!important;align-items:center!important;gap:4px!important;border-bottom:1px solid #1a1a1a!important;padding:4px 2px!important;background:transparent!important}
277
- #ls-content .leaderboard-item .team{flex:1!important;min-width:0!important;display:flex!important;align-items:center!important;gap:4px!important}
278
- #ls-content .leaderboard-item .team span{display:inline-block!important;width:18px!important;min-width:18px!important;text-align:center!important;color:#888!important;font-size:10px!important;font-weight:600!important}
279
- #ls-content .leaderboard-item .team a{display:inline-flex!important;align-items:center!important;gap:4px!important;font-size:11px!important;color:#ccc!important;text-decoration:none!important;overflow:hidden!important;min-width:0!important}
280
- #ls-content .leaderboard-item .team a img{width:16px!important;height:16px!important;object-fit:contain!important;flex:0 0 auto!important}
281
- #ls-content .leaderboard-item .team a p{font-size:11px!important;color:#ccc!important;margin:0!important;white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important}
282
- #ls-content .leaderboard-item .copy{display:flex!important;align-items:center!important;gap:2px!important;white-space:nowrap!important}
283
- #ls-content .leaderboard-item .copy p{display:inline-block!important;min-width:20px!important;text-align:center!important;font-size:11px!important;color:#ccc!important;margin:0!important}
284
- #ls-content .leaderboard-item .copy p strong{font-weight:800!important;color:#f0c040!important;min-width:20px!important;text-align:center!important}
285
- #ls-content .leaderboard-item .copy p.form{display:inline-flex!important;flex-wrap:nowrap!important}
286
- #ls-content .leaderboard-item .copy p.form span{width:14px!important;height:14px!important;line-height:14px!important;font-size:9px!important;border-radius:2px!important;color:#fff!important;margin:0 1px!important;text-align:center!important}
287
- #ls-content .leaderboard-item .copy p.form span.bg-green{background:#2d8659!important;display:inline-block!important}
288
- #ls-content .leaderboard-item .copy p.form span.bg-gray-5{background:#555!important;color:#ccc!important;display:inline-block!important}
289
- #ls-content .leaderboard-item .copy p.form span.bg-red{background:#c0392b!important;display:inline-block!important}
290
- #ls-content .leaderboard-item>div[class*="w-["]{display:none!important}#ls-content .leaderboard-item>div[class*="w-["]{display:none!important}
291
-
292
- /* ============================================================
293
- FPT PLAY / HIGHLIGHT VIDEO OVERFLOW FIX v2
294
- fptplay videos open in the TikTok-style feed inside .yt-thumb-wrap >
295
- iframe (YouTube) or <video>. <iframe> ignores object-fit, so a 9:16
296
- Shorts (or any non-16:9) source stretched the slide and overflowed
297
- width/height — the iframe's intrinsic aspect ratio pushed it beyond the
298
- slide bounds.
299
-
300
- BUG FIX v2 (two issues):
301
- 1) "FPT Play videos displayed differently from Short AI videos — too tall
302
- and wide": The old rule sized iframes to 177.78vh (16:9 of viewport
303
- height, ~1.78x screen wide). Short AI <video> tags used width:100%;
304
- height:100%; object-fit:contain. The iframe was much wider/taller than
305
- the video. Fix: make iframe use width:100%; height:100% — identical to
306
- <video> — centered and clipped by the slide's overflow:hidden.
307
-
308
- 2) "9:16 ↔ 16:9 ratio toggle button (🖥️/📺) doesn't work on football
309
- player slides and wall videos": The inline CSS .ratio-wide rule
310
- (specificity 0,3,1) was overridden by fm_fix.css selectors using the
311
- #tiktok-feed ID (specificity 1,3,1). The .ratio-wide rules never applied
312
- to iframes inside #tiktok-feed. Fix: add .ratio-wide override rules
313
- with #tiktok-feed ID prefix (matching or higher specificity) AFTER the
314
- default iframe rules, so the !important cascade honors the toggle.
315
-
316
- Sizing model: iframes don't support object-fit, so we use
317
- position:absolute + transform centering inside .yt-thumb-wrap (which is
318
- position:relative, width:100%, height:100%). The slide's
319
- overflow:hidden clips any letterbox/pillarbox bars — same visual result
320
- as object-fit:contain on <video>.
321
- ============================================================ */
322
- .tiktok-slide{overflow:hidden!important;position:relative!important}
323
- .tiktok-slide video{max-width:100%!important;max-height:100%!important;object-fit:contain!important;width:100%!important;height:100%!important;border:none!important}
324
- /* FPT play / YouTube iframe in the TikTok viewer: SAME sizing as <video>.
325
- Width and height 100% of .yt-thumb-wrap (which fills .tiktok-slide),
326
- centered via transform, clipped by overflow:hidden on the slide.
327
- This makes iframes appear IDENTICAL to Short AI <video> tags. */
328
- #tiktok-feed .tiktok-slide .yt-thumb-wrap iframe,
329
- #wc-shorts-feed .tiktok-slide .yt-thumb-wrap iframe,
330
- #tt-feed .tiktok-slide .yt-thumb-wrap iframe,
331
- .tiktok-slide .yt-thumb-wrap iframe{
332
- position:absolute!important;
333
- top:50%!important;
334
- left:50%!important;
335
- transform:translate(-50%,-50%)!important;
336
- width:100%!important; /* match <video> — 100% of slide */
337
- height:100%!important; /* match <video> — 100% of slide */
338
- min-width:100%!important;
339
- min-height:100%!important;
340
- max-height:100%!important;
341
- max-width:100vw!important; /* never overflow screen width */
342
- border:none!important;
343
- }
344
- /* WC Shorts path: iframe is a DIRECT child of .tiktok-slide (no .yt-thumb-wrap) */
345
- #tiktok-feed .tiktok-slide > iframe,
346
- #wc-shorts-feed .tiktok-slide > iframe,
347
- .tiktok-slide > iframe{
348
- position:absolute!important;
349
- top:50%!important;
350
- left:50%!important;
351
- transform:translate(-50%,-50%)!important;
352
- width:100%!important; /* match <video> — 100% of slide */
353
- height:100%!important; /* match <video> — 100% of slide */
354
- min-width:100%!important;
355
- min-height:100%!important;
356
- max-height:100%!important;
357
- max-width:100vw!important; /* never overflow screen width */
358
- border:none!important;
359
- }
360
- /* RATIO TOGGLE FIX: when .ratio-wide is on a .tiktok-slide inside
361
- #tiktok-feed, switch from 9:16 portrait to 16:9 landscape.
362
- These rules use #tiktok-feed ID prefix (same specificity as the default
363
- iframe rules above) AND .ratio-wide class, so they win the CSS cascade
364
- only when the toggle button is active. The default 9:16 sizing (width:100%,
365
- height:100%) is overridden to 16:9 landscape (width:100vw, height:56.25vw). */
366
- #tiktok-feed .tiktok-slide.ratio-wide .yt-thumb-wrap iframe,
367
- #wc-shorts-feed .tiktok-slide.ratio-wide .yt-thumb-wrap iframe,
368
- #tt-feed .tiktok-slide.ratio-wide .yt-thumb-wrap iframe,
369
- .tiktok-slide.ratio-wide .yt-thumb-wrap iframe{
370
- position:absolute!important;
371
- top:50%!important;
372
- left:50%!important;
373
- transform:translate(-50%,-50%)!important;
374
- width:calc(100vw - 1px)!important;
375
- height:56.25vw!important;
376
- max-width:100vw!important;
377
- max-height:100dvh!important;
378
- min-width:100%!important;
379
- min-height:100%!important;
380
- border:none!important;
381
- pointer-events:auto!important;
382
- }
383
- #tiktok-feed .tiktok-slide.ratio-wide > iframe,
384
- #wc-shorts-feed .tiktok-slide.ratio-wide > iframe,
385
- .tiktok-slide.ratio-wide > iframe{
386
- position:absolute!important;
387
- top:50%!important;
388
- left:50%!important;
389
- transform:translate(-50%,-50%)!important;
390
- width:calc(100vw - 1px)!important;
391
- height:56.25vw!important;
392
- max-width:100vw!important;
393
- max-height:100dvh!important;
394
- min-width:100%!important;
395
- min-height:100%!important;
396
- border:none!important;
397
- pointer-events:auto!important;
398
- }
399
- /* Toggle back to 9:16 (default) — reset to 100% sizing */
400
- #tt-feed .tiktok-slide:not(.ratio-wide) .yt-thumb-wrap iframe,
401
- #tt-feed .tiktok-slide:not(.ratio-wide) > iframe{
402
- width:100%!important;
403
- height:100%!important;
404
- max-width:100vw!important;
405
- min-width:100%!important;
406
- }
407
- /* .yt-thumb-wrap is the positioning context for the centered iframe */
408
- .yt-thumb-wrap{position:relative!important;overflow:hidden!important;width:100%!important;height:100%!important;background:#000!important}
409
- .yt-thumb-wrap img,.yt-thumb-wrap video{width:100%!important;height:100%!important;object-fit:cover!important}
410
- .wall-item{overflow:hidden!important}
411
- .wall-thumb img,.wall-thumb video{max-width:100%!important;max-height:100%!important;object-fit:cover!important}
412
- .slider-thumb{overflow:hidden!important}
413
- .slider-thumb img,.slider-thumb video{max-width:100%!important;max-height:100%!important;object-fit:cover!important}
414
- .fpt-slider-thumb img,.fpt-slider-thumb video{max-width:100%!important;max-height:100%!important;object-fit:cover!important}
415
-
416
- /* FPT Play slider moved into Livescore section - ensure it fits within the ls-section */
417
- .ls-section #home-fpt-section{margin-top:4px;padding:0 4px}
 
168
  min-width:100%!important;max-width:none!important;max-height:none!important;
169
  object-fit:cover!important;
170
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/hot_multi.js CHANGED
@@ -1,35 +1,17 @@
1
  // === OVERRIDE: loadHotTopics loads from MULTIPLE hashtags ===
2
- // v3: 5 topics (AI Thế Giới + AI Việt Nam + top 3 hot) + lazy load more
3
  // This file loaded AFTER app_v2.js, overrides the function
4
 
5
- const HT_AI_TOPICS = ['AI Thế Giới', 'AI Việt Nam'];
6
- let _htAllSources = [];
7
- let _htTopics = [];
8
- let _htPages = 0;
9
- let _htDates = [];
10
-
11
  async function loadHotTopics(){
12
  const j=await fetch('/api/hot_topics').then(r=>r.json()).catch(()=>({topics:[]}));
13
  const el=document.getElementById('hot-topics');if(!el)return;
14
  const topics=j.topics||[];
15
-
16
- // Prepend AI topics that aren't already in the list
17
- const prepend = HT_AI_TOPICS.filter(ai =>
18
- !topics.some(t => (t.topic || '').toLowerCase().includes(ai.toLowerCase()))
19
- ).map(ai => ({label: '#' + ai.replace(/\s+/g, ''), topic: ai, count: 0}));
20
-
21
- const finalTopics = [...prepend, ...topics].slice(0, 18);
22
-
23
- el.innerHTML=finalTopics.map(t=>{
24
  const topicText=t.topic||t.label.replace(/^#/,'');
25
  return`<button class="hot-chip" onclick="searchTopic('${topicText.replace(/'/g,"\\'")}')">${esc(t.label)}</button>`;
26
  }).join('');
27
-
28
- // Load tin HOT = tổng hợp từ TOP 5 hashtag (AI Thế Giới + AI Việt Nam + top 3 hot)
29
- const top5 = [...prepend, ...topics].slice(0, 5);
30
- if(top5.length>=2){
31
- _htTopics = top5.map(t=>t.topic||t.label.replace(/^#/,''));
32
- loadMultiHashtag(_htTopics);
33
  }else if(topics.length){
34
  searchTopic(topics[0].topic||topics[0].label.replace(/^#/,''));
35
  }
@@ -37,9 +19,6 @@ async function loadHotTopics(){
37
 
38
  async function loadMultiHashtag(topicList){
39
  const box=document.getElementById('hashtag-box');if(!box)return;
40
- _htAllSources = [];
41
- _htPages = 0;
42
-
43
  box.innerHTML=`<div class="hashtag-sources"><h3>🔥 Tin HOT tổng hợp</h3><div class="hashtag-loading"><div class="hashtag-spinner"></div>Tổng hợp từ ${topicList.length} chủ đề nóng nhất...</div></div>`;
44
  try{
45
  const results=await Promise.all(topicList.map(topic=>
@@ -54,70 +33,17 @@ async function loadMultiHashtag(topicList){
54
  if(src&&src.url&&!seen.has(src.url)){seen.add(src.url);src._topic=topicList[j];all.push(src);}
55
  }
56
  }
57
- _htAllSources = all;
58
- _renderHT();
 
 
 
 
 
 
 
 
 
 
59
  }catch(e){box.innerHTML=`<div class="hashtag-sources"><h3>🔥 Tin HOT</h3><div style="color:#e74c3c;padding:8px">Lỗi tải tin</div></div>`;}
60
  }
61
-
62
- function _renderHT(){
63
- const box=document.getElementById('hashtag-box');if(!box)return;
64
- const all = _htAllSources;
65
- if(!all.length){box.innerHTML=`<div class="hashtag-sources"><h3>🔥 Tin HOT</h3><div style="color:#888;padding:8px">Đang cập nhật...</div></div>`;return;}
66
-
67
- const perPage = 12;
68
- const total = all.length;
69
- const shown = Math.min((_htPages + 1) * perPage, total);
70
- const visible = all.slice(0, shown);
71
-
72
- let h=`<div class="hashtag-sources"><h3>🔥 Tin HOT tổng hợp <span style="font-size:10px;color:#888">(${total} bài · ${_htTopics.length} chủ đề)</span></h3><div id="ht-list">`;
73
- visible.forEach((s,i)=>{
74
- const dateStr = _htDates[i] ? `<span style="font-size:9px;color:#666;margin-left:4px">${esc(_htDates[i])}</span>` : '';
75
- h+=`<div class="hashtag-src-item" onclick="readArticle('${esc(s.url)}')"><div class="hashtag-src-img" id="ht-img-${i}"></div><div class="hashtag-src-text"><div class="hashtag-src-title">${esc(s.title)}</div><div class="hashtag-src-via">${esc(s.via||'')}${dateStr} · <span style="color:#f0c040;font-size:9px">#${esc(s._topic||'')}</span></div></div></div>`;
76
- });
77
- h+=`</div><div style="display:flex;gap:4px;flex-wrap:wrap;margin-top:8px">`;
78
- _htTopics.forEach(t=>{h+=`<button class="hot-chip" onclick="searchTopic('${t.replace(/'/g,"\\'")}')" style="font-size:10px">🔍 #${esc(t)}</button>`;});
79
- h+=`</div>`;
80
- if(shown < total){
81
- h+=`<button class="hashtag-load-more" id="ht-load-more" onclick="htLoadMore()">Tải thêm (${total - shown} tin) ▼</button>`;
82
- }
83
- h+=`</div>`;
84
- box.innerHTML=h;
85
-
86
- // Lazy load images + dates
87
- visible.forEach((s,i)=>{if(!s.url)return;const ctrl=new AbortController();setTimeout(()=>ctrl.abort(),4000);fetch('/api/article?url='+encodeURIComponent(s.url),{signal:ctrl.signal}).then(r=>r.json()).then(d=>{if(d&&(d.og_image||d.img)){const el=document.getElementById('ht-img-'+i);if(el)el.innerHTML=`<img src="${esc(d.og_image||d.img)}" onerror="this.style.display='none'">`;}if(d&&d.date_vn){_htDates[i]=d.date_vn;const viaEl=document.querySelector('#ht-list .hashtag-src-item:nth-child('+(i+1)+') .hashtag-src-via');if(viaEl&&!viaEl.querySelector('.ht-date')){const sp=document.createElement('span');sp.className='ht-date';sp.style.cssText='font-size:9px;color:#666;margin-left:4px';sp.textContent=d.date_vn;viaEl.insertBefore(sp,viaEl.querySelector('span')||null);}}}).catch(()=>{});});
88
- _htTopic = _htTopics[0];
89
- }
90
-
91
- async function htLoadMore(){
92
- const btn=document.getElementById('ht-load-more');if(!btn)return;
93
- btn.disabled=true;btn.textContent='Đang tải thêm...';
94
- const nextPage = _htPages + 1;
95
-
96
- try{
97
- // Fetch next page from each topic
98
- const results=await Promise.all(_htTopics.map(topic=>
99
- fetch(`/api/hashtag/sources?topic=${encodeURIComponent(topic)}&page=${nextPage}`).then(r=>r.json()).catch(()=>({sources:[]}))
100
- ));
101
- _htPages = nextPage;
102
-
103
- // Interleave new sources
104
- const seen=new Set(_htAllSources.map(s=>s.url));
105
- const mx=Math.max(...results.map(r=>(r.sources||[]).length));
106
- const newItems=[];
107
- for(let i=0;i<mx;i++){
108
- for(let j=0;j<results.length;j++){
109
- const src=(results[j].sources||[])[i];
110
- if(src&&src.url&&!seen.has(src.url)){seen.add(src.url);src._topic=_htTopics[j];newItems.push(src);}
111
- }
112
- }
113
-
114
- if(newItems.length){
115
- _htAllSources = [..._htAllSources, ...newItems];
116
- }
117
-
118
- _renderHT();
119
- }catch(e){
120
- btn.disabled=false;btn.textContent='Tải thêm ▼';
121
- toast('❌ Lỗi tải thêm');
122
- }
123
- }
 
1
  // === OVERRIDE: loadHotTopics loads from MULTIPLE hashtags ===
 
2
  // This file loaded AFTER app_v2.js, overrides the function
3
 
 
 
 
 
 
 
4
  async function loadHotTopics(){
5
  const j=await fetch('/api/hot_topics').then(r=>r.json()).catch(()=>({topics:[]}));
6
  const el=document.getElementById('hot-topics');if(!el)return;
7
  const topics=j.topics||[];
8
+ el.innerHTML=topics.slice(0,18).map(t=>{
 
 
 
 
 
 
 
 
9
  const topicText=t.topic||t.label.replace(/^#/,'');
10
  return`<button class="hot-chip" onclick="searchTopic('${topicText.replace(/'/g,"\\'")}')">${esc(t.label)}</button>`;
11
  }).join('');
12
+ // Load tin HOT = tổng hợp từ TOP 3 hashtag nóng nhất
13
+ if(topics.length>=2){
14
+ loadMultiHashtag(topics.slice(0,3).map(t=>t.topic||t.label.replace(/^#/,'')));
 
 
 
15
  }else if(topics.length){
16
  searchTopic(topics[0].topic||topics[0].label.replace(/^#/,''));
17
  }
 
19
 
20
  async function loadMultiHashtag(topicList){
21
  const box=document.getElementById('hashtag-box');if(!box)return;
 
 
 
22
  box.innerHTML=`<div class="hashtag-sources"><h3>🔥 Tin HOT tổng hợp</h3><div class="hashtag-loading"><div class="hashtag-spinner"></div>Tổng hợp từ ${topicList.length} chủ đề nóng nhất...</div></div>`;
23
  try{
24
  const results=await Promise.all(topicList.map(topic=>
 
33
  if(src&&src.url&&!seen.has(src.url)){seen.add(src.url);src._topic=topicList[j];all.push(src);}
34
  }
35
  }
36
+ if(!all.length){box.innerHTML=`<div class="hashtag-sources"><h3>🔥 Tin HOT</h3><div style="color:#888;padding:8px">Đang cập nhật...</div></div>`;return;}
37
+ let h=`<div class="hashtag-sources"><h3>🔥 Tin HOT tổng hợp <span style="font-size:10px;color:#888">(${all.length} bài · ${topicList.length} chủ đề)</span></h3><div id="ht-list">`;
38
+ all.slice(0,12).forEach((s,i)=>{
39
+ h+=`<div class="hashtag-src-item" onclick="readArticle('${esc(s.url)}')"><div class="hashtag-src-img" id="ht-img-${i}"></div><div class="hashtag-src-text"><div class="hashtag-src-title">${esc(s.title)}</div><div class="hashtag-src-via">${esc(s.via||'')} · <span style="color:#f0c040;font-size:9px">#${esc(s._topic||'')}</span></div></div></div>`;
40
+ });
41
+ h+=`</div><div style="display:flex;gap:4px;flex-wrap:wrap;margin-top:8px">`;
42
+ topicList.forEach(t=>{h+=`<button class="hot-chip" onclick="searchTopic('${t.replace(/'/g,"\\'")}')" style="font-size:10px">🔍 #${esc(t)}</button>`;});
43
+ h+=`</div></div>`;
44
+ box.innerHTML=h;
45
+ // Lazy load images
46
+ all.slice(0,12).forEach((s,i)=>{if(!s.url)return;fetch('/api/article?url='+encodeURIComponent(s.url)).then(r=>r.json()).then(d=>{if(d&&(d.og_image||d.img)){const el=document.getElementById('ht-img-'+i);if(el)el.innerHTML=`<img src="${esc(d.og_image||d.img)}" onerror="this.style.display='none'">`;}}).catch(()=>{});});
47
+ _htTopic=topicList[0];
48
  }catch(e){box.innerHTML=`<div class="hashtag-sources"><h3>🔥 Tin HOT</h3><div style="color:#e74c3c;padding:8px">Lỗi tải tin</div></div>`;}
49
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/index_v2.html CHANGED
@@ -8,34 +8,13 @@
8
  <meta property="og:title" content="VNEWS - Tin Tức Việt Nam">
9
  <meta property="og:image" content="https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg">
10
  <link rel="canonical" href="https://bep40-vnews.hf.space">
11
- <link rel="stylesheet" href="/static/wc2026.css"><link rel="stylesheet" href="/static/fm_fix.css">
12
  <script src="https://cdn.jsdelivr.net/npm/hls.js@1/dist/hls.min.js"></script>
13
- <style>
14
- *{box-sizing:border-box;margin:0;padding:0}body{background:#111;color:#eee;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;overflow-x:hidden}.header{background:linear-gradient(135deg,#0d1117,#1a3a2a 50%,#8b7500);padding:12px;text-align:center}.header h1{font-size:18px;color:#fff}.header p{font-size:10px;color:#aaa}.cats{display:flex;overflow-x:auto;background:#1a1a1a;border-bottom:1px solid #333;padding:0 4px;position:sticky;top:0;z-index:50;scrollbar-width:none}.cats::-webkit-scrollbar{display:none}.cat{padding:9px 11px;color:#888;font-size:11px;white-space:nowrap;border-bottom:2px solid transparent;cursor:pointer;flex-shrink:0}.cat.active{color:#5cb87a;border-bottom-color:#5cb87a;font-weight:700}.view{display:none}.view.active{display:block}.loading{text-align:center;padding:30px;color:#777;font-size:12px}.slider-wrap{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}.slider-header{padding:7px 10px;display:flex;align-items:center;justify-content:space-between}.slider-label{color:#f0c040;font-size:13px;font-weight:800}.slider-note{font-size:10px;color:#777}.slider-track{display:flex;overflow-x:auto;overflow-y:hidden;gap:8px;padding:4px 10px 10px;scrollbar-width:none;-webkit-overflow-scrolling:touch;touch-action:pan-x pan-y;overscroll-behavior-x:contain;scroll-snap-type:x proximity}.slider-track>*{flex:0 0 auto;scroll-snap-align:start;-webkit-tap-highlight-color:transparent}.slider-track::-webkit-scrollbar{display:none}.slider-item{flex:0 0 160px;cursor:pointer;box-sizing:border-box}.hl-league-block{display:inline-flex;align-items:flex-start;flex:0 0 auto;min-width:0}.slider-thumb{position:relative;width:100%;aspect-ratio:16/9;border-radius:6px;overflow:hidden;background:#333}.slider-thumb img,.slider-thumb video{width:100%;height:100%;object-fit:cover}.slider-title{font-size:10px;color:#ccc;margin-top:3px;line-height:1.2;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.card-play{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:30px;height:30px;border-radius:50%;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px}.grid{display:grid;grid-template-columns:repeat(2,1fr);gap:6px;padding:6px 4px}@media(min-width:650px){.grid{grid-template-columns:repeat(3,1fr)}}.card{background:#1a1a1a;border:1px solid #222;border-radius:8px;overflow:hidden;cursor:pointer}.card-img{position:relative;aspect-ratio:16/9;background:#333}.card-img img{width:100%;height:100%;object-fit:cover}.card-body{padding:6px 8px}.card-title{font-size:11px;line-height:1.35;color:#eee;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.badge{font-size:8px;padding:1px 5px;border-radius:3px;font-weight:700;display:inline-block;margin-bottom:2px;color:#fff}.badge-vne{background:#c0392b}.badge-genk{background:#6a1b9a}.badge-ai{background:#2d8659}.badge-wc{background:#0b6bcb}.section-title{font-size:13px;font-weight:800;color:#5cb87a;margin:8px 0 4px;padding-left:8px;border-left:3px solid #5cb87a}.back-btn{background:#111;color:#fff;border:none;padding:10px;font-size:12px;width:100%;position:sticky;top:0;z-index:60;cursor:pointer}.article-view{padding:12px 8px 40px;max-width:760px;margin:0 auto}.article-title{font-size:18px;font-weight:800;line-height:1.3;margin-bottom:8px}.article-summary{background:#1a2a1f;border-left:3px solid #2d8659;padding:10px;margin-bottom:14px;color:#ccc;font-size:13px}.article-p{font-size:14px;line-height:1.7;color:#ccc;margin-bottom:10px}.article-img{width:100%;border-radius:6px;margin:10px 0}.article-h2{font-size:16px;margin:16px 0 8px;color:#eee}.article-actions{display:flex;gap:8px;flex-wrap:wrap;border-top:1px solid #333;margin-top:16px;padding-top:10px}.article-actions button{background:#1a1a1a;border:1px solid #333;color:#ccc;padding:7px 12px;border-radius:14px;font-size:11px;cursor:pointer}.article-actions button.primary{background:#2d8659;border-color:#2d8659;color:#fff}.article-ai-ask{margin-top:12px;background:#141414;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.article-ai-ask textarea{width:100%;min-height:60px;background:#222;border:1px solid #444;color:#eee;border-radius:8px;padding:9px;font-size:12px}.article-ai-ask button{background:#2d8659;border:0;color:#fff;border-radius:10px;padding:8px 12px;margin-top:6px;font-size:11px;cursor:pointer}.article-ai-answer{white-space:pre-wrap;color:#ccc;font-size:13px;line-height:1.55;margin-top:8px}.tiktok-container{width:100%;height:80vh;max-height:680px;min-height:400px;background:#000}.tiktok-container.feed-fullscreen{position:fixed;inset:0;width:100vw;height:100dvh;max-height:none;min-height:0;z-index:99990;background:#000}.tiktok-container.feed-fullscreen .tiktok-feed,.tiktok-container.feed-fullscreen .tiktok-slide{height:100dvh;max-height:100dvh;min-height:0}.tiktok-feed{height:100%;overflow-y:scroll;-webkit-overflow-scrolling:touch;scroll-behavior:smooth;scroll-snap-type:y mandatory;scrollbar-width:none;touch-action:pan-y;-webkit-user-select:none;user-select:none;overscroll-behavior:contain}.tiktok-feed::-webkit-scrollbar{display:none}.tiktok-slide{height:80vh;max-height:680px;min-height:400px;scroll-snap-align:start;position:relative;background:#000;display:flex;align-items:center;justify-content:center;touch-action:pan-y;cursor:pointer}.tiktok-slide video{width:100%;height:100%;object-fit:cover;border:none;touch-action:manipulation}.tiktok-slide iframe{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:100%;height:100%;border:none;pointer-events:none}.tiktok-slide .slide-gesture{position:absolute;inset:0;z-index:2;touch-action:pan-y;pointer-events:auto;cursor:pointer;background:transparent}.tiktok-slide .tiktok-bottom,.tiktok-slide .tiktok-right,.tiktok-slide .tiktok-counter{pointer-events:auto}.tiktok-slide .inline-comments{pointer-events:auto}.yt-thumb-wrap{position:relative;width:100%;height:100%;background-size:cover;background-position:center;background-image:url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="1" height="1"%3E%3C/svg%3E')}.yt-thumb-wrap iframe{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:100%;height:100%;border:none;pointer-events:auto;cursor:pointer}.tiktok-slide.ratio-wide video{width:100%!important;height:100%!important;object-fit:contain!important}.tiktok-slide.ratio-wide iframe{position:absolute!important;top:50%!important;left:50%!important;transform:translate(-50%,-50%)!important;width:calc(100vw - 1px)!important;height:56.25vw!important;max-width:100vw!important;max-height:100%!important;border:none!important;pointer-events:none!important}.tiktok-bottom{position:absolute;bottom:0;left:0;right:60px;padding:12px 10px 16px;background:linear-gradient(transparent,rgba(0,0,0,.85));z-index:3}.tiktok-title{font-size:12px;color:#fff;max-height:34px;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}.tiktok-desc{font-size:10px;color:#bbb;margin-top:3px;max-height:40px;overflow:hidden;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical}.tiktok-counter{position:absolute;top:8px;left:8px;background:rgba(0,0,0,.5);font-size:9px;padding:2px 7px;border-radius:8px;color:#fff;z-index:4}.tiktok-right{position:absolute;right:8px;bottom:100px;display:flex;flex-direction:column;align-items:center;gap:14px;z-index:5}.tiktok-right-btn{display:flex;flex-direction:column;align-items:center;gap:2px;background:none;border:0;color:#fff;cursor:pointer;font-size:10px}.tiktok-right-btn .icon{width:42px;height:42px;border-radius:50%;background:rgba(255,255,255,.12);display:flex;align-items:center;justify-content:center;font-size:20px}.tiktok-right-btn .count{font-size:10px;color:#ddd}.inline-comments{position:absolute;bottom:0;left:0;right:0;max-height:60%;min-height:140px;background:rgba(18,18,18,.95);border-radius:14px 14px 0 0;z-index:10;overflow:clip;display:flex;flex-direction:column}.inline-cmt-header{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid #333;color:#5cb87a;font-size:12px;font-weight:700;flex-shrink:0}.inline-cmt-header button{background:none;border:0;color:#fff;font-size:16px;cursor:pointer}.inline-cmt-list{flex:1 1 auto;overflow-y:auto;padding:6px 10px;max-height:140px;min-height:40px}.inline-cmt-item{background:#222;border-radius:8px;padding:6px 8px;margin:4px 0;color:#ccc;font-size:11px;line-height:1.3}.inline-cmt-time{font-size:9px;color:#777;margin-right:6px}.inline-cmt-input{display:flex;gap:6px;padding:8px 10px;border-top:1px solid #333;flex-shrink:0;position:sticky;bottom:0;background:rgba(18,18,18,.98)}.inline-cmt-input input{flex:1;background:#222;border:1px solid #444;color:#eee;border-radius:16px;padding:7px 12px;font-size:11px;min-height:32px}.inline-cmt-input button{background:#2d8659;border:0;color:#fff;border-radius:16px;padding:7px 12px;font-size:11px;cursor:pointer;min-height:32px}.wc2026-section{margin:6px 4px;background:linear-gradient(135deg,#0d1117,#1a1a3a);border:1px solid #1a3a5a;border-radius:10px;overflow:hidden}.wc-header{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;background:linear-gradient(90deg,#0b2e4a,#1a3a5a)}.wc-header h2{font-size:15px;color:#fff;margin:0}.wc-live-badge{font-size:10px;color:#e74c3c;font-weight:700;animation:wc-pulse 1.5s infinite}@keyframes wc-pulse{0%,100%{opacity:1}50%{opacity:.4}}.wc-tabs{display:flex;gap:4px;padding:8px 10px;overflow-x:auto;scrollbar-width:none}.wc-tabs::-webkit-scrollbar{display:none}.wc-tab{padding:5px 10px;background:#1a2a3a;border:1px solid #2a3a4a;border-radius:12px;color:#8ab4f0;font-size:10px;cursor:pointer;white-space:nowrap;flex-shrink:0}.wc-tab.active{background:#0b6bcb;border-color:#0b6bcb;color:#fff;font-weight:700}.wc-content{padding:8px 10px;max-height:500px;overflow-y:auto}.wc-news-grid{display:flex;flex-direction:column;gap:8px}.wc-news-item{display:flex;gap:8px;padding:8px;background:#1a2030;border-radius:8px;cursor:pointer}.wc-news-item:active{opacity:.8}.wc-news-img{flex:0 0 70px;aspect-ratio:16/9;border-radius:6px;overflow:hidden;background:#222}.wc-news-img img{width:100%;height:100%;object-fit:cover}.wc-news-text{flex:1;min-width:0}.wc-news-title{font-size:11px;font-weight:700;color:#eee;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.wc-news-via{font-size:9px;color:#6a9fca;margin-top:2px}.ls-section{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}.ls-header{padding:7px 10px;display:flex;align-items:center;justify-content:space-between}.ls-header h3{color:#f0c040;font-size:13px;font-weight:800}.ls-tabs{display:flex;gap:4px;padding:0 10px 8px;overflow-x:auto;scrollbar-width:none}.ls-tabs::-webkit-scrollbar{display:none}.ls-tab{padding:4px 10px;background:#222;border:1px solid #333;border-radius:12px;color:#999;font-size:10px;white-space:nowrap;cursor:pointer;flex-shrink:0}.ls-tab.active{background:#2d8659;border-color:#2d8659;color:#fff;font-weight:700}.ls-content{max-height:420px;overflow-y:auto;padding:0 6px 8px;font-size:12px;color:#ddd}.ls-content ul{list-style:none;padding:0;margin:0}.ls-content .title-content{display:flex;gap:6px;align-items:center;background:#222;border-radius:4px;margin:4px 0;padding:5px 8px}.ls-content .title-content img{width:18px;height:18px}.ls-content .title-content strong{font-size:11px;color:#ccc}.ls-content .match-detail{padding:6px;border-bottom:1px solid #262626;cursor:pointer}.ls-content .match-detail:hover{background:#1a2a1f}.ls-content .match{display:flex;flex-wrap:wrap;align-items:center;gap:4px}.ls-content .datetime{width:100%;font-size:9px;color:#888}.ls-content .teams{display:flex;width:100%;align-items:center;gap:4px}.ls-content .team{flex:1;display:flex;align-items:center;gap:4px;min-width:0;text-decoration:none}.ls-content .team .name{font-size:11px;color:#ddd;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ls-content .team .logo img{width:18px;height:18px}.ls-content .home-team{justify-content:flex-end;text-align:right}.ls-content .status{flex:0 0 54px;text-align:center}.ls-content .status a{color:#fff;text-decoration:none;font-weight:800;font-size:12px}.ls-content .status .label{font-size:8px;color:#888;display:block}.ls-content .status .label.live{color:#e74c3c}.ls-content .info,.ls-content .btns{display:none}.ls-content table{width:100%;border-collapse:collapse;font-size:11px;color:#ccc}.ls-content table th{background:#222;color:#999;padding:5px 4px;font-size:10px;border-bottom:1px solid #333}.ls-content table td{padding:4px 3px;border-bottom:1px solid #1a1a1a}.ls-content table .team-name{display:flex;align-items:center;gap:4px}.ls-content table .team-name img{width:16px;height:16px}.ls-content table .pts{font-weight:800;color:#f0c040}.match-overlay{position:fixed;inset:0;background:#111;z-index:9999;display:none;flex-direction:column;overflow:auto}.match-overlay.active{display:flex}.mo-header{padding:10px;background:#1a1a1a;display:flex;justify-content:space-between;align-items:center;position:sticky;top:0;z-index:1}.mo-header h3{font-size:13px;color:#eee}.mo-close{background:none;border:0;color:#fff;font-size:22px;cursor:pointer}.mo-tabs{display:flex;gap:4px;padding:8px 10px;background:#1a1a1a;overflow-x:auto}.mo-tab{padding:5px 12px;background:#222;border:1px solid #333;border-radius:10px;color:#999;font-size:10px;cursor:pointer;white-space:nowrap}.mo-tab.active{background:#2d8659;color:#fff}.mo-body{padding:8px;overflow-x:auto;font-size:12px;color:#ddd}.mo-body ul{list-style:none;padding:0;margin:0}.mo-body li{padding:5px 0;border-bottom:1px solid #222}.featured-match{margin:6px 4px;background:linear-gradient(135deg,#1a2a1f,#0d1117);border:1px solid #2d8659;border-radius:10px;padding:12px;cursor:pointer}.fm-league{text-align:center;color:#5cb87a;font-size:9px;font-weight:700;text-transform:uppercase}.fm-teams{display:flex;align-items:center;justify-content:center;gap:10px;margin-top:6px}.fm-team{flex:1;display:flex;flex-direction:column;align-items:center;gap:4px}.fm-team img{width:32px;height:32px;object-fit:contain}.fm-team span{font-size:10px;color:#ccc;text-align:center}.fm-score{font-size:22px;font-weight:900;min-width:60px;text-align:center;color:#fff}.fm-status{text-align:center;margin-top:6px;font-size:9px;color:#e74c3c;font-weight:700}.fm-status.upcoming{color:#f0c040}.ai-compose{margin:6px 4px;background:#141414;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.ai-compose-title{font-size:13px;font-weight:800;color:#5cb87a;margin-bottom:8px}.ai-compose-row{display:flex;gap:6px;margin-top:6px}.ai-compose input{flex:1;background:#222;border:1px solid #333;color:#eee;border-radius:18px;padding:9px 12px;font-size:12px;min-width:0}.ai-compose button{background:#2d8659;border:0;color:#fff;border-radius:18px;padding:9px 12px;font-size:11px;font-weight:700;cursor:pointer;white-space:nowrap}.ai-compose button.secondary{background:#333}.ai-compose button.hot-short-btn{background:linear-gradient(135deg,#8b1a5a,#c0392b);border:1px solid #e07050;color:#fff;box-shadow:0 0 10px rgba(192,57,43,.4);animation:hot-pulse 2s infinite}@keyframes hot-pulse{0%,100%{box-shadow:0 0 6px rgba(192,57,43,.35)}50%{box-shadow:0 0 16px rgba(192,57,43,.75)}}.hot-topic-row{display:flex;gap:6px;overflow-x:auto;padding:4px 0;scrollbar-width:none}.hot-topic-row::-webkit-scrollbar{display:none}.hot-chip{flex:0 0 auto;background:#222;border:1px solid #333;color:#ddd;border-radius:16px;padding:5px 10px;font-size:11px;cursor:pointer;white-space:nowrap}.hot-chip:active{transform:scale(.96)}.hashtag-sources{margin:8px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.hashtag-sources h3{font-size:13px;color:#5cb87a;margin-bottom:8px}.hashtag-src-item{display:flex;gap:8px;padding:8px;background:#202020;border-radius:8px;margin:6px 0;cursor:pointer}.hashtag-src-item:active{opacity:.8}.hashtag-src-img{flex:0 0 80px;aspect-ratio:16/9;background:#333;border-radius:6px;overflow:hidden}.hashtag-src-img img{width:100%;height:100%;object-fit:cover}.hashtag-src-text{flex:1;min-width:0}.hashtag-src-title{font-size:12px;font-weight:700;color:#eee;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.hashtag-src-via{font-size:10px;color:#888;margin-top:2px}.hashtag-rewrite-btn{width:100%;margin-top:8px;background:#2d8659;border:0;color:#fff;padding:9px;border-radius:10px;font-size:12px;font-weight:700;cursor:pointer}.hashtag-load-more{width:100%;margin-top:8px;background:#222;border:1px solid #333;color:#ccc;padding:9px;border-radius:10px;font-size:12px;cursor:pointer}.hashtag-loading{display:flex;align-items:center;gap:8px;padding:12px;color:#888;font-size:12px}.hashtag-spinner{width:16px;height:16px;border:2px solid #333;border-top-color:#5cb87a;border-radius:50%;animation:ht-spin .8s linear infinite}@keyframes ht-spin{to{transform:rotate(360deg)}}.wall-item{flex:0 0 260px;background:#141414;border:1px solid #2b2b2b;border-radius:10px;padding:8px}.wall-item-new{animation:wall-flash 1.8s ease-out}@keyframes wall-flash{0%{border-color:#f0c040;box-shadow:0 0 18px rgba(240,192,64,.35)}30%{border-color:#f0c040;box-shadow:0 0 12px rgba(240,192,64,.2)}100%{border-color:#2b2b2b;box-shadow:none}}.wall-thumb{width:100%;aspect-ratio:16/9;border-radius:8px;background:#222;overflow:hidden;margin-bottom:6px;position:relative}.wall-thumb img,.wall-thumb video{width:100%;height:100%;object-fit:cover}.wall-video-badge{position:absolute;top:4px;right:4px;background:rgba(45,134,89,.9);color:#fff;font-size:10px;padding:2px 6px;border-radius:6px;font-weight:700}.wall-title{font-size:12px;color:#5cb87a;font-weight:800;line-height:1.3;margin-bottom:4px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.wall-text{font-size:11px;color:#bbb;line-height:1.4;white-space:pre-wrap;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}.wall-actions{display:flex;gap:6px;margin-top:8px}.wall-actions button{flex:1;border:1px solid #333;background:#222;color:#ddd;border-radius:14px;padding:6px 8px;font-size:10px;cursor:pointer}.wall-actions button.primary{background:#2d8659;border-color:#2d8659;color:#fff}.wall-actions button.wall-btn-design{background:#1a3a5a;border-color:#3a5a7a;color:#fff;font-weight:700}#progress-toast{position:fixed;bottom:70px;left:50%;transform:translateX(-50%);background:#2d8659;color:#fff;padding:10px 20px;border-radius:20px;font-size:12px;z-index:99998;box-shadow:0 4px 12px rgba(0,0,0,.4);display:none;white-space:nowrap}.storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 4px}
15
- .hl-load-more{margin:4px 8px 8px;background:#222;border:1px solid #333;color:#ccc;padding:6px 12px;border-radius:8px;font-size:11px;cursor:pointer;width:calc(100% - 16px);display:block}
16
- .hl-load-more:hover{background:#2a2a2a}
17
- .ls-section-header{padding:8px 10px;font-size:11px;font-weight:700;color:#5cb87a;border-bottom:1px solid #2a2a2a}
18
- .ls-section-header.upcoming{color:#f0c040}
19
- .ls-section-header.finished{color:#e74c3c}
20
- .ls-section-header.yesterday{color:#8ab4f0}
21
- .ls-section-header.older{color:#888}.ls-section-header.older{color:#888}
22
- /* FPT PLAY / HIGHLIGHT video overflow fix v2 — same containment as short-AI wall
23
- FIX: iframes now use width:100%/height:100% (matching <video>) instead of
24
- width:177.78vh. FPT/YouTube iframes now appear IDENTICAL to Short AI <video> tags.
25
- The .ratio-wide toggle (16:9) is handled by fm_fix.css with matching ID specificity. */
26
- .tiktok-slide{overflow:hidden!important}
27
- .tiktok-slide video{position:absolute!important;top:50%!important;left:50%!important;transform:translate(-50%,-50%)!important;width:100%!important;height:100%!important;object-fit:contain!important;border:none!important;pointer-events:auto!important}
28
- .tiktok-slide iframe{position:absolute!important;top:50%!important;left:50%!important;transform:translate(-50%,-50%)!important;width:100%!important;height:100%!important;border:none!important;pointer-events:none!important}
29
- .tiktok-slide.ratio-wide iframe{position:absolute!important;top:50%!important;left:50%!important;transform:translate(-50%,-50%)!important;width:calc(100vw - 1px)!important;height:56.25vw!important;max-width:100vw!important;max-height:100dvh!important;border:none!important;pointer-events:auto!important}
30
- .yt-thumb-wrap{overflow:hidden!important}
31
- .yt-thumb-wrap iframe{position:absolute!important;top:50%!important;left:50%!important;transform:translate(-50%,-50%)!important;width:100%!important;height:100%!important;border:none!important;pointer-events:auto!important;cursor:pointer!important}
32
- .wall-thumb img,.wall-thumb video{max-width:100%!important;max-height:100%!important;object-fit:cover!important}
33
- </style>
34
  </head>
35
  <body>
36
- <div class="header"><h1>📰 VNEWS</h1><p>Tin tức · Bóng đá LIVE · Highlight · AI · World Cup 2026</p></div>
37
  <div class="cats" id="cat-bar"></div>
38
- <div id="home-hl-section"></div>
39
  <div id="view-home" class="view active"><div class="loading">Đang tải...</div></div>
40
  <div id="view-cat" class="view"></div>
41
  <div id="view-video" class="view"></div>
@@ -51,49 +30,18 @@
51
  var _cats=[],_hlLeagueData={},_currentArticle=null;window._currentEventId='';
52
  function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]))}
53
  function showView(id){document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.getElementById(id)?.classList.add('active')}
54
- function switchCat(id){document.querySelectorAll('.cat').forEach(c=>c.classList.remove('active'));document.querySelector('[data-cat="'+id+'"]')?.classList.add('active');document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.querySelectorAll('video').forEach(v=>{v.pause();if(v._hls){v._hls.destroy();v._hls=null}});document.querySelectorAll('iframe[data-yt-src]').forEach(f=>{f.src=''});if(id==='home')document.getElementById('view-home').classList.add('active');else if(id==='news-all'){document.getElementById('view-cat').classList.add('active');loadNewsTab()}else{document.getElementById('view-cat').classList.add('active');loadCat(id)}}
55
  function toast(msg){let t=document.getElementById('progress-toast');if(t){t.textContent=msg;t.style.display='block';setTimeout(()=>{t.style.display='none'},3500)}}
56
- function doShare(title,url,img,postId){
57
- var shareUrl;
58
- if(postId){
59
- shareUrl = SPACE+'/s?post_id='+encodeURIComponent(postId)+'&title='+encodeURIComponent(title);
60
- } else {
61
- shareUrl = SPACE+'/s?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title)+'&img='+encodeURIComponent(img||'');
62
- }
63
- if(navigator.clipboard && navigator.clipboard.writeText){
64
- navigator.clipboard.writeText(shareUrl).then(function(){
65
- toast('📋 Đã sao chép link!');
66
- try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){}
67
- }).catch(function(){
68
- try{
69
- var ta=document.createElement('textarea');ta.value=shareUrl;ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='-9999px';ta.style.opacity='0';
70
- document.body.appendChild(ta);ta.select();ta.setSelectionRange(0,99999);
71
- if(document.execCommand('copy')){toast('📋 Đã sao chép link!');}else{prompt('📋 Sao chép link:', shareUrl);}
72
- document.body.removeChild(ta);
73
- }catch(e){prompt('📋 Sao chép link:', shareUrl);}
74
- try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){}
75
- });
76
- } else {
77
- try{
78
- var ta=document.createElement('textarea');ta.value=shareUrl;ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='-9999px';ta.style.opacity='0';
79
- document.body.appendChild(ta);ta.select();ta.setSelectionRange(0,99999);
80
- if(document.execCommand('copy')){toast('📋 Đã sao chép link!');}else{prompt('📋 Sao chép link:', shareUrl);}
81
- document.body.removeChild(ta);
82
- }catch(e){prompt('📋 Sao chép link:', shareUrl);}
83
- try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){}
84
- }
85
- }
86
- async function init(){_cats=await fetch('/api/categories').then(r=>r.json()).catch(()=>[]);let bar='<div class="cat active" data-cat="home">🏠</div><div class="cat" data-cat="news-all">📰 Tin tức</div>';_cats.forEach(c=>{bar+='<div class="cat" data-cat="'+c.id+'">'+c.name+'</div>'});document.getElementById('cat-bar').innerHTML=bar;document.querySelectorAll('.cat').forEach(t=>{t.onclick=()=>switchCat(t.dataset.cat)});}
87
  var SPACE=location.origin;
88
  </script>
89
- <script src="/static/app_v2.js?v=20260828fptrestore"></script>
90
- <script src="/static/designer_v2.js?v=20260817fix1"></script>
91
  <script src="/static/yt_live.js"></script>
92
- <script src="/static/vtv_init.js"></script>
93
- <script src="/static/hot_multi.js?v=1"></script>
94
  <script src="/static/wc2026_v2.js"></script>
95
  <script src="/static/live_mode.js"></script>
96
  <script src="/static/match_detail_v6.js"></script>
97
- <script>init();loadHome();</script>
98
  </body>
99
  </html>
 
8
  <meta property="og:title" content="VNEWS - Tin Tức Việt Nam">
9
  <meta property="og:image" content="https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg">
10
  <link rel="canonical" href="https://bep40-vnews.hf.space">
11
+ <link rel="stylesheet" href="/static/wc2026.css">
12
  <script src="https://cdn.jsdelivr.net/npm/hls.js@1/dist/hls.min.js"></script>
13
+ <style>*{box-sizing:border-box;margin:0;padding:0}body{background:#111;color:#eee;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;overflow-x:hidden}.header{background:linear-gradient(135deg,#0d1117,#1a3a2a 50%,#8b7500);padding:12px;text-align:center}.header h1{font-size:18px;color:#fff}.header p{font-size:10px;color:#aaa}.cats{display:flex;overflow-x:auto;background:#1a1a1a;border-bottom:1px solid #333;padding:0 4px;position:sticky;top:0;z-index:50;scrollbar-width:none}.cats::-webkit-scrollbar{display:none}.cat{padding:9px 11px;color:#888;font-size:11px;white-space:nowrap;border-bottom:2px solid transparent;cursor:pointer;flex-shrink:0}.cat.active{color:#5cb87a;border-bottom-color:#5cb87a;font-weight:700}.view{display:none}.view.active{display:block}.loading{text-align:center;padding:30px;color:#777;font-size:12px}.slider-wrap{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}.slider-header{padding:7px 10px;display:flex;align-items:center;justify-content:space-between}.slider-label{color:#f0c040;font-size:13px;font-weight:800}.slider-note{font-size:10px;color:#777}.slider-track{display:flex;overflow-x:auto;gap:8px;padding:4px 10px 10px;scrollbar-width:none}.slider-track::-webkit-scrollbar{display:none}.slider-item{flex:0 0 160px;cursor:pointer}.shorts-item{flex:0 0 110px!important}.slider-thumb{position:relative;width:100%;aspect-ratio:16/9;border-radius:6px;overflow:hidden;background:#333}.shorts-thumb{aspect-ratio:3/4!important;border-radius:8px!important}.slider-thumb img,.slider-thumb video{width:100%;height:100%;object-fit:cover}.slider-title{font-size:10px;color:#ccc;margin-top:3px;line-height:1.2;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.card-play{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:30px;height:30px;border-radius:50%;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px}.grid{display:grid;grid-template-columns:repeat(2,1fr);gap:6px;padding:6px 4px}@media(min-width:650px){.grid{grid-template-columns:repeat(3,1fr)}}.card{background:#1a1a1a;border:1px solid #222;border-radius:8px;overflow:hidden;cursor:pointer}.card-img{position:relative;aspect-ratio:16/9;background:#333}.card-img img{width:100%;height:100%;object-fit:cover}.card-body{padding:6px 8px}.card-title{font-size:11px;line-height:1.35;color:#eee;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.badge{font-size:8px;padding:1px 5px;border-radius:3px;font-weight:700;display:inline-block;margin-bottom:2px;color:#fff}.badge-vne{background:#c0392b}.badge-bbc{background:#b80000}.badge-dt{background:#1565c0}.badge-genk{background:#6a1b9a}.badge-fpt{background:#f26522}.badge-ai{background:#2d8659}.badge-wc{background:#0b6bcb}.section-title{font-size:13px;font-weight:800;color:#5cb87a;margin:8px 0 4px;padding-left:8px;border-left:3px solid #5cb87a}.back-btn{background:#111;color:#fff;border:none;padding:10px;font-size:12px;width:100%;position:sticky;top:0;z-index:60;cursor:pointer}.article-view{padding:12px 8px 40px;max-width:760px;margin:0 auto}.article-title{font-size:18px;font-weight:800;line-height:1.3;margin-bottom:8px}.article-summary{background:#1a2a1f;border-left:3px solid #2d8659;padding:10px;margin-bottom:14px;color:#ccc;font-size:13px}.article-p{font-size:14px;line-height:1.7;color:#ccc;margin-bottom:10px}.article-img{width:100%;border-radius:6px;margin:10px 0}.article-h2{font-size:16px;margin:16px 0 8px;color:#eee}.article-actions{display:flex;gap:8px;flex-wrap:wrap;border-top:1px solid #333;margin-top:16px;padding-top:10px}.article-actions button{background:#1a1a1a;border:1px solid #333;color:#ccc;padding:7px 12px;border-radius:14px;font-size:11px;cursor:pointer}.article-actions button.primary{background:#2d8659;border-color:#2d8659;color:#fff}.article-ai-ask{margin-top:12px;background:#141414;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.article-ai-ask textarea{width:100%;min-height:60px;background:#222;border:1px solid #444;color:#eee;border-radius:10px;padding:9px;font-size:12px}.article-ai-ask button{background:#2d8659;border:0;color:#fff;border-radius:10px;padding:8px 12px;margin-top:6px;font-size:11px;cursor:pointer}.article-ai-answer{white-space:pre-wrap;color:#ccc;font-size:13px;line-height:1.55;margin-top:8px}.tiktok-container{width:100%;height:80vh;max-height:680px;min-height:400px;background:#000}.tiktok-feed{height:100%;overflow-y:scroll;scroll-snap-type:y mandatory;scrollbar-width:none}.tiktok-feed::-webkit-scrollbar{display:none}.tiktok-slide{height:80vh;max-height:680px;min-height:400px;scroll-snap-align:start;position:relative;background:#000;display:flex;align-items:center;justify-content:center}.tiktok-slide video,.tiktok-slide iframe{width:100%;height:100%;object-fit:cover;border:none}.tiktok-slide.ratio-wide video,.tiktok-slide.ratio-wide iframe{object-fit:contain}.tiktok-bottom{position:absolute;bottom:0;left:0;right:60px;padding:12px 10px 16px;background:linear-gradient(transparent,rgba(0,0,0,.85));z-index:3}.tiktok-title{font-size:12px;color:#fff}.tiktok-counter{position:absolute;top:8px;left:8px;background:rgba(0,0,0,.5);font-size:9px;padding:2px 7px;border-radius:8px;color:#fff;z-index:4}.tiktok-right{position:absolute;right:8px;bottom:100px;display:flex;flex-direction:column;align-items:center;gap:14px;z-index:5}.tiktok-right-btn{display:flex;flex-direction:column;align-items:center;gap:2px;background:none;border:0;color:#fff;cursor:pointer;font-size:10px}.tiktok-right-btn .icon{width:42px;height:42px;border-radius:50%;background:rgba(255,255,255,.12);display:flex;align-items:center;justify-content:center;font-size:20px}.tiktok-right-btn .count{font-size:10px;color:#ddd}.inline-comments{position:absolute;bottom:0;left:0;right:0;max-height:50%;background:rgba(18,18,18,.95);border-radius:14px 14px 0 0;z-index:10;overflow:hidden;display:flex;flex-direction:column}.inline-cmt-header{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid #333;color:#5cb87a;font-size:12px;font-weight:700}.inline-cmt-header button{background:none;border:0;color:#fff;font-size:16px;cursor:pointer}.inline-cmt-list{flex:1;overflow-y:auto;padding:6px 10px;max-height:180px}.inline-cmt-item{background:#222;border-radius:8px;padding:6px 8px;margin:4px 0;color:#ccc;font-size:11px;line-height:1.3}.inline-cmt-time{font-size:9px;color:#777;margin-right:6px}.inline-cmt-input{display:flex;gap:6px;padding:8px 10px;border-top:1px solid #333}.inline-cmt-input input{flex:1;background:#222;border:1px solid #444;color:#eee;border-radius:16px;padding:7px 12px;font-size:11px}.inline-cmt-input button{background:#2d8659;border:0;color:#fff;border-radius:16px;padding:7px 12px;font-size:11px;cursor:pointer}.wc2026-section{margin:6px 4px;background:linear-gradient(135deg,#0d1117,#1a1a3a);border:1px solid #1a3a5a;border-radius:10px;overflow:hidden}.wc-header{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;background:linear-gradient(90deg,#0b2e4a,#1a3a5a)}.wc-header h2{font-size:15px;color:#fff;margin:0}.wc-live-badge{font-size:10px;color:#e74c3c;font-weight:700;animation:wc-pulse 1.5s infinite}@keyframes wc-pulse{0%,100%{opacity:1}50%{opacity:.4}}.wc-tabs{display:flex;gap:4px;padding:8px 10px;overflow-x:auto;scrollbar-width:none}.wc-tabs::-webkit-scrollbar{display:none}.wc-tab{padding:5px 10px;background:#1a2a3a;border:1px solid #2a3a4a;border-radius:12px;color:#8ab4d8;font-size:10px;cursor:pointer;white-space:nowrap;flex-shrink:0}.wc-tab.active{background:#0b6bcb;border-color:#0b6bcb;color:#fff;font-weight:700}.wc-content{padding:8px 10px;max-height:500px;overflow-y:auto}.wc-news-grid{display:flex;flex-direction:column;gap:8px}.wc-news-item{display:flex;gap:8px;padding:8px;background:#1a2030;border-radius:8px;cursor:pointer}.wc-news-item:active{opacity:.8}.wc-news-img{flex:0 0 70px;aspect-ratio:16/9;border-radius:6px;overflow:hidden;background:#222}.wc-news-img img{width:100%;height:100%;object-fit:cover}.wc-news-text{flex:1;min-width:0}.wc-news-title{font-size:11px;font-weight:700;color:#eee;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.wc-news-via{font-size:9px;color:#6a9fca;margin-top:2px}.ls-section{margin:6px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;overflow:hidden}.ls-header{padding:7px 10px;display:flex;align-items:center;justify-content:space-between}.ls-header h3{color:#f0c040;font-size:13px;font-weight:800}.ls-tabs{display:flex;gap:4px;padding:0 10px 8px;overflow-x:auto;scrollbar-width:none}.ls-tabs::-webkit-scrollbar{display:none}.ls-tab{padding:4px 10px;background:#222;border:1px solid #333;border-radius:12px;color:#999;font-size:10px;white-space:nowrap;cursor:pointer;flex-shrink:0}.ls-tab.active{background:#2d8659;border-color:#2d8659;color:#fff;font-weight:700}.ls-content{max-height:420px;overflow-y:auto;padding:0 6px 8px;font-size:12px;color:#ddd}.ls-content ul{list-style:none;padding:0;margin:0}.ls-content .title-content{display:flex;gap:6px;align-items:center;background:#222;border-radius:4px;margin:4px 0;padding:5px 8px}.ls-content .title-content img{width:18px;height:18px}.ls-content .title-content strong{font-size:11px;color:#ccc}.ls-content .match-detail{padding:6px;border-bottom:1px solid #262626;cursor:pointer}.ls-content .match-detail:hover{background:#1a2a1f}.ls-content .match{display:flex;flex-wrap:wrap;align-items:center;gap:4px}.ls-content .datetime{width:100%;font-size:9px;color:#888}.ls-content .teams{display:flex;width:100%;align-items:center;gap:4px}.ls-content .team{flex:1;display:flex;align-items:center;gap:4px;min-width:0;text-decoration:none}.ls-content .team .name{font-size:11px;color:#ddd;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ls-content .team .logo img{width:18px;height:18px}.ls-content .home-team{justify-content:flex-end;text-align:right}.ls-content .status{flex:0 0 54px;text-align:center}.ls-content .status a{color:#fff;text-decoration:none;font-weight:800;font-size:12px}.ls-content .status .label{font-size:8px;color:#888;display:block}.ls-content .status .label.live{color:#e74c3c}.ls-content .info,.ls-content .btns{display:none}.ls-content table{width:100%;border-collapse:collapse;font-size:11px;color:#ccc}.ls-content table th{background:#222;color:#999;padding:5px 4px;font-size:10px;border-bottom:1px solid #333}.ls-content table td{padding:4px 3px;border-bottom:1px solid #1a1a1a}.ls-content table .team-name{display:flex;align-items:center;gap:4px}.ls-content table .team-name img{width:16px;height:16px}.ls-content table .pts{font-weight:800;color:#f0c040}.match-overlay{position:fixed;inset:0;background:#111;z-index:9999;display:none;flex-direction:column;overflow:auto}.match-overlay.active{display:flex}.mo-header{padding:10px;background:#1a1a1a;display:flex;justify-content:space-between;align-items:center;position:sticky;top:0;z-index:1}.mo-header h3{font-size:13px;color:#eee}.mo-close{background:none;border:0;color:#fff;font-size:22px;cursor:pointer}.mo-tabs{display:flex;gap:4px;padding:8px 10px;background:#1a1a1a;overflow-x:auto}.mo-tab{padding:5px 12px;background:#222;border:1px solid #333;border-radius:10px;color:#999;font-size:10px;cursor:pointer;white-space:nowrap}.mo-tab.active{background:#2d8659;color:#fff}.mo-body{padding:8px;overflow-x:auto;font-size:12px;color:#ddd}.mo-body ul{list-style:none;padding:0;margin:0}.mo-body li{padding:5px 0;border-bottom:1px solid #222}.featured-match{margin:6px 4px;background:linear-gradient(135deg,#1a2a1f,#0d1117);border:1px solid #2d8659;border-radius:10px;padding:12px;cursor:pointer}.fm-league{text-align:center;color:#5cb87a;font-size:9px;font-weight:700;text-transform:uppercase}.fm-teams{display:flex;align-items:center;justify-content:center;gap:10px;margin-top:6px}.fm-team{flex:1;display:flex;flex-direction:column;align-items:center;gap:4px}.fm-team img{width:32px;height:32px;object-fit:contain}.fm-team span{font-size:10px;color:#ccc;text-align:center}.fm-score{font-size:22px;font-weight:900;min-width:60px;text-align:center;color:#fff}.fm-status{text-align:center;margin-top:6px;font-size:9px;color:#e74c3c;font-weight:700}.fm-status.upcoming{color:#f0c040}.ai-compose{margin:6px 4px;background:#141414;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.ai-compose-title{font-size:13px;font-weight:800;color:#5cb87a;margin-bottom:8px}.ai-compose-row{display:flex;gap:6px;margin-top:6px}.ai-compose input{flex:1;background:#222;border:1px solid #333;color:#eee;border-radius:18px;padding:9px 12px;font-size:12px;min-width:0}.ai-compose button{background:#2d8659;border:0;color:#fff;border-radius:18px;padding:9px 12px;font-size:11px;font-weight:700;cursor:pointer;white-space:nowrap}.ai-compose button.secondary{background:#333}.hot-topic-row{display:flex;gap:6px;overflow-x:auto;padding:4px 0;scrollbar-width:none}.hot-topic-row::-webkit-scrollbar{display:none}.hot-chip{flex:0 0 auto;background:#222;border:1px solid #333;color:#ddd;border-radius:16px;padding:5px 10px;font-size:11px;cursor:pointer;white-space:nowrap}.hot-chip:active{transform:scale(.96)}.hashtag-sources{margin:8px 4px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.hashtag-sources h3{font-size:13px;color:#5cb87a;margin-bottom:8px}.hashtag-src-item{display:flex;gap:8px;padding:8px;background:#202020;border-radius:8px;margin:6px 0;cursor:pointer}.hashtag-src-item:active{opacity:.8}.hashtag-src-img{flex:0 0 80px;aspect-ratio:16/9;background:#333;border-radius:6px;overflow:hidden}.hashtag-src-img img{width:100%;height:100%;object-fit:cover}.hashtag-src-text{flex:1;min-width:0}.hashtag-src-title{font-size:12px;font-weight:700;color:#eee;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.hashtag-src-via{font-size:10px;color:#888;margin-top:2px}.hashtag-rewrite-btn{width:100%;margin-top:8px;background:#2d8659;border:0;color:#fff;padding:9px;border-radius:10px;font-size:12px;font-weight:700;cursor:pointer}.hashtag-load-more{width:100%;margin-top:8px;background:#222;border:1px solid #333;color:#ccc;padding:9px;border-radius:10px;font-size:12px;cursor:pointer}.hashtag-loading{display:flex;align-items:center;gap:8px;padding:12px;color:#888;font-size:12px}.hashtag-spinner{width:16px;height:16px;border:2px solid #333;border-top-color:#5cb87a;border-radius:50%;animation:ht-spin .8s linear infinite}@keyframes ht-spin{to{transform:rotate(360deg)}}.wall-item{flex:0 0 260px;background:#141414;border:1px solid #2b2b2b;border-radius:10px;padding:8px}.wall-item-new{animation:wall-flash 1.8s ease-out}@keyframes wall-flash{0%{border-color:#f0c040;box-shadow:0 0 18px rgba(240,192,64,.35)}30%{border-color:#f0c040;box-shadow:0 0 12px rgba(240,192,64,.2)}100%{border-color:#2b2b2b;box-shadow:none}}.wall-thumb{width:100%;aspect-ratio:16/9;border-radius:8px;background:#222;overflow:hidden;margin-bottom:6px;position:relative}.wall-thumb img{width:100%;height:100%;object-fit:cover}.wall-video-badge{position:absolute;top:4px;right:4px;background:rgba(45,134,89,.9);color:#fff;font-size:10px;padding:2px 6px;border-radius:6px;font-weight:700}.wall-title{font-size:12px;color:#5cb87a;font-weight:800;line-height:1.3;margin-bottom:4px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.wall-text{font-size:11px;color:#bbb;line-height:1.4;white-space:pre-wrap;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}.wall-actions{display:flex;gap:6px;margin-top:8px}.wall-actions button{flex:1;border:1px solid #333;background:#222;color:#ddd;border-radius:14px;padding:6px 8px;font-size:10px;cursor:pointer}.wall-actions button.primary{background:#2d8659;border-color:#2d8659;color:#fff}#progress-toast{position:fixed;bottom:70px;left:50%;transform:translateX(-50%);background:#2d8659;color:#fff;padding:10px 20px;border-radius:20px;font-size:12px;z-index:99998;box-shadow:0 4px 12px rgba(0,0,0,.4);display:none;white-space:nowrap}.storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 4px}</style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  </head>
15
  <body>
16
+ <div class="header"><h1>📰 VNEWS</h1><p>Tin tức · Bóng đá LIVE · Video · AI · World Cup 2026</p></div>
17
  <div class="cats" id="cat-bar"></div>
 
18
  <div id="view-home" class="view active"><div class="loading">Đang tải...</div></div>
19
  <div id="view-cat" class="view"></div>
20
  <div id="view-video" class="view"></div>
 
30
  var _cats=[],_hlLeagueData={},_currentArticle=null;window._currentEventId='';
31
  function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]))}
32
  function showView(id){document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.getElementById(id)?.classList.add('active')}
33
+ function switchCat(id){document.querySelectorAll('.cat').forEach(c=>c.classList.remove('active'));document.querySelector(`[data-cat="${id}"]`)?.classList.add('active');document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.querySelectorAll('video').forEach(v=>{v.pause();if(v._hls){v._hls.destroy();v._hls=null}});document.querySelectorAll('iframe[data-yt-src]').forEach(f=>{f.src=''});if(id==='home')document.getElementById('view-home').classList.add('active');else if(id==='news-all'){document.getElementById('view-cat').classList.add('active');loadNewsTab()}else{document.getElementById('view-cat').classList.add('active');loadCat(id)}}
34
  function toast(msg){let t=document.getElementById('progress-toast');if(t){t.textContent=msg;t.style.display='block';setTimeout(()=>{t.style.display='none'},3500)}}
35
+ function doShare(title,url,img){const shareUrl=SPACE+'/s?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title)+'&img='+encodeURIComponent(img||'');if(navigator.share)navigator.share({title,url:shareUrl}).catch(()=>{});else navigator.clipboard.writeText(shareUrl).then(()=>alert('Đã sao chép!')).catch(()=>{})}
36
+ async function init(){_cats=await fetch('/api/categories').then(r=>r.json()).catch(()=>[]);let bar='<div class="cat active" data-cat="home">🏠</div><div class="cat" data-cat="news-all">📰 Tin tức</div>';_cats.forEach(c=>{bar+=`<div class="cat" data-cat="${c.id}">${c.name}</div>`});document.getElementById('cat-bar').innerHTML=bar;document.querySelectorAll('.cat').forEach(t=>{t.onclick=()=>switchCat(t.dataset.cat)});}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  var SPACE=location.origin;
38
  </script>
39
+ <script src="/static/app_v2.js"></script>
 
40
  <script src="/static/yt_live.js"></script>
41
+ <script src="/static/hot_multi.js"></script>
 
42
  <script src="/static/wc2026_v2.js"></script>
43
  <script src="/static/live_mode.js"></script>
44
  <script src="/static/match_detail_v6.js"></script>
45
+ <script>init();</script>
46
  </body>
47
  </html>
static/live_mode.js CHANGED
@@ -23,29 +23,7 @@
23
  .hashtag-src-img img{width:100%!important;height:100%!important;object-fit:cover!important}
24
  .hashtag-src-text{flex:1!important;min-width:0!important}
25
  .hashtag-src-title{font-size:12px!important;font-weight:700!important;color:#eee!important;display:-webkit-box!important;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden!important}
26
- .hashtag-src-via{font-size:10px!important;color:#888!important;margin-top:2px!important}
27
- #ls-content .ranking-table .head,#ls-content .leaderboard .head{width:100%!important}
28
- #ls-content .ranking-table .leaderboard-item,#ls-content .leaderboard .leaderboard-item{display:flex!important;width:100%!important;align-items:center!important;gap:4px!important;border-bottom:1px solid #1a1a1a!important;padding:4px 2px!important;background:transparent!important}
29
- #ls-content .ranking-table .leaderboard-item>div.team,#ls-content .ranking-table .leaderboard-item>.team,#ls-content .leaderboard .leaderboard-item .team{flex:1!important;min-width:0!important;display:flex!important;align-items:center!important;gap:4px!important}
30
- #ls-content .leaderboard-item .team a{display:inline-flex!important;align-items:center!important;gap:4px!important;font-size:11px!important;color:#ccc!important;text-decoration:none!important;overflow:hidden!important}
31
- #ls-content .leaderboard-item .team a img{width:16px!important;height:16px!important;object-fit:contain!important}
32
- #ls-content .leaderboard-item .team a p{font-size:11px!important;color:#ccc!important;margin:0!important;white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important}
33
- #ls-content .leaderboard-item .copy{display:flex!important;align-items:center!important;gap:2px!important;white-space:nowrap!important}
34
- #ls-content .leaderboard-item .copy p{display:inline-block!important;min-width:20px!important;text-align:center!important;font-size:11px!important;color:#ccc!important;margin:0!important}
35
- #ls-content .leaderboard-item .copy p strong{font-weight:800!important;color:#f0c040!important;min-width:20px!important;text-align:center!important}
36
- #ls-content .leaderboard-item .copy p.form span{width:14px!important;height:14px!important;line-height:14px!important;font-size:9px!important;border-radius:2px!important;color:#fff!important;margin:0 1px!important}
37
- #ls-content .leaderboard-item .copy p.form span.bg-green{background:#2d8659!important}
38
- #ls-content .leaderboard-item .copy p.form span.bg-gray-5{background:#555!important;color:#ccc!important}
39
- #ls-content .leaderboard-item .copy p.form span.bg-red{background:#c0392b!important}
40
- #ls-content .leaderboard-item>div[class*="w-["]{display:none!important}
41
- #ls-content .leaderboard-item .w-\[2px\]{display:none!important}
42
- /* FPT PLAY / HIGHLIGHT video overflow fix - same containment as short-AI wall */
43
- .tiktok-slide{overflow:hidden!important}
44
- .tiktok-slide video,.tiktok-slide iframe{max-width:100%!important;max-height:100%!important;object-fit:contain!important}
45
- .yt-thumb-wrap{overflow:hidden!important}
46
- .yt-thumb-wrap iframe{max-width:100%!important;max-height:100%!important}
47
- .wall-item{overflow:hidden!important}
48
- .wall-thumb img,.wall-thumb video{max-width:100%!important;max-height:100%!important;object-fit:cover!important}`;
49
  document.head.appendChild(style);
50
 
51
  // Load rewrite fix
 
23
  .hashtag-src-img img{width:100%!important;height:100%!important;object-fit:cover!important}
24
  .hashtag-src-text{flex:1!important;min-width:0!important}
25
  .hashtag-src-title{font-size:12px!important;font-weight:700!important;color:#eee!important;display:-webkit-box!important;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden!important}
26
+ .hashtag-src-via{font-size:10px!important;color:#888!important;margin-top:2px!important}`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  document.head.appendChild(style);
28
 
29
  // Load rewrite fix
static/rewrite_fix.js ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Fix rewriteArticle - call correct endpoint
2
+ // This file patches the rewriteArticle function to use /api/rewrite_slide instead of /api/rewrite_share
3
+
4
+ (function(){
5
+ // Override rewriteArticle to call /api/rewrite_slide
6
+ const origRewrite = window.rewriteArticle;
7
+ window.rewriteArticle = async function(){
8
+ const url = _currentArticle?.url;
9
+ if(!url) return;
10
+ toast('⏳ Đang tạo slide tóm tắt...');
11
+ try {
12
+ const r = await fetch('/api/rewrite_slide', {
13
+ method: 'POST',
14
+ headers: {'Content-Type': 'application/json'},
15
+ body: JSON.stringify({url, context: document.querySelector('.article-view')?.innerText?.slice(0,14000) || ''})
16
+ });
17
+ const j = await r.json();
18
+ if (!r.ok || j.error) throw new Error(j.error);
19
+ toast('✅ Đã đăng Tường AI!');
20
+ if (j.post) prependWallPost(j.post);
21
+ // Navigate to the new post on Tường AI (home). Slide overlay (if any) stays on top.
22
+ if (j.post && typeof goToWallPost === 'function') goToWallPost(j.post.id);
23
+ // Show slides preview
24
+ if (j.slides && j.slides.length) {
25
+ showSlidePreview(j.slides, j.post?.title || '');
26
+ }
27
+ } catch(e) {
28
+ // Fallback: try /api/rewrite_share (old endpoint from ai_ext)
29
+ try {
30
+ const r2 = await fetch('/api/rewrite_share', {
31
+ method: 'POST',
32
+ headers: {'Content-Type': 'application/json'},
33
+ body: JSON.stringify({url, context: document.querySelector('.article-view')?.innerText?.slice(0,14000) || ''})
34
+ });
35
+ const j2 = await r2.json();
36
+ if (r2.ok && !j2.error) {
37
+ toast('✅ Đã đăng Tường AI!');
38
+ if (j2.post) prependWallPost(j2.post);
39
+ if (j2.post && typeof goToWallPost === 'function') goToWallPost(j2.post.id);
40
+ return;
41
+ }
42
+ } catch(e2) {}
43
+ toast('❌ ' + e.message);
44
+ }
45
+ };
46
+
47
+ // Show slides as fullscreen overlay
48
+ window.showSlidePreview = function(slides, title) {
49
+ if (!slides || !slides.length) return;
50
+ const overlay = document.createElement('div');
51
+ overlay.id = 'slide-preview';
52
+ overlay.style.cssText = 'position:fixed;inset:0;background:#000;z-index:99999;display:flex;flex-direction:column;overflow:hidden';
53
+
54
+ let currentSlide = 0;
55
+ function renderSlide(idx) {
56
+ const s = slides[idx];
57
+ overlay.innerHTML = `
58
+ <div style="position:absolute;top:10px;left:10px;right:10px;display:flex;justify-content:space-between;align-items:center;z-index:2">
59
+ <button onclick="document.getElementById('slide-preview').remove()" style="background:rgba(0,0,0,.6);border:0;color:#fff;padding:8px 14px;border-radius:20px;font-size:12px;cursor:pointer">✕ Đóng</button>
60
+ <span style="color:#fff;font-size:11px;background:rgba(0,0,0,.6);padding:4px 10px;border-radius:10px">${idx+1}/${slides.length}</span>
61
+ </div>
62
+ <div style="flex:1;display:flex;align-items:center;justify-content:center;padding:20px">
63
+ ${s.image ? `<img src="${esc(s.image)}" style="max-width:100%;max-height:60vh;border-radius:10px;object-fit:contain" onerror="this.style.display='none'">` : ''}
64
+ </div>
65
+ <div style="padding:16px 20px;background:linear-gradient(transparent,rgba(0,0,0,.9));min-height:100px">
66
+ <p style="color:#fff;font-size:14px;line-height:1.6">${esc(s.text)}</p>
67
+ </div>
68
+ <div style="display:flex;gap:10px;padding:10px 20px 20px;justify-content:center">
69
+ <button onclick="prevSlide()" style="background:#333;border:0;color:#fff;padding:10px 20px;border-radius:20px;font-size:12px;cursor:pointer" ${idx===0?'disabled style="opacity:.3"':''}>← Trước</button>
70
+ <button onclick="nextSlide()" style="background:#2d8659;border:0;color:#fff;padding:10px 20px;border-radius:20px;font-size:12px;cursor:pointer" ${idx===slides.length-1?'disabled style="opacity:.3"':''}>Tiếp →</button>
71
+ </div>
72
+ `;
73
+ }
74
+
75
+ window.nextSlide = function() { if (currentSlide < slides.length - 1) { currentSlide++; renderSlide(currentSlide); } };
76
+ window.prevSlide = function() { if (currentSlide > 0) { currentSlide--; renderSlide(currentSlide); } };
77
+
78
+ renderSlide(0);
79
+ document.body.appendChild(overlay);
80
+
81
+ // Swipe support
82
+ let startX = 0;
83
+ overlay.addEventListener('touchstart', e => { startX = e.touches[0].clientX; });
84
+ overlay.addEventListener('touchend', e => {
85
+ const diff = e.changedTouches[0].clientX - startX;
86
+ if (diff < -50) nextSlide();
87
+ else if (diff > 50) prevSlide();
88
+ });
89
+ };
90
+ })();
static/rewrite_fix_v2.js DELETED
@@ -1,2 +0,0 @@
1
- // No-op - all functionality built into app_v2.js
2
- (function(){})();