1"""Fetch a YouTube video's captions the way YouTube's own apps do, with fallbacks.
2
3Method (verified 4 Oct 2026)
4- Ask YouTube's player API (`youtubei/v1/player`) for the video as one of several official clients. The answer
5 holds the video's details and its caption tracks: one signed timedtext URL per language, manual or
6 auto-generated.
7- Download the chosen track from the timedtext endpoint as json3 and parse it.
8- Clients, in order: WEB (needs the player script's signature timestamp, read once per run; gives the full track
9 list, 150+ auto-translation languages and publish date), then ANDROID and IOS (no setup), VISIONOS and
10 ANDROID_VR (need a visitor id from an earlier answer), MWEB and TVHTML5_SIMPLY (need the signature timestamp).
11- A caption URL carrying `exp=xpe`/`xpv` would need a proof-of-origin (PO) token, which only YouTube's own
12 player can mint. We do not mint or fake those tokens: such a client is skipped and the next one is asked.
13- "Sign in to confirm you're not a bot", HTTP 429 or a network error moves the video to a fresh proxy exit.
14 Statuses that end the job (private, removed, age-restricted, no captions...) must be reported by two different
15 clients before they are believed, because some clients misreport a working video as unavailable.
16- Auto-translation (`tlang`) is rate-limited by YouTube far more than plain captions: about one request in six
17 to ten succeeds. It is retried from fresh exits and is best effort.
18"""
19
20from __future__ import annotations
21
22import asyncio
23import random
24import re
25import time
26from collections import Counter, defaultdict
27from dataclasses import dataclass, field
28from typing import Any
29from urllib.parse import parse_qsl, urlencode, urljoin, urlsplit, urlunsplit
30
31from .captions import CaptionParseError, Segment, parse_any
32from .net import Exit, ExitPool, NetError
33
34API = "https://www.youtube.com/youtubei/v1"
35DEFAULT_WEB_VERSION = "2.20261002.01.00"
36
37
38@dataclass(frozen=True)
39class Client:
40 key: str
41 name: str
42 version: str
43 number: int
44 user_agent: str | None = None
45 extra: tuple[tuple[str, Any], ...] = ()
46 needs_sts: bool = False
47 needs_visitor: bool = False
48 web_like: bool = False
49
50
51CLIENTS: dict[str, Client] = {c.key: c for c in (
52 Client("web", "WEB", DEFAULT_WEB_VERSION, 1, needs_sts=True, web_like=True),
53 Client("android", "ANDROID", "21.26.364", 3,
54 "com.google.android.youtube/21.26.364 (Linux; U; Android 11) gzip",
55 (("androidSdkVersion", 30), ("osName", "Android"), ("osVersion", "11"))),
56 Client("ios", "IOS", "21.26.4", 5,
57 "com.google.ios.youtube/21.26.4 (iPhone16,2; U; CPU iOS 18_3_2 like Mac OS X;)",
58 (("deviceMake", "Apple"), ("deviceModel", "iPhone16,2"), ("osName", "iPhone"),
59 ("osVersion", "18.3.2.22D82"))),
60 Client("visionos", "VISIONOS", "1.02", 101,
61 "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/605.1.15 (KHTML, like Gecko) "
62 "Version/26.0 Safari/605.1.15",
63 (("deviceMake", "Apple"), ("deviceModel", "RealityDevice17,1"), ("osName", "visionOS"),
64 ("osVersion", "26.5.23O471")), needs_visitor=True),
65 Client("android_vr", "ANDROID_VR", "1.65.10", 28,
66 "com.google.android.apps.youtube.vr.oculus/1.65.10 (Linux; U; Android 12L; eureka-user "
67 "Build/SQ3A.220605.009.A1) gzip",
68 (("deviceMake", "Oculus"), ("deviceModel", "Quest 3"), ("androidSdkVersion", 32), ("osName", "Android"),
69 ("osVersion", "12L")), needs_visitor=True),
70 Client("mweb", "MWEB", "2.20260708.05.00", 2,
71 "Mozilla/5.0 (iPad; CPU OS 16_7_10 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) "
72 "Version/16.6 Mobile/15E148 Safari/604.1,gzip(gfe)", needs_sts=True, web_like=True),
73 Client("tv_simply", "TVHTML5_SIMPLY", "1.0", 75, needs_sts=True, needs_visitor=True),
74)}
75DEFAULT_ORDER = ("web", "android", "ios", "visionos", "android_vr", "mweb", "tv_simply")
76
77
78TERMINAL = ("unavailable", "private", "age-restricted", "members-only", "region-blocked", "upcoming")
79TRANSLATE_TRIES = 12
80
81
82class Blocked(Exception):
83 """YouTube refused this exit (bot check, 429, 403, an HTML error page). The next try uses a new exit."""
84
85
86
87
88@dataclass
89class Bootstrap:
90 """Facts read once per run: the signature timestamp (sts) WEB-type clients must send, and WEB's version."""
91
92 sts: int | None = None
93 web_version: str = DEFAULT_WEB_VERSION
94 player_id: str | None = None
95 notes: list[str] = field(default_factory=list)
96
97 @classmethod
98 async def load(cls, pool: ExitPool) -> "Bootstrap":
99 boot = cls()
100
101 for via in ("direct", "proxy"):
102 ex = Exit(None, "boot") if via == "direct" else await pool.acquire()
103 try:
104 await boot._load_with(ex)
105 except Exception as e:
106 boot.notes.append(f"{via}: {type(e).__name__}: {str(e)[:120]}")
107 finally:
108 if via == "direct":
109 await ex.close()
110 else:
111 await pool.release(ex, healthy=not ex.bad)
112 if boot.sts:
113 break
114 return boot
115
116 async def _load_with(self, ex: Exit) -> None:
117 r = await ex.request("GET", "https://www.youtube.com/sw.js_data", timeout=20)
118 m = re.search(r"\b(2\.20\d{6}\.\d{2}\.\d{2})\b", r.text if r.status_code == 200 else "")
119 if m:
120 self.web_version = m.group(1)
121 r = await ex.request("GET", "https://www.youtube.com/iframe_api", timeout=20)
122 m = re.search(r"player\\?/([0-9a-fA-F]{8})\\?/", r.text)
123 if not m:
124 raise RuntimeError(f"player id not found in iframe_api (HTTP {r.status_code})")
125 self.player_id = m.group(1)
126 for variant in ("player_ias.vflset/en_US/base.js", "tv-player-ias.vflset/tv-player-ias.js"):
127 r = await ex.request("GET", f"https://www.youtube.com/s/player/{self.player_id}/{variant}", timeout=40)
128 m = re.search(r"(?:signatureTimestamp|sts)\s*[:=]\s*(\d{5})", r.text) if r.status_code == 200 else None
129 if m:
130 self.sts = int(m.group(1))
131 return
132 raise RuntimeError("signature timestamp not found in the player script")
133
134 def version(self, client: Client) -> str:
135 return self.web_version if client.key == "web" else client.version
136
137
138class ClientHealth:
139 """Skips a client for the rest of the run after repeated failures that are the client's, not the video's
140 (outdated client, PO token demanded, empty caption files). Successes reset the count."""
141
142 def __init__(self, order: tuple[str, ...] = DEFAULT_ORDER, limit: int = 6) -> None:
143 self.keys = list(order)
144 self.limit = limit
145 self.streak: Counter[str] = Counter()
146 self.disabled: set[str] = set()
147 self.used: Counter[str] = Counter()
148 self.reasons: Counter[str] = Counter()
149
150 def order(self) -> list[Client]:
151 keys = [k for k in self.keys if k not in self.disabled] or self.keys
152 return [CLIENTS[k] for k in keys]
153
154 def fail(self, key: str, why: str) -> None:
155 self.reasons[f"{key}:{why}"] += 1
156 self.streak[key] += 1
157 if self.streak[key] >= self.limit:
158 self.disabled.add(key)
159
160 def ok(self, key: str) -> None:
161 self.streak[key] = 0
162 self.used[key] += 1
163
164
165
166
167def _text(v: Any) -> str:
168 if isinstance(v, str):
169 return v
170 if isinstance(v, dict):
171 if "simpleText" in v:
172 return str(v["simpleText"])
173 if "runs" in v:
174 return "".join(str(r.get("text", "")) for r in v.get("runs") or [])
175 return ""
176
177
178def playability_texts(pr: dict[str, Any]) -> tuple[str, str, list[str]]:
179 ps = pr.get("playabilityStatus") or {}
180 texts = [str(ps.get("reason") or "")]
181 pem = ((ps.get("errorScreen") or {}).get("playerErrorMessageRenderer") or {})
182 texts += [_text(pem.get("reason")), _text(pem.get("subreason"))]
183 for m in ps.get("messages") or []:
184 texts.append(str(m))
185 texts = [t.strip() for t in texts if t and t.strip()]
186 return str(ps.get("status") or ""), (texts[0] if texts else ""), texts
187
188
189def classify(pr: dict[str, Any], video_id: str) -> tuple[str, str]:
190 """(kind, reason). kind: ok, live, bot, client, login, unavailable, private, age-restricted, members-only,
191 region-blocked, upcoming, other."""
192 status, reason, texts = playability_texts(pr)
193 blob = " ".join(texts).lower()
194 vd = pr.get("videoDetails") or {}
195 ps = pr.get("playabilityStatus") or {}
196 if vd.get("videoId") and vd.get("videoId") != video_id:
197 return "bot", "YouTube answered with a different video"
198 if "not a bot" in blob or "unusual traffic" in blob:
199 return "bot", reason or "Sign in to confirm you're not a bot"
200 if status == "OK":
201 mf = (pr.get("microformat") or {}).get("playerMicroformatRenderer") or {}
202 if vd.get("isLive") or (mf.get("liveBroadcastDetails") or {}).get("isLiveNow"):
203 return "live", "live stream in progress"
204 return "ok", ""
205 if status == "LIVE_STREAM_OFFLINE" or vd.get("isUpcoming"):
206 return "upcoming", reason or "scheduled live stream or premiere that has not started"
207 if "page needs to be reloaded" in blob or status == "CLIENT_ERROR":
208 return "client", reason or status
209 if "private" in blob:
210 return "private", "This video is private"
211 if (status in ("AGE_CHECK_REQUIRED", "AGE_VERIFICATION_REQUIRED", "CONTENT_CHECK_REQUIRED")
212 or ps.get("desktopLegacyAgeGateReason") or "confirm your age" in blob
213 or "inappropriate for some users" in blob or "age-restricted" in blob):
214 return "age-restricted", "Age-restricted: YouTube shows it only to signed-in adults"
215 if "members" in blob and ("join" in blob or "only" in blob):
216 return "members-only", "Members-only video"
217 if "available in your country" in blob or "not available in your location" in blob:
218 return "region-blocked", reason or "Not available in the proxy's country"
219 if status == "LOGIN_REQUIRED":
220 return "login", reason or "sign-in requested"
221 if status in ("ERROR", "UNPLAYABLE"):
222 return "unavailable", reason or "Video unavailable"
223 return "other", f"{status}: {reason}".strip(": ")
224
225
226
227
228LANG_ALIASES = {
229 "he": "iw", "iw": "he", "id": "in", "in": "id", "yi": "ji", "ji": "yi", "jv": "jw", "jw": "jv",
230 "fil": "tl", "tl": "fil", "nb": "no", "no": "nb", "zh-hans": "zh-cn", "zh-cn": "zh-hans", "zh-hant": "zh-tw",
231 "zh-tw": "zh-hant", "zh-hk": "zh-hant",
232}
233
234
235def norm_lang(code: str | None) -> str:
236 return (code or "").strip().replace("_", "-").lower()
237
238
239def base_lang(code: str | None) -> str:
240 return norm_lang(code).split("-")[0]
241
242
243@dataclass
244class Track:
245 base_url: str
246 code: str
247 name: str
248 auto: bool
249 translatable: bool
250 track_name: str = ""
251 vss_id: str = ""
252 needs_pot: bool = False
253 is_default: bool = False
254 original_audio: bool = True
255
256 def public(self) -> dict[str, Any]:
257 return {"code": self.code, "name": self.name, "isAutoGenerated": self.auto,
258 "isTranslatable": self.translatable}
259
260
261def original_audio_language(pctr: dict[str, Any], raw_tracks: list[dict[str, Any]]) -> str | None:
262 """The language spoken in the video. Auto-dubbed videos list one audio track per language; the default one
263 (id like "ru.4", dubs are "xx.10") is the original. Without audio tracks: the only auto-generated track."""
264 audio = pctr.get("audioTracks") or []
265 if audio:
266 a_idx = pctr.get("defaultAudioTrackIndex") or 0
267 a = audio[a_idx] if 0 <= a_idx < len(audio) else audio[0]
268 tid = str(a.get("audioTrackId") or "")
269 if "." in tid and tid.split(".")[0]:
270 return tid.split(".")[0]
271 asr = [t for t in raw_tracks if t.get("kind") == "asr"]
272 return str(asr[0].get("languageCode")) if len(asr) == 1 else None
273
274
275def parse_tracks(pr: dict[str, Any]) -> tuple[list[Track], dict[str, str], str | None]:
276 """Caption tracks, the auto-translation languages (code -> name) and the original audio language."""
277 pctr = ((pr.get("captions") or {}).get("playerCaptionsTracklistRenderer") or {})
278 raw = [t for t in pctr.get("captionTracks") or [] if isinstance(t, dict) and t.get("baseUrl")]
279 default_idx = None
280 audio = pctr.get("audioTracks") or []
281 if audio:
282 a_idx = pctr.get("defaultAudioTrackIndex") or 0
283 default_idx = (audio[a_idx] if 0 <= a_idx < len(audio) else audio[0]).get("defaultCaptionTrackIndex")
284 orig = original_audio_language(pctr, raw)
285 tracks = []
286 for i, t in enumerate(raw):
287 url = urljoin("https://www.youtube.com", t["baseUrl"])
288 exp = dict(parse_qsl(urlsplit(url).query)).get("exp", "")
289 name = _text(t.get("name")) or t.get("languageCode", "")
290 auto = t.get("kind") == "asr"
291 code = str(t.get("languageCode") or "")
292 name = re.sub(r"\s*\(auto-generated\)\s*$", "", name)
293 tracks.append(Track(
294 base_url=url, code=code, name=name, auto=auto,
295 translatable=bool(t.get("isTranslatable")), track_name=str(t.get("trackName") or ""),
296 vss_id=str(t.get("vssId") or ""), needs_pot=exp in ("xpe", "xpv"),
297 is_default=(i == default_idx),
298 original_audio=not (auto and orig and base_lang(code) != base_lang(orig))))
299 langs = {}
300 for tl in pctr.get("translationLanguages") or []:
301 code = tl.get("languageCode")
302 if code:
303 langs[code] = _text(tl.get("languageName")) or code
304 return tracks, langs, orig
305
306
307def _lang_match(track_code: str, wanted: str, level: int) -> bool:
308 t, w = norm_lang(track_code), norm_lang(wanted)
309 if level == 0:
310 return t == w
311 if level == 1:
312 return LANG_ALIASES.get(w) == t or LANG_ALIASES.get(t) == w
313 tb, wb = base_lang(t), base_lang(w)
314 return tb == wb or LANG_ALIASES.get(wb) == tb
315
316
317def _type_order(caption_type: str) -> list[bool]:
318 """Order of 'auto' values to try: manual-first -> [False, True], auto-first -> [True, False]..."""
319 return {"manual-first": [False, True], "auto-first": [True, False], "manual-only": [False],
320 "auto-only": [True]}.get(caption_type, [False, True])
321
322
323def find_language(tracks: list[Track], wanted: str, caption_type: str = "manual-first") -> Track | None:
324 """The best track in one language: exact code, then alias (he/iw...), then same base language (en/en-GB)."""
325 for auto in _type_order(caption_type):
326 pool = [t for t in tracks if t.auto == auto]
327 for level in (0, 1, 2):
328 hits = [t for t in pool if _lang_match(t.code, wanted, level)]
329 if hits:
330 hits.sort(key=lambda t: (not t.original_audio, not t.is_default, bool(t.track_name)))
331 return hits[0]
332 return None
333
334
335def choose_track(tracks: list[Track], languages: list[str], caption_type: str = "manual-first",
336 fallback_any: bool = True, original: str | None = None) -> tuple[Track | None, str | None]:
337 """Pick the track to return and say why: 'preferred', 'original' or None (nothing suitable).
338
339 `original` is the language spoken in the video (see original_audio_language)."""
340 allowed = {False, True} & set(_type_order(caption_type))
341 usable = [t for t in tracks if t.auto in allowed]
342 for wanted in languages:
343 t = find_language(usable, wanted, caption_type)
344 if t is not None:
345 return t, "preferred"
346 if not fallback_any or not usable:
347 return None, None
348
349 if not original:
350 asr = [t for t in tracks if t.auto and t.original_audio]
351 original = asr[0].code if len(asr) == 1 else None
352 if original:
353 t = find_language(usable, original, caption_type)
354 if t is not None:
355 return t, "original"
356
357 t = find_language(usable, "en", caption_type)
358 if t is not None:
359 return t, "fallback"
360 defaults = [t for t in usable if t.is_default]
361 if defaults:
362 return defaults[0], "fallback"
363 order = _type_order(caption_type)
364 usable.sort(key=lambda t: (order.index(t.auto), not t.original_audio))
365 return usable[0], "fallback"
366
367
368def timedtext_url(base_url: str, fmt: str | None = "json3", tlang: str | None = None) -> str:
369 parts = urlsplit(base_url)
370 q = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True) if k not in ("fmt", "tlang", "xosf")]
371 if fmt:
372 q.append(("fmt", fmt))
373 if tlang:
374 q.append(("tlang", tlang))
375 return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(q), ""))
376
377
378
379
380@dataclass
381class Options:
382 languages: list[str] = field(default_factory=list)
383 caption_type: str = "manual-first"
384 fallback_any: bool = True
385 translate_to: str | None = None
386 max_tries: int = 5
387 word_timestamps: bool = False
388
389
390@dataclass
391class VideoResult:
392 video_id: str
393 status: str = "blocked"
394 error: str | None = None
395 video_details: dict[str, Any] = field(default_factory=dict)
396 microformat: dict[str, Any] = field(default_factory=dict)
397 tracks: list[Track] = field(default_factory=list)
398 tracks_from_web: bool = False
399 translation_languages: dict[str, str] = field(default_factory=dict)
400 audio_language: str | None = None
401 chosen: Track | None = None
402 chosen_by: str | None = None
403 segments: list[Segment] | None = None
404 language: str | None = None
405 language_name: str | None = None
406 is_translated: bool = False
407 translated_from: str | None = None
408 translation_error: str | None = None
409 client: str | None = None
410 tries: int = 0
411 wire_bytes: int = 0
412 seconds: float = 0.0
413 log: list[str] = field(default_factory=list)
414
415 @property
416 def ok(self) -> bool:
417 return self.status == "ok" and bool(self.segments)
418
419
420class VideoFetcher:
421 def __init__(self, pool: ExitPool, boot: Bootstrap, opts: Options, health: ClientHealth | None = None) -> None:
422 self.pool = pool
423 self.boot = boot
424 self.opts = opts
425 self.health = health or ClientHealth()
426 self.translate_stats: Counter[str] = Counter()
427 self.last_visitor: str | None = None
428 self.hedges = 0
429
430
431
432 async def player(self, ex: Exit, client: Client, video_id: str) -> dict[str, Any]:
433 version = self.boot.version(client)
434 ctx: dict[str, Any] = {"clientName": client.name, "clientVersion": version, "hl": "en", "gl": "US",
435 "timeZone": "UTC", "utcOffsetMinutes": 0, **dict(client.extra)}
436 headers = {"Content-Type": "application/json", "X-YouTube-Client-Name": str(client.number),
437 "X-YouTube-Client-Version": version, "Origin": "https://www.youtube.com"}
438 if client.user_agent:
439 ctx["userAgent"] = client.user_agent
440 headers["User-Agent"] = client.user_agent
441 if client.needs_visitor and ex.visitor:
442 ctx["visitorData"] = ex.visitor
443 headers["X-Goog-Visitor-Id"] = ex.visitor
444 playback: dict[str, Any] = {"html5Preference": "HTML5_PREF_WANTS"}
445 if client.needs_sts and self.boot.sts:
446 playback["signatureTimestamp"] = self.boot.sts
447 body = {"context": {"client": ctx}, "videoId": video_id, "contentCheckOk": True, "racyCheckOk": True,
448 "playbackContext": {"contentPlaybackContext": playback}}
449 r = await ex.request("POST", f"{API}/player?prettyPrint=false", json_body=body, headers=headers,
450 timeout=(8, 12))
451 if r.status_code in (403, 429):
452 ex.bad = True
453 raise Blocked(f"player HTTP {r.status_code}")
454 if r.status_code >= 500:
455 ex.bad = True
456 raise NetError(f"player HTTP {r.status_code}")
457 if r.status_code >= 400:
458 return {"playabilityStatus": {"status": "CLIENT_ERROR", "reason": f"HTTP {r.status_code}"}}
459 try:
460 data = r.json()
461 except ValueError:
462 ex.bad = True
463 raise Blocked("player answered with a web page instead of data") from None
464 visitor = (data.get("responseContext") or {}).get("visitorData")
465 if visitor:
466 ex.visitor = ex.visitor or visitor
467 self.last_visitor = visitor
468 return data
469
470 async def timedtext(self, ex: Exit, client: Client, track: Track, video_id: str,
471 tlang: str | None = None) -> tuple[str, list[Segment] | None]:
472 """('ok', segments) | ('empty', None) | ('rate-limited', None) | ('http', None) | ('parse', None).
473
474 Format: srv1 (YouTube's default XML, lines only) unless word timings are wanted, then json3. For
475 auto-generated captions srv1 is about half the bytes of json3; the other format is the fallback if one
476 stops parsing."""
477 headers = {"Referer": f"https://www.youtube.com/watch?v={video_id}"}
478 if client.user_agent:
479 headers["User-Agent"] = client.user_agent
480 for fmt in (("json3", None) if self.opts.word_timestamps else (None, "json3")):
481 r = await self._hedged_get(ex, timedtext_url(track.base_url, fmt, tlang), headers)
482 if r.status_code == 429:
483 return "rate-limited", None
484 if r.status_code != 200:
485 return "http", None
486 body = r.content or b""
487 if not body.strip():
488 return "empty", None
489 try:
490 return "ok", parse_any(body)
491 except CaptionParseError:
492 continue
493 return "parse", None
494
495 async def ensure_visitor(self, ex: Exit) -> bool:
496 """Give the exit a YouTube visitor id (VISIONOS, ANDROID_VR and TVHTML5_SIMPLY ask for one): the last one
497 seen in this run, or a fresh one from the visitor_id endpoint (about 2 KB)."""
498 if ex.visitor:
499 return True
500 if self.last_visitor:
501 ex.visitor = self.last_visitor
502 return True
503 r = await ex.request("POST", f"{API}/visitor_id?prettyPrint=false",
504 json_body={"context": {"client": {"clientName": "WEB", "hl": "en",
505 "clientVersion": self.boot.web_version}}},
506 headers={"X-YouTube-Client-Name": "1", "X-YouTube-Client-Version": self.boot.web_version,
507 "Origin": "https://www.youtube.com"}, timeout=(8, 10))
508 try:
509 visitor = (r.json().get("responseContext") or {}).get("visitorData") if r.status_code == 200 else None
510 except ValueError:
511 visitor = None
512 if visitor:
513 ex.visitor = self.last_visitor = visitor
514 return bool(visitor)
515
516 async def _hedged_get(self, ex: Exit, url: str, headers: dict[str, str], hedge_after: float = 4.0):
517 """GET, and if YouTube has not answered after `hedge_after` seconds, ask once more and take the first
518 answer. YouTube's caption server sometimes holds a request for about ten seconds when several arrive at
519 once; a second request is usually answered at once. Only slow requests cost the extra bytes."""
520 first = asyncio.create_task(ex.request("GET", url, headers=headers, timeout=(8, 22)))
521 done, _ = await asyncio.wait({first}, timeout=hedge_after)
522 if done:
523 return first.result()
524 self.hedges += 1
525 second = asyncio.create_task(ex.request("GET", url, headers=headers, timeout=(8, 22)))
526 pending = {first, second}
527 error: BaseException | None = None
528 try:
529 while pending:
530 done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
531 for task in done:
532 if task.exception() is None:
533 return task.result()
534 error = task.exception()
535 raise error
536 finally:
537 for task in pending:
538 task.cancel()
539
540
541
542 async def fetch(self, video_id: str) -> VideoResult:
543 res = VideoResult(video_id)
544 t0 = time.monotonic()
545 votes: dict[str, set[str]] = defaultdict(set)
546 reasons: dict[str, str] = {}
547 settled: set[str] = set()
548 last_problem = None
549 for _ in range(self.opts.max_tries):
550 ex = await self.pool.acquire()
551 before = ex.wire_bytes
552 res.tries += 1
553 healthy = True
554 try:
555 outcome = await self._try_exit(ex, res, votes, reasons, settled)
556 if outcome == "done":
557 break
558 if outcome == "exhausted":
559 self._settle_without_agreement(res, votes, reasons, last_problem)
560 break
561 except (Blocked, NetError) as e:
562 healthy = False
563 last_problem = str(e)
564 res.log.append(f"exit {ex.session_id}: {e}")
565 finally:
566 res.wire_bytes += ex.wire_bytes - before
567 await self.pool.release(ex, healthy and not ex.bad)
568 else:
569 self._settle_without_agreement(res, votes, reasons, last_problem)
570 if res.ok and self.opts.translate_to:
571 await self._translate(res)
572 res.seconds = round(time.monotonic() - t0, 2)
573 return res
574
575 def _settle_without_agreement(self, res: VideoResult, votes: dict[str, set[str]], reasons: dict[str, str],
576 last_problem: str | None) -> None:
577 """Out of tries. One client's definite answer beats nothing; otherwise YouTube blocked every try."""
578 ranked = sorted(((len(v), k) for k, v in votes.items() if v), reverse=True)
579 if ranked:
580 kind = ranked[0][1]
581 res.status = kind if kind != "language" else "language-unavailable"
582 res.error = reasons.get(kind)
583 return
584 res.status = "blocked"
585 res.error = (f"YouTube refused all {res.tries} tries (last: {last_problem})" if last_problem
586 else "none of the YouTube clients could be asked (missing signature timestamp or visitor id)")
587
588 def _merge(self, res: VideoResult, pr: dict[str, Any], client: Client) -> None:
589 vd = pr.get("videoDetails") or {}
590 if vd.get("videoId") == res.video_id and len(vd) > len(res.video_details):
591 res.video_details = vd
592 mf = (pr.get("microformat") or {}).get("playerMicroformatRenderer") or {}
593 if mf and not res.microformat:
594 res.microformat = mf
595
596 async def _try_exit(self, ex: Exit, res: VideoResult, votes: dict[str, set[str]], reasons: dict[str, str],
597 settled: set[str]) -> str:
598 """Ask the clients in turn through one exit: "done" (the video's job is finished), "retry" (try another
599 address) or "exhausted" (every client already gave a definite answer)."""
600 bot_hits = 0
601 asked = 0
602 vid = res.video_id
603 for client in self.health.order():
604 if client.key in settled:
605 continue
606 if client.needs_sts and not self.boot.sts:
607 continue
608 if client.needs_visitor and not ex.visitor and not await self.ensure_visitor(ex):
609 continue
610 asked += 1
611 t0 = time.monotonic()
612 pr = await self.player(ex, client, vid)
613 kind, reason = classify(pr, vid)
614 res.log.append(f"{client.key}: {kind} {reason}".strip() + f" ({time.monotonic() - t0:.1f}s)")
615 if kind == "bot":
616 bot_hits += 1
617 if bot_hits >= 2:
618 ex.bad = True
619 raise Blocked(f"bot check ({reason})")
620 continue
621 if kind in ("client", "login", "other"):
622 self.health.fail(client.key, kind)
623 continue
624 self._merge(res, pr, client)
625 if kind in TERMINAL:
626 settled.add(client.key)
627 votes[kind].add(client.key)
628 reasons.setdefault(kind, reason)
629 if len(votes[kind]) >= 2:
630 res.status, res.error = kind, reasons[kind]
631 return "done"
632 continue
633 if kind == "live":
634 res.status, res.error = "live", "Live stream in progress: captions are available after it ends"
635 return "done"
636
637 tracks, langs, orig = parse_tracks(pr)
638 res.translation_languages.update(langs)
639 res.audio_language = res.audio_language or orig
640 if tracks and (client.web_like or not res.tracks_from_web) and len(tracks) >= len(res.tracks):
641 res.tracks, res.tracks_from_web = tracks, client.web_like or res.tracks_from_web
642 if not tracks:
643 settled.add(client.key)
644 votes["no-captions"].add(client.key)
645 reasons.setdefault("no-captions", "This video has no captions or subtitles")
646 if len(votes["no-captions"]) >= 2:
647 res.status, res.error = "no-captions", reasons["no-captions"]
648 return "done"
649 continue
650 usable = [t for t in tracks if not t.needs_pot]
651 if not usable:
652 self.health.fail(client.key, "po-token")
653 continue
654 track, why = choose_track(usable, self.opts.languages, self.opts.caption_type, self.opts.fallback_any,
655 res.audio_language)
656 if track is None:
657
658 fuller, _ = choose_track(res.tracks, self.opts.languages, self.opts.caption_type,
659 self.opts.fallback_any, res.audio_language)
660 settled.add(client.key)
661 if fuller is not None:
662 continue
663 votes["language"].add(client.key)
664 wanted = ", ".join(self.opts.languages) or "any language"
665 kinds = {"manual-only": "manual ", "auto-only": "auto-generated "}.get(self.opts.caption_type, "")
666 reasons.setdefault("language", f"No {kinds}captions in {wanted}; see availableLanguages")
667 if client.web_like or len(votes["language"]) >= 2:
668 res.status, res.error = "language-unavailable", reasons["language"]
669 return "done"
670 continue
671 t0 = time.monotonic()
672 outcome, segments = await self.timedtext(ex, client, track, vid)
673 res.log.append(f"{client.key} timedtext {track.code}{' (auto)' if track.auto else ''}: {outcome} "
674 f"({time.monotonic() - t0:.1f}s)")
675 if outcome == "rate-limited":
676 ex.bad = True
677 raise Blocked("caption download HTTP 429")
678 if outcome != "ok":
679 self.health.fail(client.key, f"timedtext-{outcome}")
680 continue
681 if not segments:
682 settled.add(client.key)
683 votes["no-captions"].add(client.key)
684 reasons.setdefault("no-captions", "The caption track is empty")
685 continue
686 self.health.ok(client.key)
687 res.status, res.error = "ok", None
688 res.chosen, res.chosen_by, res.segments, res.client = track, why, segments, client.key
689 res.language, res.language_name = track.code, track.name
690 return "done"
691 if asked:
692 ex.bad = True
693 return "retry"
694 return "exhausted"
695
696 async def _translate(self, res: VideoResult) -> None:
697 """Replace the transcript with YouTube's auto-translation into `translate_to`, if YouTube allows it.
698
699 A native track in the target language is used directly instead. Failures keep the original transcript.
700 """
701 target = norm_lang(self.opts.translate_to)
702 src = res.chosen
703 if src is None or not target:
704 return
705 if base_lang(src.code) == base_lang(target) and _lang_match(src.code, target, 2):
706 return
707 native = find_language(res.tracks, target, "manual-first")
708 if native is not None and not native.needs_pot:
709 ok = await self._fetch_track_into(res, native)
710 if ok:
711 return
712 if not src.translatable:
713 res.translation_error = "YouTube does not offer auto-translation for this caption track"
714 return
715 code = next((c for c in res.translation_languages if norm_lang(c) == target), None)
716 if code is None and res.tracks_from_web and len(res.translation_languages) > 50:
717 res.translation_error = f"YouTube does not auto-translate into '{self.opts.translate_to}'"
718 return
719 code = code or self.opts.translate_to
720 client = CLIENTS.get(res.client or "web", CLIENTS["web"])
721 ex = await self.pool.acquire()
722 before = ex.wire_bytes
723 failures = 0
724 try:
725 for attempt in range(TRANSLATE_TRIES):
726 if attempt and attempt % 3 == 0:
727 res.wire_bytes += ex.wire_bytes - before
728 await self.pool.release(ex, healthy=False)
729 ex = await self.pool.acquire()
730 before = ex.wire_bytes
731 try:
732 outcome, segments = await self.timedtext(ex, client, src, res.video_id, tlang=code)
733 except NetError:
734 outcome, segments = "network", None
735 self.translate_stats[outcome] += 1
736 if outcome == "ok" and segments:
737 res.segments = segments
738 res.is_translated, res.translated_from = True, src.code
739 res.language = code
740 res.language_name = res.translation_languages.get(code, code)
741 res.translation_error = None
742 return
743 failures += 1
744 await asyncio.sleep(0.8 + random.random())
745 res.translation_error = (f"YouTube refused to auto-translate into '{code}' {failures} times in a row "
746 "(it rate-limits translations); the original transcript is returned")
747 finally:
748 res.wire_bytes += ex.wire_bytes - before
749 await self.pool.release(ex, healthy=False)
750
751 async def _fetch_track_into(self, res: VideoResult, track: Track) -> bool:
752 client = CLIENTS.get(res.client or "web", CLIENTS["web"])
753 for _ in range(2):
754 ex = await self.pool.acquire()
755 before = ex.wire_bytes
756 healthy = True
757 try:
758 outcome, segments = await self.timedtext(ex, client, track, res.video_id)
759 except NetError:
760 outcome, segments, healthy = "network", None, False
761 finally:
762 res.wire_bytes += ex.wire_bytes - before
763 await self.pool.release(ex, healthy and outcome == "ok")
764 if outcome == "ok" and segments:
765 res.chosen, res.segments = track, segments
766 res.language, res.language_name = track.code, track.name
767 res.chosen_by = "translate-target"
768 return True
769 return False