Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

feat(youtube): ScrapeCreators as default-on backup for transcripts + comments (#637)

Matt Van Horn75badd911798
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 0c35ae66..c7689f64 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -68,7 +68,8 @@ The project-scoped file is the cleanest pattern for **per-client setups**: drop
| Hacker News | none | always on | yes |
| Polymarket | none | always on | yes |
| GitHub | `gh` CLI installed (uses your GitHub auth) | always on if `gh` present | yes |
-| YouTube | `yt-dlp` CLI installed | always on if `yt-dlp` present | yes |
+| YouTube | `yt-dlp` CLI installed; `SCRAPECREATORS_API_KEY` adds a server-side transcript fallback used only when yt-dlp fails (429 / bot-gate) | always on if `yt-dlp` present; SC transcript fallback default-on when key set (no credit spent unless yt-dlp fails) | yes |
+| YouTube comments | `SCRAPECREATORS_API_KEY` (default-on; suppress via `EXCLUDE_SOURCES=youtube_comments`) | top comments on the top ~3 videos by engagement | ~3 calls/run; 10K free calls |
| Digg | `digg-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install digg --cli-only`; binary defaults to `$HOME/.local/bin` — Hermes/OpenClaw agent subprocesses must inherit that dir on PATH for Digg to activate; prior pp-digg installs use the same path) | always on if `digg-pp-cli` on PATH | yes (free, keyless, read-only) |
| X / Twitter | one of: `AUTH_TOKEN` + `CT0` (browser cookies, Bird CLI), `XAI_API_KEY`, `XQUIK_API_KEY`, `SCRAPECREATORS_API_KEY`, or `FROM_BROWSER` (cookie-jar auth) | X items in results | cookie-jar / Bird = free; Xquik / xAI / ScrapeCreators = key-based |
| TikTok | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `tiktok` | TikTok items | 10K free calls |
diff --git a/README.md b/README.md
index 32a3fa19..17e8a897 100644
--- a/README.md
+++ b/README.md
@@ -157,7 +157,7 @@ Say "eli5 on" after any research run. The synthesis rewrites in plain language.
- **YouTube transcripts that actually work.** Widened candidate pool 3x past music videos to reach talk/review content with captions.
- **TikTok, Instagram, Threads.** All three activate automatically once `SCRAPECREATORS_API_KEY` is set — same key, same per-call cost. Suppress any of them with `EXCLUDE_SOURCES=tiktok,instagram,threads` (any comma-separated subset).
- **Pinterest.** Per-query opt-in (visual pins, narrow utility): the model passes `--search=pinterest` for the runs that need it. Requires `SCRAPECREATORS_API_KEY`.
-- **YouTube + TikTok comments.** Persistent opt-in via `INCLUDE_SOURCES=youtube_comments,tiktok_comments` because each video pulls N extra ScrapeCreators calls on top of the base search. Surface top comments with vote counts the same way Reddit does.
+- **YouTube comments + transcript fallback.** Both activate automatically once `SCRAPECREATORS_API_KEY` is set, the same default-on backup tier. Transcripts only fall back to ScrapeCreators when yt-dlp fails (no credit spent on success); comments are bounded to the top few videos (~3 extra calls per run). Suppress comments with `EXCLUDE_SOURCES=youtube_comments`. **TikTok comments** stay opt-in via `INCLUDE_SOURCES=tiktok_comments`. Surface top comments with vote counts the same way Reddit does.
- **Perplexity Sonar.** Grounded web search with citations via OpenRouter. Add `OPENROUTER_API_KEY` and `INCLUDE_SOURCES=perplexity` (it's a separate paid API — opt-in keeps you from being surprise-billed).
- **Polymarket noise filtering.** Common-word disambiguation prevents "Apple" from matching "Will Apple release a car?"
- **Resilient Reddit.** Timeout budgets and runtime fallback. One slow thread doesn't kill the whole run.
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index 96eefc64..b73e0738 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -1067,7 +1067,7 @@ The script will automatically:
**Read the ENTIRE output.** It contains EIGHT data sections in this order: Reddit items, X items, YouTube items, TikTok items, Instagram Reels items, Hacker News items, Polymarket items, and WebSearch items. If you miss sections, you will produce incomplete stats.
-**YouTube items in the output look like:** `**{video_id}** (score:N) {channel_name} [N views, N likes]` followed by a title, URL, **transcript highlights** (pre-extracted quotable excerpts from the video), and an optional full transcript in a collapsible section. **Quote the highlights directly in your synthesis.** When YouTube items also include top comments (enabled via `youtube_comments`), quote those too with their like counts - they capture how viewers reacted to the video. Transcript highlights and top comments are complementary signals; use both when present. Attribute transcript quotes to the channel name, comment quotes to the commenter. Count them and include them in your synthesis and stats block.
+**YouTube items in the output look like:** `**{video_id}** (score:N) {channel_name} [N views, N likes]` followed by a title, URL, **transcript highlights** (pre-extracted quotable excerpts from the video), and an optional full transcript in a collapsible section. **Quote the highlights directly in your synthesis.** When YouTube items also include top comments (default-on once a ScrapeCreators key is set; suppress via `EXCLUDE_SOURCES=youtube_comments`), quote those too with their like counts - they capture how viewers reacted to the video. Transcript highlights and top comments are complementary signals; use both when present. Attribute transcript quotes to the channel name, comment quotes to the commenter. Count them and include them in your synthesis and stats block.
**TikTok items in the output look like:** `**{TK_id}** (score:N) @{creator} [N views, N likes]` followed by a caption, URL, hashtags, and optional caption snippet. Count them and include them in your synthesis and stats block.
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index ba625ea5..c2ca16a2 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -644,12 +644,17 @@ def is_ytdlp_available() -> bool:
def is_youtube_comments_available(config: dict[str, Any]) -> bool:
"""Check if YouTube comment enrichment is available.
- Requires SCRAPECREATORS_API_KEY AND youtube_comments in INCLUDE_SOURCES.
+ Default-on when SCRAPECREATORS_API_KEY is set — the same key-only backup
+ tier as the YouTube transcript fallback (``is_youtube_sc_available``). Cost
+ is bounded by ``enrich_with_comments(max_videos=3)`` (~3 credits per run).
+ Suppress via ``EXCLUDE_SOURCES=youtube_comments``.
+
+ Note: TikTok/Instagram comments remain explicit ``INCLUDE_SOURCES`` opt-ins
+ (see ``is_tiktok_comments_available``); only YouTube comments are default-on.
"""
if not config.get('SCRAPECREATORS_API_KEY'):
return False
- include = _parse_include_sources(config)
- return 'youtube_comments' in include
+ return 'youtube_comments' not in _parse_exclude_sources(config)
def is_tiktok_comments_available(config: dict[str, Any]) -> bool:
@@ -763,6 +768,12 @@ def _parse_include_sources(config: dict[str, Any]) -> set[str]:
return {s.strip().lower() for s in raw.split(',') if s.strip()}
+def _parse_exclude_sources(config: dict[str, Any]) -> set[str]:
+ """Parse EXCLUDE_SOURCES config value into a set of lowercase source names."""
+ raw = config.get('EXCLUDE_SOURCES') or ''
+ return {s.strip().lower() for s in raw.split(',') if s.strip()}
+
+
def is_threads_available(config: dict[str, Any]) -> bool:
"""Check if Threads source is available.
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 9c6dbce2..18f8fc5a 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -635,7 +635,13 @@ def _finalize_items_by_source(
# relevance. Backfill survivors that arrived without one so the
# transcript budget lands on videos the brief actually shows
# (#542).
- youtube_yt.backfill_transcripts(items, topic=topic, depth=depth)
+ sc_token = (
+ config.get("SCRAPECREATORS_API_KEY")
+ if config and env.is_youtube_sc_available(config) else None
+ )
+ youtube_yt.backfill_transcripts(
+ items, topic=topic, depth=depth, token=sc_token,
+ )
# Post-merge topic-relevance filter for Polymarket: comparison queries
# fan out into per-entity subqueries ("Hermes", "OpenClaw") whose topic
# is too narrow for Gamma API to filter meaningfully. Re-validating the
@@ -1147,22 +1153,34 @@ def _retrieve_stream(
# from the original user topic, not the planner's narrowed search_query.
yt_query = raw_topic or subquery.search_query
result = None
- # Try yt-dlp first, fall back to SC YouTube if it fails or isn't installed
+ # ScrapeCreators key (when present) is the default-on backup tier: it
+ # powers the per-video transcript fallback, the SC search fallback, and
+ # comment enrichment. None when no key, which keeps everything keyless.
+ sc_token = (
+ config.get("SCRAPECREATORS_API_KEY", "")
+ if env.is_youtube_sc_available(config) else None
+ )
+ # Try yt-dlp first; the SC transcript fallback covers per-video failures.
if which("yt-dlp"):
try:
- result = youtube_yt.search_and_transcribe(yt_query, from_date, to_date, depth=depth)
+ result = youtube_yt.search_and_transcribe(
+ yt_query, from_date, to_date, depth=depth, token=sc_token,
+ )
except Exception:
result = None
- if (result is None or not result.get("items")) and env.is_youtube_sc_available(config):
- sc_token = config.get("SCRAPECREATORS_API_KEY", "")
- result = youtube_yt.search_youtube_sc(yt_query, from_date, to_date, depth=depth, token=sc_token)
+ # Fall back to SC YouTube search if yt-dlp failed or isn't installed.
+ if (result is None or not result.get("items")) and sc_token:
+ result = youtube_yt.search_youtube_sc(
+ yt_query, from_date, to_date, depth=depth, token=sc_token,
+ )
if result is None:
result = {"items": []}
- # Enrich top videos with comments when SC key is available
+ # Enrich top videos with comments (default-on when a key is present).
items = youtube_yt.parse_youtube_response(result)
if items and env.is_youtube_comments_available(config):
- sc_token = config.get("SCRAPECREATORS_API_KEY", "")
- youtube_yt.enrich_with_comments(items, token=sc_token)
+ youtube_yt.enrich_with_comments(
+ items, token=config.get("SCRAPECREATORS_API_KEY", ""),
+ )
return items, {}
if source == "tiktok":
# Use raw_topic so expand_tiktok_queries() generates diverse variants
diff --git a/skills/last30days/scripts/lib/youtube_yt.py b/skills/last30days/scripts/lib/youtube_yt.py
index 811420eb..a1fde08d 100644
--- a/skills/last30days/scripts/lib/youtube_yt.py
+++ b/skills/last30days/scripts/lib/youtube_yt.py
@@ -69,6 +69,9 @@ from .relevance import token_overlap_relevance as _compute_relevance
# backoff.
_TRANSCRIPT_MAX_RETRIES = 2
_TRANSCRIPT_BACKOFF_BASE = 2.0 # seconds; multiplied by (attempt + 1)
+_TRANSCRIPT_TIMEOUT = 30 # seconds per yt-dlp attempt (keyless: no fallback to fail over to)
+_TRANSCRIPT_FAST_TIMEOUT = 12 # seconds per attempt when a ScrapeCreators fallback exists
+_SC_LOW_CREDIT_THRESHOLD = 50 # warn once ScrapeCreators credits drop below this
# 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"
@@ -612,6 +615,7 @@ def _fetch_transcript_ytdlp(
video_id: str,
temp_dir: str,
status: Optional[Dict[str, Any]] = None,
+ fast_fail: bool = False,
) -> Optional[str]:
"""Fetch transcript using yt-dlp (original implementation).
@@ -623,6 +627,12 @@ def _fetch_transcript_ytdlp(
error (rate-limit / bot-check / network / timeout) apart from a
video that genuinely has no captions, and skip the misleading
"no captions found" log + the YouTube-blocked HTTP fallback.
+ fast_fail: When True, a ScrapeCreators fallback is available, so a
+ transient failure (429 / bot-gate) should fail over fast rather
+ than retry into the same rate limit. Collapses to a single attempt
+ with a shorter per-attempt timeout. The slow thing in a run is
+ yt-dlp retrying, not the fast SC fetch, so this is what keeps
+ "yt-dlp first" from reintroducing the multi-minute hang.
Returns:
Raw VTT text, or None if no captions are available or the fetch failed.
@@ -641,14 +651,15 @@ def _fetch_transcript_ytdlp(
f"https://www.youtube.com/watch?v={video_id}",
]
- attempts = _TRANSCRIPT_MAX_RETRIES + 1
+ timeout = _TRANSCRIPT_FAST_TIMEOUT if fast_fail else _TRANSCRIPT_TIMEOUT
+ attempts = 1 if fast_fail else _TRANSCRIPT_MAX_RETRIES + 1
last_reason: Optional[str] = None
for attempt in range(attempts):
try:
- result = subproc.run_with_timeout(cmd, timeout=30)
+ result = subproc.run_with_timeout(cmd, timeout=timeout)
except subproc.SubprocTimeout:
- last_reason = "timed out after 30s"
- _log(f"yt-dlp transcript timed out after 30s for {video_id} "
+ last_reason = f"timed out after {timeout}s"
+ _log(f"yt-dlp transcript timed out after {timeout}s for {video_id} "
f"(attempt {attempt + 1}/{attempts})")
if attempt < attempts - 1:
time.sleep(_transcript_backoff(video_id, attempt))
@@ -704,15 +715,30 @@ def _fetch_transcript_ytdlp(
return None
+def _should_try_sc_transcript(status: Optional[Dict[str, Any]]) -> bool:
+ """Whether to spend a ScrapeCreators credit after the keyless cascade failed.
+
+ Skip when the keyless path *proved* the uploader has no caption track
+ (``no_caption_tracks``): SC would also return nothing, so a credit would be
+ wasted. A transient hard failure (``ytdlp_error``: 429 / bot-gate / timeout)
+ is a false negative, so SC is worth trying.
+ """
+ st = status or {}
+ return not st.get("no_caption_tracks")
+
+
def fetch_transcript(
video_id: str,
temp_dir: str,
status: Optional[Dict[str, Any]] = None,
+ token: Optional[str] = None,
) -> Optional[str]:
"""Fetch auto-generated transcript for a YouTube video.
Uses yt-dlp when available (preferred, more robust). Falls back to
- direct HTTP transcript fetching when yt-dlp is not installed.
+ direct HTTP transcript fetching when yt-dlp is not installed, and finally
+ to the ScrapeCreators transcript endpoint when a key is present and the
+ keyless cascade comes back empty.
Args:
video_id: YouTube video ID
@@ -721,6 +747,11 @@ def fetch_transcript(
per-video signals like ``no_caption_tracks``. Used to surface a
captions-disabled count so the quality nudge avoids false-positive
"stale yt-dlp" flags.
+ token: Optional ScrapeCreators API key. When present, yt-dlp fails over
+ fast (see ``_fetch_transcript_ytdlp`` ``fast_fail``) and a true hard
+ failure falls back to the SC transcript endpoint. A credit is only
+ spent on a genuine yt-dlp failure, never on success and never on a
+ video proven to have no captions. None preserves keyless behavior.
Returns:
Plaintext transcript string, or None if no captions available.
@@ -733,36 +764,49 @@ def fetch_transcript(
_log(f"SSH yt-dlp transcript failed for {video_id}, trying direct HTTP fallback")
raw_vtt = _fetch_transcript_direct(video_id, status=status)
elif is_ytdlp_installed():
- raw_vtt = _fetch_transcript_ytdlp(video_id, temp_dir, status=status)
+ raw_vtt = _fetch_transcript_ytdlp(
+ video_id, temp_dir, status=status, fast_fail=bool(token),
+ )
if not raw_vtt:
ytdlp_error = (status or {}).get("ytdlp_error")
if ytdlp_error:
+ # Hard failure (429 / bot-gate / timeout). The direct-HTTP
+ # fallback is also YouTube-blocked, so skip it and let the
+ # ScrapeCreators fallback below handle it when a key is present.
_log(f"Transcript fetch failed for {video_id}: {ytdlp_error}")
- return None
- _log(f"yt-dlp found no captions for {video_id}, trying direct HTTP fallback")
- raw_vtt = _fetch_transcript_direct(video_id, status=status)
+ else:
+ _log(f"yt-dlp found no captions for {video_id}, trying direct HTTP fallback")
+ raw_vtt = _fetch_transcript_direct(video_id, status=status)
else:
_log("yt-dlp not installed, using direct HTTP transcript fetch")
raw_vtt = _fetch_transcript_direct(video_id, status=status)
- if not raw_vtt:
- _log(f"No transcript available for {video_id} (no captions found)")
- return None
-
- transcript = _clean_vtt(raw_vtt)
-
- # Truncate to max words
- words = transcript.split()
- if len(words) > TRANSCRIPT_MAX_WORDS:
- transcript = ' '.join(words[:TRANSCRIPT_MAX_WORDS]) + '...'
-
- return transcript if transcript else None
+ if raw_vtt:
+ transcript = _clean_vtt(raw_vtt)
+ # Truncate to max words
+ words = transcript.split()
+ if len(words) > TRANSCRIPT_MAX_WORDS:
+ transcript = ' '.join(words[:TRANSCRIPT_MAX_WORDS]) + '...'
+ return transcript if transcript else None
+
+ # Keyless cascade produced nothing. When a ScrapeCreators key is present and
+ # the video was not proven caption-less, fall back to the SC transcript
+ # endpoint (fetched server-side: no 429, cookies, or PO tokens). Returns
+ # already-cleaned, word-capped plaintext.
+ if token and _should_try_sc_transcript(status):
+ sc_transcript = _sc_fetch_transcript(video_id, token)
+ if sc_transcript:
+ return sc_transcript
+
+ _log(f"No transcript available for {video_id}")
+ return None
def fetch_transcripts_parallel(
video_ids: List[str],
max_workers: int = 5,
out_captions_disabled: Optional[Set[str]] = None,
+ token: Optional[str] = None,
) -> Dict[str, Optional[str]]:
"""Fetch transcripts for multiple videos in parallel.
@@ -772,6 +816,9 @@ def fetch_transcripts_parallel(
out_captions_disabled: Optional set mutated to record video_ids whose
uploader confirmed no caption tracks (vs. transient fetch failures).
Backward-compatible: callers that don't care can omit.
+ token: Optional ScrapeCreators API key, threaded to each
+ ``fetch_transcript`` so the per-video SC fallback activates on
+ yt-dlp failure. None preserves keyless behavior.
Returns:
Dict mapping video_id to transcript text (or None).
@@ -786,7 +833,9 @@ def fetch_transcripts_parallel(
with tempfile.TemporaryDirectory() as temp_dir:
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {
- executor.submit(fetch_transcript, vid, temp_dir, statuses[vid]): vid
+ executor.submit(
+ fetch_transcript, vid, temp_dir, statuses[vid], token,
+ ): vid
for vid in video_ids
}
for future in as_completed(futures):
@@ -811,8 +860,16 @@ def fetch_transcripts_parallel(
return results
-def backfill_transcripts(items: List[Any], topic: str = "", depth: str = "default") -> None:
- """Second-pass transcript fetch for finalized items that lack one (#542)."""
+def backfill_transcripts(
+ items: List[Any], topic: str = "", depth: str = "default",
+ token: Optional[str] = None,
+) -> None:
+ """Second-pass transcript fetch for finalized items that lack one (#542).
+
+ ``token`` is the optional ScrapeCreators key, threaded to
+ ``fetch_transcripts_parallel`` so the SC fallback covers backfill survivors
+ that yt-dlp can't fetch. None preserves keyless behavior.
+ """
limit = TRANSCRIPT_LIMITS.get(depth, TRANSCRIPT_LIMITS["default"])
if limit <= 0 or not items or not is_ytdlp_installed():
return
@@ -838,6 +895,7 @@ def backfill_transcripts(items: List[Any], topic: str = "", depth: str = "defaul
transcripts = fetch_transcripts_parallel(
[it.item_id for it in attempts],
out_captions_disabled=captions_disabled,
+ token=token,
)
for it in attempts:
if it.item_id in captions_disabled:
@@ -871,6 +929,7 @@ def search_and_transcribe(
from_date: str,
to_date: str,
depth: str = "default",
+ token: Optional[str] = None,
) -> Dict[str, Any]:
"""Full YouTube search: find videos, then fetch transcripts for top results.
@@ -882,6 +941,8 @@ def search_and_transcribe(
from_date: Start date (YYYY-MM-DD)
to_date: End date (YYYY-MM-DD)
depth: 'quick', 'default', or 'deep'
+ token: Optional ScrapeCreators key for the per-video transcript
+ fallback (threaded to fetch_transcripts_parallel).
Returns:
Dict with 'items' list. Each item has a 'transcript_snippet' field.
@@ -923,6 +984,7 @@ def search_and_transcribe(
_log(f"Fetching transcripts for up to {attempt_count} videos (target: {transcript_limit}): {candidate_ids}")
transcripts = fetch_transcripts_parallel(
candidate_ids, out_captions_disabled=captions_disabled_ids,
+ token=token,
)
# Record fetch outcomes (captions-disabled videos can never succeed,
# so they don't count as failures) for the stale-yt-dlp nudge.
@@ -1236,6 +1298,30 @@ def _sc_youtube_search(keyword: str, token: str) -> List[Dict[str, Any]]:
return []
+def _sc_segment_text(seg: Any) -> str:
+ """Extract caption text from a ScrapeCreators transcript segment.
+
+ The transcript endpoint returns a list of segment dicts
+ (``{text, startMs, endMs}``); older/simpler shapes return plain strings.
+ Pull the ``text`` field for dicts so segment metadata is not stringified
+ into the output (``{'text': ...}`` garbage).
+ """
+ if isinstance(seg, dict):
+ # `or ""` (not a get default): a present-but-null `text` returns None,
+ # which would stringify to the literal "None" for silent/music segments.
+ return str(seg.get("text") or "")
+ return str(seg)
+
+
+def _warn_low_sc_credits(data: Dict[str, Any]) -> None:
+ """Surface a low-credit warning from a ScrapeCreators response, if present."""
+ credits = data.get("credits_remaining")
+ if isinstance(credits, (int, float)) and not isinstance(credits, bool):
+ if credits < _SC_LOW_CREDIT_THRESHOLD:
+ _log(f"ScrapeCreators credits low: {int(credits)} remaining "
+ f"(below {_SC_LOW_CREDIT_THRESHOLD})")
+
+
def _sc_fetch_transcript(video_id: str, token: str) -> Optional[str]:
"""Fetch transcript for a YouTube video via ScrapeCreators.
@@ -1259,12 +1345,14 @@ def _sc_fetch_transcript(video_id: str, token: str) -> Optional[str]:
_log(f"SC transcript error for {video_id}: {exc}")
return None
+ _warn_low_sc_credits(data)
+
transcript = data.get("transcript")
if not transcript:
return None
if isinstance(transcript, list):
- transcript = " ".join(str(s) for s in transcript)
+ transcript = " ".join(_sc_segment_text(seg) for seg in transcript).strip()
# Clean VTT formatting if present
transcript = _clean_vtt(transcript)
diff --git a/tests/test_youtube_backfill.py b/tests/test_youtube_backfill.py
index 72119b46..d2d709ab 100644
--- a/tests/test_youtube_backfill.py
+++ b/tests/test_youtube_backfill.py
@@ -106,7 +106,7 @@ class TestBackfillTranscripts(unittest.TestCase):
def test_marks_newly_discovered_captions_disabled(self):
"""A backfill attempt that reveals no caption tracks feeds quality_nudge."""
- def fake_fetch(video_ids, out_captions_disabled=None):
+ def fake_fetch(video_ids, out_captions_disabled=None, token=None):
if out_captions_disabled is not None:
out_captions_disabled.add("vidA")
return {"vidA": None, "vidB": TRANSCRIPT}
diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.py
index f4b136b5..8ef5e571 100644
--- a/tests/test_youtube_yt.py
+++ b/tests/test_youtube_yt.py
@@ -375,7 +375,7 @@ class TestFetchTranscriptFallback(unittest.TestCase):
mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp", return_value="WEBVTT\n\nfake") as yt_mock, \
mock.patch.object(youtube_yt, "_fetch_transcript_direct") as direct_mock:
result = youtube_yt.fetch_transcript("vid1", "/tmp/test")
- yt_mock.assert_called_once_with("vid1", "/tmp/test", status=None)
+ yt_mock.assert_called_once_with("vid1", "/tmp/test", status=None, fast_fail=False)
direct_mock.assert_not_called()
def test_uses_direct_when_ytdlp_missing(self):
@@ -518,7 +518,7 @@ class TestTranscriptCandidateSortKey(unittest.TestCase):
call_args_list = []
- def fake_fetch(video_ids, max_workers=5, out_captions_disabled=None):
+ def fake_fetch(video_ids, max_workers=5, out_captions_disabled=None, token=None):
call_args_list.extend(video_ids)
return {vid: "transcript" for vid in video_ids}
@@ -559,7 +559,7 @@ class TestSearchAndTranscribe(unittest.TestCase):
]
# fetch_transcripts_parallel returns None for music videos, text for talks
- def fake_parallel(video_ids, max_workers=5, out_captions_disabled=None):
+ def fake_parallel(video_ids, max_workers=5, out_captions_disabled=None, token=None):
result = {}
for vid in video_ids:
if vid.startswith("talk"):
@@ -629,7 +629,7 @@ class TestTranscriptFetchStats(unittest.TestCase):
def _run(self, items, fake_parallel=None):
if fake_parallel is None:
- def fake_parallel(video_ids, max_workers=5, out_captions_disabled=None):
+ def fake_parallel(video_ids, max_workers=5, out_captions_disabled=None, token=None):
return {vid: "A detailed transcript about the topic." for vid in video_ids}
with mock.patch.object(youtube_yt, "search_youtube", return_value={"items": items}), \
mock.patch.object(youtube_yt, "fetch_transcripts_parallel", side_effect=fake_parallel):
@@ -644,7 +644,7 @@ class TestTranscriptFetchStats(unittest.TestCase):
self._make_item("nocap1", 1_000, "2026-03-10"),
]
- def fake_parallel(video_ids, max_workers=5, out_captions_disabled=None):
+ def fake_parallel(video_ids, max_workers=5, out_captions_disabled=None, token=None):
result = {}
for vid in video_ids:
if vid.startswith("nocap"):
@@ -860,5 +860,213 @@ class TestTranscriptSSHRouting(unittest.TestCase):
self.assertIn("hello there friends", result)
+class TestScTranscriptFallback(unittest.TestCase):
+ """ScrapeCreators fallback wiring in fetch_transcript (U1/U2)."""
+
+ def _ytdlp_hard_fail(self, reason="HTTP Error 429: Too Many Requests"):
+ def _fake(video_id, temp_dir, status=None, fast_fail=False):
+ if status is not None:
+ status["ytdlp_error"] = reason
+ return None
+ return _fake
+
+ def test_sc_fallback_fires_on_ytdlp_hard_failure_with_token(self):
+ """A yt-dlp hard failure (429) with a key falls back to ScrapeCreators."""
+ status = {}
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp",
+ side_effect=self._ytdlp_hard_fail()), \
+ mock.patch.object(youtube_yt, "_fetch_transcript_direct") as direct_mock, \
+ mock.patch.object(youtube_yt, "_sc_fetch_transcript",
+ return_value="scrapecreators transcript text") as sc_mock:
+ result = youtube_yt.fetch_transcript("vidA", "/tmp/x", status=status, token="key123")
+ sc_mock.assert_called_once_with("vidA", "key123")
+ direct_mock.assert_not_called() # hard error skips the (also-blocked) direct path
+ self.assertEqual(result, "scrapecreators transcript text")
+
+ def test_sc_not_called_when_ytdlp_succeeds(self):
+ """No credit is spent when yt-dlp returns a transcript."""
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp",
+ return_value="WEBVTT\n\nreal captions here"), \
+ mock.patch.object(youtube_yt, "_sc_fetch_transcript") as sc_mock:
+ result = youtube_yt.fetch_transcript("vidB", "/tmp/x", status={}, token="key123")
+ sc_mock.assert_not_called()
+ self.assertIn("real captions", result)
+
+ def test_sc_not_called_without_token(self):
+ """Keyless behavior unchanged: no token means no ScrapeCreators."""
+ status = {}
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp",
+ side_effect=self._ytdlp_hard_fail()), \
+ mock.patch.object(youtube_yt, "_sc_fetch_transcript") as sc_mock:
+ result = youtube_yt.fetch_transcript("vidC", "/tmp/x", status=status, token=None)
+ sc_mock.assert_not_called()
+ self.assertIsNone(result)
+
+ def test_sc_skipped_when_proven_captionless(self):
+ """A video proven to have no caption track must not spend a credit."""
+ def _ytdlp_no_captions(video_id, temp_dir, status=None, fast_fail=False):
+ return None # exit-0 no captions: returns None, no ytdlp_error
+
+ def _direct_no_tracks(video_id, status=None):
+ if status is not None:
+ status["no_caption_tracks"] = True
+ return None
+
+ status = {}
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp", side_effect=_ytdlp_no_captions), \
+ mock.patch.object(youtube_yt, "_fetch_transcript_direct", side_effect=_direct_no_tracks), \
+ mock.patch.object(youtube_yt, "_sc_fetch_transcript") as sc_mock:
+ result = youtube_yt.fetch_transcript("vidD", "/tmp/x", status=status, token="key123")
+ sc_mock.assert_not_called()
+ self.assertIsNone(result)
+
+ def test_should_try_sc_transcript_predicate(self):
+ self.assertTrue(youtube_yt._should_try_sc_transcript(None))
+ self.assertTrue(youtube_yt._should_try_sc_transcript({}))
+ self.assertTrue(youtube_yt._should_try_sc_transcript({"ytdlp_error": "429"}))
+ self.assertFalse(youtube_yt._should_try_sc_transcript({"no_caption_tracks": True}))
+
+ def test_token_threads_through_parallel(self):
+ """fetch_transcripts_parallel passes the token to every fetch_transcript."""
+ captured = {}
+
+ def _fake_fetch_transcript(video_id, temp_dir, status=None, token=None):
+ captured[video_id] = token
+ return None
+
+ with mock.patch.object(youtube_yt, "fetch_transcript", side_effect=_fake_fetch_transcript):
+ youtube_yt.fetch_transcripts_parallel(["v1", "v2"], token="tok")
+ self.assertEqual(captured, {"v1": "tok", "v2": "tok"})
+
+
+class TestYtdlpFastFail(unittest.TestCase):
+ """Fail-fast behavior when a ScrapeCreators key is present (U3)."""
+
+ def _transient_fail(self):
+ from lib.subproc import SubprocResult
+ return SubprocResult(
+ returncode=1, stdout="",
+ stderr="ERROR: HTTP Error 429: Too Many Requests",
+ )
+
+ def test_fast_fail_single_attempt_short_timeout(self):
+ """token present -> one attempt, shortened timeout, no retry sleeps."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ status = {}
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(youtube_yt.subproc, "run_with_timeout",
+ return_value=self._transient_fail()) as run_mock, \
+ mock.patch.object(youtube_yt.time, "sleep") as sleep_mock:
+ vtt = youtube_yt._fetch_transcript_ytdlp("vidF", temp_dir, status, fast_fail=True)
+ self.assertIsNone(vtt)
+ self.assertEqual(run_mock.call_count, 1) # no retries
+ self.assertEqual(run_mock.call_args.kwargs.get("timeout"), 12)
+ sleep_mock.assert_not_called()
+ self.assertIn("ytdlp_error", status)
+
+ def test_no_token_retries_with_full_timeout(self):
+ """token absent -> full retry budget and 30s timeout, unchanged."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ status = {}
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(youtube_yt.subproc, "run_with_timeout",
+ return_value=self._transient_fail()) as run_mock, \
+ mock.patch.object(youtube_yt.time, "sleep"):
+ vtt = youtube_yt._fetch_transcript_ytdlp("vidG", temp_dir, status, fast_fail=False)
+ self.assertIsNone(vtt)
+ self.assertEqual(run_mock.call_count, youtube_yt._TRANSCRIPT_MAX_RETRIES + 1)
+ self.assertEqual(run_mock.call_args.kwargs.get("timeout"), 30)
+
+
+class TestScTranscriptParsing(unittest.TestCase):
+ """ScrapeCreators transcript parse + credits warning (U4)."""
+
+ def test_list_of_dict_segments_parsed_to_text(self):
+ payload = {
+ "transcript": [
+ {"text": "hello there", "startMs": 0, "endMs": 1000},
+ {"text": "general kenobi", "startMs": 1000, "endMs": 2000},
+ ],
+ "credits_remaining": 9999,
+ }
+ with mock.patch.object(youtube_yt.http, "get", return_value=payload):
+ result = youtube_yt._sc_fetch_transcript("vidH", "key")
+ self.assertIsNotNone(result)
+ self.assertIn("hello there", result)
+ self.assertIn("general kenobi", result)
+ self.assertNotIn("startMs", result)
+ self.assertNotIn("{'text'", result)
+
+ def test_null_text_segment_does_not_emit_none(self):
+ """A present-but-null text field (silent/music segment) must not become "None"."""
+ payload = {
+ "transcript": [
+ {"text": "real words here", "startMs": 0},
+ {"text": None, "startMs": 1000},
+ {"text": "more real words", "startMs": 2000},
+ ],
+ "credits_remaining": 9999,
+ }
+ with mock.patch.object(youtube_yt.http, "get", return_value=payload):
+ result = youtube_yt._sc_fetch_transcript("vidNull", "key")
+ self.assertIsNotNone(result)
+ self.assertNotIn("None", result)
+ self.assertIn("real words here", result)
+ self.assertIn("more real words", result)
+
+ def test_plain_string_transcript_preserved(self):
+ payload = {"transcript": "just a plain transcript string here", "credits_remaining": 9999}
+ with mock.patch.object(youtube_yt.http, "get", return_value=payload):
+ result = youtube_yt._sc_fetch_transcript("vidI", "key")
+ self.assertIn("just a plain transcript", result)
+
+ def test_low_credits_emits_warning(self):
+ payload = {"transcript": "some transcript text", "credits_remaining": 5}
+ logs = []
+ with mock.patch.object(youtube_yt.http, "get", return_value=payload), \
+ mock.patch.object(youtube_yt, "_log", side_effect=lambda m: logs.append(m)):
+ youtube_yt._sc_fetch_transcript("vidJ", "key")
+ self.assertTrue(any("credits low" in m.lower() for m in logs))
+
+ def test_healthy_credits_no_warning(self):
+ payload = {"transcript": "some transcript text", "credits_remaining": 9999}
+ logs = []
+ with mock.patch.object(youtube_yt.http, "get", return_value=payload), \
+ mock.patch.object(youtube_yt, "_log", side_effect=lambda m: logs.append(m)):
+ youtube_yt._sc_fetch_transcript("vidK", "key")
+ self.assertFalse(any("credits low" in m.lower() for m in logs))
+
+
+class TestYoutubeCommentsGating(unittest.TestCase):
+ """YouTube comments default-on gating (U5)."""
+
+ def test_default_on_with_key_and_no_include_sources(self):
+ from lib import env
+ self.assertTrue(env.is_youtube_comments_available({"SCRAPECREATORS_API_KEY": "k"}))
+
+ def test_unavailable_without_key(self):
+ from lib import env
+ self.assertFalse(env.is_youtube_comments_available({}))
+
+ def test_exclude_sources_suppresses(self):
+ from lib import env
+ cfg = {"SCRAPECREATORS_API_KEY": "k", "EXCLUDE_SOURCES": "youtube_comments"}
+ self.assertFalse(env.is_youtube_comments_available(cfg))
+
+ def test_tiktok_comments_still_opt_in(self):
+ """Regression: TikTok comments must STILL require INCLUDE_SOURCES."""
+ from lib import env
+ self.assertFalse(
+ env.is_tiktok_comments_available({"SCRAPECREATORS_API_KEY": "k"})
+ )
+ self.assertTrue(env.is_tiktok_comments_available(
+ {"SCRAPECREATORS_API_KEY": "k", "INCLUDE_SOURCES": "tiktok_comments"}
+ ))
+
+
if __name__ == "__main__":
unittest.main()