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).
This commit is contained in:
parent
861134f8fe
commit
b3e44643cc
4 changed files with 729 additions and 118 deletions
161
clip_selection.py
Normal file
161
clip_selection.py
Normal file
|
|
@ -0,0 +1,161 @@
|
||||||
|
"""
|
||||||
|
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))
|
||||||
363
gemini_worker.py
Normal file
363
gemini_worker.py
Normal file
|
|
@ -0,0 +1,363 @@
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from google import genai
|
||||||
|
from google.genai import types as genai_types
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from clip_selection import lookup_model_prices
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
|
||||||
|
# --- Structured output schemas (passed as response_schema so the API
|
||||||
|
# --- guarantees the format instead of us repairing free-form JSON). ---
|
||||||
|
|
||||||
|
class ScoredWindowModel(BaseModel):
|
||||||
|
id: str
|
||||||
|
start: float
|
||||||
|
end: float
|
||||||
|
score: int
|
||||||
|
reason: str
|
||||||
|
|
||||||
|
|
||||||
|
class ScoreResponse(BaseModel):
|
||||||
|
windows: List[ScoredWindowModel]
|
||||||
|
|
||||||
|
|
||||||
|
class DetailClipModel(BaseModel):
|
||||||
|
start: float
|
||||||
|
end: float
|
||||||
|
source_window_id: str
|
||||||
|
predicted_score: int
|
||||||
|
video_description_for_tiktok: str
|
||||||
|
video_description_for_instagram: str
|
||||||
|
video_title_for_youtube_short: str
|
||||||
|
viral_hook_text: str
|
||||||
|
|
||||||
|
|
||||||
|
class DetailResponse(BaseModel):
|
||||||
|
shorts: List[DetailClipModel]
|
||||||
|
|
||||||
|
|
||||||
|
def _configure_stdio() -> None:
|
||||||
|
for stream_name in ("stdout", "stderr"):
|
||||||
|
stream = getattr(sys, stream_name, None)
|
||||||
|
if not stream or not hasattr(stream, "reconfigure"):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _log(message: str) -> None:
|
||||||
|
stream = sys.stdout
|
||||||
|
text = str(message)
|
||||||
|
try:
|
||||||
|
stream.write(text + "\n")
|
||||||
|
except UnicodeEncodeError:
|
||||||
|
encoding = getattr(stream, "encoding", None) or "utf-8"
|
||||||
|
safe_text = text.encode(encoding, errors="replace").decode(encoding, errors="replace")
|
||||||
|
stream.write(safe_text + "\n")
|
||||||
|
stream.flush()
|
||||||
|
|
||||||
|
SCORE_PROMPT_TEMPLATE = """
|
||||||
|
You are a senior short-form video strategist.
|
||||||
|
Select the MOST viral candidate windows from this batch.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
- Return only valid JSON.
|
||||||
|
- Choose up to 3 windows from this batch.
|
||||||
|
- `score` must be an integer from 0 to 100.
|
||||||
|
- 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
|
||||||
|
work with prior context score low.
|
||||||
|
- Prefer windows with strong hooks, conflict, surprise, outrage, emotion,
|
||||||
|
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}
|
||||||
|
VIDEO_DURATION_SECONDS: {video_duration}
|
||||||
|
WINDOWS_JSON:
|
||||||
|
{windows_json}
|
||||||
|
|
||||||
|
Return only:
|
||||||
|
{{
|
||||||
|
"windows": [
|
||||||
|
{{
|
||||||
|
"id": "<window id>",
|
||||||
|
"start": <number>,
|
||||||
|
"end": <number>,
|
||||||
|
"score": <integer 0-100>,
|
||||||
|
"reason": "<very short reason>"
|
||||||
|
}}
|
||||||
|
]
|
||||||
|
}}
|
||||||
|
"""
|
||||||
|
|
||||||
|
DETAIL_PROMPT_TEMPLATE = """
|
||||||
|
You are a senior short-form video editor and viral copywriter.
|
||||||
|
Choose the BEST short clips from these shortlisted candidate windows.
|
||||||
|
|
||||||
|
CLIP RULES:
|
||||||
|
- Return only valid JSON.
|
||||||
|
- Each clip must be 15 to 60 seconds long, in absolute seconds from the start of the source video.
|
||||||
|
- Stay within the candidate window boundaries.
|
||||||
|
- THE 2-SECOND RULE: the clip MUST open on its strongest moment. If the first
|
||||||
|
2 seconds would not stop a cold viewer from scrolling, move the start or skip the clip.
|
||||||
|
- Start slightly before the hook and end slightly after the payoff when possible.
|
||||||
|
- Do not cut in the middle of a word or phrase.
|
||||||
|
- No generic intros/outros unless they are the hook.
|
||||||
|
- Prefer one great clip per candidate window. Maximum 2 clips per window only if clearly justified.
|
||||||
|
- DIVERSITY: never return two clips that make the same point, tell the same
|
||||||
|
story, or land the same joke — even across different windows. Pick the
|
||||||
|
stronger one and drop the other.
|
||||||
|
|
||||||
|
HOOK PLAYBOOK — pick the strongest fitting pattern for `viral_hook_text` (max 10 words):
|
||||||
|
- Open question: "Why does everyone get this wrong?"
|
||||||
|
- Hot take / controversy: "Stop doing this. Seriously."
|
||||||
|
- Number / fact shock: "97% of people miss this."
|
||||||
|
- Story loop: "This one email almost ruined me."
|
||||||
|
- POV / pattern interrupt: "POV: you finally understand it."
|
||||||
|
(These are English PATTERNS — always write the actual hook in TRANSCRIPT_LANGUAGE.)
|
||||||
|
|
||||||
|
COPY RULES — ALL text fields (descriptions, title, hook) MUST be written in TRANSCRIPT_LANGUAGE ({language}):
|
||||||
|
- Descriptions (TikTok + Instagram): 1-2 punchy sentences that tease the payoff
|
||||||
|
without spoiling it, then 3-5 topically relevant hashtags. No generic hashtag spam.
|
||||||
|
- `video_title_for_youtube_short`: max 100 chars, curiosity-driven, no fake claims.
|
||||||
|
- `predicted_score`: honest 0-100 estimate of viral potential.
|
||||||
|
|
||||||
|
TRANSCRIPT_LANGUAGE: {language}
|
||||||
|
VIDEO_DURATION_SECONDS: {video_duration}
|
||||||
|
CANDIDATE_WINDOWS_JSON:
|
||||||
|
{windows_json}
|
||||||
|
|
||||||
|
Return only:
|
||||||
|
{{
|
||||||
|
"shorts": [
|
||||||
|
{{
|
||||||
|
"start": <number>,
|
||||||
|
"end": <number>,
|
||||||
|
"source_window_id": "<window id>",
|
||||||
|
"predicted_score": <integer 0-100>,
|
||||||
|
"video_description_for_tiktok": "<description + hashtags>",
|
||||||
|
"video_description_for_instagram": "<description + hashtags>",
|
||||||
|
"video_title_for_youtube_short": "<title max 100 chars>",
|
||||||
|
"viral_hook_text": "<short overlay max 10 words>"
|
||||||
|
}}
|
||||||
|
]
|
||||||
|
}}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_code_fences(text: str) -> str:
|
||||||
|
text = (text or "").strip()
|
||||||
|
if text.startswith("```"):
|
||||||
|
lines = text.splitlines()
|
||||||
|
if lines:
|
||||||
|
lines = lines[1:]
|
||||||
|
if lines and lines[-1].strip() == "```":
|
||||||
|
lines = lines[:-1]
|
||||||
|
text = "\n".join(lines).strip()
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_json_candidate(text: str) -> str:
|
||||||
|
cleaned = _strip_code_fences(text)
|
||||||
|
start = cleaned.find("{")
|
||||||
|
end = cleaned.rfind("}")
|
||||||
|
if start != -1 and end != -1 and end > start:
|
||||||
|
return cleaned[start:end + 1]
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def _escape_invalid_unicode_escapes(text: str) -> str:
|
||||||
|
chars = []
|
||||||
|
i = 0
|
||||||
|
while i < len(text):
|
||||||
|
if text[i] == "\\" and i + 1 < len(text) and text[i + 1] == "u":
|
||||||
|
hex_digits = text[i + 2:i + 6]
|
||||||
|
if len(hex_digits) < 4 or any(ch not in "0123456789abcdefABCDEF" for ch in hex_digits):
|
||||||
|
chars.append("\\\\u")
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
chars.append(text[i])
|
||||||
|
i += 1
|
||||||
|
return "".join(chars)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_json_response_text(text: str) -> dict:
|
||||||
|
if not text:
|
||||||
|
raise ValueError("Gemini returned an empty response body.")
|
||||||
|
candidate = _extract_json_candidate(text).replace("\x00", "").strip()
|
||||||
|
if not candidate:
|
||||||
|
raise ValueError("Gemini response did not contain a JSON object.")
|
||||||
|
parse_attempts = [candidate]
|
||||||
|
sanitized_candidate = _escape_invalid_unicode_escapes(candidate)
|
||||||
|
if sanitized_candidate != candidate:
|
||||||
|
parse_attempts.append(sanitized_candidate)
|
||||||
|
last_error: Optional[Exception] = None
|
||||||
|
for parse_candidate in parse_attempts:
|
||||||
|
try:
|
||||||
|
return json.loads(parse_candidate)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
last_error = e
|
||||||
|
raise ValueError(f"Failed to parse Gemini JSON response: {last_error}")
|
||||||
|
|
||||||
|
|
||||||
|
def _get_response_text(response) -> str:
|
||||||
|
try:
|
||||||
|
text = response.text
|
||||||
|
if text:
|
||||||
|
return text
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
parts = []
|
||||||
|
for candidate in getattr(response, "candidates", []) or []:
|
||||||
|
content = getattr(candidate, "content", None)
|
||||||
|
for part in getattr(content, "parts", []) or []:
|
||||||
|
part_text = getattr(part, "text", None)
|
||||||
|
if part_text:
|
||||||
|
parts.append(part_text)
|
||||||
|
return "\n".join(parts).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _calculate_cost_analysis(response, model_name: str) -> Optional[dict]:
|
||||||
|
usage = getattr(response, "usage_metadata", None)
|
||||||
|
if not usage:
|
||||||
|
return None
|
||||||
|
prices = lookup_model_prices(model_name)
|
||||||
|
price_estimated = prices is None
|
||||||
|
if prices is None:
|
||||||
|
# Unknown model: conservative estimate so the UI shows something sane.
|
||||||
|
prices = (0.50, 3.00)
|
||||||
|
input_price_per_million, output_price_per_million = prices
|
||||||
|
prompt_tokens = usage.prompt_token_count or 0
|
||||||
|
output_tokens = usage.candidates_token_count or 0
|
||||||
|
# Thinking tokens bill at the output rate even though they are invisible.
|
||||||
|
thinking_tokens = getattr(usage, "thoughts_token_count", 0) or 0
|
||||||
|
input_cost = (prompt_tokens / 1_000_000) * input_price_per_million
|
||||||
|
output_cost = ((output_tokens + thinking_tokens) / 1_000_000) * output_price_per_million
|
||||||
|
total_cost = input_cost + output_cost
|
||||||
|
return {
|
||||||
|
"input_tokens": prompt_tokens,
|
||||||
|
"output_tokens": output_tokens,
|
||||||
|
"thinking_tokens": thinking_tokens,
|
||||||
|
"input_cost": input_cost,
|
||||||
|
"output_cost": output_cost,
|
||||||
|
"total_cost": total_cost,
|
||||||
|
"model": model_name,
|
||||||
|
"price_estimated": price_estimated,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _thinking_config_from_env(model_name: str):
|
||||||
|
"""GEMINI_THINKING_SCORE: off (default) | low | high | <token budget>.
|
||||||
|
|
||||||
|
Applied only to the scoring stage. Gemini 3 models take thinking_level,
|
||||||
|
Gemini 2.5 takes thinking_budget; returns None (= model default) if the
|
||||||
|
setting is off or the SDK rejects the config."""
|
||||||
|
raw = (os.getenv("GEMINI_THINKING_SCORE") or "off").strip().lower()
|
||||||
|
if raw in ("", "off", "0", "none", "false"):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
if raw.isdigit():
|
||||||
|
return genai_types.ThinkingConfig(thinking_budget=int(raw))
|
||||||
|
if raw in ("low", "high"):
|
||||||
|
if model_name.startswith("gemini-3"):
|
||||||
|
return genai_types.ThinkingConfig(thinking_level=raw)
|
||||||
|
return genai_types.ThinkingConfig(thinking_budget=2048 if raw == "low" else 8192)
|
||||||
|
except Exception as e:
|
||||||
|
_log(f"⚠️ Ignoring GEMINI_THINKING_SCORE={raw!r}: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _config_for_strategy(strategy: str, mode: str, model_name: str) -> genai_types.GenerateContentConfig:
|
||||||
|
# The detail stage writes creative copy (hooks/descriptions) — it gets a
|
||||||
|
# high temperature; timestamps are validated and word-snapped afterwards.
|
||||||
|
# The score stage stays precise. Fallback strategies get conservative.
|
||||||
|
creative = mode == "detail"
|
||||||
|
kwargs = {
|
||||||
|
"response_mime_type": "application/json",
|
||||||
|
"candidate_count": 1,
|
||||||
|
}
|
||||||
|
if strategy == "strict-json":
|
||||||
|
kwargs["temperature"] = 0.7 if creative else 0.1
|
||||||
|
elif strategy == "json-text-recovery":
|
||||||
|
kwargs["temperature"] = 0.2 if creative else 0.0
|
||||||
|
else: # structured-schema: schema-enforced output, primary strategy
|
||||||
|
kwargs["temperature"] = 0.9 if creative else 0.2
|
||||||
|
kwargs["response_schema"] = DetailResponse if mode == "detail" else ScoreResponse
|
||||||
|
if mode == "score":
|
||||||
|
thinking = _thinking_config_from_env(model_name)
|
||||||
|
if thinking is not None:
|
||||||
|
kwargs["thinking_config"] = thinking
|
||||||
|
return genai_types.GenerateContentConfig(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
_configure_stdio()
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="Run a single Gemini request for clip scoring/detailing.")
|
||||||
|
parser.add_argument("--mode", choices=["score", "detail"], required=True)
|
||||||
|
parser.add_argument("--input", dest="input_path", required=True)
|
||||||
|
parser.add_argument("--output", dest="output_path", required=True)
|
||||||
|
parser.add_argument("--strategy", default="structured-schema")
|
||||||
|
parser.add_argument("--model", default="gemini-2.5-flash")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
api_key = os.getenv("GEMINI_API_KEY")
|
||||||
|
if not api_key:
|
||||||
|
raise SystemExit("Missing GEMINI_API_KEY.")
|
||||||
|
|
||||||
|
with open(args.input_path, "r", encoding="utf-8") as f:
|
||||||
|
payload = json.load(f)
|
||||||
|
|
||||||
|
model_name = args.model
|
||||||
|
client = genai.Client(api_key=api_key)
|
||||||
|
config = _config_for_strategy(args.strategy, args.mode, model_name)
|
||||||
|
language = str(payload.get("language") or "unknown")
|
||||||
|
|
||||||
|
template = SCORE_PROMPT_TEMPLATE if args.mode == "score" else DETAIL_PROMPT_TEMPLATE
|
||||||
|
prompt = template.format(
|
||||||
|
video_duration=payload["video_duration"],
|
||||||
|
language=language,
|
||||||
|
windows_json=json.dumps(payload["windows"], ensure_ascii=False),
|
||||||
|
)
|
||||||
|
|
||||||
|
_log(f"🤖 Gemini worker request: mode={args.mode} strategy={args.strategy} model={model_name} items={len(payload.get('windows', []))}")
|
||||||
|
response = client.models.generate_content(
|
||||||
|
model=model_name,
|
||||||
|
contents=prompt,
|
||||||
|
config=config,
|
||||||
|
)
|
||||||
|
|
||||||
|
raw_text = _get_response_text(response)
|
||||||
|
# With response_schema the SDK returns an already-validated object; fall
|
||||||
|
# back to the text-repair path only when that is unavailable.
|
||||||
|
parsed_obj = getattr(response, "parsed", None)
|
||||||
|
if parsed_obj is not None:
|
||||||
|
parsed = parsed_obj.model_dump() if hasattr(parsed_obj, "model_dump") else parsed_obj
|
||||||
|
else:
|
||||||
|
parsed = _parse_json_response_text(raw_text)
|
||||||
|
result = {
|
||||||
|
"mode": args.mode,
|
||||||
|
"payload": parsed,
|
||||||
|
"cost_analysis": _calculate_cost_analysis(response, model_name),
|
||||||
|
"raw_text": raw_text,
|
||||||
|
}
|
||||||
|
with open(args.output_path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(result, f, indent=2, ensure_ascii=False)
|
||||||
|
_log(f"✅ Gemini worker success: mode={args.mode}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
219
main.py
219
main.py
|
|
@ -17,6 +17,9 @@ import mediapipe as mp
|
||||||
# import whisper (replaced by faster_whisper inside function)
|
# import whisper (replaced by faster_whisper inside function)
|
||||||
from google import genai
|
from google import genai
|
||||||
from google.genai import types as genai_types
|
from google.genai import types as genai_types
|
||||||
|
|
||||||
|
import gemini_worker
|
||||||
|
from clip_selection import build_transcript_windows, snap_clip_to_words
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
import json
|
import json
|
||||||
|
|
||||||
|
|
@ -847,148 +850,132 @@ def transcribe_video(video_path):
|
||||||
'language': info.language
|
'language': info.language
|
||||||
}
|
}
|
||||||
|
|
||||||
def get_viral_clips(transcript_result, video_duration):
|
def _run_gemini_stage(client, model_name, prompt, schema):
|
||||||
print("🤖 Analyzing with Gemini...")
|
"""One schema-enforced Gemini call with transient-error backoff.
|
||||||
|
Returns (parsed_dict, cost_analysis)."""
|
||||||
|
config = genai_types.GenerateContentConfig(
|
||||||
|
response_mime_type="application/json",
|
||||||
|
response_schema=schema,
|
||||||
|
)
|
||||||
|
max_attempts = 3
|
||||||
|
response = None
|
||||||
|
for attempt in range(1, max_attempts + 1):
|
||||||
|
try:
|
||||||
|
response = client.models.generate_content(model=model_name, contents=prompt, config=config)
|
||||||
|
break
|
||||||
|
except Exception as e:
|
||||||
|
msg = str(e)
|
||||||
|
transient = any(tok in msg for tok in (
|
||||||
|
'503', 'UNAVAILABLE', '429', 'RESOURCE_EXHAUSTED',
|
||||||
|
'500', 'INTERNAL', 'overloaded', 'Deadline'))
|
||||||
|
if attempt == max_attempts or not transient:
|
||||||
|
raise
|
||||||
|
wait = 5 * (2 ** (attempt - 1))
|
||||||
|
print(f"⚠️ Gemini transient error (attempt {attempt}/{max_attempts}), retrying in {wait}s: {msg[:150]}")
|
||||||
|
time.sleep(wait)
|
||||||
|
|
||||||
|
parsed_obj = getattr(response, "parsed", None)
|
||||||
|
if parsed_obj is not None:
|
||||||
|
parsed = parsed_obj.model_dump() if hasattr(parsed_obj, "model_dump") else parsed_obj
|
||||||
|
else:
|
||||||
|
parsed = gemini_worker._parse_json_response_text(gemini_worker._get_response_text(response))
|
||||||
|
cost = gemini_worker._calculate_cost_analysis(response, model_name)
|
||||||
|
return parsed, cost
|
||||||
|
|
||||||
|
|
||||||
|
def get_viral_clips(transcript_result, video_duration):
|
||||||
|
"""Two-pass clip selection: score transcript windows, then detail the best.
|
||||||
|
|
||||||
|
Windowing gives even coverage on long videos (a single call over the whole
|
||||||
|
transcript clusters picks near the start), and the cheap scoring pass keeps
|
||||||
|
the expensive detail reasoning focused on the shortlist. Cuts are snapped to
|
||||||
|
word boundaries so clips don't start/end mid-word.
|
||||||
|
"""
|
||||||
|
print("\U0001f916 Analyzing with Gemini (2-pass: score → detail)...")
|
||||||
api_key = os.getenv("GEMINI_API_KEY")
|
api_key = os.getenv("GEMINI_API_KEY")
|
||||||
if not api_key:
|
if not api_key:
|
||||||
print("❌ Error: GEMINI_API_KEY not found in environment variables.")
|
print("❌ Error: GEMINI_API_KEY not found in environment variables.")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
client = genai.Client(api_key=api_key)
|
client = genai.Client(api_key=api_key)
|
||||||
|
|
||||||
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
|
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
|
||||||
|
language = str(transcript_result.get('language') or 'unknown')
|
||||||
|
print(f"\U0001f916 Model: {model_name} | language: {language}")
|
||||||
|
|
||||||
print(f"🤖 Initializing Gemini with model: {model_name}")
|
# Full word list — ground truth for snapping cut points.
|
||||||
|
|
||||||
# Extract words
|
|
||||||
words = []
|
words = []
|
||||||
for segment in transcript_result['segments']:
|
for segment in transcript_result['segments']:
|
||||||
for word in segment.get('words', []):
|
for word in segment.get('words', []):
|
||||||
words.append({
|
words.append({'w': word['word'], 's': word['start'], 'e': word['end']})
|
||||||
'w': word['word'],
|
|
||||||
's': word['start'],
|
|
||||||
'e': word['end']
|
|
||||||
})
|
|
||||||
|
|
||||||
prompt = GEMINI_PROMPT_TEMPLATE.format(
|
|
||||||
video_duration=video_duration,
|
|
||||||
transcript_text=json.dumps(transcript_result['text']),
|
|
||||||
words_json=json.dumps(words)
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Retry transient Gemini failures (503 high demand, 429 quota, 500)
|
windows = build_transcript_windows(transcript_result, video_duration)
|
||||||
# with exponential backoff before giving up (issue #27).
|
print(f" Built {len(windows)} scoring window(s).")
|
||||||
max_attempts = 3
|
costs = []
|
||||||
response = None
|
|
||||||
# Force valid JSON output. Manual fence-stripping + json.loads breaks on
|
|
||||||
# models that emit trailing text or truncate (e.g. flash-lite), so let
|
|
||||||
# the API guarantee a JSON body. Fall back to a plain call if the SDK
|
|
||||||
# or model rejects the option.
|
|
||||||
try:
|
|
||||||
gen_config = genai_types.GenerateContentConfig(response_mime_type="application/json")
|
|
||||||
except Exception:
|
|
||||||
gen_config = None
|
|
||||||
for attempt in range(1, max_attempts + 1):
|
|
||||||
try:
|
|
||||||
response = client.models.generate_content(
|
|
||||||
model=model_name,
|
|
||||||
contents=prompt,
|
|
||||||
config=gen_config,
|
|
||||||
) if gen_config is not None else client.models.generate_content(
|
|
||||||
model=model_name,
|
|
||||||
contents=prompt,
|
|
||||||
)
|
|
||||||
break
|
|
||||||
except Exception as e:
|
|
||||||
msg = str(e)
|
|
||||||
transient = any(tok in msg for tok in (
|
|
||||||
'503', 'UNAVAILABLE', '429', 'RESOURCE_EXHAUSTED',
|
|
||||||
'500', 'INTERNAL', 'overloaded', 'Deadline'
|
|
||||||
))
|
|
||||||
if attempt == max_attempts or not transient:
|
|
||||||
raise
|
|
||||||
wait = 5 * (2 ** (attempt - 1))
|
|
||||||
print(f"⚠️ Gemini transient error (attempt {attempt}/{max_attempts}), retrying in {wait}s: {msg[:150]}")
|
|
||||||
time.sleep(wait)
|
|
||||||
|
|
||||||
# --- Cost Calculation ---
|
# --- Pass 1: score windows in batches, keep the highest-scoring ---
|
||||||
try:
|
scored = []
|
||||||
usage = response.usage_metadata
|
SCORE_BATCH = 8
|
||||||
if usage:
|
for b in range(0, len(windows), SCORE_BATCH):
|
||||||
# USD per 1M tokens, longest-prefix match on the model name so
|
batch = windows[b:b + SCORE_BATCH]
|
||||||
# env-overridden models still price correctly (ai.google.dev).
|
payload = [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in batch]
|
||||||
MODEL_PRICES = {
|
prompt = gemini_worker.SCORE_PROMPT_TEMPLATE.format(
|
||||||
"gemini-3.5-flash": (1.50, 9.00),
|
video_duration=video_duration, language=language,
|
||||||
"gemini-3.1-flash-lite": (0.25, 1.50),
|
windows_json=json.dumps(payload, ensure_ascii=False))
|
||||||
"gemini-3-flash-preview": (0.50, 3.00),
|
parsed, cost = _run_gemini_stage(client, model_name, prompt, gemini_worker.ScoreResponse)
|
||||||
"gemini-2.5-flash-lite": (0.10, 0.40),
|
if cost:
|
||||||
"gemini-2.5-flash": (0.30, 2.50),
|
costs.append(cost)
|
||||||
}
|
scored.extend(parsed.get("windows") or [])
|
||||||
match = None
|
|
||||||
for key in MODEL_PRICES:
|
|
||||||
if model_name.startswith(key) and (match is None or len(key) > len(match)):
|
|
||||||
match = key
|
|
||||||
input_price_per_million, output_price_per_million = (
|
|
||||||
MODEL_PRICES[match] if match else (0.50, 3.00) # conservative default
|
|
||||||
)
|
|
||||||
|
|
||||||
prompt_tokens = usage.prompt_token_count
|
# Shortlist the top windows; scale with duration so long videos surface
|
||||||
output_tokens = usage.candidates_token_count
|
# more candidates without exploding the detail call.
|
||||||
|
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}
|
||||||
|
shortlist = [by_id[w["id"]] for w in scored[:target] if w.get("id") in by_id]
|
||||||
|
if not shortlist:
|
||||||
|
shortlist = windows[:target] # scoring returned nothing usable
|
||||||
|
print(f" Shortlisted {len(shortlist)} window(s) for detail.")
|
||||||
|
|
||||||
input_cost = (prompt_tokens / 1_000_000) * input_price_per_million
|
# --- Pass 2: detailed clip extraction on the shortlist ---
|
||||||
output_cost = (output_tokens / 1_000_000) * output_price_per_million
|
payload = [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in shortlist]
|
||||||
total_cost = input_cost + output_cost
|
prompt = gemini_worker.DETAIL_PROMPT_TEMPLATE.format(
|
||||||
|
video_duration=video_duration, language=language,
|
||||||
|
windows_json=json.dumps(payload, ensure_ascii=False))
|
||||||
|
detail, cost = _run_gemini_stage(client, model_name, prompt, gemini_worker.DetailResponse)
|
||||||
|
if cost:
|
||||||
|
costs.append(cost)
|
||||||
|
|
||||||
cost_analysis = {
|
shorts = detail.get("shorts") or []
|
||||||
"input_tokens": prompt_tokens,
|
# Snap each proposed clip onto real word boundaries (+ a bit of silence).
|
||||||
"output_tokens": output_tokens,
|
for s in shorts:
|
||||||
"input_cost": input_cost,
|
ns, ne = snap_clip_to_words(s.get("start", 0), s.get("end", 0), words, video_duration)
|
||||||
"output_cost": output_cost,
|
s["start"], s["end"] = ns, ne
|
||||||
"total_cost": total_cost,
|
|
||||||
"model": model_name
|
|
||||||
}
|
|
||||||
|
|
||||||
print(f"💰 Token Usage ({model_name}):")
|
# Aggregate cost across both passes.
|
||||||
print(f" - Input Tokens: {prompt_tokens} (${input_cost:.6f})")
|
cost_analysis = None
|
||||||
print(f" - Output Tokens: {output_tokens} (${output_cost:.6f})")
|
if costs:
|
||||||
print(f" - Total Estimated Cost: ${total_cost:.6f}")
|
cost_analysis = {
|
||||||
|
"input_tokens": sum(c.get("input_tokens", 0) for c in costs),
|
||||||
|
"output_tokens": sum(c.get("output_tokens", 0) for c in costs),
|
||||||
|
"total_cost": sum(c.get("total_cost", 0) for c in costs),
|
||||||
|
"model": model_name,
|
||||||
|
}
|
||||||
|
print(f"\U0001f4b0 Total cost ({model_name}, 2-pass, {len(costs)} calls): ${cost_analysis['total_cost']:.6f}")
|
||||||
|
|
||||||
except Exception as e:
|
if not shorts:
|
||||||
print(f"⚠️ Could not calculate cost: {e}")
|
print("⚠️ 2-pass returned no clips.")
|
||||||
cost_analysis = None
|
return None
|
||||||
# ------------------------
|
|
||||||
|
|
||||||
# Clean response if it contains markdown code blocks
|
|
||||||
text = (response.text or "").strip()
|
|
||||||
if text.startswith("```json"):
|
|
||||||
text = text[7:]
|
|
||||||
elif text.startswith("```"):
|
|
||||||
text = text[3:]
|
|
||||||
if text.endswith("```"):
|
|
||||||
text = text[:-3]
|
|
||||||
text = text.strip()
|
|
||||||
|
|
||||||
try:
|
|
||||||
result_json = json.loads(text)
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
# Rescue: extract the outermost {...} object if the model wrapped
|
|
||||||
# the JSON in prose or appended stray tokens.
|
|
||||||
first, last = text.find('{'), text.rfind('}')
|
|
||||||
if first == -1 or last <= first:
|
|
||||||
raise
|
|
||||||
result_json = json.loads(text[first:last + 1])
|
|
||||||
|
|
||||||
|
result = {"shorts": shorts}
|
||||||
if cost_analysis:
|
if cost_analysis:
|
||||||
result_json['cost_analysis'] = cost_analysis
|
result["cost_analysis"] = cost_analysis
|
||||||
|
return result
|
||||||
return result_json
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ Gemini Error: {e}")
|
print(f"❌ Gemini Error: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
parser = argparse.ArgumentParser(description="AutoCrop-Vertical with Viral Clip Detection.")
|
parser = argparse.ArgumentParser(description="AutoCrop-Vertical with Viral Clip Detection.")
|
||||||
|
|
||||||
|
|
|
||||||
100
tests/test_clip_selection.py
Normal file
100
tests/test_clip_selection.py
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
"""Tests for the pure clip-selection helpers (windows, snapping, pricing)."""
|
||||||
|
from clip_selection import (
|
||||||
|
build_transcript_windows,
|
||||||
|
snap_clip_to_words,
|
||||||
|
compact_words,
|
||||||
|
lookup_model_prices,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _seg(start, end, text):
|
||||||
|
return {"start": start, "end": end, "text": text}
|
||||||
|
|
||||||
|
|
||||||
|
def _word(w, s, e):
|
||||||
|
return {"w": w, "s": s, "e": e}
|
||||||
|
|
||||||
|
|
||||||
|
class TestBuildTranscriptWindows:
|
||||||
|
def test_windows_align_to_segment_boundaries(self):
|
||||||
|
transcript = {"segments": [
|
||||||
|
_seg(0, 40, "a"), _seg(40, 80, "b"), _seg(80, 100, "c"), _seg(100, 150, "d"),
|
||||||
|
]}
|
||||||
|
windows = build_transcript_windows(transcript, 150, window_seconds=90, overlap_seconds=30)
|
||||||
|
segment_edges = {0, 40, 80, 100, 150}
|
||||||
|
for w in windows:
|
||||||
|
assert w["start"] in segment_edges
|
||||||
|
assert w["end"] in segment_edges
|
||||||
|
|
||||||
|
def test_windows_overlap(self):
|
||||||
|
transcript = {"segments": [_seg(i * 10, (i + 1) * 10, f"s{i}") for i in range(30)]}
|
||||||
|
windows = build_transcript_windows(transcript, 300, window_seconds=90, overlap_seconds=30)
|
||||||
|
assert len(windows) >= 3
|
||||||
|
for prev, nxt in zip(windows, windows[1:]):
|
||||||
|
# next window starts before the previous one ends (overlap)
|
||||||
|
assert nxt["start"] < prev["end"]
|
||||||
|
# full coverage to the end
|
||||||
|
assert windows[-1]["end"] == 300
|
||||||
|
|
||||||
|
def test_empty_transcript_falls_back_to_full_video(self):
|
||||||
|
windows = build_transcript_windows({"segments": []}, 120)
|
||||||
|
assert len(windows) == 1
|
||||||
|
assert windows[0]["start"] == 0.0
|
||||||
|
assert windows[0]["end"] == 120
|
||||||
|
|
||||||
|
def test_always_progresses(self):
|
||||||
|
# One giant segment must not loop forever
|
||||||
|
transcript = {"segments": [_seg(0, 500, "long monolog")]}
|
||||||
|
windows = build_transcript_windows(transcript, 500, window_seconds=90, overlap_seconds=30)
|
||||||
|
assert len(windows) == 1
|
||||||
|
|
||||||
|
|
||||||
|
class TestSnapClipToWords:
|
||||||
|
def _words(self):
|
||||||
|
# words every ~2s with 0.4s gaps: [0,1.6], [2,3.6], [4,5.6], ...
|
||||||
|
return [_word(f"w{i}", i * 2.0, i * 2.0 + 1.6) for i in range(40)]
|
||||||
|
|
||||||
|
def test_start_snaps_into_silence_before_word(self):
|
||||||
|
words = self._words()
|
||||||
|
# Gemini proposes 10.3 — nearest word start is 10.0, gap before is 9.6->10.0
|
||||||
|
start, end = snap_clip_to_words(10.3, 30.1, words, 80.0)
|
||||||
|
assert 9.8 <= start <= 10.0 # word start minus half-gap lead
|
||||||
|
# end 30.1 -> nearest word end 29.6 plus tail
|
||||||
|
assert 29.6 <= end <= 30.05
|
||||||
|
|
||||||
|
def test_no_words_nearby_keeps_original(self):
|
||||||
|
words = [_word("far", 200.0, 201.0)]
|
||||||
|
assert snap_clip_to_words(10.0, 40.0, words, 300.0) == (10.0, 40.0)
|
||||||
|
|
||||||
|
def test_empty_words_keeps_original(self):
|
||||||
|
assert snap_clip_to_words(5.0, 25.0, [], 100.0) == (5.0, 25.0)
|
||||||
|
|
||||||
|
def test_duration_repaired_to_minimum(self):
|
||||||
|
words = self._words()
|
||||||
|
# snapping would yield ~14.4s; must be extended to >= 15s on a word end
|
||||||
|
start, end = snap_clip_to_words(10.0, 24.5, words, 80.0)
|
||||||
|
assert end - start >= 15.0
|
||||||
|
|
||||||
|
def test_duration_capped_at_maximum(self):
|
||||||
|
words = self._words()
|
||||||
|
start, end = snap_clip_to_words(0.0, 59.9, words, 80.0)
|
||||||
|
assert end - start <= 60.0
|
||||||
|
|
||||||
|
|
||||||
|
class TestPricing:
|
||||||
|
def test_known_models(self):
|
||||||
|
assert lookup_model_prices("gemini-2.5-flash") == (0.30, 2.50)
|
||||||
|
assert lookup_model_prices("gemini-3-flash-preview") == (0.50, 3.00)
|
||||||
|
|
||||||
|
def test_prefix_match_with_suffix(self):
|
||||||
|
assert lookup_model_prices("gemini-2.5-flash-002") == (0.30, 2.50)
|
||||||
|
|
||||||
|
def test_unknown_model_returns_none(self):
|
||||||
|
assert lookup_model_prices("gpt-9-mega") is None
|
||||||
|
assert lookup_model_prices(None) is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestCompactWords:
|
||||||
|
def test_rounds_timestamps(self):
|
||||||
|
words = [{"w": " hi", "s": 17.240000000000002, "e": 17.899999999999999}]
|
||||||
|
assert compact_words(words) == [{"w": " hi", "s": 17.24, "e": 17.9}]
|
||||||
Loading…
Reference in a new issue