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.
JavaScript 2d-animationai-agentsai-videoanimationclaude-codecodexmulti-agentstyle-transfervideo-generation
Lint every video-clone script, not only the perception tools
許元豪a8b1b5cc2177
diff --git a/.claude/skills/video-clone/scripts/align_lyrics.py b/.claude/skills/video-clone/scripts/align_lyrics.pyindex 01e61d6..7d2dd29 100644--- a/.claude/skills/video-clone/scripts/align_lyrics.py+++ b/.claude/skills/video-clone/scripts/align_lyrics.py@@ -15,6 +15,7 @@ are interpolated between their neighbours. Writes:and prints a quality report: lines matched, mean match ratio. Low ratios mean "check by ear" (the app shows them)."""import argparse, difflib, json, os, re, shutil, subprocess, sys, tempfile+from pathlib import PathFFMPEG_FALLBACK = os.environ.get("FFMPEG_DIR", "") # folder with ffmpeg/ffprobe when they are not on PATHif not shutil.which("ffmpeg") and FFMPEG_FALLBACK and os.path.isdir(FFMPEG_FALLBACK): os.environ["PATH"] += os.pathsep + FFMPEG_FALLBACK@@ -72,7 +73,7 @@ def main():ap.add_argument("--start", type=float, default=0.0); ap.add_argument("--end", type=float)ap.add_argument("--model", default="medium"); ap.add_argument("--lang", default="zh")a = ap.parse_args()- lines = lyric_lines(open(a.lyrics, encoding="utf-8").read())+ lines = lyric_lines(Path(a.lyrics).read_text(encoding="utf-8"))if not lines: sys.exit("no lyric lines in " + a.lyrics)tmp = os.path.join(tempfile.mkdtemp(), "clip.wav")cmd = ["ffmpeg", "-v", "error", "-y", "-ss", str(a.start)]@@ -108,7 +109,7 @@ def main():if out[k]["start"] < out[k - 1]["start"]: out[k]["start"] = out[k - 1]["end"]with open(a.out, "w", encoding="utf-8") as f:for o in out: f.write(f"{fmt(o['start'])}{o['text']}\n")- json.dump({"clip_start": a.start, "lines": out}, open(os.path.splitext(a.out)[0] + ".json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)+ Path(os.path.splitext(a.out)[0] + ".json").write_text(json.dumps({"clip_start": a.start, "lines": out}, ensure_ascii=False, indent=1), encoding="utf-8")ok = [o for o in out if not o.get("interpolated")]print(f"lines {len(out)}, matched {len(ok)}, mean match {sum(o['match'] for o in out) / len(out):.2f}")for o in out: print(f" {fmt(o['start'])}–{fmt(o['end'])} match {o['match']:.2f}{' (interpolated)' if o.get('interpolated') else ''} {o['text']}")diff --git a/.claude/skills/video-clone/scripts/analyze.py b/.claude/skills/video-clone/scripts/analyze.pyindex daa596d..0ad06e1 100644--- a/.claude/skills/video-clone/scripts/analyze.py+++ b/.claude/skills/video-clone/scripts/analyze.py@@ -208,7 +208,7 @@ def _shot_details_part(path, spans, offset):crit = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)_, lab, cen = cv2.kmeans(sample, 4, None, crit, 2, cv2.KMEANS_PP_CENTERS)order = np.argsort(-np.bincount(lab.ravel(), minlength=4))- dom = ["#%02X%02X%02X" % (int(cen[k][2]), int(cen[k][1]), int(cen[k][0])) for k in order]+ dom = [f"#{int(cen[k][2]):02X}{int(cen[k][1]):02X}{int(cen[k][0]):02X}" for k in order]out.append({"shot": i + 1, "start": round(a, 2), "end": round(b, 2), "camera": mv,"look": {"brightness": round(float(lum.mean()), 3), "contrast": round(float(lum.std()), 3),"dark_ratio": round(float((lum < 0.08).mean()), 3), "colourfulness": round(colorful, 3), "dominant": dom}})@@ -225,8 +225,8 @@ def audio(path, info, out):y, sr = librosa.load(raw, sr=22050, mono=False)if y.ndim == 1: y = np.stack([y, y])db = lambda x: float(20 * np.log10(np.sqrt(np.mean(x ** 2)) + 1e-12))- L, R, M = db(y[0]), db(y[1]), db((y[0] + y[1]) / 2)- phase_inverted = M < max(L, R) - 10+ left, right, mono = db(y[0]), db(y[1]), db((y[0] + y[1]) / 2)+ phase_inverted = mono < max(left, right) - 10mix = "pan=mono|c0=c0" if phase_inverted else "pan=mono|c0=0.5*c0+0.5*c1"wav = os.path.join(out, "audio.wav")run(["ffmpeg", "-v", "error", "-y", "-i", path, "-vn", "-af", f"{mix},loudnorm=I=-14:TP=-1.5", "-ar", "44100", wav])@@ -234,7 +234,7 @@ def audio(path, info, out):y, sr = librosa.load(wav, sr=22050, mono=True)level = db(y)if level < -45:- return {"present": True, "silent": True, "levels_db": {"L": L, "R": R, "mono": M}, "phase_inverted": phase_inverted,+ return {"present": True, "silent": True, "levels_db": {"L": left, "R": right, "mono": mono}, "phase_inverted": phase_inverted,"note": "no usable sound: ask the user to re-record with system audio on, or to supply the audio file"}tempo, beats = librosa.beat.beat_track(y=y, sr=sr, units="time")tempo = float(np.atleast_1d(tempo)[0])@@ -250,7 +250,7 @@ def audio(path, info, out):# noise floor: the quietest 10th percentile of 0.5 s windowshop = sr // 2; w = [db(y[i:i + hop]) for i in range(0, len(y) - hop, hop)]peaks = peak_candidates(y, sr, beats)- return {"present": True, "silent": False, "levels_db": {"L": round(L, 1), "R": round(R, 1), "mono": round(M, 1)},+ return {"present": True, "silent": False, "levels_db": {"L": round(left, 1), "R": round(right, 1), "mono": round(mono, 1)},"phase_inverted": bool(phase_inverted), "noise_floor_db": round(float(np.percentile(w, 10)), 1) if w else None,"bpm": round(bpm, 2), "beat_seconds": round(60 / bpm, 4), "first_beat": round(float(beats[0]), 3) if len(beats) else None,"beats": [round(float(b), 3) for b in beats],@@ -284,7 +284,7 @@ def peak_candidates(y, sr, beats, n=3):out.append((rise + 0.5 * max(0.0, before - dip) + 0.3 * after, i * 0.25, rise, after))out.sort(reverse=True)picked = []- for score, t, rise, after in out:+ for _score, t, rise, after in out:if len(beats): t = float(beats[np.argmin(np.abs(np.asarray(beats) - t))])if any(abs(t - p["t"]) < 6 for p in picked): continuepicked.append({"t": round(t, 2), "rise": round(float(rise), 2), "level_after": round(float(after), 2),diff --git a/.claude/skills/video-clone/scripts/clip_strip.py b/.claude/skills/video-clone/scripts/clip_strip.pyindex 16115f3..6d396ac 100644--- a/.claude/skills/video-clone/scripts/clip_strip.py+++ b/.claude/skills/video-clone/scripts/clip_strip.py@@ -14,7 +14,7 @@ and a reference row that comes out (almost) black stops with an error instead ofWith --vs, the reference range is sampled into the same number of frames and each reference row sits directly abovethe matching row of ours (labelled REF / OURS with the time of every frame), so the build, the hit and the hold line up."""-import argparse, os, shutil, subprocess, sys, tempfile+import argparse, os, shutil, subprocess, tempfileFFMPEG_FALLBACK = os.environ.get("FFMPEG_DIR", "")if not shutil.which("ffmpeg") and FFMPEG_FALLBACK and os.path.isdir(FFMPEG_FALLBACK):@@ -72,7 +72,7 @@ def main():W = a.cols * a.w + 50; H = len(bands) * (fh + lab) + (len(rows) * 8 if ref else 0)sheet = Image.new("RGB", (W, H), (24, 24, 28)); d = ImageDraw.Draw(sheet)y = 0- for i, (name, row) in enumerate(bands):+ for name, row in bands:d.text((4, y + lab + fh // 2 - 7), name, fill=(255, 200, 80) if name == "REF" else (120, 220, 255), font=f)for j, (t, im) in enumerate(row):x = 50 + j * a.wdiff --git a/.claude/skills/video-clone/scripts/compare.py b/.claude/skills/video-clone/scripts/compare.pyindex edfdae6..28565b4 100644--- a/.claude/skills/video-clone/scripts/compare.py+++ b/.claude/skills/video-clone/scripts/compare.py@@ -14,6 +14,7 @@ reference shot number it maps to, and start_s/end_s). Analyses our video with thOpen the images and score each shot (see the engine skill's Review section). Numbers flag, eyes decide."""import argparse, json, os, sys+from pathlib import Pathimport numpy as np, cv2sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from analyze import shot_details # same measurements for both films@@ -39,8 +40,8 @@ def label(img, text, y=18):def main():ap = argparse.ArgumentParser(); ap.add_argument("project"); ap.add_argument("--video", default="out/video.mp4")a = ap.parse_args(); P = a.project- rep = json.load(open(os.path.join(P, "analysis", "report.json"), encoding="utf-8"))- plan = json.load(open(os.path.join(P, "plan.json"), encoding="utf-8"))+ rep = json.loads(Path(P, "analysis", "report.json").read_text(encoding="utf-8"))+ plan = json.loads(Path(P, "plan.json").read_text(encoding="utf-8"))ref_video = os.path.join(P, "analysis", rep.get("analysed", "source.mp4"))if not os.path.exists(ref_video): ref_video = os.path.join(P, "analysis", "source.mp4")ours = os.path.join(P, a.video)@@ -65,7 +66,7 @@ def main():result.append({"id": s["id"], "ref_shot": rn, "ref": rd and {"camera": rd["camera"], "look": rd["look"]}, "ours": {"camera": od["camera"], "look": od["look"]}})if rows:cv2.imwrite(os.path.join(out_dir, "compare_all.jpg"), np.vstack(rows), [cv2.IMWRITE_JPEG_QUALITY, 85])- json.dump(result, open(os.path.join(out_dir, "compare.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)+ Path(out_dir, "compare.json").write_text(json.dumps(result, ensure_ascii=False, indent=1), encoding="utf-8")for r in result:rc, oc = (r["ref"] or {}).get("camera", {}), r["ours"]["camera"]flag = "" if not rc or rc.get("pace") == oc.get("pace") or (rc.get("pace") != "still" and oc.get("pace") != "still") else " ← motion mismatch"diff --git a/.claude/skills/video-clone/scripts/hf_frames.py b/.claude/skills/video-clone/scripts/hf_frames.pyindex 44af3e5..4f03dad 100644--- a/.claude/skills/video-clone/scripts/hf_frames.py+++ b/.claude/skills/video-clone/scripts/hf_frames.py@@ -26,6 +26,7 @@ times a few ms off the 30 fps grid, saw the in-between it had designed, and the"""import argparse, glob, hashlib, json, os, re, shutil, subprocess, sys, tempfile, timefrom concurrent.futures import ThreadPoolExecutor+from pathlib import Pathfrom PIL import ImageMAX_PARALLEL = int(os.environ.get("HF_SNAPSHOT_SLOTS", "3"))@@ -84,8 +85,8 @@ def silent_mirror(build, key):for f in files:src, out = os.path.join(root, f), os.path.join(tmp, rel, f)if f.endswith(".html"):- s = open(src, encoding="utf-8", errors="surrogateescape").read()- open(out, "w", encoding="utf-8", errors="surrogateescape").write(AUDIO.sub("", s))+ s = Path(src).read_text(encoding="utf-8", errors="surrogateescape")+ Path(out).write_text(AUDIO.sub("", s), encoding="utf-8", errors="surrogateescape")else:try: os.link(src, out)except OSError: shutil.copy2(src, out)@@ -113,7 +114,7 @@ def snapshot(build, times, outdir):def film_fps(build):for f in (os.path.join(os.path.dirname(build), "plan.json"), os.path.join(build, "production.json")):try:- d = json.load(open(f, encoding="utf-8-sig")); v = (d.get("format") or {}).get("fps") or d.get("fps")+ d = json.loads(Path(f).read_text(encoding="utf-8-sig")); v = (d.get("format") or {}).get("fps") or d.get("fps")if v: return float(v)except (OSError, ValueError, AttributeError): passreturn Nonediff --git a/.claude/skills/video-clone/scripts/yating_tts.py b/.claude/skills/video-clone/scripts/yating_tts.pyindex def7009..f3792ea 100644--- a/.claude/skills/video-clone/scripts/yating_tts.py+++ b/.claude/skills/video-clone/scripts/yating_tts.py@@ -13,6 +13,7 @@ speed: SMALLER = faster (0.5–1.5); pitch/energy 0.5–1.5. Plain text ≤ 600"""import argparse, base64, json, os, sys, time, urllib.request, urllib.errorfrom concurrent.futures import ThreadPoolExecutor+from pathlib import PathURL = "https://tts.api.yating.tw/v2/speeches/short"VOICES = {"zh_en_female_1": "雅婷(女)", "zh_en_female_2": "意晴(女)", "zh_en_male_1": "家豪(男)", "zh_en_male_2": "志明(男)",@@ -24,7 +25,7 @@ def key():if not k:for p in ("~/.reelmimic/secrets.json", "~/.clone-studio/secrets.json"): # second: pre-rename locationp = os.path.expanduser(p)- if os.path.exists(p): k = json.load(open(p)).get("YATING_KEY"); break+ if os.path.exists(p): k = json.loads(Path(p).read_text(encoding="utf-8")).get("YATING_KEY"); breakif not k: sys.exit("no YATING_KEY (env or ~/.reelmimic/secrets.json)")return k@@ -39,7 +40,7 @@ def synth(text, out, voice="zh_en_female_1", speed=1.0, pitch=1.0, energy=1.0, stry:with urllib.request.urlopen(req, timeout=150) as r: d = json.load(r)os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)- open(out, "wb").write(base64.b64decode(d["audioContent"]))+ Path(out).write_bytes(base64.b64decode(d["audioContent"]))return outexcept urllib.error.HTTPError as e:msg = e.read().decode("utf-8", "replace")[:400]@@ -61,7 +62,7 @@ def main():for k, v in VOICES.items(): print(k, v)returnif a.lines:- L = json.load(open(a.lines, encoding="utf-8"))+ L = json.loads(Path(a.lines).read_text(encoding="utf-8"))def one(x):return synth(x["text"], os.path.join(a.outdir, f"{x['id']}.wav"), x.get("voice", a.voice), x.get("speed", a.speed), x.get("pitch", a.pitch), x.get("energy", a.energy), x.get("ssml", a.ssml))with ThreadPoolExecutor(3) as ex: # the API allows 3 concurrent requests per key