feat(reframe): pick the layout from 12 frames instead of uploading the video

Gemini bills video at ~300 tokens per second. An hour of source is ~1.08M
tokens (past a 1M context window) and a 1-2GB upload to get one word back. This
pipeline ingests hour-long podcasts, so uploading the file failed in exactly the
normal case.

Measured over the same 48 clips against the hand-checked labels:

  whole video          94% / 92% / 96%   18,17,18 of 20 found
  12 frames @ 640px    90% / 90%         15,16 of 20
  12 frames @ 1024px   92%               17 of 20
  24 frames @ 1024px   90%               16 of 20

Resolution was the gap, not frame count: at 640px a spreadsheet is unreadable,
and doubling the frames made it slightly worse. At 1024px the difference from
sending the whole video sits inside the run-to-run variance the whole-video mode
already has (92-96%), at 2.2s per clip instead of ~15s, with a cost that no
longer depends on the source duration.

It also removes the Files API dance: no upload, no waiting for ACTIVE.
This commit is contained in:
juancarlos.cavero 2026-07-31 13:28:45 +02:00
parent 094e13c2f9
commit 3f7ac4da18
4 changed files with 91 additions and 17 deletions

View file

@ -96,6 +96,16 @@ corpus de 48 contra etiquetas revisadas a mano: 94% / 92% / 96% en tres pasadas,
con 0-1 falsos positivos sobre los 28 clips que no deben tocarse, y solo 2 clips con 0-1 falsos positivos sobre los 28 clips que no deben tocarse, y solo 2 clips
que cambian de respuesta entre pasadas. que cambian de respuesta entre pasadas.
**Manda 12 fotogramas a 1024px, no el vídeo.** Gemini factura vídeo a ~300
tokens por segundo: una hora de fuente son ~1,08M de tokens (no cabe en una
ventana de 1M) y una subida de 1-2 GB para recibir una palabra. Doce fotogramas
cuestan ~3k tokens **dure lo que dure la fuente**, que es lo que hace viable
esto con los podcasts de una hora que entran de verdad. La resolución importa y
el número de fotogramas no: a 640px detecta 15 de 20 (una hoja de cálculo es
ilegible), a 1024px sube a 17, y pasar a 24 fotogramas lo empeora. A 1024px la
diferencia con mandar el vídeo entero cae dentro de la varianza que ya tiene el
propio modo vídeo, a 2,2 s por clip en vez de ~15 s.
Lo que hace que funcione, y que conviene no deshacer: se le pide una **decisión Lo que hace que funcione, y que conviene no deshacer: se le pide una **decisión
entre opciones cerradas**, no una medida. Los cuatro intentos anteriores (Canny, entre opciones cerradas**, no una medida. Los cuatro intentos anteriores (Canny,
MSER, cobertura temporal, anchura) le pedían un número y ninguno separó una hoja MSER, cobertura temporal, anchura) le pedían un número y ninguno separó una hoja

View file

@ -93,7 +93,8 @@ class LayoutChoice(BaseModel):
# instruction and from naming the exact decorations (corner bugs, score # instruction and from naming the exact decorations (corner bugs, score
# counters, subtitles) that four earlier attempts kept mistaking for content. # counters, subtitles) that four earlier attempts kept mistaking for content.
LAYOUT_CHOICE_PROMPT = """ LAYOUT_CHOICE_PROMPT = """
You are choosing how to re-frame this landscape video into a vertical 9:16 clip. These frames are sampled at regular intervals from a single landscape video.
You are choosing how to re-frame that video into a vertical 9:16 clip.
Pick ONE layout: Pick ONE layout:
@ -107,8 +108,8 @@ Pick ONE layout:
or a map that the viewer must read to follow it. If you cannot read words or or a map that the viewer must read to follow it. If you cannot read words or
numbers off the screen that matter to the point being made, it is not this. numbers off the screen that matter to the point being made, it is not this.
- "split": stack two people. ONLY when two people are visible IN THE SAME SHOT - "split": stack two people. ONLY when two people are visible IN THE SAME SHOT
at the same time for most of the video, talking to each other. A video that at the same time in most frames, talking to each other. Frames that alternate
cuts between one-person close-ups is NOT this, however many people speak. between one-person close-ups are NOT this, however many people appear.
"none" is by far the most common correct answer. Choose anything else only if "none" is by far the most common correct answer. Choose anything else only if
you would defend it to an editor. If you are unsure, answer "none". you would defend it to an editor. If you are unsure, answer "none".

View file

@ -20,15 +20,36 @@ the same video scored 1% and 97% coverage on consecutive runs. The variance was
in asking for a continuous measurement, not in the model: a categorical choice in asking for a continuous measurement, not in the model: a categorical choice
between closed options is stable. between closed options is stable.
It samples FRAMES instead of uploading the video. Gemini bills video at ~300
tokens per second, so an hour of source is ~1.08M tokens — past a 1M context
window before it starts — and means pushing a 1-2GB upload to get back one word.
This pipeline ingests hour-long podcasts, so that scales badly in exactly the
normal case. Twelve stills cost ~3k tokens whatever the source runs to.
Measured on the same 48 clips (whole video vs sampled frames):
whole video 94% / 92% / 96% 18,17,18 of 20 found
12 frames @ 640px 90% / 90% 15,16 of 20
12 frames @ 1024px 92% 17 of 20
24 frames @ 1024px 90% 16 of 20
Resolution was the gap, not frame count: at 640px a spreadsheet is unreadable,
and doubling the frames made it slightly worse rather than better. At 1024px the
difference from sending the whole video sits inside the run-to-run variance the
whole-video mode already has, at 2.2s per clip instead of ~15s.
Off by default (``AUTO_LAYOUT=1``). A caller that already switched layouts on Off by default (``AUTO_LAYOUT=1``). A caller that already switched layouts on
by hand wins: this only ever ADDS, so an explicit choice is never overridden. by hand wins: this only ever ADDS, so an explicit choice is never overridden.
""" """
import json import json
import os import os
import time
ENABLED = os.environ.get("AUTO_LAYOUT", "0") == "1" ENABLED = os.environ.get("AUTO_LAYOUT", "0") == "1"
# 12 frames at 1024px wide. Both numbers are measured, not guessed: see above.
SAMPLE_FRAMES = int(os.environ.get("LAYOUT_SAMPLE_FRAMES", "12"))
SAMPLE_WIDTH = int(os.environ.get("LAYOUT_SAMPLE_WIDTH", "1024"))
# What each decision turns on. Keys match the layout names in the prompt. # What each decision turns on. Keys match the layout names in the prompt.
DECISION_FLAGS = { DECISION_FLAGS = {
"none": [], "none": [],
@ -68,6 +89,35 @@ def apply(decision):
return touched return touched
def sample_frames(video_path, n=None, width=None):
"""JPEG bytes for ``n`` frames spread evenly across the video."""
import cv2
n = n or SAMPLE_FRAMES
width = width or SAMPLE_WIDTH
cap = cv2.VideoCapture(video_path)
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
out = []
try:
if total <= 0:
return out
for i in range(n):
cap.set(cv2.CAP_PROP_POS_FRAMES, int(i * total / n))
ok, frame = cap.read()
if not ok:
continue
h, w = frame.shape[:2]
scaled = cv2.resize(frame, (width, max(2, int(h * width / w))),
interpolation=cv2.INTER_AREA)
ok, buf = cv2.imencode(".jpg", scaled,
[cv2.IMWRITE_JPEG_QUALITY, 80])
if ok:
out.append(buf.tobytes())
finally:
cap.release()
return out
def pick(video_path, video_duration): def pick(video_path, video_duration):
"""The layout Gemini picks for this video, or "none" on any failure. """The layout Gemini picks for this video, or "none" on any failure.
@ -89,22 +139,17 @@ def pick(video_path, video_duration):
from google.genai import types as genai_types from google.genai import types as genai_types
import gemini_worker import gemini_worker
client = genai.Client(api_key=api_key) frames = sample_frames(video_path)
upload = client.files.upload(file=video_path) if not frames:
deadline = time.time() + 180 print(" ⚠️ No readable frames — keeping the default layout.")
while True: return "none"
info = client.files.get(name=upload.name)
state = str(getattr(getattr(info, "state", info), "name", "")).upper()
if state == "ACTIVE":
break
if state == "FAILED" or time.time() > deadline:
print(" ⚠️ Upload not usable — keeping the default layout.")
return "none"
time.sleep(2)
client = genai.Client(api_key=api_key)
parts = [genai_types.Part.from_bytes(data=b, mime_type="image/jpeg")
for b in frames]
response = client.models.generate_content( response = client.models.generate_content(
model=model_name, model=model_name,
contents=[upload, gemini_worker.LAYOUT_CHOICE_PROMPT], contents=parts + [gemini_worker.LAYOUT_CHOICE_PROMPT],
config=genai_types.GenerateContentConfig( config=genai_types.GenerateContentConfig(
response_mime_type="application/json", response_mime_type="application/json",
response_schema=gemini_worker.LayoutChoice, response_schema=gemini_worker.LayoutChoice,

View file

@ -97,3 +97,21 @@ class TestValidDecisions:
# The model answers "none" for most videos; it must not be treated as # The model answers "none" for most videos; it must not be treated as
# an unrecognised value and logged as a warning on every job. # an unrecognised value and logged as a warning on every job.
assert "none" in layout_picker.VALID assert "none" in layout_picker.VALID
class TestSampleFrames:
def test_unreadable_video_yields_no_frames(self):
# A path that cannot be opened must come back empty, not raise: pick()
# turns "no frames" into "none" and the job carries on.
assert layout_picker.sample_frames("/nonexistent/video.mp4") == []
def test_no_frames_degrades_to_none(self, monkeypatch):
monkeypatch.setattr(layout_picker, "ENABLED", True)
monkeypatch.setenv("GEMINI_API_KEY", "x")
monkeypatch.setattr(layout_picker, "sample_frames", lambda *a, **k: [])
assert pick("video.mp4", 60) == "none"
def test_sample_size_is_configurable(self, monkeypatch):
# The 12/1024px pair is measured; keep it overridable without a deploy.
monkeypatch.setenv("LAYOUT_SAMPLE_FRAMES", "6")
assert layout_picker.SAMPLE_FRAMES == 12 # read at import, not per call