AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(youtube): request the preferred language from the ScrapeCreators transcript fallback (#1191)
Jay Hemnani422c97eda773
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 3d7a96c6..88e5fd8a 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -186,7 +186,7 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \**Reddit keyless pacing.** Unauthenticated reddit.com requests (site search, listing partials, shreddit) share one token bucket. The default is `1` request per second with a burst of 2, slow enough that engine fan-out does not trip HTTP 429 on a typical home IP. Set `LAST30DAYS_REDDIT_KEYLESS_RATE` to a float req/sec to trade wall-clock for coverage: higher finishes faster and loses more sub-requests to 429; lower is safer and slower. Invalid or non-positive values fall back to `1`. A 429'd search or listing sub-request is retried once after a short jittered pause, still through the limiter. Identical reddit.com requests within one command (subreddit listings, listing feeds, comment pages, which repeat across subqueries) are fetched once and memoized, so a typical four-subquery run issues roughly a quarter of the requests it used to. Comment enrichment covers 4 / 8 / 12 threads per subquery at quick / default / deep depth. This does not change ScrapeCreators routing (`LAST30DAYS_REDDIT_BACKEND` / `LAST30DAYS_REDDIT_SC_MIN_ITEMS`).-**YouTube transcript tuning.** `LAST30DAYS_YT_SUB_LANGS` controls the comma-separated caption-language priority passed to yt-dlp and defaults to `en,es,pt`. `LAST30DAYS_YT_PLAYER_CLIENT` defaults to `android` so yt-dlp can pass YouTube's web bot-gate without cookies (search, transcripts, and comments); set it empty to disable. When `SCRAPECREATORS_API_KEY` is available, yt-dlp uses one fast attempt before the paid fallback; set `LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT` to the number of seconds allowed for that attempt when a throttled host needs longer than the 12-second default. A VTT completed before the timeout is reused rather than discarded. `LAST30DAYS_YT_SEARCH_TIMEOUT` sets the per-search yt-dlp deadline (default 120s). Comparison-mode fan-out also caps concurrent yt-dlp processes process-wide and caches identical searches within a run so redundant `ytsearch` calls do not self-throttle the same IP.+**YouTube transcript tuning.** `LAST30DAYS_YT_SUB_LANGS` controls the comma-separated caption-language priority passed to yt-dlp and defaults to `en,es,pt`. The ScrapeCreators transcript fallback tries at most the first three distinct languages in that order, with a shared 30-second deadline per video; it stops after the first usable transcript. `LAST30DAYS_YT_PLAYER_CLIENT` defaults to `android` so yt-dlp can pass YouTube's web bot-gate without cookies (search, transcripts, and comments); set it empty to disable. When `SCRAPECREATORS_API_KEY` is available, yt-dlp uses one fast attempt before the paid fallback; set `LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT` to the number of seconds allowed for that attempt when a throttled host needs longer than the 12-second default. A VTT completed before the timeout is reused rather than discarded. `LAST30DAYS_YT_SEARCH_TIMEOUT` sets the per-search yt-dlp deadline (default 120s). Comparison-mode fan-out also caps concurrent yt-dlp processes process-wide and caches identical searches within a run so redundant `ytsearch` calls do not self-throttle the same IP.**X backend priority (bird first).** The default X backend chain is bird (browser cookies) → xai (API key) → xurl (OAuth2 CLI) → xquik (API key). Cookies beat `XAI_API_KEY` when both are present. A leftover grok login never steals the X lane; see below. `xapi` (the official X API v2 with `X_BEARER_TOKEN`) is opt-in on these hosts (`LAST30DAYS_X_BACKEND=xapi`), so an ambient bearer never spends X API credits when the free path comes back empty. **Grok Bot exception.** On a Grok Bot host (`LAST30DAYS_HOST=grok-bot`) the unpinned chain is the official chain instead: xapi (`X_BEARER_TOKEN`) → xai (`XAI_API_KEY`) → xurl (the X API through X's CLI). When the bot fetched X itself (its built-in X tools, or the X connector), those results come first and the chain is not called at all; see [Grok Bot](#grok-bot) under Per-client patterns.diff --git a/changelog.d/1169.fixed.md b/changelog.d/1169.fixed.mdnew file mode 100644index 00000000..ad8d144a--- /dev/null+++ b/changelog.d/1169.fixed.md@@ -0,0 +1 @@+The ScrapeCreators YouTube transcript fallback now requests up to three distinct preferred caption languages in order (`LAST30DAYS_YT_SUB_LANGS`, default `en,es,pt`). It skips empty tracks and limits total fallback time to 30 seconds per video.diff --git a/skills/last30days/scripts/lib/youtube_yt.py b/skills/last30days/scripts/lib/youtube_yt.pyindex 0927f79b..ea44be13 100644--- a/skills/last30days/scripts/lib/youtube_yt.py+++ b/skills/last30days/scripts/lib/youtube_yt.py@@ -89,6 +89,8 @@ _search_cache_lock = threading.Lock()# comment API can never dominate a run's wall clock (bounded to 3 videos)._COMMENT_TIMEOUT = 20_SC_LOW_CREDIT_THRESHOLD = 50 # warn once ScrapeCreators credits drop below this+_SC_TRANSCRIPT_MAX_LANGUAGES = 3+_SC_TRANSCRIPT_TIMEOUT = 30# Transient = worth retrying (and definitely not "no captions")._TRANSIENT_RE = re.compile(r"429|too many requests|sign in to confirm|not a bot|rate.?limit"@@ -1726,33 +1728,47 @@ def _sc_fetch_transcript(video_id: str, token: str) -> Optional[str]:Plaintext transcript string, or None if unavailable."""video_url = f"https://www.youtube.com/watch?v={video_id}"- try:- # Isolate SC transcript fetch errors from the pipeline-level- # capture_failures() context.- with http.capture_failures() as _tf:- data = http.get(- f"{SCRAPECREATORS_YT_BASE}/video/transcript",- params={"url": video_url},- headers=http.scrapecreators_headers(token),- timeout=30,- retries=1,- )- except Exception as exc:- _log(f"SC transcript error for {video_id}: {exc}")- return None+ transcript = None+ deadline = time.monotonic() + _SC_TRANSCRIPT_TIMEOUT+ # Without a language the endpoint may return an auto-dubbed track (#1169).+ languages = list(dict.fromkeys(_ytdlp_sub_langs().split(",")))[:_SC_TRANSCRIPT_MAX_LANGUAGES]+ for language in languages:+ if time.monotonic() >= deadline:+ break+ try:+ # Isolate SC transcript fetch errors from the pipeline-level+ # capture_failures() context.+ with http.capture_failures() as _tf:+ data = http.get(+ f"{SCRAPECREATORS_YT_BASE}/video/transcript",+ params={"url": video_url, "language": language},+ headers=http.scrapecreators_headers(token),+ timeout=_SC_TRANSCRIPT_TIMEOUT,+ retries=1,+ max_429_retries=0,+ deadline_monotonic=deadline,+ owned_get=True,+ )+ except Exception as exc:+ _log(f"SC transcript error for {video_id} ({language}): {exc}")+ if getattr(exc, "status_code", None) == 404:+ continue+ return None- _warn_low_sc_credits(data)+ _warn_low_sc_credits(data)- transcript = data.get("transcript")+ transcript = data.get("transcript")+ if isinstance(transcript, list):+ transcript = " ".join(_sc_segment_text(seg) for seg in transcript).strip()+ if not isinstance(transcript, str):+ transcript = None+ continue+ transcript = _clean_vtt(transcript)+ if transcript:+ breakif not transcript:return None- if isinstance(transcript, list):- transcript = " ".join(_sc_segment_text(seg) for seg in transcript).strip()-- # Clean VTT formatting if present- transcript = _clean_vtt(transcript)-# Truncate to max wordswords = transcript.split()if len(words) > TRANSCRIPT_MAX_WORDS:diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.pyindex aed56443..533c157a 100644--- a/tests/test_youtube_yt.py+++ b/tests/test_youtube_yt.py@@ -1109,6 +1109,111 @@ class TestScTranscriptParsing(unittest.TestCase):youtube_yt._sc_fetch_transcript("vidJ", "key")self.assertTrue(any("credits low" in m.lower() for m in logs))+ def test_requests_preferred_language(self):+ """Without a language the endpoint can return an auto-dubbed track (#1169)."""+ payload = {"transcript": "some transcript text", "credits_remaining": 9999}+ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": ""}), \+ mock.patch.object(youtube_yt.http, "get", return_value=payload) as get_mock:+ youtube_yt._sc_fetch_transcript("vidL", "key")+ self.assertEqual(get_mock.call_args.kwargs["params"]["language"], "en")++ def test_language_follows_sub_langs_setting(self):+ payload = {"transcript": "some transcript text", "credits_remaining": 9999}+ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "es,en"}), \+ mock.patch.object(youtube_yt.http, "get", return_value=payload) as get_mock:+ youtube_yt._sc_fetch_transcript("vidM", "key")+ self.assertEqual(get_mock.call_args.kwargs["params"]["language"], "es")++ def test_tries_next_language_when_first_has_no_transcript(self):+ responses = [{"transcript": None}, {"transcript": "texto en español"}]+ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": ""}), \+ mock.patch.object(youtube_yt.http, "get", side_effect=responses) as get_mock:+ out = youtube_yt._sc_fetch_transcript("vidN", "key")+ self.assertEqual(out, "texto en español")+ self.assertEqual(+ [c.kwargs["params"]["language"] for c in get_mock.call_args_list], ["en", "es"],+ )++ def test_default_fallback_reaches_third_language_with_one_deadline(self):+ responses = [+ {"transcript": None},+ {"transcript": None},+ {"transcript": "legendas em português"},+ ]+ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": ""}), \+ mock.patch.object(youtube_yt.http, "get", side_effect=responses) as get_mock:+ out = youtube_yt._sc_fetch_transcript("vidP", "key")+ self.assertEqual(out, "legendas em português")+ self.assertEqual(+ [c.kwargs["params"]["language"] for c in get_mock.call_args_list],+ ["en", "es", "pt"],+ )+ self.assertEqual(+ len({c.kwargs["deadline_monotonic"] for c in get_mock.call_args_list}), 1,+ )+ self.assertTrue(all(c.kwargs["max_429_retries"] == 0 for c in get_mock.call_args_list))+ self.assertTrue(all(c.kwargs["owned_get"] for c in get_mock.call_args_list))++ def test_custom_language_list_deduplicates_and_stops_after_three_requests(self):+ with mock.patch.dict(+ os.environ, {"LAST30DAYS_YT_SUB_LANGS": "fr,fr,de,ja,en,es"},+ ), mock.patch.object(+ youtube_yt.http, "get", return_value={"transcript": None},+ ) as get_mock:+ out = youtube_yt._sc_fetch_transcript("vidQ", "key")+ self.assertIsNone(out)+ self.assertEqual(+ [c.kwargs["params"]["language"] for c in get_mock.call_args_list],+ ["fr", "de", "ja"],+ )++ def test_empty_caption_segments_do_not_stop_language_fallback(self):+ responses = [+ {"transcript": [{"text": None}, {"text": " "}]},+ {"transcript": [{"text": "texto en español"}]},+ ]+ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en,es"}), \+ mock.patch.object(youtube_yt.http, "get", side_effect=responses) as get_mock:+ out = youtube_yt._sc_fetch_transcript("vidR", "key")+ self.assertEqual(out, "texto en español")+ self.assertEqual(get_mock.call_count, 2)++ def test_404_tries_next_language(self):+ responses = [+ youtube_yt.http.HTTPError("HTTP 404", status_code=404),+ {"transcript": "texto en español"},+ ]+ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en,es"}), \+ mock.patch.object(youtube_yt.http, "get", side_effect=responses) as get_mock:+ out = youtube_yt._sc_fetch_transcript("vidS", "key")+ self.assertEqual(out, "texto en español")+ self.assertEqual(get_mock.call_count, 2)++ def test_shared_deadline_stops_before_another_request(self):+ clock = {"now": 100.0}++ def first_request(*_args, **_kwargs):+ clock["now"] = 131.0+ return {"transcript": None}++ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en,es"}), \+ mock.patch.object(youtube_yt.time, "monotonic", side_effect=lambda: clock["now"]), \+ mock.patch.object(youtube_yt.http, "get", side_effect=first_request) as get_mock:+ out = youtube_yt._sc_fetch_transcript("vidT", "key")+ self.assertIsNone(out)+ self.assertEqual(get_mock.call_count, 1)+ self.assertEqual(get_mock.call_args.kwargs["deadline_monotonic"], 130.0)++ def test_stops_on_non_404_error(self):+ with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": ""}), \+ mock.patch.object(+ youtube_yt.http, "get",+ side_effect=youtube_yt.http.HTTPError("HTTP 429", status_code=429),+ ) as get_mock:+ out = youtube_yt._sc_fetch_transcript("vidO", "key")+ self.assertIsNone(out)+ self.assertEqual(get_mock.call_count, 1)+def test_healthy_credits_no_warning(self):payload = {"transcript": "some transcript text", "credits_remaining": 9999}logs = []