On a stacked two-shot the seam between the halves is the one place the
text covers nobody (OpusClip does the same), so every word event inside a
SPLIT stretch is anchored mid-frame with an inline \an5; other layouts keep
the style's alignment, and the text moves with the cut.
The render records which stretches use which layout in a <clip>.layout.json
sidecar (layout_ranges.py). The job pipeline, rerender and manual reframe
copy it into the clip's metadata as layout_ranges, so /api/subtitle finds it
on a restyle too. auto_caption_clip reads the sidecar when not told, which
is how recut hands it over.
Only the ASS path can do this; SRT burns keep one alignment per file.
Checked on the 45-clip corpus with SPLIT on: 45/45 render, 0 caption
errors, 42 with no split at all, and the 3 that split are real two-shots.
The vision path only fired when the source had no audio track. A nursery
rhyme or a dashcam drive has audio, so it went through transcription, came
back as one segment, built one scoring window and Gemini returned no clips:
three failed jobs on 25-aug-2026, one user twice. Below 8 words or 5 words
per minute the transcript cannot drive selection, so route it like a silent
video (vision, no captions). Thresholds env-overridable.
A job interrupted by a container restart is re-enqueued from its resume
manifest and re-run from scratch in the same output directory. Transcription
is the slow, paid stage that had already finished, so main.py now leaves it
there as .transcript_checkpoint.json and the re-run picks it up (same shape
and validation as --transcript). Removed when the job completes so a later
run in a reused directory never inherits it.
Verified locally: run killed after transcription, re-run in the same
directory logged 'Reusing the transcript from the interrupted run' and
delivered both clips.
At every scene boundary the tracker kept the previous shot's speaker (sticky
bonus + 30-frame cooldown returning None) and the cameraman's jump damping
held the new face for JUMP_CONFIRM_FRAMES detections, so the frame started
on the old subject and slid across at pan speed. Seen on a two-camera
podcast as a headless torso for 1.5s after each cut.
Reset both at the cut, force a detection on the cut frame, and snap the
camera to the first target accepted in the new shot. SCENE_CUT_RESET=0
restores the old behaviour.
Measured on the 45-clip corpus plus the reported clip (123 TRACK scenes):
first-frame framing error 97 -> 34 px, frames to settle 18.9 -> 3.8,
in-scene reversals unchanged (0.02/s), camera travel 12 -> 7 px/s.
A job in flight published every clip as the clean reframe name, guessed by the
status poller. The hook and the captions live in derived files
(hooked_<ts>_<clean>, subtitled_<ts>_hooked_<ts>_<clean>), and only when the
WHOLE job finished did the result get rebuilt through _canonical_clip_file and
resolve to them. So a six-clip job showed clip 1 hook-less for the five clips
after it, which reads as the hook feature being broken.
main.py now prints CLIP_READY <index> <filename> at the end of each clip's
chain, after the caption step and carrying its result, so the name is the file
that will actually be delivered. app.py consumes the marker the way it already
consumes PROXY_BYTES: intercepted in enqueue_output, never shown as a log line.
The poller now serves only announced clips. That also closes the older hazard
in the code it replaces, whose own comment admitted it was guessing: presence
on disk was treated as done, so a clip could be served while ffmpeg was still
writing it. A clip whose marker never arrives (it failed) stays hidden until
the job ends and the result is rebuilt from disk, as before.
"canción" has two Unicode spellings: a precomposed ó, or an o followed by a
combining acute. yt-dlp hands over titles in either, and sanitize_filename let
the decomposed form through into the clip file, the R2 key and the URL path.
Measured against prod on 24-ago-2026, on a clip whose title carried the
combining form: a <video> element loads it fine, and fetch() of the very same
URL comes back 503, while curl gets 206 with the identical headers. So the
download button, which fetches, was broken on effectively every Spanish title,
and playback hid it.
Normalising at sanitize_filename fixes the whole chain at its source: one name
for both spellings, and a no-op for the ASCII names that already worked. Clips
already archived keep their decomposed name and still play.
reframe_v2 built its filtergraph as sendcmd=f='<abs path>' with the path
interpolated raw. On Windows tempfile.mkdtemp() returns C:\Users\..., and
the drive colon terminates the filter option, so ffmpeg exits non-zero and
every TRACK scene silently falls back to the v1 Python frame loop. GENERAL
and SPLIT hide the bug because only the TRACK branch emits a sendcmd.
subtitles._escape_ffmpeg_filter_value already solved exactly this for the
ass/fontsdir filter three modules away, so this moves it to ffmpeg_utils as
escape_filter_value() and uses it in both places. subtitles keeps its
wrapper and its docstring; behaviour there is unchanged (verified equal
output on absolute, relative and space/comma paths).
Measured on a 12s 1280x720 clip with one face, Windows 10 + ffmpeg 9:
before 53.5s "Reframe v2 failed (CalledProcessError ...)" -> v1 loop
after 30.8s v2 native, same framing
Also: `-o <dir>` crashed with PermissionError [WinError 5] because
--skip-analysis passed the directory straight through as the output
filename and it reached os.remove(). --output is documented as "directory
or file", so derive the filename when it names a directory, and guard the
stale-file sweep with isfile() so a directory can never be handed to
os.remove().
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QiYkHKB7Tp7X6NdnEutda2
Issue #68: publishing a video to YouTube from the Studio now offers
'create clips from this video'. /api/process accepts a
thumbnail_session_id, hardlinks the session's source under the job's
name (so /api/source, the clip editor and retention treat it like a
normal upload) and forwards the session's transcript via a new
main.py --transcript flag, so the pipeline skips a second Whisper pass.
Any problem with the forwarded transcript (missing file, no segments,
silent source) falls back to transcribing normally, and empty
transcripts are not forwarded at all. Contract pinned by six endpoint
tests plus a fallback case; verified end to end locally against the
running app (speech video: 'Reusing precomputed transcript (4
segments)' in the job log).
Adds YOLO_MODEL_PATH (default unchanged) and bakes the weights into
/tmp/Ultralytics in the image so a volume mounted over /app can't shadow
them, plus removes the redundant top-level scenedetect import.
Adapted from #47 by @kayceepeece, minus the CPU-only torch pin which
would conflict with the GPU production build.
The v1 frame loop has been the rarely-taken fallback since the v2 engine
shipped in July; give it the same shape as the rest of the file while it
sticks around as the REFRAME_ENGINE=v1 rollback:
- get_video_resolution releases its capture in a finally block
- staging files named .v1video/.v1audio next to the final output, cleaned
with one loop instead of three inline conditionals
- the rawvideo pipe spells out demuxer options (-video_size/-framerate/
pipe:0) instead of the short aliases, and drops the redundant -vcodec
- encoder/reader names instead of ffmpeg_process/cap; single -c copy mux
command built by list concatenation
- dead script_start_time assignment removed
Behavior is unchanged: verified end to end with REFRAME_ENGINE=v1 on a 6s
clip (180 frames, 1080x1920 h264+aac, faststart, scrubbed metadata).
New STATIC_PROXY_URLS env (comma-separated): dedicated ISP IPs with
unlimited traffic, tried after the direct attempt and before the per-GB
paid proxy. With it unset the chain is byte-identical to before.
- plan_download_attempts: pure, unit-tested attempt ordering. Cheapest
bandwidth first: direct -> statics (rotated per job, uncapped 1080p,
free bytes) -> paid HD (720p cost cap) -> fallback via paid.
- The 720p cap and the PROXY_BYTES monthly counter now apply ONLY to
attempts that actually bill per GB — static downloads come in at 1080p
and don't count toward the cost alert.
- alerts.py watcher generalized to multiple targets: the static pool
(down = ingest silently moves to per-GB billing, nag with a cost hint)
and the paid proxy (down = ingest at risk), each with its own
down/nag/recovered incident state.
Context: the server's IPv4 is hard-banned by YouTube (19-aug-2026), so
DIRECT_FIRST serves nothing and every download was going through
DataImpulse at $1/GB capped to 720p. Verified from prod: all 3 Decodo
dedicated IPs pass the bot-check with cookies+bgutil at 1080p.
The auto-hook was burned into the canonical clip in place, so editing the
hook stacked a second overlay on top of the first. Hooks now follow the
exact derivation pattern captions use:
- main.py: auto_hook_clip writes hooked_<ts>_<clean>.mp4 next to the clean
canonical instead of mutating it; captions burn on top of the hooked file
(subtitled_<ts>_hooked_<ts>_<clean>). Watermark moves BEFORE the hook so
the branding lives in the canonical and survives hook replacement.
- app.py: _strip_burned_hook walks hooked_/legacy hook_ prefixes back like
_strip_burned_captions; /api/hook strips captions AND the old hook before
burning, so a new hook always REPLACES the previous one. New remove flag
strips the hook entirely (captions re-applied, no metering). Burned hook
recorded/cleared in clip metadata (auto_hook key) and returned as
burned_hook. _canonical_clip_file resolves hooked_*/hook_* derivations.
- cloud/videos.py: archive the hooked_ intermediate of a captioned hook so
restored projects keep the walk-back chain editable.
- ResultCard: stripBurns knows hooked_<ts>_ (the Remotion preview now
composes over the truly clean clip — no more stacked preview), burned
hook tracked in state, remove handler wired to the modal.
- HookModal: warning now says replace, plus a 'remove hook from clip'
action when one is burned.
Auto-hook (opt-in per job, dashboard default ON):
- /api/process accepts auto_hook + auto_hook_style; absent means off, so
API/MCP/webhook callers keep byte-identical output.
- main.py auto_hook_clip burns each clip's viral_hook_text (Gemini already
produced it, it was only used to pre-fill the modal) into the canonical
clip in place — after reframe, under watermark and captions — so every
derived-name convention (subtitled_/recut_ walk-backs, R2 archive,
restore) keeps working untouched. Fail-open like auto_caption_clip.
- Burned hook recorded as clip.auto_hook in metadata; the hook modal warns
before stacking a second one.
- MediaInput: 'auto hook titles' toggle + style select in advanced options,
persisted in localStorage.
Emoji that actually render:
- Gemini prompt now asks for 1-2 emojis in viral_hook_text.
- Dockerfile installs fonts-noto-color-emoji — without it prod silently
stripped every emoji (no candidate font existed in the image).
- hooks.py supports fixed-bitmap color fonts (NotoColorEmoji only loads at
its 109px strike; Apple Color Emoji at 160): glyphs render at native size
and are Lanczos-rescaled to the text size instead of being treated as
unavailable. macOS system font added for local dev.
Editor polish:
- HookModal persists last style/position/size/entrance (always reset to
classic before, which read as the picker being broken).
- Remotion preview positions aligned to hooks.py (top 20%, bottom 70%).
- Warning when a bottom hook will overlap burned/preview captions.
- Entrance-animation control greyed out with a note when the clip
re-renders on the server, where the hook is static.
Conflicts were the parallel override parameters: render_clip /
process_video_to_vertical / reframe_v2.render / perform_recut now carry
BOTH force_strategy (whole-clip framing, main) and crop_overrides
(per-scene manual framing, PR #70). The v1-fallback safety net now also
raises for force_strategy, which had the same silent-revert hole the PR
fixed for crop_overrides.
The reframe engine picks the crop automatically and is right most of the
time. When it is wrong it is badly wrong, and there was no way to say
"no, frame it here".
The unit is the SCENE, not the clip. A podcast cuts between a fixed close
camera and a fixed wide one, and the right crop differs per camera; scene
boundaries already are those camera changes. Scenes the user never touches
keep the automatic camera, so correcting one bad shot cannot spoil the
shots the tracker got right.
Backend:
- reframe_v2.apply_crop_overrides() replaces a scene's slice of the camera
trajectory with a constant and forces it to TRACK, so a scene the
classifier had sent to GENERAL comes back to a vertical crop. It runs
after every automatic pass, including the ALTERNATE writes, so a manual
choice always wins.
- A scene can also be split by hand: the override writes straight into
`splits`, which means the user can stack a scene the detector never
proposed, with no dependency on SPLIT_LAYOUT being enabled.
- GET /api/clip/{job}/{i}/scenes returns the scenes with a frame from the
UNCROPPED cut plus a light preview with audio, and suggests a centre from
the largest face in each shot.
- POST /api/clip/reframe re-renders with the clip's cut untouched. It is
deliberately separate from /api/clip/rerender: a scene index only means
something against a given cut, so letting framing ride along with a trim
save would move every override onto the wrong shot.
- render_clip raises instead of falling back to the v1 engine when manual
framing is present, since v1 ignores it and would silently return an
automatically framed clip.
Frontend:
- ReframeEditor lists the scenes, each with the source frame, a draggable
9:16 window, and a play button that plays that scene from the preview so
the user can hear who is talking before choosing.
- Saved overrides are loaded when the editor reopens. Without that the next
save would discard every earlier adjustment, because a re-render rebuilds
from source using only what it receives.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The scene classifier only counts faces, so a screencast-style video with a
presenter in frame gets TRACK and the crop eats the slide (the SCREENCAST/
WIDE detectors sit behind the opt-in layouts=auto flag). The clip editor now
has a framing selector that pins every scene's layout: 'full' renders the
whole source frame (WIDE: no side-crop, blurred bands), 'track' forces the
subject-tracking crop, 'auto' returns to the classifier.
Plumbed as force_strategy through reframe_v2.render -> render_clip ->
perform_recut -> /api/clip/rerender (and the recut_clip MCP tool). A
non-auto choice always re-reframes from the retained source (409 without
it) and persists in the clip's recipe, so later plain trims inherit the
look instead of silently reverting; an explicit 'auto' resets it.
Verified live: framing=full on a TRACK-cropped clip re-rendered with the
full frame visible edge to edge (125s source path), and the editor reopens
with the persisted choice preselected.
The detail prompt keeps clips inside their candidate window, so the default
90s scoring windows silently capped user-requested long clips (a 60-90s band
barely fit, anything above did not). Windows now grow to 1.5x the requested
max length; the default band keeps the exact old behavior.
/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.
Every clip now exposes its recipe (which source segments it was cut from)
via GET /api/clip/{job}/{i}/edl, and POST /api/clip/rerender re-renders it
from an edited segment list: fast path recuts from the already-reframed
canonical file, source path re-reframes from the retained source
(--keep-original now passed for URL jobs). Captions/subtitles/transcript
remap piecewise through recut.virtual_transcript for multi-segment clips.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
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.
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.
Auto-captions have been silently failing in prod on any video whose title
contains an apostrophe — constant in English ("Earth's", "Don't"). The clip
that surfaced it: "Inside Earth's Most Mysterious Temple". Four failures in a
two-hour window, each swallowed by the guard that ships the clip uncaptioned,
so nothing alerted.
The .ass path is interpolated INTO a filter string (-vf ass='...'), where a
literal apostrophe closes the quote and truncates the filter. /api/subtitle has
always been safe because it names its file subs_<i>_<ts>.ass; shipping captions
by default introduced a name built from the clip stem, which carries the title.
So the .ass name drops the stem. It also gains a uuid: clips render in parallel
under CLIP_WORKERS, and a bare timestamp would let two clips in the same second
write the same file and burn each other's captions. The OUTPUT name keeps the
stem, and must — the modal's walk-back and _canonical_clip_file reconstruct the
clean original from it — but that one is only ever an argv element, never
inside a filter.
Smarter escaping was tried first and is worse, so the reasoning is recorded in
_escape_ffmpeg_filter_value rather than left for someone to rediscover: the
shell idiom "'\''" is not understood by ffmpeg's filtergraph parser, which
dropped the apostrophe AND swallowed the following option, resolving
ass='…Earth'\''s.ass':fontsdir='…' to a filename of "…Earths.ass:fontsdir=…".
An apostrophe in a filter path cannot be escaped; it has to be absent.
Verified in the prod image against the failing filename: the burn now produces
a 540x960 clip where it previously errored.
The rule was meant to route a screencast that happens to contain one face to
GENERAL, so its headlines don't get cropped mid-word. Testing it against the
case it exists for showed it does the opposite of what it claims.
Measured on a constructed talking-head-beside-a-chart, and the same shot without
the panels:
with text panels density 0.012 -> TRACK (rule missed it)
same shot, no panels density 0.029 -> TRACK (scored HIGHER)
Canny counts edges, and a flat panel of text has far fewer of them than ordinary
scene detail like foliage or clothing — so the signal measures visual busyness,
not text. The threshold was wrong too: across 151 frames of real footage the
density ran median 0.007 / p90 0.018 / max 0.068, so 0.085 could never fire.
The underlying problem is real and still open. A fix needs an actual text
detector (MSER or EAST) validated against clips that contain the failure mode —
the current corpus is highlights and vlogs and has almost none, which is why the
broad run only reclassified 2 of 438 scenes and told us nothing.
Keeping a heuristic that has been shown not to work would only add risk, so it
comes out and the finding stays as a comment where the next attempt will read it.
Captions must always be the LAST layer. Editing or hooking a clip that already
had them burned in produced `edited_subtitled_<...>`, and the next subtitle pass
stacked a second caption layer on top of the first — visibly doubled and
unreadable in a real user clip found in prod today. /api/edit and /api/hook now
derive from the clean file and put captions back afterwards, so a restyle always
has an un-captioned base to burn onto. The latent bug predates auto-captions but
shipping them by default made it the normal path. The walk-back is now one
helper instead of being open-coded in the subtitle endpoint.
Loudness was uncontrolled. A clip inherited whatever its source was mastered at,
measured across real delivered clips from -13.8 LUFS on a loud upload down to
-28 on a quiet talk, while TikTok/Reels/Shorts all normalise playback to around
-14 — so the quiet ones just sound thin in the feed. loudnorm at the clip cut,
where the audio is already being encoded, so it costs nothing. Verified to pull
both extremes to target: -29.7 -> -13.7 and -10.1 -> -13.5. AUDIO_NORMALIZE=0.
The GENERAL layout wasted the frame. Fitting a 16:9 source to full width left
it 608px tall in a 1920 frame: 32% content, 68% blurred filler. Now scaled by
height to 42%, trimming the overflow. Deliberately conservative — GENERAL is
chosen for groups and landscapes, exactly where cropping the sides cuts someone
out, so 0.55 was tried and rejected for throwing away 42% of the width. 0.42
keeps ~76%. GENERAL_CONTENT_HEIGHT_RATIO=0.32 restores the old behaviour.
The TRACK/GENERAL classifier only counted faces, so a screencast that happened
to contain one face was cropped to it — real prod clips came out with headlines
cut mid-word and unreadable. A cheap Canny pass over the side thirds (the part a
9:16 crop discards), with face boxes blanked first, now routes text-dense scenes
to GENERAL instead. GRAPHIC_DENSITY_THRESHOLD=1.0 disables it.
The camera swung between subjects because a single detection could teleport the
target anywhere and the frame followed immediately. On real user footage pulled
from prod, 22% of target updates moved further than the entire safe zone.
A move that large is far more often a detector error — a second face, a false
positive, a box snapping to a different body part — than a person who actually
moved that far. It now has to repeat JUMP_CONFIRM_FRAMES (3) consecutive
detections before the camera commits; a wrong reading disappears on the next
detection and never moves the frame. Contradictory outliers cannot confirm each
other, so a detector flapping between two wrong places holds the frame still.
Measured over 262s of TRACK footage across 12 chunks of two real user videos,
counting only reversals INSIDE a scene (a cut is supposed to re-frame, so
scoring scene-change snaps would measure the feature, not the bug):
confirm=1 0.41 rev/s 91 px/s —
confirm=2 0.20 rev/s 76 px/s -51%
confirm=3 0.13 rev/s 60 px/s -69%
confirm=4 0.10 rev/s 48 px/s -76%
3 is the knee: 4 buys another 7 points of reversals for a third more latency.
Honest about the downside — per scene, travel gets calmer in 54 of 84 and is
unchanged in 23, but 7 get BUSIER (worst 59 -> 108px/s, and one dead-still scene
starts drifting at 31px/s), because committing later can leave the camera
further to travel. Net strongly positive, not universally so.
Tried and rejected: a 3s switch cooldown, which bought only -19% on its own and
is precisely what would make a two-person interview stop following the
conversation. JUMP_CONFIRM_FRAMES=1 restores the old behaviour without a deploy.
Methodology note: variants are compared by recording the detections once and
replaying them through the cameraman, so every variant sees identical input
rather than a fresh run of a non-deterministic detector.
/api/hook has been returning 500 in prod on any clip whose video title is
non-Latin: OSError 36, "File name too long". sanitize_filename() capped the
title at 100 CHARACTERS, but filesystems cap a name at 255 BYTES, and one
Bengali or Arabic character costs three — so a title was already ~300 bytes
before the pipeline decorated it.
Every derived name stacks on that stem: "_clip_10.mp4", "subtitled_<ts>_",
"temp_hook_<hex8>_", "autosubs_<ts>_.ass". Shipping captions by default added
one more layer, which is what pushed the borderline cases over and surfaced it.
- sanitize_filename now trims to MAX_TITLE_BYTES (120) via truncate_bytes(),
which never splits a multi-byte character. 120 leaves room for every
decoration stacked and still lands well under 255.
- The hook overlay stopped embedding the full source name: its uuid already
guarantees uniqueness, so the name rides along only as a debugging hint and
is trimmed to 80 bytes.
Deliberately NOT trimmed: the auto-caption output, which must stay exactly
"subtitled_<ts>_<clip filename>" because the subtitle modal's walk-back and
_canonical_clip_file both reconstruct the clean original from it. Length is
bounded upstream instead; a legacy clip that predates the budget raises
OSError 36, which the existing guard turns into "ship it uncaptioned".
The cooldown that keeps the camera from swinging between subjects only applied
when the active speaker happened to be detected in the current frame. If they
were missing — a blink, a head turn, one motion-blurred frame — the guard fell
through and switched immediately, so it only ever held when it wasn't needed.
Measured on a 12s clip: 3 of 7 target switches jumped the cooldown this way.
Now the cooldown holds regardless: it returns the active speaker's box when
visible and None otherwise, and the caller only calls update_target() on a
truthy box, so the camera keeps its target and finishes whatever move it was
making. The hold stays bounded by the cooldown, so a subject who really did
leave the shot is still released once the window expires.
Measured on the same clip: cooldown bypasses 3 -> 0, target switches 7 -> 5.
This does NOT by itself calm the camera down — reversals stayed at 13 over 12s.
The dominant driver is target jitter (p90 of 496px per update, 15 of 67 updates
alone exceeding the 101px safe zone) plus faces losing their identity on
re-detection, both of which need tuning against representative footage rather
than a screen recording.
Captions are what make a short readable with the sound off, and 91% of
delivered clips had none (35 subtitle jobs against 380 process jobs in the
25-jul-2026 prod audit) because they were opt-in behind a modal. Now every clip
comes out captioned and the modal becomes a re-style, not a discovery.
The look was picked by rendering four candidates on a real clip and comparing
them: white Anton uppercase, yellow active word, heavy black outline, gentle
pop. Yellow because it is the one colour that almost never occurs in footage,
so the active word reads instantly on any background. The base text stays fully
opaque — dimming it, which several caption tools do, tested worse over bright
scenes. Captured in AUTO_CAPTION_STYLE so there is one place to change it.
Two fixes fell out of rendering it for real:
- Captions sat at MarginV=25 (8.7% of frame height), underneath TikTok's and
Reels' own bottom chrome. Raised to a documented SAFE_MARGIN_V of ~15%, now
a parameter rather than a hardcoded literal.
- The pop effect scaled the active word 75->112, wide enough that any frame
caught mid-animation read as a sizing bug. Softened to 90->108.
Wiring follows the convention already used by /api/subtitle: the captioned file
is written as subtitled_<ts>_<clip>.mp4 next to the untouched original, so
re-styling from the modal replaces the captions instead of burning a second
layer over them (its existing walk-back resolves this unchanged). The places
that rebuild the canonical clip name from disk — restore after a restart, the
project reopen, the download bundle — now resolve through _canonical_clip_file
so a redeploy cannot silently serve the uncaptioned version. R2 uploads follow
video_url, so the durable library gets the captioned clip too.
Captions are applied after the watermark, never before, and any failure is
swallowed: a caption problem must not cost the user a clip they already paid
for. Silent videos have no transcript and are skipped. AUTO_CAPTIONS=0 is the
rollback lever.
Verified end to end in the container: burn produces the derived file, the app
resolves to it, the modal walks back to the clean original, silent input ships
uncaptioned, the kill switch works, and the newest styling wins.
An audit of 45 real user clips pulled from R2 on 25-jul-2026 found 86% below
1080 wide, 80% of them exactly 406x720 — well under what TikTok, Reels and
Shorts expect, so the platforms re-encode an already soft image. Two causes,
one on top of the other:
- The download capped format selection at 720p whenever PROXY_URL was set. The
cap exists to control paid-proxy bandwidth, but it was decided once from
`_proxy` rather than per attempt, so it also capped the DIRECT attempt — the
one that costs nothing and, with DIRECT_FIRST=1, serves most downloads. It is
now chosen per attempt: direct pulls up to 1080p, proxied stays at 720p.
- The reframe set out_h = orig_h, so a 720p source could only ever produce a
406x720 crop. `delivery_size()` now upscales to a 1080-wide floor and leaves
anything already above it untouched — a 4K source still delivers 1216x2160,
so no one loses resolution they supplied.
Applied to the v1 fallback too: an emergency render is still the clip the user
posts. Its frame loop already resizes to the target dims, so only the target
changed.
Crop geometry is unaffected — SmoothedCameraman derives the crop from the source
dimensions and never reads the output pair, which the call site now documents.
Verified end to end: a 1280x720 source that previously rendered 406x720 now
renders 1080x1920, correct aspect, no distortion.
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.
El concat de reframe_v2 (el camino real de prod) y el merge de
process_video_to_vertical escribían el moov atom al final del MP4. Sin
faststart el <video> del navegador no puede empezar a reproducir hasta
descargar el fichero entero → el preview se queda con el spinner eterno.
Descargar el clip funcionaba (por eso pasó desapercibido), pero
previsualizarlo en la app no.
Verificado con ffprobe: antes moov al 98%, ahora al frente. Bug
preexistente, no introducido por el scrub de metadata.
Los clips arrastraban el handler de stream "ISO Media file produced by
Google Inc." del vídeo original de YouTube: ffmpeg copia la metadata del
input por defecto, así que sobrevivía a todos los reencodes y acababa
publicado en la red social. Rastro innecesario del origen.
Se añade METADATA_SCRUB en ffmpeg_utils y se aplica en cada productor de
fichero final: el concat de reframe_v2 (el camino real de prod), el merge
de process_video_to_vertical, el passthrough horizontal, el watermark, y
los reencodes de subtítulos/hooks/editor.
Detalle que costó verificar: -map_metadata -1 global NO basta — el
handler_name a nivel de stream sobrevive a un -c copy. Hacen falta los
especificadores por stream (-map_metadata:s:v -1 -map_metadata:s:a -1);
son inofensivos cuando falta un stream. Verificado con ffprobe sobre un
clip real del pipeline completo: sin rastro de Google.
No promete boost de alcance (eso lo decide el fingerprint de contenido,
no los tags del fichero); es higiene y quitar el rastro del origen.
Tres jobs de prod murieron el 22-jul porque Gemini contestó 200 con el
cuerpo vacío. Eso revienta al parsear, no al llamar, así que se escapaba
del bucle de reintentos: un parpadeo de la API bastaba para perder el job.
El mismo payload funciona 5 de 5 al reintentarlo.
- gemini: el parseo pasa a estar dentro del bucle, y la respuesta vacía o
no parseable cuenta como error transitorio.
- descarga: reintento del 403 de YouTube, que casi siempre viene de que el
proxy residencial rota la IP de salida entre la extracción y la descarga
(3 de 62 descargas en 24h).
- se elimina el fallback de reframear el vídeo entero: no escribía
metadata.json, así que app.py marcaba el job como fallido igualmente
después de gastar GPU en un render que nadie llegaba a ver.
- alertas: la clasificación lee ahora las líneas de error del log en vez
de las 10 últimas, que eran ruido de progreso y hacían culpar al
subsistema equivocado (un parpadeo de Gemini se reportó como ffmpeg).
Validado en prod 21-jul: con cookies + PO token bgutil la IP del servidor
descarga directa de YouTube (~110 MiB/s); sin cookies YouTube la bloquea
tras la primera petición. El proxy residencial queda como fallback y
PROXY_BYTES solo se emite cuando el intento ganador usó el proxy.
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).
El error del admin ('High download failure rate... rebuild image') era
engañoso: el fallo real no era descarga sino transcripción de un vídeo SUBIDO
sin pista de audio (un clip generado por IA, Gen-4 de Runway). faster-whisper
revienta dentro de libav con 'tuple index out of range' cuando el fichero no
tiene audio.
- transcribe_media detecta la ausencia de pista de audio (ffprobe) ANTES de
transcribir y lanza NoAudioError con mensaje claro; main.py lo convierte en
un fallo user-facing ('NO_AUDIO: este vídeo no tiene audio...') en vez de un
traceback. Verificado en contenedor con vídeo con/sin audio.
- La alerta de tasa de fallos ya no culpa siempre a la descarga: clasifica el
último error (proxy / youtube download / no audio / transcription / gemini /
ffmpeg) y lo pone en el título.
123 tests (nuevos: vídeo mudo + clasificación de fallos).
Al 40% quedaba demasiado dentro de la imagen; el usuario la quiere más arriba,
a un tercio de la altura. 0.34 es el punto donde empieza el contenido en un
16:9 letterboxed: la marca se apoya justo en el borde de la imagen, se lee
arriba pero ya pisa footage real, así que recortarla sigue costando cortar el
vídeo.
1. Watermark al 40% de la altura en vez de arriba del todo: ahí caía en la
banda negra/desenfocada del 9:16, espacio muerto que se recorta sin tocar
la imagen. Un 16:9 letterboxed ocupa del 34% al 66%, así que ahora quitarla
obliga a cortar vídeo de verdad.
2. OUTPUT_DIR no es durable en prod (cada redeploy lo vacía), y los endpoints
que leen ficheros del job devolvían 404 en proyectos que el usuario sigue
viendo en su biblioteca: transcript, download-all, subtítulos, hooks,
efectos, doblaje y publicación. Nuevo _ensure_job_files() que rehidrata
desde R2 bajo demanda reutilizando el flujo de /restore. Se deja fuera el
polling de /api/status para no machacar R2.
3. download-all no encontraba ningún clip en proyectos restaurados: el
metadata.json en disco nunca lleva video_url (se inyecta solo en memoria),
así que derivaba nombres vacíos. Ahora usa el registro en memoria (que
además refleja ediciones subtitled_/hook_) y cae al nombre canónico.
Verificado en local con docker compose contra R2 real: transcript 200 con 103
palabras y ZIP de 6,2 MB con los 4 clips, sobre un proyecto sin ficheros en
disco.
- La marca pasa de texto abajo-centrado a un lockup blanco (símbolo +
OpenShorts) superpuesto arriba a la izquierda: el borde inferior es lo
que se recorta al repostear, así que ahí la marca se quitaba gratis.
PNG pre-renderizado en assets/ para no depender de fuentes del contenedor.
- WatermarkModal: aviso único al descargar en plan free (descargar igual /
upgrade / no volver a mostrar), al estilo del de OpusClip.
- StarBanner también durante la generación, que es donde el usuario tiene
minutos muertos esperando.
- Plan free resuelto en metering (sin fila Stripe): 20 min/mes para cuentas
Google, período sintético de mes natural con reset automático
- TRIAL_DAYS=0 para nuevos checkouts; trials en curso grandfathered
- Watermark drawtext en clips free (pasada única post-render, sobrevive
subtítulos/hooks); thumbnails IA solo de pago
- Anti-abuso: 3 jobs/día por cuenta, 5 por IP, rate-limit de probes,
contador mensual de GB de proxy con alerta Telegram a 100 GB
- Clips free caducan a 7 días (purge_free_expired); purge_expired respeta
a cancelados que ahora son free
- Galería UGC pública pasa a opt-in (share_to_gallery, antes publicaba
producto+guion de todos los usuarios sin permiso)
- Emails: clips listos (con star-ask) y sin-minutos (cooldown 24h)
- Frontend: card Free en pricing, copy sin trial (landing/legal/gates),
StarBanner en resultados y TopUpModal, upsell de watermark
- Sample 5 evenly-spread frames clamped inside the scene (old start+5/end-5
fell outside scenes shorter than ~10 frames)
- Skip near-black frames so fades stop dragging single-person scenes to GENERAL
- Hysteresis: a sub-2s scene flanked by agreeing neighbors adopts their
strategy — each TRACK<->GENERAL flip is a full layout change on screen
New scene_detection module: TransNetV2 (small 3D-CNN, runs on 48x27 frames)
as the primary shot-boundary detector — far more accurate than the fixed
ContentDetector threshold on fast motion, flashes and gradual transitions.
Adds a min-scene-length merge (SCENE_MIN_SEC, default 1s) to stop camera-snap
bursts. Legacy PySceneDetect path is preserved untouched as automatic
fallback and selectable via SCENE_ENGINE=pyscenedetect.