Commit graph

130 commits

Author SHA1 Message Date
juancarlos.cavero
0bfe27561d Merge PR #70 (manual per-scene reframing) onto current main
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.
2026-08-19 12:01:02 +02:00
Tulio Vianna
b92012d824 feat: manual reframing, per scene
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>
2026-08-18 22:33:52 -03:00
juancarlos.cavero
9c220efddb feat(editor): manual framing override (auto / full frame / track subject)
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.
2026-08-19 01:06:48 +02:00
juancarlos.cavero
4611ca119b fix(generate): scale scoring windows with the requested clip band
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.
2026-08-18 19:41:15 +02:00
juancarlos.cavero
b81125c572 feat(generate): manual clip count and duration controls (discussion #65)
/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.
2026-08-18 19:21:42 +02:00
victorcavero14
d9b15b4328 feat(editor): per-clip EDL backend — recut engine, /edl + /rerender endpoints, MCP tool
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>
2026-08-05 11:03:15 +02:00
juancarlos.cavero
18f2cf4dbd feat(selection): put a floor under the clip count
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.
2026-08-03 11:17:33 +02:00
juancarlos.cavero
094e13c2f9 feat(reframe): optional layouts, and a Gemini-picked layout per video
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.
2026-07-31 13:28:45 +02:00
juancarlos.cavero
be4dd06189 fix(captions): keep apostrophes out of the burned subtitle path
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.
2026-07-29 15:04:50 +02:00
juancarlos.cavero
6c7456cb70 revert(reframe): drop the text-density classifier rule, it measured the wrong thing
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.
2026-07-26 20:59:04 +02:00
juancarlos.cavero
ea78445953 feat(clips): four quality fixes found by auditing real user output
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.
2026-07-26 20:59:04 +02:00
juancarlos.cavero
bdd9e5d53d fix(reframe): ignore lone target jumps so the camera stops swinging
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.
2026-07-26 20:59:04 +02:00
juancarlos.cavero
bedecdc850 fix(files): bound filenames by bytes, not characters
/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".
2026-07-26 20:59:04 +02:00
juancarlos.cavero
f0ecb0d078 fix(reframe): stop the switch cooldown from failing open
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.
2026-07-26 11:44:27 +02:00
juancarlos.cavero
a2237d07d3 feat(clips): ship every clip captioned by default
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.
2026-07-25 17:42:08 +02:00
juancarlos.cavero
98fd35130c fix(clips): deliver 1080x1920 instead of inheriting the source height
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.
2026-07-25 17:09:03 +02:00
juancarlos.cavero
77905a9790 fix(gemini): distinguir bloqueo de contenido de fallo transitorio
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.
2026-07-24 00:37:14 +02:00
juancarlos.cavero
6dd3ef8117 fix(clips): +faststart en el render final para que el navegador reproduzca
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.
2026-07-23 11:11:05 +02:00
juancarlos.cavero
6ea46ca5d2 feat(clips): borrar la metadata heredada del source en los clips finales
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.
2026-07-23 01:34:59 +02:00
juancarlos.cavero
be4510aa43 fix(jobs): reintentar los fallos transitorios en vez de tumbar el job
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).
2026-07-23 00:24:31 +02:00
juancarlos.cavero
ed3bdc45a8 feat(download): intento directo sin proxy antes del fallback de pago (DIRECT_FIRST=1)
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.
2026-07-21 22:35:37 +02:00
juancarlos.cavero
738d52b080 feat(clips): clipear vídeos sin audio con Gemini visión
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).
2026-07-21 21:33:14 +02:00
juancarlos.cavero
b8159990a9 fix(transcribe): manejar vídeos sin audio + alerta de fallos honesta
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).
2026-07-21 21:13:59 +02:00
juancarlos.cavero
3a2741bb33 Revert "fix(watermark): bajar la marca al borde superior del contenido (0.34)"
This reverts commit 177737fdef.
2026-07-21 00:14:12 +02:00
juancarlos.cavero
177737fdef fix(watermark): bajar la marca al borde superior del contenido (0.34)
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.
2026-07-20 22:52:24 +02:00
juancarlos.cavero
e8cfa5fdd7 fix: marca de agua sobre el contenido + resistencia a la pérdida del disco de trabajo
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.
2026-07-20 22:00:28 +02:00
juancarlos.cavero
70260108cc feat(free): watermark lockup arriba-izquierda + modal de upgrade + star-ask durante el render
- 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.
2026-07-20 18:58:00 +02:00
juancarlos.cavero
9fd1cacb0c feat(billing): free plan (20 min/mes sin tarjeta) + retirar trial + opt-in galería UGC
- 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
2026-07-20 00:26:21 +02:00
juancarlos.cavero
36cf6d33b1 fix(reframe): robustify per-scene TRACK/GENERAL strategy
- 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
2026-07-18 03:51:50 +02:00
juancarlos.cavero
101a467c34 feat(reframe): TransNetV2 neural scene detection with PySceneDetect fallback
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.
2026-07-18 03:49:01 +02:00
juancarlos.cavero
dd867f098a feat(reframe): parallel clip processing (CLIP_WORKERS, default 3) with detector lock; fix v2 Fraction fps 2026-07-18 03:08:34 +02:00
juancarlos.cavero
7ff41735a6 feat(reframe): v2 engine — downscaled analysis pass + native ffmpeg render (sendcmd dynamic crop, per-scene segments, stream-copy concat), auto-fallback to v1 2026-07-18 03:05:36 +02:00
juancarlos.cavero
aeca9dbf98 perf(cut): stream-copy remux in passthrough finalize — the cut is already freshly encoded, re-encoding only added time and generation loss 2026-07-18 02:57:39 +02:00
juancarlos.cavero
402e585af7 perf(reframe): downscaled detection (640px), stride 2->4, throttled YOLO fallback, linear resize, quarter-res background blur, per-stage timing 2026-07-18 02:48:53 +02:00
juancarlos.cavero
b9aeaac692 security: never print cookie-file content; scrub credential URLs from worker-appended error log lines 2026-07-18 02:38:16 +02:00
juancarlos.cavero
719d444139 feat: GPU pipeline — Parakeet ASR backend with whisper fallback + NVENC encoder helper
- transcribe_backends.py: parakeet-tdt-0.6b-v3 (onnx-asr, VAD+timestamps) as
  selectable backend (TRANSCRIBE_BACKEND), token->word reconstruction keeping
  the leading-space convention, absolute timestamps, native floats, language
  detection via py3langid, and automatic whisper fallback (errors, empty
  output, or language outside parakeet's 25).
- whisper singleton + ASR GPU semaphore (model stays resident; GPU decodes
  serialized; CPU path behavior unchanged).
- ffmpeg_utils.py: central encoder args (FFMPEG_ENCODER=x264|nvenc|auto with
  cached probe + fallback); migrated the 9 hardcoded libx264 call sites.
- saasshorts now honors WHISPER_* config instead of hardcoded base/cpu/int8.
- Dockerfile: ARG GPU=1 installs CUDA user-space libs (cuBLAS/cuDNN9) +
  onnx-asr/onnxruntime-gpu; LD_LIBRARY_PATH + NVIDIA_DRIVER_CAPABILITIES.
- Validated on prod GPU (RTX 4000 Ada, driver 580): 94s clip transcribed in
  6.5s, word timestamps within ~0.1s of whisper, fallback path exercised.
2026-07-18 01:38:11 +02:00
juancarlos.cavero
b3e44643cc feat: 2-pass Gemini clip pipeline (score windows -> detail shortlist)
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).
2026-07-17 22:32:04 +02:00
juancarlos.cavero
861134f8fe feat: quality gate, output-format selection, whisper small (PR #50)
- 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.
2026-07-17 22:21:46 +02:00
juancarlos.cavero
880efb4d12 fix(gemini): force JSON output + rescue parse for clip detection
gemini-3.1-flash-lite intermittently emitted JSON the manual fence-strip +
json.loads couldn't parse ('Expecting value: line 16 ...'), so clip
detection failed and fell back to whole-video conversion -> 'No metadata
file generated'. Request response_mime_type=application/json so the API
guarantees a JSON body, and on a parse miss rescue the outermost {...}
object before giving up.
2026-07-17 21:26:04 +02:00
juancarlos.cavero
6a3b1e58ab fix(cost): price table with prefix match instead of hardcoded 2.5-flash rates 2026-07-17 21:26:04 +02:00
juancarlos.cavero
e5d88999cf config: default all Gemini text/analysis calls to gemini-3.1-flash-lite
Unified via GEMINI_MODEL (plus per-task overrides GEMINI_MODEL_EDITOR /
GEMINI_MODEL_SAAS / GEMINI_MODEL_THUMBNAIL). The thumbnail image model stays
on gemini-3.1-flash-image-preview — flash-lite cannot generate images.
2026-07-17 21:26:04 +02:00
juancarlos.cavero
f791a74807 quality: CRF 18 on all encode steps, Lanczos resampling on resizes
Re-encode passes (vertical render, hooks, subtitles, AI effects) ran at
CRF 22-23, stacking visible generation loss across steps (#13). Bump all
of them to CRF 18; post-process steps also move preset fast -> medium
(the realtime reframe pipe keeps fast to not slow the streamed encode).
OpenCV resizes now use INTER_LANCZOS4 for sharper scaling.

Adopted from PR #14 review (the good parts, rebased on current main).
2026-07-17 17:11:14 +02:00
juancarlos.cavero
b1113d7a3f fix: Gemini retry with backoff, hook overlay duration, configurable job retention
- 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)
2026-07-17 16:47:38 +02:00
juancarlos.cavero
c32d579675 chore: scrub infra hints from repo
- Remove vendor name (proxy provider) and strategy-revealing comments across
  Dockerfile, docker-compose.cloud.yml, main.py, cloud/metering.py, cloud/alerts.py
- Stop tracking .env.cloud.example (kept local only; added to .gitignore)

Functional references (yt-dlp helper plugin, env var names) necessarily remain.
2026-07-16 18:31:55 +02:00
juancarlos.cavero
d298f69f12 feat(cloud): bake bgutil 720p into image, profile menu, video-URL info, trial→pricing
- Dockerfile: bake bgutil PO-token provider in script mode (no sidecar); 720p verified
- main.py / cloud/metering.py: support BGUTIL_SCRIPT_PATH (script mode) alongside HTTP
- docker-compose.cloud.yml: drop bgutil sidecar; .env.cloud.example documents script mode
- docker-compose.e2e.local.yml: local FRONTEND_URL/ALLOWED_ORIGINS/VITE_API_URL for testing
- AuthContext: new/non-entitled sign-ins land on pricing to start the trial
- ProfileMenu: header account dropdown (email, account & billing, sign out)
- MediaInput: "YouTube URL" → "Video URL" + supported-platforms info popover
2026-07-16 02:07:53 +02:00
juancarlos.cavero
12d423d739 feat: 720p->360p download fallback + SMTP email alerts
- 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.
2026-07-14 14:00:02 +02:00
juancarlos.cavero
ebe876c497 feat: unlock 720p/1080p YouTube downloads (Deno + bgutil PO tokens)
YouTube now forces SABR streaming, capping downloads at 360p without a GVS PO
token. Adds the full recipe (cloud mode only):
- Dockerfile: Deno JS runtime (nsig challenge) + latest yt-dlp[default] nightly
  + bgutil-ytdlp-pot-provider plugin
- docker-compose.cloud.yml: bgutil PO-token sidecar + BGUTIL_BASE_URL
- main.py / metering.py: when BGUTIL_BASE_URL is set, use yt-dlp default clients
  + the bgutil HTTP provider (→ 720p); self-host keeps the conservative fallback

Verified E2E through the container: managed user -> YouTube -> DataImpulse
residential proxy + Deno + bgutil -> real 720p (format 136) download, no 403.
2026-07-14 13:42:07 +02:00
juancarlos.cavero
05578c5456 feat: add hosted paid mode (managed keys, Stripe trial, metering)
Adds an optional cloud/paid mode behind a BILLING_ENABLED flag. With the flag
off the app is byte-identical to today's self-hosted BYOK build (regression-zero).

Backend (cloud/ package, only imported when BILLING_ENABLED):
- Auth: magic link (Resend) + Google OAuth (authlib) + JWT sessions
- Stripe: hosted Checkout with 3-day card trial, Customer Portal, idempotent
  order-safe webhooks; 3 plans (Starter/Creator/Pro) resolved by lookup_key
- Postgres + SQLAlchemy async; atomic minute metering (reserve/commit/release,
  plan->topup FIFO, restart-safe) with sweeper
- Managed keys: Gemini + Upload-Post server-side for entitled users; paid-only
  (BYOK core header ignored on hosted); Upload-Post white-label per-user profiles
- Metering wired into /api/process (probe->reserve->402, priority queue) and
  thumbnail image generation (3 min/batch)
- yt-dlp residential PROXY_URL support + 720p cap for hosted YouTube downloads

Frontend:
- AuthContext, LoginModal, PricingSection (3-day trial), AccountPage, UsageMeter,
  TopUpModal, TrialGate/AdvancedBanner
- Paid-only UI: hide BYOK core inputs, trial prompts per tool
- Included (Clip Generator, YouTube Studio) vs BYOK (AI Shorts/dubbing: fal.ai +
  ElevenLabs) clearly separated; ThumbnailStudio + SaaShortsTab managed-aware
- Landing: free-self-host vs paid-hosted messaging

Verified end-to-end against real Postgres + Stripe test mode.
2026-07-14 13:04:43 +02:00
juancarlos.cavero
771d7da552 fix: Migrate scene detection to PySceneDetect 0.6+ API
VideoManager/SceneManager top-level imports were removed in 0.6+, causing
ImportError on job start. Switched to open_video() and SceneManager.detect_scenes(video=...).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 10:36:50 +02:00
juancarlos.cavero
6a83ebdcd7 fix: Strip '#' from sanitized filenames to prevent broken clip URLs
YouTube titles containing '#' (e.g. hashtags like #shorts) were saved to disk correctly, but the browser parses '#' as a URL fragment, so the frontend could never request the actual file and clips appeared missing. Add '#' to the regex in sanitize_filename().

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 07:05:27 +02:00
juancarlos.cavero
3946c49ad1 added youtube studio 2026-02-20 01:11:27 +01:00
juancarlos.cavero
bf577494b7 Update hooks, fix captions, and ignore uploads 2026-01-23 14:53:57 +01:00
juancarlos.cavero
207f1aa8e3 fix upload video 2025-12-23 09:55:39 +01:00
juancarlos.cavero
9d767897b3 try fix youtube download 2025-12-23 00:10:35 +01:00
juancarlos.cavero
d3ef8ccd26 try fix youtube download 2025-12-22 23:43:18 +01:00
juancarlos.cavero
e8debfa0e8 try fix youtube download 2025-12-22 23:07:42 +01:00
juancarlos.cavero
79d672b918 try fix youtube download 2025-12-22 22:46:39 +01:00
juancarlos.cavero
479ef8a188 try fix youtube download 2025-12-22 22:30:31 +01:00
juancarlos.cavero
c5e2d4818f try fix youtube download 2025-12-22 22:18:15 +01:00
juancarlos.cavero
c381c624be added subtitles 2025-12-22 18:21:17 +01:00
juancarlos.cavero
6913e74f84 fix downloads 2025-12-21 23:38:50 +01:00
juancarlos.cavero
f9b43b3648 improve video preview and added new recognition system MediaPipe lib 2025-12-21 03:09:34 +01:00
juancarlos.cavero
3c92d6ce67 improve video preview 2025-12-21 01:59:15 +01:00
juancarlos.cavero
5be810d606 added video cost to executions 2025-12-21 00:06:59 +01:00
juancarlos.cavero
1121b7940f reafactor readme added instructions and texts 2025-12-20 13:48:22 +01:00
juancarlos.cavero
3ab5404fbe fix yt-dlp error in prod 2025-12-19 22:42:53 +01:00
juancarlos.cavero
6e005d7398 fix yt-dlp error in prod 2025-12-19 22:37:51 +01:00
juancarlos.cavero
ba8a46740f fix yt-dlp error in prod 2025-12-19 21:56:52 +01:00
juancarlos.cavero
8ad6ad0912 fix yt-dlp error in prod 2025-12-19 21:50:48 +01:00
juancarlos.cavero
f724e537cc fix yt-dlp error in prod 2025-12-19 21:46:10 +01:00
juancarlos.cavero
f8f2f476b9 fix yt-dlp error in prod 2025-12-19 21:43:50 +01:00
juancarlos.cavero
51592d0ffa fix yt-dlp error in prod 2025-12-19 21:36:36 +01:00
juancarlos.cavero
99eb1b19ce fix yt-dlp error in prod 2025-12-19 21:30:53 +01:00
juancarlos.cavero
fbe2871ed0 fix yt-dlp error in prod 2025-12-19 21:25:59 +01:00
juancarlos.cavero
e5dd902e8a added upload to social networks and change to fast-whisper 2025-12-19 20:30:13 +01:00
juancarlos.cavero
892383acc3 added generate clips from video with gemini 2025-12-19 16:00:44 +01:00
juancarlos.cavero
a5649a3987 added docker compose, and youtube url process 2025-12-19 13:47:23 +01:00
kamil
adf614ae24 feat: Enhance video processing script with argparse for input/output handling and add progress indicators 2025-08-19 12:52:43 +02:00
kamil
77af869412 feat: Refactor video processing script to use FFmpeg for output and remove moviepy dependency 2025-08-19 12:38:05 +02:00
kamil
946c9f51ba feat: Initial implementation of smart video cropping script 2025-08-19 11:47:53 +02:00