creative-brain-os / scripts /ab_presenter.py
kpranav022's picture
Claude Opus 5.5 (1M context)
Stop paying twice, measure every run, and make the picture, voice and props hold up
13354e2
Raw History Blame Contribute Delete
6.48 kB
"""Render one candidate once per presenter model, for a side-by-side A/B.
python scripts/ab_presenter.py <asset_id> <candidate> veed/fabric-1.0 fal-ai/creatify/aurora
python scripts/ab_presenter.py <asset_id> <candidate> <models...> --yes # PAID
Dry run by default: prints the plan and each model's estimated cost, renders
nothing. With --yes every model is a full paid render (b-roll included), saved
and tracked like any other. See evals/AB_PRESENTER.md.
The plan is built once, the way GET /render-plan builds it, so every run gets the
same segments; only settings.omnihuman_model changes between runs (in-process).
"""
from __future__ import annotations
import argparse
import json
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
RESULTS = ROOT / "evals" / "results"
from app.core.config import settings # noqa: E402
from app.services import costs # noqa: E402
from app.services.omnihuman import ADAPTERS, DEFAULT_MODEL, PER_SECOND # noqa: E402
def build_plan(store: Any, asset_id: str, candidate_number: int, mode: str | None) -> dict:
"""Same as routes.get_candidate_render_plan, without HTTP."""
from app.schemas import FinalOutput
from app.services.video import build_render_plan
asset = store.get_asset(asset_id)
if not asset or not asset.get("agent_outputs"):
raise SystemExit("Generation not found or not complete")
final = FinalOutput.model_validate(asset["agent_outputs"])
candidate = next((c for c in final.candidates if c.candidate_number == candidate_number), None)
if candidate is None:
raise SystemExit(f"No candidate {candidate_number} on this asset")
return build_render_plan(candidate, mode or final.render_mode).model_dump(mode="json")
def presenter_seconds(plan: dict) -> float:
"""Seconds the presenter model animates, by mode (as costs.render_estimate counts them)."""
segments = plan.get("segments") or []
total = sum(float(s.get("duration_seconds") or 0) for s in segments)
mode = plan.get("render_mode") or settings.render_mode
if mode == "continuous":
return 0.0
if mode in ("greenscreen", "split"):
return total
return total - sum(float(s.get("duration_seconds") or 0) for s in segments if s.get("is_broll"))
def estimate(plan: dict, model: str) -> float:
"""costs.render_estimate, with OmniHuman's rate swapped for this model's."""
mode = plan.get("render_mode") or settings.render_mode
base = costs.render_estimate(plan, mode)
return round(base + presenter_seconds(plan) * (PER_SECOND[model] - costs.OMNIHUMAN_PER_SECOND), 4)
def main(argv: list[str] | None = None, store: Any = None, render: Any = None) -> dict:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("asset_id")
ap.add_argument("candidate", type=int)
ap.add_argument("models", nargs="*", default=[DEFAULT_MODEL])
ap.add_argument("--mode", help="render mode override (default: the generation's)")
ap.add_argument("--yes", action="store_true", help="actually render (PAID)")
args = ap.parse_args(argv)
unknown = [m for m in args.models if m not in ADAPTERS]
if unknown: # the render would still run them with OmniHuman's shape; an A/B shouldn't guess
raise SystemExit(f"Unknown presenter model(s) {unknown}. Supported: {', '.join(ADAPTERS)}")
if store is None:
from app.services.supabase_store import SupabaseStore
store = SupabaseStore()
plan = build_plan(store, args.asset_id, args.candidate, args.mode)
mode = plan.get("render_mode") or settings.render_mode
print(f"plan: {len(plan['segments'])} segments, mode={mode}, "
f"presenter seconds={presenter_seconds(plan):.1f}")
for s in plan["segments"]:
print(f" #{s['segment_number']} {s['duration_seconds']:.1f}s {'b-roll' if s.get('is_broll') else 'presenter'}")
if mode == "continuous" or not settings.use_omnihuman_presenter:
print("WARNING: this render never calls the presenter model (continuous mode or "
"USE_OMNIHUMAN_PRESENTER off) — every run would be the same. Pass --mode classic.")
report: dict[str, Any] = {"asset_id": args.asset_id, "candidate": args.candidate, "mode": mode,
"dry_run": not args.yes, "plan": plan, "runs": []}
for m in args.models:
print(f"{m}: estimated ${estimate(plan, m):.2f}")
if not args.yes:
print("dry run — nothing rendered. Re-run with --yes to render (paid).")
return report
if render is None:
from app.services.render import run_render as render
original = settings.omnihuman_model
try:
for m in args.models:
settings.omnihuman_model = m
run: dict[str, Any] = {"model": m, "estimated_cost_usd": estimate(plan, m)}
started = time.monotonic()
try:
result = render(args.asset_id, args.candidate, plan)
run.update(render_id=result.get("render_id"), file=result.get("file_name"),
recovered=result.get("recovered"))
rows = store.select("renders", filters={"id": result.get("render_id")},
columns="scorecard,critic", limit=1) if result.get("render_id") else []
row = rows[0] if rows else {}
run["scorecard"] = row.get("scorecard")
run["critic"] = row.get("critic") or result.get("critic")
except Exception as exc: # noqa: BLE001 - one model failing shouldn't lose the others
run["error"] = str(exc)[:500]
run["wall_seconds"] = round(time.monotonic() - started, 1)
report["runs"].append(run)
critic = run.get("critic") or {}
print(f"{m}: {run.get('render_id') or 'FAILED'} {run.get('file') or run.get('error')} "
f"{run['wall_seconds']}s, critic issues={len(critic.get('issues') or [])}")
finally:
settings.omnihuman_model = original
RESULTS.mkdir(parents=True, exist_ok=True)
out = RESULTS / f"ab_presenter_{datetime.now(timezone.utc):%Y%m%dT%H%M%SZ}.json"
out.write_text(json.dumps(report, indent=2, default=str))
print(f"wrote {out}")
return report
if __name__ == "__main__":
main()