diff --git a/.env.example b/.env.example index 85de103..c3fe4e3 100644 --- a/.env.example +++ b/.env.example @@ -24,6 +24,20 @@ AWS_S3_PUBLIC_BUCKET=your-public-bucket-name # Whisper transcription model (main pipeline). "small" is better than "base" on # non-English audio; "base" is faster. device/compute for GPU tuning. +# Prod GPU: WHISPER_MODEL=large-v3-turbo WHISPER_DEVICE=cuda WHISPER_COMPUTE=float16 # WHISPER_MODEL=small # WHISPER_DEVICE=cpu # WHISPER_COMPUTE=int8 + +# Transcription backend: whisper (default) | parakeet. Parakeet (NVIDIA +# parakeet-tdt-0.6b-v3 via onnx-asr, GPU image only) is ~2x faster than +# whisper-turbo-GPU and auto-falls-back to whisper on errors or languages +# outside its 25 European ones. +# TRANSCRIBE_BACKEND=whisper + +# Concurrent GPU transcriptions (parakeet or whisper-on-cuda). Keep 1. +# ASR_GPU_CONCURRENCY=1 + +# Video encoder for all ffmpeg encodes: x264 (default) | nvenc | auto. +# auto probes h264_nvenc once at startup and falls back to x264 if unusable. +# FFMPEG_ENCODER=x264 diff --git a/Dockerfile b/Dockerfile index 0bcdb03..02e7653 100644 --- a/Dockerfile +++ b/Dockerfile @@ -19,6 +19,17 @@ RUN pip install --no-cache-dir -r requirements.txt # are only imported when BILLING_ENABLED is set. Harmless/unused in self-host. RUN pip install --no-cache-dir -r requirements-billing.txt +# GPU build (--build-arg GPU=1): user-space CUDA libs only — the NVIDIA +# container runtime injects the driver. cuBLAS 12 + cuDNN 9 for CTranslate2 +# (faster-whisper CUDA), onnx-asr + onnxruntime-gpu for Parakeet. Adds ~2GB, +# so the default CPU image stays slim. +ARG GPU=0 +RUN if [ "$GPU" = "1" ]; then \ + pip install --no-cache-dir \ + "nvidia-cublas-cu12<13" "nvidia-cudnn-cu12>=9,<10" \ + onnx-asr onnxruntime-gpu; \ + fi + # Final stage FROM python:3.11-slim @@ -53,6 +64,13 @@ COPY --from=builder /opt/venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" ENV PYTHONUNBUFFERED=1 +# GPU runtime wiring — harmless no-ops on CPU builds / hosts without the +# NVIDIA runtime. LD_LIBRARY_PATH points at the pip-installed CUDA libs +# (paths simply don't exist in CPU images); DRIVER_CAPABILITIES asks the +# runtime for compute (CUDA) + video (NVENC) driver libs. +ENV LD_LIBRARY_PATH=/opt/venv/lib/python3.11/site-packages/nvidia/cublas/lib:/opt/venv/lib/python3.11/site-packages/nvidia/cudnn/lib:/opt/venv/lib/python3.11/site-packages/nvidia/cuda_runtime/lib:/opt/venv/lib/python3.11/site-packages/nvidia/cu13/lib +ENV NVIDIA_DRIVER_CAPABILITIES=compute,video,utility + # Latest yt-dlp (nightly — it updates frequently) plus its helper plugin. RUN pip install --upgrade --pre --no-cache-dir "yt-dlp[default]" bgutil-ytdlp-pot-provider @@ -62,8 +80,10 @@ COPY . . # Create a non-root user (Moved up) RUN groupadd -r appuser && useradd -r -g appuser -d /app -s /sbin/nologin appuser -# Create directories including Ultralytics cache config -RUN mkdir -p /app/uploads /app/output /tmp/Ultralytics +# Create directories including Ultralytics cache config. /app/.cache/huggingface +# exists in-image (appuser-owned via the chown below) so a persistent volume +# mounted there inherits writable ownership for the ASR model downloads. +RUN mkdir -p /app/uploads /app/output /app/.cache/huggingface /tmp/Ultralytics # Fix permissions: /app for code/uploads, /tmp/Ultralytics for AI cache RUN chown -R appuser:appuser /app /tmp/Ultralytics diff --git a/editor.py b/editor.py index 59dff8a..2a743d1 100644 --- a/editor.py +++ b/editor.py @@ -9,6 +9,7 @@ from google.genai import types from pydantic import BaseModel from edit_builder import build_filter_string +from ffmpeg_utils import video_encode_args, QUALITY class EditDecision(BaseModel): @@ -471,7 +472,7 @@ class VideoEditor: 'ffmpeg', '-y', '-i', input_path, '-vf', filter_string, - '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', + *video_encode_args(QUALITY), '-c:a', 'copy', '-movflags', '+faststart', output_path diff --git a/ffmpeg_utils.py b/ffmpeg_utils.py new file mode 100644 index 0000000..dcb032a --- /dev/null +++ b/ffmpeg_utils.py @@ -0,0 +1,102 @@ +"""Central video-encoder selection for every ffmpeg encode call site. + +FFMPEG_ENCODER env values: + x264 (default) — CPU libx264, exact pre-GPU behavior + nvenc — force h264_nvenc; probed once and falls back to x264 + (with a warning) if the GPU/driver is unavailable + auto — h264_nvenc when the probe succeeds, else x264 + +Only the codec/quality args live here; surrounding args (-movflags, -pix_fmt, +audio codecs, filters) stay at each call site. +""" +import os +import subprocess +import threading + +# Quality tiers pinning the historical libx264 settings. +QUALITY = "quality" # was: -preset medium -crf 18 +QUALITY_FAST = "quality_fast" # was: -preset fast -crf 18 +DELIVERY = "delivery" # was: -preset fast -crf 22 + +_X264_ARGS = { + QUALITY: ["-c:v", "libx264", "-preset", "medium", "-crf", "18"], + QUALITY_FAST: ["-c:v", "libx264", "-preset", "fast", "-crf", "18"], + DELIVERY: ["-c:v", "libx264", "-preset", "fast", "-crf", "22"], +} + +# NVENC -cq is not 1:1 with x264 CRF: benchmarked on the prod GPU (RTX 4000 +# Ada), cq ≈ crf + 7 lands in the same file-size ballpark, with vbr + AQ for +# quality. Presets p1-p7: p5 ≈ "medium", p4 ≈ "fast". +_NVENC_ARGS = { + QUALITY: ["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq", + "-rc", "vbr", "-cq", "25", "-b:v", "0", + "-spatial-aq", "1", "-temporal-aq", "1"], + QUALITY_FAST: ["-c:v", "h264_nvenc", "-preset", "p4", "-tune", "hq", + "-rc", "vbr", "-cq", "25", "-b:v", "0", "-spatial-aq", "1"], + DELIVERY: ["-c:v", "h264_nvenc", "-preset", "p4", + "-rc", "vbr", "-cq", "29", "-b:v", "0", "-spatial-aq", "1"], +} + +_probe_lock = threading.Lock() +_nvenc_ok = None # None = not probed yet +_announced = False + + +def _probe_nvenc(): + """One tiny lavfi encode to prove h264_nvenc works end-to-end. + + NVENC rejects frames smaller than ~145px, so the probe uses 256x256. + Any failure (no ffmpeg binary, no GPU, no driver libs) means False. + """ + cmd = [ + "ffmpeg", "-hide_banner", "-loglevel", "error", + "-f", "lavfi", "-i", "color=black:s=256x256:d=0.1", + "-c:v", "h264_nvenc", "-f", "null", "-", + ] + try: + result = subprocess.run( + cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30 + ) + return result.returncode == 0 + except Exception: + return False + + +def nvenc_available(): + """Probe h264_nvenc once and cache the verdict (thread-safe).""" + global _nvenc_ok + if _nvenc_ok is None: + with _probe_lock: + if _nvenc_ok is None: + _nvenc_ok = _probe_nvenc() + return _nvenc_ok + + +def reset_encoder_cache(): + """Test hook: forget the cached probe result.""" + global _nvenc_ok, _announced + with _probe_lock: + _nvenc_ok = None + _announced = False + + +def video_encode_args(tier=QUALITY): + """Return the codec/quality args for one encode, honoring FFMPEG_ENCODER.""" + global _announced + if tier not in _X264_ARGS: + raise ValueError(f"Unknown encode tier: {tier!r}") + + mode = os.environ.get("FFMPEG_ENCODER", "x264").strip().lower() + use_nvenc = False + if mode in ("nvenc", "auto"): + use_nvenc = nvenc_available() + if mode == "nvenc" and not use_nvenc: + print("⚠️ [Encoder] FFMPEG_ENCODER=nvenc but h264_nvenc is not " + "usable here — falling back to libx264") + + if not _announced: + _announced = True + print(f"🎞️ [Encoder] video encoder: {'h264_nvenc' if use_nvenc else 'libx264'} " + f"(FFMPEG_ENCODER={mode})") + + return list((_NVENC_ARGS if use_nvenc else _X264_ARGS)[tier]) diff --git a/hooks.py b/hooks.py index 5bc29a0..bb58fd7 100644 --- a/hooks.py +++ b/hooks.py @@ -6,6 +6,8 @@ import urllib.request import uuid from PIL import Image, ImageDraw, ImageFont, ImageFilter +from ffmpeg_utils import video_encode_args, QUALITY + FONT_URL = "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Bold.ttf" FONT_DIR = "fonts" FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf") @@ -363,7 +365,7 @@ def add_hook_to_video(video_path, text, output_path, position="top", font_scale= '-filter_complex', f"[0:v][1:v]overlay={overlay_x}:{overlay_y}" + (f":enable='between(t,0,{float(duration)})'" if duration else ""), '-c:a', 'copy', - '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', + *video_encode_args(QUALITY), '-movflags', '+faststart', output_path ] diff --git a/main.py b/main.py index 22a8c1a..5e7a657 100644 --- a/main.py +++ b/main.py @@ -20,6 +20,7 @@ from google.genai import types as genai_types import gemini_worker from clip_selection import build_transcript_windows, snap_clip_to_words +from ffmpeg_utils import video_encode_args, QUALITY, QUALITY_FAST from dotenv import load_dotenv import json @@ -596,7 +597,7 @@ def finalize_clip_passthrough(input_video, final_output_video): print(f"🎬 Passthrough (native framing): {input_video}") cmd = [ 'ffmpeg', '-y', '-i', input_video, - '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', + *video_encode_args(QUALITY), '-c:a', 'aac', '-movflags', '+faststart', final_output_video, ] @@ -674,8 +675,8 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE command = [ 'ffmpeg', '-y', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-s', f'{OUTPUT_WIDTH}x{OUTPUT_HEIGHT}', '-pix_fmt', 'bgr24', - '-r', str(fps), '-i', '-', '-c:v', 'libx264', - '-preset', 'fast', '-crf', '18', '-an', temp_video_output + '-r', str(fps), '-i', '-', + *video_encode_args(QUALITY_FAST), '-an', temp_video_output ] ffmpeg_process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) @@ -795,60 +796,18 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE return True def transcribe_video(video_path): - print("🎙️ Transcribing video with Faster-Whisper (CPU Optimized)...") - from faster_whisper import WhisperModel + print("🎙️ Transcribing video...") + from transcribe_backends import transcribe_media - # "small" is noticeably better than "base" on non-English audio (e.g. German - # compound words) at a modest speed cost. Overridable via env for tuning. - model_size = os.environ.get("WHISPER_MODEL", "small") - device = os.environ.get("WHISPER_DEVICE", "cpu") - compute = os.environ.get("WHISPER_COMPUTE", "int8") - model = WhisperModel(model_size, device=device, compute_type=compute) + transcript = transcribe_media(video_path) - # vad_filter drops silence; condition_on_previous_text off avoids repetition - # loops / hallucinations across segments. - segments, info = model.transcribe( - video_path, - word_timestamps=True, - beam_size=5, - vad_filter=True, - condition_on_previous_text=False, - ) - - print(f" Detected language '{info.language}' with probability {info.language_probability:.2f}") - - # Convert to openai-whisper compatible format - transcript_segments = [] - full_text = "" - - for segment in segments: + print(f" Detected language '{transcript['language']}', " + f"{len(transcript['segments'])} segments") + for segment in transcript['segments']: # Print progress to keep user informed (and prevent timeouts feeling) - print(f" [{segment.start:.2f}s -> {segment.end:.2f}s] {segment.text}") - - seg_dict = { - 'text': segment.text, - 'start': segment.start, - 'end': segment.end, - 'words': [] - } - - if segment.words: - for word in segment.words: - seg_dict['words'].append({ - 'word': word.word, - 'start': word.start, - 'end': word.end, - 'probability': word.probability - }) - - transcript_segments.append(seg_dict) - full_text += segment.text + " " - - return { - 'text': full_text.strip(), - 'segments': transcript_segments, - 'language': info.language - } + print(f" [{segment['start']:.2f}s -> {segment['end']:.2f}s] {segment['text']}") + + return transcript def _run_gemini_stage(client, model_name, prompt, schema): """One schema-enforced Gemini call with transient-error backoff. @@ -1088,7 +1047,7 @@ if __name__ == '__main__': '-ss', str(start), '-to', str(end), '-i', input_video, - '-c:v', 'libx264', '-crf', '18', '-preset', 'fast', + *video_encode_args(QUALITY_FAST), '-c:a', 'aac', clip_temp_path ] diff --git a/requirements.txt b/requirements.txt index c32e858..c40891d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,6 +5,7 @@ torchvision==0.26.0 tqdm==4.67.3 yt-dlp faster-whisper==1.2.1 +py3langid==0.3.0 google-genai==1.75.0 python-dotenv==1.2.2 mediapipe==0.10.14 diff --git a/saasshorts.py b/saasshorts.py index 5e27074..63dc715 100644 --- a/saasshorts.py +++ b/saasshorts.py @@ -17,6 +17,8 @@ import re import json import time import subprocess + +from ffmpeg_utils import video_encode_args, DELIVERY import httpx from urllib.parse import urljoin from typing import Optional, List, Dict, Callable @@ -1018,7 +1020,7 @@ def generate_broll( "-vf", zoompan_filter, "-t", str(dur_secs), "-map", "0:v", "-map", "1:a", - "-c:v", "libx264", "-preset", "fast", "-crf", "22", + *video_encode_args(DELIVERY), "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-shortest", @@ -1068,24 +1070,19 @@ def _format_ass_time(seconds: float) -> str: def transcribe_audio_for_subs(audio_path: str) -> list: """ - Transcribe audio with word-level timestamps using faster-whisper. + Transcribe audio with word-level timestamps via the configured ASR backend. Returns list of {"word": str, "start": float, "end": float}. """ - from faster_whisper import WhisperModel + from transcribe_backends import transcribe_media print(f"[SaaSShorts] 🎙️ Transcribing audio for subtitles...") - model = WhisperModel("base", device="cpu", compute_type="int8") - segments, info = model.transcribe(audio_path, word_timestamps=True) + transcript = transcribe_media(audio_path) - words = [] - for segment in segments: - if segment.words: - for w in segment.words: - words.append({ - "word": w.word.strip(), - "start": w.start, - "end": w.end, - }) + words = [ + {"word": w["word"].strip(), "start": w["start"], "end": w["end"]} + for segment in transcript["segments"] + for w in segment.get("words", []) + ] print(f"[SaaSShorts] ✅ Transcribed {len(words)} words") return words @@ -1203,7 +1200,7 @@ def composite_video( "ffmpeg", "-y", "-i", talking_head_path, "-vf", sub_filter, - "-c:v", "libx264", "-preset", "fast", "-crf", "22", + *video_encode_args(DELIVERY), "-c:a", "aac", "-b:a", "128k", output_path, ] @@ -1293,7 +1290,7 @@ def composite_video( "-filter_complex", filter_str, "-map", "[finalv]", "-map", "[outa]", - "-c:v", "libx264", "-preset", "fast", "-crf", "22", + *video_encode_args(DELIVERY), "-c:a", "aac", "-b:a", "128k", output_path, ] diff --git a/subtitles.py b/subtitles.py index 80cd67f..a011e91 100644 --- a/subtitles.py +++ b/subtitles.py @@ -3,6 +3,8 @@ import re import subprocess import sys +from ffmpeg_utils import video_encode_args, QUALITY + _STDIO_CONFIGURED = False @@ -96,41 +98,15 @@ def _normalize_subtitle_word(value): def transcribe_audio(video_path): """ - Transcribe audio from a video file using faster-whisper. + Transcribe audio from a video file via the configured ASR backend. Returns transcript in the same format as main.py for compatibility. """ - from faster_whisper import WhisperModel + # Lazy import: transcribe_backends imports helpers from this module. + from transcribe_backends import transcribe_media _log(f"🎙️ Transcribing audio from: {video_path}") - - cfg = get_whisper_config() - model = WhisperModel(cfg["model_size"], device=cfg["device"], compute_type=cfg["compute_type"]) - - segments, info = model.transcribe(video_path, **WHISPER_TRANSCRIBE_PARAMS) - - transcript = { - "segments": [], - "language": info.language - } - - for segment in segments: - seg_data = { - "start": segment.start, - "end": segment.end, - "text": segment.text, - "words": [] - } - if segment.words: - # Keep the leading-space boundary signal, then merge continuation - # fragments so compound words stay intact (see merge_continuation_words). - raw_words = [ - {"word": word.word, "start": word.start, "end": word.end} - for word in segment.words - ] - seg_data["words"] = merge_continuation_words(raw_words) - transcript["segments"].append(seg_data) - - _log(f"✅ Transcription complete. Language: {info.language}") + transcript = transcribe_media(video_path) + _log(f"✅ Transcription complete. Language: {transcript['language']}") return transcript @@ -514,7 +490,7 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16, '-i', video_path, '-vf', vf, '-c:a', 'copy', - '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', + *video_encode_args(QUALITY), '-movflags', '+faststart', output_path ] diff --git a/tests/test_ffmpeg_utils.py b/tests/test_ffmpeg_utils.py new file mode 100644 index 0000000..8beba5b --- /dev/null +++ b/tests/test_ffmpeg_utils.py @@ -0,0 +1,77 @@ +import subprocess + +import pytest + +import ffmpeg_utils +from ffmpeg_utils import ( + DELIVERY, + QUALITY, + QUALITY_FAST, + reset_encoder_cache, + video_encode_args, +) + + +@pytest.fixture(autouse=True) +def _clean_encoder_state(monkeypatch): + monkeypatch.delenv("FFMPEG_ENCODER", raising=False) + reset_encoder_cache() + yield + reset_encoder_cache() + + +def test_default_args_pin_historical_x264_settings(): + assert video_encode_args(QUALITY) == [ + "-c:v", "libx264", "-preset", "medium", "-crf", "18"] + assert video_encode_args(QUALITY_FAST) == [ + "-c:v", "libx264", "-preset", "fast", "-crf", "18"] + assert video_encode_args(DELIVERY) == [ + "-c:v", "libx264", "-preset", "fast", "-crf", "22"] + + +def test_unknown_tier_raises(): + with pytest.raises(ValueError): + video_encode_args("ultra") + + +def test_nvenc_mode_uses_nvenc_when_probe_passes(monkeypatch): + monkeypatch.setenv("FFMPEG_ENCODER", "nvenc") + monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", lambda: True) + args = video_encode_args(QUALITY) + assert args[:2] == ["-c:v", "h264_nvenc"] + assert "-cq" in args + + +def test_nvenc_mode_falls_back_to_x264_when_probe_fails(monkeypatch): + monkeypatch.setenv("FFMPEG_ENCODER", "nvenc") + monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", lambda: False) + assert video_encode_args(QUALITY)[:2] == ["-c:v", "libx264"] + + +def test_auto_probes_only_once(monkeypatch): + calls = [] + + def fake_probe(): + calls.append(1) + return True + + monkeypatch.setenv("FFMPEG_ENCODER", "auto") + monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", fake_probe) + for _ in range(3): + video_encode_args(QUALITY_FAST) + assert len(calls) == 1 + + +def test_missing_ffmpeg_binary_means_x264(monkeypatch): + def raise_missing(*args, **kwargs): + raise FileNotFoundError("ffmpeg") + + monkeypatch.setenv("FFMPEG_ENCODER", "auto") + monkeypatch.setattr(subprocess, "run", raise_missing) + assert video_encode_args(DELIVERY)[:2] == ["-c:v", "libx264"] + + +def test_returns_a_fresh_list_each_call(): + first = video_encode_args(QUALITY) + first.append("-mutated") + assert "-mutated" not in video_encode_args(QUALITY) diff --git a/tests/test_transcribe_backends.py b/tests/test_transcribe_backends.py new file mode 100644 index 0000000..6cd2472 --- /dev/null +++ b/tests/test_transcribe_backends.py @@ -0,0 +1,204 @@ +import json +import sys +import types +from types import SimpleNamespace + +import pytest + +import transcribe_backends as tb + + +class FakeFloat(float): + """Stands in for numpy scalar types (float subclasses) from onnx-asr.""" + + +def _seg(start, end, text, tokens, timestamps): + return SimpleNamespace( + start=FakeFloat(start), end=FakeFloat(end), text=text, + tokens=tokens, timestamps=[FakeFloat(t) for t in timestamps], + ) + + +# --- token -> word reconstruction ------------------------------------------ + +def test_words_from_tokens_groups_by_leading_space(): + words = tb._words_from_tokens( + [" T", "odo", " el", " mundo", "."], + [0.0, 0.16, 0.32, 0.40, 0.60], + seg_start=10.0, seg_end=12.0, + ) + assert [w["word"] for w in words] == [" Todo", " el", " mundo."] + # Absolute (segment-offset) start times. + assert words[0]["start"] == pytest.approx(10.0) + assert words[1]["start"] == pytest.approx(10.32) + # End inferred from the next word's start; last word ends at segment end. + assert words[0]["end"] == pytest.approx(10.32) + assert words[2]["end"] == pytest.approx(11.0, abs=0.3) + + +def test_words_from_tokens_first_token_without_space_gets_one(): + words = tb._words_from_tokens([ + "Hola", " que", " tal"], [0.0, 0.5, 1.0], seg_start=0.0, seg_end=2.0) + assert words[0]["word"] == " Hola" + + +def test_words_from_tokens_end_capped_after_long_silence(): + # Second word starts 5s later; first word's end must stay near its + # own tokens (cap = last token + 0.6), not stretch across the gap. + words = tb._words_from_tokens( + [" uno", " dos"], [0.0, 5.0], seg_start=0.0, seg_end=6.0) + assert words[0]["end"] <= 0.7 + + +def test_words_from_tokens_all_floats_are_native(): + words = tb._words_from_tokens( + [" a", "b", " c"], [0.0, 0.1, 0.2], seg_start=FakeFloat(1), seg_end=FakeFloat(2)) + for w in words: + assert type(w["start"]) is float + assert type(w["end"]) is float + + +# --- parakeet transcript assembly ------------------------------------------ + +@pytest.fixture +def fake_parakeet(monkeypatch): + segs = [ + _seg(0.35, 2.43, "Todo el mundo habla.", + [" Todo", " el", " mundo", " hab", "la", "."], + [0.0, 0.32, 0.40, 0.56, 0.72, 0.80]), + _seg(2.59, 5.57, "Pero, ¿qué es esto?", + [" Pero", ",", " ¿", "qu", "é", " es", " esto", "?"], + [0.0, 0.24, 0.32, 0.48, 0.64, 0.80, 1.04, 1.36]), + ] + model = SimpleNamespace(recognize=lambda path: iter(segs)) + monkeypatch.setattr(tb, "_get_parakeet_model", lambda: model) + monkeypatch.setattr(tb, "_extract_wav", lambda path: "/tmp/fake.wav") + monkeypatch.setattr(tb.os, "remove", lambda path: None) + return segs + + +def test_parakeet_transcript_matches_contract(fake_parakeet, monkeypatch): + monkeypatch.setattr(tb, "_detect_language", lambda text: "es") + t = tb._transcribe_with_parakeet("video.mp4") + + assert t["text"] == "Todo el mundo habla. Pero, ¿qué es esto?" + assert t["language"] == "es" + assert len(t["segments"]) == 2 + + seg = t["segments"][1] + assert type(seg["start"]) is float and type(seg["end"]) is float + # Continuations (",", "qu", "é") merged; leading spaces preserved. + assert [w["word"] for w in seg["words"]] == [" Pero,", " ¿qué", " es", " esto?"] + # Segment offset applied to word times. + assert seg["words"][0]["start"] == pytest.approx(2.59) + # Whole transcript is JSON-serializable (metadata json.dump path). + json.dumps(t) + + +def test_parakeet_words_survive_merge_continuation_words(fake_parakeet, monkeypatch): + from subtitles import merge_continuation_words + monkeypatch.setattr(tb, "_detect_language", lambda text: "es") + t = tb._transcribe_with_parakeet("video.mp4") + for seg in t["segments"]: + assert merge_continuation_words(seg["words"]) == seg["words"] + + +# --- fallback policy -------------------------------------------------------- + +def _valid_transcript(n_words=200, duration=120.0, language="es"): + words = [ + {"word": f" w{i}", "start": i * duration / n_words, + "end": (i + 1) * duration / n_words} + for i in range(n_words) + ] + return {"text": "x " * n_words, "language": language, + "segments": [{"start": 0.0, "end": duration, "text": "x", "words": words}]} + + +def test_fallback_reason_none_for_good_result(): + assert tb._parakeet_fallback_reason(_valid_transcript()) is None + + +def test_fallback_when_no_words(): + t = {"text": "", "language": "es", + "segments": [{"start": 0, "end": 5, "text": "x", "words": []}]} + assert "no words" in tb._parakeet_fallback_reason(t) + + +def test_fallback_when_language_unsupported(): + assert "outside" in tb._parakeet_fallback_reason( + _valid_transcript(language="ja")) + + +def test_fallback_when_word_rate_absurdly_low(): + assert tb._parakeet_fallback_reason( + _valid_transcript(n_words=5, duration=600.0)) is not None + + +def test_transcribe_media_falls_back_on_parakeet_exception(monkeypatch): + def boom(path): + raise RuntimeError("onnx exploded") + + sentinel = {"text": "ok", "language": "en", "segments": []} + monkeypatch.setenv("TRANSCRIBE_BACKEND", "parakeet") + monkeypatch.setattr(tb, "_transcribe_with_parakeet", boom) + monkeypatch.setattr(tb, "_transcribe_with_whisper", lambda path: sentinel) + assert tb.transcribe_media("video.mp4") is sentinel + + +def test_transcribe_media_default_is_whisper(monkeypatch): + sentinel = {"text": "ok", "language": "en", "segments": []} + monkeypatch.delenv("TRANSCRIBE_BACKEND", raising=False) + monkeypatch.setattr( + tb, "_transcribe_with_parakeet", + lambda path: (_ for _ in ()).throw(AssertionError("should not run"))) + monkeypatch.setattr(tb, "_transcribe_with_whisper", lambda path: sentinel) + assert tb.transcribe_media("video.mp4") is sentinel + + +# --- whisper singleton ------------------------------------------------------ + +@pytest.fixture +def fake_faster_whisper(monkeypatch): + created = [] + + class FakeModel: + def __init__(self, model_size, device=None, compute_type=None): + self.model_size = model_size + self.device = device + created.append(self) + + def transcribe(self, path, **params): + segs = (s for s in [SimpleNamespace( + start=0.0, end=1.0, text=" hola", words=None)]) + return segs, SimpleNamespace(language="es") + + fake_module = types.SimpleNamespace(WhisperModel=FakeModel) + monkeypatch.setitem(sys.modules, "faster_whisper", fake_module) + monkeypatch.setattr(tb, "_whisper_model", None) + monkeypatch.setattr(tb, "_whisper_key", None) + return created + + +def test_whisper_model_is_singleton(fake_faster_whisper, monkeypatch): + monkeypatch.delenv("WHISPER_MODEL", raising=False) + a, _ = tb._get_whisper_model() + b, _ = tb._get_whisper_model() + assert a is b + assert len(fake_faster_whisper) == 1 + + +def test_whisper_model_rebuilds_when_env_changes(fake_faster_whisper, monkeypatch): + monkeypatch.setenv("WHISPER_MODEL", "small") + a, _ = tb._get_whisper_model() + monkeypatch.setenv("WHISPER_MODEL", "large-v3-turbo") + b, _ = tb._get_whisper_model() + assert a is not b + assert b.model_size == "large-v3-turbo" + + +def test_run_whisper_transcription_materializes_segments(fake_faster_whisper, monkeypatch): + monkeypatch.delenv("WHISPER_MODEL", raising=False) + segments, info = tb.run_whisper_transcription("video.mp4") + assert isinstance(segments, list) + assert info.language == "es" diff --git a/transcribe_backends.py b/transcribe_backends.py new file mode 100644 index 0000000..7a38300 --- /dev/null +++ b/transcribe_backends.py @@ -0,0 +1,286 @@ +"""Transcription backends: NVIDIA Parakeet (onnx-asr) with faster-whisper fallback. + +Every caller goes through transcribe_media(), which returns the transcript +contract the whole pipeline depends on: + + { + "text": str, # full punctuated transcript + "language": str, # whisper-style short code ("es", "en", ...) + "segments": [ + {"start": float, "end": float, "text": str, + "words": [{"word": str, "start": float, "end": float}, ...]}, + ], + } + +Invariants the consumers rely on (clip cutting, karaoke subtitles, Remotion): + - word["word"] carries a LEADING SPACE on true word starts; continuation + fragments are merged into their base word (merge_continuation_words). + - all numerics are native Python floats (json.dump of the transcript). + - words sorted by start, segments chronological, absolute file timestamps. + +TRANSCRIBE_BACKEND env: "whisper" (default) | "parakeet". +The parakeet path falls back to whisper automatically when the model errors, +produces no usable words, or the detected language is outside its 25 +supported European languages (e.g. Japanese/Chinese/Arabic uploads). +""" +import os +import subprocess +import tempfile +import threading + +from subtitles import ( + get_whisper_config, + WHISPER_TRANSCRIBE_PARAMS, + merge_continuation_words, +) + +PARAKEET_MODEL_ID = "nemo-parakeet-tdt-0.6b-v3" + +# The 25 European languages parakeet-tdt-0.6b-v3 supports (ISO 639-1). +PARAKEET_LANGS = { + "bg", "hr", "cs", "da", "nl", "en", "et", "fi", "fr", "de", "el", "hu", + "it", "lv", "lt", "mt", "pl", "pt", "ro", "sk", "sl", "es", "sv", "ru", + "uk", +} + +# Serializes GPU transcription across concurrent jobs so N jobs can't stack +# N model contexts / decode batches in VRAM. CPU whisper stays ungated +# (CTranslate2 models are thread-safe and that matches the old behavior). +_ASR_GATE = threading.Semaphore(int(os.environ.get("ASR_GPU_CONCURRENCY", "1"))) + + +class _NullGate: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +_NULL_GATE = _NullGate() + +# --- whisper singleton ------------------------------------------------------ + +_whisper_model = None +_whisper_key = None +_whisper_lock = threading.Lock() + + +def _get_whisper_model(): + """Process-wide WhisperModel singleton, rebuilt if the env config changes. + + Keeping the model resident avoids a full reload per transcription (which + on GPU would also mean re-allocating a couple of GB of VRAM per job). + """ + global _whisper_model, _whisper_key + cfg = get_whisper_config() + key = (cfg["model_size"], cfg["device"], cfg["compute_type"]) + with _whisper_lock: + if _whisper_model is None or _whisper_key != key: + from faster_whisper import WhisperModel + _whisper_model = WhisperModel(key[0], device=key[1], compute_type=key[2]) + _whisper_key = key + return _whisper_model, cfg["device"] + + +def run_whisper_transcription(media_path, **params): + """Transcribe and FULLY materialize the segments inside the GPU gate. + + faster-whisper returns a lazy generator — decoding happens while + iterating, so the gate must wrap list(segments), not just transcribe(). + Returns (segments_list, info). + """ + model, device = _get_whisper_model() + gate = _ASR_GATE if device != "cpu" else _NULL_GATE + with gate: + segments, info = model.transcribe(media_path, **params) + return list(segments), info + + +def _transcribe_with_whisper(media_path): + segments, info = run_whisper_transcription(media_path, **WHISPER_TRANSCRIBE_PARAMS) + + out_segments = [] + text_parts = [] + for segment in segments: + words = [ + {"word": w.word, "start": float(w.start), "end": float(w.end)} + for w in (segment.words or []) + ] + out_segments.append({ + "start": float(segment.start), + "end": float(segment.end), + "text": segment.text, + "words": merge_continuation_words(words), + }) + text_parts.append(segment.text.strip()) + + return { + "text": " ".join(part for part in text_parts if part), + "language": info.language, + "segments": out_segments, + } + + +# --- parakeet --------------------------------------------------------------- + +_parakeet_model = None +_parakeet_lock = threading.Lock() + + +def _get_parakeet_model(): + global _parakeet_model + with _parakeet_lock: + if _parakeet_model is None: + import onnx_asr + model = onnx_asr.load_model( + PARAKEET_MODEL_ID, + providers=["CUDAExecutionProvider", "CPUExecutionProvider"], + ) + vad = onnx_asr.load_vad("silero") + _parakeet_model = model.with_vad(vad).with_timestamps() + return _parakeet_model + + +def _extract_wav(media_path): + """Parakeet wants 16kHz mono PCM wav; ffmpeg-extract to a temp file.""" + fd, wav_path = tempfile.mkstemp(suffix=".wav", prefix="asr_") + os.close(fd) + cmd = [ + "ffmpeg", "-y", "-loglevel", "error", "-i", media_path, + "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", wav_path, + ] + subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, timeout=1800) + return wav_path + + +def _words_from_tokens(tokens, timestamps, seg_start, seg_end): + """Group parakeet BPE tokens into words with absolute timestamps. + + Verified on the prod model: tokens already carry the leading-space + word-start convention (" T", "odo", " el", ...) and timestamps are token + START times in seconds relative to the VAD segment. A token without a + leading space (subword continuations, punctuation like ",") belongs to + the previous word — same semantics merge_continuation_words expects. + Word end is inferred: next word's start, capped near the word's last + token so a long inter-word silence doesn't stretch the highlight. + """ + words = [] + last_token_ts = [] + for token, ts in zip(tokens, timestamps): + if not token: + continue + abs_ts = float(ts) + seg_start + if token.startswith(" ") or not words: + words.append({ + "word": token if token.startswith(" ") else " " + token, + "start": abs_ts, + }) + last_token_ts.append(abs_ts) + else: + words[-1]["word"] += token + last_token_ts[-1] = abs_ts + + for i, word in enumerate(words): + next_start = words[i + 1]["start"] if i + 1 < len(words) else seg_end + cap = last_token_ts[i] + 0.6 + word["end"] = float(max(word["start"] + 0.05, min(next_start, cap))) + + return words + + +def _transcribe_with_parakeet(media_path): + model = _get_parakeet_model() + wav_path = _extract_wav(media_path) + try: + with _ASR_GATE: + results = list(model.recognize(wav_path)) + finally: + try: + os.remove(wav_path) + except OSError: + pass + + out_segments = [] + text_parts = [] + for seg in results: + seg_start = float(seg.start) + seg_end = float(seg.end) + seg_text = str(seg.text or "").strip() + if not seg_text: + continue + out_segments.append({ + "start": seg_start, + "end": seg_end, + "text": seg_text, + "words": _words_from_tokens( + list(seg.tokens or []), list(seg.timestamps or []), + seg_start, seg_end, + ), + }) + text_parts.append(seg_text) + + text = " ".join(text_parts) + return { + "text": text, + "language": _detect_language(text), + "segments": out_segments, + } + + +def _detect_language(text): + """Parakeet doesn't report a language; classify the transcribed text. + + py3langid is pure-Python and returns ISO 639-1 codes compatible with the + whisper codes the pipeline expects (thumbnail titles, Gemini prompts). + """ + sample = (text or "").strip() + if len(sample) < 20: + return "en" + try: + import py3langid + lang, _score = py3langid.classify(sample[:4000]) + return lang + except Exception: + return "en" + + +def _parakeet_fallback_reason(transcript, duration_hint=None): + """Return why the parakeet result is untrustworthy, or None if it's fine.""" + segments = transcript.get("segments") or [] + total_words = sum(len(s.get("words") or []) for s in segments) + if total_words == 0: + return "no words recognized" + language = transcript.get("language") + if language not in PARAKEET_LANGS: + return f"language '{language}' outside parakeet's supported set" + duration = duration_hint or (segments[-1]["end"] if segments else 0) + # Real speech averages >100 wpm; under ~12 wpm on a long video means the + # audio was mostly not recognized (e.g. unsupported language or music). + if duration > 60 and total_words < duration * 0.2: + return f"only {total_words} words in {duration:.0f}s of audio" + return None + + +# --- public entry point ----------------------------------------------------- + +def transcribe_media(media_path): + """Transcribe with the configured backend, falling back to whisper.""" + backend = os.environ.get("TRANSCRIBE_BACKEND", "whisper").strip().lower() + + if backend == "parakeet": + try: + transcript = _transcribe_with_parakeet(media_path) + reason = _parakeet_fallback_reason(transcript) + if reason is None: + print(f"🎙️ [ASR] parakeet ok: lang={transcript['language']} " + f"segments={len(transcript['segments'])}") + return transcript + print(f"⚠️ [ASR] parakeet result rejected ({reason}) — " + f"falling back to whisper") + except Exception as e: + print(f"⚠️ [ASR] parakeet failed ({type(e).__name__}: {e}) — " + f"falling back to whisper") + + return _transcribe_with_whisper(media_path)