fix(selection): score every window and enforce the clip floor
A 9:10 source delivered 3 clips in prod where the pipeline had asked itself for 6-12. Two independent leaks, both in the chain that derives the clip count. The scoring pass SELECTED instead of ranking: "choose up to 3 windows from this batch" put the shortlist ceiling at 3 * n_batches rather than shortlist_target, so 9 windows batched 8 + 1 shortlisted 4 of a target of 8, and clip_count_targets then asked the detail pass for 4-8 clips instead of 6-12. Every source under ~30 min was starved the same way, which is the mechanism behind "95% of jobs deliver 3 clips or fewer" — the clip count D2 retention hangs on (0.4% for 1-3 clips, 16.1% for 4-9). It also discarded the ranking it was computing: a batch holding five great moments could still contribute only three, while a batch of filler contributed its own three. The prompt now scores every window it is given and the shortlist is the global top N. Batches are near-equal instead of "full ones plus the remainder": a trailing batch of one window came back with that window whatever its score, because a cap of 3 cannot filter a batch of 1, so the tail of the video entered the shortlist by arithmetic. Same call count as before. And the floor was only a sentence in the detail prompt, with nothing in code checking it, so a pass that returned half shipped half. When it comes back under min_clips the shortlist windows that produced nothing get one more call for the difference; an empty answer is accepted, because padding is worse than a short list. Measured on that source, same transcript, three runs: shortlist 4 -> 8, clips 4 -> 6, cost unchanged (~$0.005, 3 calls).
This commit is contained in:
parent
d4480c6257
commit
4cc2fe32e0
7 changed files with 318 additions and 20 deletions
37
CLAUDE.md
37
CLAUDE.md
|
|
@ -157,6 +157,43 @@ otherwise process 45 minutes on a 20-minute reservation. `/api/status` and
|
||||||
the process response carry `partial`, and the results view says which part
|
the process response carry `partial`, and the results view says which part
|
||||||
of the video the clips came from, with the upsell for the rest.
|
of the video the clips came from, with the upsell for the rest.
|
||||||
|
|
||||||
|
### How many clips a job returns (`clip_selection.py`)
|
||||||
|
|
||||||
|
The count is not a setting, it is derived, and every stage of the derivation
|
||||||
|
used to leak. `get_viral_clips` builds ~90s scoring windows over the
|
||||||
|
transcript, scores them in batches, shortlists the best `shortlist_target`
|
||||||
|
(`min(10, duration//90 + 2)`, floor 3) and asks the detail pass for
|
||||||
|
`clip_count_targets(len(shortlist))` clips — a floor that matters because
|
||||||
|
users who got 1-3 clips came back a second day 0.4% of the time against
|
||||||
|
16.1% for 4-9.
|
||||||
|
|
||||||
|
Two things broke that chain, both found on a 9:10 source on 22-sep-2026 that
|
||||||
|
delivered 3 clips in prod:
|
||||||
|
|
||||||
|
- **The scoring pass selected instead of ranking.** Its prompt said "choose up
|
||||||
|
to 3 windows from this batch", so the shortlist ceiling was
|
||||||
|
`3 * n_batches`, not the target: 9 windows batched 8 + 1 gave 3 + 1 = 4
|
||||||
|
against a target of 8, and `clip_count_targets` then asked for 4-8 clips
|
||||||
|
instead of 6-12. Every source under ~30 min was starved this way — this is
|
||||||
|
the mechanism behind "95% of jobs deliver 3 clips or fewer". It also threw
|
||||||
|
away the ranking it was computing, since a batch of five great moments
|
||||||
|
could still only contribute three. The prompt now scores **every** window
|
||||||
|
and the shortlist is the global top N. Batches are near-equal
|
||||||
|
(`score_batches`) for the same reason the cap is gone: a trailing batch of
|
||||||
|
one window returned that window whatever its score, so the tail of the
|
||||||
|
video entered the shortlist by arithmetic.
|
||||||
|
- **The clip floor was only a sentence in the prompt.** Nothing in code
|
||||||
|
checked it, so a detail pass that returned half was shipped as-is. When it
|
||||||
|
comes back under `min_clips`, the shortlist windows that produced nothing
|
||||||
|
get one more call for the difference. An empty answer is accepted: that is
|
||||||
|
material that genuinely holds no more, and padding is worse than a short
|
||||||
|
list.
|
||||||
|
|
||||||
|
Measured on that source, same transcript, three runs: shortlist 4 → 8 and
|
||||||
|
4 clips → 6, at the same cost (~$0.005, 3 calls). `target_clips` on
|
||||||
|
`/api/process` (dashboard: advanced options) still pins both ends via
|
||||||
|
`CLIP_TARGET_MIN`/`MAX` when the user wants an exact number.
|
||||||
|
|
||||||
### Silent footage: the vision fallback (`main.get_visual_clips`)
|
### Silent footage: the vision fallback (`main.get_visual_clips`)
|
||||||
|
|
||||||
The moment picker reads the transcript, so a video with nothing said in it
|
The moment picker reads the transcript, so a video with nothing said in it
|
||||||
|
|
|
||||||
|
|
@ -67,6 +67,68 @@ def clip_count_targets(n_windows):
|
||||||
return low, max(low, high)
|
return low, max(low, high)
|
||||||
|
|
||||||
|
|
||||||
|
def shortlist_target(video_duration):
|
||||||
|
"""How many scored windows the detail pass should get.
|
||||||
|
|
||||||
|
Scales with duration so a long video surfaces more candidates without
|
||||||
|
exploding the detail call, floored at 3 so a short one still gets a
|
||||||
|
choice. ``score_batches`` exists to make this number reachable.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
seconds = float(video_duration or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
seconds = 0.0
|
||||||
|
return max(3, min(10, int(seconds // 90) + 2))
|
||||||
|
|
||||||
|
|
||||||
|
def score_batches(windows, batch_size):
|
||||||
|
"""Split ``windows`` into near-equal scoring batches.
|
||||||
|
|
||||||
|
Two things were wrong with the old ``range(0, n, batch_size)`` walk plus a
|
||||||
|
prompt that said "choose up to 3 windows from this batch".
|
||||||
|
|
||||||
|
The cap made the shortlist unreachable. Its real ceiling was
|
||||||
|
``3 * n_batches``, not ``shortlist_target``: measured 22-sep-2026 on a
|
||||||
|
9:10 source, 9 windows batched 8 + 1 returned 3 + 1 = 4 windows against a
|
||||||
|
target of 8. ``clip_count_targets`` then derives the clip floor from that
|
||||||
|
halved shortlist, so the detail pass was asked for 4-8 clips instead of
|
||||||
|
6-12 and the job delivered 4 (3 in prod on the same video). Every source
|
||||||
|
under ~30 minutes was starved the same way, which is the mechanism behind
|
||||||
|
"95% of jobs deliver 3 clips or fewer" — the clip count the retention
|
||||||
|
curve hangs on (see clip_count_targets). The prompt now scores every
|
||||||
|
window it is given and the shortlist is the global top ``target``, so the
|
||||||
|
selection happens where the scores can actually be compared.
|
||||||
|
|
||||||
|
Per-batch selection also threw away the ranking it was computing: a batch
|
||||||
|
holding five great moments could only contribute three, while a batch of
|
||||||
|
filler still contributed its own three.
|
||||||
|
|
||||||
|
The remainder was its own bug: a trailing batch of one window came back
|
||||||
|
with that window whatever its score, because a cap of 3 cannot filter a
|
||||||
|
batch of 1 — the tail of the video entered the shortlist by arithmetic
|
||||||
|
rather than merit (``window_009`` did exactly that on the measured run).
|
||||||
|
Near-equal batches keep that from happening and also keep each score
|
||||||
|
comparable, since a window judged alone is judged against nothing.
|
||||||
|
"""
|
||||||
|
windows = list(windows or [])
|
||||||
|
n = len(windows)
|
||||||
|
if not n:
|
||||||
|
return []
|
||||||
|
size = max(1, int(batch_size or 1))
|
||||||
|
n_batches = max(1, -(-n // size)) # ceil
|
||||||
|
base, extra = divmod(n, n_batches)
|
||||||
|
|
||||||
|
out = []
|
||||||
|
start = 0
|
||||||
|
for index in range(n_batches):
|
||||||
|
take = base + (1 if index < extra else 0)
|
||||||
|
batch = windows[start:start + take]
|
||||||
|
start += take
|
||||||
|
if batch:
|
||||||
|
out.append(batch)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def trim_to_best(shorts, max_clips):
|
def trim_to_best(shorts, max_clips):
|
||||||
"""Cut an over-long detail-pass result down to ``max_clips`` BY SCORE.
|
"""Cut an over-long detail-pass result down to ``max_clips`` BY SCORE.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -249,19 +249,22 @@ def _log(message: str) -> None:
|
||||||
|
|
||||||
SCORE_PROMPT_TEMPLATE = """
|
SCORE_PROMPT_TEMPLATE = """
|
||||||
You are a senior short-form video strategist.
|
You are a senior short-form video strategist.
|
||||||
Select the MOST viral candidate windows from this batch.
|
RANK these candidate windows by how well each would work as a standalone short.
|
||||||
|
|
||||||
Rules:
|
Rules:
|
||||||
- Return only valid JSON.
|
- Return only valid JSON.
|
||||||
- Choose up to 3 windows from this batch.
|
- Score EVERY window in this batch: exactly one entry per input window, with
|
||||||
- `score` must be an integer from 0 to 100.
|
the id you were given. Do not drop the weak ones — say they are weak.
|
||||||
|
- `score` must be an integer from 0 to 100, and the ranking is what matters:
|
||||||
|
use the whole range instead of clustering. Most windows of a normal video
|
||||||
|
are not clippable, so reserve 70+ for the ones that pass the test below,
|
||||||
|
and put weak filler, housekeeping, outros, rambling transitions and
|
||||||
|
low-signal padding under 30 even when the topic is interesting.
|
||||||
- THE 2-SECOND TEST is the main criterion: would the first 2 seconds of this
|
- THE 2-SECOND TEST is the main criterion: would the first 2 seconds of this
|
||||||
moment force a cold viewer (no context) to keep watching? Windows that only
|
moment force a cold viewer (no context) to keep watching? Windows that only
|
||||||
work with prior context score low.
|
work with prior context score low.
|
||||||
- Prefer windows with strong hooks, conflict, surprise, outrage, emotion,
|
- Prefer windows with strong hooks, conflict, surprise, outrage, emotion,
|
||||||
novelty, big numbers, or a clear payoff.
|
novelty, big numbers, or a clear payoff.
|
||||||
- Ignore weak filler, housekeeping, outros, rambling transitions, and
|
|
||||||
low-signal padding unless there is an obvious hook or payoff.
|
|
||||||
|
|
||||||
TRANSCRIPT_LANGUAGE: {language}
|
TRANSCRIPT_LANGUAGE: {language}
|
||||||
VIDEO_DURATION_SECONDS: {video_duration}
|
VIDEO_DURATION_SECONDS: {video_duration}
|
||||||
|
|
@ -596,7 +599,7 @@ def main() -> int:
|
||||||
if args.mode != "score":
|
if args.mode != "score":
|
||||||
# Score mode receives every window, not a shortlist, so a count target
|
# Score mode receives every window, not a shortlist, so a count target
|
||||||
# derived from it would be meaningless — and the score template has no
|
# derived from it would be meaningless — and the score template has no
|
||||||
# placeholder for one anyway.
|
# placeholder for one: it ranks whatever it is given.
|
||||||
fmt["min_clips"], fmt["max_clips"] = clip_count_targets(len(payload.get("windows") or []))
|
fmt["min_clips"], fmt["max_clips"] = clip_count_targets(len(payload.get("windows") or []))
|
||||||
fmt["min_secs"], fmt["max_secs"] = clip_duration_bounds()
|
fmt["min_secs"], fmt["max_secs"] = clip_duration_bounds()
|
||||||
prompt = template.format(**fmt)
|
prompt = template.format(**fmt)
|
||||||
|
|
|
||||||
45
main.py
45
main.py
|
|
@ -28,6 +28,7 @@ import layout_picker
|
||||||
import llm_backend
|
import llm_backend
|
||||||
from clip_selection import (build_transcript_windows, clip_count_targets,
|
from clip_selection import (build_transcript_windows, clip_count_targets,
|
||||||
clip_duration_bounds, dedupe_overlapping,
|
clip_duration_bounds, dedupe_overlapping,
|
||||||
|
score_batches, shortlist_target,
|
||||||
snap_clip_to_words, trim_to_best)
|
snap_clip_to_words, trim_to_best)
|
||||||
from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY,
|
from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY,
|
||||||
QUALITY_FAST, METADATA_SCRUB)
|
QUALITY_FAST, METADATA_SCRUB)
|
||||||
|
|
@ -1728,6 +1729,13 @@ def get_viral_clips(transcript_result, video_duration):
|
||||||
# 4096 unless OLLAMA_CONTEXT_LENGTH says otherwise) and 8 windows of
|
# 4096 unless OLLAMA_CONTEXT_LENGTH says otherwise) and 8 windows of
|
||||||
# transcript do not fit; a silently truncated prompt scores garbage.
|
# transcript do not fit; a silently truncated prompt scores garbage.
|
||||||
SCORE_BATCH = score_batch_size()
|
SCORE_BATCH = score_batch_size()
|
||||||
|
# The batches only split the work: the prompt scores every window it
|
||||||
|
# is given and the shortlist below is the global top `target`. Letting
|
||||||
|
# each batch SELECT instead (the old "up to 3 per batch") capped the
|
||||||
|
# shortlist at 3 * n_batches, under the target for any source shorter
|
||||||
|
# than ~30 min. See clip_selection.score_batches.
|
||||||
|
target = shortlist_target(video_duration)
|
||||||
|
|
||||||
def _payload(ws):
|
def _payload(ws):
|
||||||
return [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in ws]
|
return [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in ws]
|
||||||
|
|
||||||
|
|
@ -1736,15 +1744,14 @@ def get_viral_clips(transcript_result, video_duration):
|
||||||
video_duration=video_duration, language=language,
|
video_duration=video_duration, language=language,
|
||||||
windows_json=json.dumps(_payload(ws), ensure_ascii=False))
|
windows_json=json.dumps(_payload(ws), ensure_ascii=False))
|
||||||
|
|
||||||
for b in range(0, len(windows), SCORE_BATCH):
|
for batch in score_batches(windows, SCORE_BATCH):
|
||||||
scored.extend(_run_stage_split(
|
scored.extend(_run_stage_split(
|
||||||
client, model_name, windows[b:b + SCORE_BATCH], _score_prompt,
|
client, model_name, batch, _score_prompt,
|
||||||
gemini_worker.ScoreResponse, "windows", costs, "score"))
|
gemini_worker.ScoreResponse, "windows", costs, "score"))
|
||||||
|
|
||||||
# Shortlist the top windows; scale with duration so long videos surface
|
# Shortlist the top windows; scale with duration so long videos surface
|
||||||
# more candidates without exploding the detail call.
|
# more candidates without exploding the detail call.
|
||||||
scored.sort(key=lambda w: w.get("score", 0), reverse=True)
|
scored.sort(key=lambda w: w.get("score", 0), reverse=True)
|
||||||
target = max(3, min(10, int(video_duration // 90) + 2))
|
|
||||||
by_id = {w["id"]: w for w in windows}
|
by_id = {w["id"]: w for w in windows}
|
||||||
shortlist = [by_id[w["id"]] for w in scored[:target] if w.get("id") in by_id]
|
shortlist = [by_id[w["id"]] for w in scored[:target] if w.get("id") in by_id]
|
||||||
if not shortlist:
|
if not shortlist:
|
||||||
|
|
@ -1754,17 +1761,43 @@ def get_viral_clips(transcript_result, video_duration):
|
||||||
# --- Pass 2: detailed clip extraction on the shortlist ---
|
# --- Pass 2: detailed clip extraction on the shortlist ---
|
||||||
min_clips, max_clips = clip_count_targets(len(shortlist))
|
min_clips, max_clips = clip_count_targets(len(shortlist))
|
||||||
|
|
||||||
def _detail_prompt(ws):
|
def _detail_prompt_for(lo, hi):
|
||||||
# A split batch keeps the full clip-count band: a short list can
|
# A split batch keeps the full clip-count band: a short list can
|
||||||
# still hold the best clips, and the model returns fewer anyway.
|
# still hold the best clips, and the model returns fewer anyway.
|
||||||
|
def build(ws):
|
||||||
return gemini_worker.DETAIL_PROMPT_TEMPLATE.format(
|
return gemini_worker.DETAIL_PROMPT_TEMPLATE.format(
|
||||||
video_duration=video_duration, language=language,
|
video_duration=video_duration, language=language,
|
||||||
min_clips=min_clips, max_clips=max_clips,
|
min_clips=lo, max_clips=hi,
|
||||||
min_secs=min_secs, max_secs=max_secs,
|
min_secs=min_secs, max_secs=max_secs,
|
||||||
windows_json=json.dumps(_payload(ws), ensure_ascii=False))
|
windows_json=json.dumps(_payload(ws), ensure_ascii=False))
|
||||||
|
return build
|
||||||
|
|
||||||
shorts = _run_stage_split(client, model_name, shortlist, _detail_prompt,
|
shorts = _run_stage_split(client, model_name, shortlist,
|
||||||
|
_detail_prompt_for(min_clips, max_clips),
|
||||||
gemini_worker.DetailResponse, "shorts", costs, "detail")
|
gemini_worker.DetailResponse, "shorts", costs, "detail")
|
||||||
|
|
||||||
|
# The floor lived only in the prompt, and a prompt is not a contract:
|
||||||
|
# the model regularly returned half of it and the job shipped that.
|
||||||
|
# The windows it passed over are the cheap second chance — they are
|
||||||
|
# already the best-scoring ones in the video — so they get one more
|
||||||
|
# call for the missing clips. It may still come back empty, which is
|
||||||
|
# the honest answer for material that does not hold more.
|
||||||
|
if len(shorts) < min_clips:
|
||||||
|
used = {str(s.get("source_window_id") or "") for s in shorts}
|
||||||
|
spare = [w for w in shortlist if w["id"] not in used]
|
||||||
|
if spare:
|
||||||
|
missing = min_clips - len(shorts)
|
||||||
|
print(f" Detail returned {len(shorts)} clip(s) of {min_clips}; "
|
||||||
|
f"asking the {len(spare)} unused window(s) for {missing} more.")
|
||||||
|
extra = _run_stage_split(
|
||||||
|
client, model_name, spare,
|
||||||
|
_detail_prompt_for(missing, max(missing, len(spare))),
|
||||||
|
gemini_worker.DetailResponse, "shorts", costs, "detail-floor")
|
||||||
|
if extra:
|
||||||
|
shorts = sorted(shorts + extra,
|
||||||
|
key=lambda s: float(s.get("start") or 0))
|
||||||
|
print(f" Recovered {len(extra)} clip(s) from them.")
|
||||||
|
|
||||||
if len(shorts) > max_clips:
|
if len(shorts) > max_clips:
|
||||||
# By score, never by position: the results arrive in transcript
|
# By score, never by position: the results arrive in transcript
|
||||||
# order, so slicing kept the earliest clips and silently dropped
|
# order, so slicing kept the earliest clips and silently dropped
|
||||||
|
|
|
||||||
101
tests/test_clip_floor.py
Normal file
101
tests/test_clip_floor.py
Normal file
|
|
@ -0,0 +1,101 @@
|
||||||
|
"""The clip floor must survive a model that ignores it.
|
||||||
|
|
||||||
|
`min_clips` lived only in the detail prompt, so a run that came back with
|
||||||
|
half the requested clips shipped half the clips: the measured 9:10 source
|
||||||
|
asked for 6-12 and delivered 3-4. The windows the detail pass skipped get
|
||||||
|
one more call before the job settles for less.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
main = pytest.importorskip("main")
|
||||||
|
|
||||||
|
|
||||||
|
def _transcript(n_segments=40):
|
||||||
|
segments = []
|
||||||
|
for i in range(n_segments):
|
||||||
|
start = i * 15.0
|
||||||
|
segments.append({
|
||||||
|
"start": start, "end": start + 15.0,
|
||||||
|
"text": f"sentence number {i} with enough words to score",
|
||||||
|
"words": [{"word": f"w{i}", "start": start, "end": start + 0.4}],
|
||||||
|
})
|
||||||
|
return {"language": "es", "segments": segments}
|
||||||
|
|
||||||
|
|
||||||
|
def _clip(start, window_id, score=80):
|
||||||
|
return {
|
||||||
|
"start": start, "end": start + 30.0, "source_window_id": window_id,
|
||||||
|
"predicted_score": score, "video_description_for_tiktok": "d",
|
||||||
|
"video_description_for_instagram": "d",
|
||||||
|
"video_title_for_youtube_short": "t", "viral_hook_text": "h",
|
||||||
|
"why": "because",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _run(monkeypatch, detail_responses):
|
||||||
|
"""Drive get_viral_clips with canned stage results; returns (clips, calls)."""
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_stage(client, model, prompt, schema):
|
||||||
|
payload = json.loads(prompt.split("WINDOWS_JSON:")[-1].split("Return only:")[0]
|
||||||
|
if "WINDOWS_JSON:" in prompt else "[]")
|
||||||
|
if schema is main.gemini_worker.ScoreResponse:
|
||||||
|
ids = [w["id"] for w in payload]
|
||||||
|
calls.append(("score", ids))
|
||||||
|
# The prompt asks for every window to be scored.
|
||||||
|
return {"windows": [{"id": i, "start": 0, "end": 90, "score": 90 - n,
|
||||||
|
"reason": "r"}
|
||||||
|
for n, i in enumerate(ids)]}, None
|
||||||
|
windows = json.loads(prompt.split("CANDIDATE_WINDOWS_JSON:")[-1]
|
||||||
|
.split("Return only:")[0])
|
||||||
|
ids = [w["id"] for w in windows]
|
||||||
|
calls.append(("detail", ids))
|
||||||
|
return {"shorts": detail_responses.pop(0)}, None
|
||||||
|
|
||||||
|
monkeypatch.setattr(main, "_run_gemini_stage", fake_stage)
|
||||||
|
monkeypatch.setenv("GEMINI_API_KEY", "test-key")
|
||||||
|
monkeypatch.setattr(main.genai, "Client", lambda api_key=None: object())
|
||||||
|
out = main.get_viral_clips(_transcript(), 600.0)
|
||||||
|
return (out or {}).get("shorts", []), calls
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_short_detail_result_asks_the_unused_windows(monkeypatch):
|
||||||
|
# Two clips back on a shortlist that asked for six: the four windows that
|
||||||
|
# produced nothing get a second call, and its clips are kept.
|
||||||
|
first = [_clip(0, "window_001"), _clip(120, "window_003")]
|
||||||
|
second = [_clip(240, "window_005"), _clip(300, "window_006"),
|
||||||
|
_clip(360, "window_007"), _clip(420, "window_008")]
|
||||||
|
clips, calls = _run(monkeypatch, [first, second])
|
||||||
|
|
||||||
|
detail_calls = [c for c in calls if c[0] == "detail"]
|
||||||
|
assert len(detail_calls) == 2, "the floor never triggered a second call"
|
||||||
|
# The retry only revisits windows the first pass returned nothing for.
|
||||||
|
assert "window_001" not in detail_calls[1][1]
|
||||||
|
assert "window_003" not in detail_calls[1][1]
|
||||||
|
assert len(clips) >= 6
|
||||||
|
assert [c["start"] for c in clips] == sorted(c["start"] for c in clips)
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_second_call_when_the_floor_is_met(monkeypatch):
|
||||||
|
enough = [_clip(i * 60, f"window_{i + 1:03d}") for i in range(6)]
|
||||||
|
clips, calls = _run(monkeypatch, [enough])
|
||||||
|
assert len([c for c in calls if c[0] == "detail"]) == 1
|
||||||
|
assert len(clips) == 6
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_empty_retry_is_accepted_rather_than_padded(monkeypatch):
|
||||||
|
# Material that genuinely holds two clips still returns two, not filler.
|
||||||
|
clips, calls = _run(monkeypatch, [[_clip(0, "window_001")], []])
|
||||||
|
assert len([c for c in calls if c[0] == "detail"]) == 2
|
||||||
|
assert len(clips) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_scoring_fills_the_shortlist_it_targets(monkeypatch):
|
||||||
|
# 600s -> target 8. Every window is scored, so the shortlist is the top 8
|
||||||
|
# globally instead of the 3-per-batch a constant cap allowed.
|
||||||
|
clips, calls = _run(monkeypatch, [[_clip(i * 60, f"window_{i + 1:03d}")
|
||||||
|
for i in range(6)]])
|
||||||
|
detail_windows = [c[1] for c in calls if c[0] == "detail"][0]
|
||||||
|
assert len(detail_windows) == 8
|
||||||
|
|
@ -7,6 +7,8 @@ from clip_selection import (
|
||||||
build_transcript_windows,
|
build_transcript_windows,
|
||||||
clip_count_targets,
|
clip_count_targets,
|
||||||
dedupe_overlapping,
|
dedupe_overlapping,
|
||||||
|
score_batches,
|
||||||
|
shortlist_target,
|
||||||
snap_clip_to_words,
|
snap_clip_to_words,
|
||||||
compact_words,
|
compact_words,
|
||||||
lookup_model_prices,
|
lookup_model_prices,
|
||||||
|
|
@ -244,3 +246,60 @@ class TestDedupeOverlapping:
|
||||||
def test_disjoint_untouched(self):
|
def test_disjoint_untouched(self):
|
||||||
clips = [self._clip(0, 30, 50), self._clip(30, 60, 60), self._clip(100, 130, 40)]
|
clips = [self._clip(0, 30, 50), self._clip(30, 60, 60), self._clip(100, 130, 40)]
|
||||||
assert dedupe_overlapping(clips) == clips
|
assert dedupe_overlapping(clips) == clips
|
||||||
|
|
||||||
|
|
||||||
|
class TestScoreBatches:
|
||||||
|
"""The scoring pass must be able to fill the shortlist it is aiming for.
|
||||||
|
|
||||||
|
Regression for 22-sep-2026: a 9:10 source built 9 windows, was batched
|
||||||
|
8 + 1 against a prompt capped at "up to 3 windows", and shortlisted 4 of
|
||||||
|
a target of 8 — which halved the clip floor downstream.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _windows(n):
|
||||||
|
return [{"id": f"w{i}", "start": i * 60, "end": i * 60 + 90, "text": "t"}
|
||||||
|
for i in range(n)]
|
||||||
|
|
||||||
|
def test_every_window_is_scored_exactly_once_and_in_order(self):
|
||||||
|
# The shortlist is the global top N of the scores, so a window that
|
||||||
|
# never reaches the model can never be picked.
|
||||||
|
for n in (1, 2, 7, 8, 9, 17, 38):
|
||||||
|
batches = score_batches(self._windows(n), 8)
|
||||||
|
seen = [w["id"] for batch in batches for w in batch]
|
||||||
|
assert seen == [w["id"] for w in self._windows(n)]
|
||||||
|
|
||||||
|
def test_the_nine_window_case_has_no_tail_of_one(self):
|
||||||
|
# The measured job split 9 into 8 + 1, and a batch of 1 cannot be
|
||||||
|
# filtered: window_009 entered the shortlist by arithmetic.
|
||||||
|
assert [len(b) for b in score_batches(self._windows(9), 8)] == [5, 4]
|
||||||
|
|
||||||
|
def test_batches_are_near_equal_and_within_the_size_limit(self):
|
||||||
|
for n in (9, 16, 17, 38, 100):
|
||||||
|
sizes = [len(b) for b in score_batches(self._windows(n), 8)]
|
||||||
|
assert max(sizes) <= 8
|
||||||
|
assert max(sizes) - min(sizes) <= 1
|
||||||
|
assert sum(sizes) == n
|
||||||
|
|
||||||
|
def test_batch_count_is_never_worse_than_the_naive_walk(self):
|
||||||
|
# Balancing must not cost extra Gemini calls.
|
||||||
|
for n in range(1, 60):
|
||||||
|
naive = -(-n // 8)
|
||||||
|
assert len(score_batches(self._windows(n), 8)) == naive
|
||||||
|
|
||||||
|
def test_degenerate_input_does_not_crash(self):
|
||||||
|
assert score_batches([], 8) == []
|
||||||
|
assert score_batches(None, 8) == []
|
||||||
|
assert [len(b) for b in score_batches(self._windows(2), 0)] == [1, 1]
|
||||||
|
|
||||||
|
|
||||||
|
class TestShortlistTarget:
|
||||||
|
def test_scales_with_duration_and_is_capped(self):
|
||||||
|
assert shortlist_target(60) == 3 # floor
|
||||||
|
assert shortlist_target(9 * 60) == 8 # the measured job
|
||||||
|
assert shortlist_target(60 * 60) == 10 # ceiling
|
||||||
|
assert shortlist_target(3 * 60 * 60) == 10
|
||||||
|
|
||||||
|
def test_degenerate_input_does_not_crash(self):
|
||||||
|
assert shortlist_target(None) == 3
|
||||||
|
assert shortlist_target("nonsense") == 3
|
||||||
|
|
|
||||||
|
|
@ -74,8 +74,11 @@ class TestPromptTemplates:
|
||||||
assert "2–4 MOST engaging" in text
|
assert "2–4 MOST engaging" in text
|
||||||
assert "10 to 20 seconds" in text
|
assert "10 to 20 seconds" in text
|
||||||
|
|
||||||
def test_score_template_needs_no_new_keys(self):
|
def test_score_template_ranks_every_window(self):
|
||||||
# The scoring pass has no count/duration placeholders; formatting with
|
# The pass used to SELECT ("choose up to 3 windows from this batch"),
|
||||||
# only its classic keys must keep working.
|
# which capped the shortlist at 3 * n_batches and threw away the
|
||||||
_templates()["SCORE_PROMPT_TEMPLATE"].format(
|
# ranking it was computing. It scores everything now.
|
||||||
|
text = _templates()["SCORE_PROMPT_TEMPLATE"].format(
|
||||||
video_duration=100, language="es", windows_json="[]")
|
video_duration=100, language="es", windows_json="[]")
|
||||||
|
assert "Score EVERY window" in text
|
||||||
|
assert "up to 3 windows" not in text
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue