videogen/ugc-tool-cto-plan.md
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

315 lines
20 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ReelForge — CTO Build Plan (All Decisions Locked)
**Product:** Screen recording + prompt → viral UGC video (AI avatar, hook script, karaoke captions), TR/EN, 1080×1920.
**Base:** Fork of MoneyPrinterTurbo (MIT). This document is final — no open questions. Hand it to the developer as-is.
---
## 0. Locked technology decisions
| Layer | Decision | Why (one line) |
|---|---|---|
| Backend | Python 3.11, FastAPI (from MPT fork) | Keep MPT's pipeline + REST layer |
| Job queue | **Celery 5 + Redis 7** | Battle-tested, retries/timeouts built in, easy worker scaling |
| DB | **Neon Postgres** + SQLAlchemy 2 + Alembic | Already in our stack; branching for dev |
| Object storage | **Cloudflare R2** (S3 API, presigned URLs) | Zero egress; already on Cloudflare |
| LLM (script) | **Claude Sonnet 4.6** (`claude-sonnet-4-6`) | Best TR quality/cost ratio; structured JSON output |
| TTS | **ElevenLabs `eleven_multilingual_v2`**, `/with-timestamps` | One voice for TR+EN; char-level timing drives everything downstream |
| Avatar/lip-sync (Tier A, launch) | **HeyGen API v2** (talking photo + video avatar) | Best quality, zero GPU infra |
| Avatar (Tier B, Phase 3) | **LatentSync** on RunPod Serverless (A10G) | ~20× cheaper per minute at volume |
| Captions | **ASS karaoke (`\k` tags) burned via FFmpeg libass** | Frame-accurate, zero desync, CapCut look |
| Composition/render | **Pure FFmpeg filter graph** (no MoviePy in prod path) | Single-pass, hw-accel capable |
| Frontend (Phase 2) | **Next.js 15 (App Router) + Tailwind + shadcn/ui**, deployed on Cloudflare Pages | Our standard stack |
| Auth | **Clerk** (email + Google) | 1-day integration, free to 10k MAU |
| Payments | **Stripe** (global) + **iyzico** (TR local cards), credit ledger in Postgres | TR conversion needs iyzico |
| Deploy | **Docker Compose on Hetzner** (existing box or CPX41), Cloudflare Tunnel in front | Reuse infra we already pay for |
| Errors/monitoring | **Sentry** (API+workers) + per-job telemetry table in Postgres | Unit economics visible from job #1 |
| CI | GitHub Actions: lint (ruff), tests (pytest), Docker build, golden-video regression | |
Named the project **ReelForge** internally; rename freely.
---
## 1. System architecture
```
┌──────────────┐ presigned PUT ┌──────────────┐
│ Next.js UI │ ─────────────────► │ Cloudflare R2 │◄─── outputs (presigned GET)
│ (CF Pages) │ └──────┬───────┘
│ Clerk auth │ │
└──────┬───────┘ │
│ REST (JWT) │
┌──────▼──────────────────────────────────▼──────────┐
│ FastAPI (Hetzner, Docker) │
│ POST /v1/jobs → enqueue → 202 {job_id} │
│ GET /v1/jobs/{id} → status/progress/result_url │
└──────┬─────────────────────────────────────────────┘
│ Celery (Redis broker)
┌──────▼─────────────────────────────────────────────┐
│ Worker(s): pipeline stages as one Celery chain │
│ script → tts → avatar → captions → compose → upload│
│ External: Anthropic API · ElevenLabs · HeyGen │
└────────────────────────────────────────────────────┘
```
- API and workers are the **same Docker image**, different entrypoints. Scale workers independently.
- Every stage writes progress + cost to `job_events`. UI polls `GET /v1/jobs/{id}` every 3s (webhooks in Phase 3).
- All media flows through R2 — nothing large ever passes through the API server.
---
## 2. Repository structure (fork of MPT, restructured)
```
reelforge/
├─ app/
│ ├─ api/ # FastAPI routers: jobs, assets, avatars, voices, health
│ ├─ core/ # config (pydantic-settings), security, logging
│ ├─ models/ # SQLAlchemy: User, Job, JobEvent, Asset, CreditLedger, AvatarPreset
│ ├─ services/
│ │ ├─ script/ # Claude client, hook library (tr.yaml / en.yaml), JSON schema
│ │ ├─ tts/ # base.py + elevenlabs.py (timestamps) + edge.py (dev fallback)
│ │ ├─ avatar/ # base.py + heygen.py (+ latentsync_runpod.py in P3)
│ │ ├─ captions/ # timestamps → word groups → .ass generator
│ │ ├─ compose/ # ffprobe analysis, filter-graph builder, render
│ │ └─ storage/ # R2 client, presigned URLs
│ ├─ workers/ # celery_app.py, tasks.py (stage tasks + chain)
│ └─ telemetry/ # cost/timing recorder
├─ resource/fonts/ # Inter Black, Montserrat ExtraBold, TT-supporting; licensed
├─ migrations/ # Alembic
├─ tests/ # unit + golden/ (10 reference jobs, SSIM+timing asserts)
├─ web/ # Next.js app (Phase 2)
├─ docker-compose.yml # api, worker, redis
└─ .github/workflows/ci.yml
```
---
## 3. Data model (Postgres)
```sql
users(id uuid pk, clerk_id text unique, email, created_at)
jobs(
id uuid pk, user_id fk, status text -- queued|script|tts|avatar|captions|compose|done|failed
, language text -- 'tr' | 'en'
, layout text -- 'hook_intro' | 'pip' | 'split'
, avatar_preset_id fk, voice_id text
, input_video_key text -- R2 key
, prompt text, app_context text
, script_json jsonb, output_key text
, error text, created_at, finished_at
)
job_events(id, job_id fk, stage, status, duration_ms,
cost_usd numeric, meta jsonb, created_at)
assets(id, user_id, kind text /*upload|output|avatar_clip|audio*/,
r2_key, bytes, duration_s, created_at)
avatar_presets(id, name, provider text /*heygen|latentsync*/,
provider_ref text, thumb_key, active bool)
credit_ledger(id, user_id, delta int, reason text /*purchase|job|refund*/,
job_id nullable, stripe_ref nullable, created_at)
-- balance = SUM(delta); 1 credit = 1 rendered video
```
---
## 4. API contract (v1)
```
POST /v1/uploads/presign {filename, content_type} → {put_url, r2_key}
POST /v1/jobs {input_video_key, prompt?, language, layout,
avatar_preset_id, voice_id, variants: 1..3}
→ 202 {job_id}
GET /v1/jobs/{id} → {status, stage, progress_pct, result_url?, error?}
GET /v1/jobs?limit=&cursor= → job history
GET /v1/avatars → active presets (name, thumbnail)
GET /v1/voices → curated ElevenLabs voices (3 TR-capable, 3 EN)
POST /v1/jobs/{id}/retry
GET /v1/me → {email, credits}
```
Auth: Clerk JWT verified in FastAPI middleware. Phase 1 internal mode: single static API key, same routes.
---
## 5. Pipeline stage specs (implementation-level)
### Stage 1 — Script (Claude Sonnet 4.6)
- System prompt: native-TR and native-EN "UGC creator" personas (two prompts, not translated). Few-shot: 12 hook templates per language from `resource/hooks/{tr,en}.yaml`.
- Inputs: app_context (name, one-liner, key feature), user prompt, target duration derived from screen recording length (clamped 25–60s).
- **Output schema (enforced, retry on invalid JSON):**
```json
{"hook": "string, ≤12 words, spoken ≤2.5s",
"segments": [{"text": "...", "onscreen_moment_hint": "..."}],
"cta": "string",
"full_text": "hook + segments + cta joined",
"est_duration_s": 42}
```
- Temperature 0.9 for variants (batch mode generates N distinct scripts in one call).
- Cost target < $0.01/job.
### Stage 2 — TTS (ElevenLabs)
- `POST /v1/text-to-speech/{voice_id}/with-timestamps`, model `eleven_multilingual_v2`, `output_format=mp3_44100_128`.
- Persist audio to R2 + normalized char-timestamp array to `jobs.script_json.timing`.
- Derive **word timings** (group chars by whitespace) — this array is the single source of truth for captions AND avatar duration validation.
- Curated voices: pick 3 voices verified for natural Turkish (test "ğ/ş/İ" words + question intonation) + 3 EN. Hard-code IDs in `voices.yaml`.
### Stage 3 — Avatar (HeyGen v2)
- `AvatarProvider.generate(audio_url, preset) → mp4_url` interface.
- HeyGen: create video with `audio` input (our ElevenLabs file — do NOT let HeyGen do TTS, or timing sources diverge), green-screen background, 720×1280. Poll status; typical 1–3 min.
- Download → R2 as `avatar_clip`. Validate: `abs(avatar_duration − audio_duration) < 0.15s`, else fail stage with retry.
- Preset library: license/generate 8–10 UGC-style talking-photo avatars (mixed gender/age, casual settings) during week 1.
### Stage 4 — Captions (ASS karaoke)
- Word timings → groups of 1–3 words (break on punctuation or >0.8s gap).
- Emit `.ass`: PlayRes 1080×1920, style `Fontname=Montserrat ExtraBold, Fontsize=88, PrimaryColour=white, SecondaryColour=&H00FFFF (yellow), Outline=5, Shadow=1, Alignment=8 (top-center), MarginV=380`; karaoke via `{\k<cs>}` per word → active word flips white→yellow with pop (`\fscx110\fscy110` on 80ms `\t`).
- Turkish glyph QA test in CI (render "İĞÜŞÖÇ ığüşöç" frame, assert non-tofu via pixel diff).
### Stage 5 — Compose + render (FFmpeg, single pass)
- `ffprobe` the screen recording: resolution, duration, fps. Auto: scale/crop to 1080×1920 (blur-pad if aspect can't crop cleanly), trim leading static frames (freezedetect), `setpts` speed-ramp up to 1.6× max if recording > script duration.
- **Layout `hook_intro` (default):** avatar fullscreen 0→hook_end, hard cut to screen recording with avatar as 300px circular PiP bottom-left (chromakey → `colorkey=0x00FF00:0.3:0.1`, `geq` circular alpha mask), captions throughout.
- Layouts `pip` and `split` (50/50 vstack) as config variants of the same graph builder.
- Audio: voiceover −3 LUFS target, optional bg music from `resource/music/` sidechain-ducked (`sidechaincompress`).
- Render: `libx264 preset=medium crf=19` CPU baseline; auto-switch `h264_nvenc` / `h264_videotoolbox` if available. `-movflags +faststart`, AAC 192k. Target ≤ 90s render time for a 60s video on CPX41.
### Stage 6 — Upload + finalize
- Output → R2, presigned 7-day GET, `jobs.status=done`, credit deducted (ledger), telemetry row per stage.
---
## 6. Delivery plan — 8 weeks, sprint by sprint
**Sprint 1 (wk 1–2): Skeleton + spine**
Fork MPT, strip stock-footage code, repo restructure, Docker Compose (api/worker/redis), Neon schema + Alembic, R2 wiring, Celery chain with stub stages, ElevenLabs adapter w/ timestamps, Claude script service + hook libraries, curated voices. *Exit: prompt → script → TTS audio in R2 via API.*
**Sprint 2 (wk 3–4): Video core**
HeyGen provider + preset library, ASS karaoke generator, FFmpeg graph builder (all 3 layouts), screen-recording auto-analysis, end-to-end chain, telemetry. *Exit: full pipeline produces acceptance-quality video, TR + EN. **This is the Phase-1 internal launch** — I start posting real content from it.*
**Sprint 3 (wk 5–6): Hardening + web app**
Retries/idempotency, golden test set (5 TR + 5 EN) in CI with timing-drift assertions (≤50ms), Sentry, batch variants, Next.js app: Clerk auth, upload w/ presign, job wizard (avatar/voice/layout pickers), dashboard w/ previews, mobile-responsive. *Exit: non-technical user ships a video from the browser.*
**Sprint 4 (wk 7–8): Monetization**
Credit ledger + Stripe Checkout + iyzico, plans (Free 3 credits / Starter 30 / Pro 120), rate limits, ToS/AI-disclosure toggle, landing page, deploy web to CF Pages, prod hardening. *Exit: a stranger can pay and generate.*
**Phase 3 backlog (post-launch, prioritized):** RunPod LatentSync tier (margin), direct TikTok/IG/Shorts publish via Upload-Post (reuse MPT integration), user photo → custom avatar, mobile app (Expo thin client), webhook API for power users.
---
## 7. Budget
**One-time / dev:** developer fee (your negotiation) + ~$100 avatar/font licensing.
**Monthly fixed:** Hetzner (existing) ~€0 incremental · Neon free tier · R2 ~$1 · Clerk $0 · Sentry $0 · HeyGen Creator API plan ~$99 (includes credits) · ElevenLabs Creator $22. **≈ $125/mo.**
**Per 60s video:** Claude <$0.01 · ElevenLabs ~$0.15 · HeyGen ~$0.50–1.00 · compute ~$0.01 → **~$0.70–1.20** (Tier A) → **~$0.20** after LatentSync (Phase 3).
**Pricing:** credits at ~$1.99/video retail (packs discount to ~$1.20) → gross margin ~40% day one, ~85% at Tier B.
## 8. Definition of done (contractual acceptance)
1. 10/10 golden jobs pass in CI: correct language, hook ≤2.5s, caption drift ≤50ms, avatar/audio duration delta ≤150ms, output 1080×1920 ≥8 Mbps.
2. 60s video end-to-end ≤5 min p95 on Hetzner CPX41.
3. Any stage failure → clean `failed` status with error, retryable, no credit burned.
4. Fresh-machine deploy from README in ≤30 min (`docker compose up`).
5. Zero secrets in repo; all config via env; Sentry receiving events.
## 9. Accounts/keys to create before kickoff (Arhan)
Anthropic API · ElevenLabs Creator · HeyGen API plan · Cloudflare R2 bucket + token · Neon project (`reelforge`) · Clerk app · Sentry project · GitHub repo (private fork) · Stripe + iyzico (needed by Sprint 4 only).
---
## 10. OSS foundation map — fork vs. strip, with licenses (adoption status)
> Strategy in one line: **fork MPT as the skeleton, transplant captacity's caption
> logic + ShortGPT's multilingual patterns, bolt on LatentSync as Tier-B avatar,
> lift OpenCut's editor UI when needed** — everything MIT/Apache, with **Wav2Lip,
> F5-TTS weights, Remotion, and Postiz-code-merging explicitly off-limits.**
> Status column reconciled against the tree as of 2026-08-13.
### 10.1 Full-pipeline bases
| Repo | License | Role | Status |
|---|---|---|---|
| **MoneyPrinterTurbo** (harry0703) | MIT ✅ | Our "VS Code": pipeline orchestration, TTS/LLM abstraction, subtitle timing, render | ✅ **Forked (this repo)** |
| ShortGPT (RayVentura) | MIT ✅ | Steal EdgeTTS multilingual voiceover + caption patterns + content-engine structure | ⏳ **adopt: EdgeTTS free-voice backend** |
| short-video-maker (gyoridavid) | MIT ✅ | Reference for an MCP/agent-facing API (Claude agents driving ReelForge) | ⏳ **adopt: ReelForge MCP server** |
| NarratoAI | check | Script-to-edit reference only | reference-only |
### 10.2 Avatar / lip-sync (Tier-B moat)
| Repo | License | Note | Status |
|---|---|---|---|
| **LatentSync** (ByteDance) | Apache-2.0 ✅ | Best quality/speed OSS lip-sync; A10G | ✅ **shipped (Tier B, `avatar/latentsync_runpod.py`)** |
| MuseTalk (Tencent) | MIT code ✅ (verify weights) | Real-time 30fps+; fallback | candidate |
| SadTalker | Apache-2.0 ✅ | Photo → talking head (user-uploaded avatar, no HeyGen) | ⏳ **adopt: photo-avatar provider** |
| EchoMimic v2 (Ant) | Apache-2.0 ✅ | Half-body gestures, more "UGC human" | candidate (alt to SadTalker) |
| ~~Wav2Lip~~ | ❌ non-commercial | **OFF-LIMITS in SaaS** — research license only | blocked |
### 10.3 Captions (karaoke)
**captacity** (MIT) — lift its word-grouping/styling into our ASS generator (`captions/ass_karaoke.py`) rather than expanding from scratch. Timing: **faster-whisper** (MIT, ✅ already in `transcribe.py`) + **stable-ts** (MIT) as the fallback when audio isn't ours. Status: ⏳ **adopt captacity presets + stable-ts alt backend.**
### 10.4 Rendering — the license trap
Our FFmpeg/libass path is fully free ✅. **Remotion** is source-available with a **company license fee → avoid.** If we ever want programmatic React rendering, use **Revideo** (open fork) instead. Status: ✅ **compliant (pure FFmpeg); Remotion flagged off-limits.**
### 10.5 Web editor UI (Phase 2/3)
**OpenCut** (MIT) — the open-source CapCut alternative; fork its timeline/preview components into the Next.js dashboard rather than building an NLE. (See [`docs/reelforge/RESEARCH_ROUND2_CAPCUT_EDITORS.md`](docs/reelforge/RESEARCH_ROUND2_CAPCUT_EDITORS.md): prefer `opencut-classic`/`openreel-video`, server stays render-authoritative.) Status: ⏳ **candidate (MEDIUM, narrow trim/caption/overlay editor).**
### 10.6 Self-hosted TTS (only if ElevenLabs cost bites)
**Fish Speech / OpenAudio** (verify per-version license) and **F5-TTS** (MIT code, **CC-BY-NC weights → commercial trap**). TR quality below ElevenLabs today. Prefer **Chatterbox** (MIT) / **Kokoro** (Apache) for a self-host fallback tier. Status: ⏳ **adopt Chatterbox/Kokoro fallback behind the `voice.synthesize()` seam; F5-TTS weights flagged off-limits.**
### 10.7 Publishing/scheduling (Phase 3)
**Postiz** — OSS social scheduler (TikTok/IG/YT) but **AGPL-3.0**: fine to **self-host as a separate service we call over API**, do **NOT** merge its code into our MIT codebase. Status: ✅ **already have native OAuth publish + `upload_post` + scheduler; Postiz-code-merge flagged off-limits.**
### 10.8 License off-limits (hard rules for a proprietary SaaS)
- **Wav2Lip** — non-commercial → never ship.
- **F5-TTS weights** (CC-BY-NC), **SVD / FLUX.1-dev / InsightFace antelopev2** — non-commercial weights → never ship.
- **Remotion** — source-available company license → avoid; use Revideo.
- **Postiz** (AGPL), **RobustVideoMatting** (GPL) — never merge into this MIT tree (self-host-behind-API only, or use a permissive alt like `rembg`).
- Verify **code AND model-weights** licenses separately before cloning anything — see [`docs/reelforge/RESEARCH_HIGGSFIELD_OSS.md`](docs/reelforge/RESEARCH_HIGGSFIELD_OSS.md).
> **Build sequencing** (each a graph-engineered workflow, sequenced because they
> share `schema.py`/`router.py`/`reelforge.py` until the domain restructure lands
> — see [`docs/reelforge/ARCHITECTURE_RESTRUCTURE.md`](docs/reelforge/ARCHITECTURE_RESTRUCTURE.md)):
> editing-polish suite → captacity+stable-ts+EdgeTTS/Chatterbox voice wave →
> SadTalker photo-avatar provider → repurposing engine (yt-dlp+WhisperX+ClipsAI)
> → ReelForge MCP server → OpenCut editor.
---
## 11. Post-plan expansion — from tool to platform (delivered)
> Supersedes the "1 credit = 1 video" model in §3/§4 for **marketplace** jobs;
> the original fixed-credit pipeline (§5) still runs unchanged (the marketplace is
> additive). Detail: [`docs/reelforge/PROVIDER_MARKETPLACE_PLAN.md`],
> [`docs/reelforge/MARKETPLACE_EXECUTION_PLAN.md`], [`docs/reelforge/PRODUCT_ROADMAP.md`].
### 11.1 Pay-as-you-go marketplace
- **USD wallet** (integer microdollars): append-only `wallet_ledger_entries`,
reserve→settle→release, `wallet_accounts` cache. Money-in via **Creem** hosted
checkout → signed webhook → idempotent grant (the ONLY credit path).
- **Reviewed catalog**: providers/models/`price_versions`/`generation_profiles`;
22 providers × 35 models seeded across script/voice/avatar/video/image/music
(shadow-by-default) + OpenRouter import.
- **Routing engine**: `ProviderAdapter` contract + 5 adapters (OpenRouter,
ElevenLabs, HeyGen, Pixelle, Image); consented fallback; submit→poll→
price-from-our-version→settle-actual. Celery `generation` queue.
- **Signed quotes**: profile → HMAC price snapshot → wallet reserve on `POST /jobs`
(additive `generation_profile_id`) → settle at measured cost.
### 11.2 Monetization & enterprise depth
- **BYOK**: encrypted (Fernet) customer keys, per-use audit, consent gate; BYOK
stages charge a disclosed **routing fee** (`byok_fee_bps`, default 10%) instead
of the pass-through provider price — revenue stream §1.3.
- **Spend controls**: per-user AND per-workspace monthly budget caps enforced at
reserve; `GET/PUT /spend/policy`.
- **Safe live-promotion**: `ga` only with a reconciled price + a registered adapter.
### 11.3 New product surfaces
- **Repurposing engine** (Opus Clip/ClipsAI class): long video → transcript →
LLM-ranked highlight clips (pure non-overlapping top-N policy) → promote to a
reel draft.
- **Clients**: web wallet/catalog/model-picker + reel-wizard pay-as-you-go
selector; Expo wallet + catalog screens.
### 11.4 Remaining backlog (⏭)
SadTalker photo-avatar · multi-backend voice fallback · **ReelForge MCP server** ·
OpenCut editor · workspace-funded generation reserve · usage analytics drill-down.