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).
The existing test's words all sat inside the removed ±45s window, so it
passed with or without the change. Add words starting 160s after the clip
ends: the old windowed code drops them, the new contract ships them. Also
assert the words arrive sorted by start time, which the editor's
follow-along binary search depends on.
Turns the clip editor into a three-point editing surface: mark in/out on
the source, send the range to the clip, and scrub the result — with the
timeline honest about which parts of the edit the last render can already
show.
- Chrome: the source track ignored drags entirely. Without preventDefault
the gesture became a text selection and then a native drag, which
swallows every later pointer event and shows the not-allowed cursor.
- The source track's block is draggable (body moves, edges trim) and every
gesture on it scrubs the source monitor, so a cut is chosen against the
picture rather than against numbers.
- Three-point editing: mark in / mark out (i / o) off the monitor's
playhead, then "replace #N" (.) or "insert after #N" (,). Dragging empty
track marks a range instead of silently appending a segment.
- /edl ships the whole source transcript instead of a ±45s window: a cut
can only be extended into words the editor was sent. The panel shows all
of it, follows playback, and seeks the monitor on click.
- Layout: source monitor + its track + transcript | clip preview + its
track | controls. Each track sits under the video it drives.
- The clip timeline works while edited. A cut that only removes material
keeps nothing but frames the last render already produced, so it stays
scrubbable and playable; only material the render never saw is marked
red, and the playhead — now a solid handle — stops at its edge.
Transcript words render in memoised 50-word slices: repainting a couple of
thousand of them costs ~66ms, and timeupdate fires four times a second.
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 residential proxy ran out of traffic (407 TRAFFIC_EXHAUSTED,
19-aug-2026) and every YouTube-URL job failed with only easy-to-miss
one-shot alerts. Now:
- cloud/alerts.py: a background watcher probes the proxy every 30 min
(generate_204, a few bytes of paid traffic). On failure it alerts
immediately, re-alerts every 2 h while the proxy stays down, and sends
a recovery confirmation when it answers again — so exhaustion is caught
even before the next user job fails.
- record_job_outcome: a proxy-classified job failure also opens the
incident, so job-driven detection and the probe share one state.
- app.py: the watcher starts from the lifespan in managed mode.
- tests/test_proxy_watch.py: state machine (first alert, renotify window,
recovery + reset, job-error trigger).
- test_hooks.py: the 6-style contract the frontend mirrors (boxed vs
outline), fixed-bitmap emoji rescaling (_emoji_scale/_measure_width),
and create_hook_image rendering every style (emoji included) with the
unknown-style fallback.
- test_hook_layers.py: _strip_burned_hook walk-back (hooked_/legacy hook_,
missing-file stop), the two-step subtitled->hooked->clean strip /api/hook
replaces through, and _canonical_clip_file resolving hook chains with
newest-derivation-wins.
transcript_words() strips each word, so the remapped transcript handed to
the caption generators lost the leading-space convention the block
collector uses as its word-boundary signal — every recut/reframe with
re-applied captions burned the whole line glued together
("...creesycambiatodo"). Latent since the clip-editor merge; surfaced by
the first caption burn over a recut with real words.
- Meter the re-render: /api/clip/reframe now reserves/commits/releases
minutes exactly like a source-path /rerender — it is the same GPU work,
and it was free and uncapped.
- Re-apply captions by default (reapply_captions param to opt out): every
default clip ships with burned captions, and the reframe silently
returned caption-less files.
- Read metadata.json INSIDE the per-job lock (same _reframe_locked shape
as /rerender): the read-outside/write-inside window let a concurrent
rerender's recipe get clobbered by a stale write.
- Interplay with whole-clip framing: recipe.framing keeps forcing its
layout on the scenes the user did not hand-position (apply_crop_overrides
runs after force_strategy, so per-scene wins where named), and the
recipe is preserved through the reframe instead of being rebuilt bare.
- /rerender clears stale crop_overrides: scene indices only mean anything
against the cut they were made for, and the trim render does not apply
them — leaving them made /scenes reopen showing overrides that would
land on the wrong shots.
- /scenes: entitlement-gated (it cuts, scene-detects and encodes on every
open), serialized per job (stable output names tore under concurrent
opens), 400 on horizontal jobs, real aspect for square jobs, temp_
prefix on preview/thumbnails (kept out of the self-host S3 backup),
faststart + timeout on the preview encode.
- Tests for all of it plus the apply_crop_overrides math the PR described
but did not include (12 new, suite at 502).
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.
/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.
- Per-job asyncio lock around /api/clip/rerender (same pattern as
_restore_locks): concurrent saves raced on the metadata.json
read-modify-write, with the last writer silently reverting the other
clip's recipe and video_url.
- Re-run normalize_segments after snap_to_words + clamp: a segment fully
outside the canonical range used to clamp to an inverted (end < start)
window that passed within_range and died in ffmpeg as a 500; it is now a
clean 400.
- Add METADATA_SCRUB + '-movflags +faststart' to the cut and concat
commands: a fast-path recut IS the delivered file, and without a fronted
moov atom the browser preview hangs (same invariant as every other
final-artifact producer in the repo).
- Unique per-invocation temp names (uuid token) for part/list files and a
uuid suffix on the output name: two concurrent recuts in one job dir no
longer overwrite or delete each other's intermediates, and same-second
saves of one clip no longer collide on the output filename.
- 1800s timeout on ffmpeg runs (matching apply_watermark) so a hung render
can't pin an executor thread and its quota reservation until restart.
Review findings on the MX-gate commit, addressed:
- Rate limits now run BEFORE the DNS work, and the attempt row is
inserted before the MX gate, so rejected junk-domain floods count
toward both limits instead of getting unlimited free DNS lookups.
- Existing accounts bypass the MX gate: it protects sign-up only, so a
domain whose MX later matches the disposable list can't lock an owner
out of their account.
- RFC 5321 implicit MX now also checks AAAA (IPv6-only mail domains
were falsely rejected).
- Error-derived verdicts cache for 60s instead of 1h: a transient
NXDOMAIN no longer pins a lockout, a resolver blip no longer
whitelists a domain for an hour.
- One shared resolver with an LRU record cache (was: new resolver +
resolv.conf read per lookup); verdict cache evicts FIFO instead of
full clear.
- MX blocklist moved to disposable_mx.txt, same loader and ops workflow
as disposable_domains.txt (the two lists were already drifting).
- Both rate-limit counts merged into one FILTER query; distinct 429
message for the per-IP limit (shared-NAT lockouts diagnosable).
- Index on (request_ip, created_at) + 30-day token purge in the
retention sweeper. NOTE: schema is create_all-only, prod needs:
CREATE INDEX IF NOT EXISTS ix_magic_ip_created
ON magic_link_tokens (request_ip, created_at);
Bot sign-ups with rotating temp-mail domains (onldm.net -> 10minutemail's
SMTP) and nonexistent addresses were bouncing every magic link back into
the support inbox and hurting sender reputation.
- email_policy.mx_verdict(): resolve the domain's MX (A fallback per RFC
5321) and reject when nothing can receive mail or when the MX target
belongs to known disposable-mail infrastructure - catches the rotating
front domains the static blocklist can't keep up with. Cached per
domain, fails open on resolver trouble.
- auth: per-IP rate limit on magic-link requests (bots rotate addresses,
not IPs).
- blocklist: add onldm.net; pin dnspython (already transitive via
email-validator).
New mcp_ui module holds the template: preview each 9:16 clip inline,
select the keepers and publish them via publish_clip from inside the
conversation. One template, three data paths, because the ecosystem has
not converged: baked-in JSON on the per-call embedded resource, the
ChatGPT Apps window.openai bridge, and the MCP Apps ready/render-data
postMessage handshake. Titles are JSON-escaped so a clip name cannot
break out of the script tag, and the template is fully inline because
host CSPs block external fetches.
The server grows resources/list, resources/read and the resources
capability; list_clips declares the template under both _meta.ui
.resourceUri and openai/outputTemplate. Non-UI clients see the same
text and structured content as before; the extra content entry is
spec-tolerated. The unknown-method protocol test moves off
resources/list, which is now a real method.
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>
Agents don't forget to come back; humans do. Make the whole pipeline
drivable without the dashboard:
- API keys (osk_...): sha256-stored tokens minted from the account page.
get_current_user_optional resolves them like a session, so metering,
entitlement, priority and job ownership apply to agents with zero
endpoint changes. Key management refuses API-key auth (a leaked key
cannot mint replacements).
- MCP server at /mcp: stateless Streamable-HTTP JSON-RPC, no SDK
dependency. Six tools (process_video, get_job_status, list_clips,
get_quota, add_subtitles, publish_clip) that call back into this same
app in-process via ASGITransport with the caller's auth headers, so
MCP can never drift from REST behavior. Cloud requires a key;
self-host stays BYOK-open.
- Completion webhooks: webhook_url (+ optional HMAC webhook_secret) on
/api/process, SSRF-checked at submit AND delivery, fired once after
the R2 archive so payloads carry durable links, survives redeploys
via the resume manifest.
- Dashboard: API keys card in the account page (create once-shown key,
list, revoke).
- Tests pin BILLING_ENABLED=0 in conftest so the suite no longer
depends on the developer's personal .env.
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.
AUTO_LAYOUT=shadow runs the picker, prints one greppable line per job, and
applies nothing. The render is what it would have been with the picker off,
verified end to end on the production image: excel.mp4 decides "screencast",
logs it, and still renders with every layout module disabled.
Everything measured about this picker was measured on 48 YouTube clips chosen
by hand. What users actually upload is a different distribution nobody has
looked at, and the honest way to find out is to ask the question on real jobs
without letting the answer reach the output. A week of this costs 0.002 USD and
~2s per video and cannot damage a clip somebody paid for.
Log line is deliberately not routed through cloud/analytics.py: that path is
opt-in and host-scoped, and a shadow run has to work on any deployment,
self-hosted included.
[layout-shadow] decision=screencast would_enable=screencast_layout duration=121s
Three horizontal bands was the obvious shape and it is geometrically wrong.
A 1080x640 band is LANDSCAPE, so filling one from a 1080-tall source needs a
1551px-wide crop; on a 1920 frame holding three people that reaches both
neighbours, and the rendered bands each showed two faces. Clamping the crop to
the space a person owns then produced 328x194, upscaled 3.3x into a blurry
close-up of a nose. Both were rendered and looked at before this changed.
A 2x2 grid has PORTRAIT tiles (540x960), which ask for a tall narrow crop, the
shape a person actually occupies. Three people take three cells and the fourth
holds the wide shot, letterboxed rather than cropped, which doubles as context
for who else is in the room.
The neighbour clamp stays: it is what stops a crop reaching the next person
whenever the tile aspect would otherwise allow it.
Verified on a synthetic wide shot built from three corpus talking heads (the
first attempt at that was wrong too: hstacking three 640x360 tiles and scaling
to 1080 tall stretched every face 3x and the detector found nothing).
Generalises stacking past two: three 1080x640 bands, or a 2x2 grid of 540x960.
Same criteria as SPLIT (coexistence in the same frame, minimum size,
separation) because the failure modes are the same.
Every tile the same size on purpose: a bigger tile claims that person matters
more, and the layout has no way to know that.
The separation test moves from horizontal gap to distance between centres.
Measured on a real recording: two webcams on the same side of the frame, 18px
apart horizontally and 545px vertically. Judging by horizontal gap alone called
them the same person and threw the scene away.
Added overlap suppression (IoU) before counting heads. It is a guard rather
than a fix for a measured bug: on the corpus no pair of boxes exceeds the
threshold, so today it changes no decision.
NOT VALIDATED against real material: of eight panel downloads three failed and
none of the other five is a wide shot of 3-4 people.
One source: the whole screen (a game, a desktop) with the person composited
into a corner. It is how OBS records and how any stream VOD looks, and it is
the case screencast_layout got wrong: there the speaker band is a large crop
taken AROUND the face, which on a full-screen source means more screen. On the
measured Excel clip the output showed the same spreadsheet twice, whole and
enlarged.
What is needed is the inset's own rectangle, and finding it has three traps,
each of which cost an iteration:
- The inset does not touch two edges. YOLO returns an upper-body box that stops
at the chest, so a webcam pinned to the right side measured 18% clear of the
bottom and the "corner" filter threw it away. The test that works is subject
SMALL and OFF-CENTRE.
- A presenter standing in front of a screen passes any geometric filter. What
separates them is that a composited inset DOES NOT MOVE: 3-11px between
samples versus 316px for a person. With a plain min-max range the filter was
too brittle (one lost sample killed three good detections), so it clusters
around the median and requires a majority.
- The height cannot be scaled from the detection: for a webcam of about 325x180
YOLO returned 246x86, and growing that shape still cut the head off. It is
derived from the width assuming 16:9 and pinned to the edge the inset touches.
The filtergraph keeps the screen at full width (the HUD and the edges are the
content) and the camera band takes its height from the inset's real aspect:
forcing a fixed ratio stretched faces 12% horizontally.
Verified on 10 clips: finds the 4 with a composited camera and rejects the 6
without one (presenter in front of a screen, talking heads, presenter
composited full-screen). The miss is a 720p clip whose webcam is too small for
either detector.
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.
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.
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.
Captions are table stakes for short-form — a clip without them barely works on
any platform — but every burn cost 2 minutes, 10% of the free monthly quota,
roughly what generating the clip cost in the first place. People skipped them:
only 9% of delivered clips had captions in the 25-jul-2026 prod audit (35
subtitle jobs against 380 process jobs).
The charge never matched the work. The normal path reads the transcript already
stored in metadata.json and runs one short FFmpeg pass — measured at 4s on CPU
for a 12s clip, 1-2s on the GPU. Charging 120s of quota for that is ~30x the
compute, and it was invisible in the UI, so users were drained without being
told. The endpoint is already gated by require_managed_entitlement, so the
charge was never what bounded abuse.
Dubbed clips keep the charge: subtitling them re-runs Whisper over the
translated audio, which is real work. The rule lives in cloud.config next to
the constant so it stays testable without importing app.
Also short-circuit reserve_managed_action on a zero-minute action rather than
writing a 0-minute ledger row on every call.
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.
A declined card left the account in a state with no way out. `past_due` grants
no minutes, so the metering layer resolved the user to the free plan — which
meant /api/me reported status=null, the account page swapped "Manage billing"
for "Upgrade" (hiding the only button that fixes a card), and the checkout guard
then rejected the upgrade with a 409 that every call site swallowed into a
generic "Could not start checkout." Silently free, unwarned, unable to pay.
Found on 25-jul-2026 in prod: 14 subscriptions in this state, all first charges
that failed when the (now retired) 3-day trial ended. The trial is gone, but the
trap is not — a renewal failure or an abandoned 3DS payment reproduces it.
- metering: split `_subscription_row` (raw) from `_active_subscription`
(entitling), and expose both on the balance. Entitlement logic is unchanged.
- /api/me: report status/interval from a row needing attention when no
subscription entitles, plus `has_billing_account` to route the portal button.
- checkout: drop `incomplete` from the blocking states. Stripe collects nothing
on it and expires it within 24h, so blocking only stopped the user's retry.
Give past_due/unpaid a message that names the problem and the fix.
- account page: explain the failed payment inline with a link to the portal
instead of showing a bare "past_due" chip, and keep the portal reachable for
any Stripe relationship, live or broken.
- api client: throw a typed ApiError carrying the server's detail so callers
stop replacing real, actionable messages with generic copy.
Verified against a real DB: past_due stays blocked but visible and fixable,
incomplete can retry, canceled is silent and can subscribe again.
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.
La imagen Docker solo traía DejaVu: todas las fuentes que ofrece el modal
(Verdana, Arial, Impact, Helvetica, Georgia) caían en silencio al fallback
de fontconfig, así que el burn salía siempre con la misma letra por mucho
que el usuario cambiara los ajustes — mientras el preview del navegador,
que usa las fuentes del sistema del usuario, prometía otra cosa. Reportado
en la issue #57 como "captions coming out wrong / settings set to default".
- Dockerfile: fontconfig + fonts-liberation (equivalentes métricos de
Arial/Helvetica/Verdana y Georgia) y registro de las fuentes del repo.
- fonts/Anton-Regular.ttf (OFL): sustituta estándar de Impact.
- fonts/openshorts-fontmap.conf: alias fontconfig nombre-de-UI -> fuente real.
- subtitles.py: fontsdir en los filtros subtitles/ass para que libass vea
las fuentes del repo aunque el fontconfig del sistema esté pelado.
Verificado en contenedor: fc-match Impact->Anton, Verdana->Liberation Sans,
Georgia->Liberation Serif, y dos burns reales muestran letra distinta por
elección (antes idénticas). El backend de /api/subtitle ya aplicaba bien
los estilos en pasadas repetidas (walk-back correcto, sin doble subtítulo).
El CI instala solo pytest+pillow+httpx+pydantic+sqlalchemy. test_gemini_retry
importa main (cv2/torch) y test_job_error_text importa app (dotenv/fastapi),
que faltan → ModuleNotFoundError en la colección. importorskip los salta en
CI y los corre entero en el contenedor/local donde sí están las deps.
Verificado en un venv réplica del CI: 125 passed, 2 skipped.
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).
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).
El free ya no exige Google: cualquier cuenta Google o de email permanente
entra. Para que no sea un grifo de minutos gratis:
- Bloqueo de dominios desechables/temp-mail en el registro por email
(cloud/disposable_domains.txt, 155 dominios: los clásicos temp-mail + los
vistos en nuestra propia DB). Refrescable desde el proyecto upstream.
- Normalización de alias: gmail dots/+tags y +tags de otros proveedores se
colapsan a una sola cuenta canónica, para que foo+1@ / f.oo@ no minten
cuentas infinitas. Aplicado en magic-link y en Google OAuth.
- free_plan_eligible: Google siempre; email solo si el dominio no es
desechable (defensa en profundidad además del bloqueo en registro).
- Popup de bienvenida ahora sale una vez por navegador en el primer registro
(Google o email), no solo a los no-entitled; el botón free arranca directo
sin forzar Google.
Verificado: registro con mailinator/luckfeed -> 400; gmail -> 200. 115 tests
(9 nuevos de email_policy).
- 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
- log_view.py: whitelist-based cloud log view — transcription percentage,
clip counters, errors; no file paths, model names or pipeline internals.
Self-host (BILLING off) and DEBUG_LOGS keep the full raw output.
- transcribe_backends: emit '🎙️ Transcribing… NN% (Xs)' at 25% steps from
both parakeet and whisper paths.
- dashboard: profile selector shows connected networks instead of the
auto-generated os_<hash> id.
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).
Ported from PR #50 (Themegaindex) onto current main, adapted to the
billing-mode app.py and the Lumen dashboard:
- subtitles.py: karaoke ASS generation (word-level highlight, glow/pop/box
effects, dim/uppercase), whisper continuation-word merging, env-configurable
whisper model, ASS/font input sanitization, faststart
- editor.py + edit_builder.py: Auto-Edit v2 — Gemini returns a structured
edit-decision list and the FFmpeg filter is built deterministically with
hard caps (no raw filter strings from the LLM), 2s dry-run + one
self-repair round, caption-safe mode blocks zooms on subtitled clips
- app.py: /api/subtitle karaoke fields + re-subtitle prefix walk-back
(fixes double subtitles), has_captions passed to Auto-Edit
- hooks.py: emoji rendering (color-emoji font with strip fallback),
char-level hard wrap, unique temp PNGs, ffmpeg timeouts; keeps the
duration/enable overlay from b1113d7
- translate.py: exponential-backoff retries for transient ElevenLabs errors
- dashboard: 11 caption presets in SubtitleModal; karaoke burns server-side
- tests/: 50 pytest tests; .github/workflows/ci.yml runs them + fe build
Encode settings kept at CRF 18 (medium for post-process steps) per f791a74.
Co-authored-by: Themegaindex <themegaindex@users.noreply.github.com>