Commit graph

432 commits

Author SHA1 Message Date
juancarlos.cavero
5280054d32 fix(seo): stop the 404 page claiming to be authored content
The 404 was rendered through the same template as the comparison pages, so it
carried a byline and "Published 2024-06-01 / Updated 2026-07-27", and its schema
declared an Article with an author and a publication date. Both assert authorship
of a page nobody wrote, and the date read as a bug to anyone who landed on it.

noindex pages now render without the byline and describe themselves as a plain
WebPage. Verified: 404.html has no byline, no datePublished anywhere, and a
WebPage node; the real pages keep their byline and Article node unchanged.
2026-07-27 12:35:45 +02:00
juancarlos.cavero
985761a340 fix(seo): permanent apex redirect, real 404s, and gallery links that resolve
Three routing fixes, all in nginx.conf so they live in version control.

Apex to www is now a 301. Traefik was answering 307 because Coolify generates
`redirectregex.permanent=false` and hardcodes it, so pinning the label would be
overwritten on the next deploy. Moving the redirect into the container means the
app's `redirect` setting in Coolify must be `both`, otherwise Traefik still
redirects the apex before nginx ever sees it. A temporary redirect consolidates
nothing, and every canonical on the site pointed through it.

Unknown paths now return 404 instead of 200 with the SPA shell. The app routes
entirely through the hash (#/pricing, #/auth/callback), which never reaches the
server, so nothing deep-links to a path and the fallback was load-bearing for
nothing. Answering 200 with byte-identical markup for every made-up path made
the site look like a single page duplicated infinitely. The 404 body is a
branded page generated by the same renderer, marked noindex and kept out of both
the sitemap and llms.txt.

/gallery and /video/* now 301 to api.openshorts.app, which is where those
server-rendered pages actually live. The README has linked them on the apex since
they were written, and the apex quietly served the landing page instead.

Verified against the production nginx config in a container: 15 real routes 200,
6 made-up paths 404, both gallery paths 301 to the API host, apex 301s to www
preserving path and query. Coolify's health check for this app is disabled and
would target /, which still returns 200.
2026-07-27 11:48:33 +02:00
juancarlos.cavero
ce67cdcdf5 feat(seo): make the site readable by AI crawlers
The dashboard is a client-rendered SPA, so the HTML served for / contained an
empty <div id="root"> and nothing else. Googlebot renders JavaScript and saw the
real landing page; GPTBot, ClaudeBot and PerplexityBot do not, and measured the
homepage as zero characters of text. That is why the site ranks #1 in Google for
its own name and is absent from AI answers. Verified: curl with a GPTBot UA
returned 13,651 bytes of markup and 0 characters of body text.

vite-plugin-seo.js fixes it at build time, with no runtime cost and no change to
how the app mounts:

- Injects crawler-visible homepage content into #root. React replaces it on
  mount, so users get the app unchanged. Homepage now serves 7,524 characters
  of text instead of 0.
- Emits eight standalone static pages: four "X alternative" comparisons plus
  free-ai-clip-generator, open-source-video-clipper, how-openshorts-works and an
  /alternatives hub. Commercial-investigation prompts are answered almost
  entirely out of comparison content, and informational pages are cited far more
  than product pages.
- Generates sitemap.xml (was one hand-written URL with a stale lastmod) and
  llms.txt from the same page list so the three cannot drift.

Also corrects three things that were actively misinforming engines:

- canonical pointed at the apex, which 302s to www. It named a URL that only
  ever redirects. Now www everywhere, matching what is served.
- The schema declared one SoftwareApplication at price 0. That is true of the
  self-hosted edition and false of the hosted one, so the whole product read as
  free. Split into SoftwareApplication (MIT, $0) and Service (Cloud, real
  AggregateOffer of $12-59), and the FAQ answers now name both prices together.
- Opus Clip was described as "$15-228/month" and the Cloud tier as a "3-day free
  trial". Both are stale. Competitor pricing now lives in seo/data.js with the
  date it was checked rendered next to it on the page.

nginx: try_files gains $uri.html before $uri/, so the generated pages resolve at
their clean path with a 200. Resolving them as directories makes nginx 301 to a
trailing slash, which would point every canonical at a redirect.

Verified against the production nginx config in a container: all 12 routes 200,
no redirects, all 9 JSON-LD graphs parse, React mounts with a clean console.
2026-07-27 10:56:15 +02:00
juancarlos.cavero
ccaa06a862 docs(readme): stop advertising against our own pricing page
The README opened with "Free & open source... No watermarks, no limits" and
the comparison table listed Price: Free, Watermark: Never, Upload limits:
None. openshorts.app was mentioned only as a gallery link. Anyone arriving
at the site from here expected an unlimited free tool, which is exactly what
the paid plans charge to remove, and the numbers show it: 1.7% of users come
back, identically whether their clips succeeded or failed.

Self-hosting really is free with no watermark and no limits, so that claim
stays. What changes is that the hosted service now exists on this page, with
the two costs it actually covers named up front: the GPU (about 50s per
8-minute video against 5-8 min on CPU) and the managed API keys.

- Lead with a two-column table: self-hosted vs hosted, price, speed, keys,
  limits, setup, data.
- Qualify the three competitor-table rows that read as unconditional.
- Add the hosted option to "How Much Does It Cost?".
2026-07-27 10:39:40 +02:00
juancarlos.cavero
9b01e02a9b feat(attribution): record where each new account came from
Every strategic read on the funnel so far has been inference: 94% of search
clicks are brand queries, so the real acquisition channel is upstream of
Google, but `users` stores no source at all and we cannot tell GitHub from
YouTube from a directory listing, nor say which channel produced the few
accounts that pay.

Capture `document.referrer` + UTM on the first page load, keep it in
localStorage (our own auth redirects destroy the referrer), and post it once
the account exists. First touch wins, so arriving from GitHub and later
returning via a search still attributes to GitHub.

- New `signup_attribution` table rather than columns on `users`: the schema
  bootstrap is create_all, which adds missing tables but never ALTERs an
  existing one, so this lands on deploy with no migration.
- Only recorded for accounts minutes old, so the 1196 existing users cannot
  be mislabelled with their next login.
- ON CONFLICT DO NOTHING for two tabs finishing the same redirect; the client
  call is fire-and-forget and can never fail a sign-in.
2026-07-27 10:39:24 +02:00
juancarlos.cavero
be1093bd4c feat(pricing): sell the GPU, the keys and the setup instead of the software
The pricing page asked people to pay for things our own MIT repo already
gives away for free (no watermark, no limits), and then closed with a
"Self-host free" button competing with the checkout right below the plans.
Nothing named the two costs self-hosting actually has: our GPU and the
managed API keys.

- Name the real hosted value on every plan card, free included, since free
  runs on the same GPU with the same bundled key: ~50s per 8-min video vs
  5-8 min on CPU. Add the missing no-watermark bullet to the paid tiers.
- Turn the landing's "Two ways to use OpenShorts" cards into a real
  side-by-side: GPU vs your CPU, our key vs your keys, we maintain it vs
  you maintain it.
- Add a detailed hosted vs self-hosted table to the standalone #/pricing,
  which had no equivalent. It lives there rather than in PricingSection so
  it does not duplicate the landing block sitting right above it.
- Realign both copies of the billing FAQ and the open-source trust card.

Retention is 1.7% and identical whether clips succeed or fail, so the plans
have to earn their price on running costs, not on features we open source.
2026-07-27 10:21:58 +02:00
juancarlos.cavero
ef7f856469 fix(pricing): name the actual platforms in the auto-posting line
"TikTok, Reels & Shorts" mixes a platform with two format names, so the two
destinations a reader is most likely to be checking for — Instagram and
YouTube — never appear. Spell all three out.
2026-07-26 23:22:23 +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
victormanuel.caverogracia
28a1f6aef2 Remove Plausible analytics (migrated to OpenPanel) 2026-07-26 20:39:28 +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
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
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
5b5d3d2306 fix(billing): stop stranding customers whose payment failed
A declined card left the account in a state with no way out. `past_due` grants
no minutes, so the metering layer resolved the user to the free plan — which
meant /api/me reported status=null, the account page swapped "Manage billing"
for "Upgrade" (hiding the only button that fixes a card), and the checkout guard
then rejected the upgrade with a 409 that every call site swallowed into a
generic "Could not start checkout." Silently free, unwarned, unable to pay.

Found on 25-jul-2026 in prod: 14 subscriptions in this state, all first charges
that failed when the (now retired) 3-day trial ended. The trial is gone, but the
trap is not — a renewal failure or an abandoned 3DS payment reproduces it.

- metering: split `_subscription_row` (raw) from `_active_subscription`
  (entitling), and expose both on the balance. Entitlement logic is unchanged.
- /api/me: report status/interval from a row needing attention when no
  subscription entitles, plus `has_billing_account` to route the portal button.
- checkout: drop `incomplete` from the blocking states. Stripe collects nothing
  on it and expires it within 24h, so blocking only stopped the user's retry.
  Give past_due/unpaid a message that names the problem and the fix.
- account page: explain the failed payment inline with a link to the portal
  instead of showing a bare "past_due" chip, and keep the portal reachable for
  any Stripe relationship, live or broken.
- api client: throw a typed ApiError carrying the server's detail so callers
  stop replacing real, actionable messages with generic copy.

Verified against a real DB: past_due stays blocked but visible and fixable,
incomplete can retry, canceled is silent and can subscribe again.
2026-07-25 15:14:15 +02:00
juancarlos.cavero
c88239921e feat(conversion): vender también en los momentos buenos, no solo en el muro
Hasta ahora el único camino al upgrade era fallar contra la cuota. Tres
momentos nuevos, todos con el mismo mensaje ya validado (watermark +
caducidad 7d + minutos):

- Resultados (pico de satisfacción): banner para usuarios free junto a
  sus clips recién generados — "Like these clips? Keep them forever →" —
  que abre la modal de upgrade en modo 'upsell' (copy adaptado: aún
  tienen minutos, se vende permanencia y limpieza, no "te quedaste sin").
- Medidor del header: para free abre la modal de upgrade en vez de ir a
  account — antes no existía ningún camino visible a los planes desde el
  dashboard sin fallar primero.
- Email "tus clips se borran mañana": warn_free_expiring() en el sweeper
  avisa el día 6 de los 7 de retención free, con descarga o upgrade como
  salidas. Aversión a la pérdida honesta: la fecha es real y hoy se
  borraba en silencio, lo que no convertía a nadie. Dedupe en memoria
  (peor caso tras restart: un duplicado).

Eventos UpsellModalSeen/UpsellModalCheckout separados de los del muro
para medir cada momento por su lado.

Verificado: lógica del aviso probada contra la DB local (clip de 6.5d
avisa, el de 8d ya purgeable no, segundo pase no duplica); 141 tests y
build del dashboard en verde.
2026-07-25 02:27:34 +02:00
juancarlos.cavero
95a9a5ff1e feat(conversion): vender el plan (no top-ups) en el momento del muro de cuota
De 76 impactos del muro 402 en 72h solo 4 llegaron a checkout y la única
compra fue un top-up: la modal antigua ofrecía packs de minutos sueltos
como opción principal, el upgrade a plan era un párrafo NO clickable y
un StarBanner empujaba a GitHub en pleno momento de compra.

Nueva modal (mismo fichero/props, cero cambios en App.jsx):
- Starter destacado + Creator al lado como ancla de precio; bullets del
  valor real de pagar: 5x/15x minutos, sin watermark, clips permanentes
  (los free caducan a 7 dias) y prioridad de cola sobre free — todo
  cierto, sin escasez inventada ni cuentas atras falsas.
- Copy goal-gradient con los datos del 402: "this video needs X min and
  you have Y left — upgrade and it starts processing right away".
- "cancel anytime" como reversion de riesgo; top-ups relegados a un link
  discreto que expande; StarBanner fuera.
- Eventos QuotaWallSeen / QuotaWallCheckout para medir la conversion del
  muro, que hasta ahora era invisible.

El email de sin-minutos replica el mismo mensaje (perdida + plan concreto
+ CTA unico) y por fin deja rastro en logs al enviarse.

Verificado end-to-end en local: usuario free con cuota agotada via DB,
402 real de /api/process, modal con datos reales y packs expandibles.
2026-07-25 02:14:58 +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
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
1c6431e8a0 test(ci): saltar los tests que importan main/app en el CI mínimo
El CI instala solo pytest+pillow+httpx+pydantic+sqlalchemy. test_gemini_retry
importa main (cv2/torch) y test_job_error_text importa app (dotenv/fastapi),
que faltan → ModuleNotFoundError en la colección. importorskip los salta en
CI y los corre entero en el contenedor/local donde sí están las deps.
Verificado en un venv réplica del CI: 125 passed, 2 skipped.
2026-07-23 11:40:05 +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
7d6c232165 feat(alerts): prefijo 'OPENSHORTS ✂️ -' en todos los mensajes de Telegram
El chat de Telegram es compartido con Upload-Post y otros productos, así que
cada mensaje de OpenShorts se marca con el nombre para distinguirlos de un
vistazo. Aplicado en send_telegram, cubre todas las alertas (pagos, subs,
churn, clips).
2026-07-21 02:20:56 +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
26135fb485 feat(abuse): abrir free a email normal + bloquear dominios desechables
El free ya no exige Google: cualquier cuenta Google o de email permanente
entra. Para que no sea un grifo de minutos gratis:
- Bloqueo de dominios desechables/temp-mail en el registro por email
  (cloud/disposable_domains.txt, 155 dominios: los clásicos temp-mail + los
  vistos en nuestra propia DB). Refrescable desde el proyecto upstream.
- Normalización de alias: gmail dots/+tags y +tags de otros proveedores se
  colapsan a una sola cuenta canónica, para que foo+1@ / f.oo@ no minten
  cuentas infinitas. Aplicado en magic-link y en Google OAuth.
- free_plan_eligible: Google siempre; email solo si el dominio no es
  desechable (defensa en profundidad además del bloqueo en registro).
- Popup de bienvenida ahora sale una vez por navegador en el primer registro
  (Google o email), no solo a los no-entitled; el botón free arranca directo
  sin forzar Google.

Verificado: registro con mailinator/luckfeed -> 400; gmail -> 200. 115 tests
(9 nuevos de email_policy).
2026-07-21 00:45:54 +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
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
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
d2fd9d3d1b fix(landing): jerarquía del hero — badge visible de 'no credit card' y la subida como enlace secundario
Dos píldoras grandes seguidas competían entre sí, y el argumento que
desactiva la objeción principal (no hace falta tarjeta) iba escondido en
un párrafo gris. Ahora el CTA manda, debajo va la badge verde y 'or upload
a video' baja a enlace.
2026-07-20 21:32:40 +02:00
juancarlos.cavero
6cb8551aa4 fix(landing): 'paste a video link' — el ingest no es solo youtube 2026-07-20 21:29:54 +02:00
juancarlos.cavero
e0b43dee83 feat(landing): input de URL en el hero — la landing arranca el producto, no la página de precios
El CTA del hero mandaba a #pricing: pedía plantearse pagar antes de ver
nada, justo el muro que el plan free venía a quitar (7.7% de los registros
pasaban). Ahora el hero acepta un enlace, lo guarda y abre la app con la
URL ya cargada en MediaInput; el login se pide al generar, no antes.
No se auto-envía: la casilla de derechos sobre el vídeo la marca el usuario.
2026-07-20 19:14:17 +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
f68bf12fee ci: install sqlalchemy so the free-plan metering tests can import cloud.metering 2026-07-20 18:12:33 +02:00
juancarlos.cavero
a42297f120 Merge origin/main: analytics + billing cross-sub guard
Conflicto resuelto en AuthContext (se mantienen el track('Signup') y el
enrutado del plan free). Además, fix de la interacción entre ambos cambios:
AccountPage daba el checkout por activado en cuanto /api/me devolvía un
plan, pero 'free' ahora existe desde el primer instante — se exige un plan
de pago antes de parar el polling, disparar el goal Subscribed y llevar al
usuario a conectar sus redes.
2026-07-20 15:22:52 +02:00
juancarlos.cavero
afcc9de9e2 Merge feat/free-plan: plan free 20 min/mes sin tarjeta, sin trial, galería opt-in 2026-07-20 15:19:38 +02:00
victormanuel.caverogracia
9685346cd6 Add OpenPanel analytics snippet (parallel to Plausible) 2026-07-20 11:28:21 +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
victormanuel.caverogracia
99e113130d analytics: track funnel goals (Signup, CheckoutStarted, Subscribed) via Plausible
Add a small no-op-safe track() helper and emit three custom events so we can
see where users drop off between landing and paid: Signup on auth callback,
CheckoutStarted before the Stripe redirect, Subscribed on plan activation.

Plausible here is Community Edition (no revenue goals), so the plan price rides
along as a plain value_usd prop instead of a revenue field. Self-hosted builds
without the analytics script are unaffected (track() no-ops).
2026-07-19 14:18:11 +02:00
victormanuel.caverogracia
747a1d5f95 fix(billing): don't let a non-current subscription clobber the live row
subscriptions keeps one row per user, keyed on user_id in _upsert. An event
for a *different* sub of the same user (e.g. canceling a dangling past_due
annual while a monthly trial is live) would overwrite the good row. Add a
cross-subscription guard: another sub only takes over the row when the stored
one is no longer live.
2026-07-18 23:42:21 +02:00
juancarlos.cavero
d5f2767d70 Merge fix/ui-model-badge-clip-preview: clip card redesign + social connect gating 2026-07-18 23:38:14 +02:00