clipwright/CLAUDE.md
juancarlos.cavero 3f7ac4da18 feat(reframe): pick the layout from 12 frames instead of uploading the video
Gemini bills video at ~300 tokens per second. An hour of source is ~1.08M
tokens (past a 1M context window) and a 1-2GB upload to get one word back. This
pipeline ingests hour-long podcasts, so uploading the file failed in exactly the
normal case.

Measured over the same 48 clips against the hand-checked labels:

  whole video          94% / 92% / 96%   18,17,18 of 20 found
  12 frames @ 640px    90% / 90%         15,16 of 20
  12 frames @ 1024px   92%               17 of 20
  24 frames @ 1024px   90%               16 of 20

Resolution was the gap, not frame count: at 640px a spreadsheet is unreadable,
and doubling the frames made it slightly worse. At 1024px the difference from
sending the whole video sits inside the run-to-run variance the whole-video mode
already has (92-96%), at 2.2s per clip instead of ~15s, with a cost that no
longer depends on the source duration.

It also removes the Files API dance: no upload, no waiting for ACTIVE.
2026-07-31 13:28:45 +02:00

190 lines
11 KiB
Markdown

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
OpenShorts is an AI-powered vertical video generator that transforms long YouTube videos or local uploads into viral-ready short clips (9:16 format) for TikTok, Instagram Reels, and YouTube Shorts. Uses Google Gemini 2.0 Flash for viral moment detection and title generation.
## Development Commands
### Local Development (Docker)
```bash
docker compose up --build # Build and run full stack
```
- Backend: http://localhost:8000 (FastAPI/Uvicorn)
- Frontend: http://localhost:5175 (Vite proxies API calls to backend)
### Frontend Only (Dashboard)
```bash
cd dashboard
npm install
npm run dev # Dev server with HMR (port 5173)
npm run build # Production build
npm run lint # ESLint (strict, --max-warnings 0)
```
### Backend Only
```bash
pip install -r requirements.txt
uvicorn app:app --host 0.0.0.0 --port 8000
```
## Architecture
### Core Processing Pipeline
1. **Ingest** - YouTube download (yt-dlp) or local upload
2. **Transcription** - faster-whisper with word-level timestamps
3. **Scene Detection** - PySceneDetect for segment boundaries
4. **AI Analysis** - Gemini identifies 3-15 viral moments (15-60 sec each)
5. **FFmpeg Extraction** - Precise clip cutting
6. **AI Cropping** - Vertical reframing with subject tracking
7. **Effects/Subtitles** - Optional AI-generated FFmpeg filters
8. **Hook Overlay** - Text overlays with styled fonts
9. **Voice Dubbing** - Optional ElevenLabs AI translation (30+ languages)
10. **S3 Backup** - Silent background upload
11. **Social Distribution** - Upload-Post API (async upload)
### Key Files
| File | Purpose |
|------|---------|
| `main.py` | Core video processing: transcription, scene detection, clip extraction, vertical reframing |
| `app.py` | FastAPI server with async job queue and REST endpoints |
| `editor.py` | Gemini AI integration for dynamic video effects (FFmpeg filter generation) |
| `hooks.py` | Hook text overlay generation with font rendering |
| `s3_uploader.py` | AWS S3 upload with caching |
| `subtitles.py` | SRT generation, FFmpeg subtitle burning, and dubbed video transcription |
| `translate.py` | ElevenLabs dubbing API for AI voice translation |
| `dashboard/src/App.jsx` | Main React component with state management |
| `dashboard/src/components/TranslateModal.jsx` | Voice dubbing UI with language selection |
| `dashboard/vite-plugin-seo.js` | Build-time SEO surface: injects crawler-visible homepage content, emits static pages, sitemap.xml and llms.txt |
| `dashboard/seo/data.js` | Single source of truth for pricing, pipeline and competitor facts used by every generated page |
### SEO / AI-crawler surface
The dashboard is a client-rendered SPA with hash routing, so the HTML served for
`/` used to contain an empty `<div id="root">`. Googlebot renders JavaScript and
saw the real page; GPTBot, ClaudeBot and PerplexityBot do not and measured the
homepage as zero characters of text. `vite-plugin-seo.js` fixes that at build time:
- Injects the content of `seo/landing-fallback.js` into `#root`. React's
`createRoot().render()` replaces it on mount, so users get the app and
non-executing clients get the copy. **Keep it in sync with `Landing.jsx`.**
- Emits the standalone pages under `/alternatives`, `/free-ai-clip-generator`,
`/open-source-video-clipper` and `/how-openshorts-works` as flat `.html` files.
nginx resolves the clean URL through `try_files $uri $uri.html`; serving them as
directories instead makes nginx 301 to a trailing slash and every canonical
would then point at a redirect.
- Generates `sitemap.xml` and `llms.txt` from the same page list, so they cannot
drift. Do not add a static `public/sitemap.xml` back.
When editing pricing anywhere, edit `seo/data.js` too. Nothing on the site should
say "OpenShorts is free" without naming the Cloud price in the same breath: both
are true of different editions and quoting only the first one is what makes AI
answers describe the paid product as free.
### Cómo se elige el layout
`POST /api/process` acepta `layouts`: una lista (JSON) o cadena separada por
comas con `auto`, `split`, `screencast`, `speaker_cut`, `punch_in`. Cada nombre
enciende su variable de entorno para **ese** trabajo (`app.py:layout_env`); sin
`layouts` el pipeline se comporta exactamente como antes.
`auto` activa `layout_picker.py`: **una** llamada a Gemini por vídeo de origen
(no por clip) que elige entre `none` / `screencast` / `split`. Medido sobre el
corpus de 48 contra etiquetas revisadas a mano: 94% / 92% / 96% en tres pasadas,
con 0-1 falsos positivos sobre los 28 clips que no deben tocarse, y solo 2 clips
que cambian de respuesta entre pasadas.
**Manda 12 fotogramas a 1024px, no el vídeo.** Gemini factura vídeo a ~300
tokens por segundo: una hora de fuente son ~1,08M de tokens (no cabe en una
ventana de 1M) y una subida de 1-2 GB para recibir una palabra. Doce fotogramas
cuestan ~3k tokens **dure lo que dure la fuente**, que es lo que hace viable
esto con los podcasts de una hora que entran de verdad. La resolución importa y
el número de fotogramas no: a 640px detecta 15 de 20 (una hoja de cálculo es
ilegible), a 1024px sube a 17, y pasar a 24 fotogramas lo empeora. A 1024px la
diferencia con mandar el vídeo entero cae dentro de la varianza que ya tiene el
propio modo vídeo, a 2,2 s por clip en vez de ~15 s.
Lo que hace que funcione, y que conviene no deshacer: se le pide una **decisión
entre opciones cerradas**, no una medida. Los cuatro intentos anteriores (Canny,
MSER, cobertura temporal, anchura) le pedían un número y ninguno separó una hoja
de cálculo de un marcador de esquina. La varianza que este repo atribuía a
Gemini era de las medidas continuas, no del modelo.
`layout_picker.apply()` sólo **añade**: una elección explícita del usuario nunca
se desactiva porque el modelo diga `none`.
### Video Reframing Modes
- **TRACK Mode** (single subject): MediaPipe face detection + YOLOv8 fallback with "Heavy Tripod" stabilization
- **GENERAL Mode** (groups/landscapes): Blurred background layout preserving full width
- **SPLIT Mode** (two-shot conversation, `split_layout.py`): both speakers stacked
in half-frames. Off by default (`SPLIT_LAYOUT=1`); v2 engine only, so a
fallback to the v1 loop silently renders GENERAL instead. It upgrades scenes
the classifier already sent to GENERAL, never TRACK ones, and needs both faces
visible **in the same frame** for at least half the sampled frames — that is
what separates a real two-shot from a plano/contraplano, where stacking would
show the same person twice. `SPLIT_TIGHTNESS` (default 0.8) trades a little
upscale for keeping the other speaker out of each half.
- **SCREENCAST / WIDE Modes** (`screencast_layout.py`, `SCREENCAST_LAYOUT=1`):
for scenes whose meaning lives outside the centre. Gemini reports each range's
**width_fraction**, and that is the gate — coverage was tried before and did
not separate a spreadsheet from a corner ticker, while width does (a bug spans
~15% and survives any crop, a spreadsheet spans ~100% and cannot). Content
narrower than 0.5 moves nothing. Between 0.5 and 0.85 there is room beside the
content, so SCREENCAST stacks it over the presenter. Above 0.85 the presenter
is composited **on top of** the content and stacking would show it twice, so
those scenes get WIDE: the GENERAL layout with side-cropping disabled.
- **ALTERNATE Mode** (`active_speaker.py`, `SPEAKER_SIGNAL=1` + `SPEAKER_CUT=1`):
hard cuts to whoever is talking, rendered through the TRACK path as a
trajectory with jumps. `SPEAKER_SIGNAL=1` alone just gates SPLIT on both people
actually speaking. Mouth activity **must** be normalised per speaker before
comparing (`normalise_activity`): raw frame-difference magnitude scales with
local contrast and lighting, and on a real two-shot it handed one speaker
90-100% of the scene.
- **Punch-in** (`punch_in.py`, `PUNCH_IN=1`): not a layout. A ~12% push on the
clip's beats, riding the TRACK path by widening its per-frame crop command
from x-only to w/h/x/y. Beats currently come from the audio envelope;
`emphasis_times` is a plain list of seconds so the transcript's hook words can
replace it without touching the module.
### Key Classes
- `SmoothedCameraman` - Stabilized camera movement with safe zone logic (prevents jitter)
- `SpeakerTracker` - Prevents rapid speaker switching, handles temporary occlusions
### API Endpoints
| Method | Route | Purpose |
|--------|-------|---------|
| POST | `/api/process` | Submit video for processing |
| GET | `/api/status/{job_id}` | Poll job status and logs |
| POST | `/api/edit` | Apply AI video effects |
| POST | `/api/subtitle` | Generate and apply subtitles (auto-transcribes dubbed videos) |
| POST | `/api/hook` | Add text hook overlays |
| POST | `/api/translate` | AI voice dubbing via ElevenLabs |
| GET | `/api/translate/languages` | List supported dubbing languages |
| POST | `/api/social/post` | Post to social media (async upload) |
### Concurrency Model
Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour.
## Environment Variables
**Server-side (.env):**
- `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`, `AWS_S3_BUCKET` - For S3 backup
- `MAX_CONCURRENT_JOBS` - Concurrent processing limit (default: 5)
- `VITE_API_URL` - Production API URL override
- `VITE_OPENPANEL_API_URL`, `VITE_OPENPANEL_CLIENT_ID` - Optional product analytics, read at **build** time. Unset (the default, including every self-hosted build) means no analytics is initialised and no third-party script is loaded. `dashboard/index.html` also gates reporting on an `ANALYTICS_HOSTS` allowlist, so a build carrying credentials stays inert on any other host.
- `OPENPANEL_CLIENT_ID`, `OPENPANEL_CLIENT_SECRET` - Optional **server-side** analytics (`cloud/analytics.py`), same opt-in rule: unset means a silent no-op. Reports job outcomes with the user's job index, which the browser cannot do reliably — a render finishes after the tab is often gone, and ad-blockers eat a share of client events. Needs a *write* client; the read client used for querying is a different credential.
**Client-side (localStorage, encrypted):**
- `GEMINI_API_KEY` - Google Gemini API key (required)
- `ELEVENLABS_API_KEY` - ElevenLabs API key for voice dubbing (optional)
- `UPLOAD_POST_API_KEY` - Upload-Post API key for social posting (optional)
> API keys are stored encrypted in the browser and sent via headers only when needed. Never stored server-side.
## Tech Stack
- **Backend:** Python 3.11, FastAPI, google-genai, faster-whisper, ultralytics (YOLOv8), mediapipe, opencv-python, yt-dlp, FFmpeg, httpx
- **Frontend:** React 18, Vite 4, Tailwind CSS 3.4
- **External APIs:** Google Gemini, ElevenLabs Dubbing, Upload-Post
- **Infrastructure:** Docker + Docker Compose, AWS S3