返回 last30days-skill
youtube_yt.py
根目录 / skills / last30days / scripts / lib / youtube_yt.py
1 """YouTube search and transcript extraction via yt-dlp for the v3.0.0 pipeline.
2
3 Uses yt-dlp (https://github.com/yt-dlp/yt-dlp) for both YouTube search and
4 transcript extraction. No API keys needed — just have yt-dlp installed.
5
6 Inspired by Peter Steinberger's toolchain approach (yt-dlp + summarize CLI).
7 """
8
9 import contextlib
10 import contextvars
11 import copy
12 import glob
13 import json
14 import math
15 import os
16 import re
17 import shlex
18 import shutil
19 import sys
20 import tempfile
21 import threading
22 import time
23 import urllib.error
24 import urllib.parse
25 import urllib.request
26 import datetime as _dt
27 from concurrent.futures import ThreadPoolExecutor, as_completed
28 from concurrent.futures import TimeoutError as FuturesTimeout
29 from dataclasses import dataclass
30 from pathlib import Path
31 from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple
32
33 # Depth configurations: how many videos to search / transcribe
34 DEPTH_CONFIG = {
35 "quick": 6,
36 "default": 8,
37 "deep": 40,
38 }
39
40 TRANSCRIPT_LIMITS = {
41 "quick": 0,
42 "default": 2,
43 "deep": 8,
44 }
45
46 # Cumulative yt-dlp transcript-fetch stats for the current process. The final
47 # report only sees post-pruning items, so it can't distinguish "fetches failed
48 # (stale binary)" from "fetches succeeded but the videos were pruned later".
49 # quality_nudge reads these via last30days.py to suppress the stale-yt-dlp
50 # nudge when every attempted fetch actually succeeded. yt-dlp path only: the
51 # nudge diagnoses the local binary, not the ScrapeCreators API.
52 #
53 # ``target`` sums each search's transcript target, so health is measured
54 # against what the run tried to get rather than every surviving video.
55 # ``blocked`` counts searches whose yt-dlp hit a YouTube bot check or rate
56 # limit, and ``sc_rescued`` counts transcripts the ScrapeCreators fallback
57 # fetched instead: those failures are the network, not a stale binary.
58 _TRANSCRIPT_FETCH_STATS = {
59 "attempts": 0, "failures": 0, "target": 0, "blocked": 0, "sc_rescued": 0,
60 }
61 _TRANSCRIPT_FETCH_STATS_LOCK = threading.Lock()
62
63
64 def get_transcript_fetch_stats() -> Dict[str, int]:
65 """Return cumulative transcript-fetch stats for this process."""
66 with _TRANSCRIPT_FETCH_STATS_LOCK:
67 return dict(_TRANSCRIPT_FETCH_STATS)
68
69
70 def reset_transcript_fetch_stats() -> None:
71 """Reset cumulative transcript-fetch stats (used by tests)."""
72 with _TRANSCRIPT_FETCH_STATS_LOCK:
73 for key in _TRANSCRIPT_FETCH_STATS:
74 _TRANSCRIPT_FETCH_STATS[key] = 0
75
76
77 def _add_transcript_fetch_stats(**counts: int) -> None:
78 with _TRANSCRIPT_FETCH_STATS_LOCK:
79 for key, value in counts.items():
80 _TRANSCRIPT_FETCH_STATS[key] += value
81
82 # Max words to keep from each transcript
83 TRANSCRIPT_MAX_WORDS = 5000
84
85 from . import bounded_get, dates, health, http, log, public_host, subproc
86 from .query import infer_query_intent
87
88 from .relevance import token_overlap_relevance as _compute_relevance
89
90 # yt-dlp transcript-fetch resilience. A non-zero yt-dlp exit means a real fetch
91 # error (rate-limit / bot-check / network), NOT "no captions" — yt-dlp exits 0
92 # with no file for a video that genuinely lacks the requested captions. So we
93 # capture the returncode, log a classified reason instead of failing silently,
94 # and retry transient errors a couple of times with a small per-video staggered
95 # backoff.
96 _TRANSCRIPT_MAX_RETRIES = 2
97 _TRANSCRIPT_BACKOFF_BASE = 2.0 # seconds; multiplied by (attempt + 1)
98 _TRANSCRIPT_TIMEOUT = 30 # seconds per yt-dlp attempt (keyless: no fallback to fail over to)
99 _TRANSCRIPT_FAST_TIMEOUT = 12 # seconds per attempt when a ScrapeCreators fallback exists
100 _SEARCH_TIMEOUT = 120 # seconds per ytsearch metadata extraction
101 # Comparison-mode fan-out (and nested transcript/comment pools) can stampede the
102 # same throttled YouTube IP. Cap concurrent yt-dlp processes process-wide.
103 _YTDLP_MAX_CONCURRENT = 2
104 _ytdlp_slots = threading.Semaphore(_YTDLP_MAX_CONCURRENT)
105 # In-run search cache: comparison mode re-issues identical ytsearch queries from
106 # every entity sub-run; cache hits avoid the redundant expensive --dump-json work.
107 # Inflight coalescing prevents N concurrent identical searches from all missing
108 # the cache and stampeding YouTube together.
109 _search_cache: Dict[Tuple[str, int, str, str, Optional[str], Optional[str]], Dict[str, Any]] = {}
110 _search_inflight: Dict[Tuple[str, int, str, str, Optional[str], Optional[str]], tuple[threading.Event, list]] = {}
111 _search_cache_lock = threading.Lock()
112 # Comments are enrichment, not core evidence: keep the budget tight so a slow
113 # comment API can never dominate a run's wall clock (bounded to 3 videos).
114 _COMMENT_TIMEOUT = 20
115 _SC_LOW_CREDIT_THRESHOLD = 50 # warn once ScrapeCreators credits drop below this
116 _SC_TRANSCRIPT_MAX_LANGUAGES = 3
117 _SC_TRANSCRIPT_TIMEOUT = 30
118 # Transient = worth retrying (and definitely not "no captions").
119 _TRANSIENT_RE = re.compile(
120 r"429|too many requests|sign in to confirm|not a bot|rate.?limit"
121 r"|temporarily|try again|timed out|timeout|connection|unable to (extract|download)"
122 r"|failed to (extract|download)|got error|read error",
123 re.IGNORECASE,
124 )
125 # A genuine no-captions signal — treat as no captions, never retry/surface.
126 _NO_CAPTION_RE = re.compile(
127 r"no subtitles|requested (format|language)|there'?s no .*subtitles",
128 re.IGNORECASE,
129 )
130
131
132 def extract_transcript_highlights(
133 transcript: str, topic: str, limit: int = 5, *, max_words: int = 50,
134 ) -> list[str]:
135 """Extract quotable highlights from a YouTube transcript.
136
137 ``max_words`` bounds a sentence; short-form spoken captions run long
138 sentences together, so their callers pass a higher bound.
139
140 Filters filler (subscribe, welcome back, etc.), scores sentences by
141 specificity (numbers, proper nouns, topic relevance), and returns
142 the top highlights.
143 """
144 if not transcript:
145 return []
146
147 sentences = re.split(r'(?<=[.!?])\s+', transcript)
148
149 # Fallback for punctuation-free transcripts (common with auto-captions):
150 # chunk into ~20-word segments so they pass the 8-to-max_words filter.
151 if len(sentences) <= 1 and len(transcript.split()) > max_words:
152 words = transcript.split()
153 sentences = [' '.join(words[i:i+20]) for i in range(0, len(words), 20)]
154
155 filler = [
156 r"^(hey |hi |what's up|welcome back|in today's video|don't forget to)",
157 r"(subscribe|like and comment|hit the bell|check out the link|down below)",
158 r"^(so |and |but |okay |alright |um |uh )",
159 r"(thanks for watching|see you (next|in the)|bye)",
160 ]
161
162 topic_words = [w.lower() for w in topic.lower().split() if len(w) > 2]
163
164 candidates = []
165 for sent in sentences:
166 sent = sent.strip()
167 words = sent.split()
168 if len(words) < 8 or len(words) > max_words:
169 continue
170 if any(re.search(p, sent, re.IGNORECASE) for p in filler):
171 continue
172
173 score = 0
174 if re.search(r'\d', sent):
175 score += 2
176 if re.search(r'[A-Z][a-z]+', sent):
177 score += 1
178 if '?' in sent:
179 score += 1
180 sent_lower = sent.lower()
181 if any(w in sent_lower for w in topic_words):
182 score += 2
183
184 candidates.append((score, sent))
185
186 candidates.sort(key=lambda x: -x[0])
187 return [sent for _, sent in candidates[:limit]]
188
189
190 def _log(msg: str):
191 log.source_log("YouTube", msg, tty_only=False)
192
193
194 # The research run's stop state, set by the pipeline for the YouTube lane:
195 # ``stopped()`` is True once the run is over (deadline passed or cancelled),
196 # and ``cancel``/``deadline`` bound each paid request and its retries to the
197 # same moment. An abandoned lane keeps running after the report is saved, and
198 # every ScrapeCreators call it made then was a paid result nobody would read
199 # (#1315). Pool workers inherit it through http.submit_with_context.
200 @dataclass(frozen=True)
201 class _SCSpendLimit:
202 stopped: Callable[[], bool]
203 cancel: Optional[threading.Event] = None
204 deadline: Optional[float] = None
205 return_deadline: Optional[float] = None
206
207
208 _sc_spend_limit: contextvars.ContextVar[Optional[_SCSpendLimit]] = (
209 contextvars.ContextVar("youtube_sc_spend_limit", default=None)
210 )
211
212
213 @contextlib.contextmanager
214 def sc_spend_until(
215 stopped: Callable[[], bool],
216 *,
217 cancel: Optional[threading.Event] = None,
218 deadline: Optional[float] = None,
219 return_deadline: Optional[float] = None,
220 ) -> Iterator[None]:
221 """Refuse ScrapeCreators YouTube calls in this context once ``stopped()``.
222
223 ``cancel`` and ``deadline`` (monotonic) also cut off a request, or its
224 retries, that is still running when the run ends. A lane can supply an
225 earlier ``return_deadline`` to preserve time for handing back its results.
226 """
227 token = _sc_spend_limit.set(_SCSpendLimit(stopped, cancel, deadline, return_deadline))
228 try:
229 yield
230 finally:
231 _sc_spend_limit.reset(token)
232
233
234 # The pipeline discards a lane that is still running at its deadline, so the
235 # lane must hand back what it found this long before that moment.
236 _LANE_RETURN_MARGIN_SECONDS = 10.0
237
238
239 def _lane_deadline() -> Optional[float]:
240 limit = _sc_spend_limit.get()
241 if limit is None:
242 return None
243 deadline = limit.return_deadline
244 if deadline is None:
245 if limit.deadline is None:
246 return None
247 deadline = limit.deadline - _LANE_RETURN_MARGIN_SECONDS
248 return deadline
249
250
251 def _lane_seconds_left() -> Optional[float]:
252 """Seconds until this lane must return its results, or None if unbounded."""
253 deadline = _lane_deadline()
254 return None if deadline is None else deadline - time.monotonic()
255
256
257 def _lane_out_of_time() -> bool:
258 limit = _sc_spend_limit.get()
259 if limit is not None and limit.cancel is not None and limit.cancel.is_set():
260 return True
261 seconds_left = _lane_seconds_left()
262 return seconds_left is not None and seconds_left <= 0
263
264
265 # Another expanded search has to leave this long for transcripts. A default
266 # run targets 2 (60s); a deep run targets 8 (75s). In between, scale linearly.
267 _TRANSCRIPT_RESERVE_FLOOR_SECONDS = 60.0
268 _TRANSCRIPT_RESERVE_CEILING_SECONDS = 75.0
269 _TRANSCRIPT_RESERVE_FLOOR_TARGET = 2
270 _TRANSCRIPT_RESERVE_CEILING_TARGET = 8
271
272
273 def _transcript_search_reserve(transcript_limit: int) -> float:
274 """Seconds to keep for transcripts before starting another expanded search."""
275 if transcript_limit <= 0:
276 return 0.0
277 span = (transcript_limit - _TRANSCRIPT_RESERVE_FLOOR_TARGET) / (
278 _TRANSCRIPT_RESERVE_CEILING_TARGET - _TRANSCRIPT_RESERVE_FLOOR_TARGET
279 )
280 span = min(1.0, max(0.0, span))
281 return _TRANSCRIPT_RESERVE_FLOOR_SECONDS + (
282 _TRANSCRIPT_RESERVE_CEILING_SECONDS - _TRANSCRIPT_RESERVE_FLOOR_SECONDS
283 ) * span
284
285
286 def _lane_under_transcript_reserve(reserve: float) -> bool:
287 """True when another search would spend the time kept for transcripts."""
288 seconds_left = _lane_seconds_left()
289 return reserve > 0 and seconds_left is not None and seconds_left < reserve
290
291
292 # yt-dlp text for "stop calling YouTube for transcripts this search".
293 # Timeouts are not included: one slow video is not a block.
294 _YOUTUBE_BLOCK_RE = re.compile(
295 r"429|too many requests|sign in to confirm(?! your age)|not a bot|bot-gate",
296 re.IGNORECASE,
297 )
298
299
300 def _is_youtube_bot_or_rate_limit(detail: str) -> bool:
301 return bool(detail) and _YOUTUBE_BLOCK_RE.search(detail) is not None
302
303
304 class _YouTubeBlock:
305 """Shared 'yt-dlp is blocked' flag for one search and its transcript workers."""
306
307 def __init__(self) -> None:
308 self.tripped = False
309 self._lock = threading.Lock()
310
311 def note(self, detail: str) -> None:
312 if not _is_youtube_bot_or_rate_limit(detail):
313 return
314 with self._lock:
315 self.tripped = True
316
317
318 _youtube_block: contextvars.ContextVar[Optional["_YouTubeBlock"]] = (
319 contextvars.ContextVar("youtube_ytdlp_block", default=None)
320 )
321
322
323 @contextlib.contextmanager
324 def _youtube_block_scope() -> Iterator["_YouTubeBlock"]:
325 """Reuse a parent flag, or own one for this call and the workers it submits."""
326 current = _youtube_block.get()
327 if current is not None:
328 yield current
329 return
330 block = _YouTubeBlock()
331 token = _youtube_block.set(block)
332 try:
333 yield block
334 finally:
335 _youtube_block.reset(token)
336
337
338 def _note_youtube_block(detail: str) -> None:
339 block = _youtube_block.get()
340 if block is not None:
341 block.note(detail)
342
343
344 def _youtube_transcripts_blocked() -> bool:
345 block = _youtube_block.get()
346 return block is not None and block.tripped
347
348
349 def _sc_spend_blocked(what: str) -> bool:
350 """True when research stopped or the lane must return before buying ``what``."""
351 limit = _sc_spend_limit.get()
352 if limit is None:
353 return False
354 lane_expired = limit.return_deadline is not None and time.monotonic() >= limit.return_deadline
355 if not limit.stopped() and not lane_expired:
356 return False
357 _log(f"Skipping ScrapeCreators {what}: the research stopped or the lane deadline passed")
358 return True
359
360
361 def _sc_request_bounds(deadline: Optional[float] = None) -> Dict[str, Any]:
362 """``http.get`` kwargs that stop a paid request when the research run ends.
363
364 ``deadline`` is the caller's own monotonic deadline, if any; the earlier
365 of it, the run's deadline, and the lane's return deadline wins.
366 """
367 limit = _sc_spend_limit.get()
368 bounds: Dict[str, Any] = {}
369 deadlines = [d for d in (
370 deadline,
371 limit.deadline if limit else None,
372 limit.return_deadline if limit else None,
373 ) if d is not None]
374 if deadlines:
375 bounds["deadline_monotonic"] = min(deadlines)
376 if limit is not None and limit.cancel is not None:
377 bounds["cancel"] = limit.cancel
378 return bounds
379
380
381 def reset_search_cache() -> None:
382 """Clear the in-run ytsearch cache.
383
384 Call at the start of each top-level research run so a long-lived process
385 (agent host, REPL, test suite) does not reuse results across runs. Within
386 one comparison fan-out the cache stays hot so identical queries coalesce.
387 """
388 with _search_cache_lock:
389 _search_cache.clear()
390 _search_inflight.clear()
391
392
393 def _env_positive_float(name: str, default: float) -> float:
394 """Read a positive finite float from the environment, else ``default``."""
395 raw = os.environ.get(name, "").strip()
396 try:
397 value = float(raw) if raw else float(default)
398 except ValueError:
399 return float(default)
400 if not math.isfinite(value) or value <= 0:
401 return float(default)
402 return value
403
404
405 def _search_timeout() -> float:
406 """Return the ytsearch timeout, preserving the 120s default."""
407 return _env_positive_float("LAST30DAYS_YT_SEARCH_TIMEOUT", float(_SEARCH_TIMEOUT))
408
409
410 class _YtdlpBlocked(Exception):
411 """A keyed transcript got a free slot only after YouTube was already blocked."""
412
413
414 def _remember_youtube_block(result: subproc.SubprocResult) -> subproc.SubprocResult:
415 """Record a bot-check or 429 before this worker gives up its yt-dlp slot.
416
417 The next worker rechecks the flag after acquire. The slot has to still be
418 held here, or that worker starts yt-dlp before this one records the block.
419 """
420 if result.returncode != 0:
421 _note_youtube_block(result.stderr or "")
422 return result
423
424
425 def _run_ytdlp(
426 cmd: List[str],
427 *,
428 timeout: float,
429 abort_if_blocked: bool = False,
430 ) -> subproc.SubprocResult:
431 """Run a yt-dlp (or SSH-wrapped) command under the process-wide concurrency gate.
432
433 The wait for a slot and the run itself both end when the lane must return.
434 A keyed transcript checks the bot-check flag again after the wait. It may
435 have been clear when the worker queued and set while the worker was waiting.
436 """
437 def _abort_if_blocked() -> None:
438 if abort_if_blocked and _youtube_transcripts_blocked():
439 raise _YtdlpBlocked()
440
441 limit = _sc_spend_limit.get()
442 cancel = limit.cancel if limit else None
443 deadline = _lane_deadline()
444 if deadline is None and cancel is None:
445 with _ytdlp_slots:
446 _abort_if_blocked()
447 return _remember_youtube_block(subproc.run_with_timeout(cmd, timeout=timeout))
448 if deadline is None:
449 deadline = time.monotonic() + timeout
450 while True:
451 if cancel is not None and cancel.is_set():
452 raise subproc.SubprocTimeout("YouTube lane cancelled", started=False)
453 seconds_left = deadline - time.monotonic()
454 if seconds_left <= 0:
455 raise subproc.SubprocTimeout("no yt-dlp slot before the lane deadline", started=False)
456 if _ytdlp_slots.acquire(timeout=min(0.05, seconds_left) if cancel is not None else seconds_left):
457 break
458 try:
459 _abort_if_blocked()
460 seconds_left = deadline - time.monotonic()
461 if seconds_left <= 0:
462 raise subproc.SubprocTimeout("lane deadline passed", started=False)
463 bounded = min(timeout, seconds_left)
464 try:
465 result = subproc.run_with_timeout(
466 cmd, timeout=bounded, deadline_monotonic=deadline, cancel=cancel,
467 )
468 except subproc.SubprocTimeout as exc:
469 # The attempt cap was not what stopped the process. The lane
470 # deadline was shorter, so don't report the full cap.
471 if bounded < timeout:
472 raise subproc.SubprocTimeout(
473 "lane deadline reached", started=exc.started,
474 ) from exc
475 raise
476 return _remember_youtube_block(result)
477 finally:
478 _ytdlp_slots.release()
479
480
481 def _claim_search_slot(
482 cache_key: Tuple[str, int, str, str, Optional[str], Optional[str]],
483 ) -> tuple[Optional[Dict[str, Any]], Optional[threading.Event], Optional[list], bool]:
484 """Return ``(cached, event, slot, is_leader)`` for search coalesce.
485
486 - Cache hit: ``(payload, None, None, False)`` — caller returns ``payload``.
487 - Waiter: ``(None, event, slot, False)`` — caller awaits ``slot`` via ``event``.
488 - Leader: ``(None, event, slot, True)`` — caller runs yt-dlp and finishes the slot.
489 """
490 with _search_cache_lock:
491 cached = _search_cache.get(cache_key)
492 if cached is not None:
493 return copy.deepcopy(cached), None, None, False
494 existing = _search_inflight.get(cache_key)
495 if existing is not None:
496 return None, existing[0], existing[1], False
497 event = threading.Event()
498 slot: list = [None]
499 _search_inflight[cache_key] = (event, slot)
500 return None, event, slot, True
501
502
503 def _finish_search_slot(
504 cache_key: Tuple[str, int, str, str, Optional[str], Optional[str]],
505 payload: Dict[str, Any],
506 *,
507 event: threading.Event,
508 slot: list,
509 ) -> Dict[str, Any]:
510 """Publish a search result to waiters; cache only clean (non-error) payloads.
511
512 Ownership is by slot identity: after ``reset_search_cache()`` clears the
513 registry, a stale leader must still wake its own waiters but must not pop
514 or overwrite a newer run's registration for the same key.
515 """
516 shared = copy.deepcopy(payload)
517 with _search_cache_lock:
518 if slot[0] is not None:
519 # Idempotent re-finish of this slot (e.g. finally after return).
520 event.set()
521 return payload
522 slot[0] = shared
523 current = _search_inflight.get(cache_key)
524 if current is not None and current[1] is slot:
525 if not payload.get("error"):
526 _search_cache[cache_key] = shared
527 _search_inflight.pop(cache_key, None)
528 # else: stale leader after a reset — wake local waiters only.
529 event.set()
530 return payload
531
532
533 def _await_search_slot(
534 event: threading.Event,
535 slot: list,
536 ) -> Dict[str, Any]:
537 """Wait for a leader search to publish.
538
539 Waiters block until the leader finishes (success or failure). The leader
540 path always publishes via ``_finish_search_slot``, including on unexpected
541 exceptions, so a timed wait would only invent a false timeout while the
542 leader was still queued behind other yt-dlp work.
543 """
544 event.wait()
545 shared = slot[0]
546 if isinstance(shared, dict):
547 return copy.deepcopy(shared)
548 return {"items": [], "error": "YouTube search failed"}
549
550
551 def classify_run_failure(detail: str) -> str:
552 """Map yt-dlp's text-only throttling and bot-gate errors."""
553 text = detail.lower()
554 if any(marker in text for marker in ("yt-dlp not installed", "yt-dlp not found")):
555 return health.SKIPPED_UNCONFIGURED
556 if any(marker in text for marker in ("timed out", "timeout")):
557 return health.TIMEOUT
558 if any(
559 marker in text
560 for marker in ("http error 429", "confirm you're not a bot", "confirm you’re not a bot", "bot-gate")
561 ):
562 return health.RATE_LIMITED
563 if any(marker in text for marker in ("sign in", "login required", "cookies are no longer valid")):
564 return health.AUTH_FAILED
565 return http.classify_failure(message=detail)
566
567
568 _ssh_host_override: contextvars.ContextVar[Optional[str]] = (
569 contextvars.ContextVar("youtube_ssh_host_override", default=None)
570 )
571
572
573 @contextlib.contextmanager
574 def ssh_host_scope(host: Optional[str]) -> Iterator[None]:
575 """Scope a config-supplied LAST30DAYS_YOUTUBE_SSH_HOST to this call tree."""
576 token = _ssh_host_override.set(host)
577 try:
578 yield
579 finally:
580 _ssh_host_override.reset(token)
581
582
583 def is_ytdlp_installed() -> bool:
584 """Check if yt-dlp is available locally, or if SSH routing is configured.
585
586 When LAST30DAYS_YOUTUBE_SSH_HOST is set, returns True without a local check —
587 yt-dlp lives on the remote host. Failures surface naturally on first use.
588 """
589 if _ytdlp_ssh_host():
590 return True
591 return shutil.which("yt-dlp") is not None
592
593
594 # Host aliases must be plain hostnames / SSH config aliases — no flags, no
595 # shell metacharacters. Rejects any value that could be reinterpreted by ssh
596 # (or the surrounding shell) as something other than a destination.
597 _SSH_HOST_ALIAS_RE = re.compile(r"^(?!-)[a-zA-Z0-9._-]+$")
598
599
600 def _ytdlp_ssh_host() -> Optional[str]:
601 """Return SSH host alias if yt-dlp should be routed via SSH, else None.
602
603 Set LAST30DAYS_YOUTUBE_SSH_HOST=<ssh-alias> (e.g. 'macmini') in the environment
604 to route yt-dlp through SSH for residential IP egress. This bypasses
605 YouTube's bot-wall on datacenter IPs (Hetzner, DigitalOcean, AWS, etc.)
606 where ytsearch returns 0 results regardless of cookies.
607
608 The remote host must have yt-dlp installed and reachable via the named
609 SSH alias (configured in ~/.ssh/config). On macOS hosts with Homebrew,
610 add brew shellenv to ~/.zshenv (not just ~/.zprofile) so non-login SSH
611 shells find yt-dlp on PATH.
612
613 Validation: host value must match ``[A-Za-z0-9._-]+``. Anything starting
614 with ``-`` or containing shell/SSH metacharacters is rejected with a
615 stderr warning and treated as unset, so a misconfigured or attacker-
616 controlled value can't slip through as an SSH option flag or proxy command.
617 The ``--`` option terminator in ``_wrap_ytdlp_cmd`` is a second line of
618 defense; this regex closes the door on the env var ever reaching ssh
619 in the first place.
620
621 To use a value from ~/.config/last30days/.env, export it into the
622 environment before invoking the engine, e.g. in a wrapper:
623 set -a; source ~/.config/last30days/.env; set +a
624 python3 last30days.py "..."
625 """
626 if "LAST30DAYS_YOUTUBE_SSH_HOST" in os.environ:
627 host = os.environ.get("LAST30DAYS_YOUTUBE_SSH_HOST", "").strip()
628 else:
629 host = str(_ssh_host_override.get() or "").strip()
630 if not host:
631 return None
632 if not _SSH_HOST_ALIAS_RE.match(host):
633 sys.stderr.write(
634 f"[youtube_yt] WARNING: LAST30DAYS_YOUTUBE_SSH_HOST={host!r} "
635 "does not look like a plain hostname/alias; ignoring. "
636 "Expected pattern: letters, digits, dot, underscore, hyphen.\n"
637 )
638 return None
639 return host
640
641
642 _PLAYER_CLIENT_RE = re.compile(r"^[A-Za-z0-9_-]+$")
643
644
645 def _ytdlp_player_client() -> Optional[str]:
646 """Return the yt-dlp YouTube player_client, or None to leave the default.
647
648 Default is ``android``, which bypasses the web bot-gate without cookies.
649 Set ``LAST30DAYS_YT_PLAYER_CLIENT`` empty to disable; any other value is
650 passed through when it is a safe extractor token.
651 """
652 if "LAST30DAYS_YT_PLAYER_CLIENT" in os.environ:
653 raw = os.environ.get("LAST30DAYS_YT_PLAYER_CLIENT", "").strip()
654 if not raw:
655 return None
656 else:
657 raw = "android"
658 if not _PLAYER_CLIENT_RE.match(raw):
659 sys.stderr.write(
660 f"[youtube_yt] WARNING: LAST30DAYS_YT_PLAYER_CLIENT={raw!r} "
661 "is not a plain player-client token; ignoring.\n"
662 )
663 return None
664 return raw
665
666
667 def _ytdlp_cmd_needs_player_client(cmd: List[str]) -> bool:
668 blob = " ".join(cmd)
669 return any(
670 marker in blob
671 for marker in (
672 "ytsearch",
673 "youtube.com",
674 "--write-comments",
675 "--write-auto-subs",
676 )
677 )
678
679
680 def _append_ytdlp_option(cmd: List[str], option_args: List[str]) -> List[str]:
681 """Insert ``option_args`` before ``--`` if present, else append to ``cmd``."""
682 out = list(cmd)
683 if "--" in out:
684 idx = out.index("--")
685 return out[:idx] + list(option_args) + out[idx:]
686 out.extend(option_args)
687 return out
688
689
690 def _inject_youtube_player_client(cmd: List[str]) -> List[str]:
691 """Merge player_client into a single youtube --extractor-args (#1052).
692
693 yt-dlp does not merge two ``--extractor-args`` for the same extractor;
694 the last one wins. Always fold into an existing ``youtube:`` spec.
695 """
696 client = _ytdlp_player_client()
697 if not client or not _ytdlp_cmd_needs_player_client(cmd):
698 return list(cmd)
699 out = list(cmd)
700 needle = f"player_client={client}"
701 for i, arg in enumerate(out):
702 if arg == "--":
703 break
704 if arg == "--extractor-args" and i + 1 < len(out):
705 spec = out[i + 1]
706 if spec.startswith("youtube:"):
707 if "player_client=" in spec:
708 return out
709 out[i + 1] = f"{spec};{needle}"
710 return out
711 return _append_ytdlp_option(out, ["--extractor-args", f"youtube:{needle}"])
712
713
714 def _ytdlp_proxy() -> Optional[str]:
715 """Return the proxy URL for yt-dlp, or None when unset.
716
717 Set ``YOUTUBE_PROXY`` (or ``YT_PROXY``) to any proxy URL that yt-dlp
718 accepts: ``socks5://127.0.0.1:1080``, ``http://proxy:3128``, etc.
719 ``YOUTUBE_PROXY`` takes precedence over ``YT_PROXY``. Only routes
720 yt-dlp traffic through the proxy — other HTTP requests the skill makes
721 are unaffected (use ``HTTP_PROXY`` / ``HTTPS_PROXY`` for those).
722 """
723 proxy = os.environ.get("YOUTUBE_PROXY", "").strip() or os.environ.get("YT_PROXY", "").strip()
724 return proxy or None
725
726
727 def wrap_ytdlp_cmd(cmd: List[str]) -> List[str]:
728 """Wrap a yt-dlp command list with `ssh <host>` when SSH routing is set.
729
730 Args are shell-quoted to survive the remote shell. Uses BatchMode=yes so
731 a misconfigured key fails fast instead of hanging on a password prompt.
732 The `--` option terminator prevents an SSH option-injection if
733 LAST30DAYS_YOUTUBE_SSH_HOST were ever set to a value starting with `-`.
734 """
735 cmd = _inject_youtube_player_client(cmd)
736 proxy = _ytdlp_proxy()
737 if proxy:
738 cmd = _append_ytdlp_option(cmd, ["--proxy", proxy])
739 host = _ytdlp_ssh_host()
740 if not host:
741 return cmd
742 remote_cmd = " ".join(shlex.quote(a) for a in cmd)
743 return ["ssh", "-o", "BatchMode=yes", "--", host, remote_cmd]
744
745
746 def _extract_core_subject(topic: str) -> str:
747 """Extract core subject from verbose query for YouTube search.
748
749 NOTE: 'tips', 'tricks', 'tutorial', 'guide', 'review', 'reviews'
750 are intentionally KEPT — they're YouTube content types that improve search.
751 """
752 from .query import VIRAL_NOISE, extract_core_subject
753 # YouTube extends VIRAL_NOISE with temporal/meta words the planner emits
754 # that don't appear in YouTube titles (months, recent year tokens, etc.).
755 _YT_EXTRA = frozenset({
756 'last', 'days', 'recent', 'recently', 'month', 'week',
757 'january', 'february', 'march', 'april', 'may', 'june',
758 'july', 'august', 'september', 'october', 'november', 'december',
759 '2025', '2026', '2027',
760 'music', 'public', 'appearances', 'developments', 'discussions', 'coverage',
761 })
762 return extract_core_subject(topic, noise=VIRAL_NOISE | _YT_EXTRA)
763
764
765 def comparison_share(total: int, entity_count: int) -> int:
766 """One comparison entity's share of a single-topic yt-dlp budget (#1335).
767
768 Every entity's yt-dlp work queues on the same ``_YTDLP_MAX_CONCURRENT``
769 slots, so N full budgets overran the stream wait; each keeps at least one.
770 """
771 if total <= 0 or entity_count <= 1:
772 return total
773 return max(1, -(-total // entity_count))
774
775
776 def expand_youtube_queries(topic: str, depth: str, entity_count: int = 1) -> List[str]:
777 """Generate multiple YouTube search queries from a topic.
778
779 Mirrors reddit.py's expand_reddit_queries() pattern:
780 1. Extract core subject (strip noise words)
781 2. Include original topic if different from core
782 3. Add intent-specific OR-joined content-type variants
783 4. Cap by depth: 1 for quick, 2 for default, 3 for deep
784
785 Returns 1-3 query strings depending on depth.
786 """
787 core = _extract_core_subject(topic)
788 queries = [core]
789
790 # Include cleaned original topic as variant if different from core
791 original_clean = topic.strip().rstrip('?!.')
792 if core.lower() != original_clean.lower() and len(original_clean.split()) <= 8:
793 queries.append(original_clean)
794
795 qtype = infer_query_intent(topic)
796
797 # Intent-specific YouTube content-type variants
798 if qtype == "opinion":
799 queries.append(f"{core} review OR reaction OR breakdown")
800 elif qtype == "product":
801 queries.append(f"{core} review OR comparison OR unboxing")
802 elif qtype == "comparison":
803 queries.append(f"{core} vs OR compared OR head to head")
804 elif qtype == "how_to":
805 queries.append(f"{core} tutorial OR guide OR explained")
806 else:
807 # breaking_news / general — YouTube content types
808 queries.append(f"{core} review OR reaction OR breakdown")
809
810 # Deep depth: add full-length content variant
811 if depth == "deep":
812 queries.append(f"{core} full OR complete OR official")
813
814 # Cap by depth budget
815 caps = {"quick": 1, "default": 2, "deep": 3}
816 cap = comparison_share(caps.get(depth, 2), entity_count)
817 return queries[:cap]
818
819
820 # Freshness modes where an out-of-window video is noise, not a fallback: a
821 # recent topic with no in-range videos returns an honest empty result rather
822 # than years-old, often off-topic matches.
823 _RECENT_FRESHNESS_MODES = frozenset({"strict_recent", "balanced_recent"})
824
825
826 def _apply_date_window(
827 items: List[Dict[str, Any]],
828 from_date: str,
829 to_date: str,
830 freshness_mode: Optional[str],
831 ) -> List[Dict[str, Any]]:
832 """Prefer in-window videos; scope the keep-all fallback by freshness mode.
833
834 Videos published after ``to_date`` (an --as-of window) are never kept.
835 3+ in-window videos: keep only those (every mode). Fewer: recent modes
836 keep only the in-window ones; evergreen_ok and unknown/None keep all so
837 evergreen topics can still fall back to older videos.
838 """
839 items = [i for i in items if not (i["date"] and i["date"] > to_date)]
840 recent = [i for i in items if i["date"] and i["date"] >= from_date]
841 if len(recent) >= 3:
842 _log(f"Found {len(recent)} videos within date range")
843 return recent
844 if freshness_mode in _RECENT_FRESHNESS_MODES:
845 _log(
846 f"Found {len(items)} videos ({len(recent)} within date range, "
847 f"keeping only in-range for {freshness_mode})"
848 )
849 return recent
850 _log(f"Found {len(items)} videos ({len(recent)} within date range, keeping all)")
851 return items
852
853
854 # YouTube's own upload-date search filters (the ``sp`` results-page parameter),
855 # smallest first: this week, this month, this year.
856 _UPLOAD_DATE_FILTERS = ((7, "EgIIAw=="), (31, "EgIIBA=="), (366, "EgIIBQ=="))
857 # The filters count back from now, so they only fit a window ending about today.
858 _UPLOAD_FILTER_MAX_END_LAG_DAYS = 2
859
860
861 def _upload_date_filter(from_date: str, to_date: str) -> Optional[str]:
862 """Return the smallest YouTube upload filter covering the window, or None."""
863 try:
864 start = _dt.date.fromisoformat(from_date)
865 end = _dt.date.fromisoformat(to_date)
866 except ValueError:
867 return None
868 today = _dt.datetime.now(_dt.timezone.utc).date()
869 if (today - end).days > _UPLOAD_FILTER_MAX_END_LAG_DAYS:
870 return None
871 span = (today - start).days
872 for max_days, sp in _UPLOAD_DATE_FILTERS:
873 if span <= max_days:
874 return sp
875 return None
876
877
878 def _first_stderr_line(stderr: Optional[str]) -> str:
879 lines = (stderr or "").strip().splitlines()
880 return lines[0] if lines else "(no stderr)"
881
882
883 def _count_in_window(items: List[Dict[str, Any]], from_date: str, to_date: str) -> int:
884 return sum(1 for i in items if i["date"] and from_date <= i["date"] <= to_date)
885
886
887 def _parse_search_stdout(stdout: str, core_topic: str) -> List[Dict[str, Any]]:
888 """Parse yt-dlp ``--dump-json`` lines into video items."""
889 items = []
890 for line in stdout.strip().split("\n"):
891 line = line.strip()
892 if not line:
893 continue
894 try:
895 video = json.loads(line)
896 except json.JSONDecodeError:
897 continue
898
899 video_id = video.get("id", "")
900 if not isinstance(video_id, str):
901 video_id = ""
902 if video_id and not _is_valid_video_id(video_id):
903 _log(f"Skipping YouTube search item with invalid video_id: {video_id!r}")
904 continue
905 view_count = video.get("view_count") if video.get("view_count") is not None else 0
906 like_count = video.get("like_count") if video.get("like_count") is not None else 0
907 comment_count = video.get("comment_count") if video.get("comment_count") is not None else 0
908 upload_date = video.get("upload_date", "") # YYYYMMDD
909
910 # Convert YYYYMMDD to YYYY-MM-DD
911 date_str = None
912 if upload_date and len(upload_date) == 8:
913 date_str = f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"
914
915 description = str(video.get("description", ""))[:500]
916 items.append({
917 "video_id": video_id,
918 "title": video.get("title", ""),
919 "url": _youtube_watch_url(video_id) if video_id else "",
920 "channel_name": video.get("channel", video.get("uploader", "")),
921 "date": date_str,
922 "engagement": {
923 "views": view_count,
924 "likes": like_count,
925 "comments": comment_count,
926 },
927 "duration": video.get("duration"),
928 "relevance": _compute_relevance(core_topic, f"{video.get('title', '')} {description}"),
929 "why_relevant": f"YouTube: {video.get('title', core_topic)[:60]}",
930 "description": description,
931 })
932 return items
933
934
935 def _search_recent_uploads(
936 core_topic: str, count: int, sp: str, timeout: float,
937 ) -> Tuple[List[Dict[str, Any]], Optional[str]]:
938 """Search YouTube's results page with an upload-date filter.
939
940 Relevance-ranked ``ytsearch`` fills its top results with years-old videos
941 for topics that have a big back catalog (a music artist's official videos),
942 so a recent window can come back empty while new uploads exist. The
943 filtered results page returns only uploads from the period.
944
945 Returns the parsed videos and an error string when the search failed
946 without producing any, so the caller can keep the failure visible.
947 """
948 query = urllib.parse.urlencode({"search_query": core_topic, "sp": sp})
949 cmd = [
950 "yt-dlp",
951 "--ignore-config",
952 "--no-cookies-from-browser",
953 f"https://www.youtube.com/results?{query}",
954 "--playlist-end",
955 str(count),
956 "--dump-json",
957 "--no-warnings",
958 "--no-download",
959 ]
960 try:
961 result = _run_ytdlp(_wrap_ytdlp_cmd(cmd), timeout=timeout)
962 except subproc.SubprocTimeout:
963 _log(f"YouTube upload-date search timed out ({timeout:g}s)")
964 return [], f"Upload-date search timed out after {timeout:g}s"
965 except FileNotFoundError:
966 return [], "yt-dlp not found"
967 if result.returncode != 0:
968 _note_youtube_block(result.stderr or "")
969 items = _parse_search_stdout(result.stdout or "", core_topic)
970 _log(f"YouTube upload-date search found {len(items)} videos")
971 if result.returncode != 0 and not items:
972 return [], f"yt-dlp upload-date search failed: {_first_stderr_line(result.stderr)}"
973 return items, None
974
975
976 def search_youtube(
977 topic: str,
978 from_date: str,
979 to_date: str,
980 depth: str = "default",
981 freshness_mode: Optional[str] = None,
982 ) -> Dict[str, Any]:
983 """Search YouTube via yt-dlp. No API key needed.
984
985 Args:
986 topic: Search topic
987 from_date: Start date (YYYY-MM-DD)
988 to_date: End date (YYYY-MM-DD)
989 depth: 'quick', 'default', or 'deep'
990 freshness_mode: Plan freshness mode; scopes the out-of-window
991 fallback (see _apply_date_window). None keeps the soft fallback.
992
993 Returns:
994 Dict with 'items' list of video metadata dicts.
995 """
996 if not is_ytdlp_installed():
997 return {"items": [], "error": "yt-dlp not installed"}
998
999 count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
1000 core_topic = _extract_core_subject(topic)
1001 ssh_host = _ytdlp_ssh_host()
1002 cache_key = (core_topic, count, from_date, to_date, freshness_mode, ssh_host)
1003 timeout = _search_timeout()
1004
1005 cached, event, slot, is_leader = _claim_search_slot(cache_key)
1006 if cached is not None:
1007 _log(f"YouTube search cache hit for '{core_topic}' (count={count})")
1008 return cached
1009 assert event is not None and slot is not None
1010 if not is_leader:
1011 _log(f"YouTube search awaiting in-flight query for '{core_topic}'")
1012 return _await_search_slot(event, slot)
1013
1014 def _publish(payload: Dict[str, Any]) -> Dict[str, Any]:
1015 return _finish_search_slot(cache_key, payload, event=event, slot=slot)
1016
1017 _log(f"Searching YouTube for '{core_topic}' (since {from_date}, count={count})")
1018
1019 # yt-dlp search with full metadata (no --flat-playlist so dates are real).
1020 # NOTE: --dateafter intentionally omitted — YouTube search returns
1021 # relevance-sorted results and strict date filtering returns 0 for
1022 # evergreen topics. Python soft filter (below) handles date filtering.
1023 cmd = [
1024 "yt-dlp",
1025 "--ignore-config",
1026 "--no-cookies-from-browser",
1027 f"ytsearch{count}:{core_topic}",
1028 "--dump-json",
1029 "--no-warnings",
1030 "--no-download",
1031 ]
1032 cmd = _wrap_ytdlp_cmd(cmd)
1033
1034 published: Dict[str, Any] | None = None
1035 try:
1036 try:
1037 result = _run_ytdlp(cmd, timeout=timeout)
1038 except subproc.SubprocTimeout:
1039 _log(f"YouTube search timed out ({timeout:g}s)")
1040 published = _publish(
1041 {"items": [], "error": f"Search timed out after {timeout:g}s"}
1042 )
1043 return published
1044 except FileNotFoundError:
1045 published = _publish({"items": [], "error": "yt-dlp not found"})
1046 return published
1047
1048 stdout = result.stdout
1049 # A bot-check can land after yt-dlp has already printed some videos.
1050 # Keep those videos. Still record the block so later transcripts in
1051 # this search do not start another yt-dlp call. An empty stdout keeps
1052 # going through the error path below.
1053 if result.returncode != 0:
1054 _note_youtube_block(result.stderr or "")
1055 stderr = result.stderr or ""
1056 blocked = result.returncode != 0 and _is_youtube_bot_or_rate_limit(stderr)
1057 search_error: Optional[str] = None
1058 if result.returncode != 0 and not stdout.strip():
1059 first_line = _first_stderr_line(stderr)
1060 if ssh_host:
1061 _log(
1062 f"YouTube search via SSH host {ssh_host!r} failed "
1063 f"(rc={result.returncode}): {first_line}"
1064 )
1065 search_error = f"SSH routing to {ssh_host!r} failed: {first_line}"
1066 else:
1067 _log(f"YouTube search failed (rc={result.returncode}): {first_line}")
1068 search_error = f"yt-dlp search failed: {first_line}"
1069
1070 items = _parse_search_stdout(stdout, core_topic) if stdout.strip() else []
1071
1072 # Old catalog videos can crowd every relevance slot, and an age-gated
1073 # result can leave stdout empty. For a recent window, retry once with
1074 # YouTube's upload-date filter and merge. A bot block skips it.
1075 retry_error: Optional[str] = None
1076 sp = None
1077 if (
1078 freshness_mode in _RECENT_FRESHNESS_MODES
1079 and _count_in_window(items, from_date, to_date) < 3
1080 and not blocked
1081 and not _lane_out_of_time()
1082 ):
1083 sp = _upload_date_filter(from_date, to_date)
1084 if sp:
1085 _log(f"Retrying YouTube for '{core_topic}' with an upload-date filter")
1086 recent_items, retry_error = _search_recent_uploads(core_topic, count, sp, timeout)
1087 seen = {i["video_id"] for i in items}
1088 for item in recent_items:
1089 if item["video_id"] not in seen:
1090 seen.add(item["video_id"])
1091 items.append(item)
1092 if not items and not search_error and not retry_error:
1093 _log("YouTube search returned 0 results")
1094
1095 # Date filter: prefer recent items; the keep-all fallback is scoped
1096 # by freshness mode (evergreen only), see _apply_date_window.
1097 items = _apply_date_window(items, from_date, to_date, freshness_mode)
1098
1099 # Sort by views descending
1100 items.sort(key=lambda x: x["engagement"]["views"], reverse=True)
1101 payload: Dict[str, Any] = {"items": items}
1102 # Nothing usable survived: keep whichever search failed visible so the
1103 # run reports a failed source instead of a quiet zero.
1104 if not items and (search_error or retry_error):
1105 payload["error"] = search_error or retry_error
1106 published = _publish(payload)
1107 return published
1108 except Exception as exc:
1109 # Post-subprocess failures (parse/relevance/sort) must still unblock
1110 # coalesced waiters — otherwise the inflight key orphans forever.
1111 published = _publish({"items": [], "error": str(exc)})
1112 return published
1113 finally:
1114 if published is None:
1115 _publish({"items": [], "error": "YouTube search failed"})
1116
1117
1118 def _clean_vtt(vtt_text: str) -> str:
1119 """Convert VTT subtitle format to clean plaintext."""
1120 # Strip VTT header
1121 text = re.sub(r'^WEBVTT.*?\n\n', '', vtt_text, flags=re.DOTALL)
1122 # Strip timestamps
1123 text = re.sub(r'\d{2}:\d{2}:\d{2}\.\d{3}\s*-->\s*\d{2}:\d{2}:\d{2}\.\d{3}.*\n', '', text)
1124 # Strip position/alignment tags
1125 text = re.sub(r'<[^>]+>', '', text)
1126 # Strip cue numbers
1127 text = re.sub(r'^\d+\s*$', '', text, flags=re.MULTILINE)
1128 # Deduplicate overlapping lines
1129 lines = text.strip().split('\n')
1130 seen = set()
1131 unique = []
1132 for line in lines:
1133 stripped = line.strip()
1134 if stripped and stripped not in seen:
1135 seen.add(stripped)
1136 unique.append(stripped)
1137 return re.sub(r'\s+', ' ', ' '.join(unique)).strip()
1138
1139
1140 _YT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
1141
1142 # Safe YouTube video ID alphabet (base64url; real IDs are 11 chars, 1-64 permits
1143 # synthetic/fallback IDs while blocking path separators, traversal dots, glob
1144 # metacharacters, whitespace, control characters, and URL delimiters).
1145 _VIDEO_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
1146
1147 _MAX_TRANSCRIPT_RESPONSE_BYTES = 5 * 1024 * 1024 # 5 MiB cap for watch HTML & VTT
1148 _YT_TRANSCRIPT_EXACT_HOSTS = frozenset({"youtube.com", "video.google.com"})
1149 _YT_TRANSCRIPT_SUFFIX_HOSTS = (".youtube.com", ".googlevideo.com", ".ytimg.com")
1150 _YT_TRANSCRIPT_REDIRECT_POLICY = {
1151 "https_only": True,
1152 "require_public_syntax": True,
1153 "exact_hosts": sorted(_YT_TRANSCRIPT_EXACT_HOSTS),
1154 "suffix_hosts": list(_YT_TRANSCRIPT_SUFFIX_HOSTS),
1155 "allowed_ports": [443],
1156 }
1157 _STRICT_HOSTNAME_RE = re.compile(
1158 r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$"
1159 )
1160
1161
1162 def _is_valid_video_id(video_id: Any) -> bool:
1163 """Return True when ``video_id`` is a safe YouTube video identifier."""
1164 return isinstance(video_id, str) and bool(_VIDEO_ID_RE.fullmatch(video_id))
1165
1166
1167 def _youtube_watch_url(video_id: str) -> str:
1168 """Build a canonical YouTube watch URL after strictly validating ``video_id``."""
1169 if not _is_valid_video_id(video_id):
1170 raise ValueError(f"invalid YouTube video_id: {video_id!r}")
1171 return f"https://www.youtube.com/watch?v={urllib.parse.quote(video_id, safe='')}"
1172
1173
1174 def _is_allowed_youtube_transcript_url(url: str) -> bool:
1175 """Validate a YouTube watch or caption URL (and any redirect target)."""
1176 if not isinstance(url, str) or not url or url != url.strip():
1177 return False
1178 if any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in url):
1179 return False
1180 if not public_host.is_public_address_syntax(url):
1181 return False
1182 try:
1183 parts = urllib.parse.urlsplit(url)
1184 port = parts.port
1185 except ValueError:
1186 return False
1187 if parts.scheme.lower() != "https":
1188 return False
1189 if parts.username is not None or parts.password is not None:
1190 return False
1191 if "\\" in parts.netloc or port not in (None, 443):
1192 return False
1193 raw_host = parts.hostname or ""
1194 if not raw_host or not raw_host.isascii():
1195 return False
1196 host = raw_host[:-1].lower() if raw_host.endswith(".") else raw_host.lower()
1197 if len(host) > 253 or not _STRICT_HOSTNAME_RE.fullmatch(host):
1198 return False
1199 if public_host._parse_ip_literal(host) is not None:
1200 return False
1201 return host in _YT_TRANSCRIPT_EXACT_HOSTS or host.endswith(_YT_TRANSCRIPT_SUFFIX_HOSTS)
1202
1203
1204 def _read_bounded_response(
1205 response: Any,
1206 max_bytes: int = _MAX_TRANSCRIPT_RESPONSE_BYTES,
1207 ) -> bytes:
1208 """Read at most ``max_bytes`` from an HTTP response object."""
1209 try:
1210 data = response.read(max_bytes + 1)
1211 except TypeError:
1212 # Minimal unit-test stubs implement read() without a size parameter.
1213 data = response.read()
1214 if not isinstance(data, (bytes, bytearray)):
1215 raise OSError("unexpected non-bytes HTTP response body")
1216 if len(data) > max_bytes:
1217 raise OSError(f"YouTube transcript response exceeded {max_bytes} bytes")
1218 return bytes(data)
1219
1220
1221 def _read_transcript_url(req: urllib.request.Request, timeout: float) -> str:
1222 if not _is_allowed_youtube_transcript_url(req.full_url):
1223 raise urllib.error.URLError(
1224 f"refused disallowed YouTube transcript URL: {req.full_url!r}"
1225 )
1226 setattr(req, http._REDIRECT_GUARD_ATTR, _is_allowed_youtube_transcript_url)
1227 setattr(req, http._PUBLIC_ONLY_ATTR, True)
1228 setattr(req, bounded_get._REDIRECT_POLICY_ATTR, _YT_TRANSCRIPT_REDIRECT_POLICY)
1229 deadline = _lane_deadline()
1230 if deadline is None:
1231 with http.open_request(req, timeout) as response:
1232 raw = _read_bounded_response(response, _MAX_TRANSCRIPT_RESPONSE_BYTES)
1233 return raw.decode("utf-8", errors="replace")
1234 if deadline <= time.monotonic():
1235 raise TimeoutError("YouTube lane deadline passed")
1236 limit = _sc_spend_limit.get()
1237 _, body, error = bounded_get.get(
1238 req, timeout=timeout, deadline_monotonic=deadline,
1239 cancel=limit.cancel if limit else None, read_error_body=False,
1240 max_bytes=_MAX_TRANSCRIPT_RESPONSE_BYTES,
1241 )
1242 if error is not None:
1243 raise error
1244 if body is not None and len(body) > _MAX_TRANSCRIPT_RESPONSE_BYTES:
1245 raise OSError(
1246 f"YouTube transcript response exceeded {_MAX_TRANSCRIPT_RESPONSE_BYTES} bytes"
1247 )
1248 return (body or b"").decode("utf-8", errors="replace")
1249
1250
1251 def _fetch_transcript_direct(
1252 video_id: str,
1253 timeout: int = 30,
1254 status: Optional[Dict[str, Any]] = None,
1255 ) -> Optional[str]:
1256 """Fetch YouTube transcript via direct HTTP without yt-dlp.
1257
1258 Scrapes the watch page HTML for the captions track URL in
1259 ytInitialPlayerResponse, then fetches the VTT subtitle file.
1260
1261 Args:
1262 video_id: YouTube video ID
1263 timeout: HTTP request timeout in seconds
1264 status: Optional dict mutated to record per-video signals. Sets
1265 ``status["no_caption_tracks"] = True`` when the player response
1266 confirms the uploader has no caption tracks (vs. fetch failure).
1267
1268 Returns:
1269 Raw VTT text, or None if captions are unavailable.
1270 """
1271 if not _is_valid_video_id(video_id):
1272 _log(f"Direct transcript: refused invalid video_id {video_id!r}")
1273 return None
1274 watch_url = _youtube_watch_url(video_id)
1275 headers = {
1276 "User-Agent": _YT_USER_AGENT,
1277 "Accept-Language": "en-US,en;q=0.9",
1278 }
1279
1280 # Step 1: Fetch the watch page HTML
1281 req = urllib.request.Request(watch_url, headers=headers)
1282 try:
1283 html = _read_transcript_url(req, timeout)
1284 except (urllib.error.URLError, urllib.error.HTTPError, OSError, TimeoutError) as exc:
1285 _log(f"Direct transcript: failed to fetch watch page for {video_id}: {exc}")
1286 return None
1287
1288 # Step 2: Extract captions URL from ytInitialPlayerResponse
1289 # YouTube embeds this as a JS variable in the page HTML
1290 match = re.search(
1291 r'ytInitialPlayerResponse\s*=\s*(\{.+?\})\s*;(?:\s*var\s|\s*<\/script>)',
1292 html,
1293 )
1294 if not match:
1295 # Fallback: try the JSON embedded in the script tag
1296 match = re.search(
1297 r'var\s+ytInitialPlayerResponse\s*=\s*(\{.+?\})\s*;',
1298 html,
1299 )
1300 if not match:
1301 _log(f"Direct transcript: no ytInitialPlayerResponse found for {video_id}")
1302 return None
1303
1304 try:
1305 player_response = json.loads(match.group(1))
1306 except json.JSONDecodeError:
1307 _log(f"Direct transcript: failed to parse ytInitialPlayerResponse for {video_id}")
1308 return None
1309 if not isinstance(player_response, dict):
1310 return None
1311
1312 # Navigate to caption tracks
1313 captions = player_response.get("captions") or {}
1314 renderer = captions.get("playerCaptionsTracklistRenderer") or {} if isinstance(captions, dict) else {}
1315 caption_tracks = renderer.get("captionTracks") or [] if isinstance(renderer, dict) else []
1316 if not isinstance(caption_tracks, list):
1317 caption_tracks = []
1318 caption_tracks = [track for track in caption_tracks if isinstance(track, dict)]
1319
1320 if not caption_tracks:
1321 _log(f"Direct transcript: no caption tracks for {video_id}")
1322 if status is not None:
1323 status["no_caption_tracks"] = True
1324 return None
1325
1326 # Find English track (prefer exact 'en', then any en variant, then first track)
1327 base_url = None
1328 for track in caption_tracks:
1329 lang = track.get("languageCode", "")
1330 if lang == "en":
1331 base_url = track.get("baseUrl")
1332 break
1333 if not base_url:
1334 for track in caption_tracks:
1335 lang = track.get("languageCode", "")
1336 if isinstance(lang, str) and lang.startswith("en"):
1337 base_url = track.get("baseUrl")
1338 break
1339 if not base_url:
1340 # Fall back to first available track
1341 base_url = caption_tracks[0].get("baseUrl")
1342 if not isinstance(base_url, str) or not base_url:
1343 _log(f"Direct transcript: no baseUrl in caption tracks for {video_id}")
1344 return None
1345 if not _is_allowed_youtube_transcript_url(base_url):
1346 _log(f"Direct transcript: refused disallowed caption baseUrl for {video_id}: {base_url!r}")
1347 return None
1348
1349 # Step 3: Fetch the VTT subtitle file
1350 parsed_base = urllib.parse.urlsplit(base_url)
1351 clean_base = urllib.parse.urlunsplit(parsed_base._replace(fragment=""))
1352 sep = "&" if "?" in clean_base else "?"
1353 vtt_url = f"{clean_base}{sep}fmt=vtt"
1354 if not _is_allowed_youtube_transcript_url(vtt_url):
1355 _log(f"Direct transcript: refused disallowed VTT URL for {video_id}")
1356 return None
1357 vtt_req = urllib.request.Request(vtt_url, headers=headers)
1358 try:
1359 vtt_text = _read_transcript_url(vtt_req, timeout)
1360 except (urllib.error.URLError, urllib.error.HTTPError, OSError, TimeoutError) as exc:
1361 _log(f"Direct transcript: failed to fetch VTT for {video_id}: {exc}")
1362 return None
1363
1364 if not vtt_text or not vtt_text.strip():
1365 return None
1366
1367 return vtt_text
1368
1369
1370 def _fetch_transcript_ytdlp_via_ssh(
1371 video_id: str,
1372 ssh_host: str,
1373 *,
1374 abort_if_blocked: bool = False,
1375 ) -> Optional[str]:
1376 """Fetch transcript via yt-dlp on a remote SSH host (mktemp + cat pipeline)."""
1377 if not _SSH_HOST_ALIAS_RE.match(ssh_host) or not _is_valid_video_id(video_id):
1378 return None
1379 url = _youtube_watch_url(video_id)
1380 quoted_url = shlex.quote(url)
1381 sub_langs = shlex.quote(_ytdlp_request_langs())
1382 client = _ytdlp_player_client()
1383 extractor = (
1384 f"--extractor-args {shlex.quote(f'youtube:player_client={client}')} "
1385 if client
1386 else ""
1387 )
1388 proxy = _ytdlp_proxy()
1389 proxy_flag = f"--proxy {shlex.quote(proxy)} " if proxy else ""
1390 remote_script = (
1391 "set -e; "
1392 "TMPD=$(mktemp -d); "
1393 "YTDLP_RC=0; "
1394 "yt-dlp --ignore-config --no-cookies-from-browser "
1395 f"{extractor}"
1396 f"{proxy_flag}"
1397 f"--write-subs --write-auto-subs --sub-lang {sub_langs} --sub-format vtt "
1398 "--skip-download --no-warnings "
1399 f'-o "$TMPD/%(id)s" -- {quoted_url} >/dev/null || YTDLP_RC=$?; '
1400 'VTT=$(find "$TMPD" -maxdepth 1 -name "*.vtt" 2>/dev/null | head -1); '
1401 '[ -n "$VTT" ] && cat "$VTT"; '
1402 'rm -rf "$TMPD"; exit "$YTDLP_RC"'
1403 )
1404 cmd = ["ssh", "-o", "BatchMode=yes", "--", ssh_host, remote_script]
1405 try:
1406 result = _run_ytdlp(cmd, timeout=45, abort_if_blocked=abort_if_blocked)
1407 except subproc.SubprocTimeout:
1408 _log(f"SSH yt-dlp transcript timed out for {video_id} via {ssh_host!r}")
1409 return None
1410 except FileNotFoundError:
1411 _log("ssh executable not found; cannot route transcript fetch")
1412 return None
1413 out = result.stdout or ""
1414 if not out.strip().startswith("WEBVTT"):
1415 if result.returncode != 0 and result.stderr:
1416 first_line = result.stderr.strip().splitlines()[0]
1417 _log(
1418 f"SSH yt-dlp transcript via {ssh_host!r} failed for "
1419 f"{video_id} (rc={result.returncode}): {first_line}"
1420 )
1421 return None
1422 return out
1423
1424
1425 def _ytdlp_sub_langs() -> str:
1426 """Caption languages to try, from LAST30DAYS_YT_SUB_LANGS (default en,es,pt)."""
1427 raw = os.environ.get("LAST30DAYS_YT_SUB_LANGS", "").strip()
1428 if not raw:
1429 return "en,es,pt"
1430 return ",".join(code.strip().lower() for code in raw.split(",") if code.strip()) or "en,es,pt"
1431
1432
1433 def _ytdlp_request_langs() -> str:
1434 """The ``--sub-lang`` value: every configured ``<lang>-orig``, then the plain codes.
1435
1436 Auto-dubbed videos expose the original-speech auto track as
1437 ``<lang>-orig``, and their plain ``<lang>`` tracks are translations that
1438 can 429 every time while ``-orig`` downloads (#1314). yt-dlp downloads
1439 languages in order and stops at the first error, so every ``-orig`` track
1440 comes before any plain code: a Spanish video dubbed into English must
1441 reach ``es-orig`` before the translated ``en`` can fail. The partial-VTT
1442 salvage keeps the ``-orig`` file when a plain track then fails. yt-dlp
1443 skips languages a video does not have, so non-dubbed videos are
1444 unaffected. A code configured as ``-orig`` stays original-only.
1445 """
1446 codes = _ytdlp_sub_langs().split(",")
1447 originals = [code if code.endswith("-orig") else f"{code}-orig" for code in codes]
1448 plain = [code for code in codes if not code.endswith("-orig")]
1449 return ",".join(dict.fromkeys(originals + plain))
1450
1451
1452 def _transcript_fast_timeout() -> float:
1453 """Return the keyed-run yt-dlp timeout, preserving the 12s default."""
1454 return _env_positive_float(
1455 "LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT",
1456 float(_TRANSCRIPT_FAST_TIMEOUT),
1457 )
1458
1459
1460 def _transcript_fast_attempts() -> int:
1461 """Return keyed-run yt-dlp attempts before the SC rescue (default 1, #1316)."""
1462 raw = os.environ.get("LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS", "").strip()
1463 try:
1464 value = int(raw)
1465 except ValueError:
1466 return 1
1467 return value if value > 0 else 1
1468
1469 def _pick_ytdlp_vtt(video_id: str, temp_dir: str, priority: List[str]) -> Optional[Path]:
1470 """Return the best on-disk VTT match for video_id, preferring priority order."""
1471 if not _is_valid_video_id(video_id):
1472 return None
1473 base_dir = Path(temp_dir).resolve()
1474 escaped = glob.escape(video_id)
1475 # Require a dot separator after video_id so prefix IDs like YT1 cannot match YT10.en.vtt.
1476 raw_matches = list(base_dir.glob(f"{escaped}.*.vtt"))
1477 exact_vtt = base_dir / f"{video_id}.vtt"
1478 if exact_vtt.exists():
1479 raw_matches.append(exact_vtt)
1480 matches: List[Path] = []
1481 seen_paths: Set[Path] = set()
1482 for candidate in raw_matches:
1483 if candidate.is_symlink():
1484 continue
1485 try:
1486 resolved = candidate.resolve(strict=True)
1487 except OSError:
1488 continue
1489 if resolved.parent != base_dir or not resolved.is_file():
1490 continue
1491 if resolved not in seen_paths:
1492 seen_paths.add(resolved)
1493 matches.append(resolved)
1494 if not matches:
1495 return None
1496 # A configured "en-orig" ranks as "en": files are matched by base code.
1497 priority_index: Dict[str, int] = {}
1498 for code in priority:
1499 priority_index.setdefault(code.removesuffix("-orig"), len(priority_index))
1500
1501 def rank(p: Path) -> Tuple[int, int]:
1502 stem = p.stem
1503 suffix = stem[len(video_id) + 1:] if stem.startswith(video_id + ".") else ""
1504 code = suffix.split("-")[0].split(".")[0]
1505 # Within one language, a plain track that downloaded wins: it is the
1506 # uploaded subtitle when one exists, and otherwise the same speech
1507 # recognition as -orig. The -orig file is the fallback for when the
1508 # plain track 429s (#1314).
1509 return (priority_index.get(code, len(priority_index)), 1 if suffix.endswith("-orig") else 0)
1510
1511 return sorted(matches, key=rank)[0]
1512
1513
1514 def _transcript_backoff(video_id: str, attempt: int) -> float:
1515 """Backoff seconds before a transcript retry.
1516
1517 Staggered per-video (a sub-second offset derived from the id) so parallel
1518 workers don't retry in lockstep and re-trip YouTube's limiter.
1519 """
1520 offset = (sum(ord(c) for c in video_id) % 1000) / 1000.0 # 0.0–1.0s
1521 return _TRANSCRIPT_BACKOFF_BASE * (attempt + 1) + offset
1522
1523
1524 def _wait_for_transcript_retry(video_id: str, attempt: int) -> bool:
1525 delay = _transcript_backoff(video_id, attempt)
1526 remaining = _lane_seconds_left()
1527 if remaining is not None and delay >= remaining:
1528 return False
1529 limit = _sc_spend_limit.get()
1530 if limit is not None and limit.cancel is not None:
1531 return not limit.cancel.wait(delay)
1532 time.sleep(delay)
1533 return True
1534
1535
1536 def _read_vtt(video_id: str, temp_dir: str) -> Optional[str]:
1537 """Return the VTT text yt-dlp wrote for ``video_id``, or None if absent."""
1538 vtt_path = _pick_ytdlp_vtt(video_id, temp_dir, _ytdlp_sub_langs().split(","))
1539 if vtt_path is None:
1540 return None
1541
1542 try:
1543 return vtt_path.read_text(encoding="utf-8", errors="replace")
1544 except OSError:
1545 return None
1546
1547
1548 def _fetch_transcript_ytdlp(
1549 video_id: str,
1550 temp_dir: str,
1551 status: Optional[Dict[str, Any]] = None,
1552 fast_fail: bool = False,
1553 ) -> Optional[str]:
1554 """Fetch transcript using yt-dlp (original implementation).
1555
1556 Args:
1557 video_id: YouTube video ID
1558 temp_dir: Temporary directory for subtitle files
1559 status: Optional dict mutated to record a yt-dlp failure reason
1560 (``status["ytdlp_error"]``) so the caller can tell a real fetch
1561 error (rate-limit / bot-check / network / timeout) apart from a
1562 video that genuinely has no captions, and skip the misleading
1563 "no captions found" log + the YouTube-blocked HTTP fallback.
1564 fast_fail: When True, a ScrapeCreators fallback is available, so a
1565 transient failure (429 / bot-gate) should fail over fast rather
1566 than retry into the same rate limit. Collapses to a single attempt
1567 (``LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS`` raises it) with a
1568 shorter per-attempt timeout. The slow thing in a run is
1569 yt-dlp retrying, not the fast SC fetch, so this is what keeps
1570 "yt-dlp first" from reintroducing the multi-minute hang.
1571
1572 Returns:
1573 Raw VTT text, or None if no captions are available or the fetch failed.
1574 On a hard (non-no-caption) failure, sets ``status["ytdlp_error"]``.
1575 """
1576 if not _is_valid_video_id(video_id):
1577 _log(f"yt-dlp transcript: refused invalid video_id {video_id!r}")
1578 return None
1579 watch_url = _youtube_watch_url(video_id)
1580 cmd = [
1581 "yt-dlp",
1582 "--ignore-config",
1583 "--no-cookies-from-browser",
1584 # --write-subs: a video with uploaded subtitles and no auto track
1585 # otherwise exits 0 with no file and falls through to paid SC (#1313).
1586 # yt-dlp prefers the uploaded track when both exist for a language.
1587 "--write-subs",
1588 "--write-auto-subs",
1589 "--sub-lang", _ytdlp_request_langs(),
1590 "--sub-format", "vtt",
1591 "--skip-download",
1592 "--no-warnings",
1593 "-o", f"{temp_dir}/%(id)s",
1594 "--",
1595 watch_url,
1596 ]
1597 cmd = _inject_youtube_player_client(cmd)
1598 proxy = _ytdlp_proxy()
1599 if proxy:
1600 cmd = _append_ytdlp_option(cmd, ["--proxy", proxy])
1601
1602 timeout = _transcript_fast_timeout() if fast_fail else _TRANSCRIPT_TIMEOUT
1603 attempts = _transcript_fast_attempts() if fast_fail else _TRANSCRIPT_MAX_RETRIES + 1
1604 last_reason: Optional[str] = None
1605 for attempt in range(attempts):
1606 try:
1607 result = _run_ytdlp(
1608 cmd, timeout=timeout, abort_if_blocked=fast_fail,
1609 )
1610 except subproc.SubprocTimeout as exc:
1611 if "lane deadline" in str(exc).lower():
1612 last_reason = "lane deadline reached"
1613 _log(
1614 f"yt-dlp transcript for {video_id} hit the lane deadline "
1615 f"(attempt {attempt + 1}/{attempts})"
1616 )
1617 else:
1618 last_reason = f"timed out after {timeout}s"
1619 _log(f"yt-dlp transcript timed out after {timeout}s for {video_id} "
1620 f"(attempt {attempt + 1}/{attempts})")
1621 # yt-dlp downloads requested languages sequentially. A timeout can
1622 # therefore leave a complete first-choice VTT on disk; keep it
1623 # instead of spending a ScrapeCreators fallback credit.
1624 partial_vtt = _read_vtt(video_id, temp_dir)
1625 if partial_vtt is not None:
1626 return partial_vtt
1627 if attempt < attempts - 1 and _wait_for_transcript_retry(video_id, attempt):
1628 continue
1629 break
1630 except FileNotFoundError:
1631 # yt-dlp binary missing — not transient, not retryable.
1632 if status is not None:
1633 status["ytdlp_error"] = "yt-dlp not found"
1634 return None
1635
1636 if result.returncode == 0:
1637 vtt = _read_vtt(video_id, temp_dir)
1638 if vtt is not None:
1639 return vtt
1640 # Exit 0 with no file == the uploader has no matching captions.
1641 # Genuine no-captions: return quietly (caller may still try direct).
1642 return None
1643
1644 # Non-zero exit, but yt-dlp may have written a usable VTT before the
1645 # failing language errored. With the default `--sub-lang en,es,pt`, an
1646 # English video fetches `en` fine, then `es`/`pt` hit a 429 and yt-dlp
1647 # exits non-zero — yet the `en` track is already on disk. A partial
1648 # success is still a real transcript, so salvage any VTT before
1649 # classifying this as an error (and, worse, retrying straight back into
1650 # the same rate limit). This is the root cause of the 0/N transcript
1651 # runs reported when every video had captions.
1652 partial_vtt = _read_vtt(video_id, temp_dir)
1653 if partial_vtt is not None:
1654 return partial_vtt
1655
1656 # Non-zero exit == a real error worth classifying & surfacing.
1657 stderr = (result.stderr or "").strip()
1658 snippet = (stderr.splitlines()[-1][:200] if stderr
1659 else f"exit {result.returncode}")
1660 if _NO_CAPTION_RE.search(stderr):
1661 # yt-dlp can exit non-zero when the requested language is absent.
1662 # Treat as genuine no-captions, not an error worth retrying.
1663 return None
1664 last_reason = snippet
1665 if (
1666 _TRANSIENT_RE.search(stderr) and attempt < attempts - 1
1667 and _wait_for_transcript_retry(video_id, attempt)
1668 ):
1669 _log(f"yt-dlp transcript transient failure for {video_id} "
1670 f"(attempt {attempt + 1}/{attempts}): {snippet}")
1671 continue
1672 # Non-transient, or retries exhausted — surface the real reason.
1673 _log(f"yt-dlp transcript failed for {video_id} "
1674 f"(exit {result.returncode}): {snippet}")
1675 break
1676
1677 if status is not None and last_reason is not None:
1678 status["ytdlp_error"] = last_reason
1679 return None
1680
1681
1682 def _should_try_sc_transcript(status: Optional[Dict[str, Any]]) -> bool:
1683 """Whether to spend a ScrapeCreators credit after the keyless cascade failed.
1684
1685 Skip when the keyless path *proved* the uploader has no caption track
1686 (``no_caption_tracks``): SC would also return nothing, so a credit would be
1687 wasted. A transient hard failure (``ytdlp_error``: 429 / bot-gate / timeout)
1688 is a false negative, so SC is worth trying.
1689 """
1690 st = status or {}
1691 return not st.get("no_caption_tracks")
1692
1693
1694 class _RescueBudget:
1695 """Thread-safe cap on successful SC transcript rescues in one batch.
1696
1697 A call reserves a slot before it is made and settles it afterwards: a
1698 transcript fills the slot, an empty result frees it. While every open slot
1699 is held by a call still in flight, other workers wait for one to settle
1700 instead of skipping their video, so a miss never leaves the target short.
1701 """
1702
1703 def __init__(self, limit: int):
1704 self._limit = limit
1705 self._filled = 0
1706 self._pending = 0
1707 self._cond = threading.Condition()
1708
1709 def reserve(self) -> bool:
1710 with self._cond:
1711 while self._filled < self._limit and self._filled + self._pending >= self._limit:
1712 self._cond.wait()
1713 if self._filled >= self._limit:
1714 return False
1715 self._pending += 1
1716 return True
1717
1718 def settle(self, filled: bool) -> None:
1719 with self._cond:
1720 self._pending -= 1
1721 if filled:
1722 self._filled += 1
1723 self._cond.notify_all()
1724
1725
1726 def fetch_transcript(
1727 video_id: str,
1728 temp_dir: str,
1729 status: Optional[Dict[str, Any]] = None,
1730 token: Optional[str] = None,
1731 rescue_budget: Optional[_RescueBudget] = None,
1732 ) -> Optional[str]:
1733 """Fetch auto-generated transcript for a YouTube video.
1734
1735 Uses yt-dlp when available (preferred, more robust). Falls back to
1736 direct HTTP transcript fetching when yt-dlp is not installed, and finally
1737 to the ScrapeCreators transcript endpoint when a key is present and the
1738 keyless cascade comes back empty.
1739
1740 Args:
1741 video_id: YouTube video ID
1742 temp_dir: Temporary directory for subtitle files
1743 status: Optional dict mutated by the direct-HTTP path to record
1744 per-video signals like ``no_caption_tracks``. Used to surface a
1745 captions-disabled count so the quality nudge avoids false-positive
1746 "stale yt-dlp" flags.
1747 token: Optional ScrapeCreators API key. When present, yt-dlp fails over
1748 fast (see ``_fetch_transcript_ytdlp`` ``fast_fail``) and a true hard
1749 failure falls back to the SC transcript endpoint. A credit is only
1750 spent on a genuine yt-dlp failure, never on success and never on a
1751 video proven to have no captions. None preserves keyless behavior.
1752 rescue_budget: Optional cap shared across a batch. A rescue reserves a
1753 slot before the paid call and keeps it only when it returns a
1754 transcript; once the cap is filled the video stays without one.
1755
1756 Returns:
1757 Plaintext transcript string, or None if no captions available.
1758 """
1759 if not _is_valid_video_id(video_id):
1760 _log(f"Refused invalid YouTube video_id: {video_id!r}")
1761 return None
1762 raw_vtt = None
1763 skip_ytdlp = False
1764 ssh_host = _ytdlp_ssh_host()
1765 # A bot-check or 429 already happened in this search. More yt-dlp calls
1766 # hit the same wall, so a keyed run goes straight to ScrapeCreators.
1767 # With no key, every video still tries yt-dlp. Workers that queued for a
1768 # slot before the flag flipped raise _YtdlpBlocked once the slot is free.
1769 if token and _youtube_transcripts_blocked():
1770 skip_ytdlp = True
1771 elif ssh_host and is_ytdlp_installed():
1772 try:
1773 if token:
1774 raw_vtt = _fetch_transcript_ytdlp_via_ssh(
1775 video_id, ssh_host, abort_if_blocked=True,
1776 )
1777 else:
1778 raw_vtt = _fetch_transcript_ytdlp_via_ssh(video_id, ssh_host)
1779 except _YtdlpBlocked:
1780 skip_ytdlp = True
1781 else:
1782 if not raw_vtt:
1783 if token and _youtube_transcripts_blocked():
1784 skip_ytdlp = True
1785 else:
1786 _log(f"SSH yt-dlp transcript failed for {video_id}, trying direct HTTP fallback")
1787 raw_vtt = _fetch_transcript_direct(video_id, status=status)
1788 elif is_ytdlp_installed():
1789 try:
1790 raw_vtt = _fetch_transcript_ytdlp(
1791 video_id, temp_dir, status=status, fast_fail=bool(token),
1792 )
1793 except _YtdlpBlocked:
1794 skip_ytdlp = True
1795 else:
1796 if not raw_vtt:
1797 ytdlp_error = (status or {}).get("ytdlp_error")
1798 if ytdlp_error:
1799 # Hard failure (429 / bot-gate / timeout). The direct-HTTP
1800 # fallback is also YouTube-blocked, so skip it and let the
1801 # ScrapeCreators fallback below handle it when a key is present.
1802 # A 429 or bot-check also stops later videos in this search
1803 # from starting another yt-dlp call.
1804 _note_youtube_block(ytdlp_error)
1805 _log(f"Transcript fetch failed for {video_id}: {ytdlp_error}")
1806 else:
1807 _log(f"yt-dlp found no captions for {video_id}, trying direct HTTP fallback")
1808 raw_vtt = _fetch_transcript_direct(video_id, status=status)
1809 else:
1810 _log("yt-dlp not installed, using direct HTTP transcript fetch")
1811 raw_vtt = _fetch_transcript_direct(video_id, status=status)
1812
1813 if skip_ytdlp:
1814 _log(
1815 f"Skipping yt-dlp transcript for {video_id} after a YouTube "
1816 f"bot-check or rate limit"
1817 )
1818
1819 if raw_vtt:
1820 transcript = _clean_vtt(raw_vtt)
1821 # Truncate to max words
1822 words = transcript.split()
1823 if len(words) > TRANSCRIPT_MAX_WORDS:
1824 transcript = ' '.join(words[:TRANSCRIPT_MAX_WORDS]) + '...'
1825 return transcript if transcript else None
1826
1827 # Keyless cascade produced nothing. When a ScrapeCreators key is present and
1828 # the video was not proven caption-less, fall back to the SC transcript
1829 # endpoint (fetched server-side: no 429, cookies, or PO tokens). Returns
1830 # already-cleaned, word-capped plaintext.
1831 if (
1832 token
1833 and _should_try_sc_transcript(status)
1834 and not _lane_out_of_time()
1835 and (rescue_budget is None or rescue_budget.reserve())
1836 ):
1837 sc_transcript = None
1838 try:
1839 sc_transcript = _sc_fetch_transcript(video_id, token)
1840 finally:
1841 if rescue_budget is not None:
1842 rescue_budget.settle(bool(sc_transcript))
1843 if sc_transcript:
1844 # The keyless cascade (yt-dlp / direct HTTP) already logged its
1845 # failure above. Without this line that failure is the last thing
1846 # printed for this video, and the batch summary in
1847 # fetch_transcripts_parallel() counts it as a plain success —
1848 # making a rate-limited/bot-gated run look like nothing went
1849 # wrong. Log the rescue and flag it in `status` so the summary
1850 # can report it explicitly instead of masking it (#831).
1851 _log(f"ScrapeCreators transcript fallback rescued {video_id} "
1852 f"after the keyless fetch cascade failed")
1853 if status is not None:
1854 status["sc_rescued"] = True
1855 return sc_transcript
1856
1857 _log(f"No transcript available for {video_id}")
1858 return None
1859
1860
1861 def fetch_transcripts_parallel(
1862 video_ids: List[str],
1863 max_workers: int = 5,
1864 out_captions_disabled: Optional[Set[str]] = None,
1865 token: Optional[str] = None,
1866 max_sc_rescues: Optional[int] = None,
1867 ) -> Dict[str, Optional[str]]:
1868 """Fetch transcripts for multiple videos in parallel.
1869
1870 Args:
1871 video_ids: List of YouTube video IDs
1872 max_workers: Max parallel fetches
1873 out_captions_disabled: Optional set mutated to record video_ids whose
1874 uploader confirmed no caption tracks (vs. transient fetch failures).
1875 Backward-compatible: callers that don't care can omit.
1876 token: Optional ScrapeCreators API key, threaded to each
1877 ``fetch_transcript`` so the per-video SC fallback activates on
1878 yt-dlp failure. None preserves keyless behavior.
1879 max_sc_rescues: Cap on successful SC rescues across the batch,
1880 normally the transcript target. Callers try up to 3x the target so
1881 free fetches have headroom; without a cap every yt-dlp failure in
1882 that headroom was a paid call. None = no cap.
1883
1884 Returns:
1885 Dict mapping video_id to transcript text (or None). A video still
1886 fetching when the lane ran out of time has no entry.
1887 """
1888 with _youtube_block_scope():
1889 return _fetch_transcripts_parallel(
1890 video_ids,
1891 max_workers=max_workers,
1892 out_captions_disabled=out_captions_disabled,
1893 token=token,
1894 max_sc_rescues=max_sc_rescues,
1895 )
1896
1897
1898 def _fetch_transcripts_parallel(
1899 video_ids: List[str],
1900 max_workers: int = 5,
1901 out_captions_disabled: Optional[Set[str]] = None,
1902 token: Optional[str] = None,
1903 max_sc_rescues: Optional[int] = None,
1904 ) -> Dict[str, Optional[str]]:
1905 if not video_ids:
1906 return {}
1907 rescue_budget = _RescueBudget(max_sc_rescues) if max_sc_rescues is not None else None
1908
1909 _log(f"Fetching transcripts for {len(video_ids)} videos")
1910
1911 results = {}
1912 statuses: Dict[str, Dict[str, Any]] = {vid: {} for vid in video_ids}
1913 unfinished: List[str] = []
1914 seconds_left = _lane_seconds_left()
1915 # A yt-dlp child killed at the lane deadline can still be writing here.
1916 with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as temp_dir:
1917 executor = ThreadPoolExecutor(max_workers=max_workers)
1918 try:
1919 futures = {}
1920 for idx, vid in enumerate(video_ids):
1921 vid_dir = os.path.join(temp_dir, f"v{idx}")
1922 os.makedirs(vid_dir, exist_ok=True)
1923 fut = http.submit_with_context(
1924 executor, fetch_transcript, vid, vid_dir, statuses[vid], token,
1925 rescue_budget=rescue_budget,
1926 )
1927 futures[fut] = vid
1928 try:
1929 for future in as_completed(
1930 futures, timeout=None if seconds_left is None else max(0.0, seconds_left),
1931 ):
1932 vid = futures[future]
1933 try:
1934 results[vid] = future.result()
1935 except OSError as exc:
1936 _log(f"Transcript fetch error for {vid}: {exc}")
1937 results[vid] = None
1938 except Exception as exc:
1939 _log(f"Unexpected transcript error for {vid}: {type(exc).__name__}: {exc}")
1940 results[vid] = None
1941 except FuturesTimeout:
1942 unfinished = [vid for future, vid in futures.items() if vid not in results]
1943 _log(f"Stopped waiting for {len(unfinished)} transcripts: the lane is out of time")
1944 finally:
1945 executor.shutdown(wait=not unfinished, cancel_futures=bool(unfinished))
1946
1947 if out_captions_disabled is not None:
1948 for vid, st in statuses.items():
1949 if st.get("no_caption_tracks"):
1950 out_captions_disabled.add(vid)
1951
1952 got = sum(1 for v in results.values() if v)
1953 errors = sum(1 for v in results.values() if v is None)
1954 # `got` includes videos that only succeeded because the ScrapeCreators
1955 # fallback rescued a failed keyless fetch — yt-dlp when available, or the
1956 # direct HTTP path alone (see fetch_transcript()). Folding
1957 # those into a bare "M failed" count previously made a fully rate-limited
1958 # yt-dlp run — every fetch failing, silently saved by the fallback — read
1959 # as "0 failed", with no trace of the fallback ever having fired (#831).
1960 # Surface the split so the summary can't misrepresent a masked failure
1961 # as a clean success.
1962 sc_rescued = sum(1 for st in statuses.values() if st.get("sc_rescued"))
1963 _add_transcript_fetch_stats(sc_rescued=sc_rescued)
1964 if sc_rescued:
1965 _log(f"Got transcripts for {got}/{len(video_ids)} videos "
1966 f"({errors} failed, {sc_rescued} rescued via ScrapeCreators fallback)")
1967 else:
1968 _log(f"Got transcripts for {got}/{len(video_ids)} videos ({errors} failed)")
1969 return results
1970
1971
1972 def backfill_transcripts(
1973 items: List[Any], topic: str = "", depth: str = "default",
1974 token: Optional[str] = None, entity_count: int = 1,
1975 ) -> None:
1976 """Second-pass transcript fetch for finalized items that lack one (#542).
1977
1978 ``token`` is the optional ScrapeCreators key, threaded to
1979 ``fetch_transcripts_parallel`` so the SC fallback covers backfill survivors
1980 that yt-dlp can't fetch. None preserves keyless behavior.
1981 """
1982 limit = comparison_share(
1983 TRANSCRIPT_LIMITS.get(depth, TRANSCRIPT_LIMITS["default"]), entity_count,
1984 )
1985 if limit <= 0 or not items or not is_ytdlp_installed():
1986 return
1987 have = sum(
1988 1 for it in items
1989 if it.metadata.get("transcript_highlights") or it.metadata.get("transcript_snippet")
1990 )
1991 need = limit - have
1992 if need <= 0:
1993 return
1994 missing = [
1995 it for it in items
1996 if it.item_id
1997 and not it.metadata.get("transcript_highlights")
1998 and not it.metadata.get("transcript_snippet")
1999 and not it.metadata.get("captions_disabled")
2000 ]
2001 attempts = missing[: need * 3]
2002 if not attempts:
2003 return
2004 _log(f"Backfilling transcripts for {len(attempts)} finalized videos (target: {need})")
2005 captions_disabled: Set[str] = set()
2006 with _youtube_block_scope() as block:
2007 transcripts = fetch_transcripts_parallel(
2008 [it.item_id for it in attempts],
2009 out_captions_disabled=captions_disabled,
2010 token=token,
2011 max_sc_rescues=need,
2012 )
2013 # A bot check here is a network loss like one in the search pass, so the
2014 # footer gives the bot-check advice rather than "upgrade yt-dlp".
2015 if block.tripped:
2016 _add_transcript_fetch_stats(blocked=1)
2017 for it in attempts:
2018 if it.item_id in captions_disabled:
2019 it.metadata["captions_disabled"] = True
2020 continue
2021 transcript = transcripts.get(it.item_id)
2022 if not transcript:
2023 continue
2024 it.metadata["transcript_snippet"] = transcript
2025 highlights = extract_transcript_highlights(transcript, topic)
2026 if highlights:
2027 it.metadata["transcript_highlights"] = highlights
2028 if not it.snippet:
2029 it.snippet = " ".join(transcript.split()[:80])
2030
2031
2032 def _transcript_candidate_sort_key(item: dict) -> tuple:
2033 """Sort key for transcript candidate selection.
2034
2035 Combines views with recency so that recent videos (which survive
2036 strict_recent freshness pruning) are prioritised over old high-view
2037 videos whose transcripts would be discarded downstream.
2038 """
2039 views = item.get("engagement", {}).get("views", 0) or 0
2040 recency = dates.recency_score(item.get("date", ""))
2041 return (views, recency)
2042
2043
2044 def _prefer_search_error(current: Optional[str], new: str) -> str:
2045 """Keep the most actionable search failure across multi-query merges."""
2046 if current is None:
2047 return new
2048 priority = ("timed out", "timeout", "429", "bot")
2049
2050 def _rank(text: str) -> int:
2051 lower = text.lower()
2052 for index, marker in enumerate(priority):
2053 if marker in lower:
2054 return index
2055 return len(priority)
2056
2057 return new if _rank(new) < _rank(current) else current
2058
2059
2060 def search_and_transcribe(
2061 topic: str,
2062 from_date: str,
2063 to_date: str,
2064 depth: str = "default",
2065 token: Optional[str] = None,
2066 freshness_mode: Optional[str] = None,
2067 entity_count: int = 1,
2068 ) -> Dict[str, Any]:
2069 """Full YouTube search: find videos, then fetch transcripts for top results.
2070
2071 Uses expand_youtube_queries() to generate multiple search queries,
2072 runs yt-dlp for each, and merges/deduplicates results by video ID.
2073
2074 Args:
2075 topic: Search topic
2076 from_date: Start date (YYYY-MM-DD)
2077 to_date: End date (YYYY-MM-DD)
2078 depth: 'quick', 'default', or 'deep'
2079 token: Optional ScrapeCreators key for the per-video transcript
2080 fallback (threaded to fetch_transcripts_parallel).
2081 freshness_mode: Plan freshness mode, threaded to search_youtube().
2082 entity_count: Comparison entities sharing the yt-dlp slots; each
2083 gets ``comparison_share`` of the queries and transcripts.
2084
2085 Returns:
2086 Dict with 'items' list. Each item has a 'transcript_snippet' field.
2087 """
2088 with _youtube_block_scope():
2089 return _search_and_transcribe(
2090 topic, from_date, to_date, depth, token, freshness_mode, entity_count,
2091 )
2092
2093
2094 def _search_and_transcribe(
2095 topic: str,
2096 from_date: str,
2097 to_date: str,
2098 depth: str = "default",
2099 token: Optional[str] = None,
2100 freshness_mode: Optional[str] = None,
2101 entity_count: int = 1,
2102 ) -> Dict[str, Any]:
2103 # Step 1: Multi-query search — run yt-dlp for each expanded query.
2104 # Leave a reserve for transcripts: another full search is not worth
2105 # starting once the lane has less than that left.
2106 transcript_limit = comparison_share(
2107 TRANSCRIPT_LIMITS.get(depth, TRANSCRIPT_LIMITS["default"]), entity_count,
2108 )
2109 reserve = _transcript_search_reserve(transcript_limit)
2110 queries = expand_youtube_queries(topic, depth, entity_count)
2111 seen_ids: Set[str] = set()
2112 items: List[Dict[str, Any]] = []
2113 search_error: Optional[str] = None
2114 skipped_queries = 0
2115 for done_queries, q in enumerate(queries):
2116 if items and _lane_out_of_time():
2117 skipped_queries = len(queries) - done_queries
2118 _log(f"Skipping {skipped_queries} YouTube searches: the lane is out of time")
2119 break
2120 if items and _lane_under_transcript_reserve(reserve):
2121 held = len(queries) - done_queries
2122 seconds_left = _lane_seconds_left() or 0.0
2123 _log(
2124 f"Skipping {held} YouTube searches: {seconds_left:.0f}s left, "
2125 f"under the {reserve:.0f}s transcript reserve"
2126 )
2127 break
2128 search_result = search_youtube(
2129 q, from_date, to_date, depth, freshness_mode=freshness_mode,
2130 )
2131 err = search_result.get("error")
2132 if err:
2133 search_error = _prefer_search_error(search_error, str(err))
2134 _note_youtube_block(str(err))
2135 for item in search_result.get("items", []):
2136 vid = item.get("video_id", "")
2137 if vid and vid not in seen_ids:
2138 seen_ids.add(vid)
2139 items.append(item)
2140
2141 # Sort merged results by views descending
2142 items.sort(key=lambda x: x.get("engagement", {}).get("views") or 0, reverse=True)
2143
2144 if not items:
2145 result = {"items": [], **({"error": search_error} if search_error else {})}
2146 if _lane_out_of_time():
2147 result["out_of_time"] = "no search finished before the stream deadline"
2148 return result
2149
2150 # Step 2: Fetch transcripts for top videos.
2151 # Sort candidates by a combination of views and recency so that recent
2152 # videos (which survive strict_recent pruning) are not starved of
2153 # transcript budget by older high-view-count outliers.
2154 # Try more candidates than the limit because some videos (music videos,
2155 # short clips) lack captions. Attempt up to 3x the limit so we have a
2156 # good chance of reaching the target number of successful transcripts.
2157 transcripts: Dict[str, Optional[str]] = {}
2158 captions_disabled_ids: Set[str] = set()
2159 unfinished_ids: Set[str] = set()
2160 if transcript_limit > 0:
2161 attempt_count = min(len(items), transcript_limit * 3)
2162 transcript_candidates = sorted(
2163 items, key=_transcript_candidate_sort_key, reverse=True,
2164 )
2165 candidate_ids = [item["video_id"] for item in transcript_candidates[:attempt_count]]
2166 _log(f"Fetching transcripts for up to {attempt_count} videos (target: {transcript_limit}): {candidate_ids}")
2167 transcripts = fetch_transcripts_parallel(
2168 candidate_ids, out_captions_disabled=captions_disabled_ids,
2169 token=token, max_sc_rescues=transcript_limit,
2170 )
2171 unfinished_ids = {vid for vid in candidate_ids if vid not in transcripts}
2172 # Record fetch outcomes (captions-disabled videos can never succeed,
2173 # and unfinished ones never ran to an answer, so neither counts as a
2174 # failure) for the stale-yt-dlp nudge.
2175 finished_ids = [vid for vid in candidate_ids if vid not in unfinished_ids]
2176 _add_transcript_fetch_stats(
2177 attempts=len(finished_ids),
2178 failures=sum(
2179 1 for vid in finished_ids
2180 if not transcripts.get(vid) and vid not in captions_disabled_ids
2181 ),
2182 target=transcript_limit,
2183 blocked=int(_youtube_transcripts_blocked()),
2184 )
2185 else:
2186 _log(f"Transcript limit is 0 for depth={depth}, skipping transcript fetch")
2187
2188 # Step 3: Attach transcripts and extract highlights. Mark captions_disabled
2189 # so quality_nudge can subtract those videos from the degraded-ratio
2190 # denominator (uploader-disabled captions can never produce a transcript;
2191 # counting them was producing false-positive stale-yt-dlp nudges).
2192 core_topic = _extract_core_subject(topic)
2193 for item in items:
2194 vid = item["video_id"]
2195 transcript = transcripts.get(vid)
2196 item["transcript_snippet"] = transcript or ""
2197 item["transcript_highlights"] = extract_transcript_highlights(
2198 transcript or "", core_topic,
2199 )
2200 item["captions_disabled"] = vid in captions_disabled_ids
2201
2202 result: Dict[str, Any] = {"items": items}
2203 if search_error:
2204 # Partial coverage: some queries succeeded; keep the failure visible so
2205 # source_status becomes partial/timeout rather than a quiet OK.
2206 result["error"] = search_error
2207 cut = []
2208 if skipped_queries:
2209 cut.append(f"skipped {skipped_queries} of {len(queries)} searches")
2210 if unfinished_ids:
2211 cut.append(f"left {len(unfinished_ids)} of {len(candidate_ids)} transcript fetches unfinished")
2212 if cut:
2213 result["out_of_time"] = f"{' and '.join(cut)} to return before the stream deadline"
2214 elif _lane_out_of_time():
2215 # Transcript fetches that hit the deadline answer None instead of
2216 # going missing, so the deadline itself is the signal.
2217 result["out_of_time"] = "reached the stream deadline while fetching transcripts"
2218 return result
2219
2220
2221 def parse_youtube_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
2222 """Parse YouTube search response to normalized format.
2223
2224 Returns:
2225 List of item dicts ready for normalization.
2226 """
2227 return response.get("items", [])
2228
2229
2230 # ---------------------------------------------------------------------------
2231 # ScrapeCreators YouTube API support
2232 # ---------------------------------------------------------------------------
2233
2234 SCRAPECREATORS_YT_BASE = "https://api.scrapecreators.com/v1/youtube"
2235
2236
2237 def _sc_yt_base() -> str:
2238 if SCRAPECREATORS_YT_BASE != "https://api.scrapecreators.com/v1/youtube":
2239 return SCRAPECREATORS_YT_BASE
2240 from . import env
2241 return f"{env.get_scrapecreators_base_url()}/v1/youtube"
2242
2243
2244 def _total_engagement(item: Dict[str, Any]) -> int:
2245 """Combined engagement score for ranking which videos to enrich."""
2246 eng = item.get("engagement", {})
2247 views = eng.get("views", 0) or 0
2248 likes = eng.get("likes", 0) or 0
2249 comments = eng.get("comments", 0) or 0
2250 return views + likes + comments
2251
2252
2253 def enrich_with_comments(
2254 items: List[Dict[str, Any]],
2255 token: str,
2256 max_videos: int = 3,
2257 max_comments: int = 5,
2258 entity_count: int = 1,
2259 ) -> List[Dict[str, Any]]:
2260 """Enrich top YouTube videos with comment data from ScrapeCreators.
2261
2262 For the top N videos by engagement, fetches comments via the SC API
2263 and attaches them as a ``top_comments`` field on each item.
2264
2265 Args:
2266 items: YouTube items from search_and_transcribe() or search_youtube_sc()
2267 token: ScrapeCreators API key
2268 max_videos: How many videos to enrich with comments
2269 max_comments: Max comments to keep per video
2270 entity_count: Comparison entities sharing the yt-dlp slots; each
2271 enriches ``comparison_share`` of ``max_videos``.
2272
2273 Returns:
2274 Items list (mutated in place) with top_comments added to enriched items.
2275 """
2276 max_videos = comparison_share(max_videos, entity_count)
2277 if not items or max_videos <= 0:
2278 return items
2279 # yt-dlp needs no key, so an empty token is only fatal when it is absent too.
2280 if not token and not is_ytdlp_installed():
2281 return items
2282
2283 ranked = sorted(items, key=_total_engagement, reverse=True)
2284 top_items = ranked[:max_videos]
2285 _log(f"Enriching comments for {len(top_items)} YouTube videos")
2286
2287 from concurrent.futures import ThreadPoolExecutor, as_completed
2288
2289 def _enrich_one(item: dict) -> bool:
2290 video_id = item.get("video_id", "")
2291 if not video_id:
2292 return False
2293 try:
2294 comments = _fetch_video_comments(video_id, token, max_comments)
2295 if comments:
2296 item["top_comments"] = comments
2297 return True
2298 except Exception as exc:
2299 _log(f"Comment enrichment failed for {video_id}: {exc}")
2300 return False
2301
2302 enriched_count = 0
2303 with ThreadPoolExecutor(max_workers=min(4, len(top_items))) as executor:
2304 futures = {http.submit_with_context(executor, _enrich_one, item): item for item in top_items}
2305 for future in as_completed(futures):
2306 if future.result():
2307 enriched_count += 1
2308
2309 _log(f"Enriched {enriched_count}/{len(top_items)} videos with comments")
2310 return items
2311
2312
2313 def _ytdlp_comments_result(
2314 video_id: str,
2315 max_comments: int = 5,
2316 ) -> tuple[List[Dict[str, Any]], bool]:
2317 """Fetch top comments via yt-dlp, returning ``(comments, ran_cleanly)``.
2318
2319 The bool distinguishes "yt-dlp succeeded, this video simply has no
2320 comments" (True, []) from "yt-dlp was absent or errored" (False, []), so
2321 the caller only spends a ScrapeCreators credit on a genuine failure — not
2322 on a video that legitimately has zero comments. Mirrors the transcript
2323 path, which is likewise careful not to bill SC for a caption-less video.
2324
2325 Comments are sorted by top so a low ``max_comments`` still returns the
2326 highest-voted ones rather than an arbitrary slice.
2327 """
2328 if not _is_valid_video_id(video_id) or not is_ytdlp_installed():
2329 return [], False
2330 if max_comments <= 0:
2331 return [], True
2332
2333 # Request top-level parents only (0 replies, 0 replies per thread) with a
2334 # small buffer so empty-text entries do not starve the requested cap.
2335 fetch_cap = max_comments + 2
2336 cmd = _wrap_ytdlp_cmd([
2337 "yt-dlp",
2338 "--write-comments",
2339 "--skip-download",
2340 "--dump-single-json",
2341 "--no-warnings",
2342 "--ignore-config",
2343 "--no-cookies-from-browser",
2344 "--extractor-args",
2345 f"youtube:comment_sort=top;max_comments={fetch_cap},{fetch_cap},0,0",
2346 "--",
2347 _youtube_watch_url(video_id),
2348 ])
2349
2350 try:
2351 result = _run_ytdlp(cmd, timeout=_COMMENT_TIMEOUT)
2352 except Exception as exc:
2353 _log(f"yt-dlp comment fetch failed for {video_id}: {exc}")
2354 return [], False
2355
2356 if result.returncode != 0 or not result.stdout:
2357 _log(f"yt-dlp comment fetch failed for {video_id} (exit {result.returncode})")
2358 return [], False
2359
2360 try:
2361 payload = json.loads(result.stdout)
2362 except (ValueError, TypeError) as exc:
2363 _log(f"yt-dlp comment JSON parse failed for {video_id}: {exc}")
2364 return [], False
2365
2366 if not isinstance(payload, dict):
2367 _log(f"yt-dlp comment JSON payload was not an object for {video_id}")
2368 return [], False
2369
2370 raw_comments = payload.get("comments")
2371 if not isinstance(raw_comments, list):
2372 raw_comments = []
2373
2374 channel_id = str(payload.get("channel_id") or "")
2375 comments = []
2376 for c in raw_comments:
2377 if len(comments) >= max_comments:
2378 break
2379 if not isinstance(c, dict):
2380 continue
2381 parent = c.get("parent")
2382 if parent not in (None, "", "root"):
2383 continue
2384 raw_text = c.get("text")
2385 if not isinstance(raw_text, str):
2386 continue
2387 text = raw_text.strip()
2388 if not text:
2389 continue
2390 comment = {
2391 "author": c.get("author") or "",
2392 "text": text[:400],
2393 "likes": c.get("like_count") or 0,
2394 "date": c.get("_time_text") or "",
2395 }
2396 # Whether the channel itself wrote this. A channel's display name and
2397 # the handle on its comments can differ, so the name cannot say: yt-dlp
2398 # does (author_is_uploader), and failing that the channel ids do. The
2399 # key is left out when neither is known.
2400 if isinstance(c.get("author_is_uploader"), bool):
2401 comment["is_uploader"] = c["author_is_uploader"]
2402 elif channel_id and c.get("author_id"):
2403 comment["is_uploader"] = str(c["author_id"]) == channel_id
2404 comments.append(comment)
2405 return comments, True
2406
2407
2408 def _fetch_video_comments_ytdlp(
2409 video_id: str,
2410 max_comments: int = 5,
2411 ) -> List[Dict[str, Any]]:
2412 """Comments for a video via yt-dlp (free, keyless), or [] on any failure.
2413
2414 Thin list-returning wrapper over ``_ytdlp_comments_result`` for callers
2415 that don't need to tell a clean empty result from a failure.
2416 """
2417 return _ytdlp_comments_result(video_id, max_comments)[0]
2418
2419
2420 def _fetch_video_comments(
2421 video_id: str,
2422 token: str,
2423 max_comments: int = 5,
2424 ) -> List[Dict[str, Any]]:
2425 """Fetch comments for one video, preferring the free yt-dlp path.
2426
2427 yt-dlp is tried first because it is keyless and costs nothing.
2428 ScrapeCreators stays as the backstop for when yt-dlp is absent or gets
2429 throttled, and is only called when a token is actually configured.
2430
2431 Args:
2432 video_id: YouTube video ID
2433 token: ScrapeCreators API key (may be empty — yt-dlp needs none)
2434 max_comments: Maximum comments to return
2435
2436 Returns:
2437 List of comment dicts with author, text, likes, date.
2438 """
2439 if not _is_valid_video_id(video_id):
2440 _log(f"Comment fetch: refused invalid video_id {video_id!r}")
2441 return []
2442 ytdlp_comments, ran_cleanly = _ytdlp_comments_result(video_id, max_comments)
2443 if ytdlp_comments:
2444 return ytdlp_comments
2445 # Clean run with no comments -> the video simply has none. Don't spend an
2446 # SC credit chasing comments that aren't there; only fall back on failure.
2447 if ran_cleanly:
2448 return []
2449
2450 if not token or _sc_spend_blocked(f"comments for {video_id}"):
2451 return []
2452
2453 video_url = _youtube_watch_url(video_id)
2454 try:
2455 data = http.get(
2456 f"{_sc_yt_base()}/video/comments",
2457 params={"url": video_url},
2458 headers=http.scrapecreators_headers(token),
2459 timeout=30,
2460 retries=2,
2461 **_sc_request_bounds(),
2462 )
2463 except Exception as exc:
2464 _log(f"Comment fetch error for {video_id}: {exc}")
2465 return []
2466
2467 raw_comments = data.get("comments", data.get("data", []))
2468 comments = []
2469 for c in raw_comments[:max_comments]:
2470 text = c.get("text") or c.get("body") or c.get("content", "")
2471 if not text:
2472 continue
2473
2474 # SC returns author as {"name": "@handle", ...}; legacy mocks may pass a string.
2475 author = c.get("author") or c.get("author_name", "")
2476 is_uploader = _sc_comment_is_uploader(c)
2477 if isinstance(author, dict):
2478 author = author.get("name") or author.get("handle") or ""
2479
2480 # SC nests likes under engagement.likes; legacy shapes used top-level keys.
2481 engagement = c.get("engagement") or {}
2482 likes = c.get("likes")
2483 if likes is None:
2484 likes = engagement.get("likes", 0) if isinstance(engagement, dict) else 0
2485 if not likes:
2486 likes = c.get("vote_count", 0)
2487
2488 date = (
2489 c.get("date")
2490 or c.get("published_at")
2491 or c.get("publishedTime")
2492 or c.get("publishedTimeText", "")
2493 )
2494
2495 comment = {
2496 "author": author,
2497 "text": text[:400],
2498 "likes": likes,
2499 "date": date,
2500 }
2501 if is_uploader is not None:
2502 comment["is_uploader"] = is_uploader
2503 comments.append(comment)
2504
2505 return comments
2506
2507
2508 # Keys under which a comment payload may say its author is the video's
2509 # channel. Read from the comment and from its author object; a payload with
2510 # none of them leaves the comment's authorship unknown.
2511 _SC_UPLOADER_FLAG_KEYS = (
2512 "author_is_uploader", "authorIsChannelOwner", "isChannelOwner", "isCreator",
2513 "is_creator",
2514 )
2515
2516
2517 def _sc_comment_is_uploader(comment: Dict[str, Any]) -> Optional[bool]:
2518 """The channel-owner flag a ScrapeCreators comment carries, or None."""
2519 author = comment.get("author")
2520 for holder in (comment, author if isinstance(author, dict) else {}):
2521 for key in _SC_UPLOADER_FLAG_KEYS:
2522 if isinstance(holder.get(key), bool):
2523 return holder[key]
2524 return None
2525
2526
2527 def search_youtube_sc(
2528 topic: str,
2529 from_date: str,
2530 to_date: str,
2531 depth: str = "default",
2532 token: str = None,
2533 skip_transcript_ids: Optional[Set[str]] = None,
2534 freshness_mode: Optional[str] = None,
2535 entity_count: int = 1,
2536 ) -> Dict[str, Any]:
2537 """Search YouTube via ScrapeCreators when yt-dlp is absent, empty, or thin.
2538
2539 Uses SC keyword search to find videos and SC transcript endpoint to
2540 fetch transcripts. The pipeline uses the configured thin-result floor.
2541
2542 Args:
2543 topic: Search topic
2544 from_date: Start date (YYYY-MM-DD)
2545 to_date: End date (YYYY-MM-DD)
2546 depth: 'quick', 'default', or 'deep'
2547 token: ScrapeCreators API key
2548 skip_transcript_ids: Video IDs already transcribed by the free search
2549 freshness_mode: Plan freshness mode; scopes the out-of-window
2550 fallback (see _apply_date_window). None keeps the soft fallback.
2551 entity_count: Comparison entities; each pays for
2552 ``comparison_share`` of the transcript target.
2553
2554 Returns:
2555 Dict with 'items' list of video metadata dicts.
2556 """
2557 if not token:
2558 return {"items": [], "error": "No SCRAPECREATORS_API_KEY configured"}
2559
2560 count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
2561 core_topic = _extract_core_subject(topic)
2562 _log(f"Searching YouTube via ScrapeCreators for '{core_topic}' (depth={depth})")
2563
2564 # Step 1: Search
2565 raw_items = _sc_youtube_search(core_topic, token)
2566 if not raw_items:
2567 _log("SC YouTube search returned 0 results")
2568 return {"items": []}
2569
2570 # Parse into normalized items
2571 items = []
2572 for i, raw in enumerate(raw_items[:count]):
2573 video_id = (
2574 raw.get("id") or raw.get("video_id") or raw.get("videoId") or ""
2575 )
2576 if not isinstance(video_id, str):
2577 video_id = ""
2578 if video_id and not _is_valid_video_id(video_id):
2579 _log(f"Skipping SC YouTube item with invalid video_id: {video_id!r}")
2580 continue
2581 title = raw.get("title", "")
2582 # SC's /v1/youtube/search returns camelCase fields (viewCountInt,
2583 # publishedTime, lengthSeconds) and `channel` as an object; the
2584 # snake_case names stay as fallbacks.
2585 channel = raw.get("channel") or raw.get("channel_name") or raw.get("uploader", "")
2586 if isinstance(channel, dict):
2587 channel = channel.get("title") or channel.get("handle") or ""
2588 description = str(raw.get("description", ""))[:500]
2589 view_count = raw.get("view_count") or raw.get("viewCountInt") or raw.get("views", 0)
2590 like_count = raw.get("like_count") or raw.get("likes", 0)
2591 comment_count = raw.get("comment_count") or raw.get("comments", 0)
2592
2593 # Date: try multiple field names
2594 date_str = (
2595 raw.get("upload_date") or raw.get("date") or raw.get("published_at")
2596 or raw.get("publishedTime") or ""
2597 )
2598 if date_str and len(date_str) == 8 and date_str.isdigit():
2599 date_str = f"{date_str[:4]}-{date_str[4:6]}-{date_str[6:8]}"
2600 elif date_str and "T" in date_str:
2601 date_str = date_str[:10]
2602
2603 url = raw.get("url", "")
2604 if not url and video_id:
2605 url = _youtube_watch_url(video_id)
2606
2607 items.append({
2608 "video_id": video_id,
2609 "title": title,
2610 "url": url,
2611 "channel_name": channel,
2612 "date": date_str if date_str else None,
2613 "engagement": {
2614 "views": view_count or 0,
2615 "likes": like_count or 0,
2616 "comments": comment_count or 0,
2617 },
2618 "duration": raw.get("duration") or raw.get("lengthSeconds"),
2619 "relevance": _compute_relevance(core_topic, f"{title} {description}"),
2620 "why_relevant": f"YouTube: {title[:60]}" if title else f"YouTube: {core_topic}",
2621 "description": description,
2622 })
2623
2624 # Date filter (keep-all fallback scoped by freshness mode)
2625 items = _apply_date_window(items, from_date, to_date, freshness_mode)
2626
2627 # Sort by views
2628 items.sort(key=lambda x: x["engagement"]["views"], reverse=True)
2629
2630 # Step 2: Fetch transcripts for top videos
2631 transcript_limit = comparison_share(
2632 TRANSCRIPT_LIMITS.get(depth, TRANSCRIPT_LIMITS["default"]), entity_count,
2633 )
2634 if transcript_limit > 0 and items:
2635 # Same in-window-first ordering as search_and_transcribe(): don't let
2636 # an out-of-window back-catalog (kept by the soft date filter above)
2637 # consume the transcript budget of videos the freshness scorer keeps.
2638 in_window = [i for i in items if i.get("date") and i["date"] >= from_date]
2639 out_of_window = [i for i in items if not (i.get("date") and i["date"] >= from_date)]
2640 excluded_ids = skip_transcript_ids or set()
2641 transcript_candidates = [
2642 item for item in in_window + out_of_window
2643 if item["video_id"] not in excluded_ids
2644 ]
2645 attempt_count = min(len(transcript_candidates), transcript_limit * 3)
2646 _log(f"Fetching SC transcripts for up to {attempt_count} videos (target: {transcript_limit})")
2647 # Transcripts the free search already has count toward the target, so
2648 # a thin backfill tops up to it instead of paying for a full target
2649 # on top of them.
2650 got = len(excluded_ids)
2651 for item in transcript_candidates[:attempt_count]:
2652 # Each attempt is paid: stop once the target is met. The 3x
2653 # headroom is only for videos that come back without captions.
2654 if got >= transcript_limit:
2655 break
2656 vid = item["video_id"]
2657 if not vid:
2658 continue
2659 transcript = _sc_fetch_transcript(vid, token)
2660 if transcript:
2661 got += 1
2662 item["transcript_snippet"] = transcript or ""
2663 item["transcript_highlights"] = extract_transcript_highlights(
2664 transcript or "", core_topic,
2665 )
2666 else:
2667 for item in items:
2668 item["transcript_snippet"] = ""
2669 item["transcript_highlights"] = []
2670
2671 _log(f"SC YouTube: {len(items)} videos returned")
2672 return {"items": items}
2673
2674
2675 def _sc_youtube_search(keyword: str, token: str) -> List[Dict[str, Any]]:
2676 """Call ScrapeCreators YouTube search endpoint.
2677
2678 Args:
2679 keyword: Search keyword
2680 token: ScrapeCreators API key
2681
2682 Returns:
2683 List of raw video dicts from the API.
2684 """
2685 if _sc_spend_blocked(f"search for {keyword!r}"):
2686 return []
2687 try:
2688 # SC's /v1/youtube/search rejects ?keyword= with HTTP 400; the canonical
2689 # parameter for that endpoint is `query`. Other SC endpoints use their
2690 # own per-endpoint param names so this was the lone outlier.
2691 data = http.get(
2692 f"{_sc_yt_base()}/search",
2693 params={"query": keyword},
2694 headers=http.scrapecreators_headers(token),
2695 timeout=30,
2696 retries=2,
2697 **_sc_request_bounds(),
2698 )
2699 return data.get("videos", data.get("data", data.get("items", [])))
2700 except Exception as exc:
2701 _log(f"SC YouTube search error: {exc}")
2702 return []
2703
2704
2705 def _sc_segment_text(seg: Any) -> str:
2706 """Extract caption text from a ScrapeCreators transcript segment.
2707
2708 The transcript endpoint returns a list of segment dicts
2709 (``{text, startMs, endMs}``); older/simpler shapes return plain strings.
2710 Pull the ``text`` field for dicts so segment metadata is not stringified
2711 into the output (``{'text': ...}`` garbage).
2712 """
2713 if isinstance(seg, dict):
2714 # `or ""` (not a get default): a present-but-null `text` returns None,
2715 # which would stringify to the literal "None" for silent/music segments.
2716 return str(seg.get("text") or "")
2717 return str(seg)
2718
2719
2720 def _warn_low_sc_credits(data: Dict[str, Any]) -> None:
2721 """Surface a low-credit warning from a ScrapeCreators response, if present."""
2722 credits = data.get("credits_remaining")
2723 if isinstance(credits, (int, float)) and not isinstance(credits, bool):
2724 if credits < _SC_LOW_CREDIT_THRESHOLD:
2725 _log(f"ScrapeCreators credits low: {int(credits)} remaining "
2726 f"(below {_SC_LOW_CREDIT_THRESHOLD})")
2727
2728
2729 def _sc_fetch_transcript(video_id: str, token: str) -> Optional[str]:
2730 """Fetch transcript for a YouTube video via ScrapeCreators.
2731
2732 Args:
2733 video_id: YouTube video ID
2734 token: ScrapeCreators API key
2735
2736 Returns:
2737 Plaintext transcript string, or None if unavailable.
2738 """
2739 if not _is_valid_video_id(video_id):
2740 _log(f"SC transcript: refused invalid video_id {video_id!r}")
2741 return None
2742 if _sc_spend_blocked(f"transcript for {video_id}"):
2743 return None
2744 video_url = _youtube_watch_url(video_id)
2745 transcript = None
2746 deadline = time.monotonic() + _SC_TRANSCRIPT_TIMEOUT
2747 # Without a language the endpoint may return an auto-dubbed track (#1169).
2748 # SC takes plain codes; a configured `en-orig` means `en` here (#1314).
2749 languages = list(dict.fromkeys(
2750 code.removesuffix("-orig") for code in _ytdlp_sub_langs().split(",")
2751 ))[:_SC_TRANSCRIPT_MAX_LANGUAGES]
2752 for language in languages:
2753 if time.monotonic() >= deadline:
2754 break
2755 # The run can end while an earlier language is in flight; don't
2756 # buy the next one.
2757 if language != languages[0] and _sc_spend_blocked(f"transcript for {video_id}"):
2758 return None
2759 try:
2760 # Isolate SC transcript fetch errors from the pipeline-level
2761 # capture_failures() context.
2762 with http.capture_failures() as _tf:
2763 data = http.get(
2764 f"{_sc_yt_base()}/video/transcript",
2765 params={"url": video_url, "language": language},
2766 headers=http.scrapecreators_headers(token),
2767 timeout=_SC_TRANSCRIPT_TIMEOUT,
2768 retries=1,
2769 max_429_retries=0,
2770 owned_get=True,
2771 **_sc_request_bounds(deadline),
2772 )
2773 except Exception as exc:
2774 _log(f"SC transcript error for {video_id} ({language}): {exc}")
2775 if getattr(exc, "status_code", None) == 404:
2776 continue
2777 return None
2778
2779 _warn_low_sc_credits(data)
2780
2781 transcript = data.get("transcript")
2782 if isinstance(transcript, list):
2783 transcript = " ".join(_sc_segment_text(seg) for seg in transcript).strip()
2784 if not isinstance(transcript, str):
2785 transcript = None
2786 continue
2787 transcript = _clean_vtt(transcript)
2788 if transcript:
2789 break
2790 if not transcript:
2791 return None
2792
2793 # Truncate to max words
2794 words = transcript.split()
2795 if len(words) > TRANSCRIPT_MAX_WORDS:
2796 transcript = " ".join(words[:TRANSCRIPT_MAX_WORDS]) + "..."
2797
2798 return transcript if transcript else None
2799
2800
2801 # Backward-compat alias: internal call sites predate the public name.
2802 _wrap_ytdlp_cmd = wrap_ytdlp_cmd
2803
2803 lines PYTHON