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.

Style compiler: perception fingerprint, Motion Score IR, CMA-ES camera optimizer

許元豪6a199476f7a1
diff --git a/.claude/skills/video-clone/CONTRACT.md b/.claude/skills/video-clone/CONTRACT.md
index a60b263..42657b8 100644
--- a/.claude/skills/video-clone/CONTRACT.md
+++ b/.claude/skills/video-clone/CONTRACT.md
@@ -2,6 +2,8 @@
每支影片一個資料夾 `projects/<id>/`。Agent(Claude Code 或 Codex)與 App 後端只透過這些檔案溝通,
所以兩種 agent 都能接,前端也只要讀檔案就能畫出畫面。**Agent 必須照這裡的路徑與欄位寫檔。**
+**JSON 檔必須是標準 JSON**(不能有註解、結尾逗號、單引號):系統每一步都會檢查必產的 JSON 能不能解析、最外層型態對不對,
+壞掉的會請同一個 agent 修一次,再壞就停下來。
```
projects/<id>/
@@ -10,6 +12,8 @@ projects/<id>/
inputs/ 使用者上傳的素材 / 音檔 / LRC(唯讀)
analysis/
report.json analyze.py 產出(量測數據)
+ fingerprint.json analyze.py 產出:Style Fingerprint(每格運鏡、每鏡擬合的緩動、張力曲線與高潮形狀、切點對拍、cadence、色彩),
+ fingerprint.png 是同一時間軸的圖;格式見 docs/COMPILER.md
sheet_1fps.jpg 每秒一格總覽
sheet_scenes.jpg 每個鏡頭中間格
STYLE.md ← agent:風格拆解(給人看)
@@ -107,6 +111,12 @@ projects/<id>/
```
build/production.json 導演:{ cast_sheet, characters, chunks: [{id, shots}], shot_files, how_to_preview, how_to_render, shared_readonly,
prerender: { cwd, cmd 含 {start} {end} } ← 有影格快取的引擎才寫;每段通過審查後系統自動在背景渲染那段的正式影格 }
+build/score/film.json Motion Score(docs/COMPILER.md):{ version, fps, bpm, offset, duration, cues: { 名稱: 時間 } }
+build/score/shots/<shot>.json 每鏡一檔:{ id, start, end, ref_shot, cadence, camera: { base: {x,y,zoom,rot}, moves: [{ at, dur|until, to|by, ease, from_ref }], shakes, drift },
+ tracks };時間寫法 "B12-2f"、"P1_hit+1b"、"S+0.25s";motion_score.py validate / predict / compile
+out/check/score_predict.json motion_score.py predict:不渲染就預測的每鏡運鏡 vs 參考片(camera_score、findings)
+out/check/score_optimize.json motion_score.py optimize:每組鏡頭的 before/after 成本、changes(改了哪個運鏡的什麼,原值記在 "tuned")
+out/check/score_tuned/ optimize 的提案(同 build/score 格式);--apply 才寫回 build/score
out/check/cast/sheet_<角色>.jpg 每個角色一張設定圖(正面/3/4/側面/表情/姿勢);sheet.jpg = 全角色並排
build/assets/cast/<角色>.js 每個角色一個定義檔(多角色時各自由一組審查+修正同時進行,不能共用一個檔)
out/check/cast/review_<角色>.json / fixes_<角色>.json 個別角色的審查與修正(要改共用骨架的項目 status: shared,由導演統一改)
@@ -119,6 +129,10 @@ out/check/shots/<Cn>.fixes.json 製作 agent 修正:[{ shot, issue, change, b
out/check/critique.json 最後評審:{ pass, peaks:[{id, ours, ref, strip, verdict: ours_better|equal|ref_better, why}], scores, score_notes,
shots:[{id, score, why}], must_fix, needs_user, verified_fixes, nice_to_have, summary }
任何高潮 ref_better 都不會通過(系統會自動補成必修)
+out/check/fingerprint.json compare.py:我們成片的 Style Fingerprint(鏡頭 id = plan 的 shot id)
+out/check/style_distance.json compare.py:和參考片的實測距離 { overall, components:{tension, peaks, camera, rhythm, look, frames: {score…}},
+ shots:[{id, ref_shot, camera, look}], findings:[{component, where, severity: major|minor, text}] }
+out/check/fingerprint_overlay.png 參考片的張力與運鏡速度(DTW 對齊到我們的時間軸)疊在我們的上面
out/check/motion/motion.json motion_check.py:硬切點、長時間靜止、黑格、閃白、片尾硬切黑(每項附前後影格 strip)
out/check/fixes.json 導演修成片:[{ issue, shot, time, change, before, after, status }]
analysis/lyrics/subs.lrc|.json 使用者貼的歌詞,自動對時結果(每句時間與匹配度)
diff --git a/.claude/skills/video-clone/SKILL.md b/.claude/skills/video-clone/SKILL.md
index 260f9b3..0a51dd2 100644
--- a/.claude/skills/video-clone/SKILL.md
+++ b/.claude/skills/video-clone/SKILL.md
@@ -98,7 +98,9 @@ peaks 裡的鏡頭標 `hero: true`。核准前先把每個爆點那一格做到
1. **企劃核准前**:plan.json 的 `required_inputs` 列出只有使用者能給的東西(歌詞文字、自家角色設計圖、產品照、Logo)。
沒提供也沒略過就不能核准,生產中不會再卡在「缺歌詞」。
-2. **導演建置**:共用素材、角色定義、分段(`build/production.json`,每段 2–5 鏡)。
+2. **導演建置**:共用素材、角色定義、分段(`build/production.json`,每段 2–5 鏡),以及 **Motion Score**(`build/score/`):
+ `scripts/motion_score.py from-ref` 把參考片每鏡實測的運鏡(時長、量、擬合的緩動)轉成資料,導演照企劃調整構圖目標,
+ `predict` 不渲染就預測和參考片的差距,`compile` 給引擎載入。鏡頭檔用 `Score.cam(id, t)` 取運鏡、`Score.cue()` / `Score.beat()` 取時間,不手寫。
3. **角色關**:先出角色設定圖(正面、表情 8+、本片會用到的姿勢 6+)→ 全新對話的審查員用人眼清單看全解析度裁切 → 不過就修,過了才開始做鏡頭。
2D 向量角色一律用 `assets/vector_rig/`(骨架+一體輪廓;見它的 README),不准用圓形、長方形另外拼頭、身體、手臂。
4. **分段製作+即時審查**:多個製作 agent 平行做不同段;每段一做完,就由一個全新的審查員看那一段的每鏡 sheet、strip 與角色裁切,
diff --git a/.claude/skills/video-clone/assets/engine-kit/ENGINE_BRIEF.md b/.claude/skills/video-clone/assets/engine-kit/ENGINE_BRIEF.md
index 436a257..44a5063 100644
--- a/.claude/skills/video-clone/assets/engine-kit/ENGINE_BRIEF.md
+++ b/.claude/skills/video-clone/assets/engine-kit/ENGINE_BRIEF.md
@@ -18,6 +18,9 @@ building one more.
`<!-- SCENES -->` with `<script src="src/scenes/demo.js"></script>`.
- `package.json` → `template/package.json` (rename `name`; add deps only if truly needed).
- `new_project.sh` → `scripts/new_project.sh`.
+- `.claude/skills/video-clone/assets/score/score.js` — the Motion Score runtime (docs/COMPILER.md). Projects compile
+ their score into `build/src/score.js` and load it before the scenes; scenes take the camera from
+ `Score.cam(id, t)` → `camBegin(c.x, c.y, c.zoom, c.rot)`. Keep `camBegin` semantics unchanged so this keeps working.
- `.claude/skills/painted-animation/` — the reference engine. Read its `SKILL.md` and `template/ANIMATION_GUIDE.md`
for the standard of craft expected (animation principles, reads, review loop). Don't copy its Clawd character.
diff --git a/.claude/skills/video-clone/assets/score/score.js b/.claude/skills/video-clone/assets/score/score.js
new file mode 100644
index 0000000..b14334e
--- /dev/null
+++ b/.claude/skills/video-clone/assets/score/score.js
@@ -0,0 +1,117 @@
+// score.js — the Motion Score runtime (docs/COMPILER.md, stage 2). Evaluates a *resolved* score: every time already in
+// seconds, every move a segment { t0, t1, v0, v1, ease }. Parsing and checking happen in scripts/score/ (Python);
+// this file only evaluates, and must give the same numbers as scripts/score/runtime.py (tests/test_score.py checks).
+//
+// Score.load(resolved)
+// Score.cam(id, t) → { x, y, zoom, rot, rotDeg } t = film time; canvas: camBegin(c.x, c.y, c.zoom, c.rot)
+// Score.camLocal(id, lt) → same with time inside the shot (HyperFrames compositions)
+// Score.svgCamLocal(id, lt) → that camera as an SVG transform: S.cam.setAttribute('transform', …)
+// Score.track(id, name, t), Score.cue(name), Score.beat(n), Score.held(id, t) (cadence: on twos → 12 drawings/s)
+// Score.shot(id) → { start, end, cadence, ref_shot }
+// Pure functions of t: safe for parallel, out-of-order frame rendering.
+(function (root) {
+ const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
+ const hash = (i) => { const x = Math.sin(i * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); };
+
+ // ---------- eases (GSAP's formulas, the same table as perception/curves.py) ----------
+ const pw = (p) => ({ in: (u) => u ** p, out: (u) => 1 - (1 - u) ** p, inOut: (u) => (u < 0.5 ? (2 * u) ** p / 2 : 1 - (2 * (1 - u)) ** p / 2) });
+ const NAMED = { none: (u) => u };
+ for (const n of [1, 2, 3, 4]) for (const [k, f] of Object.entries(pw(n + 1))) NAMED[`power${n}.${k}`] = f;
+ Object.assign(NAMED, {
+ 'sine.in': (u) => 1 - Math.cos((u * Math.PI) / 2), 'sine.out': (u) => Math.sin((u * Math.PI) / 2), 'sine.inOut': (u) => -(Math.cos(Math.PI * u) - 1) / 2,
+ 'expo.in': (u) => (u <= 0 ? 0 : 2 ** (10 * (u - 1))), 'expo.out': (u) => (u >= 1 ? 1 : 1 - 2 ** (-10 * u)),
+ 'expo.inOut': (u) => (u < 0.5 ? 2 ** (20 * u - 10) / 2 : (2 - 2 ** (-20 * u + 10)) / 2),
+ 'circ.in': (u) => 1 - Math.sqrt(clamp(1 - u * u)), 'circ.out': (u) => Math.sqrt(clamp(1 - (u - 1) ** 2)),
+ 'back.out': (u) => 1 + 2.70158 * (u - 1) ** 3 + 1.70158 * (u - 1) ** 2, 'back.in': (u) => 2.70158 * u ** 3 - 1.70158 * u ** 2,
+ });
+ function back(dir, s, u) {
+ if (dir === 'in') return (s + 1) * u ** 3 - s * u ** 2;
+ if (dir === 'out') return 1 + (s + 1) * (u - 1) ** 3 + s * (u - 1) ** 2;
+ const s2 = s * 1.525;
+ return u < 0.5 ? ((2 * u) ** 2 * ((s2 + 1) * 2 * u - s2)) / 2 : ((2 * u - 2) ** 2 * ((s2 + 1) * (2 * u - 2) + s2) + 2) / 2;
+ }
+ function bezier(u, x1, y1, x2, y2) { // CSS cubic-bezier: solve x(s) = u by bisection (30 steps, as runtime.py)
+ let lo = 0, hi = 1;
+ for (let i = 0; i < 30; i++) {
+ const s = (lo + hi) / 2, x = 3 * (1 - s) ** 2 * s * x1 + 3 * (1 - s) * s ** 2 * x2 + s ** 3;
+ if (x < u) lo = s; else hi = s;
+ }
+ const s = (lo + hi) / 2;
+ return 3 * (1 - s) ** 2 * s * y1 + 3 * (1 - s) * s ** 2 * y2 + s ** 3;
+ }
+ function spring(tau, omega, zeta) {
+ zeta = Math.min(zeta, 0.999); tau = Math.max(0, tau);
+ const wd = omega * Math.sqrt(1 - zeta * zeta);
+ return 1 - Math.exp(-zeta * omega * tau) * (Math.cos(wd * tau) + ((zeta * omega) / wd) * Math.sin(wd * tau));
+ }
+ function progress(e, u, elapsed) {
+ u = clamp(u);
+ switch (e.kind) {
+ case 'named': return NAMED[e.name](u);
+ case 'back': return back(e.dir, e.s, u);
+ case 'bezier': return bezier(u, ...e.p);
+ case 'hold': return u >= 1 ? 1 : 0;
+ case 'spring': return spring(elapsed, e.omega, e.zeta);
+ default: throw new Error(`score.js: unknown ease kind ${e.kind}`);
+ }
+ }
+
+ // ---------- evaluation ----------
+ function channel(segs, base, t) {
+ let cur = null;
+ for (const s of segs || []) { if (s.t0 <= t) cur = s; else break; }
+ if (!cur) return base;
+ const span = cur.t1 - cur.t0;
+ const p = cur.ease.kind === 'spring' ? progress(cur.ease, 0, t - cur.t0) : span <= 0 ? 1 : progress(cur.ease, (t - cur.t0) / span);
+ return cur.v0 + (cur.v1 - cur.v0) * p;
+ }
+ function shake(sh, t) {
+ if (t < sh.t0) return [0, 0];
+ const f = Math.floor(t * sh.rate + 1e-6), k = sh.amp * Math.exp(-sh.decay * (t - sh.t0));
+ return [(hash(f * 1.7 + sh.seed) - 0.5) * 2 * k, (hash(f * 2.3 + 9 + sh.seed) - 0.5) * 2 * k];
+ }
+
+ let R = null, SHOTS = {};
+ const need = (id) => { const s = SHOTS[id]; if (!s) throw new Error(`score.js: no shot ${id} in the score (have ${Object.keys(SHOTS).join(', ')})`); return s; };
+ const Score = {
+ load(resolved) { R = resolved; SHOTS = Object.fromEntries(resolved.shots.map((s) => [s.id, s])); return Score; },
+ get data() { return R; },
+ shot(id) { const s = need(id); return { start: s.start, end: s.end, dur: s.end - s.start, cadence: s.cadence, ref_shot: s.ref_shot }; },
+ cam(id, t) {
+ const c = need(id).camera, v = {};
+ for (const ch of ['x', 'y', 'zoom', 'rot']) v[ch] = channel(c.channels[ch], c.base[ch], t);
+ const d = c.drift; // a slow change over the whole shot, layered under the moves (zoom multiplies)
+ if (d) {
+ const span = d.t1 - d.t0, p = progress(d.ease, span > 0 ? (t - d.t0) / span : 1, 0);
+ for (const [ch, by] of Object.entries(d.by)) v[ch] = ch === 'zoom' ? v[ch] * by ** p : v[ch] + by * p;
+ }
+ for (const sh of c.shakes) { const [dx, dy] = shake(sh, t); v.x += dx; v.y += dy; }
+ v.rotDeg = (v.rot * 180) / Math.PI;
+ return v;
+ },
+ camLocal(id, lt) { return Score.cam(id, need(id).start + lt); },
+ // SVG engines (HyperFrames): the same camera as canvas camBegin(x, y, zoom, rot), as a transform for the camera group.
+ // Use it instead of a project Kit's own S.camera(), whose handling of roll differs between projects (some ignore it):
+ // S.cam.setAttribute('transform', Score.svgCamLocal('S3', t))
+ svgCam(id, t) {
+ const c = Score.cam(id, t), [w, h] = R.size || [1920, 1080];
+ return `translate(${w / 2},${h / 2}) rotate(${c.rotDeg.toFixed(4)}) scale(${c.zoom.toFixed(5)}) translate(${(-c.x).toFixed(3)},${(-c.y).toFixed(3)})`;
+ },
+ svgCamLocal(id, lt) { return Score.svgCam(id, need(id).start + lt); },
+ track(id, name, t) {
+ const tr = need(id).tracks[name];
+ if (!tr) throw new Error(`score.js: shot ${id} has no track "${name}"`);
+ return channel(tr.segs, tr.base, t);
+ },
+ cue(name) { if (!(name in R.cues)) throw new Error(`score.js: no cue "${name}"`); return R.cues[name]; },
+ beat(n) { return R.offset + (n * 60) / R.bpm; },
+ held(id, t) {
+ const s = need(id), n = s.cadence;
+ if (n <= 1) return t;
+ const f = Math.max(0, Math.floor((t - s.start) * R.fps + 1e-6)); // ≥ 0: JS and Python disagree on % of negatives
+ return s.start + (f - (f % n)) / R.fps;
+ },
+ };
+ if (typeof module !== 'undefined' && module.exports) module.exports = Score;
+ else root.Score = Score;
+})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/.claude/skills/video-clone/scripts/analyze.py b/.claude/skills/video-clone/scripts/analyze.py
index a3b334d..daa596d 100644
--- a/.claude/skills/video-clone/scripts/analyze.py
+++ b/.claude/skills/video-clone/scripts/analyze.py
@@ -21,7 +21,7 @@ Lessons baked in (each one broke a real run):
"""
import argparse, hashlib, json, os, re, shutil, subprocess, sys, collections
-ANALYZE_VERSION = 2 # bump when report.json gains fields, so cached analyses are redone
+ANALYZE_VERSION = 3 # bump when report.json gains fields, so cached analyses are redone
CACHE = os.path.join(os.path.expanduser("~"), ".reelmimic", "cache", "analysis")
FFMPEG_FALLBACK = os.environ.get("FFMPEG_DIR", "") # folder with ffmpeg/ffprobe when they are not on PATH
@@ -311,6 +311,23 @@ def flashes(path, dur):
return out
+def fingerprint(out, rep):
+ """Style Fingerprint (perception/, docs/COMPILER.md): camera trajectories with fitted eases, tension and its peaks,
+ cut/beat phase, cadence. Written to fingerprint.json + fingerprint.png; the report keeps a summary."""
+ try:
+ from perception import plot
+ from perception.cli import reference, _save
+ fp = reference(out, rep)
+ except Exception as e: # never lose the rest of the analysis over it
+ print("fingerprint skipped:", e)
+ return None
+ _save(fp, os.path.join(out, "fingerprint.json"))
+ plot.single(fp, os.path.join(out, "fingerprint.png"))
+ r = fp["rhythm"]
+ return {"file": "fingerprint.json", "cadence": fp["cadence"], "peaks": fp["peaks"], "static_overlay": fp["static_overlay"],
+ "rhythm": {k: r[k] for k in ("on_beat_ratio", "mean_offset_frames", "phase_mean", "phase_R", "cuts_per_beat") if k in r}}
+
+
def cache_key(src):
"""URL → the URL; local file → its size plus the first and last 4 MB (the same file copied into another project hits)."""
h = hashlib.sha1(f"v{ANALYZE_VERSION}|".encode())
@@ -333,9 +350,12 @@ def summary(rep, out):
print(f"audio {au['bpm']} bpm, first beat {au['first_beat']}s, noise floor {au['noise_floor_db']} dB, phase_inverted={au['phase_inverted']}")
print(f"best 30s windows: {[c['start'] for c in au['best_30s_starts']]}")
print(f"peak candidates (build → hit): {[(p['t'], p['kind']) for p in au.get('peak_candidates', [])]}")
+ fp = rep.get("fingerprint")
+ if fp:
+ print(f"motion {fp['cadence'].get('label', '?')} ({fp['cadence'].get('drawings_per_second', '?')} drawings/s), tension peaks at {[p['t'] for p in fp['peaks']]}")
if rep.get("flashes"): print(f"flash frames: {rep['flashes']}")
- elif au.get("silent"): print("audio SILENT —", au["note"])
- else: print("audio none")
+ if au.get("silent"): print("audio SILENT —", au["note"])
+ elif not au.get("present"): print("audio none")
print("wrote", os.path.join(out, "report.json"))
@@ -377,6 +397,8 @@ def main():
"camera_kinds": sorted({k for x in sd for k in x["camera"]["kind"]})}
if rep["audio"].get("bpm") and lens:
rep["pacing"]["mean_shot_beats"] = round(rep["pacing"]["mean_shot_s"] / rep["audio"]["beat_seconds"], 1)
+ if info["width"]:
+ rep["fingerprint"] = fingerprint(a.out, rep)
with open(os.path.join(a.out, "report.json"), "w", encoding="utf-8") as f:
json.dump(rep, f, ensure_ascii=False, indent=1)
try: # cache the whole analysis folder (the agents later read source/proxy from it too)
diff --git a/.claude/skills/video-clone/scripts/compare.py b/.claude/skills/video-clone/scripts/compare.py
index ac8b830..edfdae6 100644
--- a/.claude/skills/video-clone/scripts/compare.py
+++ b/.claude/skills/video-clone/scripts/compare.py
@@ -8,6 +8,9 @@ reference shot number it maps to, and start_s/end_s). Analyses our video with th
out/check/compare_<id>.jpg reference frames (top row) vs ours (bottom row), 3 moments each, with the stats
out/check/compare.json per shot: reference vs ours — camera kind/pace/speed, brightness, contrast, dark ratio, colourfulness
out/check/compare_all.jpg every pair at mid-shot on one sheet
+ out/check/style_distance.json measured distance (perception/): scores per component and shot + findings in words
+ (fitted eases, move timing, tension peaks, cut/beat phase, cadence, colour)
+ out/check/fingerprint_overlay.png reference tension and camera speed time-warped onto ours
Open the images and score each shot (see the engine skill's Review section). Numbers flag, eyes decide.
"""
import argparse, json, os, sys
@@ -68,6 +71,11 @@ def main():
flag = "" if not rc or rc.get("pace") == oc.get("pace") or (rc.get("pace") != "still" and oc.get("pace") != "still") else " ← motion mismatch"
print(f"{r['id']} ↔ ref #{r['ref_shot']}: ours {oc.get('kind')} {oc.get('pace')} vs ref {rc.get('kind')} {rc.get('pace')}{flag}")
print("wrote", out_dir)
+ try: # the measured comparison: style_distance.json + fingerprint_overlay.png (perception/, docs/COMPILER.md)
+ from perception.cli import project, report
+ print(report(project(P, a.video)))
+ except Exception as e:
+ print("style distance skipped:", e)
if __name__ == "__main__":
diff --git a/.claude/skills/video-clone/scripts/fingerprint.py b/.claude/skills/video-clone/scripts/fingerprint.py
new file mode 100644
index 0000000..2a8cc3f
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/fingerprint.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+"""Style Fingerprint of a film, and how far our film is from the reference (perception/, docs/COMPILER.md).
+
+ python fingerprint.py project projects/<id> # the usual call: reference vs out/video.mp4, findings printed
+ python fingerprint.py extract <video> --out fp.json [--shots report.json|plan.json] [--plot fp.png]
+ python fingerprint.py compare ref.json ours.json --out style_distance.json [--plan plan.json]
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from perception.cli import main # noqa: E402
+
+if __name__ == "__main__":
+ main()
diff --git a/.claude/skills/video-clone/scripts/motion_score.py b/.claude/skills/video-clone/scripts/motion_score.py
new file mode 100644
index 0000000..3b7bcaf
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/motion_score.py
@@ -0,0 +1,18 @@
+#!/usr/bin/env python3
+"""Motion Score: the film's camera and timing as data — validate, compile for the engine, transfer the reference's
+camera, predict the measured result before rendering (score/, docs/COMPILER.md).
+
+ python motion_score.py from-ref projects/<id> # camera moves transferred from the reference
+ python motion_score.py validate projects/<id>/build/score
+ python motion_score.py compile projects/<id>/build/score --out projects/<id>/build/src/score.js
+ python motion_score.py predict projects/<id>
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from score.cli import main # noqa: E402
+
+if __name__ == "__main__":
+ main()
diff --git a/.claude/skills/video-clone/scripts/optimize/__init__.py b/.claude/skills/video-clone/scripts/optimize/__init__.py
new file mode 100644
index 0000000..8fd8a53
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/optimize/__init__.py
@@ -0,0 +1,8 @@
+"""Stage 3 of the style compiler (docs/COMPILER.md): search a score's camera and timing for the version closest to the
+reference — render-free, with CMA-ES over a bounded space that keeps the director's framing.
+
+ cmaes the optimizer (unit box, deterministic per seed)
+ space which numbers may change, their bounds, and writing a point back as an edited score
+ objective camera distance per shot + predicted tension at plan peaks + staying near the author's values
+ run the per-project driver (motion_score.py optimize)
+"""
diff --git a/.claude/skills/video-clone/scripts/optimize/cmaes.py b/.claude/skills/video-clone/scripts/optimize/cmaes.py
new file mode 100644
index 0000000..87c82c4
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/optimize/cmaes.py
@@ -0,0 +1,102 @@
+"""CMA-ES: covariance matrix adaptation evolution strategy, (μ/μ_w, λ) with rank-one and rank-μ updates and
+cumulative step-size adaptation (Hansen, "The CMA Evolution Strategy: A Tutorial", 2016).
+
+Why this optimizer: the objective here (how far a predicted camera or tension curve is from the reference) has no
+gradient — peaks appear and disappear, fits switch models — and is cheap but noisy-ish. CMA-ES needs only rankings of
+candidates, learns the correlations between parameters (start time and duration trade off against each other), and
+works well for 5–60 dimensions.
+
+Search happens in the unit box [0, 1]^n. Candidates outside it are evaluated at their projection onto the box plus a
+quadratic penalty (the boundary handling of Hansen's reference code), so the distribution stays unbiased.
+"""
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field
+from typing import Callable
+
+import numpy as np
+
+
+class CMAES:
+ def __init__(self, x0: np.ndarray, sigma0: float = 0.2, popsize: int | None = None, seed: int = 0):
+ self.n = n = len(x0)
+ self.mean = np.asarray(x0, float).copy()
+ self.sigma = float(sigma0)
+ self.rng = np.random.default_rng(seed)
+ self.lam = lam = popsize or 4 + int(3 * math.log(n))
+ self.mu = mu = lam // 2
+ w = math.log(mu + 0.5) - np.log(np.arange(1, mu + 1))
+ self.w = w / w.sum()
+ self.mueff = mueff = 1 / float(np.sum(self.w ** 2))
+ self.cc = (4 + mueff / n) / (n + 4 + 2 * mueff / n)
+ self.cs = (mueff + 2) / (n + mueff + 5)
+ self.c1 = 2 / ((n + 1.3) ** 2 + mueff)
+ self.cmu = min(1 - self.c1, 2 * (mueff - 2 + 1 / mueff) / ((n + 2) ** 2 + mueff))
+ self.damps = 1 + 2 * max(0.0, math.sqrt((mueff - 1) / (n + 1)) - 1) + self.cs
+ self.chiN = math.sqrt(n) * (1 - 1 / (4 * n) + 1 / (21 * n * n))
+ self.pc, self.ps = np.zeros(n), np.zeros(n)
+ self.B, self.D = np.eye(n), np.ones(n)
+ self.C, self.invsqrtC = np.eye(n), np.eye(n)
+ self.evals, self._eigen_at = 0, 0
+
+ def ask(self) -> np.ndarray:
+ z = self.rng.standard_normal((self.lam, self.n))
+ return self.mean + self.sigma * (z * self.D) @ self.B.T
+
+ def tell(self, X: np.ndarray, f: np.ndarray):
+ n, lam, mu = self.n, self.lam, self.mu
+ self.evals += lam
+ order = np.argsort(f)
+ Xs = X[order[:mu]]
+ old = self.mean
+ self.mean = self.w @ Xs
+ yw = (self.mean - old) / self.sigma
+ self.ps = (1 - self.cs) * self.ps + math.sqrt(self.cs * (2 - self.cs) * self.mueff) * (self.invsqrtC @ yw)
+ hsig = np.linalg.norm(self.ps) / math.sqrt(1 - (1 - self.cs) ** (2 * self.evals / lam)) / self.chiN < 1.4 + 2 / (n + 1)
+ self.pc = (1 - self.cc) * self.pc + hsig * math.sqrt(self.cc * (2 - self.cc) * self.mueff) * yw
+ art = (Xs - old) / self.sigma
+ self.C = ((1 - self.c1 - self.cmu) * self.C
+ + self.c1 * (np.outer(self.pc, self.pc) + (1 - hsig) * self.cc * (2 - self.cc) * self.C)
+ + self.cmu * (art.T * self.w) @ art)
+ self.sigma *= math.exp((self.cs / self.damps) * (np.linalg.norm(self.ps) / self.chiN - 1))
+ if self.evals - self._eigen_at > lam / (self.c1 + self.cmu) / n / 10: # O(n²) per generation on average
+ self._eigen_at = self.evals
+ self.C = np.triu(self.C) + np.triu(self.C, 1).T
+ d2, self.B = np.linalg.eigh(self.C)
+ self.D = np.sqrt(np.maximum(d2, 1e-20))
+ self.invsqrtC = (self.B / self.D) @ self.B.T
+
+
+@dataclass
+class Result:
+ x: np.ndarray
+ f: float
+ evals: int
+ history: list[float] = field(default_factory=list) # best value after each generation
+
+
+def minimize(f: Callable[[np.ndarray], float], x0: np.ndarray, sigma0: float = 0.2, budget: int = 400, seed: int = 0,
+ popsize: int | None = None, tol: float = 1e-9) -> Result:
+ """Minimise f over the unit box [0, 1]^n starting from x0 (in the box). Deterministic for a given seed."""
+ x0 = np.clip(np.asarray(x0, float), 0, 1)
+ if len(x0) == 0:
+ return Result(x0, float(f(x0)), 1)
+ es = CMAES(x0, sigma0, popsize, seed)
+ best_x, best_f = x0, float(f(x0))
+ hist, evals = [best_f], 1
+ while evals + es.lam <= budget:
+ X = es.ask()
+ vals = np.empty(len(X))
+ for i, x in enumerate(X):
+ xc = np.clip(x, 0, 1)
+ fx = float(f(xc))
+ if fx < best_f:
+ best_x, best_f = xc, fx
+ vals[i] = fx + 1e3 * float(np.sum((x - xc) ** 2)) # outside the box: evaluated on it, penalised by the distance
+ evals += len(X)
+ es.tell(X, vals)
+ hist.append(best_f)
+ if es.sigma * float(es.D.max()) < tol:
+ break
+ return Result(best_x, best_f, evals, hist)
diff --git a/.claude/skills/video-clone/scripts/optimize/objective.py b/.claude/skills/video-clone/scripts/optimize/objective.py
new file mode 100644
index 0000000..c9ffa83
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/optimize/objective.py
@@ -0,0 +1,158 @@
+"""What the optimizer minimises, computed without rendering.
+
+ cost = Σ_shots camera_cost(shot) 100 − camera_pair score against the mapped reference shot
+ + w_peaks · Σ_peaks peak_cost(peak) predicted tension around each plan peak vs the reference's peak shape
+ + w_reg · ‖u − u₀‖² stay near what the director wrote
+ + penalties a score that no longer resolves, moves pushed outside their shot
+
+Predicted tension is multi-fidelity: the sound is the film's own (fixed), camera speed and cuts come exactly from the
+score, and in-frame motion (local motion, frame difference, flashes) comes from the last render's fingerprint when
+there is one — the optimizer moves the camera, not the characters, so those stay as measured.
+
+The peak cost is one-sided: a breath deeper than the reference's, a hit that lands faster, a peak that stands out more
+cost nothing. The goal is to beat the reference at its best moment, not to copy its numbers.
+"""
+from __future__ import annotations
+
+import os
+import subprocess
+import tempfile
+
+import numpy as np
+
+from perception import curves, distance, tension
+from perception.video import ensure_ffmpeg
+from score import model, predict
+from score.runtime import Score
+
+from .space import Space
+
+W = 1920.0
+
+
+# ---------- predicted tension ----------
+def audio_features(path: str | None, n: int, fps: float, offset: float = 0.0) -> dict[str, np.ndarray]:
+ """Loudness and flux of the film's sound; `offset` = where the film starts in the file (a song's chosen section)."""
+ if not path or not os.path.exists(path):
+ return {}
+ ensure_ffmpeg()
+ fd, wav = tempfile.mkstemp(suffix=".wav")
+ os.close(fd)
+ try:
+ r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", path, "-vn", "-ac", "1", "-ar", "22050", wav], capture_output=True)
+ return tension.audio_features(wav, n, fps, t0=offset) if r.returncode == 0 else {}
+ finally:
+ os.remove(wav)
+
+
+def visual_features(fp: dict | None, n: int, fps: float) -> dict[str, np.ndarray]:
+ """In-frame motion from the last render, resampled to n frames from 0 s."""
+ if not fp:
+ return {}
+ s = fp["series"]
+ t_src = fp["start"] + np.arange(fp["frames"]) / fp["fps"]
+ t = np.arange(n) / fps
+ get = lambda v: np.interp(t, t_src, np.asarray(v, float))
+ return {"local": get(s["local"]) * fp["fps"], "diff": get(s["diff"]), "flash": tension.flashes(get(s["lab"][0]), fps)}
+
+
+def camera_speed(score: Score, n: int, fps: float) -> tuple[np.ndarray, list[int]]:
+ """Per-frame camera speed in perception units, and the frames where a new shot starts."""
+ speed, cuts = np.zeros(n), []
+ shots = sorted(score.shots.values(), key=lambda s: s["start"])
+ for k, s in enumerate(shots):
+ f0, f1 = int(round(s["start"] * fps)), min(n, int(round(s["end"] * fps)))
+ if f1 - f0 < 2:
+ continue
+ if k:
+ cuts.append(f0)
+ t, traj = predict.trajectory(score, s["id"])
+ m = min(len(t), f1 - f0)
+ d = np.sqrt(sum(np.diff(traj[a][:m], prepend=traj[a][0]) ** 2 for a in ("x", "y", "z", "r"))) * fps
+ speed[f0:f0 + m] = d
+ return speed, cuts
+
+
+def predicted_tension(score: Score, n: int, fps: float, audio: dict, visual: dict) -> np.ndarray:
+ speed, cuts = camera_speed(score, n, fps)
+ return tension.curve({**audio, **visual, "camera": speed, "cuts": tension.cut_density(cuts, n, fps)}, fps)
+
+
+def peak_cost(T: np.ndarray, fps: float, target_t: float, ref: dict) -> tuple[float, dict | None]:
+ """One-sided distance from our predicted peak near target_t to the reference peak's shape."""
+ ours = [p for p in tension.describe_peaks(T, fps, n=8, min_gap_s=1.0) if abs(p["t"] - target_t) <= 1.0]
+ if not ours:
+ return 40.0, None
+ q = min(ours, key=lambda p: abs(p["t"] - target_t))
+ c = (20 * abs(q["t"] - target_t)
+ + 60 * max(0.0, ref["breath_depth"] - q["breath_depth"])
+ + 2.0 * max(0, q["rise_frames"] - ref["rise_frames"])
+ + 60 * max(0.0, ref["prominence"] - q["prominence"])
+ + 15 * max(0.0, ref["hold_s"] - q["hold_s"]))
+ return float(c), q
+
+
+# ---------- the objective ----------
+class Objective:
+ def __init__(self, space: Space, ref_fp: dict, shots: list[str], *, w_reg: float = 30.0,
+ peaks: list[dict] | None = None, w_peaks: float = 1.0, audio: dict | None = None, visual: dict | None = None):
+ self.space, self.shots = space, shots
+ from perception.fingerprint import reference_for
+ ordered = sorted(space.resolved["shots"], key=lambda s: s["start"])
+ self.ref_shots = reference_for(ref_fp, [(s["id"], s.get("ref_shot"), s["end"] - s["start"]) for s in ordered]) # by OUR shot id
+ self.w_reg, self.peaks, self.w_peaks = w_reg, peaks or [], w_peaks
+ self.audio, self.visual = audio or {}, visual or {}
+ self.u0 = space.u0
+ self.evals = 0
+
+ def verified_camera_costs(self, u: np.ndarray) -> dict[str, float] | None:
+ """The camera cost the way a rendered film is measured (ease fits, frame sampling), for the final check: the
+ search reads shapes straight off the exact curve, which can reward a curve no fitted model describes."""
+ r, diag = model.resolve_score(self.space.apply(u))
+ if not diag.ok:
+ return None
+ score, out = Score(r), {}
+ for p in predict.predicted_shots(score):
+ rs = self.ref_shots.get(p["id"])
+ if p["id"] in self.shots and rs is not None:
+ out[p["id"]] = 100.0 - distance.camera_pair(rs, p)[0]
+ return out
+
+ def camera_costs(self, score: Score) -> dict[str, float]:
+ out = {}
+ for sid in self.shots:
+ s = score.shots[sid]
+ rs = self.ref_shots.get(sid)
+ if rs is None:
+ continue
+ # exact and 10× finer than the frames: read the shape off the curve, no fitting (≈ 100× faster)
+ t, traj = predict.trajectory(score, sid, 10 * float(score.r["fps"]))
+ if len(t) < 2:
+ continue
+ sc, _, _ = distance.camera_pair(rs, {"id": sid, "start": s["start"], "end": s["end"], "move": curves.describe_shot(t, traj, fit=False)})
+ out[sid] = 100.0 - sc
+ return out
+
+ def evaluate(self, u: np.ndarray) -> dict:
+ authored = self.space.apply(u)
+ r, diag = model.resolve_score(authored)
+ if not diag.ok:
+ return {"cost": 1000.0 + 50 * len(diag.errors), "errors": diag.errors}
+ outside = sum(1 for w in diag.warnings if "outside the shot" in w and any(w.startswith(f"{sid}.") for sid in self.shots))
+ score = Score(r)
+ cam = self.camera_costs(score)
+ out = {"camera": cam, "camera_cost": float(sum(cam.values())), "outside": outside}
+ cost = out["camera_cost"] + 25.0 * outside + self.w_reg * float(np.sum((u - self.u0) ** 2))
+ if self.peaks:
+ fps = float(r["fps"])
+ n = int(round(float(r["duration"]) * fps))
+ T = predicted_tension(score, n, fps, self.audio, self.visual)
+ pk = [peak_cost(T, fps, p["t"], p["ref"]) for p in self.peaks]
+ out["peaks"] = [{"target": p["t"], "cost": round(c, 2), "ours": q, "ref": p["ref"]} for p, (c, q) in zip(self.peaks, pk)]
+ cost += self.w_peaks * sum(c for c, _ in pk)
+ out["cost"] = float(cost)
+ return out
+
+ def __call__(self, u: np.ndarray) -> float:
+ self.evals += 1
+ return self.evaluate(u)["cost"]
diff --git a/.claude/skills/video-clone/scripts/optimize/run.py b/.claude/skills/video-clone/scripts/optimize/run.py
new file mode 100644
index 0000000..a8fd7a0
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/optimize/run.py
@@ -0,0 +1,127 @@
+"""Optimise a project's score against its reference, render-free (motion_score.py optimize).
+
+Shots are independent for the camera objective, so each is searched on its own (few dimensions, fast convergence);
+with --peaks, the shots around each plan peak are searched together, because the tension curve they shape is shared.
+A group's result is kept only if it beats the author's version; the next group starts from the improved score.
+"""
+from __future__ import annotations
+
+import json
+import os
+import time
+
+import numpy as np
+
+from perception import tension
+from score import model
+
+from . import cmaes
+from .objective import Objective, audio_features, visual_features
+from .space import Space
+
+
+def _load(p: str):
+ with open(p, encoding="utf-8") as f:
+ return json.load(f)
+
+
+def peak_targets(P: str, ref_fp: dict, plan: dict) -> list[dict]:
+ """Each plan peak's hit time, with the shape of the reference peak it answers (from the reference tension curve)."""
+ ref_peaks_p = os.path.join(P, "analysis", "peaks.json")
+ agent_peaks = {p.get("id"): p for p in (_load(ref_peaks_p) if os.path.exists(ref_peaks_p) else [])}
+ T = np.asarray(ref_fp["series"]["tension"], float)
+ found = tension.describe_peaks(T, ref_fp["fps"], n=12, min_gap_s=1.0)
+ for p in found:
+ p["t"] += ref_fp["start"]
+ out = []
+ for pk in plan.get("peaks") or []:
+ if pk.get("hit_s") is None:
+ continue
+ ref_hit = (agent_peaks.get(pk.get("ref_peak")) or {}).get("hit")
+ cands = [q for q in found if ref_hit is None or abs(q["t"] - float(ref_hit)) <= 1.5]
+ if not cands:
+ continue
+ ref = min(cands, key=lambda q: abs(q["t"] - float(ref_hit))) if ref_hit is not None else max(cands, key=lambda q: q["prominence"])
+ out.append({"id": pk.get("id"), "t": float(pk["hit_s"]), "ref": ref})
+ return out
+
+
+def optimize_project(P: str, score_dir: str, *, shots: list[str] | None = None, budget: int = 240, peaks: bool = False,
+ tune_amounts: bool = False, seed: int = 0, log=print) -> dict:
+ t_start = time.time()
+ authored, origin = model.load(score_dir)
+ resolved, diag = model.resolve_score(authored, origin)
+ if not diag.ok:
+ raise model.ScoreError(diag)
+ from perception.cli import ensure_reference
+ ref_fp = ensure_reference(P)
+ plan = _load(os.path.join(P, "plan.json"))
+ ref_ids = {s["id"] for s in ref_fp["shots"]}
+ movable = [s["id"] for s in resolved["shots"] if s.get("ref_shot") in ref_ids and (s["camera"]["move_times"] or s["camera"]["shakes"])]
+ shots = [s for s in (shots or movable) if s in {x["id"] for x in resolved["shots"]}]
+
+ targets, audio, visual, hero = [], {}, {}, []
+ if peaks:
+ targets = peak_targets(P, ref_fp, plan)
+ fps = float(resolved["fps"])
+ n = int(round(float(resolved["duration"]) * fps))
+ video = os.path.join(P, "out", "video.mp4")
+ music = (plan.get("music") or {})
+ if os.path.exists(video):
+ audio = audio_features(video, n, fps)
+ elif music.get("file"):
+ audio = audio_features(os.path.join(P, music["file"]), n, fps, offset=float((music.get("section") or {}).get("start_s") or 0))
+ fp_p = os.path.join(P, "out", "check", "fingerprint.json")
+ visual = visual_features(_load(fp_p), n, fps) if os.path.exists(fp_p) else {}
+ for tg in targets:
+ for s in resolved["shots"]:
+ if s["end"] > tg["t"] - 1.5 and s["start"] < tg["t"] + 1.0 and s["id"] not in hero:
+ hero.append(s["id"])
+ log(f"peaks: {[(t['id'], t['t']) for t in targets]} → shots {hero}; audio {'yes' if audio else 'no'}, in-frame motion {'from the last render' if visual else 'none'}")
+
+ groups = ([hero] if hero else []) + [[s] for s in shots if s not in hero]
+ current, cur_res = authored, resolved
+ report = {"groups": [], "changes": []}
+ for g in groups:
+ propose = {}
+ if peaks and g is hero:
+ for tg in targets:
+ sh = next((s for s in cur_res["shots"] if s["start"] <= tg["t"] < s["end"]), None)
+ if sh and not any(abs(x["t0"] - tg["t"]) < 0.2 for x in sh["camera"]["shakes"]):
+ propose.setdefault(sh["id"], []).append(tg["t"])
+ space = Space(current, cur_res, g, tune_amounts=tune_amounts, propose_shakes=propose)
+ if not space.params:
+ continue
+ obj = Objective(space, ref_fp, g, peaks=targets if g is hero else None, audio=audio, visual=visual)
+ before = obj.evaluate(space.u0)
+ res = cmaes.minimize(obj, space.u0, sigma0=0.15, budget=budget * (2 if g is hero else 1), seed=seed)
+ after = obj.evaluate(res.x)
+ kept = after["cost"] < before["cost"] - 0.5
+ if kept: # gate: the gain must hold measured the way a rendered film is (fitted eases, frames), not only on the search's fast path
+ vb, va = obj.verified_camera_costs(space.u0), obj.verified_camera_costs(res.x)
+ if vb is not None and va is not None and sum(va.values()) > sum(vb.values()) - 0.5 * len(va):
+ kept = False
+ after["verified"] = {"before": vb, "after": va}
+ entry = {"shots": g, "dims": len(space.params), "evals": res.evals, "kept": kept,
+ "before": _brief(before), "after": _brief(after), "history": [round(h, 2) for h in res.history]}
+ report["groups"].append(entry)
+ log(f"{'+'.join(g)}: {len(space.params)} params, {res.evals} evals, cost {before['cost']:.1f} → {after['cost']:.1f}{'' if kept else ' (kept the original)'}")
+ if kept:
+ report["changes"] += space.changes(res.x)
+ current = space.apply(res.x)
+ cur_res, d = model.resolve_score(current)
+ report["seconds"] = round(time.time() - t_start, 1)
+ report["score"] = current
+ return report
+
+
+def _brief(ev: dict) -> dict:
+ out = {"cost": round(ev["cost"], 2)}
+ if "camera" in ev:
+ out["camera"] = {k: round(v, 1) for k, v in ev["camera"].items()}
+ if "peaks" in ev:
+ out["peaks"] = [{"target": p["target"], "cost": p["cost"], "ours": p["ours"] and {k: p["ours"][k] for k in ("t", "breath_depth", "rise_frames", "prominence", "hold_s")},
+ "ref": {k: p["ref"][k] for k in ("t", "breath_depth", "rise_frames", "prominence", "hold_s")}} for p in ev["peaks"]]
+ if "errors" in ev:
+ out["errors"] = ev["errors"][:5]
+ return out
diff --git a/.claude/skills/video-clone/scripts/optimize/space.py b/.claude/skills/video-clone/scripts/optimize/space.py
new file mode 100644
index 0000000..7702982
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/optimize/space.py
@@ -0,0 +1,193 @@
+"""The search space: which numbers of a score the optimizer may change, their bounds, and how a point in the unit box
+becomes an edited score again.
+
+Per camera move of a tuned shot:
+ at start, within ±max_shift of where the author put it (and inside the shot)
+ dur duration × 2^v, v ∈ [−1, 1]
+ ease the curve as cubic-bezier (x1, y1, x2, y2), started from the author's ease converted to a bezier;
+ springs tune ω (× 2^v) and ζ instead; "hold" (a jump) has no curve to tune
+ by.* only with tune_amounts: ±30 % (zoom: of the push itself). Amounts are the director's framing intent, so
+ they are locked by default
+Per shake: amplitude (0–3× and able to reach 0, which removes it) and decay (× 2^v).
+Optional *proposed* shakes at plan peaks (amplitude starts at 0): structure the optimizer may add, never forced.
+
+Written back in the author's terms where nothing changed: an unchanged start keeps "B12", an unchanged ease keeps
+"power3.out"; every changed move records what it was in "tuned".
+"""
+from __future__ import annotations
+
+import copy
+from dataclasses import dataclass
+
+import numpy as np
+from scipy.optimize import least_squares
+
+from perception import curves
+from score import eases
+
+MIN_SHAKE_PX = 4.0 # stage pixels at 1080p: below this a shake is not visible
+BEZ_LO, BEZ_HI = (0.0, -0.15, 0.0, -0.15), (1.0, 1.25, 1.0, 1.25) # eases a viewer reads as eases (modest overshoot at most);
+# wider, the search found curves no fitted model describes — great on the exact trajectory, unrecognisable once measured
+
+
+def to_bezier(e: dict) -> list[float]:
+ """The cubic-bezier closest to a normalised ease (least squares on 60 samples)."""
+ if e["kind"] == "bezier":
+ return list(e["p"])
+ u = np.linspace(0, 1, 60)
+ v = eases.progress(e, u)
+ r = min((least_squares(lambda p: curves.bezier(u, *p) - v, x0, bounds=(BEZ_LO, BEZ_HI))
+ for x0 in [(0.25, 0.1, 0.25, 1.0), (0.42, 0.0, 0.58, 1.0), (0.16, 1.0, 0.3, 1.0)]), key=lambda r: r.cost)
+ return [float(x) for x in r.x]
+
+
+@dataclass
+class Param:
+ shot: str
+ kind: str # at | dur | bez0..3 | omega | zeta | by:<ch> | amp | decay
+ index: int # move index, or shake index
+ lo: float
+ hi: float
+ x0: float # in natural units
+ log2: bool = False
+
+ def to_unit(self, x: float) -> float:
+ return (x - self.lo) / (self.hi - self.lo)
+
+ def from_unit(self, u: float) -> float:
+ return self.lo + float(np.clip(u, 0, 1)) * (self.hi - self.lo)
+
+
+class Space:
+ def __init__(self, authored: dict, resolved: dict, shots: list[str], *, tune_amounts: bool = False, max_shift: float = 0.25,
+ propose_shakes: dict[str, list[float]] | None = None):
+ self.authored, self.resolved = authored, resolved
+ self.res = {s["id"]: s for s in resolved["shots"]}
+ self.src = {str(s["id"]): s for s in authored["shots"]}
+ self.params: list[Param] = []
+ self.bez0: dict[tuple[str, int], list[float]] = {} # each move's starting curve as a bezier (fitted once)
+ self.proposed: dict[str, list[float]] = {k: v for k, v in (propose_shakes or {}).items() if k in shots}
+ for sid in shots:
+ self._shot_params(sid, tune_amounts, max_shift)
+
+ # ---------- building the space ----------
+ def _shot_params(self, sid: str, tune_amounts: bool, max_shift: float):
+ src, res = self.src[sid], self.res[sid]
+ s, e = res["start"], res["end"]
+ P = self.params
+ for i, mv in enumerate((src.get("camera") or {}).get("moves") or []):
+ tt = res["camera"]["move_times"][i] if i < len(res["camera"]["move_times"]) else None
+ if not tt:
+ continue
+ t0, t1 = tt
+ ease = eases.normalise(mv.get("ease"))
+ shift = min(max_shift, 0.25 * (e - s))
+ lo, hi = max(s, t0 - shift), min(e, t0 + shift)
+ P.append(Param(sid, "at", i, lo, max(hi, lo + 1e-3), t0))
+ if ease["kind"] != "spring":
+ P.append(Param(sid, "dur", i, -1.0, 1.0, 0.0, log2=True))
+ if ease["kind"] == "spring":
+ P.append(Param(sid, "omega", i, -1.0, 1.0, 0.0, log2=True))
+ P.append(Param(sid, "zeta", i, 0.1, 0.95, min(0.95, max(0.1, ease["zeta"]))))
+ elif ease["kind"] != "hold":
+ self.bez0[(sid, i)] = to_bezier(ease)
+ for k, (v, lo, hi) in enumerate(zip(self.bez0[(sid, i)], BEZ_LO, BEZ_HI)):
+ P.append(Param(sid, f"bez{k}", i, lo, hi, float(np.clip(v, lo, hi))))
+ if tune_amounts and isinstance(mv.get("by"), dict):
+ for ch in mv["by"]:
+ P.append(Param(sid, f"by:{ch}", i, -0.3, 0.3, 0.0))
+ for j, sh in enumerate((src.get("camera") or {}).get("shakes") or []):
+ P.append(Param(sid, "amp", j, 0.0, 3.0 * float(sh.get("amp", 10)), float(sh.get("amp", 10))))
+ P.append(Param(sid, "decay", j, -1.0, 1.0, 0.0, log2=True))
+ n0 = len((src.get("camera") or {}).get("shakes") or [])
+ for k, _ in enumerate(self.proposed.get(sid, [])):
+ P.append(Param(sid, "amp", n0 + k, 0.0, 40.0, 0.0))
+ P.append(Param(sid, "decay", n0 + k, -1.0, 1.0, 0.0, log2=True))
+
+ @property
+ def u0(self) -> np.ndarray:
+ return np.array([p.to_unit(p.x0) for p in self.params])
+
+ # ---------- applying a point ----------
+ def apply(self, u: np.ndarray) -> dict:
+ out = copy.deepcopy(self.authored)
+ shots = {str(s["id"]): s for s in out["shots"]}
+ clock_fps = float(self.resolved["fps"])
+ beat, offset = 60.0 / float(self.resolved["bpm"]), float(self.resolved["offset"])
+ by_move: dict[tuple[str, int], dict[str, float]] = {}
+ by_shake: dict[tuple[str, int], dict[str, float]] = {}
+ for p, x in zip(self.params, u):
+ v = p.from_unit(x)
+ (by_shake if p.kind in ("amp", "decay") else by_move).setdefault((p.shot, p.index), {})[p.kind] = v
+ for (sid, i), vals in by_move.items():
+ shot, res = shots[sid], self.res[sid]
+ mv = shot["camera"]["moves"][i]
+ old = {k: copy.deepcopy(mv[k]) for k in ("at", "dur", "until", "ease", "by") if k in mv}
+ t0, t1 = res["camera"]["move_times"][i]
+ changed = False
+ if "at" in vals and abs(vals["at"] - t0) > 0.25 / clock_fps:
+ k = round((vals["at"] - offset) / beat)
+ tb = offset + k * beat
+ mv["at"] = f"B{k}" if abs(tb - vals["at"]) <= 0.5 / clock_fps else f"S+{vals['at'] - res['start']:.4f}s"
+ changed = True
+ if "dur" in vals and abs(vals["dur"]) > 0.01:
+ mv.pop("until", None)
+ mv["dur"] = f"{(t1 - t0) * 2 ** vals['dur']:.4f}s"
+ changed = True
+ bez = [vals.get(f"bez{k}") for k in range(4)]
+ if all(b is not None for b in bez):
+ p0 = self.bez0[(sid, i)]
+ if max(abs(a - b) for a, b in zip(bez, p0)) > 0.02:
+ mv["ease"] = {"bezier": [round(b, 3) for b in bez]}
+ changed = True
+ if "omega" in vals or "zeta" in vals:
+ e = eases.normalise(old.get("ease"))
+ w, z = e["omega"] * 2 ** vals.get("omega", 0.0), vals.get("zeta", e["zeta"])
+ if abs(w - e["omega"]) > 0.05 * e["omega"] or abs(z - e["zeta"]) > 0.02:
+ mv["ease"] = {"spring": {"omega": round(w, 2), "zeta": round(z, 3)}}
+ changed = True
+ for key, v in vals.items():
+ if key.startswith("by:") and abs(v) > 0.01:
+ ch = key[3:]
+ a = float(mv["by"][ch])
+ mv["by"][ch] = round(a ** (1 + v), 4) if ch == "zoom" and a > 0 else round(a * (1 + v), 2)
+ changed = True
+ if changed:
+ mv["tuned"] = {"from": old}
+ for (sid, j), vals in by_shake.items():
+ shakes = shots[sid]["camera"].setdefault("shakes", [])
+ n0 = len((self.src[sid].get("camera") or {}).get("shakes") or [])
+ if j >= n0: # a proposed shake at a plan peak
+ hit = self.proposed[sid][j - n0]
+ shakes.append({"at": f"{hit:.4f}", "amp": round(vals.get("amp", 0.0), 2), "decay": round(10 * 2 ** vals.get("decay", 0.0), 2),
+ "tuned": {"proposed": "shake at a plan peak"}})
+ else:
+ sh = shakes[j]
+ old = {k: sh.get(k) for k in ("amp", "decay")}
+ sh["amp"] = round(vals.get("amp", sh.get("amp", 10)), 2)
+ sh["decay"] = round(float(sh.get("decay", 10)) * 2 ** vals.get("decay", 0.0), 2)
+ if abs(sh["amp"] - (old["amp"] or 0)) > 0.5 or abs(sh["decay"] - (old["decay"] or 10)) > 0.2:
+ sh["tuned"] = {"from": old}
+ for sid in shots: # a shake too small to see is no shake (and must not count for anything)
+ cam = shots[sid].get("camera") or {}
+ if cam.get("shakes"):
+ cam["shakes"] = [sh for sh in cam["shakes"] if float(sh.get("amp", 0)) >= MIN_SHAKE_PX]
+ return out
+
+ def changes(self, u: np.ndarray) -> list[dict]:
+ """What a point changes in this space's shots, move by move, in words a director reads."""
+ tuned = self.apply(u)
+ mine = {p.shot for p in self.params}
+ out = []
+ for s in tuned["shots"]:
+ if str(s["id"]) not in mine:
+ continue
+ for i, mv in enumerate((s.get("camera") or {}).get("moves") or []):
+ if "tuned" in mv:
+ out.append({"shot": s["id"], "move": i, "from": mv["tuned"]["from"], "to": {k: mv[k] for k in ("at", "dur", "until", "ease", "by") if k in mv}})
+ for j, sh in enumerate((s.get("camera") or {}).get("shakes") or []):
+ if "tuned" in sh:
+ out.append({"shot": s["id"], "shake": j, "from": sh["tuned"].get("from") or sh["tuned"].get("proposed"),
+ "to": {"at": sh["at"], "amp": sh["amp"], "decay": sh["decay"]}})
+ return out
+
diff --git a/.claude/skills/video-clone/scripts/perception/__init__.py b/.claude/skills/video-clone/scripts/perception/__init__.py
new file mode 100644
index 0000000..869fc04
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/__init__.py
@@ -0,0 +1,8 @@
+"""Perception: measure a film as time series (camera trajectory, easing, tension, rhythm, colour) and compare two films.
+
+Stage 1 of the style compiler (docs/COMPILER.md). Entry points:
+
+ fingerprint.extract(video, shots=…, audio=…, beats=…) → fingerprint dict (analysis/fingerprint.json)
+ distance.style_distance(ref_fp, our_fp, pairs=…) → scores per component and shot, plus findings
+ python .claude/skills/video-clone/scripts/fingerprint.py --help
+"""
diff --git a/.claude/skills/video-clone/scripts/perception/camera.py b/.claude/skills/video-clone/scripts/perception/camera.py
new file mode 100644
index 0000000..b603838
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/camera.py
@@ -0,0 +1,178 @@
+"""Global camera motion between consecutive frames, and the motion that is left once the camera is accounted for.
+
+Model: the image of frame k+1 is a similarity transform of frame k about the frame centre,
+
+ p' = s · R(θ) · p + t (p measured from the centre, in pixels)
+
+estimated robustly from sparse tracks:
+
+ Shi–Tomasi corners → pyramidal Lucas–Kanade → forward–backward consistency check → RANSAC similarity.
+
+The result is reported in *camera* terms, so a plan can say what the camera did:
+
+ dx camera moves right (+) / left (−), in frame widths (image content moves the other way)
+ dy camera moves down (+) / up (−), in frame widths
+ dz log scale: push in (+) / pull out (−) (ln 1.1 ≈ 0.095 = a 10 % push)
+ dr camera roll in radians, + = clockwise roll (image turns counter-clockwise)
+
+`local` is the median residual of all tracked points after removing the global transform, in frame widths: characters
+moving, things falling, a hand waving — motion the camera did not cause.
+"""
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+
+import cv2
+import numpy as np
+
+MIN_TRACKS = 12 # fewer usable tracks than this → no estimate (black stage, flat colour field)
+FB_MAX_ERR = 1.0 # px: a track that does not come back to where it started is dropped
+RANSAC_PX = 1.0 # px: inlier threshold for the similarity fit
+MIN_INLIER_RATIO = 0.3 # below this the "camera" is really several things moving: the estimate is not trusted
+PHOTO_MAX_ERR = 0.06 # a warp that leaves less mean abs error than this (0–1) is always accepted
+PHOTO_GAIN = 0.75 # otherwise it must explain at least 25 % of the change between the two frames
+BG_MARGIN = 0.06 # the moving subject's region is grown by this share of the width before "the rest" is judged
+BG_MIN_SHARE = 0.2 # the rest must be at least this share of the frame to be evidence
+BG_SPREAD = 0.15 # background tracks must spread over this share of the frame: a burned-in caption strip is
+ # many corners in a thin band that never moves, not evidence about the world
+BG_SAME = 0.0015 # the rest did not change at all (mean abs difference, 0–1): nothing there moved
+BG_GAIN = 0.85 # a camera move must explain the rest at least 15 % better than standing still
+MIN_BG_TRACKS = 8 # background tracks needed to measure the camera from the background alone
+
+_LK = dict(winSize=(21, 21), maxLevel=3, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 30, 0.01))
+
+
+@dataclass(frozen=True)
+class Step:
+ dx: float = 0.0
+ dy: float = 0.0
+ dz: float = 0.0
+ dr: float = 0.0
+ local: float = 0.0
+ ok: bool = False
+ tracks: int = 0
+
+
+def estimate(prev_gray: np.ndarray, gray: np.ndarray, mask: np.ndarray | None = None) -> Step:
+ """Camera motion from prev_gray to gray (both single-channel uint8, same size). `mask` (255 = usable) keeps corners
+ off static overlays."""
+ h, w = gray.shape
+ pts = cv2.goodFeaturesToTrack(prev_gray, maxCorners=500, qualityLevel=0.01, minDistance=7, blockSize=7, mask=mask)
+ if pts is None or len(pts) < MIN_TRACKS:
+ return Step()
+ nxt, st1, _ = cv2.calcOpticalFlowPyrLK(prev_gray, gray, pts, None, **_LK)
+ back, st2, _ = cv2.calcOpticalFlowPyrLK(gray, prev_gray, nxt, None, **_LK)
+ fb = np.linalg.norm((pts - back).reshape(-1, 2), axis=1)
+ good = (st1.ravel() == 1) & (st2.ravel() == 1) & (fb < FB_MAX_ERR)
+ if good.sum() < MIN_TRACKS:
+ return Step(tracks=int(good.sum()))
+ centre = np.array([w / 2, h / 2], np.float32)
+ p0 = pts.reshape(-1, 2)[good] - centre
+ p1 = nxt.reshape(-1, 2)[good] - centre
+ M, inl = cv2.estimateAffinePartial2D(p0, p1, method=cv2.RANSAC, ransacReprojThreshold=RANSAC_PX,
+ maxIters=2000, confidence=0.995)
+ if M is None or inl is None or inl.mean() < MIN_INLIER_RATIO:
+ return Step(tracks=int(good.sum()))
+ if not photometric_ok(prev_gray, gray, M, centre):
+ return Step(tracks=int(good.sum()))
+ # Camera motion is motion against the world. When the tracks that agree sit on one subject, the background decides:
+ # its own tracks (searched for separately, so faint detail like sparkles counts), else whether it changed at all.
+ region = subject_region(gray.shape, p1[inl.ravel() == 1] + centre)
+ if region is not None:
+ bg = background_motion(prev_gray, gray, region, centre)
+ if bg is not None:
+ M = bg
+ elif background_says_still(prev_gray, gray, M, centre, region):
+ # a subject moved over a plain background, not the camera: that is motion inside the frame
+ return Step(local=float(np.median(np.linalg.norm(p1 - p0, axis=1))) / w, ok=True, tracks=int(good.sum()))
+ a, b, tx, ty = M[0, 0], M[1, 0], M[0, 2], M[1, 2]
+ scale, theta = math.hypot(a, b), math.atan2(b, a)
+ residual = np.linalg.norm(p1 - (p0 @ M[:, :2].T + M[:, 2]), axis=1)
+ return Step(dx=-tx / w, dy=-ty / w, dz=math.log(scale), dr=-theta, local=float(np.median(residual)) / w,
+ ok=True, tracks=int(good.sum()))
+
+
+def _warp(prev_gray: np.ndarray, M: np.ndarray, centre: np.ndarray) -> np.ndarray:
+ h, w = prev_gray.shape
+ A = M[:, :2]
+ full = np.hstack([A, (M[:, 2] + centre - A @ centre)[:, None]]).astype(np.float32)
+ return cv2.warpAffine(prev_gray, full, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
+
+
+def subject_region(shape: tuple[int, int], inliers: np.ndarray) -> np.ndarray | None:
+ """Mask of what the agreeing tracks cover (grown a little), or None when they cover most of the frame — then the
+ whole frame moved together, and that is the camera."""
+ h, w = shape
+ if len(inliers) < 3:
+ return None
+ region = np.zeros((h, w), np.uint8)
+ cv2.fillConvexPoly(region, cv2.convexHull(inliers.astype(np.int32)), 255)
+ k = max(3, int(BG_MARGIN * w)) | 1
+ region = cv2.dilate(region, np.ones((k, k), np.uint8))
+ return region if (_inner(shape) & (region == 0)).mean() >= BG_MIN_SHARE else None
+
+
+def _inner(shape: tuple[int, int]) -> np.ndarray:
+ h, w = shape
+ m = np.zeros((h, w), bool)
+ m[h // 10:h - h // 10, w // 10:w - w // 10] = True # the warp fills the borders in
+ return m
+
+
+def background_motion(prev_gray: np.ndarray, gray: np.ndarray, region: np.ndarray, centre: np.ndarray) -> np.ndarray | None:
+ """The background's own motion, from corners searched for outside the subject with a low threshold (a plain
+ background's only detail — sparkles, a horizon, a texture — is weak next to a character's outlines)."""
+ bg_mask = np.where(region == 0, 255, 0).astype(np.uint8)
+ pts = cv2.goodFeaturesToTrack(prev_gray, maxCorners=300, qualityLevel=0.001, minDistance=7, blockSize=7, mask=bg_mask)
+ if pts is None or len(pts) < MIN_BG_TRACKS:
+ return None
+ nxt, st1, _ = cv2.calcOpticalFlowPyrLK(prev_gray, gray, pts, None, **_LK)
+ back, st2, _ = cv2.calcOpticalFlowPyrLK(gray, prev_gray, nxt, None, **_LK)
+ good = (st1.ravel() == 1) & (st2.ravel() == 1) & (np.linalg.norm((pts - back).reshape(-1, 2), axis=1) < FB_MAX_ERR)
+ if good.sum() < MIN_BG_TRACKS:
+ return None
+ M, inl = cv2.estimateAffinePartial2D(pts.reshape(-1, 2)[good] - centre, nxt.reshape(-1, 2)[good] - centre, method=cv2.RANSAC,
+ ransacReprojThreshold=RANSAC_PX, maxIters=2000, confidence=0.995)
+ if M is None or inl is None or inl.mean() < 0.5:
+ return None
+ agree = pts.reshape(-1, 2)[good][inl.ravel() == 1]
+ if len(agree) < 3 or cv2.contourArea(cv2.convexHull(agree.astype(np.float32))) < BG_SPREAD * prev_gray.size:
+ return None
+ return M
+
+
+def background_says_still(prev_gray: np.ndarray, gray: np.ndarray, M: np.ndarray, centre: np.ndarray, region: np.ndarray) -> bool:
+ """No trackable background: if moving the camera explains the rest of the frame no better than not moving it, the
+ camera stood still and the subject moved. Without background evidence the simpler answer wins (a head tilt read as
+ a 2.5° camera roll on a real film is what this fixes)."""
+ bg = _inner(gray.shape) & (region == 0)
+ err_still = float(np.mean(cv2.absdiff(prev_gray, gray)[bg])) / 255
+ err_warp = float(np.mean(cv2.absdiff(_warp(prev_gray, M, centre), gray)[bg])) / 255
+ return err_still < BG_SAME or err_warp > BG_GAIN * err_still
+
+
+def photometric_ok(prev_gray: np.ndarray, gray: np.ndarray, M: np.ndarray, centre: np.ndarray) -> bool:
+ """Verify the fit on the pixels, not only on the tracks: warping the previous frame by the estimated transform must
+ explain the current one clearly better than not moving at all. Between two unrelated pictures (a cut the shot list
+ missed by a frame, a hard transition) RANSAC still finds *some* similarity; this is where it is caught."""
+ h, w = gray.shape
+ warped = _warp(prev_gray, M, centre)
+ my, mx = h // 10, w // 10 # borders are filled in by the warp
+ inner = (slice(my, h - my), slice(mx, w - mx))
+ err_warp = float(np.mean(cv2.absdiff(warped[inner], gray[inner]))) / 255
+ err_still = float(np.mean(cv2.absdiff(prev_gray[inner], gray[inner]))) / 255
+ return err_warp <= max(PHOTO_MAX_ERR, PHOTO_GAIN * err_still)
+
+
+def hsv_hist(bgr: np.ndarray) -> np.ndarray:
+ hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)
+ h = cv2.calcHist([hsv], [0, 1], None, [16, 8], [0, 180, 0, 256])
+ return cv2.normalize(h, h).ravel()
+
+
+def looks_like_cut(prev_hist: np.ndarray, hist: np.ndarray, prev_gray: np.ndarray, gray: np.ndarray) -> bool:
+ """A hard cut: the colour distribution and the pixels both change at once (a fast pan changes pixels, not colours)."""
+ corr = cv2.compareHist(prev_hist.astype(np.float32), hist.astype(np.float32), cv2.HISTCMP_CORREL)
+ diff = float(np.mean(cv2.absdiff(prev_gray, gray))) / 255
+ return corr < 0.6 and diff > 0.12
diff --git a/.claude/skills/video-clone/scripts/perception/cli.py b/.claude/skills/video-clone/scripts/perception/cli.py
new file mode 100644
index 0000000..e1c41b8
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/cli.py
@@ -0,0 +1,183 @@
+"""Command line for perception (run through scripts/fingerprint.py).
+
+ fingerprint.py extract <video> --out fp.json [--shots report.json|plan.json] [--audio a.wav] [--plot fp.png]
+ fingerprint.py compare <ref_fp.json> <our_fp.json> --out style_distance.json [--plan plan.json] [--window a:b] [--plot overlay.png]
+ fingerprint.py plan-check <projects/id>
+ before building: the plan's cutting against the stretch of reference it clones (slower is flagged, faster is
+ the brief's call), and which shots are too short for the reference camera movement they answer
+ fingerprint.py project <projects/id> [--video out/video.mp4]
+ reference fingerprint (analysis/fingerprint.json, made if missing) + ours (out/check/fingerprint.json)
+ + out/check/style_distance.json + out/check/fingerprint_overlay.png, and the findings printed
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+
+from . import curves, distance, fingerprint, plot
+
+
+def _load(p: str):
+ with open(p, encoding="utf-8") as f:
+ return json.load(f)
+
+
+def _save(obj, p: str):
+ os.makedirs(os.path.dirname(os.path.abspath(p)), exist_ok=True)
+ with open(p, "w", encoding="utf-8") as f:
+ json.dump(obj, f, ensure_ascii=False, separators=(",", ":"))
+
+
+def _shots_from(path: str | None):
+ if not path:
+ return None
+ j = _load(path)
+ return j.get("shots") if isinstance(j, dict) else j
+
+
+def reference(analysis: str, report: dict | None = None) -> dict:
+ """Fingerprint of the analysed reference, using analyze.py's cuts and beats (one source of truth for both)."""
+ report = report or _load(os.path.join(analysis, "report.json"))
+ video = os.path.join(analysis, report.get("analysed") or "source.mp4")
+ wav = os.path.join(analysis, "audio.wav")
+ au = report.get("audio") or {}
+ return fingerprint.extract(video, shots=report.get("shots") or None, audio=wav if os.path.exists(wav) else None,
+ beats=au.get("beats") if au.get("beats") else None)
+
+
+def ensure_reference(P: str) -> dict:
+ """The project's reference fingerprint, made (or remade) when missing or written by an older version of this code:
+ projects analysed before perception existed, or before its last change, work without re-running analyze.py."""
+ an = os.path.join(P, "analysis")
+ ref_p = os.path.join(an, "fingerprint.json")
+ if os.path.exists(ref_p):
+ ref = _load(ref_p)
+ if ref.get("version") == fingerprint.VERSION:
+ return ref
+ ref = reference(an)
+ _save(ref, ref_p)
+ plot.single(ref, os.path.join(an, "fingerprint.png"))
+ return ref
+
+
+def pairs_from_plan(plan: dict) -> list[dict]:
+ return [{"id": s["id"], "ref_shot": fingerprint.ref_shot_id(s.get("ref_shot"))} for s in plan.get("shots", [])
+ if s.get("id") is not None and fingerprint.ref_shot_id(s.get("ref_shot")) is not None]
+
+
+def project(P: str, video: str = "out/video.mp4") -> dict:
+ chk = os.path.join(P, "out", "check")
+ ref = ensure_reference(P)
+ plan = _load(os.path.join(P, "plan.json"))
+ shots = [s for s in plan.get("shots", []) if s.get("start_s") is not None and s.get("end_s") is not None]
+ ours = fingerprint.extract(os.path.join(P, video), shots=shots or None)
+ _save(ours, os.path.join(chk, "fingerprint.json"))
+ sd = distance.style_distance(ref, ours, pairs_from_plan(plan))
+ _save(sd, os.path.join(chk, "style_distance.json"))
+ R = fingerprint.window(ref, *sd["ref_window"]) if sd["ref_window"] else ref
+ _, _, mapping = distance.tension_component(R, ours)
+ plot.overlay(R, ours, mapping, os.path.join(chk, "fingerprint_overlay.png"))
+ return sd
+
+
+def plan_check(P: str) -> dict:
+ """How the plan's cutting compares with the stretch of reference it clones, before anything is built: too slow is
+ flagged; faster is reported (with shots too short for the reference's camera movement, whose moves get sped up or
+ left out) but left to the brief — the picture should change at least as often as the reference's does."""
+ plan, ref = _load(os.path.join(P, "plan.json")), ensure_reference(P)
+ shots = [s for s in plan.get("shots", []) if s.get("start_s") is not None and s.get("end_s") is not None]
+ answers = fingerprint.reference_for(ref, [(s.get("id"), fingerprint.ref_shot_id(s.get("ref_shot")), float(s["end_s"]) - float(s["start_s"]))
+ for s in shots])
+ mapped = [(s, answers.get(s.get("id"))) for s in shots]
+ refs_used = [r for _, r in mapped if r is not None]
+ if not shots or not refs_used:
+ return {"ok": True, "note": "no shots mapped to the reference"}
+ a = min((r.get("part_of") or [r["start"]])[0] for r in refs_used)
+ b = max((r.get("part_of") or [0, r["end"]])[1] for r in refs_used)
+ R = fingerprint.window(ref, a, b)
+ ours_len = max(float(s["end_s"]) for s in shots) - min(float(s["start_s"]) for s in shots)
+ ref_rate = len(R["cuts"]) / max(1e-6, R["end"] - R["start"]) * 10
+ our_rate = (len(shots) - 1) / max(1e-6, ours_len) * 10
+ squeezed = []
+ for s, r in mapped:
+ if r is None:
+ continue
+ mv = r["move"]
+ moving = curves.on_screen(mv) + sum(float(o.get("duration") or 0) for o in mv.get("other_moves") or [])
+ length = float(s["end_s"]) - float(s["start_s"])
+ if moving > 0 and length < curves.MIN_PACE * moving:
+ squeezed.append({"shot": s.get("id"), "ref_shot": r["id"], "shot_s": round(length, 2), "ref_moving_s": round(moving, 2)})
+ ratio = our_rate / ref_rate if ref_rate > 0 else None
+ # Only *slower* than the reference is a problem. An A/B run showed the other side: held to the reference's hard-cut
+ # count, a plan went from 14 shots to 8 and lost variety — the reference changes scene inside its shots (curtains,
+ # smoke, an iris), so its cuts undercount how often the picture changes. Faster cutting is the brief's call.
+ return {"ok": ratio is None or ratio >= 1 / 1.3, "cuts_per_10s": {"plan": round(our_rate, 2), "reference": round(ref_rate, 2)},
+ "ratio": round(ratio, 2) if ratio else None, "ref_window": [round(a, 2), round(b, 2)], "squeezed": squeezed}
+
+
+def report(sd: dict) -> str:
+ c = sd["components"]
+ lines = [f"style distance: overall {sd['overall']} = style {sd['style']} (looks and moves like it) + structure {sd['structure']} "
+ f"(follows its arc) (ref window {sd['ref_window']})",
+ " " + " ".join(f"{k} {c[k]['score'] if c[k].get('score') is not None else '-'}" for k in distance.WEIGHTS)]
+ lines += [f" [{f['severity']}] {f['component']} {f['where']}: {f['text']}" for f in sd["findings"]]
+ return "\n".join(lines)
+
+
+def main(argv: list[str] | None = None):
+ if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(encoding="utf-8")
+ ap = argparse.ArgumentParser(prog="fingerprint.py", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ e = sub.add_parser("extract")
+ e.add_argument("video")
+ e.add_argument("--out", required=True)
+ e.add_argument("--shots", help="report.json (analyze.py) or plan.json: use these shot boundaries instead of detecting cuts")
+ e.add_argument("--audio")
+ e.add_argument("--fps", type=float, default=24.0)
+ e.add_argument("--start", type=float, default=0.0)
+ e.add_argument("--end", type=float)
+ e.add_argument("--plot")
+ c = sub.add_parser("compare")
+ c.add_argument("ref")
+ c.add_argument("ours")
+ c.add_argument("--out", required=True)
+ c.add_argument("--plan")
+ c.add_argument("--window", help="a:b seconds of the reference")
+ c.add_argument("--plot")
+ pc = sub.add_parser("plan-check")
+ pc.add_argument("dir")
+ p = sub.add_parser("project")
+ p.add_argument("dir")
+ p.add_argument("--video", default="out/video.mp4")
+ a = ap.parse_args(argv)
+
+ if a.cmd == "extract":
+ fp = fingerprint.extract(a.video, shots=_shots_from(a.shots), audio=a.audio, fps=a.fps, start=a.start, end=a.end)
+ _save(fp, a.out)
+ if a.plot:
+ plot.single(fp, a.plot)
+ print(f"{len(fp['shots'])} shots, {len(fp['cuts'])} cuts, peaks at {[p['t'] for p in fp['peaks']]} → {a.out}")
+ elif a.cmd == "compare":
+ ref, ours = _load(a.ref), _load(a.ours)
+ win = tuple(map(float, a.window.split(":"))) if a.window else None
+ sd = distance.style_distance(ref, ours, pairs_from_plan(_load(a.plan)) if a.plan else None, win)
+ _save(sd, a.out)
+ if a.plot:
+ R = fingerprint.window(ref, *sd["ref_window"]) if sd["ref_window"] else ref
+ plot.overlay(R, ours, distance.tension_component(R, ours)[2], a.plot)
+ print(report(sd))
+ elif a.cmd == "plan-check":
+ r = plan_check(a.dir)
+ if "cuts_per_10s" in r:
+ c = r["cuts_per_10s"]
+ verdict = "slower than the reference: add cuts or in-shot scene changes" if not r["ok"] else "ok" if r["ratio"] <= 1.3 else "faster than the reference: fine when the brief asks for energy"
+ print(f"cutting: plan {c['plan']} cuts / 10 s, reference {c['reference']} hard cuts (×{r['ratio']}) — {verdict}")
+ for q in r.get("squeezed", []):
+ print(f" note {q['shot']}: {q['shot_s']} s for ref #{q['ref_shot']}'s {q['ref_moving_s']} s of camera movement — the transfer will keep its biggest moves")
+ if "note" in r:
+ print(r["note"])
+ else:
+ print(report(project(a.dir, a.video)))
diff --git a/.claude/skills/video-clone/scripts/perception/curves.py b/.claude/skills/video-clone/scripts/perception/curves.py
new file mode 100644
index 0000000..384063f
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/curves.py
@@ -0,0 +1,333 @@
+"""The shape of a camera move: when it starts and stops, how far it goes, and the easing curve it follows.
+
+The whole shot trajectory x(t) of the dominant axis is fitted with a *timed* ease model
+
+ x(t) = B + A · E( clip((t − t0) / D, 0, 1) )
+
+so start time t0, duration D, amount A, offset B and the ease shape E are estimated together. Cutting the move out by a
+speed threshold first would bias the shape: a power3.out spends its last quarter below 8 % of peak speed and would be
+clipped and stretched. E is described three ways:
+
+ named the nearest GSAP ease (power1–4, sine, expo, circ, back), so a builder can type it directly
+ bezier CSS cubic-bezier(x1, y1, x2, y2), with x(s) = u solved per sample
+ spring damped oscillator x(t) = B + A·(1 − e^(−ζωτ)(cos ω_d τ + ζω/ω_d · sin ω_d τ)), τ = t − t0, ω in rad/s
+
+plus overshoot (how far past the target it goes before settling) and the measured progress curve on the fitted
+[t0, t0 + D] window, which is what two moves are compared on.
+"""
+from __future__ import annotations
+
+from typing import Callable
+
+import numpy as np
+from scipy.ndimage import gaussian_filter1d
+from scipy.optimize import least_squares
+from scipy.signal import find_peaks
+
+PROGRESS_SAMPLES = 21
+Ease = Callable[[np.ndarray], np.ndarray]
+
+
+# ---------- named eases (GSAP's formulas) ----------
+def _power(p: float) -> dict[str, Ease]:
+ return {"in": lambda t: t ** p, "out": lambda t: 1 - (1 - t) ** p,
+ "inOut": lambda t: np.where(t < 0.5, (2 * t) ** p / 2, 1 - (2 * (1 - t)) ** p / 2)}
+
+
+def _named() -> dict[str, Ease]:
+ out: dict[str, Ease] = {"none": lambda t: t}
+ for n in (1, 2, 3, 4):
+ for k, f in _power(n + 1).items():
+ out[f"power{n}.{k}"] = f
+ out.update({
+ "sine.in": lambda t: 1 - np.cos(t * np.pi / 2), "sine.out": lambda t: np.sin(t * np.pi / 2),
+ "sine.inOut": lambda t: -(np.cos(np.pi * t) - 1) / 2,
+ "expo.in": lambda t: np.where(t <= 0, 0.0, 2.0 ** (10 * (t - 1))), "expo.out": lambda t: np.where(t >= 1, 1.0, 1 - 2.0 ** (-10 * t)),
+ "expo.inOut": lambda t: np.where(t < 0.5, 2.0 ** (20 * t - 10) / 2, (2 - 2.0 ** (-20 * t + 10)) / 2),
+ "circ.in": lambda t: 1 - np.sqrt(np.clip(1 - t ** 2, 0, 1)), "circ.out": lambda t: np.sqrt(np.clip(1 - (t - 1) ** 2, 0, 1)),
+ "back.out": lambda t: 1 + 2.70158 * (t - 1) ** 3 + 1.70158 * (t - 1) ** 2,
+ "back.in": lambda t: 2.70158 * t ** 3 - 1.70158 * t ** 2,
+ })
+ return out
+
+
+NAMED = _named()
+
+
+# ---------- cubic bezier ----------
+def bezier(u: np.ndarray, x1: float, y1: float, x2: float, y2: float) -> np.ndarray:
+ """CSS cubic-bezier easing evaluated at progress u (x1, x2 ∈ [0, 1] keep x(s) monotonic; bisection on s)."""
+ u = np.clip(np.asarray(u, float), 0, 1)
+ lo, hi = np.zeros_like(u), np.ones_like(u)
+ for _ in range(30):
+ s = (lo + hi) / 2
+ x = 3 * (1 - s) ** 2 * s * x1 + 3 * (1 - s) * s ** 2 * x2 + s ** 3
+ lo, hi = np.where(x < u, s, lo), np.where(x < u, hi, s)
+ s = (lo + hi) / 2
+ return 3 * (1 - s) ** 2 * s * y1 + 3 * (1 - s) * s ** 2 * y2 + s ** 3
+
+
+_BEZIER_STARTS = [(0.25, 0.1, 0.25, 1.0), (0.42, 0.0, 0.58, 1.0), (0.16, 1.0, 0.3, 1.0), (0.34, 1.56, 0.64, 1.0)]
+
+
+def spring(tau: np.ndarray, omega: float, zeta: float) -> np.ndarray:
+ """Unit step response of a damped oscillator after tau seconds (0 before)."""
+ zeta = min(zeta, 0.999)
+ tau = np.clip(tau, 0, None)
+ wd = omega * np.sqrt(1 - zeta ** 2)
+ return 1 - np.exp(-zeta * omega * tau) * (np.cos(wd * tau) + zeta * omega / wd * np.sin(wd * tau))
+
+
+# ---------- timed fits ----------
+def _initial_timing(t: np.ndarray, x: np.ndarray) -> tuple[float, float, float, float]:
+ """t0, D, A, B from where the trajectory crosses 2 % and 98 % of its net travel."""
+ B, A = float(x[0]), float(x[-1] - x[0])
+ p = (x - B) / A
+ i0 = int(np.argmax(p >= 0.02))
+ i1 = int(np.argmax(p >= 0.98)) if (p >= 0.98).any() else len(x) - 1
+ dt = float(t[1] - t[0])
+ return float(t[i0]) - dt, max(2 * dt, float(t[i1] - t[i0]) / 0.96), A, B
+
+
+def _fit(t: np.ndarray, x: np.ndarray, shape: Callable, shape0: tuple, shape_lo: tuple, shape_hi: tuple, init) -> tuple[np.ndarray, float]:
+ """Least squares for x(t) = B + A·shape(u, *params), u = clip((t − t0)/D); residual relative to |A|."""
+ t0, D, A, B = init
+ span, dt, scale = float(t[-1] - t[0]), float(t[1] - t[0]), abs(A) or 1.0
+ k = len(shape0)
+
+ def res(p):
+ u = np.clip((t - p[k]) / p[k + 1], 0, 1)
+ return (p[k + 3] + p[k + 2] * shape(u, *p[:k]) - x) / scale
+
+ lo = [*shape_lo, t[0] - span, dt, -np.inf, -np.inf]
+ hi = [*shape_hi, t[-1], 2 * span + dt, np.inf, np.inf]
+ p0 = np.clip([*shape0, t0, D, A, B], np.array(lo) + 1e-9, np.array(hi) - 1e-9)
+ r = least_squares(res, p0, bounds=(lo, hi), x_scale="jac")
+ return r.x, float(np.sqrt(np.mean(r.fun ** 2)))
+
+
+def fit_named(t: np.ndarray, x: np.ndarray, init) -> tuple[str, np.ndarray, float]:
+ best = ("none", np.asarray(init), float("inf"))
+ for name, f in NAMED.items():
+ p, err = _fit(t, x, lambda u, f=f: f(u), (), (), (), init)
+ if err < best[2]:
+ best = (name, p, err)
+ return best
+
+
+def fit_bezier(t: np.ndarray, x: np.ndarray, init) -> tuple[np.ndarray, float]:
+ best = (np.asarray([0.0, 0.0, 1.0, 1.0, *init]), float("inf"))
+ for s0 in _BEZIER_STARTS:
+ p, err = _fit(t, x, bezier, s0, (0, -1, 0, -1), (1, 2, 1, 2), init)
+ if err < best[1]:
+ best = (p, err)
+ return best
+
+
+def fit_spring(t: np.ndarray, x: np.ndarray, init) -> tuple[dict[str, float], float]:
+ t0, D, A, B = init
+ scale = abs(A) or 1.0
+ best: tuple[dict[str, float], float] = ({}, float("inf"))
+ for w0, z0 in [(6.0, 0.9), (10.0, 0.5), (16.0, 0.3)]:
+ p0 = [np.clip(t0, t[0] - 1 + 1e-6, t[-1] - 1e-6), A, B, np.clip(w0 / max(D, 0.05), 0.6, 199), z0]
+ r = least_squares(lambda p: (p[2] + p[1] * spring(t - p[0], p[3], p[4]) - x) / scale, p0,
+ bounds=([t[0] - 1, -np.inf, -np.inf, 0.5, 0.05], [t[-1], np.inf, np.inf, 200, 0.999]))
+ err = float(np.sqrt(np.mean(r.fun ** 2)))
+ if err < best[1]:
+ w, z = float(r.x[3]), float(r.x[4])
+ best = ({"omega": round(w, 2), "zeta": round(z, 3), "start": round(float(r.x[0]), 3),
+ "settle_s": round(4 / (z * w), 3), "_A": float(r.x[1]), "_B": float(r.x[2])}, err)
+ return best
+
+
+# ---------- moves ----------
+AXES = ("x", "y", "z", "r")
+KIND = {"x": ("move_right", "move_left"), "y": ("move_down", "move_up"), "z": ("push_in", "pull_out"), "r": ("roll_cw", "roll_ccw")}
+MIN_AMOUNT = {"x": 0.015, "y": 0.015, "z": 0.015, "r": 0.015} # below this an axis counts as still
+SHAKE_RATE = 1.5 # direction changes per second for a shake
+SNAP_S = 2.5 / 24 # a move done this fast is a jump cut / impact jolt
+STILL_S, PAD_S, MIN_MOVE_S = 0.25, 0.125, 0.2 # move segmentation, in seconds (any sampling rate)
+
+
+def describe_move(t: np.ndarray, traj: dict[str, np.ndarray], fit: bool = True) -> dict:
+ """traj: cumulative camera position per axis (x, y in frame widths, z log-scale, r radians), starting at 0.
+ fit=False skips the ease fits (≈ 300 ms) and reads timing and shape straight off the curve: for exact, finely
+ sampled trajectories (a score's predicted camera) that is the same answer, and it is what the optimizer needs."""
+ amount = {a: float(traj[a][-1] - traj[a][0]) for a in AXES}
+ swing = {a: float(np.ptp(traj[a])) for a in AXES}
+ kinds = [KIND[a][0 if amount[a] > 0 else 1] for a in AXES if abs(amount[a]) >= MIN_AMOUNT[a]]
+ out: dict = {"kind": kinds or ["static"], "amount": {a: round(amount[a], 4) for a in AXES}}
+ axis = max(AXES, key=lambda a: swing[a])
+ if swing[axis] < MIN_AMOUNT[axis] or len(t) < 6:
+ return out
+ # turns back on itself at least twice by a third of its swing: a shake, not a move to somewhere (a move with an
+ # overshoot turns once; a spring's later wobbles are smaller than that)
+ # … and quickly: a camera that drifts down and back up over twelve seconds is several moves, not a shake
+ turns = sum(len(find_peaks(s * traj[axis], prominence=swing[axis] / 3)[0]) for s in (1, -1))
+ rate = turns / max(1e-6, float(t[-1] - t[0]))
+ if (turns >= 2 or abs(amount[axis]) < 0.2 * swing[axis]) and rate >= SHAKE_RATE:
+ out["kind"] = kinds + ["shake"] if kinds else ["shake"]
+ out["shake"] = {"axis": axis, "swing": round(swing[axis], 4)}
+ return out
+ # engines tween scale, not log-scale: fit the ease on the scale itself so "power3.out" means what a builder types
+ x = np.exp(traj[axis]) if axis == "z" else traj[axis]
+ if not fit:
+ t5, t95, prog = canonical_progress(t, x)
+ p = (x - x[0]) / ((x[-1] - x[0]) or 1.0)
+ out.update({"snap": t95 - t5 <= SNAP_S, "axis": axis, "start": round(t5, 3), "end": round(t95, 3), "t5": round(t5, 3), "t95": round(t95, 3),
+ "duration": round((t95 - t5) / 0.9, 3), "span90": round(t95 - t5, 3),
+ "overshoot": round(max(0.0, float(p.max()) - 1), 4), "progress": [round(float(v), 4) for v in prog]})
+ return out
+ init = _initial_timing(t, x)
+ name, pn, err_n = fit_named(t, x, init)
+ pb, err_b = fit_bezier(t, x, tuple(pn[-4:]))
+ sp, err_s = fit_spring(t, x, tuple(pn[-4:]))
+ t0, D, A, B = (float(v) for v in pn[-4:])
+ # What two moves are compared on: the curve between the 5 % and 95 % points of its travel. This window does not
+ # depend on which model fitted best ("flat start + ease" and "later start + another ease" are the same motion, and
+ # fitted windows would make them look different). It is read off the best-fitting model sampled 10× finer than the
+ # frames: a fast move spans only a few frames, and where those frames fall would otherwise change its shape.
+ best = min((("named", err_n), ("bezier", err_b), ("spring", err_s)), key=lambda p: p[1])[0]
+ # The model a builder (and the transfer) uses: a GSAP name when it fits nearly as well as the best — easier to read
+ # and tweak — else the best. Its curve and its own window are the move's shape, start and duration, so every reader
+ # (transfer, comparison, reports) shares one description of the move.
+ pick = "named" if err_n <= 1.1 * min(err_n, err_b, err_s) + 0.002 else best
+ timing = {"named": (t0, D), "bezier": (float(pb[4]), float(pb[5])),
+ "spring": (float(sp.get("start", t0)), float(sp.get("settle_s", D)))}
+ m0, mD = timing[pick]
+ fine = np.linspace(t[0], t[-1], 10 * len(t))
+ if pick == "named":
+ xm = B + A * NAMED[name](np.clip((fine - t0) / D, 0, 1))
+ elif pick == "bezier":
+ xm = pb[7] + pb[6] * bezier(np.clip((fine - pb[4]) / pb[5], 0, 1), *pb[:4])
+ else:
+ xm = sp["_B"] + sp["_A"] * spring(fine - sp["start"], sp["omega"], sp["zeta"])
+ t5, t95, prog = canonical_progress(fine, xm)
+ # A move the edit cuts off (real footage often cuts mid-move): how much of it is on screen, in time and in progress
+ shape = {"named": lambda u: NAMED[name](u), "bezier": lambda u: bezier(u, *pb[:4]),
+ "spring": lambda u: spring(u * mD, sp["omega"], sp["zeta"]) if sp else u}[pick]
+ u_in, u_out = max(0.0, (float(t[0]) - m0) / mD), min(1.0, (float(t[-1]) - m0) / mD)
+ seen = float(shape(np.asarray(u_out)) - shape(np.asarray(u_in))) if u_out > u_in else 0.0
+ after = (x[t >= t0] - B) / A
+ speed = np.abs(np.gradient(x, t))
+ out.update({
+ "snap": t95 - t5 <= SNAP_S, # done within a couple of frames: a jump, its "ease" means nothing
+ "axis": axis, "start": round(max(m0, float(t[0])), 3), "end": round(min(m0 + mD, float(t[-1])), 3), "duration": round(mD, 3),
+ "hold_before": round(max(0.0, m0 - float(t[0])), 3), "hold_after": round(max(0.0, float(t[-1]) - m0 - mD), 3),
+ "peak_speed": round(float(speed.max()), 4),
+ "ease": {"named": name, "named_rmse": round(err_n, 4),
+ "bezier": [round(float(v), 3) for v in pb[:4]], "bezier_rmse": round(err_b, 4),
+ "spring": {k: v for k, v in sp.items() if not k.startswith("_")}, "spring_rmse": round(err_s, 4), "best": best, "pick": pick,
+ "overshoot": round(max(0.0, float(after.max()) - 1) if len(after) else 0.0, 4)},
+ "timing": {k: [round(a, 4), round(b, 4)] for k, (a, b) in timing.items()},
+ "span90": round(t95 - t5, 3), "t5": round(t5, 3), "t95": round(t95, 3),
+ "progress": [round(float(v), 4) for v in prog],
+ "visible": round(max(0.0, min(m0 + mD, float(t[-1])) - max(m0, float(t[0]))), 3),
+ "cut_off": m0 + mD > float(t[-1]) + float(t[1] - t[0]), # still moving at the cut out
+ "lead_in": round(max(0.0, float(t[0]) - m0), 3), # already moving this long at the cut in
+ "seen": round(seen, 4), # share of the move's travel that is on screen (< 1 when the cut interrupts it)
+ })
+ return out
+
+
+def canonical_progress(t: np.ndarray, x: np.ndarray, lo: float = 0.05, hi: float = 0.95) -> tuple[float, float, np.ndarray]:
+ """Times where the travel first reaches lo and hi of its net amount, and the curve between them rescaled to 0–1."""
+ p = (x - x[0]) / ((x[-1] - x[0]) or 1.0)
+ def cross(level):
+ i = int(np.argmax(p >= level))
+ if i == 0:
+ return float(t[0])
+ return float(np.interp(level, [p[i - 1], p[i]], [t[i - 1], t[i]])) if p[i] != p[i - 1] else float(t[i])
+ t5, t95 = cross(lo), cross(hi)
+ if t95 <= t5:
+ t95 = t5 + float(t[1] - t[0])
+ u = np.linspace(0, 1, PROGRESS_SAMPLES)
+ prog = (np.interp(t5 + u * (t95 - t5), t, p) - lo) / (hi - lo)
+ return t5, t95, prog
+
+
+MIN_PACE = 0.5 # a move may be sped up to 2× to fit a shorter shot; beyond that the smaller moves are left out
+
+
+def on_screen(m: dict) -> float:
+ """How long a move is on screen (a move a cut interrupts shows only part of its length)."""
+ partial = m.get("cut_off") or (m.get("lead_in") or 0) > 0.05
+ return float((m.get("visible") if partial and m.get("visible") is not None else m.get("duration")) or 0.0)
+
+
+def moves_that_fit(moves: list[dict], length: float) -> list[dict]:
+ """The moves a shot of `length` seconds keeps from a reference shot: all of them when they fit at ≥ MIN_PACE of
+ their speed, else the biggest ones (squeezing twelve seconds of slow drifting into two makes whip pans). Shared by
+ the transfer (what it writes) and the comparison (what pace it expects), so the two never disagree."""
+ kept = list(moves)
+ while len(kept) > 1 and sum(on_screen(m) for m in kept) > length / MIN_PACE:
+ kept.remove(min(kept, key=lambda m: max(abs(v) / MIN_AMOUNT[a] for a, v in m["amount"].items())))
+ return kept
+
+
+def moving_segments(t: np.ndarray, traj: dict[str, np.ndarray]) -> list[tuple[int, int]]:
+ """Index ranges where the camera moves, split where it stays still for at least STILL_S seconds."""
+ if len(t) < 4:
+ return []
+ dt = float(t[1] - t[0])
+ min_still, pad, min_len = max(1, round(STILL_S / dt)), max(1, round(PAD_S / dt)), max(2, round(MIN_MOVE_S / dt))
+ speed = gaussian_filter1d(np.sqrt(sum(np.gradient(traj[a], t) ** 2 for a in AXES)), 0.0625 / dt)
+ active = speed > max(0.12 * float(speed.max()), 0.02)
+ segs, k, n = [], 0, len(t)
+ while k < n:
+ if not active[k]:
+ k += 1
+ continue
+ e = k
+ while e + 1 < n and (active[e + 1] or active[e + 2:e + 1 + min_still].any()):
+ e += 1
+ segs.append((max(0, k - pad), min(n - 1, e + pad)))
+ k = e + 1
+ return [(a, b) for a, b in segs if b - a >= min_len and max(np.ptp(traj[x][a:b + 1]) for x in AXES) >= min(MIN_AMOUNT.values())]
+
+
+def describe_shot(t: np.ndarray, traj: dict[str, np.ndarray], fit: bool = True) -> dict:
+ """The shot's camera as a whole (kind, total amount) plus each separate move inside it; the top-level ease, timing
+ and progress are those of the biggest move, which is what a shot is compared on.
+
+ Travel that no move accounts for is a *drift*: a slow push or pan running under the whole shot, too slow next to
+ its quick moves to be segmented as one (seen on a real reference: a 16 % push of which segmentation kept half).
+ Its rate comes from the travel outside the moves; each move's own amount has the drift during it taken out."""
+ whole = describe_move(t, traj, fit)
+ if "axis" not in whole: # still, or a shake
+ net = {x: float(whole["amount"][x]) for x in AXES if abs(whole["amount"][x]) >= MIN_AMOUNT[x]}
+ if "shake" in whole["kind"] and net: # a shake that also travels: the travel is a drift under it
+ whole = {**whole, "drift": {x: round(v, 4) for x, v in net.items()}}
+ return whole
+ segs = moving_segments(t, traj)
+ moves = []
+ for a, b in segs:
+ sub = describe_move(t[a:b + 1], {x: traj[x][a:b + 1] - traj[x][a] for x in AXES}, fit)
+ if "axis" in sub:
+ # a segment's edges inside the shot are not cuts: only a segment touching the shot's start or end can be
+ # interrupted by one
+ if a > 0 and "lead_in" in sub:
+ sub["lead_in"] = 0.0
+ if b < len(t) - 1 and "cut_off" in sub:
+ sub["cut_off"] = False
+ if "seen" in sub and not sub.get("cut_off") and not sub.get("lead_in"):
+ sub["seen"], sub["visible"] = 1.0, sub["duration"]
+ moves.append((sub, float(t[b] - t[a])))
+ total_t = float(t[-1] - t[0])
+ moving_t = sum(d for _, d in moves)
+ residual = {x: float(whole["amount"][x]) - sum(m["amount"][x] for m, _ in moves) for x in AXES}
+ drift = {x: v for x, v in residual.items() if abs(v) >= MIN_AMOUNT[x]} if moves and total_t - moving_t > 0.25 * total_t else {}
+ if len(moves) <= 1 and not drift:
+ return {**whole, "moves": 1}
+ rate = {x: v / max(1e-6, total_t - moving_t) for x, v in drift.items()} # per second, outside the moves
+ for m, d in moves:
+ m["amount"] = {x: round(m["amount"][x] - rate.get(x, 0.0) * d, 4) for x in AXES}
+ moves = [m for m, _ in moves]
+ if not moves:
+ return {**whole, "moves": 1}
+ main = max(moves, key=lambda m: abs(m["amount"][m["axis"]]) / MIN_AMOUNT[m["axis"]])
+ others = [{k: m[k] for k in ("kind", "axis", "start", "duration", "amount")} | {"ease": m["ease"]["named"] if "ease" in m else None} for m in moves if m is not main]
+ out = {**main, "kind": whole["kind"], "amount": whole["amount"], "move_amount": main["amount"], "moves": len(moves), "other_moves": others}
+ if drift:
+ out["drift"] = {x: round(r * total_t, 4) for x, r in rate.items()}
+ return out
diff --git a/.claude/skills/video-clone/scripts/perception/distance.py b/.claude/skills/video-clone/scripts/perception/distance.py
new file mode 100644
index 0000000..3d95c92
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/distance.py
@@ -0,0 +1,495 @@
+"""style_distance: how far our film is from the reference, per component, per shot, and in words.
+
+Components (each 0–100, higher = closer):
+
+ tension DTW between the two tension curves (8 Hz): same build-and-release shape, allowing the timing to stretch
+ peaks the reference's climax against ours at the DTW-aligned moment: breath, how fast the hit lands, height, hold
+ camera per mapped shot pair: same kind of move, easing curve RMSE, duration and amount ratios
+ rhythm cut/beat phase: on-beat ratio, where in the beat cuts land, cuts per beat
+ look per mapped shot pair: Wasserstein distance of the Lab histograms
+ frames DTW over frame descriptors (layout of light and colour), a weak signal across media
+
+Scores are exp(−cost / scale) with hand-set scales — a calibration that a learned critic will replace (docs/COMPILER.md,
+stage 5). Findings are the point: concrete, numeric, and tied to a shot or a time, so a builder knows what to change.
+"""
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+from typing import Callable
+
+import numpy as np
+from scipy.spatial.distance import cdist
+
+from . import curves, tension
+from . import look as look_
+from .fingerprint import times, window
+
+# Two questions, two scores. STYLE: does it look and move like the reference (palette, pace, camera, colour per shot,
+# cut rhythm)? STRUCTURE: does it follow the arc of the section it clones (tension, peaks)? Validated by split-half
+# retrieval on the references (docs/COMPILER.md): palette and pace pick a window's own reference far above chance,
+# rhythm and frames weakly, tension and peaks not at all — they describe *this* stretch's content, so they are only
+# meaningful against the mapped window, never as "style".
+STYLE = {"camera": 0.30, "palette": 0.20, "pace": 0.20, "look": 0.15, "rhythm": 0.10, "frames": 0.05}
+STRUCTURE = {"tension": 0.5, "peaks": 0.5}
+OVERALL = {"style": 0.65, "structure": 0.35}
+WEIGHTS = {**{k: OVERALL["style"] * w for k, w in STYLE.items()}, **{k: OVERALL["structure"] * w for k, w in STRUCTURE.items()}}
+CURVE_HZ = 8.0
+
+
+# ---------- DTW ----------
+def dtw(a: np.ndarray, b: np.ndarray, band: float = 0.2, metric: str = "cityblock") -> tuple[float, list[tuple[int, int]]]:
+ """Dynamic time warping with a Sakoe–Chiba band (fraction of the longer series) around the scaled diagonal.
+
+ Each row is solved in vectorised form: with x_j = min(D[i−1, j], D[i−1, j−1]) the recurrence
+ d_j = c_j + min(d_{j−1}, x_j) unrolls to d_j = S_j + min_{k ≤ j}(x_k − S_{k−1}), S = cumsum(c),
+ i.e. one cumsum and one running minimum per row. Returns (mean cost along the path, path)."""
+ a, b = np.asarray(a, float).reshape(len(a), -1), np.asarray(b, float).reshape(len(b), -1)
+ n, m = len(a), len(b)
+ if n == 0 or m == 0:
+ return float("inf"), []
+ C = cdist(a, b, metric)
+ r = max(2, int(band * max(n, m)))
+ D = np.full((n, m), np.inf)
+ for i in range(n):
+ centre = i * (m - 1) / max(1, n - 1)
+ lo, hi = max(0, int(centre - r)), min(m - 1, int(centre + r))
+ c = C[i, lo:hi + 1]
+ S = np.cumsum(c)
+ S_prev = np.r_[0.0, S[:-1]]
+ if i == 0:
+ x = np.full(len(c), np.inf)
+ x[0] = 0.0 if lo == 0 else np.inf
+ else:
+ up = D[i - 1, lo:hi + 1]
+ diag = np.r_[D[i - 1, lo - 1] if lo > 0 else np.inf, D[i - 1, lo:hi]]
+ x = np.minimum(up, diag)
+ D[i, lo:hi + 1] = S + np.minimum.accumulate(x - S_prev)
+ if not np.isfinite(D[-1, -1]):
+ return float("inf"), []
+ path, i, j = [(n - 1, m - 1)], n - 1, m - 1
+ while i > 0 or j > 0:
+ steps = [(i - 1, j - 1), (i - 1, j), (i, j - 1)]
+ i, j = min((s for s in steps if s[0] >= 0 and s[1] >= 0), key=lambda s: D[s])
+ path.append((i, j))
+ path.reverse()
+ return float(sum(C[p] for p in path) / len(path)), path
+
+
+def resample(fp: dict, values: list[float], hz: float = CURVE_HZ) -> tuple[np.ndarray, np.ndarray]:
+ t = times(fp)
+ tt = np.arange(t[0], t[-1], 1 / hz) if len(t) > 1 else t
+ return tt, np.interp(tt, t, np.asarray(values, float))
+
+
+def _score(cost: float, scale: float) -> float:
+ return round(100 * math.exp(-cost / scale), 1) if math.isfinite(cost) else 0.0
+
+
+def _finding(component: str, where: str, severity: str, text: str) -> dict:
+ return {"component": component, "where": where, "severity": severity, "text": text}
+
+
+# ---------- components ----------
+def tension_component(ref: dict, ours: dict) -> tuple[dict, list[dict], list[tuple[float, float]]]:
+ tr, R = resample(ref, ref["series"]["tension"])
+ to, O = resample(ours, ours["series"]["tension"])
+ cost, path = dtw(R, O, band=0.25)
+ mapping = [(float(tr[i]), float(to[j])) for i, j in path]
+ findings = []
+ if len(R) and len(O):
+ # where our film sits clearly below the reference's energy for a stretch (≥ 1 s at the aligned moment)
+ gap = np.array([R[i] - O[j] for i, j in path])
+ low = gap > 0.25
+ k = 0
+ while k < len(low):
+ if low[k]:
+ e = k
+ while e + 1 < len(low) and low[e + 1]:
+ e += 1
+ if (e - k + 1) / CURVE_HZ >= 1.0:
+ a, b = to[path[k][1]], to[path[e][1]]
+ findings.append(_finding("tension", f"{a:.1f}–{b:.1f}s", "major" if gap[k:e + 1].mean() > 0.4 else "minor",
+ f"energy is {gap[k:e + 1].mean():.2f} below the reference at the aligned moment "
+ f"(ref {tr[path[k][0]]:.1f}–{tr[path[e][0]]:.1f}s): more motion, cuts or sound there"))
+ k = e + 1
+ else:
+ k += 1
+ return {"score": _score(cost, 0.12), "dtw_cost": round(cost, 4)}, findings, mapping
+
+
+def _map(mapping: list[tuple[float, float]], t_ref: float) -> float | None:
+ if not mapping:
+ return None
+ k = int(np.argmin([abs(a - t_ref) for a, _ in mapping]))
+ return mapping[k][1]
+
+
+def peaks_component(ref: dict, ours: dict, mapping: list[tuple[float, float]]) -> tuple[dict, list[dict]]:
+ rp = sorted(ref["peaks"], key=lambda p: -p["prominence"] * p["height"])
+ if not rp:
+ return {"score": None, "note": "the reference has no clear peak in this window"}, []
+ findings, pairs, costs = [], [], []
+ for p in rp[:2]:
+ at = _map(mapping, p["t"])
+ cand = [q for q in ours["peaks"] if at is not None and abs(q["t"] - at) <= 1.5]
+ if not cand:
+ findings.append(_finding("peaks", f"{at:.1f}s" if at is not None else "-", "major",
+ f"the reference peaks at {p['t']:.1f}s (height {p['height']:.2f}); ours has no peak within 1.5 s of the aligned moment"))
+ costs.append(1.0)
+ continue
+ q = min(cand, key=lambda q: abs(q["t"] - at))
+ pairs.append({"ref": p, "ours": q})
+ where = f"{q['t']:.1f}s"
+ c = 0.0
+ if p["breath_depth"] >= 0.1 and q["breath_depth"] < 0.5 * p["breath_depth"]:
+ c += 0.35
+ findings.append(_finding("peaks", where, "major", f"no held breath before the hit: dip {q['breath_depth']:.2f} vs {p['breath_depth']:.2f} in the reference "
+ f"({p['breath_s']:.2f}s before its hit) — pull energy down right before the hit"))
+ if q["rise_frames"] > 1.8 * p["rise_frames"] + 2:
+ c += 0.25
+ findings.append(_finding("peaks", where, "major", f"the hit lands slowly: {q['rise_frames']} frames to 90 % vs {p['rise_frames']} in the reference — make it land on one frame"))
+ if q["prominence"] < 0.6 * p["prominence"]:
+ c += 0.25
+ findings.append(_finding("peaks", where, "major" if q["prominence"] < 0.4 * p["prominence"] else "minor",
+ f"the hit stands out less: prominence {q['prominence']:.2f} vs {p['prominence']:.2f}"))
+ if p["hold_s"] > 0.3 and q["hold_s"] < 0.5 * p["hold_s"]:
+ c += 0.15
+ findings.append(_finding("peaks", where, "minor", f"the hit lets go too soon: holds {q['hold_s']:.2f}s vs {p['hold_s']:.2f}s"))
+ if "beat_offset_frames" in p and "beat_offset_frames" in q and abs(p["beat_offset_frames"]) <= 1 < abs(q["beat_offset_frames"]):
+ c += 0.15
+ findings.append(_finding("peaks", where, "major", f"the hit is {q['beat_offset_frames']:+.0f} frames off the beat; the reference's is on it"))
+ costs.append(min(1.0, c))
+ return {"score": round(100 * (1 - float(np.mean(costs))), 1), "pairs": pairs}, findings
+
+
+def _pct(z: float) -> str:
+ return f"{(math.exp(z) - 1) * 100:+.0f}%"
+
+
+def _amount(axis: str, v: float) -> str:
+ return _pct(v) if axis == "z" else f"{math.degrees(v):+.1f}°" if axis == "r" else f"{v:+.2f} frame widths"
+
+
+def _does(kinds: list[str]) -> str:
+ """'holds still' / 'pushes in and moves left' — move kinds as words."""
+ if kinds == ["static"]:
+ return "holds still"
+ verbs = {"push_in": "pushes in", "pull_out": "pulls out", "move_left": "moves left", "move_right": "moves right", "move_up": "moves up",
+ "move_down": "moves down", "roll_cw": "rolls clockwise", "roll_ccw": "rolls counter-clockwise", "shake": "shakes"}
+ words = [verbs.get(k, k.replace("_", " ")) for k in kinds]
+ return words[0] if len(words) == 1 else ", ".join(words[:-1]) + " and " + words[-1]
+
+
+def _ease_name(m: dict) -> str:
+ return (m.get("ease") or {}).get("named") or "an unfitted curve"
+
+
+def _membership(move: dict) -> dict[str, float]:
+ """How clearly a move goes each way, 0–1: an amount at half the 'still' threshold counts 0, at twice it 1. Kinds are
+ thresholds; comparing them as sets made 0.0149 vs 0.0151 of roll a different kind of move (89 → 53 points)."""
+ out = {}
+ for a, v in move.get("amount", {}).items():
+ lim = curves.MIN_AMOUNT.get(a, 0.015)
+ w = float(np.clip((abs(v) - 0.5 * lim) / (1.5 * lim), 0, 1))
+ if w > 0:
+ out[f"{a}{'+' if v > 0 else '-'}"] = w
+ if "shake" in move.get("kind", []):
+ out["shake"] = 1.0
+ return out
+
+
+def kind_similarity(a: dict, b: dict) -> float:
+ """Soft Jaccard of what two camera moves do (1 = the same kinds of move, 0 = nothing in common)."""
+ ma, mb = _membership(a), _membership(b)
+ keys = set(ma) | set(mb)
+ if not keys:
+ return 1.0
+ return sum(min(ma.get(k, 0), mb.get(k, 0)) for k in keys) / sum(max(ma.get(k, 0), mb.get(k, 0)) for k in keys)
+
+
+def time_available(rs: dict, os_: dict) -> float:
+ """How fast our shot has to move compared with the reference shot (≤ 1). A plan may make a shot shorter than the
+ reference's moves; then the moves that fit (curves.moves_that_fit — the transfer's own rule) are expected to be
+ that much faster, instead of being "too fast". Penalising that pushed the optimizer to bend eases into fake
+ longer moves."""
+ rm = rs["move"]
+ our_len = float(os_.get("end", 0) or 0) - float(os_.get("start", 0) or 0)
+ moves = [{"duration": rm.get("duration"), "visible": rm.get("visible"), "cut_off": rm.get("cut_off"),
+ "lead_in": rm.get("lead_in"), "amount": rm.get("move_amount", rm["amount"])}] + list(rm.get("other_moves") or [])
+ total = sum(curves.on_screen(m) for m in curves.moves_that_fit(moves, our_len)) if our_len > 0 else 0.0
+ if total <= 0 or our_len <= 0:
+ return 1.0
+ return min(1.0, our_len / total)
+
+
+def _frac(shot: dict, t: float) -> float:
+ a, b = float(shot.get("start", 0) or 0), float(shot.get("end", 0) or 0)
+ return float(np.clip((t - a) / (b - a), 0, 1)) if b > a else 0.0
+
+
+def placement_gap(rs: dict, os_: dict, k: float = 1.0) -> float:
+ """Where in the shot the main move happens — at the start, through it, at the end — as the share of the shot at
+ which its travel reaches 5 % and 95 %. A push in the first half and the same push in the second half feel different,
+ and nothing else in the comparison saw it (an optimizer moved one and a held-out check caught it).
+
+ The expectation follows the transfer's own time mapping, so the two rules never fight: the move starts at the same
+ share of the shot, and lasts its reference length × k seconds (k = time_available)."""
+ rm, om = rs["move"], os_["move"]
+ if "t5" not in rm or "t5" not in om:
+ return 0.0
+ our_len = float(os_.get("end", 0) or 0) - float(os_.get("start", 0) or 0)
+ want5 = _frac(rs, rm["t5"])
+ want95 = min(1.0, want5 + (rm["t95"] - rm["t5"]) * k / our_len) if our_len > 0 else _frac(rs, rm["t95"])
+ return abs(want5 - _frac(os_, om["t5"])) + abs(want95 - _frac(os_, om["t95"]))
+
+
+def camera_pair(rs: dict, os_: dict) -> tuple[float, dict, list[dict]]:
+ rm, om = rs["move"], os_["move"]
+ jac = kind_similarity(rm, om)
+ where = f"{os_['id']} ↔ ref #{rs['id']}"
+ detail, findings, cost = {"ref": rm["kind"], "ours": om["kind"], "kind_match": round(jac, 2)}, [], (1 - jac) * 1.5
+ if jac < 0.6 and set(rm["kind"]) != set(om["kind"]): # say it only when the kinds a person reads differ
+ amount = f" ({_amount(rm['axis'], rm['amount'][rm['axis']])})" if "axis" in rm else ""
+ findings.append(_finding("camera", where, "major" if jac < 0.25 else "minor",
+ f"the reference camera {_does(rm['kind'])}{amount}; ours {_does(om['kind'])}"))
+ if "progress" in rm and "progress" in om and rm["axis"] != om["axis"]:
+ cost += 1.0 # the main moves are on different axes: their timing and easing are not comparable (the kind finding says it)
+ elif "progress" in rm and "progress" in om and (rm.get("snap") or om.get("snap")) and rm.get("snap") != om.get("snap"):
+ cost += 1.0
+ snapped, eased = (om, rm) if om.get("snap") else (rm, om)
+ findings.append(_finding("camera", where, "major", f"{'ours' if snapped is om else 'the reference'} jumps in one frame where "
+ f"{'the reference' if snapped is om else 'ours'} moves over {eased['duration']:.2f}s ({_ease_name(eased)})"))
+ elif "progress" in rm and "progress" in om:
+ e = float(np.sqrt(np.mean((np.asarray(rm["progress"]) - np.asarray(om["progress"])) ** 2)))
+ ax = rm["axis"]
+ dur_r, dur_o = rm.get("span90", rm["duration"]), om.get("span90", om["duration"]) # the 5–95 % travel time
+ k = time_available(rs, os_)
+ dur = math.log2(max(dur_o, 1e-3) / max(dur_r * k, 1e-3))
+ amt = math.log2(max(abs(om["amount"][ax]), 1e-3) / max(abs(rm["amount"][ax]), 1e-3))
+ place = placement_gap(rs, os_, k)
+ cost += e / 0.15 + abs(dur) / 1.5 + abs(amt) / 1.5 + place / 0.4
+ if place > 0.3:
+ fr = lambda s_, m_: f"{_frac(s_, m_['t5']):.0%}–{_frac(s_, m_['t95']):.0%}"
+ findings.append(_finding("camera", where, "major" if place > 0.6 else "minor",
+ f"the move happens at another point of the shot: {fr(os_, om)} of ours vs {fr(rs, rm)} of the reference's"
+ f"{' (its pace kept in this shorter shot)' if k < 0.99 else ''}"))
+ detail.update({"placement": round(place, 3), "ease_rmse": round(e, 3), "duration_log2": round(dur, 2), "amount_log2": round(amt, 2),
+ "ref_ease": _ease_name(rm), "ours_ease": _ease_name(om), "ref_bezier": (rm.get("ease") or {}).get("bezier")})
+ if e > 0.08:
+ same = _ease_name(om) == _ease_name(rm)
+ what = (f"both read as {_ease_name(rm)} but the curves still differ by {e:.2f}" if same
+ else f"ours ≈ {_ease_name(om)}, reference ≈ {_ease_name(rm)}")
+ re_ = rm.get("ease") or {}
+ over = f", overshoot {re_['overshoot']:.0%}" if re_.get("overshoot", 0) > 0.02 else ""
+ use = f" — use cubic-bezier({', '.join(map(str, re_['bezier']))}){over}" if re_.get("bezier") else ""
+ findings.append(_finding("camera", where, "major" if e > 0.15 else "minor", f"easing differs: {what}{use}"))
+ if abs(dur) > 0.5:
+ findings.append(_finding("camera", where, "major" if abs(dur) > 1 else "minor",
+ f"the move takes {dur_o:.2f}s vs {dur_r * k:.2f}s in the reference"
+ f"{f' (its {dur_r:.2f}s scaled to this shorter shot)' if k < 0.99 else ''} ({2 ** dur:.1f}× {'slower' if dur > 0 else 'faster'})"))
+ if abs(amt) > 0.6:
+ findings.append(_finding("camera", where, "major" if abs(amt) > 1.2 else "minor",
+ f"the move goes {_amount(ax, om['amount'][ax])} vs {_amount(ax, rm['amount'][ax])} in the reference"))
+ elif "progress" in rm and "progress" not in om:
+ cost += 1.0
+ return _score(cost, 1.5), detail, findings
+
+
+def look_pair(rs: dict, os_: dict) -> tuple[float, dict, list[dict]]:
+ wL, wa, wb = look_.wasserstein(np.asarray(rs["look"]["hist"]), np.asarray(os_["look"]["hist"]))
+ dL, db = os_["look"]["L"] - rs["look"]["L"], os_["look"]["b"] - rs["look"]["b"]
+ where, findings = f"{os_['id']} ↔ ref #{rs['id']}", []
+ if wL > 10:
+ findings.append(_finding("look", where, "major" if wL > 20 else "minor", f"{'brighter' if dL > 0 else 'darker'} than the reference (mean L {os_['look']['L']:.0f} vs {rs['look']['L']:.0f}, EMD {wL:.1f})"))
+ if abs(db) > 8:
+ findings.append(_finding("look", where, "minor", f"{'warmer' if db > 0 else 'cooler'} than the reference (Lab b {os_['look']['b']:+.0f} vs {rs['look']['b']:+.0f})"))
+ return _score(wL / 12 + (wa + wb) / 10, 1.0), {"emd_L": round(wL, 2), "emd_a": round(wa, 2), "emd_b": round(wb, 2)}, findings
+
+
+def cadence_finding(ref: dict, ours: dict) -> tuple[float, list[dict]]:
+ """Drawings per second while things move: animating on ones vs. twos changes the whole feel of 2D motion."""
+ r, o = ref.get("cadence", {}), ours.get("cadence", {})
+ if "frames_per_drawing" not in r or "frames_per_drawing" not in o:
+ return 0.0, []
+ gap = abs(math.log2(o["frames_per_drawing"] / r["frames_per_drawing"]))
+ if gap < 0.25:
+ return gap, []
+ advice = (f"hold drawings longer: about {r['frames_per_drawing']:.1f} frames per drawing" if r["frames_per_drawing"] > o["frames_per_drawing"]
+ else "draw new frames more often")
+ return gap, [_finding("rhythm", "whole film", "major" if gap > 0.5 else "minor",
+ f"the reference animates {r['label']} (~{r['drawings_per_second']:.0f} new drawings/s while things move); "
+ f"ours {o['label']} (~{o['drawings_per_second']:.0f}/s) — {advice}")]
+
+
+def rhythm_component(ref: dict, ours: dict) -> tuple[dict, list[dict]]:
+ r, o = ref["rhythm"], ours["rhythm"]
+ cad_cost, findings = cadence_finding(ref, ours)
+ if "on_beat_ratio" not in r or "on_beat_ratio" not in o:
+ if findings:
+ return {"score": _score(cad_cost, 1.5), "note": "cadence only (no beats or no cuts on one side)"}, findings
+ return {"score": None, "note": "no beats or no cuts on one side"}, []
+ cost = cad_cost
+ d_on = o["on_beat_ratio"] - r["on_beat_ratio"]
+ cost += abs(d_on) / 0.3
+ if d_on < -0.25:
+ findings.append(_finding("rhythm", "cuts", "major", f"the reference cuts on the beat {r['on_beat_ratio']:.0%} of the time (±1 frame); ours {o['on_beat_ratio']:.0%}"))
+ if r["phase_R"] > 0.5: # the reference has a consistent place in the beat where it cuts
+ dphi = abs(((o["phase_mean"] - r["phase_mean"]) + 0.5) % 1.0 - 0.5)
+ cost += dphi * r["phase_R"] / 0.15
+ if dphi > 0.15:
+ findings.append(_finding("rhythm", "cuts", "minor", f"the reference cuts consistently at {r['phase_mean']:.2f} of the beat (R={r['phase_R']:.2f}); ours at {o['phase_mean']:.2f}"))
+ dens = math.log2(max(o["cuts_per_beat"], 1e-3) / max(r["cuts_per_beat"], 1e-3))
+ cost += abs(dens) / 1.0
+ if abs(dens) > 0.6:
+ findings.append(_finding("rhythm", "cuts", "major" if abs(dens) > 1 else "minor",
+ f"{'more' if dens > 0 else 'fewer'} cuts per beat than the reference ({o['cuts_per_beat']:.2f} vs {r['cuts_per_beat']:.2f})"))
+ return {"score": _score(cost, 1.5), "ref": {k: r[k] for k in ("on_beat_ratio", "phase_mean", "phase_R", "cuts_per_beat")},
+ "ours": {k: o[k] for k in ("on_beat_ratio", "phase_mean", "phase_R", "cuts_per_beat")}}, findings
+
+
+def film_palette(fp: dict) -> np.ndarray:
+ """The whole stretch's Lab histogram, each shot weighted by how long it is on screen."""
+ h = np.zeros((3, look_.BINS))
+ for s in fp["shots"]:
+ on = max(0.0, min(s["end"], fp["end"]) - max(s["start"], fp["start"]))
+ h += np.asarray(s["look"]["hist"]) * on
+ return look_.normalise(h)
+
+
+def palette_component(ref: dict, ours: dict) -> tuple[dict, list[dict]]:
+ if not ref["shots"] or not ours["shots"]:
+ return {"score": None}, []
+ pr, po = film_palette(ref), film_palette(ours)
+ wl, wa, wb = look_.wasserstein(pr, po)
+ centre = look_.mean
+ dL, da, db = (centre(po, c) - centre(pr, c) for c in range(3))
+ findings = []
+ if wl > 8:
+ findings.append(_finding("palette", "whole film", "major" if wl > 15 else "minor",
+ f"overall {'brighter' if dL > 0 else 'darker'} than the reference (mean L {centre(po, 0):.0f} vs {centre(pr, 0):.0f}, EMD {wl:.1f})"))
+ if wa + wb > 10:
+ hue = ("warmer" if db > 0 else "cooler") if abs(db) >= abs(da) else ("redder" if da > 0 else "greener")
+ findings.append(_finding("palette", "whole film", "major" if wa + wb > 18 else "minor",
+ f"overall {hue} than the reference (Lab a {centre(po, 1):+.0f} vs {centre(pr, 1):+.0f}, b {centre(po, 2):+.0f} vs {centre(pr, 2):+.0f})"))
+ return {"score": _score(wl / 12 + (wa + wb) / 10, 1.0), "emd_L": round(wl, 2), "emd_a": round(wa, 2), "emd_b": round(wb, 2)}, findings
+
+
+@dataclass(frozen=True)
+class PaceFeature:
+ """One number describing how busy a film is: its raw value, how it is compared (a compressed scale, so that 2 vs 4
+ cuts counts like 4 vs 8), how big a gap is worth a finding, and how to print it."""
+ name: str
+ raw: Callable[[dict], float]
+ scale: Callable[[float], float]
+ limit: float
+ fmt: str
+
+
+def _cuts_per_10s(fp: dict) -> float:
+ return len(fp["cuts"]) / max(1e-6, fp["end"] - fp["start"]) * 10
+
+
+def _moving_share(fp: dict) -> float:
+ """Share of shots where the camera visibly moves (≥ a quarter of their frames above the dead zone). A shot's total
+ travel would not do: in a long shot, measurement noise and line boil add up to a "move" no viewer sees."""
+ if not fp["shots"]:
+ return 0.0
+ c = fp["series"]["camera"]
+ v = np.sqrt(sum(np.asarray(c[k], float) ** 2 for k in ("dx", "dy", "dz", "dr"))) * fp["fps"]
+ t = fp["start"] + np.arange(len(v)) / fp["fps"]
+ seen = [float(np.mean(v[(t >= s["start"]) & (t < s["end"])] > tension.DEADZONE["camera"])) for s in fp["shots"]
+ if np.any((t >= s["start"]) & (t < s["end"]))]
+ return float(np.mean([x >= 0.25 for x in seen])) if seen else 0.0
+
+
+def _camera_speed(fp: dict) -> float:
+ """Typical *visible* camera speed: speeds under the dead zone a viewer does not see are 0. Without it this measured
+ each source's noise floor (compression, line boil) — a signature of the file, not of its style."""
+ c = fp["series"]["camera"]
+ v = np.sqrt(sum(np.asarray(c[k], float) ** 2 for k in ("dx", "dy", "dz", "dr"))) * fp["fps"]
+ return float(np.median(np.maximum(0.0, v - tension.DEADZONE["camera"])))
+
+
+PACE = (
+ PaceFeature("cuts per 10 s", _cuts_per_10s, np.log1p, 0.4, "{:.1f}"),
+ PaceFeature("share of shots with a moving camera", _moving_share, float, 0.3, "{:.0%}"),
+ PaceFeature("frames per drawing", lambda fp: (fp.get("cadence") or {}).get("frames_per_drawing") or 1.0, np.log2, 0.35, "{:.1f}"),
+ PaceFeature("typical camera speed (frame widths/s)", _camera_speed, lambda v: np.log1p(v * 50), 0.5, "{:.3f}"),
+ PaceFeature("motion inside the frame", lambda fp: float(np.mean(fp["series"]["local"])), lambda v: np.log1p(v * 2000), 0.5, "{:.4f}"),
+)
+
+
+def pace_vector(fp: dict) -> np.ndarray:
+ return np.array([f.scale(f.raw(fp)) for f in PACE], float)
+
+
+def pace_component(ref: dict, ours: dict) -> tuple[dict, list[dict]]:
+ """How busy the film is: cut rate, how much the camera moves, cadence, how much moves inside the frame."""
+ r, o = pace_vector(ref), pace_vector(ours)
+ gap = np.abs(o - r)
+ findings = []
+ for f, g, ov, rv in zip(PACE, gap, o, r):
+ if g > f.limit:
+ findings.append(_finding("pace", "whole film", "major" if g > 2 * f.limit else "minor",
+ f"{'more' if ov > rv else 'less'} {f.name} than the reference "
+ f"({f.fmt.format(f.raw(ours))} vs {f.fmt.format(f.raw(ref))})"))
+ return {"score": _score(float(gap.sum()), 1.5), "ref": [round(float(x), 3) for x in r], "ours": [round(float(x), 3) for x in o]}, findings
+
+
+def frames_component(ref: dict, ours: dict) -> dict:
+ a, b = np.asarray(ref["descriptors"]["data"]), np.asarray(ours["descriptors"]["data"])
+ if not len(a) or not len(b):
+ return {"score": None}
+ cost, _ = dtw(a, b, band=0.25, metric="cosine")
+ return {"score": _score(cost, 0.25), "dtw_cost": round(cost, 4)}
+
+
+# ---------- the whole comparison ----------
+def style_distance(ref: dict, ours: dict, pairs: list[dict] | None = None, ref_window: tuple[float, float] | None = None) -> dict:
+ """pairs: [{"id": our shot id, "ref_shot": reference shot number}, …] (plan.json shots). Without a window, the
+ reference is cut to the span of the shots the plan maps to (a 30 s film is compared to the 30 s it clones)."""
+ by_ref = {s["id"]: s for s in ref["shots"]}
+ if ref_window is None and pairs:
+ mapped = [by_ref[p["ref_shot"]] for p in pairs if p.get("ref_shot") in by_ref]
+ if mapped:
+ ref_window = (min(s["start"] for s in mapped), max(s["end"] for s in mapped))
+ R = window(ref, *ref_window) if ref_window else ref
+ comps, findings = {}, []
+ comps["tension"], f, mapping = tension_component(R, ours)
+ findings += f
+ comps["peaks"], f = peaks_component(R, ours, mapping)
+ findings += f
+ comps["rhythm"], f = rhythm_component(R, ours)
+ findings += f
+ comps["frames"] = frames_component(R, ours)
+ comps["palette"], f = palette_component(R, ours)
+ findings += f
+ comps["pace"], f = pace_component(R, ours)
+ findings += f
+ by_ours = {s["id"]: s for s in ours["shots"]}
+ from .fingerprint import reference_for
+ answers = reference_for(ref, [(p.get("id"), p.get("ref_shot"),
+ (by_ours[p["id"]]["end"] - by_ours[p["id"]]["start"]) if p.get("id") in by_ours else 1.0) for p in pairs or []])
+ shots, cam_scores, look_scores = [], [], []
+ for p in pairs or []:
+ rs, os_ = answers.get(p.get("id")), by_ours.get(p.get("id"))
+ if not rs or not os_:
+ continue
+ cs, cd, cf = camera_pair(rs, os_)
+ ls, ld, lf = look_pair(rs, os_)
+ cam_scores.append(cs)
+ look_scores.append(ls)
+ findings += cf + lf
+ shots.append({"id": os_["id"], "ref_shot": rs["id"], "camera": {"score": cs, **cd}, "look": {"score": ls, **ld}})
+ comps["camera"] = {"score": round(float(np.mean(cam_scores)), 1) if cam_scores else None, "pairs": len(cam_scores)}
+ comps["look"] = {"score": round(float(np.mean(look_scores)), 1) if look_scores else None, "pairs": len(look_scores)}
+ def mix(weights):
+ used = {k: w for k, w in weights.items() if comps.get(k, {}).get("score") is not None}
+ return round(sum(w * comps[k]["score"] for k, w in used.items()) / sum(used.values()), 1) if used else None
+ style, structure = mix(STYLE), mix(STRUCTURE)
+ parts = {k: v for k, v in (("style", style), ("structure", structure)) if v is not None}
+ overall = round(sum(OVERALL[k] * v for k, v in parts.items()) / sum(OVERALL[k] for k in parts), 1) if parts else None
+ findings.sort(key=lambda x: (x["severity"] != "major", x["component"]))
+ return {"version": 2, "ref_window": [round(x, 3) for x in ref_window] if ref_window else None,
+ "overall": overall, "style": style, "structure": structure, "components": comps, "shots": shots, "findings": findings}
diff --git a/.claude/skills/video-clone/scripts/perception/fingerprint.py b/.claude/skills/video-clone/scripts/perception/fingerprint.py
new file mode 100644
index 0000000..91e827d
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/fingerprint.py
@@ -0,0 +1,299 @@
+"""Style Fingerprint: every measurable signal of one film on one frame clock.
+
+ fp = extract("analysis/proxy.mp4", shots=report["shots"], audio="analysis/audio.wav", beats=report["audio"]["beats"])
+
+One streaming pass over the frames computes camera motion, local motion, frame difference, the Lab colour of each frame
+and a small descriptor; then per shot the camera trajectory is integrated and its move described (curves.py); then the
+sound is folded in and the tension curve and its peaks are computed (tension.py), and the cut/beat phase (rhythm.py).
+All times in the output are seconds on the video's own timeline.
+"""
+from __future__ import annotations
+
+import math
+import os
+from typing import Iterable
+
+import cv2
+import numpy as np
+from scipy.ndimage import gaussian_filter1d
+
+from . import camera, curves, look, rhythm, tension
+from .video import extract_audio, frame_size, frames, probe, static_mask
+
+VERSION = 15
+DESC_FPS = 2.0 # frame descriptors per second
+DESC_GRID = (8, 4) # descriptor = this grid of Lab means → 96 numbers
+THUMB_W = 96 # colour, difference and descriptors are measured on a thumbnail this wide
+
+
+def _spans(shots: Iterable | None) -> list[dict] | None:
+ """Accepts [[a, b], …] (analyze.py), [{"id", "start_s", "end_s"}, …] (plan.json) or [{"start", "end"}, …]."""
+ if shots is None:
+ return None
+ out = []
+ for k, s in enumerate(shots):
+ if isinstance(s, dict):
+ a, b = s.get("start_s", s.get("start")), s.get("end_s", s.get("end"))
+ out.append({"id": s.get("id", k + 1), "start": float(a), "end": float(b)})
+ else:
+ out.append({"id": k + 1, "start": float(s[0]), "end": float(s[1])})
+ return out
+
+
+HOLD_DIFF = 0.004 # mean abs difference (0–1) below which a frame repeats the previous drawing
+MAX_HOLD = 3 # a longer still stretch is the scene standing still, not a held drawing
+CUT_SNAP = 3 # frames: a given cut this close to a detected one is that cut
+
+
+def held_frames(diff: np.ndarray, cut_frames: list[int]) -> np.ndarray:
+ """Frames that repeat the previous drawing inside motion — limited animation (on twos, threes) or a duplicated frame:
+ runs of at most MAX_HOLD still frames with a *real* change on both sides. The first frame (nothing before it) and a
+ cut (a change, but not motion) do not count as that change: a camera that rests three frames after a cut and then
+ moves is resting, and spreading its first step back over the rest would start the move early."""
+ still = diff < HOLD_DIFF
+ moved = ~still
+ moved[0] = False
+ cuts = set(cut_frames)
+ for f in cuts:
+ moved[f] = False
+ hold, n, k = np.zeros_like(still), len(diff), 1
+ while k < n:
+ if not still[k] or k in cuts:
+ k += 1
+ continue
+ e = k
+ while e + 1 < n and still[e + 1] and e + 1 not in cuts:
+ e += 1
+ if e - k + 1 <= MAX_HOLD and moved[k - 1] and e + 1 < n and moved[e + 1]:
+ hold[k:e + 1] = True
+ k = e + 1
+ return hold
+
+
+def spread_over_holds(delta: np.ndarray, hold: np.ndarray) -> np.ndarray:
+ """Per-frame motion with each held run sharing the step that ends it (the trajectory itself is unchanged)."""
+ out, n, k = delta.copy(), len(delta), 1
+ while k < n:
+ if not hold[k]:
+ k += 1
+ continue
+ e = k
+ while e + 1 < n and hold[e + 1]:
+ e += 1
+ if e + 1 < n:
+ out[k:e + 2] = delta[k:e + 2].sum() / (e + 2 - k)
+ k = e + 2
+ return out
+
+
+def cadence(diff: np.ndarray, hold: np.ndarray, cut_frames: list[int], fps: float) -> dict:
+ """How many new drawings per second while things move: 'on ones' (every frame new), 'on twos' (each drawing held
+ for two frames) … A strong style trait of 2D animation that no single frame shows."""
+ moving = gaussian_filter1d(diff, 2.0) > 0.008
+ moving[list(cut_frames)] = False
+ if moving.sum() < fps / 2:
+ return {"moving_frames": int(moving.sum())}
+ ratio = float(hold[moving].mean())
+ per = 1 / max(1e-6, 1 - ratio) # frames each drawing stays on screen, on average
+ label = "on ones" if per < 1.25 else "mixed ones and twos" if per < 1.75 else "on twos" if per < 2.5 else "on threes"
+ return {"moving_frames": int(moving.sum()), "hold_ratio": round(ratio, 3), "frames_per_drawing": round(per, 2),
+ "drawings_per_second": round(fps / per, 1), "label": label}
+
+
+def extract(video: str, *, shots: Iterable | None = None, audio: str | None = None, beats: list[float] | None = None,
+ fps: float = 24.0, width: int = 320, start: float = 0.0, end: float | None = None) -> dict:
+ info = probe(video)
+ end = info.duration if end is None else min(end, info.duration)
+ spans = _spans(shots)
+ if spans is not None:
+ spans = [s for s in spans if s["end"] > start and s["start"] < end]
+ # frame index where each given shot starts; cuts are detected anyway and the given ones snap to them (a plan's
+ # times can be a frame off the real cut, and a step measured across a cut is a huge fake camera move)
+ given_cuts = {max(0, round((s["start"] - start) * fps)) for s in (spans or [])} - {0}
+
+ overlay = static_mask(video, frame_size(info, width), start, end) # phone UI, watermark, letterbox: never tracked
+
+ cols = {k: [] for k in ("dx", "dy", "dz", "dr", "local", "ok", "diff", "L", "a", "b")}
+ desc, detected, frame_hists = [], [], []
+ prev_gray = prev_hist = prev_thumb = None
+ desc_every = max(1, round(fps / DESC_FPS))
+ n = 0
+ for i, bgr in enumerate(frames(video, fps=fps, width=width, start=start, end=end)):
+ n = i + 1
+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
+ th = cv2.resize(bgr, (THUMB_W, round(THUMB_W * bgr.shape[0] / bgr.shape[1])), interpolation=cv2.INTER_AREA)
+ th_gray = cv2.cvtColor(th, cv2.COLOR_BGR2GRAY)
+ hist = camera.hsv_hist(th)
+ cut = prev_gray is not None and camera.looks_like_cut(prev_hist, hist, prev_thumb, th_gray)
+ if cut:
+ detected.append(i)
+ step = camera.estimate(prev_gray, gray, overlay) if prev_gray is not None and not cut and i not in given_cuts else camera.Step()
+ for k in ("dx", "dy", "dz", "dr", "local"):
+ cols[k].append(getattr(step, k))
+ cols["ok"].append(int(step.ok))
+ cols["diff"].append(float(np.mean(cv2.absdiff(prev_thumb, th_gray))) / 255 if prev_thumb is not None else 0.0)
+ lab = look.lab(th)
+ for c, k in enumerate("Lab"):
+ cols[k].append(float(lab[..., c].mean()))
+ frame_hists.append(look.hist(lab))
+ if i % desc_every == 0:
+ g = cv2.resize(lab, DESC_GRID, interpolation=cv2.INTER_AREA) / np.array([100, 128, 128], np.float32)
+ desc.append(g.ravel())
+ prev_gray, prev_hist, prev_thumb = gray, hist, th_gray
+ if n < 2:
+ raise ValueError(f"no frames decoded from {video}")
+
+ if spans is None:
+ cut_frames = detected
+ else:
+ snap = lambda g: min((d for d in detected if abs(d - g) <= CUT_SNAP), key=lambda d: abs(d - g), default=g)
+ cut_frames = sorted({snap(g) for g in given_cuts})
+ for k in ("dx", "dy", "dz", "dr", "local"): # no motion across any cut, given or found
+ for f in set(detected) | set(cut_frames):
+ cols[k][f] = 0.0
+ S = {k: np.asarray(v, float) for k, v in cols.items()}
+ t = start + np.arange(n) / fps
+ hold = held_frames(S["diff"], sorted(set(detected) | set(cut_frames)))
+ for k in ("dx", "dy", "dz", "dr", "local"): # a held drawing moves nothing, the next one moves for both: share it out
+ S[k] = spread_over_holds(S[k], hold)
+
+ # ---------- shots: integrate the camera, describe the move ----------
+ bounds = [0, *cut_frames, n]
+
+ def shot_id(f0: int, f1: int, k: int):
+ """The given shot that contains the middle of this frame range (keeps plan ids like "s3"), else its number."""
+ mid = start + (f0 + f1) / 2 / fps
+ return next((s["id"] for s in spans or [] if s["start"] <= mid < s["end"]), k + 1)
+
+ shot_out = []
+ for k, (f0, f1) in enumerate(zip(bounds, bounds[1:])):
+ if f1 - f0 < 2:
+ continue
+ sl = slice(f0, f1)
+ traj = {"x": S["dx"][sl], "y": S["dy"][sl], "z": S["dz"][sl], "r": S["dr"][sl]}
+ traj = {a: np.cumsum(np.r_[0.0, v[1:]]) for a, v in traj.items()} # first frame of a shot has no motion into it
+ h = look.normalise(np.sum(frame_hists[f0:f1], axis=0))
+ shot_out.append({
+ "id": shot_id(f0, f1, k), "start": round(float(t[f0]), 3), "end": round(float(start + f1 / fps), 3),
+ "move": curves.describe_shot(t[sl], traj),
+ "local_motion": round(float(S["local"][sl].mean()), 5),
+ "tracked": round(float(S["ok"][sl][1:].mean()) if f1 - f0 > 1 else 0.0, 3),
+ "look": {"L": round(float(S["L"][sl].mean()), 2), "a": round(float(S["a"][sl].mean()), 2), "b": round(float(S["b"][sl].mean()), 2),
+ "hist": np.round(h, 4).tolist()},
+ })
+
+ # ---------- sound, tension, rhythm ----------
+ tmp = None
+ if audio is None and info.has_audio:
+ audio = tmp = extract_audio(video)
+ try:
+ feats: dict[str, np.ndarray] = {}
+ if audio and os.path.exists(audio):
+ feats.update(tension.audio_features(audio, n, fps, t0=start))
+ if beats is None:
+ beats = tension.beats(audio)
+ finally:
+ if tmp:
+ os.remove(tmp)
+ speed = np.sqrt(S["dx"] ** 2 + S["dy"] ** 2 + S["dz"] ** 2 + S["dr"] ** 2) * fps
+ feats.update({"camera": speed, "local": S["local"] * fps, "diff": S["diff"],
+ "cuts": tension.cut_density(cut_frames, n, fps), "flash": tension.flashes(S["L"] / 100, fps)})
+ T = tension.curve(feats, fps)
+ beats_in = [b for b in (beats or []) if start <= b <= end]
+ peaks = tension.describe_peaks(T, fps, [b - start for b in beats_in])
+ for p in peaks:
+ p["t"] = round(p["t"] + start, 3)
+ cut_times = [round(start + f / fps, 3) for f in cut_frames]
+
+ r5 = lambda a: [round(float(x), 5) for x in a]
+ return {
+ "version": VERSION, "video": os.path.basename(video), "fps": fps, "start": round(start, 3), "end": round(float(start + n / fps), 3),
+ "frames": n, "size": [info.width, info.height], "static_overlay": round(float((overlay == 0).mean()), 3) if overlay is not None else 0.0,
+ "series": {"camera": {k: r5(S[k]) for k in ("dx", "dy", "dz", "dr")}, "tracked": S["ok"].astype(int).tolist(),
+ "local": r5(S["local"]), "diff": r5(S["diff"]), "lab": [r5(S["L"] / 100), r5(S["a"] / 128), r5(S["b"] / 128)],
+ "tension": r5(T), "features": sorted(k for k in feats if np.ptp(feats[k]) > 1e-9)},
+ "cuts": cut_times, "beats": [round(float(b), 3) for b in beats_in],
+ "shots": shot_out, "peaks": peaks, "rhythm": rhythm.cut_phase(cut_times, beats_in, fps), "cadence": cadence(S["diff"], hold, cut_frames, fps),
+ "descriptors": {"fps": round(fps / desc_every, 3), "grid": list(DESC_GRID), "data": [[round(float(x), 3) for x in d] for d in desc]},
+ }
+
+
+def ref_shot_id(v) -> int | None:
+ """A plan's ref_shot as the reference shot number: 6, "6" and "#6" all mean shot 6 (plans are written by agents)."""
+ if isinstance(v, bool):
+ return None
+ if isinstance(v, int):
+ return v
+ if isinstance(v, float) and v.is_integer():
+ return int(v)
+ if isinstance(v, str) and v.strip().lstrip("#").isdigit():
+ return int(v.strip().lstrip("#"))
+ return None
+
+
+def describe_span(fp: dict, a: float, b: float, sid=None) -> dict:
+ """A stretch of a fingerprint described like a shot: its camera move from the stored per-frame camera."""
+ f0 = max(0, int(round((a - fp["start"]) * fp["fps"])))
+ f1 = min(fp["frames"], int(round((b - fp["start"]) * fp["fps"])))
+ c = {k: np.asarray(v[f0:f1], float) for k, v in fp["series"]["camera"].items()}
+ t = fp["start"] + np.arange(f0, f1) / fp["fps"]
+ traj = {ax: np.cumsum(np.r_[0.0, c[k][1:]]) for ax, k in (("x", "dx"), ("y", "dy"), ("z", "dz"), ("r", "dr"))} if f1 - f0 > 1 else None
+ move = curves.describe_shot(t, traj) if traj else {"kind": ["static"], "amount": {x: 0.0 for x in curves.AXES}}
+ return {"id": sid, "start": round(a, 3), "end": round(b, 3), "move": move}
+
+
+def reference_for(ref_fp: dict, ours: list[tuple]) -> dict:
+ """Our shot id → the reference shot it answers, from [(our id, ref shot id, our duration), …] in plan order.
+
+ A plan often cuts one long reference take into several shots (a real run mapped four shots to one 12 s take, and
+ every one of them was then given — and compared against — the whole take). Consecutive shots that share a
+ reference shot each get their share of it, in order and in proportion to their length, re-described from the
+ reference's per-frame camera; the look of the whole shot is kept. Used by the transfer, the comparison, the
+ prediction and the optimizer alike, so they always agree on what a shot answers."""
+ by = {s["id"]: s for s in ref_fp["shots"]}
+ out, i = {}, 0
+ while i < len(ours):
+ j = i
+ while j + 1 < len(ours) and ours[j + 1][1] is not None and ours[j + 1][1] == ours[i][1]:
+ j += 1
+ rs = by.get(ours[i][1])
+ run = ours[i:j + 1]
+ if rs is None:
+ pass
+ elif len(run) == 1:
+ out[run[0][0]] = rs
+ else:
+ total = sum(max(1e-6, float(d or 0)) for _, _, d in run)
+ a = rs["start"]
+ for oid, _, d in run:
+ b = a + (rs["end"] - rs["start"]) * max(1e-6, float(d or 0)) / total
+ part = describe_span(ref_fp, a, b, rs["id"])
+ out[oid] = {**rs, **part, "part_of": [rs["start"], rs["end"]]}
+ a = b
+ i = j + 1
+ return out
+
+
+def times(fp: dict) -> np.ndarray:
+ return fp["start"] + np.arange(fp["frames"]) / fp["fps"]
+
+
+def window(fp: dict, a: float, b: float) -> dict:
+ """The part of a fingerprint between a and b seconds (shots, cuts, beats and peaks inside it; series cut to it)."""
+ f0 = max(0, math.floor((a - fp["start"]) * fp["fps"]))
+ f1 = min(fp["frames"], math.ceil((b - fp["start"]) * fp["fps"]))
+ s = fp["series"]
+ cut = lambda v: v[f0:f1]
+ d = fp["descriptors"]
+ d0, d1 = int(f0 / fp["fps"] * d["fps"]), int(math.ceil(f1 / fp["fps"] * d["fps"]))
+ inside = lambda x: a <= x <= b
+ new_start = fp["start"] + f0 / fp["fps"]
+ cut_f = [round((c - new_start) * fp["fps"]) for c in fp["cuts"] if inside(c) and 0 < round((c - new_start) * fp["fps"]) < f1 - f0]
+ diff = np.asarray(cut(s["diff"]), float)
+ return {**fp, "cadence": cadence(diff, held_frames(diff, cut_f), cut_f, fp["fps"]) if len(diff) else {}, "start": round(fp["start"] + f0 / fp["fps"], 3), "end": round(fp["start"] + f1 / fp["fps"], 3), "frames": f1 - f0,
+ "series": {**s, "camera": {k: cut(v) for k, v in s["camera"].items()}, "tracked": cut(s["tracked"]), "local": cut(s["local"]),
+ "diff": cut(s["diff"]), "lab": [cut(v) for v in s["lab"]], "tension": cut(s["tension"])},
+ "cuts": [c for c in fp["cuts"] if inside(c)], "beats": [x for x in fp["beats"] if inside(x)],
+ "shots": [x for x in fp["shots"] if x["end"] > a and x["start"] < b], "peaks": [p for p in fp["peaks"] if inside(p["t"])],
+ "rhythm": rhythm.cut_phase([c for c in fp["cuts"] if inside(c)], [x for x in fp["beats"] if inside(x)], fp["fps"]),
+ "descriptors": {**d, "data": d["data"][d0:d1]}}
diff --git a/.claude/skills/video-clone/scripts/perception/look.py b/.claude/skills/video-clone/scripts/perception/look.py
new file mode 100644
index 0000000..e130b6d
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/look.py
@@ -0,0 +1,49 @@
+"""Colour: per-frame CIELAB means (the colour arc of the film) and per-shot Lab histograms.
+
+Histograms are compared with the 1-D Wasserstein (earth mover's) distance per channel: unlike bin-by-bin distances it
+knows that a slightly warmer orange is close to orange, so a grade that drifted a little scores a little worse.
+"""
+from __future__ import annotations
+
+import cv2
+import numpy as np
+
+BINS = 32
+
+
+def lab(bgr: np.ndarray) -> np.ndarray:
+ """float Lab, L in 0–100, a and b in −128…127 (OpenCV's 8-bit Lab rescaled)."""
+ x = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB).astype(np.float32)
+ x[..., 0] *= 100 / 255
+ x[..., 1:] -= 128
+ return x
+
+
+RANGES = ((0.0, 100.0), (-128.0, 128.0), (-128.0, 128.0))
+
+
+def hist(lab_px: np.ndarray) -> np.ndarray:
+ """(3, BINS) marginal histograms, each summing to 1."""
+ px = lab_px.reshape(-1, 3)
+ return np.stack([np.histogram(px[:, c], BINS, RANGES[c])[0] for c in range(3)]).astype(float)
+
+
+def normalise(h: np.ndarray) -> np.ndarray:
+ s = h.sum(axis=1, keepdims=True)
+ return np.divide(h, s, out=np.zeros_like(h), where=s > 0)
+
+
+def wasserstein(h1: np.ndarray, h2: np.ndarray) -> list[float]:
+ """W1 per channel, in that channel's units (L: lightness points, a/b: colour points)."""
+ out = []
+ for c in range(3):
+ lo, hi = RANGES[c]
+ out.append(float(np.abs(np.cumsum(h1[c]) - np.cumsum(h2[c])).sum() * (hi - lo) / BINS))
+ return out
+
+
+def mean(h: np.ndarray, c: int) -> float:
+ """Mean value of channel c of a normalised histogram (bin centres weighted by the histogram)."""
+ lo, hi = RANGES[c]
+ centres = lo + (np.arange(BINS) + 0.5) * (hi - lo) / BINS
+ return float(np.sum(h[c] * centres))
diff --git a/.claude/skills/video-clone/scripts/perception/plot.py b/.claude/skills/video-clone/scripts/perception/plot.py
new file mode 100644
index 0000000..ac43070
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/plot.py
@@ -0,0 +1,85 @@
+"""Pictures of fingerprints, drawn with OpenCV (no plotting dependency): one film, or ours with the reference warped
+onto our clock by the tension DTW, so "where are we early, late, flat" is one look."""
+from __future__ import annotations
+
+import cv2
+import numpy as np
+
+from .fingerprint import times
+
+W, LANE, PAD, AXIS = 1600, 120, 46, 26
+REF, OURS, GRID, INK, BG = (40, 140, 245), (230, 190, 40), (70, 70, 70), (225, 225, 225), (24, 24, 24)
+
+
+def _lane(img, y0: int, label: str):
+ cv2.rectangle(img, (PAD, y0), (W - 12, y0 + LANE), GRID, 1)
+ cv2.putText(img, label, (PAD + 6, y0 + 16), cv2.FONT_HERSHEY_SIMPLEX, 0.45, INK, 1, cv2.LINE_AA)
+
+
+def _poly(img, y0: int, t: np.ndarray, v: np.ndarray, t0: float, t1: float, color, vmax: float | None = None):
+ if len(t) < 2:
+ return
+ vmax = vmax or (float(np.percentile(v, 99)) or 1.0)
+ x = PAD + (t - t0) / max(1e-9, t1 - t0) * (W - 12 - PAD)
+ y = y0 + LANE - 4 - np.clip(v / vmax, 0, 1) * (LANE - 24)
+ cv2.polylines(img, [np.stack([x, y], 1).astype(np.int32)], False, color, 2, cv2.LINE_AA)
+
+
+def _ticks(img, y0: int, ts, t0: float, t1: float, color, h: int):
+ for s in ts:
+ if t0 <= s <= t1:
+ x = int(PAD + (s - t0) / max(1e-9, t1 - t0) * (W - 12 - PAD))
+ cv2.line(img, (x, y0 + LANE - h), (x, y0 + LANE), color, 1)
+
+
+def _axis(img, y: int, t0: float, t1: float):
+ step = 1 if t1 - t0 <= 12 else 5 if t1 - t0 <= 90 else 15
+ for s in np.arange(np.ceil(t0 / step) * step, t1 + 1e-9, step):
+ x = int(PAD + (s - t0) / max(1e-9, t1 - t0) * (W - 12 - PAD))
+ cv2.putText(img, f"{s:.0f}s", (x - 10, y + 18), cv2.FONT_HERSHEY_SIMPLEX, 0.4, INK, 1, cv2.LINE_AA)
+
+
+def _speed(fp: dict) -> np.ndarray:
+ c = fp["series"]["camera"]
+ return np.sqrt(sum(np.asarray(c[k]) ** 2 for k in ("dx", "dy", "dz", "dr"))) * fp["fps"]
+
+
+def single(fp: dict, out: str):
+ t, t0, t1 = times(fp), fp["start"], fp["end"]
+ img = np.full((PAD + 4 * (LANE + 8) + AXIS, W, 3), BG, np.uint8)
+ lanes = [("tension (peaks marked)", np.asarray(fp["series"]["tension"]), 1.0), ("camera speed", _speed(fp), None),
+ ("local motion", np.asarray(fp["series"]["local"]), None), ("frame difference", np.asarray(fp["series"]["diff"]), None)]
+ for k, (name, v, vmax) in enumerate(lanes):
+ y0 = PAD + k * (LANE + 8)
+ _lane(img, y0, name)
+ _ticks(img, y0, fp["beats"], t0, t1, GRID, 10)
+ _ticks(img, y0, fp["cuts"], t0, t1, (120, 120, 200), LANE)
+ _poly(img, y0, t, v, t0, t1, REF, vmax)
+ for p in fp["peaks"]:
+ x = int(PAD + (p["t"] - t0) / max(1e-9, t1 - t0) * (W - 12 - PAD))
+ cv2.circle(img, (x, PAD + LANE - 4 - int(p["height"] * (LANE - 24))), 6, (60, 60, 255), 2)
+ cv2.putText(img, f"{fp['video']} {t1 - t0:.1f}s {len(fp['cuts'])} cuts {len(fp['beats'])} beats (red ticks: cuts, grey: beats)",
+ (PAD, 28), cv2.FONT_HERSHEY_SIMPLEX, 0.55, INK, 1, cv2.LINE_AA)
+ _axis(img, PAD + 4 * (LANE + 8) - 6, t0, t1)
+ cv2.imwrite(out, img)
+
+
+def overlay(ref: dict, ours: dict, mapping: list[tuple[float, float]], out: str):
+ """Reference curves warped onto our timeline through the DTW mapping (ref time → our time)."""
+ t, t0, t1 = times(ours), ours["start"], ours["end"]
+ tr = times(ref)
+ img = np.full((PAD + 2 * (LANE + 8) + AXIS, W, 3), BG, np.uint8)
+ m = np.asarray(sorted({(o, r) for r, o in mapping})) # our time → reference time
+ warp = (lambda tt: np.interp(tt, m[:, 0], m[:, 1])) if len(m) > 1 else (lambda tt: tt)
+ for k, (name, rv, ov, vmax) in enumerate([("tension", np.asarray(ref["series"]["tension"]), np.asarray(ours["series"]["tension"]), 1.0),
+ ("camera speed", _speed(ref), _speed(ours), None)]):
+ y0 = PAD + k * (LANE + 8)
+ _lane(img, y0, name)
+ _ticks(img, y0, ours["cuts"], t0, t1, (120, 120, 200), LANE)
+ vmax = vmax or float(max(np.percentile(rv, 99), np.percentile(ov, 99), 1e-6))
+ _poly(img, y0, t, np.interp(warp(t), tr, rv), t0, t1, REF, vmax)
+ _poly(img, y0, t, ov, t0, t1, OURS, vmax)
+ cv2.putText(img, "orange: reference (time-warped onto ours) cyan: ours red ticks: our cuts", (PAD, 28),
+ cv2.FONT_HERSHEY_SIMPLEX, 0.55, INK, 1, cv2.LINE_AA)
+ _axis(img, PAD + 2 * (LANE + 8) - 6, t0, t1)
+ cv2.imwrite(out, img)
diff --git a/.claude/skills/video-clone/scripts/perception/rhythm.py b/.claude/skills/video-clone/scripts/perception/rhythm.py
new file mode 100644
index 0000000..17c20e8
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/rhythm.py
@@ -0,0 +1,36 @@
+"""Where cuts land against the beat.
+
+Each cut gets a signed offset to the nearest beat (in frames: one frame early reads differently from one frame late) and
+a phase within its beat interval (0 = on the beat, 0.5 = on the "and"). The summary uses circular statistics on the
+phase: the mean direction says *where* in the beat this editor cuts, the resultant length R (0–1) says how consistently.
+"""
+from __future__ import annotations
+
+import numpy as np
+
+ON_BEAT_FRAMES = 1.0
+
+
+def cut_phase(cuts: list[float], beats: list[float], fps: float) -> dict:
+ b = np.asarray(beats, float)
+ if len(b) < 2 or not cuts:
+ return {"cuts": len(cuts), "beats": len(b)}
+ offsets, phases = [], []
+ for c in cuts:
+ nearest = b[np.argmin(np.abs(b - c))]
+ offsets.append((c - nearest) * fps)
+ k = int(np.clip(np.searchsorted(b, c, side="right") - 1, 0, len(b) - 2))
+ phases.append(((c - b[k]) / (b[k + 1] - b[k])) % 1.0)
+ off, ph = np.asarray(offsets), np.asarray(phases)
+ z = np.exp(2j * np.pi * ph).mean()
+ span = (b[-1] - b[0]) or 1.0
+ return {
+ "cuts": len(cuts), "beats": len(b),
+ "on_beat_ratio": round(float((np.abs(off) <= ON_BEAT_FRAMES).mean()), 3),
+ "mean_abs_offset_frames": round(float(np.abs(off).mean()), 2),
+ "mean_offset_frames": round(float(off.mean()), 2), # < 0: cuts tend to come early, before the beat
+ "phase_mean": round(float(np.angle(z) / (2 * np.pi)) % 1.0, 3),
+ "phase_R": round(float(abs(z)), 3),
+ "cuts_per_beat": round(len(cuts) / (span / float(np.median(np.diff(b)))), 3),
+ "offsets_frames": [round(float(x), 1) for x in off],
+ }
diff --git a/.claude/skills/video-clone/scripts/perception/tension.py b/.claude/skills/video-clone/scripts/perception/tension.py
new file mode 100644
index 0000000..893fdea
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/tension.py
@@ -0,0 +1,122 @@
+"""Tension: one curve per film that rises as it builds, dips when it holds its breath, and spikes at the hit.
+
+ tension(t) = smooth( Σ w_k · robust01(feature_k(t)) ) / Σ w_k (features that are missing drop out)
+
+Features, all on the frame clock: loudness (RMS dB) and spectral flux from the sound; camera speed, local (in-frame)
+motion and frame difference from the picture; cut density; flashes (luminance jumping above its running median).
+robust01 maps the 5th–95th percentile of each feature in *this* film to 0–1, so a quiet film and a loud one are compared
+on shape, not on mastering level — but never stretches a range smaller than what a viewer can notice (JND).
+
+A peak is then described the way an editor would: how long and steep the build is, whether there is a held breath
+(a dip right before the hit) and how deep, how many frames the hit takes to land, how long it holds and decays.
+"""
+from __future__ import annotations
+
+import numpy as np
+from scipy.ndimage import gaussian_filter1d, median_filter
+from scipy.signal import find_peaks
+
+WEIGHTS = {"loudness": 0.28, "flux": 0.20, "camera": 0.14, "local": 0.10, "diff": 0.10, "cuts": 0.10, "flash": 0.08}
+# Just-noticeable ranges: a feature that varies less than this over the whole film is not stretched to fill 0–1.
+# Without a floor, robust01 makes any wobble in a still film "the strongest motion": an optimizer found that a 1-pixel
+# shake at the hit moved the predicted climax onto its target — invisible to a viewer, decisive for the number.
+JND = {"loudness": 6.0, # dB
+ "flux": 1.0, # onset strength units
+ "camera": 0.08, # frame widths per second (≈ 150 px/s at 1080p)
+ "local": 0.03, # frame widths per second of motion inside the frame
+ "diff": 0.02, # mean absolute frame difference (0–1)
+ "cuts": 0.5, # cuts per second
+ "flash": 0.05} # luminance jump above the running median (0–1)
+# Motion below these is not seen at all (dead zone, subtracted before normalising): a ±1 px jitter is 0.025 frame
+# widths per second, a slow but visible drift ≈ 0.05. Loudness and flux have no meaningful zero, so no dead zone.
+DEADZONE = {"camera": 0.04, "local": 0.015, "diff": 0.005, "flash": 0.02}
+SMOOTH_S = 0.15
+
+
+def robust01(x: np.ndarray, jnd: float = 0.0) -> np.ndarray:
+ """5th–95th percentile → 0–1, but never stretching a range smaller than `jnd` (what a viewer can notice)."""
+ lo, hi = np.percentile(x, 5), np.percentile(x, 95)
+ span = max(hi - lo, jnd)
+ return np.clip((x - lo) / span, 0, 1) if span > 1e-9 else np.zeros_like(x, dtype=float)
+
+
+def audio_features(wav: str, n: int, fps: float, t0: float = 0.0) -> dict[str, np.ndarray]:
+ """Loudness and spectral flux resampled to the n frames at t0 + i / fps."""
+ import librosa
+ y, sr = librosa.load(wav, sr=22050, mono=True)
+ hop = 512
+ rms = librosa.feature.rms(y=y, frame_length=2048, hop_length=hop)[0]
+ flux = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop)
+ ta = librosa.frames_to_time(np.arange(len(rms)), sr=sr, hop_length=hop)
+ tf = librosa.frames_to_time(np.arange(len(flux)), sr=sr, hop_length=hop)
+ t = t0 + np.arange(n) / fps
+ return {"loudness": np.interp(t, ta, 20 * np.log10(rms + 1e-6)), "flux": np.interp(t, tf, flux)}
+
+
+def beats(wav: str) -> list[float]:
+ import librosa
+ y, sr = librosa.load(wav, sr=22050, mono=True)
+ _, b = librosa.beat.beat_track(y=y, sr=sr, units="time")
+ return [round(float(x), 3) for x in b]
+
+
+def cut_density(cut_frames: list[int], n: int, fps: float) -> np.ndarray:
+ imp = np.zeros(n)
+ for k in cut_frames:
+ if 0 <= k < n:
+ imp[k] = 1.0
+ return gaussian_filter1d(imp, 0.75 * fps) * fps # cuts per second, smoothed
+
+
+def flashes(lum: np.ndarray, fps: float) -> np.ndarray:
+ base = median_filter(lum, size=max(3, int(fps)) | 1, mode="nearest")
+ return np.clip(lum - base, 0, None)
+
+
+def curve(features: dict[str, np.ndarray], fps: float) -> np.ndarray:
+ # a feature that was measured but never changes contributes 0 — it is not dropped, or the other weights would jump
+ # the moment it moves at all; only features that were not measured (no sound track) leave the mix
+ used = {k: w for k, w in WEIGHTS.items() if k in features and features[k] is not None and len(features[k])}
+ if not used:
+ n = len(next(iter(features.values()))) if features else 0
+ return np.zeros(n)
+ seen = {k: np.maximum(0.0, np.asarray(features[k], float) - DEADZONE[k]) if k in DEADZONE else features[k] for k in used}
+ mix = sum(w * robust01(seen[k], JND.get(k, 0.0)) for k, w in used.items()) / sum(used.values())
+ return gaussian_filter1d(mix, SMOOTH_S * fps)
+
+
+def describe_peaks(T: np.ndarray, fps: float, beat_times: list[float] | None = None, n: int = 3, min_gap_s: float = 4.0) -> list[dict]:
+ """The n most prominent peaks, each with the shape of its build, breath, hit and release."""
+ if len(T) < int(fps):
+ return []
+ idx, props = find_peaks(T, prominence=0.12, distance=max(1, int(min_gap_s * fps)))
+ order = np.argsort(-(props["prominences"] * T[idx]))[:n]
+ beats_ = np.asarray(beat_times or [])
+ out = []
+ for k in sorted(idx[order]):
+ f = int(k)
+ while f > 0 and T[f - 1] >= 0.97 * T[k]: # the hit is where the peak starts, not the middle of its plateau
+ f -= 1
+ a = max(0, f - int(2.0 * fps))
+ dip = f - 1 - int(np.argmin(T[a:f][::-1])) if f > a else f # the last low point before the hit
+ pre = T[max(0, dip - int(4 * fps)):dip + 1]
+ breath_depth = float(pre.max() - T[dip]) if len(pre) else 0.0
+ b_start = dip # the held breath starts where the curve first fell to near its bottom
+ while b_start > 0 and T[b_start - 1] <= T[dip] + 0.2 * breath_depth:
+ b_start -= 1
+ b0 = max(0, b_start - int(8 * fps))
+ build = np.polyfit(np.arange(b0, b_start + 1) / fps, T[b0:b_start + 1], 1)[0] if b_start - b0 >= 4 else 0.0
+ top, low = float(T[k]), float(T[dip])
+ rise = int(np.argmax(T[dip:f + 1] >= low + 0.9 * (top - low))) # frames from the bottom of the breath to 90 % of the hit
+ after = T[f:]
+ hold = int(np.argmax(after < 0.9 * top)) if (after < 0.9 * top).any() else len(after)
+ half = top - 0.5 * (top - low)
+ decay = int(np.argmax(after < half)) if (after < half).any() else len(after)
+ p = {"t": round(f / fps, 3), "height": round(top, 3), "prominence": round(float(props["prominences"][list(idx).index(k)]), 3),
+ "build_slope": round(float(build), 4), "breath_s": round((f - b_start) / fps, 3), "breath_depth": round(breath_depth, 3),
+ "rise_frames": rise, "hold_s": round(hold / fps, 3), "decay_s": round(decay / fps, 3)}
+ if len(beats_):
+ nb = beats_[np.argmin(np.abs(beats_ - f / fps))]
+ p["beat_offset_frames"] = round(float((f / fps - nb) * fps), 1)
+ out.append(p)
+ return out
diff --git a/.claude/skills/video-clone/scripts/perception/video.py b/.claude/skills/video-clone/scripts/perception/video.py
new file mode 100644
index 0000000..e9baf21
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/perception/video.py
@@ -0,0 +1,96 @@
+"""Decoded frames on a fixed clock.
+
+Every signal in a fingerprint is sampled on one clock, so the reference and our film can be compared frame for frame no
+matter what frame rate either was encoded at. Frames are streamed from an ffmpeg pipe: a three-minute reference never
+sits in memory as a whole.
+"""
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import tempfile
+from dataclasses import dataclass
+from typing import Iterator
+
+import numpy as np
+
+
+def ensure_ffmpeg() -> None:
+ """Put FFMPEG_DIR on PATH when ffmpeg is not already there (same rule as analyze.py)."""
+ extra = os.environ.get("FFMPEG_DIR", "")
+ if not shutil.which("ffmpeg") and extra and os.path.isdir(extra):
+ os.environ["PATH"] += os.pathsep + extra
+
+
+@dataclass(frozen=True)
+class VideoInfo:
+ width: int
+ height: int
+ duration: float
+ has_audio: bool
+
+
+def probe(path: str) -> VideoInfo:
+ ensure_ffmpeg()
+ r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height",
+ "-of", "json", path], capture_output=True, text=True, check=True)
+ j = json.loads(r.stdout)
+ v = next(s for s in j["streams"] if s["codec_type"] == "video")
+ return VideoInfo(int(v["width"]), int(v["height"]), float(j["format"]["duration"]),
+ any(s["codec_type"] == "audio" for s in j["streams"]))
+
+
+def frame_size(info: VideoInfo, width: int) -> tuple[int, int]:
+ """(width, height) after scaling to `width`, height rounded to an even number like ffmpeg's scale=w:-2."""
+ return width, max(2, round(width * info.height / info.width / 2) * 2)
+
+
+def frames(path: str, fps: float = 24.0, width: int = 320, start: float = 0.0, end: float | None = None) -> Iterator[np.ndarray]:
+ """BGR frames at `fps`, scaled to `width`; frame i shows time start + i / fps."""
+ ensure_ffmpeg()
+ w, h = frame_size(probe(path), width)
+ cmd = ["ffmpeg", "-v", "error", "-ss", f"{start:.3f}", "-i", path]
+ if end is not None:
+ cmd += ["-t", f"{max(0.0, end - start):.3f}"]
+ cmd += ["-vf", f"fps={fps},scale={w}:{h}:flags=area", "-f", "rawvideo", "-pix_fmt", "bgr24", "-"]
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
+ size = w * h * 3
+ try:
+ while True:
+ buf = p.stdout.read(size)
+ if len(buf) < size:
+ break
+ yield np.frombuffer(buf, np.uint8).reshape(h, w, 3)
+ finally:
+ p.stdout.close()
+ p.kill()
+ p.wait()
+
+
+def static_mask(path: str, size: tuple[int, int], start: float = 0.0, end: float | None = None,
+ std_max: float = 3.0, sample_fps: float = 4.0) -> np.ndarray | None:
+ """uint8 mask (255 = usable) at `size` that excludes pixels which never change over the whole clip: a phone UI
+ over a screen recording, a watermark, a channel logo, letterbox bars. Their corners would vote for "the camera did
+ not move". None when nothing (or nearly everything) is static — then there is nothing to exclude safely."""
+ import cv2
+ stack = np.stack([cv2.cvtColor(f, cv2.COLOR_BGR2GRAY) for f in frames(path, fps=sample_fps, width=96, start=start, end=end)]).astype(np.float32)
+ if len(stack) < 8:
+ return None
+ static = (stack.std(axis=0) < std_max).astype(np.uint8)
+ frac = float(static.mean())
+ if frac < 0.01 or frac > 0.6:
+ return None
+ static = cv2.dilate(static, np.ones((3, 3), np.uint8))
+ return np.where(cv2.resize(static, size, interpolation=cv2.INTER_NEAREST) > 0, 0, 255).astype(np.uint8)
+
+
+def extract_audio(path: str, sr: int = 22050) -> str | None:
+ """Mono wav of the video's sound in a temp file (the caller deletes it), or None when there is no audio."""
+ if not probe(path).has_audio:
+ return None
+ fd, wav = tempfile.mkstemp(suffix=".wav")
+ os.close(fd)
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", path, "-vn", "-ac", "1", "-ar", str(sr), wav], check=True)
+ return wav
diff --git a/.claude/skills/video-clone/scripts/score/__init__.py b/.claude/skills/video-clone/scripts/score/__init__.py
new file mode 100644
index 0000000..7cf4b11
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/score/__init__.py
@@ -0,0 +1,9 @@
+"""Motion Score: the film's camera and timing as data (stage 2 of the style compiler, docs/COMPILER.md).
+
+ timeexpr musical, frame-exact times ("B12-2f", "drop+1b", "S+0.25s")
+ eases GSAP names, cubic-bezier, springs → one normalised form
+ model load / validate / resolve (a folder with one file per shot, so parallel builders never collide)
+ runtime evaluate a resolved score (twin of assets/score/score.js, which the engines load)
+ transfer motion transfer: the reference's measured moves → score moves
+ predict what perception will measure for the score's camera, before rendering
+"""
diff --git a/.claude/skills/video-clone/scripts/score/cli.py b/.claude/skills/video-clone/scripts/score/cli.py
new file mode 100644
index 0000000..7bfc279
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/score/cli.py
@@ -0,0 +1,176 @@
+"""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
diff --git a/.claude/skills/video-clone/scripts/score/eases.py b/.claude/skills/video-clone/scripts/score/eases.py
new file mode 100644
index 0000000..2a97800
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/score/eases.py
@@ -0,0 +1,85 @@
+"""Ease specs: what authors write, and the one normalised form both runtimes evaluate.
+
+ "power3.out" a GSAP name (the formulas in perception.curves.NAMED)
+ "back.out(2.2)" GSAP's back with its overshoot parameter
+ {"bezier": [x1, y1, x2, y2]} CSS cubic-bezier
+ {"spring": {"omega": 18, "zeta": .4}} damped spring in seconds; the move has no fixed end (it settles in ≈ 4/(ζω))
+ "hold" jump at the end of the move (a cut-like snap)
+
+Normalised: {"kind": "named", "name": …} | {"kind": "back", "s": …} | {"kind": "bezier", "p": […]} |
+ {"kind": "spring", "omega": …, "zeta": …} | {"kind": "hold"}
+"""
+from __future__ import annotations
+
+import re
+
+import numpy as np
+
+from perception import curves
+
+ALIASES = {"linear": "none", "ease": "power1.inOut", "easeIn": "power2.in", "easeOut": "power2.out", "easeInOut": "power2.inOut"}
+
+
+class EaseError(ValueError):
+ pass
+
+
+def normalise(spec) -> dict:
+ if spec is None:
+ return {"kind": "named", "name": "power2.inOut"}
+ if isinstance(spec, str):
+ name = ALIASES.get(spec, spec)
+ if name == "hold":
+ return {"kind": "hold"}
+ m = re.fullmatch(r"back\.(in|out|inOut)\(([\d.]+)\)", name)
+ if m:
+ return {"kind": "back", "dir": m.group(1), "s": float(m.group(2))}
+ if name not in curves.NAMED:
+ raise EaseError(f"unknown ease {spec!r}; use a GSAP name ({', '.join(sorted(curves.NAMED))}), back.out(s), "
+ f"{{'bezier': [x1, y1, x2, y2]}} or {{'spring': {{'omega', 'zeta'}}}}")
+ return {"kind": "named", "name": name}
+ if isinstance(spec, dict) and "bezier" in spec:
+ p = [float(v) for v in spec["bezier"]]
+ if len(p) != 4 or not (0 <= p[0] <= 1 and 0 <= p[2] <= 1):
+ raise EaseError(f"bezier needs [x1, y1, x2, y2] with x1, x2 in 0..1, got {spec['bezier']}")
+ return {"kind": "bezier", "p": p}
+ if isinstance(spec, dict) and "spring" in spec:
+ s = spec["spring"]
+ omega, zeta = float(s.get("omega", 12)), float(s.get("zeta", 0.5))
+ if omega <= 0 or not 0 < zeta < 1:
+ raise EaseError(f"spring needs omega > 0 and 0 < zeta < 1, got {s}")
+ return {"kind": "spring", "omega": omega, "zeta": zeta}
+ if isinstance(spec, dict) and spec.get("kind"):
+ return spec # already normalised
+ raise EaseError(f"cannot read ease {spec!r}")
+
+
+def _back(dir_: str, s: float, u: np.ndarray) -> np.ndarray:
+ if dir_ == "in":
+ return (s + 1) * u ** 3 - s * u ** 2
+ if dir_ == "out":
+ return 1 + (s + 1) * (u - 1) ** 3 + s * (u - 1) ** 2
+ s2 = s * 1.525 # GSAP's inOut back
+ return np.where(u < 0.5, (2 * u) ** 2 * ((s2 + 1) * 2 * u - s2) / 2, ((2 * u - 2) ** 2 * ((s2 + 1) * (2 * u - 2) + s2) + 2) / 2)
+
+
+def progress(e: dict, u: np.ndarray | float, elapsed: np.ndarray | float | None = None) -> np.ndarray:
+ """0→1 progress of a move: u = normalised time (clamped) for timed eases, elapsed seconds for springs."""
+ u = np.clip(np.asarray(u, float), 0, 1)
+ k = e["kind"]
+ if k == "named":
+ return np.asarray(curves.NAMED[e["name"]](u), float)
+ if k == "back":
+ return _back(e["dir"], e["s"], u)
+ if k == "bezier":
+ return curves.bezier(u, *e["p"])
+ if k == "hold":
+ return (u >= 1).astype(float)
+ if k == "spring":
+ return curves.spring(np.asarray(elapsed, float), e["omega"], e["zeta"])
+ raise EaseError(f"unknown ease kind {k!r}")
+
+
+def settle_time(e: dict) -> float | None:
+ """How long a spring takes to settle (≈ 2 % band); None for timed eases."""
+ return 4.0 / (e["zeta"] * e["omega"]) if e["kind"] == "spring" else None
diff --git a/.claude/skills/video-clone/scripts/score/model.py b/.claude/skills/video-clone/scripts/score/model.py
new file mode 100644
index 0000000..9f70e8d
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/score/model.py
@@ -0,0 +1,269 @@
+"""Motion Score: load the authored score, check it, and resolve it to plain numbers for the runtimes.
+
+Authored (what directors, builders and tools write), as one file or as a folder with one file per shot so parallel
+builders never edit the same file:
+
+ build/score/film.json { "version": 1, "fps": 24, "bpm": 123.05, "offset": 0, "duration": 30,
+ "cues": { "drop": "B28", "slap": "5.80" } }
+ build/score/shots/S3.json { "id": "S3", "start": "B8", "end": "B12", "ref_shot": 3, "cadence": 1,
+ "camera": { "base": { "x": 960, "y": 540, "zoom": 1, "rot": 0 },
+ "moves": [ { "at": "S+2f", "dur": "1b", "to": { "zoom": 1.2 }, "ease": "expo.out" },
+ { "at": "B10", "until": "E", "by": { "x": 60 }, "ease": { "bezier": [.4, 0, .2, 1] } } ],
+ "shakes": [ { "at": "slap", "amp": 12, "decay": 12 } ] },
+ "tracks": { "reach": { "base": 0, "moves": [ { "at": "B8", "dur": "3f", "to": 1, "ease": "power2.out" } ] } } }
+
+A move marked "past_cut": true is meant to be interrupted by a cut — begun before the shot, or still going at its
+end — as real footage often cuts mid-move.
+
+Camera: world coordinates of a 1920×1080 stage; x, y = the world point at the centre of the frame, zoom = scale
+(> 1 = pushed in), rot = roll in radians (+ = the image turns clockwise, as canvas rotate()). A move sets channels "to"
+a value or changes them "by" an amount (zoom "by" multiplies: by 1.2 = a 20 % push). Moves on one channel run one after
+the other; a spring may be interrupted by the next move. "drift" ({"by": {...}, "ease": "none"}) is a slow change over
+the whole shot layered under the moves (zoom multiplies): the slow push a reference keeps going while it also does
+quicker moves. Tracks are any other named numbers a shot animates.
+
+Resolved (what score.js and runtime.py evaluate): every time in seconds, every move a segment
+{ t0, t1, v0, v1, ease } per channel, in time order.
+"""
+from __future__ import annotations
+
+import glob
+import json
+import os
+from dataclasses import dataclass, field
+
+from perception.fingerprint import ref_shot_id
+
+from . import eases
+from .timeexpr import Clock, TimeError, resolve
+
+VERSION = 1
+CHANNELS = ("x", "y", "zoom", "rot")
+DEFAULT_BASE = {"x": 960.0, "y": 540.0, "zoom": 1.0, "rot": 0.0}
+
+
+@dataclass
+class Diagnostics:
+ errors: list[str] = field(default_factory=list)
+ warnings: list[str] = field(default_factory=list)
+
+ def error(self, where: str, msg: str):
+ self.errors.append(f"{where}: {msg}")
+
+ def warn(self, where: str, msg: str):
+ self.warnings.append(f"{where}: {msg}")
+
+ @property
+ def ok(self) -> bool:
+ return not self.errors
+
+
+class ScoreError(ValueError):
+ def __init__(self, diag: Diagnostics):
+ super().__init__("\n".join(diag.errors))
+ self.diag = diag
+
+
+# ---------- loading ----------
+def _read(p: str, label: str) -> dict:
+ try:
+ with open(p, encoding="utf-8-sig") as f: # -sig: a byte-order mark from a Windows editor is not an error
+ return json.load(f)
+ except json.JSONDecodeError as e:
+ d = Diagnostics()
+ d.error(label, f"not valid JSON at line {e.lineno}, column {e.colno}: {e.msg} (no comments, trailing commas or single quotes)")
+ raise ScoreError(d) from None
+
+
+def load(path: str) -> tuple[dict, dict[str, str]]:
+ """The authored score as one dict ({…film, "shots": [...]}) and where each shot came from (for messages)."""
+ if os.path.isdir(path):
+ film = _read(os.path.join(path, "film.json"), "film.json")
+ shots, origin = [], {}
+ for p in sorted(glob.glob(os.path.join(path, "shots", "*.json"))):
+ rel = os.path.relpath(p, path).replace("\\", "/")
+ s = _read(p, rel)
+ shots.append(s)
+ origin[str(s.get("id"))] = rel
+ return {**film, "shots": shots}, origin
+ score = _read(path, os.path.basename(path))
+ return score, {str(s.get("id")): f"shots[{i}]" for i, s in enumerate(score.get("shots", []))}
+
+
+def save_shot(path: str, shot: dict):
+ """Write one shot file of a score folder (atomic: a builder reading it never sees half a file)."""
+ p = os.path.join(path, "shots", f"{shot['id']}.json")
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ tmp = p + ".tmp"
+ with open(tmp, "w", encoding="utf-8") as f:
+ json.dump(shot, f, ensure_ascii=False, indent=1)
+ os.replace(tmp, p)
+
+
+# ---------- resolving ----------
+def _segments(moves: list, base: dict[str, float], channels: tuple[str, ...] | None, ctx, where: str, diag: Diagnostics,
+ shot_span: tuple[float, float], times: list | None = None) -> dict[str, list[dict]]:
+ """Moves → per-channel segments. ctx(expr, length) resolves a time inside this shot. `times`, if given, receives
+ each move's resolved [t0, t1] by index (None where the move could not be read) — the optimizer edits moves by it."""
+ segs: dict[str, list[dict]] = {}
+ if times is not None:
+ times[:] = [None] * len(moves or [])
+ for i, mv in enumerate(moves or []):
+ w = f"{where}.moves[{i}]"
+ try:
+ t0 = ctx(mv["at"], False)
+ except (KeyError, TimeError) as e:
+ diag.error(w + ".at", str(e) if isinstance(e, TimeError) else "missing")
+ continue
+ try:
+ ease = eases.normalise(mv.get("ease"))
+ except eases.EaseError as e:
+ diag.error(w + ".ease", str(e))
+ continue
+ try:
+ if "until" in mv:
+ t1 = ctx(mv["until"], False)
+ elif "dur" in mv:
+ t1 = t0 + ctx(mv["dur"], True)
+ elif ease["kind"] == "spring":
+ t1 = t0 + eases.settle_time(ease)
+ else:
+ diag.error(w, "needs \"dur\" or \"until\" (only a spring may leave its length out)")
+ continue
+ except TimeError as e:
+ diag.error(w + (".until" if "until" in mv else ".dur"), str(e))
+ continue
+ if t1 < t0:
+ diag.error(w, f"ends ({t1:.3f}s) before it starts ({t0:.3f}s)")
+ continue
+ if (t0 < shot_span[0] - 1e-6 or t1 > shot_span[1] + 1e-6) and not mv.get("past_cut"):
+ diag.warn(w, f"runs {t0:.3f}–{t1:.3f}s, outside the shot ({shot_span[0]:.3f}–{shot_span[1]:.3f}s)"
+ ' (if a cut is meant to interrupt it, mark it "past_cut": true)')
+ if times is not None:
+ times[i] = [round(t0, 6), round(t1, 6)]
+ to, by = mv.get("to"), mv.get("by")
+ if (to is None) == (by is None):
+ diag.error(w, "needs exactly one of \"to\" or \"by\"")
+ continue
+ targets = (to if isinstance(to, dict) else {"value": to}) if to is not None else (by if isinstance(by, dict) else {"value": by})
+ for ch, v in targets.items():
+ if channels is not None and ch not in channels:
+ diag.error(f"{w}.{'to' if to is not None else 'by'}.{ch}", f"unknown channel (camera has {', '.join(channels)})")
+ continue
+ prev = segs.setdefault(ch, [])
+ if prev and prev[-1]["t1"] > t0 + 1e-9 and prev[-1]["ease"]["kind"] != "spring":
+ diag.error(w, f"{ch} is still moving until {prev[-1]['t1']:.3f}s (moves[{prev[-1]['_i']}]); start at or after it")
+ continue
+ v0 = value_at(prev, base.get(ch, 0.0), t0)
+ v1 = float(v) if to is not None else (v0 * float(v) if ch == "zoom" else v0 + float(v))
+ if ch == "zoom" and v1 <= 0:
+ diag.error(f"{w}.{ch}", f"zoom must stay > 0, got {v1}")
+ continue
+ prev.append({"t0": round(t0, 6), "t1": round(t1, 6), "v0": round(v0, 6), "v1": round(v1, 6), "ease": ease, "_i": i})
+ for L in segs.values():
+ for s in L:
+ s.pop("_i", None)
+ return segs
+
+
+def value_at(segs: list[dict], base: float, t: float) -> float:
+ """Channel value at t (the resolver needs it to know where a move starts from; runtime.py is the full evaluator)."""
+ from .runtime import channel
+ return channel(segs, base, t)
+
+
+def resolve_score(score: dict, origin: dict[str, str] | None = None) -> tuple[dict, Diagnostics]:
+ diag, origin = Diagnostics(), origin or {}
+ if score.get("version", VERSION) != VERSION:
+ diag.error("film", f"version {score.get('version')} is not supported (this tool reads {VERSION})")
+ try:
+ clock = Clock(bpm=float(score.get("bpm", 120)), offset=float(score.get("offset", 0)), fps=float(score.get("fps", 24)))
+ except (TypeError, ValueError):
+ diag.error("film", "bpm, offset and fps must be numbers")
+ return {}, diag
+ cues: dict[str, float] = {}
+ for name, expr in (score.get("cues") or {}).items(): # in order: a cue may use the ones before it
+ try:
+ cues[name] = round(resolve(expr, clock, cues), 6)
+ except TimeError as e:
+ diag.error(f"film.cues.{name}", str(e))
+ out_shots = []
+ for s in score.get("shots", []):
+ sid = str(s.get("id", "?"))
+ where = origin.get(sid, sid)
+ try:
+ span = (resolve(s["start"], clock, cues), resolve(s["end"], clock, cues))
+ except KeyError:
+ diag.error(where, "needs \"start\" and \"end\"")
+ continue
+ except TimeError as e:
+ diag.error(where, str(e))
+ continue
+ if span[1] <= span[0]:
+ diag.error(where, f"ends ({span[1]:.3f}s) before it starts ({span[0]:.3f}s)")
+ continue
+ ctx = lambda expr, length, span=span: resolve(expr, clock, cues, span, length)
+ cam = s.get("camera") or {}
+ base = {**DEFAULT_BASE, **{k: float(v) for k, v in (cam.get("base") or {}).items() if k in CHANNELS}}
+ for k in (cam.get("base") or {}):
+ if k not in CHANNELS:
+ diag.error(f"{where}.camera.base.{k}", f"unknown channel (camera has {', '.join(CHANNELS)})")
+ move_times: list = []
+ channels = _segments(cam.get("moves"), base, CHANNELS, ctx, f"{where}.camera", diag, span, move_times)
+ shakes = []
+ for i, sh in enumerate(cam.get("shakes") or []):
+ try:
+ shakes.append({"t0": round(ctx(sh["at"], False), 6), "amp": float(sh.get("amp", 10)), "decay": float(sh.get("decay", 10)),
+ "rate": float(sh.get("rate", clock.fps)), "seed": float(sh.get("seed", i))})
+ except (KeyError, TimeError) as e:
+ diag.error(f"{where}.camera.shakes[{i}]", str(e) if isinstance(e, TimeError) else "needs \"at\"")
+ drift = None
+ if cam.get("drift"):
+ dr = cam["drift"]
+ try:
+ by = {k: float(v) for k, v in (dr.get("by") or {}).items()}
+ bad = [k for k in by if k not in CHANNELS]
+ if bad:
+ diag.error(f"{where}.camera.drift.by.{bad[0]}", f"unknown channel (camera has {', '.join(CHANNELS)})")
+ elif by.get("zoom", 1.0) <= 0:
+ diag.error(f"{where}.camera.drift.by.zoom", "a zoom drift multiplies: it must be > 0")
+ else:
+ drift = {"t0": round(span[0], 6), "t1": round(span[1], 6), "by": by, "ease": eases.normalise(dr.get("ease", "none"))}
+ except (TypeError, ValueError):
+ diag.error(f"{where}.camera.drift", "needs \"by\": {channel: number}")
+ except eases.EaseError as e:
+ diag.error(f"{where}.camera.drift.ease", str(e))
+ tracks = {}
+ for name, tr in (s.get("tracks") or {}).items():
+ tb = float(tr.get("base", 0))
+ tracks[name] = {"base": tb, "segs": _segments(tr.get("moves"), {"value": tb}, None, ctx, f"{where}.tracks.{name}", diag, span).get("value", [])}
+ cad = int(s.get("cadence", 1))
+ if cad not in (1, 2, 3, 4):
+ diag.error(f"{where}.cadence", "must be 1, 2, 3 or 4 (frames each drawing is held)")
+ out_shots.append({"id": sid, "start": round(span[0], 6), "end": round(span[1], 6), "ref_shot": ref_shot_id(s.get("ref_shot")), "cadence": cad,
+ "camera": {"base": base, "channels": channels, "shakes": shakes, "drift": drift, "move_times": move_times}, "tracks": tracks})
+ out_shots.sort(key=lambda x: x["start"])
+ for a, b in zip(out_shots, out_shots[1:]):
+ gap = b["start"] - a["end"]
+ if abs(gap) > 0.5 / clock.fps:
+ diag.warn(f"{origin.get(b['id'], b['id'])}", f"{'gap' if gap > 0 else 'overlap'} of {abs(gap):.3f}s after {a['id']}")
+ dur = float(score.get("duration", out_shots[-1]["end"] if out_shots else 0))
+ if out_shots and out_shots[-1]["end"] > dur + 1e-6:
+ diag.warn("film", f"the last shot ends at {out_shots[-1]['end']:.3f}s, after the film's duration {dur:.3f}s")
+ ids = [s["id"] for s in out_shots]
+ for d in {x for x in ids if ids.count(x) > 1}:
+ diag.error("film", f"shot id {d!r} is used more than once")
+ size = [int(v) for v in score.get("size", [1920, 1080])]
+ return {"version": VERSION, "fps": clock.fps, "bpm": clock.bpm, "offset": clock.offset, "duration": dur, "size": size,
+ "cues": cues, "shots": out_shots}, diag
+
+
+def compile_path(path: str) -> dict:
+ """Load + resolve, raising ScoreError with every problem listed when the score is not valid."""
+ score, origin = load(path)
+ resolved, diag = resolve_score(score, origin)
+ if not diag.ok:
+ raise ScoreError(diag)
+ resolved["_warnings"] = diag.warnings
+ return resolved
+
diff --git a/.claude/skills/video-clone/scripts/score/predict.py b/.claude/skills/video-clone/scripts/score/predict.py
new file mode 100644
index 0000000..2b17c2a
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/score/predict.py
@@ -0,0 +1,64 @@
+"""Predict what perception will measure for a score's camera — without rendering a frame.
+
+The score fully determines the camera, and perception's camera model is the same similarity transform, so the
+per-frame trajectory perception would recover can be computed directly:
+
+ stage camera (cx, cy, zoom, rot), world → screen s = C + zoom · R(rot) · (p − c)
+ perception (frame widths / log scale / radians, camera terms):
+ (x, y) += zoom · R(rot) · (Δcx, Δcy) / W z = ln(zoom / zoom₀) r = −(rot − rot₀)
+
+(rot turns the image clockwise as canvas rotate() does; perception reports a clockwise *camera* roll as +, which turns
+the image the other way.) The predicted trajectory goes through the same describe_shot() and is compared with the
+reference shot by the same camera_pair() as a rendered film: the director sees "the push in S3 is 1.8× slower than ref
+#4" before anything is built, and the optimizer (stage 3) can search camera parameters without rendering at all.
+"""
+from __future__ import annotations
+
+import numpy as np
+
+from perception import curves, distance
+
+from .runtime import Score
+
+W = 1920.0
+
+
+def trajectory(score: Score, sid: str, fps: float | None = None) -> tuple[np.ndarray, dict[str, np.ndarray]]:
+ t, c = score.camera_series(sid, fps)
+ z, rot = c["zoom"], c["rot"]
+ dcx, dcy = np.r_[0.0, np.diff(c["x"])], np.r_[0.0, np.diff(c["y"])]
+ mid = lambda v: np.r_[v[0], (v[1:] + v[:-1]) / 2]
+ zm, rm = mid(z), mid(rot)
+ # a world move seen through a rolled camera moves the picture along the rolled axes (screen = zoom · R(rot) · world)
+ sx = zm * (np.cos(rm) * dcx - np.sin(rm) * dcy) / W
+ sy = zm * (np.sin(rm) * dcx + np.cos(rm) * dcy) / W
+ return t, {"x": np.cumsum(sx), "y": np.cumsum(sy), "z": np.log(z / z[0]), "r": -(rot - rot[0])}
+
+
+def predicted_shots(score: Score) -> list[dict]:
+ out = []
+ for sid, s in score.shots.items():
+ t, traj = trajectory(score, sid)
+ if len(t) < 2:
+ continue
+ out.append({"id": sid, "ref_shot": s.get("ref_shot"), "start": s["start"], "end": s["end"], "move": curves.describe_shot(t, traj)})
+ return out
+
+
+def against_reference(score: Score, ref_fp: dict) -> dict:
+ """Camera-only style distance of the score against the reference fingerprint, per mapped shot."""
+ from perception.fingerprint import reference_for
+ preds = predicted_shots(score)
+ answers = reference_for(ref_fp, [(p["id"], p["ref_shot"], p["end"] - p["start"]) for p in sorted(preds, key=lambda p: p["start"])])
+ shots, findings, scores = [], [], []
+ for p in preds:
+ rs = answers.get(p["id"])
+ if rs is None:
+ shots.append({"id": p["id"], "ref_shot": p["ref_shot"], "move": p["move"]["kind"], "note": "no reference shot mapped"})
+ continue
+ sc, detail, f = distance.camera_pair(rs, p)
+ scores.append(sc)
+ findings += f
+ shots.append({"id": p["id"], "ref_shot": rs["id"], "score": sc, **detail})
+ return {"camera_score": round(float(np.mean(scores)), 1) if scores else None, "shots": shots,
+ "findings": sorted(findings, key=lambda x: x["severity"] != "major")}
diff --git a/.claude/skills/video-clone/scripts/score/runtime.py b/.claude/skills/video-clone/scripts/score/runtime.py
new file mode 100644
index 0000000..37fb8fd
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/score/runtime.py
@@ -0,0 +1,133 @@
+"""Evaluate a resolved score — the Python twin of assets/score/score.js.
+
+Both must give the same numbers (tests/test_score.py runs the JS one under Node and compares): the JS one draws the film,
+this one predicts what the film's camera will measure as without rendering a frame (predict.py).
+"""
+from __future__ import annotations
+
+import math
+
+import numpy as np
+
+from . import eases
+
+
+def _hash(i: float) -> float:
+ """Same stable noise as kit.js: fract(sin(i · 127.1 + 311.7) · 43758.5453)."""
+ x = math.sin(i * 127.1 + 311.7) * 43758.5453
+ return x - math.floor(x)
+
+
+def channel(segs: list[dict], base: float, t: float) -> float:
+ """The value of one channel at t: base before the first move, then each move from its v0 to its v1."""
+ cur = None
+ for s in segs:
+ if s["t0"] <= t:
+ cur = s
+ else:
+ break
+ if cur is None:
+ return base
+ e, span = cur["ease"], cur["t1"] - cur["t0"]
+ if e["kind"] == "spring":
+ p = float(eases.progress(e, 0, t - cur["t0"]))
+ else:
+ p = 1.0 if span <= 0 else float(eases.progress(e, (t - cur["t0"]) / span))
+ return cur["v0"] + (cur["v1"] - cur["v0"]) * p
+
+
+def channel_array(segs: list[dict], base: float, t: np.ndarray) -> np.ndarray:
+ """channel() over many times at once (same numbers; tests check it against the scalar twin of score.js)."""
+ t = np.asarray(t, float)
+ out = np.full(t.shape, float(base))
+ for k, s in enumerate(segs):
+ nxt = segs[k + 1]["t0"] if k + 1 < len(segs) else np.inf
+ m = (t >= s["t0"]) & (t < nxt)
+ if not m.any():
+ continue
+ e, span = s["ease"], s["t1"] - s["t0"]
+ if e["kind"] == "spring":
+ p = eases.progress(e, 0, t[m] - s["t0"])
+ else:
+ p = np.ones(int(m.sum())) if span <= 0 else eases.progress(e, (t[m] - s["t0"]) / span)
+ out[m] = s["v0"] + (s["v1"] - s["v0"]) * p
+ return out
+
+
+def _hash_array(i: np.ndarray) -> np.ndarray:
+ x = np.sin(i * 127.1 + 311.7) * 43758.5453
+ return x - np.floor(x)
+
+
+def shake(sh: dict, t: float) -> tuple[float, float]:
+ if t < sh["t0"]:
+ return 0.0, 0.0
+ f = math.floor(t * sh["rate"] + 1e-6)
+ k = sh["amp"] * math.exp(-sh["decay"] * (t - sh["t0"]))
+ return (_hash(f * 1.7 + sh["seed"]) - 0.5) * 2 * k, (_hash(f * 2.3 + 9 + sh["seed"]) - 0.5) * 2 * k
+
+
+class Score:
+ def __init__(self, resolved: dict):
+ self.r = resolved
+ self.shots = {s["id"]: s for s in resolved["shots"]}
+
+ def shot_at(self, t: float) -> dict:
+ cur = self.r["shots"][0]
+ for s in self.r["shots"]:
+ if s["start"] <= t:
+ cur = s
+ return cur
+
+ def cam(self, sid: str, t: float) -> dict[str, float]:
+ s = self.shots[sid]
+ c = s["camera"]
+ v = {ch: channel(c["channels"].get(ch, []), c["base"][ch], t) for ch in ("x", "y", "zoom", "rot")}
+ d = c.get("drift")
+ if d:
+ span = d["t1"] - d["t0"]
+ p = float(eases.progress(d["ease"], (t - d["t0"]) / span if span > 0 else 1.0))
+ for ch, by in d["by"].items():
+ v[ch] = v[ch] * by ** p if ch == "zoom" else v[ch] + by * p
+ for sh in c["shakes"]:
+ dx, dy = shake(sh, t)
+ v["x"] += dx
+ v["y"] += dy
+ return v
+
+ def track(self, sid: str, name: str, t: float) -> float:
+ tr = self.shots[sid]["tracks"][name]
+ return channel(tr["segs"], tr["base"], t)
+
+ def held(self, sid: str, t: float) -> float:
+ """t snapped to the shot's cadence (on twos: each drawing held for two frames)."""
+ s, fps = self.shots[sid], self.r["fps"]
+ n = s["cadence"]
+ if n <= 1:
+ return t
+ f = max(0, math.floor((t - s["start"]) * fps + 1e-6)) # ≥ 0: Python and JS disagree on % of negatives
+ return s["start"] + (f - f % n) / fps
+
+ def cam_array(self, sid: str, t: np.ndarray) -> dict[str, np.ndarray]:
+ """cam() at many times at once."""
+ c = self.shots[sid]["camera"]
+ v = {ch: channel_array(c["channels"].get(ch, []), c["base"][ch], t) for ch in ("x", "y", "zoom", "rot")}
+ d = c.get("drift")
+ if d:
+ span = d["t1"] - d["t0"]
+ p = eases.progress(d["ease"], (t - d["t0"]) / span if span > 0 else np.ones_like(t))
+ for ch, by in d["by"].items():
+ v[ch] = v[ch] * by ** p if ch == "zoom" else v[ch] + by * p
+ for sh in c["shakes"]:
+ on = t >= sh["t0"]
+ f = np.floor(t * sh["rate"] + 1e-6)
+ k = np.where(on, sh["amp"] * np.exp(-sh["decay"] * np.maximum(0.0, t - sh["t0"])), 0.0)
+ v["x"] = v["x"] + (_hash_array(f * 1.7 + sh["seed"]) - 0.5) * 2 * k
+ v["y"] = v["y"] + (_hash_array(f * 2.3 + 9 + sh["seed"]) - 0.5) * 2 * k
+ return v
+
+ def camera_series(self, sid: str, fps: float | None = None) -> tuple[np.ndarray, dict[str, np.ndarray]]:
+ """The camera at every frame of the shot (times, {x, y, zoom, rot} arrays)."""
+ s, fps = self.shots[sid], fps or self.r["fps"]
+ t = s["start"] + np.arange(int(round((s["end"] - s["start"]) * fps))) / fps
+ return t, self.cam_array(sid, t)
diff --git a/.claude/skills/video-clone/scripts/score/timeexpr.py b/.claude/skills/video-clone/scripts/score/timeexpr.py
new file mode 100644
index 0000000..6f48dbe
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/score/timeexpr.py
@@ -0,0 +1,87 @@
+"""Time expressions: musical, frame-exact times that read like an editor's notes.
+
+ B12 beat 12 (offset + 12 · 60/bpm) absolute
+ S, E start / end of the shot the expression is in absolute
+ drop a named cue from the film's "cues" absolute
+ 3.95, 3.95s seconds absolute when alone, a length when added
+ 1b, 0.5b beats (a length)
+ 2f frames (a length)
+
+ "B12-2f" two frames before beat 12
+ "drop+1b" one beat after the cue "drop"
+ "S+0.25s" a quarter second into the shot
+
+An *instant* has exactly one absolute term (B…, S, E, a cue, or a bare number); a *length* ("dur") has none.
+Everything resolves to seconds on the film's clock.
+"""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+_TOKEN = re.compile(r"\s*([+-])?\s*(B-?\d+(?:\.\d+)?|[A-Za-z_][A-Za-z0-9_]*|\d+(?:\.\d+)?(?:[sbf])?)\s*")
+
+
+class TimeError(ValueError):
+ pass
+
+
+@dataclass(frozen=True)
+class Clock:
+ bpm: float
+ offset: float = 0.0
+ fps: float = 24.0
+
+ @property
+ def beat(self) -> float:
+ return 60.0 / self.bpm
+
+
+def _terms(expr: str) -> list[tuple[int, str]]:
+ s, pos, out = str(expr).strip(), 0, []
+ if not s:
+ raise TimeError("empty time")
+ while pos < len(s):
+ m = _TOKEN.match(s, pos)
+ if not m or m.end() == pos:
+ raise TimeError(f"cannot read {s!r} at {s[pos:]!r}")
+ sign = -1 if m.group(1) == "-" else 1
+ if out and m.group(1) is None:
+ raise TimeError(f"missing + or - before {m.group(2)!r} in {s!r}")
+ out.append((sign, m.group(2)))
+ pos = m.end()
+ return out
+
+
+def resolve(expr, clock: Clock, cues: dict[str, float] | None = None, shot: tuple[float, float] | None = None,
+ length: bool = False) -> float:
+ """Seconds for an instant (length=False) or a length (length=True). Numbers are accepted as-is (seconds)."""
+ if isinstance(expr, (int, float)):
+ return float(expr)
+ terms = _terms(expr)
+ total, anchors = 0.0, 0
+ for sign, tok in terms:
+ if tok[0] == "B" and re.fullmatch(r"B-?\d+(?:\.\d+)?", tok):
+ total += sign * (clock.offset + float(tok[1:]) * clock.beat)
+ anchors += 1
+ elif tok in ("S", "E"):
+ if shot is None:
+ raise TimeError(f"{tok!r} (shot start/end) is only valid inside a shot")
+ total += sign * (shot[0] if tok == "S" else shot[1])
+ anchors += 1
+ elif re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", tok):
+ if not cues or tok not in cues:
+ raise TimeError(f"unknown cue {tok!r}" + (f" (cues: {', '.join(sorted(cues))})" if cues else ""))
+ total += sign * cues[tok]
+ anchors += 1
+ else:
+ unit = tok[-1] if tok[-1] in "sbf" else ""
+ v = float(tok[:-1] if unit else tok)
+ total += sign * (v * clock.beat if unit == "b" else v / clock.fps if unit == "f" else v)
+ if unit in ("", "s") and not length and len(terms) == 1:
+ anchors += 1 # seconds on their own are an absolute time
+ if length and anchors:
+ raise TimeError(f"{expr!r} is an instant; a length takes only s / b / f terms")
+ if not length and anchors != 1:
+ raise TimeError(f"{expr!r} needs exactly one anchor (B…, S, E, a cue or a time in seconds), found {anchors}")
+ return total
diff --git a/.claude/skills/video-clone/scripts/score/transfer.py b/.claude/skills/video-clone/scripts/score/transfer.py
new file mode 100644
index 0000000..873ec45
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/score/transfer.py
@@ -0,0 +1,194 @@
+"""Motion transfer: write a score whose camera does what the reference camera measurably did.
+
+For every plan shot mapped to a reference shot (plan.json "ref_shot"), each move perception found in that reference shot
+— the main one and any other_moves — becomes a score move with the same pace (seconds), amount (converted from frame
+widths to stage pixels at the current zoom) and ease (the fitted curve). Shots whose plan already defines a camera
+start from it. Moves that started on a beat in the reference start on a beat here, written as "B<n>".
+
+The result is a starting point the director edits, not a verdict: the plan's own intent (a push to the eyes, a reveal)
+may need different targets. Every generated move records where it came from ("from_ref") so a reviewer can tell
+transferred motion from authored motion.
+"""
+from __future__ import annotations
+
+import math
+
+from perception import curves
+from perception.fingerprint import ref_shot_id
+
+from .timeexpr import Clock
+
+W = 1920.0
+AXIS_CH = {"x": "x", "y": "y", "z": "zoom", "r": "rot"}
+
+
+def ease_spec(m: dict) -> tuple[object, float | None, float | None]:
+ """The fitted ease as a score ease, with the start and duration *of that fit* (each model has its own window).
+ A GSAP name when it fits nearly as well as the best: easier to read and to tweak."""
+ e, tm = m["ease"], m.get("timing") or {}
+ if m.get("snap"):
+ return "hold", None, None
+ pick = e.get("pick") or e.get("best") or "named" # the model perception chose for builders; its own window
+ t0, d = (tm.get(pick) or (None, None))[:2] if tm.get(pick) else (None, None)
+ if pick == "named":
+ return e["named"], t0, d
+ if pick == "spring" and e.get("spring"):
+ return {"spring": {"omega": e["spring"]["omega"], "zeta": min(0.95, e["spring"]["zeta"])}}, t0, None
+ return {"bezier": e["bezier"]}, t0, d
+
+
+def _by(amount: dict[str, float], zoom: float) -> dict[str, float]:
+ by = {}
+ for ax, v in amount.items():
+ if abs(v) < curves.MIN_AMOUNT[ax]:
+ continue
+ if ax == "z":
+ by["zoom"] = round(math.exp(v), 4)
+ elif ax == "r":
+ by["rot"] = round(-v, 4)
+ else:
+ by[AXIS_CH[ax]] = round(v * W / zoom, 1)
+ return by
+
+
+def schedule(want: list[float], durs: list[float], start: float, end: float) -> tuple[list[float], list[float], float]:
+ """Place moves one after another inside [start, end]: each as close to where it was wanted as possible, never
+ overlapping, never outside the shot. Pace (duration) is kept when the moves fit; when they do not, every move is
+ compressed by the same factor (returned) and they run back to back."""
+ L, total = end - start, sum(durs)
+ if total > L:
+ k = L / total
+ durs = [d * k for d in durs]
+ starts, t = [], start
+ for d in durs:
+ starts.append(t)
+ t += d
+ return starts, durs, k
+ s = [min(max(w, start), end) for w in want]
+ for i in range(len(s)): # forward: after the previous one
+ if i:
+ s[i] = max(s[i], s[i - 1] + durs[i - 1])
+ for i in reversed(range(len(s))): # backward: finish before the next one / the shot's end
+ s[i] = min(s[i], (s[i + 1] if i + 1 < len(s) else end) - durs[i])
+ return s, durs, 1.0
+
+
+def _at(t: float, lo: float, hi: float, clock: Clock, shot_start: float) -> str:
+ """'B<n>' when a beat within 1.5 frames keeps the move inside [lo, hi], else seconds into the shot."""
+ k = round((t - clock.offset) / clock.beat)
+ tb = clock.offset + k * clock.beat
+ if abs(tb - t) <= 1.5 / clock.fps and lo - 1e-9 <= tb <= hi + 1e-9:
+ return f"B{k}"
+ return f"S+{max(0.0, t - shot_start):.3f}s"
+
+
+def shot_moves(ref_shot: dict, our_start: float, our_end: float, clock: Clock, zoom: float = 1.0) -> list[dict]:
+ rm = ref_shot["move"]
+ if "axis" not in rm:
+ return [] # still, or a shake (transferred as camera.shakes, see shot_shakes)
+ r0, r1 = ref_shot["start"], ref_shot["end"]
+ scale = (our_end - our_start) / max(1e-6, r1 - r0)
+ main = {"start": rm["start"], "duration": rm["duration"], "amount": rm.get("move_amount", rm["amount"]), "ease": rm["ease"],
+ "snap": rm.get("snap"), "axis": rm["axis"], "timing": rm.get("timing"), "which": "main",
+ "cut_off": (bool(rm.get("cut_off")) or (rm.get("lead_in") or 0) > 0.05) and (rm.get("seen") or 0) > 0.05,
+ "visible": rm.get("visible"), "seen": rm.get("seen"), "lead_in": rm.get("lead_in") or 0.0}
+ if isinstance(main["ease"], dict): # the chosen model's own window
+ _, t0, d = ease_spec(main)
+ if t0 is not None:
+ main["start"] = max(r0, t0) # where it is first on screen; lead_in says how long it had been moving
+ if d:
+ main["duration"] = d
+ found = [m for m in sorted([main] + [{**o, "which": i} for i, o in enumerate(rm.get("other_moves") or [])], key=lambda m: m["start"])
+ if _by(m["amount"], 1.0)]
+ if not found:
+ return []
+ # where in the shot a move happens scales with the shot; how fast it moves (its duration) is kept when it fits
+ # a much shorter shot keeps the biggest moves at ≤ 2× their speed instead of squeezing them all into whip pans
+ kept = curves.moves_that_fit(found, our_end - our_start)
+ dropped = [round(m["start"] - r0, 3) for m in found if m not in kept]
+ found = kept
+ room_of = curves.on_screen
+ want = [our_start + (m["start"] - r0) * scale for m in found]
+ # a move the reference's cut interrupts only needs room for what was on screen; the rest runs past our cut too
+ room = [room_of(m) for m in found]
+ starts, roomy, k = schedule(want, room, our_start, our_end)
+ durs = [m["duration"] * k if m.get("cut_off") else d for m, d in zip(found, roomy)]
+ frame = 1 / clock.fps
+ moves = []
+ for i, (m, t0, d) in enumerate(zip(found, starts, durs)):
+ d = max(frame, math.floor(d * 1000) / 1000) # round down: never spill past the next move or the cut
+ hi = (starts[i + 1] if i + 1 < len(starts) else our_end) - (roomy[i] if m.get("cut_off") else d)
+ lo = (starts[i - 1] + roomy[i - 1]) if i else our_start
+ amount = m["amount"]
+ if m.get("cut_off"): # the amount seen is part of the whole move: the whole move is what we write
+ amount = {ax: v / m["seen"] for ax, v in amount.items()}
+ by = _by(amount, zoom)
+ if "zoom" in by:
+ zoom *= by["zoom"]
+ ref_ease = m["ease"]["named"] if isinstance(m["ease"], dict) else m["ease"]
+ src = {"shot": ref_shot["id"], "move": m["which"], "ease": ref_ease, "duration": round(m["duration"], 3)}
+ if k < 1:
+ src["compressed"] = round(k, 3) # the plan's shot is shorter than the reference's moves: all sped up by 1/k
+ if dropped and i == 0:
+ src["left_out"] = dropped # reference moves (seconds into its shot) this shorter shot has no room for
+ lead = float(m.get("lead_in") or 0.0) * (k if m.get("cut_off") else 1.0)
+ at = _at(t0, lo, hi, clock, our_start) if lead <= 1e-3 else f"S{t0 - lead - our_start:+.3f}s" # it began before our cut in, too
+ mv = {"at": at, "dur": f"{d:.3f}s", "by": by,
+ "ease": ease_spec(m)[0] if isinstance(m["ease"], dict) else m["ease"], "from_ref": src}
+ if m.get("cut_off"):
+ mv["past_cut"] = True # like the reference, a cut interrupts it: only part of it is on screen
+ src["seen"] = m["seen"]
+ moves.append(mv)
+ return moves
+
+
+def shot_shakes(ref_shot: dict, our_start: float, zoom: float = 1.0) -> list[dict]:
+ sh = ref_shot["move"].get("shake")
+ if not sh:
+ return []
+ # the score's shake jitters the frame position: express the measured swing as how far the picture edge moves
+ edge = {"x": W / 2, "y": W / 2, "z": W / 4, "r": 540.0}[sh["axis"]] # frame widths · W/2, log-zoom · W/4, radians · H/2
+ return [{"at": f"S+{0.0:.3f}s", "amp": round(sh["swing"] * edge / zoom, 1), "decay": 3.0,
+ "from_ref": {"shot": ref_shot["id"], "swing": sh["swing"], "axis": sh["axis"]}}]
+
+
+def cadence_from(fp: dict) -> int:
+ per = fp.get("cadence", {}).get("frames_per_drawing")
+ return 1 if not per or per < 1.75 else 2 if per < 2.5 else 3
+
+
+def from_reference(plan: dict, ref_fp: dict, bpm: float, offset: float = 0.0, fps: float = 24.0) -> dict:
+ """A whole authored score (film + shots) from the plan's shot list and the reference fingerprint."""
+ clock = Clock(bpm=bpm, offset=offset, fps=fps)
+ from perception.fingerprint import reference_for
+ timed = [s for s in plan.get("shots", []) if s.get("start_s") is not None and s.get("end_s") is not None]
+ answers = reference_for(ref_fp, [(s["id"], ref_shot_id(s.get("ref_shot")), float(s["end_s"]) - float(s["start_s"])) for s in timed])
+ cad = cadence_from(ref_fp)
+ cues = {}
+ for pk in plan.get("peaks") or []:
+ if pk.get("id") and pk.get("hit_s") is not None:
+ cues[f"{pk['id']}_hit"] = f"{float(pk['hit_s']):.3f}"
+ shots = []
+ for s in plan.get("shots", []):
+ if s.get("start_s") is None or s.get("end_s") is None:
+ continue
+ a, b = float(s["start_s"]), float(s["end_s"])
+ cam = s.get("camera") if isinstance(s.get("camera"), dict) else {}
+ frm = cam.get("from") if isinstance(cam.get("from"), dict) else {}
+ base = {k: float(frm[k]) for k in ("x", "y", "zoom") if isinstance(frm.get(k), (int, float))}
+ if isinstance(frm.get("rot"), (int, float)):
+ base["rot"] = math.radians(float(frm["rot"])) # plans write roll in degrees
+ shot = {"id": s["id"], "start": f"{a:.3f}", "end": f"{b:.3f}", # cuts stay where the plan put them
+ "ref_shot": ref_shot_id(s.get("ref_shot")), "cadence": cad, "camera": {"base": base, "moves": [], "shakes": []}}
+ rs = answers.get(s["id"])
+ if rs:
+ shot["camera"]["moves"] = shot_moves(rs, a, b, clock, base.get("zoom", 1.0))
+ shot["camera"]["shakes"] = shot_shakes(rs, a, base.get("zoom", 1.0))
+ drift = _by(rs["move"].get("drift") or {}, base.get("zoom", 1.0))
+ if drift: # the slow push / pan under the whole reference shot (its pace per second kept: scaled to our length)
+ k = (b - a) / max(1e-6, rs["end"] - rs["start"])
+ drift = {ch: (round(v ** k, 4) if ch == "zoom" else round(v * k, 4 if ch == "rot" else 1)) for ch, v in drift.items()}
+ shot["camera"]["drift"] = {"by": drift, "ease": "none", "from_ref": {"shot": rs["id"], "drift": rs["move"]["drift"]}}
+ shots.append(shot)
+ end = max((float(s["end_s"]) for s in plan.get("shots", []) if s.get("end_s") is not None), default=0.0)
+ return {"version": 1, "fps": fps, "bpm": bpm, "offset": offset, "duration": float(plan.get("duration_s") or end), "cues": cues, "shots": shots}
diff --git a/.claude/skills/video-clone/scripts/tests/conftest.py b/.claude/skills/video-clone/scripts/tests/conftest.py
new file mode 100644
index 0000000..2302cb2
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/tests/conftest.py
@@ -0,0 +1,5 @@
+import os
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path[:0] = [os.path.dirname(HERE), HERE] # scripts/ (the perception package) and tests/ (synth)
diff --git a/.claude/skills/video-clone/scripts/tests/synth.py b/.claude/skills/video-clone/scripts/tests/synth.py
new file mode 100644
index 0000000..b4d71b6
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/tests/synth.py
@@ -0,0 +1,56 @@
+"""Synthetic films with a known camera: a textured plate filmed by a virtual camera whose position, zoom and roll are
+set per frame. What perception measures can then be checked against what was rendered."""
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import cv2
+import numpy as np
+
+
+def plate(seed: int, w: int = 1800, h: int = 1100) -> np.ndarray:
+ """Texture at several scales plus coloured discs: corners everywhere, distinct colours per plate (cuts are visible)."""
+ rng = np.random.default_rng(seed)
+ img = np.zeros((h, w, 3), np.float32)
+ for s in (3, 9, 27):
+ n = cv2.resize(rng.random((h // s + 1, w // s + 1, 3)).astype(np.float32), (w, h), interpolation=cv2.INTER_CUBIC)
+ img += n / 3
+ tint = rng.random(3).astype(np.float32)
+ img = 0.55 * img + 0.45 * tint
+ for _ in range(160):
+ c = tuple(int(v) for v in rng.integers(0, 255, 3))
+ cv2.circle(img, (int(rng.integers(0, w)), int(rng.integers(0, h))), int(rng.integers(6, 40)), [v / 255 for v in c], -1, cv2.LINE_AA)
+ return np.clip(img * 255, 0, 255).astype(np.uint8)
+
+
+@dataclass
+class Cam:
+ x: float = 0.0 # camera centre offset from the plate centre, in output frame widths
+ y: float = 0.0
+ scale: float = 1.0 # > 1 = pushed in
+ roll: float = 0.0 # radians, + = clockwise camera roll (image turns counter-clockwise)
+ plate: int = 0
+
+
+def render(path: str, cams: list[Cam], fps: int = 24, size: tuple[int, int] = (640, 360)) -> None:
+ W, H = size
+ plates: dict[int, np.ndarray] = {}
+ vw = cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*"mp4v"), fps, size)
+ for c in cams:
+ P = plates.setdefault(c.plate, plate(c.plate))
+ ph, pw = P.shape[:2]
+ cx, cy = pw / 2 + c.x * W, ph / 2 + c.y * W
+ # frame = scale · R(−roll) · (plate − cam) + frame centre (camera rolls clockwise → image turns counter-clockwise)
+ a, b = c.scale * np.cos(-c.roll), c.scale * np.sin(-c.roll)
+ M = np.array([[a, -b, W / 2 - (a * cx - b * cy)], [b, a, H / 2 - (b * cx + a * cy)]], np.float32)
+ vw.write(cv2.warpAffine(P, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT))
+ vw.release()
+
+
+def move(n: int, start: int, length: int, ease, a: float, b: float) -> list[float]:
+ """Per-frame value going from a to b over [start, start + length) with `ease`, held before and after."""
+ out = []
+ for f in range(n):
+ u = min(1.0, max(0.0, (f - start) / length))
+ out.append(a + (b - a) * float(ease(np.asarray(u))))
+ return out
diff --git a/.claude/skills/video-clone/scripts/tests/test_curves.py b/.claude/skills/video-clone/scripts/tests/test_curves.py
new file mode 100644
index 0000000..7bca1ca
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/tests/test_curves.py
@@ -0,0 +1,80 @@
+"""Easing recovery on analytic trajectories: the timed fit must find start, duration, amount and shape."""
+import numpy as np
+import pytest
+
+from perception import curves
+
+FPS = 24
+
+
+def canonical(name):
+ """The ease's own curve in the same 5–95 % travel window perception compares moves on."""
+ u = np.linspace(0, 1, 2001)
+ return curves.canonical_progress(u, curves.NAMED[name](u))[2]
+
+
+def trajectory(ease, t0=0.5, dur=1.0, amount=0.3, total=3.0, noise=0.0, seed=0):
+ t = np.arange(int(total * FPS)) / FPS
+ x = amount * ease(np.clip((t - t0) / dur, 0, 1))
+ if noise:
+ x = x + np.random.default_rng(seed).normal(0, noise, len(x))
+ return t, {"x": x - x[0], "y": np.zeros_like(t), "z": np.zeros_like(t), "r": np.zeros_like(t)}
+
+
[email protected]("name", ["power3.out", "power2.inOut", "expo.out", "sine.inOut", "back.out", "none"])
+def test_named_ease_is_recovered(name):
+ t, traj = trajectory(curves.NAMED[name])
+ m = curves.describe_move(t, traj)
+ assert m["kind"] == ["move_right"]
+ assert m["ease"]["named"] == name or m["ease"]["named_rmse"] < 0.01
+ assert m["start"] == pytest.approx(0.5, abs=0.05)
+ assert m["duration"] == pytest.approx(1.0, rel=0.08)
+
+
+def test_long_tail_ease_keeps_its_tail():
+ """power3.out spends its last quarter almost still; a speed-threshold window would cut it off and call it shorter."""
+ t, traj = trajectory(curves.NAMED["power3.out"], dur=1.2)
+ m = curves.describe_move(t, traj)
+ assert m["duration"] == pytest.approx(1.2, rel=0.08)
+ truth = canonical("power3.out")
+ assert np.sqrt(np.mean((np.asarray(m["progress"]) - truth) ** 2)) < 0.03
+
+
+def test_bezier_matches_a_css_curve():
+ ease = lambda u: curves.bezier(u, 0.16, 1.0, 0.3, 1.0) # "easeOutExpo"-like CSS curve
+ t, traj = trajectory(ease, noise=0.001)
+ m = curves.describe_move(t, traj)
+ u = np.linspace(0, 1, 50)
+ assert np.max(np.abs(curves.bezier(u, *m["ease"]["bezier"]) - ease(u))) < 0.06
+
+
+def test_overshoot_is_measured():
+ t, traj = trajectory(curves.NAMED["back.out"])
+ m = curves.describe_move(t, traj)
+ assert m["ease"]["overshoot"] == pytest.approx(0.1, abs=0.03) # back.out(1.7) overshoots by ≈ 10 %
+
+
+def test_noise_does_not_change_the_answer():
+ t, traj = trajectory(curves.NAMED["power2.inOut"], noise=0.002)
+ m = curves.describe_move(t, traj)
+ assert m["ease"]["named"] in ("power2.inOut", "sine.inOut", "power1.inOut")
+ assert m["duration"] == pytest.approx(1.0, rel=0.12)
+
+
+def test_static_and_shake():
+ t = np.arange(48) / FPS
+ flat = {a: np.zeros_like(t) for a in curves.AXES}
+ assert curves.describe_move(t, flat)["kind"] == ["static"]
+ shake = dict(flat, x=0.03 * np.sin(2 * np.pi * 4 * t))
+ assert "shake" in curves.describe_move(t, shake)["kind"]
+
+
+def test_slow_there_and_back_is_moves_not_a_shake():
+ """A real reference: over twelve seconds the camera drifts down and back up a few times — several moves."""
+ t = np.arange(10 * FPS) / FPS
+ x = 0.12 * curves.NAMED["sine.inOut"](np.clip(t / 3, 0, 1)) - 0.09 * curves.NAMED["sine.inOut"](np.clip((t - 5) / 3, 0, 1))
+ traj = {"x": x, "y": np.zeros_like(t), "z": np.zeros_like(t), "r": np.zeros_like(t)}
+ m = curves.describe_shot(t, traj)
+ assert "shake" not in m["kind"] and m.get("moves") == 2, m["kind"]
+ fast = {**traj, "x": 0.03 * np.sin(2 * np.pi * 3 * t)} # 3 Hz: a shake
+ assert "shake" in curves.describe_shot(t, fast)["kind"]
diff --git a/.claude/skills/video-clone/scripts/tests/test_engine_render.py b/.claude/skills/video-clone/scripts/tests/test_engine_render.py
new file mode 100644
index 0000000..2e6bbe7
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/tests/test_engine_render.py
@@ -0,0 +1,144 @@
+"""End to end through a real engine: the engine kit (kit.js + render.mjs, unchanged) renders a scene whose camera comes
+only from the compiled Motion Score, in headless Chrome; perception measures the film; the measurement must equal the
+render-free prediction. Skipped where Chrome or puppeteer-core is not available (CI).
+
+This is the test that found the roll/translation coupling missing from predict.py and the rest-before-a-move that
+perception took for a held drawing."""
+import glob
+import json
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from perception import distance, fingerprint
+from score import model, predict
+from score.cli import compile_js
+from score.runtime import Score
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+REPO = os.path.abspath(os.path.join(HERE, "..", "..", "..", "..", ".."))
+KIT = os.path.join(REPO, ".claude", "skills", "video-clone", "assets", "engine-kit")
+CHROMES = [os.environ.get("CHROME_PATH"), r"C:/Program Files/Google/Chrome/Application/chrome.exe",
+ r"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", "/usr/bin/google-chrome", "/usr/bin/chromium"]
+
+
+def _puppeteer() -> str | None:
+ env = os.environ.get("REELMIMIC_NODE_MODULES")
+ if env and os.path.isdir(os.path.join(env, "puppeteer-core")):
+ return env
+ found = glob.glob(os.path.join(REPO, ".claude", "skills", "*", "template", "node_modules", "puppeteer-core")) + \
+ glob.glob(os.path.join(REPO, "projects", "*", "build", "node_modules", "puppeteer-core"))
+ return os.path.dirname(found[0]) if found else None
+
+
+NODE_MODULES = _puppeteer()
+CHROME = next((c for c in CHROMES if c and os.path.exists(c)), None)
+pytestmark = pytest.mark.skipif(not (shutil.which("node") and NODE_MODULES and CHROME), reason="needs node, Chrome and puppeteer-core")
+
+FILM = {"version": 1, "fps": 24, "bpm": 120, "offset": 0, "duration": 4, "cues": {"hit": "B6"}}
+SHOTS = [
+ {"id": "S1", "start": "0", "end": "B4", "camera": {"moves": [
+ {"at": "S+3f", "dur": "0.75s", "by": {"zoom": 1.35}, "ease": "power3.out"},
+ {"at": "B2", "dur": "0.8s", "by": {"x": 380}, "ease": {"bezier": [0.4, 0, 0.2, 1]}}]}},
+ {"id": "S2", "start": "B4", "end": "4", "camera": {"base": {"x": 1100, "y": 500, "zoom": 1.2}, "moves": [
+ {"at": "S+2f", "to": {"rot": 0.18}, "ease": {"spring": {"omega": 9, "zeta": 0.45}}},
+ {"at": "B6", "dur": "0.5s", "by": {"y": 160}, "ease": "sine.inOut"}], "shakes": [{"at": "hit", "amp": 10, "decay": 7}]}},
+]
+SCENE = """
+function world(seed) {
+ const r = rnd('world' + seed);
+ G.fillStyle = seed ? '#1d2a44' : '#3b2a1e'; G.fillRect(-1500, -1500, W + 3000, H + 3000);
+ for (let i = 0; i < 900; i++) {
+ const x = -1200 + r() * (W + 2400), y = -1200 + r() * (H + 2400), s = 6 + r() * 46;
+ G.fillStyle = `hsl(${Math.floor(r() * 360)},${50 + r() * 40}%,${35 + r() * 45}%)`;
+ G.beginPath(); if (r() < .5) G.arc(x, y, s, 0, TAU); else G.rect(x, y, s * 1.6, s); G.fill();
+ }
+}
+shots([
+ [0, (t) => { const c = Score.cam('S1', t); camBegin(c.x, c.y, c.zoom, c.rot); world(0); }],
+ [2, (t) => { const c = Score.cam('S2', t); camBegin(c.x, c.y, c.zoom, c.rot); world(1); }],
+]);
+"""
+
+
+def _link(src: str, dst: str):
+ if sys.platform == "win32":
+ subprocess.run(["cmd", "/c", "mklink", "/J", dst, src], check=True, capture_output=True)
+ else:
+ os.symlink(src, dst)
+
+
+def test_engine_render_matches_prediction(tmp_path):
+ d = tmp_path / "proj"
+ (d / "src" / "scenes").mkdir(parents=True)
+ shutil.copy(os.path.join(KIT, "render.mjs"), d)
+ shutil.copy(os.path.join(KIT, "package.json"), d)
+ shutil.copy(os.path.join(KIT, "kit.js"), d / "src" / "kit.js")
+ html = Path(KIT, "studio.html").read_text(encoding="utf-8")
+ html = html.replace("<!-- ENGINE-LIBS -->", '<script src="src/score.js"></script>').replace("<!-- SCENES -->", '<script src="src/scenes/world.js"></script>')
+ (d / "studio.html").write_text(html, encoding="utf-8")
+ (d / "src" / "config.js").write_text("const PROJECT = { duration: 4, bpm: 120, offset: 0, fps: 24 };", encoding="utf-8")
+ (d / "src" / "scenes" / "world.js").write_text(SCENE, encoding="utf-8")
+ resolved, diag = model.resolve_score({**FILM, "shots": SHOTS})
+ assert diag.ok, diag.errors
+ (d / "src" / "score.js").write_text(compile_js(resolved), encoding="utf-8")
+ _link(NODE_MODULES, str(d / "node_modules"))
+ try:
+ subprocess.run(["node", "render.mjs", "--clip", "--out=out/video.mp4", f"--chrome={CHROME}"], cwd=d, check=True, capture_output=True, timeout=300)
+ meas = fingerprint.extract(str(d / "out" / "video.mp4"), shots=[{"id": "S1", "start_s": 0, "end_s": 2}, {"id": "S2", "start_s": 2, "end_s": 4}])
+ finally:
+ if sys.platform == "win32":
+ subprocess.run(["cmd", "/c", "rmdir", str(d / "node_modules")], capture_output=True) # the junction, not its target
+ pred = {p["id"]: p for p in predict.predicted_shots(Score(resolved))}
+ for s in meas["shots"]:
+ p = pred[s["id"]]
+ assert set(s["move"]["kind"]) == set(p["move"]["kind"]), (s["id"], s["move"]["kind"], p["move"]["kind"])
+ for ax in ("x", "y", "z", "r"):
+ assert s["move"]["amount"][ax] == pytest.approx(p["move"]["amount"][ax], abs=0.004), (s["id"], ax)
+ score, _, findings = distance.camera_pair(s, p)
+ assert score > 95, (s["id"], score, json.dumps(findings))
+
+
+def test_svg_camera_is_the_canvas_camera(tmp_path):
+ """Score.svgCam (HyperFrames) and camBegin(...Score.cam) (canvas engines) must put every world point at the same
+ screen position: checked in Chrome through the SVG's own getScreenCTM against kit.js toScreen."""
+ resolved, _ = model.resolve_score({**FILM, "shots": SHOTS})
+ page = tmp_path / "svg.html"
+ page.write_text(f"""<!doctype html><html><body style="margin:0">
+<svg id="s" width="1920" height="1080" viewBox="0 0 1920 1080"><g id="cam"><circle id="p" r="1"/></g></svg>
+<script>const W = 1920, H = 1080;</script>
+<script>{Path(KIT, 'kit.js').read_text(encoding='utf-8').split('// ---------- shots ----------')[0].replace('const W = 1920, H = 1080, TAU', 'const TAU').replace('const DUR = PROJECT.duration, BPM = PROJECT.bpm || 120, BEAT = 60 / BPM, OFF = PROJECT.offset || 0;', '').replace('const FPS = PROJECT.fps || 24;', '')}</script>
+<script>{compile_js(resolved)}</script>
+<script>
+function toScreenCam(x, y, c) {{ const dx = (x - c.x) * c.zoom, dy = (y - c.y) * c.zoom, co = Math.cos(c.rot), si = Math.sin(c.rot); return [W / 2 + dx * co - dy * si, H / 2 + dx * si + dy * co]; }}
+window.check = () => {{
+ const out = [], g = document.getElementById('cam'), pt = document.getElementById('s').createSVGPoint();
+ for (const [id, t] of [['S1', 0.3], ['S1', 1.4], ['S2', 2.4], ['S2', 3.2], ['S2', 3.9]]) {{
+ g.setAttribute('transform', Score.svgCam(id, t));
+ const m = g.getCTM(), c = Score.cam(id, t);
+ for (const [x, y] of [[0, 0], [960, 540], [1700, 200], [300, 900]]) {{
+ pt.x = x; pt.y = y; const p = pt.matrixTransform(m), q = toScreenCam(x, y, c);
+ out.push(Math.hypot(p.x - q[0], p.y - q[1]));
+ }}
+ }}
+ return out;
+}};
+</script></body></html>""", encoding="utf-8")
+ js = tmp_path / "run.mjs"
+ js.write_text(f"""import puppeteer from 'puppeteer-core';
+const b = await puppeteer.launch({{ executablePath: {json.dumps(CHROME)}, headless: true }});
+const p = await b.newPage(); await p.goto({json.dumps(page.as_uri())});
+console.log(JSON.stringify(await p.evaluate(() => window.check()))); await b.close();""", encoding="utf-8")
+ _link(NODE_MODULES, str(tmp_path / "node_modules"))
+ try:
+ r = subprocess.run(["node", str(js)], cwd=tmp_path, capture_output=True, text=True, timeout=120)
+ finally:
+ if sys.platform == "win32":
+ subprocess.run(["cmd", "/c", "rmdir", str(tmp_path / "node_modules")], capture_output=True)
+ assert r.returncode == 0, r.stderr
+ err = json.loads(r.stdout.strip().splitlines()[-1])
+ assert max(err) < 0.05, err # pixels
diff --git a/.claude/skills/video-clone/scripts/tests/test_fingerprint.py b/.claude/skills/video-clone/scripts/tests/test_fingerprint.py
new file mode 100644
index 0000000..6d8899c
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/tests/test_fingerprint.py
@@ -0,0 +1,246 @@
+"""End to end on rendered video: a known push-in, a cut, a known pan — perception must measure what was filmed."""
+import json
+import math
+
+import numpy as np
+import pytest
+
+import synth
+from perception import curves, distance, fingerprint
+
+FPS = 24
+
+
+def canonical(name):
+ """The ease's own curve in the same 5–95 % travel window perception compares moves on."""
+ u = np.linspace(0, 1, 2001)
+ return curves.canonical_progress(u, curves.NAMED[name](u))[2]
+N = 48 # frames per shot
+
+
[email protected](scope="module")
+def film(tmp_path_factory):
+ """Shot 1: push in 1.0 → 1.3 with power3.out over frames 6–30. Shot 2 (another plate): pan right 0.25 frame widths
+ with power2.inOut over frames 6–30."""
+ p3, p2 = curves.NAMED["power3.out"], curves.NAMED["power2.inOut"]
+ zoom = synth.move(N, 6, 24, p3, 1.0, 1.3)
+ pan = synth.move(N, 6, 24, p2, 0.0, 0.25)
+ cams = [synth.Cam(scale=z, plate=0) for z in zoom] + [synth.Cam(x=x, plate=1) for x in pan]
+ path = str(tmp_path_factory.mktemp("synth") / "film.mp4")
+ synth.render(path, cams, FPS)
+ return path
+
+
[email protected](scope="module")
+def fp(film):
+ return fingerprint.extract(film, fps=FPS)
+
+
+def test_cut_is_detected(fp):
+ assert fp["cuts"] == [pytest.approx(2.0, abs=1 / FPS)]
+ assert len(fp["shots"]) == 2
+
+
+def test_push_in_is_measured(fp):
+ m = fp["shots"][0]["move"]
+ assert m["kind"] == ["push_in"]
+ assert m["amount"]["z"] == pytest.approx(math.log(1.3), rel=0.05)
+ assert m["start"] == pytest.approx(6 / FPS, abs=0.06)
+ assert m["duration"] == pytest.approx(1.0, rel=0.12)
+ truth = canonical("power3.out")
+ assert np.sqrt(np.mean((np.asarray(m["progress"]) - truth) ** 2)) < 0.05
+
+
+def test_pan_is_measured(fp):
+ m = fp["shots"][1]["move"]
+ assert m["kind"] == ["move_right"]
+ assert m["amount"]["x"] == pytest.approx(0.25, rel=0.06)
+ truth = canonical("power2.inOut")
+ assert np.sqrt(np.mean((np.asarray(m["progress"]) - truth) ** 2)) < 0.05
+
+
+def test_given_shots_keep_their_ids(film):
+ fp = fingerprint.extract(film, fps=FPS, shots=[{"id": "s1", "start_s": 0, "end_s": 2}, {"id": "s2", "start_s": 2, "end_s": 4}])
+ assert [s["id"] for s in fp["shots"]] == ["s1", "s2"]
+
+
+def test_roll_sign(tmp_path):
+ path = str(tmp_path / "roll.mp4")
+ synth.render(path, [synth.Cam(roll=r) for r in synth.move(36, 4, 24, curves.NAMED["sine.inOut"], 0.0, 0.2)], FPS)
+ m = fingerprint.extract(path, fps=FPS)["shots"][0]["move"]
+ assert m["kind"] == ["roll_cw"] and m["amount"]["r"] == pytest.approx(0.2, rel=0.08)
+
+
+def test_same_film_scores_high_and_slower_move_is_flagged(film, fp, tmp_path):
+ same = distance.style_distance(fp, fp, pairs=[{"id": 1, "ref_shot": 1}, {"id": 2, "ref_shot": 2}])
+ assert same["components"]["camera"]["score"] > 95 and not [f for f in same["findings"] if f["component"] == "camera"]
+ # the same push, twice as slow and with a linear ease
+ slow = synth.move(N, 6, 40, curves.NAMED["none"], 1.0, 1.3)
+ path = str(tmp_path / "slow.mp4")
+ synth.render(path, [synth.Cam(scale=z) for z in slow], FPS)
+ ours = fingerprint.extract(path, fps=FPS)
+ sd = distance.style_distance(fp, ours, pairs=[{"id": 1, "ref_shot": 1}], ref_window=(0, 2))
+ text = " ".join(f["text"] for f in sd["findings"] if f["component"] == "camera")
+ assert "slower" in text and "easing differs" in text
+ assert sd["shots"][0]["camera"]["score"] < 60
+
+
+def test_cadence_on_twos_vs_ones(tmp_path):
+ """The same pan, once drawn every frame and once with every drawing held for two frames."""
+ pan = synth.move(48, 4, 40, curves.NAMED["none"], 0.0, 0.3)
+ ones, twos = str(tmp_path / "ones.mp4"), str(tmp_path / "twos.mp4")
+ synth.render(ones, [synth.Cam(x=x) for x in pan], FPS)
+ synth.render(twos, [synth.Cam(x=pan[f - f % 2]) for f in range(48)], FPS)
+ c1, c2 = fingerprint.extract(ones, fps=FPS)["cadence"], fingerprint.extract(twos, fps=FPS)["cadence"]
+ assert c1["label"] == "on ones" and c2["label"] == "on twos"
+ assert c2["drawings_per_second"] == pytest.approx(12, abs=1.5)
+ # holds share out the motion: the trajectory is the same, the speed has no comb
+ m = fingerprint.extract(twos, fps=FPS)["shots"][0]["move"]
+ assert m["amount"]["x"] == pytest.approx(0.3, rel=0.06)
+
+
+def test_shot_list_one_frame_off_the_cut(film):
+ """A plan whose cut is a frame late must not turn the cut into a huge camera move."""
+ fp = fingerprint.extract(film, fps=FPS, shots=[{"id": "a", "start_s": 0, "end_s": 2 + 1 / FPS}, {"id": "b", "start_s": 2 + 1 / FPS, "end_s": 4}])
+ assert fp["cuts"] == [pytest.approx(2.0, abs=0.01)] # snapped to the real cut
+ assert fp["shots"][1]["move"]["kind"] == ["move_right"]
+ assert fp["shots"][1]["move"]["amount"]["x"] == pytest.approx(0.25, rel=0.06)
+
+
+def test_unrelated_frames_are_not_a_camera_move():
+ a, b = synth.plate(1)[:360, :640], synth.plate(2)[:360, :640]
+ import cv2
+ from perception import camera
+ step = camera.estimate(cv2.cvtColor(a, cv2.COLOR_BGR2GRAY), cv2.cvtColor(b, cv2.COLOR_BGR2GRAY))
+ assert not step.ok
+
+
+def test_two_moves_in_one_shot(tmp_path):
+ """Push in, rest, then pan: two moves, each with its own timing."""
+ n = 72
+ zoom = synth.move(n, 4, 18, curves.NAMED["power2.out"], 1.0, 1.25)
+ pan = synth.move(n, 40, 24, curves.NAMED["sine.inOut"], 0.0, 0.3)
+ path = str(tmp_path / "two.mp4")
+ synth.render(path, [synth.Cam(scale=z, x=x) for z, x in zip(zoom, pan)], FPS)
+ m = fingerprint.extract(path, fps=FPS)["shots"][0]["move"]
+ assert m["moves"] == 2 and set(m["kind"]) == {"push_in", "move_right"}
+ other = m["other_moves"][0]
+ starts = sorted([m["start"], other["start"]])
+ assert starts[0] == pytest.approx(4 / FPS, abs=0.08) and starts[1] == pytest.approx(40 / FPS, abs=0.08)
+
+
+def test_static_overlay_does_not_hold_the_camera(tmp_path):
+ """A screen recording: the pan happens under a UI strip that never moves. The strip must not vote "no motion"."""
+ import cv2
+ pan = synth.move(48, 4, 36, curves.NAMED["sine.inOut"], 0.0, 0.25)
+ raw, rec = str(tmp_path / "raw.mp4"), str(tmp_path / "rec.mp4")
+ synth.render(raw, [synth.Cam(x=x) for x in pan], FPS)
+ ui = synth.plate(9)[:360, :200]
+ cap, vw = cv2.VideoCapture(raw), cv2.VideoWriter(rec, cv2.VideoWriter_fourcc(*"mp4v"), FPS, (640, 360))
+ while True:
+ ok, f = cap.read()
+ if not ok:
+ break
+ f[:, 440:] = ui # a textured, rich, perfectly still overlay over the right third
+ vw.write(f)
+ vw.release()
+ fp = fingerprint.extract(rec, fps=FPS)
+ assert fp["static_overlay"] > 0.2
+ assert fp["shots"][0]["move"]["amount"]["x"] == pytest.approx(0.25, rel=0.1)
+
+
+def test_a_rest_before_a_move_is_not_a_held_drawing():
+ """Three still frames at the start, then a push: the push must start where it starts (found by rendering through
+ the real engine — the rest was taken for limited animation and the first step spread back over it)."""
+ diff = np.r_[0.0, 0.0, 0.0, 0.0, 0.05, 0.04, 0.0, 0.03, 0.03, 0.0, 0.0, 0.0, 0.0, 0.0, 0.03]
+ hold = fingerprint.held_frames(diff, [])
+ assert not hold[1:4].any() # the opening rest
+ assert hold[6] # a single still frame inside motion: a held drawing
+ assert not hold[9:14].any() # five still frames: the scene resting, not a hold
+ assert not fingerprint.held_frames(np.r_[0.0, 0.03, 0.2, 0.0, 0.03], [2])[3] # a still frame right after a cut
+
+
+def _flat_scene(path, frames, fps=FPS, size=(640, 360), sparkles=0):
+ """A soft vertical gradient (optionally with small sparkles) and a textured character disc; frames: list of
+ (camera_dx_px, char_dx_px, char_rot_deg)."""
+ import cv2
+ W, H = size
+ big_w = W + 400
+ bg = np.zeros((H, big_w, 3), np.uint8)
+ for y in range(H):
+ bg[y] = (200 - y // 8, 190 - y // 10, 235 - y // 12)
+ rng = np.random.default_rng(3)
+ for _ in range(sparkles):
+ cv2.circle(bg, (int(rng.integers(0, big_w)), int(rng.integers(0, H))), 2, (255, 255, 255), -1)
+ char = synth.plate(5, 220, 220)
+ mask = np.zeros((220, 220), np.uint8)
+ cv2.circle(mask, (110, 110), 105, 255, -1)
+ vw = cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*"mp4v"), fps, size)
+ for cam_dx, char_dx, rot in frames:
+ f = bg[:, 200 + int(round(cam_dx)):200 + int(round(cam_dx)) + W].copy()
+ R = cv2.getRotationMatrix2D((110, 110), rot, 1.0)
+ c = cv2.warpAffine(char, R, (220, 220), borderMode=cv2.BORDER_REFLECT)
+ x0, y0 = int(W / 2 - 110 + char_dx - cam_dx), 70
+ roi = f[y0:y0 + 220, x0:x0 + 220]
+ roi[mask > 0] = c[mask > 0]
+ vw.write(f)
+ vw.release()
+
+
+def test_a_character_moving_over_a_plain_background_is_not_a_camera_move(tmp_path):
+ """Real film: a character's head tilt over a flat gradient was read as a 2.5° camera roll."""
+ path = str(tmp_path / "flat.mp4")
+ tilt = synth.move(48, 6, 30, curves.NAMED["sine.inOut"], 0.0, 9.0)
+ _flat_scene(path, [(0, 25 * k / 47, r) for k, r in enumerate(tilt)])
+ fp = fingerprint.extract(path, fps=FPS)
+ m = fp["shots"][0]["move"]
+ assert m["kind"] == ["static"], m
+ assert fp["shots"][0]["local_motion"] > 0.0005
+
+
+def test_a_pan_over_a_plain_background_with_some_detail_is_still_found(tmp_path):
+ """The other side: the camera really pans; a few sparkles in the background are the evidence."""
+ path = str(tmp_path / "pan.mp4")
+ pan = synth.move(48, 4, 36, curves.NAMED["sine.inOut"], 0.0, 160.0)
+ _flat_scene(path, [(p, p, 0.0) for p in pan], sparkles=60)
+ m = fingerprint.extract(path, fps=FPS)["shots"][0]["move"]
+ assert m["kind"] == ["move_right"], m
+ assert m["amount"]["x"] == pytest.approx(160 / 640, rel=0.15)
+
+
+def test_a_push_on_a_frame_filling_subject_is_not_overruled_by_a_caption(tmp_path):
+ """Real film: a bowl and two arms filling the frame, pushed in 26 %, with a burned-in caption that never moves.
+ The caption's corners must not turn the push into a still camera."""
+ import cv2
+ zoom = synth.move(48, 4, 40, curves.NAMED["sine.inOut"], 1.0, 1.3)
+ raw, out = str(tmp_path / "raw.mp4"), str(tmp_path / "cap.mp4")
+ synth.render(raw, [synth.Cam(scale=z) for z in zoom], FPS)
+ cap, vw = cv2.VideoCapture(raw), cv2.VideoWriter(out, cv2.VideoWriter_fourcc(*"mp4v"), FPS, (640, 360))
+ while True:
+ ok, f = cap.read()
+ if not ok:
+ break
+ cv2.rectangle(f, (150, 312), (490, 344), (250, 250, 250), -1)
+ cv2.putText(f, "EGGS ARE EASY. SHELLS: MORE", (160, 336), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (20, 20, 20), 2, cv2.LINE_AA)
+ vw.write(f)
+ vw.release()
+ m = fingerprint.extract(out, fps=FPS)["shots"][0]["move"]
+ assert "push_in" in m["kind"], m
+ assert m["amount"]["z"] == pytest.approx(np.log(1.3), rel=0.15)
+
+
+def test_plan_check_flags_slow_plans_and_reports_squeezed_shots(tmp_path, monkeypatch):
+ from perception import cli
+ ref = {"start": 0.0, "end": 20.0, "frames": 480, "fps": 24, "cuts": [5.0, 10.0, 15.0],
+ "shots": [{"id": i + 1, "start": 5.0 * i, "end": 5.0 * (i + 1), "move": {"kind": ["push_in"], "amount": {"x": 0, "y": 0, "z": 0.1, "r": 0},
+ "duration": 4.0}} for i in range(4)],
+ "series": {"camera": {k: [0.0] * 480 for k in ("dx", "dy", "dz", "dr")}, "tracked": [1] * 480, "local": [0.0] * 480,
+ "diff": [0.0] * 480, "lab": [[0.5] * 480] * 3, "tension": [0.0] * 480},
+ "beats": [], "peaks": [], "descriptors": {"fps": 2, "grid": [8, 4], "data": []}}
+ monkeypatch.setattr(cli, "ensure_reference", lambda P: ref)
+ (tmp_path / "plan.json").write_text(json.dumps({"shots": [{"id": f"S{i}", "start_s": 1.0 * i, "end_s": 1.0 * (i + 1), "ref_shot": i % 4 + 1} for i in range(20)]}))
+ r = cli.plan_check(str(tmp_path))
+ assert r["ok"] and r["ratio"] > 3 # 19 cuts in 20 s against 3: faster is the brief's call …
+ assert r["squeezed"] and r["squeezed"][0]["ref_moving_s"] == 4.0 # … but 1 s shots for 4 s pushes are reported
+ (tmp_path / "plan.json").write_text(json.dumps({"shots": [{"id": "S1", "start_s": 0.0, "end_s": 20.0, "ref_shot": 1}]}))
+ assert not cli.plan_check(str(tmp_path))["ok"] # one shot for a take the reference cuts three times: too slow
diff --git a/.claude/skills/video-clone/scripts/tests/test_optimize.py b/.claude/skills/video-clone/scripts/tests/test_optimize.py
new file mode 100644
index 0000000..24a9165
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/tests/test_optimize.py
@@ -0,0 +1,112 @@
+"""Stage 3: CMA-ES itself, the search space round trip, the one-sided peak cost, and the optimizer recovering a
+reference camera from a deliberately wrong score — render-free."""
+import json
+import os
+
+import numpy as np
+import pytest
+
+import synth
+from optimize import cmaes
+from optimize.objective import peak_cost
+from optimize.run import optimize_project
+from optimize.space import Space
+from perception import curves, fingerprint
+from score import model
+
+FPS = 24
+
+
+# ---------- CMA-ES ----------
+def test_sphere_and_rosenbrock():
+ sphere = lambda x: float(np.sum((x - 0.3) ** 2))
+ r = cmaes.minimize(sphere, np.full(6, 0.8), sigma0=0.3, budget=1500, seed=1)
+ assert r.f < 1e-6 and np.allclose(r.x, 0.3, atol=1e-3)
+ rosen = lambda x: float(sum(100 * (4 * x[1:] - 2 - (4 * x[:-1] - 2) ** 2) ** 2 + (1 - (4 * x[:-1] - 2)) ** 2)) # min at x = 0.75
+ r = cmaes.minimize(rosen, np.full(4, 0.2), sigma0=0.3, budget=6000, seed=2)
+ assert r.f < 1e-4, r.f
+ assert r.history == sorted(r.history, reverse=True) # best-so-far never gets worse
+
+
+def test_optimum_outside_the_box_ends_on_its_edge_and_runs_repeat():
+ f = lambda x: float(np.sum((x - np.array([1.4, -0.3, 0.5])) ** 2))
+ a = cmaes.minimize(f, np.full(3, 0.5), budget=900, seed=7)
+ b = cmaes.minimize(f, np.full(3, 0.5), budget=900, seed=7)
+ assert np.allclose(a.x, [1, 0, 0.5], atol=1e-3)
+ assert np.array_equal(a.x, b.x) and a.f == b.f
+
+
+# ---------- the search space ----------
+AUTH = {"version": 1, "fps": FPS, "bpm": 120, "offset": 0.0, "duration": 4, "cues": {},
+ "shots": [{"id": "S1", "start": 0, "end": 4, "ref_shot": 1, "camera": {"moves": [
+ {"at": "B1", "dur": "1b", "by": {"zoom": 1.3}, "ease": "power3.out"},
+ {"at": "B4", "dur": "0.8s", "by": {"x": 200}, "ease": {"spring": {"omega": 12, "zeta": 0.6}}}],
+ "shakes": [{"at": "B6", "amp": 12, "decay": 8}]}}]}
+
+
+def test_the_starting_point_writes_back_unchanged():
+ r, d = model.resolve_score(AUTH)
+ assert d.ok
+ sp = Space(AUTH, r, ["S1"])
+ kinds = [p.kind for p in sp.params]
+ assert kinds == ["at", "dur", "bez0", "bez1", "bez2", "bez3", "at", "omega", "zeta", "amp", "decay"]
+ assert sp.apply(sp.u0) == AUTH and sp.changes(sp.u0) == []
+
+
+def test_a_changed_point_records_what_it_was_and_keeps_amounts():
+ r, _ = model.resolve_score(AUTH)
+ sp = Space(AUTH, r, ["S1"])
+ u = sp.u0.copy()
+ u[0] = 1.0 # start as late as allowed
+ u[1] = 1.0 # twice as long
+ out = sp.apply(u)["shots"][0]["camera"]["moves"][0]
+ assert out["tuned"]["from"]["at"] == "B1" and out["by"] == {"zoom": 1.3}
+ assert out["dur"] == "1.0000s"
+ rr, d = model.resolve_score(sp.apply(u))
+ assert d.ok and rr["shots"][0]["camera"]["move_times"][0][0] == pytest.approx(0.75, abs=1e-3)
+
+
+def test_peak_cost_is_one_sided():
+ ref = {"breath_depth": 0.3, "rise_frames": 3, "prominence": 0.4, "hold_s": 0.5}
+ n = 6 * FPS
+ T = np.full(n, 0.2)
+ T[FPS:3 * FPS - 12] = 0.5 # a build …
+ T[3 * FPS - 12:3 * FPS] = 0.05 # … a deep breath
+ T[3 * FPS:3 * FPS + FPS] = 1.0 # hits on one frame, holds a second
+ T[3 * FPS + FPS:] = 0.2
+ c, q = peak_cost(T, FPS, 3.0, ref)
+ assert q is not None and c == pytest.approx(0.0, abs=0.5) # better than the reference everywhere: free
+ flat = np.full(n, 0.2)
+ assert peak_cost(flat, FPS, 3.0, ref)[0] == 40.0
+
+
+# ---------- the optimizer recovers the reference camera ----------
+def test_optimizer_recovers_a_reference_move(tmp_path):
+ """Reference: an expo.out push in 0.5 s starting at 0.2 s. The author wrote the right push but slow, late and
+ linear. Optimising (render-free) must bring timing and shape back without touching the amount."""
+ zoom = synth.move(72, 5, 12, curves.NAMED["expo.out"], 1.0, 1.3)
+ ref_path = str(tmp_path / "ref.mp4")
+ synth.render(ref_path, [synth.Cam(scale=z) for z in zoom], FPS)
+ P = tmp_path / "proj"
+ (P / "analysis").mkdir(parents=True)
+ (P / "analysis" / "fingerprint.json").write_text(json.dumps(fingerprint.extract(ref_path, fps=FPS)))
+ (P / "plan.json").write_text(json.dumps({"shots": [{"id": "S1", "start_s": 0, "end_s": 3, "ref_shot": 1}]}))
+ wrong = {"version": 1, "fps": FPS, "bpm": 120, "offset": 0, "duration": 3, "cues": {}, "shots": [
+ {"id": "S1", "start": "0", "end": "3", "ref_shot": 1, "camera": {"moves": [{"at": "S+0.4s", "dur": "1.1s", "by": {"zoom": 1.3}, "ease": "none"}]}}]}
+ sdir = P / "build" / "score"
+ os.makedirs(sdir / "shots")
+ (sdir / "film.json").write_text(json.dumps({k: v for k, v in wrong.items() if k != "shots"}))
+ (sdir / "shots" / "S1.json").write_text(json.dumps(wrong["shots"][0]))
+ rep = optimize_project(str(P), str(sdir), budget=300, log=lambda *_: None)
+ g = rep["groups"][0]
+ assert g["kept"] and g["after"]["camera"]["S1"] < 0.35 * g["before"]["camera"]["S1"], g
+ mv = rep["score"]["shots"][0]["camera"]["moves"][0]
+ assert mv["by"] == {"zoom": 1.3} # framing intent untouched
+ # the motion itself (5–95 % of the travel) now takes about as long as the reference's; the model's own duration may
+ # stay longer with a curve that starts fast — that is the same motion
+ from score import predict
+ from score.runtime import Score
+ r, d = model.resolve_score(rep["score"])
+ ref_span = json.loads((P / "analysis" / "fingerprint.json").read_text())["shots"][0]["move"]["span90"]
+ ours = predict.predicted_shots(Score(r))[0]["move"]
+ assert ours["span90"] == pytest.approx(ref_span, rel=0.3), (ours["span90"], ref_span)
diff --git a/.claude/skills/video-clone/scripts/tests/test_score.py b/.claude/skills/video-clone/scripts/tests/test_score.py
new file mode 100644
index 0000000..4480c93
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/tests/test_score.py
@@ -0,0 +1,232 @@
+"""Motion Score: time expressions, resolving, the JS/Python runtimes agreeing, prediction matching measurement, and
+motion transfer closing the loop (reference → measured → score → predicted ≈ reference)."""
+import json
+import math
+import shutil
+import subprocess
+
+import numpy as np
+import pytest
+
+import synth
+from perception import curves, fingerprint
+from score import model, predict, transfer
+from score.cli import RUNTIME_JS
+from score.runtime import Score
+from score.timeexpr import Clock, TimeError, resolve
+
+FPS = 24
+CLOCK = Clock(bpm=120, offset=0.1, fps=FPS) # a beat is 0.5 s; beat n at 0.1 + n/2
+
+
+# ---------- time expressions ----------
[email protected]("expr, want", [("B4", 2.1), ("B4-2f", 2.1 - 2 / 24), ("B4+1b", 2.6), ("3.95", 3.95), ("3.95s", 3.95),
+ ("drop+0.5s", 7.5), ("S+1b", 10.5), ("E-1f", 12 - 1 / 24)])
+def test_instants(expr, want):
+ assert resolve(expr, CLOCK, {"drop": 7.0}, (10.0, 12.0)) == pytest.approx(want)
+
+
+def test_lengths_and_errors():
+ assert resolve("1b-2f", CLOCK, length=True) == pytest.approx(0.5 - 2 / 24)
+ for bad, kw in [("B4+B5", {}), ("2f", {}), ("B4", {"length": True}), ("nope", {}), ("S", {}), ("B4 2f", {})]:
+ with pytest.raises(TimeError):
+ resolve(bad, CLOCK, {"drop": 7.0}, **kw)
+
+
+# ---------- resolving ----------
+def film(*shots, cues=None):
+ return {"version": 1, "fps": FPS, "bpm": 120, "offset": 0.1, "duration": 10, "cues": cues or {}, "shots": list(shots)}
+
+
+def test_moves_chain_and_zoom_multiplies():
+ r, d = model.resolve_score(film({"id": "A", "start": 0, "end": 4, "camera": {"base": {"zoom": 1.2}, "moves": [
+ {"at": "S", "dur": "1b", "by": {"zoom": 1.5, "x": 100}, "ease": "power3.out"},
+ {"at": "B2", "dur": "4f", "to": {"x": 0}, "ease": "hold"}]}}))
+ assert d.ok, d.errors
+ ch = r["shots"][0]["camera"]["channels"]
+ assert ch["zoom"][0]["v0"] == 1.2 and ch["zoom"][0]["v1"] == pytest.approx(1.8)
+ assert ch["x"][1]["v0"] == pytest.approx(1060) and ch["x"][1]["v1"] == 0
+ s = Score(r)
+ assert s.cam("A", 0.25)["zoom"] == pytest.approx(1.2 + 0.6 * curves.NAMED["power3.out"](np.asarray(0.5)))
+ assert s.cam("A", 1.0)["x"] == pytest.approx(1060) and s.cam("A", 1.1 + 3 / 24)["x"] == pytest.approx(1060) and s.cam("A", 1.3)["x"] == 0
+
+
+def test_problems_are_reported_with_their_place():
+ _, d = model.resolve_score(film({"id": "A", "start": 0, "end": 2, "camera": {"moves": [
+ {"at": "S", "dur": "1s", "to": {"x": 1}},
+ {"at": "S+0.5s", "dur": "1s", "to": {"x": 2}}, # x still moving
+ {"at": "S", "dur": "1s", "to": {"pan": 2}}, # no such channel
+ {"at": "S", "to": {"y": 2}}, # no length
+ {"at": "S", "dur": "1s", "to": {"y": 2}, "ease": "wobbly"}]}}))
+ text = "\n".join(d.errors)
+ assert "A.camera.moves[1]: x is still moving" in text
+ assert "moves[2].to.pan: unknown channel" in text
+ assert "moves[3]: needs \"dur\" or \"until\"" in text
+ assert "moves[4].ease: unknown ease 'wobbly'" in text
+
+
+def test_a_spring_can_be_interrupted_and_gaps_warn():
+ r, d = model.resolve_score(film({"id": "A", "start": 0, "end": 2, "camera": {"moves": [
+ {"at": "S", "to": {"zoom": 1.3}, "ease": {"spring": {"omega": 14, "zeta": 0.3}}},
+ {"at": "S+0.4s", "dur": "0.5s", "to": {"zoom": 1.0}}]}}, {"id": "B", "start": 2.5, "end": 3}))
+ assert d.ok, d.errors
+ assert any("gap of 0.500s after A" in w for w in d.warnings)
+ z = r["shots"][0]["camera"]["channels"]["zoom"]
+ assert z[1]["v0"] == pytest.approx(1 + 0.3 * curves.spring(np.asarray(0.4), 14, 0.3)) # starts from where the spring was
+
+
+# ---------- the two runtimes agree ----------
+EVERYTHING = film(
+ {"id": "A", "start": "B0", "end": "B6", "cadence": 2, "camera": {"base": {"x": 900, "rot": 0.02}, "moves": [
+ {"at": "S", "dur": "1b", "by": {"x": 120}, "ease": "expo.out"},
+ {"at": "B1", "dur": "0.7s", "to": {"zoom": 1.4}, "ease": {"bezier": [0.16, 1, 0.3, 1]}},
+ {"at": "B3", "to": {"rot": -0.05}, "ease": {"spring": {"omega": 20, "zeta": 0.35}}},
+ {"at": "B2", "dur": "3f", "by": {"y": -40}, "ease": "back.out(2.2)"},
+ {"at": "B4", "dur": "1b", "by": {"y": 40}, "ease": "sine.inOut"}],
+ "shakes": [{"at": "hit", "amp": 14, "decay": 9}], "drift": {"by": {"zoom": 1.08, "x": -30}, "ease": "sine.inOut"}},
+ "tracks": {"reach": {"base": 0, "moves": [{"at": "B1", "dur": "2f", "to": 1, "ease": "power2.out"}, {"at": "B2", "dur": "1b", "to": 0, "ease": "circ.in"}]}}},
+ {"id": "B", "start": "B6", "end": 5, "camera": {"moves": [{"at": "S", "until": "E", "by": {"zoom": 0.8}, "ease": "power4.inOut"}]}},
+ cues={"hit": "B5+1f"})
+
+
[email protected](not shutil.which("node"), reason="node not installed")
+def test_js_and_python_runtimes_agree(tmp_path):
+ r, d = model.resolve_score(EVERYTHING)
+ assert d.ok, d.errors
+ times = [round(x, 4) for x in np.arange(0, 5, 1 / 48)]
+ py = Score(r)
+ want = {"A": [py.cam("A", t) for t in times], "B": [py.cam("B", t) for t in times],
+ "reach": [py.track("A", "reach", t) for t in times], "held": [py.held("A", t) for t in times]}
+ js = tmp_path / "eval.js"
+ js.write_text(f"""
+const Score = require({json.dumps(RUNTIME_JS)});
+Score.load({json.dumps(r)});
+const T = {json.dumps(times)};
+const out = {{ A: T.map(t => Score.cam('A', t)), B: T.map(t => Score.cam('B', t)), reach: T.map(t => Score.track('A', 'reach', t)),
+ held: T.map(t => Score.held('A', t)) }};
+process.stdout.write(JSON.stringify(out));
+""", encoding="utf-8")
+ got = json.loads(subprocess.run(["node", str(js)], capture_output=True, text=True, check=True).stdout)
+ for sid in ("A", "B"):
+ for w, g in zip(want[sid], got[sid]):
+ for k in ("x", "y", "zoom", "rot"):
+ assert g[k] == pytest.approx(w[k], rel=1e-9, abs=1e-9), (sid, k)
+ assert got["reach"] == pytest.approx(want["reach"], abs=1e-12)
+ assert got["held"] == pytest.approx(want["held"], abs=1e-12)
+
+
+def test_vectorised_evaluation_matches_the_scalar_twin():
+ r, d = model.resolve_score(EVERYTHING)
+ sc = Score(r)
+ t = np.arange(0, 5, 1 / 96)
+ for sid in ("A", "B"):
+ v = sc.cam_array(sid, t)
+ for i, x in enumerate(t):
+ c = sc.cam(sid, float(x))
+ for k in ("x", "y", "zoom", "rot"):
+ assert v[k][i] == pytest.approx(c[k], rel=1e-12, abs=1e-12), (sid, k, x)
+
+
+# ---------- prediction = measurement ----------
+def _render_score(score: Score, sid: str, path: str):
+ """Film the score's camera with the synthetic plate: stage px → frame widths, canvas roll → synth roll."""
+ t, c = score.camera_series(sid, FPS)
+ cams = [synth.Cam(x=(x - 960) / 1920, y=(y - 540) / 1920, scale=z, roll=-r) for x, y, z, r in zip(c["x"], c["y"], c["zoom"], c["rot"])]
+ synth.render(path, cams, FPS)
+
+
+def test_prediction_matches_what_perception_measures(tmp_path):
+ r, d = model.resolve_score(film({"id": "A", "start": 0, "end": 3, "camera": {"moves": [
+ {"at": "S+0.25s", "dur": "0.75s", "by": {"zoom": 1.3}, "ease": "power3.out"},
+ {"at": "S+1.6s", "dur": "1s", "by": {"x": 300}, "ease": "sine.inOut"}]}}))
+ assert d.ok
+ sc = Score(r)
+ path = str(tmp_path / "s.mp4")
+ _render_score(sc, "A", path)
+ measured = fingerprint.extract(path, fps=FPS)["shots"][0]["move"]
+ predicted = predict.predicted_shots(sc)[0]["move"]
+ assert set(measured["kind"]) == set(predicted["kind"]) == {"push_in", "move_right"}
+ for ax in ("x", "z"):
+ assert measured["amount"][ax] == pytest.approx(predicted["amount"][ax], rel=0.06)
+ assert measured["duration"] == pytest.approx(predicted["duration"], rel=0.12)
+ assert np.sqrt(np.mean((np.asarray(measured["progress"]) - np.asarray(predicted["progress"])) ** 2)) < 0.05
+
+
+# ---------- motion transfer closes the loop ----------
+def test_transfer_reproduces_the_reference_camera(tmp_path):
+ """A 'reference' with a fast expo push then a slow pan: measure it, transfer it into a plan whose shot is a bit
+ longer, and the predicted camera must match the reference move for move."""
+ n = 72
+ zoom = synth.move(n, 5, 12, curves.NAMED["expo.out"], 1.0, 1.35)
+ pan = synth.move(n, 36, 30, curves.NAMED["sine.inOut"], 0.0, -0.2)
+ ref_path = str(tmp_path / "ref.mp4")
+ synth.render(ref_path, [synth.Cam(scale=z, x=x) for z, x in zip(zoom, pan)], FPS)
+ ref = fingerprint.extract(ref_path, fps=FPS)
+ plan = {"shots": [{"id": "S1", "start_s": 0.0, "end_s": 3.5, "ref_shot": 1}]}
+ authored = transfer.from_reference(plan, ref, bpm=120, offset=0.0)
+ moves = authored["shots"][0]["camera"]["moves"]
+ assert len(moves) == 2 and "zoom" in moves[0]["by"] and "x" in moves[1]["by"]
+ r, d = model.resolve_score(authored)
+ assert d.ok, d.errors
+ res = predict.against_reference(Score(r), ref)
+ assert res["camera_score"] > 80, res
+ assert not [f for f in res["findings"] if f["severity"] == "major"], res["findings"]
+
+
+def test_a_slow_drift_under_a_quick_move_is_transferred(tmp_path):
+ """Reference: a slow push through the whole shot plus a quick pan in the middle. Segmentation alone keeps the pan
+ and loses most of the push (seen on a real reference); the drift must carry it over."""
+ n = 96
+ zoom = [1.0 + 0.2 * f / (n - 1) for f in range(n)] # +20 % over 4 s, linear
+ pan = synth.move(n, 40, 10, curves.NAMED["power2.inOut"], 0.0, 0.2)
+ ref_path = str(tmp_path / "ref.mp4")
+ synth.render(ref_path, [synth.Cam(scale=z, x=x) for z, x in zip(zoom, pan)], FPS)
+ ref = fingerprint.extract(ref_path, fps=FPS)
+ m = ref["shots"][0]["move"]
+ assert "drift" in m and m["drift"]["z"] == pytest.approx(math.log(1.2), rel=0.25), m.get("drift")
+ authored = transfer.from_reference({"shots": [{"id": "S1", "start_s": 0, "end_s": 4, "ref_shot": 1}]}, ref, bpm=120)
+ assert "drift" in authored["shots"][0]["camera"]
+ r, d = model.resolve_score(authored)
+ assert d.ok, d.errors
+ p = predict.predicted_shots(Score(r))[0]["move"]
+ assert p["amount"]["z"] == pytest.approx(m["amount"]["z"], rel=0.1) and p["amount"]["x"] == pytest.approx(m["amount"]["x"], rel=0.1)
+
+
+def test_a_hand_edited_shot_file_that_is_not_json_is_named(tmp_path):
+ d = tmp_path / "score"
+ (d / "shots").mkdir(parents=True)
+ (d / "film.json").write_text("" + json.dumps({"version": 1, "bpm": 120}), encoding="utf-8") # BOM: fine
+ (d / "shots" / "S3.json").write_text('{ "id": "S3", "start": 0, "end": 1, }', encoding="utf-8")
+ with pytest.raises(model.ScoreError) as e:
+ model.load(str(d))
+ assert "shots/S3.json: not valid JSON at line 1" in str(e.value)
+
+
+def test_a_much_shorter_shot_keeps_the_biggest_moves_at_their_pace():
+ """Twelve seconds of slow moves into a two-second shot: keep the biggest, at ≤ 2× speed — not every move as a whip."""
+ t = np.arange(12 * FPS) / FPS
+ sine = curves.NAMED["sine.inOut"]
+ y = 0.15 * sine(np.clip(t / 3, 0, 1)) - 0.06 * sine(np.clip((t - 4) / 3, 0, 1)) + 0.03 * sine(np.clip((t - 8) / 3, 0, 1))
+ traj = {"x": np.zeros_like(t), "y": y, "z": np.zeros_like(t), "r": np.zeros_like(t)}
+ ref = {"shots": [{"id": 1, "start": 0.0, "end": 12.0, "move": curves.describe_shot(t, traj)}], "cadence": {}}
+ moves = transfer.shot_moves(ref["shots"][0], 0.0, 2.0, CLOCK)
+ assert len(moves) == 1 and moves[0]["by"]["y"] > 0 # the big first move down
+ assert float(moves[0]["dur"][:-1]) >= 0.5 * 3 * 0.9 # at no more than ~2× its speed
+ assert moves[0]["from_ref"].get("left_out")
+
+
+def test_shots_sharing_one_long_reference_take_each_get_their_part(tmp_path):
+ """A real plan cut one 12 s reference take into four shots and every shot got the take's moves. Three shots on one
+ 9 s take with a pan only in its middle third: only the middle shot pans, and each is compared with its part."""
+ n = 9 * FPS
+ pan = synth.move(n, 3 * FPS + 6, 2 * FPS, curves.NAMED["sine.inOut"], 0.0, 0.25)
+ path = str(tmp_path / "take.mp4")
+ synth.render(path, [synth.Cam(x=x) for x in pan], FPS)
+ ref = fingerprint.extract(path, fps=FPS)
+ plan = {"shots": [{"id": f"S{i + 1}", "start_s": 2.0 * i, "end_s": 2.0 * (i + 1), "ref_shot": 1} for i in range(3)]}
+ moves = {s["id"]: s["camera"]["moves"] for s in transfer.from_reference(plan, ref, bpm=120)["shots"]}
+ assert not moves["S1"] and not moves["S3"], moves
+ assert moves["S2"] and moves["S2"][0]["by"].get("x", 0) > 0
+ r, d = model.resolve_score(transfer.from_reference(plan, ref, bpm=120))
+ res = predict.against_reference(Score(r), ref)
+ assert all(s.get("score", 100) > 80 for s in res["shots"]), res["shots"]
diff --git a/.claude/skills/video-clone/scripts/tests/test_signals.py b/.claude/skills/video-clone/scripts/tests/test_signals.py
new file mode 100644
index 0000000..4605802
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/tests/test_signals.py
@@ -0,0 +1,100 @@
+"""DTW, tension peaks, cut/beat phase and colour distance on signals whose answer is known."""
+import numpy as np
+import pytest
+
+from perception import distance, look, rhythm, tension
+
+FPS = 24
+
+
+def test_dtw_identical_is_zero_and_warped_is_small():
+ t = np.linspace(0, 1, 120)
+ a = np.sin(2 * np.pi * 2 * t)
+ assert distance.dtw(a, a)[0] == pytest.approx(0.0, abs=1e-12)
+ warped = np.sin(2 * np.pi * 2 * t ** 1.3) # same shape, different timing
+ other = np.cos(2 * np.pi * 5 * t) # different shape
+ assert distance.dtw(a, warped)[0] < 0.1 < distance.dtw(a, other)[0]
+
+
+def test_dtw_matches_brute_force():
+ rng = np.random.default_rng(1)
+ a, b = rng.random(17), rng.random(23)
+ D = np.full((18, 24), np.inf)
+ D[0, 0] = 0
+ for i in range(1, 18):
+ for j in range(1, 24):
+ D[i, j] = abs(a[i - 1] - b[j - 1]) + min(D[i - 1, j - 1], D[i - 1, j], D[i, j - 1])
+ cost, path = distance.dtw(a, b, band=1.0)
+ assert sum(abs(a[i] - b[j]) for i, j in path) == pytest.approx(D[-1, -1])
+ assert path[0] == (0, 0) and path[-1] == (16, 22)
+
+
+def test_peak_shape_build_breath_hit():
+ """Build for 4 s, drop for 0.5 s (the held breath), hit in 2 frames, hold 1 s, release."""
+ n = 10 * FPS
+ T = np.full(n, 0.1)
+ f_build, f_dip, f_hit = 2 * FPS, 6 * FPS, int(6.5 * FPS)
+ T[f_build:f_dip] = np.linspace(0.1, 0.6, f_dip - f_build)
+ T[f_dip:f_hit] = 0.15
+ T[f_hit:f_hit + FPS] = 1.0
+ T[f_hit - 1] = 0.6
+ T[f_hit + FPS:] = np.linspace(1.0, 0.1, n - f_hit - FPS)
+ peaks = tension.describe_peaks(T, FPS)
+ p = max(peaks, key=lambda p: p["height"])
+ assert p["t"] == pytest.approx(6.5, abs=0.1)
+ assert p["breath_depth"] == pytest.approx(0.45, abs=0.05)
+ assert p["breath_s"] == pytest.approx(0.5, abs=0.15)
+ assert p["rise_frames"] <= 2
+ assert p["build_slope"] > 0.05
+
+
+def test_cut_phase_on_beat_and_on_the_and():
+ beats = list(np.arange(0, 20, 0.5))
+ on = rhythm.cut_phase([b for b in beats[2:30:2]], beats, FPS)
+ assert on["on_beat_ratio"] == 1.0 and on["phase_R"] > 0.99 and min(on["phase_mean"], 1 - on["phase_mean"]) < 0.01
+ off = rhythm.cut_phase([b + 0.25 for b in beats[2:30:2]], beats, FPS)
+ assert off["on_beat_ratio"] == 0.0 and off["phase_mean"] == pytest.approx(0.5, abs=0.01)
+ early = rhythm.cut_phase([b - 1 / FPS for b in beats[2:30:2]], beats, FPS)
+ assert early["mean_offset_frames"] == pytest.approx(-1.0, abs=0.01)
+
+
+def test_colour_distance_is_ordered():
+ def solid(L, a, b):
+ px = np.zeros((8, 8, 3), np.float32)
+ px[..., 0], px[..., 1], px[..., 2] = L, a, b
+ return look.normalise(look.hist(px))
+ base = solid(50, 10, 20)
+ near, far = solid(55, 10, 20), solid(85, 10, 20)
+ assert look.wasserstein(base, base)[0] == 0
+ assert 0 < look.wasserstein(base, near)[0] < look.wasserstein(base, far)[0]
+ assert look.wasserstein(base, far)[0] == pytest.approx(35, abs=4)
+
+
+def test_invisible_motion_does_not_make_tension():
+ """A 1-pixel camera jitter in an otherwise still film must not read as tension (an optimizer exploited this)."""
+ n = 10 * FPS
+ rng = np.random.default_rng(0)
+ base = {"loudness": -20 + 3 * np.sin(np.arange(n) / 30), "flux": rng.random(n)}
+ still = tension.curve({**base, "camera": np.zeros(n)}, FPS)
+ jitter = np.zeros(n)
+ jitter[5 * FPS:5 * FPS + 6] = 2 / 1920 * FPS # ±1 px a frame for a quarter second
+ jittered = tension.curve({**base, "camera": jitter}, FPS)
+ assert np.max(np.abs(jittered - still)) < 0.02
+ real = np.zeros(n)
+ real[5 * FPS:6 * FPS] = 0.6 # a real whip pan: 0.6 frame widths per second
+ assert np.max(tension.curve({**base, "camera": real}, FPS) - still) > 0.08
+
+
+def test_histogram_mean_is_in_range():
+ h = np.zeros((3, look.BINS))
+ h[0, 0] = h[0, -1] = 0.5 # half black, half white → L ≈ 50
+ h[1, look.BINS // 2] = 1 # a = just above 0
+ h[2, 0] = 1 # b = most blue
+ assert look.mean(h, 0) == pytest.approx(50, abs=0.1)
+ assert 0 < look.mean(h, 1) < 8 and look.mean(h, 2) == pytest.approx(-128 + 4, abs=0.1)
+
+
+def test_no_finding_says_both_hold_still():
+ still = lambda amt: {"id": 1, "start": 0.0, "end": 2.0, "move": {"kind": ["static"], "amount": amt}}
+ _, _, findings = distance.camera_pair(still({"x": 0.012, "y": 0, "z": 0, "r": 0}), still({"x": 0, "y": -0.012, "z": 0, "r": 0}))
+ assert not findings
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 83192ac..bed2ba7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -27,3 +27,19 @@ jobs:
- run: npm run lint
- run: npm test
- run: npm run build
+
+ perception:
+ name: Perception (Python)
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ cache: pip
+ - run: sudo apt-get update && sudo apt-get install -y ffmpeg
+ - run: pip install numpy opencv-python-headless scipy librosa pytest ruff
+ - name: Lint (pyflakes rules, bugbear, simplify)
+ working-directory: .claude/skills/video-clone/scripts
+ run: ruff check perception score optimize tests fingerprint.py motion_score.py --select F,E9,B,UP,SIM --ignore UP006,UP035,SIM108,B905,UP038
+ - run: python -m pytest .claude/skills/video-clone/scripts/tests -q
diff --git a/.gitignore b/.gitignore
index af2cf5d..2e15ef2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,3 +41,4 @@ Thumbs.db
.claude/skills/remotion-studio/
.claude/skills/remotion-upgrade/
.claude/skills/media-use/audio/assets/sfx/*.mp3
+.pytest_cache/
diff --git a/docs/COMPILER.md b/docs/COMPILER.md
new file mode 100644
index 0000000..7eb7a01
--- /dev/null
+++ b/docs/COMPILER.md
@@ -0,0 +1,265 @@
+# ReelMimic as a style compiler — design
+
+Status: stages 1–3 are implemented, tested and wired into the production line; the measurable part of stage 4 (agent
+outputs checked, not just timestamped) is in; the rest of stage 4 and stage 5 are deliberately not built yet — see
+[Decisions](#decisions-what-was-not-built-and-why). [Validation](#validation) says what was measured and what it showed,
+including the parts that did not work.
+
+## Why
+
+Today the pipeline is open-loop: an agent writes engine code, another agent looks at screenshots and says whether it is
+good. Nothing in the system *understands* what was built, and the only quantity we measure about the reference is one
+averaged camera vector per shot plus a label (`push_in / slow`). What makes a reference film land — the shape of a push,
+where a cut sits against the beat, how tension builds, holds its breath and hits — is a set of continuous, time-varying
+signals, and we measure none of them.
+
+The direction: treat ReelMimic as a **compiler** from a reference film to a new film.
+
+```
+reference video ──[1 perception]──▶ Style Fingerprint (time series + fitted curves)
+ │
+brief + plan ─────[LLM planning]───▶ Motion Score IR (typed scene graph, parametric curves, beat-anchored time)
+ │ ▲
+ │ └──[3 optimizer] tunes IR parameters against style_distance
+ ▼
+ [2 backends] HyperFrames · canvas engines · …
+ ▼
+ render ──▶ perception again ──▶ feedback
+```
+
+## Stages
+
+| # | Stage | What it adds | Where |
+|---|---|---|---|
+| 1 | **Perception** | Style Fingerprint: per-frame camera trajectory, fitted easing curves, local (in-frame) motion, tension curve with peak shapes, cut-vs-beat phase, colour arc, frame descriptors; `style_distance` between two fingerprints with readable findings | `.claude/skills/video-clone/scripts/perception/` |
+| 2 | **Motion Score IR** | A typed scene description: shots, layers, rig references, keyframe tracks whose curves are parametric (bezier / spring / named ease) and whose times are musical (`beat 17 + 2f`). Agents emit and patch IR for camera, timing and easing; engines compile it. Drawing code stays agent-written (IR and free code coexist) | `ir/` (schema + validator), one backend per engine, HyperFrames first |
+| 3 | **Closed-loop optimizer** | CMA-ES over IR parameters of the climax shots, objective = `style_distance` to the reference peak, multi-fidelity (low-res proxy renders of key frames → full render to confirm). The LLM decides structure; the optimizer decides numbers | `optimize/` |
+| 4 | **Orchestration kernel** | Event-sourced job state (state = fold(events)), a typed task DAG with declared inputs/outputs, schema-validated agent outputs instead of mtime checks, content-addressed caching, one resource-aware scheduler (agent tokens, Chrome, CPU/GPU) instead of three ad-hoc locks | `app/server/kernel/` replacing `jobs.ts` |
+| 5 | **Learned critic** | Pairwise preference model over fingerprint features + frame embeddings, trained on reviewer verdicts and user feedback, used to calibrate the LLM critic | later |
+
+Order: perception first (every later stage consumes it), then IR (the largest piece), then the kernel (task types only
+settle once the IR exists), then the optimizer and the learned critic.
+
+## Stage 1 — Perception
+
+### Signals
+
+All signals are sampled on one clock (`fps`, default 24) so they line up frame for frame.
+
+| Module | Signal | Method |
+|---|---|---|
+| `video.py` | frames | ffmpeg → raw BGR pipe at fixed fps and width, streamed (a 3-minute reference never sits in memory) |
+| `camera.py` | global motion per frame: `dx, dy` (frame widths), `dz` (log scale), `dr` (radians), camera convention (camera right = +x, push in = +z) | Shi–Tomasi corners → pyramidal Lucas–Kanade with forward–backward check → RANSAC similarity on centred coordinates; low texture falls back to 0 with `ok=false` |
+| | local motion energy | median residual of tracked points after removing the global similarity (characters moving vs. the camera moving) |
+| | cuts | HSV histogram correlation + mean abs difference, or the cut list from `analyze.py` |
+| `curves.py` | per-shot move: active window, amplitude per axis, duration, easing as CSS `cubic-bezier`, damped spring, overshoot, nearest GSAP ease name | least squares on the normalised progress curve (Newton-solved bezier x(s)=u); presets sampled from GSAP's formulas |
+| `tension.py` | tension(t) ∈ [0,1] and peak shapes | robust-normalised mix of loudness, spectral flux, camera speed, local motion, cut density and luminance jumps; each peak described by build slope, breath (dip before the hit), rise frames, height, decay |
+| `rhythm.py` | cut phase against the beat | signed frame offset to the nearest beat, on-beat ratio (±1 frame), circular mean phase (on the beat vs. on the "and") |
+| `look.py` | colour arc | per-frame Lab mean/std and a per-shot Lab histogram |
+| `distance.py` | `style_distance` | banded DTW on curves, sliced Wasserstein on Lab histograms, easing curve RMSE, log ratios of durations and amplitudes; every component maps to 0–100 and produces findings in words |
+
+### What real footage taught (each one is handled and tested)
+
+| Problem | Seen on | Handling |
+|---|---|---|
+| A static overlay (phone UI over a screen recording, watermark, letterbox) votes "the camera did not move" | `20261002-xqmlk`: TikTok UI down the right side | pre-pass at 4 fps: pixels that never change over the clip are masked out of corner detection (`video.static_mask`) |
+| A character moving over a plain background is read as the camera moving | a real film: a head tilt over a flat gradient measured as a 2.5° camera roll | two-layer motion: the tracks that agree mark the subject; the background's own motion is measured from corners searched for outside it (faint detail like sparkles counts); with no trackable background, the camera stands still unless moving it explains the background better than not (`camera.background_motion`, `background_says_still`) |
+| A burned-in caption is a strip of strong corners that never moves | a real film: a 26 % push on a bowl read as "still" because the caption held still | background tracks only count when they spread over ≥ 15 % of the frame |
+| A camera that rests a few frames before a move looked like limited animation | found by rendering through the real engine | a held drawing needs a real change on both sides; the first frame and cuts do not count |
+| A move the edit cuts into or out of is fitted as a longer move than the shot | a real reference: a 1.83 s shot showing part of a 3.57 s push | the move's on-screen share is measured (`visible`, `seen`, `cut_off`, `lead_in`); the transfer writes the whole curve and lets our cut interrupt it the same way (`"past_cut": true`) |
+| A slow drift down and back up over twelve seconds was called a shake | a real reference shot | a shake must change direction ≥ 1.5 times a second; slower back-and-forth is segmented into moves |
+| A shot list a frame off the real cut turns the cut into a huge fake camera move | plan cut at 7.92 s, picture cut one frame later: "14 % pan in one frame" | cuts are always detected; given cuts snap to a detected one within ±3 frames; every fit is **photometrically verified** — warping the previous frame must explain the current one (`camera.photometric_ok`) |
+| Limited animation (drawings held for two frames) makes speed a comb: 0, 2v, 0, 2v | the reference: 31 % of moving frames are holds | held runs (≤ 3 frames inside motion) share the step that ends them; the hold ratio itself is reported as **cadence** (on ones / mixed / on twos / on threes) |
+| A speed-threshold window clips an ease's slow tail and stretches the shape | power3.out measured as 0.72 s instead of 1.0 s | start, duration, amount, offset and ease are fitted **jointly** on the whole shot: `x(t) = B + A·E(clip((t − t0)/D))` |
+| An ease fitted on log-scale is not the ease a builder types | power3.out zoom read as power4.out | zoom eases are fitted on scale (`exp z`), the quantity engines tween |
+| One long shot holds several moves | ref shot 3: settle, then a 1.2 s back.in pan | moves are segmented by still stretches; the biggest is the shot's move, the rest are `other_moves` |
+| Comparing moves on different axes (a pull-out against a pan) gives nonsense timings | "0.04 s vs 2.10 s" | timing/ease compared only on the same main axis; 1–2-frame moves are `snap` (jump cuts, impact jolts), not eases |
+
+### Files
+
+```
+analysis/fingerprint.json reference fingerprint (written by analyze.py)
+analysis/fingerprint.png tension, camera speed, cuts, beats, peaks on one time axis
+out/check/fingerprint.json our film's fingerprint (written by compare.py)
+out/check/style_distance.json scores per component and per mapped shot, plus findings
+out/check/fingerprint_overlay.png reference vs. ours, tension and camera speed overlaid
+```
+
+`fingerprint.json` is versioned (`"version"`); readers ignore fields they do not know.
+
+### How it is used now
+
+- `analyze.py` writes the reference fingerprint; the style and plan prompts can quote fitted eases and peak shapes
+ instead of "slow push".
+- `compare.py` adds `style_distance.json`; the final critic reads its findings ("s3 vs ref #4: the push is 38% slower
+ and eases ≈ power1.out where the reference uses ≈ expo.out") as evidence next to the frames.
+
+### Verification
+
+`scripts/tests/` renders synthetic videos with known camera moves (a textured plate warped by a known similarity on a
+known ease, with a cut) and checks that the trajectory, the fitted ease and the cut are recovered; curve fitting, DTW,
+tension peaks and beat phase have analytic tests. Run: `python -m pytest .claude/skills/video-clone/scripts/tests`.
+
+## Stage 2 — Motion Score IR
+
+The camera and the timing of every shot as data instead of expressions buried in scene code
+(`camBegin(lerp(925, 985, k), …)` with `k = ease(lt / dur)` and hit times typed as literals).
+
+### Layers
+
+```
+authored score (build/score/film.json + shots/<id>.json) ← director (from-ref, then edits), builders (their own shot file)
+ │ score/model.py: parse time expressions, normalise eases, check, resolve
+ ▼
+resolved score (every time in seconds, every move a segment {t0, t1, v0, v1, ease})
+ ├── assets/score/score.js runtime the engines load (canvas kit and HyperFrames Kit share one camera model)
+ └── score/runtime.py the same evaluator in Python — tests/test_score.py runs both and compares
+ │
+ └── score/predict.py camera → the trajectory perception would measure → compared with the reference
+```
+
+The front end does all parsing and checking, so the JS runtime is only evaluation (≈ 100 lines): the engines cannot
+disagree with the tools about what a score means. One file per shot keeps parallel builders from colliding.
+
+### Language
+
+- **Time** (`score/timeexpr.py`): `B12` (beat 12), `S` / `E` (shot start / end), cue names, lengths in `s`, `b` (beats),
+ `f` (frames): `"B12-2f"`, `"P1_hit+1b"`, `"S+0.25s"`. An instant has exactly one anchor; a length has none.
+- **Camera**: `base {x, y, zoom, rot}` in stage coordinates (1920×1080, x/y = the world point at the frame centre) and
+ `moves [{at, dur | until, to | by, ease}]`; zoom `by` multiplies. Moves on one channel run one after the other (a
+ spring may be interrupted). `shakes [{at, amp, decay}]` use the kit's stable per-frame noise.
+- **Eases**: GSAP names (the same formulas perception fits), `back.out(s)`, `{bezier: [...]}`, `{spring: {omega, zeta}}`,
+ `hold`.
+- **Tracks**: any other named number a shot animates (a reach, a lean) with the same moves. **Cadence**: 1–4 frames per
+ drawing; `Score.held(id, t)` snaps time for limited animation.
+
+Errors carry their place: `shots/S3.json.camera.moves[1]: x is still moving until 4.550s (moves[0]); start at or after it`.
+
+### Motion transfer (`motion_score.py from-ref`)
+
+Each move perception found in the mapped reference shot becomes a score move: same pace in seconds, amount converted
+from frame widths to stage pixels at the current zoom, ease = the fitted curve (a GSAP name when it fits within 10 % of
+the best model, else the cubic-bezier or spring) with *that model's own* start and duration. A scheduler places the
+moves inside our (usually shorter) shot: as near as possible to where they happened, never overlapping, pace kept when
+they fit, all compressed by one factor when they do not (recorded as `from_ref.compressed`). Cuts stay where the plan
+put them; move starts snap to a beat only when that keeps them in place.
+
+### Render-free prediction (`motion_score.py predict`)
+
+The stage camera maps to perception's camera terms exactly (x += zoom·Δcx/W, z = ln zoom/zoom₀, r = −Δrot), so the
+trajectory perception *would* measure is computed from the score and compared with the reference shot by the same
+`camera_pair()` used on rendered films. Moves are compared on a model-free window — the curve between 5 % and 95 % of
+the travel, read off the best-fitting model at 10× frame resolution — because "flat start + ease" and "later start +
+another ease" are the same motion, and a fast move spans only a few frames.
+
+On `20261002-xqmlk`: the delivered film's hand-written camera measures **10.4**; the transferred score predicts
+**71.5** before a frame is rendered (73.3 after `optimize`). Across 18 projects see [Validation](#validation).
+
+### Verification
+
+`tests/test_score.py`: time expressions; resolving and its error messages; **the JS and Python runtimes agree** to 1e-9
+on a score exercising every ease kind, shakes, tracks and cadence (it caught `%` on negative frame numbers differing
+between the languages); **prediction = measurement** (the score's camera is filmed on the synthetic plate and perception
+recovers the predicted kinds, amounts, duration and shape); **transfer closes the loop** (reference → measured →
+score → predicted ≈ reference, score > 80, no major finding).
+
+## Stage 3 — Closed-loop optimizer
+
+`motion_score.py optimize <project> [--peaks] [--apply]` searches a score for the version closest to the reference,
+render-free.
+
+- **Search** (`optimize/cmaes.py`): CMA-ES in the unit box (Hansen's tutorial algorithm, boundary handling by
+ projection + penalty), deterministic per seed. Tested on the sphere, Rosenbrock and an optimum outside the box.
+- **Space** (`optimize/space.py`): per move its start (± 0.25 s), duration (× 2^±1) and curve (as a cubic-bezier,
+ springs as ω, ζ); per shake amplitude and decay. **Amounts are locked** — they are the director's framing intent —
+ unless `--tune-amounts`. A point is written back in the author's terms (an unchanged start keeps `B12`, an unchanged
+ ease keeps its name) and every changed move records what it was (`"tuned": {"from": …}`).
+- **Objective** (`optimize/objective.py`): per shot 100 − camera_pair against the mapped reference shot, read off the
+ exact predicted trajectory sampled 10× finer than the frames (no fitting, vectorised evaluation: 1.8 ms an
+ evaluation, 50× faster than the first version); plus staying near the author's values; with `--peaks`, the predicted
+ tension at each plan peak against the reference peak's shape (one-sided: a deeper breath or a sharper hit than the
+ reference costs nothing). Predicted tension is multi-fidelity: the film's own sound, the score's exact camera and
+ cuts, in-frame motion from the last render.
+- **Groups**: shots are independent for the camera, so each is searched alone; the shots around a plan peak are
+ searched together. A group's result is kept only if it beats the author's version.
+
+On `20261002-xqmlk`: 8 s for the whole film; with `--peaks` it proposes an 8 px shake on the chorus downbeat (which
+the plan asked for) and moves the predicted climax onto the beat.
+
+### Four ways the optimizer gamed its objective, and the fixes
+
+Each was caught by checking a result some other way than the optimizer's own number.
+
+1. **An invisible shake.** The first `--peaks` run "fixed" the climax with a 1.07 px shake: tension normalised each
+ feature to the film's own range, so in a still film 1 px read as strong motion. Fix: just-noticeable floors per
+ feature, perceptual dead zones for motion (`tension.JND`, `DEADZONE`), measured-but-constant features kept in the
+ mix (dropping them made the weights jump), shakes under 4 px removed. Regression test: a ±1 px jitter changes
+ tension by < 0.02, a real whip pan by > 0.08.
+2. **Bent eases in a shortened shot.** When the plan makes a shot shorter than the reference's moves, the move must be
+ faster — but the duration term compared absolute seconds, so the optimizer bent the curve to stretch its 5–95 %
+ window, and a metric it never saw (the camera-speed profile) got worse (0.106 → 0.186). Fix: moves are expected to
+ be as much faster as the shot is shorter (`distance.time_available`), the same rule the transfer schedules by.
+ After it, that held-out metric improves too (table below).
+3. **Curves no measurement describes.** The search reads shapes straight off the exact predicted curve; a rendered
+ film is measured through fitted eases. With wide bezier bounds it found curves that score well on the exact curve
+ and are unrecognisable once measured (88.8 predicted, 32.8 measured). Fix: eases bounded to readable curves
+ (modest overshoot at most), and a **verification gate** — a group's result is kept only if it also wins measured
+ the way a rendered film is (`Objective.verified_camera_costs`).
+4. **Where in the shot.** Nothing in the comparison saw whether a move happens at the start or at the end of its
+ shot; the optimizer moved one, and the held-out speed profile caught it. Fix: a placement term
+ (`distance.placement_gap`), its expectation following the transfer's own time mapping.
+
+## Validation
+
+What was checked beyond unit tests, on the 18 projects with a reference and a delivered film (7 distinct references).
+The scripts only read projects; results below are with the final code.
+
+| Question | Method | Result |
+|---|---|---|
+| Does style_distance measure *style*? | split-half retrieval: 12 s windows of each reference find the other half of the same reference among all (balanced: ≤ 4 queries and candidates per reference, mean not max, ties count half) | **style** ranks the own reference **2.35** (chance 4.0): palette 2.12, pace 2.53, rhythm 3.00, frames 3.03; **tension 3.71 and peaks 3.74 ≈ chance** — they describe a stretch's content, not a style, so they only count as *structure* against the mapped window. Pace counts only *visible* camera motion (dead zone): with raw speed it partly measured each file's noise floor; removing that cost little (2.35 → 2.53), so it measures style |
+| Do the delivered films (old pipeline) look like their references? | each film against every reference's best-matching window | palette **2.44**: colour was cloned; pace **3.22**, style 3.11: how the films *move* was barely cloned — the gap stages 1–3 target |
+| Would following the score close that gap? | counterfactual: each film's measured camera replaced by its transferred score's camera, all else as measured | **per shot, yes**: camera_pair against the mapped reference shot **36.4 → 75.1** (median 24.9 → 83.0) over 202 shots, better in 73 % (the rest equal, mostly still against still). **Whole-film pace, no**: own-reference rank 3.22 → 3.39 — see the next row |
+| Why not the whole film? | pace features of the delivered films against the stretch of reference they clone | the plans cut **1.6× as often** as their references' hard cuts (3.8 vs 2.4 per 10 s). First reading: a pacing gap made at planning. A real A/B run corrected it (below): references change scene *inside* their shots, so hard cuts undercount how often their picture changes, and holding a plan to them cost variety. `fingerprint.py plan-check` now only flags plans *slower* than the reference; the plan prompt asks for at least the reference's rate of scene changes (cuts + in-shot transitions) |
+| Does the browser runtime do what the tools predict? | the engine kit renders a scene whose camera comes only from `Score.cam` in headless Chrome; perception measures it | camera_pair(measured, predicted) **99.2 / 99.6**; SVG camera = canvas camera to < 0.05 px (`tests/test_engine_render.py`) |
+| Does optimizing help a *rendered* film, or only the number? | before/after cameras filmed on the textured plate, measured with full fitting (not the optimizer's path); plus a metric the optimizer never sees (DTW of camera-speed profiles) | from the transferred score (the production path): camera_pair **68.9 → 76.4**, held-out 0.052 → 0.051 (unchanged); from a hand-written camera (every move spread over the shot with a generic ease, as builders write today): **17.4 → 45.2**, held-out 0.105 → 0.124 — better on one shot, equal on one, worse on one whose reference move (already moving at the cut in, then still) cannot keep pace, placement and speed profile at once in a shorter shot. The optimizer proposes; the director applies |
+| Do the tools work on projects made before them? | every command of the setup prompt run on a copy of a pre-perception HyperFrames project | yes, after making the reference fingerprint build itself when missing or stale (`ensure_reference`) |
+| Cost | analysis adds the fingerprint | ≈ 20–40 s for a 30 s reference, ≈ 2.5 min for a 13 min one; optimize ≈ 8 s per film |
+
+### Real productions (A/B)
+
+The same reference, brief and inputs as two earlier projects, produced again end to end by real agents (Claude Code)
+through the app with the new system; the earlier films are the baseline. Times are from `timeline.py`.
+
+| | 30 s party MV (HyperFrames; old film: painted) | 15 s pixel story (pixel-art) |
+|---|---|---|
+| plan cutting vs reference | 1.12× (old plan 2.22×) | 1.07× |
+| camera: the film follows the score? | yes — per shot measured ≈ predicted (S3 73.6 / 79.6, S6 36.8 / 36.8, S7 51.3 / 51.3) | mostly; an iris transition (a screen-space overlay) was read as a still background — see limits |
+| measured vs reference | overall 30.2 → 36.4, style 13.9 → 21.0, camera 10.1 → 28.1 | — |
+| final critic | 4 rounds, all 13 scores 4/5, both climaxes *beat* the reference | 4 rounds, climax 5/5, variety 5/5, both climaxes beat the reference (old critic had no climax check) |
+| by eye | new: a clearer story (Clawd + Mimi), climaxes land; old: more varied compositions — the plan had been held to the reference's hard cuts (14 → 8 shots), the lesson behind the plan-check change | new clearly better: big expressive subject, a real reveal at the climax, a warm ending; old: tiny subject in wide shots |
+| approve → done | 167 min (old 160) | 90 min (old 49) |
+| where the time went | setup 13 (old 7), cast 19 (41), shots 65 (49), final 46 + one revise round (58) | setup 10 (4), cast 13 (20), shots 23 (33), final 42 (7) |
+
+Production itself got faster on both (cast and shots); setup costs ≈ 6 min more (transfer, prediction, optimization);
+the final review is where the time goes — the critic of this branch is much stricter (12 must-fix items in round 1 of
+the pixel film against 1 for the old critic) and each round is ≈ 10–15 min. Found in these runs and fixed: a long
+reference take mapped to several shots gave each shot the whole take (now each gets its part —
+`fingerprint.reference_for`); the final review stopped at 9 → 3 must-fix items with a character still teleporting
+(it now continues while the list halves or is ≤ 3); a contradictory finding ("holds still; ours holds still").
+
+Limits: screen-space layers (an iris, a spotlight, a vignette) look like a background that does not move, so a push
+behind them can be read as a still camera; and a single critic is still the final judge of quality.
+
+
+## Decisions: what was not built, and why
+
+- **Stage 4, event-sourced kernel.** Measured first: a `log()` rewrites job.json (≈ 260 KB) in 3.9 ms, and the busiest
+ real minute had 82 events — 0.5 % of a core. Rewriting a working, tested orchestrator for that would be change for
+ its own sake. What stage 4 was for that *does* fail in practice is in: outputs are checked
+ (`app/server/outputs.ts`), with one repair turn in the same conversation — before it, a critique.json with a
+ trailing comma was read as "nothing to fix" and the film delivered as passed, and a broken production.json built
+ nothing yet reached "done" (both reproduced in `pipeline.test.ts`).
+- **Stage 5, learned critic.** It needs labelled outcomes — which findings a director acted on, which the user agreed
+ with — and there are 18 projects, judged only by an LLM critic. A model trained on that would learn the LLM critic
+ and overfit. The data it needs is now produced for every film (`style_distance.json` next to `critique.json` and the
+ user's notes); build it when there are a few hundred.
diff --git a/requirements.txt b/requirements.txt
index 1974202..78ea807 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -3,8 +3,11 @@ numpy
opencv-python
scenedetect
librosa
+scipy
Pillow
yt-dlp
# optional: automatic lyrics timing against the user's audio
faster-whisper
opencc-python-reimplemented
+# development: python -m pytest .claude/skills/video-clone/scripts/tests
+pytest