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

Plan generation from the remake intent and the model's limits

juneb6f82ed3160f
diff --git a/docs/capsule-cinema.md b/docs/capsule-cinema.md
index 98624bf..d53f3cb 100644
--- a/docs/capsule-cinema.md
+++ b/docs/capsule-cinema.md
@@ -12,15 +12,16 @@ rea-video --env-file $CC/.env decompose ref.mp4 -o out/ref --vlm
rea-video capsule-draft out/ref/breakdown.json \
--capsule-root $CC --capsule-name my_ref_remake # 加 --write-capsule 才落盘到 capsules/
-# 2b) 复刻 AI 类镜头:生成任务 → 调 capsule-cinema 生成 → 按原时间线拼回并出对比片
-rea-video remake-plan out/ref/breakdown.json --capsule-root $CC --engine seedance2.0
+# 2b) 复刻:按意图和模型出方案 → 生成任务 → 调 capsule-cinema 生成 → 按原时间线拼回并出对比片
+rea-video plan out/ref --model seedance-2.5 # 读 out/ref/remake/intent.yaml;最终提示词放 remake/prompts.json
+rea-video remake-plan out/ref/breakdown.json --capsule-root $CC
rea-video remake-run out/ref/remake/jobs.json --dry-run # 先看任务
rea-video remake-run out/ref/remake/jobs.json # 真正调用(会产生费用)
rea-video assemble out/ref/breakdown.json out/ref/remake/results.json
```
-- AI 视频 / 3D / 实拍 / 数字人镜头:默认用原镜头的**首尾帧 + VLM 提示词**做 `first_last_frame` 生成(`--mode image_to_video` 只用首帧)。
+- 生成的镜头:一个生成单元的每次调用一个任务,输入方式照方案(参考原片视频 / 每镜一张原片关键帧 / 首尾帧 / 纯文字),提示词用 `remake/prompts.json` 里的最终版;方案检查有错误时不出任务。
- 静态图推拉、静帧:不调模型,`assemble` 用测得的缩放/平移参数在本地重建。
- 代码渲染、录屏镜头:默认保留原片(`keep_original`),重建请按报告中的文字轨/版式用 Remotion 实现。
-- 只复刻部分镜头:`remake-run ... --only 2,5`(也可以写镜头 id:`--only shot_002,shot_005`)。有镜头没生成出视频时,命令以非 0 退出,失败详情在 results.json。
+- 只跑一部分:`remake-run ... --only G2`(生成单元),或 `--only 2,5` / `--only shot_002`(包含这些镜头的单元)。有镜头没生成出视频时,命令以非 0 退出,失败详情在 results.json。
- capsule-cinema 不在默认路径(`~/code/github/capsule-cinema`)时,用 `rea-video prefs capsule_root <路径>` 设一次;或者每次都带 `--capsule-root`,`remake-run` 要和 `remake-plan` 一致;jobs.json 里记录的路径对不上会拒绝执行。
diff --git a/docs/cli.md b/docs/cli.md
index 78d8f78..536516b 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -75,7 +75,8 @@ rea-video stems ref.mp4 -o out/ref
```bash
CC=~/code/github/capsule-cinema # capsule-cinema 仓库;也可以设 CAPSULE_CINEMA_ROOT,或 rea-video prefs capsule_root $CC 设一次,之后不用再带 --capsule-root
-rea-video remake-plan out/ref/breakdown.json --capsule-root $CC # AI 类镜头 → 首尾帧生成任务
+rea-video plan out/ref --model seedance-2.5 # 按 remake/intent.yaml 和模型出复刻方案(报告第二部分)并检查
+rea-video remake-plan out/ref/breakdown.json --capsule-root $CC # 方案里的生成单元 → 生成任务(检查有错误时不出)
rea-video remake-run out/ref/remake/jobs.json # 调 capsule-cinema 生成(会计费,可先 --dry-run)
rea-video assemble out/ref/breakdown.json out/ref/remake/results.json # 按原时间线拼回 + 对比片;加 --overlays 把字幕和花字叠回换掉的镜头
rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name my_remake
@@ -83,7 +84,7 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name
- 静态图推拉和静帧:不调模型,本地用测得的缩放和平移参数精确重建。
- 代码渲染和录屏:报告给出文字轨和版式,用 Remotion 重建。
-- 字幕、花字、贴纸:不进生成提示词。参考帧上带着原字幕的镜头,`remake-plan` 会提醒先擦掉;生成完用 `assemble --overlays` 叠回。
+- 字幕、花字、贴纸:不进生成提示词。从原片取的参考(参考视频、关键帧、首尾帧)都擦掉了字;生成完用 `assemble --overlays` 叠回。
- `capsule-draft`:通过 capsule-cinema 自带的 `tool_factory` 注入拆解结果,生成可复用的配方草稿,不需要改 capsule-cinema 的代码。
见 [capsule-cinema.md](capsule-cinema.md)。
@@ -110,9 +111,10 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name
| `drive OUT_DIR --join [RESULTS]` | 把生成好的段(默认 `drive/results.json`:`{"seg_01": 路径}`)按段长对齐、拼起来、按镜头切开,写进 `remake/mine.json`,再跑 `remake` 出对比片 |
| `eval labels.yaml` | 在带标注的样本上评测准确率和切点 F1 |
| `capsule breakdown.json` | 导出 capsule-cinema 的视频分析 JSON |
-| `models [ID] [--plan OUT_DIR]` | 列出能力地图里的生成模型;带 id 时打印这个模型的提示词写法和关键帧要求(`models keyframes` 是关键帧通用做法);`--plan` 把已有拆解的复刻方案改按该模型重出 |
-| `remake-plan` / `assemble` | 生成复刻任务、拼回成片 |
-| `remake-run JOBS [--dry-run] [--only 2,5\|shot_002] [--capsule-root]` | 用 capsule-cinema 执行复刻任务(会计费);有镜头没生成出视频时退出码非 0 |
+| `models [ID]` | 列出能力地图里的生成模型;带 id 时打印这个模型的提示词写法和关键帧要求(`models keyframes` 是关键帧通用做法);`~/.rea-video/capabilities/models/*.yaml` 里补充的模型也会列出 |
+| `plan OUT_DIR [--model ID] [--generate ai\|all]` | 按复刻意图 `remake/intent.yaml`(模型、整条重做还是只做 AI 镜头、换什么)出报告第二部分:生成单元、每次喂什么、提示词草稿和方案检查;`remake/prompts.json` 里按模型写好的最终提示词会做格式检查;拆解结果不变 |
+| `remake-plan` / `assemble` | 把方案里的生成单元写成任务、拼回成片 |
+| `remake-run JOBS [--dry-run] [--only G2\|2,5\|shot_002] [--capsule-root]` | 用 capsule-cinema 执行复刻任务(会计费);有任务没生成出视频时退出码非 0 |
| `capsule-draft breakdown.json` | 生成 capsule-cinema 胶囊草稿 |
## 工作流(设计目标;目前完成到拆解和 AI 镜头复刻)
diff --git a/rea_video/capabilities/prompting.yaml b/rea_video/capabilities/prompting.yaml
index 07edc27..a215afe 100644
--- a/rea_video/capabilities/prompting.yaml
+++ b/rea_video/capabilities/prompting.yaml
@@ -59,6 +59,8 @@ models:
- https://docs.volcengine.com/docs/ark/seedance-portrait-asset-guide?lang=zh
- https://fal.ai/learn/devs/seedance-2-5-prompting-guide
- https://runway.com/resources/seedance-2-5-prompt-guide
+ lint:
+ max_cjk: 500
seedance-2.5-flash:
basis: vendor
@@ -103,6 +105,10 @@ models:
- https://docs.volcengine.com/docs/82379/2222480
- https://docs.volcengine.com/docs/ark/seedance-2-0?lang=zh
- https://docs.volcengine.com/docs/ark/create-video-generation-task-api?lang=zh
+ lint:
+ max_cjk: 500
+ forbid:
+ - {re: '镜头\s*\d+\s*[((]\s*\d|从\s*\d+(\.\d+)?\s*秒起', why: Seedance 2.0 不要给镜头写秒数(官方说精确时间支持不稳定)}
kling-4.0:
basis: vendor
@@ -364,6 +370,12 @@ models:
- https://huggingface.co/MiniMaxAI/MiniMax-H3/raw/main/docs/VIDEO_PROMPT_WRITING_GUIDE_ref_en.md
- https://platform.minimax.io/docs/api-reference/video-generation-v2-create
- https://docs.comfy.org/tutorials/video/minimax/minimax-h3-prompt-guide.md
+ lint:
+ language: en
+ max_chars: 7000
+ require: ["overall_soundscape:", "non_diegetic_music:"]
+ forbid:
+ - {re: '\d+(\.\d+)?\s*[-–~]\s*\d+(\.\d+)?\s*s\b', why: 镜头时间要写单个时间点(At 00:03.500),不写时间段}
minimax-h3-max:
basis: vendor
@@ -386,6 +398,12 @@ models:
只给尾帧行不行,文档前后说法矛盾,尾帧和首帧一起给
sources:
- https://platform.minimax.io/docs/api-reference/video-generation-v2-create
+ lint:
+ language: en
+ max_chars: 7000
+ require: ["overall_soundscape:", "non_diegetic_music:"]
+ forbid:
+ - {re: '\d+(\.\d+)?\s*[-–~]\s*\d+(\.\d+)?\s*s\b', why: 镜头时间要写单个时间点(At 00:03.500),不写时间段}
pika-h3-flex:
basis: vendor
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 2ccc4cf..ee1368b 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -235,9 +235,11 @@ def cmd_remake_plan(args) -> int:
bdir = Path(args.breakdown).parent
root = _capsule_root(args)
- jobs = build_remake_jobs(read_json(Path(args.breakdown)), bdir, capsule_root=root,
- engine=args.engine, # None: keep the engine chosen at decompose time
- mode=args.mode, labels=args.labels.split(",") if args.labels else None)
+ try: # the jobs are the remake plan's units as they stand: change the model or the swaps with `rea-video plan`
+ jobs = build_remake_jobs(read_json(Path(args.breakdown)), bdir, capsule_root=root)
+ except ValueError as exc:
+ print(f"rea-video: {exc}", file=sys.stderr)
+ return 2
print(jobs)
return 0
@@ -537,37 +539,53 @@ def cmd_correct(args) -> int:
def cmd_plan(args) -> int:
- """The remake part of the report, for the model the user will actually use. The breakdown itself is not touched."""
+ """The remake part of the report, from the remake intent (remake/intent.yaml: model, generate all or only the AI
+ shots, what is swapped for what). The breakdown itself is not touched."""
+ from .generation import load_intent, save_intent
+ from .integrations.capsule_cinema import ref_clips
from .pipeline import finalize
from .plan import CAP, Planner, user_capabilities
from .production import _norm
+ out = Path(args.out_dir)
+ intent = load_intent(out)
+ if args.model:
+ intent["model"] = args.model
+ if args.generate:
+ intent["generate"] = args.generate
+ if not intent.get("model"):
+ print(T("rea-video: 还没选模型:问用户用哪个,写进 {p} 的 model,或加 --model", "rea-video: no model yet: ask the user, then set model in {p} or pass --model",
+ p=out / "remake" / "intent.yaml"), file=sys.stderr)
+ return 2
pl = Planner()
live = {k: m for k, m in pl.models.items() if m.get("status") not in ("shutdown", "deprecated")}
- m = next((x for x in live.values() if _norm(x["id"]) == _norm(args.model) or _norm(x.get("name", "")) == _norm(args.model)), None)
+ m = next((x for x in live.values() if _norm(x["id"]) == _norm(intent["model"]) or _norm(x.get("name", "")) == _norm(intent["model"])), None)
if not m:
- print(f"rea-video: 能力地图里没有 {args.model}。先查这个模型的官方文档(单次时长、能不能吃参考视频 / 参考图和各几个、"
+ print(f"rea-video: 能力地图里没有 {intent['model']}。先查这个模型的官方文档(单次时长、能不能吃参考视频 / 参考图和各几个、"
f"能不能一次出多镜头、首尾帧、原生音频、提示词写法),按 {CAP / 'models' / 'video.yaml'} 的格式写进 "
- f"{user_capabilities() / 'models' / (re.sub(r'[^a-z0-9.-]+', '-', args.model.lower()) + '.yaml')},再跑一次。"
+ f"{user_capabilities() / 'models' / (re.sub(r'[^a-z0-9.-]+', '-', intent['model'].lower()) + '.yaml')},再跑一次。"
"已有的模型:rea-video models", file=sys.stderr)
return 2
- out = Path(args.out_dir)
+ intent["model"] = m["id"]
+ save_intent(out, intent)
b = read_json(out / "breakdown.json")
set_lang(b.get("lang", "zh"))
b = finalize(b, out, engine=m["id"])
- from .integrations.capsule_cinema import ref_clips
-
- n = 0
- for u in (b.get("production_plan") or {}).get("units") or []:
- if u.get("method") == "remix": # the source stretches to upload with each prompt
- n += len(ref_clips(b, out, u))
+ plan = b.get("production_plan") or {}
+ n = sum(len(ref_clips(b, out, u)) for u in plan.get("units") or [])
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", "")))
if n:
- print(T("参考视频 {n} 段(已擦掉字幕):{d}", "{n} reference clips (subtitles erased): {d}", n=n, d=out / "remake" / "refs"))
+ print(T("原片参考 {n} 个(已擦掉字幕):{d}", "{n} source references (subtitles erased): {d}", n=n, d=out / "remake" / "refs"))
print(T("模型资料:{src},核实于 {d}", "Model facts: {src}, checked {d}", src="本地补充" if m.get("local") else "能力地图", d=v.get("date") or "?"))
- return 0
+ from .generation import check_lines
+
+ cs = plan.get("checks") or []
+ if cs:
+ print(T("方案检查:", "Plan checks:"))
+ print("\n".join(check_lines(cs)))
+ return 1 if any(c["level"] == "error" for c in cs) else 0
def cmd_models(args) -> int:
@@ -602,14 +620,6 @@ def cmd_models(args) -> int:
"多参考" if "video.multi_reference" in m["primitives"] else "", "参考视频" if "video.reference_video" in m["primitives"] else "",
"原生音频" if (m.get("audio") or {}).get("native") else ""]
print(f"{m['id']} · {m['name']}" + (" · " + " · ".join(x for x in facts if x) if any(facts) else ""))
- if args.plan: # re-plan an existing breakdown for this model: units, inputs and report are rewritten, the measurements stay
- from .pipeline import finalize
-
- out = Path(args.plan)
- b = read_json(out / "breakdown.json")
- set_lang(b.get("lang", "zh"))
- b = finalize(b, out, engine=m["id"])
- print(T("已按 {m} 重出复刻方案:{p}", "Remake plan redone for {m}: {p}", m=m["id"], p=b["summary"].get("production", "")))
notes = pl.prompting.get(m["id"])
if not notes:
print("这个模型还没有记录提示词写法,按通用规则写。")
@@ -714,12 +724,9 @@ def main(argv: list[str] | None = None) -> int:
c.add_argument("-o", "--out")
c.set_defaults(func=cmd_capsule)
- r = sub.add_parser("remake-plan", help="为 AI 类镜头生成 capsule-cinema 复刻任务")
+ r = sub.add_parser("remake-plan", help="把复刻方案的生成单元写成 capsule-cinema 任务(模型和要换的东西在 rea-video plan 里定)")
r.add_argument("breakdown")
r.add_argument("--capsule-root", help="capsule-cinema 仓库;默认 $CAPSULE_CINEMA_ROOT、prefs capsule_root,再退到 ~/code/github/capsule-cinema")
- r.add_argument("--engine", help="换用另一个视频引擎;默认沿用拆解时的引擎")
- r.add_argument("--mode", default="first_last_frame", choices=["first_last_frame", "image_to_video", "text_to_video"])
- r.add_argument("--labels", default="", help="只复刻这些底层类别(逗号分隔),默认 ai_video,cg_3d,avatar,anim_2d,stop_motion;实拍镜头要生成时加 live_action")
r.set_defaults(func=cmd_remake_plan)
rr = sub.add_parser("remake-run", help="用 capsule-cinema 执行 remake-plan 生成的任务(会计费,先 --dry-run)")
@@ -835,12 +842,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", required=True, help="模型 id 或名称(rea-video models 列出的;没有的先查资料补进 ~/.rea-video/capabilities/models/)")
+ pl_.add_argument("--model", help="模型 id 或名称,写进 remake/intent.yaml(rea-video models 列出的;没有的先查资料补进 ~/.rea-video/capabilities/models/)")
+ pl_.add_argument("--generate", choices=["ai", "all"], help="ai:只生成原片里 AI 做的镜头,实拍的出拍摄方案;all:整条都用模型生成(换人、换物后整条复刻)")
pl_.set_defaults(func=cmd_plan)
mo = sub.add_parser("models", help="列出能力地图里的生成模型;带模型 id 时打印这个模型的提示词写法和关键帧要求")
mo.add_argument("model", nargs="?", help="模型 id(如 seedance-2.5、kling-3.0);keyframes 打印关键帧通用做法")
- mo.add_argument("--plan", metavar="OUT_DIR", help="把这个拆解目录的复刻方案改按该模型重出(不重新拆解)")
mo.set_defaults(func=cmd_models)
pf = sub.add_parser("prefs", help="查看 / 设置用户偏好(默认引擎、是否开 VLM、VLM 配置文件、复核者、自由文字说明)")
diff --git a/rea_video/drive.py b/rea_video/drive.py
index e48febb..a3292f0 100644
--- a/rea_video/drive.py
+++ b/rea_video/drive.py
@@ -273,6 +273,19 @@ def clean_clip(b: dict, ranges: list[list[float]], path: Path, width: int = 720,
return path
+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"])
+ 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)
+ write_image(path, erase(f, _mask(boxes, t, f.shape[1], f.shape[0]) if boxes else None))
+ 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")
diff --git a/rea_video/generation.py b/rea_video/generation.py
new file mode 100644
index 0000000..a1aabb0
--- /dev/null
+++ b/rea_video/generation.py
@@ -0,0 +1,516 @@
+"""The generation part of a remake: which shots a video model makes and how they are fed to it.
+
+Three inputs, kept apart:
+ - the breakdown: the source's shots, scenes and timing (facts, the same whatever model is used)
+ - the remake intent (remake/intent.yaml, filled in with the user): the model, whether every shot is generated or only
+ the ones the source generated, and what is swapped for what (people, animals, products), with images where given
+ - the model's limits from the capability map: seconds per call, shots per call, reference video / images it takes
+
+One packer turns them into generation units. The feed is chosen from what the model takes, best first:
+ remix the source stretch as reference video; the model copies cuts, camera and pacing
+ keyframes no reference video but several shots and images per call: one source frame per shot fixes composition
+ frames one shot per call from its first (and last) frame
+ text prompt only
+and consecutive shots go into as few calls as the limits allow (a long stretch is cut where the scene changes).
+
+Prompts come in two layers: a brief per unit (what each shot is in the source, what changes, which image is which) with a
+generic draft, and the final prompt the agent writes for the model's own format (remake/prompts.json). `checks()` reports
+what would go wrong before anything is paid for: images or reference seconds over the limit, very short units, too many
+calls, swaps with nothing to show them, prompts that break the model's format.
+"""
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+import yaml
+
+from . import performance
+from .classify import LABEL_ZH
+from .i18n import T, join, lang, model_name, semi, shot_ids
+from .plan import framing_words, shot_prompts, with_acting
+
+REF_CLIP_S = 15.0 # one reference video: Seedance / Kling take clips up to about 15 s each
+SHORT_UNIT_S = 3.0 # a call this short on its own is unstable and wasteful
+CALLS_PER_MIN = 12 # more calls than this per generated minute: the plan is cutting too finely
+UNKNOWN_IMAGES = 4 # a model that takes reference images without a stated limit is planned for this many
+
+GEN_LABELS = ("ai_video", "cg_3d", "anim_2d")
+# generate = all: filmed and clipped shots are generated too (the user swaps people / products and remakes it by model);
+# code, screen and still inserts are still built locally
+ALL_GEN_LABELS = GEN_LABELS + ("live_action", "stop_motion", "film_footage", "avatar")
+INSERT_LABELS = ("code_render", "screen_capture", "still_motion", "static_hold")
+INTENT_FILE = Path("remake") / "intent.yaml"
+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")}
+
+
+def strategy_name(s: str) -> str:
+ zh, en = STRATEGY_ZH.get(s, (s, s))
+ 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": []}
+ if isinstance(d.get("model"), str) and d["model"].strip():
+ out["model"] = d["model"].strip()
+ for s in d.get("swaps") or []:
+ if not isinstance(s, dict) or not (s.get("to") or s.get("image")):
+ continue
+ img = s.get("image")
+ img = str(Path(img).expanduser().resolve()) if isinstance(img, str) and img.strip() else None
+ 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()
+ return out
+
+
+def load_intent(out: Path) -> dict:
+ p = Path(out) / INTENT_FILE
+ if not p.is_file():
+ return clean_intent({})
+ try:
+ return clean_intent(yaml.safe_load(p.read_text(encoding="utf-8")))
+ except yaml.YAMLError as exc:
+ return {**clean_intent({}), "error": str(exc)[:200]}
+
+
+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, "", [])}
+ p.write_text(yaml.safe_dump(keep, allow_unicode=True, sort_keys=False), encoding="utf-8")
+ return p
+
+
+def load_prompts(out: Path) -> dict[str, str]:
+ """remake/prompts.json: {"G1": "<final prompt>"}, written for the chosen model's own format."""
+ p = Path(out) / PROMPTS_FILE
+ try:
+ got = json.loads(p.read_text(encoding="utf-8")) if p.is_file() else {}
+ except (OSError, ValueError):
+ return {}
+ return {k: v for k, v in got.items() if isinstance(v, str) and v.strip()} if isinstance(got, dict) else {}
+
+
+# ---------------------------------------------------------------- what the model takes
+def spec_of(model: dict | None) -> dict:
+ m = model 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
+ return {"max": float(d.get("max") or 10), "min": float(d.get("min") or 0),
+ "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")),
+ "first": "video.i2v_first_frame" in prim, "last": "video.i2v_first_last" in prim,
+ "exclusive": bool(lim.get("exclusive_inputs")), "native_audio": bool((m.get("audio") or {}).get("native"))}
+
+
+def choose_strategy(spec: dict, n_own: int) -> str:
+ if spec["ref_video"]:
+ return "remix"
+ if spec["multi_shot"] and spec["multi_ref"] and spec["images"] >= n_own + 2:
+ return "keyframes"
+ if spec["first"]:
+ return "frames"
+ return "text"
+
+
+# ---------------------------------------------------------------- packing
+def runs(shots: list[dict], labels: tuple, skip: set[int], joinable_inserts: bool) -> list[list[dict]]:
+ """Stretches of consecutive shots to generate. Inserts made elsewhere (code, screen, stills, a clip reused from
+ another unit) do not break a stretch when the strategy can carry them; anything else does."""
+ out, cur = [], []
+ for r in shots:
+ lab = r["base"]["label"]
+ if lab in labels and r["index"] not in skip:
+ cur.append(r)
+ continue
+ if cur and joinable_inserts and (lab in INSERT_LABELS or r["index"] in skip):
+ continue
+ if cur:
+ out.append(cur)
+ cur = []
+ if cur:
+ out.append(cur)
+ return out
+
+
+def pack(run: list[dict], max_s: float, max_shots: int | None, new_scene: set[int], new_part: set[int] | None = None) -> list[list[dict]]:
+ """Fewest calls within the per-call seconds and shots; where there is a choice, cut where a part of the story
+ starts (a new caption card or narrative step) and at a scene change, and avoid calls shorter than SHORT_UNIT_S.
+ A single shot longer than max_s stays one unit (made in parts)."""
+ new_part = new_part or set()
+ n = len(run)
+ best = [0.0] + [float("inf")] * n
+ prev = [0] * (n + 1)
+ for j in range(1, n + 1):
+ for i in range(j - 1, -1, -1):
+ seg = run[i:j]
+ dur = sum(r["duration"] for r in seg)
+ if len(seg) > 1 and (dur > max_s + 1e-6 or (max_shots and len(seg) > max_shots)):
+ break
+ # a story part (caption card, narrative step) is the stronger seam; a colour-histogram scene change the weaker
+ cost = (1.0 + (0.3 if i > 0 and run[i]["index"] not in new_part else 0.0) + (0.2 if i > 0 and run[i]["index"] not in new_scene else 0.0)
+ + (0.5 if dur < SHORT_UNIT_S else 0.0))
+ if best[i] + cost < best[j]:
+ best[j], prev[j] = best[i] + cost, i
+ out, j = [], n
+ while j > 0:
+ out.append(run[prev[j]:j])
+ j = prev[j]
+ return out[::-1]
+
+
+def _ranges(seg: list[dict]) -> list[list[float]]:
+ out: list[list[float]] = []
+ for r in seg:
+ if out and abs(out[-1][1] - r["start"]) < 1e-3:
+ out[-1][1] = r["end"]
+ else:
+ out.append([r["start"], r["end"]])
+ return [[round(a, 3), round(z, 3)] for a, z in out]
+
+
+def _clips(ranges: list[list[float]], each: float) -> list[list[list[float]]]:
+ """Source ranges as reference clips of at most `each` seconds."""
+ clips, cur, used = [], [], 0.0
+ for a, z in ranges:
+ while z - a > 1e-3:
+ take = min(z - a, each - used)
+ cur.append([round(a, 3), round(a + take, 3)])
+ used += take
+ a += take
+ if used >= each - 1e-3:
+ clips.append(cur)
+ cur, used = [], 0.0
+ if cur:
+ clips.append(cur)
+ return clips
+
+
+# ---------------------------------------------------------------- one unit
+def _shot_text(r: dict) -> str:
+ """What happens in the shot, in the report's language when the reader wrote it in both."""
+ p = shot_prompts(r)
+ if lang() == "en" and p.get("video_prompt_en"):
+ return p["video_prompt_en"]
+ return p.get("video_prompt") or (r.get("review") or r.get("vlm") or {}).get("description") or ""
+
+
+def _brief(seg: list[dict], keyframe_tag: dict[int, str]) -> list[dict]:
+ out, acc = [], 0.0
+ for r in seg:
+ act = performance.of(r)
+ out.append({"shot": r["index"], "time": [round(r["start"], 3), round(r["end"], 3)], "at": round(acc, 3),
+ "duration": round(r["duration"], 3), "label": r["base"]["label"],
+ "source": (r.get("review") or r.get("vlm") or {}).get("description") or "",
+ "action": with_acting(_shot_text(r), act, en=lang() == "en"), "framing": framing_words(r)[0],
+ "composition": keyframe_tag.get(r["index"]), **({"acting": performance.summary(act)} if act else {})})
+ acc += r["duration"]
+ return out
+
+
+def _draft(strategy: str, refs: list[dict], brief: list[dict], swaps_txt: list[str], style: str) -> str:
+ """A generic prompt from the brief: what to keep, what changes, shot by shot. The final one is written per model."""
+ vids = "".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) and change only what is 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 += swaps_txt
+ if style:
+ head.append(style)
+ head.append(T("画面里不要出现字幕、文字和水印", "No subtitles, captions or watermarks in the picture"))
+ lines = []
+ for i, x in enumerate(brief, 1):
+ text = x["action"] or T("(缺镜头描述:先看图复核补写)", "(no description: write one in the image review)")
+ if x.get("composition"):
+ text += T("(构图参考 {k})", " (composition: {k})", k=x["composition"])
+ if 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=x["at"], t=text))
+ return T("。", ". ").join(h.rstrip("。.") for h in head) + T("。\n", ".\n") + "\n".join(lines)
+
+
+def _inputs(strategy: str, refs: list[dict], seg: list[dict], spec: dict) -> 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("@视频")]
+ out = [{"kind": "text", "need": "yes", "source": T("见下面的提示词", "see the prompt below"),
+ "why": T("按这个模型的写法写最终版(remake/prompts.json)", "final version in this model's format (remake/prompts.json)")}]
+ if vids:
+ out.append({"kind": "ref_video", "need": "yes", "source": semi().join(f"`{r['tag']}` " + r["what"] for r in vids),
+ "why": T("模型照它出同样的镜头切换、运镜和动作,一次出完这段的镜头", "the model copies its cuts, camera and action and makes the stretch in one go")})
+ if own:
+ out.append({"kind": "ref_image", "need": "yes", "source": semi().join(f"`{r['tag']}` " + r["what"] for r in own),
+ "why": T("换进去的人、动物、商品,跨镜头一致", "what is swapped in, the same in every shot")})
+ if kf:
+ out.append({"kind": "ref_image", "need": "yes", "source": T("原片镜头 {s} 的画面(擦掉字幕)", "source frames of shots {s} (subtitles erased)",
+ s="、".join(f"#{r['keyframe']}" for r in kf)),
+ "why": T("每个镜头一帧原片定构图和机位", "one source frame per shot fixes composition and camera")})
+ if strategy == "frames":
+ r = seg[0]
+ 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")
+ 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")})
+ return out
+
+
+def build_unit(seg: list[dict], k: int, strategy: str, spec: dict, own: list[dict], swaps_txt: list[str], style: str,
+ model: dict | None) -> dict:
+ t0, t1 = seg[0]["start"], seg[-1]["end"]
+ dur = round(sum(r["duration"] for r in seg), 3)
+ ranges = _ranges(seg)
+ votes: dict[str, float] = {}
+ for r in seg:
+ votes[r["base"]["label"]] = votes.get(r["base"]["label"], 0.0) + r["duration"]
+ label = max(votes.items(), key=lambda kv: kv[1])[0]
+ parts = int(-(-dur // spec["max"])) if len(seg) == 1 and dur > spec["max"] + 1e-6 else 1
+ refs = [dict(r) for r in own] if strategy != "frames" or not spec["exclusive"] else []
+ keyframe_tag: dict[int, str] = {}
+ if strategy == "remix":
+ each = min(REF_CLIP_S, spec["ref_total"])
+ 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))})
+ elif strategy == "keyframes":
+ for r in seg:
+ 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} 的画面(擦掉字幕):只参考构图、景别和机位", "source shot #{i} (subtitles erased): composition, size and camera only", i=r["index"])})
+ brief = _brief(seg, keyframe_tag)
+ unit = {"id": f"G{k}", "kind": "generate", "strategy": strategy, "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), "model": (model or {}).get("id"), "model_name": model_name((model or {}).get("name")),
+ "refs": refs, "brief": brief, "draft": _draft(strategy, refs, brief, swaps_txt, style),
+ "inputs": _inputs(strategy, refs, seg, spec)}
+ missing = [x["shot"] for x in brief if not x["action"]]
+ if missing:
+ unit["prompt_missing"] = missing
+ acting = [{"shot": r["index"], "line": performance.summary(a), "key": a["key"],
+ "how": performance.ROUTE_ZH[performance.route_kind(a, r["base"]["label"])]} for r in seg for a in [performance.of(r)] if a]
+ if acting:
+ unit["acting"] = acting
+ if len(ranges) > 1:
+ unit["note"] = T("这几镜在成片里被插入画面隔开:连着生成,剪辑时把插入画面放回去",
+ "these shots are separated by inserts in the cut: generate them together and put the inserts back in the edit")
+ return unit
+
+
+# ---------------------------------------------------------------- the whole generation part
+def part_starts(b: dict) -> set[int]:
+ """Shots where a part of the video begins: a narrative step starts, or a caption card / title changes there."""
+ from .narrative import beats
+
+ out = {x["shots"][0] for x in beats(b) if x.get("shots")}
+ cues = [c for c in (b.get("packaging") or {}).get("text_cues") or [] if c.get("kind") in ("subtitle", "title", "huazi", "label")]
+ for r in b["shots"]:
+ if any(abs(c["t0"] - r["start"]) <= 0.5 for c in cues):
+ out.add(r["index"])
+ return out
+
+
+def plan_generation(b: dict, model: dict | None, intent: dict, new_scene: set[int], style: str, skip: set[int]) -> 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
+ own = []
+ swaps_txt = []
+ for s in intent.get("swaps") or []:
+ tag = None
+ if s.get("image"):
+ tag = f"@图片{len(own) + 1}"
+ own.append({"tag": tag, "user": True, "path": s["image"],
+ "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_txt.append(T("原片的{f}换成{t}", "the source's {f} becomes {t}", f=s["from"] or T("主体", "subject"), t=s["to"] or tag)
+ + (T("(参考 {k})", " (see {k})", k=tag) if tag else ""))
+ strategy = choose_strategy(spec, len(own))
+ if strategy == "remix":
+ max_s, max_shots = min(spec["max"], spec["ref_total"]), spec["shots"]
+ elif strategy == "keyframes":
+ max_s, max_shots = spec["max"], min(x for x in (spec["shots"], spec["images"] - len(own)) if x)
+ elif strategy == "text" and spec["multi_shot"]:
+ max_s, max_shots = 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")):
+ 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_txt, style, model))
+ 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")}}
+
+
+# ---------------------------------------------------------------- checks
+TAG_RES = (r"@图片(\d+)", r"<Picture (\d+)>", r"(?<![@<])图片(\d+)", r"\[Image (\d+)\]", r"\bImage (\d+)\b")
+VIDEO_TAG_RES = (r"@视频(\d+)", r"<Video (\d+)>", r"\bVideo (\d+)\b")
+
+
+def lint_prompt(text: str, n_images: int, n_videos: int, notes: dict | None) -> list[str]:
+ """What breaks the model's own format: image / video numbers past what is sent, length, required and forbidden
+ parts (from the model's `lint` notes in the capability map)."""
+ rules = (notes or {}).get("lint") or {}
+ errs = []
+ imgs = [int(x) for p in TAG_RES for x in re.findall(p, text)]
+ vids = [int(x) for p in VIDEO_TAG_RES for x in re.findall(p, text)]
+ if imgs and max(imgs) > n_images:
+ errs.append(T("提到了第 {k} 张图,但只传 {n} 张", "refers to image {k} but only {n} are sent", k=max(imgs), n=n_images))
+ if vids and max(vids) > n_videos:
+ errs.append(T("提到了第 {k} 段视频,但只传 {n} 段", "refers to video {k} but only {n} are sent", k=max(vids), n=n_videos))
+ if rules.get("max_cjk") and len(re.findall(r"[\u3400-\u9fff]", text)) > int(rules["max_cjk"]):
+ errs.append(T("中文 {n} 字,超过这个模型的 {m} 字", "{n} Chinese characters, over this model's {m}",
+ n=len(re.findall(r"[\u3400-\u9fff]", text)), m=rules["max_cjk"]))
+ if rules.get("max_chars") and len(text) > int(rules["max_chars"]):
+ errs.append(T("{n} 字符,超过这个模型的 {m}", "{n} characters, over this model's {m}", n=len(text), m=rules["max_chars"]))
+ for need in rules.get("require") or []:
+ if need not in text:
+ errs.append(T("缺少「{x}」", "missing “{x}”", x=need))
+ for f in rules.get("forbid") or []:
+ if isinstance(f, dict) and f.get("re") and re.search(f["re"], text):
+ errs.append(str(f.get("why") or f["re"]))
+ if rules.get("language") == "en":
+ body = re.sub(r"<d>.*?</d>|\"[^\"]*\"", "", text, flags=re.S) # dialogue and on-screen text keep their own language
+ cjk = len(re.findall(r"[㐀-鿿]", body))
+ if cjk > 0.05 * max(1, len(body)):
+ errs.append(T("这个模型的提示词要用英文(台词和画面文字除外)", "this model's prompts should be in English (dialogue and on-screen text aside)"))
+ return errs
+
+
+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("@图片")]
+
+
+def checks(plan: dict, intent: dict, prompts: dict[str, str], notes: dict | None, gen_seconds: float) -> list[dict]:
+ """Problems to fix before paying for generation. level "error" blocks `remake-plan`; "warn" is shown."""
+ spec, units = plan.get("spec") or {}, plan.get("units") or []
+ out: list[dict] = []
+
+ def add(level: str, msg: str, unit: str | None = None) -> None:
+ out.append({"level": level, "msg": msg, **({"unit": unit} if unit else {})})
+
+ if intent.get("error"):
+ add("error", T("remake/intent.yaml 读不了:{e}", "remake/intent.yaml cannot be read: {e}", e=intent["error"]))
+ if not intent.get("model"):
+ add("warn", T("还没选模型:问用户用哪个,写进 remake/intent.yaml 的 model", "no model chosen: ask the user and set model in remake/intent.yaml"))
+ if intent.get("generate") == "all" and not intent.get("swaps"):
+ add("warn", T("整条重做,但意图里没写要换什么(swaps)", "the whole video is remade but the intent lists nothing to swap (swaps)"))
+ for s in intent.get("swaps") or []:
+ if s.get("image") and not Path(s["image"]).is_file():
+ add("error", T("参考图不存在:{p}", "reference image not found: {p}", p=s["image"]))
+ if spec.get("multi_ref") and not spec.get("images_stated"):
+ add("warn", T("能力地图没写这个模型最多几张参考图,按 {n} 张排的;查到实际数后补进模型资料", "the capability map has no image limit for this model; planned for {n}, add the real one", n=UNKNOWN_IMAGES))
+ 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 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("@视频")}):
+ secs = sum(z - a for r in u["refs"] if r["tag"].startswith("@视频") and r.get("part", 1) == part for a, z in r["ranges"])
+ if secs > spec.get("ref_total", 1e9) + 1e-3:
+ add("error", T("{u} 参考视频共 {s:.1f} 秒,超过这个模型的 {m:.0f} 秒", "{u} has {s:.1f}s of reference video, over this model's {m:.0f}s",
+ u=u["id"], s=secs, m=spec["ref_total"]), u["id"])
+ 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"])
+ final = prompts.get(u["id"])
+ if not final:
+ add("warn", T("{u} 还是通用草稿:按 {m} 的写法写好最终提示词,放进 remake/prompts.json", "{u} still has the generic draft: write the final prompt in {m}'s format into remake/prompts.json",
+ u=u["id"], m=u.get("model_name") or u.get("model") or "?"), u["id"])
+ else:
+ for e in lint_prompt(final, n_img, n_vid, notes):
+ add("error", f"{u['id']}: {e}", u["id"])
+ calls = sum(u["calls"] for u in units)
+ if units and gen_seconds > 0 and calls / (gen_seconds / 60) > CALLS_PER_MIN:
+ add("warn", T("{c} 次生成做 {s:.0f} 秒,切得太碎", "{c} calls for {s:.0f}s: cut too finely", c=calls, s=gen_seconds))
+ return out
+
+
+def check_lines(cs: list[dict]) -> list[str]:
+ icon = {"error": "❌", "warn": "⚠️"}
+ return [f"- {icon.get(c['level'], '-')} {c['msg']}" for c in cs]
+
+
+# ---------------------------------------------------------------- report
+INPUT_ZH = {"text": ("文字提示词", "text prompt"), "first_frame": ("首帧图", "first frame"), "last_frame": ("尾帧图", "last frame"),
+ "ref_image": ("参考图", "reference images"), "ref_video": ("参考视频", "reference video")}
+NEED_ZH = {"yes": ("要", "yes"), "opt": ("建议", "worth it"), "no": ("不用", "no")}
+
+
+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 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."""
+ 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 takes no reference video: 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]
+ L = [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)]
+ if plan.get("audio_note"):
+ L.append(T("- 声音:{a}", "- Audio: {a}", a=plan["audio_note"]))
+ if plan.get("overlay_note"):
+ L.append(T("- 包装层:{a}", "- Packaging: {a}", a=plan["overlay_note"]))
+ L += ["", T("| 单元 | 镜头 | 时间 | 时长 | 要喂的 | 提示词 |", "| Unit | Shots | Time | Length | Feed | Prompt |"), "|---|---|---|---|---|---|"]
+ for u in units:
+ when = join(f"{a:.1f}–{z:.1f}s" for a, z in u["ranges"])
+ L.append(f"| {u['id']} | {shot_ids(u['shots'])} | {when} | {u['duration']:.1f}s"
+ f"{T('({c} 次)', ' ({c} calls)', c=u['calls']) if u['calls'] > 1 else ''} | {_fed(u) or '—'} | "
+ f"{T('最终版', 'final') if u['id'] in prompts else T('草稿', 'draft')} |")
+ for u in units:
+ L += ["", "<details><summary>" + T("{id} · 镜头 {sh} · {d:.1f}s · {m}", "{id} · shots {sh} · {d:.1f}s · {m}",
+ id=u["id"], sh=shot_ids(u["shots"]), d=u["duration"], m=strategy_name(u["strategy"])) + "</summary>", "",
+ T("| 输入 | 要不要 | 从哪来 | 为什么 |", "| Input | Needed | From | Why |"), "|---|---|---|---|"]
+ L += [f"| {T(*INPUT_ZH[x['kind']])} | {T(*NEED_ZH[x['need']])} | {x['source']} | {x['why']} |" for x in u["inputs"]]
+ for k in ("note",):
+ if u.get(k):
+ L += ["", f"- {u[k]}"]
+ for a in u.get("acting") or []:
+ L.append(T("- 表演 #{s}{k}:{l}({h},见「表演与情绪」)", "- Acting #{s}{k}: {l} ({h}, see “Acting and emotion”)",
+ s=a["shot"], k=T("(看点)", " (key)") if a["key"] else "", l=a["line"], h=a["how"]))
+ final = prompts.get(u["id"])
+ L += ["", T("最终提示词(按 {m} 的写法):", "Final prompt ({m} format):", m=u.get("model_name") or u.get("model")) if final
+ else T("提示词草稿(通用写法,生成前按 {m} 的写法改写进 remake/prompts.json):", "Draft prompt (generic; rewrite it in {m}'s format into remake/prompts.json before generating):",
+ m=u.get("model_name") or u.get("model")),
+ "", "```text", final or u["draft"], "```", "", "</details>"]
+ return L
diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.py
index f1a5fe1..687ad2f 100644
--- a/rea_video/integrations/capsule_cinema.py
+++ b/rea_video/integrations/capsule_cinema.py
@@ -3,9 +3,8 @@
1. export_capsule_analysis(): converts a rea-video breakdown into the analyzer JSON that
capsule-cinema's video->capsule pipeline expects (scripts/analyze_video_to_capsule.py),
so a reusable capsule draft can be produced from an accurate, evidence-backed breakdown.
-2. build_remake_jobs(): turns AI-replicable shots (AI video / 3D / live action / avatar)
- into generation jobs for capsule-cinema's UniversalVideoGenerationTool, using the original
- shot's first/last frames and the VLM-derived prompt. Still-image shots are rebuilt locally.
+2. build_remake_jobs(): turns the generation units of the remake plan into jobs for the chosen engine's
+ capsule-cinema tool (one per call), with the source references cut and cleaned. Still-image shots are rebuilt locally.
"""
from __future__ import annotations
@@ -15,7 +14,6 @@ from pathlib import Path
from ..classify import LABEL_ZH
from ..i18n import T, join, semi
-from ..packaging import overlays_at
from ..util import fmt_time, write_json
FORMAT_MAP = {"口播": "short_video", "剧情": "story", "商品展示": "product_showcase", "知识讲解": "explainer",
@@ -23,7 +21,6 @@ FORMAT_MAP = {"口播": "short_video", "剧情": "story", "商品展示": "produ
CAMERA_ZH = {"static": "固定机位", "static_with_subject_motion": "固定机位、主体运动", "planar_zoom_pan": "整图推拉/平移",
"handheld_like": "手持晃动", "smooth_move": "平滑运镜", "unknown": "未知"}
# generated by default; filmed shots are shot by the user (pass --labels live_action to approximate them with a model)
-AI_LABELS = ("ai_video", "cg_3d", "avatar", "anim_2d", "stop_motion")
def _aspect(b: dict) -> str:
@@ -211,162 +208,114 @@ def export_capsule_analysis(b: dict, out_path: Path) -> Path:
return out_path
-def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path, engine: str | None = None,
- mode: str = "first_last_frame", labels: list[str] | None = None) -> Path:
- """Write jobs.json for `rea-video remake-run` (rea_video/integrations/run_remake.py).
- Output dirs live under <capsule_root>/output/ to satisfy capsule-cinema's output guard.
- engine: overrides the engine planned at decompose time (None keeps the plan's)."""
- from ..plan import engine_range
+def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path) -> Path:
+ """Write jobs.json for `rea-video remake-run` (rea_video/integrations/run_remake.py): one job per call of each
+ generation unit in the remake plan (the model and intent the user chose), stills rebuilt locally, every other shot
+ kept as the original. Refuses while the plan checks report an error (an image over the limit, a prompt that breaks
+ the model's format...). Output dirs live under <capsule_root>/output/ to satisfy capsule-cinema's output guard."""
+ from ..generation import checks, load_intent, load_prompts
- labels = labels or list(AI_LABELS)
+ plan = b.get("production_plan") or {}
+ plan = {**plan, "units": plan.get("units") or []}
+ # the intent and the final prompts may have changed since the plan was written: check what will actually be sent
+ prompts = load_prompts(bdir)
+ cs = checks(plan, load_intent(bdir), prompts, plan.get("prompting"), sum(u["duration"] for u in plan["units"])) if plan["units"] else []
+ errors = [c["msg"] for c in cs if c["level"] == "error"]
+ if errors:
+ raise ValueError(T("方案检查没过,先改:", "the plan checks failed, fix these first: ") + semi().join(errors))
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
slug = re.sub(r"[^A-Za-z0-9_-]+", "_", Path(b["source"]["filename"]).stem)[:40]
run_dir = capsule_root / "output" / f"rea_remake_{slug}_{stamp}"
- jobs = []
- # the jobs follow the plan in the report (the model the user picked, at that model's real limits); they are not
- # cut down to what the executor supports today: an engine capsule-cinema lacks is capsule-cinema's to add
- eng_run = engine or (b.get("production_plan") or {}).get("model") or b.get("engine") or "seedance2.0"
- unit_jobs, in_units = _unit_jobs(b, bdir, run_dir, eng_run, labels)
- jobs += unit_jobs
+ jobs = _unit_jobs(b, bdir, run_dir, plan, prompts)
+ covered = {i for j in jobs for i in j["shots"]}
for sh in b["shots"]:
- if sh["index"] in in_units:
+ if sh["index"] in covered:
continue
lab = sh["base"]["label"]
- rep = sh["replication"]
+ rep = sh.get("replication") or {}
if lab in ("still_motion", "static_hold"):
- jobs.append({"shot": sh["index"], "id": sh["id"], "executor": "local_ffmpeg", "label": lab,
+ jobs.append({"shot": sh["index"], "id": sh["id"], "shots": [sh["index"]], "executor": "local_ffmpeg", "label": lab,
"image": str((bdir / sh["assets"]["first_frame"]).resolve()), "duration": sh["duration"],
"motion": rep.get("local", {}), "user_assets": rep.get("user_assets", [])})
- continue
- if lab not in labels or rep["executor"] != "capsule_cinema":
- jobs.append({"shot": sh["index"], "id": sh["id"], "executor": "keep_original", "label": lab,
+ else:
+ jobs.append({"shot": sh["index"], "id": sh["id"], "shots": [sh["index"]], "executor": "keep_original", "label": lab,
"reason": rep.get("note", ""), "user_assets": rep.get("user_assets", [])})
- continue
- cap = rep["capsule"]
- gen_type = mode if mode != "first_last_frame" or sh["duration"] >= 1.0 else "image_to_video"
- prompt = cap.get("prompt") or ((sh.get("vlm") or {}).get("description")) or ""
- if not prompt:
- prompt = f"保持参考图的画面、主体与风格,{CAMERA_ZH.get(sh['features'].get('camera', 'unknown'), '')},自然连贯的动作"
- eng = engine or cap.get("engine") or "seedance2.0"
- gen_dur = cap.get("duration", 5)
- if eng != cap.get("engine"): # planned for another engine: re-fit the clip length to this one's limits
- lo, hi = engine_range(eng)
- gen_dur = int(min(hi, max(lo, round(sh["duration"] + 0.49))))
- params = {"prompt": prompt, "output_dir": str(run_dir / sh["id"]), "generation_type": gen_type,
- "engine": eng, "aspect_ratio": cap.get("aspect_ratio", "9:16"), "duration": gen_dur}
- first = str((bdir / sh["assets"]["first_frame"]).resolve())
- last = str((bdir / sh["assets"]["last_frame"]).resolve())
- if gen_type == "first_last_frame":
- params.update({"start_image_path": first, "end_image_path": last})
- elif gen_type == "image_to_video":
- params["image_path"] = first
- warn = ["原镜头是真实素材:生成结果只是近似,建议换成你自己的素材"] if rep.get("user_assets") else []
- # the first / last frames go to the model as-is: subtitles or stickers burned into them get copied into the clip
- used = [(sh["start"], sh["start"] + 0.15)] + ([(sh["end"] - 0.15, sh["end"])] if gen_type == "first_last_frame" else [])
- layers = list(dict.fromkeys(k for a, z in used for k in overlays_at(b.get("packaging"), a, z)))
- if layers:
- warn.append(T("参考帧上带着原片的{k}:直接给模型,生成画面多半会带上这些字;先擦掉(剪映去字幕 / 图像模型擦除)再生成,"
- "包装层最后用 assemble --overlays 叠回",
- "the reference frames carry the source's {k}: handed to the model as-is, the clip will likely copy them; "
- "erase them first (subtitle removal / image inpainting), then lay the packaging back on with assemble --overlays",
- k=join(layers)))
- jobs.append({"shot": sh["index"], "id": sh["id"], "executor": "capsule_cinema", "label": lab,
- "tool": "UniversalVideoGenerationTool", "params": params, "trim_to": sh["duration"],
- "prompt_source": "vlm" if cap.get("prompt") else "fallback",
- "user_assets": rep.get("user_assets", []), "overlays_in_frames": layers,
- "warning": semi().join(warn)})
jobs.sort(key=lambda j: (j["shot"], j.get("part", 0)))
out = bdir / "remake" / "jobs.json"
write_json(out, {"breakdown": str((bdir / "breakdown.json").resolve()), "capsule_root": str(capsule_root),
- "run_dir": str(run_dir), "engine": engine or b.get("engine") or "seedance2.0", "mode": mode, "jobs": jobs})
+ "run_dir": str(run_dir), "engine": plan.get("model"), "strategy": plan.get("strategy"), "jobs": jobs})
return out
-def _refs_given(bdir: Path) -> dict[str, str]:
- """remake/refs.json: {"@图片1": "/path/product.jpg", ...}, the user's own product / character images."""
- from ..util import read_json
+GEN_TYPE = {"remix": "multimodal", "keyframes": "image_to_video", "frames": "first_last_frame", "text": "text_to_video"}
- p = bdir / "remake" / "refs.json"
- got = read_json(p) if p.is_file() else {}
- return {k: str(Path(v).expanduser().resolve()) for k, v in got.items() if isinstance(v, str) and Path(v).expanduser().is_file()}
+def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[str, str]) -> list[dict]:
+ """One job per call of each unit, fed as the plan says: the source stretch as reference video (remix), one source
+ 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 ..generation import unit_images
-def _drop_tags(prompt: str, tags: list[str]) -> str:
- """Remove the sentences that point at reference images the user has not supplied."""
- if not tags:
- return prompt
- parts = re.split(r"(?<=[。.])", prompt)
- return "".join(p for p in parts if not any(t in p for t in tags))
-
-
-def _unit_jobs(b: dict, bdir: Path, run_dir: Path, eng: str, labels: list[str]) -> tuple[list[dict], set[int]]:
- """One job per remix generation (a unit, or each part of a long shot): the source stretch as the reference clip
- with its subtitles erased, the user's reference images, the unit prompt, exactly as the report plans them.
- Only an explicit other engine (--engine) re-plans, for that engine's own limits."""
- from ..production import _limits, production_plan
- from ..plan import Planner
-
- plan = b.get("production_plan") or {}
- if _norm_engine(plan.get("model")) != _norm_engine(eng):
- plan = production_plan(b, bdir, engine=eng)
- if (plan.get("rules") or {}).get("mode") != "remix":
- return [], set()
- lim = _limits(Planner().models.get(plan.get("model") or ""))
- lo, hi = int(lim["min"] or 1), int(lim["max"])
- eng = plan.get("model") or eng
- given = _refs_given(bdir)
- by_index = {r["index"]: r for r in b["shots"]}
- jobs, covered = [], set()
- for u in plan.get("units") or []:
- if u.get("kind", "generate") != "generate" or u.get("method") != "remix":
- continue
- if not all(by_index[i]["base"]["label"] in labels for i in u["shots"] if i in by_index):
- continue
- imgs = [r for r in u["refs"] if r["tag"].startswith("@图片")]
- missing = [r["tag"] for r in imgs if r["tag"] not in given]
- prompt = _drop_tags(u["prompt"], missing)
- parts = sorted({r.get("part", 1) for r in u["refs"] if r["tag"].startswith("@视频")}) or [1]
- clips = ref_clips(b, bdir, u)
+ spec = plan.get("spec") or {}
+ lo, hi = int(spec.get("min") or 1), int(spec.get("max") or 15)
+ eng = plan.get("model")
+ jobs = []
+ for u in plan["units"]:
+ files = ref_clips(b, bdir, u)
+ images = [{"tag": r["tag"], "path": r["path"] if r.get("user") else files[(1, r["tag"])], "what": r["what"]} for r in unit_images(u)]
+ prompt = prompts.get(u["id"]) or u["draft"]
+ parts = sorted({r.get("part", 1) for r in u["refs"] if r["tag"].startswith("@视频")}) or list(range(1, u["calls"] + 1))
for part in parts:
- vids = [r for r in u["refs"] if r["tag"].startswith("@视频") and r.get("part", 1) == part]
- paths = [clips[(part, r["tag"])] for r in vids]
- secs = sum(z - a for r in vids for a, z in r["ranges"])
- warn = []
- if missing:
- warn.append(T("没给 {t}({w}):先把图片路径写进 remake/refs.json,否则商品 / 人物会照原片来",
- "{t} not supplied ({w}): put the image paths in remake/refs.json, or the product / people follow the source",
- t="、".join(missing), w=";".join(r["what"] for r in imgs if r["tag"] in missing)))
+ vids = [files[(part, r["tag"])] for r in u["refs"] if r["tag"].startswith("@视频") and r.get("part", 1) == part]
+ secs = u["generate_s"]
+ gtype = GEN_TYPE[u["strategy"]]
+ params = {"prompt": prompt, "output_dir": str(run_dir / (u["id"] if len(parts) == 1 else f"{u['id']}-{part}")),
+ "generation_type": gtype, "engine": eng, "aspect_ratio": b["source"].get("aspect_ratio") or "9:16",
+ "duration": int(min(hi, max(lo, round(secs + 0.49))))}
+ if vids:
+ params["video_paths"] = vids
+ if images:
+ params["image_paths"] = [x["path"] for x in images]
+ if u["strategy"] == "frames":
+ first, last = files.get((1, "first")), files.get((1, "last"))
+ if last:
+ params.update(start_image_path=first, end_image_path=last)
+ else:
+ params.update(generation_type="image_to_video", image_path=first)
jid = u["id"] if len(parts) == 1 else f"{u['id']}-{part}"
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"], "tool": "VideoGenerator.multimodal",
- "params": {"prompt": prompt, "output_dir": str(run_dir / jid), "generation_type": "multimodal", "engine": eng,
- "video_paths": paths, "image_paths": [given[r["tag"]] for r in imgs if r["tag"] in given],
- "aspect_ratio": (b["source"].get("aspect_ratio") or "9:16"),
- "duration": int(min(hi, max(lo, round(secs + 0.49))))},
- "trim_to": round(secs, 3), "prompt_source": "plan", "user_assets": [], "overlays_in_frames": [],
- "warning": semi().join(warn)})
- covered |= set(u["shots"])
- return jobs, covered
-
-
-def _norm_engine(x) -> str:
- return re.sub(r"[^a-z0-9]", "", str(x or "").lower())
+ "executor": "capsule_cinema", "label": u["label"], "strategy": u["strategy"], "images": images,
+ "params": params, "trim_to": round(secs, 3), "prompt_source": "final" if u["id"] in prompts else "draft"})
+ return jobs
def ref_clips(b: dict, bdir: Path, unit: dict) -> dict[tuple[int, str], str]:
- """The reference clips of one remix unit, cut from the source with the edit's text erased:
- {(part, "@视频1"): path}. Written once into remake/refs/ (named by the unit's span, so a re-plan that cuts
- differently writes new files instead of reusing a clip of the wrong stretch)."""
- from ..drive import clean_clip
+ """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 ({(1, "first"): path, (1, "last"): path}). Files are named by span, so a re-plan never reuses a stale one."""
+ from ..drive import clean_clip, clean_frame
+ d = bdir / "remake" / "refs"
out = {}
for r in unit.get("refs") or []:
- if not r["tag"].startswith("@视频") or not r.get("ranges"):
- continue
- a, z = r["ranges"][0][0], r["ranges"][-1][1]
- f = bdir / "remake" / "refs" / f"{unit['id']}_p{r.get('part', 1)}_v{r['tag'][3:]}_{a:.1f}-{z:.1f}.mp4"
- if not f.is_file():
- clean_clip(b, r["ranges"], f)
- out[(r.get("part", 1), r["tag"])] = str(f.resolve())
+ if r.get("keyframe"):
+ f = d / f"{unit['id']}_shot{int(r['keyframe']):03d}_{r['t']:.2f}.jpg"
+ if not f.is_file():
+ clean_frame(b, r["t"], f)
+ 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"
+ if not f.is_file():
+ clean_clip(b, r["ranges"], f)
+ out[(r.get("part", 1), r["tag"])] = str(f.resolve())
+ if unit.get("strategy") == "frames":
+ s0, s1 = unit["start"], unit["end"]
+ for key, t in (("first", s0 + 0.05), ("last", s1 - 0.08)):
+ if key == "last" and not any(x["kind"] == "last_frame" and x["need"] != "no" for x in unit.get("inputs") or []):
+ continue
+ f = d / f"{unit['id']}_{key}_{t:.2f}.jpg"
+ if not f.is_file():
+ clean_frame(b, t, f)
+ out[(1, key)] = str(f.resolve())
return out
-
diff --git a/rea_video/integrations/run_remake.py b/rea_video/integrations/run_remake.py
index ca10b37..958f252 100644
--- a/rea_video/integrations/run_remake.py
+++ b/rea_video/integrations/run_remake.py
@@ -100,7 +100,7 @@ def main() -> None:
label = j["id"] if j.get("unit") else f"shot {j['shot']}"
print(f"{label}: {j['params']['generation_type']} via {j['params']['engine']} ...", flush=True)
try:
- if j["params"]["generation_type"] == "multimodal": # reference clip + images: the engine's own tool takes these
+ if j.get("unit"): # a unit's references go straight to the engine's own tool
p = {k: v for k, v in j["params"].items() if k != "engine"}
res = vgt._tool_for_engine(vgt.normalize_video_engine(j["params"]["engine"]))._run(**p)
else:
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 0ad406a..da12cd0 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -631,10 +631,14 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:
out = Path(out)
set_lang(breakdown.get("lang", "zh"))
# remember the engine: apply-review / correct / eval call finalize without one and must not reset it.
- # "engine_chosen": the user named a model (decompose --engine, prefs engine, `rea-video plan --model`); until then the
- # report's remake part asks for one instead of presenting a plan for a model nobody picked
+ # A model the user named (decompose --engine, prefs engine) goes into the remake intent unless it already names one;
+ # until a model is named, the report's remake part asks for one instead of planning for a model nobody picked
if engine:
- breakdown["engine_chosen"] = True
+ from .generation import load_intent, save_intent
+
+ it = load_intent(out)
+ if not it.get("model"):
+ save_intent(out, {**it, "model": engine})
engine = breakdown["engine"] = engine or breakdown.get("engine") or "seedance2.0"
shot_records = breakdown["shots"]
audio = breakdown.get("audio", {})
diff --git a/rea_video/plan.py b/rea_video/plan.py
index aa12bf9..e093cdf 100644
--- a/rea_video/plan.py
+++ b/rea_video/plan.py
@@ -27,27 +27,27 @@ LABEL_ROUTE = {
"film_footage": ("R21-film-footage", "source_footage", None),
}
NOTE = LangDict({
- "ai_video": "原片为 AI 生成:取原镜头首尾帧做首尾帧生成,可高度还原构图与动作;换主体时先用图像模型改首帧",
+ "ai_video": "原片为 AI 生成:用视频模型重做;和哪些镜头一起生成、喂什么(参考原片、关键帧或首尾帧)按所选模型排,见复刻方案的生成单元",
"live_action": "原片为实拍:按拍摄方案(景别/机位/打光)重新拍摄;没有拍摄条件时才用 AI 图生视频近似(以首帧为参考)",
"avatar": "数字人口播:先克隆/合成配音,再用数字人模型由人像 + 音频驱动",
- "cg_3d": "3D 渲染:可用首尾帧 AI 生成近似;需要精确多角度时走 3D 建模 + Blender 渲染",
+ "cg_3d": "3D 渲染:可以用视频模型近似(见复刻方案的生成单元);需要精确多角度时走 3D 建模 + Blender 渲染",
"code_render": "代码渲染:用 Remotion/HTML 按文字轨与版式重建,100% 可控,不需要生成模型",
"screen_capture": "录屏/截图:用真实界面录屏或网页截图重建",
"still_motion": "静态图推拉:用一张图 + 测得的缩放/平移参数在本地 ffmpeg 精确复刻",
"static_hold": "静帧:一张图定格即可",
- "anim_2d": "2D 动画:先出角色设定图定画风,再首尾帧生成;要精确口型和动作时做 AE / Live2D / Spine 工程",
+ "anim_2d": "2D 动画:先出角色设定图定画风,再用视频模型生成(见复刻方案的生成单元);要精确口型和动作时做 AE / Live2D / Spine 工程",
"stop_motion": "定格动画:首选真的拍(手机固定 + 定格 App,每秒约 12 张);AI 生成只能近似顿挫感",
"film_footage": "影视片段:画面剪自已有的电影/电视剧/短剧,复刻要找到原片对应片段再剪(版权属于片方,商用要授权);不用原片时,按同样景别、机位和打光自己拍,或用 AI 做近似画面",
}, en={
- "ai_video": "Source is AI-generated: use the shot's first and last frames for first/last-frame generation to closely match composition and motion; to change the subject, edit the first frame with an image model first",
+ "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",
"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: AI first/last-frame generation gives an approximation; for precise multiple angles, model in 3D and render in Blender",
+ "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: rebuild in Remotion / HTML from the text tracks and layout, 100% controllable, no generative model needed",
"screen_capture": "Screen recording / screenshot: rebuild from a real screen recording or web screenshot",
"still_motion": "Still-image move: one image + the measured zoom / pan parameters, reproduced exactly with local ffmpeg",
"static_hold": "Static frame: one held image is enough",
- "anim_2d": "2D animation: make a character sheet to lock the style, then first/last-frame generation; for precise lip sync and motion, build an AE / Live2D / Spine project",
+ "anim_2d": "2D animation: make a character sheet to lock the style, then generate with a video model (see the generation units); for precise lip sync and motion, build an AE / Live2D / Spine project",
"stop_motion": "Stop motion: shooting for real is the first choice (phone locked off + a stop-motion app, about 12 frames per second); AI generation only approximates the stepped feel",
"film_footage": "Film / TV footage: the picture is cut from an existing film, series or short drama; a remake has to find the same clip in the source and cut it (rights belong to the studio, commercial use needs a licence); without the source, shoot it yourself with the same shot size, camera setup and lighting, or approximate it with AI",
})
@@ -348,27 +348,6 @@ class Planner:
if refs:
plan["references"] = refs
plan["note"] += semi() + T("生成时作参考:", "references for generation: ") + join(dict.fromkeys(r["kind_zh"] for r in refs))
- if executor == "capsule_cinema":
- lo, hi = engine_range(engine, self.models)
- gen_dur = int(min(hi, max(lo, round(dur + 0.49))))
- rep = shot_prompts(shot)
- prompt = rep.get("video_prompt") or (shot.get("vlm") or shot.get("review") or {}).get("description") or ""
- # the measured / seen framing goes in front, so a remake keeps the camera height, angle and subject position
- fw, fw_en = framing_words(shot)
- still = T(",", ", ").join(w for w in fw.split(T(",", ", ")) if not w.startswith(T("镜头", "camera ")))
- from .performance import of as _acting
-
- act = _acting(shot)
- plan["capsule"] = {
- "engine": engine, "generation_type": gen_type, "duration": gen_dur,
- "trim_to": round(dur, 3), "aspect_ratio": video.get("aspect_ratio", "9:16"),
- "prompt": with_acting(_with_framing(prompt, fw), act), "prompt_en": with_acting(_with_framing(rep.get("video_prompt_en", ""), fw_en), act, en=True),
- "image_prompt": with_acting(_with_framing(rep.get("image_prompt", ""), still), act, image=True), "framing": fw,
- "needs_split": dur > hi,
- }
- if not prompt:
- plan["capsule"]["prompt_missing"] = T("未运行 VLM,缺少视频提示词;请用 --vlm 重新拆解或手动补写",
- "VLM was not run, so there is no video prompt; re-run the breakdown with --vlm or write one by hand")
if executor == "local_ffmpeg":
m = shot.get("features", {})
plan["local"] = {"zoom_per_s": m.get("zoom_per_s", 0.0), "pan_px_per_s": m.get("pan_px_per_s", 0.0),
diff --git a/rea_video/playbook.py b/rea_video/playbook.py
index ed9f818..0e46e53 100644
--- a/rea_video/playbook.py
+++ b/rea_video/playbook.py
@@ -175,9 +175,19 @@ def _content(b: dict) -> str | None:
return T("**写内容**:照分镜表的 {n} 个镜头逐镜写自己的画面", "**Write the content**: one picture of your own for each of the {n} shots in the shot list", n=n)
+def _all_generated(b: dict) -> bool:
+ """The user remakes the whole video with a model (people, animals or products swapped): nothing is filmed or reused."""
+ return (b.get("intent") or {}).get("generate") == "all"
+
+
+def model_chosen(b: dict) -> bool:
+ """The user named the model the remake is for (remake/intent.yaml); until then nothing model-specific is shown."""
+ return bool((b.get("intent") or {}).get("model"))
+
+
def _material(b: dict, live: bool, refs: bool) -> str | None:
s = b.get("summary") or {}
- rm = s.get("real_material") or {}
+ rm = {} if _all_generated(b) else (s.get("real_material") or {})
kinds: list[str] = []
for k in rm.get("kinds") or {}:
k = k.split("(")[0].split(" (")[0].strip()
@@ -185,7 +195,17 @@ def _material(b: dict, live: bool, refs: bool) -> str | None:
kinds.append(k)
cast = entities.cast(b)
who = [c.get("name") for c in cast.get("characters") or [] if c.get("name")]
+ 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
+ have = [x["to"] or x["from"] for x in swaps if x.get("image")]
+ bare = [x["to"] or x["from"] for x in swaps if not x.get("image")]
+ if have:
+ out.append(T("参考图已有:{h}", "reference images in hand: {h}", h=T(";", "; ").join(have)))
+ 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 = []
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)))
@@ -203,6 +223,8 @@ def _first(x: str) -> str:
def _shoot(b: dict) -> list[str]:
"""One step: how many scenes, how it is framed and lit, in words a person can set up. The numbers stay under “Shoot”."""
+ if _all_generated(b):
+ return []
plan, sp = b.get("production_plan") or {}, b.get("shooting_plan") or {}
shoot = plan.get("shoot") or []
if not shoot and not sp:
@@ -235,7 +257,7 @@ def _generate(b: dict) -> list[str]:
plan, units = b.get("production_plan") or {}, _units(b)
if not units:
return []
- if not b.get("engine_chosen"): # the split, the calls and the prompts depend on a model the user has not named yet
+ if not model_chosen(b): # the split, the calls and the prompts depend on a model the user has not named yet
n = sum(len(u.get("shots") or []) for u in units)
secs = sum(float(u.get("duration") or 0) for u in units)
return [T("**AI 镜头**:{n} 个镜头(共 {s:.0f} 秒)要用视频模型生成。先选模型:告诉 agent 你用哪个,"
@@ -243,7 +265,7 @@ def _generate(b: dict) -> list[str]:
"**AI shots**: {n} shots ({s:.0f} s) to make with a video model. Pick the model first: tell the agent which one and it "
"plans the stretches, inputs and prompts for it (`rea-video plan <folder> --model <model>`)", n=n, s=secs)]
L = []
- if any("缺提示词" in (u.get("prompt") or "") or "missing prompt" in (u.get("prompt") or "").lower() for u in units):
+ if any(u.get("prompt_missing") for u in units):
L.append(T("**补提示词**:这次没开看图,生成单元里的镜头描述是空的;先让 agent 跑 `rea-video review` 看图补写",
"**Fill in the prompts**: this run had no image reading, so the shot descriptions in the units are empty; have the agent run `rea-video review` first"))
secs = sum(float(u.get("duration") or 0) for u in units)
@@ -251,11 +273,17 @@ def _generate(b: dict) -> list[str]:
for u in units)
native = ((b.get("sound_sources") or {}).get("voice") or {}).get("source") == "ai_video_native"
calls = plan.get("calls") or len(units)
- if (plan.get("rules") or {}).get("mode") == "remix":
+ if 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 "
"its shots and pacing; the prompt says only what each shot becomes. The reference clips, subtitles erased, are in `remake/refs/`", c=calls, p="" if calls == 1 else "s", s=secs))
+ elif plan.get("strategy") == "keyframes":
+ L.append(T("**AI 生成**:{c} 次生成(共 {s:.0f} 秒),每次连着出几个镜头。每个镜头给一张原片画面定构图(已擦掉字幕,在 `remake/refs/`),"
+ "换进去的人、动物、商品各给一张参考图,提示词按镜头顺序写动作",
+ "**Generate**: {c} call{p} ({s:.0f} s), several shots each. Each shot gets one source frame for composition (subtitles "
+ "erased, in `remake/refs/`), the swapped-in people, animals and products get reference images, and the prompt lists the shots in order",
+ c=calls, p="" if calls == 1 else "s", s=secs))
else:
L.append(T("**AI 生成**:{u} 段(共 {s:.0f} 秒),每段的首帧图、参考图和提示词在「AI 生成」", "**Generate**: {u} unit{p} ({s:.0f} s); first frame, references and prompt for each under “AI generation”",
u=len(units), p="" if len(units) == 1 else "s", s=secs)
@@ -263,6 +291,12 @@ def _generate(b: dict) -> list[str]:
L[-1] = (L[-1]
+ (T(";原片的对白是随画面一起生成的,台词写进提示词", "; the original's dialogue was generated with the picture, so the lines go in the prompt") if native else ""))
m = model_name(plan.get("model_name"))
+ done = plan.get("prompts") or {}
+ if done and all(u["id"] in done for u in units):
+ errs = [c for c in plan.get("checks") or [] if c["level"] == "error"]
+ L.append(T("**提示词**:已按 {m} 的写法写好(`remake/prompts.json`)", "**Prompts**: written in {m}'s format (`remake/prompts.json`)", m=m)
+ + (T(",格式检查通过", ", format checks passed") if not errs else T(",格式检查有 {n} 处要改(见「方案检查」)", ", {n} format problems to fix (see “Plan checks”)", n=len(errs))))
+ return L
L.append(T("**按模型改提示词**:报告里的提示词是通用写法,不同模型的写法不一样(分镜头怎么写、参考图怎么指代、台词怎么写都不同)。"
"生成前按你实际用的模型的官方提示词指南改一遍,或者让 agent 用这个模型的提示词 skill 优化",
"**Adapt the prompts to your model**: the prompts in this report are generic, and every model reads them differently (how shots are "
@@ -276,7 +310,7 @@ def _drive(b: dict) -> str | None:
drive = (b.get("production_plan") or {}).get("drive") or []
if not drive:
return None
- if not b.get("engine_chosen"):
+ if not model_chosen(b):
n = sum(len(u["shots"]) for u in drive)
return T("**动作镜头**:{n} 个舞蹈 / 动作镜头要拿原片当动作驱动来生成,先选模型再出路线(`rea-video plan <拆解目录> --model <模型>`)",
"**Motion shots**: {n} dance / action shots to generate driven by the source motion; pick the model first "
@@ -300,7 +334,7 @@ def _drive(b: dict) -> str | None:
def _shoot_few(b: dict) -> str | None:
"""A handful of live shots inside a generated video: point at the plan instead of measuring the whole film as if it were shot."""
shoot = (b.get("production_plan") or {}).get("shoot") or []
- if not shoot:
+ if not shoot or _all_generated(b):
return None
n = sum(len(x.get("shots") or []) for x in shoot)
return T("**实拍镜头**:{n} 个镜头要自己拍,机位和布光见下方「拍摄」", "**Live shots**: {n} shots to film yourself; camera and light under “Shoot” below", n=n)
@@ -345,7 +379,10 @@ def _voice(b: dict) -> str | None:
k = len(entities.script(b))
acted = performance.table(b)[0]
src = src.strip()
- bits = [T("原片是{sp}{s}", "the original is {s}", s=src, sp=" " if src[:1].isascii() else "")] if src else []
+ if src in (T("待确认", "to confirm"),) or src.startswith(T("待确认", "to confirm")):
+ bits = [T("原片人声的来源待确认", "where the original voice comes from is to confirm")]
+ else:
+ bits = [T("原片是{sp}{s}", "the original is {s}", s=src, sp=" " if src[:1].isascii() else "")] if src else []
bits.append(T("自己录或用 TTS 配", "record it yourself or use TTS"))
if k:
bits.append(T("{k} 句台词和每句的语速在「声音」的脚本表", "{k} lines with their pace in the script table under “Sound”", k=k))
diff --git a/rea_video/production.py b/rea_video/production.py
index 5683ab9..0935202 100644
--- a/rea_video/production.py
+++ b/rea_video/production.py
@@ -25,9 +25,13 @@ from .aspects.vocab import canon, show
from .plan import CODE_STYLES, Planner, code_scene, shot_prompts, with_acting
from . import performance
-GEN_LABELS = ("ai_video", "cg_3d", "anim_2d")
+from .generation import ALL_GEN_LABELS, GEN_LABELS # noqa: E402 what a video model makes, per remake intent
+
SHOOT_LABELS = ("live_action", "stop_motion")
-GEN_ZH = LangDict({"ai_video": "AI 视频", "cg_3d": "3D 渲染", "anim_2d": "2D 动画"}, en={"ai_video": "AI video", "cg_3d": "3D render", "anim_2d": "2D animation"})
+GEN_ZH = LangDict({"ai_video": "AI 视频", "cg_3d": "3D 渲染", "anim_2d": "2D 动画", "live_action": "实拍", "stop_motion": "定格动画",
+ "film_footage": "影视片段", "avatar": "数字人"},
+ en={"ai_video": "AI video", "cg_3d": "3D render", "anim_2d": "2D animation", "live_action": "live action",
+ "stop_motion": "stop motion", "film_footage": "film footage", "avatar": "digital avatar"})
CODE_LABELS = ("code_render", "screen_capture")
LOCAL_LABELS = ("still_motion", "static_hold")
SIZE_ORDER = {"远景": 0, "全景": 1, "中景": 2, "近景": 3, "特写": 4, # zh / en shot-size words (aspects.framing.SIZES);
@@ -201,9 +205,7 @@ def _limits(m: dict | None) -> dict:
refs = lim.get("refs") or {}
rv = (lim.get("ref_video_s") or {}).get("max")
return {"max": float(d.get("max") or 10), "min": float(d.get("min") or 0), "refs": refs,
- # how much source footage one request can take as reference: the stated total, else one clip of
- # REF_CLIP_S per reference-video slot
- "ref_total": float(rv) if rv else REF_CLIP_S * max(1, int(refs.get("video") or 1)),
+ "ref_total": float(rv) if rv else 15.0 * max(1, int(refs.get("video") or 1)),
"multi_shot": "video.multi_shot" in (m or {}).get("primitives", []),
"ref_video": "video.reference_video" in (m or {}).get("primitives", []),
"multi_ref": "video.multi_reference" in (m or {}).get("primitives", []),
@@ -214,104 +216,6 @@ def _limits(m: dict | None) -> dict:
# ---------------------------------------------------------------- generation units
-INPUT_ZH = LangDict({"text": "文字提示词", "first_frame": "首帧图", "last_frame": "尾帧图", "ref_image": "参考图", "ref_video": "参考视频"},
- en={"text": "text prompt", "first_frame": "first frame", "last_frame": "last frame", "ref_image": "reference image",
- "ref_video": "reference video"})
-METHOD_ZH = LangDict({"t2v": "文生视频", "i2v": "首帧图生视频", "first_last": "首尾帧生视频", "reference": "多参考生成",
- "remix": "参考原片改写"},
- en={"t2v": "text to video", "i2v": "first-frame image to video", "first_last": "first + last frame to video",
- "reference": "multi-reference generation", "remix": "remix of the source clip"})
-REF_CLIP_S = 15.0 # one reference video: Seedance / Kling take clips up to about 15 s each
-
-
-def _fed(u: dict) -> str:
- """The inputs a unit uses besides the prompt, short: "首帧 + 尾帧 + 参考图"."""
- return " + ".join(INPUT_ZH[x["kind"]] for x in u.get("inputs") or [] if x["need"] != "no" and x["kind"] != "text")
-
-
-def _first_note(u: dict) -> str:
- """The plain "first frame from the source" note: already in the unit's input table, so the overview leaves it out."""
- c = u.get("continuity") or ""
- return c if c.startswith(T("首帧:", "first frame:")) else ""
-
-
-def _inputs(seg: list[dict], lim: dict, refs: list[dict], prev_id: str | None, parts: int) -> tuple[str, list[dict]]:
- """What one generation call is fed, each with where it comes from and why -> (method, inputs).
- need: "yes" required, "opt" worth it, "no" not used (kept so the reader sees it was considered).
- Models whose frame inputs and reference inputs cannot share a request (lim["exclusive"]: Seedance 2.x API) get
- one mode per unit: references when a product or person must stay the same, else first / last frames."""
- first, last = seg[0], seg[-1]
- one = len(seg) == 1 and parts == 1
- moves = (first.get("features") or {}).get("camera") not in (None, "static", "unknown")
- imgs = [r for r in refs if r["tag"].startswith("@图片")]
- by_ref = bool(imgs) and lim.get("multi_ref", True)
- frames_alone = lim.get("exclusive") and by_ref # frames can only ride along as references
- out = [{"kind": "text", "need": "yes", "source": T("见下面的提示词", "see the prompt below"),
- "why": T("描述画面、动作和运镜;其他输入都只是约束它", "describes picture, action and camera; every other input only constrains it")}]
- as_ref = T("。这个模型首帧和参考图不能同时传:作为第 {n} 张参考图传入,提示词写「@图片{n} 作为首帧」(即梦全能参考支持,API 多半不支持)",
- "; this model takes frame inputs or references, not both: pass it as one more reference image and write "
- "“@图片{n} as the first frame” in the prompt (Jimeng's omni-reference accepts this; most APIs do not, drop it if refused)",
- n=len(imgs) + 1)
- if prev_id or lim["first_frame"]:
- src = (T("{p} 生成结果的最后一帧", "the last frame of {p}'s result", p=prev_id) if prev_id else
- T("原片 `{f}`(换产品、人物或画风时,用图像模型照下面的首帧提示词重画)",
- "source frame `{f}` (to change product, person or style, redraw it with an image model from the first-frame prompt below)",
- f=first["assets"]["first_frame"]))
- why = (T("和上一段硬切相连,同一场景,首帧接上才不会跳", "hard cut from the previous unit in the same scene; matching the first frame keeps it from jumping")
- if prev_id else T("构图、景别、主体位置一次锁定;只给文字,每次生成的构图都不一样",
- "locks composition, shot size and subject position; with text alone every generation frames it differently"))
- out.append({"kind": "first_frame", "need": "opt" if frames_alone else "yes", "source": src + (as_ref if frames_alone else ""), "why": why})
- if len(seg) > 1:
- out.append({"kind": "last_frame", "need": "no", "source": "—",
- "why": T("一次出多个镜头,尾帧只能约束最后一镜,不用", "several shots in one call; a last frame would only constrain the final shot")})
- elif frames_alone:
- out.append({"kind": "last_frame", "need": "no", "source": "—",
- "why": T("这一单元用参考图保住商品和人物,这个模型在参考模式下不收尾帧", "this unit uses references to keep the product and people; the model takes no last frame alongside them")})
- elif one and lim["first_last"] and (moves or first["duration"] >= 3):
- out.append({"kind": "last_frame", "need": "opt",
- "source": T("原片 `{f}`,处理方式同首帧", "source frame `{f}`, treated like the first frame", f=last["assets"]["last_frame"]),
- "why": T("镜头有运镜或动作,给定终点画面,模型只补中间过程,动作和落幅更接近原片",
- "the shot moves; pinning the end frame leaves the model only the in-between, so motion and the final framing stay close to the source")})
- if imgs:
- out.append({"kind": "ref_image", "need": "yes", "source": semi().join(f"`{r['tag']}` " + r["what"] for r in imgs),
- "why": T("首帧只管第一帧,后面画面里的商品和人靠参考图保持一致",
- "the first frame only fixes frame one; reference images keep the product and people consistent after it")})
- vid = next((r for r in refs if r["tag"] == "@视频1"), None)
- if vid:
- out.append({"kind": "ref_video", "need": "opt", "source": "`@视频1` " + vid["what"].split(":")[0].split(": ")[0],
- "why": T("照着学动作、运镜和剪辑节奏;只作参考,不会复制画面",
- "follow the action, camera move and cutting rhythm; reference only, the picture is not copied")})
- elif lim["ref_video"]:
- out.append({"kind": "ref_video", "need": "no", "source": "—",
- "why": T("这一单元用首尾帧锁构图,这个模型在首尾帧模式下不收参考视频,动作和运镜写进提示词",
- "this unit locks framing with first / last frames; the model takes no reference video alongside them, so put action and camera move in the prompt")})
- else:
- out.append({"kind": "ref_video", "need": "no", "source": "—",
- "why": T("这个模型不支持参考视频,动作和运镜都要写进提示词", "this model takes no reference video; put action and camera move in the prompt")})
- used = {x["kind"] for x in out if x["need"] != "no"}
- method = ("reference" if used & {"ref_image", "ref_video"} else
- "first_last" if "last_frame" in used else "i2v" if "first_frame" in used else "t2v")
- return method, out
-
-
-def _remix_inputs(refs: list[dict]) -> tuple[str, list[dict]]:
- """A remix is fed the source clip (and product / people references when the video has them), never frames."""
- vids = [r for r in refs if r["tag"].startswith("@视频")]
- imgs = [r for r in refs if r["tag"].startswith("@图片")]
- out = [{"kind": "text", "need": "yes", "source": T("见下面的提示词", "see the prompt below"),
- "why": T("只写每个镜头换成什么,分镜和节奏交给参考视频", "says only what each shot becomes; the reference clip carries the shots and pacing")},
- {"kind": "ref_video", "need": "yes", "source": semi().join(f"`{r['tag']}` " + r["what"].split(":")[0].split(": ")[0] for r in vids),
- "why": T("模型照着它出同样的镜头切换、运镜和动作,一次出完这一段的所有镜头;`rea-video remake-plan` 会切好并擦掉字幕",
- "the model copies its cuts, camera and action and makes every shot of the stretch in one go; `rea-video remake-plan` cuts it and erases the subtitles")}]
- if imgs:
- out.append({"kind": "ref_image", "need": "yes", "source": semi().join(f"`{r['tag']}` " + r["what"] for r in imgs),
- "why": T("换成你的商品和人物,跨镜头长相一致", "your product and people, the same in every shot")})
- out.append({"kind": "first_frame", "need": "no", "source": "—",
- "why": T("参考视频模式下不收首帧,构图跟着参考视频走", "no first frame alongside a reference clip; framing follows the clip")})
- return "remix", out
-
-
-INSERT_LABELS = CODE_LABELS + LOCAL_LABELS # made separately and cut in during editing
def reused_footage(gen: list[dict]) -> dict[int, int]:
"""Generated shots an image reader marked as the same clip as another generated shot (a trailer cut from the
finished clip up front, a replay): {shot shown again: shot it is cut from}. Pixels alone cannot tell this from
@@ -326,98 +230,6 @@ def reused_footage(gen: list[dict]) -> dict[int, int]:
return out
-def _runs(shots: list[dict], same_scene, labels: tuple, skip: set[int] | None = None, any_cut: bool = False) -> list[list[dict]]:
- """Runs of generated shots that may share one generation: same scene, joined by hard cuts. Shots cut in
- between them (UI, screenshots, stills) do not break a run: the generated shots are produced back to back
- and the inserts are placed in the edit, which is how a talk-plus-UI video is usually made."""
- runs, cur, gap = [], [], False
- for r in shots:
- lab = r["base"]["label"]
- if lab not in labels or r["index"] in (skip or ()):
- if (lab in INSERT_LABELS or r["index"] in (skip or ())) and cur:
- gap = True
- continue
- if cur:
- runs.append(cur)
- cur, gap = [], False
- continue
- joinable = cur and same_scene(cur[-1], r) and (gap or any_cut or r.get("transition_in") in ("cut", "jump", "flash"))
- if cur and not joinable:
- runs.append(cur)
- cur = []
- cur.append(r)
- gap = False
- if cur:
- runs.append(cur)
- return runs
-
-
-def _split_run(run: list[dict], lim: dict, hard: dict, unit_min: float) -> list[list[dict]]:
- """Fewest units first, then avoid multi-shot units past the preferred hard-cut length and units under the
- minimum generation length (dynamic programming over cut points)."""
- if not lim["multi_shot"]:
- return [[r] for r in run]
- cap = min(lim["max"], hard["max"])
- n = len(run)
- best = [0.0] + [float("inf")] * n
- prev = [0] * (n + 1)
- for j in range(1, n + 1):
- for i in range(j - 1, -1, -1):
- seg = run[i:j]
- dur = sum(r["duration"] for r in seg)
- if len(seg) > 1 and dur > cap:
- break
- cost = 1.0 + (0.4 if len(seg) > 1 and dur > hard["prefer"] else 0.0) + (0.2 if dur < unit_min else 0.0)
- if best[i] + cost < best[j]:
- best[j], prev[j] = best[i] + cost, i
- out, j = [], n
- while j > 0:
- out.append(run[prev[j]:j])
- j = prev[j]
- return out[::-1]
-
-
-def _split_remix(run: list[dict], cap: float, new_scene: set[int], unit_min: float) -> list[list[dict]]:
- """Units for a remix of the source: as few calls as the per-call cap allows (the source clip carries the cuts,
- so there is no hard-cut guard and no same-scene rule), cutting at a scene change where there is a choice and
- avoiding units under the shortest generation length. A single shot longer than the cap stays one unit (S02)."""
- n = len(run)
- best = [0.0] + [float("inf")] * n
- prev = [0] * (n + 1)
- for j in range(1, n + 1):
- for i in range(j - 1, -1, -1):
- seg = run[i:j]
- dur = sum(r["duration"] for r in seg)
- if len(seg) > 1 and dur > cap:
- break
- cut_mid_scene = i > 0 and run[i]["index"] not in new_scene
- cost = 1.0 + (0.3 if cut_mid_scene else 0.0) + (0.2 if dur < unit_min else 0.0)
- if best[i] + cost < best[j]:
- best[j], prev[j] = best[i] + cost, i
- out, j = [], n
- while j > 0:
- out.append(run[prev[j]:j])
- j = prev[j]
- return out[::-1]
-
-
-def _ref_clips(ranges: list[list[float]], each: float) -> list[list[list[float]]]:
- """The unit's source ranges as reference clips of at most `each` seconds (a 30 s unit becomes @视频1 + @视频2)."""
- clips, cur, used = [], [], 0.0
- for a, z in ranges:
- while z - a > 1e-3:
- take = min(z - a, each - used)
- cur.append([round(a, 3), round(a + take, 3)])
- used += take
- a += take
- if used >= each - 1e-3:
- clips.append(cur)
- cur, used = [], 0.0
- if cur:
- clips.append(cur)
- return clips
-
-
def _style_line(shots: list[dict], aspect_ratio: str) -> str:
"""One style sentence for every unit (most common lighting reading across the generated shots, by duration),
so separately generated units still look like one video."""
@@ -438,147 +250,6 @@ def _style_line(shots: list[dict], aspect_ratio: str) -> str:
return semi().join(bits)
-def _unit(seg: list[dict], k: int, lim: dict, model: dict | None, style: str, cast: dict, prev_unit: dict | None,
- same_scene_prev: bool, unit_min: float, remix: bool = False) -> dict:
- t0, t1 = seg[0]["start"], seg[-1]["end"]
- dur = round(sum(r["duration"] for r in seg), 3) # generated length; inserts cut in between are not generated
- ranges: list[list[float]] = []
- for r in seg:
- if ranges and abs(ranges[-1][1] - r["start"]) < 1e-3:
- ranges[-1][1] = r["end"]
- else:
- ranges.append([r["start"], r["end"]])
- contiguous = len(ranges) == 1
- votes: dict[str, float] = {}
- for r in seg:
- votes[r["base"]["label"]] = votes.get(r["base"]["label"], 0.0) + r["duration"]
- label = max(votes.items(), key=lambda kv: kv[1])[0]
- product, people = cast["product"], cast["people"]
- refs, tags = [], {}
- if product:
- tags["product"] = "@图片1"
- refs.append({"tag": "@图片1", "what": T("产品实拍图(正面 + 带 Logo 面),用户提供",
- "product photos (front + the side with the logo), supplied by the user"), "user": True})
- if people:
- tags["person"] = f"@图片{len(refs) + 1}"
- refs.append({"tag": tags["person"], "what": T("人物参考图(每个角色一张正脸 + 半身),保证跨镜头长相一致",
- "character reference images (one frontal face + one half-body per character) so the look stays consistent across shots"), "user": True})
- # frame inputs and references cannot share a request on some models: a unit without product / people refs
- # goes the first / last frame way and gets no reference clip
- # a single shot longer than one call is made in parts; each part gets its own stretch of the source as @视频1
- n_parts = int(-(-dur // lim["max"])) if remix and len(seg) == 1 and dur > lim["max"] else 1
- each = min(REF_CLIP_S, lim["ref_total"])
- for part in range(n_parts):
- a0 = t0 + dur * part / n_parts
- pr = [[a0, a0 + dur / n_parts]] if n_parts > 1 else ranges
- for c, rr in enumerate(_ref_clips(pr, each) if remix else [], 1):
- tag = f"@视频{c}"
- tags.setdefault("video", tag)
- refs.append({"tag": tag, "what": (T("第 {k} 次:", "call {k}: ", k=part + 1) if n_parts > 1 else "")
- + T("原片 {span}(擦掉字幕和贴纸)", "source clip {span} (subtitles and stickers erased)",
- span=join(f"{a:.1f}–{z:.1f}s" for a, z in rr))
- + T(":照它的分镜、运镜、动作和节奏生成", ": follow its shots, camera, action and pacing"), "user": False,
- "ranges": rr, "part": part + 1})
- if not remix and lim["ref_video"] and (not lim.get("exclusive") or product or people):
- tags["video"] = "@视频1"
- span = join(f"{a:.1f}–{z:.1f}s" for a, z in ranges)
- refs.append({"tag": "@视频1", "what": T("原片 {span} 片段", "source clip {span}", span=span)
- + (T("(剪掉中间插入的画面后拼成一段)", " (inserted shots removed, pieces joined)") if not contiguous else "")
- + T(":参考动作、运镜和剪辑节奏(只作参考,不复制画面)",
- ": reference for action, camera movement and cutting rhythm (reference only, do not copy the picture)"), "user": False})
- cont, chained = None, False
- if remix:
- pass # the reference clip carries composition and continuity; frame inputs cannot ride along on these models
- elif prev_unit and same_scene_prev and seg[0].get("transition_in") in ("cut", "jump", "flash") and abs(prev_unit["ranges"][-1][1] - t0) < 1e-3:
- cont, chained = T("首帧用 {p} 的尾帧,接上动作", "first frame = last frame of {p}, continue the action", p=prev_unit["id"]), True
- elif lim["first_frame"]:
- cont = T("首帧:参照原片第 {i} 镜首帧({f})的构图出图", "first frame: generate an image matching the composition of source shot {i}'s first frame ({f})",
- i=seg[0]["index"], f=seg[0]["assets"]["first_frame"]) + (T(",产品换成 @图片1", ", with the product replaced by @图片1") if product else "")
- vids = "".join(dict.fromkeys(r["tag"] for r in refs if r["tag"].startswith("@视频")))
- head = [T("{v} 是原片:照它的分镜生成,镜头数、每个镜头的时长、景别、机位、运镜、动作和剪辑节奏都跟它一致,只把画面内容换成下面逐镜写的",
- "{v} is the source: follow its shots — the number of shots, each one's length, size, camera position, movement, action and "
- "cutting rhythm — and change only what is in the picture, as written shot by shot below", v=vids)] if remix else []
- head.append(style)
- if product:
- head.append(T("产品外观以 @图片1 为准,Logo 和细节保持一致", "Product appearance follows @图片1, keep the logo and details consistent"))
- if people:
- head.append(T("人物以 {t} 为准", "Characters follow {t}", t=tags["person"]))
- if "video" in tags and not remix:
- head.append(T("参考 @视频1 的动作、运镜和剪辑节奏", "Follow the action, camera movement and cutting rhythm of @视频1"))
- if len(seg) > 1 and not remix:
- head.append(T("镜头之间硬切", "Hard cuts between shots"))
- if remix:
- head.append(T("画面里不要出现字幕、文字和水印", "No subtitles, captions or watermarks in the picture"))
- lines, lines_en, missing, acting = [], [], [], []
- acc = 0.0
- for i, r in enumerate(seg, 1):
- p = shot_prompts(r)
- text = p.get("video_prompt") or (r.get("vlm") or r.get("review") or {}).get("description") or ""
- if not text:
- missing.append(r["index"])
- text = T("(缺提示词:开 --vlm 或 agent 看图补写)", "(prompt missing: run --vlm or have the agent write one from the frames)")
- act = performance.of(r)
- text = with_acting(text, act)
- if act:
- acting.append({"shot": r["index"], "line": performance.summary(act), "key": act["key"],
- "how": performance.ROUTE_ZH[performance.route_kind(act, r["base"]["label"])]})
- a, z = acc, acc + r["duration"]
- acc = z
- # a remix takes its timing from the reference clip: no seconds in the prompt (several models handle them badly)
- if len(seg) > 1 and remix:
- lines.append(T("镜头{i}:{text}", "Shot {i}: {text}", i=i, text=text))
- else:
- lines.append(T("镜头{i}({a:.1f}–{z:.1f}s):{text}", "Shot {i} ({a:.1f}–{z:.1f}s): {text}", i=i, a=a, z=z, text=text) if len(seg) > 1 else text)
- if p.get("video_prompt_en"):
- en = with_acting(p["video_prompt_en"], act, en=True)
- lines_en.append((f"Shot {i}: {en}" if remix else f"Shot {i} ({a:.1f}-{z:.1f}s): {en}") if len(seg) > 1 else en)
- parts = 1
- if len(seg) == 1 and dur > lim["max"]:
- parts = int(-(-dur // lim["max"]))
- mode = "multi_shot" if len(seg) > 1 else ("split" if parts > 1 else "single")
- unit = {"id": f"G{k}", "kind": "generate", "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": [[round(a, 3), round(z, 3)] for a, z in ranges],
- "mode": mode, "calls": parts, "model": (model or {}).get("id"), "model_name": model_name((model or {}).get("name")),
- "generate_s": max(dur, lim["min"], unit_min if len(seg) == 1 else 0), "refs": refs, "continuity": cont,
- "prompt": T("。", ". ").join(head) + T("。\n", ".\n") + "\n".join(lines),
- "prompt_en": ("\n".join(lines_en) if len(lines_en) == len(seg) else ""),
- "image_prompt": with_acting(shot_prompts(seg[0]).get("image_prompt", ""), performance.of(seg[0]), image=True)}
- if acting:
- unit["acting"] = acting
- if remix:
- unit["method"], unit["inputs"] = _remix_inputs(refs)
- unit["image_prompt"] = "" # no first frame on this route
- else:
- unit["method"], unit["inputs"] = _inputs(seg, lim, refs, prev_unit["id"] if chained else None, parts)
- if missing:
- unit["prompt_missing"] = missing
- if parts > 1:
- unit["note"] = T("单镜 {d:.1f}s 超过 {m} 单次上限 {mx:.0f}s:在动作停顿处切成 {p} 段,后一段用前一段尾帧作首帧(S02)",
- "Single shot of {d:.1f}s exceeds the {m} per-call limit of {mx:.0f}s: split into {p} parts at pauses in the action, "
- "each part starting from the previous part's last frame (S02)", d=dur, m=unit["model_name"], mx=lim["max"], p=parts)
- if unit["generate_s"] > dur + 0.5:
- unit["note"] = T("生成 {g:.0f}s 后剪到 {d:.1f}s(太短的镜头单独生成不稳定)",
- "Generate {g:.0f}s and trim to {d:.1f}s (very short shots are unstable when generated on their own)", g=unit["generate_s"], d=dur)
- if not contiguous:
- unit["note"] = (unit.get("note", "") + semi() if unit.get("note") else "") + \
- T("这几镜在成片里被插入画面隔开:生成时连着出,剪辑时再把插入画面放回去",
- "In the final cut these shots are separated by inserts: generate them back to back and put the inserts back in the edit")
- if label == "anim_2d" or "anim_2d" in votes:
- unit["alt"] = T("另一条路:2D 动画工程。角色拆层做 Live2D / Spine 骨骼动画,或在 AE 里做;简单的扁平风格动画也可以让 LLM 写 "
- "Lottie / Canvas 代码。口型、动作要逐帧精确时比视频模型可控(R19)",
- "Alternative: a 2D animation project. Split the character into layers and rig it in Live2D / Spine, or animate in After Effects; "
- "simple flat-style animation can also be Lottie / Canvas code written by an LLM. More controllable than a video model when "
- "lip sync and motion must be frame-accurate (R19)")
- if label == "cg_3d" or "cg_3d" in votes:
- unit["alt"] = T("另一条路:3D 工程。让 LLM 写 Blender 脚本或 Three.js 场景,角色/道具建模一次、按镜头设机位渲染,"
- "多角度和角色一致性最好,改文案和镜头也只是改代码",
- "Alternative: a 3D project. Have an LLM write a Blender script or a Three.js scene; model the characters / props once and "
- "render each shot from its own camera. Best for multiple angles and character consistency, and changing copy or shots is "
- "just a code change")
- return unit
-
-
# ---------------------------------------------------------------- shooting setups
def _setups(shots: list[dict], sig: dict, thr: float, b: dict) -> list[dict]:
from .entities import cast as _cast
@@ -647,12 +318,19 @@ def _light_words(r: dict, light: dict) -> str:
# ---------------------------------------------------------------- whole plan
def production_plan(b: dict, out: Path, engine: str = "seedance2.0") -> dict:
+ """The remake part: generation units (for the model and intent in remake/intent.yaml), motion drive, shooting
+ scenes, code builds, local rebuilds, film clips. `engine` is used when the intent names no model."""
+ from . import generation as gen_mod
+
shots = b["shots"]
+ intent = gen_mod.load_intent(out)
+ if 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)
planner = Planner()
seg = planner.routing.get("segmentation", {}).get("defaults", {})
- hard = seg.get("multishot_hardcut_s") or {"prefer": 8, "max": 10}
thr = float(seg.get("same_scene_distance", 0.5))
- unit_min = float((seg.get("generation_unit_s") or {}).get("min", 4))
sig = scene_signatures(shots, out)
from .entities import cast as _cast
@@ -665,48 +343,32 @@ def production_plan(b: dict, out: Path, engine: str = "seedance2.0") -> dict:
return scene_distance(sig[a["index"]], sig[c["index"]]) <= thr
same_prev = {r["index"]: same_scene(p, r) for p, r in zip(shots, shots[1:])}
- eng, model = pick_model(planner, engine)
- lim = _limits(model)
- gen = [r for r in shots if r["base"]["label"] in GEN_LABELS]
- # product / people that recur across the video are referenced in every unit, not only where they were detected
- cast = {"product": any(it.get("kind") in PRODUCT_KINDS and (it.get("real_material") or it in m.get("references", []))
- for r in (shots if gen else []) for m in [r.get("material") or {}] for it in m.get("items", []) + m.get("references", [])),
- "people": sum(r["duration"] for r in gen if (r.get("faces") or 0) > 0.3) >= 1.0}
+ new_scene = {r["index"] for r in shots if not same_prev.get(r["index"], False)}
+ eng, model = pick_model(planner, intent.get("model") or engine)
+ gen = [r for r in shots if r["base"]["label"] in gen_labels]
style = _style_line(gen, b["source"].get("aspect_ratio", "")) if gen else ""
reused = reused_footage(gen)
from . import dance
motion = dance.motion_indices(b) # the moves are the point: driven from the source motion, not generated from frames
- units: list[dict] = []
- # with a model that takes a reference video, the source clip itself is the storyboard: consecutive generated shots
- # go in as few calls as the per-call length allows, the prompt only says what changes (what remakes in practice do)
- remix = bool(lim["ref_video"])
- cap = min(lim["max"], lim["ref_total"]) if remix else None
- new_scene = {r["index"] for r in shots if not same_prev.get(r["index"], False)}
- for run in _runs(shots, (lambda a, c: True) if remix else same_scene, GEN_LABELS, skip=set(reused) | motion, any_cut=remix):
- for segm in (_split_remix(run, cap, new_scene, unit_min) if remix else _split_run(run, lim, hard, unit_min)):
- prev = units[-1] if units else None
- units.append(_unit(segm, len(units) + 1, lim, model, style, cast, prev, same_prev.get(segm[0]["index"], False), unit_min, remix=remix))
- units.sort(key=lambda u: u["start"])
- for k, u in enumerate(units, 1):
- u["id"] = f"G{k}"
+ g = gen_mod.plan_generation(b, model, intent, new_scene, style, set(reused) | motion)
+ units = g["units"]
for again, src in sorted(reused.items()):
u = next((u for u in units if src in u["shots"]), None)
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")),
- "model_limits": {k: lim[k] for k in ("max", "min", "multi_shot", "ref_video", "native_audio")},
- "rules": {"hardcut_s": hard, "same_scene_distance": thr, "mode": "remix" if remix else "frames", "cap_s": cap}, "units": units}
+ 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}
+ lim = g["spec"]
gen_shots = sum(len(u["shots"]) for u in units)
if units:
calls = sum(u["calls"] for u in units)
plan["calls"] = calls
plan["gen_shots"] = gen_shots
if model and (not eng or eng["id"] != model["id"]):
- plan["engine_note"] = T("能力地图里没有可用来生成视频的 {e},这里按 {m} 规划(单次 ≤{mx:.0f}s),共 {c} 次;可选的模型用 `rea-video models` 查看",
- "The capability map has no video generator named {e}; this plan is for {m} (≤{mx:.0f}s per call), {c} call{cs} in total. "
- "`rea-video models` lists the models to choose from",
- e=model_name(eng["name"]) if eng else engine, m=model_name(model["name"]), mx=lim["max"], c=calls, cs=_s(calls))
+ plan["engine_note"] = T("能力地图里没有 {e},这里按 {m} 规划(单次 ≤{mx:.0f}s),共 {c} 次;先查这个模型的资料补进能力地图",
+ "The capability map has no {e}; this plan is for {m} (≤{mx:.0f}s per call), {c} call{cs} in total. Look the model up and add it first",
+ e=intent.get("model") or engine, m=model_name(model["name"]), mx=lim["max"], c=calls, cs=_s(calls))
if model and planner.prompting.get(model["id"]):
plan["prompting"] = planner.prompting[model["id"]]
voice = ((b.get("audio") or {}).get("voice") or {}).get("present")
@@ -722,11 +384,15 @@ def production_plan(b: dict, out: Path, engine: str = "seedance2.0") -> dict:
on_gen = list(dict.fromkeys(k for u in units for a, z in u["ranges"] for k in overlays_at(b.get("packaging"), a, z)))
if on_gen: # generated picture stays clean; the packaging is laid on afterwards, so a new wording can move it
- plan["overlay_note"] = T("生成单元镜头上的{k}属于后期包装,不写进提示词;参考帧上带着的先擦掉,生成后按「剪辑包装层」的时间轴叠回",
- "the {k} on the generated shots is post-production packaging: keep it out of the prompts, erase it from reference frames, "
+ plan["overlay_note"] = T("生成镜头上的{k}属于后期包装,不写进提示词;原片参考上带着的已擦掉,生成后按「剪辑包装层」的时间轴叠回",
+ "the {k} on the generated shots is post-production packaging: keep it out of the prompts (erased from source references) "
"and lay it back on from the packaging timeline after generation", k=join(on_gen))
+ gen_s = sum(u["duration"] for u in units)
+ 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)
plan["drive"] = dance.units(b)
- plan["shoot"] = _setups(shots, sig, thr, b)
+ plan["shoot"] = _setups([r for r in shots if r["base"]["label"] not in gen_labels], sig, thr, b)
code, cur = [], []
for r in shots + [None]:
if r is not None and r["base"]["label"] in CODE_LABELS:
@@ -900,83 +566,11 @@ def report_md(plan: dict) -> list[str]:
if plan.get("engine_note"):
L += [f"- {plan['engine_note']}"]
if plan["units"]:
- lim = plan["model_limits"]
- if plan["rules"].get("mode") == "remix":
- L += [T("- 分组规则:原片里连着的 AI 镜头连成一段,每段一次生成(单次 ≤{c:.0f}s),把这段原片当参考视频喂给模型,"
- "模型照它的分镜、运镜和节奏一次出完这段所有镜头;提示词只写每个镜头换成什么。段太长时优先在换场景处切开",
- "- Grouping: consecutive AI shots in the source form one stretch, generated in one call (≤{c:.0f}s) with that stretch of the "
- "source as the reference video; the model follows its shots, camera and pacing and makes them all at once, and the prompt "
- "says only what each shot becomes. A stretch that is too long is split at a scene change first", c=plan["rules"]["cap_s"])]
- else:
- L += [T("- 分组规则:同场景、硬切相连的 AI 镜头合并为一次生成;单次 ≤{mx:.0f}s;单元内连续硬切尽量 ≤{p}s、最多 {m}s;在叠化/淡入淡出和换场景处切开",
- "- Grouping: AI shots in the same scene joined by hard cuts are generated in one call; ≤{mx:.0f}s per call; "
- "consecutive hard cuts inside a unit preferably ≤{p}s, at most {m}s; split at dissolves / fades and scene changes",
- mx=lim["max"], p=plan["rules"]["hardcut_s"]["prefer"], m=plan["rules"]["hardcut_s"]["max"])]
- if plan.get("audio_note"):
- L.append(T("- 声音:{a}", "- Audio: {a}", a=plan["audio_note"]))
- if plan.get("overlay_note"):
- L.append(T("- 包装层:{a}", "- Packaging: {a}", a=plan["overlay_note"]))
- if plan.get("prompting"):
- L.append(T("- 下面的提示词是通用写法;用 {m} 生成前,按它的写法改写(时间和镜头怎么分、参考素材怎么指代、台词和不想要的内容怎么写):",
- "- The prompts below are written generically; before generating with {m}, rewrite them the way it expects "
- "(timing and shots, how references are addressed, dialogue, exclusions): `rea-video models {i}`",
- m=plan["model_name"], i=plan["model"]))
- if lang() == "zh":
- L += ["", "<details><summary>" + f"{plan['model_name']} 的提示词写法" + "</summary>", ""] + prompting_md(plan["prompting"]) + ["", "</details>"]
- L += ["", T("AI 视频模型能吃这几种输入,每个生成单元下面写了要喂哪些、从哪来:",
- "A video model can take these inputs; each generation unit below lists which ones to feed and where they come from:"),
- T("- **文字提示词**:必需,描述画面、动作、运镜", "- **Text prompt**: always; describes the picture, action and camera"),
- T("- **首帧图**:锁住第一帧的构图和主体。不给就是纯文生,构图每次都不一样",
- "- **First frame**: locks the composition and subject of frame one. Without it this is plain text-to-video and framing changes every time"),
- T("- **尾帧图**:再锁住最后一帧,模型只补中间过程。适合单个有运镜或动作的镜头",
- "- **Last frame**: also locks the final frame so the model only fills in between. Suits a single shot with a camera move or action"),
- T("- **参考图**:商品、人物的样子,让多个镜头里长得一样(提示词里用 `@图片1` 指代)",
- "- **Reference images**: how the product and people look, so they stay the same across shots (`@图片1` in the prompt)"),
- T("- **参考视频**:照着学动作、运镜和节奏,不复制画面(`@视频1`);不是每个模型都支持",
- "- **Reference video**: copy the action, camera move and rhythm, not the picture (`@视频1`); not every model takes one"),
- "", T("### 生成单元", "### Generation units"), "",
- T("每个单元一次生成。表里是要喂给模型的东西,展开单元看来源和提示词。",
- "One generation per unit. The table lists what to feed the model; open a unit for where each input comes from and the prompt."), "",
- T("| 单元 | 镜头 | 时间 | 时长 | 方式 | 要喂的 | 衔接 |", "| Unit | Shots | Time | Duration | Mode | Feed | Continuity |"), "|---|---|---|---|---|---|---|"]
- mode_zh = LangDict({"multi_shot": "一次多镜头", "single": "单镜", "split": "超长切段"},
- en={"multi_shot": "multi-shot", "single": "single shot", "split": "long shot, split"})
- for u in plan["units"]:
- sh = f"#{u['shots'][0]}" + (f"–#{u['shots'][-1]}" if len(u["shots"]) > 1 else "")
- sh = shot_ids(u["shots"]) if len(u["ranges"]) > 1 else sh
- when = join(f"{a:.1f}–{z:.1f}s" for a, z in u["ranges"])
- L.append(f"| {u['id']} | {sh} | {when} | {u['duration']:.1f}s | {mode_zh[u['mode']]}"
- f"{T('({c} 次)', ' ({c} calls)', c=u['calls']) if u['calls'] > 1 else ''}"
- f" | {_fed(u) or '—'} | {u['continuity'] if u.get('continuity') and u['continuity'] != _first_note(u) else '—'} |")
- reuse = [(x, u["id"]) for u in plan["units"] for x in u.get("reused") or []]
- if reuse:
- L += ["", T("同一段成片用了不止一次(看图认出的):只生成一次,剪辑时再放到每一处。",
- "The same clip is used more than once (spotted by the image reader): generate it once and place it at each spot in the edit.")]
- L += [T("- #{a} 和 #{s} 是同一段画面:从 {u} 的成片里剪出来", "- #{a} and #{s} are the same footage: cut it from {u}'s result",
- a=x["shot"], s=x["from"], u=uid) for x, uid in reuse]
- for u in plan["units"]:
- L += ["", "<details><summary>" + T("{id} · 镜头 {sh} · {d:.1f}s · {m}", "{id} · shots {sh} · {d:.1f}s · {m}",
- id=u["id"], sh=shot_ids(u["shots"]), d=u["duration"], m=METHOD_ZH[u["method"]] if u.get("method") else u["label_zh"])
- + "</summary>", ""]
- if u.get("inputs"):
- need = LangDict({"yes": "要", "opt": "建议", "no": "不用"}, en={"yes": "yes", "opt": "worth it", "no": "no"})
- L += [T("| 输入 | 要不要 | 从哪来 | 为什么 |", "| Input | Needed | From | Why |"), "|---|---|---|---|"]
- L += [f"| {INPUT_ZH[x['kind']]} | {need[x['need']]} | {x['source']} | {x['why']} |" for x in u["inputs"]]
- L.append("")
- elif u["refs"]:
- L.append(T("- 参考素材:", "- References: ") + semi().join(f"`{r['tag']}` {r['what']}" for r in u["refs"]))
- if u.get("image_prompt"):
- L.append(T("- 首帧图像提示词:{p}", "- First-frame image prompt: {p}", p=u["image_prompt"]))
- for k in ("note", "alt"):
- if u.get(k):
- L.append(f"- {u[k]}")
- for a in u.get("acting") or []:
- L.append(T("- 表演 #{s}{k}:{l}({h},见「表演与情绪」)", "- Acting #{s}{k}: {l} ({h}, see “Acting and emotion”)", s=a["shot"], k=T("(看点)", " (key)") if a["key"] else "", l=a["line"], h=a["how"]))
- if u.get("prompt_missing"):
- L.append(T("- 镜头 {sh} 缺提示词", "- Shots {sh} have no prompt", sh=shot_ids(u["prompt_missing"])))
- L += ["", "```text", u["prompt"], "```"]
- if u.get("prompt_en"):
- L += ["", T("英文提示词:", "English prompt:"), "", "```text", u["prompt_en"], "```"]
- L += ["", "</details>"]
+ from .generation import report_md as gen_report
+
+ L += ["", T("### 生成单元", "### Generation units"), ""] + gen_report(plan, plan.get("prompts") or {})
+ if plan.get("prompting") and lang() == "zh":
+ L += ["", "<details><summary>" + f"{plan['model_name']} 的提示词写法" + "</summary>", ""] + prompting_md(plan["prompting"]) + ["", "</details>"]
if plan.get("drive"):
from .dance import report_md as _drive_md
diff --git a/rea_video/report.py b/rea_video/report.py
index d57dd85..7e4d1bc 100644
--- a/rea_video/report.py
+++ b/rea_video/report.py
@@ -16,6 +16,7 @@ from .classify import LABEL_ZH
from .i18n import LangDict, T, join, lang, semi, shot_ids
from .packaging import layer_name, anchor_text
from .production import report_md as production_md
+from .plan import shot_prompts
from .sound_source import MUSIC_ZH, SFX_ZH, VOICE_ZH
from .util import fmt_time
from .visual import LABEL_COLOR
@@ -455,7 +456,7 @@ def _plan_md(b: dict) -> list[str]:
plan = b.get("production_plan") or {}
parts = report_parts(plan) if plan else {}
- chosen = bool(b.get("engine_chosen"))
+ chosen = playbook.model_chosen(b)
if not chosen: # generation units, prompts and calls belong to a model the user has not picked yet
for k in ("units", "pre", "drive"):
parts.pop(k, None)
@@ -490,13 +491,13 @@ def _plan_md(b: dict) -> list[str]:
if pre: # grouping rules, the model's prompt conventions, the input primer: needed when writing prompts, not to follow the steps
pre = ["", f'<details class="ref"><summary>{html.escape(T("写提示词前看:分组规则、模型写法、能喂哪些输入", "Before writing prompts: grouping, the model's conventions, what it takes as input"))}</summary>', ""] + pre + ["", "</details>", ""]
m = plan.get("model_name") or T("视频模型", "the video model")
- tip = T("> ⚠️ 下面的提示词是通用写法,按 {m} 的能力规划。不同模型的提示词写法不一样(分镜头怎么写、参考图怎么指代、台词怎么写、哪些写法会被忽略),"
- "生成前按你实际用的模型的官方提示词指南改一遍,或者让 agent 用这个模型的提示词 skill 优化;换了模型,单次时长和能喂的图也要按新模型调。",
- "> ⚠️ The prompts below are generic and planned for {m}. Every model reads prompts differently (how shots are split, how references are "
- "addressed, how dialogue is written, what gets ignored). Before generating, rewrite them following the official prompt guide of the model "
- "you actually use, or have the agent refine them with that model's prompting skill; with another model, also adjust the length per call "
- "and the images it can take.", m=m)
- sub(T("AI 生成", "AI generation"), [f"**{plan['summary'].split(T(';', '; '))[0]}**", "", tip, ""] + pre + parts["units"])
+ drafts = [u["id"] for u in plan.get("units") or [] if u["id"] not in (plan.get("prompts") or {})]
+ tip = (T("> ⚠️ {u} 的提示词还是通用草稿。生成前按 {m} 的官方写法改好(或让 agent 用这个模型的提示词 skill 写),放进 `remake/prompts.json`,"
+ "图片编号按单元里「参考图」的顺序;写好后 `rea-video plan` 会检查格式。",
+ "> ⚠️ {u}: the prompts are still generic drafts. Rewrite them in {m}'s official format (or have the agent write them with that model's "
+ "prompting skill) into `remake/prompts.json`, numbering images in the unit's reference order; `rea-video plan` then checks the format.",
+ u="、".join(drafts), m=m) if drafts else "")
+ sub(T("AI 生成", "AI generation"), [f"**{plan['summary'].split(T(';', '; '))[0]}**", ""] + ([tip, ""] if tip else []) + pre + parts["units"])
if parts.get("drive"):
steps.append(T("**动作驱动**:舞蹈 / 动作镜头用原片当驱动,见下方「动作驱动」", "**Motion drive**: the dance / action shots are driven from the source, see “Motion drive” below"))
sub(T("动作驱动", "Motion drive"), parts["drive"])
@@ -526,9 +527,19 @@ def _plan_md(b: dict) -> list[str]:
head = ["", T("# 第二部分 · 复刻方案", "# Part two · Remake plan"), ""]
if chosen and plan.get("units"):
+ from .generation import check_lines, strategy_name
+
+ it = b.get("intent") or {}
head += [T("按 **{m}** 排的:{f}。换模型就换方案:`rea-video plan <拆解目录> --model <模型>`。",
"Planned for **{m}**: {f}. Another model gets its own plan: `rea-video plan <folder> --model <model>`.",
- m=plan.get("model_name") or plan.get("model"), f=model_facts(plan.get("model"))), ""]
+ m=plan.get("model_name") or plan.get("model"), f=model_facts(plan.get("model"))), "",
+ T("- 复刻范围:{g}", "- Scope: {g}", g=T("整条都用模型生成", "the whole video by model") if it.get("generate") == "all"
+ else T("只生成原片里 AI 做的镜头,实拍的自己拍", "only the shots the source generated; filmed shots are filmed")),
+ T("- 输入方式:{s}", "- Feed: {s}", s=strategy_name(plan.get("strategy", "")))]
+ head += [T("- 换:{f} → {t}", "- Swap: {f} → {t}", f=x["from"] or "—", t=x["to"] or T("参考图", "the reference image"))
+ + (T("(有参考图)", " (with image)") if x.get("image") else "") for x in it.get("swaps") or []]
+ cs = plan.get("checks") or []
+ head += [""] + ([T("**方案检查**", "**Plan checks**"), ""] + check_lines(cs) if cs else [T("方案检查:没有问题。", "Plan checks: nothing to fix.")]) + [""]
elif _units_needed(b):
head += [T("> 还没选视频模型。AI 镜头怎么分段、一次能出多长、能不能直接拿原片当参考、提示词怎么写,每个模型都不一样,"
"所以这部分要按你实际用的模型来排:告诉 agent 你用哪个模型或平台(即梦 / Seedance、可灵、Veo、海螺……),"
@@ -1048,10 +1059,9 @@ def _shot_detail_md(r: dict) -> list[str]:
L += [f" - {e}" for e in measured[:8]]
rep = r["replication"]
L += ["", T("- 复刻:{n}", "- Remake: {n}", n=rep["note"])]
- if rep.get("capsule", {}).get("image_prompt"):
- L.append(T(" - 首帧图像提示词:{p}", " - First-frame image prompt: {p}", p=rep["capsule"]["image_prompt"]))
- if rep.get("capsule", {}).get("prompt"):
- L.append(T(" - 视频提示词:{p}", " - Video prompt: {p}", p=rep["capsule"]["prompt"]))
+ p = shot_prompts(r)
+ 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"]))
return L
diff --git a/scripts/validate_capabilities.py b/scripts/validate_capabilities.py
index 38f744d..bda3ac5 100644
--- a/scripts/validate_capabilities.py
+++ b/scripts/validate_capabilities.py
@@ -151,6 +151,12 @@ def main() -> int:
for k, x in n.items():
if k == "basis":
continue
+ if k == "lint": # machine-checked format rules for final prompts (rea_video/generation.py lint_prompt)
+ ok = isinstance(x, dict) and set(x) <= {"language", "max_chars", "max_cjk", "require", "forbid"} and all(
+ isinstance(f, dict) and f.get("re") and f.get("why") for f in x.get("forbid") or [])
+ if not ok:
+ errors.append(f"prompting.yaml:{mid}: lint 格式不对")
+ continue
if k in text_keys and not isinstance(x, str) or k in list_keys and not (isinstance(x, list) and all(isinstance(i, str) for i in x)):
errors.append(f"prompting.yaml:{mid}: 字段 {k} 类型不对")
elif k not in text_keys | list_keys:
diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.md
index c177e48..9fa62fc 100644
--- a/skills/rea-video/SKILL.md
+++ b/skills/rea-video/SKILL.md
@@ -98,10 +98,23 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复
报告分两部分:第一部分是拆解(结构,和用什么模型无关),第二部分是复刻方案(按一个模型排)。拆解不要因为复刻去合并镜头。
-有 AI 镜头时,复刻方案要按用户实际用的模型来排:
-1. 先问用户用哪个模型或平台(即梦 / Seedance、可灵、Veo、海螺……),不要替用户选。
+有 AI 镜头时,复刻方案按用户的意图和实际用的模型来排:
+1. 问用户:用哪个模型或平台(即梦 / Seedance、可灵、Veo、海螺……,不要替用户选);整条都用模型重做,还是只生成原片里 AI 做的镜头;要换什么、换成什么、有没有参考图。写进 `out/ref/remake/intent.yaml`:
+
+ ```yaml
+ model: seedance-2.5
+ generate: all # all:整条用模型生成;ai(默认):只生成 AI 镜头,实拍的出拍摄方案
+ swaps:
+ - from: 女主播
+ to: 三十岁左右的男主播,短发,深色西装
+ - from: 原片的口红
+ to: 用户的保温杯
+ image: /绝对路径/product.jpg
+ ```
2. 方案按这个模型的最新实际情况来:`rea-video models <id>` 看能力地图里的资料和核实日期,再上网核对它最新的官方文档和更新(有没有新版本,单次时长、参考视频 / 参考图的数量和时长、一次多镜头、首尾帧、原生音频、提示词写法有没有变)。能力地图里没有、或和最新资料不一致的,按能力地图的格式写进 `~/.rea-video/capabilities/models/<id>.yaml`(同 id 会覆盖自带的),写上来源和核实日期。
-3. `rea-video plan out/ref --model <id>`:按这个模型重出报告第二部分,能吃参考视频的模型会把原片对应段擦掉字幕切好放在 `remake/refs/`。
+3. `rea-video plan out/ref`:按意图和模型出报告第二部分,并做方案检查。工具按模型能吃什么选输入方式(参考原片视频 / 每镜一张原片关键帧 / 首尾帧 / 纯文字),在单次时长和参考数量以内用最少的调用装下所有镜头,原片参考擦掉字幕后放在 `remake/refs/`。
+4. 按这个模型的提示词写法(`rea-video models <id>`,或这个模型的提示词 skill)把每个单元的草稿写成最终提示词,放进 `out/ref/remake/prompts.json`(`{"G1": "..."}`,图片编号按单元里参考图的顺序),再跑一次 `rea-video plan`,直到方案检查没有 ❌。
+5. 把方案给用户看(调用次数、每次喂什么、检查结果),用户同意后再生成。
用户要自己动手做时,先给报告第二部分「照着做」的步骤,不要先讲模型规则和输入表。
diff --git a/skills/rea-video/references/remake.md b/skills/rea-video/references/remake.md
index 17d3522..aeabf17 100644
--- a/skills/rea-video/references/remake.md
+++ b/skills/rea-video/references/remake.md
@@ -12,14 +12,13 @@
## 用哪个模型
-- 用户指定了视频模型:拆解时加 `--engine <id>`(`rea-video models` 列出可选的 id);已经拆完的用 `rea-video models <id> --plan out/ref` 改按它重出方案。
-- 用户没指定:不用问,直接用默认的那个。
-- 把提示词交给用户之前,按 `rea-video models <id>` 打印的写法改写每个生成单元的提示词:时间和镜头怎么分、参考素材怎么指代、台词和不想要的内容怎么写;首帧 / 首尾帧模式下只留运动和运镜。要重画首帧时,图像提示词按所用图像模型的写法改(同一个命令)。
+- 模型、整条重做还是只做 AI 镜头、换什么,都写在 `remake/intent.yaml`(见 SKILL.md「复刻」),`rea-video plan out/ref` 按它出方案。用户没说用哪个模型就先问。
+- 报告里每个单元的提示词是草稿。按 `rea-video models <id>` 打印的写法写成最终版放进 `remake/prompts.json`:时间和镜头怎么分、参考素材怎么指代、台词和不想要的内容怎么写;首帧 / 首尾帧模式下只留运动和运镜。`rea-video plan` 会按这个模型的格式规则检查。
- 选帧、擦字、首尾帧怎么配:`rea-video models keyframes`。
## 各类镜头怎么复刻
-- **AI 类镜头**:模型能吃参考视频时(Seedance、Kling 等),默认「参考原片改写」:原片里连着的 AI 镜头连成一段,每段一次生成(不超过模型单次上限),这段原片擦掉字幕后当 `@视频1`,模型照它的分镜和节奏出完这段的镜头,提示词只写每个镜头换成什么。不能吃参考视频的模型才用首尾帧逐段生成。可以通过 [capsule-cinema](https://github.com/JuneYaooo/capsule-cinema) 自动跑(会计费,先 `--dry-run`,并征得用户同意)。
+- **AI 类镜头**(`generate: all` 时实拍镜头也算):连着的镜头尽量放进同一次生成。输入方式按模型能吃什么选:能吃参考视频就把这段原片擦掉字幕当 `@视频1`,模型照它的分镜和节奏出;不吃参考视频、但能一次多镜头和多图的,每个镜头给一张原片画面定构图;都不行才逐镜用首尾帧。要换进去的东西按意图里的图和描述写。可以通过 [capsule-cinema](https://github.com/JuneYaooo/capsule-cinema) 自动跑(会计费,先 `--dry-run`,并征得用户同意)。
- **静态图推拉、静帧**:本地按测得的运动参数重建。
- **代码渲染**:先跑 `rea-video code-remake out/ref`。它按拆片包 `frames/` 里每个场景的采样点或抠图、测得的运动和背景光,写出 `out/ref/code/`(`spec.json` 每个场景一项、`render.py` 渲染器、`overlays.ass` 文字),逐场景把量和亮度对齐原片,渲染出 `code/remake.mp4`,再和原片打分。
- 往下改都从这一版开始:先改 `spec.json` 里的数(粒子数 `count`、大小 `dot`、亮度 `gain`、运动 `motion`、背景光 `glow`);要换成新形状,就把 `points` 换成自己的点文件;要做原片没有的效果再改 `render.py`,或照着它改写成 Remotion / Three.js。改完重跑同一条命令,改过的 `spec.json` 会保留,`--reset` 才会从头重建。`python code/render.py --frame 12.5` 可以只出一帧来看。
@@ -30,8 +29,7 @@
- **表演和情绪**:报告「表演与情绪」一节逐镜写了情绪、表情、动作和语气,生成单元的提示词里已经带上表情和动作。改写提示词时保留看得见的表情和动作,不要换成「开心」「难过」这类词,也不要把幅度写大;有台词的镜头先做有语气的配音,再让画面跟着声音演。
- **声音**:TTS(按脚本表里每句的语气)、BGM(按 BPM / 调性 / 情绪)、音效(按时间点)三条轨分别准备。
- **剪辑包装(字幕、花字、贴纸)**:不进生成。生成模型只出干净的人和画面,包装层最后按「剪辑包装层」的时间轴叠上去,这样字不会被模型画糊,换文案时也只改包装层。
- - 参考视频由 `remake-plan` 切好放在 `remake/refs/`,字幕、花字和常驻文字已经擦掉;首尾帧路线的任务里有 `overlays_in_frames` 警告,先擦掉字再当参考图。
- - 用户自己的商品图、人物图写进 `remake/refs.json`(`{"@图片1": "绝对路径"}`),没给的那句参考会从提示词里去掉。
+ - 从原片取的参考(参考视频、关键帧、首尾帧)在 `remake/refs/`,字幕、花字和常驻文字已经擦掉。
- 换文案时,花字和贴纸按报告里的「按台词定位」放到新文案的对应句子上,不沿用原秒数;「常驻图层」整段叠一次。
**用户自己拍的素材、或在网页上手动生成的视频,拼回原时间线**(不需要 capsule-cinema):
@@ -41,7 +39,7 @@
3. `rea-video remake out/ref`:每段素材整段变速塞进原镜头时长(最多快 3 倍、慢 1.25 倍,超出部分再裁),切点和原片对齐,没填的镜头暂时用原片占位,声音沿用原片;输出 `remake/remake.mp4`、左右对比的 `remake/compare.mp4` 和 `remake/status.md`。告诉用户哪些镜头还是原片占位、声音还要换。只想拼不想重画代码镜头时用 `rea-video assemble out/ref/breakdown.json <results.json 路径>`。
- 字幕叠回(`remake` 默认叠,`assemble` 要加 `--overlays`):把测得的字幕 / 花字 / 标题按原样式叠到换掉的镜头上(原片占位的镜头本来就有字,不重复叠)。字体是通用无衬线体,颜色和底框是测量值,可能和原片有出入;贴纸只在 `assemble_log.json` 的 `stickers_to_add` 里列出来,要自己找素材贴。
-**自动生成**:`remake-plan` 照报告第二部分的方案出任务(用户选的模型、这个模型的真实上限),一个单元一次调用(参考视频 + 参考图 + 提示词),`remake-run` 交给 capsule-cinema 跑完,`remake` 按原片切点拆回各镜头。方案不迁就执行端:capsule-cinema 还没接的模型会在 `remake-run` 时报错,这时把单元提示词和 `remake/refs/` 里的参考视频交给用户在模型自己的平台上生成。
+**自动生成**:`remake-plan` 照报告第二部分的方案出任务(一个单元的每次调用一个任务,用 `remake/prompts.json` 里的最终提示词),方案检查有 ❌ 时不出任务;`remake-run` 交给 capsule-cinema 跑完,`remake` 按原片切点拆回各镜头。方案不迁就执行端:capsule-cinema 还没接的模型会在 `remake-run` 时报错,这时把提示词和 `remake/refs/` 里的参考交给用户在模型自己的平台上生成。
## 对接 capsule-cinema
@@ -49,7 +47,7 @@
```bash
CC=$CAPSULE_CINEMA_ROOT # capsule-cinema 仓库路径
-rea-video remake-plan out/ref/breakdown.json --capsule-root $CC --engine seedance2.0 # 参考原片改写;--labels ai_video 只做 AI 镜头
+rea-video remake-plan out/ref/breakdown.json --capsule-root $CC # 照报告第二部分的方案出任务
rea-video remake-run out/ref/remake/jobs.json --dry-run # 先给用户看任务和费用;--only G2 只跑一个单元
rea-video remake-run out/ref/remake/jobs.json # 用户确认后再跑
rea-video assemble out/ref/breakdown.json out/ref/remake/results.json # 拼回原时间线 + compare.mp4