clipwright/clip_selection.py
juancarlos.cavero 36dba9b3b1 feat(selection): say why each clip was picked, drop clips that overlap a better one
The detail pass now returns a one-sentence `why` per clip (what makes this
moment a clip, not the topic), stored in the metadata and shown under the
title in the dashboard card: the score said how much, nothing said why.
Defaulted in the schema so a small local model that skips it keeps the clip.

After the word snap, clips overlapping an already-kept clip by half the
shorter one are dropped in favour of the higher predicted_score. The prompt's
DIVERSITY rule was the only thing preventing the same moment twice; in ~330
clips over 8 talks it never fired, so this is a guard, not a fix.

Each clip also keeps the model's raw `proposed` boundaries before the snap,
which is what made boundary accuracy measurable: p90 0.4-0.5 s from a word
on 8 talks (21-sep-2026), inside snap_clip_to_words' 1.5 s reach.

Two ideas borrowed from AutoClip were measured with a blind judge on the
same corpus and NOT adopted: quoting per-sentence timestamps in the detail
pass lost 24%/23% (p<0.001, two seeds — it shortens clips and drops the
payoff), and an "end on the reaction, not the line" rule was inert
(47%/53%, p=0.71).
2026-09-21 22:47:55 +02:00

300 lines
12 KiB
Python

"""
Pure helpers for the Gemini clip-selection pipeline.
Standard-library only so both main.py and gemini_worker.py can import it and
the logic stays unit-testable without the heavy video dependencies.
"""
# USD per 1M tokens (input, output incl. thinking), from ai.google.dev pricing.
MODEL_PRICES = {
"gemini-3.5-flash": (1.50, 9.00),
"gemini-3.1-flash-lite": (0.25, 1.50),
"gemini-3-flash-preview": (0.50, 3.00),
"gemini-2.5-flash-lite": (0.10, 0.40),
"gemini-2.5-flash": (0.30, 2.50),
"gemini-2.0-flash": (0.10, 0.40), # deprecated (shut down 2026-06-01)
}
def lookup_model_prices(model_name):
"""Longest-prefix match against MODEL_PRICES; None if unknown."""
name = str(model_name or "").lower()
best_key = None
for key in MODEL_PRICES:
if name.startswith(key) and (best_key is None or len(key) > len(best_key)):
best_key = key
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 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
15-60 — set per job by /api/process when the user asks for a specific
length, or by hand for A/B runs. Values are clamped to platform-sane
limits and re-ordered so bad input degrades instead of breaking the job.
"""
import os
def _read(name, default):
try:
return float(os.environ.get(name, ""))
except ValueError:
return default
lo = _read("CLIP_MIN_SECONDS", 15.0)
hi = _read("CLIP_MAX_SECONDS", 60.0)
lo = min(max(lo, 5.0), 175.0)
hi = min(max(hi, 10.0), 180.0)
if hi < lo + 5.0: # keep a real band: degenerate ranges starve the model
hi = min(180.0, lo + 5.0)
return round(lo, 3), round(hi, 3)
def compact_words(words, precision=2):
"""Round word timestamps for prompts — full float precision wastes tokens."""
return [
{
"w": w.get("w", ""),
"s": round(float(w.get("s", 0)), precision),
"e": round(float(w.get("e", 0)), precision),
}
for w in words
]
def build_transcript_windows(transcript_result, video_duration,
window_seconds=90, overlap_seconds=30):
"""
Build scoring windows aligned to Whisper segment boundaries, so a sentence
(and usually a viral moment) is never cut in half mid-window. Windows grow
segment by segment to roughly window_seconds (up to 1.25x for the closing
segment) and the next window starts ~overlap_seconds before the previous
end, also snapped to a segment start.
"""
segments = []
for segment in transcript_result.get("segments", []):
text = str(segment.get("text") or "").strip()
if not text:
continue
segments.append((float(segment.get("start", 0)), float(segment.get("end", 0)), text))
windows = []
window_index = 1
i = 0
n = len(segments)
while i < n:
w_start = segments[i][0]
j = i
# Extend while the NEXT segment still fits within a tolerant cap, so the
# window closes on a segment boundary near window_seconds.
while j + 1 < n and segments[j + 1][1] - w_start <= window_seconds * 1.25:
j += 1
if segments[j][1] - w_start >= window_seconds:
break
w_end = segments[j][1]
windows.append({
"id": f"window_{window_index:03d}",
"start": round(w_start, 3),
"end": round(w_end, 3),
"text": " ".join(seg[2] for seg in segments[i:j + 1]),
})
window_index += 1
if j >= n - 1:
break
# Next window starts at the first segment beginning after (end - overlap),
# but always makes progress.
target = w_end - overlap_seconds
k = i + 1
while k <= j and segments[k][0] < target:
k += 1
i = max(k, i + 1)
if not windows:
windows.append({
"id": "window_001",
"start": 0.0,
"end": round(float(video_duration), 3),
"text": str(transcript_result.get("text", "") or ""),
})
return windows
def dedupe_overlapping(shorts, ratio=0.5):
"""Drop clips that overlap an already-kept clip by ``ratio`` of the
shorter one, keeping the higher ``predicted_score`` (earlier on a tie).
The detail prompt's DIVERSITY rule is the only thing that stopped two
clips from sharing the same seconds, and a rule is not a guarantee: two
picks from one window can cover the same moment with different edges,
and the user then downloads the same short twice. Survivors come back in
transcript order, like ``trim_to_best``.
"""
def _score(c):
try:
return float(c.get("predicted_score") or 0)
except (TypeError, ValueError, AttributeError):
return 0.0
def _span(c):
try:
return float(c.get("start", 0)), float(c.get("end", 0))
except (TypeError, ValueError, AttributeError):
return 0.0, 0.0
indexed = list(enumerate(shorts))
kept = []
for idx, clip in sorted(indexed, key=lambda p: (-_score(p[1]), p[0])):
s, e = _span(clip)
clash = False
for _, other in kept:
os_, oe = _span(other)
overlap = min(e, oe) - max(s, os_)
shorter = max(1e-6, min(e - s, oe - os_))
if overlap > 0 and overlap / shorter >= ratio:
clash = True
break
if not clash:
kept.append((idx, clip))
return [c for _, c in sorted(kept, key=lambda p: p[0])]
def snap_clip_to_words(start, end, words, video_duration,
min_duration=15.0, max_duration=60.0,
search_window=1.5, max_lead=0.35, max_tail=0.45):
"""
Snap Gemini-proposed clip boundaries onto real word boundaries plus a bit
of the surrounding silence. LLMs are bad at millisecond arithmetic; the
word-level timestamps are ground truth, so cuts land in pauses instead of
mid-word.
words: [{'w','s','e'}, ...] for the whole video, sorted by start.
Returns (start, end); falls back to the input if no words are nearby or
snapping cannot satisfy the duration bounds.
"""
original = (round(float(start), 3), round(float(end), 3))
if not words:
return original
starts = [float(w.get("s", 0)) for w in words]
ends = [float(w.get("e", 0)) for w in words]
# START: snap to the nearest word start, then lead into the silence before it.
new_start = float(start)
candidates = [s for s in starts if abs(s - new_start) <= search_window]
if candidates:
word_start = min(candidates, key=lambda s: abs(s - new_start))
prev_ends = [e for e in ends if e <= word_start]
if prev_ends:
gap = max(0.0, word_start - max(prev_ends))
lead = min(max_lead, gap / 2)
else:
lead = max_lead
new_start = max(0.0, word_start - lead)
# END: snap to the nearest word end, then trail into the silence after it.
new_end = float(end)
candidates = [e for e in ends if abs(e - new_end) <= search_window]
if candidates:
word_end = min(candidates, key=lambda e: abs(e - new_end))
next_starts = [s for s in starts if s >= word_end]
if next_starts:
gap = max(0.0, min(next_starts) - word_end)
tail = min(max_tail, gap / 2)
else:
tail = max_tail
new_end = min(float(video_duration), word_end + tail)
# Repair duration bounds while staying on word boundaries.
if new_end - new_start < min_duration:
target = new_start + min_duration
later = sorted(e for e in ends if e >= target)
if later and later[0] - new_start <= max_duration:
new_end = min(float(video_duration), later[0] + 0.2)
else:
return original
if new_end - new_start > max_duration:
target = new_start + max_duration
earlier = [e for e in ends if new_start < e <= target]
new_end = (max(earlier) + 0.2) if earlier else target
new_end = min(new_end, new_start + max_duration, float(video_duration))
if new_end <= new_start or new_end - new_start < min_duration:
return original
return (round(new_start, 3), round(new_end, 3))