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.
47 KiB
ReelForge Integration Contract
Status: Authoritative. This is the single source of truth every builder agent MUST follow. Scope: Forked MoneyPrinterTurbo (MPT) codebase at
/Users/arhansubasi/videogen. Rule of precedence: If a builder's local assumption conflicts with this document, this document wins. If this document conflicts with an observed real function name/signature in the repo, STOP and raise the discrepancy — do not silently diverge.
All paths in this document are absolute. All Python signatures are prescriptive: implement them exactly (names, params, type hints, return types). Where a signature cites an existing MPT function (e.g. voice.tts, sm.state.patch_task), that function is real and already in the repo — reuse it, do not reimplement it.
0. Architectural Summary
ReelForge is a parallel UGC avatar pipeline layered on top of MPT's existing state machine, config, and service plumbing. It reuses:
- State machine:
app/services/state.py(sm.state.update_task/get_task/patch_task) andapp/models/const.pytask-state constants. - LLM plumbing:
app/services/llm.py::_generate_response(single provider choke point) vialitellm→ Claude. - TTS plumbing:
app/services/voice.py::ttsdispatcher and theSubMakerlegacy.subs/.offsetcontract consumed bycreate_subtitle/get_audio_duration. - Compose:
app/services/video.pycodec/ffmpeg helpers (utils.get_ffmpeg_binary,_get_effective_video_codec, libx264 fallback). - Publish:
app/services/upload_post.py::cross_post_video. - Router:
app/controllers/v1/base.py::new_router(prefix/api/v1), envelopeutils.get_response.
ReelForge adds: a Postgres/Neon persistence layer (SQLAlchemy + Alembic), a Celery/Redis task orchestration layer, Cloudflare R2 object storage, a HeyGen avatar provider, an ElevenLabs /with-timestamps TTS adapter, an ASS karaoke caption generator, and a pure-FFmpeg compose service.
Canonical DAG: script → tts → {avatar ∥ captions} → compose → upload.
THE SINGLE-SOURCE-OF-TRUTH TIMING RULE (load-bearing, read §9 before building tts/avatar/captions): ElevenLabs
/with-timestampscharacter alignment is the ONE authority for timing. Word timings derived from it drive BOTH the ASS karaoke captions AND the avatar-duration validation. No second forced-alignment pass (no WhisperX/aeneas). The audio duration computed fromalignment.character_end_times_seconds[-1]is the contract value that the avatar render duration and the caption end-time must both agree with.
1. New File Layout (exact paths to create)
Create these under /Users/arhansubasi/videogen/. Keep each file focused (200–400 lines typical, 800 max per repo rule).
1.1 Services — script / tts / avatar / captions / compose / storage
app/services/script/__init__.py
app/services/script/ugc.py # generate_ugc_script (wraps llm._generate_response)
app/services/tts/__init__.py
app/services/tts/elevenlabs_timestamps.py # elevenlabs_tts_with_timestamps + WordTiming
app/services/avatar/__init__.py
app/services/avatar/base.py # TalkingHeadProvider protocol + registry
app/services/avatar/heygen.py # HeyGenClient + HeyGenProvider
app/services/captions/__init__.py
app/services/captions/ass_karaoke.py # build_ass / write_ass / KaraokeStyle
app/services/captions/words.py # group_chars_to_words / phrase grouping
app/services/compose/__init__.py
app/services/compose/compose_ffmpeg.py # compose_avatar_over_screen + layouts
app/platform/storage/__init__.py
app/platform/storage/r2.py # canonical R2Client adapter
app/services/storage/r2.py # compatibility alias during migration
app/services/reelforge.py # ReelForgeParams DTO + stage fns (thin; Celery calls these)
1.2 Persistence — SQLAlchemy models + Alembic
app/models/db/__init__.py
app/models/db/base.py # Declarative Base, engine, SessionLocal, get_session()
app/models/db/models.py # User, Job, JobEvent, Asset, AvatarPreset, CreditLedger
app/models/db/repositories.py # JobRepository, AssetRepository, ... (repository pattern)
migrations/env.py # Alembic env (imports Base.metadata)
migrations/script.py.mako
migrations/versions/ # generated revisions
alembic.ini
1.3 Workers — Celery app + tasks + pipeline
app/workers/__init__.py
app/workers/celery_app.py # Celery() instance (broker/backend = Redis)
app/workers/context.py # JobContext TypedDict + (de)serialization
app/workers/tasks.py # @celery_app.task stage tasks
app/workers/pipeline.py # build_chain() + start_pipeline()
1.4 Telemetry
app/telemetry/__init__.py
app/telemetry/events.py # record_event(job_id, stage, status, payload) -> JobEvent
app/telemetry/progress.py # stage weight -> progress helpers
1.5 API controller
app/domains/reels/router.py # POST /jobs, GET /jobs/{id}, avatars, voices, retry, /me
app/domains/media/router.py # presign and caller-owned upload registration
1.6 Files to EDIT (not create)
app/models/const.py # add REELFORGE_* constants (§4.0)
app/models/schema.py # add request/response Pydantic models (§5)
app/config/config.py # add heygen/anthropic/r2/neon sections (§3)
config.example.toml # add stub sections (§3)
app/router.py # include_router(reels_router)
app/services/voice.py # wire elevenlabs timestamps branch into tts() (§9)
pyproject.toml / requirements.txt / uv.lock# add deps (§7)
2. Module Interfaces (precise signatures)
Every signature below is prescriptive. Type hints are mandatory. All functions that can fail on external I/O return None or an error-envelope dict rather than raising to the caller (mirroring MPT's generate_* and _generate_response conventions).
2.1 app/services/script/ugc.py
Plugs into app/services/llm.py::_generate_response(prompt, app_config=None) — the single provider dispatch choke point. Reuses llm._strip_code_fence, llm._clamp_text, llm._max_retries, and the "Error: " in response guard.
import math
MAX_UGC_SUBJECT_LENGTH: int = 500
UGC_WORDS_PER_SECOND: float = 2.5 # ~150 wpm narration
UGC_SEGMENT_MIN: int = 1
UGC_SEGMENT_MAX: int = 8
def build_ugc_script_prompt(
video_subject: str,
language: str = "auto",
target_duration_s: int = 30,
) -> str: ...
def _parse_ugc_script(response: str) -> dict:
"""Returns {hook: str, segments: list[str], cta: str, full_text: str, est_duration_s: int}.
Raises ValueError on invalid JSON/missing fields to trigger a retry in the caller."""
...
def generate_ugc_script(
video_subject: str,
language: str = "auto",
target_duration_s: int = 30,
app_config=None, # config snapshot passed through to _generate_response
) -> dict | None:
"""Retry-on-invalid-JSON loop (up to llm._max_retries). Returns the parsed dict or None."""
...
Provider wiring (zero new adapter code): Set in config.toml [app]: llm_provider = "litellm", litellm_model_name = "anthropic/claude-sonnet-5", and export ANTHROPIC_API_KEY (litellm reads it from env). generate_ugc_script calls _generate_response(prompt, app_config=app_config) unchanged.
Gotcha: _normalize_text_response strips ALL newlines for openai-compatible/litellm/azure/modelscope adapters. Reconstruct full_text from hook/segments/cta rather than relying on embedded newlines (already done in _parse_ugc_script).
2.2 app/services/tts/elevenlabs_timestamps.py
Produces a SubMaker that is a drop-in for the existing voice.create_subtitle / voice.get_audio_duration (legacy .subs/.offset path) AND carries word/char-level timings. See §9 for the full body spec and the tts() dispatcher wiring.
from typing import NamedTuple, Union
from app.services.voice import SubMaker, ensure_legacy_submaker_fields
_ELEVENLABS_TIMESTAMPS_URL: str = (
"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}/with-timestamps"
)
_HUNDRED_NS: int = 10_000_000
class WordTiming(NamedTuple):
"""Immutable word/char timing for karaoke captions (seconds)."""
text: str
start: float
end: float
def elevenlabs_tts_with_timestamps(
text: str,
voice_id: str,
voice_file: str,
voice_rate: float = 1.0,
voice_volume: float = 1.0,
model_id: str = "",
) -> Union[SubMaker, None]:
"""POST /with-timestamps. Writes mp3 to voice_file (base64-decoded audio_base64).
Returns SubMaker with .subs/.offset (legacy branch), plus .words / .characters
(list[WordTiming], seconds). 3 retries; non-retryable {401,403,422} +
{'voice_disabled','voice_access_denied','unauthorized'}. Returns None on failure."""
...
def _build_submaker_from_elevenlabs_alignment(
characters: list[str],
starts: list[float],
ends: list[float],
) -> SubMaker:
"""One legacy .subs/.offset segment PER non-space char (feeds the tolerant
_match_script_line accumulator). Also sets .words (whitespace-grouped) and
.characters (per-glyph). offset units = 100ns tuples (start_100ns, end_100ns)."""
...
2.3 app/services/avatar/base.py
Provider-registry shape mirroring MPT's _VIDEO_MUSIC_PROVIDERS (task.py:61-76) so an optional preflight (is_enabled()) can gate the run before spending LLM/TTS budget.
from typing import Protocol, runtime_checkable
@runtime_checkable
class TalkingHeadProvider(Protocol):
name: str
def is_enabled(self) -> bool: ...
def list_avatars(self) -> list[dict]: ...
def generate_avatar(
self,
audio_url: str, # public URL (R2) OR local path (uploaded to provider)
avatar_id: str,
*,
width: int = 1080,
height: int = 1920,
background: dict | None = None,
expected_duration_s: float | None = None, # §9 timing-validation input
timeout_s: float = 1800.0,
) -> dict | None:
"""Returns {'avatar_video': <local_path>, 'duration': float, 'provider_video_id': str}
or None on failure/timeout."""
...
AVATAR_PROVIDERS: dict[str, TalkingHeadProvider] = {} # populated at import by heygen module
def get_avatar_provider(provider_id: str = "heygen") -> TalkingHeadProvider: ...
2.4 app/services/avatar/heygen.py
HeyGen v2 audio-driven client (X-Api-Key header, NOT bearer). Behind the TalkingHeadProvider interface for swappability/mocking.
class HeyGenClient:
UPLOAD: str = "https://upload.heygen.com/v1/asset"
GEN: str = "https://api.heygen.com/v2/video/generate"
STATUS: str = "https://api.heygen.com/v1/video_status.get"
AVATARS: str = "https://api.heygen.com/v2/avatars"
def __init__(self, api_key: str | None = None) -> None: ...
def upload_audio(self, path: str, mime: str = "audio/wav") -> str: ... # raw bytes -> asset_id
def create_avatar_video(
self, *, character: dict, voice: dict,
background: dict | None = None, width: int = 1080, height: int = 1920,
) -> str: ... # returns video_id
def wait(self, video_id: str, *, interval: float = 8.0, timeout: float = 1800.0) -> dict: ...
def list_avatars(self) -> list[dict]: ...
class HeyGenProvider: # implements TalkingHeadProvider
name: str = "heygen"
def __init__(self) -> None: ... # reads config.heygen.get("api_key")
def is_enabled(self) -> bool: ... # bool(api_key)
def list_avatars(self) -> list[dict]: ...
def generate_avatar(self, audio_url, avatar_id, *, width=1080, height=1920,
background=None, expected_duration_s=None, timeout_s=1800.0) -> dict | None:
"""Prefer voice={'type':'audio','audio_url': audio_url} (ReelForge R2 URL) to avoid
the upload hop. Polls wait(); downloads out['video_url'] to a local temp; re-hosts
via storage.r2 (signed HeyGen URLs are short-lived). Validates duration against
expected_duration_s (§9). Returns {'avatar_video','duration','provider_video_id'}."""
...
Validation at boundary (mandatory): exactly one of audio_url/audio_asset_id; MIME ∈ {mp3, wav}; hard timeout 30 min; retry-once on transient failed. Download and re-host the signed output URL immediately.
2.5 app/services/captions/ass_karaoke.py and words.py
# words.py
def group_chars_to_words(alignment: dict) -> list[WordTiming]:
"""ElevenLabs char alignment -> word-level WordTiming list. Whitespace = boundary;
word.start = first char start, word.end = last non-space char end."""
...
def group_words_into_phrases(
words: list[WordTiming],
max_words: int = 4,
max_dur: float = 1.4,
) -> list[list[WordTiming]]:
"""CapCut pacing: cap ~3-5 words or ~1.2-1.4s per phrase-line."""
...
# ass_karaoke.py
from dataclasses import dataclass
@dataclass(frozen=True)
class KaraokeStyle:
font: str = "Montserrat ExtraBold"
fontsize: int = 88
primary: str = "&H00FFFFFF" # white (spoken)
secondary: str = "&H0000FFFF" # yellow (unspoken)
outline_col: str = "&H00000000"
back_col: str = "&H64000000"
outline: int = 5
shadow: int = 1
alignment: int = 8 # top-center
margin_v: int = 380
margin_lr: int = 60
play_w: int = 1080
play_h: int = 1920
pop: bool = True # per-word scale bounce
def build_ass(lines: list[list[WordTiming]], style: KaraokeStyle = KaraokeStyle(),
upper: bool = False) -> str: ...
def write_ass(path: str, lines: list[list[WordTiming]], style: KaraokeStyle = KaraokeStyle(),
upper: bool = False) -> str: ... # UTF-8, no BOM; returns path
\k values MUST sum to line_end - line_start in centiseconds (clamp/pad last word). Timestamps render H:MM:SS.cc. Turkish glyphs: font must cover Latin Extended-A; use Turkish-safe uppercase (i→İ, ı→I) before writing; Style Encoding = 1.
2.6 app/services/compose/compose_ffmpeg.py
Pure-FFmpeg filtergraph. Reuses app.utils.utils.get_ffmpeg_binary(), video._get_effective_video_codec() + libx264 fallback, VideoAspect.to_resolution(), utils.font_dir(). Do NOT hardcode "ffmpeg".
from app.models.schema import VideoAspect
_PIP_DIAMETER: int = 480
_PIP_MARGIN: int = 48
_HOOK_DURATION: float = 3.0
_LAYOUTS: dict[str, callable] = {"hook_intro": ..., "pip": ..., "split": ...}
def compose_avatar_over_screen(
screen_path: str,
avatar_path: str,
audio_path: str,
output_file: str,
*,
layout: str = "pip", # "hook_intro" | "pip" | "split"
ass_path: str | None = None, # karaoke .ass burned as last filtergraph node
aspect: VideoAspect = VideoAspect.portrait,
chroma_color: str = "0x00FF00",
chroma_similarity: float = 0.18,
chroma_blend: float = 0.10,
pip_diameter: int = _PIP_DIAMETER,
pip_margin: int = _PIP_MARGIN,
threads: int = 2,
fps: int = 30,
) -> str:
"""Builds filtergraph via _LAYOUTS[layout] up to [comp], then ';[comp]ass=<esc>[final]'
(or ';[comp]null[final]'). subprocess.run(capture_output=True, text=True, check=False);
raise RuntimeError(stderr) on non-zero. libx264 fallback on hw-codec failure.
Keeps -pix_fmt yuv420p -c:a aac -b:a 192k -r 30 for interchange with generate_video."""
...
def _escape_ass_filter_path(p: str) -> str:
"""abspath -> forward slashes -> escape ':' and \"'\" for the libass filter arg."""
...
Layout builders each return the filtergraph string up to [comp]:
def _layout_pip(W: int, H: int, diameter: int, margin: int, chroma: dict) -> str: ...
def _layout_hook_intro(W: int, H: int, diameter: int, margin: int, chroma: dict) -> str: ...
def _layout_split(W: int, H: int, diameter: int, margin: int, chroma: dict) -> str: ...
Validate layout in _LAYOUTS at the boundary (raise ValueError with the allowed set). Fill semantics = scale=...:force_original_aspect_ratio=increase then crop=W:H (crop-to-fill, NOT the fit+letterbox used in combine_videos).
2.7 app/platform/storage/r2.py
Cloudflare R2 via boto3 (S3-compatible). endpoint_url custom, region_name="auto", SigV4 mandatory.
from dataclasses import dataclass
@dataclass(frozen=True)
class PresignResult:
put_url: str
get_url: str
key: str
headers: dict[str, str] # signed headers client MUST echo (e.g. Content-Type)
class R2Client:
def __init__(self) -> None:
"""Reads config.r2: account_id, access_key_id, secret_access_key, bucket, public_base_url."""
...
def presign_put(self, key: str, content_type: str, expires: int = 900) -> str: ...
def presign_get(self, key: str, expires: int = 900,
download_name: str | None = None) -> str: ...
def upload_file(self, local_path: str, key: str, content_type: str | None = None) -> str:
"""put_object; returns the public/permanent object URL (public_base_url + key)."""
...
def presign_upload(self, filename: str, content_type: str, size: int,
prefix: str = "uploads") -> PresignResult:
"""Generates key = f'{prefix}/{uuid4()}{ext}', returns PUT+GET urls. Used by /uploads/presign."""
...
def ensure_cors(self, origins: list[str]) -> None:
"""Idempotent put_bucket_cors (PUT/GET/HEAD). Call from a one-shot bootstrap, not per-request."""
...
r2_client: R2Client # module singleton (lazy)
2.8 app/services/reelforge.py
Thin DTO + stage functions. In the Celery design these stage functions are called by app/workers/tasks.py (each stage = one Celery task). The functions are pure transforms on the shared JobContext dict and return the artifacts they produce (or raise a typed error for Celery retry).
from dataclasses import dataclass
@dataclass(frozen=True)
class ReelForgeParams:
video_subject: str
video_script: str = "" # optional manual script; else LLM-generated
voice_name: str = "" # "elevenlabs:<voice_id>"
voice_rate: float = 1.0
avatar_id: str = ""
avatar_provider: str = "heygen"
caption_style: str = "default"
layout: str = "pip" # pip | hook_intro | split
aspect: str = "9:16"
language: str = "auto"
target_duration_s: int = 30
platforms: tuple[str, ...] = () # empty => skip upload stage
youtube_privacy_status: str = "private"
screen_recording_key: str = "" # R2 key of the uploaded screen recording (optional)
Stage functions operate on JobContext (see §6):
def stage_script(job_id: str, params: ReelForgeParams, ctx: dict) -> dict:
"""reuse script.ugc.generate_ugc_script (or params.video_script). Returns {'script': str}."""
def stage_tts(job_id: str, params: ReelForgeParams, ctx: dict) -> dict:
"""reuse voice.tts (routes to elevenlabs_tts_with_timestamps) + voice.get_audio_duration.
Returns {'audio_key': <r2 key>, 'audio_url': <public url>, 'audio_duration': float,
'words': [[text,start,end],...]}. sub_maker.words serialized to plain tuples;
audio uploaded to R2 (avatar needs a public URL). audio_duration is the TIMING AUTHORITY (§9)."""
def stage_avatar(job_id: str, params: ReelForgeParams, ctx: dict) -> dict:
"""avatar.get_avatar_provider(params.avatar_provider).generate_avatar(
ctx['audio_url'], params.avatar_id, expected_duration_s=ctx['audio_duration']).
Returns {'avatar_key': <r2 key>, 'avatar_video': <local path>, 'avatar_duration': float}."""
def stage_captions(job_id: str, params: ReelForgeParams, ctx: dict) -> dict:
"""captions.words.group_words_into_phrases(ctx['words']) -> ass_karaoke.write_ass.
Runs in PARALLEL with stage_avatar. Returns {'ass_key': <r2 key>, 'ass_path': <local path>}."""
def stage_compose(job_id: str, params: ReelForgeParams, ctx: dict) -> dict:
"""compose.compose_avatar_over_screen(screen, ctx['avatar_video'], audio, out,
layout=params.layout, ass_path=ctx['ass_path']). Returns {'final_key','final_video'}."""
def stage_upload(job_id: str, params: ReelForgeParams, ctx: dict) -> dict:
"""reuse upload_post.cross_post_video(final_video, title, platforms=list(params.platforms)).
Returns {'upload_results': [...], 'request_id': str}."""
Note on execution model: MPT's in-process
ThreadPoolExecutorDAG (documented in the research) is the fallback design if Celery is unavailable. The authoritative ReelForge execution model is Celery (§6). Builders implement the Celery path. The stage function signatures above are shared by both.
3. Config Keys
Config lives in app/config/config.py (loaded via load_config(), bound as module attributes, accessed from app.config import config).
3.1 New sections in config.py (after existing section bindings)
heygen = _SynchronizedConfig(_cfg.get("heygen", {}))
anthropic = _SynchronizedConfig(_cfg.get("anthropic", {}))
r2 = _SynchronizedConfig(_cfg.get("r2", {}))
neon = _SynchronizedConfig(_cfg.get("neon", {}))
CRITICAL — extend save_config()'s explicit persist list (else runtime writes to these sections are silently dropped):
config_to_save["heygen"] = dict(heygen)
config_to_save["anthropic"] = dict(anthropic)
config_to_save["r2"] = dict(r2)
config_to_save["neon"] = dict(neon)
Env override for secrets (mirror the existing redis_host precedence pattern):
anthropic["api_key"] = os.getenv("ANTHROPIC_API_KEY", anthropic.get("api_key", ""))
elevenlabs["api_key"] = os.getenv("ELEVENLABS_API_KEY", elevenlabs.get("api_key", ""))
heygen["api_key"] = os.getenv("HEYGEN_API_KEY", heygen.get("api_key", ""))
r2.update({
"account_id": os.getenv("R2_ACCOUNT_ID", r2.get("account_id", "")),
"access_key_id": os.getenv("R2_ACCESS_KEY_ID", r2.get("access_key_id", "")),
"secret_access_key": os.getenv("R2_SECRET_ACCESS_KEY", r2.get("secret_access_key", "")),
"bucket": os.getenv("R2_BUCKET", r2.get("bucket", "")),
})
neon["database_url"] = os.getenv("NEON_DATABASE_URL", neon.get("database_url", ""))
3.2 config.example.toml stub sections
[anthropic]
api_key = ""
model = "claude-sonnet-5"
[heygen]
api_key = ""
[r2]
account_id = ""
access_key_id = ""
secret_access_key = ""
bucket = ""
public_base_url = ""
[neon]
database_url = ""
3.3 Reuse existing sections (do NOT fork)
[elevenlabs]already exists (api_key,model_iddefaulteleven_multilingual_v2,music_model_id, ...). ADD one new key:word_timestamps(bool, defaulttrue) — toggles the timestamps adapter vs plainelevenlabs_tts.[app]llm keys: setllm_provider = "litellm",litellm_model_name = "anthropic/claude-sonnet-5".- redis / celery: reuse the existing
[app]redis keys (enable_redis,redis_host,redis_port,redis_db,redis_password). ADDcelery_broker_urlandcelery_result_backendunder[app](default both to the composedredis://[:password@]host:port/db). Do NOT create a separate[redis]section. - upload_post: reuse existing
[app]keys (upload_post_api_key,upload_post_username,upload_post_enabled,upload_post_platforms, ...).
3.4 Startup validation (fail-fast, per security rule)
Validate a required secret only when its feature is enabled: require heygen.api_key when a job requests avatar_provider="heygen"; require elevenlabs.api_key when a job uses an elevenlabs: voice; require r2.* and neon.database_url at worker/API startup (they are core infra). Log a clear warning and refuse the job (400) rather than crashing mid-pipeline.
4. SQLAlchemy Data Model
4.0 New constants — app/models/const.py
REELFORGE_STAGE_PENDING = "pending"
REELFORGE_STAGE_RUNNING = "running"
REELFORGE_STAGE_COMPLETE = "complete"
REELFORGE_STAGE_FAILED = "failed"
REELFORGE_DAG: dict[str, tuple[str, ...]] = {
"script": (),
"tts": ("script",),
"avatar": ("tts",),
"captions": ("tts",),
"compose": ("avatar", "captions"),
"upload": ("compose",),
}
REELFORGE_STAGE_WEIGHTS: dict[str, int] = {
"script": 10, "tts": 20, "avatar": 30, "captions": 15, "compose": 20, "upload": 5,
}
Reuse existing TASK_STATE_FAILED = -1, TASK_STATE_COMPLETE = 1, TASK_STATE_PROCESSING = 4 for the Job.state integer.
4.1 app/models/db/base.py
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker, Session
from app.config import config
class Base(DeclarativeBase): ...
engine = create_engine(config.neon.get("database_url"), pool_pre_ping=True, pool_size=5,
max_overflow=10, future=True)
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False, future=True)
def get_session() -> Session: ... # context-managed helper for FastAPI deps + workers
4.2 app/models/db/models.py — tables
All PKs are uuid (str, default uuid4().hex) unless noted. All timestamps TIMESTAMP(timezone=True), server default now(). Immutability rule: append-only for job_events and credit_ledger; never mutate a ledger row.
import uuid
from datetime import datetime
from sqlalchemy import String, Integer, BigInteger, Float, Boolean, ForeignKey, JSON, Text, DateTime, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.db.base import Base
def _uuid() -> str: return uuid.uuid4().hex
class User(Base):
__tablename__ = "users"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)
email: Mapped[str] = mapped_column(String(320), unique=True, index=True, nullable=False)
display_name: Mapped[str] = mapped_column(String(200), default="")
api_key_hash: Mapped[str] = mapped_column(String(128), default="") # sha256 of the user's key
credits: Mapped[int] = mapped_column(Integer, default=0) # denormalized cache of ledger
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
jobs: Mapped[list["Job"]] = relationship(back_populates="user")
class Job(Base):
__tablename__ = "jobs"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)
user_id: Mapped[str] = mapped_column(ForeignKey("users.id"), index=True, nullable=False)
kind: Mapped[str] = mapped_column(String(40), default="avatar_reel")
state: Mapped[int] = mapped_column(Integer, default=4, index=True) # TASK_STATE_*
progress: Mapped[int] = mapped_column(Integer, default=0)
# per-stage status map, e.g. {"script":"complete","tts":"running",...}
stages: Mapped[dict] = mapped_column(JSON, default=dict)
params: Mapped[dict] = mapped_column(JSON, default=dict) # ReelForgeParams dump
failed_stage: Mapped[str] = mapped_column(String(40), default="")
error: Mapped[str] = mapped_column(Text, default="")
celery_task_id:Mapped[str] = mapped_column(String(64), default="", index=True)
result_key: Mapped[str] = mapped_column(String(512), default="") # final R2 key
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True),
server_default=func.now(), onupdate=func.now())
user: Mapped["User"] = relationship(back_populates="jobs")
events: Mapped[list["JobEvent"]] = relationship(back_populates="job")
assets: Mapped[list["Asset"]] = relationship(back_populates="job")
class JobEvent(Base): # append-only telemetry / audit trail
__tablename__ = "job_events"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
job_id: Mapped[str] = mapped_column(ForeignKey("jobs.id"), index=True, nullable=False)
stage: Mapped[str] = mapped_column(String(40), nullable=False)
status: Mapped[str] = mapped_column(String(20), nullable=False) # REELFORGE_STAGE_*
message: Mapped[str] = mapped_column(Text, default="")
payload: Mapped[dict] = mapped_column(JSON, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
job: Mapped["Job"] = relationship(back_populates="events")
class Asset(Base):
__tablename__ = "assets"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)
job_id: Mapped[str] = mapped_column(ForeignKey("jobs.id"), index=True, nullable=True)
user_id: Mapped[str] = mapped_column(ForeignKey("users.id"), index=True, nullable=False)
kind: Mapped[str] = mapped_column(String(40)) # screen|audio|avatar|ass|final|upload
r2_key: Mapped[str] = mapped_column(String(512), nullable=False)
content_type: Mapped[str] = mapped_column(String(120), default="")
size_bytes: Mapped[int] = mapped_column(BigInteger, default=0)
duration_s: Mapped[float] = mapped_column(Float, default=0.0)
meta: Mapped[dict] = mapped_column(JSON, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
job: Mapped["Job"] = relationship(back_populates="assets")
class AvatarPreset(Base):
__tablename__ = "avatar_presets"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)
user_id: Mapped[str] = mapped_column(ForeignKey("users.id"), index=True, nullable=True) # null=global
provider: Mapped[str] = mapped_column(String(40), default="heygen")
provider_avatar_id: Mapped[str] = mapped_column(String(120), nullable=False)
display_name: Mapped[str] = mapped_column(String(200), default="")
voice_name: Mapped[str] = mapped_column(String(120), default="") # "elevenlabs:<voice_id>"
thumbnail_url: Mapped[str] = mapped_column(String(512), default="")
config: Mapped[dict] = mapped_column(JSON, default=dict) # background, style, dimension
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class CreditLedger(Base): # append-only; balance = SUM(delta)
__tablename__ = "credit_ledger"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
user_id: Mapped[str] = mapped_column(ForeignKey("users.id"), index=True, nullable=False)
job_id: Mapped[str] = mapped_column(ForeignKey("jobs.id"), index=True, nullable=True)
delta: Mapped[int] = mapped_column(Integer, nullable=False) # +grant / -debit
reason: Mapped[str] = mapped_column(String(80), nullable=False) # signup|purchase|job_debit|refund
balance_after: Mapped[int] = mapped_column(Integer, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
4.3 Repositories (app/models/db/repositories.py)
Repository pattern per repo convention — business logic depends on these, not on SQLAlchemy directly.
class JobRepository:
def __init__(self, session: Session) -> None: ...
def create(self, user_id: str, kind: str, params: dict) -> Job: ...
def get(self, job_id: str) -> Job | None: ...
def list_for_user(self, user_id: str, limit: int = 50, offset: int = 0) -> list[Job]: ...
def update_stage(self, job_id: str, stage: str, status: str) -> Job | None: ...
def set_progress(self, job_id: str, progress: int) -> None: ...
def mark_failed(self, job_id: str, stage: str, error: str) -> Job | None: ... # first-failure guard
def mark_complete(self, job_id: str, result_key: str) -> Job | None: ...
class AssetRepository: ... # create, get, list_for_job
class CreditRepository:
def balance(self, user_id: str) -> int: ...
def debit(self, user_id: str, amount: int, job_id: str, reason: str) -> CreditLedger: ... # atomic
def grant(self, user_id: str, amount: int, reason: str) -> CreditLedger: ...
mark_failed implements the first-failure guard: if the job is already TASK_STATE_FAILED with a non-empty error, return unchanged (earliest root cause wins) — mirroring task.py::_mark_task_failed.
5. v1 API Contract
All routes served under /api/v1 (from new_router(); prefix is /api/v1, NOT bare /v1). Controller: app/domains/reels/router.py. Envelope: utils.get_response(status, data, message) → {status, data?, message?}. Errors: raise HttpException(task_id=..., status_code=..., message=...). Register in app/router.py via root_api_router.include_router(reels_router).
Add request/response Pydantic models to app/models/schema.py (subclass BaseResponse; use model_config = ConfigDict(extra="allow") for status data).
5.1 Endpoints
| Method | Path (full) | Request body | Success data |
|---|---|---|---|
| POST | /api/v1/uploads/presign |
PresignRequest{filename, content_type, size>=1} |
PresignData{upload_url, get_url, key, headers} |
| POST | /api/v1/jobs |
JobCreateRequest{params: ReelForgeParams-shape, avatar_id?, voice_id?} |
JobData{job_id, state, progress} |
| GET | /api/v1/jobs/{job_id} |
— | JobData{job_id, state, progress, stages, failed_stage?, error?, result_url?} |
| POST | /api/v1/jobs/{job_id}/retry |
— | JobData{job_id, state, progress} (re-enqueues from failed_stage) |
| GET | /api/v1/avatars |
— | list[dict] (merged AvatarPreset rows + provider list_avatars()) |
| GET | /api/v1/voices |
— | list[dict] (ElevenLabs GET /v1/voices normalized) |
| GET | /api/v1/me |
— | MeData{user_id, email, credits, jobs_count} |
5.2 Handler contracts (signatures)
router = new_router() # /api/v1
@router.post("/uploads/presign", response_model=PresignResponse, summary="Presign an upload")
def presign_upload(request: Request, body: PresignRequest): ...
@router.post("/jobs", response_model=JobResponse, summary="Create a job")
def create_job(request: Request, body: JobCreateRequest): ...
# 1. auth -> user (base.verify_token / x-api-key). 2. credits.balance check (402 if insufficient).
# 3. validate enabled-feature secrets (§3.4). 4. JobRepository.create(...).
# 5. pipeline.start_pipeline(job_id, params) -> celery_task_id; persist it.
# 6. credits.debit(...). 7. return get_response(200, {job_id, state, progress}).
@router.get("/jobs/{job_id}", response_model=JobResponse, summary="Get job status")
def get_job(request: Request, job_id: str = Path(...)): ...
# JobRepository.get; 404 via HttpException if None; add result_url via r2.presign_get(result_key).
@router.post("/jobs/{job_id}/retry", response_model=JobResponse, summary="Retry a failed job")
def retry_job(request: Request, job_id: str = Path(...)): ...
# only if state == TASK_STATE_FAILED; rebuild chain from job.failed_stage (§6.3).
@router.get("/avatars", response_model=AvatarListResponse, summary="List avatars")
def list_avatars(request: Request): ...
@router.get("/voices", response_model=VoiceListResponse, summary="List voices")
def list_voices(request: Request): ...
@router.get("/me", response_model=MeResponse, summary="Current user")
def me(request: Request): ...
Reuse base.get_task_id(request) for the per-request id in error messages, and video.py security helpers (_sanitize_upload_filename, file_security.resolve_path_within_directory) for any filename handling. To gate the whole group behind auth: new_router(dependencies=[Depends(base.verify_token)]).
6. Celery Chain + Shared Job Context
6.1 app/workers/celery_app.py
import os
from celery import Celery
from app.config import config
def _redis_url() -> str:
pw = config.app.get("redis_password", "")
auth = f":{pw}@" if pw else ""
return (config.app.get("celery_broker_url")
or f"redis://{auth}{config.app.get('redis_host','localhost')}:"
f"{config.app.get('redis_port',6379)}/{config.app.get('redis_db',0)}")
celery_app = Celery("reelforge", broker=_redis_url(),
backend=config.app.get("celery_result_backend") or _redis_url(),
include=["app.workers.tasks"])
celery_app.conf.update(
task_serializer="json", result_serializer="json", accept_content=["json"],
timezone="UTC", enable_utc=True,
task_acks_late=True, worker_prefetch_multiplier=1,
broker_connection_retry_on_startup=True, result_expires=3600,
task_routes={"app.workers.tasks.stage_avatar_task": {"queue": "render"},
"app.workers.tasks.stage_compose_task": {"queue": "render"}},
)
6.2 Shared Job Context (app/workers/context.py)
The JobContext is a plain JSON-serializable dict passed between chain stages (each task's return value becomes the next task's first arg). It MUST be JSON-safe — never place live objects (e.g. SubMaker) in it; the ElevenLabs sub_maker.words is flattened to list[[text, start, end]].
from typing import TypedDict
class JobContext(TypedDict, total=False):
job_id: str
params: dict # ReelForgeParams.__dict__
# script stage
script: str
# tts stage (audio_duration is the SINGLE TIMING AUTHORITY, §9)
audio_key: str
audio_url: str # public R2 URL (HeyGen needs a URL)
audio_duration: float
words: list[list] # [[text, start_s, end_s], ...] from ElevenLabs alignment
# avatar stage (parallel)
avatar_key: str
avatar_video: str # local path (re-hosted from HeyGen)
avatar_duration: float
# captions stage (parallel)
ass_key: str
ass_path: str # local path
# compose stage
final_key: str
final_video: str
# upload stage
upload_results: list
request_id: str
6.3 app/workers/tasks.py + pipeline.py
Fan-out/fan-in: avatar and captions both depend only on tts and run concurrently; compose merges them. Use a Celery chord for the parallel middle (group of avatar+captions, callback = compose), wrapped in a chain:
from celery import chain, group, chord
from app.workers.celery_app import celery_app
@celery_app.task(bind=True, autoretry_for=(ConnectionError,), max_retries=3,
retry_backoff=True, soft_time_limit=120, time_limit=150)
def stage_script_task(self, ctx: dict) -> dict: ... # returns {**ctx, **stage_script(...)}
@celery_app.task(bind=True, autoretry_for=(ConnectionError,), max_retries=3,
retry_backoff=True, soft_time_limit=180, time_limit=210)
def stage_tts_task(self, ctx: dict) -> dict: ...
@celery_app.task(bind=True, autoretry_for=(ConnectionError,), max_retries=2,
retry_backoff=True, soft_time_limit=1800, time_limit=1860) # HeyGen is slow
def stage_avatar_task(self, ctx: dict) -> dict: ...
@celery_app.task(bind=True, soft_time_limit=120, time_limit=150)
def stage_captions_task(self, ctx: dict) -> dict: ...
@celery_app.task(bind=True, soft_time_limit=1800, time_limit=1860) # ffmpeg compose + broll + upload; was 600s, too tight on a shared CPU box
def stage_compose_task(self, results: list[dict]) -> dict:
"""chord callback: results = [avatar_ctx, captions_ctx]. Merge both partials into one ctx
(both carry the same base keys; union the avatar_* and ass_* keys), then stage_compose(...)."""
...
@celery_app.task(bind=True, autoretry_for=(ConnectionError,), max_retries=5,
retry_backoff=True, soft_time_limit=120, time_limit=150)
def stage_upload_task(self, ctx: dict) -> dict: ...
# pipeline.py
def build_chain(job_id: str, params: ReelForgeParams):
parallel = chord(
group(stage_avatar_task.s(), stage_captions_task.s()),
stage_compose_task.s(),
)
steps = [stage_script_task.s({"job_id": job_id, "params": params.__dict__}),
stage_tts_task.s(), parallel]
if params.platforms:
steps.append(stage_upload_task.s())
return chain(*steps)
def start_pipeline(job_id: str, params: ReelForgeParams) -> str:
async_result = build_chain(job_id, params).apply_async()
return async_result.id # persist to Job.celery_task_id
State reporting: every task, on start/success/failure, calls telemetry.events.record_event(job_id, stage, status, payload) (writes a JobEvent row) and JobRepository.update_stage + set_progress (progress via REELFORGE_STAGE_WEIGHTS). Each task defines on_failure → JobRepository.mark_failed(job_id, stage, str(exc)) (first-failure guard). Retry re-enqueues a sub-chain starting at job.failed_stage seeded with the last-good JobContext reconstructed from Asset rows.
Progress: progress = round(100 * sum(weights of completed stages) / sum(weights of active stages)). Upload weight excluded when params.platforms is empty.
7. Dependencies to Add
Single source of truth: pyproject.toml [project].dependencies (mirror in requirements.txt, then uv lock). requires-python = ">=3.11". None of these downgrade existing pins.
celery[redis]==5.5.3 # broker+backend share existing redis==5.2.0; needs click 8.1.x (locked OK)
sqlalchemy==2.0.43 # 2.x, Pydantic-v2-friendly
alembic==1.16.4 # migrations; pulls Mako
boto3==1.40.11 # R2/S3; botocore allows urllib3<3 (locked 2.7.0 OK). Pin whatever uv resolves.
psycopg[binary]==3.2.9 # Postgres/Neon driver (psycopg 3, preferred with SQLAlchemy 2.0)
Already present — reuse, do NOT re-add: redis==5.2.0, requests==2.33.1, faster-whisper==1.1.0, litellm==1.86.2 (Claude access — keep; native anthropic SDK is OPTIONAL and recommended to SKIP), moviepy==2.2.1, fastapi==0.136.3.
Optional / skip: anthropic==0.69.0 — only if you need Anthropic-only features (prompt caching, Messages Batches). litellm already routes to Claude with one retry/routing layer.
Dev (already present): pytest==9.1.1, coverage==7.15.1, ruff==0.15.21. Add tests per repo 80% coverage rule: unit-test filtergraph string builders (pure string asserts), ASS output, char→word grouping, and repository CRUD against a SQLite test DB.
8. Timing Rule (normative)
ElevenLabs /with-timestamps alignment is the sole timing authority. Its word timings drive BOTH captions AND avatar-duration validation.
stage_ttscallsvoice.tts(...)→ routes toelevenlabs_tts_with_timestamps(§9), which returns aSubMakercarrying.words: list[WordTiming]and.offset(100ns). Usealignment(NOTnormalized_alignment) so caption text matches the user's script.- Compute the authoritative
audio_duration = alignment.character_end_times_seconds[-1](equivalentlysub_maker.offset[-1][1] / 10_000_000, equivalentlyvoice.get_audio_duration(sub_maker)). Store it inJobContext["audio_duration"]andAsset(kind="audio").duration_s. stage_captionsbuilds the ASS only fromJobContext["words"](the same alignment). No re-transcription.\ksums per phrase-line must equal that phrase's(end-start)in centiseconds; the final caption end MUST equalaudio_duration.stage_avatarpassesexpected_duration_s=JobContext["audio_duration"]togenerate_avatar. HeyGen's returneddata["duration"]MUST match within a tolerance of±0.25s; otherwise log a warning and record aJobEvent(stage="avatar", status="warning", payload={expected, actual}). Since HeyGen lip-syncs to the exact same audio file that produced the alignment, they align 1:1 with no offset math.stage_composeuses-shortest; the burned ASS (caption timeline) and the avatar/audio track share the identical time base (0.0 = audio start), so no re-sync is needed.
Consequence: there is exactly one duration number and one word-timing array in the whole pipeline. Captions and avatar never derive timing independently.
9. ElevenLabs /with-timestamps Adapter Wiring (voice.py)
Edit app/services/voice.py::tts() (the is_elevenlabs_voice branch) to route by config:
elif is_elevenlabs_voice(voice_name):
parts = voice_name.split(":")
if len(parts) >= 2:
voice_id = parts[1]
if config.elevenlabs.get("word_timestamps", True):
from app.services.tts.elevenlabs_timestamps import elevenlabs_tts_with_timestamps
return elevenlabs_tts_with_timestamps(text, voice_id, voice_file, voice_rate, voice_volume)
return elevenlabs_tts(text, voice_id, voice_file, voice_rate, voice_volume)
logger.error(f"Invalid elevenlabs voice name format: {voice_name}")
return None
The adapter (§2.2) reuses the existing elevenlabs_tts auth/retry/error pattern: header {"xi-api-key": config.elevenlabs.get("api_key","")}, model_id default eleven_multilingual_v2, voice_settings={"stability":0.5,"similarity_boost":0.75,"style":0.0,"use_speaker_boost":True}, params={"output_format":"mp3_44100_128"}, 3 retries, non-retryable {401,403,422} + {"voice_disabled","voice_access_denied","unauthorized"}. It decodes audio_base64 to voice_file, then builds the SubMaker via _build_submaker_from_elevenlabs_alignment (one legacy .subs/.offset segment per non-space char so the tolerant _match_script_line accumulator rebuilds exact sentence counts; .cues stays empty so the legacy branch is taken). Karaoke data (.words, .characters) rides along invisibly to create_subtitle/get_audio_duration. Guard downstream reads with getattr(sub_maker, "words", []).
10. Build Order (dependency-ordered checklist for agents)
- Config + deps (§3, §7): add sections to
config.py/config.example.toml, extendsave_config(), add deps,uv lock. - Persistence (§4):
app/models/db/*, Alembic init, first migration. - Storage (§2.7):
app/platform/storage/r2.py+ one-shot CORS bootstrap. - TTS adapter (§2.2, §9):
elevenlabs_timestamps.py+voice.tts()branch. - Script (§2.1):
script/ugc.py(litellm→Claude, zero adapter code). - Avatar (§2.3, §2.4):
avatar/base.py+avatar/heygen.py. - Captions (§2.5):
captions/words.py+captions/ass_karaoke.py. - Compose (§2.6):
compose/compose_ffmpeg.py+ 3 layouts; ffmpeg--enable-libassstartup check. - Stages + workers (§6, §2.8):
reelforge.pystage fns,workers/*(celery_app, context, tasks, pipeline),telemetry/*. - API (§5):
app/domains/reels/router.py, schema models, register inapp/router.py. - Tests (§7): unit + integration + one real-ffmpeg smoke test; verify 80% coverage.
Concurrency-safety invariants (non-negotiable): the DB Job row (not the in-memory MPT task doc) is the persistent source of truth for parallel stages; use JobRepository.update_stage (atomic per-stage write) rather than overwriting the whole stages map from concurrent workers. JobContext must stay JSON-serializable (strip SubMaker). Retry honors the first-failure guard and never resurrects a deleted job.