From 60fa37a96902482632dcdf9d058e56678c55ede5 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 17 Sep 2026 17:19:57 +0200 Subject: [PATCH] fix(gpu,proxy): release ASR models in the API, probe one video not the playlist Three failures measured in prod on 17-sep-2026, one deploy. 1. 5 of 12 jobs failed with "ffmpeg could not cut clip ... exit 187, 0 bytes". Exit 187 is AVERROR_EXIT after "h264_nvenc: Could not open encoder": VRAM was full. The uvicorn process itself held 7.7 GB of the 20 GB card while idle: the thumbnail studio and /api/subtitle on a dubbed clip transcribe in-process, and the whisper (ctranslate2) and parakeet (onnxruntime CUDA) singletons then lived in the API for good. Both call transcribe_backends.release_models() now; the loaders fetch their model inside the ASR gate so a release can never pull it from under a running transcription. 2. 26 of the 37 probes that reached the per-GB proxy in 10 days were `watch?v=X&list=...` or mix links. Neither the probe nor the download set `noplaylist`, so yt-dlp walked the whole list, died on its first private / age-gated / bot-checked entry (a video nobody pasted), the probe read it as an IP problem and paid the proxy to walk the same list again, and the user got a 400 for a valid link. Reproduced in the prod container: the same URL with noplaylist answers in 9.6 s on a static. The probe also keeps every attempt's error per route now, so the anonymous retry's bot-check cannot overwrite a "confirm your age" from the cookie attempt into an escalation. 3. noplaylist does nothing for a search or a bare playlist URL: one `results?search_query=` held the probe thread for 2220 s in the container and still failed. Search, playlist, channel and feed URLs are refused by path before any request, with a message that says what to paste. --- CLAUDE.md | 28 +++++- app.py | 23 ++++- cloud/metering.py | 26 +++++- main.py | 10 +++ tests/test_probe_noplaylist.py | 123 +++++++++++++++++++++++++++ tests/test_transcribe_backends.py | 72 ++++++++++++++++ tests/test_youtube_non_video_urls.py | 81 ++++++++++++++++++ transcribe_backends.py | 65 +++++++++++++- yt_clients.py | 45 ++++++++++ 9 files changed, 464 insertions(+), 9 deletions(-) create mode 100644 tests/test_probe_noplaylist.py create mode 100644 tests/test_youtube_non_video_urls.py diff --git a/CLAUDE.md b/CLAUDE.md index ea4b06e..592644e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -395,6 +395,18 @@ Stripe retry the same doomed event for three days. ### Concurrency Model Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour. +The real limit on the GPU box is VRAM, not CPU: each `main.py` job holds +Parakeet (onnxruntime CUDA), TransNetV2 (torch, ~2 GB at peak) and an +NVENC session, and when the card is full a cut fails as "Generic error in +an external library" / exit 187 with 0 bytes, TransNetV2 as CUDA OOM, and +the reframe writer as a broken pipe. The retry in `ffmpeg_utils.cut_clip` +waits for a **busy** GPU; it cannot help with a **full** one. The API +process itself was the biggest tenant (7.7 GB idle on 17-sep-2026): the +thumbnail studio and `/api/subtitle` on a dubbed clip transcribe +in-process and the ASR singletons then lived in uvicorn for good, so both +now call `transcribe_backends.release_models()` when they are done. Size +`MAX_CONCURRENT_JOBS` against the free VRAM, not the core count. + ### Paid proxy accounting (`cloud/proxy_ledger.py`) Downloads go direct → static ISP proxies (flat rate) → DataImpulse (per GB), @@ -443,7 +455,21 @@ paid ones, each free attempt's error); `app.py` persists it as a `proxy_usage` row at job end and pages Telegram when the paid proxy carried bytes, folding a burst into one message per 5 min. The in-memory monthly counter and the container log (rotates within the hour) cannot answer "what -cost $14 on the 28th"; the table can. `PAID_PROXY_DAILY_MB` (default +cost $14 on the 28th"; the table can. Both the probe and the download pass `noplaylist`: a +`watch?v=X&list=...` or mix link is the one video the user was watching, +and without it yt-dlp walks the whole list, dies on its first private / +age-gated / bot-checked entry (a video nobody pasted), the probe reads +that as an IP problem and pays the proxy to walk the same list again, and +the user gets a 400 for a valid link (26 of the 37 paid probes between +7 and 17-sep-2026). And the probe keeps **every** attempt's error per +static route, not the last one: the anonymous retry ends in a bot-check +by design, and a "confirm your age" from the cookie attempt is the +verdict, so it must not be overwritten into an escalation. A search, +playlist or channel URL is refused by path before any request +(`yt_clients.youtube_non_video_reason`): `noplaylist` does nothing for +those and yt-dlp walks them entry by entry (one search URL held the +probe thread for 37 min in the prod container). +`PAID_PROXY_DAILY_MB` (default 500) is the hard ceiling: past it the paid proxy is dropped from the probe and from every new job's env until UTC midnight. The watcher probes the static pool against a real YouTube watch page (playable markers), not diff --git a/app.py b/app.py index 3b1e70d..3c2e71b 100644 --- a/app.py +++ b/app.py @@ -355,7 +355,12 @@ async def reserve_process_minutes(request, url, input_path, job_id, max_minutes= allow_paid=paid_allowed)) else: minutes = await loop.run_in_executor(None, _metering.probe_file_minutes, input_path) - except Exception: + except Exception as e: + from yt_clients import NotASingleVideo + if isinstance(e, NotASingleVideo): + raise HTTPException(status_code=400, detail=( + f"{e} Paste the link of one video (youtube.com/watch?v=... " + "or youtu.be/...).")) raise HTTPException(status_code=400, detail="Could not determine the video duration. Try a different source.") finally: @@ -4287,7 +4292,13 @@ async def add_subtitles(req: SubtitleRequest, request: Request): return generate_srt_from_video(input_path, srt_path) loop = asyncio.get_event_loop() - success = await loop.run_in_executor(None, run_transcribe_srt) + try: + success = await loop.run_in_executor(None, run_transcribe_srt) + finally: + # The ASR models must not stay resident in the API process: + # they held 7.7 GB of VRAM idle (transcribe_backends.release_models). + import transcribe_backends + await loop.run_in_executor(None, transcribe_backends.release_models) elif is_karaoke: success = generate_ass(sub_transcript, sub_start, sub_end, srt_path, **karaoke_opts) else: @@ -5107,7 +5118,13 @@ async def thumbnail_upload( from main import transcribe_video loop = asyncio.get_event_loop() - transcript = await loop.run_in_executor(None, transcribe_video, vpath) + try: + transcript = await loop.run_in_executor(None, transcribe_video, vpath) + finally: + # See transcribe_backends.release_models: the API process is + # long-lived and the GPU is shared with every running job. + import transcribe_backends + await loop.run_in_executor(None, transcribe_backends.release_models) segments = transcript.get("segments", []) duration = segments[-1]["end"] if segments else 0 diff --git a/cloud/metering.py b/cloud/metering.py index b72dd79..9eb674d 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -162,6 +162,12 @@ def probe_url_minutes(url: str, allow_paid: bool = True) -> float: # the live one so the probe sees the file and not an HTML page. import file_hosts url = file_hosts.resolve(url) + # Free and first: a search / playlist / channel page is walked entry by + # entry by yt-dlp and never yields a duration (yt_clients.youtube_non_video_reason). + from yt_clients import NotASingleVideo, youtube_non_video_reason + reason = youtube_non_video_reason(url) + if reason: + raise NotASingleVideo(f"This link is {reason}.") bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip() bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip() @@ -248,6 +254,13 @@ def _probe_with_proxies(url, proxies, strategies, static_errors, paid, ck_path): last_err = None for proxy in proxies: is_paid = bool(paid) and proxy == paid + # Every attempt's error on this route, not just the last one. The + # anonymous retry (see probe_url_minutes) on a static IP routinely + # ends in "Sign in to confirm you're not a bot"; if the attempt with + # the cookies had already said "confirm your age" / "Private video", + # that is the verdict, and the bot-check must not turn it into an IP + # problem worth the paid proxy (17-sep-2026, 3QFAEqE9-Kk, twice). + route_errors = [] if is_paid: # Only spend the per-GB proxy when a free route failed for a # reason another IP can fix. Content errors and "no duration" @@ -256,7 +269,16 @@ def _probe_with_proxies(url, proxies, strategies, static_errors, paid, ck_path): for e in static_errors.values()): break for step, (extractor_args, use_cookies) in enumerate(strategies): + # noplaylist: a URL pasted from a playing playlist or a mix + # (`watch?v=X&list=...`) is that ONE video. Without this yt-dlp + # walks the whole list and fails on its first private / age-gated + # / bot-checked entry, a video the user never asked for; the probe + # then escalated to the per-GB proxy, which walked the same list + # and failed the same way, and the user got a 400 for a valid + # link. 26 of the 37 paid probes between 7 and 17-sep-2026 were + # exactly this (proxy_usage: `list=` and `results?search_query`). opts = {"skip_download": True, "quiet": True, "no_warnings": True, + "noplaylist": True, "logger": _QuietLogger(), "extractor_args": extractor_args} if ck_path and use_cookies: opts["cookiefile"] = ck_path @@ -280,9 +302,11 @@ def _probe_with_proxies(url, proxies, strategies, static_errors, paid, ck_path): break except Exception as e: last_err = e + route_errors.append(str(e)[:300]) else: if not is_paid: - static_errors[_route_name(proxy, proxies)] = str(last_err)[:300] + static_errors[_route_name(proxy, proxies)] = ( + " || ".join(route_errors) if route_errors else str(last_err)[:300]) continue break if paid and any(p == paid for p in proxies) and static_errors and \ diff --git a/main.py b/main.py index 74ff992..7eb7b57 100644 --- a/main.py +++ b/main.py @@ -793,6 +793,11 @@ def download_youtube_video(url, output_dir="."): # signed links; refresh through the host's page so yt-dlp gets the file. import file_hosts url = file_hosts.resolve(url) + # Cloud mode rejects these at the probe; this is the self-host path. + from yt_clients import NotASingleVideo, youtube_non_video_reason + reason = youtube_non_video_reason(url) + if reason: + raise NotASingleVideo(f"This link is {reason}.") print(f"🔍 Debug: yt-dlp version: {yt_dlp.version.__version__}") print("📥 Downloading video from YouTube...") @@ -872,6 +877,11 @@ def download_youtube_video(url, output_dir="."): 'cookiefile': cookies_path if (cookies and cookies_path) else None, 'proxy': proxy, 'socket_timeout': 30, 'retries': 10, 'fragment_retries': 10, 'nocheckcertificate': True, 'cachedir': False, + # A `watch?v=X&list=...` link is the one video the user was + # watching, not the playlist: without this yt-dlp downloads every + # entry of the list into the SAME outtmpl (the title is the + # playlist's), paying for all of them and keeping the last. + 'noplaylist': True, 'extractor_args': extractor_args, 'http_headers': { 'User-Agent': ( diff --git a/tests/test_probe_noplaylist.py b/tests/test_probe_noplaylist.py new file mode 100644 index 0000000..c378b61 --- /dev/null +++ b/tests/test_probe_noplaylist.py @@ -0,0 +1,123 @@ +"""The duration probe asks yt-dlp for ONE video, and a content verdict wins. + +Two probe failures measured in prod between 7 and 17-sep-2026 (proxy_usage, +source='probe'): 26 of the 37 probes that reached the per-GB proxy were for a +`watch?v=X&list=...` or a `results?search_query=` URL. Without ``noplaylist`` +yt-dlp walked the whole list, died on its first private / age-gated / +bot-checked entry (a video the user never pasted), the probe read that as an +IP problem, paid the proxy to walk the same list again, and the user got a +400 for a valid link. + +The second: on a static route the attempt with the cookies said "Sign in to +confirm your age" (a content error, same on every IP) and the anonymous retry +said "not a bot"; only the last error was kept per route, so the bot-check +overrode the verdict and the paid proxy was spent on an age-gated video, +twice in 15 minutes. +""" +import sys +import types + +import pytest + +metering = pytest.importorskip("cloud.metering") + +URL = "https://www.youtube.com/watch?v=3QFAEqE9-Kk&list=PLArw552Yzuwn&rco=1" +NETSCAPE = "# Netscape HTTP Cookie File\n.youtube.com\tTRUE\t/\tTRUE\t0\tSID\tx\n" +AGE = "ERROR: [youtube] 3QFAEqE9-Kk: Sign in to confirm your age. Use --cookies" +BOT = "ERROR: [youtube] 3QFAEqE9-Kk: Sign in to confirm you’re not a bot." + + +def _fake_ytdl(monkeypatch, attempts, outcome): + """``outcome(opts)`` returns an info dict or raises.""" + + class _YDL: + def __init__(self, opts): + self.opts = opts + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def extract_info(self, url, download=False): + attempts.append(dict(self.opts)) + return outcome(self.opts) + + monkeypatch.setitem(sys.modules, "yt_dlp", types.SimpleNamespace(YoutubeDL=_YDL)) + + +@pytest.fixture(autouse=True) +def _env(monkeypatch): + import security_utils + monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u) + monkeypatch.setenv("STATIC_PROXY_URLS", "http://s1,http://s2") + monkeypatch.setenv("PROXY_URL", "http://paid") + monkeypatch.setenv("YOUTUBE_COOKIES", NETSCAPE) + monkeypatch.setenv("BGUTIL_BASE_URL", "http://127.0.0.1:4416") + monkeypatch.delenv("DIRECT_FIRST", raising=False) + # No network: the last-resort ffprobe must not run either. + monkeypatch.setattr(metering, "_ffprobe_url_seconds", lambda url, timeout=30: 0.0) + metering.pop_paid_probe_events() + yield + metering.pop_paid_probe_events() + + +class TestOneVideoNotThePlaylist: + def test_every_attempt_asks_for_the_single_video(self, monkeypatch): + attempts = [] + _fake_ytdl(monkeypatch, attempts, + lambda o: {"extractor": "youtube", "duration": 600}) + + assert abs(metering.probe_url_minutes(URL) - 10) < 1e-6 + assert attempts and all(a.get("noplaylist") is True for a in attempts) + + +class TestAContentVerdictOutranksTheAnonymousBotCheck: + def _outcome(self, opts): + # With the cookies: age-gated (same on every IP). Anonymous: bot-check. + raise RuntimeError(AGE if opts.get("cookiefile") else BOT) + + def test_the_paid_proxy_is_not_spent(self, monkeypatch): + attempts = [] + _fake_ytdl(monkeypatch, attempts, self._outcome) + + with pytest.raises(ValueError): + metering.probe_url_minutes(URL) + + assert not any(a.get("proxy") == "http://paid" for a in attempts) + assert metering.pop_paid_probe_events() == [] + + def test_both_errors_are_kept_for_the_alert(self, monkeypatch): + attempts = [] + _fake_ytdl(monkeypatch, attempts, self._outcome) + seen = {} + real = metering._probe_with_proxies + + def spy(url, proxies, strategies, static_errors, paid, ck_path): + try: + return real(url, proxies, strategies, static_errors, paid, ck_path) + finally: + seen.update(static_errors) + + monkeypatch.setattr(metering, "_probe_with_proxies", spy) + with pytest.raises(ValueError): + metering.probe_url_minutes(URL) + + assert "confirm your age" in seen["static1"] + assert "not a bot" in seen["static1"] + assert not metering.static_failure_warrants_paid(seen["static1"]) + + +class TestAnIpProblemStillEscalates: + def test_bot_check_on_every_attempt_reaches_the_paid_proxy(self, monkeypatch): + attempts = [] + + def outcome(opts): + if opts.get("proxy") == "http://paid": + return {"extractor": "youtube", "duration": 60} + raise RuntimeError(BOT) + + _fake_ytdl(monkeypatch, attempts, outcome) + assert abs(metering.probe_url_minutes(URL) - 1) < 1e-6 + assert attempts[-1]["proxy"] == "http://paid" diff --git a/tests/test_transcribe_backends.py b/tests/test_transcribe_backends.py index acb87c1..e882390 100644 --- a/tests/test_transcribe_backends.py +++ b/tests/test_transcribe_backends.py @@ -210,3 +210,75 @@ def test_run_whisper_transcription_materializes_segments(fake_faster_whisper, mo segments, info = tb.run_whisper_transcription("video.mp4") assert isinstance(segments, list) assert info.language == "es" + + +# --- release_models: the API process must not keep the models resident ------ + +class _FakeCT2: + def __init__(self): + self.unloaded = False + + def unload_model(self, to_cpu=False): + self.unloaded = True + + +class _FakeWhisper: + def __init__(self): + self.model = _FakeCT2() + + +def test_release_models_drops_both_singletons_and_unloads_whisper(monkeypatch): + whisper = _FakeWhisper() + monkeypatch.setattr(tb, "_whisper_model", whisper) + monkeypatch.setattr(tb, "_whisper_key", ("large-v3-turbo", "cuda", "float16")) + monkeypatch.setattr(tb, "_parakeet_model", object()) + + tb.release_models() + + assert tb._whisper_model is None and tb._whisper_key is None + assert tb._parakeet_model is None + assert whisper.model.unloaded # ctranslate2 frees VRAM on unload, not on GC + + +def test_release_models_hands_every_gate_slot_back(): + tb.release_models() + # Every slot is free again: a transcription can start right after. + for _ in range(tb._ASR_SLOTS): + assert tb._ASR_GATE.acquire(blocking=False) + for _ in range(tb._ASR_SLOTS): + tb._ASR_GATE.release() + + +def test_release_models_is_a_no_op_when_nothing_is_loaded(monkeypatch): + monkeypatch.setattr(tb, "_whisper_model", None) + monkeypatch.setattr(tb, "_parakeet_model", None) + tb.release_models() + assert tb._whisper_model is None and tb._parakeet_model is None + + +def test_whisper_model_is_fetched_inside_the_gate(monkeypatch): + """release_models drains the gate before unloading; that only protects a + transcription if the model is taken *after* the gate is held.""" + order = [] + + class _Gate: + def __enter__(self): + order.append("gate") + return self + + def __exit__(self, *a): + return False + + class _Model: + def transcribe(self, path, **params): + order.append("transcribe") + return iter([]), SimpleNamespace(duration=0, language="en") + + monkeypatch.setattr(tb, "_ASR_GATE", _Gate()) + monkeypatch.setattr(tb, "_whisper_device", lambda: "cuda") + monkeypatch.setattr(tb, "_get_whisper_model", + lambda: (order.append("model"), (_Model(), "cuda"))[1]) + + tb._run_whisper_once("x.mp4") + + assert order == ["gate", "model", "transcribe"] diff --git a/tests/test_youtube_non_video_urls.py b/tests/test_youtube_non_video_urls.py new file mode 100644 index 0000000..ae90860 --- /dev/null +++ b/tests/test_youtube_non_video_urls.py @@ -0,0 +1,81 @@ +"""A search, playlist or channel URL never reaches yt-dlp. + +``noplaylist`` only strips the ``list=`` off a ``watch`` link; a +``results?search_query=`` or a bare ``/playlist`` is still walked entry by +entry. In the prod container on 17-sep-2026 one search URL held the probe +for 2220 s and failed on an entry that "premieres in 4 days", having paid +the per-GB proxy three times that day for the same nothing. +""" +import sys +import types + +import pytest + +from yt_clients import NotASingleVideo, youtube_non_video_reason + + +@pytest.mark.parametrize("url", [ + "https://www.youtube.com/watch?v=3QFAEqE9-Kk", + "https://www.youtube.com/watch?v=3QFAEqE9-Kk&list=PLArw552Yzuwn&rco=1", + "https://youtu.be/e6hD7QHib3I?si=GrijVOWTpP9BwZ7b", + "https://m.youtube.com/watch?v=abc", + "https://www.youtube.com/shorts/abc123", + "https://www.youtube.com/live/abc123", + "https://www.youtube.com/embed/abc123", + "https://vimeo.com/12345", + "https://cdn.example.com/video.mp4", +]) +def test_single_videos_and_foreign_hosts_pass(url): + assert youtube_non_video_reason(url) is None + + +@pytest.mark.parametrize("url, word", [ + ("https://www.youtube.com/results?search_query=GAlatins+6", "search"), + ("https://www.youtube.com/results", "search"), + ("https://www.youtube.com/playlist?list=PLArw552Yzuwn", "playlist"), + ("https://www.youtube.com/@openshorts", "channel"), + ("https://www.youtube.com/channel/UCabc", "channel"), + ("https://www.youtube.com/c/openshorts/videos", "channel"), + ("https://www.youtube.com/user/openshorts", "channel"), + ("https://www.youtube.com/feed/subscriptions", "no video"), + ("https://www.youtube.com/", "no video"), + ("https://www.youtube.com/watch", "without a video id"), + ("https://youtu.be/", "without a video id"), +]) +def test_pages_that_are_not_one_video_are_named(url, word): + assert word in youtube_non_video_reason(url) + + +class TestTheProbeRefusesBeforeAnyRequest: + def test_no_ytdlp_call_and_no_paid_event(self, monkeypatch): + metering = pytest.importorskip("cloud.metering") + import security_utils + monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u) + monkeypatch.setenv("STATIC_PROXY_URLS", "http://s1") + monkeypatch.setenv("PROXY_URL", "http://paid") + calls = [] + + class _YDL: + def __init__(self, opts): + calls.append(opts) + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def extract_info(self, url, download=False): + return {"duration": 1} + + monkeypatch.setitem(sys.modules, "yt_dlp", types.SimpleNamespace(YoutubeDL=_YDL)) + monkeypatch.setattr(metering, "_ffprobe_url_seconds", + lambda url, timeout=30: (_ for _ in ()).throw(AssertionError("ffprobe ran"))) + metering.pop_paid_probe_events() + + with pytest.raises(NotASingleVideo) as exc: + metering.probe_url_minutes("https://www.youtube.com/results?search_query=GAlatins+6") + + assert "search" in str(exc.value) + assert calls == [] + assert metering.pop_paid_probe_events() == [] diff --git a/transcribe_backends.py b/transcribe_backends.py index 405f8e8..6dd0f85 100644 --- a/transcribe_backends.py +++ b/transcribe_backends.py @@ -27,6 +27,7 @@ with other models on the host, so loads can OOM under load). """ import os import subprocess +import sys import tempfile import threading import time @@ -49,7 +50,8 @@ PARAKEET_LANGS = { # 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"))) +_ASR_SLOTS = int(os.environ.get("ASR_GPU_CONCURRENCY", "1")) +_ASR_GATE = threading.Semaphore(_ASR_SLOTS) class _NullGate: @@ -114,10 +116,17 @@ def _get_whisper_model(): return _whisper_model, cfg["device"] +def _whisper_device(): + return "cpu" if _whisper_force_cpu else get_whisper_config()["device"] + + def _run_whisper_once(media_path, **params): - model, device = _get_whisper_model() - gate = _ASR_GATE if device != "cpu" else _NULL_GATE + gate = _ASR_GATE if _whisper_device() != "cpu" else _NULL_GATE + # The model is fetched inside the gate: release_models() drains the gate + # before unloading, so a transcription can never start on a model that is + # being dropped underneath it. with gate: + model, _device = _get_whisper_model() segments, info = model.transcribe(media_path, **params) progress = _TranscribeProgress(getattr(info, "duration", 0)) materialized = [] @@ -199,6 +208,54 @@ def _get_parakeet_model(): return _parakeet_model +def release_models(): + """Drop the resident ASR models and hand their VRAM back to the GPU. + + main.py runs one job per process, so its singletons die with the job. + The API process is different: ``/api/subtitle`` on a dubbed clip and the + thumbnail studio transcribe in-process, and after the first such request + the models sit in the long-lived uvicorn process for good. Measured in + prod on 17-sep-2026: the API held 7.7 GB of a 20 GB GPU while idle + (ctranslate2 whisper + onnxruntime CUDA parakeet + torch), and with eight + jobs running alongside it NVENC could not open a session ("Generic error + in an external library", exit 187, 0 bytes) and TransNetV2 hit CUDA OOM: + 5 of 12 jobs failed. The API calls this after each in-process + transcription; a job process never needs to. + + Drains every gate slot first, so no transcription is mid-decode on the + model being dropped, and both loaders fetch their model inside the gate. + """ + global _whisper_model, _whisper_key, _parakeet_model + for _ in range(_ASR_SLOTS): + _ASR_GATE.acquire() + try: + with _whisper_lock: + whisper, _whisper_model, _whisper_key = _whisper_model, None, None + with _parakeet_lock: + parakeet, _parakeet_model = _parakeet_model, None + finally: + for _ in range(_ASR_SLOTS): + _ASR_GATE.release() + if whisper is not None: + try: + # ctranslate2 frees the weights on unload, not on garbage + # collection: the Python wrapper can outlive the last reference. + whisper.model.unload_model() + except Exception as e: + print(f"⚠️ [ASR] whisper unload failed ({type(e).__name__}: {e})") + del whisper, parakeet + import gc + gc.collect() + try: + import torch + if torch.cuda.is_available(): + torch.cuda.empty_cache() + except Exception: + pass + if "onnxruntime" in sys.modules or "faster_whisper" in sys.modules: + print("🧹 [ASR] resident models released") + + 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_") @@ -248,7 +305,6 @@ def _words_from_tokens(tokens, timestamps, seg_start, seg_end): def _transcribe_with_parakeet(media_path): - model = _get_parakeet_model() wav_path = _extract_wav(media_path) try: # 16kHz mono s16le wav -> 32000 bytes per second of audio. @@ -257,6 +313,7 @@ def _transcribe_with_parakeet(media_path): except OSError: duration = 0.0 with _ASR_GATE: + model = _get_parakeet_model() # inside the gate: see release_models progress = _TranscribeProgress(duration) results = [] for seg in model.recognize(wav_path): diff --git a/yt_clients.py b/yt_clients.py index 459e8fc..5b39042 100644 --- a/yt_clients.py +++ b/yt_clients.py @@ -24,6 +24,51 @@ first is "unsupported", the second is skipped whenever cookies are present. HD_CLIENTS = ["default", "mweb"] +class NotASingleVideo(ValueError): + """The URL is a YouTube page that is not one video (search, playlist, + channel). Raised before yt-dlp ever sees it, by the probe and the + download alike.""" + + +def youtube_non_video_reason(url): + """Why this YouTube URL is not a single video, or None if it is one. + + A search page or a bare playlist is walked entry by entry by yt-dlp even + with ``noplaylist`` (that option only strips the ``list=`` off a + ``watch`` link). Measured in the prod container on 17-sep-2026: a + ``results?search_query=`` URL held the probe's executor thread for + 2220 s and still failed on an entry that "premieres in 4 days", after + the same URL had paid the per-GB proxy three times in a day. So the + check is by path, up front and free: nothing that is not one video is + worth a single request. + """ + from urllib.parse import urlparse, parse_qs + try: + parts = urlparse(url or "") + except ValueError: + return None + host = (parts.hostname or "").lower() + if host == "youtu.be": + return None if parts.path.strip("/") else "youtu.be link without a video id" + if not (host == "youtube.com" or host.endswith(".youtube.com")): + return None + path = parts.path.rstrip("/") or "/" + if path == "/watch": + return None if parse_qs(parts.query).get("v") else "a watch page without a video id" + first = path.split("/")[1] if path != "/" else "" + if first in ("shorts", "live", "embed", "v", "e"): + return None + if first == "results": + return "a search results page, not a video" + if first == "playlist": + return "a playlist, not a video; open one video in it and paste that link" + if first.startswith("@") or first in ("channel", "c", "user"): + return "a channel page, not a video" + if first in ("feed", "", "gaming", "music"): + return "a YouTube page with no video in it" + return None + + def pot_provider_args(bgutil_http, bgutil_script): """Extractor args selecting the PO token provider (bgutil http or script).""" if bgutil_http: