Download cloud_app.py from vqh159/vidSub: direct link, hf CLI and curl.
- Browser
- Download file 20.1 kB
-
https://huggingface.co/spaces/vqh159/vidSub/resolve/main/cloud_app.py
- Command line
-
hf download hf://spaces/vqh159/vidSub/cloud_app.py
-
curl -L -o cloud_app.py https://huggingface.co/spaces/vqh159/vidSub/resolve/main/cloud_app.py
20.1 kB
| """FastAPI backend for Hugging Face Docker Space & Local Server.""" | |
| from __future__ import annotations | |
| import ipaddress | |
| import io | |
| import json | |
| import os | |
| from pathlib import Path | |
| import queue | |
| import shutil | |
| import socket | |
| import tempfile | |
| import threading | |
| import time | |
| from urllib.parse import urlsplit | |
| import uuid | |
| import zipfile | |
| import subprocess | |
| from PIL import Image, ImageDraw, ImageFont | |
| from typing import Literal | |
| from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import FileResponse, JSONResponse, StreamingResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from starlette.background import BackgroundTask | |
| from pydantic import BaseModel | |
| import vidsub | |
| BASE_DIR = Path(__file__).parent.resolve() | |
| STATIC_DIR = BASE_DIR / "static" | |
| JOBS_ROOT = Path(tempfile.gettempdir()) / "vidsub_jobs" | |
| JOBS_ROOT.mkdir(parents=True, exist_ok=True) | |
| JOB_TTL_SECONDS = 2700 # 45 minutes | |
| app = FastAPI(title="vidSub Cloud", version="2.0.0") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=[origin.strip() for origin in os.getenv( | |
| "VIDSUB_CORS_ORIGINS", "https://vqh159-vidsub.static.hf.space" | |
| ).split(",") if origin.strip()], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| expose_headers=["X-Vidsub-Job", "Content-Language"], | |
| ) | |
| def cleanup_old_jobs() -> None: | |
| now = time.time() | |
| for item in JOBS_ROOT.iterdir(): | |
| try: | |
| if item.is_dir() and (now - item.stat().st_mtime) > JOB_TTL_SECONDS: | |
| shutil.rmtree(item, ignore_errors=True) | |
| except OSError: | |
| continue | |
| def validate_public_url(raw_url: str) -> str: | |
| url = raw_url.strip() | |
| parsed = urlsplit(url) | |
| if parsed.scheme not in ("http", "https") or not parsed.hostname: | |
| raise ValueError("Link không hợp lệ. Cần địa chỉ bắt đầu bằng http:// hoặc https://.") | |
| if os.getenv("VIDSUB_ALLOW_LOCAL_URLS") == "1": | |
| return url | |
| host = parsed.hostname | |
| try: | |
| infos = socket.getaddrinfo(host, None) | |
| except socket.gaierror as exc: | |
| raise ValueError("Không phân giải được tên miền của link. Kiểm tra lại địa chỉ.") from exc | |
| for info in infos: | |
| addr_str = info[4][0] | |
| ip = ipaddress.ip_address(addr_str) | |
| if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved or ip.is_multicast: | |
| raise ValueError("Địa chỉ nội bộ không được phép truy cập trên máy chủ đám mây.") | |
| return url | |
| def health(): | |
| device, compute_type = vidsub.detect_compute_device() | |
| return { | |
| "ok": True, | |
| "mode": "cloud", | |
| "device": device, | |
| "computeType": compute_type, | |
| "hasFfmpeg": bool(shutil.which("ffmpeg")), | |
| "hasTesseract": bool(shutil.which("tesseract")), | |
| "hasGroq": bool(os.getenv("GROQ_API_KEY", "").strip()), | |
| "hasCookies": bool((os.getenv("YT_COOKIES") or os.getenv("YT_COOKIES_B64") or "").strip()), | |
| "requiresPin": bool(os.getenv("VIDSUB_ACCESS_CODE", "").strip()), | |
| } | |
| def verify_access_code(pin: str) -> None: | |
| expected = os.getenv("VIDSUB_ACCESS_CODE", "").strip() | |
| if expected and pin.strip() != expected: | |
| raise ValueError("Mã truy cập không đúng. Hãy nhập đúng mã PIN bảo vệ Space.") | |
| async def process_media( | |
| url: str = Form(""), | |
| transcript: str = Form(""), | |
| sourceMode: str = Form("auto"), | |
| ocrLang: str = Form("eng"), | |
| whisperModel: str = Form("small"), | |
| method: str = Form("context"), | |
| notes: str = Form(""), | |
| count: int = Form(0), | |
| keepVideo: bool = Form(False), | |
| apiKey: str = Form(""), | |
| cookiesTxt: str = Form(""), | |
| accessPin: str = Form(""), | |
| file: UploadFile | None = File(None), | |
| ): | |
| expected_pin = os.getenv("VIDSUB_ACCESS_CODE", "").strip() | |
| if expected_pin and accessPin.strip() != expected_pin: | |
| def denied_stream(): | |
| yield json.dumps({"error": "Mã truy cập (PIN) không đúng hoặc còn trống."}, ensure_ascii=False) + "\n" | |
| return StreamingResponse(denied_stream(), media_type="application/x-ndjson") | |
| cleanup_old_jobs() | |
| job_id = uuid.uuid4().hex[:12] | |
| job_dir = JOBS_ROOT / job_id | |
| job_dir.mkdir(parents=True, exist_ok=True) | |
| uploaded_path: Path | None = None | |
| if file and file.filename: | |
| safe_suffix = Path(file.filename).suffix[:12] or ".bin" | |
| uploaded_path = job_dir / f"upload{safe_suffix}" | |
| with uploaded_path.open("wb") as out_f: | |
| shutil.copyfileobj(file.file, out_f) | |
| msg_queue: queue.Queue[dict | None] = queue.Queue() | |
| cancel_flag = threading.Event() | |
| def push_status(text: str) -> None: | |
| if cancel_flag.is_set(): | |
| raise InterruptedError("Đã huỷ theo yêu cầu.") | |
| msg_queue.put({"status": text}) | |
| def worker() -> None: | |
| keep_job_dir = False | |
| try: | |
| rows: list[dict] | |
| detected_lang: str | None = None | |
| source_label = "bản chép lời" | |
| video_for_mux: Path | None = None | |
| if uploaded_path is None and transcript.strip(): | |
| push_status("Đang phân tích bản chép lời…") | |
| rows = vidsub.parse_pasted_transcript(transcript) | |
| else: | |
| if uploaded_path is not None: | |
| target_source = str(uploaded_path) | |
| elif url.strip(): | |
| target_source = validate_public_url(url) | |
| else: | |
| raise ValueError("Hãy dán link, chọn file trên máy, hoặc nhập bản chép lời.") | |
| is_ocr = sourceMode == "ocr" | |
| prefer_caps = sourceMode == "auto" | |
| need_vid = is_ocr or bool(keepVideo) | |
| acq = vidsub.acquire( | |
| target_source, | |
| job_dir, | |
| prefer_captions=prefer_caps, | |
| need_video=need_vid, | |
| cookies_txt=cookiesTxt, | |
| progress=push_status, | |
| ) | |
| source_label = acq.get("source_label", "media") | |
| detected_lang = acq.get("language") | |
| if "rows" in acq: | |
| rows = acq["rows"] | |
| else: | |
| media_path: Path = acq["media_path"] | |
| if acq.get("has_video"): | |
| video_for_mux = media_path | |
| if is_ocr: | |
| rows, detected_lang = vidsub.ocr_video_file( | |
| media_path, | |
| ocr_lang=ocrLang, | |
| progress=push_status, | |
| ) | |
| source_label = "chữ trên hình (OCR)" | |
| else: | |
| push_status("Bước 3/4 · Đang tách âm thanh bằng FFmpeg…") | |
| wav_path = vidsub.audio_file(media_path, job_dir) | |
| if apiKey.strip().startswith("gsk_") or os.getenv("GROQ_API_KEY", "").strip(): | |
| push_status(f"Bước 3/4 · Đang nhận dạng lời thoại qua Groq Whisper từ audio {wav_path.stat().st_size // 1024} KB…") | |
| else: | |
| push_status(f"Bước 3/4 · Đang nhận dạng lời thoại bằng Whisper {whisperModel}…") | |
| rows, detected_lang = vidsub.transcribe_audio_file( | |
| wav_path, | |
| model_size=whisperModel, | |
| speaker_count=max(0, min(20, int(count or 0))), | |
| api_key=apiKey, | |
| progress=push_status, | |
| ) | |
| used_groq = bool((apiKey or "").strip().startswith("gsk_") or os.getenv("GROQ_API_KEY", "").strip()) | |
| source_label = "âm thanh (Groq Whisper Cloud)" if used_groq else f"âm thanh (Whisper {whisperModel})" | |
| if not rows: | |
| raise ValueError("Không tìm thấy lời thoại có mốc thời gian trong nguồn này.") | |
| push_status(f"Bước 4/4 · Đang dịch {len(rows)} câu sang tiếng Việt…") | |
| translated = vidsub.translate_rows( | |
| rows, | |
| language=detected_lang, | |
| method=method, | |
| context="", | |
| speaker_notes=notes, | |
| api_key=apiKey, | |
| progress=push_status, | |
| ) | |
| out_rows = [] | |
| for r, vi in zip(rows, translated): | |
| out_rows.append( | |
| { | |
| "start": round(float(r["start"]), 3), | |
| "end": round(float(r["end"]), 3), | |
| "speaker": r.get("speaker") or "", | |
| "text": r["source"], | |
| "vi": vi, | |
| } | |
| ) | |
| has_video = bool(video_for_mux and video_for_mux.is_file()) | |
| if has_video and video_for_mux is not None: | |
| keep_job_dir = True | |
| (job_dir / "meta.json").write_text( | |
| json.dumps({"video": video_for_mux.name}), | |
| encoding="utf-8", | |
| ) | |
| msg_queue.put( | |
| { | |
| "rows": out_rows, | |
| "language": detected_lang or "", | |
| "source": source_label, | |
| "jobId": job_id if has_video else "", | |
| "hasVideo": has_video, | |
| } | |
| ) | |
| except InterruptedError: | |
| pass | |
| except Exception as exc: | |
| msg_queue.put({"error": str(exc)}) | |
| finally: | |
| if not keep_job_dir: | |
| shutil.rmtree(job_dir, ignore_errors=True) | |
| msg_queue.put(None) | |
| thread = threading.Thread(target=worker, daemon=True) | |
| thread.start() | |
| def event_stream(): | |
| try: | |
| while True: | |
| item = msg_queue.get() | |
| if item is None: | |
| break | |
| yield json.dumps(item, ensure_ascii=False) + "\n" | |
| except GeneratorExit: | |
| cancel_flag.set() | |
| return StreamingResponse(event_stream(), media_type="application/x-ndjson") | |
| class BurnRequest(BaseModel): | |
| jobId: str = "" | |
| url: str = "" | |
| cookiesTxt: str = "" | |
| srt: str | |
| mode: Literal["soft", "hard"] = "soft" | |
| accessPin: str = "" | |
| def burn_video(req: BurnRequest): | |
| try: | |
| verify_access_code(req.accessPin) | |
| except ValueError as exc: | |
| raise HTTPException(status_code=403, detail=str(exc)) from exc | |
| cleanup_old_jobs() | |
| video_path: Path | None = None | |
| job_dir: Path | None = None | |
| if req.jobId and req.jobId.isalnum(): | |
| cand_dir = JOBS_ROOT / req.jobId | |
| meta_file = cand_dir / "meta.json" | |
| if meta_file.is_file(): | |
| meta = json.loads(meta_file.read_text(encoding="utf-8")) | |
| cand_vid = cand_dir / meta["video"] | |
| if cand_vid.is_file(): | |
| job_dir = cand_dir | |
| video_path = cand_vid | |
| if video_path is None and req.url.strip(): | |
| target_url = validate_public_url(req.url) | |
| new_id = uuid.uuid4().hex[:12] | |
| job_dir = JOBS_ROOT / new_id | |
| job_dir.mkdir(parents=True, exist_ok=True) | |
| try: | |
| acq = vidsub.acquire( | |
| target_url, | |
| job_dir, | |
| prefer_captions=False, | |
| need_video=True, | |
| cookies_txt=req.cookiesTxt, | |
| ) | |
| video_path = acq.get("media_path") | |
| if not video_path or not video_path.is_file(): | |
| raise ValueError("Không tải được luồng hình ảnh từ link này.") | |
| (job_dir / "meta.json").write_text( | |
| json.dumps({"video": video_path.name}), | |
| encoding="utf-8", | |
| ) | |
| except Exception as exc: | |
| shutil.rmtree(job_dir, ignore_errors=True) | |
| raise HTTPException(status_code=502, detail=str(exc)) from exc | |
| if video_path is None or job_dir is None: | |
| raise HTTPException(status_code=404, detail="Không tìm thấy video gốc để ghép phụ đề. Hãy chọn file video hoặc dán link video.") | |
| out_name = f"vietsub_{req.mode}_{job_dir.name[:6]}.mp4" | |
| out_path = job_dir / out_name | |
| try: | |
| vidsub.mux_subtitles_to_video( | |
| video_path, | |
| req.srt, | |
| out_path, | |
| mode="hard" if req.mode == "hard" else "soft", | |
| ) | |
| except Exception as exc: | |
| raise HTTPException(status_code=500, detail=f"Lỗi ghép phụ đề FFmpeg: {exc}") from exc | |
| headers = {"X-Vidsub-Job": job_dir.name} | |
| return FileResponse(out_path, media_type="video/mp4", filename="vietsub.mp4", headers=headers) | |
| class FrameRequest(BaseModel): | |
| url: str | |
| rows: list[dict] | |
| grouping: Literal["separate", "merge"] = "separate" | |
| maxGap: float = 1.0 | |
| def subtitle_frames(req: FrameRequest): | |
| try: | |
| url = validate_public_url(req.url) | |
| cues = [] | |
| for row in req.rows[:300]: | |
| start, end = float(row["start"]), float(row["end"]) | |
| text = str(row.get("vi") or row.get("text") or "").strip() | |
| if end > start and text: | |
| cues.append({"start": start, "end": end, "text": text, "speaker": str(row.get("speaker") or "")}) | |
| if not cues: | |
| raise ValueError("Không có câu phụ đề hợp lệ để chụp ảnh.") | |
| groups = [] | |
| for cue in cues: | |
| if ( | |
| req.grouping == "merge" and groups | |
| and groups[-1][-1]["speaker"] == cue["speaker"] | |
| and cue["start"] - groups[-1][-1]["end"] <= max(0.0, min(3.0, req.maxGap)) | |
| ): | |
| groups[-1].append(cue) | |
| else: | |
| groups.append([cue]) | |
| job_dir = Path(tempfile.mkdtemp(prefix="vidsub_frames_")) | |
| try: | |
| cookie_file = vidsub._write_cookie_file(job_dir, None) | |
| opts = {**vidsub._build_ydl_opts("default", cookie_file), "skip_download": True} | |
| with vidsub.YoutubeDL(opts) as ydl: | |
| info = ydl.extract_info(url, download=False) | |
| formats = info.get("requested_formats") or [info] | |
| video_format = next((f for f in formats if f.get("vcodec") not in (None, "none")), None) | |
| if not video_format or not video_format.get("url"): | |
| raise ValueError("Không tìm thấy luồng hình ảnh cho link này.") | |
| stream_url = video_format["url"] | |
| headers = video_format.get("http_headers") or info.get("http_headers") or {} | |
| header_arg = "\r\n".join(f"{k}: {v}" for k, v in headers.items()) | |
| output = io.BytesIO() | |
| with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive: | |
| for index, group in enumerate(groups, 1): | |
| timestamp = (group[0]["start"] + group[-1]["end"]) / 2 | |
| command = ["ffmpeg", "-nostdin", "-loglevel", "error"] | |
| if header_arg: | |
| command += ["-headers", header_arg + "\r\n"] | |
| command += ["-ss", f"{timestamp:.3f}", "-i", stream_url, "-frames:v", "1", "-vf", "scale='min(1280,iw)':-2", "-f", "image2pipe", "-vcodec", "jpeg", "pipe:1"] | |
| result = subprocess.run(command, capture_output=True, timeout=25, check=False) | |
| if result.returncode or not result.stdout: | |
| continue | |
| caption = "\n".join( | |
| f"{cue['speaker']}: {cue['text']}" if cue["speaker"] else cue["text"] | |
| for cue in group | |
| ) | |
| frame = Image.open(io.BytesIO(result.stdout)).convert("RGB") | |
| draw = ImageDraw.Draw(frame) | |
| font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", max(18, frame.width // 34)) | |
| words = caption.split() | |
| lines, line = [], "" | |
| for word in words: | |
| candidate = f"{line} {word}".strip() | |
| if draw.textbbox((0, 0), candidate, font=font)[2] <= frame.width - 48: | |
| line = candidate | |
| else: | |
| if line: | |
| lines.append(line) | |
| line = word | |
| if line: | |
| lines.append(line) | |
| lines = lines[-4:] | |
| line_height = max(draw.textbbox((0, 0), item, font=font)[3] for item in lines) + 10 | |
| y = frame.height - line_height * len(lines) - 34 | |
| draw.rectangle((0, y - 12, frame.width, frame.height), fill=(0, 0, 0)) | |
| for item in lines: | |
| width = draw.textbbox((0, 0), item, font=font)[2] | |
| draw.text(((frame.width - width) / 2, y), item, font=font, fill="white", stroke_width=2, stroke_fill="black") | |
| y += line_height | |
| image_out = io.BytesIO() | |
| frame.save(image_out, format="JPEG", quality=88) | |
| archive.writestr(f"frame_{index:03d}_{timestamp:.2f}s.jpg", image_out.getvalue()) | |
| archive.writestr(f"frame_{index:03d}_{timestamp:.2f}s.txt", caption) | |
| if not archive.namelist(): | |
| raise ValueError("Không chụp được frame từ luồng video. Link có thể chặn tải hoặc không cho tua.") | |
| return StreamingResponse( | |
| iter([output.getvalue()]), | |
| media_type="application/zip", | |
| headers={"Content-Disposition": 'attachment; filename="vidsub-frames.zip"'}, | |
| ) | |
| finally: | |
| shutil.rmtree(job_dir, ignore_errors=True) | |
| except Exception as exc: | |
| raise HTTPException(status_code=502, detail=str(exc)) from exc | |
| async def legacy_media_endpoint(request: Request): | |
| """Backward-compatible media resolver with localhost/127.0.0.1 fix.""" | |
| try: | |
| payload = await request.json() | |
| try: | |
| verify_access_code(payload.get("accessPin", "")) | |
| except ValueError as exc: | |
| return JSONResponse({"message": str(exc)}, status_code=403) | |
| raw_url = payload.get("url", "") | |
| visual = payload.get("mode") == "ocr" | |
| url = validate_public_url(raw_url) | |
| except Exception as exc: | |
| return JSONResponse({"message": str(exc)}, status_code=400) | |
| tmp_dir = Path(tempfile.mkdtemp(prefix="vidsub_media_")) | |
| try: | |
| acq = vidsub.acquire(url, tmp_dir, prefer_captions=(not visual), need_video=visual) | |
| if "rows" in acq: | |
| vtt_path = tmp_dir / "captions.vtt" | |
| vtt_path.write_text(vidsub.format_vtt(acq["rows"]), encoding="utf-8") | |
| headers = {} | |
| if acq.get("language"): | |
| headers["Content-Language"] = acq["language"] | |
| return FileResponse(vtt_path, media_type="text/vtt", headers=headers, | |
| background=BackgroundTask(shutil.rmtree, tmp_dir, ignore_errors=True)) | |
| media_path: Path = acq["media_path"] | |
| mime = "video/mp4" if visual else "audio/mpeg" | |
| return FileResponse(media_path, media_type=mime, | |
| background=BackgroundTask(shutil.rmtree, tmp_dir, ignore_errors=True)) | |
| except Exception as exc: | |
| shutil.rmtree(tmp_dir, ignore_errors=True) | |
| return JSONResponse({"message": str(exc)}, status_code=502) | |
| app.mount("/", StaticFiles(directory=str(STATIC_DIR), html=True), name="static") | |
| if __name__ == "__main__": | |
| import uvicorn | |
| port = int(os.getenv("PORT", "7860")) | |
| host = os.getenv("HOST", "0.0.0.0") | |
| uvicorn.run(app, host=host, port=port) | |