A 9:10 source delivered 3 clips in prod where the pipeline had asked
itself for 6-12. Two independent leaks, both in the chain that derives
the clip count.
The scoring pass SELECTED instead of ranking: "choose up to 3 windows
from this batch" put the shortlist ceiling at 3 * n_batches rather than
shortlist_target, so 9 windows batched 8 + 1 shortlisted 4 of a target
of 8, and clip_count_targets then asked the detail pass for 4-8 clips
instead of 6-12. Every source under ~30 min was starved the same way,
which is the mechanism behind "95% of jobs deliver 3 clips or fewer" —
the clip count D2 retention hangs on (0.4% for 1-3 clips, 16.1% for
4-9). It also discarded the ranking it was computing: a batch holding
five great moments could still contribute only three, while a batch of
filler contributed its own three. The prompt now scores every window it
is given and the shortlist is the global top N.
Batches are near-equal instead of "full ones plus the remainder": 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, so the tail of the
video entered the shortlist by arithmetic. Same call count as before.
And the floor was only a sentence in the detail prompt, with nothing in
code checking it, so a pass that returned half shipped half. When it
comes back under min_clips the shortlist windows that produced nothing
get one more call for the difference; an empty answer is accepted,
because padding is worse than a short list.
Measured on that source, same transcript, three runs: shortlist 4 -> 8,
clips 4 -> 6, cost unchanged (~$0.005, 3 calls).
The detail pass now returns a one-sentence `why` per clip (what makes this
moment a clip, not the topic), stored in the metadata and shown under the
title in the dashboard card: the score said how much, nothing said why.
Defaulted in the schema so a small local model that skips it keeps the clip.
After the word snap, clips overlapping an already-kept clip by half the
shorter one are dropped in favour of the higher predicted_score. The prompt's
DIVERSITY rule was the only thing preventing the same moment twice; in ~330
clips over 8 talks it never fired, so this is a guard, not a fix.
Each clip also keeps the model's raw `proposed` boundaries before the snap,
which is what made boundary accuracy measurable: p90 0.4-0.5 s from a word
on 8 talks (21-sep-2026), inside snap_clip_to_words' 1.5 s reach.
Two ideas borrowed from AutoClip were measured with a blind judge on the
same corpus and NOT adopted: quoting per-sentence timestamps in the detail
pass lost 24%/23% (p<0.001, two seeds — it shortens clips and drops the
payoff), and an "end on the reaction, not the line" rule was inert
(47%/53%, p=0.71).
Handed a path, the SDK copies os.path.basename(path) verbatim into the
X-Goog-Upload-File-Name header, and httpx encodes header values as ASCII.
The downloaded file is named after the video's title, so every source
titled in Japanese, Cyrillic, Arabic or Greek died with "'ascii' codec
can't encode characters in position 0-4" before a byte left the
container, on the three stages that upload the whole file: the
silent-footage vision pass, the screencast detector and the AI editor.
The user saw "the AI model did not return usable clips for this video".
gemini_worker.upload_media() passes an open handle instead, which skips
that header; the readable name still travels as display_name, in the
JSON body, which is UTF-8. An extension the stdlib cannot place falls
back to video/mp4 rather than reaching the API as octet-stream.
The test reproduces the failure through the SDK's own header building
and httpx, and fails if a new call site uses files.upload directly.
The hook and title come from the detail pass, which only reads the
transcript, so a clip whose meaning is on the screen shipped with a topic
summary ("I automated my clips with AI") while the viewer watched an MCP
connector being configured.
Two halves. The detail prompt now carries the rule that hook and title name
the concrete thing happening inside the clip, never the video's topic. And
after the render, when the layout sidecar says at least 25% of a clip is
screencast / wide / inset, hook_grounding sends three frames from those
stretches at 1024px plus the clip's own words to Gemini and rewrites hook
and title in place before auto_hook_clip burns them; the originals stay
under hook_grounding.before. Gemini-only (frames): a local-LLM install logs
one line and keeps the transcript hook. HOOK_GROUNDING=0 disables it.
Verified live on the reported frame: on_screen "Configuración del conector
del servidor MCP de OpenShorts", hook "Configura el servidor MCP de
OpenShorts paso a paso", stable across three runs.
Claude-Session: https://claude.ai/code/session_014i9z6mLTy978uRCfSsMfBq
/api/process (and the process_video MCP tool) now accept optional
target_clips (1-15) and clip_min_seconds / clip_max_seconds (5-180),
surfaced in the dashboard as a collapsed 'advanced options' section.
Blank means the AI decides, keeping the default request byte-identical.
Plumbed through the same env overrides the A/B harness already reads:
CLIP_TARGET_MIN/MAX (existing) and a new clip_duration_bounds() in
clip_selection.py backing CLIP_MIN_SECONDS/MAX_SECONDS. The detail and
visual prompts take the band as template placeholders instead of the
hardcoded 15-60, and word-snapping enforces the same bounds. All three
knobs are honest targets, not guarantees: the model still returns fewer
clips when the material doesn't hold them, and the UI copy says so.
Verified live: target_clips=2 + band 8-15s on the demo video returned
exactly 2 clips of 13.3s and 13.7s (the uncontrolled run gave one 41.7s
clip); out-of-range values 400 with a named reason.
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.
Measured with a blind judge comparing two candidates from the same video,
positions alternated and durations matched. Baseline first: the current
pipeline beats a random window of the same length 82% of the time over 60
comparisons, so selection works and the room is in the remaining 18%.
The judge's stated reasons kept naming something the prompt never asked for:
whether the moment stands on its own. Two versions of that rule were tested.
v1 "must make sense to someone who has seen nothing else"
19 vs 20, 49%, p = 1.000 -> nothing
v2 v1 plus "fix it by moving the START earlier, never by cutting the
ending short"
run 1 27 vs 11, 71%, p = 0.014
run 2 18 vs 13, 58%, p = 0.473 (replication, different seed)
pooled 45 vs 24, 65%, p = 0.015 -> adopted
Read the replication honestly: it did NOT reproduce 71% on its own. Both runs
point the same way and pooled they clear the bar, but the effect is smaller
than the first run suggested. If the true rate were 71%, seeing 18/31 or worse
has p = 0.085, so this is a weaker effect rather than a contradiction. Adopted
because it is free — no fewer clips, no extra call — and revisit it if another
selection change ever needs the same slot.
The gap between v1 and v2 is the useful finding. Asking for self-containment
alone is inert because the model buys context by delaying the start and pays
for it with the payoff, and the two cancel out; v1's losses were literally "B
ends abruptly in mid-sentence" and "A includes the final call to action".
Median overlap between the two selections was 37-42%, which is what makes the
v1 result meaningful: the prompts really do pick different seconds, so 49%
means "no better", not "no different".
Harnesses kept in the reframe-testing skill (selection_ab.py, prompt_ab.py).
Tried first as a fourth option for the classifier, and it does not work: on the
5 corpus clips that have a composited webcam, Gemini answered "screencast" on
all 5, in both runs, and overall accuracy fell from 92% to 85% and 83%.
3 options 44/48 92% screen preserved 17/20 none intact 27/28
4 options c1 41/48 85% 18/20 28/28
4 options c2 40/48 83% 18/20 28/28
Read that carefully: the fourth option did no HARM (zero regressions across the
28 that must not be touched, and it actually preserved the screen on one more).
It simply never got the new class right. Whether a webcam rectangle is present
is a geometric question, and the detector answers it 5 of 5 with no false
positives.
So the split is: Gemini decides what the video is, geometry decides the framing.
If the decision is "screencast" and camera_inset finds a rectangle, that layout
is used; otherwise full width.
Verified end to end: figma -> screencast + inset on 4 scenes; excel (presenter
composited full-screen, no rectangle) -> full width, as before.
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.
Four new layouts, all off by default, plus a picker that decides which one a
video gets.
- SPLIT (split_layout.py): two speakers stacked. The test is COEXISTENCE in the
same frame, not presence measured separately: BlazeFace loses faces in
profile, which is how someone sits while listening, so a presence test
rejects conversations for looking like conversations. Coexistence also
separates a two-shot from a shot/reverse-shot, where stacking would show the
same person twice.
- SCREENCAST / WIDE (screencast_layout.py): content over the presenter, or full
width when the content fills the frame and the presenter is composited on top
of it (stacking there shows the same thing twice).
- ALTERNATE (active_speaker.py): hard cuts to whoever is talking. Mouth activity
must be normalised per speaker against their own resting state; raw magnitude
scales with contrast and lighting and handed one person 90-100% of the scene.
- Punch-in (punch_in.py): a 12% push on the beats, riding the TRACK path by
widening its per-frame crop command from x-only to w/h/x/y.
layout_picker.py chooses between none/screencast/split with one Gemini call per
source video. Measured over the 48-clip corpus against hand-checked labels:
94/92/96% across three runs, 0-1 false positives out of 28, and 2 clips of 48
changing answer between runs. The key is asking for a DECISION between closed
options rather than a measurement: the four previous attempts (Canny, MSER,
coverage, width) all asked for a number and none separated a spreadsheet from a
corner scoreboard.
app.py exposes all of it per job through `layouts` on /api/process. Without that
field the pipeline behaves exactly as before.
83 new tests, 315 green.
La alerta del 23-jul (5/12 jobs, "empty response body") no era la API
fallando: un vídeo subido (stand-up con contenido explícito) devuelve
prompt_feedback.block_reason=PROHIBITED_CONTENT en ~300ms, de forma
determinista — verificado con la transcripción real, y BLOCK_NONE en
safety_settings NO lo levanta (es el filtro de política de Google, no
configurable). Reintentábamos 3 veces algo imposible, el error parecía
un fallo nuestro, y el usuario reintegró el mismo vídeo varias veces
inflando la tasa de fallos.
- gemini_worker: GeminiBlockedError + raise_if_blocked() (block_reason
del prompt y finish_reason SAFETY/PROHIBITED_CONTENT/... del candidato).
- main: _run_gemini_stage falla rápido sin reintentos ante bloqueo (0.5s
vs ~15s) y propaga el motivo real hasta el log del job en ambas vías
(transcript y visión); ya no se convierte en el genérico "no clips".
- alerts: categoría propia "blocked content (user video)" para que la
alerta no se lea como caída del servicio.
Antes, un vídeo sin pista de audio (clip de IA tipo Runway/Sora, gameplay o
grabación de pantalla muda) fallaba porque todo el pipeline se guía por el
transcript. Ahora, al detectar que no hay audio, en vez de fallar se manda el
vídeo a Gemini multimodal (get_visual_clips): lo *mira* y elige los momentos
visualmente más potentes, devolviendo el mismo esquema de clips que la vía por
transcript. El resto del pipeline (corte, reframe vertical, watermark) es igual.
- gemini_worker: schema VisualClipModel/VisualResponse + VISUAL_PROMPT_TEMPLATE.
- main.py: get_visual_clips (sube el vídeo, poll a ACTIVE, análisis, borra el
fichero); el flujo cae a esta vía cuando transcribe_video lanza NoAudioError.
- Sin transcript => sin subtítulos (correcto, no hay habla).
Verificado end-to-end en el contenedor con un vídeo mudo real: Gemini eligió
clip + título + hook por $0.0007, y el pipeline generó el vertical con
watermark. Usa gemini-3.1-flash-lite (el mismo modelo barato).
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).