Skip to content

Show it a video you love. Get a new video in the same style. An AI crew (Claude Code or Codex) plans, builds and reviews it with you.

8.6 KB
Raw Blame
"""Command line for the Motion Score (run through scripts/motion_score.py).

    motion_score.py validate <score>                      check it; every problem with its file and field
    motion_score.py compile  <score> --out build/src/score.js   runtime + resolved data, one <script> for the engine
    motion_score.py from-ref <project> [--out build/score] [--force]
        write a score whose camera does what the reference camera did (plan.json shots × analysis/fingerprint.json);
        existing shot files are kept unless --force
    motion_score.py predict  <project> [--score build/score]
        what perception will measure for this camera, against the reference, before anything is rendered
        → out/check/score_predict.json
    motion_score.py optimize <project> [--score build/score] [--shots S3,S8] [--budget 240] [--peaks] [--tune-amounts] [--apply]
        search each shot's move timing and easing (and, with --peaks, the shots around each plan peak together, shaping
        the predicted tension at the hit) for the version closest to the reference, render-free (CMA-ES).
        Proposal → out/check/score_tuned/ + out/check/score_optimize.json (or --out); --apply writes it into the score.
    motion_score.py sample   <score> <shot> [--step 0.25]   the camera over a shot, as numbers

<score> is a folder (film.json + shots/*.json) or one .json file.
"""
from __future__ import annotations

import argparse
import json
import os
import sys

from . import model, predict, transfer
from .runtime import Score
from perception.cli import ensure_reference

RUNTIME_JS = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "assets", "score", "score.js")


def _load_json(p: str):
    with open(p, encoding="utf-8") as f:
        return json.load(f)


def compile_js(resolved: dict) -> str:
    data = {k: v for k, v in resolved.items() if not k.startswith("_")}
    with open(RUNTIME_JS, encoding="utf-8") as f:
        runtime = f.read()
    return (f"// Generated by motion_score.py compile — do not edit; edit the score and compile again.\n{runtime}\n"
            f"Score.load({json.dumps(data, ensure_ascii=False, separators=(',', ':'))});\n")


def write_atomic(path: str, text: str):
    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        f.write(text)
    os.replace(tmp, path)


def _report(diag: model.Diagnostics) -> str:
    return "\n".join([f"error   {e}" for e in diag.errors] + [f"warning {w}" for w in diag.warnings]) or "ok"


def tempo(project: str) -> tuple[float, float]:
    """bpm and first-beat offset of the film's music: config the plan chose, else the reference's."""
    plan = _load_json(os.path.join(project, "plan.json"))
    m = plan.get("music") or {}
    if m.get("bpm"):
        return float(m["bpm"]), float(m.get("offset", 0.0))
    au = _load_json(os.path.join(project, "analysis", "report.json")).get("audio") or {}
    return float(au.get("bpm") or 120.0), 0.0


def main(argv: list[str] | None = None):
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")
    ap = argparse.ArgumentParser(prog="motion_score.py", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    v = sub.add_parser("validate"); v.add_argument("score")
    c = sub.add_parser("compile"); c.add_argument("score"); c.add_argument("--out", required=True)
    f = sub.add_parser("from-ref"); f.add_argument("project"); f.add_argument("--out"); f.add_argument("--force", action="store_true")
    p = sub.add_parser("predict"); p.add_argument("project"); p.add_argument("--score")
    o = sub.add_parser("optimize"); o.add_argument("project"); o.add_argument("--score"); o.add_argument("--shots")
    o.add_argument("--budget", type=int, default=240); o.add_argument("--peaks", action="store_true")
    o.add_argument("--tune-amounts", action="store_true"); o.add_argument("--apply", action="store_true"); o.add_argument("--seed", type=int, default=0)
    o.add_argument("--out", help="where the proposal and report go (default <project>/out/check)")
    s = sub.add_parser("sample"); s.add_argument("score"); s.add_argument("shot"); s.add_argument("--step", type=float, default=0.25)
    a = ap.parse_args(argv)

    if a.cmd == "validate":
        try:
            sc, origin = model.load(a.score)
        except model.ScoreError as e:
            print(_report(e.diag))
            sys.exit(1)
        _, diag = model.resolve_score(sc, origin)
        print(_report(diag))
        sys.exit(0 if diag.ok else 1)

    if a.cmd == "compile":
        try:
            r = model.compile_path(a.score)
        except model.ScoreError as e:
            print(_report(e.diag))
            sys.exit(1)
        write_atomic(a.out, compile_js(r))
        for w in r["_warnings"]:
            print("warning", w)
        print(f"{len(r['shots'])} shots → {a.out}")

    elif a.cmd == "from-ref":
        P = a.project
        out = a.out or os.path.join(P, "build", "score")
        bpm, offset = tempo(P)
        authored = transfer.from_reference(_load_json(os.path.join(P, "plan.json")), ensure_reference(P), bpm, offset)
        film = {k: v for k, v in authored.items() if k != "shots"}
        os.makedirs(out, exist_ok=True)
        if a.force or not os.path.exists(os.path.join(out, "film.json")):
            write_atomic(os.path.join(out, "film.json"), json.dumps(film, ensure_ascii=False, indent=1))
        kept = 0
        for shot in authored["shots"]:
            if not a.force and os.path.exists(os.path.join(out, "shots", f"{shot['id']}.json")):
                kept += 1
                continue
            model.save_shot(out, shot)
        print(f"{len(authored['shots']) - kept} shot files written, {kept} kept → {out}")
        for shot in authored["shots"]:
            mv = shot["camera"]["moves"]
            print(f"  {shot['id']} ← ref #{shot['ref_shot']}: " + ("; ".join(f"{m['at']} {m['dur']} {m['by']} {m['ease'] if isinstance(m['ease'], str) else list(m['ease'])[0]}" for m in mv) or "still"))

    elif a.cmd == "predict":
        P = a.project
        try:
            r = model.compile_path(a.score or os.path.join(P, "build", "score"))
        except model.ScoreError as e:
            print(_report(e.diag))
            sys.exit(1)
        res = predict.against_reference(Score(r), ensure_reference(P))
        write_atomic(os.path.join(P, "out", "check", "score_predict.json"), json.dumps(res, ensure_ascii=False, indent=1))
        print(f"predicted camera match: {res['camera_score']}")
        for x in res["findings"]:
            print(f"  [{x['severity']}] {x['where']}: {x['text']}")

    elif a.cmd == "optimize":
        from optimize.run import optimize_project
        P = a.project
        sdir = a.score or os.path.join(P, "build", "score")
        try:
            rep = optimize_project(P, sdir, shots=a.shots.split(",") if a.shots else None, budget=a.budget, peaks=a.peaks,
                                   tune_amounts=a.tune_amounts, seed=a.seed)
        except model.ScoreError as e:
            print(_report(e.diag))
            sys.exit(1)
        tuned = rep.pop("score")
        check = a.out or os.path.join(P, "out", "check")
        out = os.path.join(check, "score_tuned")
        write_atomic(os.path.join(out, "film.json"), json.dumps({k: v for k, v in tuned.items() if k != "shots"}, ensure_ascii=False, indent=1))
        for shot in tuned["shots"]:
            model.save_shot(out, shot)
        write_atomic(os.path.join(check, "score_optimize.json"), json.dumps(rep, ensure_ascii=False, indent=1))
        for c in rep["changes"]:
            print(f"  {c['shot']} {'move ' + str(c['move']) if 'move' in c else 'shake ' + str(c['shake'])}: {json.dumps(c['from'], ensure_ascii=False)} → {json.dumps(c['to'], ensure_ascii=False)}")
        print(f"{len(rep['changes'])} changes in {rep['seconds']} s → {out}")
        if a.apply and os.path.isdir(sdir):
            changed = {c["shot"] for c in rep["changes"]}
            for shot in tuned["shots"]:
                if shot["id"] in changed:
                    model.save_shot(sdir, shot)
            print(f"applied to {sdir}: {', '.join(sorted(changed)) or 'nothing'}")

    elif a.cmd == "sample":
        try:
            sc = Score(model.compile_path(a.score))
        except model.ScoreError as e:
            print(_report(e.diag))
            sys.exit(1)
        sh = sc.shots[a.shot]
        t = sh["start"]
        while t <= sh["end"] + 1e-9:
            c = sc.cam(a.shot, t)
            print(f"{t:7.3f}s  x {c['x']:8.1f}  y {c['y']:8.1f}  zoom {c['zoom']:.4f}  rot {c['rot']:+.4f}")
            t += a.step