Prod measurement, 3-ago-2026: 408 of 429 jobs (95%) delivered three clips or
fewer, the mode being ONE. Cross-referenced against retention on the cohort
that signed up 3-7 days ago (old enough to have returned, recent enough that
the 7-day purge has not deleted their user_videos rows):
clips delivered users came back a 2nd day
1-3 251 0.4%
4-9 31 16.1%
Forty times the retention on the far side of a boundary that 95% of jobs never
crossed. That is the mechanism behind the 96.7% of users who only ever use the
product on a single day.
The shortlist was not the constraint — a 5-minute video already shortlists 5
windows. The detail prompt was: it asked to "prefer one great clip per
candidate window", and both the 2-second rule and STANDS ALONE end in "or skip
it" with no lower bound, as does DIVERSITY's "drop the other". Three rules
pushing down and nothing holding the count up collapses to one clip.
clip_count_targets() now derives a floor and a ceiling from the shortlist size
(3 windows -> 3-6, 5 -> 4-10, 10+ -> 6-12) and the prompt states it. Every
quality rule is untouched — they are validated at 82% against random windows
and this change does not spend that.
A/B on 8 real prod transcripts (3.5-18 min, all of which delivered 1-3 clips in
production), sharing the score pass between variants so only the detail prompt
differs:
OLD mean 2.75 median 2.5 <=3 clips: 6/8
NEW mean 4.00 median 4.0 <=3 clips: 3/8
better on 7 of 8, worse on none, one tie (sign test p = 0.016)
The ceiling never bound: the most any video produced was 5 against a ceiling of
8-12, so the model is not padding to hit a number — the floor and the removal
of the one-per-window bias are doing the work. That is the outcome to want.
Read the limits honestly. Three of eight still land at three or fewer, and the
sample under-represents the sub-5-minute videos that are 54% of real jobs and
the hardest case here: both short videos in the set shortlisted only 2 windows
out of the 3-4 that existed, because the SCORE pass returned fewer usable
windows than it was given. That is the next thing to look at, and it caps this
change on exactly the videos that matter most.
CLIP_TARGET_MIN / CLIP_TARGET_MAX override both bounds for further A/B runs
without a deploy.
202 lines
7.6 KiB
Python
202 lines
7.6 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 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 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))
|