Commit graph

16 commits

Author SHA1 Message Date
victormanuel.caverogracia
a4c92cac2c perf(pipeline): halve a job's CPU with byte-identical clips
Reverts 1d3d20c (NVDEC decode + quarter-size blur): it changed the
delivered pixels (SSIM 0.998-0.9997, not identical), and clips must not
change. Replaces it with two fixes that leave every clip byte-identical.

- Parakeet's onnxruntime pool threads no longer spin
  (transcribe_backends.parakeet_session_options). While the GPU did the
  work they burned ~160 CPU-s per 9 min of audio, the biggest CPU cost of
  a job. The VAD keeps load_vad's defaults: any options there make
  onnx_asr drop its default providers and a word changes.
- analyze_scenes_strategy and split_layout read their sampled frames in
  one forward pass (frame_sampler.read_at) instead of a seek per sample,
  which re-decoded the GOP every time: 89 -> 6 CPU-s for one clip's
  samples, same frames.

Bench on balrog, 3 Carlos Gracia videos (2.5/9/17 min, 15 clips), Gemini
decisions recorded once and replayed: every clip identical to the old
code (decoded-frame MD5s + audio). Serial stage profile of the 9 min
video: 629 -> 273 CPU-s per job; Python side 332 -> 57 CPU-s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:40:22 +02:00
victormanuel.caverogracia
1d3d20c77c perf(render): decode on the GPU and blur the backdrop at quarter size
At peak (8 jobs x 3 clip workers) balrog sat at load ~100 on 20 threads
while the RTX 4000's decoder stayed at 0%: NVENC only took the encode, and
decoding plus the filter graphs ran on the CPU, starving the Coolify builds
and every other service on the box.

- ffmpeg_utils.video_decode_args(): -hwaccel cuda before the video input
  whenever the encode is on nvenc (FFMPEG_HWDECODE=0 turns it off). Used in
  the cut, the reframe v2 segments, watermark, hook and caption passes.
- ffmpeg_utils.blurred_backdrop(): the GENERAL and INSET blurred fill blurs
  at a quarter of the output size and scales up, instead of a full-size
  gblur on 1080x1920.

Measured in the prod container on a real 1080p source, 10 s GENERAL
segment: ~16-18 s of CPU before, ~5-7 s after, SSIM 0.994 against the old
output. All four hwaccel passes checked end to end on the prod GPU.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 13:33:30 +02:00
juancarlos.cavero
e2df4c1f0c feat(captions): put subtitles on the seam of SPLIT scenes
On a stacked two-shot the seam between the halves is the one place the
text covers nobody (OpusClip does the same), so every word event inside a
SPLIT stretch is anchored mid-frame with an inline \an5; other layouts keep
the style's alignment, and the text moves with the cut.

The render records which stretches use which layout in a <clip>.layout.json
sidecar (layout_ranges.py). The job pipeline, rerender and manual reframe
copy it into the clip's metadata as layout_ranges, so /api/subtitle finds it
on a restyle too. auto_caption_clip reads the sidecar when not told, which
is how recut hands it over.

Only the ASS path can do this; SRT burns keep one alignment per file.

Checked on the 45-clip corpus with SPLIT on: 45/45 render, 0 caption
errors, 42 with no split at all, and the 3 that split are real two-shots.
2026-08-25 14:35:46 +02:00
Chaakh
88a53b6f7e fix: escape the sendcmd path so TRACK reframing works on Windows
reframe_v2 built its filtergraph as sendcmd=f='<abs path>' with the path
interpolated raw. On Windows tempfile.mkdtemp() returns C:\Users\..., and
the drive colon terminates the filter option, so ffmpeg exits non-zero and
every TRACK scene silently falls back to the v1 Python frame loop. GENERAL
and SPLIT hide the bug because only the TRACK branch emits a sendcmd.

subtitles._escape_ffmpeg_filter_value already solved exactly this for the
ass/fontsdir filter three modules away, so this moves it to ffmpeg_utils as
escape_filter_value() and uses it in both places. subtitles keeps its
wrapper and its docstring; behaviour there is unchanged (verified equal
output on absolute, relative and space/comma paths).

Measured on a 12s 1280x720 clip with one face, Windows 10 + ffmpeg 9:
  before  53.5s  "Reframe v2 failed (CalledProcessError ...)" -> v1 loop
  after   30.8s  v2 native, same framing

Also: `-o <dir>` crashed with PermissionError [WinError 5] because
--skip-analysis passed the directory straight through as the output
filename and it reached os.remove(). --output is documented as "directory
or file", so derive the filename when it names a directory, and guard the
stale-file sweep with isfile() so a directory can never be handed to
os.remove().

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QiYkHKB7Tp7X6NdnEutda2
2026-08-23 08:53:20 +02:00
juancarlos.cavero
8a6ad06c8c fix(subtitles): name the filter option so ffmpeg 8 can parse the burn
ffmpeg 8's filtergraph parser rejects a quoted positional value followed
by more :name=value options — ass='x.ass':fontsdir='…' now fails with
"No option name near …", so every caption burn breaks on ffmpeg >= 8
(found live-testing the MCP add_subtitles tool on a Homebrew 8.1.1).
The named form (ass=filename='…') parses identically on 4.x through 8.
2026-08-03 22:33:16 +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
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
5f7bf42721 fix(subtitles): empaquetar fuentes reales para que el estilo elegido se aplique (#57)
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).
2026-07-23 15:55:36 +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
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
40151e1708 feat: karaoke subtitles, deterministic Auto-Edit v2, emoji hooks, retries (PR #50 block 1)
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>
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
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
a901bd6933 Add session recovery and subtitle customization UI
- Session recovery: persist job state to localStorage, auto-restore on
  page refresh with recovery banner (1h TTL matching server retention)
- Subtitle customization: font selection, text color presets + custom
  picker, border color/width slider, background box toggle with
  color/opacity controls, live preview in modal
- Backend: new SubtitleRequest fields (font_name, font_color,
  border_color, border_width, bg_color, bg_opacity), hex-to-ASS color
  conversion, outline vs box rendering modes
- Fix font size scaling from 0.5x to 0.85x for readable vertical video

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:49:27 +01:00
juancarlos.cavero
03477d4353 Add ElevenLabs voice dubbing and improve project setup
- Add AI voice dubbing with ElevenLabs (30+ languages)
- Add TranslateModal component for language selection
- Auto-transcribe dubbed videos for subtitles in new language
- Add ElevenLabs API key settings in frontend
- Add async_upload parameter to Upload-Post integration
- Add MIT LICENSE file
- Add CLAUDE.md for AI-assisted development
- Update README with dubbing feature and badges

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 20:24:15 +01:00
juancarlos.cavero
c381c624be added subtitles 2025-12-22 18:21:17 +01:00