Skip to content

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

fix(youtube): prioritise recent videos for transcript budget (#531) (#567)

SAI MOHANEESHa3445c0914f5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2ff7e3cb..16068248 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- YouTube transcript budget prioritises recent videos (by a combination of views and recency) instead of views alone, preventing transcript slots from being consumed by old high-view-count videos that would be discarded by strict_recent freshness pruning ([#531](https://github.com/mvanhorn/last30days-skill/issues/531))
- YouTube items with successfully extracted transcripts are no longer pruned by title-only relevance scoring; the transcript content proves substantive topical coverage even when the video title has low lexical overlap with the query ([#468](https://github.com/mvanhorn/last30days-skill/issues/468))
- First-run setup wizard in SKILL.md now references the existing Python setup wizard (`last30days.py setup`) instead of the missing `nux-wizard.md` file, so first-run setup actually runs on new installs. ([#574](https://github.com/mvanhorn/last30days-skill/issues/574))
- Entity-grounding rerank demotion now keys on the head token of the primary entity instead of requiring the full multi-word phrase as a contiguous substring. A high-engagement on-entity item (e.g. a 323-pt HN thread titled "Stripe is friendly to 'friendly fraud'") is no longer demoted to score 0 on a `Stripe payments` query just because it lacks the trailing search-hint word. The intended demotion still fires for items that never name the brand at all. The keyless Reddit comment-enrichment slot selection (`_slot_priority`), which mirrors this signal, was updated to the same head-token grounding so the two paths stay consistent.
diff --git a/skills/last30days/scripts/lib/youtube_yt.py b/skills/last30days/scripts/lib/youtube_yt.py
index 3e46685f..5e7380c2 100644
--- a/skills/last30days/scripts/lib/youtube_yt.py
+++ b/skills/last30days/scripts/lib/youtube_yt.py
@@ -36,7 +36,7 @@ TRANSCRIPT_LIMITS = {
# Max words to keep from each transcript
TRANSCRIPT_MAX_WORDS = 5000
-from . import http, log, subproc
+from . import dates, http, log, subproc
from .relevance import token_overlap_relevance as _compute_relevance
@@ -642,6 +642,18 @@ def fetch_transcripts_parallel(
return results
+def _transcript_candidate_sort_key(item: dict) -> tuple:
+ """Sort key for transcript candidate selection.
+
+ Combines views with recency so that recent videos (which survive
+ strict_recent freshness pruning) are prioritised over old high-view
+ videos whose transcripts would be discarded downstream.
+ """
+ views = item.get("engagement", {}).get("views", 0) or 0
+ recency = dates.recency_score(item.get("date", ""))
+ return (views, recency)
+
+
def search_and_transcribe(
topic: str,
from_date: str,
@@ -680,7 +692,10 @@ def search_and_transcribe(
if not items:
return search_result
- # Step 2: Fetch transcripts for top videos by views.
+ # Step 2: Fetch transcripts for top videos.
+ # Sort candidates by a combination of views and recency so that recent
+ # videos (which survive strict_recent pruning) are not starved of
+ # transcript budget by older high-view-count outliers.
# Try more candidates than the limit because some videos (music videos,
# short clips) lack captions. Attempt up to 3x the limit so we have a
# good chance of reaching the target number of successful transcripts.
@@ -689,7 +704,10 @@ def search_and_transcribe(
captions_disabled_ids: Set[str] = set()
if transcript_limit > 0:
attempt_count = min(len(items), transcript_limit * 3)
- candidate_ids = [item["video_id"] for item in items[:attempt_count]]
+ transcript_candidates = sorted(
+ items, key=_transcript_candidate_sort_key, reverse=True,
+ )
+ candidate_ids = [item["video_id"] for item in transcript_candidates[:attempt_count]]
_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,
diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.py
index 543b4cf1..1414e10f 100644
--- a/tests/test_youtube_yt.py
+++ b/tests/test_youtube_yt.py
@@ -5,6 +5,7 @@ import os
import tempfile
import unittest
import urllib.error
+from datetime import datetime, timedelta, timezone
from unittest import mock
from lib import youtube_yt
@@ -332,6 +333,83 @@ class TestInferQueryIntent(unittest.TestCase):
self.assertEqual(youtube_yt._infer_query_intent("Kanye West"), "breaking_news")
+class TestTranscriptCandidateSortKey(unittest.TestCase):
+ """Tests for _transcript_candidate_sort_key recency-boosted ordering."""
+
+ @staticmethod
+ def _d(days_ago: int) -> str:
+ return (datetime.now(timezone.utc) - timedelta(days=days_ago)).strftime("%Y-%m-%d")
+
+ def _make_item(self, video_id, views, date_str):
+ return {
+ "video_id": video_id,
+ "title": f"Video {video_id}",
+ "url": f"https://www.youtube.com/watch?v={video_id}",
+ "channel_name": "TestChannel",
+ "date": date_str,
+ "engagement": {"views": views, "likes": 10, "comments": 5},
+ "relevance": 0.8,
+ "why_relevant": "test",
+ "description": "test desc",
+ "duration": 600,
+ }
+
+ def test_recency_breaks_views_tie(self):
+ """When views are equal, the more recent video gets a higher sort key."""
+ new = self._make_item("new", 100_000, self._d(1))
+ old = self._make_item("old", 100_000, self._d(13))
+ self.assertGreater(
+ youtube_yt._transcript_candidate_sort_key(new),
+ youtube_yt._transcript_candidate_sort_key(old),
+ )
+
+ def test_old_high_view_can_still_qualify_for_transcript(self):
+ """An old video with very high views still gets a transcript slot;
+ recency is a tiebreaker, not a gate."""
+ old_high = self._make_item("old_high", 10_000_000, self._d(45))
+ recent_low = self._make_item("recent_low", 100, self._d(1))
+ self.assertGreater(
+ youtube_yt._transcript_candidate_sort_key(old_high),
+ youtube_yt._transcript_candidate_sort_key(recent_low),
+ )
+
+ def test_no_date_falls_to_back(self):
+ """An item with no date gets recency 0, sorting behind dated items."""
+ no_date = self._make_item("no_date", 50_000, "")
+ dated = self._make_item("dated", 50_000, self._d(5))
+ self.assertGreater(
+ youtube_yt._transcript_candidate_sort_key(dated),
+ youtube_yt._transcript_candidate_sort_key(no_date),
+ )
+
+ def test_transcript_candidates_pick_recent_over_old_same_views(self):
+ """search_and_transcribe selects candidates by (views, recency),
+ so a recent video is tried before an equal-view older video."""
+ items = [
+ self._make_item("old", 100_000, self._d(13)),
+ self._make_item("recent", 100_000, self._d(1)),
+ self._make_item("mid", 50_000, self._d(5)),
+ ]
+
+ def fake_search(*args, **kwargs):
+ return {"items": items}
+
+ call_args_list = []
+
+ def fake_fetch(video_ids, max_workers=5, out_captions_disabled=None):
+ call_args_list.extend(video_ids)
+ return {vid: "transcript" for vid in video_ids}
+
+ with mock.patch.object(youtube_yt, "search_youtube", side_effect=fake_search), \
+ mock.patch.object(youtube_yt, "fetch_transcripts_parallel", side_effect=fake_fetch):
+ youtube_yt.search_and_transcribe("test", self._d(14), self._d(0), depth="default")
+
+ # transcript_limit=2, attempt_count=4 (limited to 3 items)
+ # Sorted by (views, recency): recent(100k) > old(100k) > mid(50k)
+ self.assertEqual(call_args_list[:2], ["recent", "old"],
+ "Recent video should be tried before equal-view older video")
+
+
class TestSearchAndTranscribe(unittest.TestCase):
"""Tests for search_and_transcribe() end-to-end flow."""