clipwright/clip_selection.py
juancarlos.cavero b3e44643cc feat: 2-pass Gemini clip pipeline (score windows -> detail shortlist)
Replaces the single whole-transcript call with windowed scoring + focused
detailing (from PR #50), for better clip coverage on long videos:

- clip_selection.py: build_transcript_windows (sentence-aligned overlapping
  windows), snap_clip_to_words (cuts land in pauses, not mid-word), model
  price table.
- gemini_worker.py: score/detail prompts + Pydantic response schemas + robust
  JSON parsing and multi-stage cost accounting (incl. thinking tokens).
- main.py get_viral_clips: pass 1 scores windows in batches and shortlists the
  top (scaled by duration); pass 2 details the shortlist; every clip is snapped
  to word boundaries. Cost is summed across both passes. Falls back to
  whole-video conversion (caller) if it yields nothing.
- 13 clip_selection unit tests (63 total).
2026-07-17 22:32:04 +02:00

161 lines
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 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))