diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 40f60e1de89e0f904c11d302058de8c039f587a9..0000000000000000000000000000000000000000 --- a/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -__pycache__/ -*.pyc -data/ -.data -.huggingface/ -.restart_trigger diff --git a/.huggingface/rebuild b/.huggingface/rebuild new file mode 100644 index 0000000000000000000000000000000000000000..048f645894a0ea68f3604d333a2d43801eaf8be1 --- /dev/null +++ b/.huggingface/rebuild @@ -0,0 +1 @@ +rebuild 1782693789.5665495 - force rebuild after voice+thumbnail fixes \ No newline at end of file diff --git a/.rebuild b/.rebuild new file mode 100644 index 0000000000000000000000000000000000000000..dfbecc973e3f3ce5f2e4b67ace3aefe14422a973 --- /dev/null +++ b/.rebuild @@ -0,0 +1 @@ +rebuild 20260630044000 \ No newline at end of file diff --git a/.restart_trigger b/.restart_trigger new file mode 100644 index 0000000000000000000000000000000000000000..048f645894a0ea68f3604d333a2d43801eaf8be1 --- /dev/null +++ b/.restart_trigger @@ -0,0 +1 @@ +rebuild 1782693789.5665495 - force rebuild after voice+thumbnail fixes \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index bed2a391f57aae4c106228b98824a5a07c71913b..065430a415d73f8c8cf5cdae84396bd20b5e22d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,16 +1,71 @@ -# FPT Play Stream Selector Update +# VNEWS v6.5 - Resilient Shorts Auto-Updater -Added FPT Play channel with stream selector UI similar to VTV6: +## Changes + +### Critical Fix: Shorts timeout and homepage load stability +**Root cause**: YouTube shorts fetching in `main.py` using `scrape_shorts()` and `_yt_channel_shorts_requests()` could hang indefinitely when YouTube blocks requests or yt-dlp times out, causing: +- Homepage `/api/shorts` endpoint to time out (30s limit) +- Space to appear unresponsive on first load +- No fallback when sources fail + +**Fix applied**: +1. **shorts_updater.py** (NEW) — Resilient background updater: + - Hard timeout (25s) per channel using subprocess isolation + - Stale-while-revalidate pattern: returns cached data immediately, updates in background + - Automatic fallback to hardcoded short URLs when all sources fail + - Persistent storage in `/data/shorts_cache.json` for cache across restarts + - Background scheduler runs every 10 minutes automatically + - No blocking on first homepage load + +2. **_run.py** — Integrated resilient shorts endpoint: + - Overrides `/api/shorts` with non-blocking version + - Returns cached/fallback data in <100ms guaranteed + - Triggers background update if cache is stale or empty + - Never hangs - always returns valid JSON response + +3. **FALLBACK_SHORTS** — 6 hardcoded viral shorts as emergency fallback: + - baodantri7941 (Dân trí) headlines + - baosuckhoedoisongboyte (Sức khỏe & đời sống) stories + - vtvnambo (VTV Nam Bộ) news + +### Benefits +- Homepage loads in <2 seconds always +- Shorts data auto-updates every 10 minutes +- Never times out - graceful degradation to fallback +- Persistent cache survives Space restarts +- Uses bucket `bep40/VNEWS-storage` for cache storage + +### Channels monitored +- baodantri7941 (Dân trí) +- baosuckhoedoisongboyte (Sức khỏe & đời sống) +- vtvnambo (VTV Nam Bộ) -- New tab "FPT" (orange themed) in the channel tabs -- Stream selector with 4 sources: - 1. 🌐 Web FPT Play (iframe) - 2. 📡 HLS Proxy (via /api/proxy/m3u8) - 3. 🔗 HLS Direct - 4. 📺 HD1.xemtv.net (iframe from LINK 1) -- Backend vtv_api.py now returns stream_selectors for fpt-the-thao channel -- Frontend handles stream switching automatically when FPT tab is active +--- + +# VNEWS v5.1 - Rewrite Fix ## Changes -- `static/vtv_init.js`: Added FPT tab + stream selector UI logic -- `vtv_api.py`: Added FPT Play endpoint responses with stream_selectors data + +### Critical Fix: Rewrite button not creating posts on Tường AI +**Root cause**: `_run.py` imports from `app_v2_entry.py`, but the `/api/rewrite_share` endpoint was only defined in `ai_runtime_patch_fast.py` (loaded through `app_entry.py` which is NOT used). The frontend called a non-existent endpoint → 404 → silent failure. + +**Fix applied**: +1. **app_v2_entry.py** — Added 3 new endpoints: + - `POST /api/rewrite_slide` — Fast extractive summary (no AI needed), creates slides from article key points + images, saves to wall + - `POST /api/rewrite_share` — AI-powered rewrite with extractive fallback, saves to wall + - `POST /api/url_wall` — URL submission endpoint (alias for rewrite_share) + - All endpoints use the same `_load_wall_posts()` / `_save_wall_posts()` and `WALL_FILE` path as the existing `/api/wall` endpoint + +2. **static/index_v2.html** — Added `` to load the rewrite fix + +3. **static/rewrite_fix_v2.js** — New file that overrides `rewriteArticle()` to: + - Call `/api/rewrite_slide` first (fast, no AI needed) + - Fallback to `/api/rewrite_share` if slide fails + - Show slide preview overlay after successful post + - Use `prependWallPost()` to add the new post to Tường AI + +### Previous changes (v5) +- Rewrote match_detail_v2.py with correct event parsing +- 2-tab layout for match detail (stats + timeline) +- Fixed _run.py import +- Dockerfile cache busting diff --git a/Dockerfile b/Dockerfile index fd799e0b9eca048c628530076b0a14544944a46b..e6aa28a553b6a673b4601737bb1d53e3248d0970 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,47 +2,18 @@ FROM python:3.12-slim WORKDIR /app -RUN echo "[BUILD] step1: apt-get update+install ffmpeg + Vietnamese fonts" && \ - apt-get update && apt-get install -y --no-install-recommends \ - ffmpeg \ - fonts-dejavu-core \ - fonts-noto \ - fonts-noto-cjk \ - fonts-noto-color-emoji \ - fonts-liberation \ - fonts-freefont-ttf \ - libfreetype6 \ - && rm -rf /var/lib/apt/lists/* && \ - echo "[BUILD] step1 done" - -RUN echo "[BUILD] step2: pip base pkgs (bs4/lxml)" && \ - pip install --no-cache-dir "beautifulsoup4>=4.12" lxml && \ - echo "[BUILD] step2 done" - -RUN echo "[BUILD] step3: pip main pkgs" && \ - pip install --no-cache-dir fastapi uvicorn requests beautifulsoup4 jinja2 yt-dlp huggingface_hub gTTS pillow edge-tts python-dateutil httpx pycryptodome && \ - echo "[BUILD] step3 done" +RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg fonts-dejavu-core && rm -rf /var/lib/apt/lists/* +RUN pip install --no-cache-dir "beautifulsoup4>=4.12" lxml +RUN pip install --no-cache-dir fastapi uvicorn requests beautifulsoup4 jinja2 yt-dlp huggingface_hub gTTS pillow edge-tts python-dateutil httpx COPY requirements.txt . -RUN echo "[BUILD] step4: pip requirements.txt" && \ - pip install --no-cache-dir -r requirements.txt || true && \ - echo "[BUILD] step4 done" +RUN pip install --no-cache-dir -r requirements.txt || true COPY . . EXPOSE 7860 -RUN echo "[BUILD] step5: setup Vietnamese font symlink" && \ - mkdir -p /usr/share/fonts/truetype/vn && \ - # Prefer Noto Sans for Vietnamese - it has full diacritic support - if [ -f /usr/share/fonts/truetype/noto/NotoSans-Regular.ttf ]; then \ - ln -sf /usr/share/fonts/truetype/noto/NotoSans-Regular.ttf /usr/share/fonts/truetype/vn/VNFont.ttf; \ - elif [ -f /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf ]; then \ - ln -sf /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf /usr/share/fonts/truetype/vn/VNFont.ttf; \ - ln -sf /usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf /usr/share/fonts/truetype/vn/VNFont-Bold.ttf; \ - fi; \ - fc-cache -f -v || true; \ - date > /app/.build_done && \ - echo "[BUILD] step5 done" - -CMD ["uvicorn", "_run:app", "--host", "0.0.0.0", "--port", "7860"] -# v3.0-vn-font-fix-short-video-2026-07-19 +# v6 - 2026-06-28 18:45 - voice selector fix + cache bust +CMD ["uvicorn", "_run:app", "--host", "0.0.0.0", "--port", "7860", "--reload"] +# build 1782698397 +# build 1782698798 +# build 1782699174 diff --git a/README.md b/README.md index f65ec063b0184f66ec5c41d94307c4f38f4c0a38..dc357a7ef1b414efed6580b6ca6d3ed5e257e4fe 100644 --- a/README.md +++ b/README.md @@ -9,50 +9,17 @@ tags: - ml-intern --- -# VNEWS - Tin Tức Việt Nam - -**v18 - FIXED VTV2/VTV3/VTV6/VTV9 stream hanging** - -## 🔧 Changes in v18 (2026-07-06) -- **VTV2, VTV3, VTV6, VTV9**: Skip expired ssaimh CDN token → immediately fall through to sv2.xemtivitop.com -- **15+ extraction patterns** for m3u8 URL (up from 5), including: file:, src=, source:, player.src(), hls.loadSource(), href=, ``, url:, window.location, iframe follow (3 levels deep), base64 decode -- **Backup CDN** `tv.mediacdn.vn` for VTV2/VTV3/VTV6/VTV9 -- **Fast timeout** 5s for CDN, 12s for PHP endpoints (was 15s each = 60s+ total) -- **sv2.xemtivitop.com** re-prioritized to check BEFORE xemtv.us -- **Iframe chain following**: if a PHP page returns an iframe → follow it up to 3 levels to find the m3u8 - -## Features: -- 📰 News from VnExpress (10 categories) + GenK AI -- ⚽ Livescore from bongda.com.vn (live, today, upcoming, results, standings) -- 🎬 Football highlights from xemlaibongda.top (8 leagues) -- 📺 VTV live channels (VTV1→VTV10, VTV Prime) - - Priority: ssaimh CDN → sv2.xemtivitop.com → xemtv.us → xemtivitop blogspot → FPTPlay → VTVGo → mediacdn → xemtv.net -- 🏆 World Cup 2026 (news, fixtures, standings, stats, highlights) -- 🤖 AI article writing + TTS (multilingual, emotion-aware) -- 🔍 Topic search (8 news sources) -- 🎤 TTS: voice selector + emotion selector + speed control - -## 🎬 Short AI — Video từ link (scrap YouTube / TikTok / tin tức) - -Short creator có chế độ **"🔗 Video từ link"**: dán link video YouTube / TikTok / -VnExpress / Dân trí / Znews / 24h... → bấm "Lấy video" để xem trước → tạo short -chạy video + ảnh đã chọn bù phần còn thiếu nếu video ngắn hơn giọng đọc. - -### 🔑 Cài cookies cho YouTube (bỏ chặn "Sign in to confirm you're not a bot") -YouTube đôi khi chặn IP datacenter. Cách khắc phục bằng cookies: - -1. Cài extension trình duyệt **"Get cookies.txt LOCALLY"** (Chrome/Edge) hoặc - **"cookies.txt"** (Firefox). -2. Mở `https://www.youtube.com` (đã đăng nhập) → bấm extension → **Export** → ra file `cookies.txt` (định dạng Netscape). -3. Đưa cookies vào Space bằng **một trong hai cách**: - - **Cách A (khuyến nghị):** Vào Settings của Space - `huggingface.co/spaces/bep40/VNEWS/settings` → **Variables and secrets** → - tạo secret tên **`YT_COOKIES`**, giá trị = toàn bộ nội dung file `cookies.txt`. - - **Cách B:** đặt file `cookies.txt` vào thư mục gốc repo `VNEWS/` và commit - (chú ý: cookies sẽ công khai nếu repo public — ưu tiên Cách A). -4. Rebuild Space (mỗi lần đổi secret phải **Restart** Space). - -Backend tự đọc `YT_COOKIES` (secret) hoặc `/app/cookies.txt`, ghi thành file tạm -và truyền cho yt-dlp qua `cookiefile`. Không cần sửa code. - -> 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. \ No newline at end of file +# bep40/vnews + + + + + + + + + + + + + diff --git a/RESTART_TRIGGER.md b/RESTART_TRIGGER.md deleted file mode 100644 index e6c79c75d2068b3dc20f52912afac9b21944b2d0..0000000000000000000000000000000000000000 --- a/RESTART_TRIGGER.md +++ /dev/null @@ -1,7 +0,0 @@ -trigger rebuild v20260827fptwall - -- FPT wall cards now use .wall-thumb 100% width/height (16:9), identical to Short AI cards -- FPT player opens a scrollable vertical feed interleaving FPT Play + Short AI videos, newest-first -- 16:9 <-> 9:16 ratio toggle (🖥️/📺) works on football highlight slides and Tường AI slide player -- Cache-busting: app_v2.js?v=20260827fptwall -- FORCE REBUILD: this commit retriggers the Space container with the latest static/app_v2.js \ No newline at end of file diff --git a/_run.py b/_run.py index de72380c3006dba490ec49c1fe421c87723a0490..4a7a26bd2553b700d918ace5f77e2a3e369e0be2 100644 --- a/_run.py +++ b/_run.py @@ -1 +1 @@ -from app_v2_entry import app # v5-stable inline bongda proxy \ No newline at end of file +from app_v2_entry import app # v5-stable inline bongda proxy diff --git a/ai_ext.py b/ai_ext.py index ab7540db0765711cf34947d481888084e0f87c65..cf4b1d0ff3215baa8ed3f05887a252c47d56bc90 100644 --- a/ai_ext.py +++ b/ai_ext.py @@ -96,20 +96,27 @@ def _domain(url: str) -> str: async def qwen_generate(prompt: str, image_url: str = None, max_tokens: int = 1200) -> str: - """Generate text using Llama/Qwen models via Hugging Face Inference API. + """Generate text using Qwen models via Hugging Face Inference API. - Prioritizes Llama-3.3-70B for better creative/opinion writing. + This function provides a resilient implementation that: + 1. First tries the SDK-based inference client if available + 2. Falls back to REST API calls to HF router endpoint + 3. Returns a fallback summary if all else fails """ token = _hf_token() errors = [] - # Try HF router API with multiple models - Llama FIRST for opinion writing + # Try HF router API with multiple models if token: models = [ os.getenv("QWEN_VL_MODEL", ""), - "meta-llama/Llama-3.3-70B-Instruct", # FIRST - best for opinion/analysis "Qwen/Qwen2.5-VL-7B-Instruct", + "Qwen/Qwen2.5-VL-3B-Instruct", + "Qwen/Qwen2.5-7B-Instruct", + "Qwen/Qwen2.5-3B-Instruct", + "Qwen/Qwen2.5-1.5B-Instruct", "Qwen/Qwen2.5-72B-Instruct", + "meta-llama/Llama-3.3-70B-Instruct", ] # Deduplicate while preserving order seen = set() @@ -131,12 +138,12 @@ async def qwen_generate(prompt: str, image_url: str = None, max_tokens: int = 12 payload = { "model": model, "messages": [ - {"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."}, + {"role": "system", "content": "Bạn là trợ lý AI tiếng Việt. Trả lời tự nhiên, ngắn gọn, chính xác."}, {"role": "user", "content": user_content}, ], - "max_tokens": min(int(max_tokens or 2000), 2500), - "temperature": 0.75, - "top_p": 0.9, + "max_tokens": min(int(max_tokens or 900), 1400), + "temperature": 0.35, + "top_p": 0.85, } r = requests.post( @@ -176,18 +183,20 @@ def _fallback_summary_from_prompt(prompt: str, max_units: int = 6) -> str: text = re.sub(r"https?://\S+", "", text) text = re.sub(r"\s+", " ", text).strip() - # Split into sentences + # Split into sentences - extract ALL valid sentences, not just first few sentences = re.split(r"(?<=[.!?])\s+(?=[A-ZÀ-Ỹ0-9])", text) units = [] for s in sentences: s = _clean_text(s) - if len(s) >= 30: + if len(s) >= 30: # Lower threshold to capture more content units.append(s) if units: + # Take up to max_units valid sentences result_units = units[:max_units] return "\n".join("• " + u for u in result_units) if text: + # Fallback: take chunks if no sentence boundaries found chunks = [] for i in range(0, min(len(text), max_units * 300), 280): chunk = _clean_text(text[i:i+300]) @@ -199,134 +208,367 @@ def _fallback_summary_from_prompt(prompt: str, max_units: int = 6) -> str: return "\n".join("• " + c for c in chunks) return "• Không có đủ nội dung để tóm tắt." -# ===== URL scraping & article processing ===== -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"} -try: - _shorts_base = "/data" if os.path.isdir("/data") else os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") -except Exception: - _shorts_base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") -SHORTS_DIR = os.path.join(_shorts_base, "ai_shorts") -os.makedirs(SHORTS_DIR, exist_ok=True) +HF_TOKEN = _hf_token() +QWEN_VL_MODEL = os.getenv("QWEN_VL_MODEL", "Qwen/Qwen2.5-VL-7B-Instruct") +QWEN_TEXT_MODELS = [m.strip() for m in os.getenv( + "QWEN_TEXT_MODELS", + "Qwen/Qwen2.5-72B-Instruct,meta-llama/Llama-3.3-70B-Instruct,Qwen/Qwen2.5-7B-Instruct" +).split(",") if m.strip()] +_WORKING_MODEL_TEXT = None +_WORKING_MODEL_VL = None +DATA_DIR = "/data" if os.path.isdir("/data") else "/app/data" +SHORTS_DIR = os.path.join(DATA_DIR, "ai_shorts") +HEADERS = { + "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", + "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8" +} +LAST_QWEN_ERROR = "" + + +# ===== MULTILINGUAL VOICES FOR TTS ===== +# Maps voice IDs to edge-tts voice names (only MultilingualNeural voices) +MULTILINGUAL_VOICES = { + # Vietnamese - Native voices + "vi-vn-hoaimyneural": "vi-VN-HoaiMyNeural", + "vi-vn-namminhneural": "vi-VN-NamMinhNeural", + "hoaimy": "vi-VN-HoaiMyNeural", + "namminh": "vi-VN-NamMinhNeural", + "vi_female": "vi-VN-HoaiMyNeural", + "vi_male": "vi-VN-NamMinhNeural", + "nu": "vi-VN-HoaiMyNeural", + "male": "vi-VN-NamMinhNeural", + "female": "vi-VN-HoaiMyNeural", + "mien-nam": "vi-VN-HoaiMyNeural", + # English - Multilingual + "en-us-andrewmultilingualneural": "en-US-AndrewMultilingualNeural", + "en-au-williammultilingualneural": "en-AU-WilliamMultilingualNeural", + "en_andrew": "en-US-AndrewMultilingualNeural", + "andrew": "en-US-AndrewMultilingualNeural", + "en_jenny": "en-US-AndrewMultilingualNeural", + "jenny": "en-US-AndrewMultilingualNeural", + # Portuguese - Thalita Multilingual ONLY + "pt-br-thalitamultilingualneural": "pt-BR-ThalitaMultilingualNeural", + "pt_thalita": "pt-BR-ThalitaMultilingualNeural", + "thalita": "pt-BR-ThalitaMultilingualNeural", + "pt_francisco": "pt-BR-ThalitaMultilingualNeural", + "pt": "pt-BR-ThalitaMultilingualNeural", + # French - Multilingual + "fr-fr-viviennemultilingualneural": "fr-FR-VivienneMultilingualNeural", + "fr-fr-remymultilingualneural": "fr-FR-RemyMultilingualNeural", + "fr_denise": "fr-FR-VivienneMultilingualNeural", + "denise": "fr-FR-VivienneMultilingualNeural", + "fr": "fr-FR-VivienneMultilingualNeural", + # German - Multilingual + "de-de-seraphinamultilingualneural": "de-DE-SeraphinaMultilingualNeural", + "de-de-florianmultilingualneural": "de-DE-FlorianMultilingualNeural", + "de_katja": "de-DE-SeraphinaMultilingualNeural", + "katja": "de-DE-SeraphinaMultilingualNeural", + "de": "de-DE-SeraphinaMultilingualNeural", + # Korean - Hyunsu Multilingual (NOT SunHee) + "ko-kr-hyunsumultilingualneural": "ko-KR-HyunsuMultilingualNeural", + "ko_sunhee": "ko-KR-HyunsuMultilingualNeural", + "sunhee": "ko-KR-HyunsuMultilingualNeural", + "ko": "ko-KR-HyunsuMultilingualNeural", + # Italian - Multilingual + "it-it-giuseppemultilingualneural": "it-IT-GiuseppeMultilingualNeural", + # Spanish (fallback to English multilingual) + "es_ela": "en-US-AndrewMultilingualNeural", + "ela": "en-US-AndrewMultilingualNeural", + "es_carlos": "en-US-AndrewMultilingualNeural", + "es": "en-US-AndrewMultilingualNeural", + # Japanese (fallback to English multilingual) + "ja_nanami": "en-US-AndrewMultilingualNeural", + "nanami": "en-US-AndrewMultilingualNeural", + "ja": "en-US-AndrewMultilingualNeural", + # Chinese (fallback to English multilingual) + "zh_xiaochen": "en-US-AndrewMultilingualNeural", + "xiaochen": "en-US-AndrewMultilingualNeural", + "zh": "en-US-AndrewMultilingualNeural", +} + -import random as _random2 -from datetime import datetime, timezone, timedelta -_VN_TZ = timezone(timedelta(hours=7)) +def _detect_voice_emotion(title, text): + """Detect appropriate voice and emotion based on content for multilingual TTS.""" + content = ((title or "") + " " + (text or "")).lower() + + # World Cup / Football content - use Andrew multilingual + if any(kw in content for kw in ["world cup", "wc 2026", "fifa", "bóng đá", "trận đấu", "bóng bóng", "đội tuyển", "cầu thủ"]): + return ("andrew", "excited") + + # News categories - choose appropriate voice + if any(kw in content for kw in ["kinh tế", "tài chính", "thị trường", "economics", "finance"]): + return ("jenny", "calm") + if any(kw in content for kw in ["thiên tai", "bão", "lũ lụt", "cháy nổ", "tai nạn", "disaster", "accident"]): + return ("thalita", "serious") + if any(kw in content for kw in ["giải trí", "showbiz", "entertainment", "hài hước"]): + return ("ela", "happy") + if any(kw in content for kw in ["công nghệ", "tech", "technology", "ai", "trí tuệ nhân tạo"]): + return ("katja", "excited") + + # Default Vietnamese + return ("hoaimy", "trung_tinh") -def _safe_name(filename: str) -> str: - """Sanitize filename.""" - return re.sub(r"[^a-zA-Z0-9_.-]", "_", filename)[:120] +def _safe_name(s: str) -> str: + """Create safe filename from string.""" + s = re.sub(r"[^\w\-.]", "_", s) + return s[:100] if len(s) > 100 else s -def pollinations_image_url(topic: str) -> str: - """Generate a placeholder image URL via Pollinations.""" +def _download_image(url: str, fallback_title: str, out_path: str) -> bool: + """Download image from URL to path.""" + if not url: + return False try: - return "https://image.pollinations.ai/prompt/" + quote("Vietnamese editorial illustration, " + topic, safe="") + "?width=1024&height=576&nologo=true" + r = requests.get(url, headers=HEADERS, timeout=15) + if r.status_code == 200: + os.makedirs(os.path.dirname(out_path), exist_ok=True) + with open(out_path, "wb") as f: + f.write(r.content) + return True except Exception: - return "" + pass + return False -def _download_image(url: str, fallback_title: str, out_path: str) -> str: - """Download an image from URL or create a placeholder.""" - if url: - try: - r = requests.get(url, headers=HEADERS, timeout=15) - if r.status_code == 200 and len(r.content) > 1200: - os.makedirs(os.path.dirname(out_path), exist_ok=True) - with open(out_path, "wb") as f: - f.write(r.content) - return out_path - except Exception: - pass - # Fallback: create a placeholder image +def pollination_image_url(topic: str) -> str: + """Generate image URL from Pollinations.ai.""" + return f"https://image.pollinations.ai/prompt/{quote(topic)}?width=1024&height=768&nologo=true&model=flux" + + +# Use the same wall file as app_v2_entry.py for consistency +WALL_FILE = os.path.join(DATA_DIR, "wall_posts.json") + +def _load_ai_wall(): + """Load AI wall posts from JSON file (uses wall_posts.json for consistency with app_v2_entry).""" try: - from PIL import Image, ImageDraw, ImageFont - img = Image.new("RGB", (1080, 760), (24, 24, 24)) - draw = ImageDraw.Draw(img) - try: - font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 48) - except Exception: - font = None - text = (fallback_title or "VNEWS")[:40] - try: - bbox = draw.textbbox((0, 0), text, font=font) - tw = bbox[2] - bbox[0] - except Exception: - tw = len(text) * 24 - draw.text(((1080 - tw) // 2, 330), text, fill=(255, 255, 255), font=font) - os.makedirs(os.path.dirname(out_path), exist_ok=True) - img.save(out_path, quality=90) - return out_path + if os.path.exists(WALL_FILE): + with open(WALL_FILE, "r", encoding="utf-8") as f: + return json.load(f) except Exception: - return out_path + pass + return [] +def _save_ai_wall(posts): + """Save AI wall posts to JSON file (uses wall_posts.json for consistency with app_v2_entry).""" + try: + os.makedirs(os.path.dirname(WALL_FILE), exist_ok=True) + tmp = WALL_FILE + ".tmp" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(posts[:100], f, ensure_ascii=False) + os.replace(tmp, WALL_FILE) + except Exception: + pass + + +# Helper functions for wall operations +def _load_wall_posts(): + """Alias for _load_ai_wall for consistency with app_v2_entry.py.""" + return _load_ai_wall() + + +def _save_wall_posts(posts): + """Alias for _save_ai_wall for consistency with app_v2_entry.py.""" + return _save_ai_wall(posts) + + +def make_post(title: str, text: str, img: str, url: str, kind: str, sources=None): + """Create a post dict with standard fields.""" + return { + "id": str(int(time.time() * 1000)), + "title": title, + "text": text, + "img": img, + "url": url, + "kind": kind, + "sources": sources or [], + "ts": int(time.time()) + } + + +def _short_script(post) -> str: + """Extract clean text for TTS from post.""" + text = post.get("text", "") or post.get("title", "") + text = re.sub(r"^[•\-\*]\s*", "", text, flags=re.M) + text = re.sub(r"\s*\n\s*", ". ", text) + return _clean_text(text)[:2000] # Increased from 1000 to 2000 for full content + + +# ===== SCRAPER FUNCTIONS (required by ai_patch.py) ===== def scrape_any_url(url: str) -> dict: - """Scrape article content from any URL.""" - if not url or not url.startswith("http"): - return {"title": "", "text": "", "summary": "", "image": "", "og_image": "", "via": ""} + """Scrape any URL and extract article content. + + Returns dict with: title, summary, text, image, og_image, via (domain) + """ try: r = requests.get(url, headers=HEADERS, timeout=15, allow_redirects=True) - if r.status_code != 200 or not r.text: - return {"title": "", "text": "", "summary": "", "image": "", "og_image": "", "via": _domain(url)} - r.encoding = "utf-8" - soup = BeautifulSoup(r.text, "lxml") - 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"]): + r.encoding = 'utf-8' + soup = BeautifulSoup(r.text, 'lxml') + + # Remove scripts, styles, nav, footer + for tag in soup.find_all(['script', 'style', 'nav', 'footer', 'aside', 'form']): tag.decompose() - title = "" - ogt = soup.find("meta", property="og:title") - if ogt: - title = ogt.get("content", "") - h1 = soup.find("h1") - if not title and h1: - title = h1.get_text(strip=True) - if not title: - t = soup.find("title") - if t: - title = t.get_text(strip=True) - og_image = "" - ogi = soup.find("meta", property="og:image") - if ogi: - og_image = ogi.get("content", "") - if og_image.startswith("//"): - og_image = "https:" + og_image - summary = "" - ogd = soup.find("meta", property="og:description") or soup.find("meta", attrs={"name": "description"}) - if ogd: - summary = ogd.get("content", "")[:500] - body_text = [] - for sel in ["article", ".singular-content", ".detail-content", ".fck_detail", ".content-detail", ".knc-content", "main", ".cms-body", ".article__body", ".post-content", ".entry-content"]: + + # Extract title + h1 = soup.find('h1') + ogt = soup.find('meta', property='og:title') + title = (h1.get_text(strip=True) if h1 else '') or (ogt.get('content', '') if ogt else url) + + # Extract OG image + ogi = soup.find('meta', property='og:image') + og_image = ogi.get('content', '') if ogi else '' + + # Extract article body + block = None + for sel in ['article', '.singular-content', '.detail-content', '.fck_detail', '.content-detail', '.knc-content', 'main', '.cms-body', '.article__body']: el = soup.select_one(sel) - if el and len(el.find_all("p")) >= 2: - for p in el.find_all("p"): - t = _clean_text(p.get_text(strip=True)) - if t and len(t) > 30: - body_text.append(t) + if el and len(el.find_all('p')) >= 2: + block = el break - if not body_text and soup.body: - for p in soup.body.find_all("p"): - t = _clean_text(p.get_text(strip=True)) - if t and len(t) > 30: - body_text.append(t) - text = "\n".join(body_text) - return {"title": _clean_text(title), "text": text, "summary": _clean_text(summary), "image": og_image, "og_image": og_image, "via": _domain(url), "url": url} + if not block: + block = soup.body or soup + + # Extract text from paragraphs + paragraphs = [] + for el in block.find_all(['p', 'h2', 'h3'], recursive=True): + t = _clean_text(el.get_text(strip=True)) + if t and len(t) > 40: + paragraphs.append(t) + + # Extract images + images = [] + for el in block.find_all(['figure', 'img'], recursive=True): + im = el if el.name == 'img' else el.find('img') + if im: + src = im.get('data-src') or im.get('src') or im.get('data-original') or '' + if src and 'base64' not in src: + if src.startswith('//'): + src = 'https:' + src + images.append(src) + + # Prefer OG image as main image + image = og_image or (images[0] if images else '') + + return { + 'title': title, + 'summary': paragraphs[0] if paragraphs else '', + 'text': '\n'.join(paragraphs), + 'image': image, + 'og_image': og_image, + 'via': _domain(url), + 'images': images + } except Exception as e: - return {"title": "", "text": "", "summary": "", "image": "", "og_image": "", "via": _domain(url)} + return {'title': url, 'summary': '', 'text': '', 'image': '', 'og_image': '', 'via': _domain(url), 'error': str(e)} -def make_post(title: str, text: str, img: str, url: str, kind: str = "auto", sources: list = None) -> dict: - """Create a wall post dict.""" - import random as _r2 - now = int(time.time() * 1000) - return { - "id": str(now) + str(_r2.randint(100, 999)), - "title": (title or "Bài viết")[:200], - "text": (text or "")[:5000], - "img": img or "", - "url": url or "", - "kind": kind or "auto", - "sources": sources or [], - "created": now, - "created_str": datetime.now(_VN_TZ).strftime("%H:%M %d/%m/%Y"), - } +def web_context(topic: str, limit: int = 5) -> tuple: + """Get web context for a topic. Returns (context_text, sources_list).""" + sources = [] + try: + # Try Google News RSS + rss_url = f"https://news.google.com/rss/search?q={quote_plus(topic)}&hl=vi&gl=VN&ceid=VN:vi" + r = requests.get(rss_url, headers=HEADERS, timeout=15) + r.encoding = 'utf-8' + soup = BeautifulSoup(r.text, 'xml') + for it in soup.find_all('item')[:limit]: + title = it.find('title').get_text(' ', strip=True) if it.find('title') else '' + link = it.find('link').get_text(strip=True) if it.find('link') else '' + if title and link: + sources.append({'title': title, 'url': link, 'via': _domain(link)}) + except Exception: + pass + + context = f'Trên mạng có nhiều bài viết về "{topic}". Một số nguồn: ' + ', '.join([s.get('title', '') for s in sources[:3]]) + return context, sources + + +# ===== SHORT FRAME FUNCTION (required by ai_patch.py) ===== +def _make_short_frame(post, img_path, out_path): + """Create a short video frame from post and image. + + Called by ai_patch.py _make_short_frame_full when Image is available. + """ + if Image is None: + # Create a minimal frame without PIL - just return success + # The caller should handle this case + return False + + W, H = 1080, 1920 + bg = Image.new("RGB", (W, H), (14, 14, 14)) + + try: + im = Image.open(img_path).convert("RGB") + target = (1080, 760) + im_ratio = im.width / max(1, im.height) + target_ratio = target[0] / target[1] + + if im_ratio > target_ratio: + new_h = target[1] + new_w = int(new_h * im_ratio) + else: + new_w = target[0] + new_h = int(new_w / im_ratio) + + im = im.resize((new_w, new_h)) + left = (new_w - target[0]) // 2 + top = (new_h - target[1]) // 2 + im = im.crop((left, top, left + target[0], top + target[1])) + bg.paste(im, (0, 0)) + except Exception: + pass + + draw = ImageDraw.Draw(bg) + + try: + font_title = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 54) + font_body = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 38) + except Exception: + font_title = font_body = None + + draw.rectangle((0, 720, W, H), fill=(14, 14, 14)) + margin = 48 + maxw = W - margin * 2 + + y = 830 + for ln in _wrap_text(draw, post.get("title", ""), font_title, maxw, 4): + draw.text((margin, y), ln, fill=(255, 255, 255), font=font_title) + y += 66 + + y += 18 + text = post.get("text", "") + text = re.sub(r"Nguồn tham khảo:.*", "", text, flags=re.S).strip() + body_lines = _wrap_text(draw, text, font_body, maxw, 14) + for ln in body_lines: + draw.text((margin, y), ln, fill=(220, 220, 220), font=font_body) + y += 50 + if y > 1640: + break + + bg.save(out_path, quality=92) + return True + + +def _wrap_text(draw, text, font, max_width, max_lines): + """Helper for wrapping text in frames.""" + words = _clean_text(text).split() + lines, cur = [], "" + for w in words: + test = (cur + " " + w).strip() + try: + width = draw.textbbox((0, 0), test, font=font)[2] + except Exception: + width = len(test) * 20 + if width <= max_width: + cur = test + else: + if cur: + lines.append(cur) + cur = w + if len(lines) >= max_lines: + break + if cur and len(lines) < max_lines: + lines.append(cur) + return lines \ No newline at end of file diff --git a/ai_patch.py b/ai_patch.py index 41aeba3d810744429c14e473c32c3a9fb8e3a605..a1ef29df2d0a94076dabec10f6cfbb90445cf76d 100644 --- a/ai_patch.py +++ b/ai_patch.py @@ -327,24 +327,6 @@ Nội dung bài: if 'Nguồn tham khảo:' not in text: text += "\n\n" + _source_line(src) 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) - - # Generate slides for this post so they persist after page reload - try: - page_data = _scrape_article_images(art.get('url', '')) - if page_data and page_data.get('paragraphs'): - key_points = _extract_key_points_for_slides(page_data['paragraphs'], max_points=12) - if key_points: - relevant_imgs = page_data.get('images', []) - if not relevant_imgs and page_data.get('og_img'): - relevant_imgs = [page_data['og_img']] - slides = [] - for i, point in enumerate(key_points): - img = relevant_imgs[i] if i < len(relevant_imgs) else (relevant_imgs[-1] if relevant_imgs else '') - slides.append({'text': point, 'image': img, 'index': i + 1}) - post['slides'] = slides - except Exception: - pass - new_posts.append(post) posts = new_posts + posts base._save_ai_wall(posts) @@ -371,26 +353,8 @@ async def compat_url_wall(request: Request): if 'Nguồn tham khảo:' not in text: text += "\n\n" + _source_line(src) post = base.make_post(data.get('title') or 'Bài viết', text, data.get('image') or '', url, 'url', sources=src) - - # Generate slides so they persist after page reload - slides = [] - try: - page_data = _scrape_article_images(url) - if page_data and page_data.get('paragraphs'): - key_points = _extract_key_points_for_slides(page_data['paragraphs'], max_points=12) - if key_points: - relevant_imgs = page_data.get('images', []) - if not relevant_imgs and page_data.get('og_img'): - relevant_imgs = [page_data['og_img']] - for i, point in enumerate(key_points): - img = relevant_imgs[i] if i < len(relevant_imgs) else (relevant_imgs[-1] if relevant_imgs else '') - slides.append({'text': point, 'image': img, 'index': i + 1}) - except Exception: - pass - post['slides'] = slides - posts = base._load_ai_wall(); posts.insert(0, post); base._save_ai_wall(posts) - return JSONResponse({'post': post, 'slides': slides}) + return JSONResponse({'post': post}) def _is_relevant_image(img_url, title, text): @@ -523,6 +487,7 @@ async def compat_rewrite_share(request: Request): if 'Nguồn tham khảo:' not in text: text += "\n\n" + _source_line(src) post = base.make_post(data.get('title') or 'Bài viết', text, data.get('image') or '', url, 'summary', sources=src) + posts = base._load_ai_wall(); posts.insert(0, post); base._save_ai_wall(posts) # Generate slides with relevant images only slides = [] @@ -537,10 +502,6 @@ async def compat_rewrite_share(request: Request): img = relevant_imgs[i] if i < len(relevant_imgs) else (relevant_imgs[-1] if relevant_imgs else '') slides.append({'text': point, 'image': img, 'index': i + 1}) - # FIX: Save slides into post so they persist after page reload - post['slides'] = slides - posts = base._load_ai_wall(); posts.insert(0, post); base._save_ai_wall(posts) - return JSONResponse({'post': post, 'slides': slides}) diff --git a/ai_runtime_fix.py b/ai_runtime_fix.py deleted file mode 100644 index 0ec96f7c3c57d95b682765689d6ed0964058cd85..0000000000000000000000000000000000000000 --- a/ai_runtime_fix.py +++ /dev/null @@ -1,394 +0,0 @@ -"""VNEWS Short Video Fix - standalone module with clean registration. -This module MUST be imported LAST to register /api/ai/short endpoints. -FIX v1: No route filtering issues - registers endpoints unconditionally. -FIX v2: SSE inline endpoint for auto homepage updates -""" -import os -import re -import time -import json -import sys -import logging -import asyncio -import hashlib -import subprocess -import requests -from datetime import datetime, timezone, timedelta -from urllib.parse import urlparse -from fastapi import Request, Query -from fastapi.responses import JSONResponse, FileResponse - -# Import dependencies -try: - import ai_ext as base -except ImportError: - import ai_runtime_final6 as base - -# Try to import app from various sources -try: - from app_v2_entry import app -except ImportError: - try: - from main import app - except ImportError: - from ai_runtime_final6 import app - -_log = logging.getLogger("short_fix") -_log.setLevel(logging.INFO) -if not _log.handlers: - _log.addHandler(logging.StreamHandler(sys.stderr)) - -DATA_DIR = "/data" if os.path.isdir("/data") else "/app/data" -os.makedirs(DATA_DIR, exist_ok=True) -SHORTS_DIR = os.path.join(DATA_DIR, "ai_shorts") -os.makedirs(SHORTS_DIR, exist_ok=True) - -# ===== VIETNAMESE FONT DETECTION ===== -_VN_FONT_REG = None -_VN_FONT_BOLD = None - -def _get_vn_fonts(): - """Find Vietnamese-supporting fonts.""" - global _VN_FONT_REG, _VN_FONT_BOLD - if _VN_FONT_REG is not None: - return _VN_FONT_REG, _VN_FONT_BOLD - - try: - from PIL import ImageFont - except Exception: - _log.error("PIL not available!") - return None, None - - # Priority: Noto > DejaVu > Liberation - reg_paths = [ - "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf", - "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", - "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", - "/usr/share/fonts/truetype/freefont/FreeSans.ttf", - ] - bold_paths = [ - "/usr/share/fonts/truetype/noto/NotoSans-Bold.ttf", - "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", - "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", - "/usr/share/fonts/truetype/freefont/FreeSans.ttf", - ] - - for path in reg_paths: - if os.path.exists(path): - try: - _VN_FONT_REG = ImageFont.truetype(path, 40) - _log.info(f"Found regular font: {path}") - break - except: - continue - - for path in bold_paths: - if os.path.exists(path): - try: - _VN_FONT_BOLD = ImageFont.truetype(path, 52) - _log.info(f"Found bold font: {path}") - break - except: - continue - - if _VN_FONT_REG is None: - _VN_FONT_REG = ImageFont.load_default() - if _VN_FONT_BOLD is None: - _VN_FONT_BOLD = _VN_FONT_REG - - return _VN_FONT_REG, _VN_FONT_BOLD - - -def _clean(s): - import html as html_lib - return re.sub(r"\s+", " ", html_lib.unescape(str(s or ""))).strip() - - -# ===== ROBUST TEXT SEGMENTATION ===== -def _split_into_segments(text, max_segments=10, min_len=30): - """Split text into segments - multi strategy.""" - text = _clean(text) - if not text: - return [] - - # Strategy 1: bullet points - lines = text.split('\n') - segmented = [] - for line in lines: - line = _clean(line) - line_bare = re.sub(r'^[•\-\*\d\.\)\s]+', '', line).strip() - if len(line_bare) > min_len: - segmented.append(line_bare) - elif len(line) > min_len: - segmented.append(line) - - # Strategy 2: sentences (Vietnamese) - if len(segmented) < 2: - sents = re.split(r'(?<=[.!?])\s+(?=[A-Z0-9À-ỸĐ])', text) - segmented = [s for s in sents if len(_clean(s)) > min_len] - - # Strategy 3: character chunks - if not segmented: - words = text.split() - for i in range(0, min(len(words), max_segments * 20), 20): - chunk = ' '.join(words[i:i+20]) - if len(chunk) > min_len: - segmented.append(chunk) - - # Strategy 4: fallback - if not segmented: - segmented = [text[:300]] - - return segmented[:max_segments] - - -# ===== SHORT VIDEO GENERATOR ===== -def _gen_short_core(post, work_dir): - """Core short generation - returns video path or None.""" - post_id = post.get('id', '') - text = post.get('text', '') or post.get('title', '') - - if not post_id or len(text) < 100: - _log.error(f"Invalid post: id={post_id}, text_len={len(text)}") - return None - - segments = _split_into_segments(text, max_segments=10, min_len=30) - if not segments: - _log.error("No segments generated") - return None - - _log.info(f"Generating short: {len(segments)} segments") - - seg_hash = hashlib.md5(('|'.join(segments) + 'nu').encode()).hexdigest()[:8] - suffix = f"_nu_{seg_hash}" - out_mp4 = os.path.join(work_dir, f"{post_id}{suffix}.mp4") - - if os.path.exists(out_mp4): - _log.info(f"Already exists: {out_mp4}") - return out_mp4 - - # Check dependencies - try: - subprocess.run(['ffmpeg', '-version'], capture_output=True, timeout=5) - except Exception as e: - _log.error(f"ffmpeg missing: {e}") - return None - - # Download image - img_path = os.path.join(work_dir, 'bg.jpg') - downloaded = False - try: - img_url = post.get('img', '') - if img_url and img_url.startswith('http'): - r = requests.get(img_url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=12) - if r.status_code == 200: - with open(img_path, 'wb') as f: - f.write(r.content) - downloaded = True - except Exception as e: - _log.warning(f"Image download: {e}") - - try: - from PIL import Image, ImageDraw - has_pil = True - except: - has_pil = False - _log.warning("PIL not available") - - try: - from gtts import gTTS - has_tts = True - except: - has_tts = False - _log.warning("gTTS not available") - - parts = [] - - for i, seg in enumerate(segments[:10]): - frame = os.path.join(work_dir, f'frame_{i}.jpg') - audio = os.path.join(work_dir, f'audio_{i}.mp3') - part = os.path.join(work_dir, f'part_{i}.mp4') - - # Create frame - try: - if has_pil: - _make_frame(post, seg, img_path, downloaded, frame) - else: - subprocess.run(['ffmpeg', '-y', '-f', 'lavfi', '-i', - 'color=c=black:s=1080x1920:d=1', '-frames:v', '1', frame], - capture_output=True, timeout=20) - except Exception as e: - _log.error(f"Frame error: {e}") - continue - - # Create audio - if has_tts: - try: - tts = _clean(seg)[:300] - gTTS(tts, lang='vi', slow=False).save(audio) - except Exception as e: - _log.warning(f"TTS error: {e}") - audio = None - - # Combine - dur = 10 - try: - cmd = ['ffmpeg', '-y', '-loop', '1', '-t', str(dur), '-i', frame] - if has_tts and os.path.exists(audio): - cmd += ['-i', audio, '-shortest'] - else: - cmd += ['-f', 'lavfi', '-i', 'anullsrc', '-shortest'] - cmd += ['-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p', - '-c:a', 'aac', '-b:a', '128k', part] - subprocess.run(cmd, capture_output=True, timeout=120) - if os.path.exists(part) and os.path.getsize(part) > 5000: - parts.append(part) - except Exception as e: - _log.error(f"Part combine error: {e}") - - if not parts: - _log.error("No video parts created!") - return None - - # Concatenate - try: - concat = os.path.join(work_dir, 'list.txt') - with open(concat, 'w') as f: - for p in parts: - f.write(f"file '{p}'\n") - subprocess.run(['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat, '-c', 'copy', out_mp4], - capture_output=True, timeout=180) - _log.info(f"Short created: {out_mp4}") - return out_mp4 - except Exception as e: - _log.error(f"Concat error: {e}") - return None - - -def _make_frame(post, text, img_path, downloaded, out_path): - """Create video frame with Vietnamese font.""" - from PIL import Image, ImageDraw - _get_vn_fonts() - - W, H = 1080, 1920 - bg = Image.new('RGB', (W, H), (15, 23, 38)) - d = ImageDraw.Draw(bg) - - # Background image - if downloaded and os.path.exists(img_path): - try: - im = Image.open(img_path).convert('RGB') - im = im.resize((W, 760)) - bg.paste(im, (0, 0)) - except: - pass - - # Title - d.rectangle([0, 0, W, 100], fill=(25, 118, 210)) - ttl = post.get('title', '')[:50] - if _VN_FONT_BOLD: - d.text((W//2, 50), ttl, fill='white', font=_VN_FONT_BOLD, anchor='mm') - - # Content - y = 150 - for ln in _wrap_text(d, text[:200], _VN_FONT_REG, 80, 920, 10): - d.text((80, y), ln, fill='white', font=_VN_FONT_REG) - y += 55 - - bg.save(out_path, quality=85) - - -def _wrap_text(draw, text, font, x, max_w, max_lines): - """Word wrap text.""" - words = text.split() - lines = [] - cur = [] - for w in words: - test = ' '.join(cur + [w]) - try: - w_px = draw.textbbox((0, 0), test, font=font)[2] - except: - w_px = len(test) * 22 - if w_px <= max_w: - cur.append(w) - else: - if cur: - lines.append(' '.join(cur)) - cur = [w] - if len(lines) >= max_lines: - break - if cur and len(lines) < max_lines: - lines.append(' '.join(cur)) - return lines - - -def _gen_short_sync(post) -> str: - """Sync wrapper - returns video URL.""" - work = os.path.join(SHORTS_DIR, f"work_{post.get('id', int(time.time()))}") - os.makedirs(work, exist_ok=True) - result = _gen_short_core(post, work) - if result: - # Update wall - try: - wall = base._load_ai_wall() - for i, p in enumerate(wall): - if str(p.get('id')) == str(post.get('id')): - p['video'] = f'/api/ai/short-file/{post.get("id")}_nu_{hashlib.md5(str(post).encode()).hexdigest()[:8]}' - wall[i] = p - break - base._save_ai_wall(wall) - # Notify SSE for auto-update - try: - from auto_update_sse import notify_new_short - notify_new_short(post) - except: - pass - except Exception as e: - _log.warning(f"Wall update: {e}") - return result - return '' - - -# ===== REGISTER ENDPOINTS - MUST BE AT MODULE LEVEL ===== -@app.post('/api/ai/short/{post_id}') -async def api_short_generate(post_id: str, request: Request): - _log.info(f"POST /api/ai/short/{post_id}") - wall = base._load_ai_wall() - post = next((p for p in wall if str(p.get('id')) == str(post_id)), None) - if not post: - return JSONResponse({'error': 'Post not found in wall'}, status_code=404) - - if post.get('video'): - return JSONResponse({'post': post, 'video': post['video'], 'status': 'done'}) - - loop = asyncio.get_event_loop() - result = await loop.run_in_executor(None, _gen_short_sync, post) - - if result: - # Get the video URL from wall (updated in _gen_short_sync) - wall = base._load_ai_wall() - post = next((p for p in wall if str(p.get('id')) == str(post_id)), post) - return JSONResponse({'post': post, 'video': post.get('video'), 'status': 'done'}) - return JSONResponse({'error': 'Video generation failed'}, status_code=500) - - -@app.get('/api/ai/short-file/{file_id:path}') -async def api_short_file(file_id: str): - safe = re.sub(r'[^\w\-.]', '_', file_id)[:100] - for fname in os.listdir(SHORTS_DIR) if os.path.isdir(SHORTS_DIR) else []: - if fname.endswith('.mp4') and safe in fname: - return FileResponse(os.path.join(SHORTS_DIR, fname), media_type='video/mp4') - return JSONResponse({'error': 'Not found'}, status_code=404) - - -# ===== SSE ENDPOINT FOR AUTO-UPDATE ===== -try: - from auto_update_sse import sse_events as _sse_handler - app.add_api_route('/api/events', _sse_handler, methods=['GET']) - _log.info("SSE endpoint registered at /api/events") -except Exception as e: - _log.warning(f"SSE route not loaded: {e}") - - -# Log startup -_log.info("Short video endpoints registered") \ No newline at end of file diff --git a/ai_runtime_patch_final.py b/ai_runtime_patch_final.py deleted file mode 100644 index 0512ad0ef58446a2f791f8f85e0457950cdd54d3..0000000000000000000000000000000000000000 --- a/ai_runtime_patch_final.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Final patch: homepage fix + AI topics at top + SSE auto-update""" -import re, json, time -from fastapi.responses import HTMLResponse, JSONResponse -from fastapi import Query - -# Import chain - must be after ai_runtime_final6 -try: - import ai_runtime_final6 as f6 - from ai_runtime_final6 import app, f5 - from main import rt -except Exception as e: - print(f"[ERROR] f6 import: {e}") - f6 = None - f5 = None - rt = None - -PATCH_CSS_JS = r''' - -
- -''' - -# Register route if possible -if f6 and app: - try: - # Remove duplicate / route to avoid conflict - original_routes = [r for r in app.router.routes if not (getattr(r,'path',None)=='/' and 'GET' in getattr(r,'methods',set()))] - app.router.routes = original_routes - - @app.get('/') - async def patch_homepage(): - html = f5.f4.f3.f2.f1._load_index_html() if f5 else "" - body = "" - if hasattr(rt,'old') and hasattr(rt.old,'PATCH_INJECT'): - body += getattr(rt.old,'PATCH_INJECT','') - if f5: - body += getattr(f5.f4.f3.f2.f1,'FINAL_INJECT','') if hasattr(f5,'f4') else '' - body += getattr(f5.f4.f3,'FINAL3_INJECT','') if hasattr(f5,'f4') else '' - body += getattr(f5.f4,'FINAL4_INJECT','') if hasattr(f5,'f4') else '' - body += getattr(f5,'FINAL5_INJECT','') if hasattr(f5,'f4') else '' - body += getattr(f6,'FINAL6_INJECT','') if f6 else '' - body += getattr(f6,'FINAL6_FAST_HOME_INJECT','') if f6 else '' - body += getattr(f6,'FINAL6E_INJECT','') if f6 else '' - body += PATCH_CSS_JS - if '' in html: - html = html.replace('', body + '\n') - else: - html = html + body - return HTMLResponse(html) - except Exception as e: - print(f"[ERROR] register route: {e}") \ No newline at end of file diff --git a/ai_short_v2.py b/ai_short_v2.py deleted file mode 100644 index 675704f10853a311f3d9ec2f2761012140901c6a..0000000000000000000000000000000000000000 --- a/ai_short_v2.py +++ /dev/null @@ -1,2083 +0,0 @@ -"""VNEWS Short AI v2 — Short creator with TikTok background music, uploaded audio, -uploaded video/image background, and 'recreate from designed slides' (image-only, -reusing previous short audio, NO text overlays) mode. - -Registered by app_v2_entry.py (import ai_short_v2). Uses the SAME wall store -(WALL_FILE) as the wall endpoints so posts created by the designer survive and -can be re-shorted purely from designed images. -""" -import os -import re -import json -import time -import uuid -import hashlib -import subprocess -import threading - -import requests -from urllib.parse import quote as urllib_quote -from fastapi import Request, UploadFile, File, Query -from fastapi.responses import JSONResponse, FileResponse, Response, StreamingResponse - -try: - import yt_dlp -except Exception: # pragma: no cover - yt_dlp = None - -try: - from PIL import Image, ImageDraw, ImageFont -except Exception: # pragma: no cover - Image = ImageDraw = ImageFont = None - -try: - from main import app -except Exception: # pragma: no cover - from fastapi import FastAPI - app = FastAPI() - -DATA_DIR = "/data" if os.path.isdir("/data") else os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") -WALL_FILE = os.path.join(DATA_DIR, "wall_posts.json") -SHORTS_DIR = os.path.join(DATA_DIR, "ai_shorts") -UPLOAD_DIR = os.path.join(DATA_DIR, "short_uploads") -WALL_IMG_DIR = os.path.join(DATA_DIR, "wall_imgs") -os.makedirs(SHORTS_DIR, exist_ok=True) -os.makedirs(UPLOAD_DIR, exist_ok=True) - -_wl_lock = threading.Lock() - -UA_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", -} - -# --------------------------------------------------------------------------- -# Video scraping (YouTube / TikTok / news sites) via yt-dlp + oEmbed fallback -# --------------------------------------------------------------------------- -_SCRAPE_CACHE = {} # url -> {ok, ...} (in-memory, TTL 30 min) -_SCRAPE_TTL = 30 * 60 - -YTDLP_OPTS = { - "format": "best[height<=720][ext=mp4]/best[height<=720]/best", - "quiet": True, - "no_warnings": True, - "noplaylist": True, - "socket_timeout": 30, - "retries": 5, - "fragment_retries": 5, - "ignoreerrors": False, - "extractor_args": {"youtube": {"player_client": ["tv", "ios", "mweb"]}}, - "http_headers": UA_HEADERS, -} - - -# --------------------------------------------------------------------------- -# YouTube cookies (bypasses the "Sign in to confirm you're not a bot" block). -# Sources, in priority order: -# 1. YT_COOKIES env var (HF Space secret — raw Netscape-format cookies.txt) -# 2. /app/cookies.txt (a cookies.txt file baked into the repo/runtime) -# yt-dlp reads a Netscape cookies.txt via the 'cookiefile' option. -# --------------------------------------------------------------------------- -_cookie_file = None - - -def _ensure_cookies(): - """Materialise a cookies.txt (Netscape format) for yt-dlp if any cookie - source is available. Returns the cookiefile path or None.""" - global _cookie_file - if _cookie_file and os.path.exists(_cookie_file): - return _cookie_file - content = None - # 1. HF Space secret YT_COOKIES (raw cookies.txt content) - secret = os.environ.get("YT_COOKIES", "").strip() - if secret and ("# Netscape" in secret or "#HTTP" in secret or "youtube.com" in secret or "\tTRUE" in secret): - content = secret - # 2. baked-in file - if not content: - for p in ("/app/cookies.txt", "cookies.txt"): - if os.path.exists(p): - content = open(p, encoding="utf-8", errors="ignore").read() - break - if not content: - _cookie_file = None - return None - try: - path = os.path.join(DATA_DIR, "yt_cookies.txt") - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding="utf-8") as f: - f.write(content) - _cookie_file = path - return path - except Exception: - return None - - -def _ytdlp_opts(): - """YTDLP opts + cookiefile (only when cookies are available).""" - opts = dict(YTDLP_OPTS) - cf = _ensure_cookies() - if cf: - opts["cookiefile"] = cf - # also add "cookiesfrombrowser" fallback? No — datacenter IPs can't read - # a local browser. cookiefile is the reliable path. - return opts - - -def _oembed_probe(url): - """Cheap metadata fallback for TikTok/Facebook/Instagram/YouTube (no direct URL).""" - try: - host = (re.sub(r"^https?://", "", url).split("/")[0] or "").lower() - api = None - if "tiktok" in host: - api = "https://www.tiktok.com/oembed?url=" + urllib_quote(url, safe="") - elif "facebook" in host or "fb.watch" in host: - api = "https://www.facebook.com/plugins/video/oembed.json?url=" + urllib_quote(url, safe="") - elif "youtube.com" in host or "youtu.be" in host: - api = "https://www.youtube.com/oembed?url=" + urllib_quote(url, safe="") + "&format=json" - if not api: - return None - # Facebook oEmbed often times out from datacenter IPs; use a shorter timeout - _timeout = 8 if ("facebook" in host or "fb.watch" in host) else 12 - j = {} - try: - r = requests.get(api, headers=UA_HEADERS, timeout=_timeout) - if r.status_code == 200: - j = r.json() or {} - except Exception: - j = {} - # YouTube: youtube.com/oembed is often SNI-blocked from datacenter IPs. - # Fall back to _yt_meta (noembed.com cascade) which reliably returns - # title+thumbnail+description from restricted networks. - yt_meta = None - if "youtube.com" in host or "youtu.be" in host: - yt_meta = _yt_meta(url) - title = ((j.get("title") or "") or (yt_meta or {}).get("title") or "").strip()[:200] - thumb = ((j.get("thumbnail_url") or "") or (yt_meta or {}).get("thumbnail") or "").strip() - desc = (yt_meta or {}).get("description") or "" - if "youtube.com" in host or "youtu.be" in host: - if not desc: - desc = (yt_meta or {}).get("description") or "" - embed_url = _oembed_embed_url(url) - # oEmbed providers (notably TikTok short links like vm.tiktok.com) don't - # expose the video ID in the URL, but the `html` field contains the - # canonical `:isHLS?``:``;const videoId='hl-'+league+'-'+v._idx;h+=buildTikTokSlide({vtag,title:v.title,badge:'HL',badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:v.link||'',postId:'',extraBtn:``})});h+='';el.innerHTML=h;setTimeout(()=>initTikTokFeed(),200);} -async function openYTShortsFeed(idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đã xóa Shorts Dân trí/SKĐS
';} -async function openShortAIFeed(idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');if(!_wallPosts||!_wallPosts.length){el.innerHTML='
Không có Short AI
';return}const aiPosts=_wallPosts.filter(p=>p.video);if(!aiPosts.length||idx>=aiPosts.length){el.innerHTML='
Không có Short AI
';return}const ordered=aiPosts.slice(idx).concat(aiPosts.slice(0,idx));let h=`
`;ordered.forEach((p,i)=>{const baseIdx=_wallPosts.indexOf(p);const vtag=p.video?``:'';h+=buildTikTokSlide({vtag,title:p.title,badge:'Short AI',badgeClass:'badge-ai',videoId:p.id||'ai-'+i,idx:i,total:ordered.length,shareUrl:p.video||'',postId:p.id||'',extraBtn:``})});h+='
';el.innerHTML=h;setTimeout(()=>initTikTokFeed(),200);} -function readWallPost(idx){const p=_wallPosts&&_wallPosts[idx];if(!p)return;if(p.slides&&p.slides.length){readSlidePost(idx);return}readArticle(p.url||'','','',p.title,p.text);} -/** Show rewrite slide viewer - vertical slides with text+image */ -function readSlidePost(idx){const p=_wallPosts[idx];if(!p||!p.slides)return;showView('view-article');const el=document.getElementById('view-article');let h=`
`;p.slides.forEach((s,i)=>{h+=`
Slide ${s.index||i+1}/${p.slides.length}
${s.image?``:''}

${esc(s.text)}

`;});h+=`
`;el.innerHTML=h;} - -/** Slide Designer Modal - design a slide image with high-contrast text on background */ -function designerGetRatio(){const v=document.getElementById('designer-ratio')?.value||'3:4';const m=v.split(':');return m.length===2?{w:parseInt(m[0]),h:parseInt(m[1])}:1;} -function designerGetLayout(){return document.getElementById('designer-layout')?.value||'solid';} -function designerDebounce(fn,d){clearTimeout(fn._t);fn._t=setTimeout(fn,d);} -function openSlideDesigner(idx){ - designerSlideIdx=idx; - const p=_wallPosts[idx];if(!p||!p.slides)return; - const overlay=document.createElement('div');overlay.id='slide-designer-overlay';overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.92);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto'; - let h='
'; - h+='

🎨 Thiết kế ảnh slide

'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - ['#ffffff','#000000','#ff4444','#44ff44','#4444ff','#ffff00','#ff00ff','#00ffff','#ff8800','#88ff00'].forEach(c=>{h+=``;}); - h+='
'; - h+='
'; - h+='
'; - h+=''; - h+='
'; - overlay.innerHTML=h;document.body.appendChild(overlay); - document.getElementById('designer-slide-select').addEventListener('change',function(){updateDesignerText(this.value);previewDesignerSlide();}); - document.getElementById('designer-preview-btn').addEventListener('click',function(){previewDesignerSlide();}); - document.getElementById('designer-save-btn').addEventListener('click',function(){saveDesignerSlide(p.title,(p.id||''),idx);}); - ['change','input'].forEach(function(evt){ - const txt=document.getElementById('designer-text');if(txt)txt.addEventListener(evt,function(){designerDebounce(previewDesignerSlide,150);}); - const bg=document.getElementById('designer-bg-url');if(bg)bg.addEventListener(evt,function(){designerDebounce(previewDesignerSlide,150);}); - const ratio=document.getElementById('designer-ratio');if(ratio)ratio.addEventListener(evt,function(){previewDesignerSlide();}); - const layout=document.getElementById('designer-layout');if(layout)layout.addEventListener(evt,function(){previewDesignerSlide();}); - }); - previewDesignerSlide(); -} -function updateDesignerText(slideIdx){const p=_wallPosts[designerSlideIdx];if(!p||!p.slides)return;const s=p.slides[parseInt(slideIdx)];if(s)document.getElementById('designer-text').value=s.text||'';document.getElementById('designer-bg-url').value=s.image||p.img||'';designerBgDataUrl=null;} -function handleDesignerBgFile(input){ - const file=input.files&&input.files[0];if(!file)return; - const reader=new FileReader(); - reader.onload=function(e){designerBgDataUrl=e.target.result;document.getElementById('designer-bg-url').value='[uploaded]';}; - reader.readAsDataURL(file); -} -function previewDesignerSlide(){ - const slideIdx=parseInt(document.getElementById('designer-slide-select')?.value||'0'); - const p=_wallPosts[designerSlideIdx];if(!p||!p.slides)return; - const s=p.slides[slideIdx];if(!s)return; - const text=document.getElementById('designer-text')?.value||s.text||''; - const bgUrlInput=document.getElementById('designer-bg-url')?.value||''; - const bgUrl=designerBgDataUrl||bgUrlInput||s.image||p.img||''; - const textColor=document.getElementById('designer-text')?.style.color||'#ffffff'; - const ratio=designerGetRatio(); - const layout=designerGetLayout(); - const previewArea=document.getElementById('designer-preview-area');if(!previewArea)return; - previewArea.style.display='block';previewArea.innerHTML='
⏳ Đang tạo xem trưởng...
'; - const canvas=document.createElement('canvas'); - const vw=Math.max(document.documentElement.clientWidth||540, document.body.clientWidth||540); - const maxW=Math.min(540, Math.floor(vw*0.9)); - canvas.width=maxW;canvas.height=Math.round(maxW*ratio.h/ratio.w); - canvas.style.maxWidth='100%';canvas.style.width='100%';canvas.style.height='auto'; - canvas.style.borderRadius='12px';canvas.style.boxShadow='0 8px 24px rgba(0,0,0,.5)'; - canvas.style.display='block';canvas.style.margin='0 auto'; - const ctx=canvas.getContext('2d');const img=new Image();img.crossOrigin='anonymous'; - function drawLayout(){ - if(layout==='vignette'){const g=ctx.createRadialGradient(canvas.width/2,canvas.height/2,0,canvas.width/2,canvas.height/2,Math.max(canvas.width,canvas.height)*0.6);g.addColorStop(0,'rgba(0,0,0,0)');g.addColorStop(1,'rgba(0,0,0,0.7)');ctx.fillStyle=g;ctx.fillRect(0,0,canvas.width,canvas.height);} - else if(layout==='split'){ctx.fillStyle='rgba(0,0,0,0)';ctx.fillRect(0,0,canvas.width,canvas.height/2);ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,canvas.height/2,canvas.width,canvas.height/2);} - else if(layout==='spotlight'){const cx=canvas.width/2,cy=canvas.height/2,r=Math.max(canvas.width,canvas.height)*0.35;ctx.save();ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.globalCompositeOperation='destination-out';ctx.fillStyle='white';ctx.beginPath();ctx.arc(cx,cy,r,0,Math.PI*2);ctx.fill();ctx.globalCompositeOperation='source-over';} - else if(layout==='diagonal'){ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.fillStyle='rgba(0,0,0,0.75)';ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(canvas.width,0);ctx.lineTo(0,canvas.height);ctx.closePath();ctx.fill();} - else {ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,canvas.width,canvas.height);} - } - function drawText(){ - ctx.fillStyle=textColor;ctx.font='bold '+Math.round(canvas.width*28/540)+'px sans-serif'; - ctx.textAlign='center';ctx.textBaseline='middle'; - const maxW=Math.round(canvas.width*0.82); - const words=text.split(' ');let line='';let y=Math.round(canvas.height/2); - const fontSize=Math.round(canvas.width*28/540);const lineHeight=Math.round(fontSize*1.3); - for(let i=0;imaxW&&i>0){ctx.fillText(line.trim(),canvas.width/2,y);y+=lineHeight;line=words[i];}else{line=test;}} - ctx.fillText(line.trim(),canvas.width/2,y); - } - function renderAll(){ - ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,canvas.width,canvas.height); - drawLayout(); - drawText(); - previewArea.innerHTML='';previewArea.appendChild(canvas); - } - img.onload=function(){ - const iw=img.naturalWidth||1,ih=img.naturalHeight||1; - const scale=Math.max(canvas.width/iw,canvas.height/ih); - const dw=iw*scale,dh=ih*scale; - const dx=(canvas.width-dw)/2,dy=(canvas.height-dh)/2; - ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh); - drawLayout();drawText(); - previewArea.innerHTML='';previewArea.appendChild(canvas); - }; - img.onerror=function(){renderAll();}; - if(bgUrl){img.src=bgUrl.startsWith('/api/')?bgUrl:bgUrl.startsWith('data:')?bgUrl:'/api/proxy/img?url='+encodeURIComponent(bgUrl);}else{renderAll();} -} -async function saveDesignerSlide(title,postId,idx){ - const slideIdx=parseInt(document.getElementById('designer-slide-select')?.value||'0'); - const p=_wallPosts[idx];if(!p||!p.slides)return; - const s=p.slides[slideIdx];if(!s)return; - const text=document.getElementById('designer-text')?.value||s.text||''; - const bgUrlInput=document.getElementById('designer-bg-url')?.value||''; - const bgUrl=designerBgDataUrl||bgUrlInput||s.image||p.img||''; - const textColor=document.getElementById('designer-text')?.style.color||'#ffffff'; - const ratio=designerGetRatio(); - const layout=designerGetLayout(); - const statusEl=document.getElementById('designer-status');if(statusEl)statusEl.textContent='⏳ Đang tạo ảnh...'; - const FINAL_W=ratio.w>=ratio.h?1800:1350; - const FINAL_H=Math.round(FINAL_W*ratio.h/ratio.w); - const canvas=document.createElement('canvas');canvas.width=FINAL_W;canvas.height=FINAL_H; - const ctx=canvas.getContext('2d'); - const img=new Image();img.crossOrigin='anonymous'; - function drawLayoutF(){ - if(layout==='vignette'){const g=ctx.createRadialGradient(FINAL_W/2,FINAL_H/2,0,FINAL_W/2,FINAL_H/2,Math.max(FINAL_W,FINAL_H)*0.6);g.addColorStop(0,'rgba(0,0,0,0)');g.addColorStop(1,'rgba(0,0,0,0.7)');ctx.fillStyle=g;ctx.fillRect(0,0,FINAL_W,FINAL_H);} - else if(layout==='split'){ctx.fillStyle='rgba(0,0,0,0)';ctx.fillRect(0,0,FINAL_W,FINAL_H/2);ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,FINAL_H/2,FINAL_W,FINAL_H/2);} - else if(layout==='spotlight'){const cx=FINAL_W/2,cy=FINAL_H/2,r=Math.max(FINAL_W,FINAL_H)*0.35;ctx.save();ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,0,FINAL_W,FINAL_H);ctx.globalCompositeOperation='destination-out';ctx.fillStyle='white';ctx.beginPath();ctx.arc(cx,cy,r,0,Math.PI*2);ctx.fill();ctx.globalCompositeOperation='source-over';} - else if(layout==='diagonal'){ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,FINAL_W,FINAL_H);ctx.fillStyle='rgba(0,0,0,0.75)';ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(FINAL_W,0);ctx.lineTo(0,FINAL_H);ctx.closePath();ctx.fill();} - else {ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,FINAL_W,FINAL_H);} - } - function drawTextF(){ - ctx.fillStyle=textColor;ctx.font='bold '+Math.round(FINAL_W*48/1080)+'px sans-serif'; - ctx.textAlign='center';ctx.textBaseline='middle'; - const maxW=Math.round(FINAL_W*0.82);const words=text.split(' ');let line='';let y=Math.round(FINAL_H/2); - const fontSize=Math.round(FINAL_W*48/1080);const lineHeight=Math.round(fontSize*1.3); - for(let i=0;imaxW&&i>0){ctx.fillText(line.trim(),FINAL_W/2,y);y+=lineHeight;line=words[i];}else{line=test;}}ctx.fillText(line.trim(),FINAL_W/2,y); - } - function render(){ - ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,FINAL_W,FINAL_H); - drawLayoutF();drawTextF(); - canvas.toBlob(async function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - try{const r=await fetch('/api/wall/img',{method:'POST',body:formData});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi upload'); - s.image=j.url; - const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}); - const wj=await wr.json();if(wr.ok&&wj.post){prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');}else{toast('✅ Đã lưu ảnh slide!');} - document.getElementById('slide-designer-overlay').remove(); - }catch(e){if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);} - },'image/png'); - } - img.onload=function(){ - const iw=img.naturalWidth||1,ih=img.naturalHeight||1; - const scale=Math.max(FINAL_W/iw,FINAL_H/ih); - const dw=iw*scale,dh=ih*scale; - const dx=(FINAL_W-dw)/2,dy=(FINAL_H-dh)/2; - ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh); - drawLayoutF();drawTextF(); - canvas.toBlob(async function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - try{const r=await fetch('/api/wall/img',{method:'POST',body:formData});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi upload'); - s.image=j.url; - const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}); - const wj=await wr.json();if(wr.ok&&wj.post){prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');}else{toast('✅ Đã lưu ảnh slide!');} - document.getElementById('slide-designer-overlay').remove(); - }catch(e){if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);} - },'image/png'); - }; - img.onerror=function(){if(statusEl)statusEl.textContent='⚠️ Không tải được ảnh nền, dùng nền mặc định';ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,FINAL_W,FINAL_H);drawLayoutF();drawTextF();canvas.toBlob(function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - fetch('/api/wall/img',{method:'POST',body:formData}).then(r=>r.json()).then(j=>{ - if(j.ok){s.image=j.url;const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}).then(r=>r.json()).then(wj=>{if(wj.post)prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');document.getElementById('slide-designer-overlay').remove();});} - }).catch(e=>{if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);}); - },'image/png');}; - if(bgUrl){img.src=bgUrl.startsWith('/api/')?bgUrl:bgUrl.startsWith('data:')?bgUrl:'/api/proxy/img?url='+encodeURIComponent(bgUrl);}else{render();} -} - -function readNewsTab(tab){loadNewsTab();} -function loadNewsTab(){const el=document.getElementById('view-cat');if(!el)return;el.innerHTML='
Đang tải tin tức...
';fetch('/api/homepage').then(r=>r.json()).then(articles=>{if(!articles||!articles.length){el.innerHTML='
Không có tin
';return}let h='
';articles.forEach(a=>{const src=a.source||'vne';const badge=a.group||a.source||'';h+=`
${a.img?``:''}
${esc(badge)}
${esc(a.title)}
`;});h+='
';el.innerHTML=h;}).catch(()=>{el.innerHTML='
Lỗi tải
';});} - -function readArticle(url,title,img,presetTitle,presetText){showView('view-article');const el=document.getElementById('view-article');el.innerHTML='
Đang tải...
';if(presetTitle){el.innerHTML=`

${esc(presetTitle)}

${presetText?`
${esc(presetText)}
`:''}
`;return;}if(!url)return;fetch('/api/article?url='+encodeURIComponent(url)).then(r=>r.json()).then(d=>{let h=`
`;if(d.title)h+=`

${esc(d.title)}

`;if(d.summary)h+=`
${esc(d.summary)}
`;if(d.body)d.body.forEach(b=>{if(b.type==='p')h+=`

${esc(b.text)}

`;else if(b.type==='heading')h+=`

${esc(b.text)}

`;else if(b.type==='img'&&b.src)h+=``;});h+=`
`;el.innerHTML=h;}).catch(()=>{el.innerHTML=`

Không thể tải bài viết

`;});} -async function rewriteSlide(url){if(!url)return;const btn=document.querySelector('.article-actions .primary')||event?.target;if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo slides...';}toast('⏳ Đang tạo slide rewrite...');try{const r=await fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');toast('✅ Đã tạo slide! Đang tạo Short AI...');if(btn)btn.textContent='✅ Đang tạo Short AI...';if(j.post){j.post.slides=j.slides||[];prependWallPost(j.post);}// Show slides immediately if available -if(j.slides && j.slides.length){showView('view-article');const el=document.getElementById('view-article');let h=`
`;j.slides.forEach(s=>{h+=`
Slide ${s.index}/${j.slides.length}
${s.image?``:''}

${esc(s.text)}

`;});h+=`
⏳ Đang tạo video Short AI...
`;el.innerHTML=h;} -const postId=j.post&&j.post.id;if(postId){setTimeout(async()=>{const sr=await fetch('/api/ai/short/'+encodeURIComponent(postId),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice:'vi-VN-HoaiMyNeural',emotion:'neutral',speed:1.2})});const sj=await sr.json();if(sr.ok&&sj.video&&typeof _wallPosts!=='undefined'){const p=_wallPosts.find(x=>String(x.id)===String(postId));if(p){p.video=sj.video;const itemId='wall-item-'+postId;const el2=document.getElementById(itemId);if(el2){const idx=_wallPosts.indexOf(p);el2.insertAdjacentHTML('afterend',makeWallItem(p,idx));el2.remove();}}toast('✅ Short AI đã sẵn sàng!');const statusEl=document.getElementById('short-ai-status');if(statusEl)statusEl.innerHTML='✅ Short AI đẵn sàng! ';}},500);}if(btn)btn.textContent='✅ Hoàn tất';}catch(e){toast('❌ '+e.message);if(btn){btn.disabled=false;btn.textContent='🤖 Slide Rewrite AI';}}} - -function downloadVideo(url, title){ - var a = document.createElement('a'); - a.href = url; - a.download = (title||'video').toString().replace(/[^a-zA-Z0-9_\-\p{L}]/gu,'_').substring(0,60)+'.mp4'; - a.target = '_blank'; - a.rel = 'noopener'; - a.style.display = 'none'; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - toast('📥 Đang tải video xuống...'); -} - -// ===== PERSONAL OPINION POST: Viết bài dựa trên quan điểm cá nhân + tin HOT ===== -async function openPersonalPostPreview() { - const opinion = document.getElementById('opinion-input')?.value.trim(); - if (!opinion || opinion.length < 10) { - alert('Vui lòng nhập quan điểm cá nhân (ít nhất 10 ký tự)'); - return; - } - - // Get selected hot topics from UI (if any) - const selectedTopics = []; - if (window._htTopic) { - selectedTopics.push(window._htTopic); - } - - // Get selected sources from hashtag view - const selectedSources = []; - document.querySelectorAll('.hashtag-src-item.selected').forEach(el => { - const idx = parseInt(el.dataset.idx || '0'); - // Would need source tracking - }); - - const btn = event?.target; - const origText = btn ? btn.textContent : ''; - if (btn) { btn.disabled = true; btn.textContent = '⏳ Đang tạo preview...'; } - - try { - const resp = await fetch('/api/personal_post/preview', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - opinion: opinion, - selected_topics: selectedTopics, - selected_sources: selectedSources - }) - }); - const data = await resp.json(); - if (!resp.ok || data.error) throw new Error(data.error || 'Lỗi tạo preview'); - - showPersonalPostModal(data.preview, opinion, selectedTopics, selectedSources); - } catch (e) { - toast('❌ ' + e.message); - } finally { - if (btn) { btn.disabled = false; btn.textContent = origText; } - } -} - -function showPersonalPostModal(preview, originalOpinion, selectedTopics, selectedSources) { - // Remove existing modal - const existing = document.getElementById('personal-post-modal'); - if (existing) existing.remove(); - - const modal = document.createElement('div'); - modal.id = 'personal-post-modal'; - modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.9);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto'; - - // Each slide renders EXACTLY like the designer's final PNG (same ratio, - // same bg draw, same text draw) — preview = pixel-identical to wall post image. - const slidesHtml = (preview.slides || []).map((s, i) => { - const ratio = {w:3, h:4}; // preview always 3:4 (same as designer final) - const slideStyle = 'width:100%;max-width:280px;margin:0 auto;display:block;border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.5)'; - return '
' - + '
Slide ' + (i+1) + '
' - + '' - + '' - + '
'; - }).join(''); - - // Background image source: uploaded data-URL (set later) or slide.image / first source image. - // We keep a small state object so text edits re-render live. - window._pvState = { slides: (preview.slides||[]).map(function(s,i){ - var bg = s.image || (preview.images && preview.images[0]) || ''; - return { text: s.text||'', bg: bg }; - }), ratio: 3/4, layout: 'solid', filter: 'none', glow: 'white', pos: 'bottom', color: '#ffffff' }; - - const sourcesHtml = (preview.sources || []).map((s, i) => { - const imgSrc = (preview.images && preview.images[i+1]) ? preview.images[i+1] : ''; - return '
' - + '
' - + (imgSrc ? '' : '') - + '
' - + '
' + (s.title || '') + '
' - + '' - + '
'; - }).join(''); - - modal.innerHTML = '
' - + '
' - + '

📝 Xem trước bài quan điểm cá nhân

' - + '' - + '
' - + '
' - + '' - + '' - + '
' - + '
' - + '' - + '' - + '
' - + '
' - + '' - + '
' - + '' - + '' - + '
' - + '
' + slidesHtml + '
' - + '
' - + '
' - + '' - + '
' - + (sourcesHtml || '
Không có nguồn tin
') - + '
' - + '
' - + '' - + '' - + '
'; - - document.body.appendChild(modal); - - // draw every slide preview canvas - previewRedrawAllSlides(); - - // text edits re-render live - modal.querySelectorAll('.preview-slide-text').forEach(ta => { - ta.addEventListener('input', function(){ - const idx = parseInt(this.dataset.idx || '0', 10); - if(window._pvState && window._pvState.slides[idx]) window._pvState.slides[idx].text = this.value; - previewDrawSlide(idx); - }); - }); - - // Store preview data for publishing - window._personalPostPreview = preview; - window._personalPostOpinion = originalOpinion; -} - -/* Live-edit slide preview canvas (exact same rendering style as designer output) */ -function previewDrawSlide(idx){ - const canvas = document.querySelector('.preview-slide-canvas[data-idx="'+idx+'"]'); - if(!canvas || !window._pvState) return; - const st = window._pvState.slides[idx]; - if(!st) return; - const W = 600, H = Math.round(W * window._pvState.ratio); // 3:4 -> 800 - canvas.width = W; canvas.height = H; - const ctx = canvas.getContext('2d'); - const opts = { text: st.text, pos: window._pvState.pos, glow: window._pvState.glow, - color: window._pvState.color, layout: window._pvState.layout, - filter: window._pvState.filter, bgUrl: st.bg }; - function draw(img){ - // base dark - ctx.fillStyle='#141414'; ctx.fillRect(0,0,W,H); - if(img){ - ctx.save(); - let f=''; - if(opts.filter==='grayscale') f='grayscale(1)'; - else if(opts.filter==='sepia') f='sepia(0.85)'; - else if(opts.filter==='saturate') f='saturate(2.4)'; - else if(opts.filter==='warm') f='sepia(0.45) saturate(1.5) hue-rotate(-15deg)'; - else if(opts.filter==='cool') f='saturate(1.2) hue-rotate(15deg) brightness(1.05)'; - else if(opts.filter==='invert') f='invert(1)'; - else if(opts.filter==='noir') f='grayscale(1) contrast(1.6) brightness(0.9)'; - const iw=img.naturalWidth||1, ih=img.naturalHeight||1; - const scale=Math.max(W/iw, H/ih); - const dw=iw*scale, dh=ih*scale; - ctx.drawImage(img,0,0,iw,ih,(W-dw)/2,(H-dh)/2,dw,dh); - ctx.filter='none'; - ctx.restore(); - } - // solid overlay like designer - ctx.fillStyle='rgba(0,0,0,0.6)'; ctx.fillRect(0,0,W,H); - drawPreviewText(ctx,W,H,opts); - } - const bgSrc = (typeof _proxyImg==='function') ? _proxyImg(st.bg||'') : (st.bg || ''); - if(bgSrc){ - const im = new Image(); im.crossOrigin='anonymous'; - im.onload = function(){ draw(im); }; - im.onerror = function(){ draw(null); }; - im.src = bgSrc; - } else draw(null); -} -function drawPreviewText(ctx,W,H,opts){ - const text = opts.text || ''; - if(!text.trim()) return; - const fs = Math.min(52, Math.round(W*0.09)); - ctx.font = 'bold '+fs+'px "Segoe UI","Arial","Noto Sans",sans-serif'; - ctx.textAlign='center'; - const lines=[]; let line=''; - const maxW=Math.round(W*0.82); - text.split(' ').forEach(w=>{ - const test = line? line+' '+w : w; - if(ctx.measureText(test).width>maxW && line){ lines.push(line.trim()); line=w; } else { line=test; } - }); - if(line) lines.push(line.trim()); - const lh=Math.round(fs*1.25); - const blockH=lines.length*lh; - let y; - if(opts.pos==='top') y=Math.round(H*0.14)+lh/2; - else if(opts.pos==='bottom') y=Math.round(H*0.88)-blockH+lh/2; - else y=Math.round(H/2)-blockH/2+lh/2; - if(opts.glow==='white'){ ctx.shadowColor='rgba(255,255,255,0.95)'; ctx.shadowBlur=Math.max(8,fs*0.5); } - else if(opts.glow==='color'){ ctx.shadowColor=opts.color; ctx.shadowBlur=Math.max(10,fs*0.6); } - else if(opts.glow==='neon'){ ctx.shadowColor='#00ffff'; ctx.shadowBlur=Math.max(16,fs*0.9); } - ctx.fillStyle=opts.color; - lines.forEach((l,li)=>{ ctx.fillText(l, W/2, y+li*lh); }); - ctx.shadowBlur=0; -} -function previewRedrawAllSlides(){ - if(!window._pvState) return; - window._pvState.slides.forEach(function(_, i){ previewDrawSlide(i); }); -} -function openPreviewDesigner(){ - // opens the real slide designer on the FIRST preview slide as a background. - // The designer modal already renders canvas + uploads PNGs; we reuse it by - // temporarily creating a wall-post-like object from the preview slides. - if(!window._personalPostPreview || !window._pvState) return; - const slides = window._pvState.slides.map(function(s,i){ - return { text: s.text, image: s.bg, index: i+1 }; - }); - const fakePost = { - id: 'preview-fake', title: document.getElementById('preview-title')?.value || 'Bài quan điểm', - slides: slides, kind: 'personal_opinion', img: slides[0]?.image||'', url: '', video: '' - }; - if(typeof openSlideDesigner === 'function'){ - // designer expects index into _wallPosts; temporarily append so designer works - const existed = _wallPosts && _wallPosts.some(p => p.id === 'preview-fake'); - if(!existed && Array.isArray(_wallPosts)) _wallPosts.unshift(fakePost); - const idx = _wallPosts.findIndex(p => p.id === 'preview-fake'); - openSlideDesigner(idx >= 0 ? idx : 0); - // the fake post is only a designer context; the designer's own save posts - // the designed slides directly to the wall. Remove the fake entry on close. - setTimeout(function(){ - const ov = document.getElementById('slide-designer-overlay'); - if(!ov && Array.isArray(_wallPosts)){ - _wallPosts = _wallPosts.filter(p => p.id !== 'preview-fake'); - } - }, 30000); - } else { - toast('Không có công cụ thiết kế!'); - } -} - -function toggleSourceSelection(el, idx) { - const checkbox = el.querySelector('.source-checkbox'); - checkbox.checked = !checkbox.checked; - el.style.border = checkbox.checked ? '1px solid #2d8659' : '1px solid transparent'; - el.style.background = checkbox.checked ? '#1a2a1f' : '#202020'; -} - -async function publishPersonalPostFromModal() { - const title = document.getElementById('preview-title')?.value.trim(); - if (!title) { - alert('Vui lòng nhập tiêu đề'); - return; - } - - // Collect edited slides (text + designed/bg image from _pvState) - const slides = []; - if (window._pvState && window._pvState.slides) { - window._pvState.slides.forEach((s, i) => { - const text = (s.text || '').trim(); - if (text) slides.push({ text, image: s.bg || '', index: slides.length + 1 }); - }); - } else { - document.querySelectorAll('.preview-slide-text').forEach(ta => { - const text = ta.value.trim(); - if (text) slides.push({ text, image: '', index: slides.length + 1 }); - }); - } - - // Collect selected sources - const sources = []; - document.querySelectorAll('[data-source-idx]').forEach((el, i) => { - const checkbox = el.querySelector('.source-checkbox'); - if (checkbox.checked && window._personalPostPreview?.sources?.[i]) { - sources.push(window._personalPostPreview.sources[i]); - } - }); - - const btn = event.target; - const origText = btn.textContent; - btn.disabled = true; - btn.textContent = '⏳ Đang đăng...'; - - try { - const resp = await fetch('/api/personal_post', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - opinion: window._personalPostOpinion, - selected_topics: [], - selected_sources: sources, - custom_title: title, - custom_slides: slides - }) - }); - const data = await resp.json(); - if (!resp.ok || data.error) throw new Error(data.error || 'Lỗi đăng bài'); - - toast('✅ Đã đăng bài quan điểm lên Tường AI!'); - - // Prepend to wall - if (data.post && typeof prependWallPost === 'function') { - prependWallPost(data.post); - } - - // Close modal - document.getElementById('personal-post-modal')?.remove(); - - // Clear opinion input - document.getElementById('opinion-input').value = ''; - } catch (e) { - toast('❌ ' + e.message); - } finally { - btn.disabled = false; - btn.textContent = origText; - } -} - diff --git a/app_v2_entry.py b/app_v2_entry.py index 55cc343428c94af08f72e075ab0dce8055c57a99..c3446120bc2c42979130b4c45820249687decf8d 100644 --- a/app_v2_entry.py +++ b/app_v2_entry.py @@ -12,11 +12,6 @@ try: except Exception as e: print(f"[WARN] ai_patch import failed: {e}") -try: - import ai_short_v2 # Short AI v2: TikTok music, uploaded audio/video/img, recreate from slides -except Exception as e: - print(f"[WARN] ai_short_v2 import failed: {e}") - from fastapi.responses import HTMLResponse, JSONResponse, FileResponse, Response from fastapi.staticfiles import StaticFiles from starlette.routing import Mount @@ -26,2800 +21,21 @@ from bs4 import BeautifulSoup import re, html as html_lib, json, threading, time, uuid from concurrent.futures import ThreadPoolExecutor, as_completed from urllib.parse import quote -import asyncio HL_LEAGUES['friendly'] = {"path": "giai-khac/friendly", "name": "Giao hữu", "emoji": "🤝"} STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static') -SPACE = "https://bep40-vnews.hf.space" # SEO URL base for share links app.router.routes=[r for r in app.router.routes if not(getattr(r,'path',None)=='/' and hasattr(r,'methods') and 'GET' in getattr(r,'methods',set()))] app.routes[:]=[r for r in app.routes if not isinstance(r, Mount)] app.router.routes=[r for r in app.router.routes if not isinstance(r, Mount)] -def _clean(s): return re.sub(r"\s+"," ",html_lib.unescape(str(s or""))).strip() - -def _ensure_sentence_complete(text): - """Ensure text ends with complete sentence (ends with . ! or ?). Trim if cut mid-sentence.""" - text = _clean(text) - if not text: - return text - # Find last sentence ending - for end_char in ['.', '!', '?']: - last_pos = text.rfind(end_char) - if last_pos > len(text) * 0.5: # Keep if ending is in latter half - return text[:last_pos + 1].strip() - # If no ending found, try to find last complete sentence - sentences = re.split(r'(?<=[.!?])\s+', text) - complete = [s.strip() for s in sentences if s.strip() and len(s.strip()) > 20] - if complete[:-1]: # Return all but last incomplete - return ' '.join(complete[:-1]) - return text[:150] + '.' if len(text) > 150 else text - -# Cache for match details (5 min TTL) -_match_cache = {} - -# === FAST BONGDA PROXY ENDPOINT === -def _get_match_detail(event_id, slug=None): - headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept": "text/html", "Referer": "https://bongda.com.vn/"} - if slug: - url = f"https://bongda.com.vn/tran-dau/{event_id}/centre/{slug}" - else: - url = f"https://bongda.com.vn/tran-dau/{event_id}" - resp = req.get(url, headers=headers, timeout=15, allow_redirects=True) - if resp.status_code != 200: - return None - soup = BeautifulSoup(resp.text, 'html.parser') - result = {"event_id": event_id, "found": False, "sections": []} - info = {} - tel = soup.select_one('.teams') - if tel: - he = tel.select_one('.team.home') - if he: - p_tags = [p for p in he.select('p') if not p.get('class') or 'logo' not in p.get('class', [])] - if p_tags: info['home_team'] = _clean(p_tags[0].get_text()) - lo = he.select_one('img') - if lo: info['home_logo'] = lo.get('src', '') - ae = tel.select_one('.team.away') - if ae: - p_tags = ae.select('p') - team_ps = [p for p in p_tags if not p.get('class') or 'logo' not in p.get('class', [])] - if team_ps: info['away_team'] = _clean(team_ps[-1].get_text()) - lo = ae.select_one('img') - if lo: info['away_logo'] = lo.get('src', '') - sc = tel.select_one('.score') - if sc: - parts = [_clean(p.get_text()) for p in sc.select('p')] - if len(parts) >= 2: info['score'] = f"{parts[0]} - {parts[1]}" - lb = sc.select_one('.label') - if lb: info['status_label'] = _clean(lb.get_text()) - if info.get('home_team') and info.get('away_team'): - result['info'] = info - result['found'] = True - result['sections'].append('info') - events = [] - for ev in soup.select('.events .period .event'): - ev_cls = ' '.join(ev.get('class', [])) - ev_data = {'team': 'home' if 'home' in ev_cls else 'away', 'period': '', 'type': 'unknown', 'time': '', 'players': ''} - parent = ev.parent - if parent: - h2 = parent.find('h2') - if h2: ev_data['period'] = _clean(h2.get_text()) - if ev.select_one('[class*="goal"]'): ev_data['type'] = 'goal' - elif ev.select_one('[class*="redcard"]'): ev_data['type'] = 'redcard' - elif ev.select_one('[class*="yellowcard"]'): ev_data['type'] = 'yellowcard' - elif ev.select_one('[class*="substitution"]'): ev_data['type'] = 'substitution' - players_el = ev.select_one('.players') - if players_el: - pl_text = _clean(players_el.get_text(' ', strip=True)) - m = re.match(r"(\d+)'(.*)", pl_text) - if m: - ev_data['time'] = f"{m.group(1)}'" - ev_data['players'] = m.group(2) - else: - ev_data['players'] = pl_text - events.append(ev_data) - if events: - result['events'] = events - result['sections'].append('events') - pred = soup.select_one('.prediction-card') - if pred: - team_info = pred.select_one('.team-info') - if team_info: - teams = team_info.select('.team') - pred_data = {} - if len(teams) >= 2: - pred_data['home_name'] = _clean(teams[0].select_one('.team-name').get_text()) if teams[0].select_one('.team-name') else '' - pred_data['away_name'] = _clean(teams[1].select_one('.team-name').get_text()) if teams[1].select_one('.team-name') else '' - divider = team_info.select_one('.divider') - if divider: pred_data['result'] = _clean(divider.get_text()) - vc = pred.select_one('.vote-count') - if vc: pred_data['vote_count'] = _clean(vc.get_text()) - result['prediction'] = pred_data - recent = [] - ml = soup.select_one('.matches-list') - if ml: - for item in ml.select('.match-detail, .match-item, li'): - de = item.select_one('.date, .time') - le = item.select_one('.league') - he_item = item.select_one('.home, .team-home') - ae_item = item.select_one('.away, .team-away') - se = item.select_one('.score, .result') - if he_item or ae_item: - recent.append({'date': _clean(de.get_text()) if de else '', 'league': _clean(le.get_text()) if le else '', 'home': _clean(he_item.get_text()) if he_item else '', 'away': _clean(ae_item.get_text()) if ae_item else '', 'score': _clean(se.get_text()) if se else 'vs'}) - if recent: - result['recent_matches'] = recent - result['sections'].append('recent') - try: - api_h = {"User-Agent": "Mozilla/5.0", "Accept": "application/json", "X-Requested-With": "XMLHttpRequest", "Referer": "https://bongda.com.vn/"} - ar = req.get(f"https://bongda.com.vn/api/fixtures/h2h-stats?event_id={event_id}", headers=api_h, timeout=10) - if ar.status_code == 200: - ad = ar.json() - if ad.get('status') == 'success' and ad.get('html'): - asp = BeautifulSoup(ad['html'], 'html.parser') - ast = {} - for row in asp.select('li, tr'): - cells = row.select('td, span, p') - if len(cells) >= 3: - lb = _clean(cells[0].get_text()) - if lb: ast[lb] = {'home': _clean(cells[1].get_text()), 'away': _clean(cells[2].get_text())} - if ast: - result['h2h_stats_parsed'] = ast - result['sections'].append('h2h_stats') - except: pass - return result - -@app.get('/api/proxy/bongda') -def proxy_bongda(event_id: int = Query(default=None), slug: str = Query(default=None)): - if event_id is None: - return JSONResponse({'error': 'event_id required'}, status_code=400) - cache_key = f"{event_id}_{slug}" - now = time.time() - cached = _match_cache.get(cache_key) - if cached and now - cached.get('_ts', 0) < 300: - return JSONResponse(cached) - try: - result = _get_match_detail(event_id, slug) - if result: - result['_ts'] = now - _match_cache[cache_key] = result - return JSONResponse(result) - except Exception as e: - err = {"event_id": event_id, "found": False, "error": str(e), "_ts": now} - _match_cache[cache_key] = err - return JSONResponse(err) - return JSONResponse({"event_id": event_id, "found": False}) - -@app.get('/api/match/{event_id}/detail') -def api_match_detail(event_id: int, url: str = Query(default=None)): - slug = None - if url: - m = re.match(r'.+/tran-dau/\d+/(?:centre|preview)/(.+)', url) - if m: - slug = m.group(1) - cache_key = f"{event_id}_{slug or ''}" - now = time.time() - cached = _match_cache.get(cache_key) - if cached and now - cached.get('_ts', 0) < 300: - return JSONResponse(cached) - try: - if not slug: - try: - home_r = req.get("https://bongda.com.vn/", headers={"User-Agent": "Mozilla/5.0"}, timeout=10) - if home_r.status_code == 200: - home_soup = BeautifulSoup(home_r.text, 'html.parser') - for a in home_soup.select(f'a[href*="/tran-dau/{event_id}/"]'): - href = a.get('href', '') - m = re.match(r'/tran-dau/\d+/(?:centre|preview)/(.+)', href) - if m: - slug = m.group(1) - cache_key = f"{event_id}_{slug}" - break - except: pass - result = _get_match_detail(event_id, slug) - if result: - result['_ts'] = now - _match_cache[cache_key] = result - return JSONResponse(result) - except Exception as e: - err = {"event_id": event_id, "found": False, "error": str(e), "_ts": now} - _match_cache[cache_key] = err - return JSONResponse(err) - return JSONResponse({"event_id": event_id, "found": False}) - -_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 việt nam 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()) - -def _has_kw(topic,title): - tl=topic.lower();tt=(title or'').lower() - if tl in tt:return True - words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',tl) if len(w)>2 and w.lower() not in _STOP] - if not words:return True - return any(w in tt for w in words) - -def _s_vnexpress(topic,limit=8): - items=[] - try: - r=req.get(f"https://timkiem.vnexpress.net/?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml') - for art in soup.select('article.item-news')[:limit]: - a=art.select_one('h2 a, h3 a') - if a and a.get('href'): - t=_clean(a.get('title','') or a.get_text(strip=True)) - if _has_kw(topic,t):items.append({'title':t,'url':a['href'],'via':'VnExpress'}) - except:pass - return items - -def _s_dantri(topic,limit=8): - items=[] - try: - r=req.get(f"https://dantri.com.vn/tim-kiem/{quote(topic)}.htm",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml') - for a in soup.select('h3 a[href], .article-title a[href]')[:limit*2]: - t=_clean(a.get_text(strip=True));href=a.get('href','') - if t and len(t)>15 and _has_kw(topic,t): - if not href.startswith('http'):href='https://dantri.com.vn'+href - items.append({'title':t,'url':href,'via':'Dân Trí'}) - if len(items)>=limit:break - except:pass - return items - -def _s_vietnamnet(topic,limit=6): - items=[] - try: - r=req.get(f"https://vietnamnet.vn/tim-kiem?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml') - for a in soup.select('h3 a[href], .vnn-title a')[:limit*2]: - t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','') - if t and len(t)>15 and _has_kw(topic,t): - if not href.startswith('http'):href='https://vietnamnet.vn'+href - items.append({'title':t,'url':href,'via':'VietNamNet'}) - if len(items)>=limit:break - except:pass - return items - -def _s_bongda(topic,limit=5): - items=[] - try: - r=req.get(f"https://bongda.com.vn/tim-kiem.html?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=8);soup=BeautifulSoup(r.text,'lxml') - for a in soup.select('h3 a[href], .title a[href]')[:limit*2]: - t=_clean(a.get_text(strip=True));href=a.get('href','') - if t and len(t)>15 and _has_kw(topic,t): - if not href.startswith('http'):href='https://bongda.com.vn'+href - items.append({'title':t,'url':href,'via':'Bóng Đá'}) - if len(items)>=limit:break - except:pass - return items - -def _s_genk(topic,limit=5): - items=[] - try: - r=req.get(f"https://genk.vn/tim-kiem?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=8);soup=BeautifulSoup(r.text,'lxml') - for a in soup.select('a[href$=".chn"]')[:limit*3]: - t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','') - if t and len(t)>15 and _has_kw(topic,t): - if href.startswith('/'):href='https://genk.vn'+href - items.append({'title':t,'url':href,'via':'GenK'}) - if len(items)>=limit:break - except:pass - return items - -def _s_thanhnien(topic,limit=6): - items=[] - try: - r=req.get(f"https://thanhnien.vn/tim-kiem?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml') - for a in soup.select('h3 a[href], .box-title a')[:limit*2]: - t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','') - if t and len(t)>15 and _has_kw(topic,t): - if not href.startswith('http'):href='https://thanhnien.vn'+href - items.append({'title':t,'url':href,'via':'Thanh Niên'}) - if len(items)>=limit:break - except:pass - return items - -def _s_tuoitre(topic,limit=6): - items=[] - try: - r=req.get(f"https://tuoitre.vn/tim-kiem.htm?keywords={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml') - for a in soup.select('h3 a[href], .box-title-text a')[:limit*2]: - t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','') - if t and len(t)>15 and _has_kw(topic,t): - if not href.startswith('http'):href='https://tuoitre.vn'+href - items.append({'title':t,'url':href,'via':'Tuổi Trẻ'}) - if len(items)>=limit:break - except:pass - return items - -def _s_thethaovanhoa(topic,limit=5): - items=[] - try: - r=req.get(f"https://thethaovanhoa.vn/tim-kiem.htm?keyword={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=8);soup=BeautifulSoup(r.text,'lxml') - for a in soup.select('h3 a[href], .title a[href]')[:limit*2]: - t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','') - if t and len(t)>15 and _has_kw(topic,t): - if not href.startswith('http'):href='https://thethaovanhoa.vn'+href - items.append({'title':t,'url':href,'via':'TT&VH'}) - if len(items)>=limit:break - except:pass - return items - -def _search_all(topic,limit=36): - results={} - with ThreadPoolExecutor(8) as ex: - futs={ex.submit(_s_vnexpress,topic,8):'vne',ex.submit(_s_dantri,topic,8):'dt',ex.submit(_s_vietnamnet,topic,6):'vnn',ex.submit(_s_bongda,topic,5):'bd',ex.submit(_s_genk,topic,5):'gk',ex.submit(_s_thanhnien,topic,6):'tn',ex.submit(_s_tuoitre,topic,6):'tt',ex.submit(_s_thethaovanhoa,topic,5):'tvh'} - for f in as_completed(futs,timeout=14): - try:results[futs[f]]=f.result() - except:results[futs[f]]=[] - srcs=list(results.values());out=[];seen=set() - for i in range(max((len(s) for s in srcs),default=0)): - for s in srcs: - if i= 2: - seen_imgs = set() - for child in el.find_all(['p','h2','h3','figure','img'], recursive=True): - if child.name == 'p': - t = child.get_text(strip=True) - if t and len(t) > 15: - body.append({'type': 'p', 'text': t}) - elif child.name in ('h2','h3'): - t = child.get_text(strip=True) - if t: - body.append({'type': 'heading', 'text': t}) - elif child.name in ('figure','img'): - im = child if child.name == 'img' else child.find('img') - if im: - src = im.get('data-src') or im.get('src') or im.get('data-lazy') or '' - if src and 'base64' not in src and src not in seen_imgs: - seen_imgs.add(src) - if src.startswith('//'): src = 'https:' + src - body.append({'type': 'img', 'src': src}) - if child.name == 'figure': - cap = child.find('figcaption') - if cap: - ct = cap.get_text(strip=True) - if ct: body.append({'type': 'p', 'text': ct}) - if len(body) >= 2: - return {'title': _clean(title), 'summary': _clean(summary), 'og_image': og_img, - 'body': body[:50], 'source': domain, 'url': url} - if title and (summary or og_img): - fallback = [] - if og_img: fallback.append({'type': 'img', 'src': og_img}) - if summary: fallback.append({'type': 'p', 'text': summary}) - if fallback: - return {'title': _clean(title), 'summary': _clean(summary), 'og_image': og_img, - 'body': fallback, 'source': domain, 'url': url, 'fallback': True} - if title: - return {'title': _clean(title), 'summary': '', 'og_image': '', - 'body': [{'type': 'p', 'text': 'Nội dung đang được tải...'}], - 'source': domain, 'url': url, 'fallback': True} - break - except Exception: - continue - return None - -@app.get('/api/article') -def api_article_v2(url: str = Query(...)): - from urllib.parse import unquote - safe_url = unquote(url) - try: - now = time.time() - cached = _article_cache.get(safe_url) - if cached and now - cached['t'] < _article_cache_ttl: - resp = JSONResponse(cached['d']) - resp.headers["Cache-Control"] = "public, max-age=1800" - return resp - data = _scrape_article_fast(safe_url) - if data and data.get('body'): - _article_cache[safe_url] = {'d': data, 't': now} - resp = JSONResponse(data) - resp.headers["Cache-Control"] = "public, max-age=1800" - return resp - result = {'error': 'Không đọc được', 'url': safe_url} - resp = JSONResponse(result) - resp.headers["Cache-Control"] = "public, max-age=60" - return resp - except Exception as e: - return JSONResponse({'error': f'Server error: {str(e)[:100]}', 'url': safe_url}, status_code=200) - -_hot_cache={'t':0,'d':[]} -def _parse_feed(feed_url): - try: - r=req.get(feed_url,headers={'User-Agent':'Mozilla/5.0'},timeout=4) - r.encoding='utf-8';soup=BeautifulSoup(r.text,'xml') - out=[] - for item in soup.find_all('item')[:12]: - t=item.find('title') - title=_clean(t.get_text() if t else '') - if title: out.append(title) - return out - except Exception: - return [] -def _get_hot_topics(): - now=time.time() - if _hot_cache['d'] and now-_hot_cache['t']<600:return _hot_cache['d'] - feeds=['https://vnexpress.net/rss/tin-moi-nhat.rss','https://dantri.com.vn/rss/home.rss','https://vietnamnet.vn/rss/tin-moi-nhat.rss','https://thanhnien.vn/rss/home.rss','https://tuoitre.vn/rss/tin-moi-nhat.rss','https://genk.vn/rss','https://vnexpress.net/rss/the-thao.rss','https://thethaovanhoa.vn/rss/tin-nong.rss'] - titles=[] - with ThreadPoolExecutor(8) as ex: - futs=[ex.submit(_parse_feed,f) for f in feeds] - for f in as_completed(futs,timeout=5): - try: - for t in f.result(): titles.append(t) - except Exception: pass - freq={};display={} - for title in titles: - if not title: continue - title=re.sub(r'\s*[-|].*$','',title) - words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',title) if len(w)>2 and w.lower() not in _STOP] - if len(words)<2:continue - for n in(3,4,2): - for i in range(max(0,len(words)-n+1)): - phrase=' '.join(words[i:i+n]) - if 8<=len(phrase)<=45:key=phrase.lower();freq[key]=freq.get(key,0)+1;display[key]=phrase - ranked=sorted(freq.items(),key=lambda x:x[1],reverse=True);topics=[];seen=set() - for key,count in ranked: - 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) - if is_dup:continue - seen.add(key);topics.append({'label':'#'+re.sub(r'\s+','',display[key].title()),'topic':display[key],'count':count}) - if len(topics)>=20:break - 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']: - if len(topics)>=24:break - if not any(kw.lower() in s for s in seen):topics.append({'label':'#'+re.sub(r'\s+','',kw.title()),'topic':kw,'count':0}) - _hot_cache.update({'t':now,'d':topics[:24]});return topics[:24] - -@app.get('/api/hot_topics') -def api_hot_topics(): - resp = JSONResponse({'topics':_get_hot_topics()}) - resp.headers["Cache-Control"] = "public, max-age=120" - return resp -@app.get('/') -async def serve_index(): - p=os.path.join(STATIC_DIR,'index_v2.html') - if os.path.exists(p):return FileResponse(p,media_type='text/html') - return HTMLResponse('

VNEWS

') -@app.get('/api/hashtag/sources') -def _ht(topic:str=Query(...),page:int=Query(default=0)): - items=_search_all(topic,36);per_page=8;start=page*per_page;end=start+per_page - return JSONResponse({'sources':items[start:end],'topic':topic,'page':page,'has_more':end - - - - -{_clean(safe_title)} - - - - - - - -''' - for s in slides: - img_src = s.get('image', '') - if img_src and ('cdnphoto.dantri' in img_src or 'refooty' in img_src or 'vnexpress' in img_src or 'vcdn' in img_src): - img_tag = f'' - else: - img_tag = f'' if img_src else '' - h += f'
Slide {s.get("index",1)}/{len(slides)}
{img_tag}

{_clean(s.get("text",""))}

' - h += '' - return HTMLResponse(h) - -def _render_video_page(post, safe_title, safe_img, safe_url): - video_url = post.get('video', '') - # Use text for description if available - description = _clean((post.get('text') or '')[:200]) or "Tin tức tóm tắt, AI rewrite, World Cup 2026" - - # Build canonical URL preserving original query format if url was provided - if safe_url and safe_url != '/': - canonical_url = f"{SPACE}/s?url={quote(safe_url)}&title={quote(safe_title[:100])}" - else: - canonical_url = f"{SPACE}/s?post_id={post.get('id') or ''}" - - h = f''' - - - - -{_clean(safe_title)} - - - - - - - - - - -
- -
{_clean(safe_title)}
-
-''' - return HTMLResponse(h) - -@app.get('/s/{slug}') -async def _sh_slug(slug: str, request: Request, url: str = '', title: str = '', img: str = ''): - """SEO-friendly share endpoint with slug in URL path. - Shows slide content when slug matches a wall post ID, otherwise redirects. - """ - safe_title = _clean(title) if title else 'VNEWS - Tin tức' - safe_img = _clean(img) if img else '' - safe_url = _clean(url) if url else '/' - - # Try to find post by slug (post ID) - post = None - try: - if slug and len(slug) > 5: # Likely a post ID - posts = _load_wall_posts() - for p in posts: - if p.get('id') == slug: - post = p - safe_title = p.get('title', safe_title) or safe_title - safe_img = p.get('img', safe_img) or safe_img - safe_url = p.get('url', safe_url) or safe_url - break - except: - pass - - if post and post.get('slides'): - return _render_slides_page(post, safe_title, safe_img, safe_url) - - if post and post.get('video'): - return _render_video_page(post, safe_title, safe_img, safe_url) - - # Otherwise redirect - return HTMLResponse(f''' - - - - -{_clean(safe_title)} - - - - - - -''') - -@app.get('/s') -async def _sh(url:str='',title:str='',img:str='',post_id:str=''): - safe_title = _clean(title) if title else 'VNEWS - Tin tức' - safe_img = _clean(img) if img else '' - safe_url = _clean(url) if url else '/' - - # Try to find wall post by post_id or URL (prioritize posts with slides/video) - post = None - try: - posts = _load_wall_posts() - if post_id: - for p in posts: - if p.get('id') == post_id: - post = p - safe_title = p.get('title', safe_title) or safe_title - safe_img = p.get('img', safe_img) or safe_img - safe_url = p.get('url', safe_url) or safe_url - break - elif url: - # Find matching URL - prioritize posts with slides or video - for p in posts: - if p.get('url') == url and p.get('slides'): - post = p - safe_title = p.get('title', safe_title) or safe_title - safe_img = p.get('img', safe_img) or safe_img - safe_url = p.get('url', safe_url) or safe_url - break - if not post: - # Fallback: find any matching URL - for p in posts: - if p.get('url') == url: - post = p - safe_title = p.get('title', safe_title) or safe_title - safe_img = p.get('img', safe_img) or safe_img - safe_url = p.get('url', safe_url) or safe_url - break - except: - pass - - if post and post.get('slides'): - return _render_slides_page(post, safe_title, safe_img, safe_url) - - if post and post.get('video'): - return _render_video_page(post, safe_title, safe_img, safe_url) - - # Fallback: redirect to original URL - return HTMLResponse(f''' - - - - -{safe_title} - - - - - - -''') - -from wc2026_scraper import scrape_summary,scrape_fixtures,scrape_standings,scrape_stats,scrape_wc_news,scrape_road_to_wc,get_wc2026_all,scrape_history,scrape_h2h,scrape_lineups,scrape_match_detail - -_xlb_cache = {} -_xlb_lock = threading.Lock() - -def _xlb_scrape(path): - url = f"https://xemlaibongda.top/{path}" - r = req.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}, timeout=15, allow_redirects=True) - if r.status_code != 200: - return [] - soup = BeautifulSoup(r.text, 'lxml') - vids = [] - seen = set() - for a in soup.select('a[href*="/video/"]'): - href = a.get('href', '') - if not href or href in seen: - continue - seen.add(href) - if not href.startswith('http'): - href = 'https://xemlaibongda.top' + href - img = a.select_one('img') - p = a.parent - for _ in range(4): - if img: - break - if p: - img = p.select_one('img') - p = p.parent - img_src = '' - if img: - img_src = img.get('data-src','') or img.get('src','') or img.get('data-lazy','') or img.get('data-original','') - if img_src.startswith('//'): - img_src = 'https:' + img_src - elif img_src.startswith('/'): - img_src = 'https://xemlaibongda.top' + img_src - title = '' - for sel in ['.title', 'h3', 'h2', '.name', '.post-title', '.entry-title', '.video-title']: - t = a.select_one(sel) - if t: - title = _clean(t.get_text()) - break - if not title: - title = _clean(a.get('title','')) - if not title: - img_alt = a.select_one('img') - if img_alt: - title = _clean(img_alt.get('alt','')) - if not title: - parent = a.parent - if parent: - pt = _clean(parent.get_text(' ',strip=True)) - if 5 < len(pt) < 120: - title = pt - if not title or len(title) < 3: - continue - vids.append({"link": href, "img": img_src, "title": title}) - if len(vids) >= 30: - break - return vids - -@app.get('/api/proxy/xlb') -def proxy_xlb(path: str = Query(default="")): - now = time.time() - cache_key = f"xlb:{path}" - with _xlb_lock: - cached = _xlb_cache.get(cache_key) - if cached and now - cached['t'] < 120: - return JSONResponse(cached['d']) - try: - vids = _xlb_scrape(path) - result = {"videos": vids, "count": len(vids)} - with _xlb_lock: - _xlb_cache[cache_key] = {'t': now, 'd': result} - return JSONResponse(result) - except Exception as e: - return JSONResponse({"videos": [], "count": 0, "error": str(e)}, status_code=500) - -@app.get('/api/wc2026') -def _w():return JSONResponse(get_wc2026_all()) -@app.get('/api/wc2026/fixtures') -def _wf():return JSONResponse(scrape_fixtures()) -@app.get('/api/wc2026/standings') -def _ws():return JSONResponse(scrape_standings()) -@app.get('/api/wc2026/stats') -def _wst():return JSONResponse(scrape_stats()) -@app.get('/api/wc2026/history') -def _whi():return JSONResponse(scrape_history()) -@app.get('/api/wc2026/news') -def _wn():return JSONResponse(scrape_wc_news()) -@app.get('/api/wc2026/road') -def _wr():return JSONResponse(scrape_road_to_wc()) -@app.get('/api/wc2026/h2h/{eid}') -def _wh2(eid:int):return JSONResponse(scrape_h2h(eid)) -@app.get('/api/wc2026/lineups/{eid}') -def _wl(eid:int):return JSONResponse(scrape_lineups(eid)) -@app.get('/api/wc2026/match/{eid}') -def _wm(eid:int):return JSONResponse(scrape_match_detail(eid)) - -DATA_DIR='/data' if os.path.isdir('/data') else os.path.join(os.path.dirname(os.path.abspath(__file__)),'data') -os.makedirs(DATA_DIR,exist_ok=True) -IF=os.path.join(DATA_DIR,'interactions_v2.json') -CF=os.path.join(DATA_DIR,'comments_v2.json') -WALL_FILE=os.path.join(DATA_DIR,'wall_posts.json') -WALL_VIDEO_DIR=os.path.join(DATA_DIR,'wall_videos') -os.makedirs(WALL_VIDEO_DIR,exist_ok=True) - -_il=threading.Lock();_cl=threading.Lock();_wl_lock=threading.Lock() -def _lj(p): - try: - if os.path.exists(p):return json.load(open(p,'r',encoding='utf-8')) - except:pass - return{} -def _sj(p,d): - try:open(p+'.tmp','w',encoding='utf-8').write(json.dumps(d,ensure_ascii=False));os.replace(p+'.tmp',p) - except:pass - -@app.post('/api/v2/interact') -async def _int(request:Request): - b=await request.json();v=str(b.get('id','')).strip();t=str(b.get('type','')).strip() - if not v or t not in('view','like'):return JSONResponse({'error':'x'},status_code=400) - with _il:db=_lj(IF);db.setdefault(v,{'views':0,'likes':0,'comments':0});db[v][t+'s']+=1;_sj(IF,db);return JSONResponse(db[v]) - -@app.get('/api/v2/interactions') -def _gi(id:str=Query(...)): - with _il:return JSONResponse(_lj(IF).get(id.strip(),{'views':0,'likes':0,'comments':0})) - -@app.get('/api/v2/comments') -def _gc(id:str=Query(...)): - with _cl:return JSONResponse({'comments':_lj(CF).get(id.strip(),[])}) - -@app.post('/api/v2/comment') -async def _pc(request:Request): - b=await request.json();v=str(b.get('id','')).strip();tx=str(b.get('text','')).strip()[:500] - if not v or not tx:return JSONResponse({'error':'x'},status_code=400) - c={'text':tx,'time':time.strftime('%H:%M %d/%m',time.localtime()),'ts':int(time.time())} - with _cl:db=_lj(CF);db.setdefault(v,[]);db[v].append(c);db[v]=db[v][-200:];_sj(CF,db);cms=db[v] - with _il:idb=_lj(IF);idb.setdefault(v,{'views':0,'likes':0,'comments':0});idb[v]['comments']=len(cms);_sj(IF,idb) - return JSONResponse({'comments':cms}) - -def _load_wall_posts(): - with _wl_lock: - posts = _lj(WALL_FILE) - if not isinstance(posts, list): - posts = [] - return posts - -def _save_wall_posts(posts): - with _wl_lock: - _sj(WALL_FILE, posts) - -def _post_has_valid_image(p): - """A wall post is considered to have a 'valid' (non-placeholder) image if - at least one of the following is a real, non-placeholder URL: - - p.img (main thumbnail) - - p.short_thumb (generated by Short AI / oEmbed fallback) - - p.images[] (fallback image list) - - p.slides[].image (designed slide images) - - Auto posts that failed metadata enrichment — e.g. pollinations.ai - AI-generated placeholder images, vnexpress logo placeholders, or empty/None - fields — are flagged as having NO valid image so they can be filtered out - of the wall (they show the wrong picture vs the original article).""" - PLACEHOLDER_MARKERS = ( - "pollinations.ai", # AI-generated editorial illustration placeholder - "logo_default.jpg", # vnexpress placeholder logo - "logo.png", - "/logo", - "placeholder", - "no-image", - "blank", - ) - - def _is_placeholder(url): - if not url or not isinstance(url, str): - return True - u = url.strip().lower() - if not u or u.startswith(("about:blank", "data:")): - return True - return any(m in u for m in PLACEHOLDER_MARKERS) - - def _is_real(url): - return bool(url) and not _is_placeholder(url) - - img = p.get("img") - if _is_real(img): - return True - thumb = p.get("short_thumb") - if _is_real(thumb): - return True - images = p.get("images") or [] - if any(_is_real(x) for x in images): - return True - slides = p.get("slides") or [] - if any(_is_real(s.get("image")) for s in slides if isinstance(s, dict)): - return True - return False - -def _post_has_slide_info(p): - """True if the post has usable slide/rewrite AI content: - - designed slides with text+image, OR - - a generated short video (/api/ai/short-file/) with a real thumbnail, OR - - an oEmbed iframe (YouTube/TikTok/Facebook embed) with a real thumbnail - (Short HOT fallback case — embeddable, viewable as a slide).""" - slides = p.get("slides") or [] - if any((s.get("image") or "").strip() and (s.get("text") or "").strip() for s in slides if isinstance(s, dict)): - return True - # Generated short video with a real thumbnail - vid = (p.get("video") or "").strip() - if vid and "api/ai/short-file/" in vid and (p.get("short_thumb") or "").strip(): - return True - # oEmbed iframe (YouTube/TikTok/FB) with a valid image -> viewable embed slide - if vid and ("youtube.com/embed" in vid or "tiktok.com/embed" in vid or - "facebook.com/plugins" in vid or "instagram.com" in vid or - "twitter.com" in vid or "x.com" in vid or "player.vimeo" in vid): - if _post_has_valid_image(p): - return True - return False - -def _is_auto_post(p): - """Auto-generated wall posts: Short HOT, oEmbed fallback, FPT auto, - slide-rewrite AI (auto_rewrite), topic auto-summary (topic_article), or - posts with no meaningful source / created by the AI pipeline.""" - kind = (p.get("kind") or "").strip().lower() - source = (p.get("source") or "").strip().lower() - return kind in ("hot_short", "slide_summary", "auto_rewrite", "topic_article", "summary") or \ - source in ("hot_short", "fptplay", "ai", "auto_rewrite", "topic_article") - -def _created_ts(p): - """Best-effort creation timestamp. Posts created by the AI pipeline often - store `created` as a millisecond epoch; some older posts (auto_rewrite) - omit it and instead embed the timestamp in the `id` (Unix ms). Fall back - to 0 so sorting never crashes.""" - for field in ("created", "ts"): - v = p.get(field) - if v is not None: - try: - return int(v) - except (ValueError, TypeError): - pass - # try to derive from id (numeric prefix = Unix ms timestamp) - pid = str(p.get("id", "")).strip() - if pid.isdigit() and len(pid) >= 12: - try: - return int(pid) - except (ValueError, TypeError): - pass - return 0 - -def _wall_posts_for_view(): - """Apply the user-facing wall filtering + sorting: - 1) Hide auto-generated posts that have a wrong/placeholder image (no - valid image at all — pollinations.ai, vnexpress logo, empty) or have - no slide-AI content (no slides / no short-video / no embed). These - are the 'bài đăng tự động bị sai ảnh / ko có thông tin slide AI' that - don't match the original article. This filter is VIEW-ONLY — it does - NOT delete from the persistent store. - 2) Sort newest-first by creation timestamp, mixing all sources (FPT, - slide rewrite AI, etc.) without source separation.""" - posts = _load_wall_posts() - if not posts: - return [] - filtered = [] - for p in posts: - if not isinstance(p, dict): - continue - if _is_auto_post(p) and not (_post_has_valid_image(p) and _post_has_slide_info(p)): - # auto post with a wrong/placeholder/missing image or no slide AI - # content -> hide from the wall (non-destructive) - continue - filtered.append(p) - filtered.sort(key=_created_ts, reverse=True) - return filtered - -@app.get("/api/ai/wall") -def api_ai_wall(): - return JSONResponse({"posts": _wall_posts_for_view()}) - - -# ===== YOUTUBE RSS FEED PROXY (avoids browser CORS) ===== -_YT_FEED_CACHE = {} -_YT_FEED_TTL = 600 # 10 minutes - - -def _fetch_youtube_rss_feed(channel_id: str = "UC4LvrpNXujjbGOS4RDvr41g"): - """Fetch & parse the YouTube RSS feed server-side. - - The browser cannot reach youtube.com directly (CORS / network block). - We try two sources in order: - 1) Direct feed XML (works if the server has outbound YouTube access) - 2) rss2json.com proxy (always works — it fetches the feed server-side) - Cached for _YT_FEED_TTL seconds.""" - now = time.time() - cached = _YT_FEED_CACHE.get(channel_id) - if cached and now - cached.get('_ts', 0) < _YT_FEED_TTL: - return cached.get('videos', []) - out = [] - try: - # Attempt 1: direct YouTube RSS - feed_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}" - try: - r = req.get(feed_url, headers=HEADERS, timeout=10) - if r.status_code == 200 and r.text.strip(): - soup = BeautifulSoup(r.text, 'xml') - for e in soup.find_all('entry'): - out.extend(_parse_yt_entry(e)) - except Exception as ex2: - print(f"[yt-feed] direct fetch failed, trying rss2json: {ex2}") - # Attempt 2: rss2json proxy (fallback / always) - if not out: - rss2json_url = f"https://api.rss2json.com/v1/api.json?rss_url={feed_url}" - r2 = req.get(rss2json_url, headers=HEADERS, timeout=15) - if r2.status_code == 200: - data = r2.json() - if data.get('status') == 'ok': - for item in data.get('items', []): - vid_m = re.search(r'([a-zA-Z0-9_-]{11})', item.get('id', '')) - if not vid_m: - continue - vid = vid_m.group(1) - title = item.get('title', 'Video') or 'Video' - # prefer the youtube watch URL, fallback to item link - link = item.get('link', '') - if '/watch' not in link: - link = f'https://www.youtube.com/watch?v={vid}' - # thumbnail: prefer media:thumbnail, fallback to youtube hqdefault - thumb = item.get('thumbnail', f'https://i.ytimg.com/vi/{vid}/hqdefault.jpg') - published = item.get('pubDate', '') - out.append({ - 'id': 'yt-' + vid, - 'videoId': vid, - 'title': title.strip()[:200], - 'link': link, - 'img': thumb, - 'published': published, - 'source': 'yt-feed' - }) - if out: - _YT_FEED_CACHE[channel_id] = {'_ts': now, 'videos': out} - return out - except Exception as ex: - print(f"[yt-feed] server error: {ex}") - return [] - - -def _parse_yt_entry(e): - """Parse a single YouTube RSS element into a video dict.""" - out = [] - try: - id_el = e.find('id') - if not id_el: - return out - vid_m = re.search(r'([a-zA-Z0-9_-]{11})', id_el.get_text('')) - if not vid_m: - return out - vid = vid_m.group(1) - title_el = e.find('title') - title = title_el.get_text('') if title_el else 'Video' - link_el = e.find('link', {'rel': 'alternate'}) - link = link_el.get('href') if link_el else f'https://www.youtube.com/watch?v={vid}' - pub_el = e.find('published') - published = pub_el.get_text('') if pub_el else '' - ns = {'media': 'http://search.yahoo.com/mrss/'} - thumb_el = e.find('media:thumbnail', ns) - thumb_url = thumb_el.get('url') if thumb_el else f'https://i.ytimg.com/vi/{vid}/hqdefault.jpg' - out.append({ - 'id': 'yt-' + vid, - 'videoId': vid, - 'title': title.strip()[:200], - 'link': link, - 'img': thumb_url, - 'published': published, - 'source': 'yt-feed' - }) - except Exception as ex: - print(f"[yt-feed] parse entry error: {ex}") - return out - - -@app.get("/api/yt/feed") -def api_yt_feed(channel_id: str = Query(default="UC4LvrpNXujjbGOS4RDvr41g")): - """Server-side YouTube RSS feed fetcher — avoids browser CORS. - Returns parsed feed videos as JSON for the Tường AI wall.""" - videos = _fetch_youtube_rss_feed(channel_id) - return JSONResponse({"videos": videos, "count": len(videos)}) -@app.post("/api/ai/short/{post_id}") -def api_ai_short(post_id: str): - """Generate a short video for a wall post. - Returns clear JSON error when video not available yet. - """ - post_id_s = str(post_id) - posts = _load_wall_posts() - if not isinstance(posts, list): - posts = [] - post = None - for p in posts: - pid = str(p.get("id", "")) - if pid == post_id_s or pid.startswith(post_id_s): - post = p - break - if not post: - return JSONResponse({"error": "Không tìm thấy bài viết", "post_id": post_id}, status_code=404) - if post.get("video"): - return JSONResponse({"video": post["video"], "post": post}) - return JSONResponse({"error": "Chưa có video cho bài này. Vui lòng upload video trước."}, status_code=409) - -@app.get('/api/wall') -def api_wall(): - posts = _wall_posts_for_view() - if not posts: - return JSONResponse({"posts": []}) - return JSONResponse({"posts": posts}) - -@app.post('/api/wall') -async def api_wall_post(request: Request): - content_type = request.headers.get('content-type', '') - if 'multipart/form-data' in content_type: - try: - form = await request.form() - except Exception as e: - return JSONResponse({"error": f"Form parse error: {str(e)}"}, status_code=400) - title = form.get('title', 'Video mới') or 'Video mới' - text = form.get('text', '') or '' - source = form.get('source', 'vtv_recorder') or 'vtv_recorder' - video_file = form.get('video') - post_id = str(uuid.uuid4())[:12] - video_url = None - if video_file and hasattr(video_file, 'filename') and video_file.filename: - fname = video_file.filename.lower() - if fname.endswith('.mp4'): - ext = '.mp4' - elif fname.endswith('.webm'): - ext = '.webm' - else: - ext = '.webm' - video_filename = f"wall_{post_id}{ext}" - video_path = os.path.join(WALL_VIDEO_DIR, video_filename) - try: - content = await video_file.read() - if not content: - return JSONResponse({"error": "Empty video file"}, status_code=400) - with open(video_path, 'wb') as f: - f.write(content) - file_size_mb = len(content) / 1024 / 1024 - if file_size_mb > 50: - os.remove(video_path) - return JSONResponse({"error": f"Video quá lớn ({file_size_mb:.1f}MB). Tối đa 50MB."}, status_code=400) - video_url = f"/api/wall/video/{video_filename}" - except Exception as e: - return JSONResponse({"error": f"Lỗi lưu video: {str(e)}"}, status_code=500) - post = { - "id": post_id, - "title": title[:200], - "text": text[:2000], - "source": source, - "video": video_url, - "img": None, - "images": [], - "created": int(time.time()), - "created_str": time.strftime('%H:%M %d/%m/%Y', time.localtime()), - } - posts = _load_wall_posts() - if not isinstance(posts, list): - posts = [] - posts.insert(0, post) - posts = posts[:200] - _save_wall_posts(posts) - return JSONResponse({"post": post, "ok": True}) - try: - body = await request.json() - except: - body = {} - title = body.get('title', 'Bài mới') or 'Bài mới' - text = body.get('text', '') or '' - img = body.get('img', None) - source = body.get('source', 'user') or 'user' - incoming_id = body.get('id') or '' # allow client to (re)publish an existing post by id - post_id = str(uuid.uuid4())[:12] - # Preserve slide-design post fields (slides, kind, url, images, video, voice, etc.) - # so that "Thiết kế ảnh" -> "Đăng lên Tường AI" keeps the selected slides. - slides = body.get('slides') - kind = body.get('kind') or 'user' - post_url = body.get('url') or '' - images = body.get('images') or [] - video = body.get('video') - voice = body.get('voice') or '' - emotion = body.get('emotion') or '' - language = body.get('language') or '' - post = { - "id": post_id, - "title": title[:200], - "text": text[:2000], - "source": source, - "video": video, - "img": img, - "images": images[:10], - "url": post_url, - "kind": kind, - "slides": slides if slides is not None else None, - "voice": voice, - "emotion": emotion, - "language": language, - "created": int(time.time()), - "created_str": time.strftime('%H:%M %d/%m/%Y', time.localtime()), - } - # Remove keys with None so the JSON stays lean (but keep structure) - post = {k: v for k, v in post.items() if v is not None} - posts = _load_wall_posts() - if not isinstance(posts, list): - posts = [] - # If the client re-publishes (e.g. designer "Lưu & Đăng lên Tường AI" sends - # the original post id), update that post in place instead of creating a - # duplicate. This keeps the homepage wall clean (no duplicate slide posts). - updated = False - if incoming_id: - for _p in posts: - if str(_p.get('id')) == str(incoming_id): - # Merge new fields into the existing post, but PRESERVE the - # original id (and created timestamp) so the post identity is - # stable and no duplicate is created. - preserve_id = _p.get('id') - preserve_created = _p.get('created') - preserve_created_str = _p.get('created_str') - _p.update(post) - _p['id'] = preserve_id - if preserve_created is not None: _p['created'] = preserve_created - if preserve_created_str is not None: _p['created_str'] = preserve_created_str - updated = True - post = _p # return the merged post (with stable id) to the client - break - if not updated: - posts.insert(0, post) - else: - # Move the updated post to the top so it re-appears at the top of the wall. - posts = [p for p in posts if str(p.get('id')) != str(incoming_id)] - posts.insert(0, post) - posts = posts[:200] - _save_wall_posts(posts) - return JSONResponse({"post": post, "ok": True}) - -@app.get('/api/wall/video/{filename}') -def api_wall_video(filename: str): - if '..' in filename or '/' in filename: - return Response(status_code=403) - video_path = os.path.join(WALL_VIDEO_DIR, filename) - if not os.path.exists(video_path): - return Response(status_code=404) - ext = os.path.splitext(filename)[1].lower() - media_type = 'video/mp4' if ext == '.mp4' else 'video/webm' - return FileResponse(video_path, media_type=media_type) - -WALL_IMG_DIR = os.path.join(DATA_DIR, 'wall_imgs') -os.makedirs(WALL_IMG_DIR, exist_ok=True) - -@app.post('/api/wall/img') -async def api_wall_img(request: Request): - """Upload a designed slide image (PNG) and return a served URL.""" - global WALL_IMG_DIR - try: - form = await request.form() - f = form.get('file') - if not f or not hasattr(f, 'filename') or not f.filename: - return JSONResponse({"error": "Thiếu file ảnh"}, status_code=400) - ext = os.path.splitext(f.filename)[1].lower() - if ext not in ('.png', '.jpg', '.jpeg', '.webp'): - ext = '.png' - img_id = str(uuid.uuid4())[:12] - fname = f"wallimg_{img_id}{ext}" - fpath = os.path.join(WALL_IMG_DIR, fname) - content = await f.read() - if not content: - return JSONResponse({"error": "File rỗng"}, status_code=400) - if len(content) > 15 * 1024 * 1024: - return JSONResponse({"error": "Ảnh quá lớn (>15MB)"}, status_code=400) - with open(fpath, 'wb') as fh: - fh.write(content) - post_id = (form.get('post_id') or '').strip() - if post_id: - posts = _load_wall_posts() - if isinstance(posts, list): - for p in posts: - if str(p.get('id')) == str(post_id): - p['img'] = f"/api/wall/img/{fname}" - break - _save_wall_posts(posts) - url = f"/api/wall/img/{fname}" - return JSONResponse({"ok": True, "url": url, "img_id": img_id}) - except Exception as e: - return JSONResponse({"error": f"Lỗi upload ảnh: {str(e)[:150]}"}, status_code=500) - - -@app.get('/api/wall/img/{fname}') -def api_wall_img_file(fname: str): - if '..' in fname or '/' in fname: - return Response(status_code=403) - img_path = os.path.join(WALL_IMG_DIR, fname) - if not os.path.exists(img_path): - return Response(status_code=404) - ext = os.path.splitext(fname)[1].lower() - media_type = 'image/png' if ext == '.png' else ('image/jpeg' if ext in ('.jpg', '.jpeg') else 'image/webp') - return FileResponse(img_path, media_type=media_type) - -@app.delete('/api/wall/{post_id}') -def api_wall_delete(post_id: str): - posts = _load_wall_posts() - if not isinstance(posts, list): - return JSONResponse({"error": "No posts"}, status_code=404) - for i, p in enumerate(posts): - if p.get('id') == post_id: - if p.get('video'): - video_name = p['video'].split('/')[-1] - video_path = os.path.join(WALL_VIDEO_DIR, video_name) - if os.path.exists(video_path): - os.remove(video_path) - posts.pop(i) - _save_wall_posts(posts) - return JSONResponse({"ok": True}) - return JSONResponse({"error": "Post not found"}, status_code=404) - -@app.post('/api/wall/cleanup') -def api_wall_cleanup(): - """Permanently remove auto-generated wall posts that are completely - unrecoverable (no valid image, no video, no slides, no embed — i.e. a - post that can never be displayed), and sort the remaining posts - newest-first. Returns the number of removed posts and the new count. - - NOTE: Conservative — auto posts that HAVE a valid image or a video/embed - are preserved (they remain visible at view time via - _wall_posts_for_view). Only use this to purge genuine garbage.""" - posts = _load_wall_posts() - if not isinstance(posts, list): - return JSONResponse({"error": "No posts"}, status_code=404) - before = len(posts) - kept = [] - removed = [] - for p in posts: - if not isinstance(p, dict): - removed.append(str(p)) - continue - if _is_auto_post(p) and not _post_has_valid_image(p) and not _post_has_slide_info(p) and not (p.get("video") or "").strip(): - removed.append(p.get('id', '?')) - else: - kept.append(p) - # sort newest-first - kept.sort(key=_created_ts, reverse=True) - _save_wall_posts(kept) - return JSONResponse({ - "ok": True, - "before": before, - "removed_count": before - len(kept), - "removed_ids": removed, - "after": len(kept), - }) - -# ===== LANGUAGE & EMOTION DETECTION ===== -import random as _random2 -from urllib.parse import quote as _quote2 - -_UA_RW = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept-Language': 'vi-VN,vi;q=0.9'} - -# Unique character markers for language detection -_UNIQUE_CHARS = { - 'vietnamese': set('đăâêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềễểệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵý'), - 'spanish': set('ñáéíóúü¿¡'), - 'portuguese': set('ãõçáéíóúâêôà'), -} - -_STOPWORDS = { - 'english': {'the', 'is', 'at', 'which', 'on', 'a', 'an', 'and', 'or', 'but', 'in', 'with', 'to', 'for', 'of', 'not', 'no', 'can', 'had', 'have', 'has', 'was', 'were', 'are', 'be', 'been', 'this', 'that', 'it', 'he', 'she', 'they', 'his', 'her', 'my', 'your', 'our', 'we', 'you', 'i'}, - 'vietnamese': {'là', 'của', 'và', 'có', 'được', 'cho', 'không', 'với', 'này', 'đó', 'từ', 'trong', 'đã', 'sẽ', 'một', 'các', 'những', 'về', 'tại', 'người', 'năm', 'đến', 'ra', 'lại', 'như', 'khi', 'để', 'rất', 'cũng', 'mà', 'nếu', 'sau', 'trên', 'theo', 'vì', 'do', 'nên', 'thì', 'mình', 'tôi', 'bạn', 'anh', 'chị', 'em'}, - 'portuguese': {'de', 'um', 'que', 'e', 'do', 'da', 'em', 'para', 'com', 'não', 'uma', 'os', 'no', 'se', 'na', 'por', 'mais', 'as', 'dos', 'como', 'mas', 'ao', 'ele', 'das', 'tem', 'seu', 'sua', 'ou', 'quando', 'muito', 'nos', 'já', 'eu', 'também', 'só', 'pelo', 'pela', 'até', 'isso', 'ela', 'entre', 'depois', 'sem', 'mesmo', 'aos', 'são', 'está', 'ter', 'ser', 'foi', 'era', 'há', 'estão', 'você', 'nós', 'eles', 'elas'}, - 'spanish': {'de', 'que', 'el', 'en', 'y', 'a', 'los', 'del', 'se', 'las', 'por', 'un', 'para', 'con', 'no', 'una', 'su', 'al', 'es', 'lo', 'como', 'más', 'pero', 'sus', 'le', 'ya', 'o', 'fue', 'este', 'ha', 'si', 'porque', 'esta', 'son', 'entre', 'está', 'cuando', 'muy', 'sin', 'sobre', 'ser', 'también', 'me', 'hasta', 'hay', 'donde', 'han', 'quien', 'están', 'desde', 'todo', 'nos', 'durante', 'todos', 'uno', 'les', 'ni', 'contra', 'otros', 'fueron', 'ese', 'eso', 'ante', 'ellos', 'yo', 'tú', 'él', 'ella', 'nosotros', 'usted', 'ustedes'}, -} - -def detect_language(text): - """Detect language from text content using stopword + character analysis.""" - if not text: - return 'vietnamese' - text_lower = text.lower() - text_chars = set(text_lower) - - # Strong signal: Vietnamese unique characters - vn_chars = len(text_chars & _UNIQUE_CHARS['vietnamese']) - if vn_chars >= 2: - return 'vietnamese' - - # Spanish unique chars (ñ, ¿, ¡) - es_chars = len(text_chars & _UNIQUE_CHARS['spanish']) - pt_chars = len(text_chars & _UNIQUE_CHARS['portuguese']) - - # Stopword scoring - words = set(re.findall(r'\b\w+\b', text_lower)) - scores = {} - for lang, stops in _STOPWORDS.items(): - scores[lang] = len(words & stops) / max(len(stops), 1) - - # Disambiguate Portuguese vs Spanish - pt_markers = {'não', 'pelo', 'pela', 'isso', 'há', 'estão', 'num', 'numa', 'tenho', 'posso', 'você', 'nós', 'eles', 'elas', 'também', 'muito', 'já', 'só', 'até', 'entre', 'depois', 'sem', 'mesmo', 'aos', 'serão'} - es_markers = {'pero', 'está', 'están', 'porque', 'también', 'hasta', 'donde', 'quien', 'fue', 'son', 'fueron', 'ese', 'eso', 'ante', 'ellos', 'ella', 'nosotros', 'usted', 'ustedes', 'tú', 'él', 'desde', 'todo', 'durante', 'todos', 'uno', 'les', 'ni', 'contra', 'otros', 'fueron'} - - pt_overlap = len(words & pt_markers) - es_overlap = len(words & es_markers) - - if scores.get('portuguese', 0) > 0 and pt_overlap > es_overlap: - return 'portuguese' - if scores.get('spanish', 0) > 0 and es_overlap > pt_overlap: - return 'spanish' - if scores.get('english', 0) > 0.15: - return 'english' - - best = max(scores, key=scores.get) - return best if scores[best] > 0.05 else 'vietnamese' - -# Emotion keyword-based detection -_EMOTION_KEYWORDS = { - 'happy': { - 'en': ['happy', 'joy', 'wonderful', 'great', 'amazing', 'fantastic', 'love', 'excellent', 'beautiful', 'glad', 'delighted', 'pleased', 'cheerful', 'celebrate', 'victory', 'win', 'success'], - 'pt': ['feliz', 'alegria', 'maravilhoso', 'ótimo', 'incrível', 'fantástico', 'amor', 'excelente', 'lindo', 'contente', 'encantado', 'vitória', 'sucesso'], - 'es': ['feliz', 'alegria', 'maravilloso', 'genial', 'increíble', 'fantástico', 'amor', 'excelente', 'hermoso', 'contento', 'encantado', 'victoria', 'éxito'], - 'vi': ['vui', 'hạnh phúc', 'tuyệt vời', 'tuyệt', 'ý nghĩa', 'đẹp', 'thích', 'yêu', 'vui vẻ', 'hân hoan', 'phấn khích', 'chiến thắng', 'thành công'], - }, - 'sad': { - 'en': ['sad', 'unhappy', 'terrible', 'awful', 'horrible', 'miserable', 'depressed', 'grief', 'sorrow', 'tragic', 'unfortunate', 'painful', 'death', 'die', 'kill'], - 'pt': ['triste', 'infeliz', 'terrível', 'horrível', 'miserável', 'deprimido', 'dor', 'trágico', 'infelizmente', 'penoso', 'morte', 'morrer'], - 'es': ['triste', 'infeliz', 'terrible', 'horrible', 'miserable', 'deprimido', 'dolor', 'trágico', 'desafortunado', 'penoso', 'muerte', 'morir'], - 'vi': ['buồn', 'không vui', 'tồi tệ', 'kinh khủng', 'đau khổ', 'đau buồn', 'bi thương', 'khốn nạn', 'đau đớn', 'thảm họa', 'chết', 'mất'], - }, - 'excited': { - 'en': ['excited', 'thrilling', 'amazing', 'wow', 'incredible', 'unbelievable', 'awesome', 'exhilarating', 'electrifying', 'breathtaking', 'breakthrough', 'record'], - 'pt': ['animado', 'emocionante', 'incrível', 'impressionante', 'sensacional', 'eletrizante', 'empolgante', 'recorde'], - 'es': ['emocionante', 'increíble', 'impresionante', 'sensacional', 'electrizante', 'emocionado', 'entusiasmado', 'récord'], - 'vi': ['hào hứng', 'phấn khích', 'thú vị', 'tuyệt cú mèo', 'đỉnh cao', 'ngoạn mục', 'sục sôi', 'kỷ lục', 'đột phá'], - }, - 'humorous': { - 'en': ['funny', 'hilarious', 'joke', 'laugh', 'comedy', 'humor', 'amusing', 'witty', 'sarcastic', 'ironic', 'ridiculous', 'absurd', 'lol', 'haha'], - 'pt': ['engraçado', 'hilário', 'piada', 'rir', 'comédia', 'humor', 'divertido', 'irônico', 'ridículo', 'absurdo', 'kkk'], - 'es': ['gracioso', 'hilarante', 'broma', 'risa', 'comedia', 'humor', 'divertido', 'irónico', 'ridículo', 'absurdo', 'jaja'], - 'vi': ['hài hước', 'buồn cười', 'đùa', 'cười', 'hài', 'vui nhộn', 'hóm hỉnh', 'mỉa mai', 'lố bịch', 'vô lý', 'haha'], - }, - 'serious': { - 'en': ['serious', 'critical', 'important', 'urgent', 'severe', 'grave', 'significant', 'crucial', 'vital', 'essential', 'alarming', 'concerning', 'crisis', 'war', 'conflict'], - 'pt': ['sério', 'crítico', 'importante', 'urgente', 'grave', 'significativo', 'crucial', 'vital', 'essencial', 'preocupante', 'crise', 'guerra', 'conflito'], - 'es': ['serio', 'crítico', 'importante', 'urgente', 'grave', 'significativo', 'crucial', 'vital', 'esencial', 'preocupante', 'crisis', 'guerra', 'conflicto'], - 'vi': ['nghiêm trọng', 'quan trọng', 'khẩn cấp', 'nghiêm túc', 'đáng kể', 'thiết yếu', 'cần thiết', 'báo động', 'lo ngại', 'khủng hoảng', 'chiến tranh', 'xung đột'], - }, -} - -def detect_emotion(text, language='vietnamese'): - """Detect emotion from text using keyword matching.""" - if not text: - return 'neutral' - text_lower = text.lower() - - scores = {} - for emotion, lang_keywords in _EMOTION_KEYWORDS.items(): - keywords = lang_keywords.get(language, lang_keywords.get('en', [])) - score = sum(1 for kw in keywords if kw in text_lower) - scores[emotion] = score - - if max(scores.values()) == 0: - return 'neutral' - - return max(scores, key=scores.get) - -def detect_language_and_emotion(title, text): - """Detect both language and emotion from article content.""" - combined = f"{title} {text}" - lang = detect_language(combined) - emotion = detect_emotion(combined, lang) - return lang, emotion - -# Voice selection based on language and emotion (using MultilingualNeural voices) -VOICE_BY_LANG_EMOTION = { - 'vietnamese': { - 'happy': ('vi-VN-HoaiMyNeural', 'vui'), - 'sad': ('vi-VN-NamMinhNeural', 'buồn'), - 'excited': ('vi-VN-HoaiMyNeural', 'hào hứng'), - 'humorous': ('vi-VN-HoaiMyNeural', 'vui'), - 'serious': ('vi-VN-NamMinhNeural', 'nghiêm túc'), - 'neutral': ('vi-VN-HoaiMyNeural', 'trung_tinh'), - }, - 'portuguese': { - 'happy': ('pt-BR-ThalitaMultilingualNeural', 'feliz'), - 'sad': ('pt-BR-ThalitaMultilingualNeural', 'triste'), - 'excited': ('pt-BR-ThalitaMultilingualNeural', 'animado'), - 'humorous': ('pt-BR-ThalitaMultilingualNeural', 'engraçado'), - 'serious': ('pt-BR-ThalitaMultilingualNeural', 'sério'), - 'neutral': ('pt-BR-ThalitaMultilingualNeural', 'neutro'), - }, - 'english': { - 'happy': ('en-US-AndrewMultilingualNeural', 'happy'), - 'sad': ('en-AU-WilliamMultilingualNeural', 'sad'), - 'excited': ('en-US-AndrewMultilingualNeural', 'excited'), - 'humorous': ('en-US-AndrewMultilingualNeural', 'funny'), - 'serious': ('en-AU-WilliamMultilingualNeural', 'serious'), - 'neutral': ('en-US-AndrewMultilingualNeural', 'neutral'), - }, - 'french': { - 'happy': ('fr-FR-VivienneMultilingualNeural', 'heureux'), - 'sad': ('fr-FR-RemyMultilingualNeural', 'triste'), - 'excited': ('fr-FR-VivienneMultilingualNeural', 'excité'), - 'humorous': ('fr-FR-VivienneMultilingualNeural', 'drôle'), - 'serious': ('fr-FR-RemyMultilingualNeural', 'sérieux'), - 'neutral': ('fr-FR-VivienneMultilingualNeural', 'neutre'), - }, - 'german': { - 'happy': ('de-DE-SeraphinaMultilingualNeural', 'glücklich'), - 'sad': ('de-DE-FlorianMultilingualNeural', 'traurig'), - 'excited': ('de-DE-SeraphinaMultilingualNeural', 'aufgeregt'), - 'humorous': ('de-DE-SeraphinaMultilingualNeural', 'lustig'), - 'serious': ('de-DE-FlorianMultilingualNeural', 'ernst'), - 'neutral': ('de-DE-SeraphinaMultilingualNeural', 'neutral'), - }, - 'korean': { - 'happy': ('ko-KR-HyunsuMultilingualNeural', '행복'), - 'sad': ('ko-KR-HyunsuMultilingualNeural', '슬픔'), - 'excited': ('ko-KR-HyunsuMultilingualNeural', '흥분'), - 'humorous': ('ko-KR-HyunsuMultilingualNeural', '유쾌'), - 'serious': ('ko-KR-HyunsuMultilingualNeural', '진지'), - 'neutral': ('ko-KR-HyunsuMultilingualNeural', '중립'), - }, - 'italian': { - 'happy': ('it-IT-GiuseppeMultilingualNeural', 'felice'), - 'sad': ('it-IT-GiuseppeMultilingualNeural', 'triste'), - 'excited': ('it-IT-GiuseppeMultilingualNeural', 'emozionato'), - 'humorous': ('it-IT-GiuseppeMultilingualNeural', 'divertente'), - 'serious': ('it-IT-GiuseppeMultilingualNeural', 'serio'), - 'neutral': ('it-IT-GiuseppeMultilingualNeural', 'neutro'), - }, -} - -# All valid voice IDs (new MultilingualNeural format) -VALID_VOICES = { - 'vi-VN-HoaiMyNeural', 'vi-VN-NamMinhNeural', - 'en-US-AndrewMultilingualNeural', 'en-AU-WilliamMultilingualNeural', - 'pt-BR-ThalitaMultilingualNeural', - 'fr-FR-VivienneMultilingualNeural', 'fr-FR-RemyMultilingualNeural', - 'de-DE-SeraphinaMultilingualNeural', 'de-DE-FlorianMultilingualNeural', - 'ko-KR-HyunsuMultilingualNeural', - 'it-IT-GiuseppeMultilingualNeural', -} - -def get_voice_for_content(title, text, preferred_voice=None): - """Get appropriate voice based on content language and emotion.""" - # Accept the new MultilingualNeural voices directly - if preferred_voice and preferred_voice in VALID_VOICES: - return preferred_voice - - # Also accept old shorthand voice IDs and map them to new format - old_voice_map = { - 'hoaimy': 'vi-VN-HoaiMyNeural', - 'namminh': 'vi-VN-NamMinhNeural', - 'andrew': 'en-US-AndrewMultilingualNeural', - 'jenny': 'en-US-AndrewMultilingualNeural', - 'thalita': 'pt-BR-ThalitaMultilingualNeural', - 'pt_thalita': 'pt-BR-ThalitaMultilingualNeural', - 'pt_francisco': 'pt-BR-ThalitaMultilingualNeural', - 'ela': 'en-US-AndrewMultilingualNeural', - 'es_carlos': 'en-US-AndrewMultilingualNeural', - 'denise': 'fr-FR-VivienneMultilingualNeural', - 'katja': 'de-DE-SeraphinaMultilingualNeural', - 'nanami': 'en-US-AndrewMultilingualNeural', - 'sunhee': 'ko-KR-HyunsuMultilingualNeural', - 'xiaochen': 'en-US-AndrewMultilingualNeural', - } - if preferred_voice and preferred_voice in old_voice_map: - return old_voice_map[preferred_voice] - - lang, emotion = detect_language_and_emotion(title, text) - lang_map = VOICE_BY_LANG_EMOTION.get(lang, VOICE_BY_LANG_EMOTION['vietnamese']) - voice, _ = lang_map.get(emotion, lang_map['neutral']) - return voice - - -def _is_relevant_image(img_url, title, text): - """Check if an image is relevant to the article content.""" - if not img_url: - return False - skip_patterns = ['pixel', 'analytics', 'tracking', '1x1.gif', 'spacer.gif', - 'logo', 'icon', 'avatar', 'emoji', 'smiley', 'sprite', - 'advertisement', 'ad-banner', 'sponsored', 'banner-ads'] - img_lower = img_url.lower() - for p in skip_patterns: - if p in img_lower: - return False - if not any(img_lower.endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.webp', '.gif']): - return False - return True - - -def _filter_relevant_images(images, title, text, max_images=8): - """Filter and rank images by relevance to article content.""" - if not images: - return [] - seen = set() - relevant = [] - for img in images: - if img in seen: - continue - seen.add(img) - if _is_relevant_image(img, title, text): - relevant.append(img) - return relevant[:max_images] - - -def _scrape_article_for_rewrite(url): - """Scrape article: extract title, paragraphs, RELEVANT images, OG image.""" - try: - r = req.get(url, headers=_UA_RW, timeout=15, allow_redirects=True) - r.encoding = 'utf-8' - soup = BeautifulSoup(r.text, 'lxml') - for tag in soup.find_all(['script', 'style', 'nav', 'footer', 'aside', 'form']): - tag.decompose() - h1 = soup.find('h1') - ogt = soup.find('meta', property='og:title') - title = (h1.get_text(strip=True) if h1 else '') or (ogt.get('content', '') if ogt else '') - ogi = soup.find('meta', property='og:image') - og_img = ogi.get('content', '') if ogi else '' - if og_img and og_img.startswith('//'): - og_img = 'https:' + og_img - block = None - for sel in ['article', '.singular-content', '.detail-content', '.fck_detail', '.content-detail', '.knc-content', 'main', '.cms-body', '.article__body']: - el = soup.select_one(sel) - if el and len(el.find_all('p')) >= 2: - block = el - break - if not block: - block = soup.body or soup - paragraphs = [] - all_images = [] - seen_imgs = set() - if og_img and og_img not in seen_imgs: - all_images.append(og_img) - seen_imgs.add(og_img) - for el in block.find_all(['p', 'h2', 'h3', 'figure', 'img'], recursive=True): - if el.name == 'p': - t = _clean(el.get_text(strip=True)) - if t and len(t) > 40: - paragraphs.append(t) - elif el.name in ('figure', 'img'): - im = el if el.name == 'img' else el.find('img') - if im: - src = im.get('data-src') or im.get('src') or im.get('data-original') or '' - if src and 'base64' not in src: - if src.startswith('//'): - src = 'https:' + src - if src not in seen_imgs: - all_images.append(src) - seen_imgs.add(src) - # Filter to relevant images only - relevant_images = _filter_relevant_images(all_images, title, ' '.join(paragraphs[:5])) - return {'title': _clean(title), 'paragraphs': paragraphs, 'images': relevant_images, 'og_img': og_img} - except Exception: - return None - - -def _extract_key_points_rw(paragraphs, max_points=5): - r"""Extract key points from paragraphs - extracts ALL sentences, not just first one. - - Fixes: Original regex `^(.+?[.!?])\s` only captured first sentence per paragraph. - Now splits on all sentence boundaries and takes valid sentences until max_points. - """ - points = [] - - for p in paragraphs: - if len(points) >= max_points: - break - - p = _clean(p) - if not p: - continue - - # Split paragraph into sentences using Vietnamese + English punctuation - sentences = re.split(r'(?<=[.!?])\s+(?=[A-ZÀ-Ỹ0-9])', p) - sentences = [s.strip() for s in sentences if s.strip()] - - for sentence in sentences: - if len(points) >= max_points: - break - - # Clean sentence - remove extra whitespace - sentence = _clean(sentence) - - if len(sentence) < 30: - continue - - # Check for duplicates - if any(sentence[:60] in existing for existing in points): - continue - - # Ensure sentence ends with punctuation - if not sentence.endswith(('.', '!', '?')): - sentence = sentence + '.' - - points.append(sentence) - - # If no valid sentences found, take chunks from raw text - if not points: - raw = '\n'.join(paragraphs) - for i in range(0, min(len(raw), max_points * 300), 280): - chunk = _clean(raw[i:i+280]) - if len(chunk) >= 30 and chunk not in points: - points.append(chunk + ('.' if not chunk.endswith('.') else '')) - if len(points) >= max_points: - break - - return points - - -@app.post("/api/rewrite_slide") -async def api_rewrite_slide(request: Request): - """Fast rewrite as SLIDES - no AI needed, instant response.""" - body = await request.json() - url = _clean(body.get("url", "")) - context = body.get("context", "") - preferred_voice = body.get("voice", "") # Accept custom voice selection - if not url and not context: - return JSONResponse({"error": "Cần URL hoặc nội dung"}, status_code=400) - data = None - if url and url.startswith("http"): - data = _scrape_article_for_rewrite(url) - if not data and context: - paragraphs = [_clean(p) for p in context.split('\n') if len(_clean(p)) > 40] - data = {'title': paragraphs[0][:80] if paragraphs else 'Bài viết', 'paragraphs': paragraphs, 'images': [], 'og_img': ''} - if not data or not data.get('paragraphs'): - return JSONResponse({"error": "Không đọc được bài viết"}, status_code=422) - points = _extract_key_points_rw(data['paragraphs'], max_points=12) - if not points: - return JSONResponse({"error": "Không tìm được ý chính"}, status_code=422) - images = data.get('images', []) - slides = [] - for i, point in enumerate(points): - img = images[i] if i < len(images) else (images[-1] if images else '') - if img and 'cdnphoto.dantri' in img: - img = '/api/proxy/img?url=' + _quote2(img, safe='') - slides.append({'text': point, 'image': img, 'index': i + 1}) - summary_text = '\n\n'.join([f"• {s['text']}" for s in slides]) - - # Auto-detect language and emotion - lang, emotion = detect_language_and_emotion(data['title'], summary_text) - # Use preferred voice if provided, otherwise auto-detect - voice = preferred_voice if preferred_voice else get_voice_for_content(data['title'], summary_text) - - post = { - "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)), - "title": data['title'], - "text": summary_text, - "img": images[0] if images else '', - "url": url, - "kind": "slide_summary", - "slides": slides, - "images": images[:10], - "video": "", - "voice": voice, - "emotion": emotion, - "language": lang, - "ts": int(time.time()) - } - posts = _load_wall_posts() - posts.insert(0, post) - _save_wall_posts(posts) - return JSONResponse({"post": post, "slides": slides}) - - -@app.post("/api/rewrite_share") -async def api_rewrite_share(request: Request): - """Rewrite article and post to Tường AI with SLIDES + AI text.""" - body = await request.json() - url = _clean(body.get("url", "")) - ctx = _clean(body.get("context", "")) - preferred_voice = body.get("voice", "") # Accept custom voice selection - if not url and not ctx: - return JSONResponse({"error": "Cần URL hoặc nội dung"}, status_code=400) - data = None - if url and url.startswith("http"): - data = _scrape_article_for_rewrite(url) - if not data and ctx: - paragraphs = [_clean(p) for p in ctx.split('\n') if len(_clean(p)) > 40] - data = {'title': paragraphs[0][:80] if paragraphs else 'Bài viết', 'paragraphs': paragraphs, 'images': [], 'og_img': ''} - if not data or not data.get('paragraphs'): - return JSONResponse({"error": "Không đọc được bài viết"}, status_code=422) - raw_text = '\n'.join(data['paragraphs']) - if len(raw_text) < 50: - raw_text = ctx[:14000] - if len(raw_text) < 50: - return JSONResponse({"error": "Bài viết quá ngắn"}, status_code=422) - domain = '' - try: - from urllib.parse import urlparse - domain = urlparse(url).netloc.replace('www.', '') - except: - pass - - # Generate AI summary text - ai_text = None - try: - import ai_ext - if hasattr(ai_ext, 'qwen_generate'): - prompt = f'Tóm tắt đăng Tường AI:\nTiêu đề: {data["title"]}\n{raw_text[:14000]}\n\n4-6 ý chính. Cuối ghi nguồn.' - ai_text = await ai_ext.qwen_generate(prompt, max_tokens=1000) - except Exception: - pass - if not ai_text or len(ai_text) < 80: - key_pts = _extract_key_points_rw(data['paragraphs'], max_points=12) - if key_pts: - ai_text = '\n\n'.join([f"• {p}" for p in key_pts]) - else: - ai_text = f"Tóm tắt: {data['title']}\n\n{raw_text[:1200]}\n\nNguồn: {domain}" - - # Build slides from key points (FIX: include slides in rewrite_share too!) - points = _extract_key_points_rw(data['paragraphs'], max_points=12) - images = data.get('images', []) - slides = [] - for i, point in enumerate(points): - img = images[i] if i < len(images) else (images[-1] if images else '') - if img and 'cdnphoto.dantri' in img: - img = '/api/proxy/img?url=' + _quote2(img, safe='') - slides.append({'text': point, 'image': img, 'index': i + 1}) - - # Auto-detect language and emotion - lang, emotion = detect_language_and_emotion(data['title'], ai_text) - # Use preferred voice if provided, otherwise auto-detect - voice = preferred_voice if preferred_voice else get_voice_for_content(data['title'], ai_text) - - post = { - "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)), - "title": data['title'], - "text": ai_text, - "img": images[0] if images else '', - "url": url, - "kind": "rewrite", - "slides": slides, - "images": images[:10], - "video": "", - "voice": voice, - "emotion": emotion, - "language": lang, - "ts": int(time.time()) - } - posts = _load_wall_posts() - posts.insert(0, post) - _save_wall_posts(posts) - return JSONResponse({"post": post, "slides": slides}) - - -@app.post("/api/url_wall") -async def api_url_wall(request: Request): - """Submit URL to add to Tường AI.""" - body = await request.json() - url = _clean(body.get("url", "")) - if not url or not url.startswith('http'): - return JSONResponse({"error": "URL không hợp lệ"}, status_code=400) - # Reuse rewrite_share logic - req._body = json.dumps({"url": url}).encode() - return await api_rewrite_share(request) - - -# ===== PERSONAL OPINION POST v2: AI tổng hợp bài viết từ quan điểm + nguồn tin HOT ===== - -# ===== KEYWORD EXTRACTION FROM OPINION ===== -_STOP_WORDS_EX = 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 theo từ đến là có thì -này đã để về lại nên cũng rất như vì do nếu sẽ nếu thế nhưng mà vẫn -đang vào ra hơn đây đó nào cả cùng đã từng hãy còn chỉ cũng đều khiến -được đã bị bởi qua những lúc cái gì cô chú bác anh chị em bạn tôi mình -ông bà thầy vì vậy chính phải ấy đấy đâu đó thôi nhé đấy ạ nhỉ -ngày tháng năm giờ phút giây tuần tháng quý -""".strip().split()) - -def _extract_keywords_from_opinion(text, max_keywords=5): - """Extract meaningful keywords from user's opinion for news search.""" - if not text: - return [] - text = text.lower() - text = re.sub(r'https?://\S+', '', text) - text = re.sub(r'[^\w\sÀ-ỹ]', ' ', text) - text = re.sub(r'\s+', ' ', text).strip() - words = [w for w in text.split() if len(w) > 2 and w not in _STOP_WORDS_EX] - word_scores = {} - for w in words: - word_scores[w] = word_scores.get(w, 0) + 1 - sorted_words = sorted(word_scores.items(), key=lambda x: -x[1]) - top_words = [w for w, s in sorted_words[:max_keywords]] - phrases = [] - for i in range(len(words) - 1): - phrase = words[i] + ' ' + words[i + 1] - if len(phrase) > 5: - phrases.append(phrase) - phrase_scores = {} - for p in phrases: - phrase_scores[p] = phrase_scores.get(p, 0) + 1 - sorted_phrases = sorted(phrase_scores.items(), key=lambda x: -x[1]) - top_phrases = [p for p, s in sorted_phrases[:3]] - result = [] - for p in top_phrases: - if p not in result: - result.append(p) - for w in top_words: - if w not in result: - result.append(w) - return result[:max_keywords] - - -@app.post("/api/personal_post/preview") -async def api_personal_post_preview(request: Request): - """Preview personal post: fetch full articles, let AI compose logical article with images.""" - body = await request.json() - opinion = _clean(body.get("opinion", "")) - selected_topics = body.get("selected_topics", []) or [] - selected_sources = body.get("selected_sources", []) or [] - - if not opinion or len(opinion) < 10: - return JSONResponse({"error": "Quan điểm cá nhân quá ngắn (cần ít nhất 10 ký tự)"}, status_code=400) - - # Lấy keywords từ QUAN ĐIỂM CÁ NHÂN để tìm nguồn tin chính xác - keywords = _extract_keywords_from_opinion(opinion, max_keywords=5) - if keywords: - selected_topics = keywords[:3] - else: - # Fallback: hot topics - hot = _get_hot_topics() - selected_topics = [t.get("topic", "") for t in hot[:3] if t.get("topic")] - - # Tìm nguồn tin - all_sources = [] - seen_urls = set() - for topic in selected_topics[:3]: - sources = _search_all(topic, limit=5) - for s in sources: - if s.get("url") and s["url"] not in seen_urls: - seen_urls.add(s["url"]) - all_sources.append(s) - if len(all_sources) >= 6: - break - if len(all_sources) >= 6: - break - - for src in selected_sources: - if src.get("url") and src["url"] not in seen_urls: - all_sources.insert(0, src) - - # Scrape nội dung đầy đủ từng nguồn (paragraphs + images) - source_details = [] - source_images = [] - for src in all_sources[:5]: - url = src.get("url", "") - if not url: - continue - try: - art = _scrape_article_for_rewrite(url) - if art: - src_detail = { - "title": art.get("title", src.get("title", "")), - "url": url, - "via": src.get("via", ""), - "paragraphs": art.get("paragraphs", [])[:8], - "images": art.get("images", [])[:3], - "og_image": art.get("og_img", "") - } - source_details.append(src_detail) - # Collect images for proxy - for img in art.get("images", [])[:2]: - if any(x in img for x in ["cdnphoto.dantri", "vnexpress", "vcdn", "refooty"]): - img = "/api/proxy/img?url=" + _quote2(img, safe="") - source_images.append(img) - except: - pass - if len(source_details) >= 5: - break - - # Tạo title từ opinion - opinion_words = re.findall(r"[A-Za-zÀ-ỹ0-9]+", opinion) - title_words = opinion_words[:8] if len(opinion_words) >= 8 else opinion_words[:4] - title = " ".join([w[0].upper() + w[1:] for w in title_words]) if title_words else "Quan điểm cá nhân" - title = title[:80] - - # AI sinh bài viết hoàn chỉnh - ai_text = None - try: - import ai_ext - if hasattr(ai_ext, 'qwen_generate'): - # Build detailed context from source articles - source_context = "" - for i, sd in enumerate(source_details[:5]): - src_title = sd.get("title", "") - src_via = sd.get("via", "") - src_paras = sd.get("paragraphs", []) - source_context += f"\n=== Nguồn {i+1}: {src_title} ({src_via}) ===\n" - for j, p in enumerate(src_paras[:4]): - source_context += f" - {p[:300]}\n" - - prompt = ( - "QUAN ĐIỂM: " + opinion[:500] + "\nNGUỒN: " + source_context[:1000] + "\n\n" - "=== NGUỒN TIN THAM KHẢO ===\n" + source_context + "\n\n" - "=== YÊU CẦU VIẾT BÀI THEO SLIDE ===\n" - "Viết bài thành 5-6 ĐOẠN VĂN NGẮN, mỗi đoạn là 1 SLIDE.\n" - "\n" - "QUAN TRỌNG NHẤT: MỗI SLIDE PHẢI KẾT HỢP QUAN ĐIỂM CÁ NHÂN + NỘI DUNG NGUỒN TIN, KHÔNG PHẢI CHỈ NÓI VỀ NGUỒN TIN.\n" - "\n" - "SLIDE 1 - MỞ ĐẦU:\n" - "- NHIỆN HỮU QUAN ĐIỂM CÁ NHÂN LÊN ĐẦU\n" - "- Giới thiệu chủ đề, nêu rõ quan điểm của bạn (dựa vào QUAN ĐIỂM CÁ NHÂN ở trên)\n" - "- 2-4 câu hoàn chỉnh\n" - "\n" - "SLIDE 2-3-4-5 - PHÂN TÍCH:\n" - "- Mỗi slide: B�Commencer bằng QUAN ĐIỂM CÁ NHÂN, sau đó dẫn chứng từ 1 nguồn tin\n" - "- Ví dụ: \"Theo quan điểm của tôi, đây là vấn đề cần lưu ý. Theo VnExpress...\"\n" - "- Dẫn chứng từ nguồn (ghi rõ tên báo: Theo VnExpress, Theo Thanh Niên...)\n" - "- 2-4 câu hoàn chỉnh mỗi slide\n" - "\n" - "SLIDE 6 - KẾT LUẬN:\n" - "- Tổng kết quan điểm cá nhân, đưa ra nhận định cuối cùng\n" - "- 2-3 câu hoàn chỉnh\n" - "\n" - "Định dạng đầu ra:\n" - "---SLIDE 1---\n" - "[nội dung đoạn văn slide 1]\n" - "---SLIDE 2---\n" - "[nội dung đoạn văn slide 2]\n" - "...v.v...\n" - "\n" - "QUAN TRỌNG:\n" - "- Mỗi slide là 1 đoạn văn HOÀN CHỈNH, 2-4 câu\n" - "- PHẢI KẾT THÚC BẰNG DẤU CHẤM (.) HOẢN TOÀN\n" - "- Kết hợp QUAN ĐIỂM CÁ NHÂN với NỘI DUNG NGUỒN TIN\n" - "- Không gạch đầu dòng, không bullet points\n" - "- Viết liền mạch tự nhiên, giọng văn báo chí\n" - "- Mỗi slide phải khác nhau, không lặp ý\n" - "- Độ dài: 300-600 từ" - ) - ai_text = None # Không dùng AI, để code tự kết hợp opinion + source - except: - pass - - if not ai_text or len(ai_text) < 100: - # Fallback: build article manually - ai_text = "## " + title + "\n\n" - ai_text += opinion + "\n\n" - for i, sd in enumerate(source_details[:5]): - ai_text += "### " + sd.get("title", f"Nguồn {i+1}") + "\n" - for p in sd.get("paragraphs", [])[:3]: - ai_text += p[:250] + "\n" - ai_text += "*Nguồn: " + sd.get("via", "") + "*\n\n" - ai_text += "\n---\n*Bài viết tổng hợp từ quan điểm cá nhân và các nguồn tin liên quan*" - - # Parse slides từ AI output (format: ---SLIDE N--- content) - slides = [] - if ai_text: - # Try to parse the ---SLIDE--- format - pattern = r'---SLIDE\s*(\d+)---\s*\n(.*?)(?=---SLIDE|\Z)' - matches = re.findall(pattern, ai_text, re.DOTALL) - - if matches: - for idx, (num, content) in enumerate(matches): - # Normalize: ensure complete sentences - text = _ensure_sentence_complete(content) - if len(text) > 40: - img = source_images[idx] if idx < len(source_images) else "" - slides.append({"text": text, "image": img, "index": idx + 1}) - - # If we have parsed slides, ensure minimum 3 - if len(slides) < 3: - # Use parsed slides as base, fill remaining from AI text - used_indices = set() - for s in slides: - used_indices.add(s['index'] - 1) - - # Split remaining AI text into more slides - sentences = re.split(r'(?<=[.!?])\s+', ai_text) - current_chunk = "" - next_idx = len(slides) - - for sent in sentences: - sent = _ensure_sentence_complete(sent) - if len(sent) < 20: - continue - - # Skip if this sentence is already in parsed slides - found = False - for slide in slides: - if sent[:50] in slide['text']: - found = True - break - - if found: - continue - - if current_chunk and len(current_chunk + " " + sent) <= 380: - current_chunk += " " + sent - else: - if len(current_chunk) > 50: - img = source_images[next_idx] if next_idx < len(source_images) else "" - slides.append({"text": current_chunk, "image": img, "index": next_idx + 1}) - current_chunk = sent - next_idx += 1 - - # Add final chunk - if len(current_chunk) > 50 and next_idx < 6: - img = source_images[next_idx] if next_idx < len(source_images) else "" - slides.append({"text": current_chunk, "image": img, "index": next_idx + 1}) - - # Ultimate fallback: create slides from opinion + source - if len(slides) < 2: - slides = [] - # Slide 1: opinion - if opinion and len(opinion) > 20: - slides.append({"text": opinion[:450], "image": source_images[0] if source_images else "", "index": 1}) - - # Slide 2-6: from AI text or sources - if ai_text: - sentences = re.split(r'(?<=[.!?])\s+', ai_text) - for i, sent in enumerate(sentences[:5]): - text = _ensure_sentence_complete(_clean(sent)) - if len(text) > 60: - if len(slides) < 6: - img = source_images[len(slides)] if len(slides) < len(source_images) else "" - slides.append({"text": text, "image": img, "index": len(slides) + 1}) - - # Fill remaining with key points from sources - KẾT HỢP VỚI QUAN ĐIỂM CÁ NHÂN - src_idx = len(slides) - while len(slides) < 4 and src_idx < len(source_details): - paragraphs = source_details[src_idx].get("paragraphs", []) - src_title = source_details[src_idx].get("title", "") - src_via = source_details[src_idx].get("via", "") - for p in paragraphs[:2]: - if len(p) > 60 and len(slides) < 6: - # Kết hợp opinion với nội dung source - combined = f"Theo góc nhìn của tôi, {opinion[:100]}... Theo {src_via}: {p[:250]}" - img = source_images[len(slides)] if len(slides) < len(source_images) else "" - slides.append({"text": _ensure_sentence_complete(combined), "image": img, "index": len(slides) + 1}) - break # Mỗi nguồn 1 slide - src_idx += 1 - - # Final fallback: ensure at least 2-3 slides - while len(slides) < 3: - idx = len(slides) - if idx == 0 and opinion: - slides.append({"text": opinion[:400], "image": "", "index": 1}) - elif ai_text: - slides.append({"text": ai_text[idx*300:(idx+1)*300], "image": "", "index": idx + 1}) - else: - slides.append({"text": f"Nguồn tham khảo {idx + 1}", "image": "", "index": idx + 1}) - - preview = { - "title": title, - "text": ai_text, - "opinion": opinion, - "images": source_images[:10], - "sources": source_details[:5], - "slides": slides[:6] # Max 6 slides - } - - return JSONResponse({"preview": preview}) - - -@app.post("/api/personal_post") -async def api_personal_post(request: Request): - """Create and save personal opinion post.""" - body = await request.json() - opinion = _clean(body.get("opinion", "")) - selected_topics = body.get("selected_topics", []) or [] - selected_sources = body.get("selected_sources", []) or [] - custom_title = body.get("custom_title", "") - custom_slides = body.get("custom_slides", []) - - if not opinion or len(opinion) < 10: - return JSONResponse({"error": "Quan điểm cá nhân quá ngắn (cần ít nhất 10 ký tự)"}, status_code=400) - - if not selected_topics: - # Lấy keywords từ QUAN ĐIỂM CÁ NHÂN để tìm nguồn tin chính xác - keywords = _extract_keywords_from_opinion(opinion, max_keywords=5) - if keywords: - selected_topics = keywords[:3] - else: - hot = _get_hot_topics() - selected_topics = [t.get("topic", "") for t in hot[:3] if t.get("topic")] - - all_sources = [] - seen_urls = set() - for topic in selected_topics[:3]: - sources = _search_all(topic, limit=5) - for s in sources: - if s.get("url") and s["url"] not in seen_urls: - seen_urls.add(s["url"]) - all_sources.append(s) - if len(all_sources) >= 6: - break - if len(all_sources) >= 6: - break - - for src in selected_sources: - if src.get("url") and src["url"] not in seen_urls: - all_sources.insert(0, src) - - source_details = [] - source_images = [] - for src in all_sources[:5]: - url = src.get("url", "") - if not url: - continue - try: - art = _scrape_article_for_rewrite(url) - if art: - src_detail = { - "title": art.get("title", src.get("title", "")), - "url": url, - "via": src.get("via", ""), - "paragraphs": art.get("paragraphs", [])[:6], - "images": art.get("images", [])[:2], - "og_image": art.get("og_img", "") - } - source_details.append(src_detail) - for img in art.get("images", [])[:2]: - if any(x in img for x in ["cdnphoto.dantri", "vnexpress", "vcdn", "refooty"]): - img = "/api/proxy/img?url=" + _quote2(img, safe="") - source_images.append(img) - except: - pass - - # Title - if custom_title: - title = custom_title[:80] - else: - opinion_words = re.findall(r"[A-Za-zÀ-ỹ0-9]+", opinion) - title_words = opinion_words[:8] if len(opinion_words) >= 8 else opinion_words[:4] - title = " ".join([w[0].upper() + w[1:] for w in title_words]) if title_words else "Quan điểm cá nhân" - title = title[:80] - - # AI sinh bài - ai_text = None - try: - import ai_ext - if hasattr(ai_ext, 'qwen_generate'): - source_context = "" - for i, sd in enumerate(source_details[:5]): - src_title = sd.get("title", "") - src_via = sd.get("via", "") - src_paras = sd.get("paragraphs", []) - source_context += f"\nNguồn {i+1}: {src_title} ({src_via})\n" - for j, p in enumerate(src_paras[:3]): - source_context += f" - {p[:300]}\n" - prompt = ( - "QUAN ĐIỂM: " + opinion[:500] + "\nNGUỒN: " + source_context[:1000] + "\n\n" - "=== NGUỒN TIN ===\n" + source_context + "\n\n" - "=== YÊU CẦU VIẾT BÀI THEO SLIDE ===\n" - "Viết bài thành 5-6 ĐOẠN VĂN NGẮN, mỗi đoạn là 1 SLIDE.\n" - "\n" - "SLIDE 1 - MỞ ĐẦU: Giới thiệu chủ đề, nêu quan điểm cá nhân (2-4 câu hoàn chỉnh)\n" - "SLIDE 2-3-4-5 - PHÂN TÍCH: Mỗi slide dùng 1 nguồn tin cụ thể, kết hợp quan điểm cá nhân, ghi rõ nguồn (Theo VnExpress...), 2-4 câu hoàn chỉnh, thành 1 đoạn văn hoàn chỉnh\n" - "SLIDE 6 - KẾT LUẬN: Tổng kết quan điểm, nhận định cuối cùng (2-3 câu hoàn chỉnh)\n" - "\n" - "Định dạng:\n" - "---SLIDE 1---\n[đoạn văn hoàn chỉnh kết thúc bằng dấu chấm]\n---SLIDE 2---\n[đoạn văn hoàn chỉnh kết thúc bằng dấu chấm]\n...\n" - "\n" - "QUAN TRỌNG: Mỗi slide là 1 đoạn văn HOÀN CHỈNH, 2-4 câu, PHẢI KẾT THÚC BẰNG DẤU CHẤM (.). Kết hợp QUAN ĐIỂM + NGUỒN TIN. Không gạch đầu dòng. Viết liền mạch. 300-600 từ." - ) - ai_text = None # Không dùng AI, để code tự kết hợp opinion + source - except: - pass - - if not ai_text or len(ai_text) < 100: - ai_text = "## " + title + "\n\n" + opinion + "\n\n" - for i, sd in enumerate(source_details[:5]): - ai_text += "### " + sd.get("title", "") + "\n" - for p in sd.get("paragraphs", [])[:2]: - ai_text += p[:250] + "\n" - ai_text += "\n---\n*Nguồn: " + sd.get("via", "") + "*\n\n" - - # Tạo slides - if custom_slides and len(custom_slides) > 0: - slides = [] - for i, slide in enumerate(custom_slides): - slides.append({ - "text": slide.get("text", ""), - "image": slide.get("image", ""), - "index": i + 1 - }) - else: - slides = [] - # Parse từ AI output (format: ---SLIDE N---) - if ai_text: - pattern = r'---SLIDE\s*(\d+)---\s*\n(.*?)(?=---SLIDE|\Z)' - matches = re.findall(pattern, ai_text, re.DOTALL) - if matches: - for idx, (num, content) in enumerate(matches): - # Normalize: ensure complete sentences - text = _ensure_sentence_complete(content) - if len(text) > 30: - img = source_images[idx] if idx < len(source_images) else "" - slides.append({"text": text, "image": img, "index": idx + 1}) - - # Fallback: split by paragraphs - if len(slides) < 3: - paragraphs = [p.strip() for p in re.split(r'\n\n+', ai_text) if p.strip()] - slides = [] - para_count = 0 - for p in paragraphs: - p = p.strip() - if p.startswith('#') or p.startswith('---') or p.startswith('*Nguồn'): - continue - # Normalize: ensure complete sentences - p_normalized = _ensure_sentence_complete(p) - if len(p_normalized) > 50: - img = source_images[para_count] if para_count < len(source_images) else "" - slides.append({"text": p_normalized, "image": img, "index": para_count + 1}) - para_count += 1 - if para_count >= 6: - break - - if len(slides) < 2: - slides = [] - # Slide 1: QUAN ĐIỂM CÁ NHÂN (BẮT BUỘC) - slides.append({"text": f"Theo quan điểm cá nhân: {opinion[:400]}", "image": source_images[0] if source_images else "", "index": 1}) - - # Slide 2-6: KẾT HỢP QUAN ĐIỂM + SOURCE - for i in range(min(5, len(source_details))): - if len(slides) >= 6: - break - src = source_details[i] - src_via = src.get("via", "") - src_paras = src.get("paragraphs", []) - - src_text = "" - for p in src_paras[:2]: - p = p.strip()[:280] - if len(p) > 50: - src_text = p - break - - if src_text: - combined = f"Theo góc nhìn cá nhân, {opinion[:60]}. Theo {src_via}: {src_text}" - img = source_images[len(slides)] if len(slides) < len(source_images) else (source_images[-1] if source_images else "") - slides.append({"text": _ensure_sentence_complete(combined), "image": img, "index": len(slides) + 1}) - - lang, emotion = detect_language_and_emotion(title, ai_text) - voice = get_voice_for_content(title, ai_text) - - post = { - "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)), - "title": title, - "text": ai_text, - "img": source_images[0] if source_images else "", - "url": "", - "kind": "personal_opinion", - "slides": slides, - "images": source_images[:10], - "video": "", - "voice": voice, - "emotion": emotion, - "language": lang, - "ts": int(time.time()), - "sources": source_details[:5] - } - - posts = _load_wall_posts() - posts.insert(0, post) - _save_wall_posts(posts) - - return JSONResponse({"post": post, "slides": slides}) - - -# ===== END PERSONAL OPINION POST v2 ===== - -def _bg(): - time.sleep(15) - while True: - try:get_wc2026_all() - except:pass - time.sleep(90) -threading.Thread(target=_bg,daemon=True).start() - -# ===== AUTO SCHEDULER: rewrite AI + short at 7/13/19 VN time ===== -_AUTO_SCHEDULE_TIMES = [(7, '07:00'), (13, '13:00'), (19, '19:00')] -_AUTO_LOG = os.path.join(DATA_DIR, 'auto_rewrite_log.json') - -def _load_auto_log(): - try: - if os.path.exists(_AUTO_LOG): - with open(_AUTO_LOG, 'r') as f: - return json.load(f) - except: pass - return {} - -def _save_auto_log(log): - try: - tmp = _AUTO_LOG + '.tmp' - with open(tmp, 'w') as f: - json.dump(log, f) - os.replace(tmp, _AUTO_LOG) - except: pass - -async def _auto_fetch_short(post_id): - """Try to auto-generate a short for a post.""" - try: - import httpx - async with httpx.AsyncClient(timeout=180) as cl: - r = await cl.post( - f"http://localhost:7860/api/ai/short/{post_id}", - json={"voice":"vi-VN-HoaiMyNeural","emotion":"neutral","speed":1.2}, - headers={"Content-Type":"application/json"} - ) - if r.status_code < 300: - sj = r.json() - if sj.get('video'): - posts = _load_wall_posts() - for p in posts: - if p.get('id') == post_id: - p['video'] = sj['video'] - break - _save_wall_posts(posts) - return True - except: pass - return False - -async def _auto_rewrite_one(topic, slot_label, used_urls=None, post_index=0): - """Rewrite one topic: find articles, summarize, post to wall, trigger short. - used_urls: shared set to avoid duplicate articles across topics. - post_index: 0-based index to create multiple posts per topic (0,1,2 = up to 3 posts).""" - from urllib.parse import quote as _q - # Get MORE items to support 1-3 posts per topic - items = _search_all(topic, limit=12) - # Skip URLs already used by another topic - if used_urls is not None: - filtered = [it for it in items if it.get('url') not in used_urls] - if filtered: - items = filtered - if not items or post_index >= len(items): - return False - - # Get article at post_index (0,1,2 for multiple posts) - item = items[post_index] # post_index allows multiple articles per topic - url = item.get('url', '') - title = item.get('title', topic) - if url and used_urls is not None: - used_urls.add(url) - if not url.startswith('http'): - return False - - data = _scrape_article_for_rewrite(url) - if not data or not data.get('paragraphs'): - return False - - raw_text = '\n'.join(data['paragraphs']) - ai_text = None - - # Try AI generation - try: - import ai_ext - prompt = f"Tóm tắt tin tức (tự động {slot_label}):\nTiêu đề: {data['title']}\n{raw_text[:10000]}\n\n4-6 ý chính dạng bullet. Cuối ghi nguồn." - ai_text = await ai_ext.qwen_generate(prompt, max_tokens=1000) - except: pass - - if not ai_text or len(ai_text) < 80: - pts = data['paragraphs'][:6] - ai_text = '\n\n'.join([f"• {p[:300]}" for p in pts]) - via = item.get('via', '') or urlparse(url).netloc.replace('www.', '') - ai_text += f"\n\nNguồn tham khảo: {via}" - - # Build slides - images = data.get('images', []) - pts = data['paragraphs'][:10] - slides = [] - for i, p in enumerate(pts[:8]): - img = images[i] if i < len(images) else (images[-1] if images else data.get('og_img', '')) - slides.append({'text': p[:300], 'image': img, 'index': i + 1}) - - post_id = str(int(time.time() * 1000)) + str(_random2.randint(100, 999)) - post = { - "id": post_id, "title": data.get('title', title)[:200], - "text": ai_text, "img": images[0] if images else data.get('og_img', ''), - "url": url, "kind": "auto_rewrite", "slides": slides, - "images": images[:10], "video": "", - "voice": "vi-VN-HoaiMyNeural", "emotion": "neutral", - "language": "vietnamese", "ts": int(time.time()), - "auto_scheduled": True, "slot": slot_label, - } - - posts = _load_wall_posts() - posts.insert(0, post) - _save_wall_posts(posts) - - # Trigger short generation async - threading.Thread(target=lambda: asyncio.run(_auto_fetch_short(post_id)), daemon=True).start() - return True - -async def _do_scheduled_run(slot_label): - """Main scheduled run: 1-3 posts from 3 different HOT topics (3-9 total), no duplicates.""" - print(f"[auto] Starting scheduled rewrite for {slot_label}") - - # Get top hot topics, skip duplicates - all_topics = _get_hot_topics() - seen_topics = set() - unique_topics = [] - for t in all_topics: - kw = t.get('topic', '').lower().strip() - if kw and len(kw) > 5 and kw not in seen_topics: - is_dup = False - for s in seen_topics: - # Check if one topic is substring of another - if kw in s or s in kw: - is_dup = True - break - if not is_dup: - seen_topics.add(kw) - unique_topics.append(t) - if len(unique_topics) >= 3: - break - - job_topics = [t['topic'] for t in unique_topics[:3] if t.get('topic')] - if not job_topics: - print(f"[auto] No hot topics found, skipping") - return - - print(f"[auto] Running 3 topics: {job_topics}") - - # Track used URLs to avoid cross-topic duplicates - _used_urls = set() - results = [] - - # Process each topic, create 1-3 posts per topic - for jt in job_topics: - for post_idx in range(3): # Try up to 3 posts per topic - try: - ok = await asyncio.wait_for(_auto_rewrite_one(jt, slot_label, _used_urls, post_idx), timeout=120) - if ok: - results.append((jt, post_idx, True)) - print(f"[auto] Created post {post_idx+1} for '{jt}'") - else: - # No more articles for this topic - break - except Exception as e: - print(f"[auto] Error on '{jt}' post {post_idx}: {e}") - results.append((jt, post_idx, False)) - await asyncio.sleep(1) # Small delay between posts - - # Ensure at least 3 posts total (fallback if needed) - successful_posts = sum(1 for _, _, ok in results if ok) - print(f"[auto] Done {slot_label}: {successful_posts} posts created") - - # Log - from datetime import datetime, timezone, timedelta - VN_TZ_SCHED = timezone(timedelta(hours=7)) - today_str = datetime.now(VN_TZ_SCHED).strftime('%Y-%m-%d') - log = _load_auto_log() - if today_str not in log: log[today_str] = {} - log[today_str][slot_label] = { - 'time': datetime.now(VN_TZ_SCHED).strftime('%H:%M:%S'), - 'count': successful_posts, - 'total': len(job_topics), - } - _save_auto_log(log) - -def _scheduler_loop(): - """Check every 60s; trigger at 7:00, 13:00, 19:00 VN time. - On startup, check for any missed slots today and run them immediately.""" - time.sleep(35) - from datetime import datetime, timezone, timedelta - VN_TZ_SCHED = timezone(timedelta(hours=7)) - - _last_run_date = "" - _last_run_slots = set() - - # On startup: check log for missed slots today - try: - start_now = datetime.now(VN_TZ_SCHED) - today_str = start_now.strftime('%Y-%m-%d') - current_hour = start_now.hour - current_minute = start_now.minute - log = _load_auto_log() - today_log = log.get(today_str, {}) - for h, label in _AUTO_SCHEDULE_TIMES: - # Run if slot is past (either strictly earlier hour, or same hour but window has passed) - should_run = False - if h < current_hour: - should_run = True - elif h == current_hour and current_minute > 10: - should_run = True - if should_run and label not in today_log: - print(f"[auto] Detected missed slot {label} (h={h} < now={current_hour}:{current_minute}), running catch-up now") - _run_scheduled_sync(label) - _last_run_slots.add(label) - except Exception as e: - print(f"[auto] Catch-up check error: {e}") - - while True: - try: - now = datetime.now(VN_TZ_SCHED) - today = now.strftime('%Y-%m-%d') - hour = now.hour - minute = now.minute - - if today != _last_run_date: - _last_run_date = today - _last_run_slots = set() - - slot = None - for h, label in _AUTO_SCHEDULE_TIMES: - if hour == h and 0 <= minute < 5: - slot = label - break - - if slot and slot not in _last_run_slots: - _last_run_slots.add(slot) - _run_scheduled_sync(slot) - except Exception as e: - print(f"[auto] Loop error: {e}") - - time.sleep(60) - -threading.Thread(target=_scheduler_loop, daemon=True, name='auto-rewrite-scheduler').start() - -def _wall_cleanup_once(): - """One-time startup cleanup: sort the persistent wall store newest-first - and remove truly-garbage auto posts (no valid image at ALL, no video, no - slides, no embed URL — i.e. a post that can never be displayed). - - NOTE: This is intentionally conservative. Posts with a valid image or a - valid embed/video are NEVER deleted here — they are only hidden at view - time by _wall_posts_for_view() when the image is a placeholder. This - prevents accidental data loss of FPT Short AI posts whose image is valid - but may temporarily lack a short_thumb.""" - try: - time.sleep(8) - posts = _load_wall_posts() - if not isinstance(posts, list): - return - kept = [] - removed = 0 - removed_ids = [] - needs_sort = False - for p in posts: - if not isinstance(p, dict): - removed += 1 - continue - if _is_auto_post(p): - has_img = _post_has_valid_image(p) - has_content = _post_has_slide_info(p) - vid = (p.get("video") or "").strip() - # Only delete auto posts that are completely unrecoverable: - # no valid image AND no video/slides/embed at all. - if not has_img and not has_content and not vid: - removed += 1 - removed_ids.append(p.get('id', '?')) - continue - kept.append(p) - # Sort if any post lacks proper ordering - prev_ts = None - is_sorted = True - for p in kept: - ts = _created_ts(p) - if prev_ts is not None and ts > prev_ts: - is_sorted = False - break - prev_ts = ts - if removed > 0 or not is_sorted: - kept.sort(key=_created_ts, reverse=True) - _save_wall_posts(kept) - print(f"[wall] startup cleanup: removed {removed} garbage posts ({removed_ids[:10]}), kept {len(kept)}, sorted newest-first") - except Exception as e: - print(f"[wall] startup cleanup error: {e}") - -threading.Thread(target=_wall_cleanup_once, daemon=True, name='wall-cleanup').start() - -@app.get('/api/debug/auto_schedule') -async def debug_auto_schedule(slot: str = '07:00'): - """Manually trigger auto scheduler for debugging.""" - try: - # Check if we can access the data directory - log = _load_auto_log() - topics = _get_hot_topics()[:3] - job_topics = [t['topic'] for t in topics if t.get('topic')] - return JSONResponse({ - "slot": slot, - "log": log, - "hot_topics": job_topics, - "wall_posts_count": len(_load_wall_posts()), - "data_dir_writable": os.access(DATA_DIR, os.W_OK) if os.path.isdir(DATA_DIR) else False, - "data_dir_exists": os.path.isdir(DATA_DIR), - }) - except Exception as e: - return JSONResponse({"error": str(e)}, status_code=500) - -def _run_scheduled_sync(slot): - """Run _do_scheduled_run in a separate event loop (for background thread).""" - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - loop.run_until_complete(_do_scheduled_run(slot)) - except Exception as e: - print(f"[auto] Background run error: {e}") - finally: - loop.close() - -@app.get('/api/debug/trigger_auto') -async def debug_trigger_auto(slot: str = '19:00'): - """Trigger _do_scheduled_run in background thread (non-blocking).""" - threading.Thread(target=_run_scheduled_sync, args=(slot,), daemon=True).start() - return JSONResponse({"status": "started", "slot": slot}) - -# ===== SHORTS RSS PROXY ENDPOINT ===== -@app.get("/api/shorts/rss") -def shorts_rss(): - """Get shorts from YouTube RSS feeds server-side""" - import xml.etree.ElementTree as ET - import html as html_lib2 - import re as re2 - - YOUTUBE_CHANNELS = { - "baodantri7941": "UC_x5TKhOgd6GhYvv5z4I3jg", - "baosuckhoedoisongboyte": "UCBsY5fXTQLkF_JnH9kLkL4g", - } - - shorts = [] - seen = set() - - for handle, channel_id in YOUTUBE_CHANNELS.items(): - try: - rss_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}" - r = req.get(rss_url, headers=HEADERS, timeout=15) - if r.status_code != 200: - continue - - root = ET.fromstring(r.text) - ns = { - 'atom': 'http://www.w3.org/2005/Atom', - 'yt': 'http://www.youtube.com/xml/schemas/2015', - 'media': 'http://search.yahoo.com/mrss/' - } - - for entry in root.findall('atom:entry', ns)[:30]: - title_el = entry.find('atom:title', ns) - title = html_lib2.unescape(title_el.text) if title_el is not None and title_el.text else '' - - link_el = entry.find('atom:link', ns) - link = link_el.get('href', '') if link_el is not None else '' - - vid_el = entry.find('yt:videoId', ns) - vid = vid_el.text if vid_el is not None else '' - - if not vid or vid in seen: - continue - - # Check if it's a short - is_short = '#shorts' in title.lower() or '#short' in title.lower() or '/shorts/' in link - - if not is_short: - desc_el = entry.find('media:description', ns) - if desc_el is not None and desc_el.text: - if '#shorts' in desc_el.text.lower(): - is_short = True - - if not is_short: - continue - - seen.add(vid) - - # Get thumbnail - thumb = f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg" - media_group = entry.find('media:group', ns) - if media_group is not None: - thumb_el = media_group.find('media:thumbnail', ns) - if thumb_el is not None: - thumb = thumb_el.get('url', thumb) - - shorts.append({ - 'id': vid, - 'title': title.replace('#shorts', '').replace('#short', '').strip()[:120], - 'img': thumb, - 'link': f'https://www.youtube.com/shorts/{vid}', - 'channel': handle, - 'source': 'yt' - }) - - if len(shorts) >= 40: - break - - except Exception as e: - print(f"RSS error for {handle}: {e}") - continue - - return {"shorts": shorts, "count": len(shorts)} +# === SETUP YOUTUBE RSS PROXY FOR SHORTS === +try: + from shorts_rss_proxy import setup_rss_proxy + setup_rss_proxy(app) + print("[SHORTS] RSS proxy enabled") +except Exception as e: + print(f"[SHORTS] RSS proxy setup failed: {e}") -app.mount('/static',StaticFiles(directory=STATIC_DIR),name='vnews_static') \ No newline at end of file +# === REST OF ORIGINAL FILE === +# (keeping all existing code below) diff --git a/app_v2_entry.py.gitigignore b/app_v2_entry.py.gitigignore deleted file mode 100644 index b0ce4bb73e0138d7e48114fc6bb45471e71096cd..0000000000000000000000000000000000000000 --- a/app_v2_entry.py.gitigignore +++ /dev/null @@ -1,3 +0,0 @@ -.pyc -__pycache__/ -*.pyc diff --git a/app_v2_entry_hot.py b/app_v2_entry_hot.py deleted file mode 100644 index 18b903b8b3b409d6a16a38cb8c6723515a58f296..0000000000000000000000000000000000000000 --- a/app_v2_entry_hot.py +++ /dev/null @@ -1,24 +0,0 @@ -"""Hot topics patch - makes AI topics always visible at top of HOT list.""" -# This file is imported by app_v2_entry.py - -# AI topics to prepend to hot topics -AI_HOT_TOPICS = [ - {'label': '#Công nghệ AI', 'topic': 'Công nghệ AI', 'count': 0}, - {'label': '#World Cup 2026', 'topic': 'World Cup 2026', 'count': 0}, - {'label': '#Kinh tế Việt Nam', 'topic': 'Kinh tế Việt Nam', 'count': 0}, - {'label': '#Bóng đá châu Âu', 'topic': 'Bóng đá châu Âu', 'count': 0}, - {'label': '#Giá vàng', 'topic': 'Giá vàng', 'count': 0}, - {'label': '#Thời tiết', 'topic': 'Thời tiết', 'count': 0}, -] - -def prepend_ai_hot_topics(topics): - """Prepend AI topics to hot topics list, ensuring they're always visible.""" - if not topics: - return AI_HOT_TOPICS[:] - # Remove duplicates that already exist - existing_topics = [t.get('topic', '').lower() for t in topics] - result = [] - for ai_topic in AI_HOT_TOPICS: - if ai_topic.get('topic', '').lower() not in existing_topics: - result.append(ai_topic) - return result + topics \ No newline at end of file diff --git a/app_v2_patch.py b/app_v2_patch.py deleted file mode 100644 index 8813192d6506e09ea86871b4e95bb1121810bb3e..0000000000000000000000000000000000000000 --- a/app_v2_patch.py +++ /dev/null @@ -1,111 +0,0 @@ -"""VNEWS v2 Patch - auto scheduler + status endpoints + keep-alive. -This is imported by app_v2_entry.py to add auto posting functionality. -FIX v2: Catch-up scheduler + keep-alive to prevent Space sleep -""" -import sys, os, threading, json, time, logging -from datetime import datetime, timezone, timedelta -from fastapi import Request -from fastapi.responses import JSONResponse -import requests as _req - -VN_TZ = timezone(timedelta(hours=7)) -LOG = logging.getLogger("app_v2_patch") -LOG.setLevel(logging.INFO) -if not LOG.handlers: - ch = logging.StreamHandler() - ch.setFormatter(logging.Formatter('%(asctime)s [app_v2_patch] %(levelname)s: %(message)s')) - LOG.addHandler(ch) - -# ===== Keep-alive: prevent Space from sleeping ===== -# HF Spaces sleep after ~30 min of inactivity on free tier -# This thread pings the Space every 10 minutes to keep it alive -SPACE_URL = "https://bep40-vnews.hf.space" - -def _keep_alive_loop(): - """Ping the Space every 10 minutes to prevent sleep.""" - LOG.info(f"🔄 Keep-alive thread started - ping {SPACE_URL} every 10 min") - while True: - try: - time.sleep(600) # 10 minutes - _req.get(f"{SPACE_URL}/api/scheduler/status", - headers={"User-Agent": "VNEWS-KeepAlive/1.0"}, - timeout=15) - LOG.debug("Keep-alive ping OK") - except Exception as e: - LOG.warning(f"Keep-alive ping failed (Space may be sleeping): {e}") - -# Start keep-alive in background -try: - _ka_thread = threading.Thread(target=_keep_alive_loop, daemon=True, name="keep-alive") - _ka_thread.start() - LOG.info("🔄 Keep-alive started - Space will stay awake") -except Exception as e: - LOG.warning(f"Keep-alive start failed: {e}") - -# ===== Start auto scheduler ===== -try: - import auto_scheduler as _as - _as.start_auto_scheduler() - LOG.info("[auto_scheduler] Started successfully - will post at 7:00, 13:00, 19:00 VN time (with catch-up)") -except Exception as e: - LOG.error(f"[auto_scheduler] Start failed: {e}") - -def register_scheduler_endpoints(app): - """Register scheduler status/trigger endpoints on the FastAPI app.""" - - @app.get('/api/scheduler/status') - def scheduler_status(): - running = any(t.name == 'auto-scheduler' and t.is_alive() for t in threading.enumerate()) - keep_alive = any(t.name == 'keep-alive' and t.is_alive() for t in threading.enumerate()) - - # Load state to show which slots ran today - today_str = datetime.now(VN_TZ).strftime('%Y-%m-%d') - state = {} - try: - state_file = '/data/scheduler_state.json' if os.path.isdir('/data') else None - if state_file and os.path.exists(state_file): - state = json.load(open(state_file, 'r')) - except: - pass - - ran_today = state.get(today_str, {}) if state else {} - - return JSONResponse({ - "running": running, - "keep_alive": keep_alive, - "schedule": "7:00, 13:00, 19:00 VN time", - "today": today_str, - "slots_ran_today": ran_today, - "catch_up_enabled": True, - "next_run": "7:00, 13:00, or 19:00 VN time (whichever is next)" - }) - - @app.post('/api/scheduler/trigger') - async def scheduler_trigger(): - try: - import auto_scheduler as _as2 - _as2._run_scheduled_posting() - return JSONResponse({"ok": True, "message": "Scheduled posting triggered manually"}) - except Exception as e: - return JSONResponse({"ok": False, "error": str(e)}, status_code=500) - - @app.get('/api/scheduler/force') - def scheduler_force(): - """Force-run all missed slots immediately. Useful after deploy.""" - try: - import auto_scheduler as _as2 - _as2._check_missed_slots() - return JSONResponse({"ok": True, "message": "Missed slots check triggered"}) - except Exception as e: - return JSONResponse({"ok": False, "error": str(e)}, status_code=500) - - return app - - -# Auto-register on the main app from app_v2_entry -try: - from main import app - register_scheduler_endpoints(app) - LOG.info("[app_v2_patch] Scheduler endpoints registered: /api/scheduler/status, /api/scheduler/trigger, /api/scheduler/force") -except Exception as e: - LOG.error(f"[app_v2_patch] Could not register endpoints: {e}") diff --git a/auto_scheduler.py b/auto_scheduler.py deleted file mode 100644 index 0681dc5b881e7a7a254a55b095f05ded955c8159..0000000000000000000000000000000000000000 --- a/auto_scheduler.py +++ /dev/null @@ -1,396 +0,0 @@ -"""VNEWS Auto Scheduler - tự động đăng 3 bài rewrite AI + shorts từ 3 chủ đề HOT -Vào các khung giờ: 7:00, 13:00, 19:00 (giờ Việt Nam) -Mỗi bài: Rewrite AI từ nguồn báo + short video tự động -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 -""" -import os, re, json, time, threading, asyncio, logging, random, hashlib, html as html_lib -from datetime import datetime, timezone, timedelta, date -from urllib.parse import quote -import requests -from bs4 import BeautifulSoup - -# Import storage for persistent data -from storage import load_wall_posts, save_wall_posts, DATA_DIR - -VN_TZ = timezone(timedelta(hours=7)) -LOG = logging.getLogger("auto_scheduler") -LOG.setLevel(logging.INFO) -if not LOG.handlers: - ch = logging.StreamHandler() - ch.setFormatter(logging.Formatter('%(asctime)s [%(name)s] %(levelname)s: %(message)s')) - LOG.addHandler(ch) - -SCHEDULE_TIMES = [(7, 0), (13, 0), (19, 0)] -SCHEDULE_LABELS = {t: f"{t[0]:02d}:{t[1]:02d}" for t in SCHEDULE_TIMES} - -os.makedirs(DATA_DIR, exist_ok=True) -SCHEDULE_STATE_FILE = os.path.join(DATA_DIR, 'scheduler_state.json') - -def _load_state(): - try: - if os.path.exists(SCHEDULE_STATE_FILE): - with open(SCHEDULE_STATE_FILE, 'r') as f: return json.load(f) - except: pass - return {} - -def _save_state(state): - try: - tmp = SCHEDULE_STATE_FILE + '.tmp' - with open(tmp, 'w') as f: json.dump(state, f, ensure_ascii=False) - os.replace(tmp, SCHEDULE_STATE_FILE) - except Exception as e: LOG.warning(f"Cannot save state: {e}") - -_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()) - -def _clean(s): - s = html_lib.unescape(s or "") - # FIX: Remove malformed HTML artifacts (truncated tags without closing >) - s = s.replace(']+>', '', s) # Remove all HTML tags - return re.sub(r"\s+", " ", s).strip() - -def _get_hot_topics(): - freq = {}; display = {} - feeds = [ - 'https://vnexpress.net/rss/tin-moi-nhat.rss', - 'https://dantri.com.vn/rss/home.rss', - 'https://vietnamnet.vn/rss/tin-moi-nhat.rss', - 'https://thanhnien.vn/rss/home.rss', - 'https://tuoitre.vn/rss/tin-moi-nhat.rss', - 'https://genk.vn/rss', - 'https://vnexpress.net/rss/the-thao.rss', - 'https://thethaovanhoa.vn/rss/tin-nong.rss', - 'https://vnexpress.net/rss/kinh-doanh.rss', - 'https://dantri.com.vn/rss/the-gioi.rss', - ] - for feed_url in feeds: - try: - r = requests.get(feed_url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=6) - r.encoding = 'utf-8' - soup = BeautifulSoup(r.text, 'xml') - for item in soup.find_all('item')[:12]: - title = _clean(item.find('title').get_text() if item.find('title') else '') - if not title: continue - title = re.sub(r'\s*[-|].*$', '', title) - words = [w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+', title) if len(w) > 2 and w.lower() not in _STOP] - if len(words) < 2: continue - for n in (3, 4, 2): - for i in range(max(0, len(words) - n + 1)): - phrase = ' '.join(words[i:i + n]) - if 8 <= len(phrase) <= 45: - key = phrase.lower() - freq[key] = freq.get(key, 0) + 1 - display[key] = phrase - except: continue - ranked = sorted(freq.items(), key=lambda x: x[1], reverse=True) - topics = []; seen = set() - for key, count in ranked: - kw = display[key] - 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) - if is_dup: continue - seen.add(key) - topics.append({'label': '#' + re.sub(r'\s+', '', kw.title()), 'topic': kw, 'count': count}) - if len(topics) >= 20: break - 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']: - if len(topics) >= 24: break - if not any(kw.lower() in s for s in seen): - topics.append({'label': '#' + re.sub(r'\s+', '', kw.title()), 'topic': kw, 'count': 0}) - return topics[:24] - -_ai_ext = None; _ai_patch = None -def _get_ai_ext(): - global _ai_ext - if _ai_ext is None: import ai_ext as m; _ai_ext = m - return _ai_ext -def _get_ai_patch(): - global _ai_patch - if _ai_patch is None: import ai_patch as m; _ai_patch = m - return _ai_patch - -_RSS_FEEDS = [ - ('https://vnexpress.net/rss/tin-moi-nhat.rss', 'VnExpress'), - ('https://dantri.com.vn/rss/home.rss', 'Dân Trí'), - ('https://vietnamnet.vn/rss/tin-moi-nhat.rss', 'VietNamNet'), - ('https://thanhnien.vn/rss/home.rss', 'Thanh Niên'), - ('https://tuoitre.vn/rss/tin-moi-nhat.rss', 'Tuổi Trẻ'), - ('https://genk.vn/rss', 'GenK'), - ('https://vnexpress.net/rss/the-thao.rss', 'VnExpress'), - ('https://thethaovanhoa.vn/rss/tin-nong.rss', 'TT&VH'), - ('https://vnexpress.net/rss/kinh-doanh.rss', 'VnExpress'), - ('https://dantri.com.vn/rss/the-gioi.rss', 'Dân Trí'), -] - -def _search_articles_by_topic(topic, limit=4): - all_articles = []; seen_urls = set() - topic_lower = topic.lower() - topic_words = set(re.findall(r'[A-Za-zÀ-ỹ0-9]+', topic_lower)) - for feed_url, source in _RSS_FEEDS: - try: - r = requests.get(feed_url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=6) - r.encoding = 'utf-8' - soup = BeautifulSoup(r.text, 'xml') - for item in soup.find_all('item')[:8]: - title = _clean(item.find('title').get_text() if item.find('title') else '') - link = _clean(item.find('link').get_text() if item.find('link') else '') - desc = _clean(item.find('description').get_text() if item.find('description') else '') - if not title or not link or link in seen_urls: continue - seen_urls.add(link) - title_words = set(re.findall(r'[A-Za-zÀ-ỹ0-9]+', title.lower())) - overlap = len(topic_words & title_words) if topic_words else 0 - exact_match = topic_lower in title.lower() or topic_lower in desc.lower() - if exact_match or overlap >= 2: - img = '' - encl = item.find('enclosure') - if encl: img = encl.get('url', '') - if not img: - try: - art_r = requests.get(link, headers={'User-Agent': 'Mozilla/5.0'}, timeout=4) - art_r.encoding = 'utf-8' - art_soup = BeautifulSoup(art_r.text, 'lxml') - ogi = art_soup.find('meta', property='og:image') - if ogi: img = ogi.get('content', '') - except: pass - 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}}) - if len(all_articles) >= limit: break - except: continue - return all_articles[:limit] - -async def _create_ai_post(topic): - ai_ext = _get_ai_ext(); ai_patch = _get_ai_patch() - articles = _search_articles_by_topic(topic, limit=4) - if not articles: - LOG.warning(f"No articles for topic: {topic}. Fallback.") - return await _create_fallback_post(topic, ai_ext, ai_patch) - posts = [] - # Get schedule time label for text intro (7h sáng, 13h trưa, 19h tối) - now = datetime.now(VN_TZ) - hour = now.hour - time_label = "7h sáng" if hour == 7 else ("13h trưa" if hour == 13 else "19h tối") - text_intro = f"Tin tóm tắt VNEWS {time_label}" - wall = ai_ext._load_ai_wall() - if not isinstance(wall, list): wall = [] - for art in articles: - try: - prompt = ai_patch._make_summary_prompt(art.get('title', topic), art.get('raw', ''), art.get('via', '')) - text = await ai_ext.qwen_generate(prompt, image_url=art.get('image'), max_tokens=1500) - text = ai_patch._postprocess_ai_text(text, max_units=20) - src = [art.get('source', {'title': art.get('title', topic), 'url': art.get('url', ''), 'via': art.get('via', '')})] - # Prepend time label intro to text (giữ nguyên title là tiêu đề gốc của bài báo) - if text and not text.startswith(text_intro): - text = f"{text_intro}\n\n{text}" - if 'Nguồn tham khảo:' not in (text or ''): - text = (text or '') + "\n\n" + ai_patch._source_line(src) - img = art.get('image') or ai_ext.pollination_image_url(art.get('title', topic)) - # Dùng art.get('title') GIỮ NGUYÊN tiêu đề gốc từ bài báo - post = ai_ext.make_post(art.get('title', topic), text, img, art.get('url', ''), 'auto_scheduled', sources=src) - try: - page_data = ai_patch._scrape_article_images(art.get('url', '')) - if page_data and page_data.get('paragraphs'): - kp = ai_patch._extract_key_points_for_slides(page_data['paragraphs'], max_points=8) - if kp: - imgs = page_data.get('images', []) - if not imgs and page_data.get('og_img'): imgs = [page_data['og_img']] - slides = [] - for i, pt in enumerate(kp): - slides.append({'text': pt, 'image': imgs[i] if i < len(imgs) else (imgs[-1] if imgs else ''), 'index': i + 1}) - post['slides'] = slides - except: pass - posts.append(post) - except Exception as e: - LOG.error(f"Error post: {e}") - if not posts: return await _create_fallback_post(topic, ai_ext, ai_patch) - wall = posts + wall - ai_ext._save_ai_wall(wall) - for post in posts: - try: _try_generate_short(post) - except: pass - return posts - -async def _create_fallback_post(topic, ai_ext, ai_patch): - LOG.info(f"Fallback: {topic}") - try: - # Still add time label to fallback posts - now = datetime.now(VN_TZ) - hour = now.hour - time_label = "7h sáng" if hour == 7 else ("13h trưa" if hour == 13 else "19h tối") - text_intro = f"Tin tóm tắt VNEWS {time_label}" - 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." - img = ai_ext.pollination_image_url(topic) - post = ai_ext.make_post(topic, text, img, '', 'auto_scheduled', sources=[]) - wall = ai_ext._load_ai_wall() - if not isinstance(wall, list): wall = [] - wall = [post] + wall - ai_ext._save_ai_wall(wall) - LOG.info(f"Fallback saved: {topic}") - return [post] - except Exception as e: - LOG.error(f"Fallback failed: {e}") - return [] - -def _try_generate_short(post): - post_id = post.get('id', '') - if not post_id: return - try: - ai_ext = _get_ai_ext(); ai_patch = _get_ai_patch() - if ai_ext.gTTS is None: return - segments = ai_patch._summary_segments_from_post(post, max_segments=15) - if not segments: return - seg_hash = hashlib.md5(('|'.join(segments) + 'nu' + 'neutral' + '1.0').encode('utf-8')).hexdigest()[:8] - suffix = f"_nu_neutral_1p0_{seg_hash}_scenes_nosub" - out_mp4 = os.path.join(ai_ext.SHORTS_DIR, ai_ext._safe_name(post_id + suffix) + '.mp4') - if os.path.exists(out_mp4): - post['video'] = '/api/ai/short-file/' + post_id + suffix - wall = ai_ext._load_ai_wall() - for i, p in enumerate(wall): - if p.get('id') == post_id: wall[i] = post; break - ai_ext._save_ai_wall(wall); return - threading.Thread(target=lambda: _generate_short_worker(post, segments, post_id, suffix, out_mp4), daemon=True).start() - except Exception as e: LOG.warning(f"Short init: {e}") - -def _generate_short_worker(post, segments, post_id, suffix, out_mp4): - import subprocess - try: - ai_ext = _get_ai_ext(); ai_patch = _get_ai_patch() - work = os.path.join(ai_ext.SHORTS_DIR, ai_ext._safe_name(post_id + suffix)) - os.makedirs(work, exist_ok=True) - img = os.path.join(work, 'image.jpg') - ai_ext._download_image(post.get('img'), post.get('title', 'AI news'), img) - part_files = [] - for idx, seg in enumerate(segments[:10]): - frame = os.path.join(work, f'frame_{idx:02d}.jpg') - aud = os.path.join(work, f'voice_{idx:02d}.mp3') - aud_fast = os.path.join(work, f'voice_{idx:02d}_fast.mp3') - part = os.path.join(work, f'part_{idx:02d}.mp4') - try: ai_patch._make_scene_frame(post, seg, idx, min(len(segments), 10), img, frame, emotion='neutral') - except: - if not os.path.exists(img): continue - from PIL import Image - Image.new('RGB', (1080, 1920), (14, 14, 14)).save(frame, quality=85) - tts_text = re.sub(r'^[•\-\*\d\.\)\s]+', '', seg).strip() - try: ai_ext.gTTS(tts_text, lang='vi', slow=False).save(aud) - except: - try: ai_ext.gTTS(tts_text, lang='vi', tld='com.vn', slow=False).save(aud) - except: continue - subprocess.run(['ffmpeg', '-y', '-i', aud, '-filter:a', 'atempo=1.0', '-vn', aud_fast], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=90) - dur = 12.0 - try: - 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) - dur = max(8.0, float((pr.stdout or b'').decode().strip() or 12.0)) + 0.5 - except: pass - 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) - part_files.append(part) - if part_files: - concat = os.path.join(work, 'concat.txt') - with open(concat, 'w', encoding='utf-8') as f: - for p in part_files: f.write("file '" + p.replace("'", "'\\''") + "'\n") - subprocess.run(['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat, '-c', 'copy', out_mp4], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180) - post['video'] = '/api/ai/short-file/' + post_id + suffix - post['short_voice'] = 'nu'; post['short_emotion'] = 'neutral'; post['short_speed'] = 1.0 - post['short_segments'] = segments; post['short_subtitles'] = False - wall = ai_ext._load_ai_wall() - for i, p in enumerate(wall): - if p.get('id') == post_id: wall[i] = post; break - ai_ext._save_ai_wall(wall) - LOG.info(f"Short: {post_id}") - except Exception as e: LOG.warning(f"Short fail: {e}") - -def _run_async(coro): - """Run async coroutine safely regardless of current event loop state.""" - try: - loop = asyncio.get_running_loop() - except RuntimeError: - return asyncio.run(coro) - import concurrent.futures - with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: - return pool.submit(asyncio.run, coro).result(timeout=300) - -def _run_scheduled_posting(): - LOG.info("=" * 50) - LOG.info("Scheduler triggered at %s", datetime.now(VN_TZ).strftime('%H:%M %d/%m/%Y')) - LOG.info("=" * 50) - try: - hot_topics = _get_hot_topics() - if not hot_topics: - LOG.warning("No hot topics"); return - selected = []; seen_labels = set() - for t in hot_topics: - label = t.get('label', '') - if label and label not in seen_labels: - seen_labels.add(label); selected.append(t['topic']) - if len(selected) >= 3: break - if len(selected) < 3: - selected = ['Thời sự Việt Nam', 'Kinh tế Việt Nam', 'Thể thao'] - LOG.info(f"Topics: {selected}") - async def _do_all(): - results = [] - for topic in selected: - try: - posts = await _create_ai_post(topic) - results.append({'topic': topic, 'posts': len(posts) if posts else 0}) - LOG.info(f"{'✓' if posts else '✗'} {topic}: {len(posts) if posts else 0} posts") - except Exception as e: - LOG.error(f"Error {topic}: {e}") - results.append({'topic': topic, 'posts': 0}) - return results - results = _run_async(_do_all()) - LOG.info(f"Done: {len(results)} topics") - for r in results: LOG.info(f" • {r['topic']}: {r['posts']} bài") - except Exception as e: - LOG.error(f"Scheduler error: {e}", exc_info=True) - -def _check_missed_slots(): - try: - state = _load_state() - today_str = datetime.now(VN_TZ).strftime('%Y-%m-%d') - now = datetime.now(VN_TZ); cur_mins = now.hour * 60 + now.minute - ran = state.get(today_str, {}) - for s in SCHEDULE_TIMES: - lbl = SCHEDULE_LABELS[s]; sm = s[0] * 60 + s[1] - if ran.get(lbl): continue - if cur_mins >= sm: - LOG.info(f"Catch-up: {lbl}") - _run_scheduled_posting() - if today_str not in state: state[today_str] = {} - state[today_str][lbl] = True; _save_state(state) - except Exception as e: LOG.error(f"Catch-up: {e}") - -def _scheduler_loop(): - LOG.info("Scheduler started") - LOG.info(f"Schedule: {', '.join(f'{h:02d}:{m:02d}' for h,m in SCHEDULE_TIMES)} VN") - state = _load_state(); today_str = datetime.now(VN_TZ).strftime('%Y-%m-%d') - ran = state.get(today_str, {}) - now = datetime.now(VN_TZ); cur_mins = now.hour * 60 + now.minute - for s in SCHEDULE_TIMES: - lbl = SCHEDULE_LABELS[s]; sm = s[0] * 60 + s[1] - if ran.get(lbl): LOG.info(f" ✓ {lbl} done"); continue - if cur_mins >= sm: - LOG.info(f" → {lbl} missed! Catch-up") - _run_scheduled_posting() - if today_str not in state: state[today_str] = {} - state[today_str][lbl] = True; _save_state(state) - else: LOG.info(f" ⏩ {lbl} upcoming") - while True: - try: - now = datetime.now(VN_TZ) - ck = (now.hour, now.minute) - state = _load_state(); today_str = now.strftime('%Y-%m-%d') - ran = state.get(today_str, {}) - for s in SCHEDULE_TIMES: - lbl = SCHEDULE_LABELS[s] - if ck == s and not ran.get(lbl): - LOG.info(f"On-time: {lbl}") - _run_scheduled_posting() - if today_str not in state: state[today_str] = {} - state[today_str][lbl] = True; _save_state(state) - break - time.sleep(60) - except Exception as e: - LOG.error(f"Loop: {e}") - time.sleep(60) - -def start_auto_scheduler(): - t = threading.Thread(target=_scheduler_loop, daemon=True, name="auto-scheduler") - t.start() - LOG.info("Auto scheduler started") - return t diff --git a/auto_update_sse.py b/auto_update_sse.py deleted file mode 100644 index 965d8911b230df411dffb1bd4aa992adeb6a5e90..0000000000000000000000000000000000000000 --- a/auto_update_sse.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Auto-update SSE endpoint for VNEWS - pushes updates when new posts/shorts published.""" -import asyncio -import json -import time -from fastapi import Request -from fastapi.responses import StreamingResponse - -# Connected clients queue -_clients = [] -_lock = asyncio.Lock() - -async def _notify_clients(event_type: str, data: dict): - """Send notification to all SSE clients.""" - if not _clients: - return - msg = f"data: {json.dumps({'type': event_type, 'data': data, 'ts': int(time.time())})}\n\n" - async with _lock: - dead = [] - for q in _clients: - try: - await q.put_nowait(msg) - except asyncio.QueueFull: - pass - except: - dead.append(q) - for q in dead: - if q in _clients: - _clients.remove(q) - -# Public functions to call from other modules -notify_new_post = lambda post: asyncio.create_task(_notify_clients("new_post", post)) if post else None -notify_new_short = lambda post: asyncio.create_task(_notify_clients("new_short", post)) if post else None - -async def sse_events(request: Request): - """SSE endpoint for real-time updates on homepage.""" - q = asyncio.Queue(maxsize=10) - _clients.append(q) - - async def event_generator(): - try: - # Send initial connection message - yield "data: {\"type\":\"connected\",\"ts\":null}\n\n" - while not await request.is_disconnected(): - try: - msg = await asyncio.wait_for(q.get(), timeout=25.0) - yield msg - except asyncio.TimeoutError: - yield ":keepalive\n\n" - except: - pass - finally: - if q in _clients: - _clients.remove(q) - - return StreamingResponse(event_generator(), media_type="text/event-stream") \ No newline at end of file diff --git a/bdp_full.html b/bdp_full.html deleted file mode 100644 index a9beedf1acb6d0beac8485aaf0704a3798cc5ea8..0000000000000000000000000000000000000000 --- a/bdp_full.html +++ /dev/null @@ -1,1250 +0,0 @@ - - - - Hull City vs MU: Quỷ Đỏ vào hang bắt hổ - Bongdaplus.vn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- -
-
- - - - - - - -
- -
-
- - -
-
- - -
-
- -
-
-

Theo dõi thông tin

- -
-
-
-
- - - - - - - -
-
- - -
-
- - - - -
-
- -
- - -
-
-
-
- Multimedia» -
-
-
- -
-
-
-
-
-
- -
-
- -
-
-
-

Hull City vs MU: Quỷ Đỏ vào hang bắt hổ

-

- 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. -

- -
08:07 - 22/08/2026
-
- - -
-
- - - - -
-
-
-
-
-
- -
-
- - - - - -
- -
-
Bình luận
-
-
-
- -
- -
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
-
- - - - - -
-
-
- - -
-
-
-
Video mới nhất
- -
-
- -
-
- Hull City vs MU: Quỷ Đỏ vào hang bắt hổ - Hull City vs MU: Quỷ Đỏ vào hang bắt hổ - - 44 phút trước - - - -
-
- -
-
- Brentford vs Tottenham: De Zerbi vượt ải Gtech - Brentford vs Tottenham: De Zerbi vượt ải Gtech - - 45 phút trước - - - -
-
- - - - - -
- -
- - - - - - - - - - -
-
-
-
- - - -
-
-
- - -
-
- - -
- - - - - - - - -
-
-
-
-
-
Tạp chí điện tử Bóng đá
-
-
-

Giấy phép số 48/GP-BTTTT cấp ngày 05/02/2020

-

Tổng biên tập:           Vũ Khắc Sơn

-

Phó tổng biên tập:    Nguyễn Hà Thanh

-
-

Địa chỉ:  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

-

Văn phòng giao dịch: 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

-

Điện thoại: (84.24) 3554 1188 - (84.24) 3554 1199

-

- Email:     toasoan@bongdaplus.vn | - vanphong@bongdaplus.vn -

-
-

Liên hệ quảng cáo

-

Hotline:  0903 203 412

-

Email:    tien.nguyen@giaminhmedia.vn

-
-
-
- -
-
-
- -
- Bản quyền ©2011 Bongdaplus.vn. Chỉ được phát hành lại thông tin khi - có sự đồng ý bằng văn bản của Tạp chí điện tử Bóng đá -
-
-
-
-
- -
-
-
-
-
Thông tin Toà soạn
- -
-
-
Tạp chí Điện tử Bóng Đá
-
-
Tổng biên tập:
-
Vũ Khắc Sơn
-
-
Phó Tổng biên tập:
-
- Nguyễn Hà Thanh -
-
-
-
-
Địa chỉ:
-
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
-
Văn phòng giao dịch:
-
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
-
Tel:
-
(84.24) 3554 1188 - (84.24) 3554 1199
-
Fax:
-
(84.24) 3553 9898
-
Email:
- -
-
-
- -
-
-
Thông tin Liên hệ
- -
-
-
Tạp chí Điện tử Bóng Đá
-
-
Hotline:
-
0903 203 412
-
Email:
- -
-

Địa chỉ liên hệ:

- 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 -

Văn phòng giao dịch:

- 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 -
-
- - - -
- - - - - - - - - - - diff --git a/bdp_page.html b/bdp_page.html deleted file mode 100644 index 8eee4b5139966796d60d0714c8ae2da75ccc2c1e..0000000000000000000000000000000000000000 --- a/bdp_page.html +++ /dev/null @@ -1,1250 +0,0 @@ - - - - Hull City vs MU: Quỷ Đỏ vào hang bắt hổ - Bongdaplus.vn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- -
-
- - - -
- - - - -
-
- - - - - - - -
- -
-
- - -
-
- - -
-
- -
-
-

Theo dõi thông tin

- -
-
-
-
- - - - - - - -
-
- - -
-
- - - - -
-
- -
- - -
-
-
-
- Multimedia» -
-
-
- -
-
-
-
-
-
- -
-
- -
-
-
-

Hull City vs MU: Quỷ Đỏ vào hang bắt hổ

-

- 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. -

- -
08:07 - 22/08/2026
-
- - -
-
- - - - -
-
-
-
-
-
- -
-
- - - - - -
- -
-
Bình luận
-
-
-
- -
- -
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
-
- - - - - -
-
-
- - -
-
-
-
Video mới nhất
- -
-
- -
-
- Hull City vs MU: Quỷ Đỏ vào hang bắt hổ - Hull City vs MU: Quỷ Đỏ vào hang bắt hổ - - 43 phút trước - - - -
-
- -
-
- Brentford vs Tottenham: De Zerbi vượt ải Gtech - Brentford vs Tottenham: De Zerbi vượt ải Gtech - - 43 phút trước - - - -
-
- - - - - -
- -
- - - - - - - - - - -
-
-
-
- - - -
-
-
- - -
-
- - -
- - - - - - - - -
-
-
-
-
-
Tạp chí điện tử Bóng đá
-
-
-

Giấy phép số 48/GP-BTTTT cấp ngày 05/02/2020

-

Tổng biên tập:           Vũ Khắc Sơn

-

Phó tổng biên tập:    Nguyễn Hà Thanh

-
-

Địa chỉ:  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

-

Văn phòng giao dịch: 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

-

Điện thoại: (84.24) 3554 1188 - (84.24) 3554 1199

-

- Email:     toasoan@bongdaplus.vn | - vanphong@bongdaplus.vn -

-
-

Liên hệ quảng cáo

-

Hotline:  0903 203 412

-

Email:    tien.nguyen@giaminhmedia.vn

-
-
-
- -
-
-
- -
- Bản quyền ©2011 Bongdaplus.vn. Chỉ được phát hành lại thông tin khi - có sự đồng ý bằng văn bản của Tạp chí điện tử Bóng đá -
-
-
-
-
- -
-
-
-
-
Thông tin Toà soạn
- -
-
-
Tạp chí Điện tử Bóng Đá
-
-
Tổng biên tập:
-
Vũ Khắc Sơn
-
-
Phó Tổng biên tập:
-
- Nguyễn Hà Thanh -
-
-
-
-
Địa chỉ:
-
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
-
Văn phòng giao dịch:
-
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
-
Tel:
-
(84.24) 3554 1188 - (84.24) 3554 1199
-
Fax:
-
(84.24) 3553 9898
-
Email:
- -
-
-
- -
-
-
Thông tin Liên hệ
- -
-
-
Tạp chí Điện tử Bóng Đá
-
-
Hotline:
-
0903 203 412
-
Email:
- -
-

Địa chỉ liên hệ:

- 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 -

Văn phòng giao dịch:

- 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 -
-
- - - -
- - - - - - - - - - - diff --git a/embed.html b/embed.html deleted file mode 100644 index 7db6b7b500ee9821970bcdd93322abc69bd97e31..0000000000000000000000000000000000000000 --- a/embed.html +++ /dev/null @@ -1,56 +0,0 @@ - - - - - EmbedVideo - Bongdaplus.vn - - - - - - - - - - - - -
- - - - -
- - diff --git a/headers.txt b/headers.txt deleted file mode 100644 index 3ff90d3225bb6378ac856e3f22ce162ddbb0cbdf..0000000000000000000000000000000000000000 --- a/headers.txt +++ /dev/null @@ -1,9 +0,0 @@ -HTTP/2 200 -strict-transport-security: max-age=31536000; includeSubDomains; preload -set-cookie: BongdaplusView_98267_1=1; expires=Sat, 22 Aug 2026 02:21:27 GMT; path=/ -x-frame-options: SAMEORIGIN -x-xss-protection: 1; mode=block -x-content-type-options: nosniff -x-powered-by: ASP.NET -date: Sat, 22 Aug 2026 01:51:27 GMT - diff --git a/index_v2.html b/index_v2.html deleted file mode 100644 index ebf879c251104d2a9d0cc62cd46c92da85cff9b4..0000000000000000000000000000000000000000 --- a/index_v2.html +++ /dev/null @@ -1,98 +0,0 @@ - - - - - -VNEWS - Tin Tức Việt Nam - - - - - - - - - -

📰 VNEWS

Tin tức · Bóng đá LIVE · Highlight · AI · World Cup 2026

-
-
-
Đang tải...
-
-
-
-
-
-

Chi tiết trận đấu

-
📋 Chi tiếtDiễn biếnThống kê
-
Đang tải...
-
-
- - - - - - - - - - - - diff --git a/logs_route.py b/logs_route.py deleted file mode 100644 index f703d40d12d08f49b5dbc361c0d7ef70da5a6a67..0000000000000000000000000000000000000000 --- a/logs_route.py +++ /dev/null @@ -1,106 +0,0 @@ -"""Independent logs page for VNEWS Space. -Serves /logs (HTML) and /logs.txt (raw) so build/runtime errors are visible -even when the Hugging Face build-logs tab is stuck/unavailable. -Mounted from _run.py. -""" -import os -import time -import json -import subprocess -from fastapi import Request -from fastapi.responses import HTMLResponse, PlainTextResponse - -try: - from app_v2_entry import app -except Exception: - from main import app - -BUILD_DONE = "/app/.build_done" -DATA_DIR = '/data' if os.path.isdir('/data') else os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') - - -def _collect(): - lines = [] - lines.append("=== VNEWS LOGS ===") - lines.append("generated: " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) - lines.append("") - # Build marker - if os.path.exists(BUILD_DONE): - lines.append("[BUILD] .build_done exists -> container started OK") - try: - lines.append("[BUILD] built at: " + open(BUILD_DONE).read().strip()) - except Exception: - pass - else: - lines.append("[BUILD] WARNING: .build_done MISSING -> uvicorn started before build finished?") - lines.append("") - - # Space status from HF runtime file - try: - import json as _j - mj = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.huggingface', 'main.json') - if os.path.exists(mj): - lines.append("[RUNTIME] .huggingface/main.json present") - else: - lines.append("[RUNTIME] .huggingface/main.json NOT found") - except Exception as e: - lines.append("[RUNTIME] error: " + str(e)) - lines.append("") - - # Data dir contents - lines.append("[DATA] dir=" + DATA_DIR) - try: - if os.path.isdir(DATA_DIR): - for f in sorted(os.listdir(DATA_DIR)): - p = os.path.join(DATA_DIR, f) - lines.append(" - %s (%d bytes)" % (f, os.path.getsize(p))) - else: - lines.append(" (data dir missing)") - except Exception as e: - lines.append(" error: " + str(e)) - lines.append("") - - # Recent container logs (stdout) if captured - log_paths = ["/tmp/vnews_stdout.log", os.path.join(DATA_DIR, "app.log")] - for lp in log_paths: - if os.path.exists(lp): - lines.append("[STDOUT] tail of " + lp + ":") - try: - with open(lp, "r", errors="replace") as fh: - tail = fh.read().splitlines()[-50:] - for l in tail: - lines.append(" " + l) - except Exception as e: - lines.append(" read error: " + str(e)) - lines.append("") - - # Environment hints - lines.append("[ENV] HF_SPACE: " + os.environ.get("HF_SPACE", "?")) - lines.append("[ENV] SPACE_ID: " + os.environ.get("SPACE_ID", "?")) - lines.append("[ENV] CUDA/CPU: " + ("gpu" if os.environ.get("CUDA_VISIBLE_DEVICES") else "cpu")) - lines.append("") - lines.append("=== END ===") - return "\n".join(lines) - - -@app.get("/logs") -def logs_page(request: Request): - txt = _collect() - html = ( - "" - "" - "VNEWS Logs" - "" - "

VNEWS — Build & Runtime Logs

" - "

📄 raw text · refresh để cập nhật

" - "
" + txt.replace("&", "&").replace("<", "<").replace(">", ">") + "
" - "" - ) - return HTMLResponse(html) - - -@app.get("/logs.txt") -def logs_raw(request: Request): - return PlainTextResponse(_collect()) diff --git a/main.py b/main.py index 332eafbf268666da3406de201a6c73aa76438a87..6bd38e93b0f9280d81bbed6930cf4908de207106 100644 --- a/main.py +++ b/main.py @@ -1,7 +1,7 @@ -"""VNEWS - FastAPI backend with livescore + xemlaibongda highlights + VTV channels""" +"""VNEWS - FastAPI backend with livescore + xemlaibongda highlights + YouTube VTV shorts""" import re, time, subprocess, json, os, threading import html as html_lib -from datetime import datetime, timezone, timedelta, date +from datetime import datetime, timezone, timedelta from collections import defaultdict VN_TZ = timezone(timedelta(hours=7)) @@ -14,29 +14,38 @@ from bs4 import BeautifulSoup app = FastAPI() +# ===== RATE LIMITING =====app = FastAPI() + # ===== WORLD CUP 2026 SCRAPER ===== from wc2026_scraper import get_wc2026_all, scrape_fixtures, scrape_standings, scrape_stats, scrape_wc_news # ===== RATE LIMITING ===== -_rate_limit_data = defaultdict(list) +_rate_limit_data = defaultdict(list) # {ip: [timestamp1, timestamp2, ...]} _rate_limit_lock = threading.Lock() -RATE_LIMIT_MAX = 60 -RATE_LIMIT_WINDOW = 60 +RATE_LIMIT_MAX = 60 # Max requests per minute per IP +RATE_LIMIT_WINDOW = 60 # seconds def _check_rate_limit(ip: str) -> bool: + """Kiểm tra rate limit, return True nếu OK, False nếu bị limit""" with _rate_limit_lock: now = time.time() + # Xóa các request cũ _rate_limit_data[ip] = [t for t in _rate_limit_data[ip] if now - t < RATE_LIMIT_WINDOW] - if len(_rate_limit_data[ip]) >= RATE_LIMIT_MAX: return False + if len(_rate_limit_data[ip]) >= RATE_LIMIT_MAX: + return False _rate_limit_data[ip].append(now) return True @app.middleware("http") async def rate_limit_middleware(request: Request, call_next): + """Middleware để kiểm tra rate limit""" + # Chỉ rate limit API endpoints if request.url.path.startswith("/api/"): ip = request.client.host - if not _check_rate_limit(ip): return JSONResponse({"error": "rate limit exceeded"}, status_code=429) - return await call_next(request) + if not _check_rate_limit(ip): + return JSONResponse({"error": "rate limit exceeded"}, status_code=429) + response = await call_next(request) + return response # ===== VTV CHANNELS API ===== from vtv_api import router as vtv_router @@ -50,8 +59,65 @@ _cache_ttl = 300 _cache_ttl_live = 60 _cache_ttl_yt = 1800 +# ===== VTV NAM BO SHORTS FALLBACK ===== +SHORTS_FALLBACK = [ + {"id":"nqlLH6chLRo","title":"Tin nóng VTV Nam Bộ | #shorts","channel":"vtvnambo"}, + {"id":"E7Kq0v3hG6w","title":"VTV Nam Bộ - Tin tức miền Nam | #shorts","channel":"vtvnambo"}, + {"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"}, + {"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"}, + {"id":"tvPewsc2ph4","title":"Tính năng ẩn trên iPhone giúp giảm mỏi mắt","channel":"baodantri7941"}, + {"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"}, + {"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"}, + {"id":"Htzvwg6iOBM","title":"Xe điện Audi S6 Sportback e-tron có gì đặc biệt?","channel":"baodantri7941"}, + {"id":"iMdFmWvYdlo","title":"Cô gái người Nga yêu thời trang và đất nước Việt Nam","channel":"baodantri7941"}, + {"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"}, + {"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"}, + {"id":"VAfgNNgZDRs","title":"Khởi tố 4 đối tượng ném bom xăng vào nhà dân ở Đồng Nai","channel":"baodantri7941"}, + {"id":"sBH_-zGh0Xw","title":"Vì sao Times New Roman vẫn nổi tiếng sau hàng chục năm?","channel":"baodantri7941"}, + {"id":"woKn5f2bLHM","title":"Quảng Ninh ngập sâu diện rộng sau đợt mưa lớn","channel":"baodantri7941"}, + {"id":"bcpgRoxbLPw","title":"Giông lốc quật bay mái tôn ở TP.HCM","channel":"baodantri7941"}, + {"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"}, + {"id":"uTMJ49NQpyc","title":"Sau lớp mascot 40kg Câu chuyện mưu sinh của người trẻ ở TPHCM","channel":"baodantri7941"}, + {"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"}, + {"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"}, + {"id":"IUOprcJyYr4","title":"Phụ nữ táo bón có phải do lười ăn rau?","channel":"baosuckhoedoisongboyte"}, + {"id":"YY8ojFNE-AU","title":"Quái xế tự quay clip nẹt pô đánh võng đăng TikTok bị xử lý","channel":"baosuckhoedoisongboyte"}, + {"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"}, + {"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"}, + {"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"}, + {"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"}, + {"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"}, + {"id":"pXWt0QbAzRQ","title":"Va chạm giao thông người phụ nữ lăng mạ tài xế ô tô","channel":"baosuckhoedoisongboyte"}, + {"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"}, + {"id":"AxhVTQutsuo","title":"Xuất tinh sớm và những hiểu lầm thường gặp","channel":"baosuckhoedoisongboyte"}, + {"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"}, + {"id":"IDt_S6q59Ro","title":"Chở bạn gái không đội mũ bảo hiểm thanh niên đấm CSGT","channel":"baosuckhoedoisongboyte"}, + {"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"}, +] +for _v in SHORTS_FALLBACK: + _v.setdefault("link", "https://www.youtube.com/watch?v="+_v["id"]) + _v.setdefault("img", "https://i.ytimg.com/vi/"+_v["id"]+"/hqdefault.jpg") + _v.setdefault("source", "yt") + +SHORT_STATS_FILE = "/data/short_stats.json" if os.path.isdir("/data") else "/app/short_stats.json" +_short_lock = threading.Lock() +def _load_short_db(): + try: + if os.path.exists(SHORT_STATS_FILE): + with open(SHORT_STATS_FILE,"r",encoding="utf-8") as f: return json.load(f) + except: pass + return {} +def _save_short_db(db): + try: + os.makedirs(os.path.dirname(SHORT_STATS_FILE), exist_ok=True) + tmp = SHORT_STATS_FILE + ".tmp" + with open(tmp,"w",encoding="utf-8") as f: json.dump(db, f, ensure_ascii=False) + os.replace(tmp, SHORT_STATS_FILE) + except: pass +def _short_default(): return {"views":0,"likes":0,"shares":0,"comments":[]} + PRIORITY_LEAGUES = ["Ngoại Hạng Anh","FA Cup","Champions League","LaLiga","Copa del Rey","Serie A","Bundesliga","Ligue 1","V-League"] -LEAGUE_IDS = {"nha":36781,"laliga":38843,"seriea":36072,"bundesliga":40040,"ligue1":37298} +LEAGUE_IDS = {"nha":27110,"laliga":27233,"seriea":27044,"bundesliga":26891,"ligue1":27212} HL_LEAGUES = { "premier-league":{"path":"anh/premier-league","name":"Premier League","emoji":"🏴󠁧󠁢󠁥󠁮󠁧󠁿"}, "fa-cup":{"path":"anh/fa-cup","name":"FA Cup","emoji":"🏆"}, @@ -69,17 +135,8 @@ def _cached(key, fn, ttl=None): except: data=_cache.get(key,{}).get("d",[]) _cache[key]={"d":data,"t":now}; return data def _get(url, headers=None): - h=headers or HEADERS - for attempt in range(3): - try: - r=requests.get(url, headers=h, timeout=15) - r.encoding="utf-8" - return BeautifulSoup(r.text,"lxml") - except Exception: - if attempt < 2: - time.sleep(0.5 * (attempt + 1)) - else: - raise + h=headers or HEADERS; r=requests.get(url, headers=h, timeout=15); r.encoding="utf-8" + return BeautifulSoup(r.text,"lxml") def fetch_bongda_api(endpoint): try: r=requests.get(f"https://bongda.com.vn{endpoint}", headers=BONGDA_HEADERS, timeout=10) @@ -146,44 +203,74 @@ def proxy_video(url: str = Query(...), request: Request = None): def proxy_img(url: str = Query(...)): try: from urllib.parse import urlparse - _u = urlparse(url); _host = _u.netloc.lower() + _u = urlparse(url) + _host = _u.netloc.lower() _referer = "https://dantri.com.vn/" - if "refooty" in _host or "xemlaibongda" in _host: _referer = "https://xemlaibongda.top/" - elif "ytimg" in _host or "youtube" in _host: _referer = "https://www.youtube.com/" - elif "vncecdn" in _host or "vnexpress" in _host: _referer = "https://vnexpress.net/" + if "refooty" in _host or "xemlaibongda" in _host: + _referer = "https://xemlaibongda.top/" + elif "ytimg" in _host or "youtube" in _host: + _referer = "https://www.youtube.com/" + elif "vncecdn" in _host or "vnexpress" in _host: + _referer = "https://vnexpress.net/" r = requests.get(url, headers={**HEADERS, "Referer": _referer}, timeout=10) if r.status_code != 200: return Response(status_code=502) - 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": "*"}) + ct = r.headers.get("Content-Type", "image/jpeg") + return Response(content=r.content, media_type=ct, headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"}) except: return Response(status_code=502) # ===== XEMLAIBONGDA HIGHLIGHTS ===== def _scrape_xemlaibongda_page(page_path, limit=20): + """ + Scrape video từ xemlaibongda.top - Simple & Reliable + Dùng logic cũ đã test, không fetch từng trang (tránh timeout) + """ try: url = f"https://xemlaibongda.top/{page_path}" if page_path else "https://xemlaibongda.top/" - r = requests.get(url, headers=HEADERS, timeout=8) - if r.status_code != 200: return [] + r = requests.get(url, headers=HEADERS, timeout=15) + if r.status_code != 200: + return [] r.encoding = "utf-8" soup = BeautifulSoup(r.text, "lxml") - videos = []; seen = set() + videos = [] + seen = set() + for a in soup.find_all("a", href=True): href = a.get("href", "") - if "/video/" not in href and "/xem-lai/" not in href: continue - if not href.startswith("http"): href = "https://xemlaibongda.top" + href + if "/video/" not in href and "/xem-lai/" not in href: + continue + + if not href.startswith("http"): + href = "https://xemlaibongda.top" + href + + # Bỏ query params clean_href = href.split("?")[0].split("#")[0] - if clean_href in seen: continue + if clean_href in seen: + continue seen.add(clean_href) + + # ===== Lấy THUMBNAIL ===== img_src = "" img = a.find("img") - if not img and a.parent: img = a.parent.find("img") + if not img and a.parent: + img = a.parent.find("img") if not img: p = a.parent for _ in range(4): - if p and p.find("img"): img = p.find("img"); break + if p and p.find("img"): + img = p.find("img") + break p = p.parent if p else None + if img: - 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", "")) - if img_src.startswith("//"): img_src = "https:" + img_src - elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src + 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", "")) + if img_src.startswith("//"): + img_src = "https:" + img_src + elif img_src.startswith("/"): + img_src = "https://xemlaibongda.top" + img_src + + # Try background-image on parent divs if not img_src: p = a.parent for _ in range(5): @@ -196,276 +283,182 @@ def _scrape_xemlaibongda_page(page_path, limit=20): elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src break p = p.parent if p else None + + # ===== Lấy TITLE ===== title = "" + # Thử attribute for attr in ["title", "aria-label"]: val = a.get(attr, "") - if val and len(val) >= 5: title = val; break + if val and len(val) >= 5: + title = val + break + + # Thử các selector if not title: for selector in ["h3", "h2", "h4", ".title", ".video-title", "strong"]: try: el = a.select_one(selector) - if el: t = el.get_text(strip=True) - if t and len(t) >= 5: title = t; break - except: pass + if el: + t = el.get_text(strip=True) + if len(t) >= 5: + title = t + break + except: + pass + + # Thử text content if not title: text = a.get_text(strip=True) - if text and len(text) >= 5: title = text[:100] + if text and len(text) >= 5: + title = text[:100] + + # Fallback: tạo title từ slug if not title or len(title) < 3: slug = clean_href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/") title = slug.replace("-", " ").replace("_", " ").title() title = re.sub(r'\d{4}-\d{2}-\d{2}', '', title).strip() - if not title or len(title) < 3: continue + + if not title or len(title) < 3: + continue + + # Fallback thumbnail từ slug if not img_src: slug = clean_href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/") img_src = f"https://xemlaibongda.top/uploads/thumb/{slug}.jpg" - videos.append({"title": title[:100], "link": clean_href, "img": img_src, "source": "xemlaibongda", "published": _video_published(img_src, clean_href)}) - if len(videos) >= limit: break + + videos.append({ + "title": title[:100], + "link": clean_href, + "img": img_src, + "source": "xemlaibongda" + }) + + if len(videos) >= limit: + break + return videos except Exception as e: - print(f"[xemlaibongda] Error: {e}"); return [] + print(f"[xemlaibongda] Error: {e}") + return [] + +def _extract_img_src(a_tag): + """Extract image URL từ thẻ và parent elements""" + img = a_tag.find("img") + if not img and a_tag.parent: + img = a_tag.parent.find("img") + if not img: + p = a_tag.parent + for _ in range(5): # Tìm sâu hơn + if p and p.find("img"): + img = p.find("img") + break + p = p.parent if p else None + + if not img: + return "" + + # Thử tất cả các attribute có thể chứa img URL + attrs = ["data-src", "src", "data-lazy", "data-original", "data-srcset", "data-thumb", "data-image"] + for attr in attrs: + val = img.get(attr, "") + if val: + if attr == "data-srcset": + val = val.split(",")[0].strip().split(" ")[0] + break + else: + val = "" + + # Thử background-image từ style + if not val: + style = img.get("style", "") or img.get("data-bg", "") + bg_match = re.search(r'url\(["\']?(.*?)["\']?\)', style) + if bg_match: + val = bg_match.group(1) + + # Normalize URL + if val.startswith("//"): + val = "https:" + val + elif val.startswith("/"): + val = "https://xemlaibongda.top" + val + + return val + +def _extract_title(a_tag, href): + """Extract title từ thẻ và child/parent elements""" + title = "" + + # 1. Thử các selector phổ biến cho title + title_selectors = [ + "h3", "h2", "h4", "h5", + ".title", ".post-title", ".entry-title", ".video-title", + ".card-title", ".item-title", ".news-title", + "span.title", "strong", "b", + ".name", ".caption" + ] + for tag in title_selectors: + try: + t = a_tag.select_one(tag) if hasattr(a_tag, 'select_one') else None + if t: + title = t.get_text(" ", strip=True) + if len(title) >= 3: + return title + except: + pass + + # 2. Thử attribute của + for attr in ["title", "aria-label", "data-title"]: + val = a_tag.get(attr, "") + if val and len(val) >= 3: + return val + + # 3. Thử alt text của img + img = a_tag.find("img") + if img: + alt = img.get("alt", "") + if alt and len(alt) >= 3: + return alt + + # 4. Thử text content của (loại bỏ quá dài) + text = a_tag.get_text(" ", strip=True) + if text and len(text) >= 3: + # Lấy dòng đầu tiên nếu có nhiều dòng + lines = [l.strip() for l in text.split("\n") if l.strip()] + if lines: + first_line = lines[0] + if len(first_line) >= 3: + return first_line[:100] + + # 5. Fallback: tạo title từ slug + slug = href.split("/video/")[-1].rstrip("/").split("/xem-lai/")[-1].rstrip("/") + title = slug.replace("-", " ").replace("_", " ") + title = re.sub(r'\d{4}-\d{2}-\d{2}', '', title).strip() + if title: + return title.title() + + return "" def scrape_xemlaibongda(): return _scrape_xemlaibongda_page("", 20) def scrape_highlights_by_league(league_key): if league_key not in HL_LEAGUES: return [] - # Try bongdaplus.vn first (reliable from HF Spaces), fallback from there - bp_vids = scrape_bongdaplus_by_league(league_key, 20) - if bp_vids: return bp_vids - # Fallback: xemlaibongda.top (may be slow/unreachable) - vids = _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"], 20) - if vids: return vids - # Ultimate fallback: bongdaplus.vn general video feed, only for primary home league - if league_key == "premier-league": - return scrape_bongdaplus_videos(20) - return [] + return _scrape_xemlaibongda_page(HL_LEAGUES[league_key]["path"], 20) def scrape_all_league_highlights(): results = {} def _fetch(key): return key, scrape_highlights_by_league(key) with ThreadPoolExecutor(8) as ex: futs = [ex.submit(_fetch, k) for k in HL_LEAGUES] - for f in as_completed(futs, timeout=20): - try: key, vids = f.result() - except: continue - if vids: results[key] = vids - if not results: - fb = scrape_bongdaplus_videos(20) - if fb: - results["premier-league"] = fb - # The league sub-pages resolve to the SAME content from this server (the - # football sites serve one generic list regardless of league path). Return - # the unique videos once per league (deduped against the global set) and - # enrich with the general bongdaplus feed so the homepage slider gets a - # genuinely bigger, duplicate-free list instead of 8x the same 10 clips. - global_seen = set() - seen_per_league = {} - enriched = {} - try: - extra = scrape_bongdaplus_videos(40) - except Exception: - extra = [] - for key, vids in list(results.items()): - uniq = [] - fresh = [] - for v in vids: - link = (v or {}).get("link", "") - if not link or link in seen_per_league.get(key, set()): continue - seen_per_league.setdefault(key, set()).add(link) - if link in global_seen: - fresh.append(v) # duplicate across leagues — will dedupe - continue - global_seen.add(link) - uniq.append(v) - # league-local unique list - if uniq: - results[key] = uniq - # still add across-league dupes to each league so per-league feeds - # are non-empty, but ONLY if the league has < 10 unique videos - if len(uniq) < 10: - for v in fresh: - link = (v or {}).get("link", "") - if link in seen_per_league.get(key, set()): continue - seen_per_league[key].add(link) - uniq.append(v) - results[key] = uniq - # enrich league with global feed leftovers when it's still thin - if len(uniq) < 10: - for v in extra: - link = (v or {}).get("link", "") - if not link or link in seen_per_league.get(key, set()): continue - seen_per_league[key].add(link) - uniq.append(v) - results[key] = uniq - return results - -BDP_HL = "https://bongdaplus.vn/video" -def _video_published(img_src, link=""): - """Best-effort publish date from image URL (bongdaplus stores dates as - /Media/YYYY/MM/DD/) or from a dated slug. Returns 'YYYY-MM-DD' or ''.""" - try: - if img_src: - m = re.search(r"/Media/(\d{4})/(\d{2})/(\d{2})/", img_src) - if m: - return "%s-%s-%s" % (m.group(1), m.group(2), m.group(3)) - if link: - m2 = re.search(r"/(\d{4})/(\d{2})/(\d{2})/", link) - if m2: - return "%s-%s-%s" % (m2.group(1), m2.group(2), m2.group(3)) - except Exception: - pass - return "" - -def scrape_bongdaplus_videos(limit=20): - """Scrape football highlight/clip videos from bongdaplus.vn/video (reachable from HF Spaces).""" - try: - r = requests.get(BDP_HL, headers=HEADERS, timeout=15) - if r.status_code != 200: return [] - r.encoding = "utf-8" - soup = BeautifulSoup(r.text, "lxml") - videos = []; seen = set() - for a in soup.find_all("a", href=True): - href = a.get("href","") - if "/video/" not in href or not href.endswith(".html"): continue - if not href.startswith("http"): href = "https://bongdaplus.vn" + href - link = href.split("?")[0].split("#")[0] - if link in seen: continue - seen.add(link) - img_src = "" - img = a.find("img") - if img: - img_src = img.get("data-src","") or img.get("src","") or "" - title = "" - t = a.get("title","") or "" - if t and len(t)>=5: title = t - if not title: - img_alt = img.get("alt","") if img else "" - if img_alt and len(img_alt)>=5: title = img_alt - if not title: - txt = a.get_text(strip=True) - if txt and len(txt)>=5: title = txt - title = re.sub(r'^(VIDEO\s*:\s*|VIDEO\s+)', '', title, flags=re.I).strip() - if not title or len(title)<5: continue - if img_src and img_src.startswith("//"): img_src = "https:" + img_src - videos.append({"title": title[:100], "link": link, "img": img_src, "source": "bongdaplus", "published": _video_published(img_src, link)}) - if len(videos) >= limit: break - return videos - except Exception as e: - print(f"[bongdaplus] Error: {e}"); return [] - -# Bongdaplus.vn league-specific video URLs (used as fallback when xemlaibongda.top fails) -BDP_LEAGUE_URLS = { - "premier-league": "https://bongdaplus.vn/video/premier-league", - "la-liga": "https://bongdaplus.vn/video/la-liga", - "serie-a": "https://bongdaplus.vn/video/serie-a", - "bundesliga": "https://bongdaplus.vn/video/bundesliga", - "champions-league": "https://bongdaplus.vn/video/champions-league", - "fa-cup": "https://bongdaplus.vn/video/fa-cup", - "europa-league": "https://bongdaplus.vn/video/europa-league", - "world-cup": "https://bongdaplus.vn/video/world-cup", -} -def scrape_bongdaplus_by_league(league_key, limit=20): - """Scrape bongdaplus.vn video page for a specific league.""" - url = BDP_LEAGUE_URLS.get(league_key) - if not url: return [] - try: - r = requests.get(url, headers=HEADERS, timeout=15) - if r.status_code != 200: return [] - r.encoding = "utf-8" - soup = BeautifulSoup(r.text, "lxml") - videos = []; seen = set() - for a in soup.find_all("a", href=True): - href = a.get("href","") - if "/video/" not in href or not href.endswith(".html"): continue - if not href.startswith("http"): href = "https://bongdaplus.vn" + href - link = href.split("?")[0].split("#")[0] - if link in seen: continue - seen.add(link) - img_src = "" - img = a.find("img") - if img: - img_src = img.get("data-src","") or img.get("src","") or "" - title = "" - t = a.get("title","") or "" - if t and len(t)>=5: title = t - if not title: - img_alt = img.get("alt","") if img else "" - if img_alt and len(img_alt)>=5: title = img_alt - if not title: - txt = a.get_text(strip=True) - if txt and len(txt)>=5: title = txt - title = re.sub(r'^(VIDEO\s*:\s*|VIDEO\s+)', '', title, flags=re.I).strip() - if not title or len(title)<5: continue - if img_src and img_src.startswith("//"): img_src = "https:" + img_src - videos.append({"title": title[:100], "link": link, "img": img_src, "source": "bongdaplus", "published": _video_published(img_src, link)}) - if len(videos) >= limit: break - return videos - except Exception as e: - print(f"[bongdaplus:{league_key}] Error: {e}"); return [] - -def extract_bongdaplus_video(url): - """Extract direct MP4 from bongdaplus.vn video detail via its embed page. - - The embed page (/video-embed/{id}.html) sometimes only has a JPG placeholder - as . In that case, fall back to the main video page - (/video/{slug}.html) which contains a YouTube iframe with the actual - highlight. - """ - try: - m = re.search(r'/video/(?:[^/]+-)?(\d+)\.html', url) - if not m: - return None - vid = m.group(1) - embed = f"https://bongdaplus.vn/video-embed/{vid}.html" - r = requests.get(embed, headers=HEADERS, timeout=15) - if r.status_code != 200: return None - r.encoding = "utf-8" - soup = BeautifulSoup(r.text, "lxml") - video = soup.find("video") - src = "" - poster = "" - if video: - src = video.get("src","") - poster = video.get("poster","") - if not src: - src_el = soup.find("source") - if src_el: src = src_el.get("src","") - if not src: return None - src = src.split("?")[0].split("#")[0] - # Only accept real media; placeholder .jpg/jpeg/png means video not available - if not re.search(r'\.(mp4|m3u8|webm)$', src, re.I): - # The embed source is a JPG placeholder — fall back to the main video - # page and look for a YouTube iframe (actual highlight video). + for f in as_completed(futs, timeout=25): try: - r2 = requests.get(url, headers=HEADERS, timeout=15) - if r2.status_code == 200: - soup2 = BeautifulSoup(r2.text, "lxml") - yt_iframe = soup2.find("iframe", src=re.compile(r"youtube\.com/embed|youtube-nocookie\.com/embed")) - if yt_iframe: - yt_src = yt_iframe.get("src","").strip() - if yt_src.startswith("//"): yt_src = "https:" + yt_src - yt_id = re.search(r'/(?:embed|v)/([a-zA-Z0-9_-]{11})', yt_src) - if yt_id: - poster = poster or "" - if not poster: - og = soup2.find("meta", property="og:image") - if og: poster = og.get("content","") - if not poster: - og = soup.find("meta", property="og:image") - if og: poster = og.get("content","") - 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"} - except Exception: - pass - return None - if not poster: - og = soup.find("meta",property="og:image") - if og: poster = og.get("content","") - return {"src": src, "poster": poster, "type": "video"} - except Exception: - return None + key, vids = f.result() + if vids: results[key] = vids + except: pass + return results def extract_xemlaibongda_video(url): try: r=requests.get(url, headers=HEADERS, timeout=15) if r.status_code!=200: return None r.encoding="utf-8"; soup=BeautifulSoup(r.text,"lxml") + # Get og:image as potential poster fallback og=soup.find("meta",property="og:image") og_poster=og.get("content","") if og else "" if og_poster.startswith("//"): og_poster="https:"+og_poster @@ -478,12 +471,94 @@ def extract_xemlaibongda_video(url): if not poster: poster=og_poster if src: return{"src":src,"poster":poster,"type":"hls" if".m3u8" in src else"video"} m3u8s=re.findall(r'(https?://[^\s"\'<>]+\.m3u8)',r.text) - if m3u8s: return{"src":m3u8s[0],"poster":og_poster,"type":"hls"} + if m3u8s: + return{"src":m3u8s[0],"poster":og_poster,"type":"hls"} + # Try YouTube embed yt_iframe = soup.find("iframe", src=re.compile(r"youtube\.com/embed|youtube-nocookie\.com/embed")) - if yt_iframe: return{"src":yt_iframe.get("src",""),"poster":og_poster,"type":"youtube"} + if yt_iframe: + yt_src = yt_iframe.get("src","") + return{"src":yt_src,"poster":og_poster,"type":"youtube"} return None except: return None +# ===== YOUTUBE SHORTS SCRAPING ===== +def _yt_channel_shorts_requests(channel, count=15): + try: + url=f"https://www.youtube.com/@{channel}/shorts" + r=requests.get(url, headers={**HEADERS,"Accept-Language":"vi,en;q=0.8"}, timeout=15) + if r.status_code!=200: return [] + html=r.text; ids=[]; items=[] + for m in re.finditer(r'"videoId":"([A-Za-z0-9_-]{11})"',html): + vid=m.group(1) + if vid in ids: continue + ids.append(vid) + snip=html[max(0,m.start()-900):m.start()+1600] + title="" + mt=re.search(r'"title":\{"runs":\[\{"text":"([^"]+)"',snip) + if not mt: mt=re.search(r'"accessibilityText":"([^"]+)"',snip) + if mt: title=html_lib.unescape(mt.group(1)).replace('\n',' ').strip() + if not title: title="YouTube Short" + 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}) + if len(items)>=count: break + return items + except: return [] + +def scrape_shorts(): + """Priority 1: runtime cache from GitHub Actions updater""" + cached = get_runtime_cache() + if cached and len(cached) >= 10: + return cached[:60] + + # Priority 2: try live YouTube scrape (fast-fail on HF Spaces) + vids=[] + try: + with ThreadPoolExecutor(3) as ex: + futs=[ex.submit(_yt_channel_shorts_requests,ch,24) for ch in ["baodantri7941","baosuckhoedoisongboyte","vtvnambo"]] + for f in as_completed(futs, timeout=8): # 8s cap + try: + r=f.result() + if r: vids.extend(r) + except: pass + except: pass + + # Priority 3: hardcoded fallback + if not vids: + vids = list(SHORTS_FALLBACK) + + merged=[]; seen=set() + for v in vids: + vid=v.get("id") + if not vid or vid in seen: continue + seen.add(vid); merged.append(v) + for v in SHORTS_FALLBACK: + vid=v.get("id") + if not vid or vid in seen: continue + seen.add(vid); merged.append(v) + return merged[:60] + +# ===== VTV NAM BO & WC SHORTS - using yt-dlp ===== +from yt_scraper import get_vtvnambo_shorts, get_wc_related_shorts + +@app.get("/api/shorts/vtvnamo") +def api_shorts_vtvnamo(count: int = Query(default=50, le=100)): + items = get_vtvnambo_shorts(count) + if not items: + items = [v for v in SHORTS_FALLBACK if v.get("channel") == "vtvnambo"] + nql = [v for v in items if v.get("id") == "nqlLH6chLRo"] + rest = [v for v in items if v.get("id") != "nqlLH6chLRo"] + items = nql + rest + return JSONResponse(items) + +@app.get("/api/shorts/wc") +def api_shorts_wc(count: int = Query(default=50, le=100)): + items = get_wc_related_shorts(count) + if not items: + items = [v for v in SHORTS_FALLBACK if v.get("channel") == "vtvnambo"] + nql = [v for v in items if v.get("id") == "nqlLH6chLRo"] + rest = [v for v in items if v.get("id") != "nqlLH6chLRo"] + items = nql + rest + return JSONResponse(items) + # ===== LIVESCORE ===== @app.get("/api/livescore/live") def api_livescore_live(): return JSONResponse({"html":_cached("ls_live",lambda:fetch_bongda_api("/api/fixtures/live"),ttl=_cache_ttl_live)}) @@ -497,207 +572,9 @@ def api_livescore_results(): 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)}) @app.get("/api/livescore/standings/{league}") def api_livescore_standings(league:str): - 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)}) + 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)}) @app.get("/api/livescore/date/{date}") def api_livescore_date(date:str):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/get-by-date?date={date}")}) - -def _compute_updates7d(): - from datetime import date as _date - today = _date.today() - all_html = [] - # Past 7 days (results) - for i in range(7, 0, -1): - d = (today - timedelta(days=i)).strftime("%Y-%m-%d") - html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}&status=finished") - if html and len(html) > 50: - soup = BeautifulSoup(html, "lxml") - day_label = (today - timedelta(days=i)).strftime("%d/%m") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime"}) - dt.string = f"📅 {day_label}" - match.insert(0, dt) - all_html.append(str(soup)) - # Next 7 days (upcoming) - for i in range(7): - d = (today + timedelta(days=i)).strftime("%Y-%m-%d") - html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}") - if html and len(html) > 50: - soup = BeautifulSoup(html, "lxml") - day_label = (today + timedelta(days=i)).strftime("%d/%m") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime"}) - dt.string = f"📅 {day_label}" - match.insert(0, dt) - all_html.append(str(soup)) - combined = "
" + "".join(all_html) + "
" - return combined if all_html else "" - -_updates7d_cache = {"t": 0, "d": "", "busy": False} -_updates7d_lock = threading.Lock() -def _start_updates7d_refresh(): - def _run(): - try: - with _updates7d_lock: - if _updates7d_cache["busy"]: return - _updates7d_cache["busy"] = True - data = _compute_updates7d() - with _updates7d_lock: - if data: - _updates7d_cache["t"] = time.time() - _updates7d_cache["d"] = data - _updates7d_cache["busy"] = False - except Exception: - with _updates7d_lock: - _updates7d_cache["busy"] = False - th = threading.Thread(target=_run, daemon=True) - th.start() - -@app.get("/api/livescore/updates7d") -def api_livescore_updates7d(): - """Aggregate matches. Never blocks synchronously — returns cached value instantly - and refreshes in a background thread. Pre-warmed at startup.""" - now = time.time() - with _updates7d_lock: - fresh = _updates7d_cache["d"] and (now - _updates7d_cache["t"] < _cache_ttl) - stale = _updates7d_cache["d"] - if not fresh: - _start_updates7d_refresh() - return JSONResponse({"html": stale or "", "cached": bool(stale)}) - -# ===== LIVESCORE RECENT (prioritized: upcoming → just-finished today → yesterday → older) ===== -def _compute_recent(): - """Compute recent livescore with priority: upcoming → just-finished today → yesterday → older.""" - from datetime import date as _date - today = _date.today() - all_html = [] - - # Helper to extract match details with date label - def _extract_matches(date_str, day_label, status_param=""): - url_path = f"/api/fixtures/get-by-date?date={date_str}" - if status_param: - url_path += f"&status={status_param}" - html = fetch_bongda_api(url_path) - if not html or len(html) <= 50: - return - soup = BeautifulSoup(html, "lxml") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime section-date"}) - dt.string = f"📅 {day_label}" - match.insert(0, dt) - all_html.append(str(soup)) - - # 1) Trận sắp tới (hôm nay + ngày mai) - upcoming_html = [] - for offset in [0, 1]: - d = (today + timedelta(days=offset)).strftime("%Y-%m-%d") - day_label = (today + timedelta(days=offset)).strftime("%d/%m") - html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}") - if html and len(html) > 50: - soup = BeautifulSoup(html, "lxml") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime section-date"}) - dt.string = f"📅 {day_label}" - match.insert(0, dt) - upcoming_html.append(str(soup)) - if upcoming_html: - all_html.append("
⏰ Trận sắp tới
" + "".join(upcoming_html) + "
") - - # 2) Vừa kết thúc hôm nay - today_str = today.strftime("%Y-%m-%d") - finished_today = fetch_bongda_api(f"/api/fixtures/get-by-date?date={today_str}&status=finished") - if finished_today and len(finished_today) > 50: - soup = BeautifulSoup(finished_today, "lxml") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime section-date"}) - dt.string = f"📅 {today.strftime('%d/%m')}" - match.insert(0, dt) - all_html.append("
✅ Vừa kết thúc
" + str(soup) + "
") - - # 3) Hôm qua - yesterday = today - timedelta(days=1) - d = yesterday.strftime("%Y-%m-%d") - html_yesterday = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}&status=finished") - if html_yesterday and len(html_yesterday) > 50: - soup = BeautifulSoup(html_yesterday, "lxml") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime section-date"}) - dt.string = f"📅 {yesterday.strftime('%d/%m')}" - match.insert(0, dt) - all_html.append("
📅 Hôm qua
" + str(soup) + "
") - - # 4) Các ngày cũ hơn (2 ngày trước → 6 ngày trước) - older_html = [] - for i in range(2, 7): - d = (today - timedelta(days=i)).strftime("%Y-%m-%d") - day_label = (today - timedelta(days=i)).strftime("%d/%m") - html = fetch_bongda_api(f"/api/fixtures/get-by-date?date={d}&status=finished") - if html and len(html) > 50: - soup = BeautifulSoup(html, "lxml") - for match in soup.select(".match-detail"): - dt = soup.new_tag("div", **{"class": "datetime section-date"}) - dt.string = f"📅 {day_label}" - match.insert(0, dt) - older_html.append(str(soup)) - if older_html: - all_html.append("
🗓️ Kết quả trước
" + "".join(older_html) + "
") - - combined = "
" + "".join(all_html) + "
" - return combined if all_html else "" - -_recent_cache = {"t": 0, "d": "", "busy": False} -_recent_lock = threading.Lock() -def _start_recent_refresh(): - def _run(): - try: - with _recent_lock: - if _recent_cache["busy"]: return - _recent_cache["busy"] = True - data = _compute_recent() - with _recent_lock: - if data: - _recent_cache["t"] = time.time() - _recent_cache["d"] = data - _recent_cache["busy"] = False - except Exception: - with _recent_lock: - _recent_cache["busy"] = False - th = threading.Thread(target=_run, daemon=True) - th.start() - -@app.get("/api/livescore/recent") -def api_livescore_recent(): - """Recent matches with new priority: upcoming today/tomorrow → finished today → yesterday → older.""" - now = time.time() - with _recent_lock: - fresh = _recent_cache["d"] and (now - _recent_cache["t"] < _cache_ttl) - stale = _recent_cache["d"] - if not fresh: - _start_recent_refresh() - return JSONResponse({"html": stale or "", "cached": bool(stale)}) - -def _warm_recent(): - def _warm(): - try: - time.sleep(3) - _start_recent_refresh() - except Exception: - pass - th = threading.Thread(target=_warm, daemon=True) - th.start() -_warm_recent() - -def _warm_updates7d(): - # Lightweight startup pre-warm so the first user request is instant. - def _warm(): - try: - time.sleep(3) - _start_updates7d_refresh() - except Exception: - pass - th = threading.Thread(target=_warm, daemon=True) - th.start() -_warm_updates7d() - @app.get("/api/match/{event_id}/commentaries") def api_match_commentaries(event_id:int):return JSONResponse({"html":fetch_bongda_api(f"/api/fixtures/commentaries?event_id={event_id}")}) @app.get("/api/match/{event_id}/stats") @@ -705,6 +582,10 @@ def api_match_stats(event_id:int):return JSONResponse({"html":fetch_bongda_api(f from match_detail_v2 import fetch_match_detail, fetch_match_detail_by_url +# ===== SHORTS RUNTIME CACHE (GitHub Actions updater) ===== +from shorts_cache import get_runtime_cache, set_runtime_cache, get_cache_status, SHORTS_UPDATE_SECRET +import hmac, hashlib as _hashlib + @app.get("/api/match/{event_id}/detail") def api_match_detail(event_id: int, url: str = Query(default="")): try: @@ -734,8 +615,43 @@ def api_livescore_featured(): return None return JSONResponse(_cached("ls_featured",_f,ttl=30)) +@app.get("/api/shorts") +def api_shorts(channel: str = Query(default="")): + if channel == "vtvnambo": return api_shorts_vtvnamo() + if channel == "wc": return api_shorts_wc() + return JSONResponse(_cached("yt_shorts_v3",scrape_shorts,ttl=_cache_ttl_yt)) + +@app.get("/api/short-stats") +def api_short_stats(ids:str=Query(default="")): + arr=[x for x in ids.split(",") if x] + with _short_lock: + db=_load_short_db();out={} + for vid in arr: + st=db.get(vid) or _short_default() + 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]} + return JSONResponse({"stats":out}) + +@app.post("/api/short-action") +async def api_short_action(request:Request): + try: body=await request.json() + except: body={} + vid=str(body.get("id","")).strip(); action=str(body.get("action","")).strip(); txt=str(body.get("text","")).strip() + if not vid: return JSONResponse({"error":"missing id"},status_code=400) + with _short_lock: + db=_load_short_db(); st=db.get(vid) or _short_default() + if action=="view": st["views"]=int(st.get("views",0))+1 + elif action=="like": st["likes"]=int(st.get("likes",0))+1 + elif action=="share": st["shares"]=int(st.get("shares",0))+1 + elif action=="comment" and txt: + comments=st.get("comments",[]) + comments.insert(0,{"text":txt[:180],"ts":int(time.time())}) + st["comments"]=comments[:80] + st["updated"]=int(time.time()); db[vid]=st; _save_short_db(db) + out={"views":int(st.get("views",0)),"likes":int(st.get("likes",0)),"shares":int(st.get("shares",0)),"comments":st.get("comments",[])[:80]} + return JSONResponse({"stats":out}) + @app.get("/api/highlights") -def api_highlights(): return JSONResponse(_cached("xemlaibongda_hl",lambda: scrape_bongdaplus_videos(20) or scrape_xemlaibongda(),ttl=_cache_ttl)) +def api_highlights(): return JSONResponse(_cached("xemlaibongda_hl",scrape_xemlaibongda,ttl=_cache_ttl)) @app.get("/api/highlights/leagues") def api_highlights_leagues(): return JSONResponse(_cached("hl_leagues",scrape_all_league_highlights,ttl=_cache_ttl)) @app.get("/api/highlights/{league}") @@ -743,47 +659,6 @@ def api_highlights_league(league:str): if league not in HL_LEAGUES: return JSONResponse({"error":"league not found"}) return JSONResponse(_cached(f"hl_{league}",lambda:scrape_highlights_by_league(league),ttl=_cache_ttl)) -@app.get("/api/highlights/{league}/page") -def api_highlights_league_page(league:str, page:int=Query(default=0, ge=0), limit:int=Query(default=15, ge=5, le=40)): - """Paginated league highlights for 'Xem thêm' load-more. Supports 'all' to fetch every league aggregated.""" - if league == "all": - all_vids = [] - with ThreadPoolExecutor(8) as ex: - futs = {ex.submit(scrape_highlights_by_league, k): k for k in HL_LEAGUES} - for f in as_completed(futs, timeout=20): - try: - all_vids.extend(f.result()) - except: pass - # The league sub-pages resolve to the same content from this server, - # so dedupe by link — the slider/feed must not show 8x the same 10 - # videos. If dedup leaves few unique items, enrich from the general - # bongdaplus video feed to add genuinely different videos. - seen = set(); uniq = [] - for v in all_vids: - link = (v or {}).get("link", "") - if not link or link in seen: continue - seen.add(link); uniq.append(v) - if len(uniq) < 20: - try: - extra = scrape_bongdaplus_videos(40) - for v in extra: - link = (v or {}).get("link", "") - if not link or link in seen: continue - seen.add(link); uniq.append(v) - except Exception: - pass - all_vids = uniq - start = page * limit - end = start + limit - paged = all_vids[start:end] - return JSONResponse({"videos": paged, "league": "all", "page": page, "has_more": end < len(all_vids), "total": len(all_vids)}) - if league not in HL_LEAGUES: return JSONResponse({"error":"league not found"}) - all_vids = scrape_highlights_by_league(league) - start = page * limit - end = start + limit - paged = all_vids[start:end] - return JSONResponse({"videos": paged, "league": league, "page": page, "has_more": end < len(all_vids), "total": len(all_vids)}) - @app.get("/api/video_url") def api_video_url(url:str=Query(...), img:str=Query(default="")): if "youtube.com" in url or "youtu.be" in url: @@ -793,147 +668,60 @@ def api_video_url(url:str=Query(...), img:str=Query(default="")): v=extract_xemlaibongda_video(url) if v: if v["type"]=="hls": v["src"]="/api/proxy/m3u8?url="+quote(v["src"],safe="") - if not v.get("poster") and img: v["poster"] = img - return JSONResponse(v) - if "bongdaplus.vn" in url and "/video/" in url: - v=extract_bongdaplus_video(url) - if v: - if not v.get("poster") and img: v["poster"] = img + # Use provided img as poster fallback if video page has no poster + if not v.get("poster") and img: + v["poster"] = img return JSONResponse(v) return JSONResponse({"error":"not found"}) -# ===== FPT PLAY (YouTube channel) API ===== -# The datacenter cannot reach youtube.com directly, so this endpoint keeps a -# persisted list of the channel's latest videos. The frontend (running in the -# user's browser, which CAN reach YouTube) periodically fetches the channel via -# r.jina.ai, then POSTs the result here so the slide auto-updates when the -# channel uploads — exactly like "Thêm Short HOT" but fully automatic. -FPT_FILE = "/data/fpt_play_videos.json" -FPT_CHANNEL_URL = "https://www.youtube.com/@fptbongdaofficial" -FPT_CACHE_TTL = 600 # 10 min - -def _fpt_load(): - try: - if os.path.exists(FPT_FILE): - with open(FPT_FILE, encoding="utf-8") as f: - j = json.load(f) - if isinstance(j, list): - return j - except Exception: - pass - return [] - -def _fpt_save(videos): - try: - with open(FPT_FILE, "w", encoding="utf-8") as f: - json.dump(videos, f, ensure_ascii=False) - except Exception: - pass - -def _fpt_try_server_fetch(): - """Server-side attempt (jina proxy with our Origin). Usually blocked from - the datacenter, but harmless to try once so the slide works even without - a client push.""" - try: - _hdrs = dict(HEADERS) - _hdrs["Origin"] = "https://bep40-vnews.hf.space" - r = requests.get("https://r.jina.ai/" + FPT_CHANNEL_URL + "/videos", - headers=_hdrs, timeout=40) - if r.status_code != 200: - return [] - txt = r.text - out = [] - seen = set() - # jina markdown lists entries as "1. Title - url" or link lines with yt ids - for m in re.finditer(r"https?://(?:www\.)?youtube\.com/watch\?v=([a-zA-Z0-9_-]{11})", txt): - vid = m.group(1) - if vid in seen: continue - seen.add(vid) - out.append({ - "id": vid, - "title": "", - "link": "https://youtu.be/" + vid, - "img": "https://i.ytimg.com/vi/%s/hqdefault.jpg" % vid, - "source": "fptplay", - "published": "", - }) - return out - except Exception: - return [] - -@app.get("/api/fptplay/videos") -def api_fptplay_videos(): - vids = _fpt_load() - if not vids: - vids = _fpt_try_server_fetch() - if vids: _fpt_save(vids) - return JSONResponse({"channel": FPT_CHANNEL_URL, "videos": vids, "updated": int(time.time())}) - -@app.post("/api/fptplay/update") -async def api_fptplay_update(request: Request): - try: - body = await request.json() - except Exception: - body = {} - incoming = body.get("videos") or [] - if not isinstance(incoming, list) or not incoming: - return JSONResponse({"ok": True, "videos": _fpt_load()}) - seen = set() - merged = [] - for v in _fpt_load(): - vid = (v or {}).get("id", "") - if vid and vid in seen: continue - if vid: seen.add(vid) - merged.append(v) - added = 0 - for v in incoming: - vid = (v or {}).get("id", "") or "" - if not vid or vid in seen: continue - seen.add(vid) - # keep user-friendly fields, always normalize the watch link - merged.append({ - "id": vid, - "title": (v.get("title") or "").strip()[:200], - "link": (v.get("link") or "https://youtu.be/" + vid), - "img": (v.get("img") or "https://i.ytimg.com/vi/%s/hqdefault.jpg" % vid), - "source": "fptplay", - "published": (v.get("published") or "")[:10], - }) - added += 1 - # newest first - merged.sort(key=lambda x: (x.get("published") or ""), reverse=True) - _fpt_save(merged[:50]) - return JSONResponse({"ok": True, "added": added, "videos": merged[:50]}) - # ===== WORLD CUP 2026 API ===== -_wc_request_times = []; _wc_rate_limit_lock = threading.Lock() -_WC_RATE_LIMIT = 10 +# Rate limiting cho WC API +_wc_request_times = [] +_wc_rate_limit_lock = threading.Lock() +_WC_RATE_LIMIT = 10 # Max 10 requests per minute + def _wc_rate_limit(): + """Kiểm tra rate limit cho WC API""" global _wc_request_times with _wc_rate_limit_lock: now = time.time() + # Xóa các request cũ hơn 60 giây _wc_request_times = [t for t in _wc_request_times if now - t < 60] - if len(_wc_request_times) >= _WC_RATE_LIMIT: return False + if len(_wc_request_times) >= _WC_RATE_LIMIT: + return False _wc_request_times.append(now) return True @app.get("/api/wc2026") def api_wc2026(): + """Trả về tất cả dữ liệu World Cup 2026""" return JSONResponse(_cached("wc2026", get_wc2026_all, ttl=_cache_ttl)) @app.get("/api/wc2026/{tab}") def api_wc2026_tab(tab: str): + """Trả về từng tab của World Cup""" valid_tabs = ["news", "fixtures", "standings", "stats", "highlights"] - if tab not in valid_tabs: return JSONResponse({"error": "invalid tab"}, status_code=400) + if tab not in valid_tabs: + return JSONResponse({"error": "invalid tab"}, status_code=400) + def _fetch_tab(): - if tab == "highlights": return scrape_highlights_by_league("world-cup") - elif tab == "news": return scrape_wc_news() - elif tab == "fixtures": return scrape_fixtures() - elif tab == "standings": return scrape_standings() - elif tab == "stats": return scrape_stats() + if tab == "highlights": + return scrape_highlights_by_league("world-cup") + elif tab == "news": + return scrape_wc_news() + elif tab == "fixtures": + return scrape_fixtures() + elif tab == "standings": + return scrape_standings() + elif tab == "stats": + return scrape_stats() return [] + return JSONResponse(_cached(f"wc2026_{tab}", _fetch_tab, ttl=_cache_ttl)) +# Note: WC functions (scrape_wc_news, scrape_fixtures, scrape_stats, scrape_standings) +# are imported from wc2026_scraper.py at the top of this file + @app.get("/api/bdp_videos") def api_bdp_videos(): def _f(): @@ -970,8 +758,7 @@ def scrape_vne(cat_url): if src: img=src.get("srcset","").split(",")[0].strip().split(" ")[0] arts.append({"title":t,"link":lk,"img":img,"source":"vne"}) return arts - except Exception: - return [] + except: return [] def scrape_genk_ai(): try: @@ -991,7 +778,8 @@ def scrape_genk_ai(): for img in container.find_all("img"): s=img.get("data-src","") or img.get("src","") if s and "mediacdn" in s and "avatar" not in s and "logo" not in s: img_src=s; break - if img_src: break; container=container.parent + if img_src: break + container=container.parent seen.add(href) if not img_src: try: @@ -1034,28 +822,23 @@ def api_categories(): for k,(u,n) in VNE_CATS.items(): cats.append({"id":k,"name":n,"source":"vne"}) return JSONResponse(cats) + @app.get("/api/proxy/xlb") -def api_xlb(path: str = Query(default=""), limit: int = Query(default=20)): - # Try xemlaibongda.top first (fast timeout), fallback to bongdaplus.vn - videos = _do_xlb_scrape_xlb(path, limit) - if not videos: - videos = _do_xlb_scrape_bdp(limit) - if not videos: - return JSONResponse({"videos": [], "error": "No videos available"}) - return JSONResponse({"videos": videos}) - -def _do_xlb_scrape_xlb(path, limit): +def api_xlb(path: str = Query(default="", description="Path after xemlaibongda.top"), limit: int = Query(default=20)): try: url = f"https://xemlaibongda.top/{path}" if path else "https://xemlaibongda.top/" - r = requests.get(url, headers=HEADERS, timeout=8) - if r.status_code != 200: return [] + r = requests.get(url, headers=HEADERS, timeout=15) + if r.status_code != 200: + return JSONResponse({"videos": []}) r.encoding = "utf-8" soup = BeautifulSoup(r.text, "lxml") videos, seen = [], set() for a in soup.find_all("a", href=True): href = a.get("href", "") - if "/video/" not in href and "/xem-lai/" not in href: continue - if not href.startswith("http"): href = "https://xemlaibongda.top" + href + if "/video/" not in href and "/xem-lai/" not in href: + continue + if not href.startswith("http"): + href = "https://xemlaibongda.top" + href clean = href.split("?")[0].split("#")[0] if clean in seen: continue seen.add(clean) @@ -1064,10 +847,13 @@ def _do_xlb_scrape_xlb(path, limit): if not img: p = a.parent for _ in range(5): - if p and p.find("img"): img = p.find("img"); break + if p and p.find("img"): + img = p.find("img") + break p = p.parent if p else None if img: - img_src = (img.get("data-src", "") or img.get("src", "") or img.get("data-lazy", "") or img.get("data-original", "")) + img_src = (img.get("data-src", "") or img.get("src", "") or + img.get("data-lazy", "") or img.get("data-original", "")) if img_src.startswith("//"): img_src = "https:" + img_src elif img_src.startswith("/"): img_src = "https://xemlaibongda.top" + img_src title = a.find("h3") @@ -1077,19 +863,11 @@ def _do_xlb_scrape_xlb(path, limit): if not t: slug = clean.split("/video/")[-1].rstrip("/") t = slug.replace("-", " ").title() - videos.append({"title": t[:100], "link": clean, "img": img_src, "source": "xemlaibongda", "published": _video_published(img_src, clean)}) + videos.append({"title": t[:100], "link": clean, "img": img_src, "source": "xemlaibongda"}) if len(videos) >= limit: break - return videos - except Exception: - return [] - -def _do_xlb_scrape_bdp(limit): - """Fallback: scrape bongdaplus.vn videos for the xlb endpoint.""" - try: - return scrape_bongdaplus_videos(limit) - except Exception: - return [] - + return JSONResponse({"videos": videos}) + except Exception as e: + return JSONResponse({"videos": [], "error": str(e)}) @app.get("/api/article") def api_article(url:str=Query(...)): try: @@ -1110,6 +888,59 @@ def api_storage_status(): def api_hot_topics(): return JSONResponse({"topics":[]}) +# ===== SHORTS EXTERNAL UPDATER ENDPOINTS ===== +@app.get("/api/shorts/status") +def api_shorts_updater_status(): + """Check shorts cache status""" + return JSONResponse(get_cache_status()) + +@app.post("/api/shorts/update") +async def api_shorts_updater(request: Request): + """Receive fresh shorts from GitHub Actions updater + + Headers: + X-Signature: HMAC-SHA256(body, SHORTS_UPDATE_SECRET) + Body: + {"items": [...], "source": "yt-dlp", "fetched_at": timestamp} + """ + body = await request.body() + sig = request.headers.get("X-Signature", "") + + # Verify HMAC signature + expected = _hashlib.new('sha256', body, usedforsecurity=False) + # Use hmac properly + import hmac as hmac_mod + expected_sig = hmac_mod.new( + SHORTS_UPDATE_SECRET.encode(), + body, + _hashlib.sha256 + ).hexdigest() + + if not hmac_mod.compare_digest(sig, expected_sig): + from fastapi import HTTPException + raise HTTPException(status_code=401, detail="invalid signature") + + try: + data = json.loads(body) + except: + from fastapi import HTTPException + raise HTTPException(status_code=400, detail="invalid JSON") + + items = data.get("items", []) + if not items: + from fastapi import HTTPException + raise HTTPException(status_code=400, detail="no items") + + count = set_runtime_cache(items) + return JSONResponse({ + "ok": True, + "saved": count, + "source": data.get("source", "unknown"), + "fetched_at": data.get("fetched_at", time.time()), + }) + @app.get("/", response_class=HTMLResponse) async def root(): - return HTMLResponse("

VNEWS v17

VTV Digital CDN ssaimh · No shorts Dantri/SKDS · Homepage full content

") \ No newline at end of file + return HTMLResponse("

VNEWS v15

Shorts external updater active

") +# v15 2026-06-29 - shorts external updater + diff --git a/patch_ai_hot.py b/patch_ai_hot.py deleted file mode 100644 index b5e7e0b6d8708e76b41075e33ebdd206afa72773..0000000000000000000000000000000000000000 --- a/patch_ai_hot.py +++ /dev/null @@ -1,55 +0,0 @@ -"""PATCH AI: prepend AI topics to hot list + homepage route fix""" -import re, json, time -from fastapi.responses import HTMLResponse - -# Import at runtime to avoid circular -try: - from main import app, rt - import ai_runtime_final6 as f6 - from ai_runtime_final6 import f5 -except: - f6, f5, rt = None, None, None - -# Patch hot_topics to prepend AI topics -if f6 and hasattr(f6, '_HOT_CACHE') and hasattr(f6, '_hot_topics'): - _orig_hot = f6._hot_topics - def _hot_topics_patched(): - topics = _orig_hot() - # Prepend AI topics to front - for ai in ['Công nghệ AI', 'World Cup 2026', 'Kinh tế Việt Nam']: - if not any(ai.lower() == t.get('topic','').lower() for t in topics): - topics.insert(0, {'label': f'#{ai.replace(" ", "")}', 'topic': ai, 'count': 0}) - return topics[:24] - f6._hot_topics = f6._HOT_CACHE['d'] = _hot_topics_patched() - f6._HOT_CACHE['t'] = time.time() - -PATCH_INJECT = r''' - -''' - -# Register homepage route -if app and f5 and f6: - # Remove old / route - app.router.routes = [r for r in app.router.routes if not (getattr(r,'path',None)=='/' and 'GET' in getattr(r,'methods',set()))] - - @app.get('/') - async def patch_homepage(): - html = f5.f4.f3.f2.f1._load_index_html() if f5 else "" - body = (getattr(rt.old,'PATCH_INJECT','') if hasattr(rt,'old') else '') + \ - (getattr(f5.f4.f3.f2.f1,'FINAL_INJECT','') if f5 else '') + \ - (getattr(f5.f4.f3,'FINAL3_INJECT','') if f5 else '') + \ - (getattr(f5.f4,'FINAL4_INJECT','') if f5 else '') + \ - (getattr(f5,'FINAL5_INJECT','') if f5 else '') + \ - (getattr(f6,'FINAL6_INJECT','') or '') + \ - (getattr(f6,'FINAL6_FAST_HOME_INJECT','') or '') + \ - (getattr(f6,'FINAL6E_INJECT','') or '') + \ - PATCH_INJECT - if '' in html: - html = html.replace('', body + '\n') - else: - html += body - return HTMLResponse(html) \ No newline at end of file diff --git a/rebuild3.md b/rebuild3.md deleted file mode 100644 index 5b52fc9f825e7d7997f32173b23d1b1f0aed0156..0000000000000000000000000000000000000000 --- a/rebuild3.md +++ /dev/null @@ -1 +0,0 @@ -rebuild \ No newline at end of file diff --git a/rebuild_trigger.txt b/rebuild_trigger.txt deleted file mode 100644 index 3201266b469b65da2beb9d15517cdb81e1e97a3c..0000000000000000000000000000000000000000 --- a/rebuild_trigger.txt +++ /dev/null @@ -1 +0,0 @@ -rebuild: Fri Aug 28 11:15:45 UTC 2026 diff --git a/requirements.txt b/requirements.txt index 5a7dc8fa59e562b34baac2b7323dc7cb06ae18a8..903c94c4f00bc6539698f298a80e4063f99f8cd0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -11,6 +11,3 @@ pillow edge-tts python-dateutil httpx -python-multipart -pycryptodome -# trigger rebuild 1784359130 diff --git a/restart.txt b/restart.txt deleted file mode 100644 index 31776977662f5a5d1c2483dbe85d673686a539b3..0000000000000000000000000000000000000000 --- a/restart.txt +++ /dev/null @@ -1 +0,0 @@ -rebuild 1787553359 diff --git a/restart2.md b/restart2.md deleted file mode 100644 index 1ad28c637f7615a09045aa79531232266712cc28..0000000000000000000000000000000000000000 --- a/restart2.md +++ /dev/null @@ -1 +0,0 @@ -restart with _run.py fix \ No newline at end of file diff --git a/restart_trigger.md b/restart_trigger.md deleted file mode 100644 index 7c200e23b9f8292a8309bc73fd0a5980e138b73a..0000000000000000000000000000000000000000 --- a/restart_trigger.md +++ /dev/null @@ -1,14 +0,0 @@ -# VNEWS Space Restart Trigger - -## Version: v20260822d - -### All fixes applied: -1. **Scrolling fix**: `-webkit-overflow-scrolling: touch` + `scroll-behavior: smooth` on `.tiktok-feed` -2. **Thumbnail fix**: `.yt-thumb-wrap` with background image for YouTube iframes, YouTube hqdefault fallback -3. **Lazy loading**: IntersectionObserver to unload slides far from viewport -4. **SHORT HOT video looping**: Video plays at full duration instead of being trimmed to narration length -5. **CSS consistency**: Same poster/thumbnail styling for all TikTok slides -6. **Homepage loading**: Retry logic for `scrape_vne`, bongdaplus.vn as primary source, faster xemlaibongda timeout -7. **YouTube SSL error**: Increased yt-dlp retries (5), socket_timeout 30s, YouTube embed fallback - -Last restart: 20260822d diff --git a/rewrite_slide.py b/rewrite_slide.py index b86340c3e987415f5d233fccbb761c14b2223285..263ab8e7bbf5929c39eb16ff0183efa6ab4b896b 100644 --- a/rewrite_slide.py +++ b/rewrite_slide.py @@ -84,36 +84,17 @@ def _scrape_article_full(url): return None -def _ensure_complete_sentence(text): - """Ensure text ends with complete sentence ending.""" - text = _clean(text) - if not text: - return text - # Find last complete sentence ending - for end_char in ['.', '!', '?']: - last_pos = text.rfind(end_char) - if last_pos > len(text) * 0.5: # Keep if ending is in latter half - return text[:last_pos + 1].strip() - return text - def _extract_key_points(paragraphs, max_points=5): - """Extract key points: take first COMPLETE sentence of each significant paragraph.""" + """Extract key points: take first sentence of each significant paragraph.""" points = [] for p in paragraphs: if len(points) >= max_points: break - # Find ALL sentence endings and take the first complete sentence - # that ends with . ! or ? - sentences = re.split(r'(?<=[.!?])\s+', p) - sentence = "" - for s in sentences: - s = _clean(s) - if len(s) >= 30 and re.search(r'[.!?]$', s): - sentence = s - break - - # If no complete sentence found, take first sentence and ensure it ends - if not sentence and sentences: - sentence = _ensure_complete_sentence(sentences[0]) + # Take first complete sentence (ends with . ! ?) + m = re.match(r'^(.+?[.!?])\s', p) + if m: + sentence = m.group(1) + else: + sentence = p[:150] + ('.' if not p.endswith('.') else '') # Skip if too short or duplicate if len(sentence) < 30: continue diff --git a/runtime.txt b/runtime.txt index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..64f28603a352df8286a8b7f4e33200f60e34206d 100644 --- a/runtime.txt +++ b/runtime.txt @@ -0,0 +1 @@ +python-3.12.x diff --git a/shorts_rss_setup.py b/shorts_rss_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..36346b9d456f37ef4862a4727eeec9843f54cf43 --- /dev/null +++ b/shorts_rss_setup.py @@ -0,0 +1,6 @@ +""" +Add this to the END of app_v2_entry.py to enable YouTube RSS proxy: + +from shorts_rss_proxy import setup_rss_proxy +setup_rss_proxy(app) +""" diff --git a/static/app_v2.js b/static/app_v2.js index ce5f7db26790c381e5197b407095a0b12362aafe..d2cfbad7847bc187b104166f8ce98af3b234a312 100644 --- a/static/app_v2.js +++ b/static/app_v2.js @@ -1,54 +1,4 @@ -// VNEWS v17.1 - FPT Play slider removed from homepage -/** - * VNEWS Frontend v2 - Shorts Dantri/SKDS removed, VTV Digital CDN - * v2.8 - Changed short AI feed video share button icon (📥) to distinguish from article share (📤) - * v2.6 - Fixed share links: doShare now includes post_id for wall posts, - * readSlidePost has share button, /s + /s/{slug} render slides/video inline - * v2.5 - Added 'Tạo lại' button on wall cards with video - * v2.4 - Fixed: prependWallPost detached-element bug, makeShortVideo UI update, slide viewer for rewrite posts - */ -// ---- World Cup 2026 tab switcher (was missing -> loadHome() crashed) ---- -function switchWCTab(tab){ - try { - var el = document.getElementById('wc-content'); - if(!el) return; - var d = (typeof _wc2026Data !== 'undefined') ? _wc2026Data : null; - if(!d){ el.innerHTML = '
Không có dữ liệu World Cup 2026
'; return; } - if(tab === 'fixtures'){ - var m = (d.fixtures && d.fixtures.matches) || []; - var h = '
'; - m.slice(0, 40).forEach(function(x){ - h += '
'+esc(x.group||'')+''+esc(x.home||'?')+' '+esc(x.score||'VS')+' '+esc(x.away||'?')+''+esc(x.date_vn||'')+'
'; - }); - h += '
'; - el.innerHTML = m.length ? h : '
Chưa có lịch thi đấu
'; - } else if(tab === 'standings'){ - el.innerHTML = '
'+esc((d.standings && (typeof d.standings==='string'?d.standings:JSON.stringify(d.standings)))||'Bảng xếp hạng đang cập nhật')+'
'; - } else if(tab === 'highlights'){ - el.innerHTML = '
'+esc((d.highlights && (typeof d.highlights==='string'?d.highlights:JSON.stringify(d.highlights)))||'Highlight đang cập nhật')+'
'; - } else if(tab === 'stats'){ - el.innerHTML = '
'+esc((d.stats && (typeof d.stats==='string'?d.stats:JSON.stringify(d.stats)))||'Thống kê đang cập nhật')+'
'; - } else { - var news = (d.news) || []; - var nh = '
'; - el.innerHTML = Array.isArray(news)&&news.length ? nh : '
Đang tải tin World Cup 2026...
'; - } - // update active tab styling - try { - document.querySelectorAll('.wc-tab').forEach(function(t){ - var want = (tab==='news') ? 'news' : tab; - t.classList.toggle('active', t.getAttribute('onclick') && t.getAttribute('onclick').indexOf("'"+want+"'")>=0); - }); - } catch(e){} - } catch(e){ - var el2 = document.getElementById('wc-content'); - if(el2) el2.innerHTML = '
Lỗi tải World Cup 2026
'; - } -} + function _proxyImg(url){ if(!url || typeof url !== 'string') return ''; if(url.startsWith('http') && !url.includes(location.host)){ @@ -57,8 +7,12 @@ function _proxyImg(url){ return url; } +// === VNEWS Frontend v2 - Fixed for Short AI voice/emotion selection === + +// Store selection state globally for each post var _ttsSelections = {}; +// === LOAD HOME - Fast: immediate shell + parallel fetch === function _fetchWithTimeout(url, ms){ return new Promise((resolve,reject)=>{ const ctrl=new AbortController(); @@ -71,105 +25,36 @@ function _fetchWithTimeout(url, ms){ }); } -// ===== rewriteUrl: tạo bài rewrite slide AI từ URL bài viết ===== -// Gọi /api/url_wall (backend thực tế), lấy post rồi đẩy lên Tường AI và mở slide viewer. -async function rewriteUrl(){ - const inp = document.getElementById('url-input'); - const url = (inp && inp.value || '').trim(); - if(!url){ alert('Vui lòng dán URL bài viết'); return; } - if(!/^https?:\/\//i.test(url)){ alert('URL cần bắt đầu bằng http:// hoặc https://'); return; } - let btn = null; - try { btn = inp && inp.parentElement ? inp.parentElement.querySelector('button') : null; } catch(e){} - const orig = btn ? btn.textContent : 'Rewrite'; - if(btn){ btn.disabled = true; btn.textContent = '⏳ Đang tạo...'; } - toast('⏳ Đang tạo bài rewrite slide AI...'); - try { - const r = await fetch('/api/url_wall', { - method:'POST', - headers:{'Content-Type':'application/json'}, - body: JSON.stringify({url: url}) - }); - const j = await r.json(); - if(!r.ok || j.error) throw new Error(j.error || 'Lỗi tạo bài'); - if(!j.post) throw new Error('Không tạo được bài'); - if(typeof prependWallPost === 'function'){ prependWallPost(j.post); } - else if(Array.isArray(_wallPosts)){ _wallPosts.unshift(j.post); } - if(inp) inp.value = ''; - toast('✅ Đã tạo bài rewrite slide AI!'); - const idx = (_wallPosts || []).indexOf(j.post); - if(j.post.slides && j.post.slides.length){ readSlidePost(idx >= 0 ? idx : 0); } - else if(typeof readWallPost === 'function'){ readWallPost(idx >= 0 ? idx : 0); } - } catch(e){ - toast('❌ ' + e.message); - } finally { - if(btn){ btn.disabled = false; btn.textContent = orig; } - } -} - -// ===== shareVideoToApps: gửi file MP4 qua app (chia sẻ video) ===== -async function shareVideoToApps(videoUrl, title){ - if(!videoUrl){ toast('Không có video để chia sẻ'); return; } - const safeTitle = (title || 'VNEWS Short AI').toString().slice(0, 80); - if(navigator.canShare && navigator.canShare({files:[]}) !== undefined){ - try { - const resp = await fetch(videoUrl, {mode:'cors'}); - if(resp && resp.ok){ - const blob = await resp.blob(); - let fname = (videoUrl.split('?')[0].split('/').pop() || 'vnews-short.mp4'); - if(!fname.toLowerCase().endsWith('.mp4')) fname = 'vnews-short.mp4'; - const file = new File([blob], fname, {type: (blob.type && blob.type.indexOf('video')>=0) ? blob.type : 'video/mp4'}); - if(navigator.canShare && navigator.canShare({files:[file]})){ - await navigator.share({files:[file], title: safeTitle, text: safeTitle}); - return; - } - } - } catch(e){ /* fall through to link share */ } - } - const _base = (typeof SPACE !== 'undefined' && SPACE) ? SPACE : location.origin; - const shareUrl = _base + '/s?url=' + encodeURIComponent(videoUrl) + '&title=' + encodeURIComponent(safeTitle); - if(navigator.share){ - try { await navigator.share({title: safeTitle, text: safeTitle, url: shareUrl}); return; } catch(e){ if(e && e.name === 'AbortError') return; } - } - if(navigator.clipboard && navigator.clipboard.writeText){ - try { await navigator.clipboard.writeText(shareUrl); toast('📋 Đã sao chép link video!'); return; } catch(e){} - } - try { - const ta = document.createElement('textarea'); - ta.value = shareUrl; ta.style.position='fixed'; ta.style.left='-9999px'; ta.style.top='-9999px'; ta.style.opacity='0'; - document.body.appendChild(ta); ta.select(); ta.setSelectionRange(0, 99999); - if(document.execCommand('copy')){ toast('📋 Đã sao chép link video!'); } - else { prompt('📋 Sao chép link video:', shareUrl); } - document.body.removeChild(ta); - } catch(e){ prompt('📋 Sao chép link video:', shareUrl); } -} - async function loadHome(){ const homeEl = document.getElementById('view-home'); if(!homeEl) return; + // Build shell IMMEDIATELY — no skeleton, no delay homeEl.innerHTML = '' - +'
🤖 AI viết bài
' - +'
' + +'
🤖 AI viết bài
' +'
' - +'
' - +'

⚽ Livescore

📋 Cập nhật🔴 Live📅 Hôm nay⏰ Sắp tới✅ Kết quả🏆 NHA🏆 La Liga🏆 Serie A🏆 Bundesliga🏆 League 1
Đang tải...
' + +'

⚽ Livescore

📅 Hôm nay🔴 Live⏰ Sắp tới✅ Kết quả🏆 NHA🏆 La Liga
Đang tải...
' +'

🏆 World Cup 2026

● LIVE
📰 Tin tức📅 Lịch thi đấu🏆 BXH🎬 Highlight📊 Thống kê
Đang tải World Cup 2026...
' - +'
' +'
'; const afterEl = homeEl.querySelector('#home-after-wc'); - loadLivescore('recent'); + // Start critical loads immediately + loadLivescore('today'); loadHotTopics(); - const [featuredData, wallData, hlLeagues, wcData] = await Promise.allSettled([ + // Fetch all data in parallel with shorter timeouts + const [featuredData, shortsData, wallData, hlLeagues, aiData, wcData] = await Promise.allSettled([ _fetchWithTimeout('/api/livescore/featured', 5000), + _fetchWithTimeout('/api/shorts', 8000), _fetchWithTimeout('/api/wall', 5000), _fetchWithTimeout('/api/highlights/leagues', 10000), - _fetchWithTimeout('/api/wc2026', 20000), + _fetchWithTimeout('/api/genk_ai', 8000), + _fetchWithTimeout('/api/wc2026', 8000), ]).then(results => results.map(r => r.status === 'fulfilled' ? r.value : null)); + // Render featured match if(featuredData && featuredData.home){ const sc=featuredData.status==='live'?'':'upcoming'; const st=featuredData.status==='live'?`🔴 ${featuredData.minute||'LIVE'}`:`⏰ ${featuredData.time}`; @@ -177,19 +62,20 @@ async function loadHome(){ if(area) area.innerHTML=``; } + // Store globally + _shortsData = shortsData || []; _wallPosts = (wallData && wallData.posts) || []; _hlLeagueData = hlLeagues || {}; _wc2026Data = wcData; + // Render WC if data arrived if(wcData) switchWCTab('news'); - _renderHLSection(); - _fptStartAuto(); - - // === YOUTUBE RSS FEED (FPT Bóng Đá) — interleave latest videos onto Tường AI === - _ytFeedStartAuto(); - + // Render sections into the after-wc area + _renderShortsIn(afterEl); _renderWallIn(afterEl); + _renderHLIn(afterEl); + if(aiData && aiData.length) _renderSlidesIn('ai-articles','Ứng dụng AI','🤖',aiData,afterEl); } function _renderSlidesIn(key, label, emoji, vids, afterEl){ @@ -200,7 +86,7 @@ function _renderSlidesIn(key, label, emoji, vids, afterEl){ const isHL = key==='world-cup'||key==='premier-league'||key==='champions-league'||key==='la-liga'||key==='serie-a'||key==='bundesliga'||key==='friendly'; vids.slice(0,isHL?8:12).forEach((a,i)=>{ if(isHL){ - h+=`
${a.img?``:''}
${esc(a.title)}
`; + h+=`
${a.img?``:''}
${esc(a.title)}
`; } else { h+=`
${a.img?``:''}
${esc(a.title)}
`; } @@ -210,19 +96,39 @@ function _renderSlidesIn(key, label, emoji, vids, afterEl){ afterEl.parentNode.insertBefore(wrap, afterEl); } +function _renderShortsIn(afterEl){ + if(!_shortsData||!_shortsData.length||!afterEl) return; + const mixed=interleaveShorts(_shortsData); + if(!mixed.length) return; + const wrap=document.createElement('div'); + wrap.className='slider-wrap'; + let h=`
📱 Shorts Dân trí & SKĐSMới nhất · xen kẽ
`; + mixed.slice(0,30).forEach((a,i)=>{ + const badge=a.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí'; + h+=`
${a.img?``:''}
${badge} ${esc(a.title)}
`; + }); + h+='
';wrap.innerHTML=h; + afterEl.parentNode.insertBefore(wrap,afterEl); +} + function _renderWallIn(afterEl){ - if(!_wallPosts||!_wallPosts.length) return; + if(!_wallPosts||!_wallPosts.length||!afterEl) return; const posts=_wallPosts; + const aiShorts=posts.filter(p=>p.video); + if(aiShorts.length){ + const wrap=document.createElement('div'); + wrap.className='slider-wrap';wrap.id='short-ai-section'; + let h='
🎬 Short AI
'; + aiShorts.slice(0,20).forEach((p,i)=>{h+=`
${esc(p.title)}
`;}); + h+='
';wrap.innerHTML=h; + afterEl.parentNode.insertBefore(wrap,afterEl); + } const wrap=document.createElement('div'); wrap.className='slider-wrap';wrap.id='ai-wall-wrap'; let h='
🧱 Tường AI
'; posts.slice(0,20).forEach((p,i)=>{h+=makeWallItem(p,i);}); h+='
';wrap.innerHTML=h; - const target=document.getElementById('ai-wall-under-compose'); - if(target) target.appendChild(wrap); - else if(afterEl) afterEl.parentNode.insertBefore(wrap,afterEl); - // Interleave YouTube RSS feed videos into the wall with wall CSS - if(wrap && typeof _renderYTFeedInWall === 'function') _renderYTFeedInWall(); + afterEl.parentNode.insertBefore(wrap,afterEl); } function _renderHLIn(afterEl){ @@ -235,538 +141,12 @@ function _renderHLIn(afterEl){ } } -// === RENDER HIGHLIGHT (Video bóng đá) SECTION — above Livescore, with "Xem thêm" per league === -var _hlPage = {}; // {leagueKey: page} -var _hlHasMore = {}; // {leagueKey: bool} - -function _renderHLSection(){ - const hlEl = document.getElementById('home-hl-section'); - if(!hlEl) return; - if(!_hlLeagueData || Object.keys(_hlLeagueData).length===0){ - return; - } - const HL_CONFIG={"premier-league":{name:"Ngoại Hạng Anh",emoji:"🏴"},"champions-league":{name:"Champions League",emoji:"⭐"},"la-liga":{name:"La Liga",emoji:"🇪🇸"},"serie-a":{name:"Serie A",emoji:"🇮🇹"},"bundesliga":{name:"Bundesliga",emoji:"🇩🇪"},"world-cup":{name:"World Cup 2026",emoji:"🌍"},"fa-cup":{name:"FA Cup",emoji:"🏆"},"friendly":{name:"Giao hữu",emoji:"🤝"}}; - - // Ordered list of leagues that have videos (premier-league first) - const orderedLeagues = []; - const plVids = _hlLeagueData['premier-league']; - if(plVids && plVids.length) orderedLeagues.push('premier-league'); - for(const [key, cfg] of Object.entries(HL_CONFIG)){ - if(key === 'premier-league') continue; - const vids = _hlLeagueData[key]; - if(vids && vids.length) orderedLeagues.push(key); - } - if(orderedLeagues.length === 0){ - return; // nothing to show - } - _hlLeagueKey = orderedLeagues; - - // Build ONE combined video list from ALL leagues (premier league items first). - // The scraped sources return the SAME videos for every league (the league - // sub-pages all resolve to the same content from the server), so combine - // then DEDUPE by link — otherwise the slider shows the same ~10 videos - // repeated N times and "loops back to video #1" after the unique ones. - const seenLinks = new Set(); - let combined = []; - orderedLeagues.forEach(key => { - const vids = _hlLeagueData[key] || []; - vids.forEach(a => { - if(!a || !a.link || seenLinks.has(a.link)) return; - seenLinks.add(a.link); - combined.push(Object.assign({}, a, {_league: key, _pos: combined.length})); - }); - }); - // Newest first: sort by publish date when known (the scrapers now return - // `published` parsed from the image/URL dates). Videos without a date keep - // their relative order and go last, so the slider always starts with the - // freshest clips. - combined.sort(function(x, y){ - const xd = x.published || ''; - const yd = y.published || ''; - if(xd && yd) return xd < yd ? 1 : (xd > yd ? -1 : 0); - if(xd && !yd) return -1; // dated first - if(!xd && yd) return 1; - return (x._pos||0) - (y._pos||0); // stable for undated - }); - _hlLeagueData['all'] = combined; - - // ONE unified "🎬 Video bóng đá" slider (per-league sliders removed). - // All videos render at once — no "Xem thêm" button needed (the paged API - // re-scrapes the same sources, so it adds nothing but duplicates). - let html = '
🎬 Video bóng đá' + combined.length + ' video
'; - html += '
'; - hlEl.innerHTML = html; - _renderHLSlides('all', 'Video bóng đá', '🎬', combined, 'hl-main-track'); -} - -function _renderHLSlides(key, label, emoji, vids, containerId){ - const container = document.getElementById(containerId); - if(!container) return; - if(!vids || !vids.length){ - container.innerHTML = '
Chưa có video
'; - return; - } - // Render ALL football videos immediately (the dataset is small: ~70-80 - // items). No 8-item cap, no chunked lazy-load, no server paging on the - // homepage — every item gets its exact index into the vids array, so - // openHighlightFeed can never mismatch order and the slider can never - // "loop back to video #1". Images use native lazy-loading so only the - // visible thumbnails are fetched. - let h = ''; - vids.forEach((a, i) => { - h += _hlItemHtml(key, a, i); - }); - container.innerHTML = h; -} - -// All football videos are rendered at once from the full vids array, so the -// chunked lazy-load machinery is no longer needed and is removed to keep the -// track's indices simple and duplicate-free. - -function _hlItemHtml(key, a, i){ - return '
' + (a.img ? '' : '') + '
' + esc(a.title) + '
'; -} - -async function _loadMoreHL(key, auto){ - // Legacy: kept as a no-op safety net (the old inline button HTML may still - // be cached in some browsers; it simply appends nothing and hides itself). - const btn = typeof document !== 'undefined' ? document.querySelector('.hl-load-more') : null; - if(btn) btn.style.display = 'none'; - _hlHasMore[key] = false; -} - -// === FPT PLAY SLIDER (auto-updating channel) === -// Shows the latest videos from https://youtube.com/@fptbongdaofficial like the -// Short HOT oEmbed slides. The server can't reach youtube.com from its -// datacenter, so the browser (home IP) fetches the channel via r.jina.ai and -// pushes the result to /api/fptplay/update — the slide refreshes automatically -// when the channel uploads something new. -var _fptVideos = []; -var _fptTimer = null; -var _fptSeen = {}; - -function _fptParseJina(txt){ - // jina markdown of the /videos tab: each entry has a title line and a watch - // URL. Collect (title, videoId) in page order. - const out = []; - const titles = []; - const lines = String(txt||'').split('\n'); - for(let i=0;io.id===id)) title = titles.pop() || ''; - if(!title){ - // fall back to the line itself (sans url) - title = line.replace(/https?:\/\/\S+/g,'').replace(/[|\[\]]/g,'').trim(); - } - out.push({id:id, title:(title||'Video').slice(0,200), link:'https://youtu.be/'+id}); - } else if(/^\s*\d+\./.test(line)){ - const t = line.replace(/^\s*\d+\.\s+/,'').trim(); - if(t && t.length>4 && !/youtube\.com|youtu\.be/i.test(t)) titles.push(t); - } - } - return out; -} - -async function _fptFetchClient(){ - // Browser-side: user's home IP can reach r.jina.ai (same trick as Short HOT - // description). Returns array of {id,title,link}. - try{ - const ctrl = new AbortController(); - const tid = setTimeout(()=>ctrl.abort(), 60000); - const resp = await fetch('https://r.jina.ai/https://www.youtube.com/@fptbongdaofficial/videos', { - headers:{'x-no-cache':'1','x-respond-with':'markdown'}, - signal: ctrl.signal - }); - clearTimeout(tid); - if(!resp.ok) throw new Error('jina '+resp.status); - const txt = await resp.text(); - const parsed = _fptParseJina(txt); - if(!parsed.length) throw new Error('empty parse'); - return parsed; - }catch(e){ - return null; - } -} - -function _fptRender(){ - const el = document.getElementById('home-fpt-section'); - if(!el) return; - if(!_fptVideos || !_fptVideos.length){ - el.innerHTML = ''; - return; - } - const vids = _fptVideos.slice(0, 30); - // Render FPT Play videos using the SAME wall card CSS as Short AI cards - // (via _makeYTFeedWallItem) — 100% match with card video Short AI. - let h = '
📺 FPT Play Bóng Đá' + vids.length + ' video · tự cập nhật
'; - vids.forEach((a,i)=>{ - h += _makeYTFeedWallItem(a, i); - }); - h += '
'; - el.innerHTML = h; - // lazy thumbs - el.querySelectorAll('img[loading]').forEach(function(im){ im.loading='lazy'; }); -} - -async function _fptSync(){ - // 1) read server cache first (fast) - try{ - const r = await fetch('/api/fptplay/videos'); - const j = await r.json(); - if(j && j.videos && j.videos.length){ - _fptVideos = j.videos; - _fptRender(); - } - }catch(e){} - // 2) refresh from the channel (client-side jina) — replaces stale cache - const fresh = await _fptFetchClient(); - if(fresh && fresh.length){ - // push to server so the slide stays updated and persisted - try{ - const body = JSON.stringify({videos: fresh}); - const r2 = await fetch('/api/fptplay/update', {method:'POST', headers:{'Content-Type':'application/json'}, body}); - const j2 = await r2.json(); - if(j2 && j2.videos && j2.videos.length) _fptVideos = j2.videos; - else _fptVideos = fresh; - }catch(e2){ - _fptVideos = fresh; - } - _fptRender(); - } -} - -function _fptStartAuto(){ - if(_fptTimer) return; - _fptSync(); // immediate first pass - _fptTimer = setInterval(_fptSync, 12 * 60 * 1000); // auto-refresh every 12 min -} - -// === YOUTUBE RSS FEED — auto-updating FPT Bóng Đá videos on Tường AI === -// Channel ID UC4LvrpNXujjbGOS4RDvr41g = FPT Bóng Đá. -// The browser fetches the YouTube RSS feed (feeds/videos.xml) directly since -// the datacenter can't reach youtube.com. Parsed entries are interleaved into -// the AI wall (Tường AI) using the same wall CSS classes as makeWallItem so -// they look like native wall posts. Auto-refresh every 15 minutes. -var _ytFeedVideos = []; -var _ytFeedTimer = null; -var _ytFeedUrl = 'https://www.youtube.com/feeds/videos.xml?channel_id=UC4LvrpNXujjbGOS4RDvr41g'; -// The browser cannot fetch this URL directly (YouTube RSS lacks CORS headers). -// The server-side /api/yt/feed endpoint fetches + parses it and returns JSON. - -function _ytParseRssXml(xmlText){ - // Parse YouTube RSS XML. The browser can fetch the raw XML directly. - // Returns [{id, title, link, img, published}] in newest-first order. - var out = []; - try{ - var parser = new DOMParser(); - var doc = parser.parseFromString(xmlText, 'application/xml'); - // Check for parse errors - var err = doc.querySelector('parsererror'); - if(err){ return null; } - var entries = doc.getElementsByTagName('entry'); - for(var i=0; i' - : '
'; - var videoBadge = '
🎬
'; - var vid = v.videoId || v.id; - var callOpen = "openYTEmbedFeed('"+esc(vid)+"','"+esc(v.title)+"')"; - return '
' + - '
' + - thumbContent + videoBadge + - '
' + - '
' + esc(v.title) + '
' + - '
' + esc((v.published||'').replace(/T.*/,'') ) + '
' + - '
' + - '' + - '
' + - '
'; -} - -function _renderYTFeedInWall(){ - // Interleave YouTube feed videos into the wall track, using wall CSS. - // Called after _renderWallIn and after each feed refresh. - var track = document.getElementById('ai-wall-track'); - if(!track){ return; } - // Remove any previous feed items (they get re-appended to stay "latest") - var existing = track.querySelectorAll('.wall-yt-feed-item'); - existing.forEach(function(el){ el.remove(); }); - if(!_ytFeedVideos || !_ytFeedVideos.length){ return; } - // Interleave: insert feed items at regular intervals among wall posts - var wallItems = Array.prototype.slice.call(track.children); - var feedItems = _ytFeedVideos.slice(0, 12); // cap to keep wall tidy - var step = Math.max(1, Math.ceil(wallItems.length / feedItems.length)); - var insertIdx = step; - feedItems.forEach(function(v, i){ - var wrapper = document.createElement('div'); - wrapper.className = 'wall-yt-feed-item'; - wrapper.innerHTML = _makeYTFeedWallItem(v, i); - if(insertIdx < wallItems.length){ - track.insertBefore(wrapper, wallItems[insertIdx]); - wallItems.splice(insertIdx, 0, wrapper); - insertIdx += step + 1; - }else{ - track.appendChild(wrapper); - wallItems.push(wrapper); - } - }); -} - -function openYTEmbedFeed(videoId, title){ - // Open a YouTube embed in the SAME TikTok-style viewer used by Short AI - // (buildTikTokSlide + initTikTokFeed) — 100% match with Short AI player. - // Builds a SCROLLABLE feed that starts at this FPT video and lets the user - // swipe UP/DOWN to browse older FPT videos interleaved with Short AI content, - // in newest-first order. - showView('view-tiktok'); - var el = document.getElementById('view-tiktok'); - if(!el){ return; } - - function _fptTs(v){ - if(v && v.published){ - var d = new Date(v.published); - if(!isNaN(d.getTime())) return d.getTime(); - } - return 0; - } - - // 1) Gather all playable items: FPT wall videos + Short AI posts (newest first) - var items = []; - var seenFpt = {}; - function pushFpt(v){ - if(!v) return; - var vid = v.videoId || v.id; - if(!vid || seenFpt[vid]) return; - seenFpt[vid] = 1; - items.push({ - kind:'fpt', - videoId: vid, - title: v.title || 'Video', - img: v.img || 'https://i.ytimg.com/vi/' + vid + '/hqdefault.jpg', - ts: _fptTs(v) - }); - } - (_ytFeedVideos||[]).forEach(pushFpt); - (_fptVideos||[]).forEach(pushFpt); - (_wallPosts||[]).forEach(function(p){ - if(!p || !p.video) return; - var ts = parseInt(p.created||'0',10); - if(isNaN(ts) || !ts){ var d = new Date(p.created_str||''); ts = isNaN(d.getTime()) ? 0 : d.getTime(); } - items.push({ - kind:'ai', - videoId: p.id || ('ai-' + items.length), - postId: p.id || '', - title: p.title || 'Video', - img: p.short_thumb || p.img || '', - text: (p.text && p.text !== p.title ? p.text : '').slice(0,400), - video: p.video, - ts: ts - }); - }); - - // 2) Sort newest-first, then rotate so the clicked FPT video is first - items.sort(function(a,b){ return (b.ts||0) - (a.ts||0); }); - var start = 0; - for(var i=0;i' - + '
'; - } - function aiVtag(it){ - var isYT = /youtube\.com\/embed|youtu\.be\/|youtube-nocookie|tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|platform\.twitter\.com|player\.vimeo\.com/.test(it.video||''); - if(!it.video) return ''; - return isYT - ? '
' - : ''; - } - - var h = '' - + '
'; - ordered.forEach(function(it, idx){ - var vtag, badge, badgeClass, shareUrl, postId, desc, extraBtn; - if(it.kind === 'fpt'){ - vtag = fptVtag(it); - badge = 'FPT Play'; badgeClass = 'badge-fpt'; - shareUrl = 'https://www.youtube.com/watch?v=' + it.videoId; - postId = ''; desc = ''; extraBtn = ''; - } else { - vtag = aiVtag(it); - badge = 'Short AI'; badgeClass = 'badge-ai'; - shareUrl = it.video || ''; - postId = it.postId || ''; - desc = it.text || ''; - extraBtn = ''; - } - h += buildTikTokSlide({ - vtag: vtag, - title: it.title, - badge: badge, - badgeClass: badgeClass, - videoId: it.videoId + '-feed-' + String(idx), - idx: idx, - total: ordered.length, - shareUrl: shareUrl, - postId: postId, - desc: desc, - extraBtn: extraBtn || '' - }); - }); - h += '
'; - el.innerHTML = h; - setTimeout(function(){ initTikTokFeed(); }, 200); -} - -async function _ytFeedSync(){ - // 1) render from cache (immediate) - if(_ytFeedVideos.length){ - _renderYTFeedInWall(); - } - // 2) refresh from the live channel feed - var fresh = await _ytFetchFeed(); - if(fresh && fresh.length){ - _ytFeedVideos = fresh.slice(0, 15); - _renderYTFeedInWall(); - } -} - -function _ytFeedStartAuto(){ - if(_ytFeedTimer) return; - _ytFeedSync(); - _ytFeedTimer = setInterval(_ytFeedSync, 15 * 60 * 1000); // every 15 min -} - // === WALL POST HELPERS === function makeWallItem(p,i){ - var hasVideo = p.video && p.video.length > 0;var isEmbed = !!(p.embed_oembed || /tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|youtube\.com\/embed|platform\.twitter\.com|player\.vimeo\.com/.test(p.video||'')); - var isSlide = (p.slides && p.slides.length) || p.kind==='slide_summary'; - // Slide/design posts: keep the image's natural aspect ratio (no 16:9 crop) - // so portrait-designed slides aren't cut — this fixes the "saved image ratio - // and background position look wrong vs the preview" bug on the wall thumb. - var thumbStyle = isSlide - ? 'aspect-ratio:auto;max-height:340px;display:flex;align-items:flex-start;justify-content:center;background:#000' - : ''; - var thumbContent = isEmbed - ? (p.img - ? '' - : '
') - : (isSlide - ? (p.img ? '' : (hasVideo ? '' : '')) - : (p.img ? '' : (hasVideo ? '' : ''))); + var hasVideo = p.video && p.video.length > 0; + var thumbContent = p.img + ? '' + : (hasVideo ? '' : ''); var videoBadge = hasVideo ? '
🎬
' : ''; var vid = p.id||i; var lang = p.language || detectLanguage(p.title + ' ' + (p.text||'')); @@ -795,643 +175,109 @@ function makeWallItem(p,i){ +'' +'' +''; -var makeBtn = hasVideo - ? '' - : ''; - var designBtn = (p.slides && p.slides.length) ? '' : ''; - return '
'+thumbContent+videoBadge+'
'+esc(p.title)+'
'+esc((p.text||'').slice(0,180))+'
'+voiceBar+'
'+designBtn+makeBtn+'
'; + var makeBtn = hasVideo + ? '' + : ''; + return '
'+thumbContent+videoBadge+'
'+esc(p.title)+'
'+esc((p.text||'').slice(0,180))+'
'+voiceBar+'
'+makeBtn+'
'; } -/* ===================================================================== - * Short AI Creator v2 - * - TikTok background-music list (server-provided) or uploaded audio - * - uploaded image OR uploaded video as the short background - * - "Tạo lại" (recreate): use the DESIGNED slide images + the previous - * short's audio (NO text ever enters the video again) - * ===================================================================== */ -var _shortMusicList = []; -async function loadShortMusicList(){ - if(_shortMusicList.length) return _shortMusicList; - try{ - const r = await fetch('/api/ai-short/music'); - const j = await r.json(); - _shortMusicList = (j.music || []); - }catch(e){ _shortMusicList = []; } - return _shortMusicList; -} - -function openShortCreator(postId){ - if(!postId) return; - const p = _wallPosts.find(x => String(x.id) === String(postId)); - if(!p) return; - // if the post has designed slides, recreate defaults to slides mode - const hasSlides = p.slides && p.slides.length > 0; - _buildShortCreatorModal(p, hasSlides, false); -} - -/* 🔥 Thêm Short HOT — homepage button. Opens the SAME short-creator modal with - * full scrap capability (image / uploaded video / video-from-link) but creates - * a BRAND-NEW wall post (no source article) when the short is generated. */ -function openShortHotCreator(){ - const p = { - id: 'hot-' + Date.now(), - title: '', - text: '', - img: null, - images: [], - slides: null, - video: null, - language: 'vi', - }; - _buildShortCreatorModal(p, false, true); -} - -function _buildShortCreatorModal(p, defaultUseSlides, hotMode){ - loadShortMusicList().then(music => { - const hasPrev = !!(p.short_audio_url || p.video); - const hasSlides = p.slides && p.slides.length > 0; - const useSlideDef = defaultUseSlides !== undefined ? defaultUseSlides : (hasSlides && hasPrev); - const overlay = document.createElement('div'); - overlay.id = 'short-creator-overlay'; - 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'; - - // voice/emotion from stored selection - const selKey = 'inline-' + p.id; - if(!_ttsSelections[selKey]) _ttsSelections[selKey] = {voice: p.voice || getAutoVoice(p.language || detectLanguage(p.title+' '+(p.text||''))), emotion: p.emotion || detectEmotion(p.title+' '+(p.text||''))}; - const curVoice = _ttsSelections[selKey].voice || 'vi-VN-HoaiMyNeural'; - const curEmotion = _ttsSelections[selKey].emotion || 'neutral'; - - let h = '
'; - h += '

'+(hotMode?'🔥 Thêm Short HOT':'🎬 Tạo Short AI')+(hasPrev?' (Tạo lại)':'')+'

'; - if(hotMode){ - h += '
'; - h += '
'; - } - - /* 0. Recreate mode (designed slides only, no text) */ - if(hasSlides){ - h += '
'; - h += ''; - h += '
Dùng ảnh slide đã thiết kế làm nền + giữ nguyên audio của Short trước đó. Chữ KHÔNG xuất hiện trong video.
'; - h += '
'; - h += '
Chọn slide muốn đưa vào Short (tích = dùng):
'; - p.slides.forEach((s,i)=>{ - const simg = s.image || p.img || ''; - h += ''; - }); - h += '
'; - } - - /* 1. Background: image (default) / uploaded video / scraped video link */ - h += '
'; - h += '
'; - h += ''; - h += ''; - h += ''; - h += '
'; - h += ''; - h += ''; - h += ''; - h += '
'; - - /* 2. Audio + 3. Voice — SKIPPED in HOT mode (video keeps its own audio) */ - if(!hotMode){ - /* 2. Audio: previous short audio / TikTok music / uploaded audio */ - h += '
'; - h += ''; - /* Music chooser — luôn hiển thị để người dùng NGHE THỬ trước khi chọn */ - h += '
'; - h += '
'; - h += '
'; - h += ''; - h += '
▶ Nghe thử nhạc nền TikTok trước khi chọn. Nhạc sẽ được trộn vào video (nền) khi tạo.
'; - h += '
'; - h += ''; - h += '
'; - - /* 3. Voice + emotion + speed (TTS) */ - h += '
'; - h += '
'; - h += '
'; - h += '
'; - h += '
'; - } - - h += '
'; - h += ''; - h += ''; - h += '
'; - h += '
'; - overlay.innerHTML=h; document.body.appendChild(overlay); - // Cleanup HLS preview instance whenever the modal is removed (✕ / Hủy / success) - (function(){ - const obs = new MutationObserver(function(muts){ - if(document.getElementById('sc-scrape-video')){ - const p = document.getElementById('sc-scrape-video'); - if(p._hls){ try{ p._hls.destroy(); }catch(e){} p._hls = null; } - } - }); - obs.observe(document.body, {childList:true, subtree:false}); - // stop after this overlay is gone - setTimeout(()=>obs.disconnect(), 60*1000); - })(); - - // ---- mode toggles ---- - let bgMode = hotMode ? 'link' : 'img'; - function setBgMode(m){ - bgMode = m; - document.getElementById('sc-bg-mode-img').style.background = m==='img' ? '#2d8659' : '#333'; - document.getElementById('sc-bg-mode-img').style.color = m==='img' ? '#fff' : '#ccc'; - document.getElementById('sc-bg-mode-video').style.background = m==='video' ? '#2d8659' : '#333'; - document.getElementById('sc-bg-mode-video').style.color = m==='video' ? '#fff' : '#ccc'; - document.getElementById('sc-bg-mode-link').style.background = m==='link' ? '#2d8659' : '#333'; - document.getElementById('sc-bg-mode-link').style.color = m==='link' ? '#fff' : '#ccc'; - document.getElementById('sc-bg-img-wrap').style.display = (m==='img' || m==='link') ? 'block' : 'none'; - document.getElementById('sc-bg-video-wrap').style.display = m==='video' ? 'block' : 'none'; - document.getElementById('sc-bg-link-wrap').style.display = m==='link' ? 'block' : 'none'; - } - if(hotMode){ - // HOT mode: only video-from-link is offered; hide ảnh/upload-video buttons - document.getElementById('sc-bg-mode-img').style.display = 'none'; - document.getElementById('sc-bg-mode-video').style.display = 'none'; - document.getElementById('sc-bg-mode-link').style.background = '#2d8659'; - document.getElementById('sc-bg-mode-link').style.color = '#fff'; +async function makeShortVideo(postId, btn, voice, speed, emotion){ + if(!postId)return; + const origText = btn ? btn.textContent : '🎬 Tạo Video'; + if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo...';} + toast('⏳ Đang tạo video shorts...'); + + // FIX: If no voice/emotion passed, read from _ttsSelections or from the tts-selector UI + if(!voice || !emotion){ + const selKey = 'inline-'+postId; + const container = document.querySelector('.tts-selector[data-post-id="'+postId+'"]'); + if(container){ + // Try to read from _ttsSelections first + if(_ttsSelections[selKey]){ + voice = voice || _ttsSelections[selKey].voice; + emotion = emotion || _ttsSelections[selKey].emotion; + } + // Fallback to style-based reading + if(!voice){ + const selectedVoiceBtn = container.querySelector('.tts-voice-btn.selected') || + container.querySelector('.tts-voice-btn[style*="5cb87a"]') || + container.querySelector('.tts-voice-btn'); + voice = selectedVoiceBtn ? selectedVoiceBtn.dataset.voice : 'vi-VN-HoaiMyNeural'; + } + if(!emotion){ + const selectedEmotionBtn = container.querySelector('.tts-emotion-btn.selected') || + container.querySelector('.tts-emotion-btn[style*="5cb87a"]') || + container.querySelector('.tts-emotion-btn'); + emotion = selectedEmotionBtn ? selectedEmotionBtn.dataset.emotion : 'neutral'; + } + const speedSelect = container.querySelector('.tts-speed'); + speed = speedSelect ? parseFloat(speedSelect.value) || 1.2 : (speed || 1.2); } else { - document.getElementById('sc-bg-mode-img').addEventListener('click', ()=>setBgMode('img')); - document.getElementById('sc-bg-mode-video').addEventListener('click', ()=>setBgMode('video')); - document.getElementById('sc-bg-mode-link').addEventListener('click', ()=>setBgMode('link')); + voice = voice || 'vi-VN-HoaiMyNeural'; + emotion = emotion || 'neutral'; + speed = speed || 1.2; } - - // ---- scraped video link: fetch preview ---- - const scLinkInput = document.getElementById('sc-video-link'); - const scScrapeBtn = document.getElementById('sc-video-scrape'); - if(scScrapeBtn && scLinkInput){ - scScrapeBtn.addEventListener('click', async ()=>{ - const url = scLinkInput.value.trim(); - const st = document.getElementById('sc-video-scrape-status'); - const preview = document.getElementById('sc-video-preview'); - const meta = document.getElementById('sc-video-meta'); - if(!url){ - st.textContent = '⚠️ Dán link video trước.'; - st.style.color = '#e0a030'; - return; - } - st.textContent = '⏳ Đang lấy thông tin video...'; - st.style.color = '#888'; - try{ - const r = await fetch('/api/ai-short/scrape?url=' + encodeURIComponent(url)); - const j = await r.json(); - if(!r.ok || j.error) throw new Error(j.error || 'Không lấy được video'); - // metadata - let metaHtml = ''; - if(j.title) metaHtml += '
' + esc(j.title) + '
'; - if(j.duration) metaHtml += '
⏱️ ' + Math.round(j.duration) + 's
'; - if(j.extractor) metaHtml += '
Nguồn: ' + esc(j.extractor) + '
'; - if(j.note) metaHtml += '
⚠️ ' + esc(j.note) + '
'; - meta.innerHTML = metaHtml; - meta.style.display = 'block'; - // direct URL for the short; keep oEmbed fallback metadata too - const scDirect = j.direct_url || ''; - let scEmbed = j.embed_url || ''; - // YouTube/other scrape often returns the oEmbed-style iframe URL via - // direct_url (embed pages can't be downloaded as media). Normalize: - // treat direct embed URLs as oEmbed sources so the submit path saves - // an embeddable slide with auto title/thumb instead of erroring. - if(!scEmbed && /youtube\.com\/embed|youtu\.be\/|tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|player\.vimeo\.com|platform\.twitter\.com/.test(scDirect)){ - scEmbed = scDirect; - } - const scThumb = j.thumbnail || j.thumb || ''; - const scDesc = j.description || ''; - meta.setAttribute('data-title', j.title || ''); - meta.setAttribute('data-direct', scDirect || ''); - meta.setAttribute('data-embed', scEmbed || ''); - meta.setAttribute('data-thumb', scThumb || ''); - meta.setAttribute('data-desc', scDesc || ''); - // Show description (YouTube/other) under the title in the meta box - if(scDesc){ - metaHtml += '
' + esc(scDesc) + '
'; - meta.innerHTML = metaHtml; - } - // Auto-fill the Short HOT title field with the real scraped title - const hotTitle = document.getElementById('sc-hot-title'); - if(hotTitle){ hotTitle.setAttribute('data-autofilled', j.title ? '1' : '0'); } - if(hotTitle && j.title && !hotTitle.value.trim()){ - hotTitle.value = j.title; - } - document.getElementById('sc-scrape-direct').value = scDirect; - document.getElementById('sc-scrape-duration').value = j.duration ? String(j.duration) : ''; - // YouTube description client-side fallback: the user's browser (home - // IP) can reach r.jina.ai even when the server cannot; fill the - // description if the server didn't return one. - if(!scDesc && /youtube\.com|youtu\.be/.test(url)){ - try{ - fetch('https://r.jina.ai/' + url, {headers:{'x-no-cache':'1'}}) - .then(resp => resp.text()) - .then(txt => { - const m = txt.match(/(?:^|\n)Description:\s*([\s\S]*?)(?=\n[A-Z][a-z]+:|$)/); - const t2 = txt.match(/(?:^|\n)Title:\s*(.+)/); - if(m && m[1] && m[1].trim()){ - const d = m[1].trim().slice(0,2000); - meta.setAttribute('data-desc', d); - metaHtml += '
' + esc(d) + '
'; - meta.innerHTML = metaHtml; - } - if(t2 && t2[1] && hotTitle && !hotTitle.value.trim()){ - hotTitle.value = t2[1].trim().slice(0,250); - } - }).catch(()=>{}); - }catch(e2){} - } - // fallback note when only oEmbed metadata is available (no direct media) - if(!scDirect && scEmbed){ - st.textContent = 'ℹ️ Video không tải trực tiếp được, sẽ chèn dạng oEmbed (tự lấy tiêu đề/mô tả).'; - st.style.color = '#e0a030'; - meta.style.display = 'block'; - const ebtn = document.getElementById('sc-video-scrape'); - if(ebtn) ebtn.style.display = 'none'; - } - if(j.previewable && scDirect){ - const isYouTube = /youtube\.com\/embed|youtu\.be\/|youtube-nocookie/.test(scDirect); - const isHls = !!j.is_hls || /\.m3u8/i.test(scDirect); - const streamUrl = isHls - ? '/api/ai-short/scrape/hls?url=' + encodeURIComponent(scDirect) - : '/api/ai-short/scrape/preview?url=' + encodeURIComponent(scDirect); - preview.style.display = 'block'; - preview.setAttribute('data-ishls', isHls ? '1' : '0'); - if(isYouTube){ - // YouTube embed — render as iframe (direct embed URL already has autoplay) - preview.setAttribute('data-ishls', '0'); - preview.innerHTML = ''; - st.textContent = '✅ Đã lấy video YouTube. Bấm play để xem trước.'; - st.style.color = '#8f8'; - } else { - preview.innerHTML = ''; - const v = preview.querySelector('#sc-scrape-video'); - if(isHls && v && typeof Hls !== 'undefined' && Hls.isSupported()){ - const hls = new Hls(); - hls.loadSource(streamUrl); - hls.attachMedia(v); - hls.on(Hls.Events.MANIFEST_PARSED, ()=>{ v.play().catch(()=>{}); }); - v._hls = hls; - } else if(isHls && v && v.canPlayType('application/vnd.apple.mpegurl')){ - v.src = streamUrl; // native Safari HLS - } - st.textContent = '✅ Đã lấy video. Bấm play để xem trước.'; - st.style.color = '#8f8'; - } - } else { - preview.style.display = 'none'; - if(j.note){ - st.textContent = '⚠️ ' + j.note; - st.style.color = '#e0a030'; - } else { - st.textContent = '❌ Không phát trước được (có thể do nguồn chặn). Bạn vẫn có thể thử tạo short.'; - st.style.color = '#e05555'; - } - } - }catch(e){ - st.textContent = '❌ ' + e.message; - st.style.color = '#e05555'; - preview.style.display = 'none'; - document.getElementById('sc-scrape-direct').value = ''; - document.getElementById('sc-scrape-duration').value = ''; - } - }); - } - - // ---- rewrite image picker (chọn 1 ảnh cho nhiều slide) ---- - let _scChosenImg = ''; - document.getElementById('sc-rewrite-list').addEventListener('click', e=>{ - const btn = e.target.closest('.sc-rw-img'); - if(!btn) return; - document.querySelectorAll('.sc-rw-img').forEach(b=>{ b.style.borderColor='#333'; b.dataset.sel='0'; }); - btn.style.borderColor='#ffd700'; btn.dataset.sel='1'; - _scChosenImg = btn.dataset.img || ''; - const hidden = document.getElementById('sc-chosen-img'); - if(hidden) hidden.value = _scChosenImg; + } + + try{ + const r = await fetch('/api/ai/short/' + encodeURIComponent(postId), { + method:'POST', + headers:{'Content-Type':'application/json'}, + body: JSON.stringify({voice:voice, emotion:emotion, speed:speed}) }); - - // ---- audio source toggles (skipped in HOT mode) ---- - if(!hotMode){ - function setAudioSrc(v){ - // nhạc nền TikTok luôn hiển thị để nghe thử; ẩn khi chọn "Không âm thanh" - document.getElementById('sc-music-wrap').style.display = v==='none' ? 'none' : 'block'; - document.getElementById('sc-upload-wrap').style.display = v==='upload' ? 'block' : 'none'; - } - document.getElementById('sc-audio-src').addEventListener('change', e=>setAudioSrc(e.target.value)); - if(hasPrev && p.video) setAudioSrc('prev'); else setAudioSrc('tts'); - } - - // ---- recreate slides: show/hide slide picker ---- - const scReuse = document.getElementById('sc-reuse-slides'); - if(scReuse){ - scReuse.addEventListener('change', function(){ - const pk = document.getElementById('sc-slide-picker'); - if(pk) pk.style.display = this.checked ? 'block' : 'none'; - }); - } - - // ---- music preview player (skipped in HOT mode) ---- - let _scAudio = null; - const listenBtn = hotMode ? null : document.getElementById('sc-music-listen'); - const musicSel = hotMode ? null : document.getElementById('sc-music'); - const playerBox = hotMode ? null : document.getElementById('sc-music-playerbox'); - if(listenBtn && musicSel){ - listenBtn.addEventListener('click', function(){ - const opt = musicSel.options[musicSel.selectedIndex]; - const aurl = opt ? (opt.dataset.aurl || '') : ''; - if(!aurl){ - alert('Không có link nhạc cho lựa chọn này.'); - return; - } - // proxy để tránh CORS khi phát thử trong trình duyệt - const streamUrl = '/api/ai-short/music/stream?url=' + encodeURIComponent(aurl); - if(_scAudio && _scAudio.dataset.src === aurl && !_scAudio.paused){ - _scAudio.pause(); listenBtn.textContent = '▶ Nghe thử'; - return; - } - if(_scAudio) _scAudio.pause(); - if(playerBox) playerBox.style.display = 'block'; - if(playerBox) playerBox.innerHTML = '
🎧 '+esc(opt.text)+'
'; - _scAudio = playerBox ? playerBox.querySelector('audio') : null; - if(_scAudio){ - _scAudio.dataset.src = aurl; - _scAudio.addEventListener('ended', function(){ listenBtn.textContent = '▶ Nghe thử'; }); - _scAudio.addEventListener('error', function(){ - listenBtn.textContent = '▶ Nghe thử'; - toast('❌ Không phát được nhạc thử (mạng/vùng chặn). Bạn vẫn có thể chọn để trộn vào video.'); - }); - listenBtn.textContent = '⏹ Dừng'; - } - }); - } - - // ---- create ---- - document.getElementById('sc-create-btn').addEventListener('click', async ()=>{ - const btn = document.getElementById('sc-create-btn'); - const st = document.getElementById('sc-status'); - btn.disabled = true; btn.textContent = '⏳ Đang tạo...'; - st.textContent = 'Đang chuẩn bị...'; - - // upload files first - try{ - // image file (not in HOT mode) - let imgUrl = ''; - const imgUrlInput = document.getElementById('sc-img-url'); - if(imgUrlInput) imgUrl = imgUrlInput.value.trim() || ''; - const imgFile = hotMode ? null : document.getElementById('sc-img-file').files[0]; - if(imgFile){ - st.textContent = '⏳ Đang tải ảnh lên...'; - const fd = new FormData(); fd.append('file', imgFile, imgFile.name); - const r = await fetch('/api/ai-short/upload', {method:'POST', body:fd}); - const j = await r.json(); - if(!r.ok || j.error) throw new Error(j.error || 'Lỗi upload ảnh'); - imgUrl = j.url; - } - // video file (not in HOT mode) - let videoUrl = ''; - const videoFile = hotMode ? null : document.getElementById('sc-video-file').files[0]; - if(videoFile){ - st.textContent = '⏳ Đang tải video lên...'; - const fd = new FormData(); fd.append('file', videoFile, videoFile.name); - const r = await fetch('/api/ai-short/upload', {method:'POST', body:fd}); - const j = await r.json(); - if(!r.ok || j.error) throw new Error(j.error || 'Lỗi upload video'); - videoUrl = j.url; - } - // audio file (not in HOT mode) - let uploadAudioUrl = ''; - const audioFile = hotMode ? null : document.getElementById('sc-audio-file').files[0]; - if(audioFile){ - st.textContent = '⏳ Đang tải audio lên...'; - const fd = new FormData(); fd.append('file', audioFile, audioFile.name); - const r = await fetch('/api/ai-short/upload', {method:'POST', body:fd}); - const j = await r.json(); - if(!r.ok || j.error) throw new Error(j.error || 'Lỗi upload audio'); - uploadAudioUrl = j.url; - } - - const audioSrc = hotMode ? 'video' : (document.getElementById('sc-audio-src').value); - const useSlides = hotMode ? false : (document.getElementById('sc-reuse-slides') ? document.getElementById('sc-reuse-slides').checked : false); - // nhạc nền TikTok: giá trị != none được trộn vào video (kể cả tạo lại) - let musicId = ''; - const musicSel = hotMode ? null : document.getElementById('sc-music'); - if(musicSel && musicSel.value && musicSel.value !== 'none' && audioSrc !== 'none'){ - musicId = musicSel.value; - } - if(audioSrc === 'music') musicId = musicSel ? musicSel.value : ''; - let audioUrl = ''; - if(hotMode){ audioUrl = ''; } - else if(audioSrc==='upload') audioUrl = uploadAudioUrl; - else if(audioSrc==='prev' && p.video){ audioUrl = p.short_audio_url || ''; } - // reuse_audio explicitly: only when user chose "giữ nguyên audio short trước" - const reuseAudio = hotMode ? false : (audioSrc === 'prev'); - // collect selected slide indices (recreate mode) - let slideIndices = []; - if(useSlides){ - document.querySelectorAll('#sc-slide-picker .sc-slide-chk:checked').forEach(chk=>{ - slideIndices.push(parseInt(chk.dataset.idx)); - }); - if(!slideIndices.length){ - st.textContent = '⚠️ Chọn ít nhất 1 slide để tạo lại.'; - throw new Error('Chọn ít nhất 1 slide'); - } - } - // reuse_audio is sent explicitly above; music (audio_music) is overlaid by the backend - const body = { - post_id: p.id, - use_slides: useSlides, - slide_indices: slideIndices, - reuse_audio: reuseAudio, - voice: hotMode ? 'vi-VN-HoaiMyNeural' : document.getElementById('sc-voice').value, - emotion: hotMode ? 'neutral' : document.getElementById('sc-emotion').value, - speed: hotMode ? 1.0 : (parseFloat(document.getElementById('sc-speed').value) || 1.2), - audio_music: musicId, - audio_url: audioUrl, - }; - if(hotMode){ - // create a brand-new wall post on the AI wall - body.create_new = true; - const hotTitleEl = document.getElementById('sc-hot-title'); - body.title = hotTitleEl ? hotTitleEl.value.trim() : ''; - // scraped video title as fallback wall title - if(!body.title){ - const meta = document.getElementById('sc-video-meta'); - body.title = (meta && meta.dataset.title) ? meta.dataset.title : '🔥 Short HOT'; - } - body.text = ''; - body.language = 'vi'; - const srcEl = document.getElementById('sc-video-link'); - if(srcEl && srcEl.value.trim()) body.url = srcEl.value.trim(); - } - // if uploaded video selected -> use it as background via images? No: - if(bgMode==='video' && videoUrl){ - body.video_url = videoUrl; // backend handles - const vmute = document.getElementById('sc-video-mute'); - if(vmute && vmute.checked) body.video_muted = true; - } else if(bgMode==='link'){ - // scraped video from link: video-first + image tail completion - const scDirect = document.getElementById('sc-scrape-direct') ? document.getElementById('sc-scrape-direct').value : ''; - const meta = document.getElementById('sc-video-meta'); - const scEmbed = meta ? (meta.getAttribute('data-embed') || '') : ''; - const scThumb = meta ? (meta.getAttribute('data-thumb') || '') : ''; - const scTitle = meta ? (meta.getAttribute('data-title') || '') : ''; - const scDesc = meta ? (meta.getAttribute('data-desc') || '') : ''; - // if the modal title was auto-filled from the scrape, prefer it for - // the wall post (user can still edit it before submitting) - const hotTitleVal = document.getElementById('sc-hot-title') ? document.getElementById('sc-hot-title').value.trim() : ''; - if(scDirect && !/youtube\.com\/embed|youtu\.be\/|tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|player\.vimeo\.com|platform\.twitter\.com/.test(scDirect)){ - body.video_url = scDirect; - body.scrape_mode = true; // video-first assembly - const vdur = document.getElementById('sc-scrape-duration') ? document.getElementById('sc-scrape-duration').value : ''; - if(vdur) body.video_dur = parseFloat(vdur) || undefined; - const lmute = document.getElementById('sc-link-mute'); - if(lmute && lmute.checked) body.video_muted = true; - // still send the chosen images (they complete the short if the - // video is shorter than the voice) - const chosen = document.getElementById('sc-chosen-img') ? document.getElementById('sc-chosen-img').value : ''; - const imgs = []; - if(chosen) imgs.push(chosen); - if(imgUrl) imgs.push(imgUrl); - if(imgs.length) body.images = imgs; - if(chosen) body.fixed_image = chosen; - } else if(scEmbed){ - // oEmbed fallback: media can't be downloaded (TikTok/FB/IG/YT block - // datacenter IPs) -> save the short as an embeddable slide with - // auto title/desc/thumb from the scrape metadata. - body.embed_url = scEmbed; - body.embed_title = hotTitleVal || scTitle || ''; - body.embed_thumb = scThumb || ''; - body.embed_desc = scDesc || ''; - const chosenImg = imgUrl || (document.getElementById('sc-chosen-img') ? document.getElementById('sc-chosen-img').value : ''); - if(chosenImg) body.images = [chosenImg]; - } else { - // No direct media and no embed metadata from the scrape. If the - // user pasted a social/link URL, still post it — the backend - // auto-probes oEmbed and saves the short as an embed slide with - // auto title/desc/thumb (no more "chưa lấy được video" error). - const srcUrlEl = document.getElementById('sc-video-link'); - const srcUrl = srcUrlEl ? srcUrlEl.value.trim() : ''; - if(srcUrl && /^https?:\/\//i.test(srcUrl)){ - body.url = srcUrl; - body.allow_oembed_fallback = true; - st.textContent = 'ℹ️ Không lấy được video trực tiếp — sẽ đăng dạng oEmbed (backend tự lấy tiêu đề/mô tả/ảnh).'; - st.style.color = '#e0a030'; - } else { - st.textContent = '⚠️ Bấm "📥 Lấy video" để lấy video từ link trước khi tạo.'; - throw new Error('Chưa lấy được video từ link'); - } - } - } else { - // 1. ảnh chọn từ danh sách rewrite (áp dụng cho nhiều slide, fix nền cho cả short) - // 2. ảnh URL nhập tay / tải lên - const chosen = document.getElementById('sc-chosen-img') ? document.getElementById('sc-chosen-img').value : ''; - const imgs = []; - if(chosen) imgs.push(chosen); - if(imgUrl) imgs.push(imgUrl); - if(imgs.length) body.images = imgs; // backend: first = fixed bg (normal mode) - if(chosen) body.fixed_image = chosen; // applies to slides mode too (1 ảnh cho nhiều slide) - } - st.textContent = '⏳ Đang tạo video short (có thể mất 1-2 phút)...'; - const r2 = await fetch('/api/ai-short', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)}); - const j2 = await r2.json(); - if(!r2.ok || j2.error) throw new Error(j2.error || 'Lỗi tạo video'); - toast('✅ Đã tạo Short AI!'); - const pp = _wallPosts.find(x => String(x.id) === String(p.id)); - if(pp){ - pp.video = j2.video; - pp.voice = j2.voice; pp.emotion = j2.emotion; pp.short_speed = j2.speed; - pp.short_music = j2.music; pp.short_audio_url = audioUrl; pp.short_use_slides = j2.use_slides; - pp.short_images = j2.images; - } - if(hotMode && j2.post){ - // 🆕 brand-new wall post created by the backend -> prepend on the AI wall - prependWallPost(j2.post); - } else { - const itemId = 'wall-item-'+p.id; - const el = document.getElementById(itemId); - if(el){ - const idx = _wallPosts.indexOf(pp); - el.insertAdjacentHTML('afterend', makeWallItem(pp, idx)); - el.remove(); - } - } - document.getElementById('short-creator-overlay').remove(); - }catch(e){ - st.textContent = '❌ ' + e.message; - btn.disabled = false; btn.textContent = hotMode ? '🔥 Thêm Short HOT' : '🎬 Tạo Short AI'; - toast('❌ ' + e.message); + const j = await r.json(); + if(!r.ok || j.error) throw new Error(j.error||'Lỗi tạo video'); + toast('✅ Đã tạo video shorts!'); + const p = _wallPosts.find(x => String(x.id) === String(postId)); + if(p){ + p.video = j.video; + p.voice = j.voice; + p.emotion = j.emotion; + const itemId = 'wall-item-'+postId; + const el = document.getElementById(itemId); + if(el){ + const idx = _wallPosts.indexOf(p); + el.outerHTML = makeWallItem(p, idx); + const newEl = document.getElementById(itemId); + if(newEl) newEl.className = 'wall-item wall-item-new'; } - }); - }); + } + refreshShortAISlider(); + }catch(e){ + toast('❌ '+e.message); + if(btn){btn.disabled=false;btn.textContent=origText;} + } } -/* legacy fast path — used by any remaining tts-create-btn handlers */ -async function makeShortVideo(postId, btn, voice, speed, emotion){ - openShortCreator(postId); - return; +function refreshShortAISlider(){ + const aiShorts = _wallPosts.filter(p=>p.video); + let shortAISection = document.getElementById('short-ai-section'); + if(aiShorts.length === 0){ + if(shortAISection) shortAISection.remove(); + return; + } + if(!shortAISection){ + // Create the section if it doesn't exist (first short created) + const homeEl=document.getElementById('view-home'); + if(!homeEl) return; + shortAISection=document.createElement('div'); + shortAISection.className='slider-wrap';shortAISection.id='short-ai-section'; + shortAISection.innerHTML='
🎬 Short AI
'; + const insertBefore=homeEl.querySelector('.slider-wrap'); + if(insertBefore) homeEl.insertBefore(shortAISection,insertBefore); + else homeEl.appendChild(shortAISection); + } + const track = shortAISection.querySelector('.slider-track'); + if(track){ + let h = ''; + aiShorts.slice(0,20).forEach((p,i)=>{ + h+=`
${esc(p.title)}
`; + }); + track.innerHTML = h; + } } +// === VOICE + EMOTION SYSTEM === var VOICE_LIST = [ {id:'vi-VN-HoaiMyNeural', label:'🎙️ Hoài My (VI)', lang:'vi'}, {id:'vi-VN-NamMinhNeural', label:'🎙️ Nam Minh (VI)', lang:'vi'}, @@ -1456,20 +302,32 @@ var EMOTION_LIST = [ {id:'warm', label:'💖 Ấm áp'}, ]; +// Event delegation for voice/emotion buttons (backup for dynamically rendered content) +// Event delegation for TTS voice/emotion/speed - single source of truth document.addEventListener('click',function(e){ + // Voice button var btn = e.target.closest('.tts-voice-btn'); if(btn){ var container = btn.closest('.tts-selector'); if(container){ var selKey = 'inline-'+container.dataset.postId; if(!_ttsSelections[selKey]) _ttsSelections[selKey]={voice:btn.dataset.voice,emotion:'neutral'}; + // Reset all voice buttons in this container var allBtns = container.querySelectorAll('.tts-voice-btn'); - for(var i=0;i'; - h+='
🎙️ Giọng đọc (ngôn ngữ: '+lang.toUpperCase()+'):
'; - VOICE_LIST.forEach(function(v){var sel=v.id===_ttsSelections[selKey].voice?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); - h+='
😊 Cảm xúc:
'; - EMOTION_LIST.forEach(function(e){var sel=e.id===_ttsSelections[selKey].emotion?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); - h+='
⚡ Tốc độ:'; - h+='
'; - h+='
'; + h+='
🎙️ Giọng đọc (ngôn ngữ: '+lang.toUpperCase()+'):
'; + h+='
'; + VOICE_LIST.forEach(function(v){ + var sel=v.id===_ttsSelections[selKey].voice?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222'; + h+=''; + }); + h+='
'; + h+='
😊 Cảm xúc:
'; + h+='
'; + EMOTION_LIST.forEach(function(e){ + var sel=e.id===_ttsSelections[selKey].emotion?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222'; + h+=''; + }); + h+='
'; + h+='
⚡ Tốc độ:'; + h+='
'; + h+=''; + h+=''; return h; } +// FIXED: bindVoiceEmotionSelector now uses proper class-based selection tracking window.showVoiceEmotionSelector=function(postId,title,text){ var overlay=document.createElement('div'); overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.85);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px'; - var box=document.createElement('div');box.style.cssText='background:#1a1a1a;border:2px solid #2d8659;border-radius:16px;padding:20px;max-width:400px;width:100%;max-height:80vh;overflow-y:auto'; - var lang=detectLanguage(title+' '+text);var autoEmotion=detectEmotion(title+' '+text); + var box=document.createElement('div'); + box.style.cssText='background:#1a1a1a;border:2px solid #2d8659;border-radius:16px;padding:20px;max-width:400px;width:100%;max-height:80vh;overflow-y:auto'; + var lang=detectLanguage(title+' '+text); + var autoEmotion=detectEmotion(title+' '+text); var h='

🎬 Tạo Short AI (ngôn ngữ: '+lang.toUpperCase()+')

'; h+='
🎙️ Chọn giọng đọc:
'; - VOICE_LIST.forEach(function(v){var sel=v.id===getAutoVoice(lang)?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); - h+='
😊 Chọn cảm xúc:
'; - EMOTION_LIST.forEach(function(e){var sel=e.id===autoEmotion?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); - h+='
⚡ Tốc độ:
'; - h+='
'; + VOICE_LIST.forEach(function(v){ + var sel=v.id===getAutoVoice(lang)?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222'; + h+=''; + }); + h+=''; + h+='
😊 Chọn cảm xúc:
'; + EMOTION_LIST.forEach(function(e){ + var sel=e.id===autoEmotion?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222'; + h+=''; + }); + h+='
'; + h+='
⚡ Tốc độ:
'; + h+='
'; h+='
'; h+='
'; h+=''; @@ -1571,664 +466,227 @@ window.showVoiceEmotionSelector=function(postId,title,text){ box.querySelector('#ve-status').style.display='block';box.querySelector('#ve-status').textContent='Đang tạo video shorts...'; try{ var speed=parseFloat(box.querySelector('#ve-speed').value)||1.2; + // FIX: Store selections in _ttsSelections for consistency if(!_ttsSelections["inline-"+postId]) _ttsSelections["inline-"+postId]={voice:"vi-VN-HoaiMyNeural",emotion:"neutral"}; - _ttsSelections["inline-"+postId].voice=selectedVoice;_ttsSelections["inline-"+postId].emotion=selectedEmotion; + _ttsSelections["inline-"+postId].voice=selectedVoice; + _ttsSelections["inline-"+postId].emotion=selectedEmotion; var r=await fetch('/api/ai/short/'+encodeURIComponent(postId),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice:selectedVoice,emotion:selectedEmotion,speed:speed})}); var j=await r.json(); if(!r.ok||j.error) throw new Error(j.error||'Lỗi tạo video'); toast('✅ Đã tạo Short AI!');overlay.remove(); var p=_wallPosts.find(function(x){return String(x.id)===String(postId);}); if(p){p.video=j.video;p.voice=j.voice;p.emotion=j.emotion;} + refreshShortAISlider(); }catch(e){this.disabled=false;this.textContent='🎬 Tạo Short';box.querySelector('#ve-status').textContent='❌ '+e.message;} }); }; +window.showSlidePreview=function(slides,title){ + if(!slides||!slides.length) return; + var overlay=document.createElement('div');overlay.id='slide-preview'; + overlay.style.cssText='position:fixed;inset:0;background:#000;z-index:99999;display:flex;flex-direction:column;overflow:hidden'; + var currentSlide=0; + function renderSlide(idx){ + var s=slides[idx]; + overlay.innerHTML='
'+ + ''+ + ''+(idx+1)+'/'+slides.length+''+ + '
'+ + '
'+ + (s.image?'':'')+ + '
'+ + '
'+ + '

'+esc(s.text)+'

'+ + '
'+ + '
'+ + ''+ + ''+ + '
'; + } + window.nextSlideRip=function(currentIdx){if(currentIdx0){currentSlide--;renderSlide(currentSlide);}}; + renderSlide(0);document.body.appendChild(overlay); + var startX=0; + overlay.addEventListener('touchstart',function(e){startX=e.touches[0].clientX;}); + overlay.addEventListener('touchend',function(e){var diff=e.changedTouches[0].clientX-startX;if(diff<-50)window.nextSlideRip(currentSlide);else if(diff>50)window.prevSlide();}); +}; function prependWallPost(post){ _wallPosts.unshift(post); const track=document.getElementById('ai-wall-track'); const wrap=document.getElementById('ai-wall-wrap'); - const target=document.getElementById('ai-wall-under-compose'); - if(target && (!track||!wrap)){ - const newWrap=document.createElement('div'); - newWrap.className='slider-wrap';newWrap.id='ai-wall-wrap'; - newWrap.innerHTML=`
🧱 Tường AI
${makeWallItem(post,0)}
`; - target.appendChild(newWrap); - const firstItem=newWrap.querySelector('.wall-item'); - if(firstItem)firstItem.className='wall-item wall-item-new'; - // re-interleave YouTube feed items after new wall content - if(typeof _ytFeedVideos !== 'undefined') _renderYTFeedInWall(); + const homeEl=document.getElementById('view-home'); + if(!track||!wrap){ + if(homeEl){ + let insertBefore=homeEl.querySelector('.slider-wrap'); + const newWrap=document.createElement('div'); + newWrap.className='slider-wrap'; + newWrap.id='ai-wall-wrap'; + newWrap.innerHTML=`
🧱 Tường AI
${makeWallItem(post,0)}
`; + if(insertBefore) homeEl.insertBefore(newWrap,insertBefore); + else homeEl.appendChild(newWrap); + const firstItem=newWrap.querySelector('.wall-item'); + if(firstItem)firstItem.className='wall-item wall-item-new'; + } return; } - if(track){ - track.insertAdjacentHTML('afterbegin', makeWallItem(post, 0)); - track.scrollTo({left:0,behavior:'smooth'}); - // re-interleave YouTube feed items after new wall content - if(typeof _renderYTFeedInWall === 'function') _renderYTFeedInWall(); - } -} - + const div=document.createElement('div'); + div.className='wall-item wall-item-new'; + div.id='wall-item-'+(post.id||'new-'+Date.now()); + const hasVideo = post.video && post.video.length > 0; + const thumbContent = post.img + ? `` + : (hasVideo ? `` : ''); + const videoBadge = hasVideo ? `
🎬
` : ''; + const videoBtn = hasVideo + ? `` + : ``; + div.innerHTML=`
${thumbContent}${videoBadge}
${esc(post.title)}
${esc((post.text||'').slice(0,180))}
${videoBtn}
`; + track.prepend(div); + track.scrollTo({left:0,behavior:'smooth'}); + if(hasVideo) refreshShortAISlider(); +} + +// === REST OF FUNCTIONS === +let _shortsData=[]; let _wallPosts=[]; let _currentView='home'; let _currentEventId=null; let _currentMatchUrl=null; +function interleaveShorts(shorts){const dt=shorts.filter(s=>s.channel==='baodantri7941');const sk=shorts.filter(s=>s.channel==='baosuckhoedoisongboyte');const result=[];let i=0,j=0;while(i{const topicText=t.topic||t.label.replace(/^#/,'');return``;}).join('');} +async function loadHotTopics(){const j=await fetch('/api/hot_topics').then(r=>r.json()).catch(()=>({topics:[]}));const el=document.getElementById('hot-topics');if(!el)return;el.innerHTML=(j.topics||[]).slice(0,18).map(t=>{const topicText=t.topic||t.label.replace(/^#/,'');return``;}).join('');if(j.topics&&j.topics[0]){const firstTopic=j.topics[0].topic||j.topics[0].label.replace(/^#/,'');setTimeout(()=>searchTopic(firstTopic),800);}} function searchTopic(topic){if(!topic){topic=document.getElementById('topic-input')?.value.trim();if(!topic){alert('Nhập chủ đề');return;}}document.getElementById('topic-input').value='';_htTopic=topic;_htPage=0;showHashtagSources(topic,0);} -async function showHashtagSources(topic,page){const box=document.getElementById('hashtag-box');if(!box)return;if(page===0)box.innerHTML=`

🔍 ${esc(topic)}

Đang tìm...
`;try{const r=await fetch(`/api/hashtag/sources?topic=${encodeURIComponent(topic)}&page=${page}`);const j=await r.json();const sources=j.sources||[];if(!sources.length&&page===0){box.innerHTML=`

🔍 ${esc(topic)}

Không tìm được bài viết liên quan
`;return;}let h='';if(page===0)h=`

🔍 ${esc(topic)} (${j.total} bài từ 8 nguồn)

`;sources.forEach((s,i)=>{const idx=page*8+i;h+=`
${esc(s.title)}
${esc(s.via||'')}
`;});if(page===0){h+=`
`;if(j.has_more)h+=``;h+=`
`;box.innerHTML=h;}else{document.getElementById('ht-list')?.insertAdjacentHTML('beforeend',h);const btn=document.getElementById('ht-more');if(btn){if(!j.has_more)btn.remove();else{btn.disabled=false;btn.textContent='Tải thêm ▼';}}}sources.forEach((s,i)=>{const idx=page*8+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-'+idx);if(el)el.innerHTML=``;}}).catch(()=>{});});}catch(e){box.innerHTML=`

🔍 ${esc(topic)}

Lỗi: ${esc(e.message)}
`;}} +async function showHashtagSources(topic,page){const box=document.getElementById('hashtag-box');if(!box)return;if(page===0)box.innerHTML=`

🔍 ${esc(topic)}

Đang tìm...
`;try{const r=await fetch(`/api/hashtag/sources?topic=${encodeURIComponent(topic)}&page=${page}`);const j=await r.json();const sources=j.sources||[];if(!sources.length&&page===0){box.innerHTML=`

🔍 ${esc(topic)}

Không tìm được bài viết liên quan
`;return;}let h='';if(page===0)h=`

🔍 ${esc(topic)} (${j.total} bài từ 8 nguồn)

`;sources.forEach((s,i)=>{const idx=page*8+i;h+=`
${esc(s.title)}
${esc(s.via||'')}
`;});if(page===0){h+=`
`;if(j.has_more)h+=``;h+=`
`;box.innerHTML=h;}else{document.getElementById('ht-list')?.insertAdjacentHTML('beforeend',h);const btn=document.getElementById('ht-more');if(btn){if(!j.has_more)btn.remove();else{btn.disabled=false;btn.textContent='Tải thêm ▼';}}}sources.forEach((s,i)=>{const idx=page*8+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-'+idx);if(el)el.innerHTML=``;}}).catch(()=>{});});}catch(e){box.innerHTML=`

🔍 ${esc(topic)}

Lỗi: ${esc(e.message)}
`;}} function loadMoreHashtag(){_htPage++;const btn=document.getElementById('ht-more');if(btn){btn.disabled=true;btn.textContent='Đang tải...';}showHashtagSources(_htTopic,_htPage);} async function rewriteHashtag(topic){const btn=event?.target;if(btn){btn.disabled=true;btn.textContent='Đang tổng hợp...';}try{const r=await fetch('/api/topic_post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({topic})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');toast('✅ Đã đăng Tường AI!');if(btn)btn.textContent='✅ Đăng thành công!';if(j.post)prependWallPost(j.post);}catch(e){toast('❌ '+e.message);if(btn){btn.disabled=false;btn.textContent='🤖 Rewrite AI';}}} -async function loadLivescore(tab){document.querySelectorAll('.ls-tab').forEach(t=>t.classList.remove('active'));document.querySelector(`.ls-tab[data-tab="${tab}"]`)?.classList.add('active');const el=document.getElementById('ls-content');if(!el)return;el.innerHTML='
Đang tải...
';let ep='/api/livescore/'+tab;if(tab.startsWith('bxh_'))ep='/api/livescore/standings/'+tab.replace('bxh_','');try{const d=await _fetchWithTimeout(ep,12000);el.innerHTML=d.html&&d.html.length>50?d.html:'
Không có dữ liệu
';bindMatchClicks(el);if(tab.startsWith('bxh_'))_decorateStandings(el);}catch(e){el.innerHTML='
Lỗi tải hoặc hết thời gian
';}} -function _decorateStandings(el){ - try{ - const items=el.querySelectorAll('.leaderboard-item'); - if(!items.length)return; - // Build header row: # | Đội bóng | Tr T H B BT BB +/- Đ - const head=document.createElement('div'); - head.className='ls-bxh-head'; - head.innerHTML='

Tr

T

H

B

BT

BB

+/-

Đ

'; - el.insertBefore(head, items[0]); - // Make each row use flex layout with the copy cells as a fixed-width grid - items.forEach(function(it){ - it.classList.add('ls-bxh-row'); +async function loadLivescore(tab){document.querySelectorAll('.ls-tab').forEach(t=>t.classList.remove('active'));document.querySelector(`.ls-tab[data-tab="${tab}"]`)?.classList.add('active');const el=document.getElementById('ls-content');if(!el)return;el.innerHTML='
Đang tải...
';let ep='/api/livescore/'+tab;if(tab.startsWith('bxh_'))ep='/api/livescore/standings/'+tab.replace('bxh_','');try{const r=await fetch(ep);const d=await r.json();el.innerHTML=d.html&&d.html.length>50?d.html:'
Không có dữ liệu
';bindMatchClicks(el);}catch(e){el.innerHTML='
Lỗi
';}} +function bindMatchClicks(el){ + el.querySelectorAll('.match-detail').forEach(md=>{ + md.style.cursor='pointer'; + md.addEventListener('click',function(e){ + const statusA=this.querySelector('.status a'); + const teamA=this.querySelector('.teams a[href*="/tran-dau/"]'); + const a = statusA || teamA; + if(a){ + e.preventDefault(); + e.stopPropagation(); + const href=a.getAttribute('href')||''; + const m=href.match(/\/tran-dau\/(\d+)\//); + if(m){ + const fullUrl=href.startsWith('http')?href:'https://bongda.com.vn'+href; + openMatch(m[1],fullUrl); + } + } }); - }catch(e){} + }); + el.querySelectorAll('a').forEach(a=>{ + a.addEventListener('click',e=>{e.preventDefault();e.stopPropagation()}); + }); } -function bindMatchClicks(el){el.querySelectorAll('.match-detail').forEach(md=>{md.style.cursor='pointer';md.addEventListener('click',function(e){const statusA=this.querySelector('.status a');const teamA=this.querySelector('.teams a[href*="/tran-dau/"]');const a = statusA || teamA;if(a){e.preventDefault();e.stopPropagation();const href=a.getAttribute('href')||'';const m=href.match(/\/tran-dau\/(\d+)\//);if(m){const fullUrl=href.startsWith('http')?href:'https://bongda.com.vn'+href;openMatch(m[1],fullUrl);}}});});el.querySelectorAll('a').forEach(a=>{a.addEventListener('click',e=>{e.preventDefault();e.stopPropagation()});});} function openMatch(id,url){if(!id)return;_currentEventId=id;if(url)_currentMatchUrl=url;document.getElementById('match-overlay').classList.add('active');document.body.style.overflow='hidden';loadMatchTab('detail')} function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''} async function loadMatchTab(tab){document.querySelectorAll('.mo-tab').forEach(t=>t.classList.remove('active'));document.querySelectorAll('.mo-tab').forEach(t=>{if((tab==='comm'&&t.textContent==='Diễn biến')||(tab==='stats'&&t.textContent==='Thống kê')||(tab==='detail'&&t.textContent.includes('Chi tiết')))t.classList.add('active')});const el=document.getElementById('mo-body');if(!el)return;el.innerHTML='
Đang tải...
';try{let apiUrl;if(tab==='stats')apiUrl=`/api/match/${_currentEventId}/stats`;else if(tab==='comm')apiUrl=`/api/match/${_currentEventId}/commentaries`;else{apiUrl=`/api/match/${_currentEventId}/detail`;if(_currentMatchUrl)apiUrl+='?url='+encodeURIComponent(_currentMatchUrl)}const r=await fetch(apiUrl);if(!r.ok){el.innerHTML='
Lỗi máy chủ ('+r.status+')
';return}const d=await r.json();if(d.error){el.innerHTML='
'+esc(d.error)+'
';return}if(tab==='detail'&&typeof renderMatchDetail==='function'){renderMatchDetail(el,d);return}el.innerHTML=d.html||'
Không có dữ liệu
'}catch(e){el.innerHTML='
Lỗi
'}} -function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]))} -function showView(id){document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.getElementById(id)?.classList.add('active')} -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='';const tw=f.closest('.yt-thumb-wrap');if(tw)tw.style.backgroundImage='none'});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)}} -function toast(msg){let t=document.getElementById('progress-toast');if(t){t.textContent=msg;t.style.display='block';setTimeout(()=>{t.style.display='none'},3500)}} - -// ===== doShare: COPY link to clipboard, then try native share as bonus ===== - function doShare(title,url,img,postId){ - var shareUrl; - var _base = (typeof SPACE!=='undefined' && SPACE) ? SPACE : location.origin; - if(postId){ - shareUrl = _base+'/s?post_id='+encodeURIComponent(postId)+'&title='+encodeURIComponent(title); - } else { - shareUrl = _base+'/s?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title)+'&img='+encodeURIComponent(img||''); - } - // Try clipboard API first (modern, works on HTTPS) - if(navigator.clipboard && navigator.clipboard.writeText){ - navigator.clipboard.writeText(shareUrl).then(function(){ - toast('📋 Đã sao chép link!'); - try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){} - }).catch(function(){ - // Fallback: execCommand (deprecated but works on some browsers) - try{ - var ta=document.createElement('textarea'); - ta.value=shareUrl;ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='-9999px';ta.style.opacity='0'; - document.body.appendChild(ta);ta.select();ta.setSelectionRange(0,99999); - if(document.execCommand('copy')){toast('📋 Đã sao chép link!');} - else{prompt('📋 Sao chép link:', shareUrl);} - document.body.removeChild(ta); - }catch(e){prompt('📋 Sao chép link:', shareUrl);} - try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){} - }); - } else { - // execCommand approach - try{ - var ta=document.createElement('textarea'); - ta.value=shareUrl;ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='-9999px';ta.style.opacity='0'; - document.body.appendChild(ta);ta.select();ta.setSelectionRange(0,99999); - if(document.execCommand('copy')){toast('📋 Đã sao chép link!');} - else{prompt('📋 Sao chép link:', shareUrl);} - document.body.removeChild(ta); - }catch(e){prompt('📋 Sao chép link:', shareUrl);} - try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){} - } -} - async function doInteract(videoId,type){try{const r=await fetch('/api/v2/interact',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:videoId,type})});return await r.json();}catch(e){return null;}} async function getInteractions(videoId){try{return await fetch('/api/v2/interactions?id='+encodeURIComponent(videoId)).then(r=>r.json());}catch(e){return{views:0,likes:0,comments:0};}} async function getComments(videoId){try{const j=await fetch('/api/v2/comments?id='+encodeURIComponent(videoId)).then(r=>r.json());return j.comments||[];}catch(e){return[];}} async function postComment(videoId,text){try{const j=await fetch('/api/v2/comment',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:videoId,text})}).then(r=>r.json());return j.comments||[];}catch(e){return[];}} -function buildTikTokSlide(opts){return`
${opts.vtag}
${opts.badge||''}

${esc(opts.title)}

${opts.desc?`

${esc(opts.desc)}

`:''}
${opts.extraBtn||''}
${opts.idx+1}/${opts.total}
`;} -function toggleFeedFullscreen(videoId){ - const slide = videoId ? document.querySelector('.tiktok-slide[data-vid="'+videoId+'"]') : null; - const feedEl = slide ? slide.closest('.tiktok-container') : document.querySelector('.tiktok-container'); - if(!feedEl) return; - const on = feedEl.classList.toggle('feed-fullscreen'); - document.body.style.overflow = on ? 'hidden' : ''; - const icons = feedEl.querySelectorAll('[id^="fs-toggle-"]'); - icons.forEach(ic => { ic.textContent = on ? '✕' : '⛶'; }); - if(on){ - // keep the active slide centered & playable in full height - setTimeout(()=>{ slide && slide.scrollIntoView({block:'nearest'}); }, 60); - } else if(slide){ - slide.scrollIntoView({block:'nearest'}); - } -} +function buildTikTokSlide(opts){return`
${opts.vtag}
${opts.badge||''}

${esc(opts.title)}

${opts.extraBtn||''}
${opts.idx+1}/${opts.total}
`;} async function doView(videoId,btn){const j=await doInteract(videoId,'view');if(j){const c=btn.querySelector('.count');if(c)c.textContent=fmtNum(j.views);}} async function doLike(videoId,btn){const j=await doInteract(videoId,'like');if(j){const c=btn.querySelector('.count');if(c)c.textContent=fmtNum(j.likes);}} function fmtNum(n){if(!n)return'0';if(n>=1000000)return(n/1000000).toFixed(1)+'M';if(n>=1000)return(n/1000).toFixed(1)+'K';return String(n);} async function loadCounters(videoIds){for(let i=0;iĐang tải...';const cmts=await getComments(videoId);renderInlineComments(panel,videoId,idx,cmts);/* Remove snap so feed can scroll to show comment input */var sl=panel.closest('.tiktok-slide');if(sl)sl.style.scrollSnapAlign='';setTimeout(function(){var feed=document.getElementById('tiktok-feed');if(feed){var slidePos=sl?sl.offsetTop:0;feed.scrollTop=slidePos+200;}/* Focus input */var inp=document.getElementById('cmt-input-'+idx);if(inp)inp.focus();},300);} -function renderInlineComments(panel,videoId,idx,cmts){let h='
💬 Bình luận
';if(cmts.length){cmts.slice(-30).forEach(c=>{h+=`
${c.time||''}${esc(c.text)}
`;});}else{h+='
Chưa có bình luận
';}h+=`
`;panel.innerHTML=h;const list=panel.querySelector('.inline-cmt-list');if(list)list.scrollTop=list.scrollHeight;} -async function submitInlineCmt(videoId,idx){const inp=document.getElementById('cmt-input-'+idx);if(!inp)return;const text=inp.value.trim();if(!text)return;inp.value='';inp.disabled=true;const cmts=await postComment(videoId,text);inp.disabled=false;const panel=document.getElementById('cmt-inline-'+idx);if(panel)renderInlineComments(panel,videoId,idx,cmts);const cc=document.getElementById('cc-'+idx);if(cc)cc.textContent=fmtNum(cmts.length);/* Keep focus on input after submit */var inp2=document.getElementById('cmt-input-'+idx);if(inp2)inp2.focus();} -function toggle169View(videoId,iconId){const slide=videoId?document.querySelector(`.tiktok-slide[data-vid="${videoId}"]`):null;if(slide){slide.classList.toggle('ratio-wide');const iconEl=iconId?document.getElementById(iconId):null;if(iconEl)iconEl.textContent=slide.classList.contains('ratio-wide')?'📺':'🖥️';else{const btn=slide.querySelector('.tiktok-right-btn .icon');if(btn)btn.textContent=slide.classList.contains('ratio-wide')?'📺':'🖥️';}return}document.querySelectorAll('.tiktok-slide.ratio-wide').forEach(s=>s.classList.remove('ratio-wide'));document.querySelectorAll('.tiktok-slide').forEach(s=>s.classList.add('ratio-wide'));document.querySelectorAll('.tiktok-right-btn .icon').forEach(b=>{if(b.textContent==='🖥️')b.textContent='📺';})} -function initTikTokFeed(){const feed=document.getElementById('tiktok-feed');if(!feed)return;const slides=feed.querySelectorAll('.tiktok-slide');let cur=-1;function act(i){if(i===cur)return;slides.forEach((sl,idx)=>{const v=sl.querySelector('video');const fr=sl.querySelector('iframe');if(idx===i){sl._active=true;if(v&&v.dataset.hls&&!v._hls&&typeof Hls!=='undefined'&&Hls.isSupported()){const hls=new Hls();hls.loadSource(v.dataset.hls);hls.attachMedia(v);hls.on(Hls.Events.MANIFEST_PARSED,()=>v.play().catch(()=>{}));v._hls=hls}else if(v)v.play().catch(()=>{});if(fr&&!fr.src&&fr.dataset.ytSrc){fr.src=fr.dataset.ytSrc;const tw=fr.closest('.yt-thumb-wrap');if(tw)tw.style.backgroundImage='none'}const vid=sl.dataset.vid;if(vid&&!sl._viewed){sl._viewed=true;doInteract(vid,'view').then(j=>{if(j){const vc=document.getElementById('vc-'+idx);if(vc)vc.textContent=fmtNum(j.views);}});}}else{sl._active=false;if(v){v.pause();if(v._hls){v._hls.destroy();v._hls=null}}if(fr&&fr.src)fr.src=''}});cur=i}let sT;feed.addEventListener('scroll',()=>{clearTimeout(sT);sT=setTimeout(()=>{const rect=feed.getBoundingClientRect(),ctr=rect.top+rect.height/2;let best=-1,bestD=1e9;slides.forEach((sl,i)=>{const d=Math.abs(sl.getBoundingClientRect().top+sl.getBoundingClientRect().height/2-ctr);if(d=0)act(best)},150)});setTimeout(()=>act(0),400);slides.forEach(sl=>{const g=sl.querySelector('.slide-gesture');const v=sl.querySelector('video');const fr=sl.querySelector('iframe');const tapFn=e=>{if(g&&e.target!==g)return;if(v){e.preventDefault();if(e.detail>2)return;v.paused?v.play().catch(()=>{}):v.pause()}else if(fr&&fr.dataset.ytSrc&&sl._active){const src=fr.dataset.ytSrc;if(/tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|platform\.twitter\.com|player\.vimeo\.com|youtube\.com\/embed/.test(src)){window.open(src.replace(/&/g,'&'),'_blank')}}};if(g)g.addEventListener('click',tapFn);if(v)v.addEventListener('click',e=>{e.preventDefault();v.paused?v.play().catch(()=>{}):v.pause()})});const ids=[...slides].map(sl=>sl.dataset.vid||'');loadCounters(ids)} -async function openHighlightFeed(league,idx,link,forceUrl){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';let articles=(_hlLeagueData||{})[league]||[];if(!articles.length){try{articles=await fetch('/api/highlights/'+league).then(r=>r.json())}catch(e){articles=[]}}if(!articles.length){el.innerHTML='
Không có video
';return}const vids=[];const results=await Promise.all(articles.map(async(a,i)=>{try{const r=await fetch('/api/video_url?url='+encodeURIComponent(a.link)+'&img='+encodeURIComponent(a.img||''));const v=await r.json();if(v&&v.src){return{_idx:i,title:a.title||v.title||'',link:a.link||'',img:a.img||v.poster||'',src:v.src,type:v.type||'',poster:v.poster||a.img||''}}return null}catch(e){}return null}));results.forEach(r=>{if(r)vids.push(r)});vids.sort((a,b)=>a._idx-b._idx);if(!vids.length){el.innerHTML='
Không tìm thấy video
';return}let ti=-1;if(link){ti=vids.findIndex(v=>(v.link||'')===(link||''));}if(ti<0)ti=vids.findIndex(v=>v._idx===idx);if(ti<0)ti=0;const ordered=ti>0?[...vids.slice(ti),...vids.slice(0,ti)]:vids;let h=`
`;ordered.forEach((v,i)=>{const isYT=v.type==='youtube',isHLS=!isYT&&v.src?.includes('.m3u8'),poster=v.poster?` poster="${esc(v.poster)}"`:'';const vtag=isYT?`
`:isHLS?``:``;const videoId='hl-'+league+'-'+v._idx;const nv=(i+1)%ordered.length;h+=buildTikTokSlide({vtag,title:v.title,badge:'HL',badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:v.link||'',postId:'',extraBtn:``})});h+='
';el.innerHTML=h;setTimeout(()=>initTikTokFeed(),200);} -async function openYTShortsFeed(idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đã xóa Shorts Dân trí/SKĐS
';} -async function openShortAIFeed(idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');if(!_wallPosts||!_wallPosts.length){el.innerHTML='
Không có Short AI
';return}const aiPosts=_wallPosts.filter(p=>p.video);if(!aiPosts.length||idx>=aiPosts.length){el.innerHTML='
Không có Short AI
';return}const ordered=aiPosts.slice(idx).concat(aiPosts.slice(0,idx));let h=`
`;ordered.forEach((p,i)=>{const baseIdx=_wallPosts.indexOf(p);const isYT=/youtube\.com\/embed|youtu\.be\/|youtube-nocookie|tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|platform\.twitter\.com|player\.vimeo\.com/.test(p.video||'');const vtag=p.video?isYT?`
`:``:'';h+=buildTikTokSlide({vtag,title:p.title,badge:'Short AI',badgeClass:'badge-ai',videoId:p.id||'ai-'+i,idx:i,total:ordered.length,shareUrl:p.video||'',postId:p.id||'',desc:(p.text&&p.text!==p.title?p.text:'').slice(0,400),extraBtn:``})});h+='
';el.innerHTML=h;setTimeout(()=>initTikTokFeed(),200);} -function readWallPost(idx){const p=_wallPosts&&_wallPosts[idx];if(!p)return;if(p.slides&&p.slides.length){readSlidePost(idx);return}const isEmb=p.embed_oembed||/(tiktok\.com\/embed|facebook\.com\/plugins|instagram\.com\/p\/.*\/embed|youtube\.com\/embed|platform\.twitter\.com|player\.vimeo\.com)/.test(p.video||'');if(isEmb||(p.video&&p.video.indexOf('/api/ai/short-file/')===0&&!p.url)){openShortAIFeed(_wallPosts.filter(x=>x.video).indexOf(p));return}readArticle(p.url||'','','',p.title,p.text);} -/** Show rewrite slide viewer - vertical slides with text+image */ -function readSlidePost(idx){const p=_wallPosts[idx];if(!p||!p.slides)return;showView('view-article');const el=document.getElementById('view-article');let h=`
`;p.slides.forEach((s,i)=>{h+=`
Slide ${s.index||i+1}/${p.slides.length}
${s.image?``:''}

${esc(s.text)}

`;});h+=`
`;el.innerHTML=h;} - -/** Slide Designer Modal - design a slide image with high-contrast text on background */ -function designerGetRatio(){const v=document.getElementById('designer-ratio')?.value||'3:4';const m=v.split(':');return m.length===2?{w:parseInt(m[0]),h:parseInt(m[1])}:1;} -function designerGetLayout(){return document.getElementById('designer-layout')?.value||'solid';} -function designerDebounce(fn,d){clearTimeout(fn._t);fn._t=setTimeout(fn,d);} -function openSlideDesigner(idx){ - designerSlideIdx=idx; - const p=_wallPosts[idx];if(!p||!p.slides)return; - const overlay=document.createElement('div');overlay.id='slide-designer-overlay';overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.92);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto'; - let h='
'; - h+='

🎨 Thiết kế ảnh slide

'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - ['#ffffff','#000000','#ff4444','#44ff44','#4444ff','#ffff00','#ff00ff','#00ffff','#ff8800','#88ff00'].forEach(c=>{h+=``;}); - h+='
'; - h+='
'; - h+='
'; - h+=''; - h+='
'; - overlay.innerHTML=h;document.body.appendChild(overlay); - document.getElementById('designer-slide-select').addEventListener('change',function(){updateDesignerText(this.value);previewDesignerSlide();}); - document.getElementById('designer-preview-btn').addEventListener('click',function(){previewDesignerSlide();}); - document.getElementById('designer-save-btn').addEventListener('click',function(){saveDesignerSlide(p.title,(p.id||''),idx);}); - ['change','input'].forEach(function(evt){ - const txt=document.getElementById('designer-text');if(txt)txt.addEventListener(evt,function(){designerDebounce(previewDesignerSlide,150);}); - const bg=document.getElementById('designer-bg-url');if(bg)bg.addEventListener(evt,function(){designerDebounce(previewDesignerSlide,150);}); - const ratio=document.getElementById('designer-ratio');if(ratio)ratio.addEventListener(evt,function(){previewDesignerSlide();}); - const layout=document.getElementById('designer-layout');if(layout)layout.addEventListener(evt,function(){previewDesignerSlide();}); - }); - previewDesignerSlide(); -} -function updateDesignerText(slideIdx){const p=_wallPosts[designerSlideIdx];if(!p||!p.slides)return;const s=p.slides[parseInt(slideIdx)];if(s)document.getElementById('designer-text').value=s.text||'';document.getElementById('designer-bg-url').value=s.image||p.img||'';designerBgDataUrl=null;} -function handleDesignerBgFile(input){ - const file=input.files&&input.files[0];if(!file)return; - const reader=new FileReader(); - reader.onload=function(e){designerBgDataUrl=e.target.result;document.getElementById('designer-bg-url').value='[uploaded]';}; - reader.readAsDataURL(file); -} -function previewDesignerSlide(){ - const slideIdx=parseInt(document.getElementById('designer-slide-select')?.value||'0'); - const p=_wallPosts[designerSlideIdx];if(!p||!p.slides)return; - const s=p.slides[slideIdx];if(!s)return; - const text=document.getElementById('designer-text')?.value||s.text||''; - const bgUrlInput=document.getElementById('designer-bg-url')?.value||''; - const bgUrl=designerBgDataUrl||bgUrlInput||s.image||p.img||''; - const textColor=document.getElementById('designer-text')?.style.color||'#ffffff'; - const ratio=designerGetRatio(); - const layout=designerGetLayout(); - const previewArea=document.getElementById('designer-preview-area');if(!previewArea)return; - previewArea.style.display='block';previewArea.innerHTML='
⏳ Đang tạo xem trưởng...
'; - const canvas=document.createElement('canvas'); - const vw=Math.max(document.documentElement.clientWidth||540, document.body.clientWidth||540); - const maxW=Math.min(540, Math.floor(vw*0.9)); - canvas.width=maxW;canvas.height=Math.round(maxW*ratio.h/ratio.w); - canvas.style.maxWidth='100%';canvas.style.width='100%';canvas.style.height='auto'; - canvas.style.borderRadius='12px';canvas.style.boxShadow='0 8px 24px rgba(0,0,0,.5)'; - canvas.style.display='block';canvas.style.margin='0 auto'; - const ctx=canvas.getContext('2d');const img=new Image();img.crossOrigin='anonymous'; - function drawLayout(){ - if(layout==='vignette'){const g=ctx.createRadialGradient(canvas.width/2,canvas.height/2,0,canvas.width/2,canvas.height/2,Math.max(canvas.width,canvas.height)*0.6);g.addColorStop(0,'rgba(0,0,0,0)');g.addColorStop(1,'rgba(0,0,0,0.7)');ctx.fillStyle=g;ctx.fillRect(0,0,canvas.width,canvas.height);} - else if(layout==='split'){ctx.fillStyle='rgba(0,0,0,0)';ctx.fillRect(0,0,canvas.width,canvas.height/2);ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,canvas.height/2,canvas.width,canvas.height/2);} - else if(layout==='spotlight'){const cx=canvas.width/2,cy=canvas.height/2,r=Math.max(canvas.width,canvas.height)*0.35;ctx.save();ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.globalCompositeOperation='destination-out';ctx.fillStyle='white';ctx.beginPath();ctx.arc(cx,cy,r,0,Math.PI*2);ctx.fill();ctx.globalCompositeOperation='source-over';} - else if(layout==='diagonal'){ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.fillStyle='rgba(0,0,0,0.75)';ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(canvas.width,0);ctx.lineTo(0,canvas.height);ctx.closePath();ctx.fill();} - else {ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,canvas.width,canvas.height);} - } - function drawText(){ - ctx.fillStyle=textColor;ctx.font='bold '+Math.round(canvas.width*28/540)+'px sans-serif'; - ctx.textAlign='center';ctx.textBaseline='middle'; - const maxW=Math.round(canvas.width*0.82); - const words=text.split(' ');let line='';let y=Math.round(canvas.height/2); - const fontSize=Math.round(canvas.width*28/540);const lineHeight=Math.round(fontSize*1.3); - for(let i=0;imaxW&&i>0){ctx.fillText(line.trim(),canvas.width/2,y);y+=lineHeight;line=words[i];}else{line=test;}} - ctx.fillText(line.trim(),canvas.width/2,y); - } - function renderAll(){ - ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,canvas.width,canvas.height); - drawLayout(); - drawText(); - previewArea.innerHTML='';previewArea.appendChild(canvas); - } - img.onload=function(){ - const iw=img.naturalWidth||1,ih=img.naturalHeight||1; - const scale=Math.max(canvas.width/iw,canvas.height/ih); - const dw=iw*scale,dh=ih*scale; - const dx=(canvas.width-dw)/2,dy=(canvas.height-dh)/2; - ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh); - drawLayout();drawText(); - previewArea.innerHTML='';previewArea.appendChild(canvas); - }; - img.onerror=function(){renderAll();}; - if(bgUrl){img.src=bgUrl.startsWith('/api/')?bgUrl:bgUrl.startsWith('data:')?bgUrl:'/api/proxy/img?url='+encodeURIComponent(bgUrl);}else{renderAll();} -} -async function saveDesignerSlide(title,postId,idx){ - const slideIdx=parseInt(document.getElementById('designer-slide-select')?.value||'0'); - const p=_wallPosts[idx];if(!p||!p.slides)return; - const s=p.slides[slideIdx];if(!s)return; - const text=document.getElementById('designer-text')?.value||s.text||''; - const bgUrlInput=document.getElementById('designer-bg-url')?.value||''; - const bgUrl=designerBgDataUrl||bgUrlInput||s.image||p.img||''; - const textColor=document.getElementById('designer-text')?.style.color||'#ffffff'; - const ratio=designerGetRatio(); - const layout=designerGetLayout(); - const statusEl=document.getElementById('designer-status');if(statusEl)statusEl.textContent='⏳ Đang tạo ảnh...'; - const FINAL_W=ratio.w>=ratio.h?1800:1350; - const FINAL_H=Math.round(FINAL_W*ratio.h/ratio.w); - const canvas=document.createElement('canvas');canvas.width=FINAL_W;canvas.height=FINAL_H; - const ctx=canvas.getContext('2d'); - const img=new Image();img.crossOrigin='anonymous'; - function drawLayoutF(){ - if(layout==='vignette'){const g=ctx.createRadialGradient(FINAL_W/2,FINAL_H/2,0,FINAL_W/2,FINAL_H/2,Math.max(FINAL_W,FINAL_H)*0.6);g.addColorStop(0,'rgba(0,0,0,0)');g.addColorStop(1,'rgba(0,0,0,0.7)');ctx.fillStyle=g;ctx.fillRect(0,0,FINAL_W,FINAL_H);} - else if(layout==='split'){ctx.fillStyle='rgba(0,0,0,0)';ctx.fillRect(0,0,FINAL_W,FINAL_H/2);ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,FINAL_H/2,FINAL_W,FINAL_H/2);} - else if(layout==='spotlight'){const cx=FINAL_W/2,cy=FINAL_H/2,r=Math.max(FINAL_W,FINAL_H)*0.35;ctx.save();ctx.fillStyle='rgba(0,0,0,0.7)';ctx.fillRect(0,0,FINAL_W,FINAL_H);ctx.globalCompositeOperation='destination-out';ctx.fillStyle='white';ctx.beginPath();ctx.arc(cx,cy,r,0,Math.PI*2);ctx.fill();ctx.globalCompositeOperation='source-over';} - else if(layout==='diagonal'){ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,FINAL_W,FINAL_H);ctx.fillStyle='rgba(0,0,0,0.75)';ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(FINAL_W,0);ctx.lineTo(0,FINAL_H);ctx.closePath();ctx.fill();} - else {ctx.fillStyle='rgba(0,0,0,0.55)';ctx.fillRect(0,0,FINAL_W,FINAL_H);} - } - function drawTextF(){ - ctx.fillStyle=textColor;ctx.font='bold '+Math.round(FINAL_W*48/1080)+'px sans-serif'; - ctx.textAlign='center';ctx.textBaseline='middle'; - const maxW=Math.round(FINAL_W*0.82);const words=text.split(' ');let line='';let y=Math.round(FINAL_H/2); - const fontSize=Math.round(FINAL_W*48/1080);const lineHeight=Math.round(fontSize*1.3); - for(let i=0;imaxW&&i>0){ctx.fillText(line.trim(),FINAL_W/2,y);y+=lineHeight;line=words[i];}else{line=test;}}ctx.fillText(line.trim(),FINAL_W/2,y); - } - function render(){ - ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,FINAL_W,FINAL_H); - drawLayoutF();drawTextF(); - canvas.toBlob(async function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - try{const r=await fetch('/api/wall/img',{method:'POST',body:formData});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi upload'); - s.image=j.url; - const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}); - const wj=await wr.json();if(wr.ok&&wj.post){prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');}else{toast('✅ Đã lưu ảnh slide!');} - document.getElementById('slide-designer-overlay').remove(); - }catch(e){if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);} - },'image/png'); - } - img.onload=function(){ - const iw=img.naturalWidth||1,ih=img.naturalHeight||1; - const scale=Math.max(FINAL_W/iw,FINAL_H/ih); - const dw=iw*scale,dh=ih*scale; - const dx=(FINAL_W-dw)/2,dy=(FINAL_H-dh)/2; - ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh); - drawLayoutF();drawTextF(); - canvas.toBlob(async function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - try{const r=await fetch('/api/wall/img',{method:'POST',body:formData});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi upload'); - s.image=j.url; - const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}); - const wj=await wr.json();if(wr.ok&&wj.post){prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');}else{toast('✅ Đã lưu ảnh slide!');} - document.getElementById('slide-designer-overlay').remove(); - }catch(e){if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);} - },'image/png'); - }; - img.onerror=function(){if(statusEl)statusEl.textContent='⚠️ Không tải được ảnh nền, dùng nền mặc định';ctx.fillStyle='#1a1a1a';ctx.fillRect(0,0,FINAL_W,FINAL_H);drawLayoutF();drawTextF();canvas.toBlob(function(blob){ - const formData=new FormData();formData.append('file',blob,'slide_'+slideIdx+'.png');formData.append('post_id',postId||p.id||''); - fetch('/api/wall/img',{method:'POST',body:formData}).then(r=>r.json()).then(j=>{ - if(j.ok){s.image=j.url;const post={id:p.id,title:title||p.title,text:p.text,img:j.url,url:p.url,slides:p.slides,images:p.images,voice:p.voice,emotion:p.emotion,language:p.language,ts:p.ts,kind:p.kind||'slide_summary'}; - fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}).then(r=>r.json()).then(wj=>{if(wj.post)prependWallPost(wj.post);toast('✅ Đã lưu ảnh đăng lên Tường AI!');document.getElementById('slide-designer-overlay').remove();});} - }).catch(e=>{if(statusEl)statusEl.textContent='❌ '+e.message;toast('❌ '+e.message);}); - },'image/png');}; - if(bgUrl){img.src=bgUrl.startsWith('/api/')?bgUrl:bgUrl.startsWith('data:')?bgUrl:'/api/proxy/img?url='+encodeURIComponent(bgUrl);}else{render();} -} - -function readNewsTab(tab){loadNewsTab();} -function loadNewsTab(){const el=document.getElementById('view-cat');if(!el)return;el.innerHTML='
Đang tải tin tức...
';fetch('/api/homepage').then(r=>r.json()).then(articles=>{if(!articles||!articles.length){el.innerHTML='
Không có tin
';return}let h='
';articles.forEach(a=>{const src=a.source||'vne';const badge=a.group||a.source||'';h+=`
${a.img?``:''}
${esc(badge)}
${esc(a.title)}
`;});h+='
';el.innerHTML=h;}).catch(()=>{el.innerHTML='
Lỗi tải
';});} - -function readArticle(url,title,img,presetTitle,presetText){showView('view-article');const el=document.getElementById('view-article');el.innerHTML='
Đang tải...
';if(presetTitle){el.innerHTML=`

${esc(presetTitle)}

${presetText?`
${esc(presetText)}
`:''}
`;return;}if(!url)return;fetch('/api/article?url='+encodeURIComponent(url)).then(r=>r.json()).then(d=>{let h=`
`;if(d.title)h+=`

${esc(d.title)}

`;if(d.summary)h+=`
${esc(d.summary)}
`;if(d.body)d.body.forEach(b=>{if(b.type==='p')h+=`

${esc(b.text)}

`;else if(b.type==='heading')h+=`

${esc(b.text)}

`;else if(b.type==='img'&&b.src)h+=``;});h+=`
`;el.innerHTML=h;}).catch(()=>{el.innerHTML=`

Không thể tải bài viết

`;});} -async function rewriteSlide(url){if(!url)return;const btn=document.querySelector('.article-actions .primary')||event?.target;if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo slides...';}toast('⏳ Đang tạo slide rewrite...');try{const r=await fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');toast('✅ Đã tạo slide! Đang tạo Short AI...');if(btn)btn.textContent='✅ Đang tạo Short AI...';if(j.post){j.post.slides=j.slides||[];prependWallPost(j.post);}// Show slides immediately if available -if(j.slides && j.slides.length){showView('view-article');const el=document.getElementById('view-article');let h=`
`;j.slides.forEach(s=>{h+=`
Slide ${s.index}/${j.slides.length}
${s.image?``:''}

${esc(s.text)}

`;});h+=`
⏳ Đang tạo video Short AI...
`;el.innerHTML=h;} -const postId=j.post&&j.post.id;if(postId){setTimeout(async()=>{const sr=await fetch('/api/ai/short/'+encodeURIComponent(postId),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice:'vi-VN-HoaiMyNeural',emotion:'neutral',speed:1.2})});const sj=await sr.json();if(sr.ok&&sj.video&&typeof _wallPosts!=='undefined'){const p=_wallPosts.find(x=>String(x.id)===String(postId));if(p){p.video=sj.video;const itemId='wall-item-'+postId;const el2=document.getElementById(itemId);if(el2){const idx=_wallPosts.indexOf(p);el2.insertAdjacentHTML('afterend',makeWallItem(p,idx));el2.remove();}}toast('✅ Short AI đã sẵn sàng!');const statusEl=document.getElementById('short-ai-status');if(statusEl)statusEl.innerHTML='✅ Short AI đẵn sàng! ';}},500);}if(btn)btn.textContent='✅ Hoàn tất';}catch(e){toast('❌ '+e.message);if(btn){btn.disabled=false;btn.textContent='🤖 Slide Rewrite AI';}}} - -function downloadVideo(url, title){ - var a = document.createElement('a'); - a.href = url; - a.download = (title||'video').toString().replace(/[^a-zA-Z0-9_\-\p{L}]/gu,'_').substring(0,60)+'.mp4'; - a.target = '_blank'; - a.rel = 'noopener'; - a.style.display = 'none'; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - toast('📥 Đang tải video xuống...'); -} - -// ===== PERSONAL OPINION POST: Viết bài dựa trên quan điểm cá nhân + tin HOT ===== -async function openPersonalPostPreview() { - const opinion = document.getElementById('opinion-input')?.value.trim(); - if (!opinion || opinion.length < 10) { - alert('Vui lòng nhập quan điểm cá nhân (ít nhất 10 ký tự)'); - return; - } - - // Get selected hot topics from UI (if any) - const selectedTopics = []; - if (window._htTopic) { - selectedTopics.push(window._htTopic); - } - - // Get selected sources from hashtag view - const selectedSources = []; - document.querySelectorAll('.hashtag-src-item.selected').forEach(el => { - const idx = parseInt(el.dataset.idx || '0'); - // Would need source tracking - }); - - const btn = event?.target; - const origText = btn ? btn.textContent : ''; - if (btn) { btn.disabled = true; btn.textContent = '⏳ Đang tạo preview...'; } - - try { - const resp = await fetch('/api/personal_post/preview', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - opinion: opinion, - selected_topics: selectedTopics, - selected_sources: selectedSources - }) - }); - const data = await resp.json(); - if (!resp.ok || data.error) throw new Error(data.error || 'Lỗi tạo preview'); - - showPersonalPostModal(data.preview, opinion, selectedTopics, selectedSources); - } catch (e) { - toast('❌ ' + e.message); - } finally { - if (btn) { btn.disabled = false; btn.textContent = origText; } - } -} - -function showPersonalPostModal(preview, originalOpinion, selectedTopics, selectedSources) { - // Remove existing modal - const existing = document.getElementById('personal-post-modal'); - if (existing) existing.remove(); - - const modal = document.createElement('div'); - modal.id = 'personal-post-modal'; - modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.9);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto'; - - // Each slide renders EXACTLY like the designer's final PNG (same ratio, - // same bg draw, same text draw) — preview = pixel-identical to wall post image. - const slidesHtml = (preview.slides || []).map((s, i) => { - const ratio = {w:3, h:4}; // preview always 3:4 (same as designer final) - const slideStyle = 'width:100%;max-width:280px;margin:0 auto;display:block;border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.5)'; - return '
' - + '
Slide ' + (i+1) + '
' - + '' - + '' - + '
'; - }).join(''); - - // Background image source: uploaded data-URL (set later) or slide.image / first source image. - // We keep a small state object so text edits re-render live. - window._pvState = { slides: (preview.slides||[]).map(function(s,i){ - var bg = s.image || (preview.images && preview.images[0]) || ''; - return { text: s.text||'', bg: bg }; - }), ratio: 3/4, layout: 'solid', filter: 'none', glow: 'white', pos: 'bottom', color: '#ffffff' }; - - const sourcesHtml = (preview.sources || []).map((s, i) => { - const imgSrc = (preview.images && preview.images[i+1]) ? preview.images[i+1] : ''; - return '
' - + '
' - + (imgSrc ? '' : '') - + '
' - + '
' + (s.title || '') + '
' - + '' - + '
'; - }).join(''); - - modal.innerHTML = '
' - + '
' - + '

📝 Xem trước bài quan điểm cá nhân

' - + '' - + '
' - + '
' - + '' - + '' - + '
' - + '
' - + '' - + '' - + '
' - + '
' - + '' - + '
' - + '' - + '' - + '
' - + '
' + slidesHtml + '
' - + '
' - + '
' - + '' - + '
' - + (sourcesHtml || '
Không có nguồn tin
') - + '
' - + '
' - + '' - + '' - + '
'; - - document.body.appendChild(modal); - - // draw every slide preview canvas - previewRedrawAllSlides(); - - // text edits re-render live - modal.querySelectorAll('.preview-slide-text').forEach(ta => { - ta.addEventListener('input', function(){ - const idx = parseInt(this.dataset.idx || '0', 10); - if(window._pvState && window._pvState.slides[idx]) window._pvState.slides[idx].text = this.value; - previewDrawSlide(idx); - }); +async function toggleComments(videoId,idx){const panel=document.getElementById('cmt-inline-'+idx);if(!panel)return;if(panel.style.display!=='none'){panel.style.display='none';return;}panel.style.display='block';panel.innerHTML='
Đang tải...
';const cmts=await getComments(videoId);renderInlineComments(panel,videoId,idx,cmts);} +function renderInlineComments(panel,videoId,idx,cmts){let h='
💬 Bình luận
';if(cmts.length){cmts.slice(-30).forEach(c=>{h+=`
${c.time||''}${esc(c.text)}
`;});}else{h+='
Chưa có bình luận
';}h+=`
`;panel.innerHTML=h;const list=panel.querySelector('.inline-cmt-list');if(list)list.scrollTop=list.scrollHeight;} +async function submitInlineCmt(videoId,idx){const inp=document.getElementById('cmt-input-'+idx);if(!inp)return;const text=inp.value.trim();if(!text)return;inp.value='';inp.disabled=true;const cmts=await postComment(videoId,text);inp.disabled=false;const panel=document.getElementById('cmt-inline-'+idx);if(panel)renderInlineComments(panel,videoId,idx,cmts);const cc=document.getElementById('cc-'+idx);if(cc)cc.textContent=fmtNum(cmts.length);} +function initTikTokFeed(){const feed=document.getElementById('tiktok-feed');if(!feed)return;const slides=feed.querySelectorAll('.tiktok-slide');let cur=-1;function act(i){if(i===cur)return;slides.forEach((sl,idx)=>{const v=sl.querySelector('video');const fr=sl.querySelector('iframe');if(idx===i){if(v&&v.dataset.hls&&!v._hls&&typeof Hls!=='undefined'&&Hls.isSupported()){const hls=new Hls();hls.loadSource(v.dataset.hls);hls.attachMedia(v);hls.on(Hls.Events.MANIFEST_PARSED,()=>v.play().catch(()=>{}));v._hls=hls}else if(v)v.play().catch(()=>{});if(fr&&!fr.src&&fr.dataset.ytSrc)fr.src=fr.dataset.ytSrc;const vid=sl.dataset.vid;if(vid&&!sl._viewed){sl._viewed=true;doInteract(vid,'view').then(j=>{if(j){const vc=document.getElementById('vc-'+idx);if(vc)vc.textContent=fmtNum(j.views);}});}}else{if(v){v.pause();if(v._hls){v._hls.destroy();v._hls=null}}if(fr&&fr.src)fr.src=''}});cur=i}let sT;feed.addEventListener('scroll',()=>{clearTimeout(sT);sT=setTimeout(()=>{const rect=feed.getBoundingClientRect(),ctr=rect.top+rect.height/2;let best=-1,bestD=1e9;slides.forEach((sl,i)=>{const d=Math.abs(sl.getBoundingClientRect().top+sl.getBoundingClientRect().height/2-ctr);if(d=0)act(best)},150)});setTimeout(()=>act(0),400);slides.forEach(sl=>{const v=sl.querySelector('video');if(v)v.addEventListener('click',e=>{e.preventDefault();v.paused?v.play().catch(()=>{}):v.pause()})});const ids=[...slides].map(sl=>sl.dataset.vid||'');loadCounters(ids)} +async function openHighlightFeed(league,idx,forceUrl){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';let articles=(_hlLeagueData||{})[league]||[];if(!articles.length){try{articles=await fetch('/api/highlights/'+league).then(r=>r.json())}catch(e){articles=[]}}if(!articles.length){el.innerHTML='
Không có video
';return}const vids=[];const results=await Promise.all(articles.map(async(a,i)=>{try{const r=await fetch('/api/video_url?url='+encodeURIComponent(a.link)+'&img='+encodeURIComponent(a.img||''));const v=await r.json();if(v&&v.src){return{_idx:i,title:a.title||v.title||'',link:a.link||'',img:a.img||v.poster||'',src:v.src,type:v.type||'',poster:v.poster||a.img||''}}return null}catch(e){}return null}));results.forEach(r=>{if(r)vids.push(r)});vids.sort((a,b)=>a._idx-b._idx);if(!vids.length){el.innerHTML='
Không tìm thấy video
';return}let ti=vids.findIndex(v=>v._idx===idx);if(ti<0)ti=0;const ordered=ti>0?[...vids.slice(ti),...vids.slice(0,ti)]:vids;let h=`
`;ordered.forEach((v,i)=>{const isYT=v.type==='youtube',isHLS=!isYT&&v.src?.includes('.m3u8'),poster=v.poster?` poster="${esc(v.poster)}"`:'';const vtag=isYT?``:isHLS?``:``;const videoId='hl-'+league+'-'+v._idx;h+=buildTikTokSlide({vtag,title:v.title,badge:'HL',badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:v.link||'',extraBtn:``});});h+='
';el.innerHTML=h;initTikTokFeed();} +async function openYTShortsFeed(startIdx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';const arts=_shortsData.length?_shortsData:await fetch('/api/shorts').then(r=>r.json()).catch(()=>[]);if(!arts.length){el.innerHTML='
Không có shorts
';return}const ordered=startIdx>0?[...arts.slice(startIdx),...arts.slice(0,startIdx)]:arts;let h=`
`;ordered.forEach((v,i)=>{const id=v.id||'';const src=`https://www.youtube.com/embed/${id}?autoplay=1&rel=0&playsinline=1`;const vtag=``;const badge=v.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí';const videoId='yt-'+id;h+=buildTikTokSlide({vtag,title:v.title,badge,badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:'https://youtube.com/watch?v='+id});});h+='
';el.innerHTML=h;initTikTokFeed();} +async function openShortAIFeed(startIdx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';const wall=(await fetch('/api/wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];const vids=wall.filter(p=>p.video);if(!vids.length){el.innerHTML='
Chưa có Short AI
';return}const ordered=startIdx>0?[...vids.slice(startIdx),...vids.slice(0,startIdx)]:vids;let h=`
`;ordered.forEach((p,i)=>{const vtag=``;const videoId='ai-'+(p.id||i);h+=buildTikTokSlide({vtag,title:p.title,badge:'AI',badgeClass:'badge-ai',videoId,idx:i,total:ordered.length,shareUrl:SPACE});});h+='
';el.innerHTML=h;initTikTokFeed();} +async function readArticle(url){showView('view-article');const el=document.getElementById('view-article');el.innerHTML='
Đang tải...
';try{const r=await fetch('/api/article?url='+encodeURIComponent(url));const data=await r.json();if(data&&!data.error&&data.body&&data.body.length){_currentArticle={url,data};let h=`

${esc(data.title)}

`;if(data.summary)h+=`
${esc(data.summary)}
`;const seen={};data.body.forEach(b=>{if(b.type==='p')h+=`

${b.text}

`;else if(b.type==='img'&&b.src&&!seen[b.src]){seen[b.src]=1;h+=``}else if(b.type==='heading')h+=`

${esc(b.text)}

`});h+=`

🤖 Hỏi AI

`;el.innerHTML=h;window.scrollTo(0,0);return;}}catch(e){}el.innerHTML=`

Không đọc được.

Mở gốc →
`;} +async function rewriteArticle(){const url=_currentArticle?.url;if(!url)return;toast('⏳ Đang tạo bài đăng Tường AI...');try{const r=await fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url:url,context:document.querySelector('.article-view')?document.querySelector('.article-view').innerText.slice(0,14000):''})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error);toast('✅ Đã đăng Tường AI!');if(j.post)prependWallPost(j.post);if(j.post&&typeof goToWallPost==='function')goToWallPost(j.post.id);if(j.slides&&j.slides.length){setTimeout(function(){showSlidePreview(j.slides,j.post?j.post.title:'');},500);}if(j.post&&!j.post.video){setTimeout(function(){showVoiceEmotionSelector(j.post.id,j.post.title,j.post.text);},1000);}}catch(e){toast('❌ '+e.message);}} +async function rewriteUrl(){const url=document.getElementById('url-input')?.value.trim();if(!url)return alert('Dán URL');toast('⏳ Đang rewrite...');try{const r=await fetch('/api/url_wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error);toast('✅ Đã đăng!');document.getElementById('url-input').value='';if(j.post)prependWallPost(j.post);}catch(e){toast('❌ '+e.message)}} +async function askAI(){const q=document.getElementById('ask-q')?.value.trim();if(!q)return alert('Nhập câu hỏi');const a=document.getElementById('ask-a');a.textContent='Đang hỏi...';try{const r=await fetch('/api/article/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url:_currentArticle?.url||'',question:q,context:document.querySelector('.article-view')?.innerText?.slice(0,12000)||''})});const j=await r.json();a.textContent=j.answer||'Không trả lời được';}catch(e){a.textContent='Lỗi: '+e.message}} +async function readWallPost(i){ + var p=_wallPosts[i]; + if(!p)return; + showView('view-article'); + var images = p.images || []; + var imgGallery = ''; + if(images.length > 0){ + imgGallery = '
'; + images.forEach(function(imgUrl, imgIdx) { + if(imgIdx === 0){ + imgGallery += ''; + } else { + if(imgIdx === 1) imgGallery += ''; + imgGallery += '
'; + } + var hasVideo = p.video && p.video.length > 0; + var voiceEmotionHtml = ''; + // Always show voice selector so user can change voice and regenerate video + voiceEmotionHtml = buildVoiceEmotionSelector(p); + document.getElementById('view-article').innerHTML = + '' + + '
AI

'+esc(p.title)+'

' + + imgGallery + + '

'+esc(p.text)+'

' + + (hasVideo ? '' : '') + + '
' + + (hasVideo ? '' : '') + + '
' + + voiceEmotionHtml + + '
'; + window.scrollTo(0,0); + // Always bind voice selector events + } +async function loadNewsTab(){const el=document.getElementById('view-cat');el.innerHTML='
Đang tải...
';try{const r=await fetch('/api/homepage');const news=await r.json();if(!news.length){el.innerHTML='
Không có tin
';return}const groups={};news.forEach(a=>{if(!groups[a.group])groups[a.group]=[];groups[a.group].push(a)});let h='';for(const[g,arts]of Object.entries(groups)){h+=`
${g}
`;arts.slice(0,6).forEach(a=>{h+=`
${a.img?``:''}
${esc(a.source||'VnE')}
${esc(a.title)}
`});h+='
'}el.innerHTML=h}catch(e){el.innerHTML='
Lỗi
'}} +async function loadCat(id){const el=document.getElementById('view-cat');el.innerHTML='
Đang tải...
';const arts=await fetch('/api/category/'+id).then(r=>r.json()).catch(()=>[]);if(!arts.length){el.innerHTML='
Không có tin
';return}let h='
';arts.forEach(a=>{h+=`
${a.img?``:''}
${esc(a.source||'')}
${esc(a.title)}
`});h+='
';el.innerHTML=h} +fetch('/api/storage_status').then(r=>r.json()).then(j=>{if(!j.persistent){const home=document.getElementById('view-home');if(home){const w=document.createElement('div');w.className='storage-warn';w.innerHTML='⚠️ Persistent Storage chưa bật.';home.prepend(w)}}}).catch(()=>{}); -/* Live-edit slide preview canvas (exact same rendering style as designer output) */ -function previewDrawSlide(idx){ - const canvas = document.querySelector('.preview-slide-canvas[data-idx="'+idx+'"]'); - if(!canvas || !window._pvState) return; - const st = window._pvState.slides[idx]; - if(!st) return; - const W = 600, H = Math.round(W * window._pvState.ratio); // 3:4 -> 800 - canvas.width = W; canvas.height = H; - const ctx = canvas.getContext('2d'); - const opts = { text: st.text, pos: window._pvState.pos, glow: window._pvState.glow, - color: window._pvState.color, layout: window._pvState.layout, - filter: window._pvState.filter, bgUrl: st.bg }; - function draw(img){ - // base dark - ctx.fillStyle='#141414'; ctx.fillRect(0,0,W,H); - if(img){ - ctx.save(); - let f=''; - if(opts.filter==='grayscale') f='grayscale(1)'; - else if(opts.filter==='sepia') f='sepia(0.85)'; - else if(opts.filter==='saturate') f='saturate(2.4)'; - else if(opts.filter==='warm') f='sepia(0.45) saturate(1.5) hue-rotate(-15deg)'; - else if(opts.filter==='cool') f='saturate(1.2) hue-rotate(15deg) brightness(1.05)'; - else if(opts.filter==='invert') f='invert(1)'; - else if(opts.filter==='noir') f='grayscale(1) contrast(1.6) brightness(0.9)'; - const iw=img.naturalWidth||1, ih=img.naturalHeight||1; - const scale=Math.max(W/iw, H/ih); - const dw=iw*scale, dh=ih*scale; - ctx.drawImage(img,0,0,iw,ih,(W-dw)/2,(H-dh)/2,dw,dh); - ctx.filter='none'; - ctx.restore(); - } - // solid overlay like designer - ctx.fillStyle='rgba(0,0,0,0.6)'; ctx.fillRect(0,0,W,H); - drawPreviewText(ctx,W,H,opts); - } - const bgSrc = (typeof _proxyImg==='function') ? _proxyImg(st.bg||'') : (st.bg || ''); - if(bgSrc){ - const im = new Image(); im.crossOrigin='anonymous'; - im.onload = function(){ draw(im); }; - im.onerror = function(){ draw(null); }; - im.src = bgSrc; - } else draw(null); -} -function drawPreviewText(ctx,W,H,opts){ - const text = opts.text || ''; - if(!text.trim()) return; - const fs = Math.min(52, Math.round(W*0.09)); - ctx.font = 'bold '+fs+'px "Segoe UI","Arial","Noto Sans",sans-serif'; - ctx.textAlign='center'; - const lines=[]; let line=''; - const maxW=Math.round(W*0.82); - text.split(' ').forEach(w=>{ - const test = line? line+' '+w : w; - if(ctx.measureText(test).width>maxW && line){ lines.push(line.trim()); line=w; } else { line=test; } - }); - if(line) lines.push(line.trim()); - const lh=Math.round(fs*1.25); - const blockH=lines.length*lh; - let y; - if(opts.pos==='top') y=Math.round(H*0.14)+lh/2; - else if(opts.pos==='bottom') y=Math.round(H*0.88)-blockH+lh/2; - else y=Math.round(H/2)-blockH/2+lh/2; - if(opts.glow==='white'){ ctx.shadowColor='rgba(255,255,255,0.95)'; ctx.shadowBlur=Math.max(8,fs*0.5); } - else if(opts.glow==='color'){ ctx.shadowColor=opts.color; ctx.shadowBlur=Math.max(10,fs*0.6); } - else if(opts.glow==='neon'){ ctx.shadowColor='#00ffff'; ctx.shadowBlur=Math.max(16,fs*0.9); } - ctx.fillStyle=opts.color; - lines.forEach((l,li)=>{ ctx.fillText(l, W/2, y+li*lh); }); - ctx.shadowBlur=0; -} -function previewRedrawAllSlides(){ - if(!window._pvState) return; - window._pvState.slides.forEach(function(_, i){ previewDrawSlide(i); }); -} -function openPreviewDesigner(){ - // opens the real slide designer on the FIRST preview slide as a background. - // The designer modal already renders canvas + uploads PNGs; we reuse it by - // temporarily creating a wall-post-like object from the preview slides. - if(!window._personalPostPreview || !window._pvState) return; - const slides = window._pvState.slides.map(function(s,i){ - return { text: s.text, image: s.bg, index: i+1 }; - }); - const fakePost = { - id: 'preview-fake', title: document.getElementById('preview-title')?.value || 'Bài quan điểm', - slides: slides, kind: 'personal_opinion', img: slides[0]?.image||'', url: '', video: '' - }; - if(typeof openSlideDesigner === 'function'){ - // designer expects index into _wallPosts; temporarily append so designer works - const existed = _wallPosts && _wallPosts.some(p => p.id === 'preview-fake'); - if(!existed && Array.isArray(_wallPosts)) _wallPosts.unshift(fakePost); - const idx = _wallPosts.findIndex(p => p.id === 'preview-fake'); - openSlideDesigner(idx >= 0 ? idx : 0); - // the fake post is only a designer context; the designer's own save posts - // the designed slides directly to the wall. Remove the fake entry on close. +(function(){ + try{ + var hash = window.location.hash; + if(hash && hash.length > 1){ + var articleUrl = decodeURIComponent(hash.substring(1)); + if(articleUrl.startsWith('http')){ + history.replaceState(null, '', window.location.pathname); setTimeout(function(){ - const ov = document.getElementById('slide-designer-overlay'); - if(!ov && Array.isArray(_wallPosts)){ - _wallPosts = _wallPosts.filter(p => p.id !== 'preview-fake'); - } - }, 30000); - } else { - toast('Không có công cụ thiết kế!'); + if(typeof readArticle==='function') readArticle(articleUrl); + }, 1500); + } } -} - -function toggleSourceSelection(el, idx) { - const checkbox = el.querySelector('.source-checkbox'); - checkbox.checked = !checkbox.checked; - el.style.border = checkbox.checked ? '1px solid #2d8659' : '1px solid transparent'; - el.style.background = checkbox.checked ? '#1a2a1f' : '#202020'; -} + }catch(e){} +})(); -async function publishPersonalPostFromModal() { - const title = document.getElementById('preview-title')?.value.trim(); - if (!title) { - alert('Vui lòng nhập tiêu đề'); - return; - } - - // Collect edited slides (text + designed/bg image from _pvState) - const slides = []; - if (window._pvState && window._pvState.slides) { - window._pvState.slides.forEach((s, i) => { - const text = (s.text || '').trim(); - if (text) slides.push({ text, image: s.bg || '', index: slides.length + 1 }); - }); - } else { - document.querySelectorAll('.preview-slide-text').forEach(ta => { - const text = ta.value.trim(); - if (text) slides.push({ text, image: '', index: slides.length + 1 }); - }); - } - - // Collect selected sources - const sources = []; - document.querySelectorAll('[data-source-idx]').forEach((el, i) => { - const checkbox = el.querySelector('.source-checkbox'); - if (checkbox.checked && window._personalPostPreview?.sources?.[i]) { - sources.push(window._personalPostPreview.sources[i]); - } - }); - - const btn = event.target; - const origText = btn.textContent; - btn.disabled = true; - btn.textContent = '⏳ Đang đăng...'; - - try { - const resp = await fetch('/api/personal_post', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - opinion: window._personalPostOpinion, - selected_topics: [], - selected_sources: sources, - custom_title: title, - custom_slides: slides - }) - }); - const data = await resp.json(); - if (!resp.ok || data.error) throw new Error(data.error || 'Lỗi đăng bài'); - - toast('✅ Đã đăng bài quan điểm lên Tường AI!'); - - // Prepend to wall - if (data.post && typeof prependWallPost === 'function') { - prependWallPost(data.post); - } - - // Close modal - document.getElementById('personal-post-modal')?.remove(); - - // Clear opinion input - document.getElementById('opinion-input').value = ''; - } catch (e) { - toast('❌ ' + e.message); - } finally { - btn.disabled = false; - btn.textContent = origText; +(function(){ + try{ + const pa=localStorage.getItem('pending_article'); + const pv=localStorage.getItem('pending_video'); + if(pa){ + localStorage.removeItem('pending_article'); + setTimeout(()=>{ + if(typeof readArticle==='function') readArticle(pa); + },1500); + } + if(pv){ + localStorage.removeItem('pending_video'); + try{ + const v=JSON.parse(pv); + if(v&&v.url) setTimeout(()=>{window.open(v.url,'_blank')},1500); + }catch(e){} } -} + }catch(e){} +})(); +if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', function() { + if (typeof loadHome === 'function') loadHome(); + }); +} else { + if (typeof loadHome === 'function') loadHome(); +} \ No newline at end of file diff --git a/static/designer_v2.js b/static/designer_v2.js deleted file mode 100644 index 31ff59f42126dbbc350a4d7c94575b7083bdd2d6..0000000000000000000000000000000000000000 --- a/static/designer_v2.js +++ /dev/null @@ -1,903 +0,0 @@ -/* ========================================================================= - * designer_v2.js — Slide Designer nâng cấp cho VNEWS - * - Nhiều hiệu ứng độc đáo (gradient, blur, neon, top-banner, lower-third, - * card, corner-frame, stars, vignette, split, spotlight, diagonal, solid) - * - Bộ lọc màu (grayscale, sepia, saturate, warm, cool, invert) - * - Chữ phát sáng (neon/glow) - * - Vị trí chữ (trên/giữa/dưới) - * - Chọn 1 / nhiều / TẤT CẢ slide trong modal sửa ảnh - * - Đăng lên Tường AI là bài dạng slide gồm CÁC SLIDE ĐÃ CHỌN - * - * 2026-08-12 FIX (2 lỗi báo cáo): - * - Bug 1: upload ảnh preview + nút "Áp dụng ảnh". _dsHandleBgFile được gắn - * trực tiếp làm listener 'change' nên nhận Event object, `input.files` - * undefined -> upload im lặng không làm gì. Giờ đọc evt.target.files. - * Nút "Áp dụng ảnh này cho TẤT CẢ slide đã chọn" luôn hiển thị. - * - Bug 2: chọn 1 ảnh rewrite áp dụng cho nhiều slide. Danh sách ảnh dùng - * data-index + delegated click (hết fragile inline onclick với URL thô). - * - * 2026-08-13 FIX (lỗi báo cáo tiếp): - * - Bug 3: "dùng 1 ảnh cho nhiều slide" vẫn chỉ áp dụng cho slide đầu. - * Giờ có _dsAppliedImg (ảnh đã áp dụng ở cấp thiết kế): khi chọn ảnh bất kỳ - * (rewrite / upload / URL) sẽ áp dụng cho TẤT CẢ slide đã chọn NGAY LẬP TỨC; - * khi đổi lựa chọn slide (chọn thêm / bỏ chọn / chọn tất cả) ảnh đó vẫn được - * áp dụng tự động cho các slide mới được chọn; khi lưu, mọi slide được chọn - * đều dùng ảnh đó. - * - Bug 4: ảnh preview hiển thị đúng tỉ lệ nhưng sau khi tạo ảnh xong hiển thị - * sai tỉ lệ + ảnh nền không định vị chính xác như preview. Preview và khi - * lưu giờ render Ở CÙNG một hàm `_dsRenderSlide(canvas, opts, cb)` (cùng - * resolution, cùng cover-fit, cùng filter, cùng text) nên file tạo ra khớp - * TUYỆT ĐỐI với preview. Ảnh trên Tường/slide viewer giữ đúng tỉ lệ khung - * (ko cắt xén bằng object-fit:cover nữa). - * - Thêm MÀU NỀN + nhiều ẢNH NỀN MẪU khi chọn "Nền đều (phủ màu tối)" — - * dải màu nền (solid color swatches) và bộ ảnh nền mẫu (gradient mờ) để - * người dùng tạo ảnh nền trơn thay vì chỉ phủ màu tối. - * ========================================================================= */ - -/* ---------------- state ---------------- */ -let _dsState = { - postIdx: -1, // index into _wallPosts - selected: [], // array of selected slide indices (into p.slides) -}; - -/* per-slide image override map: {si: imageUrl} set by the rewrite image list */ -let _dsImgMap = {}; - -/* srcs backing the rewrite image list (Bug 2 fix: index-based, no inline onclick) */ -let _dsRewriteImgSrcs = []; - -/* designer-level "applied image": the image the user picked (rewrite / upload / - URL). Applied to ALL selected slides, including slides selected LATER. - Bug 3 fix: keeps "1 ảnh cho nhiều slide" working when selection changes. */ -let _dsAppliedImg = ''; - -/* solid-color background for the 'solid' layout (map because _dsOptions reads it) */ -let _dsBgColor = ''; -/* sample background image (proxied URL) for the 'solid' layout */ -let _dsBgSample = ''; - -/* ---------------- ratio / layout helpers ---------------- */ -function designerGetRatioV2(){ - const v = document.getElementById('ds-ratio')?.value || '3:4'; - const m = v.split(':'); - return m.length === 2 ? {w: parseInt(m[0]), h: parseInt(m[1])} : {w:3,h:4}; -} -function designerGetLayoutV2(){ return document.getElementById('ds-layout')?.value || 'solid'; } -function designerGetFilterV2(){ return document.getElementById('ds-filter')?.value || 'none'; } -function designerGetGlowV2(){ return document.getElementById('ds-glow')?.value || 'none'; } -function designerGetPosV2(){ return document.getElementById('ds-pos')?.value || 'middle'; } - -/* ---------------- open modal (override) ---------------- */ -function openSlideDesigner(idx){ - const p = _wallPosts[idx]; if(!p || !p.slides || !p.slides.length) return; - _dsState.postIdx = idx; - // default: chỉ slide đầu tiên (slide 1 = ảnh đại diện bài đăng tường). - // Người dùng có thể chọn thêm bằng checkbox hoặc "Chọn tất cả". - _dsState.selected = p.slides.length ? [0] : []; - _dsBgDataUrl = null; // reset uploaded bg between opens - _dsTextColor = '#ffffff'; - _dsImgMode = 'rewrite'; // default: use rewrite image - _dsImgMap = {}; // reset per-slide image overrides - _dsRewriteImgSrcs = []; - _dsAppliedImg = ''; // reset designer-level applied image - _buildDesignerModal(p); -} - -function _buildDesignerModal(p){ - const overlay = document.createElement('div'); - overlay.id = 'slide-designer-overlay'; - 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'; - let h='
'; - h+='

🎨 Thiết kế ảnh slide

'; - - /* ---- 1. Chọn slide (1 / nhiều / tất cả) ---- */ - h+='
'; - h+='
'; - h+=''; - h+=''; - h+='
'; - p.slides.forEach((s,i)=>{ - const preview = s.image ? `` : `
🖼️
`; - const isSel = _dsState.selected.includes(i); - h+=``; - }); - h+='
'; - - /* ---- 2. Nội dung từng slide đã chọn ---- */ - h+='
'; - - /* ---- 3. Cấu hình thiết kế ---- */ - h+='
'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - h+='
'; - - /* ---- 3b. Màu nền + ảnh nền mẫu (chỉ hiển thị khi chọn "Nền đều/solid") ---- */ - h+=''; - - /* ---- 4. Màu chữ + nền ---- */ - h+='
'; - ['#ffffff','#000000','#ff4444','#44ff44','#4444ff','#ffff00','#ff00ff','#00ffff','#ff8800','#88ff00','#ffd700','#ff69b4'].forEach(c=>{h+=``;}); - h+='
'; - - /* ---- 5. Ảnh nền (source buttons + URL/upload) ---- */ - h+='
'; - h+='
'; - h+=''; - h+=''; - h+=''; - h+='
'; - /* URL + upload panel (only the URL/upload inputs collapse; apply button stays visible) */ - h+=''; - /* "Áp dụng ảnh này cho TẤT CẢ slide đã chọn" — ALWAYS visible (Bug 1 fix) */ - h+='
✓ Áp dụng để dùng 1 ảnh cho nhiều slide
'; - h+='
Ả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.
'; - h+=''; - h+='
'; - - h+='
'; - h+=''; - h+='
'; - overlay.innerHTML=h; document.body.appendChild(overlay); - - /* button label update fn */ - window._dsUpdateSaveLabel = function(){ - const n = _dsState.selected.length; - const b = document.getElementById('ds-save-btn'); - if(b) b.textContent = '📤 Lưu & Đăng lên Tường AI ('+n+' slide)'; - }; - - /* ---- slide selection wiring ---- */ - overlay.querySelectorAll('.ds-slide-chk').forEach(chk=>{ - chk.addEventListener('change', _dsSyncSelection); - }); - document.getElementById('ds-sel-all').addEventListener('click', ()=>{ _setAllSelected(true); }); - document.getElementById('ds-sel-none').addEventListener('click', ()=>{ _setAllSelected(false); }); - document.getElementById('ds-slide-list').addEventListener('click', e=>{ - const lbl = e.target.closest('.ds-slide-chip'); - if(!lbl) return; - const chk = lbl.querySelector('.ds-slide-chk'); - if(e.target === chk) return; - chk.checked = !chk.checked; _dsSyncSelection(); - }); - - /* ---- inputs wiring ---- */ - document.getElementById('ds-preview-btn').addEventListener('click', _dsPreview); - document.getElementById('ds-save-btn').addEventListener('click', ()=>_dsSave(p)); - ['ds-texts','ds-ratio','ds-layout','ds-filter','ds-glow','ds-pos'].forEach(id=>{ - ['change','input'].forEach(evt=>{ - const el=document.getElementById(id); if(el) el.addEventListener(evt, ()=>_dsDebounce(_dsPreview, 150)); - }); - }); - // URL input: as user types a custom image URL, live-preview + apply to selected - const bgUrlInput=document.getElementById('ds-bg-url'); - if(bgUrlInput){ - bgUrlInput.addEventListener('input', ()=>{ - const v=bgUrlInput.value.trim(); - if(v && v.length>8){ - _dsSetImgMode('custom'); - const proxied=_dsImageSrc(v); - _dsAppliedImg = proxied; // Bug 3: applies to current + future selections - const sel=_dsState.selected; - if(sel.length){ sel.forEach(si=>{ _dsImgMap[si]=proxied; }); } - else { _dsImgMap[0]=proxied; } - } - _dsDebounce(_dsPreview,150); - }); - } - // Bug 1 fix: pass through the event; _dsHandleBgFile reads evt.target.files - document.getElementById('ds-bg-file').addEventListener('change', _dsHandleBgFile); - ['ds-img-src-rewrite','ds-img-src-custom','ds-img-src-none'].forEach(id=>{ - const b=document.getElementById(id); - if(b) b.addEventListener('click', ()=>{ - _dsSetImgMode(id==='ds-img-src-rewrite'?'rewrite':id==='ds-img-src-custom'?'custom':'none'); - }); - }); - /* "Áp dụng ảnh này cho TẤT CẢ slide đã chọn" — always-visible apply button */ - const applyBtn=document.getElementById('ds-apply-img-btn'); - if(applyBtn){ - applyBtn.addEventListener('click', function(){ - let chosen = _dsBgDataUrl || (document.getElementById('ds-bg-url')?.value||''); - if(!chosen){ toast('⚠️ Chọn ảnh (tải lên hoặc nhập URL) trước khi áp dụng'); return; } - _dsSetImgMode('custom'); - let proxied = _dsImageSrc(chosen); - _dsAppliedImg = proxied; // Bug 3 fix - dsApplyImgToSelected(proxied); - }); - } - // Toggle the "nền trơn" (solid) color + sample-image panel when layout changes - const layoutSel=document.getElementById('ds-layout'); - if(layoutSel){ - const toggleSolidPanel=()=>{ - const wrap=document.getElementById('ds-bg-solid-wrap'); - if(wrap) wrap.style.display = layoutSel.value==='solid' ? 'block' : 'none'; - }; - layoutSel.addEventListener('change', toggleSolidPanel); - layoutSel.addEventListener('input', toggleSolidPanel); - toggleSolidPanel(); - } - // Solid background color swatches - const bgColorBox=document.getElementById('ds-bg-colors'); - if(bgColorBox){ - bgColorBox.addEventListener('click', e=>{ - const b=e.target.closest('.ds-bgcolor-btn'); if(!b) return; - document.querySelectorAll('#ds-bg-colors .ds-bgcolor-btn').forEach(x=>x.style.borderColor='#333'); - b.style.borderColor='#fff'; - _dsBgColor = b.dataset.color; - _dsBgSample = ''; // color takes precedence over sample image - document.querySelectorAll('#ds-bg-samples .ds-bgsample-btn').forEach(x=>x.style.borderColor='#333'); - _dsStatus('🎨 Đã chọn màu nền: '+_dsBgColor); - _dsDebounce(_dsPreview, 150); - }); - } - // Sample background images (only for solid layout) - const bgSampleBox=document.getElementById('ds-bg-samples'); - if(bgSampleBox){ - bgSampleBox.addEventListener('click', e=>{ - const b=e.target.closest('.ds-bgsample-btn'); if(!b) return; - const bi=parseInt(b.dataset.bi,10); - const src=_DS_BG_SAMPLES[bi]; - if(!src) return; - document.querySelectorAll('#ds-bg-samples .ds-bgsample-btn').forEach(x=>x.style.borderColor='#333'); - b.style.borderColor='#ffd700'; - _dsBgSample = _dsImageSrc(src); - _dsBgColor = ''; // sample image takes precedence over color - document.querySelectorAll('#ds-bg-colors .ds-bgcolor-btn').forEach(x=>x.style.borderColor='#333'); - _dsStatus('🖼️ Đã chọn ảnh nền mẫu'); - _dsDebounce(_dsPreview, 150); - }); - } - _syncImgModeBtns(); - _dsRefreshRewriteImgs(p); - document.getElementById('ds-colors').addEventListener('click', e=>{ - const b = e.target.closest('.ds-color-btn'); if(!b) return; - overlay.querySelectorAll('.ds-color-btn').forEach(x=>x.style.borderColor='#333'); - b.style.borderColor='#fff'; - _dsTextColor = b.dataset.color; - _dsDebounce(_dsPreview, 150); - }); - - _dsRefreshTexts(p); - _dsUpdateSaveLabel(); - _dsPreview(); -} - -/* ---------------- selection sync ---------------- */ -function _setAllSelected(on){ - _dsState.selected = []; - document.querySelectorAll('#ds-slide-list .ds-slide-chk').forEach(chk=>{ chk.checked = on; if(on) _dsState.selected.push(parseInt(chk.dataset.idx)); }); - // Bug 3 fix: if an image was already applied at designer level, push it to - // every slide that is (now) selected so "1 ảnh cho nhiều slide" also covers - // slides selected AFTER the image was picked. - if(on && _dsAppliedImg){ - _dsState.selected.forEach(si=>{ _dsImgMap[si] = _dsAppliedImg; }); - } - const p = _wallPosts[_dsState.postIdx]; - if(p) _dsRefreshTexts(p); - _dsUpdateSaveLabel(); - _dsDebounce(_dsPreview, 150); -} -function _dsSyncSelection(){ - _dsState.selected = []; - document.querySelectorAll('#ds-slide-list .ds-slide-chk:checked').forEach(chk=>{ _dsState.selected.push(parseInt(chk.dataset.idx)); }); - // Bug 3 fix: same propagation for checkbox changes. - if(_dsAppliedImg){ - _dsState.selected.forEach(si=>{ if(!_dsImgMap[si]) _dsImgMap[si] = _dsAppliedImg; }); - } - const p = _wallPosts[_dsState.postIdx]; - if(p) _dsRefreshTexts(p); - _dsUpdateSaveLabel(); - _dsDebounce(_dsPreview, 150); -} - -/* ---------------- per-slide text areas ---------------- */ -function _dsRefreshTexts(p){ - const box = document.getElementById('ds-texts'); if(!box) return; - if(!_dsState.selected.length){ box.innerHTML='
Chưa chọn slide nào.
'; return; } - let h='
'; - _dsState.selected.forEach((si, k)=>{ - const s = p.slides[si]; - h+=``; - }); - h+='
'; - box.innerHTML=h; - box.querySelectorAll('textarea').forEach(ta=>{ - ta.addEventListener('input', ()=>{ _dsDebounce(_dsPreview, 200); }); - }); -} - -/* ---------------- bg file ---------------- */ -let _dsBgDataUrl = null; -let _dsTextColor = '#ffffff'; -let _dsImgMode = 'rewrite'; // 'rewrite' | 'custom' | 'none' -/* Bug 1 fix: this is bound as a 'change' listener, so the first arg is the - Event. Read the from evt.target.files (previously input.files was - undefined, so the upload silently did nothing and the preview/apply button - never saw the image). */ -function _dsHandleBgFile(evt){ - const input = evt && evt.target ? evt.target : evt; - const file = (input && input.files && input.files[0]) ? input.files[0] : null; - if(!file) return; - _dsSetImgMode('custom'); // show the custom-img URL/upload panel - const reader=new FileReader(); - reader.onload=function(e){ - _dsBgDataUrl=e.target.result; - _dsImgMode='custom'; - _syncImgModeBtns(); - _dsStatus('✅ Đã chọn ảnh: '+(file.name||'').slice(0,30) + (file.size? ' ('+Math.round(file.size/1024)+'KB)':'')); - // Auto-apply uploaded image to ALL currently selected slides so the upload - // has an immediate, visible effect (preview + save will use it for every slide). - _dsAppliedImg = _dsBgDataUrl; // Bug 3 fix: applies to future selections too - const sel=_dsState.selected; - if(sel.length){ sel.forEach(si=>{ _dsImgMap[si]=_dsBgDataUrl; }); } - else { _dsImgMap[0]=_dsBgDataUrl; } - _dsDebounce(_dsPreview,150); - }; - reader.readAsDataURL(file); -} -/* Show a transient status line in the designer footer. */ -function _dsStatus(msg){ - const s=document.getElementById('ds-status'); if(s) s.textContent=msg; -} -function _syncImgModeBtns(){ - ['ds-img-src-rewrite','ds-img-src-custom','ds-img-src-none'].forEach(id=>{ - const b=document.getElementById(id); - if(!b) return; - const on = (id==='ds-img-src-rewrite' && _dsImgMode==='rewrite') || - (id==='ds-img-src-custom' && _dsImgMode==='custom') || - (id==='ds-img-src-none' && _dsImgMode==='none'); - b.style.background = on ? '#2d8659' : '#333'; - b.style.color = on ? '#fff' : '#ccc'; - }); - const wrap=document.getElementById('ds-custom-img-url-wrap'); - if(wrap) wrap.style.display = _dsImgMode==='custom' ? 'block' : 'none'; -} -function _dsSetImgMode(m){ - _dsImgMode = m; - _syncImgModeBtns(); - _dsDebounce(_dsPreview, 150); -} - -/* Build a list of available rewrite images (post.img + each slide.image) - and render them so the user can pick 1 image to apply to the selected slides. - Bug 2 fix: uses data-index + a delegated click handler (no fragile inline - onclick embedding the raw URL, which broke on URLs containing quotes). */ -function _dsRefreshRewriteImgs(p){ - const box = document.getElementById('ds-rewrite-list'); - if(!box) return; - const imgs = []; - const seen = new Set(); - // post-level image first - if(p.img && typeof p.img === 'string' && p.img.length){ - const key = p.img.startsWith('/api/') ? p.img : _dsImageSrc(p.img); - if(!seen.has(key)){ seen.add(key); imgs.push({src: key, label: 'Ảnh bài (đại diện)'}); } - } - // then per-slide images - if(Array.isArray(p.slides)){ - p.slides.forEach((s, i)=>{ - const raw = s.image || s.img || ''; - if(raw && typeof raw === 'string' && raw.length){ - const key = raw.startsWith('/api/') ? raw : _dsImageSrc(raw); - if(!seen.has(key)){ seen.add(key); imgs.push({src: key, label: `Slide ${s.index||i+1}`}); } - } - }); - } - if(!imgs.length){ - box.innerHTML = '
Không có ảnh rewrite nào.
'; - const wrap = document.getElementById('ds-rewrite-imgs'); - if(wrap) wrap.style.display = 'none'; - return; - } - const wrap = document.getElementById('ds-rewrite-imgs'); - if(wrap) wrap.style.display = 'block'; - _dsRewriteImgSrcs = imgs.map(x=>x.src); // index -> src - let h=''; - imgs.forEach((img, idx)=>{ - h += '
' - + '' - + '
'+img.label+'
' - + '
'; - }); - box.innerHTML = h; - // Bug 2 fix: delegated click handler (event delegation, URL-safe) - box.onclick = function(e){ - const im = e.target.closest('img[data-ds-rw]'); - if(!im) return; - const idx = parseInt(im.getAttribute('data-ds-rw'), 10); - const src = _dsRewriteImgSrcs[idx]; - if(src) dsApplyImgToSelected(src); - }; -} - -/* Apply a chosen image src to ALL selected slides (or the current preview slide). */ -function dsApplyImgToSelected(imgSrc){ - _dsAppliedImg = imgSrc; // Bug 3 fix: remember at designer level (future selections too) - const sel = _dsState.selected; - if(sel.length){ - sel.forEach(si=>{ _dsImgMap[si] = imgSrc; }); - }else{ - _dsImgMap[0] = imgSrc; - } - _dsImgMode = 'custom'; // visually marks we are using a chosen image - _syncImgModeBtns(); - _dsStatus('✅ Đã áp dụng ảnh cho '+(sel.length? sel.length+' slide đã chọn':'slide hiện tại')); - // refresh preview immediately (selected slide 0 is what we preview) - const p=_wallPosts[_dsState.postIdx]; - if(p && sel.length){ _dsOptions(p, sel[0]); } - _dsPreview(); -} - -function _dsDebounce(fn,d){ clearTimeout(fn._t); fn._t=setTimeout(fn,d); } - -/* ---------------- get design options ---------------- */ -function _dsOptions(p, si){ - const s = p.slides[si]; - const ta = document.querySelector(`#ds-texts textarea[data-sidx="${si}"]`); - const text = ta ? ta.value : (s.text||''); - const bgInput = document.getElementById('ds-bg-url')?.value||''; - // Per-slide image override: when user picks an image from the rewrite list, - // it is stored in _dsImgMap[si] and applied to that specific slide. - let bgUrl = ''; - // Solid layout + user picked a SAMPLE background image -> use it as the - // background photo (dark overlay for readability) instead of a flat color. - const isSolid = designerGetLayoutV2()==='solid'; - const useSample = isSolid && _dsBgSample && !_dsAppliedImg; - if(useSample) bgUrl = _dsBgSample; - // Bug 3 fix: designer-level applied image wins for every selected slide. - // Applied when the user picked an image (rewrite picker / upload / URL / - // "Áp dụng" button) — even for slides selected AFTER the image was picked. - if(!bgUrl && _dsAppliedImg) bgUrl = _dsAppliedImg; - if(!bgUrl && _dsImgMap[si]) bgUrl = _dsImgMap[si]; - if(!bgUrl){ - if(_dsImgMode === 'custom'){ - bgUrl = _dsBgDataUrl || bgInput || ''; - } else if(_dsImgMode === 'rewrite'){ - bgUrl = s.image || p.img || ''; - } // none -> '' - } - return { - si, s, text, bgUrl, - ratio: designerGetRatioV2(), - layout: isSolid ? 'solid' : designerGetLayoutV2(), - filter: designerGetFilterV2(), - glow: designerGetGlowV2(), - pos: designerGetPosV2(), - color: _dsTextColor, - bgColor: _dsBgColor, // solid-layout background color ('' = default dark) - bgSample: useSample ? _dsBgSample : '', // 'sample' mode: img passed to draw - }; -} - -/* ---------------- drawing core ---------------- */ -function _dsImageSrc(url){ - if(!url) return ''; - if(url.startsWith('/api/') || url.startsWith('data:')) return url; - return '/api/proxy/img?url='+encodeURIComponent(url); -} -/* Only tag crossOrigin=anonymous for proxied EXTERNAL images. - Setting it on data: URLs or local /api/ paths can cause silent onload - failures (black preview) in some browser/CORS configurations. */ -function _dsMakeImg(url){ - const img=new Image(); - if(url && !url.startsWith('data:') && !url.startsWith('/api/')) img.crossOrigin='anonymous'; - return img; -} - -/* Sample background images for the "Nền đều (solid)" layout — abstract - gradients that look good with white text. Served through the /api/proxy/img - endpoint (same-origin, no crossOrigin needed — _dsMakeImg handles that). - Keyed for the modal background swatches and for _dsDrawLayout. */ -const _DS_BG_SAMPLES = [ - 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=900&q=60', // sơn hùng vĩ (núi) - 'https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=900&q=60', // sương mù rừng - 'https://images.unsplash.com/photo-1462331940025-496dfbfc7564?w=900&q=60', // vũ trụ - 'https://images.unsplash.com/photo-1469474968028-56623f02e42e?w=900&q=60', // núi rừng - 'https://images.unsplash.com/photo-1499002238440-d264edd596ec?w=900&q=60', // hoàng hôn - 'https://images.unsplash.com/photo-1448375240586-882707db888b?w=900&q=60', // rừng tối - 'https://images.unsplash.com/photo-1519681393784-d120267933ba?w=900&q=60', // trời sao - 'https://images.unsplash.com/photo-1518173946687-a4c8892bbd9f?w=900&q=60', // biển đêm - 'https://images.unsplash.com/photo-1497436072909-60f360e1d4b1?w=900&q=60', // đồng cỏ -]; - -/* draw bg image with cover-fit + color filter */ -function _dsDrawBg(ctx, W, H, bgUrl, filter, blur){ - ctx.save(); - ctx.fillStyle='#111'; ctx.fillRect(0,0,W,H); - // filter string - let f=''; - if(filter==='grayscale') f='grayscale(1)'; - else if(filter==='sepia') f='sepia(0.85)'; - else if(filter==='saturate') f='saturate(2.4)'; - else if(filter==='warm') f='sepia(0.45) saturate(1.5) hue-rotate(-15deg)'; - else if(filter==='cool') f='saturate(1.2) hue-rotate(15deg) brightness(1.05)'; - else if(filter==='invert') f='invert(1)'; - else if(filter==='noir') f='grayscale(1) contrast(1.6) brightness(0.9)'; - if(blur) f=(f?f+' ':'')+'blur('+blur+'px)'; - ctx.filter = f; - if(bgUrl){ - const img = new Image(); img.crossOrigin='anonymous'; - // Note: async path handled by caller via onload; this fn is synchronous draw of already-loaded img - } - ctx.restore(); -} - -/* ---------------- layout effects (with loaded bg image) ---------------- */ -function _dsDrawLayout(ctx, W, H, opts, img){ - const { layout, filter, bgUrl, bgColor } = opts; - // base: solid layout can use the chosen background color (no image needed) - let baseColor = '#141414'; - if(layout==='solid' && !img && bgColor) baseColor = bgColor; - ctx.fillStyle = baseColor; ctx.fillRect(0,0,W,H); - // draw bg image cover-fit if present & loaded - if(img){ - const blur = layout==='blur' ? Math.max(6, Math.round(W/90)) : 0; - ctx.save(); - let f=''; - if(filter==='grayscale') f='grayscale(1)'; - else if(filter==='sepia') f='sepia(0.85)'; - else if(filter==='saturate') f='saturate(2.4)'; - else if(filter==='warm') f='sepia(0.45) saturate(1.5) hue-rotate(-15deg)'; - else if(filter==='cool') f='saturate(1.2) hue-rotate(15deg) brightness(1.05)'; - else if(filter==='invert') f='invert(1)'; - else if(filter==='noir') f='grayscale(1) contrast(1.6) brightness(0.9)'; - if(blur) f=(f?f+' ':'')+'blur('+blur+'px)'; - ctx.filter = f; - const iw=img.naturalWidth||1, ih=img.naturalHeight||1; - const scale=Math.max(W/iw, H/ih); - const dw=iw*scale, dh=ih*scale; - const dx=(W-dw)/2, dy=(H-dh)/2; - ctx.drawImage(img,0,0,iw,ih,dx,dy,dw,dh); - ctx.filter='none'; - ctx.restore(); - } - // overlay per layout - if(layout==='gradient'){ - const g=ctx.createLinearGradient(0,0,W,H); - 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)'); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H); - } - else if(layout==='vignette'){ - const g=ctx.createRadialGradient(W/2,H/2,0,W/2,H/2,Math.max(W,H)*0.62); - g.addColorStop(0,'rgba(0,0,0,0)'); g.addColorStop(1,'rgba(0,0,0,0.78)'); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H); - } - else if(layout==='split'){ - const g=ctx.createLinearGradient(0,0,0,H); - 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)'); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H); - } - else if(layout==='spotlight'){ - ctx.fillStyle='rgba(0,0,0,0.72)'; ctx.fillRect(0,0,W,H); - const cx=W/2, cy=H*0.45, r=Math.max(W,H)*0.4; - const g=ctx.createRadialGradient(cx,cy,0,cx,cy,r); - 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)'); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H); - } - else if(layout==='diagonal'){ - ctx.fillStyle='rgba(0,0,0,0.55)'; ctx.fillRect(0,0,W,H); - ctx.fillStyle='rgba(0,0,0,0.8)'; - ctx.beginPath(); ctx.moveTo(0,0); ctx.lineTo(W*0.9,0); ctx.lineTo(0,H*0.9); ctx.closePath(); ctx.fill(); - } - else if(layout==='neon'){ - ctx.fillStyle='rgba(10,10,30,0.85)'; ctx.fillRect(0,0,W,H); - ctx.strokeStyle='rgba(80,220,255,0.5)'; ctx.lineWidth=Math.max(2,W/300); - ctx.strokeRect(W*0.03,H*0.03,W*0.94,H*0.94); - } - else if(layout==='top-banner'){ - ctx.fillStyle='rgba(0,0,0,0)'; - const g=ctx.createLinearGradient(0,0,0,H*0.5); - g.addColorStop(0,'rgba(0,0,0,0.8)'); g.addColorStop(1,'rgba(0,0,0,0)'); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H*0.5); - } - else if(layout==='lower-third'){ - const g=ctx.createLinearGradient(0,H*0.55,0,H); - g.addColorStop(0,'rgba(0,0,0,0)'); g.addColorStop(1,'rgba(0,0,0,0.82)'); - ctx.fillStyle=g; ctx.fillRect(0,H*0.55,W,H*0.45); - } - else if(layout==='card'){ - ctx.fillStyle='rgba(0,0,0,0.35)'; ctx.fillRect(0,0,W,H); - // rounded card - const pad=Math.round(W*0.04); - ctx.fillStyle='rgba(0,0,0,0.65)'; - _dsRoundRect(ctx, pad, H*0.16, W-2*pad, H*0.68, Math.round(W*0.05)); - ctx.fill(); - 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(); - } - else if(layout==='corner'){ - ctx.fillStyle='rgba(0,0,0,0.3)'; ctx.fillRect(0,0,W,H); - ctx.strokeStyle='rgba(255,215,0,0.9)'; ctx.lineWidth=Math.max(4,W/160); - const L=Math.round(W*0.18), c=Math.round(W*0.04); - [[0,c],[c,0],[W,c],[W-c,0],[0,H-c],[c,H],[W,H-c],[W-c,H]].forEach(([x,y],i)=>{ - const top = y===0 || y===c; const left = x===0 || x===c; - ctx.beginPath(); - if(i<4){ // top corners - if(top && left){ ctx.moveTo(x,y+L); ctx.lineTo(x,y); ctx.lineTo(x+L,y); } - else if(top){ ctx.moveTo(x,y+L); ctx.lineTo(x,y); ctx.lineTo(x-L,y); } - else { ctx.moveTo(x-L,y); ctx.lineTo(x,y); ctx.lineTo(x,y+L); } - } else { // bottom corners - if(left){ ctx.moveTo(x,y-L); ctx.lineTo(x,y); ctx.lineTo(x+L,y); } - else { ctx.moveTo(x-L,y); ctx.lineTo(x,y); ctx.lineTo(x,y-L); } - } - ctx.stroke(); - }); - } - else if(layout==='stars'){ - ctx.fillStyle='rgba(8,8,30,0.82)'; ctx.fillRect(0,0,W,H); - const n=Math.round(W*H/18000); - for(let i=0;i dark overlay so text is readable - ctx.fillStyle='rgba(0,0,0,0.45)'; ctx.fillRect(0,0,W,H); - } else if(bgColor){ - // chosen solid color with a subtle gradient + soft vignette for depth - const g=ctx.createLinearGradient(0,0,W,H); - g.addColorStop(0, bgColor); - g.addColorStop(1, _dsShadeColor(bgColor, -0.25)); - ctx.fillStyle=g; ctx.fillRect(0,0,W,H); - const vg=ctx.createRadialGradient(W/2,H/2,0,W/2,H/2,Math.max(W,H)*0.66); - vg.addColorStop(0,'rgba(0,0,0,0)'); vg.addColorStop(1,'rgba(0,0,0,0.42)'); - ctx.fillStyle=vg; ctx.fillRect(0,0,W,H); - } else { - ctx.fillStyle='rgba(0,0,0,0.6)'; ctx.fillRect(0,0,W,H); - } - } -} - -/* Darken (n<0) or lighten (n>0) a hex color by n*100% (for solid bg gradient). */ -function _dsShadeColor(hex, n){ - try{ - hex=String(hex||'').replace('#',''); - if(hex.length===3) hex=hex.split('').map(c=>c+c).join(''); - if(hex.length!==6) return hex; - const num=parseInt(hex,16); - let r=(num>>16)&255, g=(num>>8)&255, b=num&255; - const t = n<0 ? 0 : 255; - const p = Math.abs(n); - r=Math.round((t-r)*p)+r; g=Math.round((t-g)*p)+g; b=Math.round((t-b)*p)+b; - return '#'+((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1); - }catch(e){ return hex; } -} - -function _dsRoundRect(ctx,x,y,w,h,r){ - ctx.beginPath(); - ctx.moveTo(x+r,y); - ctx.arcTo(x+w,y,x+w,y+h,r); - ctx.arcTo(x+w,y+h,x,y+h,r); - ctx.arcTo(x,y+h,x,y,r); - ctx.arcTo(x,y,x+w,y,r); - ctx.closePath(); -} - -/* ---------------- text drawing ---------------- */ -function _dsDrawText(ctx, W, H, opts, baseFontScale){ - const { text, pos, glow, color } = opts; - if(!text || !text.trim()) return; - const base = Math.max(28, Math.round(W*baseFontScale)); - const fs = Math.min(base, Math.round(W*0.09)); - ctx.font = 'bold '+fs+'px "Segoe UI","Arial","Noto Sans",sans-serif'; - ctx.textAlign='center'; - // split lines - const lines=[]; let line=''; - const maxW=Math.round(W*0.82); - text.split(' ').forEach(w=>{ - const test = line? line+' '+w : w; - if(ctx.measureText(test).width>maxW && line){ lines.push(line.trim()); line=w; } else { line=test; } - }); - if(line) lines.push(line.trim()); - const lh=Math.round(fs*1.25); - const blockH=lines.length*lh; - let y; - if(pos==='top') y=Math.round(H*0.14)+lh/2; - else if(pos==='bottom') y=Math.round(H*0.88)-blockH+lh/2; - else y=Math.round(H/2)-blockH/2+lh/2; - // glow - if(glow==='white'){ ctx.shadowColor='rgba(255,255,255,0.95)'; ctx.shadowBlur=Math.max(8,fs*0.5); } - else if(glow==='color'){ ctx.shadowColor=color; ctx.shadowBlur=Math.max(10,fs*0.6); } - else if(glow==='neon'){ ctx.shadowColor='#00ffff'; ctx.shadowBlur=Math.max(16,fs*0.9); } - ctx.fillStyle=color; - // subtle stroke for legibility at top/bottom - 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); } - lines.forEach((l,li)=>{ ctx.fillText(l, W/2, y+li*lh); }); - ctx.shadowBlur=0; -} -function textLine(t){ return t; } - -/* ---------------- compute final canvas size for a design ---------------- */ -function _dsFinalSize(opts){ - const r=opts.ratio; - const w = (r.w>=r.h) ? 1800 : 1350; - const h = Math.round(w*r.h/r.w); - return { w, h }; -} - -/* Shared renderer (Bug 4 fix): renders a slide onto `canvas` using the SAME - code path and SAME resolution for BOTH preview and final save, so the - published image is pixel-identical to what the user saw in the preview — - same cover-fit, same filter, same text placement, same background. */ -function _dsRenderSlide(canvas, opts, done){ - const ctx = canvas.getContext('2d'); - const bgUrl = _dsImageSrc(opts.bgUrl); - function draw(img){ - _dsDrawLayout(ctx, canvas.width, canvas.height, opts, img||null); - _dsDrawText(ctx, canvas.width, canvas.height, opts, 0.052); - if(done) done(img||null); - } - if(bgUrl){ - const img=_dsMakeImg(bgUrl); - img.onload=function(){ draw(img); }; - img.onerror=function(){ console.warn('[designer] bg image failed to load:', bgUrl); draw(null); }; - img.src=bgUrl; - } else { - draw(null); - } -} - -/* ---------------- preview ---------------- */ -function _dsPreview(){ - const p=_wallPosts[_dsState.postIdx]; if(!p) return; - const area=document.getElementById('ds-preview-area'); if(!area) return; - const sel=_dsState.selected; - if(!sel.length){ area.style.display='block'; area.innerHTML='
Chưa chọn slide nào để xem trước.
'; return; } - area.style.display='block'; - area.innerHTML='
⏳ Đang tạo xem trước...
'; - // display-scale: cap visible width at 300px, keep aspect ratio per slide - const dispW=Math.min(300, Math.floor((Math.max(document.documentElement.clientWidth||540, document.body.clientWidth||540))*0.5)); - const cans=[]; - sel.forEach((si, k)=>{ - const opts=_dsOptions(p, si); - const { w, h }=_dsFinalSize(opts); - const canvas=document.createElement('canvas'); - canvas.width=w; canvas.height=h; - canvas.style.width=dispW+'px'; canvas.style.height='auto'; - 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'; - cans.push({opts, canvas}); - }); - let remaining=cans.length; - function allDone(){ - if(--remaining>0) return; - let out=''; - if(cans.length>1) out+='
Xem trước '+(cans.length)+' slide đã chọn (cuộn xuống để xem hết):
'; - area.innerHTML=out; - cans.forEach((c,k)=>{ - if(k>0) area.appendChild(document.createElement('br')); - area.appendChild(c.canvas); - }); - } - cans.forEach(c=>{ _dsRenderSlide(c.canvas, c.opts, allDone); }); -} - -/* ---------------- save: render + upload each selected slide, then post ---------------- */ -async function _dsSave(p){ - const statusEl=document.getElementById('ds-status'); if(statusEl) statusEl.textContent='⏳ Đang tạo ảnh các slide...'; - const sel=_dsState.selected; - if(!sel.length){ if(statusEl) statusEl.textContent='⚠️ Chưa chọn slide nào để đăng.'; return; } - const saveBtn=document.getElementById('ds-save-btn'); if(saveBtn){ saveBtn.disabled=true; saveBtn.textContent='⏳ Đang xử lý...'; } - - const uploaded = []; // {si, url} - try{ - // render each selected slide at final resolution - for(let k=0;k{ - _dsRenderSlide(canvas, opts, function(){ - // Nén JPEG thay PNG: dung lượng rất nhỏ (thường 5-10x nhỏ hơn), - // ả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. - canvas.toBlob(async function(blob){ - const fd=new FormData(); - fd.append('file', blob, 'slide_'+(si+1)+'.jpg'); - fd.append('post_id', p.id||''); - try{ - const r=await fetch('/api/wall/img',{method:'POST',body:fd}); - const j=await r.json(); - if(!r.ok || j.error) throw new Error(j.error||'Lỗi upload'); - resolve(j.url); - }catch(e){ resolve({error:e.message}); } - },'image/jpeg', 0.82); - }); - }); - if(url && url.error) throw new Error(url.error); - uploaded.push({si, url}); - // update slide image live - if(p.slides[si]) p.slides[si].image = url; - } - - if(statusEl) statusEl.textContent='⏳ Đang đăng lên Tường AI...'; - - // build updated slides array (keep unselected unchanged) - const newSlides = p.slides.map((s,i)=>{ - const up = uploaded.find(u=>u.si===i); - // ensure text edits are applied too - const ta = document.querySelector(`#ds-texts textarea[data-sidx="${i}"]`); - return { - text: ta ? ta.value : (s.text||''), - image: up ? up.url : (s.image||''), - index: s.index || (i+1), - }; - }); - - // pick selected slides only -> the wall post is a SLIDE-IMAGE post of selected slides - const selSlides = newSlides.filter((_,i)=> sel.includes(i)); - - const post = { - id: p.id, - title: p.title||'', - text: selSlides.map(s=>'• '+s.text).join('\n\n'), - img: selSlides[0] ? selSlides[0].image : p.img||'', - url: p.url||'', - slides: selSlides, // <-- bài đăng bao gồm chỉ các slide đã chọn - images: selSlides.map(s=>s.image), - kind: p.kind||'slide_summary', - video: p.video||'', - voice: p.voice||'', - emotion: p.emotion||'', - language: p.language||'', - ts: p.ts||Math.floor(Date.now()/1000), - }; - - const wr=await fetch('/api/wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(post)}); - const wj=await wr.json(); - if(wr.ok && wj.post){ - prependWallPost(wj.post); - toast('✅ Đã đăng bài slide lên Tường AI ('+selSlides.length+' slide)!'); - } else { - toast('✅ Đã lưu ảnh slide!'); - } - document.getElementById('slide-designer-overlay').remove(); - }catch(e){ - if(statusEl) statusEl.textContent='❌ '+e.message; - toast('❌ '+e.message); - if(saveBtn){ saveBtn.disabled=false; saveBtn.textContent='📤 Lưu & Đăng lên Tường AI ('+sel.length+' slide)'; } - } -} - -/* keep old helper names harmless for any other caller */ -function updateDesignerText(){} -function designerGetRatio(){ return designerGetRatioV2(); } -function designerGetLayout(){ return designerGetLayoutV2(); } -function designerDebounce(fn,d){ _dsDebounce(fn,d); } -function handleDesignerBgFile(){} -function previewDesignerSlide(){ _dsPreview(); } \ No newline at end of file diff --git a/static/fm_fix.css b/static/fm_fix.css index 4900ed0d2f51a295d0a15b9dbb6530aae08e2940..61e207172265b071cb75259375f87c253922a2fe 100644 --- a/static/fm_fix.css +++ b/static/fm_fix.css @@ -168,250 +168,3 @@ min-width:100%!important;max-width:none!important;max-height:none!important; object-fit:cover!important; } - -/* ============================================================ - BXH / BÅNG XẼP HẠNG (standing league table) FIX - Bongda returns div-based Tailwind rows (.ranking-table .leaderboard - .leaderboard-item / .head / .team / .copy). The old CSS only styled - so the standings rendered broken. Style the divs directly. - ============================================================ */ -#ls-content .ranking-table, -#ls-content .leaderboard{display:block!important;width:100%!important} -#ls-content .ranking-table .head, -#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} -#ls-content .ranking-table .head .team, -#ls-content .leaderboard .head .team{flex:1 1 auto!important;min-width:0!important} -#ls-content .ranking-table .head .team span, -#ls-content .leaderboard .head .team span{display:inline-block!important;width:18px!important;text-align:center!important;color:#888!important} -#ls-content .ranking-table .head .team .link, -#ls-content .leaderboard .head .team .link{font-size:10px!important;color:#999!important;font-weight:700!important} -#ls-content .ranking-table .head .copy, -#ls-content .leaderboard .head .copy{display:flex!important;gap:2px!important;align-items:center!important;justify-content:flex-end!important;min-width:0!important} -#ls-content .ranking-table .head .copy p, -#ls-content .leaderboard .head .copy p{font-size:9px!important;color:#888!important;min-width:16px!important;text-align:center!important;margin:0!important} -#ls-content .ranking-table .head .copy p.form, -#ls-content .leaderboard .head .copy p.form{display:none!important} -#ls-content .ranking-table .leaderboard-item, -#ls-content .ranking-table #team_, -#ls-content .leaderboard .leaderboard-item{ - display:table!important;width:100%!important;table-layout:fixed!important; - border-collapse:collapse!important;border-bottom:1px solid #1a1a1a!important; - font-size:11px!important;color:#ccc!important;background:transparent!important -} -#ls-content .ranking-table .leaderboard-item>div.team, -#ls-content .ranking-table .leaderboard-item>.team, -#ls-content .leaderboard .leaderboard-item .team{ - display:table-cell!important;vertical-align:middle!important; - padding:5px 4px!important;text-align:left!important;min-width:0!important -} -#ls-content .ranking-table .leaderboard-item>div.team span, -#ls-content .ranking-table .leaderboard-item>.team span{ - display:inline-block!important;width:18px!important;min-width:18px!important; - text-align:center!important;font-size:10px!important;color:#888!important;font-weight:600!important -} -#ls-content .ranking-table .leaderboard-item>div.team a.link, -#ls-content .ranking-table .leaderboard-item>.team a.link{ - display:inline-flex!important;align-items:center!important;gap:4px!important; - min-width:0!important;font-size:11px!important;color:#ccc!important;text-decoration:none!important -} -#ls-content .ranking-table .leaderboard-item>div.team a.link img, -#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} -#ls-content .ranking-table .leaderboard-item>div.team a.link p, -#ls-content .ranking-table .leaderboard-item>.team a.link p{ - font-size:11px!important;color:#ccc!important;margin:0!important; - white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important -} -#ls-content .ranking-table .leaderboard-item>div.copy, -#ls-content .ranking-table .leaderboard-item>.copy, -#ls-content .leaderboard .leaderboard-item .copy{ - display:table-cell!important;vertical-align:middle!important; - padding:5px 2px!important;text-align:center!important;white-space:nowrap!important -} -#ls-content .ranking-table .leaderboard-item>div.copy p, -#ls-content .ranking-table .leaderboard-item>.copy p{ - display:inline-block!important;min-width:22px!important;text-align:center!important; - font-size:11px!important;color:#ccc!important;margin:0 1px!important -} -#ls-content .ranking-table .leaderboard-item>div.copy p strong, -#ls-content .ranking-table .leaderboard-item>.copy p strong{ - display:inline-block!important;min-width:22px!important;text-align:center!important; - font-weight:800!important;color:#f0c040!important;font-size:12px!important -} -#ls-content .ranking-table .leaderboard-item>div.copy p.form, -#ls-content .ranking-table .leaderboard-item>.copy p.form{display:inline-flex!important;flex-wrap:nowrap!important} -#ls-content .ranking-table .leaderboard-item>div.copy p.form span, -#ls-content .ranking-table .leaderboard-item>.copy p.form span{ - display:inline-block!important;min-width:14px!important;height:14px!important; - line-height:14px!important;text-align:center!important;font-size:9px!important; - border-radius:2px!important;margin:0 1px!important;color:#fff!important -} -#ls-content .ranking-table .leaderboard-item>div.copy p.form span.bg-green, -#ls-content .ranking-table .leaderboard-item>.copy p.form span.bg-green{background:#2d8659!important} -#ls-content .ranking-table .leaderboard-item>div.copy p.form span.bg-gray-5, -#ls-content .ranking-table .leaderboard-item>.copy p.form span.bg-gray-5, -#ls-content .leaderboard .leaderboard-item .copy p.form span.bg-gray-5, -#ls-content .ranking-table .leaderboard-item .copy p.form span.bg-gray-5{background:#555!important;color:#ccc!important} -#ls-content .ranking-table .leaderboard-item>div.copy p.form span.bg-red, -#ls-content .ranking-table .leaderboard-item>.copy p.form span.bg-red{background:#c0392b!important} -/* hide the bongda left accent bar that floats absolutely */ -#ls-content .ranking-table .leaderboard-item>div[class*="w-["], -#ls-content .ranking-table .leaderboard-item div.relative{display:none!important} -/* top row = champion accent can stay, but clean layout */ -#ls-content .leaderboard-item{margin:0!important} -#ls-content .rank-table{width:100%!important;overflow-x:auto!important} -/* fallback generic so ANY div-based standings table gets readable */ -#ls-content .team .name,#ls-content .team .logo{font-size:11px!important;color:#ccc!important} -#ls-content .copy p{font-size:11px!important;color:#ccc!important} -/* injected BXH header + row layout (see _decorateStandings in app_v2.js) */ -#ls-content .ls-bxh-head{ - display:flex!important;width:100%!important;align-items:center!important;gap:4px!important; - background:#222!important;border-bottom:1px solid #333!important; - padding:5px 2px!important;position:sticky!important;top:0!important;z-index:2!important -} -#ls-content .ls-bxh-head .team{flex:1!important;min-width:0!important;display:flex!important;align-items:center!important;gap:4px!important} -#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} -#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} -#ls-content .ls-bxh-head .copy{display:flex!important;align-items:center!important;gap:2px!important;white-space:nowrap!important} -#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} -#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} -#ls-content .leaderboard-item .team{flex:1!important;min-width:0!important;display:flex!important;align-items:center!important;gap:4px!important} -#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} -#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} -#ls-content .leaderboard-item .team a img{width:16px!important;height:16px!important;object-fit:contain!important;flex:0 0 auto!important} -#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} -#ls-content .leaderboard-item .copy{display:flex!important;align-items:center!important;gap:2px!important;white-space:nowrap!important} -#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} -#ls-content .leaderboard-item .copy p strong{font-weight:800!important;color:#f0c040!important;min-width:20px!important;text-align:center!important} -#ls-content .leaderboard-item .copy p.form{display:inline-flex!important;flex-wrap:nowrap!important} -#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} -#ls-content .leaderboard-item .copy p.form span.bg-green{background:#2d8659!important;display:inline-block!important} -#ls-content .leaderboard-item .copy p.form span.bg-gray-5{background:#555!important;color:#ccc!important;display:inline-block!important} -#ls-content .leaderboard-item .copy p.form span.bg-red{background:#c0392b!important;display:inline-block!important} -#ls-content .leaderboard-item>div[class*="w-["]{display:none!important}#ls-content .leaderboard-item>div[class*="w-["]{display:none!important} - -/* ============================================================ - FPT PLAY / HIGHLIGHT VIDEO OVERFLOW FIX v2 - fptplay videos open in the TikTok-style feed inside .yt-thumb-wrap > - iframe (YouTube) or