Skip to content

Reverse-engineer any video, shot by shot: filmed, AI-generated or coded, and how to remake it. Breakdowns in the open VIDEO.md format. 逆向一切视频,逐个镜头看是拍的、AI 生成的还是代码做的,再告诉你怎么复刻;拆解结果按 VIDEO.md 格式输出。

One-command remake with a redrawn first cut of rendered shots

june32e6d8c780bf
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 22e711c..17a9dd7 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -362,6 +362,31 @@ def cmd_compare(args) -> int:
return 0
+def cmd_remake(args) -> int:
+ from .remake import remake
+
+ out = Path(args.out_dir)
+ if not (out / "breakdown.json").is_file():
+ raise SystemExit(f"rea-video: {out} 下没有 breakdown.json,先运行 decompose")
+ print(json.dumps(remake(out, code=not args.no_code, overlays=not args.no_overlays), ensure_ascii=False, indent=1))
+ return 0
+
+
+def cmd_code_remake(args) -> int:
+ from .code_remake import code_remake
+
+ out = Path(args.out_dir)
+ if not (out / "breakdown.json").is_file():
+ raise SystemExit(f"rea-video: {out} 下没有 breakdown.json,先运行 decompose")
+ try:
+ res = code_remake(out, reset=args.reset, render=not args.no_render, score=not args.no_compare)
+ except ValueError as e:
+ raise SystemExit(f"rea-video: {e}")
+ res.pop("matched", None)
+ print(json.dumps(res, ensure_ascii=False, indent=1))
+ return 0
+
+
def cmd_summary(args) -> int:
"""Compact, agent-friendly view of a breakdown (instead of reading the whole JSON)."""
from .i18n import T, join
@@ -689,6 +714,19 @@ def main(argv: list[str] | None = None) -> int:
cp.add_argument("-o", "--out", help="输出目录:compare.json 和 compare_worst.jpg")
cp.set_defaults(func=cmd_compare)
+ rm = sub.add_parser("remake", help="一条命令出复刻:代码渲染镜头重画、静图按运动重建、已生成 / 你给的镜头剪进去,其余原片占位;输出成片、对比视频和逐镜进度(remake/status.md)")
+ rm.add_argument("out_dir", help="decompose 的输出目录")
+ rm.add_argument("--no-code", action="store_true", help="不重画代码渲染镜头")
+ rm.add_argument("--no-overlays", action="store_true", help="换掉的镜头上不叠回字幕 / 花字")
+ rm.set_defaults(func=cmd_remake)
+
+ cr = sub.add_parser("code-remake", help="代码渲染镜头的第一版复刻:按场景的采样点 / 抠图、运动和背景光写出可改的工程(code/spec.json + render.py),对齐原片后渲染并打分")
+ cr.add_argument("out_dir", help="decompose 的输出目录")
+ cr.add_argument("--reset", action="store_true", help="重新生成 spec.json(默认保留改过的)")
+ cr.add_argument("--no-render", action="store_true", help="只写工程,不渲染")
+ cr.add_argument("--no-compare", action="store_true", help="渲染后不打分")
+ cr.set_defaults(func=cmd_code_remake)
+
sm = sub.add_parser("summary", help="紧凑打印拆解结果(低置信镜头会被标出来)")
sm.add_argument("breakdown")
sm.set_defaults(func=cmd_summary)
diff --git a/rea_video/code_remake.py b/rea_video/code_remake.py
new file mode 100644
index 0000000..332f136
--- /dev/null
+++ b/rea_video/code_remake.py
@@ -0,0 +1,147 @@
+"""A runnable first remake of the code-rendered shots, built from the measured scenes.
+
+`rea-video code-remake out/ref` writes `out/ref/code/`: `spec.json` (one entry per scene: ground, glow, the sampled
+points or the cut-out, particle count and size, motion, how it enters), `render.py` (the renderer, a copy of
+`redraw.py`) and `overlays.ass` (the measured text). Each scene's amount and brightness are matched to the original's
+middle frame before the whole video is rendered and scored with `compare`. Whoever takes it further edits
+spec.json, swaps the points for new shapes or rewrites render.py, then runs the command again (an existing
+spec.json is kept; --reset starts over).
+"""
+from __future__ import annotations
+
+import shutil
+from pathlib import Path
+
+import cv2
+import numpy as np
+
+from . import redraw
+from .i18n import T
+from .layers import WORK_W, _boxes_at, _text_boxes, compare, layer_mask, scene_frames, shot_label
+from .media import extract_frame
+from .packaging import fit_ass_sizes
+from .plan import code_style
+from .util import read_json, write_json
+
+POINT_STYLES = ("particles", "lineart") # drawn as particles on the sampled points; other styles move the cut-out
+
+
+def _dot(m: dict, W: int) -> float:
+ """Particle radius in output pixels from the median piece the layer splits into (pieces of a dense cloud or a
+ line merge into one, so this is capped: more particles make up the rest)."""
+ area = float(m.get("piece_area") or 0) * W * W * 9 / 16
+ return round(float(np.clip(np.sqrt(area / np.pi) if area else 1.0, 0.7, 1.4)), 2)
+
+
+def build_spec(out: Path) -> dict:
+ """spec.json for the code-rendered scenes of a breakdown, before matching."""
+ b = read_json(out / "breakdown.json")
+ src = b.get("source") or {}
+ fdir = out / "frames"
+ if not (fdir / "scenes.json").exists():
+ scene_frames(out, breakdown=b)
+ scenes = read_json(fdir / "scenes.json").get("scenes", [])
+ shots = {s.get("index"): s for s in b.get("shots", [])}
+ W, H = int(src.get("width") or 960), int(src.get("height") or 540)
+ spec: dict = {"size": [W, H], "fps": float(src.get("fps") or 25), "duration": float(src.get("duration") or 0),
+ "text": "overlays.ass" if (out / "packaging" / "overlays.ass").exists() else None,
+ "bloom": 0.5, "bloom_size": 0.012, "scenes": []}
+ for sc in scenes:
+ m = sc.get("measure") or {}
+ style = code_style(shots.get(sc.get("shot")) or {})
+ e = {"id": sc["id"], "shot": sc.get("shot"), "start": sc["start"], "end": sc["end"],
+ "ground": m.get("ground") or "#000000", "centre": m.get("centre") or [0.5, 0.5]}
+ if m.get("glow"):
+ e["glow"] = {**m["glow"], "strength": 1.0}
+ if style in POINT_STYLES and sc.get("points"):
+ e.update(draw="points", points=f"../{sc['points']}", count=4000, dot=_dot(m, W), gain=1.0)
+ elif (sc.get("frames") or {}).get("layer"):
+ e.update(draw="cutout", cutout=f"../{sc['frames']['layer']}", gain=1.0)
+ else:
+ continue
+ e["motion"] = {**{"zoom": 0, "rotate": 0, "pan": [0, 0], "drift": 0}, **(sc.get("motion") or {}),
+ "twinkle": 0.15 if e["draw"] == "points" else 0.0}
+ e["enter"] = sc.get("enter", "cut")
+ e["enter_s"] = round(min(0.8, (sc["end"] - sc["start"]) / 3), 2)
+ spec["scenes"].append(e)
+ return spec
+
+
+def _side(bgr: np.ndarray, boxes: list) -> dict:
+ """What the matching looks at: how much is drawn, how bright the drawing is and how bright the rest is."""
+ m = layer_mask(bgr, boxes)
+ L = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)[..., 0].astype(np.float32)
+ return {"cover": float(m.mean()), "lit": float(L[m].mean()) if m.any() else 0.0,
+ "rest": float(L[~m].mean()) if (~m).any() else 0.0}
+
+
+def match(out: Path, spec_path: Path, rounds: int = 5) -> list[dict]:
+ """Match each scene's particle count, brightness and background glow to the original's middle frame: render
+ that frame, measure it the same way as the original, scale, repeat."""
+ b = read_json(out / "breakdown.json")
+ video = (b.get("source") or {}).get("path")
+ boxes = _text_boxes(out, b)
+ spec = read_json(spec_path)
+ tmp = spec_path.parent / "_match.jpg"
+ log = []
+ for e in spec["scenes"]:
+ a, z = e["start"], e["end"]
+ t = a + max(0.6 * (z - a), min(z - a, float(e.get("enter_s", 0)) + 0.05)) # past the morph in
+ extract_frame(video, t, tmp, WORK_W)
+ ref = cv2.imread(str(tmp))
+ if ref is None:
+ continue
+ bx = _boxes_at(boxes, a, z)
+ want = _side(ref, bx)
+ for k in range(rounds):
+ write_json(spec_path, spec)
+ rd = redraw.Redraw(spec_path)
+ rd.scenes = [s for s in rd.scenes if s.sc["id"] == e["id"]]
+ got = _side(cv2.resize(rd.frame(t), (ref.shape[1], ref.shape[0]), interpolation=cv2.INTER_AREA), bx)
+ if e["draw"] == "points" and got["cover"] > 0 and want["cover"] > 0:
+ e["count"] = int(np.clip(e["count"] * (want["cover"] / got["cover"]) ** 0.9, 150, 40000))
+ # amount first: brightness also moves how much stands out, so it is matched only once the count settles
+ if k >= rounds // 2 and got["lit"] > 0 and want["lit"] > 0:
+ e["gain"] = round(float(np.clip(e["gain"] * want["lit"] / got["lit"], 0.5, 4.0)), 3)
+ if e.get("glow") and got["rest"] > 1 and want["rest"] > 1:
+ e["glow"]["strength"] = round(float(np.clip(e["glow"]["strength"] * want["rest"] / got["rest"], 0.2, 3.0)), 3)
+ log.append({"id": e["id"], "want": {k: round(v, 4) for k, v in want.items()},
+ "got": {k: round(v, 4) for k, v in got.items()}})
+ tmp.unlink(missing_ok=True)
+ write_json(spec_path, spec)
+ return log
+
+
+def code_remake(out: Path, reset: bool = False, render: bool = True, score: bool = True) -> dict:
+ """Write (or keep) out/code, render remake.mp4 and score it against the original."""
+ out = Path(out)
+ b = read_json(out / "breakdown.json")
+ if not any(shot_label(s) == "code_render" for s in b.get("shots", [])) and not (out / "frames" / "scenes.json").exists():
+ raise ValueError(T("没有代码渲染镜头", "no code-rendered shots"))
+ cdir = out / "code"
+ cdir.mkdir(exist_ok=True)
+ spec_path = cdir / "spec.json"
+ res: dict = {"dir": str(cdir), "spec": str(spec_path)}
+ shutil.copyfile(redraw.__file__, cdir / "render.py")
+ ass = out / "packaging" / "overlays.ass"
+ if ass.exists() and (reset or not (cdir / "overlays.ass").exists()):
+ shutil.copyfile(ass, cdir / "overlays.ass")
+ fit_ass_sizes(cdir / "overlays.ass")
+ if reset or not spec_path.exists():
+ spec = build_spec(out)
+ if not spec["scenes"]:
+ raise ValueError(T("没有可重画的场景(先运行 rea-video frames)", "no scenes to redraw (run rea-video frames first)"))
+ write_json(spec_path, spec)
+ res["matched"] = match(out, spec_path)
+ else:
+ res["kept"] = True
+ if render:
+ video = redraw.render(spec_path, cdir / "remake.mp4")
+ res["video"] = str(video)
+ if score:
+ ref = (b.get("source") or {}).get("path")
+ cmp = compare(ref, str(video), out=cdir / "compare", scenes=out / "frames" / "scenes.json")
+ res["compare"] = {k: cmp[k] for k in ("score", "place", "shape", "offset", "advice") if k in cmp}
+ res["compare"]["lowest_scenes"] = cmp.get("scenes", [])[:5]
+ res["compare"]["sheet"] = cmp.get("sheet")
+ return res
diff --git a/rea_video/layers.py b/rea_video/layers.py
index 4ddd0e6..d807f59 100644
--- a/rea_video/layers.py
+++ b/rea_video/layers.py
@@ -31,6 +31,8 @@ WORK_W = 480 # measuring width; positions are written as 0-1 of the frame, so t
GRID = (16, 9) # cells of the layout map (x, y)
SCENE_WIN = 1.5 # seconds compared on each side of a candidate scene change; also the shortest scene kept
SCENE_MOVE = 0.25 # share of the drawn layer that has to move elsewhere in the frame for a new scene
+SCENE_AMOUNT = 3.0 # or this many times more / less drawn in place
+SCENE_COLOUR = 25.0 # or the drawn colour moving this far (Lab a, b)
def _hex(bgr) -> str:
@@ -166,10 +168,12 @@ def _boxes_at(boxes, t: float, until: float | None = None) -> list:
return [b for t0, t1, b in boxes if t0 - 0.3 <= z and t <= t1 + 0.3]
-def split_scenes(maps: np.ndarray, times: np.ndarray, start: float, end: float) -> list[tuple[float, float]]:
+def split_scenes(maps: np.ndarray, times: np.ndarray, start: float, end: float,
+ looks: np.ndarray | None = None) -> list[tuple[float, float]]:
"""Scene changes inside one shot: where the layout before and after differs (share of the drawn layer that sits
- elsewhere) by more than SCENE_MOVE beyond how much it varies within each side. maps: one flattened layout per
- sampled time."""
+ elsewhere) by more than SCENE_MOVE beyond how much it varies within each side, or where the drawing turns into
+ something else in place: SCENE_AMOUNT times more or less of it, or its colour moves by SCENE_COLOUR. maps: one
+ flattened layout per sampled time; looks: [log cover, a, b] of the drawn layer per sampled time (Lab)."""
if len(times) < 2:
return [(start, end)]
step = float(np.median(np.diff(times)))
@@ -178,10 +182,14 @@ def split_scenes(maps: np.ndarray, times: np.ndarray, start: float, end: float)
for i in range(win, len(times) - win + 1):
a, b = maps[i - win:i], maps[i:i + win]
spread = 0.5 * (0.5 * np.abs(a - a.mean(0)).sum(1).mean() + 0.5 * np.abs(b - b.mean(0)).sum(1).mean())
- score[i] = 0.5 * np.abs(a.mean(0) - b.mean(0)).sum() - spread
+ score[i] = (0.5 * np.abs(a.mean(0) - b.mean(0)).sum() - spread) / SCENE_MOVE
+ if looks is not None:
+ la, lb = np.median(looks[i - win:i], axis=0), np.median(looks[i:i + win], axis=0)
+ score[i] = max(score[i], abs(float(lb[0] - la[0])) / np.log(SCENE_AMOUNT),
+ float(np.hypot(lb[1] - la[1], lb[2] - la[2])) / SCENE_COLOUR)
cuts: list[float] = []
for i in np.argsort(-score):
- if score[i] < SCENE_MOVE:
+ if score[i] < 1.0:
break
t = float(times[i])
if t - start < SCENE_WIN or end - t < SCENE_WIN or any(abs(t - c) < SCENE_WIN for c in cuts):
@@ -193,6 +201,52 @@ def split_scenes(maps: np.ndarray, times: np.ndarray, start: float, end: float)
return list(zip(edges[:-1], edges[1:]))
+def look(bgr: np.ndarray, m: np.ndarray) -> list[float]:
+ """[log cover, a, b] of the drawn layer: how much is drawn and its mean colour (Lab), for split_scenes."""
+ if m.sum() < 10:
+ return [float(np.log(1e-4)), 0.0, 0.0]
+ lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)[m].astype(np.float32)
+ return [float(np.log(m.mean() + 1e-4)), float(lab[:, 1].mean() - 128), float(lab[:, 2].mean() - 128)]
+
+
+def step_motion(prev: np.ndarray, cur: np.ndarray, mask: np.ndarray) -> list[float] | None:
+ """How the drawn layer moved from one sampled frame to the next (gray frames, mask = the drawn layer of prev):
+ [scale, rotation in degrees, pan x, pan y, drift], pan as 0-1 of the frame for the layer's centre, drift = how far
+ single points still move once the whole-layer move is taken out (0-1 of the frame width). None when too little
+ is drawn to follow."""
+ h, w = prev.shape
+ pts = cv2.goodFeaturesToTrack(prev, 300, 0.01, 3, mask=cv2.dilate(mask.astype(np.uint8), np.ones((3, 3), np.uint8)))
+ if pts is None or len(pts) < 8:
+ return None
+ nxt, ok, _ = cv2.calcOpticalFlowPyrLK(prev, cur, pts, None, winSize=(15, 15), maxLevel=2)
+ ok = ok.ravel().astype(bool)
+ p0, p1 = pts.reshape(-1, 2)[ok], nxt.reshape(-1, 2)[ok]
+ if len(p0) < 8:
+ return None
+ A, inl = cv2.estimateAffinePartial2D(p0, p1, method=cv2.RANSAC, ransacReprojThreshold=2.0)
+ if A is None or inl is None or inl.mean() < 0.3: # flickering dots: no one move most points agree on
+ return None
+ c = p0.mean(axis=0)
+ moved = A[:, :2] @ c + A[:, 2]
+ keep = inl.ravel().astype(bool)
+ res = np.linalg.norm(p1[keep] - (p0[keep] @ A[:, :2].T + A[:, 2]), axis=1)
+ return [round(float(np.hypot(A[0, 0], A[1, 0])), 5), round(float(np.degrees(np.arctan2(A[1, 0], A[0, 0]))), 4),
+ round(float(moved[0] - c[0]) / w, 5), round(float(moved[1] - c[1]) / h, 5), round(float(np.median(res)) / w, 5)]
+
+
+def scene_motion(steps: list[list[float]], every: float) -> dict:
+ """Whole-scene motion from the per-step moves: zoom (share per second, + is closer), rotation (degrees per
+ second, + is clockwise on screen), pan (0-1 of the frame per second) and drift (how fast single points wander
+ on their own, 0-1 of the frame width per second)."""
+ if not steps:
+ return {}
+ a = np.array(steps, np.float64)
+ dur = len(a) * every
+ return {"zoom": round(float(np.exp(np.log(a[:, 0]).sum() / dur) - 1), 4), "rotate": round(float(a[:, 1].sum() / dur), 3),
+ "pan": [round(float(a[:, 2].sum() / dur), 4), round(float(a[:, 3].sum() / dur), 4)],
+ "drift": round(float(np.median(a[:, 4]) / every), 4)}
+
+
def shot_label(shot: dict) -> str | None:
"""The shot's current label: after review / correction when there is one, else the measured one."""
base = (shot.get("base") or {}).get("label")
@@ -232,19 +286,27 @@ def scene_frames(out: Path, every: float = 0.25, n_points: int = 4000, all_shots
scenes: list[dict] = []
for s in shots:
st, en = float(s["start"]), float(s["end"])
- maps, times, track = [], [], []
+ maps, times, track, moves, looks = [], [], [], [], []
+ prev = None
for i, f in enumerate(iter_frames(video, info, WORK_W, start=st, duration=en - st, fps=1.0 / every)):
t = st + i * every
m = layer_mask(f, _boxes_at(boxes, t))
maps.append(layout(m).ravel())
+ looks.append(look(f, m))
times.append(t)
+ g = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
+ if prev is not None:
+ mv = step_motion(prev[0], g, prev[1])
+ if mv:
+ moves.append([round(t, 2), *mv])
+ prev = (g, m)
ys, xs = np.nonzero(m)
if len(xs) >= 10: # how the drawing moves: centre, horizontal spread and cover over time
track.append([round(t, 2), round(float(xs.mean()) / f.shape[1], 3), round(float(ys.mean()) / f.shape[0], 3),
round(float(xs.std()) / f.shape[1], 3), round(float(m.mean()), 4)])
if not times:
continue
- for a, z in split_scenes(np.array(maps), np.array(times), st, en):
+ for a, z in split_scenes(np.array(maps), np.array(times), st, en, np.array(looks)):
sid = f"scene_{len(scenes) + 1:02d}"
mid = (a + z) / 2
rec = {"id": sid, "shot": s.get("index"), "start": round(a, 2), "end": round(z, 2), "frames": {}}
@@ -263,6 +325,9 @@ def scene_frames(out: Path, every: float = 0.25, n_points: int = 4000, all_shots
"points": sample_points(img, n_points, in_scene)})
rec["points"] = f"frames/points/{sid}.json"
rec["track"] = [r for r in track if a <= r[0] < z]
+ # a step that straddles a scene change is a rearrangement, not a move
+ rec["motion"] = scene_motion([r[1:] for r in moves if a + every <= r[0] < z], every)
+ rec["enter"] = "morph" if scenes and scenes[-1]["shot"] == s.get("index") else "cut"
scenes.append(rec)
res = {"video": video, "every": every, "track_format": "t cx cy spread cover", "scenes": scenes}
write_json(fdir / "scenes.json", res)
diff --git a/rea_video/packaging.py b/rea_video/packaging.py
index 7307404..ca7d4d3 100644
--- a/rea_video/packaging.py
+++ b/rea_video/packaging.py
@@ -24,6 +24,7 @@ from __future__ import annotations
from .i18n import LangDict, T, join
import re
+import subprocess
from difflib import SequenceMatcher
from pathlib import Path
@@ -177,6 +178,16 @@ def text_style(frame: np.ndarray, box: tuple[int, int, int, int], rendered: bool
sp = {c: spread(c) for c in top}
wide = [c for c in top if sp[c] >= 0.5 * max(sp.values())] or top
fill = min(wide, key=lambda c: (round(bg_contact(c), 1), -sp[c])) if bg_mask.any() else max(wide, key=lambda c: sp[c])
+ if rendered and max(sp.values()) < 0.2:
+ # small text with one- or two-pixel strokes on a rendered picture: no colour has solid strokes, and the
+ # ground seen inside the glyphs or a dark drop shadow is as enclosed as the letters. The letters are the
+ # colour that stands out most from the ground around the line.
+ bg0 = int(np.argmax(ring_share0))
+ far = lambda c: abs(float(centers[c][0] - centers[bg0][0])) + 0.5 * float(np.linalg.norm(centers[c][1:] - centers[bg0][1:])) # noqa: E731
+ lit = [c for c in range(k) if enclosed[c] >= 0.05 * enclosed.max()]
+ best = max(far(c) for c in lit)
+ if best > 30:
+ fill = max((c for c in lit if far(c) >= 0.7 * best), key=lambda c: enclosed[c])
bgr_of = lambda c: cv2.cvtColor(np.uint8([[centers[c]]]), cv2.COLOR_LAB2BGR)[0, 0] # noqa: E731
out: dict = {"fill": _hex(bgr_of(fill)), "fill_name": color_name(bgr_of(fill))}
fm = (enc_mask == fill)
@@ -1493,6 +1504,50 @@ def _ass_color(hexrgb: str | None, default: str) -> str:
return f"&H00{b}{g}{r}".upper()
+FITTED = "; Fontsize fitted to the installed fonts"
+
+
+def fit_ass_sizes(path: Path) -> float | None:
+ """Rescale the Fontsize of every style so the letters come out as tall as measured. to_ass writes the measured
+ letter height, but libass sizes text by the font's whole line (ascent + descent), so letters render smaller by
+ an amount that depends on which fonts are installed. One probe line is rendered with ffmpeg to find out. Returns
+ the factor applied, or None when ffmpeg cannot render ASS (or the file was fitted already)."""
+ path = Path(path)
+ text = path.read_text(encoding="utf-8")
+ if FITTED in text:
+ return None
+ font = next((ln.split(",")[1] for ln in text.splitlines() if ln.startswith("Style: ")), "Sans")
+ probe = ("[Script Info]\nScriptType: v4.00+\nPlayResX: 400\nPlayResY: 200\n\n[V4+ Styles]\n"
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, "
+ "StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"
+ f"Style: p,{font},100,&H00FFFFFF,&H0000FFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,5,0,0,0,1\n\n[Events]\n"
+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"
+ "Dialogue: 0,0:00:00.00,0:00:01.00,p,,0,0,0,,{\\pos(200,100)}国国\n")
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ (Path(td) / "p.ass").write_text(probe, encoding="utf-8")
+ r = subprocess.run(["ffmpeg", "-loglevel", "error", "-f", "lavfi", "-i", "color=black:s=400x200:d=0.1", "-vf", "ass=p.ass",
+ "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "gray", "-"], cwd=td, capture_output=True)
+ if r.returncode != 0 or len(r.stdout) != 400 * 200:
+ return None
+ ys = np.nonzero(np.frombuffer(r.stdout, np.uint8).reshape(200, 400) > 100)[0]
+ if len(ys) < 10:
+ return None
+ k = 100.0 / float(ys.max() - ys.min() + 1)
+ if 0.95 <= k <= 1.05:
+ k = 1.0
+ out = []
+ for ln in text.splitlines():
+ if ln.startswith("Style: "):
+ f = ln.split(",")
+ f[2] = str(max(8, int(round(float(f[2]) * k))))
+ ln = ",".join(f)
+ out.append(ln)
+ out.insert(1, FITTED)
+ path.write_text("\n".join(out) + "\n", encoding="utf-8")
+ return round(k, 3)
+
+
def to_ass(cues: list[dict], width: int, height: int) -> str:
"""Subtitles + 花字 + titles + labels with their measured colours, size and position (\\pos), plus a \\fad / \\t
pop for the measured entrance. Fonts are not measured: replace "Sans" with the real font."""
diff --git a/rea_video/production.py b/rea_video/production.py
index b567dfb..ff2a0da 100644
--- a/rea_video/production.py
+++ b/rea_video/production.py
@@ -621,7 +621,7 @@ def production_plan(b: dict, out: Path, engine: str = "seedance2.0") -> dict:
code_shots = {sh for c in code for sh in c["shots"]}
if code_shots and ps.exists():
try:
- plan["layer_scenes"] = [{k: sc.get(k) for k in ("id", "shot", "start", "end", "points", "frames")} | {"measure": {
+ plan["layer_scenes"] = [{k: sc.get(k) for k in ("id", "shot", "start", "end", "points", "frames", "motion", "enter")} | {"measure": {
k: (sc.get("measure") or {}).get(k) for k in ("ground", "glow", "colours", "pieces", "box")}}
for sc in json.loads(ps.read_text(encoding="utf-8")).get("scenes", []) if sc.get("shot") in code_shots]
except (OSError, ValueError, TypeError):
@@ -713,6 +713,22 @@ def report_parts(plan: dict) -> dict[str, list[str]]:
return {k: v for k, v in parts.items() if any(x.strip() for x in v)}
+def scene_motion_words(sc: dict) -> str:
+ """A scene's measured motion in words: how it enters, zoom, turn, pan and how much single points wander."""
+ m = sc.get("motion") or {}
+ w = [T("从上一场景变形过来", "morphs in from the last scene")] if sc.get("enter") == "morph" else []
+ z, r, (px, py) = m.get("zoom", 0), m.get("rotate", 0), m.get("pan") or (0, 0)
+ if abs(z) >= 0.01:
+ w.append(T(f"{'推近' if z > 0 else '拉远'} {abs(z) * 100:.0f}%/s", f"{'zoom in' if z > 0 else 'zoom out'} {abs(z) * 100:.0f}%/s"))
+ if abs(r) >= 0.5:
+ w.append(T(f"{'顺' if r > 0 else '逆'}时针转 {abs(r):.1f}°/s", f"turns {'clockwise' if r > 0 else 'anticlockwise'} {abs(r):.1f}°/s"))
+ if max(abs(px), abs(py)) >= 0.005:
+ w.append(T(f"平移 ({px * 100:+.1f}%, {py * 100:+.1f}%)/s", f"pans ({px * 100:+.1f}%, {py * 100:+.1f}%)/s"))
+ if m.get("drift", 0) >= 0.004:
+ w.append(T("粒子各自漂动", "points wander"))
+ return T("、", ", ").join(w) or ("—" if not m else T("基本不动", "near still"))
+
+
def layer_scenes_md(scenes: list[dict]) -> list[str]:
"""Rendered shots split into scenes (the drawing rearranges without a cut), with the measured look and where to
find the drawn layer of each."""
@@ -727,9 +743,9 @@ def layer_scenes_md(scenes: list[dict]) -> list[str]:
"removed, alpha by how strongly it stands out), `frames/points/scene_XX.json` samples of that layer, one `x y r g b a` per row "
"with x, y in 0–1. Place particles, trace lines or redraw shapes from these instead of guessing from a description. `track` in "
"`frames/scenes.json` follows the layer's centre and spread over time)"), "",
- T("| 场景 | 镜头 | 时间 | 底色 | 背景光 | 前景颜色 | 块数 | 范围 (x0 y0 x1 y1) |",
- "| Scene | Shot | Time | Ground | Background glow | Drawn colours | Pieces | Area (x0 y0 x1 y1) |"),
- "|---|---|---|---|---|---|---|---|"]
+ T("| 场景 | 镜头 | 时间 | 底色 | 背景光 | 前景颜色 | 块数 | 范围 (x0 y0 x1 y1) | 运动 |",
+ "| Scene | Shot | Time | Ground | Background glow | Drawn colours | Pieces | Area (x0 y0 x1 y1) | Motion |"),
+ "|---|---|---|---|---|---|---|---|---|"]
for sc in scenes:
m = sc.get("measure") or {}
gl = m.get("glow") or {}
@@ -738,7 +754,7 @@ def layer_scenes_md(scenes: list[dict]) -> list[str]:
cols = " ".join(c["hex"] for c in m.get("colours") or []) or "—"
box = " ".join(f"{v:.2f}" for v in m.get("box") or []) or "—"
L.append(f"| {sc['id']} | #{sc['shot']} | {sc['start']:.1f}–{sc['end']:.1f}s | {m.get('ground') or '—'} | {gw} | {cols} | "
- f"{m.get('pieces') or '—'} | {box} |")
+ f"{m.get('pieces') or '—'} | {box} | {scene_motion_words(sc)} |")
L += ["", T("做完用 `rea-video compare 原片 成片 --scenes frames/scenes.json -o 对比目录` 打分(两边各按自己的底色取前景,换了底色也能比),"
"按 `compare_worst.jpg` 先改分数最低的场景。",
"When built, score it with `rea-video compare original remake --scenes frames/scenes.json -o dir` (each side's drawn layer "
@@ -854,7 +870,13 @@ def report_md(plan: dict) -> list[str]:
L += ["", T("### 代码合成", "### Code composition"), "",
T("一个 Remotion/HTML 工程,按文字轨和版式重建(文字、界面 100% 可控,改文案只改数据);可以让 LLM 直接写这个工程。",
"One Remotion / HTML project rebuilt from the text tracks and layout (text and UI are 100% controllable; changing copy is a data "
- "change). An LLM can write this project directly."), ""]
+ "change). An LLM can write this project directly."), "",
+ T("先跑 `rea-video code-remake <拆解目录>`:按下面每个场景的采样点 / 抠图、运动和背景光写出 `code/spec.json` + `code/render.py`,"
+ "逐场景对齐原片的量和亮度后渲染出 `code/remake.mp4` 并打分。从这一版改起(改 spec.json、换采样点、或照它改写成 Remotion),不要从零写。",
+ "Start with `rea-video code-remake <breakdown folder>`: it writes `code/spec.json` + `code/render.py` from each scene's sampled "
+ "points / cut-out, motion and background glow below, matches each scene's amount and brightness to the original, renders "
+ "`code/remake.mp4` and scores it. Work from that version (edit spec.json, swap the points, or port it to Remotion) instead of "
+ "writing one from scratch."), ""]
for c in plan["code"]:
L.append(T("- {id}:镜头 {sh}({a:.1f}–{z:.1f}s)", "- {id}: shots {sh} ({a:.1f}–{z:.1f}s)",
id=c["id"], sh=shot_ids(c["shots"]), a=c["start"], z=c["end"])
diff --git a/rea_video/redraw.py b/rea_video/redraw.py
new file mode 100644
index 0000000..0343ec4
--- /dev/null
+++ b/rea_video/redraw.py
@@ -0,0 +1,246 @@
+"""Redraw a code-rendered video from its measured scenes: a starting remake that already sits on the original's shapes.
+
+`rea-video code-remake out/ref` copies this file into `out/ref/code/render.py` next to `spec.json`, so the remake
+project runs on its own (Python with numpy and opencv, plus ffmpeg) and can be edited freely.
+
+ python render.py # spec.json -> remake.mp4
+ python render.py --frame 12.5 # one frame as frame_12.50.png, to check a scene quickly
+ python render.py --start 10 --end 20 # a stretch only
+
+spec.json holds everything that decides the picture; change values there rather than in this file:
+
+- size, fps, duration; text: an ASS file burnt in on top (the measured subtitles and labels)
+- bloom: how much the drawing glows (0 = none); bloom_size: how wide, as a share of the frame width
+- scenes, one per stretch where the drawing keeps its arrangement:
+ - start, end (seconds); ground: background colour; glow: soft background light (colour, centre 0-1, radius 0-1 of
+ the width, strength)
+ - draw: "points" (particles placed on the sampled points) or "cutout" (the cut-out picture of the drawn layer, moved)
+ - points: JSON with rows [x, y, r, g, b, a] (x, y 0-1); a remake with new shapes swaps this file for its own
+ - count: particles drawn; dot: particle radius in pixels; gain: brightness of the drawing
+ - motion: zoom (share per second), rotate (degrees per second, clockwise), pan ([x, y] share of the frame per
+ second), drift (how far each particle wanders, share of the width per second), twinkle (0-1)
+ - enter: "morph" (particles travel from the previous scene's places over enter_s seconds) or "cut"
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import cv2
+import numpy as np
+
+
+def _bgr(hexs: str) -> np.ndarray:
+ h = hexs.lstrip("#")
+ return np.array([int(h[4:6], 16), int(h[2:4], 16), int(h[0:2], 16)], np.float32) / 255.0
+
+
+def _zorder(xy: np.ndarray) -> np.ndarray:
+ """Order points along a Z curve, so two shapes sorted this way pair up points that sit near each other."""
+ q = np.clip((xy * 1023).astype(np.int64), 0, 1023)
+ code = np.zeros(len(xy), np.int64)
+ for b in range(10):
+ code |= ((q[:, 0] >> b) & 1) << (2 * b) | ((q[:, 1] >> b) & 1) << (2 * b + 1)
+ return np.argsort(code, kind="stable")
+
+
+def _ease(x: float) -> float:
+ x = min(1.0, max(0.0, x))
+ return x * x * (3 - 2 * x)
+
+
+class Scene:
+ def __init__(self, sc: dict, base: Path, W: int, H: int, seed: int):
+ self.sc, self.W, self.H = sc, W, H
+ self.start, self.end = float(sc["start"]), float(sc["end"])
+ self.draw = sc.get("draw", "points")
+ m = sc.get("motion") or {}
+ self.zoom, self.rot = float(m.get("zoom", 0)), float(m.get("rotate", 0))
+ self.pan = np.array(m.get("pan", [0, 0]), np.float32) * (W, H)
+ self.drift = float(m.get("drift", 0)) * W
+ self.twinkle = float(m.get("twinkle", 0.15))
+ self.gain = float(sc.get("gain", 1.0))
+ self.dot = float(sc.get("dot", 1.0))
+ g = sc.get("glow") or {}
+ self.ground = _bgr(sc.get("ground", "#000000"))
+ self.bg = np.empty((H, W, 3), np.float32)
+ self.bg[:] = self.ground
+ if g.get("colour"):
+ yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
+ cx, cy = g.get("centre", [0.5, 0.5])
+ sigma = max(1.0, float(g.get("radius", 0.15)) * W / 1.177) # radius is where the glow is half its peak
+ fall = np.exp(-((xx - cx * W) ** 2 + (yy - cy * H) ** 2) / (2 * sigma * sigma))
+ amp = np.clip(_bgr(g["colour"]) - self.ground, 0, None) * float(g.get("strength", 1.0))
+ self.bg += fall[..., None] * amp
+ self.centre = np.array(sc.get("centre", [0.5, 0.5]), np.float32) * (W, H)
+ rng = np.random.default_rng(seed)
+ if self.draw == "cutout":
+ img = cv2.imread(str(base / sc["cutout"]), cv2.IMREAD_UNCHANGED)
+ img = cv2.resize(img, (W, H), interpolation=cv2.INTER_AREA)
+ a = img[..., 3:4].astype(np.float32) / 255.0
+ self.layer = img[..., :3].astype(np.float32) / 255.0 * a
+ return
+ rows = np.array(json.loads((base / sc["points"]).read_text(encoding="utf-8"))["points"], np.float32).reshape(-1, 6)
+ n = int(sc.get("count", len(rows)))
+ if not len(rows) or n <= 0:
+ rows, n = np.zeros((0, 6), np.float32), 0
+ idx = np.arange(n) % max(1, len(rows))
+ pick = rows[idx]
+ xy = pick[:, :2] * (W, H)
+ extra = np.arange(n) >= len(rows) # more particles than samples: spread the copies around their sample
+ xy[extra] += rng.normal(0, max(1.5, 2.5 * self.dot), (int(extra.sum()), 2))
+ order = _zorder(xy / (W, H))
+ self.xy = xy[order].astype(np.float32)
+ self.col = (pick[order][:, [4, 3, 2]] / 255.0 * pick[order][:, 5:6]).astype(np.float32)
+ self.phase = rng.uniform(0, 2 * np.pi, (n, 3)).astype(np.float32)
+ self.freq = rng.uniform(0.15, 0.45, (n, 2)).astype(np.float32)
+
+ def _move(self, xy: np.ndarray, tau: float) -> np.ndarray:
+ s = (1 + self.zoom) ** tau
+ a = np.radians(self.rot * tau)
+ R = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]], np.float32) * s
+ return (xy - self.centre) @ R.T + self.centre + self.pan * tau
+
+ def particles(self, t: float) -> tuple[np.ndarray, np.ndarray]:
+ tau = t - self.start
+ xy = self._move(self.xy, tau)
+ if self.drift:
+ amp = self.drift / (2 * np.pi * 0.3) # wander at the measured speed around a fixed place, without flicker
+ w = 2 * np.pi * self.freq * tau
+ xy = xy + amp * np.stack([np.sin(w[:, 0] + self.phase[:, 0]), np.cos(w[:, 1] + self.phase[:, 1])], 1)
+ col = self.col * (1 - self.twinkle + self.twinkle * (0.5 + 0.5 * np.sin(3 * tau + self.phase[:, 2:3])))
+ return xy, col * self.gain
+
+ def matrix(self, t: float) -> np.ndarray:
+ tau = t - self.start
+ s = (1 + self.zoom) ** tau
+ M = cv2.getRotationMatrix2D(tuple(map(float, self.centre)), -self.rot * tau, s)
+ M[:, 2] += self.pan * tau
+ return M
+
+
+class Redraw:
+ def __init__(self, spec_path: Path):
+ self.path = Path(spec_path)
+ self.base = self.path.parent
+ self.spec = json.loads(self.path.read_text(encoding="utf-8"))
+ self.W, self.H = self.spec["size"]
+ self.scenes = [Scene(sc, self.base, self.W, self.H, i) for i, sc in enumerate(self.spec["scenes"])]
+ self.ground = np.zeros((self.H, self.W, 3), np.float32)
+
+ def at(self, t: float) -> tuple[int, Scene | None]:
+ for i, s in enumerate(self.scenes):
+ if s.start <= t < s.end:
+ return i, s
+ return -1, None
+
+ def _splat(self, buf: np.ndarray, xy: np.ndarray, col: np.ndarray) -> None:
+ """Add each particle's colour at its sub-pixel place (shared between the four nearest pixels, so slow
+ movement stays smooth)."""
+ H, W = buf.shape[:2]
+ x0, y0 = np.floor(xy[:, 0]), np.floor(xy[:, 1])
+ fx, fy = xy[:, 0] - x0, xy[:, 1] - y0
+ flat = buf.reshape(-1, 3)
+ for dx, dy, wt in ((0, 0, (1 - fx) * (1 - fy)), (1, 0, fx * (1 - fy)), (0, 1, (1 - fx) * fy), (1, 1, fx * fy)):
+ xi, yi = (x0 + dx).astype(np.int64), (y0 + dy).astype(np.int64)
+ ok = (xi >= 0) & (xi < W) & (yi >= 0) & (yi < H)
+ k = yi[ok] * W + xi[ok]
+ for c in range(3):
+ flat[:, c] += np.bincount(k, weights=col[ok, c] * wt[ok], minlength=H * W).astype(np.float32)
+
+ def frame(self, t: float) -> np.ndarray:
+ i, s = self.at(t)
+ if s is None:
+ return np.zeros((self.H, self.W, 3), np.uint8)
+ prev = self.scenes[i - 1] if i > 0 else None
+ enter = float(s.sc.get("enter_s", 0.6))
+ mix = _ease((t - s.start) / enter) if (s.sc.get("enter") == "morph" and prev is not None and enter > 0) else 1.0
+ bg = s.bg if mix >= 1 else prev.bg * (1 - mix) + s.bg * mix
+ drawn = np.zeros((self.H, self.W, 3), np.float32)
+ if s.draw == "cutout":
+ drawn += cv2.warpAffine(s.layer, s.matrix(t), (self.W, self.H)) * s.gain * mix
+ if mix < 1 and prev.draw == "cutout":
+ drawn += cv2.warpAffine(prev.layer, prev.matrix(prev.end), (self.W, self.H)) * prev.gain * (1 - mix)
+ dot = 0.0
+ else:
+ xy, col = s.particles(t)
+ dot = s.dot
+ if mix < 1 and prev.draw == "points" and len(prev.xy) and len(xy):
+ pxy, pcol = prev.particles(prev.end)
+ j = (np.arange(len(xy)) * len(pxy)) // len(xy) # both are in Z order: neighbours travel to neighbours
+ xy = pxy[j] * (1 - mix) + xy * mix
+ col = pcol[j] * (1 - mix) + col * mix
+ dot = prev.dot * (1 - mix) + s.dot * mix
+ if len(xy):
+ self._splat(drawn, xy, col)
+ sig = max(0.6, 0.7 * dot)
+ drawn = cv2.GaussianBlur(drawn, (0, 0), sig) * (2 * np.pi * sig * sig)
+ bloom = float(self.spec.get("bloom", 0.8))
+ if bloom > 0:
+ small = cv2.resize(drawn, (self.W // 4, self.H // 4), interpolation=cv2.INTER_AREA)
+ size = float(self.spec.get("bloom_size", 0.012)) * self.W / 4
+ glow = cv2.GaussianBlur(small, (0, 0), size) + 0.5 * cv2.GaussianBlur(small, (0, 0), 3 * size)
+ drawn = drawn + bloom * cv2.resize(glow, (self.W, self.H), interpolation=cv2.INTER_LINEAR)
+ out = bg + drawn
+ out = np.where(out > 0.85, 0.85 + 0.15 * np.tanh((out - 0.85) / 0.15), out) # soft roll-off instead of hard clipping
+ return (np.clip(out, 0, 1) * 255 + 0.5).astype(np.uint8)
+
+
+def _has_ass() -> bool:
+ try:
+ r = subprocess.run(["ffmpeg", "-hide_banner", "-filters"], capture_output=True, text=True)
+ return " ass " in r.stdout
+ except OSError:
+ return False
+
+
+def render(spec_path: Path, out: Path, start: float = 0.0, end: float | None = None, text: bool = True) -> Path:
+ rd = Redraw(spec_path)
+ fps = float(rd.spec.get("fps", 25))
+ end = float(rd.spec["duration"]) if end is None else end
+ vf = []
+ ass = rd.spec.get("text")
+ if text and ass and (rd.base / ass).exists():
+ if _has_ass():
+ vf = ["-vf", f"setpts=PTS+{start}/TB,ass={ass},setpts=PTS-STARTPTS"]
+ else:
+ print("ffmpeg has no ass filter (libass): text left out", file=sys.stderr)
+ cmd = ["ffmpeg", "-loglevel", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{rd.W}x{rd.H}",
+ "-r", f"{fps:g}", "-i", "-", *vf, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(Path(out).resolve())]
+ p = subprocess.Popen(cmd, stdin=subprocess.PIPE, cwd=rd.base)
+ n = int(round((end - start) * fps))
+ for k in range(n):
+ p.stdin.write(rd.frame(start + k / fps).tobytes())
+ p.stdin.close()
+ if p.wait() != 0:
+ raise RuntimeError("ffmpeg failed")
+ return Path(out)
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description="Render spec.json to a video, or one frame of it")
+ ap.add_argument("spec", nargs="?", default=str(Path(__file__).with_name("spec.json")))
+ ap.add_argument("-o", "--out")
+ ap.add_argument("--frame", type=float, help="render the frame at this second to a PNG")
+ ap.add_argument("--start", type=float, default=0.0)
+ ap.add_argument("--end", type=float)
+ ap.add_argument("--no-text", action="store_true")
+ a = ap.parse_args(argv)
+ spec = Path(a.spec)
+ if a.frame is not None:
+ out = Path(a.out or spec.with_name(f"frame_{a.frame:.2f}.png"))
+ cv2.imwrite(str(out), Redraw(spec).frame(a.frame))
+ else:
+ if not shutil.which("ffmpeg"):
+ raise SystemExit("ffmpeg not found")
+ out = render(spec, Path(a.out or spec.with_name("remake.mp4")), a.start, a.end, text=not a.no_text)
+ print(out)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/rea_video/remake.py b/rea_video/remake.py
index 1f49274..c7dc127 100644
--- a/rea_video/remake.py
+++ b/rea_video/remake.py
@@ -99,7 +99,7 @@ def replaced_spans(b: dict, legend: list[tuple]) -> list[tuple[float, float]]:
shots = {sh["index"]: sh for sh in b["shots"]}
spans: list[list[float]] = []
for i, how in legend:
- if how == "original":
+ if how in ("original", "code"): # both already carry their text
continue
a, z = shots[i]["start"], shots[i]["end"]
if spans and abs(spans[-1][1] - a) < 1e-3:
@@ -134,12 +134,16 @@ def overlay_cues(b: dict, spans: list[tuple[float, float]]) -> tuple[list[dict],
return cues, stickers
-def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = None, overlays: bool = False) -> str:
+def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = None, overlays: bool = False,
+ code_video: Path | None = None, extra: dict | None = None) -> str:
+ """code_video: a remake of the code-rendered shots on the original timeline (`code-remake`), cut in for them.
+ extra: more {shot: {"video": path}} results on top of results_path's (later ones win)."""
b = read_json(breakdown_path)
bdir = breakdown_path.parent
jobs_path = results_path.with_name("jobs.json")
jobs = {j["shot"]: j for j in read_json(jobs_path)["jobs"]} if jobs_path.is_file() else {}
results = read_json(results_path).get("results", {}) if results_path.is_file() else {}
+ results = {**results, **{str(k): v for k, v in (extra or {}).items()}}
out_dir = out_dir or results_path.parent
seg_dir = out_dir / "segments"
seg_dir.mkdir(parents=True, exist_ok=True)
@@ -158,6 +162,9 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = No
if res.get("video") and Path(res["video"]).is_file():
_fit_clip(Path(res["video"]), seg, dur, (w, h), fps)
legend.append((sh["index"], "generated"))
+ elif code_video and sh["base"]["label"] == "code_render" and Path(code_video).is_file():
+ _original_segment(Path(code_video), seg, sh["start"], dur, (w, h), fps)
+ legend.append((sh["index"], "code"))
elif job.get("executor") == "local_ffmpeg" or sh["base"]["label"] in ("still_motion", "static_hold"):
m = sh["replication"].get("local", {})
img = bdir / sh["assets"]["first_frame"]
@@ -174,12 +181,13 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = No
_ff(["-f", "concat", "-safe", "0", "-i", str(lst), "-c", "copy", str(silent)])
overlay_log: dict = {}
if overlays:
- from .packaging import to_ass
+ from .packaging import fit_ass_sizes, to_ass
cues, stickers = overlay_cues(b, replaced_spans(b, legend))
overlay_log = {"text": len(cues), "stickers_to_add": stickers}
if cues:
(out_dir / "overlays_remake.ass").write_text(to_ass(cues, w, h), encoding="utf-8")
+ fit_ass_sizes(out_dir / "overlays_remake.ass")
try: # relative name + cwd: no filter-string escaping of the path
_ff(["-i", silent.name, "-vf", "ass=overlays_remake.ass", "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p",
"remake_overlaid.mp4"], cwd=out_dir)
@@ -210,3 +218,84 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = No
(out_dir / "assemble_log.json").write_text(json.dumps(log, ensure_ascii=False, indent=2), encoding="utf-8")
LOG.info("remake -> %s ; compare -> %s", final, compare)
return json.dumps(log, ensure_ascii=False)
+
+
+GENERATED = ("ai_video", "cg_3d", "anim_2d", "stop_motion", "avatar")
+
+
+def _next_step(sh: dict) -> str:
+ """What still has to happen for a shot that is showing the original."""
+ from .i18n import T
+
+ lab = sh["base"]["label"]
+ need = (sh.get("replication") or {}).get("user_assets") or []
+ if lab in GENERATED:
+ return T("生成:用报告「生成单元」的提示词在网页上手动生成,或 remake-plan + remake-run(计费,先 --dry-run)",
+ "generate: paste the report's generation-unit prompt into a video model, or remake-plan + remake-run (paid; --dry-run first)")
+ if lab == "live_action":
+ return T("拍摄:按报告的拍摄方案拍", "shoot it: follow the report's shooting plan") + (
+ T("(要用到:{a})", " (needs: {a})", a="、".join(str(a) for a in need)) if need else "")
+ if lab == "screen_capture":
+ return T("录屏:按原片的操作重录一遍", "record the screen: redo the same steps")
+ if lab == "film_footage":
+ return T("影视片段:找到原片对应片段(有版权),或换成自己拍的", "film clip: find it in the source (rights apply) or shoot your own")
+ if lab == "code_render":
+ return T("代码渲染:rea-video code-remake 没跑成,先单独跑它看报错", "code render: code-remake did not run; run it alone to see why")
+ return T("提供素材", "provide the footage")
+
+
+def remake(out: Path, code: bool = True, overlays: bool = True) -> dict:
+ """The whole remake in one pass, as far as it can go without paid generation or the user's own footage:
+ code-rendered shots are redrawn (code-remake), stills are rebuilt from the measured move, clips already
+ generated (remake/results.json from remake-run) or supplied (remake/mine.json, {"results": {"<shot>": {"video": path}}})
+ are cut in, everything else keeps the original as a stand-in. Writes remake/remake.mp4, remake/compare.mp4 and
+ remake/status.md (per shot: how it is made now and what is still to do). Run it again whenever a clip comes in."""
+ from .i18n import T
+ from .util import write_json
+
+ out = Path(out)
+ b = read_json(out / "breakdown.json")
+ rdir = out / "remake"
+ rdir.mkdir(exist_ok=True)
+ res: dict = {}
+ code_video = out / "code" / "remake.mp4"
+ if code and any(sh["base"]["label"] == "code_render" for sh in b["shots"]):
+ from .code_remake import code_remake
+
+ try:
+ if not code_video.is_file():
+ cr = code_remake(out)
+ res["code_score"] = (cr.get("compare") or {}).get("score")
+ except (ValueError, OSError, RuntimeError) as e:
+ res["code_error"] = str(e)
+ mine = rdir / "mine.json"
+ extra = read_json(mine).get("results", {}) if mine.is_file() else {}
+ log = json.loads(assemble(out / "breakdown.json", rdir / "results.json", rdir, overlays=overlays,
+ code_video=code_video if code_video.is_file() else None, extra=extra))
+ how = dict(log["legend"])
+ HOW = {"generated": T("生成 / 你的素材", "generated / your footage"), "code": T("代码重画", "redrawn in code"),
+ "local_still": T("静图按测得的运动重建", "still rebuilt with the measured move"), "original": T("原片占位", "original as stand-in")}
+ rows, todo = [], []
+ for sh in b["shots"]:
+ h = how.get(sh["index"], "original")
+ nxt = _next_step(sh) if h == "original" else ""
+ rows.append({"shot": sh["index"], "start": sh["start"], "end": sh["end"], "label": sh["base"]["label"], "now": h, "next": nxt})
+ if nxt:
+ todo.append(sh["index"])
+ done = sum(r["end"] - r["start"] for r in rows if r["now"] != "original")
+ total = sum(r["end"] - r["start"] for r in rows) or 1.0
+ L = [T("# 复刻进度", "# Remake status"), "",
+ T(f"已经替换 {done / total:.0%} 时长;成片 `remake/{Path(log['remake']).name}`,左右对比 `remake/compare.mp4`。",
+ f"{done / total:.0%} of the running time replaced; video `remake/{Path(log['remake']).name}`, side by side `remake/compare.mp4`."), "",
+ T("拿到新的镜头视频(生成的或用户自己的)就写进 `remake/mine.json`:`{\"results\": {\"镜头号\": {\"video\": \"绝对路径\"}}}`,再跑一次 `rea-video remake <目录>`。",
+ "When a clip comes in (generated or the user's own), add it to `remake/mine.json`: `{\"results\": {\"<shot>\": {\"video\": \"<absolute path>\"}}}`, then run `rea-video remake <folder>` again."),
+ "", T("| 镜头 | 时间 | 画面类型 | 现在 | 还要做 |", "| Shot | Time | Picture | Now | To do |"), "|---|---|---|---|---|"]
+ from .classify import LABEL_ZH
+
+ for r in rows:
+ L.append(f"| #{r['shot']} | {r['start']:.1f}–{r['end']:.1f}s | {LABEL_ZH.get(r['label'], r['label'])} | {HOW[r['now']]} | {r['next'] or '—'} |")
+ (rdir / "status.md").write_text("\n".join(L) + "\n", encoding="utf-8")
+ write_json(rdir / "status.json", {"replaced_share": round(done / total, 3), "shots": rows})
+ res.update({"remake": log["remake"], "compare": log["compare"], "status": str(rdir / "status.md"),
+ "replaced_share": round(done / total, 3), "to_do": todo})
+ return res
diff --git a/rea_video/videomd.py b/rea_video/videomd.py
index 1dcc919..f7904a2 100644
--- a/rea_video/videomd.py
+++ b/rea_video/videomd.py
@@ -248,6 +248,25 @@ def _sha256(path) -> str | None:
return h.hexdigest()
+def _next_steps(b: dict) -> list[str]:
+ """The commands to run next for this video, so a reader of this page alone takes the right route."""
+ labels = {sh["base"]["label"] for sh in b["shots"]}
+ L = []
+ if not (b.get("analysis") or {}).get("review") and not ((b.get("analysis") or {}).get("vlm") or {}).get("used"):
+ L.append(T("没开 VLM:能看图就先复核,`rea-video review <本目录>` → 填 `review_answers.json` → `rea-video apply-review <本目录>`",
+ "No VLM ran: if you can see images, review first: `rea-video review <this dir>` → fill `review_answers.json` → `rea-video apply-review <this dir>`"))
+ L.append(T("复刻:`rea-video remake <本目录>`,能自动做的先做掉,其余原片占位;`remake/status.md` 逐镜写了还要做什么。拿到新镜头写进 `remake/mine.json` 再跑一次",
+ "Remake: `rea-video remake <this dir>` does what can be done automatically and keeps the original elsewhere; `remake/status.md` "
+ "says per shot what is left. Add incoming clips to `remake/mine.json` and run it again"))
+ if "code_render" in labels:
+ L.append(T("代码渲染镜头由 `rea-video code-remake <本目录>` 重画(上一条会自动跑):改 `code/spec.json` 再跑,不要从零写",
+ "Code-rendered shots are redrawn by `rea-video code-remake <this dir>` (the step above runs it): edit `code/spec.json` and rerun, do not write one from scratch"))
+ if labels & {"ai_video", "cg_3d", "anim_2d", "stop_motion", "avatar"}:
+ L.append(T("AI 类镜头:提示词在 `video/remake.md` 的「生成单元」;要自动生成跑 `rea-video remake-plan` + `remake-run --dry-run`,会计费,先问用户",
+ "AI shots: prompts are in the generation units of `video/remake.md`; for automatic generation run `rea-video remake-plan` + `remake-run --dry-run` (paid: ask the user first)"))
+ return L
+
+
def _overview(b: dict, files: list[tuple[str, str, str, int]]) -> str:
s = b["summary"]
w = b.get("whole_video_vlm") or {}
@@ -266,6 +285,7 @@ def _overview(b: dict, files: list[tuple[str, str, str, int]]) -> str:
if rm.get("shots"):
L.append(T("**要拿到的真实素材**:{n} 个镜头({r:.0%} 时长),清单见 `{d}/remake.md`", "**Real material to collect**: {n} shots ({r:.0%} of the duration), list in `{d}/remake.md`", d=DIR,
n=len(rm["shots"]), r=rm["ratio"]))
+ L += ["", T("## 下一步", "## Next steps"), ""] + [f"- {x}" for x in _next_steps(b)]
qs = entities.open_questions(b)
L += ["", T("## 不确定点", "## Open questions"), ""] + ([f"- {_one_line(q, 160)}" for q in qs[:8]] or [T("- 没有", "- None")])
if len(qs) > 8:
diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.md
index ab86536..2634b28 100644
--- a/skills/rea-video/SKILL.md
+++ b/skills/rea-video/SKILL.md
@@ -95,7 +95,7 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复
## 3. 复刻(需要时)
-见 `references/remake.md`;可用的工具和方式(capsule-cinema、ChatCut、自己动手)和各自的特点列在 `references/remake-tools.md`。在本工具里直接跑:AI 镜头走 capsule-cinema(会计费,先 `rea-video remake-run --dry-run` 并征得用户同意);实拍给拍摄方案;代码渲染用 Remotion(形状照 `frames/` 里的抠图和采样点做,做完用 `rea-video compare` 对原片打分);用户自己的素材用 `rea-video assemble` 拼回原时间线。代码渲染和用户自己的素材也可以在 ChatCut 里做。
+先跑 `rea-video remake out/ref`:能自动做的镜头先做掉(代码渲染重画、静图重建),其余原片占位,拼回原时间线,`remake/status.md` 逐镜写了还要做什么;拿到新镜头写进 `remake/mine.json` 再跑一次。细节见 `references/remake.md`;可用的工具和方式(capsule-cinema、ChatCut、自己动手)和各自的特点列在 `references/remake-tools.md`。在本工具里直接跑:AI 镜头走 capsule-cinema(会计费,先 `rea-video remake-run --dry-run` 并征得用户同意);实拍给拍摄方案;代码渲染先跑 `rea-video code-remake out/ref` 出第一版(可改的工程 + 成片 + 打分),在它上面改,不要从零写;用户自己的素材用 `rea-video assemble` 拼回原时间线。代码渲染和用户自己的素材也可以在 ChatCut 里做。
## 参考文件
diff --git a/skills/rea-video/references/remake.md b/skills/rea-video/references/remake.md
index 8e19e8c..571123b 100644
--- a/skills/rea-video/references/remake.md
+++ b/skills/rea-video/references/remake.md
@@ -2,6 +2,10 @@
复刻可以用的工具和方式单独列在 `remake-tools.md`,告诉用户有哪些可选时看那个文件。
+## 先跑一条命令
+
+`rea-video remake out/ref`:代码渲染镜头重画(自动跑 `code-remake`),静图按测得的运动重建,`remake/results.json`(`remake-run` 生成的)和 `remake/mine.json`(用户给的或网页上手动生成的,格式 `{"results": {"镜头号": {"video": "绝对路径"}}}`)里的镜头剪进去,其余原片占位,按原时间线拼好,叠回字幕。`remake/status.md` 逐镜写了现在是怎么做的、还要做什么。每拿到一个新镜头就写进 `mine.json` 再跑一次。下面各节是每类镜头的细节。
+
## 用哪个模型
- 用户指定了视频模型:拆解时加 `--engine <id>`(`rea-video models` 列出可选的 id);已经拆完的用 `rea-video models <id> --plan out/ref` 改按它重出方案。
@@ -13,10 +17,11 @@
- **AI 类镜头**:用原镜头首尾帧加 VLM 提示词,通过 [capsule-cinema](https://github.com/JuneYaooo/capsule-cinema) 生成(会计费,先 `--dry-run`,并征得用户同意)。
- **静态图推拉、静帧**:本地按测得的运动参数重建。
-- **代码渲染**:用 Remotion 重建,或在 ChatCut 里生成动效图形。用 Remotion 时,把报告「代码合成」一节(每镜做法、逐镜动效时间轴、色值)连同 `shots/` 里的元素截图、关键帧条和 `packaging/overlays.ass` 一起交给写代码的人或 LLM;按时间轴的时间和位置写动画,按截图重画图形,图标 / Logo / 插画这类画不出来的直接抠图用。
- - 拆片包的 `frames/` 里每个场景有原尺寸帧、画上去那一层的抠图(`scene_XX_layer.png`)和采样点(`points/`,x、y 为 0–1 坐标):粒子、线条、图形照着摆或描,不要照文字描述去猜形状。旧目录没有 `frames/` 时运行 `rea-video frames out/ref`。
- - 做完用 `rea-video compare 原片 成片 --scenes out/ref/frames/scenes.json -o 对比目录` 打分,按输出里的 `advice`(时间早晚、位置、范围、多少、颜色)先改分数最低的场景,对照 `compare_worst.jpg` 看。
-- **真实素材**:列清单让用户提供;拿到后用 `rea-video assemble` 拼回原时间线,或放进 ChatCut 按原片节奏剪。
+- **代码渲染**:先跑 `rea-video code-remake out/ref`。它按拆片包 `frames/` 里每个场景的采样点或抠图、测得的运动和背景光,写出 `out/ref/code/`(`spec.json` 每个场景一项、`render.py` 渲染器、`overlays.ass` 文字),逐场景把量和亮度对齐原片,渲染出 `code/remake.mp4`,再和原片打分。
+ - 往下改都从这一版开始:先改 `spec.json` 里的数(粒子数 `count`、大小 `dot`、亮度 `gain`、运动 `motion`、背景光 `glow`);要换成新形状,就把 `points` 换成自己的点文件;要做原片没有的效果再改 `render.py`,或照着它改写成 Remotion / Three.js。改完重跑同一条命令,改过的 `spec.json` 会保留,`--reset` 才会从头重建。`python code/render.py --frame 12.5` 可以只出一帧来看。
+ - 按输出里 `lowest_scenes` 的 `advice` 改,先改分数最低的场景,对照 `code/compare/compare_worst.jpg` 看。
+ - 报告「代码合成」一节的每镜画面描述、`shots/` 里的元素截图和关键帧条,用来补工具测不到的东西:标注怎么入场、图形是什么含义。
+- **真实素材**:列清单让用户提供;拿到后写进 `remake/mine.json` 再跑 `rea-video remake`,或放进 ChatCut 按原片节奏剪。
- **表演和情绪**:报告「表演与情绪」一节逐镜写了情绪、表情、动作和语气,生成单元的提示词里已经带上表情和动作。改写提示词时保留看得见的表情和动作,不要换成「开心」「难过」这类词,也不要把幅度写大;有台词的镜头先做有语气的配音,再让画面跟着声音演。
- **声音**:TTS(按脚本表里每句的语气)、BGM(按 BPM / 调性 / 情绪)、音效(按时间点)三条轨分别准备。
- **剪辑包装(字幕、花字、贴纸)**:不进生成。生成模型只出干净的人和画面,包装层最后按「剪辑包装层」的时间轴叠上去,这样字不会被模型画糊,换文案时也只改包装层。
@@ -26,9 +31,9 @@
**用户自己拍的素材、或在网页上手动生成的视频,拼回原时间线**(不需要 capsule-cinema):
1. 按分镜表(`report.md` 的镜头号和时长)把素材对应到镜头。一条长素材覆盖多个镜头时,先用 ffmpeg 按动作切开;拿不准对应关系时给用户看截图确认。
-2. 写一个 `results.json`:`{"results": {"<镜头号>": {"video": "<素材绝对路径>"}, ...}}`。手动生成的「生成单元」视频覆盖多个镜头时,同样先按单元提示词里的「镜头i(a–b s)」时间切开再填。
-3. `rea-video assemble out/ref/breakdown.json <results.json 路径>`:每段生成素材整段变速塞进原镜头时长(最多快 3 倍、慢 1.25 倍,超出部分再裁),切点和原片对齐,没填的镜头暂时用原片占位,声音沿用原片;输出 `remake.mp4` 和左右对比的 `compare.mp4`。告诉用户哪些镜头还是原片占位、声音还要换。
- - 加 `--overlays`:把测得的字幕 / 花字 / 标题按原样式叠到换掉的镜头上(原片占位的镜头本来就有字,不重复叠)。字体是通用无衬线体,颜色和底框是测量值,可能和原片有出入;贴纸只在 `assemble_log.json` 的 `stickers_to_add` 里列出来,要自己找素材贴。
+2. 写进 `out/ref/remake/mine.json`:`{"results": {"<镜头号>": {"video": "<素材绝对路径>"}, ...}}`。手动生成的「生成单元」视频覆盖多个镜头时,同样先按单元提示词里的「镜头i(a–b s)」时间切开再填。
+3. `rea-video remake out/ref`:每段素材整段变速塞进原镜头时长(最多快 3 倍、慢 1.25 倍,超出部分再裁),切点和原片对齐,没填的镜头暂时用原片占位,声音沿用原片;输出 `remake/remake.mp4`、左右对比的 `remake/compare.mp4` 和 `remake/status.md`。告诉用户哪些镜头还是原片占位、声音还要换。只想拼不想重画代码镜头时用 `rea-video assemble out/ref/breakdown.json <results.json 路径>`。
+ - 字幕叠回(`remake` 默认叠,`assemble` 要加 `--overlays`):把测得的字幕 / 花字 / 标题按原样式叠到换掉的镜头上(原片占位的镜头本来就有字,不重复叠)。字体是通用无衬线体,颜色和底框是测量值,可能和原片有出入;贴纸只在 `assemble_log.json` 的 `stickers_to_add` 里列出来,要自己找素材贴。
**自动生成的限制**:`remake-plan` 和 capsule-cinema 目前还是一个镜头调一次模型;报告里「生成单元」的多镜头提示词要用户手动贴到支持多镜头的模型(如即梦 / Seedance 2.5)上用。向用户说明这一点,并给出两种做法的调用次数。
diff --git a/tests/test_code_remake.py b/tests/test_code_remake.py
new file mode 100644
index 0000000..bfde760
--- /dev/null
+++ b/tests/test_code_remake.py
@@ -0,0 +1,90 @@
+"""A first code remake built from the measured scenes: motion of the drawn layer, the redraw renderer and the
+whole loop (write the project, match each scene, render, score)."""
+import json
+
+import cv2
+import numpy as np
+
+from rea_video.code_remake import code_remake
+from rea_video.layers import scene_motion, step_motion
+from rea_video.redraw import Redraw
+
+
+def _dots(seed=0, cx=240, cy=135, n=1200):
+ rng = np.random.default_rng(seed)
+ img = np.zeros((270, 480, 3), np.uint8)
+ for _ in range(n):
+ a, r = rng.uniform(0, 2 * np.pi), rng.uniform(0, 1) ** 0.5
+ cv2.circle(img, (int(cx + 90 * r * np.cos(a)), int(cy + 60 * r * np.sin(a))), 1, (230, 220, 60), -1)
+ return img
+
+
+def _video(path, frames, fps=8):
+ vw = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (frames[0].shape[1], frames[0].shape[0]))
+ for f in frames:
+ vw.write(f)
+ vw.release()
+ return path
+
+
+def test_step_motion_reads_zoom_rotation_and_pan():
+ g = cv2.cvtColor(_dots(), cv2.COLOR_BGR2GRAY)
+ M = cv2.getRotationMatrix2D((240, 135), -2, 1.03) # OpenCV turns anticlockwise for positive angles
+ M[0, 2] += 4
+ s, rot, px, py, drift = step_motion(g, cv2.warpAffine(g, M, (480, 270)), g > 0)
+ assert abs(s - 1.03) < 0.01 and abs(rot - 2) < 0.3 and abs(px - 4 / 480) < 0.003 and abs(py) < 0.003
+ assert drift < 0.002
+ m = scene_motion([[1.03, 2.0, 0.01, 0.0, 0.001]] * 4, 0.25)
+ assert abs(m["rotate"] - 8.0) < 1e-6 and m["zoom"] > 0.1 and abs(m["pan"][0] - 0.04) < 1e-6
+ assert scene_motion([], 0.25) == {}
+ assert step_motion(g, g, np.zeros_like(g, bool)) is None # nothing drawn to follow
+
+
+def _spec(tmp_path, scenes):
+ spec = {"size": [320, 180], "fps": 10, "duration": 4.0, "bloom": 0, "scenes": scenes}
+ (tmp_path / "spec.json").write_text(json.dumps(spec))
+ return tmp_path / "spec.json"
+
+
+def _points(tmp_path, name, xy):
+ rows = [[x, y, 255, 255, 255, 1.0] for x, y in xy]
+ (tmp_path / name).write_text(json.dumps({"points": rows}))
+ return name
+
+
+def test_redraw_places_particles_steadily_and_morphs_between_scenes(tmp_path):
+ left = _points(tmp_path, "a.json", [(0.2 + 0.001 * i, 0.5) for i in range(50)])
+ right = _points(tmp_path, "b.json", [(0.8 - 0.001 * i, 0.5) for i in range(50)])
+ still = {"zoom": 0, "rotate": 0, "pan": [0, 0], "drift": 0, "twinkle": 0}
+ spec = _spec(tmp_path, [
+ {"id": "s1", "start": 0, "end": 2, "draw": "points", "points": left, "count": 50, "dot": 1, "gain": 1, "motion": still},
+ {"id": "s2", "start": 2, "end": 4, "draw": "points", "points": right, "count": 50, "dot": 1, "gain": 1,
+ "motion": still, "enter": "morph", "enter_s": 1.0}])
+ rd = Redraw(spec)
+ a, b = rd.frame(0.5), rd.frame(0.6)
+ assert np.array_equal(a, b) # no motion asked for: nothing flickers
+ xcentre = lambda f: float(np.nonzero(f.max(axis=2) > 40)[1].mean()) / f.shape[1] # noqa: E731
+ assert abs(xcentre(a) - 0.22) < 0.03
+ assert 0.35 < xcentre(rd.frame(2.5)) < 0.65 # half way through the morph
+ assert abs(xcentre(rd.frame(3.5)) - 0.78) < 0.03
+ assert rd.frame(5.0).max() == 0 # past the last scene
+
+
+def test_code_remake_writes_a_project_that_lines_up_with_the_original(tmp_path):
+ frames = [_dots(i % 2) for i in range(24)] + [_dots(i % 2, cx=360) for i in range(24)]
+ video = _video(tmp_path / "v.mp4", frames)
+ out = tmp_path / "out"
+ out.mkdir()
+ shot = {"index": 1, "start": 0.0, "end": 6.0, "deterministic": {"probs": {"code_render": 0.9},
+ "facts": {"fine_dark": 0.9}}}
+ b = {"source": {"path": str(video), "width": 480, "height": 270, "fps": 8, "duration": 6.0}, "shots": [shot]}
+ (out / "breakdown.json").write_text(json.dumps(b))
+ res = code_remake(out)
+ spec = json.loads((out / "code" / "spec.json").read_text())
+ assert [s["draw"] for s in spec["scenes"]] == ["points", "points"] and spec["scenes"][1]["enter"] == "morph"
+ assert (out / "code" / "render.py").exists() and (out / "code" / "remake.mp4").exists()
+ assert res["compare"]["score"] > 0.6
+ spec["scenes"][0]["gain"] = 2.0 # an edit is kept on the next run
+ (out / "code" / "spec.json").write_text(json.dumps(spec))
+ assert code_remake(out, render=False)["kept"]
+ assert json.loads((out / "code" / "spec.json").read_text())["scenes"][0]["gain"] == 2.0
diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py
index 6e4725b..85ba09b 100644
--- a/tests/test_pipeline.py
+++ b/tests/test_pipeline.py
@@ -141,3 +141,26 @@ def test_english_report_has_no_chinese(media, tmp_path):
assert again["shots"][0]["base"]["label_zh"] == "静帧停留"
finally:
set_lang("zh")
+
+
+def test_remake_does_every_shot_it_can_and_says_what_is_left(breakdown, tmp_path):
+ from rea_video.remake import remake
+
+ b, out = breakdown
+ res = remake(out)
+ st = json.loads((out / "remake" / "status.json").read_text())
+ assert [r["now"] for r in st["shots"]] == ["local_still", "local_still", "code"], st
+ assert res["replaced_share"] == 1.0 and res["to_do"] == [] and (out / "code" / "spec.json").is_file()
+ assert Path(res["remake"]).is_file() and "代码重画" in (out / "remake" / "status.md").read_text()
+ # a clip handed in for a shot is cut in on the next run
+ clip = out / "remake" / "segments" / "shot_002.mp4"
+ (out / "remake" / "mine.json").write_text(json.dumps({"results": {"1": {"video": str(clip)}}}))
+ remake(out, code=False)
+ now = [r["now"] for r in json.loads((out / "remake" / "status.json").read_text())["shots"]]
+ assert now[0] == "generated" and now[2] == "code" # the earlier code render is reused
+
+
+def test_video_md_names_the_next_commands(breakdown):
+ b, out = breakdown
+ text = (out / "VIDEO.md").read_text(encoding="utf-8")
+ assert "rea-video remake" in text and "code-remake" in text