534 lines
21 KiB
Python
534 lines
21 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.
|
|
"""
|
|
|
|
import re
|
|
|
|
# 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 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):
|
|
"""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 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))
|
|
|
|
|
|
# --- Hook-first boundaries (#2a) -------------------------------------------
|
|
# The first seconds decide the swipe. A model-proposed clip routinely opens on
|
|
# wind-up ("so today we're going to...") and buries the question, the number or
|
|
# the stakes 3-8s in. Word timestamps are ground truth, so the start can be
|
|
# moved onto the first strong spoken hook deterministically — no LLM, no key.
|
|
#
|
|
# These are the signal vocabularies the scan combines. A token matching ANY set
|
|
# is a hook; the EARLIEST such token inside the allowed trim window wins. They
|
|
# are deliberately conservative: a miss leaves the clip untouched, a false
|
|
# positive only advances the start a bounded amount (see the env caps).
|
|
_HOOK_INTERROGATIVES = frozenset({
|
|
"what", "why", "how", "when", "where", "who", "whom", "whose", "which",
|
|
"is", "are", "was", "were", "do", "does", "did", "can", "could", "would",
|
|
"should", "will", "shall",
|
|
})
|
|
_HOOK_IMPERATIVES = frozenset({
|
|
"look", "watch", "imagine", "think", "stop", "try", "check", "see",
|
|
"listen", "remember", "forget", "consider", "notice", "suppose", "picture",
|
|
"keep", "take", "put", "go", "come", "use", "make", "let", "dont", "show",
|
|
"tell", "explain", "build", "create", "write", "read", "open", "close",
|
|
"click", "press", "type", "install", "run", "fix", "never", "always",
|
|
})
|
|
_HOOK_NUMBERS = frozenset({
|
|
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
|
|
"nine", "ten", "eleven", "twelve", "hundred", "thousand", "million",
|
|
"billion", "half", "quarter", "twice", "once", "double", "triple",
|
|
"dozen", "percent", "first", "second", "third",
|
|
})
|
|
_HOOK_CONTRAST = frozenset({
|
|
"but", "until", "actually", "instead", "except", "however", "though",
|
|
"although", "whereas", "yet", "still", "suddenly", "wait", "unless",
|
|
"otherwise", "despite", "nevertheless", "contrary", "opposite", "reverse",
|
|
})
|
|
_HOOK_STAKES = frozenset({
|
|
"never", "always", "first", "worst", "bug", "bugs", "crash", "crashes",
|
|
"crashed", "crashing", "broke", "broken", "break", "wrong", "lost", "lose",
|
|
"losing", "fail", "failed", "fails", "failure", "dies", "death", "dead",
|
|
"kill", "killed", "destroy", "destroyed", "ruin", "ruined", "disaster",
|
|
"mistake", "error", "errors", "segfault", "danger", "dangerous", "scared",
|
|
"terrified", "panic", "emergency", "critical", "fatal", "illegal",
|
|
"corrupt", "corrupted", "hacked", "stolen", "missing", "gone", "worse",
|
|
})
|
|
# Pure hesitation / connective words that are never hooks. The scan simply
|
|
# walks past them, so they end up in the trimmed wind-up; they must not count.
|
|
_HOOK_FILLER = frozenset({
|
|
"uh", "um", "erm", "ah", "eh", "hmm", "mmm", "so", "well", "okay", "ok",
|
|
"yeah", "yep", "right", "and", "then", "like", "basically", "just",
|
|
"you", "know", "i", "mean", "we", "the", "a", "an", "it", "that", "this",
|
|
})
|
|
|
|
# Conservative defaults: HOOK_FIRST is on, but a start only ever moves a few
|
|
# seconds and never more than a quarter of the clip.
|
|
_HOOK_FIRST_DEFAULT_MAX_TRIM = 4.0
|
|
_HOOK_FIRST_DEFAULT_MAX_FRACTION = 0.25
|
|
# A trim smaller than this is noise; leaving the clip alone is kinder than a
|
|
# sub-frame jitter that only complicates the render.
|
|
_MIN_HOOK_TRIM = 0.2
|
|
|
|
|
|
def _env_float(name, default):
|
|
"""Read a float env var, falling back to ``default`` on garbage/absence."""
|
|
import os
|
|
|
|
raw = os.environ.get(name)
|
|
if raw is None or str(raw).strip() == "":
|
|
return default
|
|
try:
|
|
return float(raw)
|
|
except (TypeError, ValueError):
|
|
return default
|
|
|
|
|
|
def hook_first_enabled():
|
|
"""Whether to move clip starts onto the first spoken hook.
|
|
|
|
``HOOK_FIRST`` defaults ON (conservatively capped); set it to ``0`` /
|
|
``false`` / ``no`` / ``off`` to disable the pass for A/B runs.
|
|
"""
|
|
import os
|
|
|
|
raw = os.environ.get("HOOK_FIRST")
|
|
if raw is None:
|
|
return True
|
|
return str(raw).strip().lower() not in ("", "0", "false", "no", "off")
|
|
|
|
|
|
def _hook_token(raw):
|
|
"""Normalise a Whisper word to a bare lowercase token.
|
|
|
|
Words are inconsistent about a leading space (" word" vs "word") and carry
|
|
trailing punctuation ("crash!"), so both are stripped before matching.
|
|
"""
|
|
token = str(raw or "").strip().lower()
|
|
token = re.sub(r"^[^0-9a-z]+", "", token)
|
|
token = re.sub(r"[^0-9a-z]+$", "", token)
|
|
return token
|
|
|
|
|
|
def _is_hook_token(token):
|
|
"""True when a normalised token carries one of the hook signals."""
|
|
if not token or token in _HOOK_FILLER:
|
|
return False
|
|
if any(ch.isdigit() for ch in token):
|
|
return True
|
|
return (token in _HOOK_INTERROGATIVES
|
|
or token in _HOOK_IMPERATIVES
|
|
or token in _HOOK_NUMBERS
|
|
or token in _HOOK_CONTRAST
|
|
or token in _HOOK_STAKES)
|
|
|
|
|
|
def find_hook_start(words, clip_start, clip_end, min_duration=15.0,
|
|
max_trim=None, max_fraction=None):
|
|
"""The strongest deterministic start for a clip, or ``None``.
|
|
|
|
Scans the opening of ``[clip_start, clip_end]`` for the EARLIEST word that
|
|
matches a hook signal (question, imperative, number/quantity, contrast or
|
|
stakes — see the vocabularies above). Leading hesitation, silence and
|
|
filler do not match, so they fall into the trimmed wind-up. Returns the
|
|
hook word's start when it is a legal trim, else ``None`` (no change — a
|
|
clip without a clear hook is left exactly where snapping put it).
|
|
|
|
``words`` is the whole-video ``[{'w','s','e'}, ...]`` list (same shape
|
|
``snap_clip_to_words`` takes). The trim is bounded three ways so the pass
|
|
can never wreck a clip:
|
|
|
|
* ``max_trim`` seconds (env ``HOOK_FIRST_MAX_TRIM``, default 4.0)
|
|
* ``max_fraction`` of the clip's duration (env ``HOOK_FIRST_MAX_FRACTION``,
|
|
default 0.25)
|
|
* the remaining clip must still be at least ``min_duration`` seconds.
|
|
"""
|
|
try:
|
|
clip_start = float(clip_start)
|
|
clip_end = float(clip_end)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
duration = clip_end - clip_start
|
|
if duration <= 0:
|
|
return None
|
|
|
|
if max_trim is None:
|
|
max_trim = _env_float("HOOK_FIRST_MAX_TRIM",
|
|
_HOOK_FIRST_DEFAULT_MAX_TRIM)
|
|
if max_fraction is None:
|
|
max_fraction = _env_float("HOOK_FIRST_MAX_FRACTION",
|
|
_HOOK_FIRST_DEFAULT_MAX_FRACTION)
|
|
try:
|
|
max_trim = max(0.0, float(max_trim))
|
|
max_fraction = max(0.0, float(max_fraction))
|
|
min_duration = float(min_duration)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
cap = min(max_trim, max_fraction * duration)
|
|
if cap < _MIN_HOOK_TRIM:
|
|
return None
|
|
latest = clip_start + cap
|
|
|
|
hook_start = None
|
|
for word in words or []:
|
|
try:
|
|
word_start = float(word.get("s", 0))
|
|
except (AttributeError, TypeError, ValueError):
|
|
continue
|
|
if word_start < clip_start or word_start > latest:
|
|
continue
|
|
if word_start >= clip_end:
|
|
continue
|
|
if _is_hook_token(_hook_token(word.get("w"))):
|
|
if hook_start is None or word_start < hook_start:
|
|
hook_start = word_start
|
|
|
|
if hook_start is None:
|
|
return None
|
|
trim = hook_start - clip_start
|
|
if trim < _MIN_HOOK_TRIM:
|
|
return None
|
|
if clip_end - hook_start < min_duration:
|
|
return None
|
|
return round(hook_start, 3)
|