From 4a137005ca40837ef3346e4e1a47202ca85556ba Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Sat, 29 Aug 2026 01:42:45 +0200 Subject: [PATCH] fix(selection): trim the detail pass by score, not by position MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The detail pass returns its clips in transcript order, batch after batch, and the overflow was cut with shorts[:max_clips] — which keeps the EARLIEST clips and drops the tail. On a 9m19s walkthrough, three runs of the same source put every surviving clip inside the first 2m40s, 4m39s and 8m55s respectively; the demo, the MCP walkthrough and the close were simply the part of the list that fell off the end. The failure scales the wrong way, too: the more clips the model proposes, the more of the video disappears (output tokens 2067 -> 8m55s of coverage, 3407 -> 2m40s). It also undoes the windowing. get_viral_clips builds scoring windows precisely because "a single call over the whole transcript clusters picks near the start", and a positional slice puts that clustering straight back. Pass 1 already sorts by score before its own cut; pass 2 just never did. trim_to_best ranks by predicted_score, which the detail prompt has always asked for and nothing here was reading, and returns the survivors in transcript order so clip numbering still runs front to back. Claude-Session: https://claude.ai/code/session_01KeQYCfUX2E9Q2fDgZMKEaJ --- clip_selection.py | 35 ++++++++++++++++++++++++ main.py | 11 ++++++-- tests/test_clip_selection.py | 52 ++++++++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 2 deletions(-) diff --git a/clip_selection.py b/clip_selection.py index b0c4650..14d9737 100644 --- a/clip_selection.py +++ b/clip_selection.py @@ -67,6 +67,41 @@ def clip_count_targets(n_windows): return low, max(low, high) +def trim_to_best(shorts, max_clips): + """Cut an over-long detail-pass result down to ``max_clips`` BY SCORE. + + The detail pass hands its clips back in transcript order, batch after + batch, so slicing the list keeps the EARLIEST clips rather than the best + ones. On a 9-minute walkthrough that quietly threw away everything past + minute three: the model proposed clips across the whole video, and the + ones covering the demo, the MCP walkthrough and the close were the tail + that got dropped. Worse, the failure scales the wrong way — the more + generous the model is, the more of the video disappears. + + That sabotages the windowing: get_viral_clips builds scoring windows + precisely because "a single call over the whole transcript clusters picks + near the start", and a positional slice puts the clustering right back. + + Ranking is by ``predicted_score`` (the detail prompt already asks for it, + and nothing else was reading it here). Ties keep transcript order, and the + survivors come back in transcript order too, so clip numbering still runs + front to back the way every caller downstream expects. + """ + max_clips = max(1, int(max_clips or 1)) + if len(shorts) <= max_clips: + return list(shorts) + + def score(item): + try: + return float(item[1].get("predicted_score") or 0) + except (TypeError, ValueError, AttributeError): + return 0.0 + + indexed = list(enumerate(shorts)) + best = sorted(indexed, key=score, reverse=True)[:max_clips] + return [item for _, item in sorted(best, key=lambda pair: pair[0])] + + def clip_duration_bounds(): """The clip length band (seconds) the selection prompts and word-snapping enforce. ``CLIP_MIN_SECONDS`` / ``CLIP_MAX_SECONDS`` override the classic diff --git a/main.py b/main.py index a8a4182..091d5fe 100644 --- a/main.py +++ b/main.py @@ -24,7 +24,8 @@ from google.genai import types as genai_types import gemini_worker import layout_picker from clip_selection import (build_transcript_windows, clip_count_targets, - clip_duration_bounds, snap_clip_to_words) + clip_duration_bounds, snap_clip_to_words, + trim_to_best) from ffmpeg_utils import (video_encode_args, audio_encode_args, QUALITY, QUALITY_FAST, METADATA_SCRUB) from dotenv import load_dotenv @@ -1586,7 +1587,13 @@ def get_viral_clips(transcript_result, video_duration): shorts = _run_stage_split(client, model_name, shortlist, _detail_prompt, gemini_worker.DetailResponse, "shorts", costs, "detail") if len(shorts) > max_clips: - shorts = shorts[:max_clips] + # By score, never by position: the results arrive in transcript + # order, so slicing kept the earliest clips and silently dropped + # the back half of the video. See trim_to_best. + dropped = len(shorts) - max_clips + shorts = trim_to_best(shorts, max_clips) + print(f" Kept the {max_clips} best-scoring clip(s) of " + f"{max_clips + dropped}.") # Snap each proposed clip onto real word boundaries (+ a bit of silence). for s in shorts: ns, ne = snap_clip_to_words(s.get("start", 0), s.get("end", 0), words, video_duration, diff --git a/tests/test_clip_selection.py b/tests/test_clip_selection.py index 9cf0d67..77e8918 100644 --- a/tests/test_clip_selection.py +++ b/tests/test_clip_selection.py @@ -9,6 +9,7 @@ from clip_selection import ( snap_clip_to_words, compact_words, lookup_model_prices, + trim_to_best, ) @@ -163,3 +164,54 @@ class TestDetailPromptCarriesTheCount: # The JSON schema example legitimately keeps braces (they are {{ }} in # the template), so assert on unsubstituted placeholders specifically. assert re.findall(r"\{[a-z_]+\}", prompt) == [] + + +class TestTrimToBest: + """The detail pass returns clips in transcript order. Slicing that list + kept the earliest ones and dropped the back of the video — measured on a + 9m19s walkthrough whose clips all landed inside the first 2m40s.""" + + @staticmethod + def _clip(start, score): + return {"start": start, "end": start + 20, "predicted_score": score} + + def test_keeps_the_best_scoring_not_the_earliest(self): + shorts = [self._clip(0, 60), self._clip(30, 55), + self._clip(300, 90), self._clip(400, 85)] + kept = trim_to_best(shorts, 2) + assert [c["start"] for c in kept] == [300, 400] + + def test_survivors_come_back_in_transcript_order(self): + shorts = [self._clip(0, 99), self._clip(100, 10), + self._clip(200, 80), self._clip(300, 90)] + kept = trim_to_best(shorts, 3) + assert [c["start"] for c in kept] == [0, 200, 300] + + def test_a_short_list_is_untouched(self): + shorts = [self._clip(0, 10), self._clip(50, 20)] + assert trim_to_best(shorts, 5) == shorts + assert trim_to_best(shorts, 2) == shorts + + def test_the_whole_video_stays_reachable(self): + # The regression in one line: 16 clips spread over 9 minutes, trimmed + # to 8. A positional slice ends at 3:30; by score the tail survives. + shorts = [self._clip(i * 35, 50 + (i % 4) * 10) for i in range(16)] + kept = trim_to_best(shorts, 8) + assert max(c["start"] for c in kept) > 8 * 35 + + def test_ties_keep_transcript_order(self): + shorts = [self._clip(0, 70), self._clip(100, 70), self._clip(200, 70)] + assert [c["start"] for c in trim_to_best(shorts, 2)] == [0, 100] + + def test_a_missing_or_bad_score_does_not_raise(self): + shorts = [{"start": 0, "end": 20}, + {"start": 100, "end": 120, "predicted_score": None}, + {"start": 200, "end": 220, "predicted_score": "x"}, + self._clip(300, 40)] + kept = trim_to_best(shorts, 2) + assert len(kept) == 2 + assert kept[-1]["start"] == 300 # the only real score survives + + def test_max_clips_is_never_below_one(self): + shorts = [self._clip(0, 10), self._clip(50, 20)] + assert len(trim_to_best(shorts, 0)) == 1