diff --git a/clip_selection.py b/clip_selection.py index 8613c80..03b8c87 100644 --- a/clip_selection.py +++ b/clip_selection.py @@ -26,6 +26,47 @@ def lookup_model_prices(model_name): return MODEL_PRICES[best_key] if best_key else None +def clip_count_targets(n_windows): + """How many clips to ask the detail pass for, given the shortlist size. + + Measured on prod 3-ago-2026: 408 of 429 jobs (95%) delivered 3 clips or + fewer, the mode being ONE, while the prompt was free to return one per + shortlisted window. Users who received 1-3 clips came back a second day + 0.4% of the time; those who received 4-9 came back 16.1% — so the clip + count, not the clip quality, is what the retention curve hangs on. + + The old prompt biased hard the other way ("prefer one great clip per + candidate window") and handed the model two unbounded licences to drop + clips (the 2-second rule and STANDS ALONE both end in "or skip it"), with + no floor to stop it collapsing to a single clip. This puts a floor and a + realistic ceiling on it instead. + + ``CLIP_TARGET_MIN`` / ``CLIP_TARGET_MAX`` override both for A/B runs + without a deploy (the reframe-testing harness drives them). + """ + import os + + n = max(1, int(n_windows or 1)) + # Floor grows with the material: 3 windows -> 3, 5 -> 4, 10+ -> 6. + low = max(2, min(6, n // 2 + 2)) + # Ceiling allows a rich window to yield more than one without inviting padding. + high = min(12, max(4, n * 2)) + low = min(low, high) + + def _override(name, current): + raw = os.environ.get(name) + if not raw: + return current + try: + return max(1, int(raw)) + except ValueError: + return current + + low = _override("CLIP_TARGET_MIN", low) + high = _override("CLIP_TARGET_MAX", high) + return low, max(low, high) + + def compact_words(words, precision=2): """Round word timestamps for prompts — full float precision wastes tokens.""" return [ diff --git a/gemini_worker.py b/gemini_worker.py index 972cc97..7bf688e 100644 --- a/gemini_worker.py +++ b/gemini_worker.py @@ -9,7 +9,7 @@ from google import genai from google.genai import types as genai_types from pydantic import BaseModel -from clip_selection import lookup_model_prices +from clip_selection import clip_count_targets, lookup_model_prices load_dotenv() @@ -254,10 +254,17 @@ CLIP RULES: A brilliant moment that needs the previous five minutes is not a clip. Fix this by moving the START earlier, never by cutting the ending short: a clip that loses its payoff to gain context has traded down. -- Prefer one great clip per candidate window. Maximum 2 clips per window only if clearly justified. +- HOW MANY: return {min_clips} to {max_clips} clips. Work through EVERY candidate + window — they were already scored as the best moments in the video, so a window + that yields nothing should be the exception, not the norm. Two or three clips + from one window are fine when they are genuinely different moments. The rules + above let you skip a weak clip; they are not a licence to return one clip and + stop. Only fall short of {min_clips} when the material truly does not hold + them, and never pad with a clip you would not publish yourself. - DIVERSITY: never return two clips that make the same point, tell the same story, or land the same joke — even across different windows. Pick the - stronger one and drop the other. + stronger one and drop the other. Two clips on the same broad topic are fine + as long as each lands its own moment. HOOK PLAYBOOK — pick the strongest fitting pattern for `viral_hook_text` (max 10 words): - Open question: "Why does everyone get this wrong?" @@ -498,11 +505,17 @@ def main() -> int: language = str(payload.get("language") or "unknown") template = SCORE_PROMPT_TEMPLATE if args.mode == "score" else DETAIL_PROMPT_TEMPLATE - prompt = template.format( - video_duration=payload["video_duration"], - language=language, - windows_json=json.dumps(payload["windows"], ensure_ascii=False), - ) + fmt = { + "video_duration": payload["video_duration"], + "language": language, + "windows_json": json.dumps(payload["windows"], ensure_ascii=False), + } + if args.mode != "score": + # Score mode receives every window, not a shortlist, so a count target + # derived from it would be meaningless — and the score template has no + # placeholder for one anyway. + fmt["min_clips"], fmt["max_clips"] = clip_count_targets(len(payload.get("windows") or [])) + prompt = template.format(**fmt) _log(f"🤖 Gemini worker request: mode={args.mode} strategy={args.strategy} model={model_name} items={len(payload.get('windows', []))}") response = client.models.generate_content( diff --git a/main.py b/main.py index 4ea462e..947ee60 100644 --- a/main.py +++ b/main.py @@ -23,7 +23,7 @@ from google.genai import types as genai_types import gemini_worker import layout_picker -from clip_selection import build_transcript_windows, snap_clip_to_words +from clip_selection import build_transcript_windows, clip_count_targets, snap_clip_to_words from ffmpeg_utils import (video_encode_args, audio_encode_args, QUALITY, QUALITY_FAST, METADATA_SCRUB) from dotenv import load_dotenv @@ -1274,8 +1274,10 @@ def get_viral_clips(transcript_result, video_duration): # --- Pass 2: detailed clip extraction on the shortlist --- payload = [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in shortlist] + min_clips, max_clips = clip_count_targets(len(shortlist)) prompt = gemini_worker.DETAIL_PROMPT_TEMPLATE.format( video_duration=video_duration, language=language, + min_clips=min_clips, max_clips=max_clips, windows_json=json.dumps(payload, ensure_ascii=False)) detail, cost = _run_gemini_stage(client, model_name, prompt, gemini_worker.DetailResponse) if cost: diff --git a/tests/test_clip_selection.py b/tests/test_clip_selection.py index 93716b6..c15d5b0 100644 --- a/tests/test_clip_selection.py +++ b/tests/test_clip_selection.py @@ -1,6 +1,11 @@ """Tests for the pure clip-selection helpers (windows, snapping, pricing).""" +import re + +import pytest + from clip_selection import ( build_transcript_windows, + clip_count_targets, snap_clip_to_words, compact_words, lookup_model_prices, @@ -98,3 +103,62 @@ class TestCompactWords: def test_rounds_timestamps(self): words = [{"w": " hi", "s": 17.240000000000002, "e": 17.899999999999999}] assert compact_words(words) == [{"w": " hi", "s": 17.24, "e": 17.9}] + + +class TestClipCountTargets: + """The floor is the whole point: prod was delivering a single clip on the + mode, and users who got 1-3 came back 0.4% of the time against 16% for 4-9. + """ + + def test_floor_clears_the_dead_zone_once_there_is_material(self): + # 4+ shortlisted windows must not be allowed to return the 1-3 band. + for n in (4, 5, 6, 8, 10): + low, high = clip_count_targets(n) + assert low >= 4, f"{n} windows asked for only {low}" + assert high >= low + + def test_tiny_shortlists_stay_modest(self): + assert clip_count_targets(1)[0] <= 2 + assert clip_count_targets(2)[0] <= 3 + + def test_ceiling_is_capped_so_long_videos_do_not_explode(self): + assert clip_count_targets(40) == clip_count_targets(12) + assert clip_count_targets(40)[1] <= 12 + + def test_low_never_exceeds_high(self): + for n in range(1, 40): + low, high = clip_count_targets(n) + assert low <= high + + def test_degenerate_input_does_not_crash(self): + assert clip_count_targets(0)[0] >= 1 + assert clip_count_targets(None)[0] >= 1 + + def test_env_overrides_for_ab_runs(self, monkeypatch): + monkeypatch.setenv("CLIP_TARGET_MIN", "1") + monkeypatch.setenv("CLIP_TARGET_MAX", "2") + assert clip_count_targets(5) == (1, 2) + + def test_garbage_env_falls_back_to_computed(self, monkeypatch): + baseline = clip_count_targets(5) + monkeypatch.setenv("CLIP_TARGET_MIN", "not-a-number") + assert clip_count_targets(5) == baseline + + def test_override_min_above_max_still_orders(self, monkeypatch): + monkeypatch.setenv("CLIP_TARGET_MIN", "9") + monkeypatch.setenv("CLIP_TARGET_MAX", "3") + low, high = clip_count_targets(5) + assert low <= high + + +class TestDetailPromptCarriesTheCount: + def test_template_formats_with_the_targets(self): + gw = pytest.importorskip("gemini_worker") + low, high = clip_count_targets(5) + prompt = gw.DETAIL_PROMPT_TEMPLATE.format( + video_duration=300, language="es", min_clips=low, max_clips=high, + windows_json="[]") + assert f"return {low} to {high} clips" in prompt + # 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) == []