Commit graph

118 commits

Author SHA1 Message Date
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
100fa583a1 Merge feat/clip-editor: per-clip EDL editor + manual generation controls (PR #62, discussion #65) 2026-08-18 19:27:49 +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
juancarlos.cavero
e381d21b54 fix(editor): serialize rerenders per job and re-validate after snapping
- 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.
2026-08-18 15:26:45 +02:00
juancarlos.cavero
cf08a9671b chore(alerts): drop free-tier 'First clips!' Telegram notifications
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.
2026-08-18 14:32:24 +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
f10655fd1c feat(agents): the pipeline as a platform — API keys, MCP server, webhooks
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.
2026-08-03 22:33:16 +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
4c04b37e4f feat(social): send TikTok uploads to drafts instead of publishing
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.
2026-07-29 00:23:59 +02:00
juancarlos.cavero
51aafb5290 feat(analytics): report job outcomes to OpenPanel, with the user's job index
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.
2026-07-28 21:49:40 +02:00
juancarlos.cavero
8f873296a1 fix(emails): stop duplicate expiry warnings and fix the button that 404s
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).
2026-07-27 22:31: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
fd7a2b2cd9 feat(subtitles): let users remove the default captions
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.
2026-07-25 17:48:08 +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
a793e02ddf fix(subtitles): stop charging quota for burning captions
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.
2026-07-25 17:16: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
2efbeb2828 feat(alerts): avisar del dinero de Stripe (con importe) y de activación de clips
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.
2026-07-21 02:06:04 +02:00
juancarlos.cavero
fe0f32e86b feat(onboarding): popup de selección de plan + quitar tope diario free y 'free trial'
- 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.
2026-07-21 00:30:56 +02:00
juancarlos.cavero
900dc441d3 feat(jobs): reanudar trabajos cortados por un redeploy en vez de perderlos
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.
2026-07-20 22:32:53 +02:00
juancarlos.cavero
bc71cb57a3 feat(disk): topes de tamaño para output/ y uploads/ + quitar el badge de trial
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.
2026-07-20 22:09:26 +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
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
927ee09ffc feat(projects): reopen archived projects from history for further editing
- 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
2026-07-18 03:42:17 +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
8160fc6465 feat(cloud): user-friendly job logs + transcription progress; hide auto profile id in header
- 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.
2026-07-18 02:20:31 +02:00
juancarlos.cavero
5bcdda38f6 cloud: also hide AI model/provider, cost and pipeline internals from client logs
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.
2026-07-18 00:36:14 +02:00
juancarlos.cavero
29fed21495 cloud: hide ingest plumbing (proxy/download/cookies) from client logs
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.
2026-07-18 00:34:24 +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
97378ab102 feat: restore original-video preview for uploads after reload
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.
2026-07-17 21:57:37 +02:00
juancarlos.cavero
ff38a9d7ee fix(cloud): compare job owner as string so recovered jobs pass the guard
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).
2026-07-17 21:46:23 +02:00
juancarlos.cavero
be3dc665a3 feat(logs): DEBUG_LOGS env to force full pipeline logs under billing
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.
2026-07-17 21:36:21 +02:00
juancarlos.cavero
82dcd0af89 feat: bulk subtitles + download-all-as-ZIP (PR #50 block 2)
- 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.
2026-07-17 21:26:04 +02:00
juancarlos.cavero
d94e126e0f feat(hook): 6 hook styles (classic/dark/yellow/red/outline/outline+)
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).
2026-07-17 21:26:04 +02:00
juancarlos.cavero
459c062851 feat: recover completed jobs from disk on startup (issue #46/#18)
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.
2026-07-17 21:26:04 +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
83b0649b20 fix(cloud): precise proxy alerts, scrub proxy creds from logs, hide system logs from paid users
- 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.
2026-07-17 21:23:54 +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
6ec6935532 fix(cloud): harden paid-mode surface + source-available license for cloud/
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.
2026-07-16 17:30:12 +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
2a0e5e0de5 chore(prod): production frontend build + skip AWS upload in cloud + /health
- 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).
2026-07-14 15:32:01 +02:00
juancarlos.cavero
0ba4fac47b feat: durable video library on Cloudflare R2 (history + retention)
- 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.
2026-07-14 14:56:40 +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
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
12c1b8e1d5 feat: Require ownership attestation before processing a video
- 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>
2026-05-06 11:55:12 +02:00
juancarlos.cavero
3f4c814e22 feat: Add DISABLE_YOUTUBE_URL flag and reframe marketing copy
- New env var DISABLE_YOUTUBE_URL gates URL ingest in /api/process (403)
- /api/config exposes the flag so MediaInput can hide the YouTube tab
- Landing.jsx and index.html (meta + JSON-LD) reworded around
  "your long-form videos" instead of marketing YouTube downloads,
  reducing inducement exposure on the public deployment

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 11:51:08 +02:00
juancarlos.cavero
9c9342c499 feat: Add Remotion integration for animated subtitles, hooks and effects
Replace static FFmpeg post-processing with Remotion-powered browser rendering:
- Animated word-by-word subtitles (pop, karaoke, glow styles) with real-time preview
- Hook overlays with entrance animations (spring, fade, slide-up)
- Video effects layer (zoom, brightness, contrast, saturate)
- Browser-side rendering via @remotion/web-renderer (WebCodecs)
- Editable transcript text in subtitle modal
- Layers accumulate across operations (subtitles + hook rendered together)
- Gemini EffectsConfig endpoint for structured JSON instead of fragile FFmpeg strings
- Render service (Node.js) as alternative server-side renderer
- New API endpoints: /api/clip/transcript, /api/effects/generate, /api/render

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 14:00:11 +02:00
juancarlos.cavero
86117d3f3e feat: AI Shorts low-cost mode, UGC gallery, universal business support
- Add Low Cost video mode (Hailuo 2.3 + VEED Lipsync ~$0.65) alongside Premium (Kling Avatar v2 ~$2)
- Add UGC video gallery with SEO pages (/gallery, /video/{id}) and JSON-LD structured data
- Make AI Shorts work for any business (URL optional, manual description supported)
- Add shared actor gallery on public S3 with prompt history
- Add custom actor photo upload
- Add Upload-Post social publishing to AI Shorts result step
- Add UGC Gallery tab with Videos + Avatars tabs
- Update landing page with 3-tools-in-1 section (Clip Generator, AI Shorts, YouTube Studio)
- Rename SaaS Shorts to AI Shorts, Dashboard to Clip Generator
- Add vite proxy for /gallery and /video routes
- Add image upload validation
- Remove hardcoded bucket names from code
- Update README with full documentation and screenshot references

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 20:29:23 +01:00
juancarlos.cavero
29681bab82 added video ugc generator 2026-03-15 20:41:35 +01:00
juancarlos.cavero
249936d3c7 Fix silent thumbnail generation failure and switch to gemini-3.1-flash
Thumbnail generation errors were silently swallowed, returning an empty
200 response and leaving the UI stuck on "Your thumbnails will appear here".
Now surfaces actual error messages to the user. Switched model from
gemini-3-pro-image-preview to gemini-3.1-flash-image-preview.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 18:13:17 +01: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
adab69f6e3 fix thumbnail generation 2026-02-20 14:13:06 +01:00
juancarlos.cavero
3946c49ad1 added youtube studio 2026-02-20 01:11:27 +01:00
juancarlos.cavero
c902b6c04c upgrade file size 2026-02-13 14:00:14 +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
bf577494b7 Update hooks, fix captions, and ignore uploads 2026-01-23 14:53:57 +01:00
juancarlos.cavero
26a4c31087 improved video edit with AI 2025-12-24 02:15:07 +01:00
juancarlos.cavero
0b0ffccb69 added save videos 2025-12-24 01:14:02 +01:00
juancarlos.cavero
207f1aa8e3 fix upload video 2025-12-23 09:55:39 +01:00
juancarlos.cavero
eb19101102 added auto schedule posts 2025-12-22 19:33:56 +01:00
juancarlos.cavero
d7b1d8b55c fix subtitles 2025-12-22 18:48:52 +01:00
juancarlos.cavero
c381c624be added subtitles 2025-12-22 18:21:17 +01:00
juancarlos.cavero
820239425c added auto editor with AI 2025-12-22 13:06:33 +01:00
juancarlos.cavero
5be810d606 added video cost to executions 2025-12-21 00:06:59 +01:00
juancarlos.cavero
d60c376013 reafactor readme added instructions and texts 2025-12-20 04:59:38 +01:00
juancarlos.cavero
d9c85f6aed added animation and fix some vite config 2025-12-19 21:00:19 +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
f7cc7b8fe3 added more security to dockerfile 2025-12-19 18:24:57 +01:00
juancarlos.cavero
d5121ed9dd added front-end and backend 2025-12-19 17:59:03 +01:00