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.
- 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).
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.
Fixes#69. The subtitle modal lets the user edit the caption text, but the
edits only traveled through the in-browser Remotion path; the FFmpeg path
(taken by every karaoke style and by any clip with server burns, i.e. all
clips with default captions) sent style params only, so the server
regenerated from the stored transcript and silently discarded the edits.
/api/subtitle now accepts an optional 'words' list (clip-relative ms, the
same shape the /transcript endpoint serves) and builds a synthetic
transcript from it, so both the SRT and karaoke ASS generators burn the
edited words verbatim. Words get Whisper's leading-space convention so the
block collector keeps their boundaries. The modal sends them only when the
text actually differs, and never on bulk apply-to-all (edits are per-clip).
Verified live: an edited 5-word line burned exactly as typed, correctly
grouped into blocks.
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.
/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.
Every new free user's first job fired a Telegram message, which at current
signup volume is pure noise. Clip-activity notifications now fire only for
paid users' jobs; the activation signal lives in analytics, not the ops chat.
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.
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.
Upload-Post's `post_mode` defaults to DIRECT_POST, so a clip went straight to
the user's TikTok feed. MEDIA_UPLOAD lands it in their drafts to finish in
TikTok's own editor instead.
Drafts are the right default for an automated pipeline: nothing reaches an
audience without the account owner seeing it, and covers, sounds and trending
hashtags are chosen inside TikTok anyway — the parts that decide whether a clip
travels are exactly the parts this cannot do from the outside.
Applied to both paths that can target TikTok (the clip publisher and the
SaaS-shorts publisher) through one constant, so they cannot drift apart.
TIKTOK_POST_MODE=DIRECT_POST restores publishing without a code change.
The UI now says so before the button is pressed, in both publishers, and leads
with the upside rather than the caveat. Without it the change reads as a bug:
someone expecting a live post, finding nothing on their profile, and concluding
the upload failed. The notice also tells them a TikTok notification is coming,
which the Upload-Post docs confirm for MEDIA_UPLOAD ("users will receive an
inbox notification"), so they know where to look.
The browser reports the funnel, but not what decides whether this product
retains: on 26-jul-2026, 491 of the 564 users who ever processed a video did it
exactly once. Every clip-quality fix that shipped that day — 1080p delivery,
captions by default, loudness normalisation — was aimed at that 87%, and
nothing in the stack could measure whether it moved.
Client-side cannot answer it. A render finishes minutes later, often after the
tab is gone, and ad-blockers eat a share of the rest. So the backend now emits
ClipsDelivered / JobFailed with the user's profileId and a `job_index` — the
count of process jobs that user has run. Counting distinct users at index 1
versus index >= 2, before and after today, answers the question directly.
Failures carry the same reason classification the Telegram alerts use, so the
"did it break or did they just not come back" split is visible too.
Fire-and-forget throughout: no config means a silent no-op (the normal state
for self-hosted), every send is a background task, and every failure is
swallowed. Analytics must never slow down or break a job.
Needs OPENPANEL_CLIENT_ID and OPENPANEL_CLIENT_SECRET in the environment — a
WRITE client, which is a different credential from the read/root client the MCP
needs. Verified against the live instance: the write path returns 200 and the
module no-ops cleanly when unconfigured.
Two bugs in the "your N clips will be deleted tomorrow" email.
The button pointed at {frontend_url}/dashboard, a route that has never existed:
the app is a single-page app routed entirely through the hash, and #app is what
opens it. Until today /dashboard fell through to the SPA fallback and quietly
showed the marketing landing, so the link looked like it worked. Now that
unknown paths return a real 404 it fails visibly. Both this and the clips-ready
email now link to /#app; the clips-ready one was passing the bare frontend URL,
which showed the landing page to anyone whose browser had not already set the
skip-landing flag.
The duplicate send is worse. De-duplication was `_warned_video_ids`, a set in
process memory, and the warning window is a full day while the sweep runs every
six hours. Any API restart inside that window re-armed the warning for everyone
already told. That is exactly what happened today: the 06:00 warning went out,
three deploys restarted the API (frontend and API share this repo, so the SEO
pushes redeployed both), the container came up at 12:36, and the sweeper's first
run six hours later at 18:36 mailed the same clips again.
Warnings are now recorded in clip_expiry_warnings, keyed by clip id, written
before the send. A new table rather than a column because the schema bootstrap
is create_all, which creates missing tables but never ALTERs one — same reason
SignupAttribution is its own table. The FK cascades from user_videos, so rows
disappear when purge_free_expired deletes the clip and no cleanup pass is needed.
Recording before sending is deliberate: a duplicate email is the failure being
fixed, while a warning row for a mail that then failed to send costs that user
one notice.
No backfill. Clips already warned about have no row yet, so the current cohort
gets one more warning after this deploys and none after that. Backfilling the
window would also silence the first warning for anyone who entered it since the
last sweep, and a missed deletion notice costs the user their clips, while a
duplicate only costs them an email.
Verified against a real Postgres: create_all builds the table, the primary key
rejects a second row for the same clip, the cascade removes warnings when the
clip is deleted, and warn_free_expiring sends exactly one email across two
sweeps plus a module reload standing in for a restart (which is what used to
produce the second email).
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.
Clips now ship captioned, and the modal could only restyle — there was no way
back to a clean clip, so anyone who didn't want captions was stuck with them.
Adds POST /api/subtitle/remove, which points the clip at its un-captioned
original. No re-encode and no quota: the pipeline already keeps the clean file
next to the derived subtitled_<ts>_ one, so removing is choosing the other file.
It reuses the burn path's walk-back, so it undoes any number of restyles, and
running it twice is a no-op.
Verified end to end: auto-caption, restyle (burning from the clean file rather
than stacking a second layer), remove, and remove again.
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.
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).
Stripe — dos huecos que faltaban:
- invoice.paid no disparaba nada: las renovaciones mensuales entraban en
silencio. Ahora 💵 'Payment received: $X' en cada cobro real (primera compra
Y renovación), con el importe y el motivo (new subscription / renewal).
- El aviso de top-up ahora incluye el importe cobrado.
- Helper _money() para formatear cents+currency ('$59.00 USD').
Clips (opción 1, alta señal para no ahogar el canal cuando crezca el free):
- _notify_clip_activity avisa por Telegram SOLO en el primer clip de un
usuario (activación) o en clips de usuarios de pago. Nada de un ping por
cada clip free. Incluye email, plan, título y nº de clips.
Verificado enviando los formatos reales al Telegram del admin.
- Quitado el tope de 3 jobs/día por cuenta y 5 por IP en el plan free: la
cuota de 20 min/mes es el único límite (el ledger ya capa el coste real y el
tope diario confundía). Verificado que un free NO puede pasar de 20 min ni
con reservas concurrentes: 10 reservas simultáneas de 5min -> solo 4
concedidas, ledger clavado en 20, el lock por usuario serializa.
- Registro por email ya no tira a la página de pricing (rayaba): aterriza en
la app y sale un popup PlanChoiceModal para elegir plan — free (via Google,
por el gate anti-abuso) o los de pago inline con su precio.
- Eliminado 'start free trial' / '3 days free' de la cabecera y de settings;
ahora dicen 'choose a plan'.
- vite.config: target del proxy configurable con VITE_PROXY_TARGET para dev
en el host contra localhost:8000 sin CORS.
Probado en dev local: el popup aparece al aterrizar sin plan y desde el botón
'choose a plan', con free + starter/creator/pro.
Un job vive solo en memoria, así que matar el contenedor a mitad de proceso
lo perdía: al usuario se le cortaba el clip. Ahora al encolar se escribe un
manifiesto mínimo (.resume.json: cmd, prioridad, user, reserva, watermark —
sin secretos, el env se reconstruye al reanudar) y en el arranque se
re-encolan los que se quedaron a medias, tras _recover_jobs_from_disk (los que
ya habían terminado de generar clips se recuperan como completados, no se
reanudan).
- Tope MAX_RESUME_ATTEMPTS=2: un vídeo que reviente el worker no puede meter
al servicio en un bucle; se rinde y se refunda por la vía de huérfanos.
- La reserva de minutos del job reanudado se conserva (no se refunda como
huérfana) para que la liquide el run reanudado.
- El manifiesto se borra en cualquier estado terminal (éxito o fallo real);
solo sobrevive si el contenedor murió a mitad, que es cuando queremos
reanudar.
Verificado en el contenedor: reanuda conservando reserva, no re-ejecuta
completados, se rinde con envenenados. Reconstruye env con la clave gestionada
sin volcar secretos a disco.
Con volumen persistente el barrido por antigüedad (1h) acota la edad de lo
guardado pero no su tamaño: una tanda de vídeos largos puede llenar el disco
dentro de la misma ventana. Se añaden topes duros (OUTPUT_MAX_GB=25,
UPLOADS_MAX_GB=15) que borran lo más antiguo hasta bajar del límite; los clips
están archivados en R2 y se rehidratan solos, así que solo cuesta una descarga.
Además el barrido saltaba a borrar output/thumbnails, que respalda un mount de
StaticFiles: borrarlo dejaba /thumbnails devolviendo 500 hasta el siguiente
arranque.
Y fuera el badge '3-Day Trial' de la landing, que ya no aplica.
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.
- 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
- New projects table (job_id, metadata_r2_key, state JSONB) — created via create_all
- archive_job also uploads the metadata JSON (transcript) and upserts the
Project row + user_videos (no more duplicate rows on re-archive)
- archive_clip_edit re-archives a clip after each server-side edit, keeping
only the pristine original + current version per clip in R2
- fix /api/edit: persist new video_url in job result + metadata.json (the
other edit endpoints already did)
- POST /api/projects/{job_id}/restore re-hydrates R2 files into output/{job_id}
(per-job lock, temp-dir download, .owner sidecar, idempotent fast path)
- GET /api/projects + PUT /api/projects/{job_id}/state (debounced Remotion
layer sync from the frontend)
- History tab groups clips by project with a reopen button; App restores
jobId/results/project state; ResultCard seeds serverVideoFile/activeLayers
from the restored state and reports changes upward
- 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.
Extend the sensitive-log filter so cloud users don't see which model powers
the app (gemini/flash), token/cost lines, or the 2-pass window/shortlist
internals — just clean transcription + clip progress. DEBUG_LOGS still shows
everything locally.
Cloud users don't need the YouTube downloader internals, proxy usage or
cookie handling in the System Logs panel — just analysis + rendering
progress. Drop lines matching those keywords from the client view even when
emoji-prefixed. DEBUG_LOGS (local dev) still shows everything.
- Quality gate: quality_probe.py probes the offered YouTube resolution before
starting; /api/process returns needs_confirmation below QUALITY_GATE_MIN_HEIGHT
(720p) and the UI shows a 'process anyway' modal that resends with
force_low_quality. Fail-open on any probe error. URL sources only.
- Output format: MediaInput picks 9:16 / 1:1 / 16:9; threaded through
/api/process -> main.py --format. render_clip() routes vertical/square to the
reframe (aspect_ratio param) and horizontal to a passthrough (keep landscape).
- Whisper: main pipeline defaults to 'small' (better non-English) with
vad_filter + no cross-segment conditioning; env-overridable.
The live-analysis preview above the logs used a blob URL for uploaded
sources, which dies on page reload — so a recovered upload session showed an
empty preview (YouTube-URL jobs were fine, their URL persists).
- GET /api/source/{job_id} streams the job's original upload (FileResponse,
unauthenticated like /videos, UUID job_id is the capability).
- ProcessingAnimation: new 'server' media type -> <video src> from the backend.
- Session save persists uploads as { type:'server', payload:/api/source/id }
instead of null, so the recovered preview plays the real source.
User.id is a uuid.UUID; live jobs store that object, but jobs recovered from
the .owner sidecar store its string form. 'UUID(x) != str(x)' is always True,
so after a restart the legitimate owner got 404 on /status, /transcript,
/hook etc. for their own recovered jobs. Compare str(user.id) != str(owner).
83b0649 hides raw yt-dlp/ffmpeg/debug spew from paid users. In local dev you
run with BILLING_ENABLED to test paid features but still want the debug logs,
so DEBUG_LOGS=true bypasses the filter regardless of billing.
- app.py: GET /api/jobs/{job_id}/download-all bundles every clip's current
file into one ZIP (stored, not deflated — already compressed), streamed
via FileResponse and cleaned up after send; owner-guarded in cloud mode.
- App.jsx: 'subtitle all' opens the SubtitleModal in bulk mode and applies
the chosen style to every clip sequentially (progress in the button),
then refreshes results so each card shows its subtitled file. 'download
all' fetches the ZIP and triggers a browser download.
- SubtitleModal: bulkCount prop -> 'apply to N clips' label.
Previously a single look (white card, black serif). Add a style parameter
end to end:
- hooks.py: HOOK_STYLES table drives box fill / text color / optional text
outline; box-less 'outline' styles (caption/MrBeast look) use a stroke.
- HookOverlay.tsx: same looks mirrored so the Remotion preview and the
browser burn match the server FFmpeg output.
- HookModal: visual style picker; ResultCard + /api/hook thread style through.
Note on t=0: the server FFmpeg burn shows the hook immediately (enable
between t,0,dur); the Remotion preview fades it in per the entrance
animation, so at exactly 0:00 the preview is mid-fade (pick 'None' for an
instant-on preview).
Jobs live in memory, so any backend restart orphaned finished clips still on
disk (frontend keeps the job_id but every endpoint 404s with Job not found).
On startup, rebuild a completed record per output dir with a metadata JSON.
Managed jobs persist their owner in a .owner sidecar so the multi-tenant
guard survives the restart; BYOK jobs recover unowned, as before.
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>
- alerts.py: _looks_like_proxy_error only matches genuine proxy/download-stage
signatures (407, ProxyError, tunnel failed, 402/out-of-credits) instead of a
bare "proxy"/"credit"/"balance" substring — a job that failed in processing (or
a video titled with one of those words) no longer fires a false "out of credits"
alert. Real proxy failures still alert.
- app.py: _scrub_secrets() masks user:pass in any URL before a subprocess line is
printed or stored, so the residential proxy URL yt-dlp echoes in verbose debug
never lands in the server console or job log.
- app.py: _visible_logs() — cloud (BILLING on) surfaces only the pipeline's own
friendly progress lines (emoji-prefixed + worker start/finish) and hides the raw
yt-dlp/ffmpeg/debug spew from paying users; self-host still shows everything.
- Retry transient Gemini errors (503/429/500) up to 3x with exponential
backoff before falling back to whole-video conversion (#27)
- Thread the hook Duration slider through /api/hook down to the FFmpeg
overlay enable filter so hooks can end after N seconds (#2)
- Read JOB_RETENTION_SECONDS from env so self-hosters can keep finished
jobs longer than the 1h default (#46)
Security fixes on the hosted/paid surface (all no-op in self-host / BYOK):
- upload path traversal: basename() client filenames in /api/process,
/api/thumbnail/upload, /api/thumbnail/analyze fallback, /api/thumbnail/generate
(face/bg + session_id) so "../" can't escape UPLOAD_DIR
- SSRF: saasshorts subpage scraper now follow_redirects=False + assert_public_url
per hop (was open to 302 -> 169.254.169.254 metadata)
- metering: reserve+commit/release on /api/render, /api/subtitle, /api/hook and a
fixed guard cost on /api/thumbnail/upload transcription (were entitlement-gated
but unmetered -> unlimited off-quota compute)
- entitlement: SaaSShorts generate/actor-options/actor-upload now require a plan
in cloud; /api/edit ignores body api_key in cloud (no gate/meter bypass)
- multi-tenant IDOR: stamp user_id on thumbnail_sessions/saas_jobs and reject
non-owners (404) across status/mutation/publish/post endpoints
- DoS: bounded/streamed reads on actor-upload and thumbnail uploads
- retry_job_id routed through _safe_under
Frontend: raw fetch -> apiFetch on the now-gated/owner-checked endpoints so the
bearer token attaches.
License: cloud/ is now source-available under the OpenShorts Commercial License
(self-host/personal use allowed; no competing hosted service). Core stays MIT.
- dashboard/Dockerfile: multi-stage — 'dev' (Vite HMR for local compose) and
'prod' (npm build -> nginx static serving, SPA fallback). Prod is the default
target so Coolify builds the static app; VITE_API_URL is a build arg.
- dashboard/nginx.conf: SPA routing + asset caching + basic security headers.
- docker-compose.yml: local frontend targets the dev stage.
- app.py: skip the redundant AWS S3 upload in cloud mode (R2 is the store now);
add a /health liveness endpoint for uptime checks.
Verified: prod image serves index.html + deep-link fallback (200).
- cloud/storage.py: R2 (S3-compatible) client — upload, presigned view/download
URLs, delete-by-prefix.
- cloud/videos.py: archive a completed managed job's clips to R2 under
users/<uid>/<job>/, GET /api/history (private signed links), and a retention
sweeper that deletes a user's videos 7 days after their subscription ends.
- models.py: user_videos table (created via create_all).
- app.py: archive clips to R2 on managed-job completion.
- billing.py: email the admin the moment a subscriber hits cancel.
- Frontend: History tab (library grid with per-video view + download).
R2 bucket 'openshorts-videos' + scoped API token created; end-to-end verified:
archive -> presigned GET (200) -> purge after grace -> object 404.
- main.py / metering.py: try the HD (bgutil/720p) strategy first, fall back to
the conservative (360p) clients on any failure, so a YouTube/yt-dlp change
degrades gracefully instead of failing the whole job.
- cloud/alerts.py: in-memory tracking of managed-job outcomes; emails the admin
(ADMIN_EMAIL) when a proxy/credit error appears or when many jobs fail in a
row, with a 1h per-alert cooldown. Wired into run_job_wrapper.
- Email switched from Resend to SMTP (cloud/emails.py) for magic link + alerts
(Namecheap Private Email). Config via SMTP_* / EMAIL_FROM / ADMIN_EMAIL in the
mounted .env (kept out of compose so the password's $/* aren't mangled).
SMTP send verified from host and from the backend container.
- MediaInput shows a checkbox the user must tick before Generate enables
- Frontend sends acknowledged=true alongside URL/file payload
- /api/process rejects with 400 if attestation is missing, and records
IP/UA/timestamp/source on the job for legal record-keeping
Defensive posture for the public deployment: shifts responsibility to
the user via an explicit affirmative act, even without login.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>