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 格式输出。

Add 3D motion forensics, capability-gated edit/frame routing, DP subcut alignment, and remake QA

junec11f1bd8fd3e
diff --git a/rea_video/aspects/__init__.py b/rea_video/aspects/__init__.py
index 93a619c..c94bf52 100644
--- a/rea_video/aspects/__init__.py
+++ b/rea_video/aspects/__init__.py
@@ -11,11 +11,11 @@ import json
from ..i18n import T, semi
from . import framing, camera, lighting, grade, editing, fmt # noqa: F401 (registration order matters)
-from .base import FILMED, PHOTOGRAPHIC, REGISTRY, ShotCtx, get
+from .base import FILMED, OWN_FILMED, PHOTOGRAPHIC, REGISTRY, ShotCtx, get
from .subject import subject
-__all__ = ["REGISTRY", "measure_shot", "finalize", "prompt_block", "review_template", "review_guide", "clean_answers",
- "summary_lines", "check", "shot_text", "report_md", "report_html", "shooting_plan"]
+__all__ = ["REGISTRY", "OWN_FILMED", "PHOTOGRAPHIC", "measure_shot", "finalize", "prompt_block", "review_template", "review_guide", "clean_answers",
+ "summary_lines", "check", "shot_text", "visual_shot_text", "report_md", "report_html", "shooting_plan"]
# ---------------------------------------------------------------- per shot ---------------------------------------
@@ -155,6 +155,17 @@ def shot_text(r: dict, brief: bool = False) -> str:
return semi().join(p for p in parts if p)
+def visual_shot_text(r: dict) -> str:
+ """Visual composition and light mood for non-filmed shots (AI, 3D, animation, film): no gimbal / rig / fill-lamp talk."""
+ asp = r.get("aspects") or {}
+ fr, cam, li, gr = ((asp.get(k) or {}).get("result") or {} for k in ("framing", "camera", "lighting", "grade"))
+ parts = [fr.get("shot_size"), fr.get("camera_angle"), fr.get("position"),
+ cam.get("move") and T("运镜{m}", "camera {m}", m=cam["move"]),
+ li.get("key_direction") and T("主光{k}", "key light {k}", k=li["key_direction"]),
+ li.get("quality"), gr.get("tone") and T("色调{t}", "{t} tone", t=gr["tone"])]
+ return semi().join(p for p in parts if p)
+
+
# ---------------------------------------------------------------- report -----------------------------------------
def _src(row: dict) -> str:
diff --git a/rea_video/aspects/base.py b/rea_video/aspects/base.py
index 699a66d..05ca36a 100644
--- a/rea_video/aspects/base.py
+++ b/rea_video/aspects/base.py
@@ -22,10 +22,19 @@ import numpy as np
from ..i18n import T
-# shots whose picture is photographic enough for camera / light analysis. Live action gets a shooting plan; AI, 3D
-# and avatar shots get the same measurements as a description of the picture (useful for generation prompts).
+# shots whose picture is photographic enough for per-shot framing / colour analysis (used internally by generation prompts,
+# and surfaced as shooting setups when the user explicitly asks for `mode: shoot`).
PHOTOGRAPHIC = ("live_action", "avatar", "ai_video", "cg_3d", "stop_motion", "film_footage")
-FILMED = ("live_action", "avatar", "stop_motion", "film_footage")
+# shots actually filmed by a camera / creator: only videos with these (or explicit `mode: shoot`) get camera / lighting / gear reports.
+OWN_FILMED = ("live_action", "stop_motion")
+FILMED = OWN_FILMED
+
+
+def filmed_shots(shots: list[dict], b: dict | None = None) -> list[dict]:
+ """Shots whose camera, lighting and editing setups belong in the report."""
+ mode = str((((b or {}).get("intent") or {}).get("mode") or "")).strip().lower()
+ pool = PHOTOGRAPHIC if mode == "shoot" else OWN_FILMED
+ return [r for r in shots if r["base"]["label"] in pool]
@dataclass
diff --git a/rea_video/aspects/camera.py b/rea_video/aspects/camera.py
index d5a923b..11ca05e 100644
--- a/rea_video/aspects/camera.py
+++ b/rea_video/aspects/camera.py
@@ -7,7 +7,7 @@ from __future__ import annotations
from ..i18n import LangDict, T, join, semi
-from .base import FILMED, PHOTOGRAPHIC, Aspect, Field, ShotCtx, field_table, register, seen, weighted_mode
+from .base import Aspect, Field, ShotCtx, field_table, filmed_shots, register, seen, weighted_mode
SUPPORT = {"handheld_like": "handheld", "smooth_move": "moving", "static": "fixed", "static_with_subject_motion": "fixed",
"planar_zoom_pan": "fixed"}
@@ -29,13 +29,16 @@ class Camera(Aspect):
def measure(self, ctx: ShotCtx) -> dict:
f = ctx.features
cam = f.get("camera")
+ traj = f.get("camera_traj")
move = None
z, pan = f.get("zoom_per_s", 0.0) or 0.0, f.get("pan_px_per_s", 0.0) or 0.0
if abs(z) > 0.01:
move = T("推", "push-in") if z > 0 else T("拉", "pull-out")
- elif pan > 6:
+ elif traj in ("push_in", "pull_out"):
+ move = T("推", "push-in") if traj == "push_in" else T("拉", "pull-out")
+ elif pan > 6 or traj in ("pan_left", "pan_right", "tilt_up", "tilt_down"):
move = T("摇/移", "pan / track")
- return {"support": SUPPORT.get(cam), "motion": cam, "move": move,
+ return {"support": SUPPORT.get(cam), "motion": cam, "move": move, "trajectory": traj,
"shake": round(float(f.get("sign_flip_rate", 0.0) or 0.0), 3)}
def interpret(self, shot: dict) -> dict:
@@ -47,7 +50,7 @@ class Camera(Aspect):
"move": show(m.get("move"))}
def summarize(self, shots: list[dict], b: dict) -> dict:
- main = [r for r in shots if r["base"]["label"] in FILMED] or [r for r in shots if r["base"]["label"] in PHOTOGRAPHIC]
+ main = filmed_shots(shots, b)
if not main:
return {}
res = {r["index"]: (r.get("aspects") or {}).get(self.key, {}).get("result") or {} for r in main}
diff --git a/rea_video/aspects/editing.py b/rea_video/aspects/editing.py
index a8d4c3e..e81de41 100644
--- a/rea_video/aspects/editing.py
+++ b/rea_video/aspects/editing.py
@@ -12,7 +12,7 @@ import numpy as np
from ..i18n import T, semi
-from .base import FILMED, Aspect, Field, ShotCtx, field_table, register
+from .base import Aspect, Field, ShotCtx, field_table, filmed_shots, register
SAME_POSITION = 18.0 # mean |diff| of 0..255 BGR cells of the 6x10 background layout
@@ -62,15 +62,13 @@ class Editing(Aspect):
def summarize(self, shots: list[dict], b: dict) -> dict:
total = sum(r["duration"] for r in shots) or 1.0
- filmed = [r for r in shots if r["base"]["label"] in FILMED]
+ filmed = filmed_shots(shots, b)
f_dur = sum(r["duration"] for r in filmed)
+ if not filmed or f_dur <= 0:
+ return {}
+ filmed_ids = {r["index"] for r in filmed}
out = {"cuts_per_min": round(max(0, len(shots) - 1) / (total / 60), 1), "avg_shot_s": round(total / max(1, len(shots)), 2),
"filmed_share": round(f_dur / total, 3), "insert_share": round(1 - f_dur / total, 3)}
- if not filmed or f_dur <= 0:
- out["lines"] = [T("剪辑:每分钟 {c} 刀,平均镜头 {a}s;没有实拍镜头", "Editing: {c} cuts per minute, {a}s average shot; no live-action shots",
- c=out["cuts_per_min"], a=out["avg_shot_s"])]
- out["result"] = {}
- return out
centers: list[list[float]] = []
pos = {}
for r in filmed:
@@ -89,7 +87,7 @@ class Editing(Aspect):
jump = punch = in_gap = joins = 0
voice = ((b.get("audio") or {}).get("voice") or {}).get("segments") or []
for prev, cur in zip(shots, shots[1:]):
- if prev["base"]["label"] not in FILMED or cur["base"]["label"] not in FILMED:
+ if prev["index"] not in filmed_ids or cur["index"] not in filmed_ids:
continue
joins += 1
if voice and _in_gap(cur["start"], voice):
diff --git a/rea_video/aspects/fmt.py b/rea_video/aspects/fmt.py
index e15c62d..63275f7 100644
--- a/rea_video/aspects/fmt.py
+++ b/rea_video/aspects/fmt.py
@@ -10,7 +10,7 @@ from __future__ import annotations
from ..i18n import LangDict, T, semi
-from .base import FILMED, Aspect, Field, field_table, register, video_seen
+from .base import Aspect, Field, field_table, filmed_shots, register, video_seen
FORMAT_ZH = LangDict({"talking_head": "人物口播", "desk": "桌面/物品拍摄(桌拍)", "product": "手持拍物品(开箱/带货/第一视角)",
"vlog": "vlog 随拍", "other": "其他实拍"},
@@ -27,7 +27,7 @@ class Format(Aspect):
])
def summarize(self, shots: list[dict], b: dict) -> dict:
- filmed = [r for r in shots if r["base"]["label"] in FILMED]
+ filmed = filmed_shots(shots, b)
f_dur = sum(r["duration"] for r in filmed)
if not filmed or f_dur < 0.2 * (sum(r["duration"] for r in shots) or 1):
return {}
diff --git a/rea_video/aspects/framing.py b/rea_video/aspects/framing.py
index f88999b..d381e01 100644
--- a/rea_video/aspects/framing.py
+++ b/rea_video/aspects/framing.py
@@ -9,7 +9,7 @@ import numpy as np
from ..i18n import LangDict, T, join, semi
-from .base import FILMED, PHOTOGRAPHIC, Aspect, Field, ShotCtx, field_table, register, seen, weighted_mode
+from .base import Aspect, Field, ShotCtx, field_table, filmed_shots, register, seen, weighted_mode
SIZES = LangDict({"ecu": "大特写", "cu": "特写", "mcu": "近景", "ms": "中景", "fs": "全景", "ls": "远景"},
en={"ecu": "extreme close-up", "cu": "close-up", "mcu": "medium close-up", "ms": "medium shot", "fs": "full shot",
@@ -72,7 +72,7 @@ class Framing(Aspect):
"subject": m.get("subject")}
def summarize(self, shots: list[dict], b: dict) -> dict:
- main = [r for r in shots if r["base"]["label"] in FILMED] or [r for r in shots if r["base"]["label"] in PHOTOGRAPHIC]
+ main = filmed_shots(shots, b)
if not main:
return {}
tot = sum(r["duration"] for r in main)
diff --git a/rea_video/aspects/grade.py b/rea_video/aspects/grade.py
index ba0d892..a84c9e3 100644
--- a/rea_video/aspects/grade.py
+++ b/rea_video/aspects/grade.py
@@ -17,7 +17,7 @@ import numpy as np
from ..i18n import T, join, semi
-from .base import PHOTOGRAPHIC, Aspect, Field, ShotCtx, field_table, register, weighted_median
+from .base import Aspect, Field, ShotCtx, field_table, filmed_shots, register, weighted_median
MEASURES = ("sat", "contrast", "black", "white", "shadow_b", "highlight_b", "mean_b", "mean_l", "bright_share", "dark_share",
"bright_sat", "hue_bins")
@@ -103,8 +103,8 @@ class Grade(Aspect):
return words(m)
def summarize(self, shots: list[dict], b: dict) -> dict:
- main = [r for r in shots if r["base"]["label"] in PHOTOGRAPHIC
- and ((r.get("aspects") or {}).get(self.key) or {}).get("measured")]
+ main = [r for r in filmed_shots(shots, b)
+ if ((r.get("aspects") or {}).get(self.key) or {}).get("measured")]
if not main:
return {}
ms = [(r["aspects"][self.key]["measured"], r["duration"]) for r in main]
diff --git a/rea_video/aspects/lighting.py b/rea_video/aspects/lighting.py
index d722d85..98b6da7 100644
--- a/rea_video/aspects/lighting.py
+++ b/rea_video/aspects/lighting.py
@@ -22,7 +22,7 @@ import numpy as np
from ..i18n import T, semi
-from .base import (FILMED, PHOTOGRAPHIC, Aspect, Field, ShotCtx, field_table, mode_seen, register, seen, video_seen,
+from .base import (OWN_FILMED, Aspect, Field, ShotCtx, field_table, filmed_shots, mode_seen, register, seen, video_seen,
weighted_median, weighted_mode)
MEASURES = ("ratio", "top_bottom", "transition", "subject_luma", "bg_luma", "dark_share", "warmth", "bg_warmth", "bg_blur", "point_lights",
@@ -328,9 +328,9 @@ class Lighting(Aspect):
return {**w, "setup": st.get("key"), "setup_name": st.get("name")}
def summarize(self, shots: list[dict], b: dict) -> dict:
- filmed = [r for r in shots if r["base"]["label"] in FILMED]
- main = [r for r in (filmed or [r for r in shots if r["base"]["label"] in PHOTOGRAPHIC])
- if ((r.get("aspects") or {}).get(self.key) or {}).get("measured", {}).get("ratio") is not None]
+ own = [r for r in shots if r["base"]["label"] in OWN_FILMED]
+ pool = filmed_shots(shots, b)
+ main = [r for r in pool if ((r.get("aspects") or {}).get(self.key) or {}).get("measured", {}).get("ratio") is not None]
if not main:
return {}
ms = [(r["aspects"][self.key]["measured"], r["duration"]) for r in main]
@@ -345,11 +345,11 @@ class Lighting(Aspect):
lines = [T("打光:{n}。主光 {k},{v};光比 {r};{q};色温{c}", "Lighting: {n}. Key light {k}, {v}; lighting ratio {r}; {q}; colour temperature {c}",
n=st["name"], k=w["key_direction"], v=w["vertical"], r=w["ratio"], q=w["quality"], c=w["color_temp"])
+ (semi() + semi().join(st["notes"]) if st.get("notes") else "")]
- if not filmed:
- lines.append(T("(画面不是实拍:以上是画面里的光影,用于写生成提示词,不是拍摄方案)",
- "(not live footage: the above describes the light in the picture, for generation prompts, not a shooting plan)"))
+ if not own:
+ lines.append(T("(原片非实拍:以上按画面光影反推真机实拍布光方案)",
+ "(source is not live footage: lighting setup translated from the picture for a live shoot)"))
return {"result": {"setup": st["key"]}, "measured": {k: (round(v, 3) if isinstance(v, float) else v) for k, v in med.items()},
- "words": w, "setup": st, "filmed": bool(filmed), "lines": lines,
+ "words": w, "setup": st, "filmed": True, "lines": lines,
"fields": field_table(self, main, b, {"light_quality": w["quality"], "color_temp": w["color_temp"]})}
diff --git a/rea_video/capabilities/models/video.yaml b/rea_video/capabilities/models/video.yaml
index 45db048..3b21ba1 100644
--- a/rea_video/capabilities/models/video.yaml
+++ b/rea_video/capabilities/models/video.yaml
@@ -442,7 +442,7 @@ models:
exclusive_inputs: [[video.i2v_first_frame, video.i2v_first_last], [video.multi_reference, video.reference_video, video.reference_audio]]
audio: {native: true}
# 复刻方案默认的排法,不改变上面的模型上限
- planning: {strategy: keyframes, images: 4}
+ planning: {strategy: keyframes}
strengths:
- 第三方榜单前三(H3 Max Elo 约 1227),且列价最低
- 权重开放(H3-Base 可在本地跑 768p)
@@ -507,7 +507,7 @@ models:
resolutions: [480p, 768p]
refs: {image: 9, video: 3, audio: 3, total: 12}
audio: {native: true, voice_ref: true}
- planning: {strategy: keyframes, images: 4}
+ planning: {strategy: keyframes}
strengths:
- 便宜、快(6 步采样);可以单独导出声音分轨
- 提示词指南写得很细,参考图、参考视频、参考音频都能用
diff --git a/rea_video/cli.py b/rea_video/cli.py
index afe28ee..e22b57c 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -397,6 +397,15 @@ def _capsule_command(args, argv: list[str]) -> int:
def cmd_remake_run(args) -> int:
jobs = Path(args.jobs).expanduser().resolve()
+ try:
+ eng = str((json.loads(jobs.read_text(encoding="utf-8")) or {}).get("engine") or "")
+ except (OSError, ValueError):
+ eng = ""
+ if eng in ("gemini-omni-flash", "veo-3.1"):
+ root = _capsule_root(args)
+ argv = ["--jobs", str(jobs), "--capsule-root", str(root)]
+ argv += (["--only", args.only] if args.only else []) + (["--dry-run"] if args.dry_run else [])
+ return _run_integration("run_remake.py", _capsule_python(args.python, root), argv)
return _capsule_command(args, ["run", str(jobs)] + (["--only", args.only] if args.only else []) + (["--dry-run"] if args.dry_run else []))
@@ -412,8 +421,28 @@ def cmd_capsule_draft(args) -> int:
def cmd_assemble(args) -> int:
- pkg = Path(args.breakdown).expanduser().resolve().parent
- argv = ["assemble", str(pkg), "--results", str(Path(args.results).expanduser().resolve())]
+ bpath = Path(args.breakdown).expanduser().resolve()
+ pkg = bpath.parent
+ rpath = Path(args.results).expanduser().resolve()
+ retime = getattr(args, "retime", "smooth") or "smooth"
+ if retime == "smooth":
+ from .memory import capsule_root
+ from .remake import assemble as local_assemble
+
+ out_dir = Path(args.out).expanduser().resolve() if args.out else rpath.parent
+ mine = out_dir / "mine.json"
+ extra = read_json(mine).get("results", {}) if mine.is_file() else {}
+ code_v = pkg / "code" / "remake.mp4"
+ log_txt = local_assemble(bpath, rpath, out_dir=out_dir, overlays=bool(args.overlays),
+ code_video=code_v if code_v.is_file() else None, extra=extra, retime="smooth")
+ print(log_txt)
+ log = json.loads(log_txt)
+ root = capsule_root(getattr(args, "capsule_root", None))
+ if (root / "scripts" / "remake_reference.py").is_file() and Path(log["remake"]).is_file():
+ return _capsule_command(args, ["compare", str(pkg), str(log["remake"]), "--remake-video", str(log["remake"]),
+ "-o", str(Path(log["remake"]).parent / "qa")])
+ return 0
+ argv = ["assemble", str(pkg), "--results", str(rpath)]
argv += ["-o", str(Path(args.out).expanduser().resolve())] if args.out else []
return _capsule_command(args, argv + ([] if args.overlays else ["--no-overlays"]))
@@ -430,7 +459,9 @@ def cmd_tiles(args) -> int:
if args.every <= 0:
raise SystemExit(U("rea-video: --every 必须大于 0(两次抽帧的间隔秒数)", "rea-video: --every must be greater than 0 (seconds between frames)"))
if Path(args.video).is_dir() and (Path(args.video) / "breakdown.json").is_file():
- args.video = read_json(Path(args.video) / "breakdown.json")["source"]["path"] # a package: its source video
+ pkg_dir = Path(args.video)
+ sp = Path(read_json(pkg_dir / "breakdown.json")["source"]["path"])
+ args.video = str(pkg_dir / sp if not sp.is_absolute() and (pkg_dir / sp).is_file() else sp) # a package: its source video
if args.start < 0:
raise SystemExit(U("rea-video: --start 不能小于 0", "rea-video: --start cannot be negative"))
if args.cols < 1:
@@ -509,13 +540,24 @@ def cmd_frames(args) -> int:
def cmd_compare(args) -> int:
+ for p in (args.ref, args.remake):
+ if not Path(p).is_file():
+ raise SystemExit(U(f"rea-video: 找不到 {p}", f"rea-video: not found: {p}"))
+ if getattr(args, "breakdown", None):
+ from .remake_qa import evaluate_remake
+
+ bp = Path(args.breakdown)
+ if not bp.is_file():
+ raise SystemExit(U(f"rea-video: 找不到 {bp}", f"rea-video: not found: {bp}"))
+ b = read_json(bp)
+ b = {**b, "source": {**(b.get("source") or {}), "path": str(Path(args.ref).resolve())}}
+ qa = evaluate_remake(b, args.remake, out_dir=Path(args.out) if args.out else None, replaced_only=False)
+ print(json.dumps(qa, ensure_ascii=False, indent=1))
+ return 0
from .layers import compare
if args.every <= 0:
raise SystemExit(U("rea-video: --every 必须大于 0", "rea-video: --every must be greater than 0"))
- for p in (args.ref, args.remake):
- if not Path(p).is_file():
- raise SystemExit(U(f"rea-video: 找不到 {p}", f"rea-video: not found: {p}"))
res = compare(args.ref, args.remake, every=args.every, out=Path(args.out) if args.out else None,
scenes=Path(args.scenes) if args.scenes else None, worst=args.worst)
brief = {k: res[k] for k in ("score", "place", "shape", "offset", "advice", "worst") if k in res}
@@ -736,8 +778,37 @@ def cmd_plan(args) -> int:
intent = load_intent(out)
if args.model:
intent["model"] = args.model
- if args.generate:
+ if getattr(args, "mode", None):
+ intent["mode"] = args.mode
+ intent["generate"] = "all" if args.mode == "ai" else ("none" if args.mode == "shoot" else "ai")
+ elif args.generate:
intent["generate"] = args.generate
+ intent["mode"] = "ai" if args.generate == "all" else "match"
+ if getattr(args, "strategy", None):
+ if args.strategy == "auto":
+ intent.pop("strategy", None)
+ else:
+ intent["strategy"] = args.strategy
+ if getattr(args, "video_ref", None):
+ if args.video_ref == "auto":
+ intent.pop("video_ref", None)
+ else:
+ intent["video_ref"] = args.video_ref
+ if getattr(args, "image_ref", None):
+ if args.image_ref == "auto":
+ intent.pop("image_ref", None)
+ else:
+ intent["image_ref"] = args.image_ref
+ if getattr(args, "max_images", None) is not None:
+ if args.max_images <= 0:
+ intent.pop("max_images", None)
+ else:
+ intent["max_images"] = int(args.max_images)
+ if getattr(args, "max_ref_video_s", None) is not None:
+ if args.max_ref_video_s <= 0:
+ intent.pop("max_ref_video_s", None)
+ else:
+ intent["max_ref_video_s"] = float(args.max_ref_video_s)
if not intent.get("model"):
from .generation import DEFAULT_MODEL
from .memory import pref
@@ -774,7 +845,9 @@ def cmd_plan(args) -> int:
plan = b.get("production_plan") or {}
print(T("已按 {m} 的写法自动重写 {n} 段提示词 → {f}", "Rewrote {n} unit prompt(s) for {m} → {f}",
m=m["id"], n=len(rewritten), f=out / "remake" / "prompts.json"))
- n = sum(len(ref_clips(b, out, u)) for u in plan.get("units") or [])
+ from .integrations.capsule_cinema import image_ref_frames
+
+ n = sum(len(ref_clips(b, out, u)) for u in plan.get("units") or []) + len(image_ref_frames(b, out, plan))
v = m.get("verified") or {}
print(T("复刻方案已按 {m} 重出(报告第二部分):{p}", "Remake plan redone for {m} (part two of the report): {p}",
m=m["id"], p=b["summary"].get("production", "")))
@@ -978,6 +1051,8 @@ def main(argv: list[str] | None = None) -> int:
a.add_argument("--capsule-root", help="capsule-cinema 仓库;默认 $CAPSULE_CINEMA_ROOT、prefs capsule_root,再退到 ~/code/github/capsule-cinema")
a.add_argument("--overlays", action="store_true",
help="把测得的字幕 / 花字 / 标题按原样式叠回换掉的镜头(保留原片的镜头本来就有);贴纸只列出来,要自己找素材")
+ a.add_argument("--retime", choices=["smooth", "warp"], default="smooth",
+ help="时间对齐方式:smooth 均匀连续帧混合重采样、零冻结帧(默认)/ warp 离散运动峰值动态时间规整")
a.set_defaults(func=cmd_assemble)
t = sub.add_parser("tiles", help="按时间抽帧拼图,近距离检查某一段(agent 复核用)")
@@ -1000,9 +1075,10 @@ def main(argv: list[str] | None = None) -> int:
fr.add_argument("--all", action="store_true", help="所有镜头都做,不只是代码渲染镜头")
fr.set_defaults(func=cmd_frames)
- cp = sub.add_parser("compare", help="逐帧比较复刻和原片画上去的那一层(落在哪、形状重合度、多少),列出最差的时刻并拼对比图")
+ cp = sub.add_parser("compare", help="比较复刻成片与原片:默认比对代码图形层,传 --breakdown 时逐镜评测运镜、姿态动态、构图与流畅度")
cp.add_argument("ref", help="原片")
cp.add_argument("remake", help="复刻成片")
+ cp.add_argument("--breakdown", help="breakdown.json:按镜头评测生成式复刻的运镜方向、主体姿态动态、构图轮廓与冻结帧")
cp.add_argument("--every", type=float, default=0.5, help="采样间隔秒数(默认 0.5)")
cp.add_argument("--scenes", help="frames/scenes.json:按场景汇总分数")
cp.add_argument("--worst", type=int, default=8, help="对比图里放几个最差时刻(默认 8)")
@@ -1092,6 +1168,12 @@ def main(argv: list[str] | None = None) -> int:
pl_ = sub.add_parser("plan", help="按用户要用的视频模型出复刻方案(报告第二部分);拆解结果不变")
pl_.add_argument("out_dir", help="拆解目录")
pl_.add_argument("--model", help="模型 id 或名称,写进 remake/intent.yaml(rea-video models 列出的;没有的先查资料补进 ~/.rea-video/capabilities/models/)")
+ pl_.add_argument("--mode", choices=["match", "ai", "shoot"], help="复刻方式:match 按原片方式复刻(默认)/ ai 整条改用 AI 生成 / shoot 整条改按真机实拍规划")
+ pl_.add_argument("--strategy", choices=["auto", "edit", "remix", "keyframes", "frames", "text"], help="AI 视频生成模态:auto 按模型能力自动选(默认)/ edit 原片动作锁定增量编辑 / remix 参考视频多模态 / keyframes 多图关键帧 / frames 首尾帧图生视频 / text 纯文生视频")
+ pl_.add_argument("--video-ref", choices=["auto", "none", "source", "depth", "edge"], help="原视频参考形式:auto 自动(默认)/ none 不传原视频 / source 原视频直接参考 / depth 灰度深度视频参考 / edge 结构边缘视频参考")
+ pl_.add_argument("--image-ref", choices=["auto", "none", "source", "depth", "edge"], help="前置生图参考形式:auto 自动(默认)/ none 纯文生图 / source 原片首帧垫图参考 / depth 深度图参考 / edge 边缘图参考")
+ pl_.add_argument("--max-images", type=int, help="覆盖实际执行渠道单次参考图上限(如聚合渠道支持 14 张时传 14;传 0 恢复能力地图默认值)")
+ pl_.add_argument("--max-ref-video-s", type=float, help="覆盖实际执行渠道单次参考视频总秒数上限(如聚合渠道支持 15 秒时传 15;传 0 恢复默认值)")
pl_.add_argument("--generate", choices=["ai", "all"], help="ai:只生成原片里 AI 做的镜头,实拍的出拍摄方案;all:整条都用模型生成(换人、换物后整条复刻)")
pl_.add_argument("--rewrite-prompts", action="store_true", help="用已配置的大模型(GEMINI_API_KEY 或 REA_VLM_*)按所选模型的提示词指南自动重写每段提示词,校验后写入 remake/prompts.json")
pl_.set_defaults(func=cmd_plan)
diff --git a/rea_video/cli_en.py b/rea_video/cli_en.py
index adfbf3b..b9f8a82 100644
--- a/rea_video/cli_en.py
+++ b/rea_video/cli_en.py
@@ -69,6 +69,7 @@ HELP = {
"capsule-draft.python": "capsule-cinema Python; same default as remake-run",
"assemble": "through Capsule Cinema: put remade shots back on the original timeline and output a comparison video",
"assemble.results": "results.json from remake-run (or your own file in the same format)",
+ "assemble.retime": "timing alignment: smooth frame-blended resampling with zero frozen frames (default) / warp discrete DTW peak matching",
"assemble.capsule_root": _CAPSULE_ROOT,
"assemble.overlays": "put measured captions / styled text / titles back on replaced shots in their original style (kept shots already have them); stickers are only listed, so source them yourself",
@@ -82,9 +83,10 @@ HELP = {
"frames.points": "sample points per scene (default 4000)",
"frames.all": "process all shots, not only code-rendered ones",
- "compare": "compare the drawn layer of a remake and the original frame by frame (position, shape overlap, amount), list the worst moments and tile them",
+ "compare": "compare a remake against the original: drawn graphics layer by default, or per-shot camera/pose/layout/smoothness QA when --breakdown is given",
"compare.ref": "original video",
"compare.remake": "remade video",
+ "compare.breakdown": "breakdown.json: score generative remakes per shot on camera move, pose dynamics, layout and freeze frames",
"compare.every": "sampling interval in seconds (default 0.5)",
"compare.scenes": "frames/scenes.json: summarize scores per scene",
"compare.worst": "worst moments to show in the comparison image (default 8)",
@@ -151,6 +153,12 @@ HELP = {
"plan": "write the remake plan for the video model the user wants (part two of the report); the breakdown does not change",
"plan.out_dir": "breakdown directory",
"plan.model": "model id or name, saved to remake/intent.yaml (from rea-video models; for others, look it up and add it under ~/.rea-video/capabilities/models/)",
+ "plan.mode": "remake mode: match follows how each shot was originally made (default) / ai remakes the whole video with AI / shoot translates the video into a live camera shoot",
+ "plan.strategy": "AI video input modality: auto picks from model capabilities (default) / edit locks source motion with delta prompt / remix uses reference video / keyframes uses multi-shot source frames / frames uses first-last frame I2V / text uses text-to-video",
+ "plan.video_ref": "source video reference form: auto (default) / none (no source video) / source (raw cleaned source video) / depth (grayscale depth control video) / edge (structural soft-edge control video)",
+ "plan.image_ref": "upstream still-image reference form: auto (default) / none (pure T2I) / source (cleaned source frame I2I) / depth (depth map I2I) / edge (edge map I2I)",
+ "plan.max_images": "override per-call reference image limit for your gateway channel (pass 0 to reset)",
+ "plan.max_ref_video_s": "override per-call reference video seconds limit for your gateway channel (pass 0 to reset)",
"plan.generate": "ai: generate only the shots that were AI in the original and write a shooting plan for live action; all: generate the whole video (full remake after swapping people or objects)",
"plan.rewrite_prompts": "use the configured model (GEMINI_API_KEY or REA_VLM_*) to rewrite each unit's prompt in the chosen video model's style, validate and save to remake/prompts.json",
diff --git a/rea_video/drive.py b/rea_video/drive.py
index c182f2c..2dc9580 100644
--- a/rea_video/drive.py
+++ b/rea_video/drive.py
@@ -219,32 +219,97 @@ def _units(b: dict, shots: list[int] | None) -> list[dict]:
return (b.get("production_plan") or {}).get("drive") or []
-def _depth_model():
- """Depth Anything V2 Small through transformers, when installed; None otherwise (the README then gives the
- Video Depth Anything command, which is the better tool: it is made for video and does not flicker)."""
+def _onnx_depth_predictor():
+ """Lightweight ONNX Depth-Anything-V2-Small runner when onnxruntime + huggingface_hub are available."""
try:
- import torch # noqa: F401
- from transformers import pipeline
+ import onnxruntime as ort
+ from huggingface_hub import hf_hub_download
except ImportError:
return None
+ for fname in ("onnx/model_quantized.onnx", "onnx/model_fp16.onnx", "onnx/model.onnx"):
+ try:
+ model_path = hf_hub_download("onnx-community/depth-anything-v2-small", fname)
+ sess = ort.InferenceSession(model_path, providers=["CPUExecutionProvider"])
+ in_name = sess.get_inputs()[0].name
+
+ def _pred(frame_bgr: np.ndarray) -> np.ndarray:
+ rgb = cv2.cvtColor(cv2.resize(frame_bgr, (518, 518), interpolation=cv2.INTER_AREA), cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
+ mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
+ std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
+ inp = np.transpose((rgb - mean) / std, (2, 0, 1))[None, ...]
+ out = sess.run(None, {in_name: inp})[0]
+ return np.asarray(out, dtype=np.float32).squeeze()
+
+ return _pred
+ except Exception:
+ continue
+ return None
+
+
+def _depth_model():
+ """Depth Anything V2 Small through transformers or onnxruntime; None when neither is available."""
try:
- return pipeline("depth-estimation", model="depth-anything/Depth-Anything-V2-Small-hf")
- except Exception as e: # network, weights, device
- LOG.warning("depth model unavailable: %s", e)
- return None
+ import torch # noqa: F401
+ from PIL import Image
+ from transformers import pipeline
+ pipe = pipeline("depth-estimation", model="depth-anything/Depth-Anything-V2-Small-hf")
+ return lambda f: np.asarray(pipe(Image.fromarray(cv2.cvtColor(f, cv2.COLOR_BGR2RGB)))["predicted_depth"].squeeze(), np.float32)
+ except Exception:
+ pass
+ onnx_fn = _onnx_depth_predictor()
+ if onnx_fn is not None:
+ return onnx_fn
+ LOG.warning("Depth-Anything-V2 unavailable (install transformers or onnxruntime+huggingface_hub); falling back to local spatial cue")
+ return None
+
+
+def _fallback_depth_array(frame_bgr: np.ndarray) -> np.ndarray:
+ """Zero-dependency spatial depth proxy (local sharpness + bilateral luminance) when no neural depth weights exist."""
+ gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY).astype(np.float32) / 255.0
+ smooth = cv2.bilateralFilter(gray, 7, 0.2, 7)
+ gx = cv2.Sobel(smooth, cv2.CV_32F, 1, 0, ksize=3)
+ gy = cv2.Sobel(smooth, cv2.CV_32F, 0, 1, ksize=3)
+ sharp = cv2.GaussianBlur(np.hypot(gx, gy), (21, 21), 0)
+ if sharp.max() > 1e-6:
+ sharp = sharp / sharp.max()
+ return 0.65 * sharp + 0.35 * smooth
+
+
+def _edge_array(frame_bgr: np.ndarray) -> np.ndarray:
+ """Soft multi-scale structural edge map (0..255 uint8) stripping colour, texture and small print while keeping silhouettes."""
+ gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
+ filt = cv2.bilateralFilter(gray, 7, 55, 55)
+ fine = cv2.Canny(filt, 40, 110).astype(np.float32)
+ coarse = cv2.Canny(cv2.GaussianBlur(filt, (5, 5), 0), 75, 175).astype(np.float32)
+ comb = np.clip(0.45 * fine + 0.75 * coarse, 0, 255)
+ return cv2.GaussianBlur(comb, (3, 3), 0).astype(np.uint8)
+
+
+def _is_hard_cut(a: np.ndarray | None, b_img: np.ndarray) -> bool:
+ if a is None:
+ return True
+ ha = cv2.calcHist([cv2.cvtColor(cv2.resize(a, (64, 64)), cv2.COLOR_BGR2HSV)], [0, 1], None, [12, 8], [0, 180, 0, 256])
+ hb = cv2.calcHist([cv2.cvtColor(cv2.resize(b_img, (64, 64)), cv2.COLOR_BGR2HSV)], [0, 1], None, [12, 8], [0, 180, 0, 256])
+ cv2.normalize(ha, ha)
+ cv2.normalize(hb, hb)
+ return float(cv2.compareHist(ha, hb, cv2.HISTCMP_BHATTACHARYYA)) > 0.38
-def _write_depth(model, frames: list[np.ndarray], path: Path, fps: float) -> None:
- from PIL import Image
- raw = [np.asarray(model(Image.fromarray(cv2.cvtColor(f, cv2.COLOR_BGR2RGB)))["predicted_depth"].squeeze(), np.float32) for f in frames]
+def _write_depth(model, frames: list[np.ndarray], path: Path, fps: float) -> None:
+ pred = model if callable(model) else _fallback_depth_array
+ raw = [pred(f) for f in frames]
lo, hi = np.percentile(np.stack(raw), [2, 98]) # one range for the whole clip: per-frame ranges flicker
h, w = frames[0].shape[:2]
- prev = None
+ prev, prev_bgr = None, None
enc = _encoder(path, w, h, fps)
- for d in raw:
+ for f_bgr, d in zip(frames, raw):
d = np.clip((d - lo) / max(hi - lo, 1e-6), 0, 1)
- prev = d if prev is None else 0.6 * d + 0.4 * prev
+ if _is_hard_cut(prev_bgr, f_bgr):
+ prev = d
+ else:
+ prev = 0.65 * d + 0.35 * prev
+ prev_bgr = f_bgr
g = cv2.resize((prev * 255).astype(np.uint8), (w, h), interpolation=cv2.INTER_LINEAR)
enc.stdin.write(cv2.cvtColor(g, cv2.COLOR_GRAY2BGR).tobytes())
enc.stdin.close()
@@ -269,10 +334,21 @@ def _sheet(rows: list[list[np.ndarray]], labels: list[str], path: Path) -> None:
write_image(path, np.concatenate([np.pad(r, ((0, 0), (0, w - r.shape[1]), (0, 0))) for r in lines], axis=0))
+def _resolve_src(b: dict, out_path: Path) -> Path:
+ src = Path(b["source"]["path"])
+ if src.is_file() or src.is_absolute():
+ return src
+ for anc in (out_path, out_path.parent, out_path.parent.parent, out_path.parent.parent.parent):
+ cand = anc / src
+ if cand.is_file():
+ return cand
+ return src
+
+
def clean_clip(b: dict, ranges: list[list[float]], path: Path, width: int = 720, crf: int = 26) -> Path:
"""The source over `ranges` (joined when there are several) with subtitles, styled text and stickers erased and no
sound: a reference video for a remix, so the model takes the shots and pacing but not the old words."""
- src = Path(b["source"]["path"])
+ src = _resolve_src(b, path)
info = video_info(src)
boxes = overlays(b, persistent=True)
w, h = scaled_size(info, min(width, info.width or width))
@@ -293,7 +369,7 @@ def clean_clip(b: dict, ranges: list[list[float]], path: Path, width: int = 720,
def clean_frame(b: dict, t: float, path: Path, width: int = 1080) -> Path:
"""One source frame at t with the edit's text erased: a composition reference for a model without reference video."""
- src = Path(b["source"]["path"])
+ src = _resolve_src(b, path)
info = video_info(src)
boxes = overlays(b, persistent=True)
w, _ = scaled_size(info, min(width, info.width or width))
@@ -306,6 +382,78 @@ def clean_frame(b: dict, t: float, path: Path, width: int = 1080) -> Path:
return path
+_CACHED_DEPTH_FN = False
+
+
+def _shared_depth_fn():
+ global _CACHED_DEPTH_FN
+ if _CACHED_DEPTH_FN is False:
+ _CACHED_DEPTH_FN = _depth_model()
+ return _CACHED_DEPTH_FN
+
+
+def control_clip(b: dict, ranges: list[list[float]], path: Path, kind: str = "depth",
+ width: int = 720, crf: int = 22, use_neural_depth: bool = True) -> Path:
+ """Appearance-free structural reference video ('depth' or 'edge') over `ranges`, overlays erased first,
+ temporal EMA reset at hard cuts so cuts stay frame-exact."""
+ src = _resolve_src(b, path)
+ info = video_info(src)
+ boxes = overlays(b, persistent=True)
+ w, h = scaled_size(info, min(width, info.width or width))
+ fps = info.fps if 0 < info.fps <= 60 else 30.0
+ path.parent.mkdir(parents=True, exist_ok=True)
+ cleaned: list[np.ndarray] = []
+ for a, z in ranges:
+ for i, f in enumerate(iter_frames(src, info, w, start=a, duration=z - a, fps=fps)):
+ t = a + i / fps
+ cleaned.append(erase(f, _mask(boxes, t, f.shape[1], f.shape[0]) if boxes else None))
+ if not cleaned:
+ return path
+ if kind == "depth":
+ fn = _shared_depth_fn() if use_neural_depth else None
+ _write_depth(fn, cleaned, path, fps)
+ return path
+ enc = _encoder(path, w, h, fps, crf=crf)
+ prev, prev_bgr = None, None
+ try:
+ for f in cleaned:
+ e = _edge_array(f).astype(np.float32)
+ if _is_hard_cut(prev_bgr, f) or prev is None:
+ prev = e
+ else:
+ prev = 0.75 * e + 0.25 * prev
+ prev_bgr = f
+ enc.stdin.write(cv2.cvtColor(prev.astype(np.uint8), cv2.COLOR_GRAY2BGR).tobytes())
+ finally:
+ enc.stdin.close()
+ enc.wait()
+ return path
+
+
+def control_frame(b: dict, t: float, path: Path, kind: str = "depth",
+ width: int = 1080, use_neural_depth: bool = True) -> Path:
+ """Single appearance-free structural frame ('depth' or 'edge') at t, overlays erased first."""
+ src = _resolve_src(b, path)
+ info = video_info(src)
+ boxes = overlays(b, persistent=True)
+ w, _ = scaled_size(info, min(width, info.width or width))
+ for f in iter_frames(src, info, w, start=t, duration=0.1):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ m = _mask(boxes, t, f.shape[1], f.shape[0]) if boxes else None
+ clean = f if m is None else cv2.inpaint(f, _strokes(f, m), 3, cv2.INPAINT_TELEA)
+ if kind == "depth":
+ fn = (_shared_depth_fn() if use_neural_depth else None) or _fallback_depth_array
+ d = fn(clean)
+ lo, hi = np.percentile(d, [2, 98])
+ norm = np.clip((d - lo) / max(hi - lo, 1e-6), 0, 1)
+ g = cv2.resize((norm * 255).astype(np.uint8), (clean.shape[1], clean.shape[0]), interpolation=cv2.INTER_LINEAR)
+ write_image(path, cv2.cvtColor(g, cv2.COLOR_GRAY2BGR))
+ else:
+ write_image(path, cv2.cvtColor(_edge_array(clean), cv2.COLOR_GRAY2BGR))
+ break
+ return path
+
+
def drive(out: Path, shots: list[int] | None = None, depth: bool = False, clean: bool = True,
prefer: float | None = None, max_s: float | None = None) -> dict:
b = read_json(out / "breakdown.json")
@@ -313,7 +461,7 @@ def drive(out: Path, shots: list[int] | None = None, depth: bool = False, clean:
if not units:
raise ValueError(T("没有动作驱动单元:先在看图复核里给舞蹈 / 动作镜头填 performance.move 并 apply-review,或用 --shots 指定镜头",
"no motion-drive units: mark the dance / action shots with performance.move in the review and apply it, or pass --shots"))
- src = Path(b["source"]["path"])
+ src = _resolve_src(b, out)
info = video_info(src)
lim = dance.segment_limits()
if prefer:
diff --git a/rea_video/features.py b/rea_video/features.py
index ec101a6..dc9bfb8 100644
--- a/rea_video/features.py
+++ b/rea_video/features.py
@@ -400,7 +400,9 @@ def shot_features(samples: ShotSamples, fps: float) -> dict:
else:
agg["start_end_mad"] = 0.0
agg.update(resampling_signature(samples.sharpness))
- agg.update(motion_summary(samples.motion, fps))
+ ms = motion_summary(samples.motion, fps)
+ agg.update(ms)
+ agg.update(kinematics_summary(samples.frames, samples.frame_times, ms))
return agg
@@ -472,3 +474,187 @@ def motion_summary(motion: list[dict], fps: float) -> dict:
"comp_block_p98": comp_p98,
"camera": camera,
}
+
+
+def kinematics_summary(frames: list[np.ndarray], frame_times: list[float], ms: dict) -> dict:
+ """3D-parallax-resilient camera trajectory and global-motion-compensated subject pose change.
+
+ Single-plane RANSAC (`global_motion`) underestimates dolly push/pull when foreground, subject and background sit at
+ different depths, and `local_motion_ratio` conflates articulated limb/torso actions with hair/cloth wind or bokeh
+ drift. Dense multi-quadrant radial divergence + aligned start-vs-end contour correlation separate them cleanly.
+ """
+ default = {"radial_zoom_per_s": 0.0, "net_zoom_pct": 0.0, "parallax_score": 0.0,
+ "camera_traj": "static", "pose_change": 0.0, "motion_regime": "near_static"}
+ if len(frames) < 2:
+ return default
+ kw = 160
+ h0, w0 = frames[0].shape[:2]
+ if h0 < 16 or w0 < 16:
+ return default
+ kh = max(24, int(round(h0 * kw / float(w0))))
+ grays = [cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY), (kw, kh), interpolation=cv2.INTER_AREA).astype(np.float32)
+ for f in frames]
+ if len(frame_times) == len(frames) and frame_times[-1] > frame_times[0] + 0.02:
+ ts = [float(t) for t in frame_times]
+ else:
+ ts = np.linspace(0.0, max(0.2, (len(frames) - 1) / 8.0), len(frames)).tolist()
+ dur = max(0.08, ts[-1] - ts[0])
+ idxs = np.unique(np.linspace(0, len(grays) - 1, num=min(len(grays), 6)).round().astype(int))
+ if len(idxs) < 2:
+ return default
+
+ xs = (np.arange(kw, dtype=np.float32) - (kw - 1) / 2.0) / max(1.0, kw / 2.0)
+ ys = (np.arange(kh, dtype=np.float32) - (kh - 1) / 2.0) / max(1.0, kh / 2.0)
+ xx, yy = np.meshgrid(xs, ys)
+ r2 = xx * xx + yy * yy
+ outer = r2 >= 0.09
+ quads = [outer & (xx < 0) & (yy < 0), outer & (xx >= 0) & (yy < 0),
+ outer & (xx < 0) & (yy >= 0), outer & (xx >= 0) & (yy >= 0)]
+
+ rad_rates: list[float] = []
+ u_rates: list[float] = []
+ v_rates: list[float] = []
+ plx_vals: list[float] = []
+ for i0, i1 in zip(idxs[:-1], idxs[1:]):
+ dt = max(0.03, ts[i1] - ts[i0])
+ g0, g1 = grays[i0], grays[i1]
+ flow = cv2.calcOpticalFlowFarneback(g0, g1, None, 0.5, 3, 15, 3, 5, 1.2, 0)
+ gx = cv2.Sobel(g0, cv2.CV_32F, 1, 0, ksize=3)
+ gy = cv2.Sobel(g0, cv2.CV_32F, 0, 1, ksize=3)
+ tex = np.hypot(gx, gy) > 8.0
+ u = flow[..., 0] / max(1.0, kw / 2.0)
+ v = flow[..., 1] / max(1.0, kh / 2.0)
+ q_u, q_v = [], []
+ for q in quads:
+ qm = (tex & q) if (tex & q).sum() >= 10 else q
+ if qm.any():
+ q_u.append(float(np.median(u[qm])))
+ q_v.append(float(np.median(v[qm])))
+ u0 = float(np.mean(q_u)) if q_u else 0.0
+ v0 = float(np.mean(q_v)) if q_v else 0.0
+ u_rates.append(u0 / dt)
+ v_rates.append(v0 / dt)
+
+ s_map = ((u - u0) * xx + (v - v0) * yy) / np.maximum(r2, 0.09)
+ q_s = []
+ for q in quads:
+ qm = (tex & q) if (tex & q).sum() >= 10 else q
+ if qm.sum() >= 10:
+ q_s.append(float(np.median(s_map[qm])))
+ pos_q = sum(x > 0.0035 for x in q_s)
+ neg_q = sum(x < -0.0035 for x in q_s)
+ s_step = 0.0
+ if q_s and ((pos_q >= 3 and neg_q == 0) or (neg_q >= 3 and pos_q == 0)
+ or (pos_q >= 2 and neg_q == 0 and np.median(q_s) > 0.005)
+ or (neg_q >= 2 and pos_q == 0 and np.median(q_s) < -0.005)
+ or (max(pos_q, neg_q) >= 3 and abs(np.median(q_s)) > 0.012)):
+ s_step = float(np.median(q_s))
+ rad_rates.append(s_step / dt)
+
+ # Depth-layer speed dispersion along the global camera vector (0 for 2D planar Ken Burns, high for 3D parallax)
+ mask = (tex & outer) if (tex & outer).sum() >= 40 else outer
+ up, vp = u0 + s_step * xx, v0 + s_step * yy
+ pmag = np.hypot(up, vp)
+ active = mask & (pmag > 0.008)
+ if active.sum() >= 30:
+ proj = (u[active] * up[active] + v[active] * vp[active]) / (pmag[active] ** 2 + 1e-6)
+ same_dir = float((proj > 0.15).mean())
+ if same_dir >= 0.72:
+ iqr = float(np.percentile(proj, 80) - np.percentile(proj, 20))
+ plx_vals.append(float(np.clip((iqr - 0.18) / 0.75, 0.0, 1.0)))
+ else:
+ plx_vals.append(0.0)
+
+ z_rad = float(np.median(rad_rates)) if rad_rates else 0.0
+ z_ransac = float(ms.get("zoom_per_s") or 0.0)
+ kb = float(ms.get("kenburns_score") or 0.0)
+ inl = float(ms.get("rigid_inlier_ratio") or 0.0)
+ if kb > 0.5:
+ z_eff = z_ransac
+ elif abs(z_rad) > 0.012 and (abs(z_rad) >= abs(z_ransac) or z_ransac * z_rad > 0):
+ z_eff = z_rad if abs(z_ransac) < 0.008 else 0.6 * z_rad + 0.4 * z_ransac
+ elif inl > 0.65 and abs(z_ransac) > 0.01:
+ z_eff = z_ransac
+ else:
+ z_eff = z_rad if abs(z_rad) > abs(z_ransac) else z_ransac
+
+ u_rate = float(np.median(u_rates)) if u_rates else 0.0
+ v_rate = float(np.median(v_rates)) if v_rates else 0.0
+ net_zoom_pct = round(z_eff * dur * 100.0, 2)
+ net_u_pct = u_rate * dur * 50.0 # u is in half-widths, so * 50 = % of full frame width
+ net_v_pct = v_rate * dur * 50.0
+ cam_kind = ms.get("camera") or "unknown"
+ if cam_kind == "handheld_like" and abs(net_zoom_pct) < 3.0 and max(abs(net_u_pct), abs(net_v_pct)) < 4.0:
+ traj = "handheld"
+ elif abs(net_zoom_pct) >= 2.2 and abs(net_zoom_pct) >= 0.75 * max(abs(net_u_pct), abs(net_v_pct)):
+ traj = "push_in" if net_zoom_pct > 0 else "pull_out"
+ elif max(abs(net_u_pct), abs(net_v_pct)) >= 2.5:
+ if abs(net_u_pct) >= abs(net_v_pct):
+ traj = "pan_right" if net_u_pct < 0 else "pan_left" # pixels moving left = camera panning/trucking right
+ else:
+ traj = "tilt_down" if net_v_pct < 0 else "tilt_up"
+ elif abs(z_eff) > 0.012:
+ traj = "push_in" if z_eff > 0 else "pull_out"
+ else:
+ traj = "static"
+
+ # Subject-depth-adaptive central contour comparison: under 3D parallax, the central subject scales at its own depth
+ # Z_subject (often faster than distant background). A held pose matches across start->end under some 2D scale + small
+ # shift (`TM_CCORR_NORMED` high); an articulated turn, limb gesture or walk changes geometry so no 2D scale+shift fits.
+ def _grad_env(g: np.ndarray) -> np.ndarray:
+ b = cv2.GaussianBlur(g, (0, 0), 2.6)
+ return np.hypot(cv2.Sobel(b, cv2.CV_32F, 1, 0, ksize=3), cv2.Sobel(b, cv2.CV_32F, 0, 1, ksize=3))
+
+ e0, e1 = _grad_env(grays[0]), _grad_env(grays[-1])
+ cy0, cy1 = int(0.14 * kh), max(int(0.14 * kh) + 12, int(0.88 * kh))
+ cx0, cx1 = int(0.18 * kw), max(int(0.18 * kw) + 12, int(0.82 * kw))
+ pad_y, pad_x = max(4, int(0.12 * kh)), max(4, int(0.12 * kw))
+ best_sim = 0.0
+ if float(np.linalg.norm(e0[cy0:cy1, cx0:cx1])) > 12.0 and float(np.linalg.norm(e1[cy0:cy1, cx0:cx1])) > 12.0:
+ for s_cand in (0.80, 0.88, 0.94, 1.0, 1.06, 1.14, 1.24):
+ if s_cand <= 1.0:
+ src_patch = e0[cy0:cy1, cx0:cx1]
+ th = max(8, int(round(src_patch.shape[0] * s_cand)))
+ tw = max(8, int(round(src_patch.shape[1] * s_cand)))
+ tpl = cv2.resize(src_patch, (tw, th), interpolation=cv2.INTER_AREA)
+ wy0, wy1 = max(0, (kh - th) // 2 - pad_y), min(kh, (kh + th) // 2 + pad_y)
+ wx0, wx1 = max(0, (kw - tw) // 2 - pad_x), min(kw, (kw + tw) // 2 + pad_x)
+ win = e1[wy0:wy1, wx0:wx1]
+ else:
+ # Subject grew larger from frame 0 -> end: match shrunk end-frame central patch inside frame 0
+ inv = 1.0 / s_cand
+ dst_patch = e1[cy0:cy1, cx0:cx1]
+ th = max(8, int(round(dst_patch.shape[0] * inv)))
+ tw = max(8, int(round(dst_patch.shape[1] * inv)))
+ tpl = cv2.resize(dst_patch, (tw, th), interpolation=cv2.INTER_AREA)
+ wy0, wy1 = max(0, (kh - th) // 2 - pad_y), min(kh, (kh + th) // 2 + pad_y)
+ wx0, wx1 = max(0, (kw - tw) // 2 - pad_x), min(kw, (kw + tw) // 2 + pad_x)
+ win = e0[wy0:wy1, wx0:wx1]
+ if win.shape[0] >= tpl.shape[0] and win.shape[1] >= tpl.shape[1]:
+ res_cc = cv2.matchTemplate(win, tpl, cv2.TM_CCORR_NORMED)
+ best_sim = max(best_sim, float(res_cc.max()))
+ pose_change = float(np.clip(1.0 - best_sim, 0.0, 1.0))
+ else:
+ pose_change = float(np.clip(np.abs(grays[0][cy0:cy1, cx0:cx1] - grays[-1][cy0:cy1, cx0:cx1]).mean() / 40.0, 0.0, 1.0))
+
+ flow_p90 = float(ms.get("flow_p90") or 0.0)
+ local_r = float(ms.get("local_motion_ratio") or 0.0)
+ mad_se = float(np.abs(grays[0] - grays[-1]).mean())
+ if flow_p90 < 0.22 and mad_se < 2.2 and traj == "static":
+ regime = "near_static"
+ elif kb > 0.5 or (pose_change < 0.13 and local_r < 0.04 and traj != "static"):
+ regime = "camera_only"
+ elif pose_change < 0.27:
+ regime = "anchored_pose"
+ else:
+ regime = "articulated_action"
+
+ parallax = round(float(np.median(plx_vals)), 3) if plx_vals and kb < 0.5 else 0.0
+ return {
+ "radial_zoom_per_s": round(z_rad, 4),
+ "net_zoom_pct": net_zoom_pct,
+ "parallax_score": parallax,
+ "camera_traj": traj,
+ "pose_change": round(pose_change, 3),
+ "motion_regime": regime,
+ }
diff --git a/rea_video/generation.py b/rea_video/generation.py
index f04592b..f756219 100644
--- a/rea_video/generation.py
+++ b/rea_video/generation.py
@@ -47,8 +47,23 @@ INTENT_FILE = Path("remake") / "intent.yaml"
REDRAWN_DIR = Path("remake") / "redrawn"
PROMPTS_FILE = Path("remake") / "prompts.json"
-STRATEGY_ZH = {"remix": ("参考原片改写", "remix of the source"), "keyframes": ("关键帧参考多镜头", "multi-shot from source keyframes"),
- "frames": ("首帧 / 首尾帧逐镜", "first / last frame, shot by shot"), "text": ("文生视频", "text to video")}
+STRATEGY_ZH = {
+ "edit": ("原视频动作锁定编辑(锁死切镜/运镜/姿态,仅做增量改观)", "motion-preserving video edit (locks cuts, camera & poses; delta look edit only)"),
+ "remix": ("多模态参考生视频(参考视频 + 参考图/音频)", "multimodal reference-to-video (reference video + images/audio)"),
+ "keyframes": ("多图关键帧参考生视频(一次多镜头)", "multi-shot keyframe reference-to-video"),
+ "frames": ("图生视频(首帧 / 首尾帧逐镜)", "image-to-video (first / last frame per shot)"),
+ "text": ("文生视频(纯文本提示词)", "text-to-video (prompt only)"),
+}
+VALID_MODES = ("match", "ai", "shoot")
+VALID_STRATEGIES = ("edit", "remix", "keyframes", "frames", "text")
+VALID_VIDEO_REFS = ("auto", "none", "source", "depth", "edge")
+VALID_IMAGE_REFS = ("auto", "none", "source", "depth", "edge")
+VIDEO_REF_ZH = {
+ "none": ("不传原视频(纯关键帧 / 提示词驱动)", "no reference video (keyframes / prompt only)"),
+ "source": ("原视频直接参考(RGB 擦除字幕)", "raw source video reference (subtitles erased)"),
+ "depth": ("深度视频参考(锁 3D 空间纵深与运镜、剥离原片外观)", "depth video reference (locks 3D depth & camera, strips source look)"),
+ "edge": ("边缘结构视频参考(锁轮廓构图与节奏、重绘材质光影)", "structural edge video reference (locks silhouettes & pacing, redraws look)"),
+}
def strategy_name(s: str) -> str:
@@ -56,13 +71,42 @@ def strategy_name(s: str) -> str:
return T(zh, en)
+def video_ref_name(vref: str) -> str:
+ zh, en = VIDEO_REF_ZH.get(vref, (vref, vref))
+ return T(zh, en)
+
+
# ---------------------------------------------------------------- intent
def clean_intent(d) -> dict:
"""The intent as the planner reads it; anything malformed is dropped, not guessed."""
d = d if isinstance(d, dict) else {}
- out: dict = {"generate": "all" if str(d.get("generate", "ai")).strip().lower() == "all" else "ai", "swaps": []}
+ raw_mode = str(d.get("mode") or "").strip().lower()
+ raw_gen = str(d.get("generate") or "").strip().lower()
+ if raw_mode in VALID_MODES:
+ mode = raw_mode
+ elif raw_gen == "all":
+ mode = "ai"
+ elif raw_gen == "none":
+ mode = "shoot"
+ else:
+ mode = "match"
+ gen_val = "all" if mode == "ai" else ("none" if mode == "shoot" else "ai")
+ out: dict = {"mode": mode, "generate": gen_val, "swaps": []}
if isinstance(d.get("model"), str) and d["model"].strip():
out["model"] = d["model"].strip()
+ st = str(d.get("strategy") or "").strip().lower()
+ if st in VALID_STRATEGIES:
+ out["strategy"] = st
+ vref = str(d.get("video_ref") or "").strip().lower()
+ if vref in VALID_VIDEO_REFS and vref != "auto":
+ out["video_ref"] = vref
+ iref = str(d.get("image_ref") or "").strip().lower()
+ if iref in VALID_IMAGE_REFS and iref != "auto":
+ out["image_ref"] = iref
+ if isinstance(d.get("max_images"), (int, float)) and int(d["max_images"]) > 0:
+ out["max_images"] = int(d["max_images"])
+ if isinstance(d.get("max_ref_video_s"), (int, float)) and float(d["max_ref_video_s"]) > 0:
+ out["max_ref_video_s"] = float(d["max_ref_video_s"])
for s in d.get("swaps") or []:
if not isinstance(s, dict) or not (s.get("to") or s.get("image")):
continue
@@ -71,6 +115,8 @@ def clean_intent(d) -> dict:
out["swaps"].append({"from": str(s.get("from") or "").strip(), "to": str(s.get("to") or "").strip(), "image": img})
if d.get("notes"):
out["notes"] = str(d["notes"]).strip()
+ if d.get("native_dialogue"):
+ out["native_dialogue"] = True
return out
@@ -87,7 +133,9 @@ def load_intent(out: Path) -> dict:
def save_intent(out: Path, intent: dict) -> Path:
p = Path(out) / INTENT_FILE
p.parent.mkdir(parents=True, exist_ok=True)
- keep = {k: v for k, v in intent.items() if k in ("model", "generate", "swaps", "notes") and v not in (None, "", [])}
+ keep_keys = ("model", "mode", "generate", "strategy", "video_ref", "image_ref", "max_images", "max_ref_video_s",
+ "swaps", "notes", "native_dialogue")
+ keep = {k: v for k, v in intent.items() if k in keep_keys and v not in (None, "", [])}
p.write_text(yaml.safe_dump(keep, allow_unicode=True, sort_keys=False), encoding="utf-8")
return p
@@ -111,31 +159,40 @@ def save_prompts(out: Path, prompts: dict[str, str]) -> Path:
# ---------------------------------------------------------------- what the model takes
-def spec_of(model: dict | None) -> dict:
+def spec_of(model: dict | None, intent: dict | None = None) -> dict:
m = model or {}
+ it = intent or {}
lim, prim = m.get("limits") or {}, set(m.get("primitives") or [])
d, refs = lim.get("duration_s") or {}, lim.get("refs") or {}
rv = (lim.get("ref_video_s") or {}).get("max")
multi_ref = "video.multi_reference" in prim
plan = m.get("planning") or {}
+ max_img_ov = int(it["max_images"]) if it.get("max_images") else None
+ max_rv_ov = float(it["max_ref_video_s"]) if it.get("max_ref_video_s") else None
+ base_images = int(refs.get("image") or (UNKNOWN_IMAGES if multi_ref else 0))
return {"max": float(d.get("max") or 10), "min": float(d.get("min") or 0),
"steps": [float(x) for x in d.get("steps") or []], "steps_with_refs": [float(x) for x in lim.get("duration_with_refs_s") or []],
"multi_shot": "video.multi_shot" in prim, "shots": int(lim.get("shots_per_generation") or 0) or None,
- "ref_video": "video.reference_video" in prim, "ref_videos": int(refs.get("video") or 1),
- "ref_total": float(rv) if rv else REF_CLIP_S * max(1, int(refs.get("video") or 1)),
- "multi_ref": multi_ref, "images": int(refs.get("image") or (UNKNOWN_IMAGES if multi_ref else 0)),
- "images_stated": bool(refs.get("image")), "prefer": plan.get("strategy"), "plan_images": plan.get("images"),
+ "ref_video": "video.reference_video" in prim or bool(max_rv_ov), "ref_videos": int(refs.get("video") or 1),
+ "control_video": "video.control_video" in prim,
+ "edit_v2v": "video.edit_v2v" in prim,
+ "pinned_keyframes": "video.keyframes" in prim,
+ "ref_total": max_rv_ov if max_rv_ov else (float(rv) if rv else REF_CLIP_S * max(1, int(refs.get("video") or 1))),
+ "multi_ref": multi_ref or bool(max_img_ov), "images": max_img_ov if max_img_ov is not None else base_images,
+ "images_stated": bool(refs.get("image") or max_img_ov),
+ "prefer": plan.get("strategy"), "plan_images": None if max_img_ov is not None else plan.get("images"),
"no_real_faces": bool(plan.get("no_real_faces")),
"no_audio_with_ref_video": bool(plan.get("no_audio_with_ref_video")),
"max_hardcut_s": float(plan["max_hardcut_s"]) if plan.get("max_hardcut_s") else None,
"api_params": dict(plan["api_params"]) if isinstance(plan.get("api_params"), dict) else {},
"first": "video.i2v_first_frame" in prim, "last": "video.i2v_first_last" in prim,
+ "ref_audio": "video.reference_audio" in prim,
"exclusive": bool(lim.get("exclusive_inputs")), "native_audio": bool((m.get("audio") or {}).get("native"))}
def effective_native_audio(spec: dict, strategy: str) -> bool:
"""Whether the chosen strategy can actually generate native sound on this model."""
- return bool(spec.get("native_audio")) and not (strategy == "remix" and spec.get("no_audio_with_ref_video"))
+ return bool(spec.get("native_audio")) and not (strategy in ("remix", "edit") and spec.get("no_audio_with_ref_video"))
def call_seconds(spec: dict, secs: float, refs: bool = False) -> int:
@@ -153,15 +210,65 @@ def planned_images(spec: dict) -> int:
return min(spec["images"], spec.get("plan_images") or spec["images"])
-def choose_strategy(spec: dict, n_own: int) -> str:
+def is_discontinuous_montage(b: dict | None, gen_shot_ids: list[int], new_scene: set[int], own: list[dict]) -> bool:
+ """Routing rule S01 guard: whether generated shots form an anthology/montage of disjoint one-off characters where
+ packing into an unpinned `video.multi_reference` pool causes cross-shot identity bleed and unpinned poses."""
+ if not b or len(gen_shot_ids) < 3 or own:
+ return False
+ chars = entities.cast(b).get("characters") or []
+ if not chars:
+ return False
+ gen_set = set(gen_shot_ids)
+ shot_chars: dict[int, set[str]] = {}
+ has_recurring = False
+ for k, ch in enumerate(chars):
+ s_in = [int(i) for i in (ch.get("shots") or []) if int(i) in gen_set]
+ if len(s_in) >= 2:
+ has_recurring = True
+ cid = str(ch.get("id") or ch.get("name") or f"C{k}")
+ for i in s_in:
+ shot_chars.setdefault(i, set()).add(cid)
+ if has_recurring or len(shot_chars) < 3:
+ return False
+ pairs = [(a, c) for a, c in zip(gen_shot_ids, gen_shot_ids[1:]) if a in shot_chars and c in shot_chars]
+ if len(pairs) < 2:
+ return False
+ disjoint = sum(1 for a, c in pairs if not (shot_chars[a] & shot_chars[c]))
+ scene_jumps = sum(1 for _, c in zip(gen_shot_ids, gen_shot_ids[1:]) if c in new_scene)
+ return disjoint >= 0.75 * len(pairs) and (disjoint == len(pairs) or scene_jumps >= 0.5 * (len(gen_shot_ids) - 1))
+
+
+def choose_strategy(spec: dict, n_own: int, override: str | None = None, video_ref: str | None = None,
+ discontinuous: bool = False) -> str:
+ vref = (video_ref or "").strip().lower()
+ if override == "edit" and vref not in ("none", "depth", "edge") and (spec.get("edit_v2v") or spec.get("ref_video")):
+ return "edit"
+ if vref in ("depth", "edge") and (spec.get("control_video") or spec.get("ref_video")):
+ return "remix"
+ if vref == "source":
+ if spec.get("ref_video"):
+ return "remix"
+ if spec.get("edit_v2v"):
+ return "edit"
+ if override == "text":
+ return "text"
+ if override == "frames" and spec["first"]:
+ return "frames"
+ if vref != "none" and override == "remix" and spec["ref_video"] and spec["ref_total"] >= REMIX_MIN_REF_S:
+ return "remix"
+ if override == "keyframes" and spec["multi_shot"] and (spec["multi_ref"] or spec.get("pinned_keyframes")) and planned_images(spec) >= n_own + 1:
+ return "keyframes"
pref = spec.get("prefer")
if pref == "text":
return "text"
if pref == "frames" and spec["first"]:
return "frames"
- if spec["ref_video"] and (spec["multi_shot"] or pref == "remix") and pref in (None, "remix") and spec["ref_total"] >= REMIX_MIN_REF_S:
+ if vref != "none" and spec["ref_video"] and (spec["multi_shot"] or pref == "remix") and pref in (None, "remix") and spec["ref_total"] >= REMIX_MIN_REF_S:
return "remix"
- if spec["multi_shot"] and spec["multi_ref"] and pref in (None, "keyframes") and planned_images(spec) >= n_own + 2:
+ # S01: disjoint multi-character montages without timestamp-pinned `video.keyframes` route to per-shot `frames` I2V
+ if discontinuous and not spec.get("pinned_keyframes") and spec["first"]:
+ return "frames"
+ if spec["multi_shot"] and (spec["multi_ref"] or spec.get("pinned_keyframes")) and (pref in (None, "keyframes") or vref == "none") and planned_images(spec) >= n_own + 2:
return "keyframes"
if spec["multi_shot"] and not spec["multi_ref"] and n_own == 0:
return "text"
@@ -306,10 +413,16 @@ def _shot_audio(b: dict | None, r: dict, want_dialogue: bool, want_sfx: bool) ->
if want_sfx:
for e in (b.get("audio_plan") or {}).get("sfx_merged") or []:
t = e.get("t")
- if isinstance(t, (int, float)) and r["start"] <= t < r["end"] and e.get("confidence") != "low" and e.get("sync_with") != "text_pop":
- desc = str(e.get("description") or e.get("type") or "").strip()
- if desc and desc not in sfx:
- sfx.append(desc)
+ if not (isinstance(t, (int, float)) and r["start"] <= t < r["end"]):
+ continue
+ if e.get("confidence") == "low" or e.get("sync_with") == "text_pop" or e.get("on"):
+ continue
+ # unverified stem-separator transients (drum hits / clicks on a music bed) must not pollute video prompts
+ if e.get("source") == "effects_stem" and not e.get("description"):
+ continue
+ desc = str(e.get("description") or e.get("type") or "").strip()
+ if desc and desc not in sfx:
+ sfx.append(desc)
return dlg, sfx
@@ -409,7 +522,7 @@ def _tail_lines(raw_tail: list[str] | None, brief: list[dict], ambience: str = "
def _draft(strategy: str, refs: list[dict], brief: list[dict], swaps: list[dict], style, fmt: dict | None = None,
- ambience: str = "", lint_rules: dict | None = None) -> str:
+ ambience: str = "", lint_rules: dict | None = None, video_ref: str = "source") -> str:
"""A prompt from the brief: what to keep, what changes, shot by shot. `fmt` (the model's `draft` block in
prompting.yaml) sets the prompt language, the shot lines, how images / videos are named, camera brackets, dialogue
syntax and the fixed fields, so the draft is already in the model's own shape."""
@@ -425,59 +538,79 @@ def _draft(strategy: str, refs: list[dict], brief: list[dict], swaps: list[dict]
en = lang() == "en"
vids = T("、", ", ").join(dict.fromkeys(r["tag"] for r in refs if r["tag"].startswith("@视频")))
head = []
- if strategy == "remix":
- head.append(T("{v} 是原片:照它的分镜生成,镜头数、每个镜头的时长、景别、机位、运镜、动作和剪辑节奏都跟它一致,画面内容照下面写",
- "{v} is the source: follow its shots (count, length, size, camera, movement, action and cutting rhythm); the picture is as written below", v=vids))
+ if strategy == "edit":
+ head.append(T("{v} 是基准原片:严格锁死它的每一个切镜时间点、3D 机位运镜轨迹、主体朝向、肢体姿态变化节奏与背景空间构图,不做二次分镜重演;仅体现下面的增量设定变化",
+ "{v} is the base video: strictly lock every shot-cut timestamp, 3D camera trajectory, subject orientation, body pose progression and spatial layout without re-staging actions; apply only the delta changes below", v=vids or "@视频1"))
+ elif strategy == "remix":
+ if video_ref == "depth":
+ head.append(T("{v} 是这段的灰度深度控制视频:严格对齐它的镜头切点、推拉运镜轨迹、前景遮挡与三维空间纵深,不要渲染成黑白灰阶;人物外观、材质、色彩和光影完全按参考图与下面的描述全彩渲染",
+ "{v} is a grayscale depth control video: strictly follow its shot cuts, camera movement, foreground occlusion and 3D spatial depth while rendering full rich color, lighting and textures from the reference images and descriptions below (never output grayscale)", v=vids))
+ elif video_ref == "edge":
+ head.append(T("{v} 是这段的结构边缘控制视频:严格对齐它的镜头切点、轮廓构图比例、运镜和动作节奏,不要渲染成线框或黑白线条;色彩、材质和光影完全按参考图与下面的描述全彩渲染",
+ "{v} is a structural edge control video: strictly follow its shot cuts, silhouette framing, camera movement and motion rhythm while rendering full rich color, lighting and textures from the reference images and descriptions below (never output wireframe or line-art)", v=vids))
+ else:
+ head.append(T("{v} 是原片:照它的分镜生成,镜头数、每个镜头的时长、景别、机位、运镜、动作和剪辑节奏都跟它一致,画面内容照下面写",
+ "{v} is the source: follow its shots (count, length, size, camera, movement, action and cutting rhythm); the picture is as written below", v=vids))
elif strategy == "keyframes":
head.append(T("按下面的镜头顺序一次生成,镜头之间硬切;每个镜头的构图、景别和机位参考对应的原片画面图",
"Generate the shots below in order in one go, hard cuts between them; each shot takes composition, size and camera from its source frame image"))
head += [_swap_line(sw) for sw in swaps]
- # in first/last-frame mode, the input frame already fixes aspect ratio, lighting and colour grade; repeating them weakens motion
- if strategy != "frames":
+ # in first/last-frame or motion-locked edit mode, repeating static scene descriptions weakens motion/pose locking
+ if strategy not in ("frames", "edit"):
st = style.get(lang(), "") if isinstance(style, dict) else style
if st:
head.append(st)
if fmt.get("negatives_line", True):
head.append(T("画面里不要出现字幕、文字和水印", "No subtitles, captions or watermarks in the picture"))
lines = []
- for i, x in enumerate(brief, 1):
- if strategy == "frames":
- text = (x.get("motion_en") if en and x.get("motion_en") else x.get("motion") or x.get("action")) \
- or T("(缺镜头描述:先看图复核补写)", "(no description: write one in the image review)")
- mv = x.get("camera_move_en") if en else x.get("camera_move")
- if fmt.get("camera_brackets") and x.get("bracket") and "[" not in text:
- text = f"{x['bracket']} {text}"
- elif mv and mv.lower() not in text.lower():
- text = mv + T(",", ", ") + text
- else:
- text = (x.get("action_en") if en and x.get("action_en") else x["action"]) \
- or T("(缺镜头描述:先看图复核补写)", "(no description: write one in the image review)")
- framing = x.get("framing_en") if en else x.get("framing")
- if strategy == "keyframes" and not x.get("composition") and framing:
- text = framing + T("。", ". ") + text
- if x.get("composition"):
- text += T("(构图参考 {k})", " (composition: {k})", k=x["composition"])
- if fmt.get("camera_brackets") and x.get("bracket") and "[" not in text:
- text = f"{x['bracket']} {text}"
- audio_tail = _format_audio_bits(x, fmt, en)
- if audio_tail:
- text = text.rstrip("。.;;") + audio_tail
- a, z = x["at"], x["at"] + x["duration"]
- i_word = _WORD_NUMS[i - 1] if i <= len(_WORD_NUMS) else str(i)
- keys = {"i": i, "I_WORD": i_word, "text": text, "a": _mmss(a), "z": _mmss(z), "at": _mmss(a, ms=True),
- "s0": int(round(a)), "s1": max(int(round(z)), int(round(a)) + 1), "d": max(1, int(round(x["duration"])))}
- shot_tpl = fmt.get("remix_shot") if strategy == "remix" and fmt.get("remix_shot") else fmt.get("shot")
- if shot_tpl:
- if len(brief) == 1 and strategy == "frames" and not fmt.get("first_shot"):
+ if strategy == "edit" and not any(x.get("dialogue") or x.get("sfx") or x.get("composition") for x in brief):
+ lines.append(T("其余所有画面内容保持完全不变(所有切镜时刻、运镜、人物朝向姿态、动作幅度、服饰道具、场景与光影全部照旧)",
+ "Keep everything else the same (preserve every cut timestamp, camera movement, subject orientation, pose motion, outfit, props, scene and lighting unchanged)"))
+ else:
+ for i, x in enumerate(brief, 1):
+ if strategy == "edit":
+ text = T("沿用 {v} 对应片段的全部机位运镜、主体朝向、动作姿态与光线构图,仅保持上述设定一致",
+ "Preserve the exact camera trajectory, subject orientation, pose motion and lighting layout of the matching segment in {v}, applying only the specified delta",
+ v=vids or "@视频1")
+ if x.get("composition"):
+ text += T("(外观参考 {k})", " (appearance reference: {k})", k=x["composition"])
+ elif strategy == "frames":
+ text = (x.get("motion_en") if en and x.get("motion_en") else x.get("motion") or x.get("action")) \
+ or T("(缺镜头描述:先看图复核补写)", "(no description: write one in the image review)")
+ mv = x.get("camera_move_en") if en else x.get("camera_move")
+ if fmt.get("camera_brackets") and x.get("bracket") and "[" not in text:
+ text = f"{x['bracket']} {text}"
+ elif mv and mv.lower() not in text.lower():
+ text = mv + T(",", ", ") + text
+ else:
+ text = (x.get("action_en") if en and x.get("action_en") else x["action"]) \
+ or T("(缺镜头描述:先看图复核补写)", "(no description: write one in the image review)")
+ framing = x.get("framing_en") if en else x.get("framing")
+ if strategy == "keyframes" and not x.get("composition") and framing:
+ text = framing + T("。", ". ") + text
+ if x.get("composition"):
+ text += T("(构图参考 {k})", " (composition: {k})", k=x["composition"])
+ if fmt.get("camera_brackets") and x.get("bracket") and "[" not in text:
+ text = f"{x['bracket']} {text}"
+ audio_tail = _format_audio_bits(x, fmt, en)
+ if audio_tail:
+ text = text.rstrip("。.;;") + audio_tail
+ a, z = x["at"], x["at"] + x["duration"]
+ i_word = _WORD_NUMS[i - 1] if i <= len(_WORD_NUMS) else str(i)
+ keys = {"i": i, "I_WORD": i_word, "text": text, "a": _mmss(a), "z": _mmss(z), "at": _mmss(a, ms=True),
+ "s0": int(round(a)), "s1": max(int(round(z)), int(round(a)) + 1), "d": max(1, int(round(x["duration"])))}
+ shot_tpl = fmt.get("remix_shot") if strategy in ("remix", "edit") and fmt.get("remix_shot") else fmt.get("shot")
+ if shot_tpl:
+ if len(brief) == 1 and strategy in ("frames", "edit") and not fmt.get("first_shot"):
+ lines.append(text)
+ else:
+ lines.append((fmt.get("first_shot") if i == 1 and fmt.get("first_shot") else shot_tpl).format(**keys))
+ elif len(brief) == 1:
lines.append(text)
+ elif strategy in ("remix", "edit"):
+ lines.append(T("镜头{i}:{t}", "Shot {i}: {t}", i=i, t=text))
else:
- lines.append((fmt.get("first_shot") if i == 1 and fmt.get("first_shot") else shot_tpl).format(**keys))
- elif len(brief) == 1:
- lines.append(text)
- elif strategy == "remix":
- lines.append(T("镜头{i}:{t}", "Shot {i}: {t}", i=i, t=text))
- else:
- lines.append(T("镜头{i}(从 {a:.1f} 秒起):{t}", "Shot {i} (from {a:.1f}s): {t}", i=i, a=a, t=text))
+ lines.append(T("镜头{i}(从 {a:.1f} 秒起):{t}", "Shot {i} (from {a:.1f}s): {t}", i=i, a=a, t=text))
sep = T("。", ". ")
join_str = fmt.get("join") if isinstance(fmt.get("join"), str) else "\n"
body_lines = join_str.join(ln.rstrip(".") + "." if join_str == " " and not ln.rstrip().endswith((".", "!", "?", '"')) else ln for ln in lines)
@@ -494,7 +627,7 @@ def _mmss(t: float, ms: bool = False) -> str:
return f"{int(t // 60):02d}:{t % 60:06.3f}" if ms else f"{int(t // 60):02d}:{int(round(t)) % 60:02d}"
-def _inputs(strategy: str, refs: list[dict], seg: list[dict], spec: dict) -> list[dict]:
+def _inputs(strategy: str, refs: list[dict], seg: list[dict], spec: dict, b: dict | None = None) -> list[dict]:
own = [r for r in refs if r.get("user")]
kf = [r for r in refs if r.get("keyframe")]
vids = [r for r in refs if r["tag"].startswith("@视频")]
@@ -515,15 +648,28 @@ def _inputs(strategy: str, refs: list[dict], seg: list[dict], spec: dict) -> lis
out.append({"kind": "first_frame", "need": "yes", "source": T("原片 `{f}`(擦掉字幕;换人、换物时先照着重画)", "source `{f}` (subtitles erased; redraw it first when people or products change)",
f=r["assets"]["first_frame"]),
"why": T("锁住构图、景别和主体位置", "locks composition, size and subject position")})
- moves = (r.get("features") or {}).get("camera") not in (None, "static", "unknown")
+ rf = r.get("features") or {}
+ moves = (rf.get("camera") not in (None, "static", "unknown")
+ or rf.get("camera_traj") not in (None, "static")
+ or rf.get("motion_regime") == "articulated_action")
if spec["last"] and (moves or r["duration"] >= 3):
out.append({"kind": "last_frame", "need": "opt", "source": T("原片 `{f}`,处理同首帧", "source `{f}`, treated like the first frame", f=r["assets"]["last_frame"]),
"why": T("有运镜或动作时给终点,动作和落幅更接近原片", "with a move, pinning the end keeps action and final framing close to the source")})
+ if b and spec.get("ref_audio") and (strategy != "frames" or not spec.get("exclusive")) and ((b.get("stems") or {}).get("ok")):
+ vtype = (((b.get("sound_sources") or {}).get("format_context") or {}).get("video_type") or "")
+ audio = b.get("audio") or {}
+ if vtype == "music_mv" or any(r["base"]["label"] == "avatar" for r in seg):
+ out.append({"kind": "ref_audio", "need": "opt", "source": T("人声干声 `stems/vocals.wav`(换歌/换台词时传新干声)", "vocal stem `stems/vocals.wav` (or your new vocal track)"),
+ "why": T("驱动演唱/说话口型与节奏对齐", "drives singing / lip-sync timing")})
+ elif audio.get("beat_synced_edit") and (audio.get("music") or {}).get("present"):
+ out.append({"kind": "ref_audio", "need": "opt", "source": T("配乐轨 `stems/music.wav`(或替换后的同 BPM 配乐)", "music stem `stems/music.wav` (or your replacement track at the same BPM)"),
+ "why": T("辅助动作与切镜卡在节拍上", "helps align motion and cuts to the beat")})
return out
def build_unit(seg: list[dict], k: int, strategy: str, spec: dict, own: list[dict], swaps: list[dict], style,
- model: dict | None, fmt: dict | None = None, b: dict | None = None, lint_rules: dict | None = None) -> dict:
+ model: dict | None, fmt: dict | None = None, b: dict | None = None, lint_rules: dict | None = None,
+ video_ref: str = "source") -> dict:
t0, t1 = seg[0]["start"], seg[-1]["end"]
dur = round(sum(r["duration"] for r in seg), 3)
ranges = _ranges(seg)
@@ -537,15 +683,33 @@ def build_unit(seg: list[dict], k: int, strategy: str, spec: dict, own: list[dic
kept_tags = {r["tag"] for r in refs}
unit_swaps = [sw if sw.get("tag") in kept_tags else {**sw, "tag": None} for sw in swaps]
keyframe_tag: dict[int, str] = {}
- if strategy == "remix":
+ eff_vref = "source" if strategy == "edit" else (video_ref if strategy == "remix" else "none")
+ if strategy in ("remix", "edit"):
each = min(REF_CLIP_S, spec["ref_total"])
+ v_desc_tpl = {
+ "depth": (T("原片 {s} 的灰度深度控制视频(只参考空间景深、运镜与切镜节奏)", "grayscale depth video of {s} (3D spatial depth, camera and cuts only)"), "depth"),
+ "edge": (T("原片 {s} 的结构边缘控制视频(只参考轮廓构图、运镜与切镜节奏)", "structural edge video of {s} (silhouette framing, camera and cuts only)"), "edge"),
+ "source": (T("原片 {s}(擦掉字幕和贴纸)", "source {s} (subtitles and stickers erased)"), "source"),
+ }
for part in range(parts):
a0 = t0 + dur * part / parts
pr = [[a0, a0 + dur / parts]] if parts > 1 else ranges
for c, rr in enumerate(_clips(pr, each), 1):
- refs.append({"tag": f"@视频{c}", "part": part + 1, "ranges": rr,
- "what": (T("第 {k} 次:", "call {k}: ", k=part + 1) if parts > 1 else "")
- + T("原片 {s}(擦掉字幕和贴纸)", "source {s} (subtitles and stickers erased)", s=join(f"{a:.1f}–{z:.1f}s" for a, z in rr))})
+ span_s = join(f"{a:.1f}–{z:.1f}s" for a, z in rr)
+ desc_txt, vkind = v_desc_tpl.get(eff_vref, v_desc_tpl["source"])
+ refs.append({"tag": f"@视频{c}", "part": part + 1, "ranges": rr, "video_kind": vkind,
+ "what": (T("第 {k} 次:", "call {k}: ", k=part + 1) if parts > 1 else "") + desc_txt.format(s=span_s)})
+ # For appearance-free control videos (depth / edge) or edit_v2v without global swap image, attach per-shot appearance keyframes if available
+ if eff_vref in ("depth", "edge") and can_ref_img and not own:
+ room = max(0, planned_images(spec) - sum(1 for x in refs if x["tag"].startswith("@图片")))
+ framed = {r["index"] for r in sorted(seg, key=lambda r: -r["duration"])[:room]}
+ for r in seg:
+ if r["index"] not in framed:
+ continue
+ tag = f"@图片{sum(1 for x in refs if x['tag'].startswith('@图片')) + 1}"
+ keyframe_tag[r["index"]] = tag
+ refs.append({"tag": tag, "keyframe": r["index"], "t": round(r["start"] + min(0.3, r["duration"] / 2), 3),
+ "what": T("镜头 #{i} 的首帧外观参考图(优先读 remake/redrawn/shot{i:03d}.png)", "appearance keyframe for shot #{i} (uses remake/redrawn/shot{i:03d}.png when present)", i=r["index"])})
elif strategy == "keyframes":
# image slots left after the user's own: when they run short, the longest shots keep their source frame and the
# rest get their framing in words (a call kept whole beats a frame for every shot when subjects have no image)
@@ -564,13 +728,13 @@ def build_unit(seg: list[dict], k: int, strategy: str, spec: dict, own: list[dic
ambience = str(((b or {}).get("whole_video_vlm") or {}).get("ambience") or "")
brief = _brief(seg, keyframe_tag, b=b, want_dialogue=want_dlg, want_sfx=can_audio)
call_s = call_seconds(spec, dur / parts, refs=bool(refs))
- unit = {"id": f"G{k}", "kind": "generate", "strategy": strategy, "label": label, "label_zh": LABEL_ZH[label],
+ unit = {"id": f"G{k}", "kind": "generate", "strategy": strategy, "video_ref": eff_vref, "label": label, "label_zh": LABEL_ZH[label],
"shots": [r["index"] for r in seg], "start": round(t0, 3), "end": round(t1, 3), "duration": dur, "ranges": ranges,
"mode": "multi_shot" if len(seg) > 1 else ("split" if parts > 1 else "single"), "calls": parts,
"generate_s": round(dur / parts, 3), "call_s": call_s, "model": (model or {}).get("id"), "model_name": model_name((model or {}).get("name")),
- "refs": refs, "brief": brief, "draft": _draft(strategy, refs, brief, unit_swaps, style, fmt, ambience=ambience, lint_rules=lint_rules),
+ "refs": refs, "brief": brief, "draft": _draft(strategy, refs, brief, unit_swaps, style, fmt, ambience=ambience, lint_rules=lint_rules, video_ref=eff_vref),
"draft_format": bool(fmt),
- "inputs": _inputs(strategy, refs, seg, spec)}
+ "inputs": _inputs(strategy, refs, seg, spec, b=b)}
unframed = [x["shot"] for x in brief if strategy == "keyframes" and not x.get("composition")]
missing = [x["shot"] for x in brief if not x["action"]]
if missing:
@@ -602,12 +766,136 @@ def part_starts(b: dict) -> set[int]:
return out
+def _fallback_image_prompt(r: dict, style_str: str, aspect_ratio: str) -> str:
+ """Reverse-engineered still-image prompt for a shot: explicit image_prompt first, else synthesized from framing + description + style."""
+ p = shot_prompts(r)
+ if lang() == "zh" and p.get("image_prompt"):
+ return p["image_prompt"]
+ orient = {"9:16": T("竖屏 9:16", "Vertical 9:16"), "16:9": T("横屏 16:9", "Horizontal 16:9"),
+ "1:1": T("方形 1:1", "Square 1:1"), "3:4": T("竖屏 3:4", "Vertical 3:4"),
+ "4:3": T("横屏 4:3", "Horizontal 4:3")}.get(aspect_ratio, aspect_ratio)
+ fr_loc, fr_en = framing_words(r)
+ fr = fr_en if lang() == "en" else fr_loc
+ desc = (p.get("video_prompt_en") if lang() == "en" else None) or shot_description(r) or _shot_text(r)
+ bits = [x for x in (orient, fr, desc, style_str if lang() == "zh" else "") if x]
+ sep = "。" if lang() == "zh" else ". "
+ return sep.join(x.rstrip("。. ") for x in bits)
+
+
+def build_image_tasks(b: dict, units: list[dict], intent: dict) -> list[dict]:
+ """Plan upstream still-image generation (Text-to-Image vs Image-to-Image) with reverse-engineered prompts and reference files."""
+ gen_ids = list(dict.fromkeys(s for u in units for s in u.get("shots") or []))
+ if not gen_ids or all(u.get("strategy") == "text" for u in units):
+ return []
+ rec_by_idx = {r["index"]: r for r in b.get("shots") or []}
+ cast = entities.cast(b)
+ style_str = str(cast.get("style") or "").strip()
+ ar = str((b.get("source") or {}).get("aspect_ratio") or "9:16")
+ swaps = [s for s in (intent.get("swaps") or []) if s.get("from") or s.get("to") or s.get("image")]
+ # recurring characters across >= 2 generated shots: first shot establishes anchor image, later shots use I2I reference
+ recurring_anchor: dict[int, tuple[int, str]] = {}
+ anchor_shots: set[int] = set()
+ for ch in cast.get("characters") or []:
+ c_shots = [i for i in (ch.get("shots") or []) if i in gen_ids]
+ if len(c_shots) >= 2:
+ anchor = c_shots[0]
+ anchor_shots.add(anchor)
+ cname = str(ch.get("name") or ch.get("id") or T("主角", "character"))
+ for s_idx in c_shots[1:]:
+ recurring_anchor.setdefault(s_idx, (anchor, cname))
+ tasks: list[dict] = []
+ img_ref = str(intent.get("image_ref") or "auto").strip().lower()
+ for idx in gen_ids:
+ r = rec_by_idx.get(idx)
+ if not r:
+ continue
+ u = next((u for u in units if idx in u["shots"]), {})
+ first_ref = (r.get("assets") or {}).get("first_frame") or ""
+ base_p = _fallback_image_prompt(r, style_str, ar)
+ if swaps:
+ method = "i2i"
+ method_zh = T("图生图(保留原片构图换主体)", "image-to-image (keep composition, swap subject)")
+ ctrl_ref = f"remake/refs/shot{idx:03d}_{img_ref}.jpg" if img_ref in ("depth", "edge") else first_ref
+ refs_in = ([f"`{ctrl_ref}`" + (T("(结构控制图定空间构图)", " (structural control frame for spatial layout)") if img_ref in ("depth", "edge")
+ else T("(原片首帧定构图与光影)", " (source first frame for composition and lighting)"))] if ctrl_ref else [])
+ refs_in += [f"`{Path(s['image']).name}`" + (T("({w})", " ({w})", w=s.get("to") or T("替换主体", "replacement subject"))) for s in swaps if s.get("image")]
+ swap_txt = semi().join(_swap_line(s) for s in swaps)
+ prompt = (f"{swap_txt}。{base_p}" if lang() == "zh" else f"{swap_txt}. {base_p}").strip(" 。.")
+ elif idx in recurring_anchor:
+ anchor, cname = recurring_anchor[idx]
+ method = "i2i"
+ method_zh = T("图生图 / 多图参考生图(锁角色外观)", "image-to-image / reference edit (lock character look)")
+ refs_in = [T("镜头 #{a} 生成的首帧基准图(锁 {n} 外观服饰)", "anchor frame from shot #{a} (locks {n} look and outfit)", a=anchor, n=cname)]
+ if img_ref in ("depth", "edge"):
+ refs_in.append(f"`remake/refs/shot{idx:03d}_{img_ref}.jpg`" + T("(结构控制图定本镜景别与机位)", " (structural frame for shot framing and pose)"))
+ elif img_ref != "none" and first_ref:
+ refs_in.append(f"`{first_ref}`" + T("(原片首帧:对照本镜景别与构图)", " (source first frame: shot framing and pose reference)"))
+ prefix = T("保持与镜头 #{a} 基准图完全一致的人物五官与服装:", "Keep the exact facial features and outfit from shot #{a}'s anchor image: ", a=anchor)
+ prompt = (prefix + base_p).strip()
+ elif img_ref == "none":
+ method = "t2i"
+ method_zh = (T("纯文生图(不垫原片帧;兼作后续镜头角色基准图)", "pure text-to-image (no source frame; serves as character anchor)")
+ if idx in anchor_shots else
+ T("纯文生图(不垫原片帧,完全凭提示词独立生成)", "pure text-to-image (independent generation without source frame)"))
+ refs_in = []
+ prompt = base_p
+ elif img_ref == "source":
+ method = "i2i"
+ method_zh = T("图生图(垫擦除字幕的原片首帧:锁渲染介质、光影反差、景深散景与机位,重绘全新角色与主体)",
+ "image-to-image (from cleaned source first frame: lock rendering medium, lighting contrast, DOF bokeh and camera angle, redraw new subject)")
+ clean_ref = f"remake/refs/shot{idx:03d}_clean.jpg"
+ refs_in = [f"`{clean_ref}`" + T("(已擦除字幕的原片首帧)", " (cleaned source first frame)")]
+ prefix = T("严格继承参考图的渲染介质质感、光影反差、景深散景与机位仰俯角,将人物与主体替换为全新设计:",
+ "Strictly inherit the reference image's rendering medium, lighting contrast, depth-of-field bokeh and camera angle while replacing the character and subject with a fresh design: ")
+ prompt = (prefix + base_p).strip()
+ elif img_ref in ("depth", "edge"):
+ method = "i2i"
+ kind_lbl = T("深度图", "depth map") if img_ref == "depth" else T("软边缘图", "soft-edge map")
+ method_zh = T("结构参考图生图(垫原片首帧{k}:锁三维构图比例,彻底剥离原片像素与文字)",
+ "structure-guided I2I (from source {k}: lock 3D spatial layout, strip source pixels and text)", k=kind_lbl)
+ ctrl_ref = f"remake/refs/shot{idx:03d}_{img_ref}.jpg"
+ refs_in = [f"`{ctrl_ref}`" + T("(本镜首帧{k})", " (shot first-frame {k})", k=kind_lbl)]
+ prefix = T("按参考{k}的空间前后层次、主体比例与机位构图进行全彩高精度渲染(不要输出黑白灰阶或线框):",
+ "Follow the reference {k} for 3D spatial layering, subject scale and camera framing while rendering full rich color and textures (never output grayscale or wireframe): ", k=kind_lbl)
+ prompt = (prefix + base_p).strip()
+ else:
+ method = "t2i"
+ method_zh = (T("文生图(兼作后续镜头角色基准图)", "text-to-image (also serves as character anchor image)")
+ if idx in anchor_shots else
+ T("文生图(或垫原片首帧做构图参考图生图)", "text-to-image (or low-denoise I2I from source frame)"))
+ refs_in = ([f"`{first_ref}`" + T("(原片首帧:构图与画风对照)", " (source first frame: composition and style reference)")] if first_ref else [])
+ prompt = base_p
+ tasks.append({"shot": idx, "role": "first_frame", "role_zh": T("首帧图", "first frame"),
+ "method": method, "method_zh": method_zh, "image_ref": img_ref, "refs": refs_in, "prompt": prompt,
+ "source_frame": first_ref, "t": round(r["start"] + min(0.25, r["duration"] / 3), 3),
+ "target": f"remake/redrawn/shot{idx:03d}.png"})
+ if u.get("strategy") == "frames" and wants_last_frame(u):
+ last_ref = (r.get("assets") or {}).get("last_frame") or ""
+ l_refs = [T("本镜已生成的首帧图", "this shot's generated first frame")]
+ if last_ref:
+ l_refs.append(f"`{last_ref}`" + T("(原片尾帧落幅对照)", " (source last-frame framing reference)"))
+ tasks.append({"shot": idx, "role": "last_frame", "role_zh": T("尾帧图", "last frame"),
+ "method": "i2i", "method_zh": T("图生图(由首帧推尾帧状态)", "image-to-image (derive end state from first frame)"),
+ "refs": l_refs,
+ "prompt": T("在本镜首帧图基础上,按动作结束状态微调画面落幅:{m}",
+ "From this shot's first frame, adjust to the ending pose and framing: {m}",
+ m=_motion_text(r, en=lang() == "en")),
+ "source_frame": last_ref, "target": f"remake/redrawn/{u['id']}_last.png"})
+ return tasks
+
+
def plan_generation(b: dict, model: dict | None, intent: dict, new_scene: set[int], style, skip: set[int],
notes: dict | None = None, hardcut_max_s: float = 10.0) -> dict:
"""Generation units and the facts they were planned on. `skip`: shots made another way (motion drive, a clip
reused from another unit)."""
- spec = spec_of(model)
- labels = ALL_GEN_LABELS if intent.get("generate") == "all" else GEN_LABELS
+ spec = spec_of(model, intent=intent)
+ mode = intent.get("mode") or ("ai" if intent.get("generate") == "all" else ("shoot" if intent.get("generate") == "none" else "match"))
+ req_vref = intent.get("video_ref")
+ if mode == "shoot" or intent.get("generate") == "none":
+ st_empty = choose_strategy(spec, 0, intent.get("strategy"), video_ref=req_vref)
+ return {"strategy": st_empty, "video_ref": "none", "spec": spec, "labels": [], "units": [], "own_refs": [], "image_tasks": [],
+ "rules": {"max_s": spec["max"], "max_shots": spec["shots"], "mode": "shoot", "generate": "none", "video_ref": "none"}}
+ labels = ALL_GEN_LABELS if (mode == "ai" or intent.get("generate") == "all") else GEN_LABELS
own = []
swaps = []
for s in intent.get("swaps") or []:
@@ -618,28 +906,33 @@ def plan_generation(b: dict, model: dict | None, intent: dict, new_scene: set[in
"what": (s["to"] or T("用户给的参考图", "the user's reference image")) + (T("(替换原片的{f})", " (replaces the source's {f})", f=s["from"]) if s["from"] else "")})
if s["from"] or s["to"]:
swaps.append({"from": s["from"], "to": s["to"], "tag": tag})
- strategy = choose_strategy(spec, len(own))
- cap_hardcut = spec.get("max_hardcut_s") or hardcut_max_s
- if strategy == "remix":
- max_s, max_shots = min(spec["max"], spec["ref_total"]), (spec["shots"] if spec["multi_shot"] else 1)
+ gen_shot_ids = [r["index"] for r in b["shots"] if r["base"]["label"] in labels and r["index"] not in skip]
+ discont = is_discontinuous_montage(b, gen_shot_ids, new_scene, own)
+ strategy = choose_strategy(spec, len(own), intent.get("strategy"), video_ref=req_vref, discontinuous=discont)
+ eff_vref = "source" if strategy == "edit" else ((req_vref if req_vref in ("source", "depth", "edge") else "source") if strategy == "remix" else "none")
+ # Respect the model's real per-call duration limit: only apply a hardcut cap when the model entry explicitly sets max_hardcut_s
+ cap_hardcut = spec.get("max_hardcut_s")
+ if strategy in ("remix", "edit"):
+ max_s, max_shots = min(spec["max"], spec["ref_total"]), (spec["shots"] if (spec["multi_shot"] or strategy == "edit") else 1)
elif strategy == "keyframes":
- # a swapped-in subject with no image is held only by its description: every extra call is another chance for it
- # to come out different, so keep calls whole and let some shots go without a source frame; otherwise apply S06 hardcut guard
text_only = any(not s.get("image") for s in intent.get("swaps") or [])
- max_s = spec["max"] if text_only else min(spec["max"], cap_hardcut)
+ max_s = spec["max"] if (text_only or not cap_hardcut) else min(spec["max"], cap_hardcut)
max_shots = spec["shots"] if text_only else min(x for x in (spec["shots"], planned_images(spec) - len(own)) if x)
elif strategy == "text" and spec["multi_shot"]:
- max_s, max_shots = min(spec["max"], cap_hardcut), spec["shots"]
+ max_s, max_shots = (min(spec["max"], cap_hardcut) if cap_hardcut else spec["max"]), spec["shots"]
else:
max_s, max_shots = spec["max"], 1
units: list[dict] = []
new_part = part_starts(b)
- for run in runs(b["shots"], labels, skip, joinable_inserts=strategy in ("remix", "keyframes", "text") and max_shots != 1):
+ for run in runs(b["shots"], labels, skip, joinable_inserts=strategy in ("edit", "remix", "keyframes", "text") and max_shots != 1):
for seg in pack(run, max_s, max_shots, new_scene, new_part):
units.append(build_unit(seg, len(units) + 1, strategy, spec, own, swaps, style, model,
- (notes or {}).get("draft"), b=b, lint_rules=(notes or {}).get("lint")))
- return {"strategy": strategy, "spec": spec, "labels": list(labels), "units": units, "own_refs": own,
- "rules": {"max_s": max_s, "max_shots": max_shots, "generate": intent.get("generate", "ai")}}
+ (notes or {}).get("draft"), b=b, lint_rules=(notes or {}).get("lint"), video_ref=eff_vref))
+ img_tasks = build_image_tasks(b, units, intent)
+ return {"strategy": strategy, "video_ref": eff_vref, "spec": spec, "labels": list(labels), "units": units, "own_refs": own,
+ "image_tasks": img_tasks, "discontinuous_montage": discont,
+ "rules": {"max_s": max_s, "max_shots": max_shots, "mode": mode, "generate": intent.get("generate", "ai"),
+ "video_ref": eff_vref, "image_ref": intent.get("image_ref", "auto")}}
# ---------------------------------------------------------------- checks
@@ -711,6 +1004,30 @@ def part_frame_name(u: dict, part: int, key: str) -> str:
return f"{u['id']}_{key}" if int(u.get("calls") or 1) <= 1 else f"{u['id']}_p{part}_{key}"
+def unit_frame_aliases(u: dict, part: int, key: str) -> list[str]:
+ """Accepted filenames under remake/redrawn/ for a frames-mode unit's first or last frame (bridges `G1_first` and `shot001`)."""
+ primary = part_frame_name(u, part, key)
+ out = [primary]
+ shots = u.get("shots") or []
+ if int(u.get("calls") or 1) <= 1 and len(shots) == 1:
+ idx = int(shots[0])
+ extra = [f"shot{idx:03d}", f"shot{idx:03d}_first"] if key == "first" else [f"shot{idx:03d}_last"]
+ for nm in extra:
+ if nm not in out:
+ out.append(nm)
+ return out
+
+
+def resolve_redrawn_frame(out: Path, names: str | list[str]) -> Path | None:
+ """First existing redrawn file among `names` (e.g. `G1_first` or `shot001`)."""
+ cands = [names] if isinstance(names, str) else list(names)
+ for nm in cands:
+ hit = redrawn_frame(out, nm)
+ if hit is not None:
+ return hit
+ return None
+
+
def wants_last_frame(u: dict) -> bool:
return any(x["kind"] == "last_frame" and x["need"] != "no" for x in u.get("inputs") or [])
@@ -724,6 +1041,24 @@ def source_frame_names(u: dict) -> list[str]:
return names
+def _unredrawn_frame_names(u: dict, root: Path | None) -> list[str]:
+ """Names of unit source frames that have not yet been redrawn under remake/redrawn/ (respecting shotNNN aliases)."""
+ out: list[str] = []
+ for r in u.get("refs") or []:
+ if r.get("keyframe"):
+ nm = f"shot{int(r['keyframe']):03d}"
+ if not (root and redrawn_frame(root, nm)):
+ out.append(nm)
+ if u.get("strategy") == "frames":
+ keys = ("first", "last") if wants_last_frame(u) else ("first",)
+ for part in range(1, int(u.get("calls") or 1) + 1):
+ for key in keys:
+ aliases = unit_frame_aliases(u, part, key)
+ if not (root and resolve_redrawn_frame(root, aliases)):
+ out.append(aliases[0])
+ return out
+
+
def unit_images(u: dict) -> list[dict]:
"""The images one unit sends, in prompt order."""
return [r for r in u.get("refs") or [] if r["tag"].startswith("@图片")]
@@ -756,6 +1091,16 @@ def checks(plan: dict, intent: dict, prompts: dict[str, str], notes: dict | None
"this model takes no reference images: only the text description is used; pick a model with reference images or first-frame input to lock appearance"))
for u in units:
n_img, n_vid = len(unit_images(u)), len({r["tag"] for r in u["refs"] if r["tag"].startswith("@视频")})
+ if u.get("video_ref") in ("depth", "edge") and not spec.get("control_video"):
+ m_name = u.get("model_name") or u.get("model") or "?"
+ add("error", T("{u} 选了 {v} 控制视频,但 {m} 仅声明语义参考视频(video.reference_video),不支持像素级空间控制(video.control_video),会导致姿态朝向丢失、跨镜串色或灰阶污染:请改用 --strategy edit(原片动作锁定编辑)、--strategy frames(逐镜首尾帧锁构图),或换支持 video.control_video 的模型(如 wan-vace)",
+ "{u} uses a {v} control video, but {m} only declares semantic reference video (video.reference_video), not pixel-aligned spatial control (video.control_video), causing pose drift, cross-shot bleed or grayscale wash: switch to --strategy edit, --strategy frames, or a video.control_video model (e.g. wan-vace)",
+ u=u["id"], v=u.get("video_ref"), m=m_name), u["id"])
+ if u.get("strategy") == "keyframes" and len(u.get("shots") or []) > 1 and not spec.get("pinned_keyframes") and plan.get("discontinuous_montage"):
+ m_name = u.get("model_name") or u.get("model") or "?"
+ add("warn", T("{u} 把多个无共享角色、跨场景的独立镜头合进了 {m} 的无时间戳多图池(video.multi_reference),容易跨镜头串角色或丢失首帧朝向:建议改用 --strategy frames 逐镜锁首尾帧,或改用 --strategy edit 锁原片动作",
+ "{u} packs disjoint multi-character shots into {m}'s unpinned image pool (video.multi_reference), risking cross-shot identity bleed and unpinned poses: prefer --strategy frames or --strategy edit",
+ u=u["id"], m=m_name), u["id"])
if spec.get("images") is not None and n_img > max(spec["images"], 0) and (n_img or spec.get("multi_ref")):
add("error", T("{u} 要传 {n} 张图,超过这个模型的 {m} 张", "{u} sends {n} images, over this model's {m}", u=u["id"], n=n_img, m=spec["images"]), u["id"])
for part in sorted({r.get("part", 1) for r in u["refs"] if r["tag"].startswith("@视频")}):
@@ -770,14 +1115,14 @@ def checks(plan: dict, intent: dict, prompts: dict[str, str], notes: dict | None
if u["generate_s"] < SHORT_UNIT_S:
add("warn", T("{u} 只有 {d:.1f} 秒:单独生成不稳,按模型最短时长生成后剪短,或和相邻镜头合到一起",
"{u} is only {d:.1f}s: unstable on its own; generate the model's minimum and trim, or join it with a neighbour", u=u["id"], d=u["generate_s"]), u["id"])
- stale_frames = [x for x in source_frame_names(u) if not (root and redrawn_frame(root, x))] if intent.get("swaps") else []
+ stale_frames = _unredrawn_frame_names(u, root) if intent.get("swaps") else []
if stale_frames:
add("warn", T("{u} 的参考帧还是原片里被替换的主体,模型会在镜头中途变来变去:先照换入的主体重画,存成 remake/redrawn/{f}.png",
"{u}'s reference frames still show the subject being swapped, so the model may morph it mid-shot: redraw them with the new subject as remake/redrawn/{f}.png",
u=u["id"], f="|".join(stale_frames)), u["id"])
if spec.get("no_real_faces"):
framed_shots = {int(r["keyframe"]) for r in u.get("refs") or [] if r.get("keyframe") and not (root and redrawn_frame(root, f"shot{int(r['keyframe']):03d}"))}
- frames_unredrawn = u.get("strategy") == "frames" and any(not (root and redrawn_frame(root, x)) for x in source_frame_names(u))
+ frames_unredrawn = u.get("strategy") == "frames" and bool(_unredrawn_frame_names(u, root))
face_shots = [x["shot"] for x in u.get("brief") or []
if x.get("real_face") and (n_vid > 0 or frames_unredrawn or x["shot"] in framed_shots)]
if face_shots:
@@ -877,6 +1222,7 @@ def rewrite_prompts(plan: dict, out: Path, client=None) -> dict[str, str]:
fmt = notes.get("draft") or {}
st = plan.get("strategy") or "frames"
st_rule = {
+ "edit": "IMPORTANT (Motion-Preserving Video Edit mode): The uploaded base video ALREADY defines every shot cut, 3D camera trajectory, subject orientation, pose progression and timing. Keep the prompt concise and delta-only: state ONLY what visual attributes/subjects differ and explicitly lock all camera moves, poses, cuts and timing to the base video without writing a verbose re-staging screenplay.",
"frames": "IMPORTANT (First/Last-Frame I2V mode): The input image ALREADY fixes subject appearance, clothing, background, lighting and framing. Write ONLY the motion progression, end state and camera movement; delete static scene/appearance descriptions.",
"remix": "IMPORTANT (Reference-video Remix mode): The reference video carries shot cuts, camera movement and pacing. Assign roles to uploaded assets clearly and describe what happens in each shot with the swapped subjects/props.",
"keyframes": "IMPORTANT (Multi-shot Keyframe Reference mode): Each framed shot gets a source composition image; swapped subjects have their own reference images. State each image's role clearly and write shots in order.",
@@ -938,7 +1284,8 @@ def check_lines(cs: list[dict]) -> list[str]:
# ---------------------------------------------------------------- report
INPUT_ZH = {"text": ("文字提示词", "text prompt"), "first_frame": ("首帧图", "first frame"), "last_frame": ("尾帧图", "last frame"),
- "ref_image": ("参考图", "reference images"), "ref_video": ("参考视频", "reference video")}
+ "ref_image": ("参考图", "reference images"), "ref_video": ("参考视频", "reference video"),
+ "ref_audio": ("参考音频", "reference audio")}
NEED_ZH = {"yes": ("要", "yes"), "opt": ("建议", "worth it"), "no": ("不用", "no")}
@@ -946,38 +1293,82 @@ def _fed(u: dict) -> str:
return " + ".join(dict.fromkeys(T(*INPUT_ZH[x["kind"]]) for x in u.get("inputs") or [] if x["need"] != "no" and x["kind"] != "text"))
+def image_tasks_md(tasks: list[dict], strategy: str) -> list[str]:
+ """Markdown block for the upstream still-image layer (Text-to-Image vs Image-to-Image + reverse-engineered prompts + refs)."""
+ if not tasks:
+ return []
+ note = (T("当前视频模态为首帧/首尾帧图生视频:先按下表逐张生成画面帧,再喂入视频模型跑纯动态。",
+ "Video modality is first/last-frame I2V: generate the still frames below first, then feed them into the video model with motion-only prompts.")
+ if strategy == "frames" else
+ T("如果不直接喂原片画面、而是要做全新角色/换主体或改走逐镜图生视频,按下表准备每镜首帧图(已区分文生图与图生图,并给出反推生图提示词与参考图):",
+ "When generating fresh visuals, swapping subjects, or running shot-by-shot I2V instead of feeding raw source frames, prepare each shot's frame as below (T2I vs I2I, reverse-engineered image prompts and reference files):"))
+ L = ["", "<details><summary>" + T("前置图片准备与反推提示词(文生图 / 图生图,共 {n} 张)",
+ "Upstream image preparation and reverse-engineered prompts (T2I / I2I, {n} images)", n=len(tasks)) + "</summary>", "",
+ note, "",
+ T("| 镜头 | 用途 | 生图方式 | 参考图输入 | 产出保存路径 |", "| Shot | Role | Image modality | Reference inputs | Save as |"),
+ "|---|---|---|---|---|"]
+ for t in tasks:
+ refs_s = semi().join(t.get("refs") or []) or "—"
+ L.append(f"| #{t['shot']} | {t['role_zh']} | {t['method_zh']} | {refs_s} | `{t['target']}` |")
+ L.append("")
+ for t in tasks:
+ if t.get("prompt"):
+ L.append(f"- **#{t['shot']} {t['role_zh']}({t['method_zh']})**" if lang() == "zh"
+ else f"- **#{t['shot']} {t['role_zh']} ({t['method_zh']})**")
+ L.append(f" - {T('图片提示词:', 'Image prompt: ')}{t['prompt']}")
+ L += ["", "</details>"]
+ return L
+
+
def report_md(plan: dict, prompts: dict[str, str]) -> list[str]:
- """The generation subsection of the remake part: how it was grouped, then one block per unit."""
+ """The generation subsection of the remake part: video modality, grouping, per-unit prompts, and upstream image layer."""
units = plan.get("units") or []
if not units:
return []
rules, spec = plan.get("rules") or {}, plan.get("spec") or {}
st = plan.get("strategy")
- how = {"remix": T("这段原片擦掉字幕后当参考视频,模型照它的分镜、运镜和节奏出完这段的镜头",
- "the source stretch, subtitles erased, is the reference video; the model follows its shots, camera and pacing"),
- "keyframes": (T("这个模型也能吃参考视频,这里按它的默认排法:", "the model also takes reference video, but its default plan is used here: ")
+ vref = plan.get("video_ref") or rules.get("video_ref") or ("source" if st in ("remix", "edit") else "none")
+ remix_how = {
+ "depth": T("把原片转为灰度深度控制视频(`depth.mp4`)传入,模型照它的三维空间纵深、运镜轨迹与切镜节奏生成,外观材质与色彩完全按参考图与提示词重绘(需模型支持 `video.control_video`;可用 `--video-ref none|source|edge` 切换)",
+ "feeds a grayscale depth control video (`depth.mp4`) so the model follows 3D spatial depth, camera and cut timing while redrawing full look and colour (requires `video.control_video`; switch with `--video-ref none|source|edge`)"),
+ "edge": T("把原片转为结构软边缘控制视频(`edge.mp4`)传入,模型照它的轮廓构图、运镜与节奏生成,外观材质与光影完全重绘(需模型支持 `video.control_video`;可用 `--video-ref none|source|depth` 切换)",
+ "feeds a structural edge control video (`edge.mp4`) so the model follows silhouette layout, camera and pacing while redrawing full look and lighting (requires `video.control_video`; switch with `--video-ref none|source|depth`)"),
+ "source": T("这段原片擦掉字幕后直接当参考视频,模型照它的分镜、运镜和节奏一次出完这段的镜头(可用 `--strategy edit` 切为极简增量动作锁定编辑,或 `--video-ref none` 不传原视频)",
+ "the source stretch, subtitles erased, is the reference video; the model follows its shots, camera and pacing in one go (pass `--strategy edit` for motion-locked delta editing, or `--video-ref none` for no reference video)"),
+ }.get(vref)
+ how = {"edit": T("把擦掉字幕的原片作为基准视频,配极简增量编辑提示词(仅声明要改的外观/属性,显式锁死原片切镜、运镜、主体朝向与动作姿态,避免模型推翻原动作重演)",
+ "feeds the subtitle-erased source clip with a delta-only edit prompt (states only visual attribute/subject changes while locking cuts, camera trajectory, orientation and poses)"),
+ "remix": remix_how,
+ "keyframes": (T("这个模型也能吃参考视频,这里按不传原视频的多图关键帧排法(可用 `--strategy edit` 或 `--video-ref source` 切为原视频参考):",
+ "the model also takes reference video; using multi-shot keyframes without reference video here (pass `--strategy edit` or `--video-ref source` for video reference): ")
if spec.get("ref_video") else T("这个模型不吃参考视频,", "the model takes no reference video: "))
- + T("每个镜头给一张擦掉字幕的原片画面定构图,换进去的东西各给参考图",
- "one source frame per shot (subtitles erased) fixes composition, swapped-in things get their own images"),
- "frames": T("一次只出一个镜头,从原片首帧(和尾帧)起步", "one shot per call, from the source's first (and last) frame"),
- "text": T("只有文字提示词", "prompt only")}[st]
- notes_md = [T("- 分组:连着的镜头尽量放进同一次生成,单次 ≤{s:.0f} 秒", "- Grouping: consecutive shots share a call where they fit, ≤{s:.0f}s per call", s=rules.get("max_s") or 0)
- + (T("、≤{n} 个镜头", ", ≤{n} shots", n=rules["max_shots"]) if rules.get("max_shots") else "")
- + T(";段太长时优先在换场景处切开", "; a long stretch is cut at a scene change first"),
- T("- 输入:{h}", "- Inputs: {h}", h=how)]
+ + T("每个镜头给一张关键帧图定构图/外观,换进去的东西各给参考图",
+ "one keyframe image per shot fixes composition/look, swapped-in things get their own images"),
+ "frames": T("一次出一个镜头,先用文生图/图生图做好首帧(及尾帧),再配纯动态提示词图生视频",
+ "one shot per call: prepare the first (and last) frame via T2I/I2I, then run image-to-video with a motion-only prompt"),
+ "text": T("纯文字提示词直接文生视频", "text-to-video from prompt only")}[st]
+ notes_md = [T("- 视频生成模态:{m}(参考形式:{v})", "- Video modality: {m} (video reference: {v})", m=strategy_name(st), v=video_ref_name(vref)),
+ T("- 可选参考形式切换:`--video-ref none`(不传原视频)/ `source`(原视频直接参考)/ `depth`(深度视频参考)/ `edge`(边缘结构视频参考);前置生图可用 `--image-ref none|source|depth|edge` 控制",
+ "- Switch reference regime: `--video-ref none` (no source video) / `source` (raw source video) / `depth` (depth video) / `edge` (edge video); control still generation with `--image-ref none|source|depth|edge`"),
+ T("- 分组:按模型真实单次上限(≤{s:.0f} 秒", "- Grouping: packed up to the model's real per-call limit (≤{s:.0f}s", s=rules.get("max_s") or 0)
+ + (T("、≤{n} 个镜头", ", ≤{n} shots", n=rules["max_shots"]) if rules.get("max_shots") else "")
+ + T(")合并,能一次生成的绝不拆碎;超长时优先在叙事段落或换景处切开", "), keeping stretches in one call whenever they fit; longer stretches cut at story seams or scene changes"),
+ T("- 输入:{h}", "- Inputs: {h}", h=how)]
if plan.get("audio_note"):
notes_md.append(T("- 声音:{a}", "- Audio: {a}", a=plan["audio_note"]))
if plan.get("overlay_note"):
notes_md.append(T("- 包装层:{a}", "- Packaging: {a}", a=plan["overlay_note"]))
- L = [T("| 段 | 镜头 | 时间 | 时长 | 要准备 |", "| Part | Shots | Time | Length | Prepare |"), "|---|---|---|---|---|"]
+ L = [T("- **视频生成方式**:{m}", "- **Video modality**: {m}", m=strategy_name(st)), "",
+ T("| 段 | 镜头 | 时间 | 时长 | 视频模型输入 |", "| Part | Shots | Time | Length | Video model inputs |"), "|---|---|---|---|---|"]
for u in units:
when = join(f"{a:.1f}–{z:.1f}s" for a, z in u["ranges"])
call = u.get("call_s") or u["generate_s"]
length = (T("生成 {m:.0f}s,剪到 {d:.1f}s", "generate {m:.0f}s, trim to {d:.1f}s", m=call, d=u["generate_s"])
if call - u["generate_s"] >= 0.5 else f"{u['duration']:.1f}s")
L.append(f"| {u['id']} | {shot_ids(u['shots'])} | {when} | {length}"
- f"{T('({c} 次)', ' ({c} calls)', c=u['calls']) if u['calls'] > 1 else ''} | {_fed(u) or '—'} |")
- L += ["", '<details class="ref"><summary>' + T("这样分段的原因", "Why it is split this way") + "</summary>", ""] + notes_md + ["", "</details>"]
+ f"{T('({c} 次)', ' ({c} calls)', c=u['calls']) if u['calls'] > 1 else ''} | {_fed(u) or T('纯文本提示词', 'text prompt')} |")
+ L += ["", '<details class="ref"><summary>' + T("模态选择与分段依据", "Modality choice and grouping basis") + "</summary>", ""] + notes_md + ["", "</details>"]
+ L += image_tasks_md(plan.get("image_tasks") or [], st)
for u in units:
L += ["", "<details><summary>" + T("{id} · 镜头 {sh} · {d:.1f}s", "{id} · shots {sh} · {d:.1f}s",
id=u["id"], sh=shot_ids(u["shots"]), d=u["duration"]) + "</summary>", "",
diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.py
index 765d8de..664c141 100644
--- a/rea_video/integrations/capsule_cinema.py
+++ b/rea_video/integrations/capsule_cinema.py
@@ -298,7 +298,7 @@ def write_handoff(b: dict, bdir: Path, jobs: list[dict]) -> Path:
return out
-GEN_TYPE = {"remix": "multimodal", "keyframes": "multimodal", "frames": "first_last_frame", "text": "text_to_video"}
+GEN_TYPE = {"edit": "multimodal", "remix": "multimodal", "keyframes": "multimodal", "frames": "first_last_frame", "text": "text_to_video"}
def _unit_model_options(u: dict, spec: dict, eng: str | None, vids: list[str], images: list[dict]) -> dict:
@@ -321,7 +321,7 @@ def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[str
frame per shot (keyframes), the shot's first / last frame (frames) or nothing but text; the user's images first; the
final prompt from remake/prompts.json, else the draft. Everything taken from the source has its subtitles erased."""
from ..drive import scene_text
- from ..generation import part_frame_name, redrawn_frame, unit_images
+ from ..generation import redrawn_frame, resolve_redrawn_frame, unit_frame_aliases, unit_images
spec = plan.get("spec") or {}
lo, hi = int(spec.get("min") or 1), int(spec.get("max") or 15)
@@ -343,23 +343,26 @@ def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[str
params["video_paths"] = vids
if images:
params["image_paths"] = [x["path"] for x in images]
+ bookend = False
if u["strategy"] == "frames":
first, last = files.get((part, "first")), files.get((part, "last"))
if last:
params.update(start_image_path=first, end_image_path=last)
+ bookend = True
else:
params.update(generation_type="image_to_video", image_path=first)
jid = u["id"] if len(parts) == 1 else f"{u['id']}-{part}"
times = [r["t"] for r in u["refs"] if r.get("keyframe") and not redrawn_frame(bdir, f"shot{int(r['keyframe']):03d}")]
if u["strategy"] == "frames":
- times += [t for key, t in _part_frame_times(u, part) if not redrawn_frame(bdir, part_frame_name(u, part, key))]
+ times += [t for key, t in _part_frame_times(u, part)
+ if (part, key) in files and not resolve_redrawn_frame(bdir, unit_frame_aliases(u, part, key))]
words = list(dict.fromkeys(w for t in times for w in scene_text(b, t)))
warning = T("参考帧里还有画面内文字({w}),模型可能照着生成:换成干净图,或确认有授权", "the reference frames still show text in the picture ({w}), which the model may copy: use a clean image or confirm you have the rights",
w=join(words[:6])) if words else None
m_opts = _unit_model_options(u, spec, eng, vids, images)
jobs.append({"shot": u["shots"][0], "id": jid, "unit": u["id"], "part": part, "parts": len(parts), "shots": u["shots"],
- "executor": "capsule_cinema", "label": u["label"], "strategy": u["strategy"], "images": images,
- "params": params, **({"model_options": m_opts} if m_opts else {}),
+ "executor": "capsule_cinema", "label": u["label"], "strategy": u["strategy"], "bookend": bookend,
+ "images": images, "params": params, **({"model_options": m_opts} if m_opts else {}),
"trim_to": round(secs, 3), "prompt_source": "final" if u["id"] in prompts else "draft",
**({"warning": warning} if warning else {})})
return jobs
@@ -377,10 +380,11 @@ def ref_clips(b: dict, bdir: Path, unit: dict) -> dict[tuple[int, str], str]:
"""What one unit takes from the source, subtitles and laid-on text erased, written once into remake/refs/:
reference clips ({(part, "@视频1"): path}), per-shot keyframes ({(1, "@图片3"): path}) and the first / last frame of
a frames unit, per call ({(part, "first"): path, (part, "last"): path}). Files are named by span, so a re-plan never reuses a stale one."""
- from ..drive import clean_clip, clean_frame
- from ..generation import part_frame_name, redrawn_frame, wants_last_frame
+ from ..drive import clean_clip, clean_frame, control_clip
+ from ..generation import load_intent, part_frame_name, redrawn_frame, resolve_redrawn_frame, unit_frame_aliases, wants_last_frame
d = bdir / "remake" / "refs"
+ intent = (b.get("production_plan") or {}).get("intent") or b.get("intent") or load_intent(bdir)
out = {}
for r in unit.get("refs") or []:
if r.get("keyframe"):
@@ -390,18 +394,57 @@ def ref_clips(b: dict, bdir: Path, unit: dict) -> dict[tuple[int, str], str]:
out[(1, r["tag"])] = str(f.resolve())
elif r["tag"].startswith("@视频") and r.get("ranges"):
a, z = r["ranges"][0][0], r["ranges"][-1][1]
- f = d / f"{unit['id']}_p{r.get('part', 1)}_v{r['tag'][3:]}_{a:.1f}-{z:.1f}.mp4"
+ vkind = r.get("video_kind") or "source"
+ prefix = "v" if vkind == "source" else f"{vkind}_v"
+ f = d / f"{unit['id']}_p{r.get('part', 1)}_{prefix}{r['tag'][3:]}_{a:.1f}-{z:.1f}.mp4"
if not f.is_file():
- clean_clip(b, r["ranges"], f)
+ if vkind in ("depth", "edge"):
+ control_clip(b, r["ranges"], f, kind=vkind)
+ else:
+ clean_clip(b, r["ranges"], f)
out[(r.get("part", 1), r["tag"])] = str(f.resolve())
if unit.get("strategy") == "frames":
for part in range(1, max(1, int(unit.get("calls") or 1)) + 1):
+ first_rd = resolve_redrawn_frame(bdir, unit_frame_aliases(unit, part, "first"))
+ last_rd = resolve_redrawn_frame(bdir, unit_frame_aliases(unit, part, "last"))
+ subject_redesigned = (first_rd is not None or bool(intent.get("swaps"))
+ or str(intent.get("image_ref") or "auto") not in ("", "auto"))
for key, t in _part_frame_times(unit, part):
- if key == "last" and not wants_last_frame(unit):
- continue
+ if key == "last":
+ if not wants_last_frame(unit):
+ continue
+ # Never pair a redesigned/swapped first frame with an unredrawn source last frame (causes mid-shot morphing back)
+ if subject_redesigned and last_rd is None:
+ continue
name = part_frame_name(unit, part, key)
- f = redrawn_frame(bdir, name) or d / f"{name}_{t:.2f}.jpg"
+ rd = first_rd if key == "first" else last_rd
+ f = rd or d / f"{name}_{t:.2f}.jpg"
if not f.is_file():
clean_frame(b, t, f)
out[(part, key)] = str(f.resolve())
return out
+
+
+def image_ref_frames(b: dict, bdir: Path, plan: dict) -> list[Path]:
+ """Export cleaned/depth/edge still reference frames into remake/refs/ when image_ref is explicitly set."""
+ from ..drive import clean_frame, control_frame
+
+ iref = str((plan.get("intent") or {}).get("image_ref") or "auto").strip().lower()
+ if iref not in ("source", "depth", "edge"):
+ return []
+ d = bdir / "remake" / "refs"
+ written: list[Path] = []
+ for t in plan.get("image_tasks") or []:
+ if t.get("role") != "first_frame":
+ continue
+ idx = int(t["shot"])
+ ts = float(t.get("t") or 0.0)
+ suffix = "clean" if iref == "source" else iref
+ dst = d / f"shot{idx:03d}_{suffix}.jpg"
+ if not dst.is_file():
+ if iref == "source":
+ clean_frame(b, ts, dst)
+ else:
+ control_frame(b, ts, dst, kind=iref)
+ written.append(dst)
+ return written
diff --git a/rea_video/integrations/run_remake.py b/rea_video/integrations/run_remake.py
index 66b3f94..4b21c4b 100644
--- a/rea_video/integrations/run_remake.py
+++ b/rea_video/integrations/run_remake.py
@@ -13,6 +13,239 @@ import time
from pathlib import Path
+_FALLBACK_ENGINE_ALIASES = {
+ "gemini-omni-flash": "gemini-omni-1.2-flash",
+ "veo-3.1": "veo3",
+}
+
+
+def _resolve_engine_name(raw_engine: str, vgt) -> str:
+ import os
+
+ routes = {}
+ for item in os.getenv("REA_VIDEO_ENGINE_ROUTES", "").split(","):
+ if "=" in item:
+ a, b = item.split("=", 1)
+ if a.strip() and b.strip():
+ routes[vgt.normalize_video_engine(a.strip())] = vgt.normalize_video_engine(b.strip())
+ norm = vgt.normalize_video_engine(raw_engine)
+ if norm in routes:
+ return routes[norm]
+ try:
+ from src.video_engines import registered_video_engines
+
+ reg = registered_video_engines()
+ except Exception:
+ reg = {}
+ if reg and norm not in reg and norm in _FALLBACK_ENGINE_ALIASES and _FALLBACK_ENGINE_ALIASES[norm] in reg:
+ return _FALLBACK_ENGINE_ALIASES[norm]
+ return norm
+
+
+def _adapt_unit_params(eng_tool, raw_params: dict, model_options: dict | None, job_id: str) -> dict:
+ """Adapt UniversalVideoGenerationSchema-shaped params to a specific engine tool's signature & schema."""
+ import inspect
+
+ sig = inspect.signature(eng_tool._run)
+ schema = getattr(eng_tool, "args_schema", None)
+ schema_fields = set(getattr(schema, "model_fields", {}) or {})
+ allowed = (schema_fields | set(sig.parameters)) - {"self", "extra", "kwargs"}
+ has_strict_schema = bool(schema_fields)
+
+ p = {k: v for k, v in raw_params.items() if k != "engine"}
+ if "output_path" in (schema_fields | set(sig.parameters)) and "output_path" not in p and p.get("output_dir"):
+ p["output_path"] = str(Path(p["output_dir"]) / f"{job_id}.mp4")
+ if "task_id" in allowed and "task_id" not in p and p.get("output_path"):
+ op = Path(p["output_path"])
+ tf = op.with_suffix(".task.json")
+ if not op.is_file() and tf.is_file():
+ saved_tid = (json.loads(tf.read_text(encoding="utf-8")) or {}).get("task_id")
+ if saved_tid:
+ p["task_id"] = saved_tid
+
+ # Map frame keys for tools that name them first_frame / last_frame (e.g. yy2img / gemini-omni-1.2-flash)
+ if "first_frame" in allowed and "first_frame" not in p:
+ first = p.get("start_image_path") or p.get("image_path")
+ if first:
+ p["first_frame"] = first
+ if "last_frame" in allowed and "last_frame" not in p and p.get("end_image_path"):
+ p["last_frame"] = p["end_image_path"]
+ if "image_path" in allowed and "image_path" not in p and p.get("start_image_path"):
+ p["image_path"] = p["start_image_path"]
+
+ m_opts = dict(model_options or {})
+ accepts_var_kw = any(param.kind == inspect.Parameter.VAR_KEYWORD for param in sig.parameters.values())
+ if has_strict_schema or not accepts_var_kw:
+ p = {k: v for k, v in p.items() if k in allowed}
+ for k, v in m_opts.items():
+ if k in allowed:
+ p[k] = v
+ if "options" in allowed and isinstance(p.get("options"), (dict, type(None))):
+ rest = {k: v for k, v in m_opts.items() if k not in allowed}
+ if rest:
+ p["options"] = {**(p.get("options") or {}), **rest}
+ elif "extra" in sig.parameters and sig.parameters["extra"].kind != inspect.Parameter.VAR_KEYWORD:
+ rest = {k: v for k, v in m_opts.items() if k not in allowed}
+ if rest:
+ p["extra"] = {**(p.get("extra") or {}), **rest}
+ else:
+ p.update(m_opts)
+ return p
+
+
+def _frame_struct_vec(bgr) -> "np.ndarray":
+ import cv2
+ import numpy as np
+
+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY).astype(np.float32)
+ small = cv2.resize(cv2.GaussianBlur(gray, (0, 0), 2.0), (24, 42), interpolation=cv2.INTER_AREA)
+ gx = np.abs(cv2.Sobel(small, cv2.CV_32F, 1, 0, ksize=3)).ravel()
+ gy = np.abs(cv2.Sobel(small, cv2.CV_32F, 0, 1, ksize=3)).ravel()
+ hog = np.concatenate([gx, gy])
+ hog = hog / (float(np.linalg.norm(hog)) + 1e-5)
+ luma = small.ravel() - float(small.mean())
+ luma = luma / (float(np.linalg.norm(luma)) + 1e-5)
+ v = np.concatenate([0.70 * hog, 0.70 * luma])
+ n = float(np.linalg.norm(v))
+ return v / n if n > 1e-5 else np.zeros_like(v)
+
+
+def _split_multishot_unit(video_file: Path, shot_ids: list[int], trim_to: float, out_dir: Path,
+ ref_shots: list[dict] | None = None, bdir: Path | None = None) -> dict[str, str]:
+ """Split a single-call multi-shot unit clip at its actual pixel hard cuts and align sub-clips to target shots.
+
+ Multi-shot generators occasionally shift cut timing or insert an extra internal sub-cut inside one shot. Rather than
+ blindly taking top-(N-1) histogram jumps (which cascades an off-by-one shift across later shots when K > N), this
+ detects all true hard cuts (K >= N sub-clips) and runs monotonic DP alignment on normalized time + appearance-invariant
+ structural similarity so every target shot gets one clean, jump-free sub-clip.
+ """
+ import subprocess
+ import cv2
+ import numpy as np
+
+ n_target = len(shot_ids)
+ if n_target < 2 or not video_file.is_file():
+ return {}
+ cap = cv2.VideoCapture(str(video_file))
+ fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0)
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
+ if fps <= 0 or total_frames < n_target * 4:
+ cap.release()
+ return {}
+ end_frame = min(total_frames, max(n_target * 4, int(round(trim_to * fps)))) if trim_to > 0 else total_frames
+ small_frames: list = []
+ hists: list = []
+ while len(small_frames) < end_frame:
+ ok, fr = cap.read()
+ if not ok:
+ break
+ sm = cv2.resize(fr, (108, 192))
+ small_frames.append(sm)
+ hsv = cv2.cvtColor(sm, cv2.COLOR_BGR2HSV)
+ h = cv2.calcHist([hsv], [0, 1, 2], None, [12, 4, 4], [0, 180, 0, 256, 0, 256])
+ cv2.normalize(h, h)
+ hists.append(h)
+ cap.release()
+ end_frame = len(small_frames)
+ if end_frame < n_target * 4:
+ return {}
+
+ # Combined cut strength: HSV Bhattacharyya jump + normalized pixel MAD spike above local neighbourhood
+ mads = np.array([float(np.mean(np.abs(small_frames[i].astype(np.int16) - small_frames[i - 1].astype(np.int16))))
+ for i in range(1, end_frame)], dtype=np.float32)
+ bhat = np.array([float(cv2.compareHist(hists[i - 1], hists[i], cv2.HISTCMP_BHATTACHARYYA))
+ for i in range(1, end_frame)], dtype=np.float32)
+ # Local contrast ratio on pixel MAD catches hard cuts even between two similarly coloured dark scenes
+ med_k = np.array([float(np.median(mads[max(0, i - 5):min(len(mads), i + 6)])) for i in range(len(mads))], dtype=np.float32)
+ spike_ratio = mads / (med_k + 2.5)
+ scores: list[tuple[int, float]] = []
+ for i in range(3, end_frame - 3):
+ sc = float(0.55 * bhat[i - 1] + 0.45 * min(1.0, mads[i - 1] / 60.0))
+ is_real_cut = (mads[i - 1] >= 28.0 and spike_ratio[i - 1] >= 2.6 and bhat[i - 1] >= 0.16) or bhat[i - 1] >= 0.36
+ scores.append((i, sc, is_real_cut))
+
+ min_gap = max(6, int(round(0.35 * fps)))
+ # First collect all genuine hard cuts (up to n_target + 3 to absorb occasional extra sub-cuts)
+ strong_cuts: list[int] = []
+ for f_idx, sc, is_real in sorted(scores, key=lambda x: -x[1]):
+ if not is_real and len(strong_cuts) >= n_target - 1:
+ break
+ if sc < 0.22:
+ break
+ if all(abs(f_idx - p) >= min_gap for p in strong_cuts):
+ strong_cuts.append(f_idx)
+ if len(strong_cuts) >= n_target + 3:
+ break
+ if len(strong_cuts) < n_target - 1:
+ return {}
+
+ cand_bounds = [0] + sorted(strong_cuts) + [end_frame]
+ subclips = [(a, b) for a, b in zip(cand_bounds[:-1], cand_bounds[1:]) if b - a >= 2]
+ k_sub = len(subclips)
+ if k_sub < n_target:
+ return {}
+
+ if k_sub == n_target:
+ chosen = subclips
+ else:
+ # Monotonic DP: match each of the N target shots to its best clean sub-clip (by structural frame match + normalized time)
+ gen_vecs = [_frame_struct_vec(small_frames[(a + b) // 2]) for a, b in subclips]
+ gen_mids = [0.5 * (a + b) / float(end_frame) for a, b in subclips]
+ ref_vecs: list = [None] * n_target
+ ref_mids = [(i + 0.5) / float(n_target) for i in range(n_target)]
+ ref_durs = [1.0 / float(n_target)] * n_target
+ if ref_shots and len(ref_shots) == n_target:
+ u_t0 = float(ref_shots[0]["start"])
+ u_span = max(0.1, float(ref_shots[-1]["end"]) - u_t0)
+ ref_mids = [(0.5 * (float(s["start"]) + float(s["end"])) - u_t0) / u_span for s in ref_shots]
+ ref_durs = [max(0.02, (float(s["end"]) - float(s["start"])) / u_span) for s in ref_shots]
+ if bdir is not None:
+ for idx_i, s in enumerate(ref_shots):
+ ff = (s.get("assets") or {}).get("first_frame")
+ p_ff = (Path(bdir) / ff) if ff else None
+ if p_ff and p_ff.is_file():
+ im = cv2.imread(str(p_ff))
+ if im is not None:
+ ref_vecs[idx_i] = _frame_struct_vec(im)
+
+ gen_durs = [max(0.02, (b - a) / float(end_frame)) for a, b in subclips]
+ dp = np.full((n_target, k_sub), -1e9, dtype=np.float64)
+ parent = np.full((n_target, k_sub), -1, dtype=np.int32)
+ for j in range(k_sub):
+ for i in range(n_target):
+ if j < i or (k_sub - 1 - j) < (n_target - 1 - i):
+ continue
+ sim = float(np.dot(ref_vecs[i], gen_vecs[j])) if ref_vecs[i] is not None else 0.5
+ t_pen = 0.65 * abs(gen_mids[j] - ref_mids[i])
+ dur_ratio = min(gen_durs[j], ref_durs[i]) / max(gen_durs[j], ref_durs[i])
+ node_sc = sim - t_pen + 0.35 * dur_ratio
+ if i == 0:
+ dp[i, j] = node_sc
+ else:
+ best_prev = int(np.argmax(dp[i - 1, :j]))
+ dp[i, j] = dp[i - 1, best_prev] + node_sc
+ parent[i, j] = best_prev
+ cur_j = int(np.argmax(dp[n_target - 1]))
+ pick_idx = []
+ for i in range(n_target - 1, -1, -1):
+ pick_idx.append(cur_j)
+ cur_j = int(parent[i, cur_j])
+ chosen = [subclips[j] for j in reversed(pick_idx)]
+
+ out_dir.mkdir(parents=True, exist_ok=True)
+ clips: dict[str, str] = {}
+ for s_id, (a, b) in zip(shot_ids, chosen):
+ dst = out_dir / f"shot_{int(s_id):03d}.mp4"
+ subprocess.run(
+ ["ffmpeg", "-v", "error", "-y", "-i", str(video_file),
+ "-vf", f"trim=start_frame={a}:end_frame={b},setpts=PTS-STARTPTS",
+ "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(dst)],
+ check=True,
+ )
+ clips[str(s_id)] = str(dst)
+ return clips
+
+
def _video_path(res) -> str | None:
"""Find the generated file in the various result shapes capsule-cinema tools return."""
if isinstance(res, str):
@@ -60,7 +293,7 @@ def main() -> None:
planned = Path(spec.get("capsule_root") or "").expanduser().resolve()
if planned != root:
sys.exit(f"jobs.json 的 capsule_root({planned})与 --capsule-root({root})不一致;确认来源可信后用 --capsule-root 指定")
- out_root = root / "output"
+ out_root = (root / "output").resolve()
for j in spec["jobs"]:
od = Path(j.get("params", {}).get("output_dir", "")).expanduser().resolve()
if j.get("executor") == "capsule_cinema" and not od.is_relative_to(out_root):
@@ -101,24 +334,9 @@ def main() -> None:
print(f"{label}: {j['params']['generation_type']} via {j['params']['engine']} ...", flush=True)
try:
if j.get("unit"): # a unit's references go straight to the engine's own tool
- import inspect
-
- eng_tool = vgt._tool_for_engine(vgt.normalize_video_engine(j["params"]["engine"]))
- p = {k: v for k, v in j["params"].items() if k != "engine"}
- m_opts = j.get("model_options") or {}
- if m_opts:
- sig = inspect.signature(eng_tool._run)
- accepts_var_kw = any(param.kind == inspect.Parameter.VAR_KEYWORD for param in sig.parameters.values())
- if accepts_var_kw:
- p.update(m_opts)
- else:
- for k, v in m_opts.items():
- if k in sig.parameters:
- p[k] = v
- if "extra" in sig.parameters and isinstance(p.get("extra"), (dict, type(None))):
- rest = {k: v for k, v in m_opts.items() if k not in sig.parameters}
- if rest:
- p["extra"] = {**(p.get("extra") or {}), **rest}
+ eng_name = _resolve_engine_name(j["params"]["engine"], vgt)
+ eng_tool = vgt._tool_for_engine(eng_name)
+ p = _adapt_unit_params(eng_tool, j["params"], j.get("model_options"), j["id"])
res = eng_tool._run(**p)
else:
res = tool._run(**j["params"])
@@ -129,11 +347,32 @@ def main() -> None:
results["results"][key] = {"id": j["id"], "video": video, "raw": res if not video else None,
"seconds": round(time.time() - t0, 1), "trim_to": j["trim_to"],
**({k: j[k] for k in ("unit", "part", "parts", "shots")} if j.get("unit") else {})}
+ if video and j.get("unit") and int(j.get("parts") or 1) == 1 and len(j.get("shots") or []) > 1:
+ try:
+ b_json = Path(spec["breakdown"]) if spec.get("breakdown") else None
+ b_data = json.loads(b_json.read_text(encoding="utf-8")) if b_json and b_json.is_file() else {}
+ by_idx = {int(s["index"]): s for s in (b_data.get("shots") or [])}
+ r_shots = [by_idx[int(i)] for i in j["shots"] if int(i) in by_idx]
+ per_shot = _split_multishot_unit(
+ Path(video), list(j["shots"]), float(j["trim_to"]), Path(video).parent / "shots",
+ ref_shots=r_shots if len(r_shots) == len(j["shots"]) else None,
+ bdir=b_json.parent if b_json else None,
+ )
+ for s_key, s_vid in per_shot.items():
+ results["results"][s_key] = {"id": f"shot_{int(s_key):03d}", "video": s_vid, "from_unit": j["unit"]}
+ except Exception:
+ pass
results_path.write_text(json.dumps(results, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
print(f" -> {video or res}", flush=True)
if not video:
failed.append(key)
print(f"results: {results_path}")
+ try:
+ from src import clip_check
+
+ print(clip_check.summary(clip_check.check_jobs(str(jobs_path))))
+ except Exception:
+ pass
if failed:
sys.exit(f"{len(failed)}/{len(todo)} 个镜头没生成出视频:{', '.join(failed)}(详情见 results.json)")
diff --git a/rea_video/moments.py b/rea_video/moments.py
index a3ac4e9..a0f857a 100644
--- a/rea_video/moments.py
+++ b/rea_video/moments.py
@@ -1159,12 +1159,13 @@ def videomd(b: dict) -> list[str]:
+ (" | to_confirm: " + "; ".join(ex["doubts"]) if ex.get("doubts") else ""))
return L
if mo.get("status") == "done":
- return ["## " + T("特殊时刻", "Special moments"), "", T("- 看过了,没有找到特殊时刻", "- Looked: no special moments found")]
+ return ["## " + T("特殊时刻", "Special moments"), "", T("- 看过了,没有找到特殊时刻", "- Looked: no special moments found")] if mo.get("genre") == "magic" else []
+ if mo.get("genre") != "magic":
+ return []
L = ["## " + T("特殊时刻", "Special moments"), "",
T("- 还没有看图找:运行 `rea-video moments <本目录>`,按输出看图作答(开了 VLM 时 decompose 会自动做)",
- "- Not looked for yet: run `rea-video moments <this dir>` and answer from the images (decompose does it itself with a VLM)")]
- if mo.get("genre") == "magic":
- L.append(T("- 这是魔术视频:建议找出每段魔术的变化瞬间", "- This is a magic video: find each trick's reveal"))
+ "- Not looked for yet: run `rea-video moments <this dir>` and answer from the images (decompose does it itself with a VLM)"),
+ T("- 这是魔术视频:建议找出每段魔术的变化瞬间", "- This is a magic video: find each trick's reveal")]
hs = mo.get("hints") or []
if hs:
L.append(T("- 工具候选(只供参考,约一成是真的):", "- Tool hints (for reference, about one in ten is real): ")
diff --git a/rea_video/packaging.py b/rea_video/packaging.py
index 3b6e6ff..a1c08e0 100644
--- a/rea_video/packaging.py
+++ b/rea_video/packaging.py
@@ -1786,10 +1786,19 @@ def clean_region(stickers: list[dict], t0: float, t1: float, min_area: float = 0
def shot_layers(pack: dict, rec: dict, label: str) -> list[dict]:
"""花字 / sticker layers on one shot. Marks stickers on content bases that are probably part of the picture."""
+ from .classify import _same_words
+
t0, t1 = rec["start"], rec["end"]
+ said = shot_overlay_text(rec)
out = []
for c in pack.get("text_cues", []):
if c["kind"] == "huazi" and min(t1, c["t1"]) - max(t0, c["t0"]) > 0.1:
+ if c.get("part_of_picture") or (isinstance(said, list) and not any(_same_words(c["text"], o) for o in said)):
+ c["part_of_picture"] = True
+ st = rec.setdefault("base", {}).setdefault("scene_text", [])
+ if c["text"] and c["text"] not in st:
+ st.append(c["text"])
+ continue
out.append({"kind": "huazi", "source": "code_or_editor", "band": c.get("band"), "texts": [c["text"]], "ref": c["id"]})
for s in pack.get("stickers", []):
ov = min(t1, s["t1"]) - max(t0, s["t0"])
diff --git a/rea_video/performance.py b/rea_video/performance.py
index 47428ae..151af63 100644
--- a/rea_video/performance.py
+++ b/rea_video/performance.py
@@ -22,7 +22,7 @@ _INTENSITY_ALIASES = {"轻": "low", "弱": "low", "小": "low", "1": "low", "2":
ACTING_LABELS = ("live_action", "ai_video", "avatar", "cg_3d", "anim_2d", "stop_motion", "film_footage")
# shared by the VLM prompt and the review instructions so both readers answer the same question
-GUIDE = """画面里有人物、动物、卡通角色或数字人在表演(脸或肢体看得清)时填 performance,否则写 null(空镜、商品特写、只有手、远景看不清脸):
+GUIDE = """画面里有人物、动物、卡通角色或数字人在表演(脸或肢体有情绪/神态演进)时填 performance,否则写 null(空镜、商品特写、只有手、远景看不清脸,或纯静态摆拍造型仅靠大风吹发/镜头推拉营造氛围且面部无表情变化的视觉展示镜头也填 null,避免给静态眼神填 low 压制画面物理动态):
- who:谁在演(和角色表里的编号或称呼一致)
- emotion:一个主情绪词(平静 / 开心 / 期待 / 好奇 / 惊讶 / 委屈 / 生气 / 紧张 / 得意 / 无奈 …);一个镜头只写一个主情绪
- intensity:low|mid|high,按看到的幅度写;多数口播、带货是 low 或 mid
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 4d7bf07..56bc6bb 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -63,8 +63,10 @@ def vlm_units(records: list[dict], max_calls: int) -> list[list[dict]]:
# modules that only run in finalize(): a change there needs no new decode. Everything else measures the video.
-_FINALIZE_ONLY = {"classify.py", "report.py", "plan.py", "production.py", "entities.py", "narrative.py", "review.py", "cli.py",
- "evaluate.py", "remake.py", "memory.py", "i18n.py", "visual.py", "readings.py", "__init__.py"}
+_FINALIZE_ONLY = {"classify.py", "report.py", "plan.py", "production.py", "generation.py", "playbook.py",
+ "entities.py", "narrative.py", "review.py", "cli.py", "cli_en.py", "evaluate.py",
+ "remake.py", "remake_qa.py", "drive.py", "code_remake.py", "clean_paths.py", "videomd.py", "pdf.py",
+ "memory.py", "i18n.py", "visual.py", "readings.py", "__init__.py"}
_DECODE_FP: str | None = None
@@ -1049,6 +1051,13 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:
from .aspects.base import PHOTOGRAPHIC
from .aspects.grade import measure_frames
+ from .generation import load_intent
+
+ disk_intent = load_intent(out)
+ if disk_intent.get("mode") != "match" or disk_intent.get("model") or disk_intent.get("swaps") or "intent" not in breakdown:
+ if not disk_intent.get("model") and (breakdown.get("intent") or {}).get("model"):
+ disk_intent["model"] = breakdown["intent"]["model"]
+ breakdown["intent"] = disk_intent
for rec in shot_records: # breakdowns made before the grade aspect existed: measure it from the saved frames
asp = rec.setdefault("aspects", {})
diff --git a/rea_video/plan.py b/rea_video/plan.py
index 8dcde27..952442f 100644
--- a/rea_video/plan.py
+++ b/rea_video/plan.py
@@ -28,7 +28,7 @@ LABEL_ROUTE = {
}
NOTE = LangDict({
"ai_video": "原片为 AI 生成:用视频模型重做;和哪些镜头一起生成、喂什么(参考原片、关键帧或首尾帧)按所选模型排,见复刻方案的生成单元",
- "live_action": "原片为实拍:按拍摄方案(景别/机位/打光)重新拍摄;没有拍摄条件时才用 AI 图生视频近似(以首帧为参考)",
+ "live_action": "原片为实拍:按拍摄方案(景别/机位/打光)重新拍摄(若想改用 AI 生成,运行 rea-video plan --mode ai)",
"avatar": "数字人口播:先克隆/合成配音,再用数字人模型由人像 + 音频驱动",
"cg_3d": "3D 渲染:可以用视频模型近似(见复刻方案的生成单元);需要精确多角度时走 3D 建模 + Blender 渲染",
"code_render": "代码渲染:让编程能力强的模型(如 Claude Opus 5.5 及以上、Gemini 4 系列)按节奏表、关键帧和版式写代码重建,可以参考 HyperFrames、Remotion 这类 HTML 视频框架;100% 可控,不需要视频模型",
@@ -40,7 +40,7 @@ NOTE = LangDict({
"film_footage": "影视片段:画面剪自已有的电影/电视剧/短剧,复刻要找到原片对应片段再剪(版权属于片方,商用要授权);不用原片时,按同样景别、机位和打光自己拍,或用 AI 做近似画面",
}, en={
"ai_video": "Source is AI-generated: remake it with a video model; which shots share a call and what it is fed (the source clip, keyframes or first / last frames) depend on the chosen model, see the generation units in the remake plan",
- "live_action": "Source is live action: reshoot per the shooting plan (shot size / camera setup / lighting); only fall back to AI image-to-video (first frame as reference) when a shoot is not possible",
+ "live_action": "Source is live action: reshoot per the shooting plan (shot size / camera setup / lighting); run rea-video plan --mode ai to remake with AI instead",
"avatar": "Digital-avatar talking head: clone or synthesize the voice first, then drive an avatar model from a portrait + the audio",
"cg_3d": "3D render: a video model gives an approximation (see the generation units); for precise multiple angles, model in 3D and render in Blender",
"code_render": "Code render: have a strong coding model (such as Claude Opus 5.5 or later, or the Gemini 4 series) rebuild it in code from the rhythm, key frames and layout, optionally on an HTML video framework such as HyperFrames or Remotion; 100% controllable, no video model needed",
@@ -115,13 +115,27 @@ def hailuo_bracket(shot: dict) -> str:
return HAILUO_MOVES[c]
if move and str(move).lower() in HAILUO_MOVES:
return HAILUO_MOVES[str(move).lower()]
- feat = (shot.get("features") or {}).get("camera")
+ feat_d = shot.get("features") or {}
+ traj = feat_d.get("camera_traj")
+ if traj == "push_in":
+ return "[Push in]"
+ if traj == "pull_out":
+ return "[Pull out]"
+ if traj == "pan_left":
+ return "[Pan left]"
+ if traj == "pan_right":
+ return "[Pan right]"
+ if traj == "tilt_up":
+ return "[Tilt up]"
+ if traj == "tilt_down":
+ return "[Tilt down]"
+ feat = feat_d.get("camera")
if feat == "handheld_like":
return "[Shake]"
if feat == "smooth_move":
return "[Tracking shot]"
if feat == "planar_zoom_pan":
- z = (shot.get("features") or {}).get("zoom_per_s", 0.0)
+ z = feat_d.get("zoom_per_s", 0.0)
return "[Push in]" if z > 0.01 else "[Pull out]" if z < -0.01 else "[Pan right]"
return "[Static shot]"
@@ -134,7 +148,20 @@ def camera_move_words(shot: dict) -> tuple[str, str]:
v = shot.get("review") or shot.get("vlm") or {}
move = cm.get("move") or (v.get("camera_move") if v.get("camera_move") not in (None, "", "固定", "static") else None)
if not move:
- feat = (shot.get("features") or {}).get("camera")
+ feat_d = shot.get("features") or {}
+ traj = feat_d.get("camera_traj")
+ traj_map = {
+ "push_in": (T("镜头推近", "camera push-in"), "camera push-in"),
+ "pull_out": (T("镜头拉远", "camera pull-out"), "camera pull-out"),
+ "pan_left": (T("镜头左摇/左移", "camera pan/truck left"), "camera pan/truck left"),
+ "pan_right": (T("镜头右摇/右移", "camera pan/truck right"), "camera pan/truck right"),
+ "tilt_up": (T("镜头上摇/上移", "camera tilt/pedestal up"), "camera tilt/pedestal up"),
+ "tilt_down": (T("镜头下摇/下移", "camera tilt/pedestal down"), "camera tilt/pedestal down"),
+ "handheld": (T("手持镜头", "handheld camera"), "handheld camera"),
+ }
+ if traj in traj_map:
+ return traj_map[traj]
+ feat = feat_d.get("camera")
if feat == "handheld_like":
return T("手持镜头", "handheld camera"), "handheld camera"
if feat == "smooth_move":
diff --git a/rea_video/playbook.py b/rea_video/playbook.py
index f76b429..d4cbfdc 100644
--- a/rea_video/playbook.py
+++ b/rea_video/playbook.py
@@ -18,13 +18,13 @@ from .i18n import LangDict, T, model_name
NAME_ZH = LangDict({
"talking_head": "人物口播", "desk": "桌拍 / 开箱 / 带货", "vlog": "vlog 随拍", "live_drama": "实拍剧情",
"ai_drama": "AI 剧情短片", "ai_product": "AI 商品广告", "ai_mv": "AI 音乐 MV", "avatar": "数字人口播",
- "ai_clip": "AI 短片段(萌宠 / 奇观 / 单场景)", "animation": "3D / 动画",
+ "ai_clip": "AI 视觉短片 / 主题混剪", "animation": "3D / 动画",
"film": "影视解说 / 混剪", "explainer": "动效科普 / 数据动画", "screen": "录屏教程 / 软件演示",
"slideshow": "图片推拉成片(图文 / 故事 / 推文)", "beat": "卡点混剪", "dance": "舞蹈 / 动作表演",
}, en={
"talking_head": "talking head", "desk": "tabletop / unboxing / product", "vlog": "vlog", "live_drama": "live-action skit",
"ai_drama": "AI story short", "ai_product": "AI product ad", "ai_mv": "AI music video", "avatar": "digital-avatar talking head",
- "ai_clip": "short AI clip (pets / spectacle / single scene)", "animation": "3D / animation",
+ "ai_clip": "AI visual short / montage", "animation": "3D / animation",
"film": "film commentary / film-clip montage", "explainer": "motion-graphics explainer", "screen": "screen tutorial / software demo",
"slideshow": "stills with pan and zoom (photo story)", "beat": "beat-synced montage", "dance": "dance / action performance",
})
@@ -194,7 +194,7 @@ def _material(b: dict, live: bool, refs: bool) -> str | None:
if k not in kinds and not (live and k in ("实拍视频素材", "live footage")):
kinds.append(k)
cast = entities.cast(b)
- who = [c.get("name") for c in cast.get("characters") or [] if c.get("name")]
+ recurring = [c.get("name") for c in cast.get("characters") or [] if c.get("name") and len(c.get("shots") or []) >= 2]
swaps = (b.get("intent") or {}).get("swaps") or []
out = []
if swaps: # the remake intent says what goes in; the source's own cast is not what needs a picture
@@ -205,12 +205,12 @@ def _material(b: dict, live: bool, refs: bool) -> str | None:
if bare:
out.append(T("只有文字描述(各给一张参考图会更稳,跨镜头不变样):{h}", "described in words only (an image each keeps them the same across shots): {h}",
h=T("、", ", ").join(re.split(r"[,,;;]", x)[0].strip() for x in bare)))
- who = []
+ recurring = []
if kinds:
out.append(T("画面里的真实素材({k})要拿到原文件,清单见「要准备的素材」", "the real material in the picture ({k}) needs the original files, listed under “What to prepare”",
k=T("、", ", ").join(kinds)))
- if who and refs:
- out.append(T("每个角色准备一张参考图,所有镜头都用同一张:{w}", "one reference image per character, the same one in every shot: {w}", w=T("、", ", ").join(who[:6])))
+ if recurring and refs:
+ out.append(T("跨多镜出场的角色各准备一张设定参考图锁住外观:{w}", "one reference image per recurring character to lock appearance across shots: {w}", w=T("、", ", ").join(recurring[:6])))
if s.get("references") and refs:
out.append(T("商品、Logo 等参考图见「复刻要准备的参考素材」", "product and logo references under “Reference material to prepare”"))
return (T("**备素材**:", "**Collect material**: ") + T(";", "; ").join(out)) if out else None
@@ -277,7 +277,11 @@ def _generate(b: dict) -> list[str]:
can_native = effective_native_audio(spec, plan.get("strategy") or "") if spec else True
native = ((b.get("sound_sources") or {}).get("voice") or {}).get("source") == "ai_video_native" and can_native
calls = plan.get("calls") or len(units)
- if plan.get("strategy") == "remix":
+ if plan.get("strategy") == "edit":
+ L.append(T("**AI 生成(动作锁定编辑)**:{c} 次生成(共 {s:.0f} 秒)。把擦掉字幕的原片当基准视频喂给模型,配极简增量编辑提示词(仅写要改的外观/属性,锁死原片切镜、运镜与动作姿态);基准视频在 `remake/refs/`",
+ "**Generate (motion-locked edit)**: {c} call{p} ({s:.0f} s). Feeds the subtitle-erased source clip as base video with a delta-only edit prompt (locking cuts, camera and poses while editing look/attributes); clips are in `remake/refs/`",
+ c=calls, p="" if calls == 1 else "s", s=secs))
+ elif plan.get("strategy") == "remix":
L.append(T("**AI 生成**:{c} 次生成(共 {s:.0f} 秒)。每次把原片对应的一段当参考视频喂给模型,模型照它的分镜和节奏出完这段的镜头,"
"提示词只写每个镜头换成什么;参考视频已擦掉字幕切好,在 `remake/refs/`",
"**Generate**: {c} call{p} ({s:.0f} s). Each call gets its stretch of the source as the reference video and the model follows "
@@ -524,6 +528,11 @@ def steps(b: dict, kind: str, also: str | None = None) -> list[str]:
def md(b: dict) -> list[str]:
"""The hands-on part of the remake section: the kind of video, then numbered steps built from this breakdown."""
+ if ((b.get("intent") or {}).get("mode") or "") == "shoot":
+ L = [T("当前按「真机实拍落地(--mode shoot)」规划:把原片画面翻译为现场机位与布光方案,按下面顺序执行。",
+ "Planned for a live camera shoot (--mode shoot): translating the source pictures into real-world camera setups and lighting."), ""]
+ L += [f"{i}. {x}" for i, x in enumerate(steps(b, "live_drama"), 1)]
+ return L + [""]
ks = kinds(b)
if not ks:
return []
diff --git a/rea_video/production.py b/rea_video/production.py
index 1065d3a..7a29ea5 100644
--- a/rea_video/production.py
+++ b/rea_video/production.py
@@ -275,10 +275,12 @@ def _style_line(shots: list[dict], aspect_ratio: str) -> str:
# ---------------------------------------------------------------- shooting setups
-def _setups(shots: list[dict], sig: dict, thr: float, b: dict) -> list[dict]:
+def _setups(shots: list[dict], sig: dict, thr: float, b: dict, shoot_all: bool = False) -> list[dict]:
+ from .aspects.base import PHOTOGRAPHIC
from .entities import cast as _cast
- filmed = [r for r in shots if r["base"]["label"] in SHOOT_LABELS]
+ pool = PHOTOGRAPHIC if shoot_all else SHOOT_LABELS
+ filmed = [r for r in shots if r["base"]["label"] in pool]
scenes: list[list[dict]] = []
named: list[dict] = []
# an image reader who named the scenes knows where each shot was filmed better than colour histograms do
@@ -348,10 +350,13 @@ def production_plan(b: dict, out: Path, engine: str = "minimax-h3") -> dict:
shots = b["shots"]
intent = gen_mod.load_intent(out)
- if not intent.get("model") and (b.get("intent") or {}).get("model"):
+ if (b.get("intent") or {}).get("mode") in ("ai", "shoot") and intent.get("mode") == "match":
+ intent = gen_mod.clean_intent({**intent, **b["intent"]})
+ elif not intent.get("model") and (b.get("intent") or {}).get("model"):
intent["model"] = b["intent"]["model"]
b["intent"] = intent
- gen_labels = tuple(ALL_GEN_LABELS if intent.get("generate") == "all" else GEN_LABELS)
+ shoot_mode = intent.get("mode") == "shoot" or intent.get("generate") == "none"
+ gen_labels = () if shoot_mode else tuple(ALL_GEN_LABELS if (intent.get("mode") == "ai" or intent.get("generate") == "all") else GEN_LABELS)
planner = Planner()
seg = planner.routing.get("segmentation", {}).get("defaults", {})
thr = float(seg.get("same_scene_distance", 0.5))
@@ -389,7 +394,9 @@ def production_plan(b: dict, out: Path, engine: str = "minimax-h3") -> dict:
if u:
u.setdefault("reused", []).append({"shot": again, "from": src})
plan: dict = {"model": (model or {}).get("id"), "model_name": model_name((model or {}).get("name")), "strategy": g["strategy"],
- "spec": g["spec"], "rules": g["rules"], "units": units, "intent": intent}
+ "video_ref": g.get("video_ref", "none"), "spec": g["spec"], "rules": g["rules"], "units": units,
+ "image_tasks": g.get("image_tasks", []), "discontinuous_montage": bool(g.get("discontinuous_montage")),
+ "intent": intent}
lim = g["spec"]
gen_shots = sum(len(u["shots"]) for u in units)
if units:
@@ -404,7 +411,7 @@ def production_plan(b: dict, out: Path, engine: str = "minimax-h3") -> dict:
plan["prompting"] = planner.prompting[model["id"]]
voice = ((b.get("audio") or {}).get("voice") or {}).get("present")
vsrc = ((b.get("sound_sources") or {}).get("voice") or {}).get("source")
- if lim.get("no_audio_with_ref_video") and g["strategy"] == "remix":
+ if lim.get("no_audio_with_ref_video") and g["strategy"] in ("remix", "edit"):
plan["audio_note"] = T("当前模型在传参考视频时不能同时开启原生音频:人声、音效和配乐全部单独准备后在后期混入(若需音画同出对白,可改选支持参考视频出声的模型或改走关键帧模式)",
"sending a reference video disables native audio on this model: prepare voice, sound effects and music separately and mix them in post")
elif lim["native_audio"]:
@@ -427,8 +434,8 @@ def production_plan(b: dict, out: Path, engine: str = "minimax-h3") -> dict:
prompts = gen_mod.load_prompts(out)
plan["prompts"] = {k: v for k, v in prompts.items() if any(u["id"] == k for u in units)}
plan["checks"] = gen_mod.checks(plan, intent, prompts, plan.get("prompting"), gen_s, root=out)
- plan["drive"] = dance.units(b)
- plan["shoot"] = _setups([r for r in shots if r["base"]["label"] not in gen_labels], sig, thr, b)
+ plan["drive"] = [] if shoot_mode else dance.units(b)
+ plan["shoot"] = _setups([r for r in shots if r["base"]["label"] not in gen_labels], sig, thr, b, shoot_all=shoot_mode)
code, cur = [], []
for r in shots + [None]:
if r is not None and r["base"]["label"] in CODE_LABELS:
diff --git a/rea_video/remake.py b/rea_video/remake.py
index c4ac0a1..f220bff 100644
--- a/rea_video/remake.py
+++ b/rea_video/remake.py
@@ -108,6 +108,12 @@ def motion_curve(frames) -> np.ndarray:
out.append(0.0 if prev is None else float(cv2.resize(np.abs(g - prev), (12, 8), interpolation=cv2.INTER_AREA).max()) / 255.0)
prev = g
c = np.array(out)
+ # Guard against boundary cut/fade-to-black spikes (e.g. a 1-frame black drop at shot end) dwarfing interior motion
+ if len(c) >= 8:
+ mid_cap = float(np.percentile(c[2:-2], 95)) * 1.5
+ if mid_cap > 0.01:
+ c[:2] = np.minimum(c[:2], mid_cap)
+ c[-2:] = np.minimum(c[-2:], mid_cap)
if len(c) >= 3:
c = np.array([c[max(0, i - 2):i + 1].max() for i in range(len(c))])
c = np.convolve(c, np.ones(3) / 3, mode="same")
@@ -195,29 +201,53 @@ def _warp_clip(src: Path, out: Path, path: list[int], size: tuple[int, int], fps
return out
-def fit_to_original(src: Path, out: Path, original: Path, first: int, frames: int, size: tuple[int, int], fps: float) -> str:
- """A generated clip into the original shot's frames: warped so its moves land where the original's do, else
- sped up or slowed down evenly. Returns how ("warped" / "even")."""
- try:
- ref = motion_curve(_frames_at(original, fps, WARP_W, first, frames, gray=True))
- gen = motion_curve(_frames_at(src, fps, WARP_W, gray=True))
- path = warp_map(ref[:frames], gen) if len(ref) >= frames - 1 else None
- if path:
- _warp_clip(src, out, path + [path[-1]] * (frames - len(path)), size, fps)
- return "warped"
- except (OSError, RuntimeError, subprocess.CalledProcessError, ValueError) as exc:
- LOG.warning("timing the clip to the original failed (%s); fitting it evenly", str(exc)[:120])
- _fit_clip(src, out, frames, size, fps)
- return "even"
+def fit_to_original(src: Path, out: Path, original: Path, first: int, frames: int, size: tuple[int, int], fps: float,
+ retime: str = "smooth", bookend: bool = True) -> str:
+ """A generated clip into the original shot's frames: `smooth` (default) resamples continuously without step=0
+ frozen frames; `warp` aligns discrete gesture peaks via dynamic time warping. When `bookend=False` (open-ended
+ first-frame or text generation padded by a model's minimum call duration), clips >1.35x longer than the shot are
+ trimmed at natural 1.0x speed instead of hyper-lapse fast-forwarding."""
+ if retime == "warp":
+ try:
+ ref = motion_curve(_frames_at(original, fps, WARP_W, first, frames, gray=True))
+ gen = motion_curve(_frames_at(src, fps, WARP_W, gray=True))
+ path = warp_map(ref[:frames], gen) if len(ref) >= frames - 1 else None
+ if path:
+ _warp_clip(src, out, path + [path[-1]] * (frames - len(path)), size, fps)
+ return "warped"
+ except (OSError, RuntimeError, subprocess.CalledProcessError, ValueError) as exc:
+ LOG.warning("timing the clip to the original failed (%s); fitting it evenly", str(exc)[:120])
+ return _fit_clip_mode(src, out, frames, size, fps, blend=(retime == "smooth"), bookend=bookend)
+
+
+def _fit_clip(src: Path, out: Path, frames: int, size: tuple[int, int], fps: float, blend: bool = False) -> Path:
+ _fit_clip_mode(src, out, frames, size, fps, blend=blend, bookend=True)
+ return out
-def _fit_clip(src: Path, out: Path, frames: int, size: tuple[int, int], fps: float) -> Path:
+def _fit_clip_mode(src: Path, out: Path, frames: int, size: tuple[int, int], fps: float,
+ blend: bool = False, bookend: bool = True) -> str:
w, h = size
- speed = fit_speed(_clip_seconds(src), frames / fps)
+ clip_s = _clip_seconds(src)
+ target_s = frames / fps
+ if not bookend and target_s > 0 and clip_s > target_s * 1.35:
+ speed, mode = 1.0, "trimmed"
+ elif blend and clip_s > 0 and target_s > clip_s:
+ # Smooth frame-blended resampling handles up to 1.65x slow-stretch cleanly, avoiding frozen tail clone frames
+ speed, mode = max(1.0 / 1.65, clip_s / target_s), "even"
+ else:
+ speed, mode = fit_speed(clip_s, target_s), "even"
tail, flags = _exact(fps, frames)
- vf = f"setpts=PTS/{speed:.4f},scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},{tail}"
- _ff(["-i", str(src), "-an", "-vf", vf, *flags, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(out)])
- return out
+ scale_crop = f"setpts=PTS/{speed:.4f},scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h}"
+ if blend:
+ smooth_tail = f"framerate=fps={fps}:interp_start=0:interp_end=255:scene=100,tpad=stop_mode=clone:stop_duration={frames / fps + 1:.3f}"
+ try:
+ _ff(["-i", str(src), "-an", "-vf", f"{scale_crop},{smooth_tail}", *flags, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(out)])
+ return mode
+ except subprocess.CalledProcessError:
+ pass
+ _ff(["-i", str(src), "-an", "-vf", f"{scale_crop},{tail}", *flags, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(out)])
+ return mode
def _original_segment(src: Path, out: Path, first: int, frames: int, size: tuple[int, int], fps: float) -> Path:
@@ -271,7 +301,7 @@ def overlay_cues(b: dict, spans: list[tuple[float, float]]) -> tuple[list[dict],
def unit_shots(b: dict, results: dict, udir: Path, size: tuple[int, int], fps: float,
- bounds: dict[int, tuple[int, int]] | None = None) -> dict:
+ bounds: dict[int, tuple[int, int]] | None = None, bdir: Path | None = None) -> dict:
"""Generation-unit clips (one call made several shots: results keyed "G2", or "G4-1", "G4-2" for the parts of a
long shot) -> one clip per shot. The parts are fitted to their lengths and joined; the shots are then cut at the
source's own cut points, because the model was given the source stretch and follows its timing.
@@ -290,10 +320,33 @@ def unit_shots(b: dict, results: dict, udir: Path, size: tuple[int, int], fps: f
got.sort(key=lambda v: v.get("part", 1))
if len(got) < int(got[0].get("parts") or 1) or not all(v.get("video") and Path(v["video"]).is_file() for v in got):
continue
+ shots_list = [i for i in (got[0].get("shots") or []) if i in by_index and i in bounds]
+ # Single-call multi-shot unit: slice at actual pixel hard cuts first so cuts never drift into neighbouring shots
+ if len(got) == 1 and len(shots_list) > 1:
+ from .integrations.run_remake import _split_multishot_unit
+
+ r_shots = [by_index[i] for i in shots_list]
+ split_map = _split_multishot_unit(Path(got[0]["video"]), shots_list, float(got[0].get("trim_to") or 0),
+ udir / f"{uid}_cuts", ref_shots=r_shots, bdir=bdir)
+ if len(split_map) == len(shots_list):
+ for s_key, s_vid in split_map.items():
+ out[s_key] = {"video": s_vid, "unit": uid}
+ continue
fitted = []
for v in got:
f = udir / f"{uid}_p{v.get('part', 1)}.mp4"
- _fit_clip(Path(v["video"]), f, max(1, int(round(float(v["trim_to"]) * fps))), size, fps)
+ trim_s = float(v["trim_to"])
+ target_frames = max(1, int(round(trim_s * fps)))
+ src_p = Path(v["video"])
+ if len(shots_list) > 1 and _clip_seconds(src_p) >= trim_s - 0.05:
+ # Trim tail padding instead of speeding up the entire multi-shot clip
+ tail, flags = _exact(fps, target_frames)
+ w, h = size
+ _ff(["-i", str(src_p), "-t", f"{trim_s:.4f}", "-an",
+ "-vf", f"scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},{tail}",
+ *flags, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(f)])
+ else:
+ _fit_clip(src_p, f, target_frames, size, fps)
fitted.append(f)
whole = fitted[0]
if len(fitted) > 1:
@@ -314,18 +367,21 @@ def unit_shots(b: dict, results: dict, udir: Path, size: tuple[int, int], fps: f
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: Path | None = None, extra: dict | None = None, retime: str = "smooth") -> 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 {}
+ raw_jobs = read_json(jobs_path)["jobs"] if jobs_path.is_file() else []
+ jobs = {s: j for j in raw_jobs for s in (j.get("shots") or [j["shot"]])}
results = read_json(results_path).get("results", {}) if results_path.is_file() else {}
out_dir = out_dir or results_path.parent
seg_dir = out_dir / "segments"
seg_dir.mkdir(parents=True, exist_ok=True)
src = Path(b["source"]["path"])
+ if not src.is_file() and not src.is_absolute() and (bdir / src).is_file():
+ src = bdir / src
w, h = b["source"]["width"], b["source"]["height"]
if b["source"].get("rotation") in (90, 270):
w, h = h, w
@@ -334,8 +390,8 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = No
results = {**results, **{str(k): v for k, v in (extra or {}).items()}}
# unit clips (one call, several shots) become per-shot clips; a shot's own clip, given later, still wins
bounds = frame_bounds(b["shots"], fps)
- results = {**unit_shots(b, results, seg_dir / "units", (w, h), fps, bounds),
- **{k: v for k, v in results.items() if not (isinstance(v, dict) and v.get("unit"))}}
+ results = {**unit_shots(b, results, seg_dir / "units", (w, h), fps, bounds, bdir=bdir),
+ **{k: v for k, v in results.items() if not (isinstance(v, dict) and (v.get("unit") or v.get("from_unit")))}}
parts, legend = [], []
timing: dict[str, str] = {} # generated shots: warped onto the original's moves, or fitted evenly
for sh in b["shots"]:
@@ -345,7 +401,8 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = No
res = results.get(str(sh["index"])) or {}
job = jobs.get(sh["index"], {})
if res.get("video") and Path(res["video"]).is_file():
- how = fit_to_original(Path(res["video"]), seg, src, first, n, (w, h), fps)
+ is_bookend = bool(res.get("bookend") if "bookend" in res else job.get("bookend", not bool(job or res.get("unit") or res.get("from_unit"))))
+ how = fit_to_original(Path(res["video"]), seg, src, first, n, (w, h), fps, retime=retime, bookend=is_bookend)
legend.append((sh["index"], "generated"))
timing[str(sh["index"])] = how
elif code_video and sh["base"]["label"] == "code_render" and Path(code_video).is_file():
@@ -400,8 +457,18 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = No
except subprocess.CalledProcessError:
if not with_text:
raise
+ qa_summary: dict | None = None
+ if any(how == "generated" for _, how in legend):
+ try:
+ from .remake_qa import evaluate_remake
+
+ qa_res = evaluate_remake({**b, "source": {**b["source"], "path": str(src)}}, final, out_dir=out_dir, legend=legend, replaced_only=True)
+ if qa_res.get("evaluated_shots"):
+ qa_summary = {k: qa_res.get(k) for k in ("evaluated_shots", "score", "camera_score", "motion_score", "layout_score", "smoothness", "issues")}
+ except Exception as exc: # noqa: BLE001 QA diagnostics must never abort assembly
+ LOG.warning("remake QA evaluation failed: %s", str(exc)[:120])
log = {"legend": legend, "remake": str(final), "compare": str(compare), **({"timing": timing} if timing else {}),
- **({"overlays": overlay_log} if overlays else {})}
+ **({"overlays": overlay_log} if overlays else {}), **({"qa": qa_summary} if qa_summary else {})}
(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)
@@ -560,8 +627,15 @@ def remake(out: Path, code: bool = False, overlays: bool = True) -> dict:
T("| 镜头 | 时间 | 画面类型 | 现在 |", "| Shot | Time | Picture | Now |"), "|---|---|---|---|"]
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']]} |")
+ qa_file = rdir / "qa.json"
+ if log.get("qa") and qa_file.is_file():
+ from .remake_qa import qa_markdown
+
+ L += qa_markdown(read_json(qa_file))
(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})
+ write_json(rdir / "status.json", {"replaced_share": round(done / total, 3), "shots": rows,
+ **({"qa": log["qa"]} if log.get("qa") else {})})
res.update({"remake": log["remake"], "compare": log["compare"], "status": str(rdir / "status.md"),
- "replaced_share": round(done / total, 3), "to_do": todo})
+ "replaced_share": round(done / total, 3), "to_do": todo,
+ **({"qa": log["qa"]} if log.get("qa") else {})})
return res
diff --git a/rea_video/remake_qa.py b/rea_video/remake_qa.py
new file mode 100644
index 0000000..8871210
--- /dev/null
+++ b/rea_video/remake_qa.py
@@ -0,0 +1,241 @@
+"""Generative remake fidelity QA: per-shot camera trajectory, subject pose dynamics, framing layout and smoothness.
+
+`layers.compare()` scores flat code-rendered graphics by foreground colour masks. For generated / filmed / 3D shots
+where characters, colours or outfits intentionally change (`swaps`), pixel colour diff is meaningless while motion and
+framing drift are critical. This module measures four appearance-invariant axes per replaced shot:
+ 1. smoothness — absence of frozen duplicate frames (`step=0` warp stutter) when the source shot is moving
+ 2. camera_score — agreement of 3D-parallax-aware `camera_traj` (catches inverted push-in vs pull-out or lost pans)
+ 3. motion_score — agreement of global-motion-compensated `pose_change` & flow energy (catches hallucinated turns on
+ anchored shots or frozen stills on active action shots)
+ 4. layout_score — coarse gradient-envelope cosine similarity on start/end frames (invariant to colour/identity swaps,
+ sensitive to framing collapse such as wide profile -> centred close-up)
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import cv2
+import numpy as np
+
+from .features import global_motion, kinematics_summary, motion_summary
+from .i18n import T
+from .media import iter_frames, video_info
+from .util import write_json
+
+QA_W = 160
+
+_OPPOSITE_TRAJ = {
+ frozenset(("push_in", "pull_out")),
+ frozenset(("pan_left", "pan_right")),
+ frozenset(("tilt_up", "tilt_down")),
+}
+
+
+def _decode_by_shots(video_path: str | Path, shots: list[dict], width: int = QA_W) -> tuple[dict[int, list[np.ndarray]], dict[int, list[float]], float]:
+ info = video_info(str(video_path))
+ fps = float(info.fps) if info.fps and 0 < info.fps <= 60 else 30.0
+ ordered = sorted(shots, key=lambda s: float(s["start"]))
+ frames_by_shot: dict[int, list[np.ndarray]] = {int(s["index"]): [] for s in ordered}
+ times_by_shot: dict[int, list[float]] = {int(s["index"]): [] for s in ordered}
+ if not ordered:
+ return frames_by_shot, times_by_shot, fps
+ margin = 0.6 / fps # stay strictly inside shot boundaries so VFR / codec rounding never samples adjacent shots
+ k = 0
+ for fi, bgr in enumerate(iter_frames(str(video_path), info, width, fps=fps)):
+ t = fi / fps
+ while k < len(ordered) and t >= float(ordered[k]["end"]) - margin:
+ k += 1
+ if k >= len(ordered):
+ break
+ sh = ordered[k]
+ if t >= float(sh["start"]) + margin:
+ idx = int(sh["index"])
+ frames_by_shot[idx].append(bgr.copy())
+ times_by_shot[idx].append(t)
+ return frames_by_shot, times_by_shot, fps
+
+
+def _shot_kinematics(frames: list[np.ndarray], times: list[float], fps: float) -> dict:
+ if len(frames) < 2:
+ return {"frozen_ratio": 0.0, "flow_p90": 0.0, "camera_traj": "static", "net_zoom_pct": 0.0,
+ "pose_change": 0.0, "motion_regime": "near_static"}
+ trim = 1 if len(frames) > 8 else 0
+ fr = frames[trim:len(frames) - trim] if trim else frames
+ ts = times[trim:len(times) - trim] if trim else times
+ if len(fr) < 2:
+ fr, ts = frames, times
+ grays = [cv2.cvtColor(f, cv2.COLOR_BGR2GRAY) for f in fr]
+ mads = [float(cv2.absdiff(grays[i], grays[i - 1]).mean()) for i in range(1, len(grays))]
+ frozen_ratio = float(np.mean([m < 0.15 for m in mads])) if mads else 0.0
+ step_idx = np.unique(np.linspace(1, len(grays) - 1, num=min(16, len(grays) - 1)).round().astype(int))
+ mot = []
+ for i in step_idx:
+ gm = global_motion(grays[i - 1], grays[i])
+ if gm is not None:
+ mot.append(gm)
+ ms = motion_summary(mot, fps)
+ keep_idx = np.unique(np.linspace(0, len(fr) - 1, num=min(12, len(fr))).round().astype(int))
+ sub_fr = [fr[i] for i in keep_idx]
+ sub_ts = [ts[i] for i in keep_idx]
+ kin = kinematics_summary(sub_fr, sub_ts, ms)
+ return {
+ "frozen_ratio": round(frozen_ratio, 3),
+ "flow_p90": round(float(ms.get("flow_p90") or 0.0), 3),
+ **kin,
+ }
+
+
+def _coarse_layout_vec(bgr: np.ndarray) -> np.ndarray:
+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY).astype(np.float32)
+ h, w = gray.shape
+ gh = max(16, int(round(24 * h / max(1, w))))
+ small = cv2.resize(cv2.GaussianBlur(gray, (0, 0), max(1.5, w / 40.0)), (24, gh), interpolation=cv2.INTER_AREA)
+ gx = np.abs(cv2.Sobel(small, cv2.CV_32F, 1, 0, ksize=3)).ravel()
+ gy = np.abs(cv2.Sobel(small, cv2.CV_32F, 0, 1, ksize=3)).ravel()
+ v = np.concatenate([gx, gy])
+ n = float(np.linalg.norm(v))
+ return v / n if n > 1e-5 else np.zeros_like(v)
+
+
+def _layout_similarity(src_frames: list[np.ndarray], rem_frames: list[np.ndarray]) -> float:
+ if not src_frames or not rem_frames:
+ return 1.0
+ pairs = [(src_frames[0], rem_frames[0])]
+ if len(src_frames) >= 3 and len(rem_frames) >= 3:
+ pairs.append((src_frames[-1], rem_frames[-1]))
+ sims = []
+ for a, b in pairs:
+ va = _coarse_layout_vec(a)
+ vb = _coarse_layout_vec(cv2.resize(b, (a.shape[1], a.shape[0]), interpolation=cv2.INTER_AREA))
+ if va.any() and vb.any():
+ sims.append(float(np.clip(np.dot(va, vb), 0.0, 1.0)))
+ return round(float(np.mean(sims)), 3) if sims else 1.0
+
+
+def evaluate_remake(breakdown: dict, remake_video: str | Path, out_dir: Path | None = None,
+ legend: list[tuple] | None = None, replaced_only: bool = True) -> dict:
+ """Compare a remake video shot-by-shot against the source breakdown on camera, pose kinematics, framing and smoothness."""
+ src_path = Path(breakdown["source"]["path"])
+ rem_path = Path(remake_video)
+ if not src_path.is_file() or not rem_path.is_file():
+ return {"ok": False, "reason": "missing_video", "shots": []}
+ how_map = {int(i): h for i, h in (legend or [])}
+ eval_shots = [s for s in breakdown.get("shots") or []
+ if not (replaced_only and how_map and how_map.get(int(s["index"])) == "original")]
+ if not eval_shots:
+ return {"ok": True, "evaluated_shots": 0, "score": None, "shots": [], "issues": []}
+
+ src_fr, src_ts, src_fps = _decode_by_shots(src_path, eval_shots)
+ rem_fr, rem_ts, rem_fps = _decode_by_shots(rem_path, eval_shots)
+ rows: list[dict] = []
+ issues: list[str] = []
+ for sh in eval_shots:
+ idx = int(sh["index"])
+ sf, st = src_fr.get(idx) or [], src_ts.get(idx) or []
+ rf, rt = rem_fr.get(idx) or [], rem_ts.get(idx) or []
+ if len(sf) < 2 or len(rf) < 2:
+ continue
+ sk = _shot_kinematics(sf, st, src_fps)
+ rk = _shot_kinematics(rf, rt, rem_fps)
+ shot_issues: list[str] = []
+
+ # 1. Smoothness (freeze-frame check)
+ if sk["frozen_ratio"] < 0.08 and rk["frozen_ratio"] > 0.18 and sk["motion_regime"] != "near_static":
+ smooth = float(np.clip(1.0 - (rk["frozen_ratio"] - 0.10) * 2.0, 0.0, 1.0))
+ shot_issues.append(T("冻结重复帧偏多({r:.0%})", "excess frozen duplicate frames ({r:.0%})", r=rk["frozen_ratio"]))
+ else:
+ smooth = 1.0
+
+ # 2. Camera trajectory agreement
+ s_tr, r_tr = sk["camera_traj"], rk["camera_traj"]
+ if s_tr == r_tr:
+ cam_sc = 1.0
+ elif frozenset((s_tr, r_tr)) in _OPPOSITE_TRAJ:
+ cam_sc = 0.0
+ shot_issues.append(T("运镜方向相反(原片 {a},成片 {b})", "opposite camera move (source {a}, remake {b})", a=s_tr, b=r_tr))
+ elif "static" in (s_tr, r_tr):
+ strong = abs(sk["net_zoom_pct"]) >= 4.0 or abs(rk["net_zoom_pct"]) >= 4.0 or s_tr not in ("static", "handheld") or r_tr not in ("static", "handheld")
+ cam_sc = 0.45 if strong else 0.75
+ if strong:
+ shot_issues.append(T("运镜不一致(原片 {a},成片 {b})", "camera move mismatch (source {a}, remake {b})", a=s_tr, b=r_tr))
+ else:
+ cam_sc = 0.65
+
+ # 3. Subject pose & motion-energy fidelity
+ sp, rp = sk["pose_change"], rk["pose_change"]
+ if sk["motion_regime"] in ("anchored_pose", "camera_only", "near_static") and sp < 0.25 and rp >= sp + 0.20:
+ mot_sc = float(np.clip(1.0 - 2.0 * (rp - sp), 0.1, 0.65))
+ shot_issues.append(T("主体姿态大幅偏离(原片稳姿 {a:.2f},成片转身/位移 {b:.2f})",
+ "unwanted pose/orientation jump (source anchored {a:.2f}, remake {b:.2f})", a=sp, b=rp))
+ elif sk["motion_regime"] == "articulated_action" and sp >= 0.30 and rp < 0.45 * sp:
+ mot_sc = 0.35
+ shot_issues.append(T("主体动作幅度不足(原片 {a:.2f},成片 {b:.2f})",
+ "under-animated subject action (source {a:.2f}, remake {b:.2f})", a=sp, b=rp))
+ else:
+ mot_sc = float(np.clip(1.0 - abs(rp - sp) * 1.1, 0.4, 1.0))
+ if sk["flow_p90"] > 0.65 and rk["flow_p90"] < 0.25 * sk["flow_p90"]:
+ mot_sc = min(mot_sc, 0.45)
+ shot_issues.append(T("物理动态偏弱(风动/粒子/运动量不足)", "weak secondary motion energy"))
+
+ # 4. Appearance-invariant framing layout similarity
+ lay_sc = _layout_similarity(sf, rf)
+ if lay_sc < 0.52:
+ shot_issues.append(T("构图景别或主体朝向偏移(轮廓布局相似度 {s:.2f})",
+ "framing or silhouette layout drift (similarity {s:.2f})", s=lay_sc))
+
+ total = round(0.30 * cam_sc + 0.35 * mot_sc + 0.25 * lay_sc + 0.10 * smooth, 3)
+ for msg in shot_issues:
+ issues.append(f"#{idx}: {msg}")
+ rows.append({
+ "shot": idx,
+ "start": sh["start"],
+ "end": sh["end"],
+ "score": total,
+ "camera_score": round(cam_sc, 3),
+ "motion_score": round(mot_sc, 3),
+ "layout_score": lay_sc,
+ "smoothness": round(smooth, 3),
+ "source": {"camera_traj": s_tr, "net_zoom_pct": sk["net_zoom_pct"], "motion_regime": sk["motion_regime"],
+ "pose_change": sp, "frozen_ratio": sk["frozen_ratio"]},
+ "remake": {"camera_traj": r_tr, "net_zoom_pct": rk["net_zoom_pct"], "motion_regime": rk["motion_regime"],
+ "pose_change": rp, "frozen_ratio": rk["frozen_ratio"]},
+ "issues": shot_issues,
+ })
+
+ mean_sc = round(float(np.mean([r["score"] for r in rows])), 3) if rows else None
+ res = {
+ "ok": True,
+ "evaluated_shots": len(rows),
+ "score": mean_sc,
+ "camera_score": round(float(np.mean([r["camera_score"] for r in rows])), 3) if rows else None,
+ "motion_score": round(float(np.mean([r["motion_score"] for r in rows])), 3) if rows else None,
+ "layout_score": round(float(np.mean([r["layout_score"] for r in rows])), 3) if rows else None,
+ "smoothness": round(float(np.mean([r["smoothness"] for r in rows])), 3) if rows else None,
+ "issues": issues,
+ "shots": rows,
+ }
+ if out_dir is not None:
+ Path(out_dir).mkdir(parents=True, exist_ok=True)
+ write_json(Path(out_dir) / "qa.json", res)
+ return res
+
+
+def qa_markdown(qa: dict) -> list[str]:
+ """Markdown section summarizing per-shot remake fidelity for `remake/status.md`."""
+ rows = qa.get("shots") or []
+ if not rows:
+ return []
+ L = ["", T("## 还原度质检(运镜 · 姿态 · 构图 · 流畅度)", "## Fidelity QA (camera · pose · layout · smoothness)"), "",
+ T("- 综合得分:**{s:.0%}**(运镜 {c:.0%} · 姿态动态 {m:.0%} · 构图轮廓 {l:.0%} · 流畅度 {f:.0%})",
+ "- Overall fidelity: **{s:.0%}** (camera {c:.0%} · pose/motion {m:.0%} · framing layout {l:.0%} · smoothness {f:.0%})",
+ s=qa.get("score") or 0, c=qa.get("camera_score") or 0, m=qa.get("motion_score") or 0,
+ l=qa.get("layout_score") or 0, f=qa.get("smoothness") or 0), ""]
+ L += [T("| 镜头 | 得分 | 原片运镜 / 姿态 | 成片运镜 / 姿态 | 构图相似 | 诊断 |",
+ "| Shot | Score | Source cam / pose | Remake cam / pose | Layout | Diagnosis |"),
+ "|---|---|---|---|---|---|"]
+ for r in rows:
+ s_info = f"`{r['source']['camera_traj']}` / `{r['source']['motion_regime']}` ({r['source']['pose_change']:.2f})"
+ r_info = f"`{r['remake']['camera_traj']}` / `{r['remake']['motion_regime']}` ({r['remake']['pose_change']:.2f})"
+ diag = ";".join(r["issues"]) if r.get("issues") else T("通过", "OK")
+ L.append(f"| #{r['shot']} | {r['score']:.0%} | {s_info} | {r_info} | {r['layout_score']:.2f} | {diag} |")
+ return L
diff --git a/rea_video/report.py b/rea_video/report.py
index dd22923..5c2ca8f 100644
--- a/rea_video/report.py
+++ b/rea_video/report.py
@@ -354,24 +354,42 @@ def _picture_how(b: dict) -> str:
def _layers_md(b: dict) -> list[str]:
- """The mental model first: every short video is a picture, things laid on top of it, and sound."""
+ """Concrete production pipeline summary for this specific video (no generic textbook filler)."""
s = b["summary"]
+ plan = b.get("production_plan") or {}
n_by: dict[str, int] = {}
for r in b["shots"]:
n_by[r["base"]["label_zh"]] = n_by.get(r["base"]["label_zh"], 0) + 1
- pic = join(T("{l} {n} 镜", "{l} {n} shot{s}", l=m["label_zh"], n=n_by.get(m["label_zh"], 0), s="" if n_by.get(m["label_zh"]) == 1 else "s")
+ pic = join(T("{l} {n} 镜({p})", "{l} {n} shot{s} ({p})", l=m["label_zh"], n=n_by.get(m["label_zh"], 0),
+ s="" if n_by.get(m["label_zh"]) == 1 else "s", p=_pct(m["ratio"]))
for m in s["production_mix"] if n_by.get(m["label_zh"]))
+ pic_how = _picture_how(b) or s.get("production") or "—"
+ if plan.get("strategy") and plan.get("units"):
+ from .generation import strategy_name
+
+ img_n = len(plan.get("image_tasks") or [])
+ pic_how += T("(模态:{m}", " (modality: {m}", m=strategy_name(plan["strategy"])) + (
+ T(";含 {n} 张前置图片方案)", "; {n} upstream frame prompts)", n=img_n) if img_n else T(")", ")"))
+ rm = s.get("real_material") or {}
+ if rm.get("shots"):
+ pic += T(";含真实素材 {n} 镜({r:.0%})", "; includes real material in {n} shot{s} ({r:.0%})",
+ n=len(rm["shots"]), s="" if len(rm["shots"]) == 1 else "s", r=rm["ratio"])
+ pack = b.get("packaging") or {}
+ pack_lines = [x for x in (pack.get("summary_zh") or []) if x]
over = _overlay_kinds(b)
snd, snd_how = _sound_brief(b)
- rows = [[T("**画面**(底层)", "**Picture** (base)"), pic, _picture_how(b) or s.get("production") or "—", T("「自己复刻」", "“Remake it yourself”")],
- [T("**包装**(叠在画面上)", "**Packaging** (on top)"), join(over) or T("没有", "none"),
- T("剪辑软件里加:字幕、花字、贴纸照时间轴摆", "add in the editor: subtitles, styled text and stickers by the timeline") if over else "—",
- T("「剪辑包装层」", "“Packaging layer”")],
- [T("**声音**", "**Sound**"), snd, snd_how, T("「声音」", "“Sound”")]]
- L = ["", T("## 一眼看懂:画面、包装、声音三层", "## At a glance: picture, packaging, sound"), "",
- T("短视频都可以拆成三层:底下是画面本身,上面叠字幕、花字、贴纸,再配上声音。复刻时一层一层做。",
- "Any short video splits into three layers: the picture, what is laid on top of it (subtitles, styled text, stickers), and the sound. Remake it one layer at a time.")]
- L += _table([T("层", "Layer"), T("这条视频里是什么", "In this video"), T("怎么做", "How to make it"), T("细节", "Detail")], rows)
+ L = ["", T("## 制作链路速览", "## Production pipeline at a glance"), ""]
+ rows = [[T("**底层画面**", "**Base picture**"), pic, pic_how]]
+ if pack_lines or over:
+ p_what = semi().join(pack_lines) if pack_lines else join(over)
+ files = (pack.get("files") or {})
+ f_hint = T("导出 `{f}` 对齐时间轴", "export `{f}` for timeline alignment",
+ f=files.get("srt") or files.get("ass") or "packaging/timeline.json")
+ rows.append([T("**后期包装**", "**Packaging**"), p_what, f_hint])
+ else:
+ rows.append([T("**后期包装**", "**Packaging**"), T("无后期字幕、花字或贴纸(纯画面呈现)", "no overlaid subtitles, styled text or stickers"), T("无需包装层", "none needed")])
+ rows.append([T("**声音配置**", "**Sound**"), snd, snd_how])
+ L += _table([T("环节", "Stage"), T("本片实际构成", "What this video uses"), T("复刻要点", "Remake approach")], rows)
return L
@@ -592,12 +610,19 @@ def _content_md(b: dict, user: bool = False) -> list[str]:
lines = entities.script(b)
L = ["", T("## 内容与结构", "## Content and structure"), ""]
if not w and not lines:
+ has_pack = bool(_overlay_kinds(b))
if narrative.beats(b):
L.append(T("- 下面的叙事线来自逐镜看图;台词没有单独整理,字幕原文见「剪辑包装层」",
- "- The narrative line below comes from reading each shot; the lines were not transcribed separately, subtitle text is under “Packaging layer”"))
+ "- The narrative line below comes from reading each shot; the lines were not transcribed separately, subtitle text is under “Packaging layer”")
+ if has_pack else
+ T("- 下面的叙事线来自逐镜看图;全片无口播台词与后期字幕",
+ "- The narrative line below comes from reading each shot; no spoken dialogue or overlaid subtitles"))
else:
L.append(T("- 这次没有分析整片内容(要开 AI 看图);字幕原文见「剪辑包装层」",
- "- The whole video's content was not analysed this time (needs AI image reading); subtitle text is under “Packaging layer”"))
+ "- The whole video's content was not analysed this time (needs AI image reading); subtitle text is under “Packaging layer”")
+ if has_pack else
+ T("- 这次没有分析整片内容(要开 AI 看图)",
+ "- The whole video's content was not analysed this time (needs AI image reading)"))
return L + _narrative_md(b)
if w.get("summary") and not user:
L.append(T("- 概括:{s}", "- Summary: {s}", s=w["summary"]))
@@ -650,10 +675,24 @@ def _narrative_md(b: dict) -> list[str]:
def _cast_md(b: dict) -> list[str]:
c = entities.cast(b)
+ has_reader = bool(((b.get("analysis") or {}).get("vlm") or {}).get("used") or (b.get("analysis") or {}).get("review"))
+ non_char_only = bool(b.get("shots")) and all(r["base"]["label"] in ("code_render", "screen_capture") for r in b.get("shots", []))
+ if has_reader and non_char_only and not (c["characters"] or c["scenes"] or c["props"] or c.get("style")):
+ return []
L = ["", T("## 角色、场景与道具", "## Cast, scenes and props"), ""]
+ if c.get("style"):
+ L.append(T("- **视觉风格**:{s}", "- **Visual style**: {s}", s=c["style"]))
+ L.append("")
if c["characters"]:
L += _table([T("编号", "Id"), T("称呼", "Name"), T("类型", "Kind"), T("外观", "Look"), T("作用", "Role"), T("声音", "Voice"), T("出场", "Shots")],
[[ch["id"], ch["name"], entities.KIND_ZH.get(ch["kind"], ch["kind"]), ch["look"], ch["role"], ch["voice"], _shots_str(ch["shots"])] for ch in c["characters"]])
+ rec_names = [ch["name"] for ch in c["characters"] if ch.get("name") and len(ch.get("shots") or []) >= 2]
+ if len(c["characters"]) >= 2 and not rec_names:
+ L += ["", T("- 角色关系:各镜头为独立单次角色(合集/混剪结构),复刻时按镜独立出图即可,无需跨镜头锁同一张角色设定图",
+ "- Cast structure: each shot features a distinct one-off character (anthology / montage); generate frames independently per shot without cross-shot face locking")]
+ elif rec_names:
+ L += ["", T("- 角色一致性:{n} 跨多个镜头出场,复刻时需先固定基准图并在后续镜头用图生图/参考图锁住外观",
+ "- Character consistency: {n} appear across multiple shots; lock an anchor image first and feed it as reference in later shots", n=join(rec_names[:5]))]
else:
L.append(T("- 这次没有整理出角色(要开 AI 看图)",
"- No cast extracted this time (needs AI image reading)")
@@ -834,15 +873,7 @@ def _audio_md(b: dict) -> list[str]:
def _visual_md(b: dict, user: bool = False) -> list[str]:
- style = entities.cast(b).get("style")
- L = aspects.report_md(b, user=user)
- if not L and not style:
- return []
- if not L:
- L = ["", T("## 拍法与打光", "## Camera and lighting") if user else T("## 拍法、打光与剪辑", "## Camera, lighting and editing"), ""]
- if style:
- L.insert(3, T("- 视觉风格:{s}", "- Visual style: {s}", s=style))
- return L
+ return aspects.report_md(b, user=user)
def packaging_md(b: dict) -> list[str]:
@@ -852,12 +883,11 @@ def packaging_md(b: dict) -> list[str]:
return []
cues = [c for c in pack.get("text_cues", []) if c["kind"] != "scene" and not c.get("part_of_picture")]
stickers = [st for st in pack.get("stickers", []) if not st.get("in_picture")]
+ if not cues and not stickers and not pack.get("vlm_text_effects"):
+ return []
L = ["", T("## 剪辑包装层(字幕 / 花字 / 贴纸 / 音效卡点)", "## Packaging layer (subtitles / styled text / stickers / sound-effect hits)"), ""]
for line in pack.get("summary_zh") or []:
L.append(f"- {line}")
- if not cues and not stickers:
- L.append(T("- 没有检出后期叠加的文字或贴纸", "- No overlaid text or stickers detected")
- + (T("(未开 OCR,文字层没有分析)", " (OCR off, text layer not analysed)") if not (b.get("analysis") or {}).get("ocr", True) else ""))
if cues:
sfx_by_ref: dict[str, list[str]] = {}
for e in [x for x in (b.get("audio_plan") or {}).get("sfx_merged", []) if not x.get("in_scene")]: # the picture's own sound is not a cue
@@ -903,10 +933,16 @@ def packaging_md(b: dict) -> list[str]:
for e in fx:
L.append(f"- {e.get('t', '')}s {e.get('kind', '')}「{e.get('text', '')}」{e.get('style', '')} {e.get('animation', '')}")
L += ["", "</details>"]
- L += ["", T("- 复刻:字幕文件 `packaging/subtitles.srt` 可以直接导入剪映,换成自己的话;带样式的版本是 `packaging/overlays.ass`"
- + (";贴纸和动图去素材库找同款" if stickers else ""),
- "- Remake: import `packaging/subtitles.srt` into your editor and put in your own words; the styled version is `packaging/overlays.ass`"
- + ("; find matching stickers and GIFs in an asset library" if stickers else ""))]
+ files = pack.get("files") or {}
+ rem_bits = []
+ if files.get("srt"):
+ rem_bits.append(T("字幕文件 `{f}` 可直接导入剪辑软件换成自己的话", "import `{f}` into your editor and replace the words", f=files["srt"]))
+ if files.get("ass"):
+ rem_bits.append(T("带样式的字幕/花字版本在 `{f}`", "styled version in `{f}`", f=files["ass"]))
+ if stickers:
+ rem_bits.append(T("贴纸和动图去素材库找同款", "find matching stickers and GIFs in an asset library"))
+ if rem_bits:
+ L += ["", T("- 复刻:", "- Remake: ") + semi().join(rem_bits)]
return L
@@ -994,9 +1030,14 @@ def _shot_detail_md(r: dict) -> list[str]:
if act:
L.append(T("- 表演:{a}", "- Acting: {a}", a=performance.summary(act))
+ (T(";语气:{v}", "; delivery: {v}", v=act["voice"]) if act.get("voice") else ""))
- cl = aspects.shot_text(r) if base["label"] in aspects.PHOTOGRAPHIC else ""
- if cl:
- L.append(T("- 拍法/打光:{c}", "- Camera / lighting: {c}", c=cl))
+ if base["label"] in aspects.OWN_FILMED:
+ cl = aspects.shot_text(r)
+ if cl:
+ L.append(T("- 拍法/打光:{c}", "- Camera / lighting: {c}", c=cl))
+ elif base["label"] in aspects.PHOTOGRAPHIC:
+ vl = aspects.visual_shot_text(r)
+ if vl:
+ L.append(T("- 构图/光影:{c}", "- Framing / light: {c}", c=vl))
if base.get("scene_text"):
L.append(T("- 画面里物体上的字(不是后期字幕):", "- Text on objects in the scene (not subtitles): ") + join(base["scene_text"][:6]))
intrinsic = base["label"] in ("code_render", "screen_capture")
@@ -1037,8 +1078,12 @@ def _shot_detail_md(r: dict) -> list[str]:
rep = r["replication"]
L += ["", T("- 复刻:{n}", "- Remake: {n}", n=rep["note"])]
p = shot_prompts(r)
+ if p.get("image_prompt"):
+ L.append(T(" - 反推首帧生图提示词:{p}", " - Reverse-engineered image prompt: {p}", p=p["image_prompt"]))
+ if p.get("motion_prompt"):
+ L.append(T(" - 图生视频纯动态提示词:{p}", " - Image-to-video motion prompt: {p}", p=p["motion_prompt"]))
if p.get("video_prompt"):
- L.append(T(" - 镜头描述(复核写的,生成提示词从它来):{p}", " - Shot description (from the review; the generation prompts start from it): {p}", p=p["video_prompt"]))
+ L.append(T(" - 完整视频提示词:{p}", " - Full video prompt: {p}", p=p["video_prompt"]))
return L
diff --git a/rea_video/review.py b/rea_video/review.py
index 549a2dc..6cea979 100644
--- a/rea_video/review.py
+++ b/rea_video/review.py
@@ -16,7 +16,7 @@ from .narrative import ROLE_GUIDE
from .vlm import SHOT_PROMPT, shot_hints
PERF_TEMPLATE = {"who": "", "emotion": "", "intensity": "", "face": "", "body": "", "arc": [], "voice": "", "key": False, "move": "", "movers": 0, "full_body": None, "backdrop": "", "en": ""}
-SHOOT_LIKE = ("live_action", "avatar", "stop_motion", "film_footage") # shots where "how was it shot / lit" applies
+SHOOT_LIKE = ("live_action", "stop_motion") # shots where "how was it shot / lit" applies
AGENT_WEIGHT = 0.85 # agent answers are softened toward uniform before fusion
IMAGE_SOURCES = ("ai_image", "photo", "graphic", "screenshot", "unknown")
EDIT_KINDS = ("face_swap", "lip_sync", "restyle", "outfit_swap", "bg_replace", "object_edit", "beautify")
@@ -53,9 +53,9 @@ kind 取 {"|".join(ASSET_KINDS)},is_real_material 为 true/false)。
画面里拍到了带字的东西(手机屏幕、包装、招牌)时填 overlay_text:这一镜后期加上去的字幕、花字、标注原文列表(画面本身的字不要写),报告会把其余 OCR 文字当成画面内容;没有这种情况就不填。
同一段成片在片中出现不止一次(开头先放一段成片当预告、结尾完整放;或中途回放),在较短的那一处填 same_clip_as:另一处的镜头号(整数),复刻时只生成一次;不是就不要填。
实拍或定格镜头被 AI 二次加工过时填 ai_edits:[{{"kind": "{"|".join(EDIT_KINDS)}", "evidence": "看到的破绽"}}](换脸、对口型、风格化、换装、换背景、加删物体、美颜);没有就留空。
-AI 生成 / 3D / 实拍镜头再填 replication:image_prompt(复刻首帧的<PROMPT_LANG>图像提示词:景别、机位高度和俯仰角、主体在画面里的位置和朝向、主体、光线、风格,有人物时写首帧的表情,具体可执行)、
-video_prompt(复刻该镜头的<PROMPT_LANG>视频提示词:先写景别、机位角度、主体在画面里的位置,再写动作过程和结束状态、运镜;人物表演写看得见的表情和动作,不写情绪词,幅度宁小勿大;只写想要的内容,不写否定句)、video_prompt_en(英文版)、
-motion_prompt(首帧/首尾帧模式下的纯动态提示词:只写动作过程、结束状态和运镜,不重复描述首帧图里已有的外貌、场景和光线)、motion_prompt_en(英文纯动态版)。
+AI 生成 / 3D / 实拍镜头再填 replication:image_prompt(复刻首帧的<PROMPT_LANG>图像提示词:景别、机位高度和俯仰角、主体在画面里的位置和朝向、主体,以及四维质感——①渲染介质[严格区分无描边 3D CG 光追硬表面/次表面渲染、真机实拍光学、2.5D 厚涂插画、2D 线稿平涂,严禁把无描边 3D CG 泛化写成二次元/插画]②材质微观肌理[皮肤纹理、织物经纬、金属磨损、流体植被细节]③光影反差[高反差暗调逆光、柔光漫射、轮廓高光]④镜头光学特征[前景遮挡失焦、大光圈散景光斑 Bokeh、边缘辉光 Bloom];有人物时写首帧自然表情)、
+video_prompt(复刻该镜头的<PROMPT_LANG>视频提示词:先对照每镜实测 `motion` 字段里的 `camera_traj`、`net_zoom_pct` 与 `motion_regime`,再看 sheet 关键帧首尾变化,写清景别、机位角度、主体位置、动作过程、环境次级物理动态、结束状态与运镜方向幅度;严禁写反推/拉方向;当 `motion_regime=anchored_pose` 时说明主体核心姿态与朝向保持锚定,动态来自 3D 视差运镜及风吹发丝衣摆/粒子流体/光影微动,足量写出真实次级物理张力但严禁凭空脑补转身、迈步或抬手等未发生的大幅肢体动作;当 `motion_regime=articulated_action` 时如实写清起止帧间的姿态变化轨迹与结束落幅;面部表情保持克制自然,只写想要的内容,不写否定句)、video_prompt_en(英文版)、
+motion_prompt(首帧/首尾帧模式下的纯动态提示词:只写实测与可见的运动过程、次级物理动态、结束状态和运镜方向幅度,不重复描述首帧图里已有的外貌、场景和光线)、motion_prompt_en(英文纯动态版)。
这些提示词会被合并进「生成单元」的多镜头提示词,所以每镜只写这一镜的内容,统一的风格和场景描述写在 description 里即可。
实拍/写实镜头再填 aspects(怎么拍、怎么打光;纯图形/界面画面不填),像素测不出的部分靠你看:
@@ -79,7 +79,7 @@ hook 开头几秒怎么抓住人(写清第几秒、画面和字幕做了什么
例如"0–6 秒先放 AI 成片预告:观众先看到结果,才有动力看完教程",不要写空话("节奏紧凑""画面精美")。
答案顶层的 cast 写整片的角色、场景和道具(看 storyboard.jpg 和各镜截图):characters 每个主要角色一条(id 编号、name 称呼、kind person|animal|cartoon|avatar|product|other、
look 外观写到能据此再画出同一个角色、role 作用、voice 音色、shots 出场镜头号);同一个角色在不同镜头要认成同一个。scenes 每个地点一条(id、where、when、look、shots);
-props 道具 / 商品 / Logo(name、note、shots);style 一句整体视觉风格与调色。
+props 道具 / 商品 / Logo(name、note、shots);style 整体视觉风格与调色(必须写清四要素:渲染介质[如无描边 3D CG 光追硬表面 vs 2.5D 插画 vs 2D 平涂 vs 实拍]、核心材质肌理、光影反差比、景深散景 Bokeh/辉光 Bloom 等光学特征)。
剪辑包装(tasks.packaging,有才做):
- stickers:工具找到的贴纸 / 动图 / 画中画,看 image(贴纸截图)和 frame_cmd 抽的帧,在答案 packaging.stickers 里填
@@ -152,7 +152,10 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
if maybe_motion(rec, breakdown) and not move_of(rec):
why = why + [T("长镜头、动作量大、有配乐少台词:如果大幅度的全身动作本身是看点(舞蹈、打斗、健身),填 performance.move / movers / full_body / backdrop", "long shot with big motion, music and few lines: if large full-body movement is the point (dance, fight, fitness), fill in performance.move / movers / full_body / backdrop")]
- shoot_like = any(l in SHOOT_LIKE for l, _ in ranked[:2])
+ shoot_like = dl in SHOOT_LIKE or (bool(alt) and alt[0][0] in SHOOT_LIKE and alt[0][1] >= 0.35 and bool(ctx.get("native30")))
+ feats = rec.get("features") or {}
+ motion_facts = {k: feats[k] for k in ("camera_traj", "net_zoom_pct", "parallax_score", "motion_regime", "pose_change")
+ if feats.get(k) is not None}
shots.append({
"id": rec["id"], "index": rec["index"], "start": rec["start"], "end": rec["end"], "duration": rec["duration"],
"priority": prio, "why": why,
@@ -160,7 +163,8 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
"second": [alt[0][0], round(alt[0][1], 3)] if alt else None,
"evidence": rec["deterministic"]["evidence"][:6]},
# the tool's top label is already in "tool"; drop it from the raw hints
- "hints": shot_hints(rec["features"], rec["deterministic"]["facts"], dl, dp).split("; 确定性初判=")[0],
+ "hints": shot_hints(feats, rec["deterministic"]["facts"], dl, dp).split("; 确定性初判=")[0],
+ **({"motion": motion_facts} if motion_facts else {}),
**({"aspects": {k: v["result"] for k, v in (rec.get("aspects") or {}).items() if v.get("result")}} if shoot_like else {}),
# the sheet already holds the key frames; separate first / last frames would triple the image tokens
**({"keyframes": [[k["t"], k.get("role", "")] for k in rec["keyframes"]]} if rec.get("keyframes") else {}),
diff --git a/rea_video/videomd.py b/rea_video/videomd.py
index 5c1399d..6718a51 100644
--- a/rea_video/videomd.py
+++ b/rea_video/videomd.py
@@ -497,8 +497,11 @@ def write(b: dict, out: Path) -> Path:
d = out / DIR
if d.is_dir():
- shutil.rmtree(d) # generated: a re-run with a different shot count must not leave stale shot files
- (d / "shots").mkdir(parents=True)
+ shutil.rmtree(d, ignore_errors=True) # generated: a re-run with a different shot count must not leave stale shot files
+ for old in list(d.rglob("*")) if d.is_dir() else []:
+ if old.is_file():
+ old.unlink(missing_ok=True)
+ (d / "shots").mkdir(parents=True, exist_ok=True)
files: list[tuple[str, str, str, int]] = []
def put(rel: str, text: str, title: str, when: str) -> None:
@@ -547,11 +550,18 @@ def write(b: dict, out: Path) -> Path:
("frames/", T("画面场景:每场景原尺寸帧、画上去那一层的抠图和采样点、测量值", "picture scenes: full-size frames, the drawn layer cut out and sampled, measurements"),
T("复刻代码渲染画面", "remaking rendered pictures")),
("audio.png", T("声音波形和节拍图", "waveform and beat chart"), T("看节奏", "seeing the rhythm"))):
+ if rel == "packaging/" and not any(f[0] == f"{DIR}/packaging.md" for f in files):
+ continue
if (out / rel.rstrip("/")).exists():
files.append((rel, what, when, 0))
entry = out / ENTRY
card = _card(b, scenes=len(scenes), transcript=transcript_rel)
entry.write_text(_front(card, _overview(b, files)), encoding="utf-8")
+ import subprocess
+ import sys
+
+ if sys.platform == "darwin" and shutil.which("dot_clean"):
+ subprocess.run(["dot_clean", "-m", str(d), str(out)], capture_output=True, check=False)
return entry
diff --git a/rea_video/vlm.py b/rea_video/vlm.py
index 2a12ac8..4fd77f1 100644
--- a/rea_video/vlm.py
+++ b/rea_video/vlm.py
@@ -350,8 +350,8 @@ AI 仿定格风格(材质在帧间漂移)与真正的定格动画(同一
"generator_guess": "可能的生成模型或工具(如 Seedance/Kling/Veo/Hailuo/Blender/Remotion/剪映 模板),无法判断写 unknown",
"description": "镜头内容:主体、动作、场景、景别、运镜、光线;代码渲染画面写清图形元素是什么(粒子/渐变/图表/卡片/文字/矢量图形)、拼成什么形状、颜色、怎么动(进场方式、流向、变形、镜头推/环绕)、文字和数字组件在哪",
"shot_size": "特写|近景|中景|全景|远景",
- "camera_move": "固定|推|拉|摇|移|跟|环绕|手持",
- "style": "画风/质感关键词",
+ "camera_move": "固定|推|拉|摇|移|跟|环绕|手持(必须结合 hints 里的实测 camera_traj 与 net_zoom_pct 校验,不要把 3D 视差推进误判成拉远或固定)",
+ "style": "四维画风与质感关键词:①渲染介质(严格区分:无描边 3D CG 光追硬表面/次表面渲染、真机实拍光学、2.5D 厚涂插画、2D 线稿平涂,严禁把无描边 3D CG 泛化写成二次元插画)②材质微观肌理(如皮肤毛孔、织物经纬、拉丝/磨损金属、水体植被颗粒)③光影反差(如高反差暗调逆光、柔光漫射、硬朗轮廓光)④镜头光学特征(如前景失焦遮挡、大光圈散景光斑 Bokeh、高光辉光溢出 Bloom)",
"overlay_text": ["后期叠加在画面上的文字(字幕/标题),不含场景里的实物文字"],
"aspects": <<SHOT_ASPECTS>>,
"material_origin": "real|ai_generated|rendered|mixed(画面主要来自真实素材 / AI 生成 / 制作方渲染 / 混合)",
@@ -359,11 +359,11 @@ AI 仿定格风格(材质在帧间漂移)与真正的定格动画(同一
"ai_edits": [{{"kind": "face_swap|lip_sync|restyle|outfit_swap|bg_replace|object_edit|beautify", "evidence": "看到的破绽"}}],
"performance": {{"who": "", "emotion": "", "intensity": "low|mid|high", "face": "", "body": "", "arc": [], "voice": "", "key": false, "move": "", "movers": 0, "full_body": null, "backdrop": "", "en": ""}},
"replication": {{
- "image_prompt": "复刻首帧的中文图像提示词(主体、构图、光线、风格,具体可执行;有人物时写首帧的表情)",
- "video_prompt": "复刻该镜头的中文视频提示词:写清动作过程和结束状态、运镜;人物表演写看得见的表情和动作(眼、眉、嘴、头、手),不写「开心」「难过」这类情绪词,幅度宁小勿大;只写想要的内容,不写否定句",
- "video_prompt_en": "same video prompt in English",
- "motion_prompt": "图生视频(首帧/首尾帧模式)的纯动态提示词:只写主体接下来的运动过程、结束状态和运镜,删掉首帧图里已有的外貌、服装、场景和光线描述",
- "motion_prompt_en": "same motion-only prompt in English (actions, end state and camera movement only, without repeating static look/scene)"
+ "image_prompt": "复刻首帧的中文图像提示词:写清景别、机位俯仰、主体在画面中的位置与朝向,以及四维质感(渲染介质、材质微观肌理、光影反差、前景虚化/散景 Bokeh/辉光 Bloom;无描边 3D CG 须写明无黑色描边线稿),具体可执行;有人物时写首帧自然神态",
+ "video_prompt": "复刻该镜头的中文视频提示词:严格对照实测运动信号(camera_traj 与 motion_regime)写清动作过程、环境次级物理动态、结束状态与运镜方向幅度;当 motion_regime=anchored_pose 时说明主体核心姿态与朝向保持锚定,动态主要来自运镜视差及风吹发丝衣摆/水流/光影粒子/微表情,足量写出这些次级动态但严禁脑补未发生的转身、迈步或抬手等大幅肢体动作;当 motion_regime=articulated_action 时按起止帧真实变化写清肢体动作轨迹与落幅;面部表情写克制可见肌肉变化,只写正向内容,不写否定句",
+ "video_prompt_en": "same video prompt in English (strictly aligned with measured camera_traj and motion_regime: preserve full secondary physics and 3D parallax without inventing unmeasured limb/torso actions)",
+ "motion_prompt": "图生视频(首帧/首尾帧模式)的纯动态提示词:只写主体接下来的真实运动变化、环境物理动态(风动/流体/粒子/光影变化)、结束状态和运镜方向幅度,不重复描述首帧图里已有的静态外貌、服饰和布景",
+ "motion_prompt_en": "same motion-only prompt in English (verified action progression, secondary physics, end state and camera trajectory only, without repeating static look/scene)"
}}
}}"""
@@ -460,8 +460,10 @@ WHOLE_PROMPT = WHOLE_PROMPT.replace("<<VIDEO_ASPECTS>>", _aspect_block(video=Tru
def shot_hints(features: dict, facts: dict, det_top: str, det_prob: float) -> str:
- keys = ["noise_sigma", "temporal_noise", "flat_ratio", "palette95", "dup_ratio", "camera", "kenburns_score", "local_motion_ratio"]
- parts = [f"{k}={features.get(k):.3g}" if isinstance(features.get(k), float) else f"{k}={features.get(k)}" for k in keys]
+ keys = ["noise_sigma", "temporal_noise", "flat_ratio", "palette95", "dup_ratio", "camera", "camera_traj",
+ "net_zoom_pct", "parallax_score", "kenburns_score", "local_motion_ratio", "pose_change", "motion_regime"]
+ parts = [f"{k}={features.get(k):.3g}" if isinstance(features.get(k), float) else f"{k}={features.get(k)}"
+ for k in keys if features.get(k) is not None or k in ("noise_sigma", "camera", "dup_ratio")]
parts.append(f"temporal_family={facts.get('temporal_family')}, pulldown={facts.get('pulldown')}, graphic_score={facts.get('graphic_score')}, fine_dark={facts.get('fine_dark')}, vector_fill={facts.get('vector_fill')}")
parts.append(f"确定性初判={det_top} ({det_prob:.0%})")
return "; ".join(parts)
diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.md
index 320afdf..45a45cc 100644
--- a/skills/rea-video/SKILL.md
+++ b/skills/rea-video/SKILL.md
@@ -120,9 +120,13 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复
image: /绝对路径/product.jpg
```
2. 方案按这个模型的最新实际情况来:`rea-video models <id>` 看能力地图里的资料和核实日期,再上网核对它最新的官方文档和更新(有没有新版本,单次时长、参考视频 / 参考图的数量和时长、一次多镜头、首尾帧、原生音频、提示词写法有没有变)。能力地图里没有、或和最新资料不一致的,按能力地图的格式写进 `~/.rea-video/capabilities/models/<id>.yaml`(同 id 会覆盖自带的),写上来源和核实日期。
-3. `rea-video plan out/ref`:按意图和模型出报告第二部分,并做方案检查。工具按模型能吃什么选输入方式(参考原片视频 / 每镜一张原片关键帧 / 首尾帧 / 纯文字),在单次时长和参考数量以内用最少的调用装下所有镜头,原片参考擦掉字幕后放在 `remake/refs/`。
+3. `rea-video plan out/ref`:按意图和模型出报告第二部分,并做方案检查。工具按模型真实能力原语选输入方式:
+ - **保留原片运镜与动作姿态、仅换外观/发色/服装/主体**:优先选 `--strategy edit`(`video.edit_v2v` 原视频动作锁定编辑,配极简增量编辑提示词,避免长篇分镜重演描述覆盖原动作)。
+ - **无共享角色的多角色异场景混剪(违背 S01 连续性)且不传原视频**:无时间戳锁帧(`video.keyframes`)的模型会自动走 `--strategy frames`(逐镜首帧/首尾帧像素级锁构图与起止姿态),不要强塞进无时间戳的 `multi_reference` 池导致跨镜头串色;注意首帧换人/换外观后若未重绘尾帧,不要传原片尾帧以免末尾变回原片角色。
+ - **深度/边缘控制视频(`--video-ref depth|edge`)**:仅用于声明了像素级空间控制 `video.control_video` 的模型(如 `wan-vace`),不要喂给仅支持语义参考视频(`video.reference_video`)的模型。
+ - 复核镜头提示词时,以每镜实测的 `motion`(`camera_traj` 推拉摇移轨迹与 `motion_regime` 姿态变化模式)为准:`anchored_pose`(核心姿态锚定 + 风动/粒子/视差微动)镜头严禁脑补未发生的转身或大幅肢体动作。
4. 写之前上网搜这个模型的提示词写法和同类镜头的优质提示词:先看口碑好的创作者的实测(X、YouTube、B站、小红书等),再看官方文档和示例;平台的教程页(CapCut、fal 这类)只当二手资料。参考结构和写法,不照抄内容;和能力地图不一致的按第 2 步记下来。报告里的草稿已按这个模型的分镜、参考标签、首帧纯运动精简和台词音效格式排好,再按它的写法(`rea-video models <id>`,或这个模型的提示词 skill)核对改写成最终提示词放进 `out/ref/remake/prompts.json`(`{"G1": "..."}`,图片编号按单元里参考图的顺序;单跑命令行时也可直接用 `rea-video plan out/ref --rewrite-prompts` 自动按模型指南重写并校验),再跑一次 `rea-video plan`,直到方案检查没有 ❌。
-5. 把方案给用户看(调用次数、每次喂什么、检查结果),用户同意后再生成。
+5. 把方案给用户看(调用次数、每次喂什么、检查结果),用户同意后再生成。生成并拼装后检查 `remake/qa.json` 与 `remake/status.md` 的「还原度质检」(或跑 `rea-video compare ref.mp4 out/ref/remake/remake.mp4 --breakdown out/ref/breakdown.json`),核验逐镜运镜方向、姿态变化量、构图轮廓与流畅度是否达标。
用户要自己动手做时,先给报告第二部分「照着做」的步骤,不要先讲模型规则和输入表。