AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(youtube): stop paying ScrapeCreators for transcripts yt-dlp can fetch (#1319)
Matt Van Horn0819ea59718d
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex d929358e..88d44b8e 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -205,7 +205,7 @@ The source table covers the engine's research sources and optional comment or trYOUTUBE_PROXY=socks5://127.0.0.1:1080```-**YouTube transcript tuning.** `LAST30DAYS_YT_SUB_LANGS` controls the comma-separated caption-language priority passed to yt-dlp and defaults to `en,es,pt`. The ScrapeCreators transcript fallback tries at most the first three distinct languages in that order, with a shared 30-second deadline per video; it stops after the first usable transcript. `LAST30DAYS_YT_PLAYER_CLIENT` defaults to `android` so yt-dlp can pass YouTube's web bot-gate without cookies (search, transcripts, and comments); set it empty to disable. When `SCRAPECREATORS_API_KEY` is available, yt-dlp uses one fast attempt before the paid fallback; set `LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT` to the number of seconds allowed for that attempt when a throttled host needs longer than the 12-second default. A VTT completed before the timeout is reused rather than discarded. `LAST30DAYS_YT_SEARCH_TIMEOUT` sets the per-search yt-dlp deadline (default 120s). Comparison-mode fan-out also caps concurrent yt-dlp processes process-wide and caches identical searches within a run so redundant `ytsearch` calls do not self-throttle the same IP.+**YouTube transcript tuning.** `LAST30DAYS_YT_SUB_LANGS` controls the comma-separated caption-language priority passed to yt-dlp and defaults to `en,es,pt`. yt-dlp asks for uploaded subtitles as well as auto captions, and requests each language's original-speech track first (`en-orig,en,es-orig,es,...`), so auto-dubbed videos whose plain track is rate-limited still get a free transcript; when both tracks download, the plain one (the uploaded subtitle, if any) is used. The ScrapeCreators transcript fallback tries at most the first three distinct languages in that order, with a shared 30-second deadline per video; it stops after the first usable transcript. `LAST30DAYS_YT_PLAYER_CLIENT` defaults to `android` so yt-dlp can pass YouTube's web bot-gate without cookies (search, transcripts, and comments); set it empty to disable. When `SCRAPECREATORS_API_KEY` is available, yt-dlp uses one fast attempt before the paid fallback; set `LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT` to the number of seconds allowed for that attempt when a throttled host needs longer than the 12-second default, and `LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS` (default `1`) to give yt-dlp more tries before the paid fallback. Set `LAST30DAYS_YOUTUBE_BACKEND=yt-dlp` to keep YouTube entirely on yt-dlp while the key still serves other sources: no ScrapeCreators YouTube search, transcript, or comment calls, and yt-dlp gets the keyless retry budget. Once a run's research budget is spent, a YouTube lane still finishing in the background makes no ScrapeCreators calls. A VTT completed before the timeout is reused rather than discarded. `LAST30DAYS_YT_SEARCH_TIMEOUT` sets the per-search yt-dlp deadline (default 120s). Comparison-mode fan-out also caps concurrent yt-dlp processes process-wide and caches identical searches within a run so redundant `ytsearch` calls do not self-throttle the same IP.**YouTube search backfill.** With `SCRAPECREATORS_API_KEY` set, `LAST30DAYS_YT_SC_MIN_ITEMS` defaults to `3`: a yt-dlp search returning 0, 1, or 2 videos makes one ScrapeCreators search per stream attempt. Set `0` for the previous empty-only behavior, or another positive integer to change the floor. An invalid value behaves like `0`, so a typo does not increase paid usage. Each backfill can also fetch transcripts for up to 6 videos at default depth (up to 3 language requests per video); endpoint retries and optional comment enrichment can add calls. A later thin-source retry may run another backfill. Free results and their transcripts remain in the merged result. A clean thin result records backfill detail; actual yt-dlp or ScrapeCreators failures mark partial coverage if retry does not recover.@@ -609,6 +609,7 @@ Every live run writes its JSON result to `~/.config/last30days/doctor-cache.json| `BROWSER_CDP_URL` | Explicit Chrome DevTools endpoint (e.g. `http://127.0.0.1:18800`) for the extra-host CDP cookie lookup. Preferred over the `18800` / `9222`+`$DISPLAY` defaults. Extra hosts only; setting an endpoint does not grant browser-cookie consent. || `LAST30DAYS_REDDIT_BACKEND` | `scrapecreators` makes ScrapeCreators the primary Reddit backend; doctor renders Reddit's conditional routing with the pin applied. || `LAST30DAYS_REDDIT_SC_MIN_ITEMS` | Integer thinness floor for ScrapeCreators Reddit **search** backfill. Default `5`: backfill when the free path returns fewer than 5 items, spending ScrapeCreators credits. Set another positive count to move the floor, or `0` to backfill only when the free path returns nothing. Unset or blank means `5`; a malformed value behaves like `0` (spends nothing extra). A run makes at most one ScrapeCreators Reddit backfill per distinct query, date window, and subreddit set, and each backfill is several API calls (searches plus comment fetches, roughly 10 at default depth). A failed backfill after free items only adds a detail note. Merged results dedupe by post id. Requires `SCRAPECREATORS_API_KEY`. Ignored when `LAST30DAYS_REDDIT_BACKEND=scrapecreators` (SC is already primary). |+| `LAST30DAYS_YOUTUBE_BACKEND` | `yt-dlp` keeps YouTube off ScrapeCreators (search backfill, transcript rescue, and comments) while `SCRAPECREATORS_API_KEY` still serves TikTok, Instagram, and Reddit; yt-dlp then uses the keyless retry budget. Unset or any other value keeps the default yt-dlp → ScrapeCreators chain. Doctor shows the pin and the disarmed backstop. || `LAST30DAYS_YT_SC_MIN_ITEMS` | Keyed YouTube search backfill floor. Default `3`; `0` restores empty-only search fallback. Invalid values behave like `0`. See [YouTube search backfill](#youtube-search-backfill) for per-stream credit usage and retry behavior. |Web search has **no** env pin — pin it per-run with `--web-backend=<name>` only (see [Web search backend priority](#web-search-backend-priority)).diff --git a/changelog.d/1313.fixed.md b/changelog.d/1313.fixed.mdnew file mode 100644index 00000000..cd6afc1f--- /dev/null+++ b/changelog.d/1313.fixed.md@@ -0,0 +1 @@+YouTube transcripts now request uploaded subtitles alongside auto captions, so videos with manual subtitles and no auto track get a free yt-dlp transcript instead of falling through to a paid ScrapeCreators rescue.diff --git a/changelog.d/1314.fixed.md b/changelog.d/1314.fixed.mdnew file mode 100644index 00000000..eb63e54e--- /dev/null+++ b/changelog.d/1314.fixed.md@@ -0,0 +1 @@+yt-dlp now asks for each caption language's original-speech track first (`en-orig,en,...`), so auto-dubbed videos whose plain track returns HTTP 429 keep a free transcript. The ScrapeCreators fallback sends plain language codes.diff --git a/changelog.d/1315.fixed.md b/changelog.d/1315.fixed.mdnew file mode 100644index 00000000..745356be--- /dev/null+++ b/changelog.d/1315.fixed.md@@ -0,0 +1 @@+A YouTube lane still running after the research budget ran out no longer spends ScrapeCreators credits on search, transcripts, or comments, and an interpreter-shutdown error is no longer treated as an empty yt-dlp result. The ScrapeCreators YouTube search also stops buying transcripts once it reaches the depth's target.diff --git a/changelog.d/1316.added.md b/changelog.d/1316.added.mdnew file mode 100644index 00000000..e834e57b--- /dev/null+++ b/changelog.d/1316.added.md@@ -0,0 +1 @@+`LAST30DAYS_YOUTUBE_BACKEND=yt-dlp` keeps YouTube on yt-dlp only, with the keyless retry budget, while `SCRAPECREATORS_API_KEY` keeps serving other sources. `LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS` sets how many keyed yt-dlp transcript attempts run before the paid fallback (default 1).diff --git a/skills/last30days/scripts/lib/backends.py b/skills/last30days/scripts/lib/backends.pyindex 4a8e553d..aad487b6 100644--- a/skills/last30days/scripts/lib/backends.py+++ b/skills/last30days/scripts/lib/backends.py@@ -138,8 +138,10 @@ class ChainDescriptor:source: strmode: strbackends: Tuple[BackendSpec, ...]- pin_var: Optional[str] = None # env var pin (X, Reddit)+ pin_var: Optional[str] = None # env var pin (X, Reddit, YouTube)pin_flag: Optional[str] = None # CLI flag pin (web: --web-backend)+ # Env pin values the runtime honors; None means any backend name.+ pin_values: Optional[Tuple[str, ...]] = None@dataclass@@ -538,7 +540,8 @@ DESCRIPTORS: Dict[str, ChainDescriptor] = {),_SC_SPEC,),- pin_var=None, # no YouTube pin knob exists+ pin_var=env.YOUTUBE_BACKEND_PIN_VAR,+ pin_values=env.YOUTUBE_BACKEND_PIN_VALUES,),"web": ChainDescriptor(source="web",@@ -678,8 +681,14 @@ def _resolve_alternative(if pin and pin not in ("auto", "none") and pin in by_name:pin_name = pinelif descriptor.pin_var:- raw = (config.get(descriptor.pin_var) or "").lower()- if raw in by_name:+ if descriptor.pin_var == env.YOUTUBE_BACKEND_PIN_VAR:+ # Same spelling rules as the runtime gate (strip, "ytdlp" alias).+ raw = env.youtube_backend_pin(config)+ else:+ raw = (config.get(descriptor.pin_var) or "").lower()+ if raw in by_name and (+ descriptor.pin_values is None or raw in descriptor.pin_values+ ):pin_name = rawif pin_name:diff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.pyindex 0ea81d09..29c7e1ed 100644--- a/skills/last30days/scripts/lib/doctor.py+++ b/skills/last30days/scripts/lib/doctor.py@@ -1168,7 +1168,8 @@ def _sub_lanes_for(source: str, config: Dict[str, Any]):backups.append({"name": "ScrapeCreators backfill", "armed": has_sc, "note": note})elif source == "youtube":backups.append({- "name": "ScrapeCreators transcript/search backstop", "armed": has_sc,+ "name": "ScrapeCreators transcript/search backstop",+ "armed": env.is_youtube_sc_available(config),"note": "used when yt-dlp is rate-limited or bot-gated",})comments = {"enabled": bool(env.is_youtube_comments_available(config))}@@ -1681,6 +1682,7 @@ _SECRET_CONFIG_VARS = KEY_PRESENCE_VARS + (_FINGERPRINT_PIN_VARS = (env.X_BACKEND_PIN_VAR,env.REDDIT_BACKEND_PIN_VAR,+ env.YOUTUBE_BACKEND_PIN_VAR,env.X_HOST_VAR,env.X_HOST_LANE_VAR,)diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex d02c0059..b9a6b043 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -620,6 +620,7 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:('LAST30DAYS_X_MODEL', None),('LAST30DAYS_X_BACKEND', None),('LAST30DAYS_REDDIT_BACKEND', None),+ ('LAST30DAYS_YOUTUBE_BACKEND', None),# Keyless reddit.com token-bucket rate (req/sec). http.py reads it# from os.environ on each acquire, so .env values are exported below.('LAST30DAYS_REDDIT_KEYLESS_RATE', None),@@ -757,6 +758,7 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:# applied there when the key is absent. Empty disables.('LAST30DAYS_YT_PLAYER_CLIENT', None),('LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT', None),+ ('LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS', None),('LAST30DAYS_YT_SEARCH_TIMEOUT', None),('GITHUB_TOKEN', None),# Host self-identification. `grok-bot` switches the X policy@@ -802,6 +804,7 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:for key in ('LAST30DAYS_YT_SUB_LANGS','LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT',+ 'LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS','LAST30DAYS_YT_SEARCH_TIMEOUT','LAST30DAYS_REDDIT_KEYLESS_RATE','LAST30DAYS_YT_PLAYER_CLIENT',@@ -1358,6 +1361,10 @@ X_BACKEND_KNOWN = _X_BACKEND_KNOWNX_OFFICIAL = _X_OFFICIALX_BACKEND_PIN_VAR = 'LAST30DAYS_X_BACKEND'REDDIT_BACKEND_PIN_VAR = 'LAST30DAYS_REDDIT_BACKEND'+# `yt-dlp` keeps YouTube off ScrapeCreators while the key still serves other+# sources (#1316). It is the only pin value; anything else means auto.+YOUTUBE_BACKEND_PIN_VAR = 'LAST30DAYS_YOUTUBE_BACKEND'+YOUTUBE_BACKEND_PIN_VALUES = ('yt-dlp',)REDDIT_SC_MIN_ITEMS_VAR = 'LAST30DAYS_REDDIT_SC_MIN_ITEMS'# Keyed runs backfill Reddit from ScrapeCreators when the free path returns# fewer than this many items. Thin topics yield 2-3 free results; healthy@@ -1630,7 +1637,7 @@ def is_youtube_comments_available(config: dict[str, Any]) -> bool:return Falseif is_ytdlp_available():return True- if not config.get('SCRAPECREATORS_API_KEY'):+ if not is_youtube_sc_available(config):return Falsereturn 'youtube_comments' in _parse_include_sources(config)@@ -1661,11 +1668,23 @@ def is_instagram_comments_available(config: dict[str, Any]) -> bool:return 'instagram_comments' in _parse_include_sources(config)+def youtube_backend_pin(config: dict[str, Any]) -> str:+ """The normalized ``LAST30DAYS_YOUTUBE_BACKEND`` pin ("" when unset or unknown)."""+ raw = (config.get(YOUTUBE_BACKEND_PIN_VAR) or '').strip().lower()+ if raw == 'ytdlp':+ raw = 'yt-dlp'+ return raw if raw in YOUTUBE_BACKEND_PIN_VALUES else ''++def is_youtube_sc_available(config: dict[str, Any]) -> bool:- """Check if ScrapeCreators YouTube search fallback is available.+ """Check if the YouTube lane may spend ScrapeCreators credits.- Used when yt-dlp is not installed or fails.+ Gates the SC search fallback, the per-video transcript rescue, and SC+ comments. False without a key, or when ``LAST30DAYS_YOUTUBE_BACKEND=yt-dlp``+ keeps YouTube keyless while the key still serves other sources."""+ if youtube_backend_pin(config) == 'yt-dlp':+ return Falsereturn bool(config.get('SCRAPECREATORS_API_KEY'))diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex fff8bfd0..c6c2b2fd 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -5424,7 +5424,36 @@ def _fetch_youtube_stream(freshness_mode: str | None = None,) -> tuple[list[dict], dict]:"""Search, backfill, transcribe, and comment-enrich one YouTube query."""+ # An abandoned lane keeps running after the report is saved; once the+ # run is over, every ScrapeCreators call in it is wasted credit (#1315).+ with youtube_yt.sc_spend_until(+ lambda: _research_stopped(config),+ cancel=config.get("_enrich_cancel"),+ deadline=config.get("_research_deadline"),+ ):+ return _fetch_youtube_stream_live(+ yt_query, from_date, to_date, depth, config,+ has_ytdlp=has_ytdlp, freshness_mode=freshness_mode,+ )+++def _interpreter_shutting_down(exc: BaseException) -> bool:+ """An abandoned lane outliving main() can no longer start thread pools."""+ return isinstance(exc, RuntimeError) and "interpreter shutdown" in str(exc)+++def _fetch_youtube_stream_live(+ yt_query: str,+ from_date: str,+ to_date: str,+ depth: str,+ config: dict[str, Any],+ *,+ has_ytdlp: bool,+ freshness_mode: str | None,+) -> tuple[list[dict], dict]:result = None+ run_over = Falseyoutube_failure: str | None = Nonerecovered_failure: str | None = None# ScrapeCreators key (when present) is the default-on backup tier: it@@ -5446,13 +5475,16 @@ def _fetch_youtube_stream(except Exception as exc:youtube_failure = str(exc)result = None+ # Not an empty yt-dlp result: the process is exiting.+ run_over = _interpreter_shutting_down(exc)+ run_over = run_over or _research_stopped(config)free_items = list((result or {}).get("items") or [])min_items = env.youtube_sc_min_items(config)backfill_thin = bool(free_items) and len(free_items) < min_itemsthin_detail: str | None = Nonethin_error = Falsethin_retryable = False- if (not free_items or backfill_thin) and sc_token:+ if (not free_items or backfill_thin) and sc_token and not run_over:backfill_scope = (http.capture_failures() if free_items else contextlib.nullcontext([]))@@ -5525,9 +5557,7 @@ def _fetch_youtube_stream(# Enrich top videos with comments (default-on when a key is present).items = youtube_yt.parse_youtube_response(result)if items and env.is_youtube_comments_available(config):- youtube_yt.enrich_with_comments(- items, token=config.get("SCRAPECREATORS_API_KEY", ""),- )+ youtube_yt.enrich_with_comments(items, token=sc_token or "")if thin_detail:if not thin_error:return items, {"_source_outcome_detail": thin_detail}diff --git a/skills/last30days/scripts/lib/youtube_yt.py b/skills/last30days/scripts/lib/youtube_yt.pyindex 50582c04..1e261a2b 100644--- a/skills/last30days/scripts/lib/youtube_yt.py+++ b/skills/last30days/scripts/lib/youtube_yt.py@@ -6,6 +6,8 @@ transcript extraction. No API keys needed — just have yt-dlp installed.Inspired by Peter Steinberger's toolchain approach (yt-dlp + summarize CLI)."""+import contextlib+import contextvarsimport copyimport jsonimport math@@ -20,8 +22,9 @@ import timeimport urllib.errorimport urllib.requestfrom concurrent.futures import ThreadPoolExecutor, as_completed+from dataclasses import dataclassfrom pathlib import Path-from typing import Any, Dict, List, Optional, Set, Tuple+from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple# Depth configurations: how many videos to search / transcribeDEPTH_CONFIG = {@@ -162,6 +165,68 @@ def _log(msg: str):log.source_log("YouTube", msg, tty_only=False)+# The research run's stop state, set by the pipeline for the YouTube lane:+# ``stopped()`` is True once the run is over (deadline passed or cancelled),+# and ``cancel``/``deadline`` bound each paid request and its retries to the+# same moment. An abandoned lane keeps running after the report is saved, and+# every ScrapeCreators call it made then was a paid result nobody would read+# (#1315). Pool workers inherit it through http.submit_with_context.+@dataclass(frozen=True)+class _SCSpendLimit:+ stopped: Callable[[], bool]+ cancel: Optional[threading.Event] = None+ deadline: Optional[float] = None+++_sc_spend_limit: contextvars.ContextVar[Optional[_SCSpendLimit]] = (+ contextvars.ContextVar("youtube_sc_spend_limit", default=None)+)+++def sc_spend_until(+ stopped: Callable[[], bool],+ *,+ cancel: Optional[threading.Event] = None,+ deadline: Optional[float] = None,+) -> Iterator[None]:+ """Refuse ScrapeCreators YouTube calls in this context once ``stopped()``.++ ``cancel`` and ``deadline`` (monotonic) also cut off a request, or its+ retries, that is still running when the run ends.+ """+ token = _sc_spend_limit.set(_SCSpendLimit(stopped, cancel, deadline))+ try:+ yield+ finally:+ _sc_spend_limit.reset(token)+++def _sc_spend_blocked(what: str) -> bool:+ """True (and logged) when the run is over and ``what`` must not be paid for."""+ limit = _sc_spend_limit.get()+ if limit is None or not limit.stopped():+ return False+ _log(f"Skipping ScrapeCreators {what}: the research run is over")+ return True+++def _sc_request_bounds(deadline: Optional[float] = None) -> Dict[str, Any]:+ """``http.get`` kwargs that stop a paid request when the research run ends.++ ``deadline`` is the caller's own monotonic deadline, if any; the earlier+ of it and the run's deadline wins.+ """+ limit = _sc_spend_limit.get()+ bounds: Dict[str, Any] = {}+ deadlines = [d for d in (deadline, limit.deadline if limit else None) if d is not None]+ if deadlines:+ bounds["deadline_monotonic"] = min(deadlines)+ if limit is not None and limit.cancel is not None:+ bounds["cancel"] = limit.cancel+ return bounds++def reset_search_cache() -> None:"""Clear the in-run ytsearch cache.@@ -816,7 +881,7 @@ def _fetch_transcript_ytdlp_via_ssh(video_id: str, ssh_host: str) -> Optional[streturn Noneurl = f"https://www.youtube.com/watch?v={video_id}"quoted_url = shlex.quote(url)- sub_langs = shlex.quote(_ytdlp_sub_langs())+ sub_langs = shlex.quote(_ytdlp_request_langs())client = _ytdlp_player_client()extractor = (f"--extractor-args {shlex.quote(f'youtube:player_client={client}')} "@@ -831,7 +896,7 @@ def _fetch_transcript_ytdlp_via_ssh(video_id: str, ssh_host: str) -> Optional[st"yt-dlp --ignore-config --no-cookies-from-browser "f"{extractor}"f"{proxy_flag}"- f"--write-auto-subs --sub-lang {sub_langs} --sub-format vtt "+ f"--write-subs --write-auto-subs --sub-lang {sub_langs} --sub-format vtt ""--skip-download --no-warnings "f'-o "$TMPD/%(id)s" {quoted_url} >/dev/null 2>&1 || true; ''VTT=$(find "$TMPD" -maxdepth 1 -name "*.vtt" 2>/dev/null | head -1); '@@ -867,6 +932,25 @@ def _ytdlp_sub_langs() -> str:return ",".join(code.strip().lower() for code in raw.split(",") if code.strip()) or "en,es,pt"+def _ytdlp_request_langs() -> str:+ """The ``--sub-lang`` value: each configured language as ``<lang>-orig,<lang>``.++ Auto-dubbed videos expose the original-speech auto track as+ ``<lang>-orig``, and their plain ``<lang>`` track can 429 every time while+ ``-orig`` downloads (#1314). yt-dlp downloads languages in order and stops+ at the first error, so ``-orig`` has to come first; the partial-VTT salvage+ keeps it when the plain track then fails. yt-dlp skips languages a video+ does not have, so non-dubbed videos are unaffected.+ """+ langs: List[str] = []+ for code in _ytdlp_sub_langs().split(","):+ variants = [code] if code.endswith("-orig") else [f"{code}-orig", code]+ for variant in variants:+ if variant not in langs:+ langs.append(variant)+ return ",".join(langs)++def _transcript_fast_timeout() -> float:"""Return the keyed-run yt-dlp timeout, preserving the 12s default."""return _env_positive_float(@@ -874,18 +958,35 @@ def _transcript_fast_timeout() -> float:float(_TRANSCRIPT_FAST_TIMEOUT),)++def _transcript_fast_attempts() -> int:+ """Return keyed-run yt-dlp attempts before the SC rescue (default 1, #1316)."""+ raw = os.environ.get("LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS", "").strip()+ try:+ value = int(raw)+ except ValueError:+ return 1+ return value if value > 0 else 1+def _pick_ytdlp_vtt(video_id: str, temp_dir: str, priority: List[str]) -> Optional[Path]:"""Return the best on-disk VTT match for video_id, preferring priority order."""matches = list(Path(temp_dir).glob(f"{video_id}*.vtt"))if not matches:return None- priority_index = {code: i for i, code in enumerate(priority)}+ # A configured "en-orig" ranks as "en": files are matched by base code.+ priority_index: Dict[str, int] = {}+ for code in priority:+ priority_index.setdefault(code.removesuffix("-orig"), len(priority_index))- def rank(p: Path) -> int:+ def rank(p: Path) -> Tuple[int, int]:stem = p.stemsuffix = stem[len(video_id) + 1:] if stem.startswith(video_id + ".") else ""code = suffix.split("-")[0].split(".")[0]- return priority_index.get(code, len(priority_index))+ # Within one language, a plain track that downloaded wins: it is the+ # uploaded subtitle when one exists, and otherwise the same speech+ # recognition as -orig. The -orig file is the fallback for when the+ # plain track 429s (#1314).+ return (priority_index.get(code, len(priority_index)), 1 if suffix.endswith("-orig") else 0)return sorted(matches, key=rank)[0]@@ -931,7 +1032,8 @@ def _fetch_transcript_ytdlp(fast_fail: When True, a ScrapeCreators fallback is available, so atransient failure (429 / bot-gate) should fail over fast ratherthan retry into the same rate limit. Collapses to a single attempt- with a shorter per-attempt timeout. The slow thing in a run is+ (``LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS`` raises it) with a+ shorter per-attempt timeout. The slow thing in a run isyt-dlp retrying, not the fast SC fetch, so this is what keeps"yt-dlp first" from reintroducing the multi-minute hang.@@ -943,8 +1045,12 @@ def _fetch_transcript_ytdlp("yt-dlp","--ignore-config","--no-cookies-from-browser",+ # --write-subs: a video with uploaded subtitles and no auto track+ # otherwise exits 0 with no file and falls through to paid SC (#1313).+ # yt-dlp prefers the uploaded track when both exist for a language.+ "--write-subs","--write-auto-subs",- "--sub-lang", _ytdlp_sub_langs(),+ "--sub-lang", _ytdlp_request_langs(),"--sub-format", "vtt","--skip-download","--no-warnings",@@ -957,7 +1063,7 @@ def _fetch_transcript_ytdlp(cmd = list(cmd) + ["--proxy", proxy]timeout = _transcript_fast_timeout() if fast_fail else _TRANSCRIPT_TIMEOUT- attempts = 1 if fast_fail else _TRANSCRIPT_MAX_RETRIES + 1+ attempts = _transcript_fast_attempts() if fast_fail else _TRANSCRIPT_MAX_RETRIES + 1last_reason: Optional[str] = Nonefor attempt in range(attempts):try:@@ -1557,7 +1663,7 @@ def _fetch_video_comments(if ran_cleanly:return []- if not token:+ if not token or _sc_spend_blocked(f"comments for {video_id}"):return []video_url = f"https://www.youtube.com/watch?v={video_id}"@@ -1568,6 +1674,7 @@ def _fetch_video_comments(headers=http.scrapecreators_headers(token),timeout=30,retries=2,+ **_sc_request_bounds(),)except Exception as exc:_log(f"Comment fetch error for {video_id}: {exc}")@@ -1712,11 +1819,18 @@ def search_youtube_sc(]attempt_count = min(len(transcript_candidates), transcript_limit * 3)_log(f"Fetching SC transcripts for up to {attempt_count} videos (target: {transcript_limit})")+ got = 0for item in transcript_candidates[:attempt_count]:+ # Each attempt is paid: stop once the target is met. The 3x+ # headroom is only for videos that come back without captions.+ if got >= transcript_limit:+ breakvid = item["video_id"]if not vid:continuetranscript = _sc_fetch_transcript(vid, token)+ if transcript:+ got += 1item["transcript_snippet"] = transcript or ""item["transcript_highlights"] = extract_transcript_highlights(transcript or "", core_topic,@@ -1740,6 +1854,8 @@ def _sc_youtube_search(keyword: str, token: str) -> List[Dict[str, Any]]:Returns:List of raw video dicts from the API."""+ if _sc_spend_blocked(f"search for {keyword!r}"):+ return []try:# SC's /v1/youtube/search rejects ?keyword= with HTTP 400; the canonical# parameter for that endpoint is `query`. Other SC endpoints use their@@ -1750,6 +1866,7 @@ def _sc_youtube_search(keyword: str, token: str) -> List[Dict[str, Any]]:headers=http.scrapecreators_headers(token),timeout=30,retries=2,+ **_sc_request_bounds(),)return data.get("videos", data.get("data", data.get("items", [])))except Exception as exc:@@ -1791,14 +1908,23 @@ def _sc_fetch_transcript(video_id: str, token: str) -> Optional[str]:Returns:Plaintext transcript string, or None if unavailable."""+ if _sc_spend_blocked(f"transcript for {video_id}"):+ return Nonevideo_url = f"https://www.youtube.com/watch?v={video_id}"transcript = Nonedeadline = time.monotonic() + _SC_TRANSCRIPT_TIMEOUT# Without a language the endpoint may return an auto-dubbed track (#1169).- languages = list(dict.fromkeys(_ytdlp_sub_langs().split(",")))[:_SC_TRANSCRIPT_MAX_LANGUAGES]+ # SC takes plain codes; a configured `en-orig` means `en` here (#1314).+ languages = list(dict.fromkeys(+ code.removesuffix("-orig") for code in _ytdlp_sub_langs().split(",")+ ))[:_SC_TRANSCRIPT_MAX_LANGUAGES]for language in languages:if time.monotonic() >= deadline:break+ # The run can end while an earlier language is in flight; don't+ # buy the next one.+ if language != languages[0] and _sc_spend_blocked(f"transcript for {video_id}"):+ return Nonetry:# Isolate SC transcript fetch errors from the pipeline-level# capture_failures() context.@@ -1810,8 +1936,8 @@ def _sc_fetch_transcript(video_id: str, token: str) -> Optional[str]:timeout=_SC_TRANSCRIPT_TIMEOUT,retries=1,max_429_retries=0,- deadline_monotonic=deadline,owned_get=True,+ **_sc_request_bounds(deadline),)except Exception as exc:_log(f"SC transcript error for {video_id} ({language}): {exc}")diff --git a/tests/test_backend_descriptors.py b/tests/test_backend_descriptors.pyindex 65fc1502..df6e56aa 100644--- a/tests/test_backend_descriptors.py+++ b/tests/test_backend_descriptors.py@@ -1034,6 +1034,33 @@ class TestYouTubeChain:assert res.active_backend == "scrapecreators"assert res.tier == backends.TIER_OK+ def test_ytdlp_pin_never_fails_over_to_sc(self):+ """#1316: a pinned yt-dlp lane reports its own failure, not SC."""+ config = {"SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_YOUTUBE_BACKEND": "yt-dlp"}+ with mock.patch(+ "lib.health.probe_dependency", _probe_dep({"yt-dlp": health.MISSING}),+ ):+ res = backends.resolve("youtube", config)+ assert res.pinned is True+ assert res.pin == "yt-dlp"+ assert res.active_backend is None+ assert res.tier == backends.TIER_ERROR++ def test_ytdlp_pin_spelling_matches_runtime_gate(self):+ """Doctor reads " YTDLP " as the same pin the runtime honors."""+ config = {"SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_YOUTUBE_BACKEND": " YTDLP "}+ with mock.patch("lib.health.probe_dependency", _probe_dep()):+ res = backends.resolve("youtube", config)+ assert res.pinned is True+ assert res.pin == "yt-dlp"++ def test_scrapecreators_is_not_a_youtube_pin_value(self):+ config = {"SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_YOUTUBE_BACKEND": "scrapecreators"}+ with mock.patch("lib.health.probe_dependency", _probe_dep()):+ res = backends.resolve("youtube", config)+ assert res.pinned is False+ assert res.active_backend == "yt-dlp"+def test_neither_available_error_carries_ytdlp_prescription(self):with mock.patch("lib.health.probe_dependency", _probe_dep({"yt-dlp": health.MISSING}),diff --git a/tests/test_doctor.py b/tests/test_doctor.pyindex caf2f5c4..ccc84e28 100644--- a/tests/test_doctor.py+++ b/tests/test_doctor.py@@ -1392,6 +1392,14 @@ class Postmortem(unittest.TestCase):class BackupAndCommentLanes(unittest.TestCase):"""U7: backup + comment sub-lanes render on their parent source."""+ def test_youtube_pin_disarms_only_the_youtube_backstop(self):+ report = _build({+ "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000",+ "LAST30DAYS_YOUTUBE_BACKEND": "yt-dlp",+ })+ self.assertTrue(report["sources"]["reddit"]["backups"][0]["armed"])+ self.assertFalse(report["sources"]["youtube"]["backups"][0]["armed"])+def test_backups_armed_with_sc_key(self):report = _build({"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"})self.assertTrue(report["sources"]["reddit"]["backups"][0]["armed"])diff --git a/tests/test_youtube_backend_pin.py b/tests/test_youtube_backend_pin.pynew file mode 100644index 00000000..834d4a0a--- /dev/null+++ b/tests/test_youtube_backend_pin.py@@ -0,0 +1,118 @@+"""LAST30DAYS_YOUTUBE_BACKEND=yt-dlp keeps YouTube keyless with a key set (#1316)."""++from pathlib import Path+from unittest import mock++import pytest+from lib import doctor, env, pipeline, schema, youtube_yt++KEYED = {"SCRAPECREATORS_API_KEY": "dummy-key"}+PINNED = {**KEYED, "LAST30DAYS_YOUTUBE_BACKEND": "yt-dlp"}+++def _youtube_stream(config):+ return pipeline._retrieve_stream_impl(+ topic="Vuori",+ subquery=schema.SubQuery(+ label="q", search_query="Vuori", ranking_query="Vuori", sources=["youtube"],+ ),+ source="youtube",+ config=config,+ depth="default",+ date_range=("2026-06-01", "2026-07-01"),+ runtime=schema.ProviderRuntime(+ reasoning_provider="mock", planner_model="mock", rerank_model="mock",+ ),+ mock=False,+ )++[email protected]("value", ["yt-dlp", "YT-DLP", " ytdlp "])+def test_pin_turns_off_youtube_sc_with_key_set(value):+ assert env.is_youtube_sc_available({**KEYED, "LAST30DAYS_YOUTUBE_BACKEND": value}) is False++[email protected]("value", [None, "", "auto", "scrapecreators", "bogus"])+def test_unset_or_unknown_pin_keeps_auto_behavior(value):+ config = {**KEYED, "LAST30DAYS_YOUTUBE_BACKEND": value}+ assert env.youtube_backend_pin(config) == ""+ assert env.is_youtube_sc_available(config) is True+++def test_pinned_without_ytdlp_disables_sc_comments_and_the_source():+ config = {**PINNED, "INCLUDE_SOURCES": "youtube_comments"}+ with mock.patch.object(env, "is_ytdlp_available", return_value=False), \+ mock.patch.object(pipeline, "which", return_value=None):+ assert env.is_youtube_comments_available(config) is False+ assert "youtube" not in pipeline.available_sources(config)+++def test_pinned_stream_makes_no_scrapecreators_calls():+ with (+ mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"),+ mock.patch.object(+ youtube_yt, "search_and_transcribe", return_value={"items": []},+ ) as free_search,+ mock.patch.object(youtube_yt, "search_youtube_sc") as sc_search,+ mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False),+ ):+ items, _artifact = _youtube_stream(dict(PINNED))++ assert items == []+ sc_search.assert_not_called()+ assert free_search.call_args.kwargs["token"] is None+++def test_pinned_stream_enriches_comments_without_the_key():+ free = {"video_id": "a", "title": "Vuori review", "transcript_snippet": "t"}+ with (+ mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"),+ mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": [free]}),+ mock.patch.object(youtube_yt, "search_youtube_sc") as sc_search,+ mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=True),+ mock.patch.object(youtube_yt, "enrich_with_comments") as comments,+ ):+ _youtube_stream(dict(PINNED))++ sc_search.assert_not_called()+ assert comments.call_args.kwargs["token"] == ""+++def test_unpinned_stream_still_passes_the_key_to_comments():+ free = {"video_id": "a", "title": "Vuori review", "transcript_snippet": "t"}+ with (+ mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"),+ mock.patch.object(+ youtube_yt, "search_and_transcribe", return_value={"items": [free] * 3},+ ),+ mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=True),+ mock.patch.object(youtube_yt, "enrich_with_comments") as comments,+ ):+ _youtube_stream(dict(KEYED))++ assert comments.call_args.kwargs["token"] == "dummy-key"+++def test_fast_attempts_override_retries_keyed_fetch(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+):+ monkeypatch.setenv("LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS", "3")+ monkeypatch.setenv("LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT", "")+ status: dict = {}+ with mock.patch.object(+ youtube_yt.subproc, "run_with_timeout", side_effect=youtube_yt.subproc.SubprocTimeout,+ ) as run_mock, mock.patch.object(youtube_yt.time, "sleep"):+ youtube_yt._fetch_transcript_ytdlp("vid", str(tmp_path), status=status, fast_fail=True)++ assert run_mock.call_count == 3+ assert {c.kwargs["timeout"] for c in run_mock.call_args_list} == {12.0}++[email protected]("value", ["", "0", "-1", "abc", "2.5"])+def test_invalid_fast_attempts_keep_one_attempt(value, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS", value)+ assert youtube_yt._transcript_fast_attempts() == 1+++def test_pin_changes_doctor_cache_fingerprint():+ assert doctor._config_fingerprint(dict(KEYED)) != doctor._config_fingerprint(dict(PINNED))diff --git a/tests/test_youtube_backstop.py b/tests/test_youtube_backstop.pyindex 78510143..6778b0d3 100644--- a/tests/test_youtube_backstop.py+++ b/tests/test_youtube_backstop.py@@ -1,3 +1,4 @@+import threadingfrom unittest import mockfrom lib import health, http, pipeline, schema, youtube_yt@@ -87,22 +88,27 @@ def test_backfill_spends_transcript_calls_only_on_missing_or_new_videos():mock.patch.object(youtube_yt, "_sc_youtube_search", return_value=raw_search) as search,mock.patch.object(youtube_yt, "_sc_fetch_transcript",- side_effect=lambda video_id, token: f"paid transcript for {video_id}",+ # new0 has no captions; the headroom moves on to new1 and new2.+ side_effect=lambda video_id, token: (+ None if video_id == "new0" else f"paid transcript for {video_id}"+ ),) as transcripts,mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False),):items, _ = _youtube_stream({"SCRAPECREATORS_API_KEY": "dummy-key"})search.assert_called_once()- assert [call.args[0] for call in transcripts.call_args_list] == video_ids[1:]- assert len(transcripts.call_args_list) == 6+ # Paid calls skip the free-transcribed video and stop at the default-depth+ # target of 2 successes instead of spending all 3x headroom (#1315).+ assert [call.args[0] for call in transcripts.call_args_list] == ["missing", "new0", "new1"]assert [item["video_id"] for item in items] == video_idsassert items[0]["title"] == "free ready"assert items[0]["transcript_snippet"] == "free transcript"assert items[1]["title"] == "free missing"assert items[1]["transcript_snippet"] == "paid transcript for missing"- assert items[-1]["title"] == "SC new4"- assert items[-1]["transcript_snippet"] == "paid transcript for new4"+ assert items[3]["title"] == "SC new1"+ assert items[3]["transcript_snippet"] == "paid transcript for new1"+ assert not items[-1].get("transcript_snippet")def test_keyless_and_disabled_floor_keep_free_results_without_paid_search():@@ -422,3 +428,131 @@ def test_freshness_mode_reaches_both_youtube_searches():assert sc_search.call_count >= 1for call in free_search.call_args_list + sc_search.call_args_list:assert call.kwargs.get("freshness_mode") == "evergreen_ok"+++def _run_ends_during(free_result):+ """A live config whose run is cancelled while yt-dlp is still working.++ The stream starts inside the budget (``_retrieve_stream_impl`` refuses a+ stopped run up front), then the main thread gives up on it, as when the+ lane is abandoned at the stream deadline.+ """+ cancel = threading.Event()+ config = {"SCRAPECREATORS_API_KEY": "dummy-key", "_enrich_cancel": cancel}++ def _free_search(*args, **kwargs):+ cancel.set()+ return free_result(**kwargs) if callable(free_result) else free_result++ return config, _free_search+++def test_abandoned_lane_skips_paid_search_after_the_run_ends():+ """#1315: once the run is over, an empty yt-dlp result buys no SC search."""+ config, free_search = _run_ends_during({"items": []})+ with (+ mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"),+ mock.patch.object(youtube_yt, "search_and_transcribe", side_effect=free_search) as free,+ mock.patch.object(youtube_yt, "search_youtube_sc") as sc_search,+ mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False),+ ):+ items, _ = _youtube_stream(config)++ free.assert_called_once()+ assert items == []+ sc_search.assert_not_called()+++def test_interpreter_shutdown_is_not_an_empty_ytdlp_result():+ """#1315: the straggler's RuntimeError must not trigger a paid search."""+ shutdown = RuntimeError("cannot schedule new futures after interpreter shutdown")+ with (+ mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"),+ mock.patch.object(youtube_yt, "search_and_transcribe", side_effect=shutdown),+ mock.patch.object(youtube_yt, "search_youtube_sc") as sc_search,+ mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False),+ ):+ _youtube_stream({"SCRAPECREATORS_API_KEY": "dummy-key"})++ sc_search.assert_not_called()+++def test_transcript_rescue_inside_an_over_run_spends_nothing():+ """#1315: per-video SC rescue in pool workers sees the stop gate."""+ rescued = {}++ def _transcribe(**kwargs):+ rescued.update(youtube_yt.fetch_transcripts_parallel(["v1", "v2"], token=kwargs["token"]))+ return {"items": []}++ config, free_search = _run_ends_during(_transcribe)+ with (+ mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"),+ mock.patch.object(youtube_yt, "search_and_transcribe", side_effect=free_search),+ mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=False),+ mock.patch.object(youtube_yt, "_fetch_transcript_direct", return_value=None),+ mock.patch.object(youtube_yt.http, "get") as paid_get,+ mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False),+ ):+ _youtube_stream(config)++ assert rescued == {"v1": None, "v2": None}+ paid_get.assert_not_called()+++def test_sc_paid_endpoints_refuse_inside_a_stopped_context():+ with mock.patch.object(youtube_yt.http, "get") as paid_get, \+ mock.patch.object(youtube_yt, "_ytdlp_comments_result", return_value=([], False)), \+ youtube_yt.sc_spend_until(lambda: True):+ assert youtube_yt._sc_youtube_search("vuori", "dummy-key") == []+ assert youtube_yt._sc_fetch_transcript("v1", "dummy-key") is None+ assert youtube_yt._fetch_video_comments("v1", "dummy-key") == []+ paid_get.assert_not_called()+++def test_sc_paid_endpoints_still_spend_while_the_run_is_live():+ with mock.patch.object(+ youtube_yt.http, "get", return_value={"transcript": "live transcript"},+ ) as paid_get, youtube_yt.sc_spend_until(lambda: False):+ assert youtube_yt._sc_fetch_transcript("v1", "dummy-key") == "live transcript"+ paid_get.assert_called_once()+++def test_sc_transcript_buys_no_next_language_after_the_run_ends():+ """#1315: the run ends while `en` is in flight; `es` and `pt` are not bought."""+ stopped = threading.Event()++ def _empty_then_stop(*args, **kwargs):+ stopped.set()+ return {"transcript": None}++ with mock.patch.object(youtube_yt.http, "get", side_effect=_empty_then_stop) as paid_get, \+ mock.patch.dict("os.environ", {"LAST30DAYS_YT_SUB_LANGS": "en,es,pt"}), \+ youtube_yt.sc_spend_until(stopped.is_set):+ assert youtube_yt._sc_fetch_transcript("v1", "dummy-key") is None+ assert [c.kwargs["params"]["language"] for c in paid_get.call_args_list] == ["en"]+++def test_sc_requests_carry_the_run_cancel_and_deadline():+ """#1315: retries of a paid request stop at the run's deadline or cancel."""+ cancel = threading.Event()+ run_deadline = 1.0 # monotonic; earlier than any per-call deadline below+ with mock.patch.object(youtube_yt.http, "get", return_value={}) as paid_get, \+ mock.patch.object(youtube_yt, "_ytdlp_comments_result", return_value=([], False)), \+ mock.patch.object(youtube_yt.time, "monotonic", return_value=0.0), \+ youtube_yt.sc_spend_until(lambda: False, cancel=cancel, deadline=run_deadline):+ youtube_yt._sc_youtube_search("vuori", "dummy-key")+ youtube_yt._fetch_video_comments("v1", "dummy-key")+ youtube_yt._sc_fetch_transcript("v1", "dummy-key")+ assert paid_get.call_count >= 3+ for call in paid_get.call_args_list:+ assert call.kwargs["cancel"] is cancel+ assert call.kwargs["deadline_monotonic"] == run_deadline+++def test_sc_transcript_keeps_its_own_deadline_outside_a_run():+ with mock.patch.object(youtube_yt.http, "get", return_value={"transcript": "t"}) as paid_get:+ assert youtube_yt._sc_fetch_transcript("v1", "dummy-key") == "t"+ kwargs = paid_get.call_args.kwargs+ assert "cancel" not in kwargs+ assert kwargs["deadline_monotonic"] > 0diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.pyindex f348ba3b..d1da6f6c 100644--- a/tests/test_youtube_yt.py+++ b/tests/test_youtube_yt.py@@ -125,7 +125,10 @@ class TestYtDlpSubLangs(unittest.TestCase):self.assertEqual(youtube_yt._ytdlp_sub_langs(), "en,es,pt")def test_transcript_cmd_uses_default_sub_langs(self):- """Regression: the --sub-lang arg is en,es,pt by default (issue #469)."""+ """Regression: the --sub-lang arg covers en,es,pt by default (issue #469).++ Each language is requested original-speech first (#1314).+ """with tempfile.TemporaryDirectory() as temp_dir, \mock.patch.dict(os.environ, {}, clear=False), \mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \@@ -137,7 +140,7 @@ class TestYtDlpSubLangs(unittest.TestCase):self.assertEqual(transcript, "Offline transcript fixture.")cmd = run_mock.call_args_list[0].args[0]idx = cmd.index("--sub-lang")- self.assertEqual(cmd[idx + 1], "en,es,pt")+ self.assertEqual(cmd[idx + 1], "en-orig,en,es-orig,es,pt-orig,pt")def test_transcript_cmd_respects_env_var_override(self):with tempfile.TemporaryDirectory() as temp_dir, \@@ -150,7 +153,80 @@ class TestYtDlpSubLangs(unittest.TestCase):self.assertEqual(transcript, "Offline transcript fixture.")cmd = run_mock.call_args_list[0].args[0]idx = cmd.index("--sub-lang")- self.assertEqual(cmd[idx + 1], "fr,de,it")+ self.assertEqual(cmd[idx + 1], "fr-orig,fr,de-orig,de,it-orig,it")++ def test_transcript_cmd_requests_uploaded_and_auto_subtitles(self):+ """#1313: manual-only subtitles must not exit 0 with no file."""+ with tempfile.TemporaryDirectory() as temp_dir, \+ mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()) as run_mock:+ _write_transcript_fixture(temp_dir)+ youtube_yt._fetch_transcript_ytdlp("abc123", temp_dir)++ cmd = run_mock.call_args_list[0].args[0]+ self.assertIn("--write-subs", cmd)+ self.assertIn("--write-auto-subs", cmd)++ def test_ssh_transcript_cmd_requests_uploaded_subs_and_orig_first(self):+ from lib.subproc import SubprocResult+ result = SubprocResult(returncode=0, stdout="WEBVTT\n", stderr="")+ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en"}), \+ mock.patch.object(youtube_yt, "_run_ytdlp", return_value=result) as run_mock:+ youtube_yt._fetch_transcript_ytdlp_via_ssh("abc123", "macmini")++ remote_script = run_mock.call_args.args[0][-1]+ self.assertIn("--write-subs --write-auto-subs --sub-lang en-orig,en ", remote_script)++ def test_request_langs_do_not_double_explicit_orig(self):+ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "fr,en-orig,en"}):+ self.assertEqual(youtube_yt._ytdlp_request_langs(), "fr-orig,fr,en-orig,en")++ def test_vtt_matching_prefers_plain_track_within_a_language(self):+ """A plain track that downloaded may be the uploaded subtitle; keep it."""+ with tempfile.TemporaryDirectory() as temp_dir:+ for name in ("abc123.en.vtt", "abc123.en-orig.vtt", "abc123.es-orig.vtt"):+ (Path(temp_dir) / name).write_text("WEBVTT\n")+ picked = youtube_yt._pick_ytdlp_vtt("abc123", temp_dir, ["en", "es", "pt"])+ self.assertEqual(picked.name, "abc123.en.vtt")++ def test_vtt_matching_falls_back_to_orig_track(self):+ with tempfile.TemporaryDirectory() as temp_dir:+ for name in ("abc123.en-orig.vtt", "abc123.es.vtt"):+ (Path(temp_dir) / name).write_text("WEBVTT\n")+ picked = youtube_yt._pick_ytdlp_vtt("abc123", temp_dir, ["en", "es", "pt"])+ self.assertEqual(picked.name, "abc123.en-orig.vtt")++ def test_configured_orig_code_keeps_its_language_priority(self):+ """`en-orig` in SUB_LANGS ranks English first, not after every listed code."""+ with tempfile.TemporaryDirectory() as temp_dir:+ for name in ("abc123.fr.vtt", "abc123.en-orig.vtt"):+ (Path(temp_dir) / name).write_text("WEBVTT\n")+ picked = youtube_yt._pick_ytdlp_vtt("abc123", temp_dir, ["en-orig", "fr"])+ self.assertEqual(picked.name, "abc123.en-orig.vtt")++ def test_dubbed_video_keeps_orig_track_after_plain_track_429(self):+ """#1314: `en` 429s after `en-orig` downloaded; keep it, no retry, no SC."""+ from lib.subproc import SubprocResult+ failed = SubprocResult(+ returncode=1, stdout="",+ stderr="ERROR: Unable to download video subtitles for 'en': HTTP Error 429: Too Many Requests",+ )+ with tempfile.TemporaryDirectory() as temp_dir:+ def _run(cmd, timeout):+ (Path(temp_dir) / "dub123.en-orig.vtt").write_text(+ "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nOriginal speech captions.\n",+ )+ return failed++ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": ""}), \+ mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \+ mock.patch.object(youtube_yt, "_ytdlp_ssh_host", return_value=None), \+ mock.patch.object(youtube_yt, "_run_ytdlp", side_effect=_run) as run_mock, \+ mock.patch.object(youtube_yt, "_sc_fetch_transcript") as sc_mock:+ transcript = youtube_yt.fetch_transcript("dub123", temp_dir, token="dummy-key")++ self.assertEqual(transcript, "Original speech captions.")+ self.assertEqual(run_mock.call_count, 1)+ sc_mock.assert_not_called()def test_vtt_matching_picks_non_english_track(self):"""When yt-dlp writes a Spanish track (no English available), we read it."""@@ -1167,6 +1243,19 @@ class TestScTranscriptParsing(unittest.TestCase):["fr", "de", "ja"],)+ def test_orig_codes_are_sent_to_sc_as_plain_languages(self):+ """#1314: SC never receives a yt-dlp-only `-orig` language code."""+ with mock.patch.dict(+ os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en-orig,en,es"},+ ), mock.patch.object(+ youtube_yt.http, "get", return_value={"transcript": None},+ ) as get_mock:+ youtube_yt._sc_fetch_transcript("vidOrig", "key")+ self.assertEqual(+ [c.kwargs["params"]["language"] for c in get_mock.call_args_list],+ ["en", "es"],+ )+def test_empty_caption_segments_do_not_stop_language_fallback(self):responses = [{"transcript": [{"text": None}, {"text": " "}]},