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 格式输出。
Python agent-skillsai-videoaigc-detectionclaude-codecodexffmpegprompt-engineeringremotionreverse-engineeringshort-videoshot-detectionsubtitlesvideo-analysisvideo-breakdownvideo-editingvideo-generationvideomdvlm
Plan remakes per model and split the report into breakdown and remake
juneed759d83ce81
diff --git a/rea_video/audio.py b/rea_video/audio.pyindex 64a0cb4..646e1d1 100644--- a/rea_video/audio.py+++ b/rea_video/audio.py@@ -563,8 +563,10 @@ def merge_audio_with_vlm(audio: dict, whole: dict | None) -> dict:return {"sfx_merged": sfx[:300], "plan": plan, "mix": whole.get("mix", "")}-def refine_with_stems(audio: dict, vocals_wav: str) -> dict:- """Re-measure the vocal style on the separated dry vocals (no BGM underneath, so pitch tracking is clean)."""+def refine_with_stems(audio: dict, vocals_wav: str, repetition: bool = True) -> dict:+ """Re-measure the vocal style on the separated dry vocals (no BGM underneath, so pitch tracking is clean).+ repetition=False skips the whole-track chorus check: when the voice was found by speech recognition under a+ score, the stem also carries the score's own singing, and only the transcribed stretches belong to the voice."""voice = audio.get("voice") or {}segs = voice.get("segments") or []if not voice.get("present") or not segs:@@ -576,7 +578,10 @@ def refine_with_stems(audio: dict, vocals_wav: str) -> dict:freqs = np.fft.rfftfreq(N_FFT, 1 / SR)beats = np.array((audio.get("music") or {}).get("beats") or [], float)st = vocal_style(x, Sh, freqs, segs, beats)- if st:+ if st and not repetition:+ voice.update(st)+ voice["style_measured_on"] = "vocals_stem"+ elif st:rep = vocal_repetition(x, freqs)st["chorus_repeat_share"] = repif rep > 0.1 and st["style"] == "speech": # repeated melodic lines = a song (rap included); narration does not repeatdiff --git a/rea_video/capabilities/models/video.yaml b/rea_video/capabilities/models/video.yamlindex 13d3fcc..82b1ce1 100644--- a/rea_video/capabilities/models/video.yaml+++ b/rea_video/capabilities/models/video.yaml@@ -77,6 +77,7 @@ models:duration_s: {min: 4, max: 15}resolutions: [720p, 1080p]refs: {image: 9, video: 3, audio: 3}+ ref_video_s: {max: 15} # 参考视频总长# 首帧 / 首尾帧 和 参考素材 不能放在同一个请求里;即梦 App 的「全能参考」可用 @图片 作为首帧exclusive_inputs: [[video.i2v_first_frame, video.i2v_first_last], [video.multi_reference, video.reference_video, video.reference_audio]]audio: {native: true}diff --git a/rea_video/capabilities/schema.json b/rea_video/capabilities/schema.jsonindex 0d471f3..df76e7f 100644--- a/rea_video/capabilities/schema.json+++ b/rea_video/capabilities/schema.json@@ -25,6 +25,7 @@"type": "object", "additionalProperties": false,"properties": {"image": {"type": "integer"}, "video": {"type": "integer"}, "audio": {"type": "integer"}, "total": {"type": "integer"}}},+ "ref_video_s": {"$ref": "#/$defs/range", "description": "Total length of the reference videos one request accepts"},"keyframes": {"type": "integer"},"shots_per_generation": {"type": "integer"},"prompt_tokens": {"type": "integer"},diff --git a/rea_video/cli.py b/rea_video/cli.pyindex 9bc0a1f..2ccc4cf 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport argparseimport jsonimport os+import reimport sysfrom pathlib import Path@@ -84,7 +85,7 @@ def cmd_decompose(args) -> int:if lang not in LANGS:raise SystemExit(f"错误:不支持的报告语言 {lang}(可选:{', '.join(LANGS)})")b = decompose(args.video, out, use_vlm=use_vlm, whole_vlm=not args.no_whole, ocr=not args.no_ocr,- workers=args.workers, engine=args.engine or pref("engine", "seedance2.0"), platform_meta=meta, stems=stems,+ workers=args.workers, engine=args.engine or pref("engine"), platform_meta=meta, stems=stems,packaging=not args.no_packaging, lang=lang, asr=not args.no_asr, max_shots_vlm=max(1, args.max_vlm_shots),speakers=not args.no_speakers)print(json.dumps({"out": str(out), "verdict": b["summary"]["verdict"], "shots": b["summary"]["shots"],@@ -456,7 +457,7 @@ def cmd_summary(args) -> int:base = r["base"]alt = sorted(base["probs"].items(), key=lambda kv: -kv[1])[1]det = r["deterministic"]["probs"]- past = None if base["decided_by"] == "user" else hint_for(max(det, key=det.get), pats)+ past = None if base["decided_by"] == "user" or r.get("review") else hint_for(max(det, key=det.get), pats) # looked at: settledmat = (r.get("material") or {}).get("origin_zh", "")second = T("(用户纠正)", "(user correction)") if base["decided_by"] == "user" else T("(次选 {l} {p:.2f})", "(runner-up {l} {p:.2f})", l=alt[0], p=alt[1])lines.append(f"#{r['index']:>2} {r['start']:7.2f}-{r['end']:7.2f} {base['label']:<14} {base['confidence']:.2f} {second} "@@ -535,6 +536,40 @@ def cmd_correct(args) -> int:return 0+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."""+ from .pipeline import finalize+ from .plan import CAP, Planner, user_capabilities+ from .production import _norm++ 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)+ if not m:+ print(f"rea-video: 能力地图里没有 {args.model}。先查这个模型的官方文档(单次时长、能不能吃参考视频 / 参考图和各几个、"+ f"能不能一次出多镜头、首尾帧、原生音频、提示词写法),按 {CAP / 'models' / 'video.yaml'} 的格式写进 "+ f"{user_capabilities() / 'models' / (re.sub(r'[^a-z0-9.-]+', '-', args.model.lower()) + '.yaml')},再跑一次。"+ "已有的模型:rea-video models", file=sys.stderr)+ return 2+ out = Path(args.out_dir)+ 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))+ 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("模型资料:{src},核实于 {d}", "Model facts: {src}, checked {d}", src="本地补充" if m.get("local") else "能力地图", d=v.get("date") or "?"))+ return 0++def cmd_models(args) -> int:"""List the generation models the capability map knows, or print how to write prompts for one of them."""from .plan import Planner@@ -684,7 +719,7 @@ def main(argv: list[str] | None = None) -> int: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,live_action,avatar,anim_2d,stop_motion")+ 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)")@@ -798,6 +833,11 @@ def main(argv: list[str] | None = None) -> int:co.add_argument("--note", help="用户的原话或理由,例如「这是定格动画,不是 AI」")co.set_defaults(func=cmd_correct)+ 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_.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="把这个拆解目录的复刻方案改按该模型重出(不重新拆解)")diff --git a/rea_video/drive.py b/rea_video/drive.pyindex ab8e650..e48febb 100644--- a/rea_video/drive.py+++ b/rea_video/drive.py@@ -42,15 +42,31 @@ def _ff(args: list[str]) -> None:subprocess.run(["ffmpeg", "-v", "error", "-y", "-nostdin", *args], check=True)-def overlays(b: dict) -> list[dict]:+def overlays(b: dict, persistent: bool = False) -> list[dict]:"""Post-production boxes to erase: subtitles, titles and styled text read steadily, and stickers laid on top- (text that is part of the picture, labels on things, one-off reads and stickers marked as in the picture stay)."""+ (text that is part of the picture, labels on things, one-off reads and stickers marked as in the picture stay).+ persistent=True also erases text that sits unchanged across cuts (disclaimers, licence numbers, corner titles):+ laid on in the edit, never part of a scene, and a reference clip should not carry it."""from .classify import _same_wordspk = b.get("packaging") or {}+ cuts = [r["start"] for r in (b.get("shots") or [])[1:]]++ def laid_on(c: dict) -> bool:+ """Text that holds still through a cut of the source, or sits on the frame's edge: added in the edit, not+ filmed or generated (product lettering moves with the product and changes between shots)."""+ if c.get("follows"):+ return False+ x, y, w, h = c["bbox"]+ if h > 0.1: # lettering this tall is on a thing in the shot (a product held up to the camera), not a caption line+ return False+ edge = y + h > 0.93 or x < 0.04 or x + w > 0.96+ crosses = any(c["t0"] + 0.2 < t < c["t1"] - 0.2 for t in cuts)+ return bool(c.get("persistent")) or crosses or edge+out = []for c in pk.get("text_cues") or []:- if c.get("part_of_picture") or c.get("kind") not in ERASE_KINDS or not c.get("bbox"):+ if c.get("part_of_picture") or not c.get("bbox") or (c.get("kind") not in ERASE_KINDS and not (persistent and laid_on(c))):continueif int(c.get("samples") or 0) < MIN_SAMPLES:continue # a flicker read: printing on a dancer's clothes, caught for a frame or two as it turns past@@ -217,9 +233,9 @@ def _write_depth(model, frames: list[np.ndarray], path: Path, fps: float) -> Nonenc.wait()-def _encoder(path: Path, w: int, h: int, fps: float):+def _encoder(path: Path, w: int, h: int, fps: float, crf: int = 18):return subprocess.Popen(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{w}x{h}", "-r", f"{fps:.4f}",- "-i", "-", "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(path)], stdin=subprocess.PIPE)+ "-i", "-", "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", str(crf), str(path)], stdin=subprocess.PIPE)def _sheet(rows: list[list[np.ndarray]], labels: list[str], path: Path) -> None:@@ -235,6 +251,28 @@ def _sheet(rows: list[list[np.ndarray]], labels: list[str], path: Path) -> None:write_image(path, np.concatenate([np.pad(r, ((0, 0), (0, w - r.shape[1]), (0, 0))) for r in lines], axis=0))+def clean_clip(b: dict, ranges: list[list[float]], path: Path, width: int = 720, crf: int = 26) -> Path:+ """The source over `ranges` (joined when there are several) with subtitles, styled text and stickers erased and no+ sound: a reference video for a remix, so the model takes the shots and pacing but not the old words."""+ src = Path(b["source"]["path"])+ info = video_info(src)+ boxes = overlays(b, persistent=True)+ w, h = scaled_size(info, min(width, info.width or width))+ fps = info.fps if 0 < info.fps <= 60 else 30.0+ path.parent.mkdir(parents=True, exist_ok=True)+ # small: the clip travels inside the request (base64) and only has to show shots, camera and pacing+ enc = _encoder(path, w, h, fps, crf=crf)+ try:+ for a, z in ranges:+ for i, f in enumerate(iter_frames(src, info, w, start=a, duration=z - a, fps=fps)):+ t = a + i / fps+ enc.stdin.write(erase(f, _mask(boxes, t, f.shape[1], f.shape[0]) if boxes else None).tobytes())+ finally:+ enc.stdin.close()+ enc.wait()+ 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/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.pyindex cf7a3b6..f1a5fe1 100644--- a/rea_video/integrations/capsule_cinema.py+++ b/rea_video/integrations/capsule_cinema.py@@ -22,7 +22,8 @@ FORMAT_MAP = {"口播": "short_video", "剧情": "story", "商品展示": "produ"MV": "music_mv", "混剪": "short_video"}CAMERA_ZH = {"static": "固定机位", "static_with_subject_motion": "固定机位、主体运动", "planar_zoom_pan": "整图推拉/平移","handheld_like": "手持晃动", "smooth_move": "平滑运镜", "unknown": "未知"}-AI_LABELS = ("ai_video", "cg_3d", "live_action", "avatar", "anim_2d", "stop_motion")+# 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:@@ -215,14 +216,21 @@ def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path, engine: str | Non"""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 CAPSULE_ENGINES+ from ..plan import engine_rangelabels = labels or list(AI_LABELS)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_jobsfor sh in b["shots"]:+ if sh["index"] in in_units:+ continuelab = sh["base"]["label"]rep = sh["replication"]if lab in ("still_motion", "static_hold"):@@ -242,7 +250,7 @@ def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path, engine: str | Noneng = 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 = CAPSULE_ENGINES.get(eng, (4, 15))+ 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}@@ -267,7 +275,98 @@ def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path, engine: str | Non"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})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++ 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 _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)+ 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)))+ 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())+++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++ 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())+ return out+diff --git a/rea_video/integrations/run_remake.py b/rea_video/integrations/run_remake.pyindex c8fc7f3..ca10b37 100644--- a/rea_video/integrations/run_remake.py+++ b/rea_video/integrations/run_remake.py@@ -33,21 +33,25 @@ def _video_path(res) -> str | None:def main() -> None:ap = argparse.ArgumentParser()ap.add_argument("--jobs", required=True)- ap.add_argument("--only", default="", help="comma-separated shots: 3,5 or shot_003,shot_005")+ ap.add_argument("--only", default="", help="comma-separated shots or units: 3,5 / shot_003 / G2")ap.add_argument("--capsule-root", required=True)ap.add_argument("--dry-run", action="store_true")args = ap.parse_args()jobs_path = Path(args.jobs).expanduser().resolve()spec = json.loads(jobs_path.read_text(encoding="utf-8"))- only = set()+ only, only_units = set(), set()for x in args.only.split(","):x = x.strip()if not x:continue+ u = re.fullmatch(r"G\d+", x, re.I)+ if u:+ only_units.add(x.upper())+ continuem = re.fullmatch(r"(?:shot_?)?0*(\d+)", x, re.I)if not m:- sys.exit(f"--only 看不懂 {x!r}:写镜头序号(3)或镜头 id(shot_003),逗号分隔")+ sys.exit(f"--only 看不懂 {x!r}:写镜头序号(3)、镜头 id(shot_003)或生成单元(G2),逗号分隔")only.add(int(m.group(1)))results_path = jobs_path.with_name("results.json")results = json.loads(results_path.read_text(encoding="utf-8")) if results_path.is_file() else {"results": {}}@@ -62,8 +66,13 @@ def main() -> None:if j.get("executor") == "capsule_cinema" and not od.is_relative_to(out_root):sys.exit(f"shot {j.get('shot')}: output_dir 不在 {out_root} 下,拒绝执行")- todo = [j for j in spec["jobs"] if j["executor"] == "capsule_cinema" and (not only or j["shot"] in only)]- if only and not todo:+ def picked(j: dict) -> bool:+ if not (only or only_units):+ return True+ return j.get("unit") in only_units or bool(only & set(j.get("shots") or [j["shot"]]))++ todo = [j for j in spec["jobs"] if j["executor"] == "capsule_cinema" and picked(j)]+ if (only or only_units) and not todo:have = sorted(j["shot"] for j in spec["jobs"] if j["executor"] == "capsule_cinema")sys.exit(f"--only {args.only} 里没有需要生成的镜头;可生成的镜头序号:{have}")print(f"{len(todo)} generation job(s); run dir {spec['run_dir']}")@@ -71,7 +80,7 @@ def main() -> None:for j in todo:p = dict(j["params"])p["prompt"] = p["prompt"][:120] + ("…" if len(p["prompt"]) > 120 else "")- print(json.dumps({"shot": j["shot"], "label": j["label"], **p}, ensure_ascii=False))+ print(json.dumps({"job": j.get("id", j["shot"]), "shots": j.get("shots") or [j["shot"]], "label": j["label"], **p}, ensure_ascii=False))if j.get("warning"):print(f" ! {j['warning']}")return@@ -81,25 +90,32 @@ def main() -> None:from env_loader import load_video_agent_env # noqa: E402load_video_agent_env(root)- from custom_tools.video_generation.video_generation_tool import UniversalVideoGenerationTool # noqa: E402+ from custom_tools.video_generation import video_generation_tool as vgt # noqa: E402- tool = UniversalVideoGenerationTool()+ tool = vgt.UniversalVideoGenerationTool()failed = []for j in todo:Path(j["params"]["output_dir"]).mkdir(parents=True, exist_ok=True)t0 = time.time()- print(f"shot {j['shot']}: {j['params']['generation_type']} via {j['params']['engine']} ...", flush=True)+ 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:- res = tool._run(**j["params"])+ if j["params"]["generation_type"] == "multimodal": # reference clip + images: the engine's own tool takes these+ 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:+ res = tool._run(**j["params"])except Exception as exc: # keep going, record the failureres = {"error": str(exc)}video = _video_path(res)- results["results"][str(j["shot"])] = {"id": j["id"], "video": video, "raw": res if not video else None,- "seconds": round(time.time() - t0, 1), "trim_to": j["trim_to"]}+ key = j["id"] if j.get("unit") else str(j["shot"]) # a unit's clip covers several shots: assemble splits it+ results["results"][key] = {"id": j["id"], "video": video, "raw": res if not video else None,+ "seconds": round(time.time() - t0, 1), "trim_to": j["trim_to"],+ **({k: j[k] for k in ("unit", "part", "parts", "shots")} if j.get("unit") else {})}results_path.write_text(json.dumps(results, ensure_ascii=False, indent=2, default=str), encoding="utf-8")print(f" -> {video or res}", flush=True)if not video:- failed.append(str(j["shot"]))+ failed.append(key)print(f"results: {results_path}")if failed:sys.exit(f"{len(failed)}/{len(todo)} 个镜头没生成出视频:{', '.join(failed)}(详情见 results.json)")diff --git a/rea_video/layers.py b/rea_video/layers.pyindex d807f59..63022cc 100644--- a/rea_video/layers.py+++ b/rea_video/layers.py@@ -410,7 +410,9 @@ def _advice(diffs: list[dict]) -> list[str]:elif ca > 0:r = cb / caif max(r, 1 / r) >= OFF_RATIO:- tips.append((max(r, 1 / r) / OFF_RATIO, T(f"画上去的量是原片的 {r:.1f} 倍", f"{r:.1f}x as much drawn as the original")))+ tips.append((max(r, 1 / r) / OFF_RATIO,+ T(f"画出来的只有原片的 {r:.0%},有元素漏画或太小", f"only {r:.0%} as much drawn as the original: elements missing or too small") if r < 1 else+ T(f"画出来的是原片的 {r:.1f} 倍,多画了或画得太大", f"{r:.1f}x as much drawn as the original: extra or oversized elements")))for key, zh, en in (("colour", "前景颜色", "drawn colour"), ("ground", "底色", "ground")):cs = [d[key] for d in diffs if key in d]if not cs:diff --git a/rea_video/memory.py b/rea_video/memory.pyindex fc02eec..7bee411 100644--- a/rea_video/memory.py+++ b/rea_video/memory.py@@ -32,7 +32,8 @@ PREF_KEYS = {"lang": "报告和结论的语言:zh(默认)/ en;agent 应按用户提问的语言选,用户明确指定时以指定为准",}ON_OFF = ("on", "off")-HINT_MIN = 2 # a correction pattern becomes a hint once it has been seen this many times+HINT_MIN = 2 # a correction pattern becomes a hint once it has been seen this many times, in this many different videos+# (one video corrected shot by shot says something about that video, not about the tool)def home() -> Path:@@ -225,7 +226,7 @@ def patterns(corrections: list[dict] | None = None) -> list[dict]:def hint_for(tool_label: str, pats: list[dict]) -> str | None:- hits = [p for p in pats if p["tool"] == tool_label and p["count"] >= HINT_MIN]+ hits = [p for p in pats if p["tool"] == tool_label and p["count"] >= HINT_MIN and p.get("videos", HINT_MIN) >= HINT_MIN]if not hits:return Nonereturn semi().join(T("用户过去 {n} 次把工具判的「{a}」改成「{b}」", "users have changed the tool's \"{a}\" to \"{b}\" {n} times before",diff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex ee87a27..0ad406a 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -85,7 +85,7 @@ def decode_fingerprint() -> str:def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False, whole_vlm: bool = True,- ocr: bool = True, workers: int = 3, engine: str = "seedance2.0", max_shots_vlm: int = 60,+ ocr: bool = True, workers: int = 3, engine: str | None = None, max_shots_vlm: int = 60,platform_meta: dict | None = None, stems: bool = True, memory: bool = True, packaging: bool = True, asr: bool = True,lang: str = "zh", speakers: bool = True) -> dict:lang = set_lang(lang)@@ -338,6 +338,11 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,source="vocals_stem" if on_stem else "mix")else:heard = {"ok": False, "reason": "not_installed"}+ if heard.get("ok") and speech.settle(heard, audio.setdefault("voice", {}), info.duration, on_stem=on_stem) and on_stem:+ from .audio import refine_with_stems++ # sung or spoken, measured only where the transcript says someone is heard+ refine_with_stems(audio, stem_info["vocals"], repetition=False)if heard.get("ok") and heard.get("lines"): # how each line is said, for the script and the voice-overfrom . import prosodyfrom .media import extract_audio@@ -625,7 +630,11 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:dance.mark(breakdown) # speech / singing share and product context per shot, for the motion-drive guardout = Path(out)set_lang(breakdown.get("lang", "zh"))- # remember the engine: apply-review / correct / eval call finalize without one and must not reset it+ # 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+ if engine:+ breakdown["engine_chosen"] = Trueengine = 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.pyindex 28e43cf..aa12bf9 100644--- a/rea_video/plan.py+++ b/rea_video/plan.py@@ -8,6 +8,7 @@ from pathlib import Pathimport yamlfrom .i18n import LangDict, T, join, model_name, semi+from .util import LOGCAP = Path(__file__).resolve().parent / "capabilities"@@ -69,7 +70,14 @@ AI_EDITS_EN = { # (what was done, how) in English, same keys as AI_EDITS"object_edit": ("object added / removed / replaced", "after the shoot, change the object in frame with a video-editing model"),"beautify": ("beauty filter / face slimming", "the beauty tools in CapCut, beauty camera apps etc. are enough, no generative model needed"),}-CAPSULE_ENGINES = {"seedance2.0": (4, 15), "minimax-h3": (4, 15)}+def engine_range(engine: str | None, models: dict | None = None) -> tuple[int, int]:+ """Seconds one call of this model can make (min, max), from the capability map; (4, 15) for a name it lacks."""+ key = re.sub(r"[^a-z0-9]", "", str(engine or "").lower())+ for m in (models if models is not None else Planner().models).values():+ if re.sub(r"[^a-z0-9]", "", m["id"].lower()) == key:+ d = (m.get("limits") or {}).get("duration_s") or {}+ return int(d.get("min") or 1), int(d.get("max") or 15)+ return 4, 15def shot_prompts(shot: dict) -> dict:@@ -256,6 +264,13 @@ def CODE_STYLES() -> dict[str, tuple[str, str]]:}+def user_capabilities() -> Path:+ """Where a user's own capability entries live (models looked up after the shipped map was written)."""+ from .memory import home++ return home() / "capabilities"++def _load(name: str):with (CAP / name).open(encoding="utf-8") as f:return yaml.safe_load(f)@@ -266,11 +281,24 @@ class Planner:self.routing = _load("routing.yaml")self.rules = {r["id"]: r for r in self.routing["rules"]}self.models = {}+ notes = _load("prompting.yaml") or {}+ self.prompting: dict[str, dict] = notes.get("models") or {} # how to write prompts for each modelfor f in sorted((CAP / "models").glob("*.yaml")):for m in (yaml.safe_load(f.read_text(encoding="utf-8")) or {}).get("models", []):self.models[m["id"]] = m- notes = _load("prompting.yaml") or {}- self.prompting: dict[str, dict] = notes.get("models") or {} # how to write prompts for each model+ # the user's own entries (~/.rea-video/capabilities/models/*.yaml, written after looking a model up) win over+ # the shipped map: same layout, plus an optional "prompting" block per model+ for f in sorted((user_capabilities() / "models").glob("*.yaml")):+ try:+ doc = yaml.safe_load(f.read_text(encoding="utf-8")) or {}+ except yaml.YAMLError as exc:+ LOG.warning("skipping %s: %s", f, exc)+ continue+ for m in doc.get("models", []) if isinstance(doc, dict) else []:+ if isinstance(m, dict) and m.get("id") and m.get("primitives"):+ self.models[m["id"]] = dict(m, local=str(f))+ if isinstance(m.get("prompting"), dict):+ self.prompting[m["id"]] = m["prompting"]self.keyframe_notes: list[str] = notes.get("keyframes") or [] # frame-picking practice shared by all modelsdef edit_steps(self, edits: list | None) -> list[dict]:@@ -321,7 +349,7 @@ class Planner:plan["references"] = refsplan["note"] += semi() + T("生成时作参考:", "references for generation: ") + join(dict.fromkeys(r["kind_zh"] for r in refs))if executor == "capsule_cinema":- lo, hi = CAPSULE_ENGINES.get(engine, (4, 15))+ 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 ""diff --git a/rea_video/playbook.py b/rea_video/playbook.pyindex 2caf2c9..ed9f818 100644--- a/rea_video/playbook.py+++ b/rea_video/playbook.py@@ -160,8 +160,8 @@ def _content(b: dict) -> str | None:beats = narrative.beats(b)lines = entities.script(b)if beats:- return T("**写内容**:原片分 {k} 段(见「内容与结构」的叙事线),照这个顺序写自己的版本,每段对应的秒数照原片",- "**Write the content**: the original runs in {k} steps (the narrative line under “Content and structure”); write yours in the same order and timing",+ return T("**写内容**:照原片的 {k} 段顺序写自己的版本(叙事线在「内容与结构」)",+ "**Write the content**: write yours in the same {k} steps as the original (narrative line under “Content and structure”)",k=len(beats))n = (b.get("summary") or {}).get("shots") or 0if n <= 1 and not lines:@@ -170,8 +170,8 @@ def _content(b: dict) -> str | None:"**Write the content**: the original is one take; what it says is in the subtitle text under “Packaging layer”; write your own")return T("**写内容**:原片一镜到底,画面内容见分镜表,写自己的版本", "**Write the content**: the original is one take, described in the shot list; write your own")if lines:- return T("**写内容**:原片台词 {k} 句(「声音」里的脚本表),{n} 个镜头,逐镜写自己的画面和台词",- "**Write the content**: the original has {k} lines (script table under “Sound”) over {n} shots; write your picture and line for each shot", k=len(lines), n=n)+ return T("**写内容**:把原片的 {k} 句台词换成自己的话(脚本表在「声音」),画面照分镜表",+ "**Write the content**: replace the original's {k} lines with your own (script table under “Sound”); pictures follow the shot list", k=len(lines))return T("**写内容**:照分镜表的 {n} 个镜头逐镜写自己的画面", "**Write the content**: one picture of your own for each of the {n} shots in the shot list", n=n)@@ -196,30 +196,34 @@ def _material(b: dict, live: bool, refs: bool) -> str | None:return (T("**备素材**:", "**Collect material**: ") + T(";", "; ").join(out)) if out else None+def _first(x: str) -> str:+ """The plain-words head of a measured line: before the first dash, semicolon or full stop."""+ return re.split(r"——|;|; |。|\. ", _after_colon(x), maxsplit=1)[0].strip()++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”."""plan, sp = b.get("production_plan") or {}, b.get("shooting_plan") or {}shoot = plan.get("shoot") or []if not shoot and not sp:return []- L = []- if shoot:- st = sum(len(x.get("setups") or []) for x in shoot)- if len(shoot) > 1 or st > 1:- L.append(T("**排拍摄**:{sc} 个场景、{st} 个机位,同一场景的镜头一起拍,顺序和每个机位要拍哪些镜头见下方「拍摄」",- "**Plan the shoot**: {sc} scenes, {st} camera setups; shoot each scene in one go, the order and the shots per setup are under “Shoot” below",- sc=len(shoot), st=st))- look = [x for x in (_aspect(b, "framing"), _aspect(b, "camera")) if x]+ bits = []+ if len(shoot) > 1:+ bits.append(T("{n} 个场景,同一场景的镜头一起拍", "{n} scenes, shoot each scene in one go", n=len(shoot)))+ look = next((_after_colon(x) for x in sp.get("steps") or [] if x.startswith((T("取景", "Framing")))), "") or _first(_aspect(b, "framing"))if look:- L.append(T("**机位**:{x};画幅 {ar}", "**Camera**: {x}; frame {ar}", x=T(";", "; ").join(look), ar=(b.get("source") or {}).get("aspect_ratio") or ""))- light = _aspect(b, "lighting")- if light:- gear = sp.get("gear") or []- L.append(T("**布光**:原片测得 {l}", "**Light**: measured on the original: {l}", l=light)- + (T("。可以这样打:{g}", ". One way to get it: {g}", g=T(";", "; ").join(gear)) if gear else ""))- grade = _aspect(b, "grade")+ ar = (b.get("source") or {}).get("aspect_ratio") or ""+ bits.append((T("手机竖拍,", "phone held vertical, ") if ar == "9:16" else "") + look)+ light = next((_first(x) for x in sp.get("steps") or [] if x.startswith(T("布光", "Light"))), "") or _first(_aspect(b, "lighting"))+ gear = (sp.get("gear") or [""])[0]+ if light or gear:+ bits.append(T("光:", "light: ") + T(",", ", ").join(x for x in (light, gear) if x))+ grade = _first(_aspect(b, "grade"))if grade:- L.append(T("**调色**:{g}", "**Grade**: {g}", g=grade))- return L+ bits.append(T("调色{g}", "grade: {g}", g=grade))+ if not bits:+ return []+ return [T("**拍摄**:", "**Shoot**: ") + T(";", "; ").join(bits) + T("(机位清单在「拍摄」)", " (setups under “Shoot”)")]def _units(b: dict) -> list[dict]:@@ -227,30 +231,44 @@ def _units(b: dict) -> list[dict]:def _generate(b: dict) -> list[str]:- """Prompts first, then first frames, then the calls: the order a generation actually needs its inputs in."""+ """Generate, then rewrite the prompts for the model actually used: every model reads prompts its own way."""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+ 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 你用哪个,"+ "它按这个模型的能力排好分段、输入和提示词(`rea-video plan <拆解目录> --model <模型>`)",+ "**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):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"))- own = [u for u in units if any(i.get("kind") == "first_frame" and i.get("need") == "yes" and "shot_" in (i.get("source") or "") for i in u.get("inputs") or [])]- chained = [u for u in units if any(i.get("kind") == "first_frame" and i.get("need") == "yes" and "shot_" not in (i.get("source") or "") for i in u.get("inputs") or [])]- if own:- L.append(T("**首帧图**:{k} 个单元从原片首帧起步(`shots/shot_XXX_first.jpg`);换人物、商品或画风时,先照单元里的首帧提示词重画这张图",- "**First frames**: {k} units start from the original's first frame (`shots/shot_XXX_first.jpg`); to change the person, product or look, redraw it from the unit's first-frame prompt first",- k=len(own))- + (T(";另外 {c} 个单元接在上一个单元的尾帧上,要按顺序生成", "; {c} more units start on the previous unit's last frame, so generate them in order", c=len(chained)) if chained else ""))- elif chained:- L.append(T("**按顺序生成**:{c} 个单元接在上一个单元的尾帧上", "**Generate in order**: {c} units start on the previous unit's last frame", c=len(chained)))+ secs = sum(float(u.get("duration") or 0) for u in units)+ chained = any(any(i.get("kind") == "first_frame" and i.get("need") == "yes" and "shot_" not in (i.get("source") or "") for i in u.get("inputs") or [])+ for u in units)native = ((b.get("sound_sources") or {}).get("voice") or {}).get("source") == "ai_video_native"- L.append(T("**生成**:{u} 个生成单元、共 {c} 次 {m},每个单元的提示词、要喂的图和衔接方式见下方「AI 生成」",- "**Generate**: {u} generation units, {c} calls to {m}; each unit's prompt, input images and how it joins the last are under “AI generation” below",- u=len(units), c=plan.get("calls") or len(units), m=model_name(plan.get("model_name")) or T("视频模型", "a video model"))- + (T(";原片的对白是随画面一起生成的,台词写在提示词里", "; the original's dialogue was generated with the picture, so the lines go in the prompt") if native else "")- + T("。可以手动贴到模型网页上生成,也可以让 agent 用 capsule-cinema 自动跑(按调用计费,先试跑看任务和费用)",- ". Paste them into the model's web page by hand, or have the agent run them through capsule-cinema (paid per call; it does a dry run first to show the jobs and cost)"))+ calls = plan.get("calls") or len(units)+ if (plan.get("rules") or {}).get("mode") == "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))+ 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)+ + (T(";有几段接在上一段的尾帧上,按顺序生成", "; some start on the previous unit's last frame, so go in order") if chained else ""))+ 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"))+ 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 "+ "split, how references are addressed, how dialogue is written). 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")+ + (T(";按 {m} 写的要点在「AI 生成」开头", "; notes for {m} at the top of “AI generation”", m=m) if m and plan.get("prompting") else ""))return L@@ -258,6 +276,11 @@ 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"):+ 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 "+ "(`rea-video plan <folder> --model <model>`)", n=n)n = sum(len(u["shots"]) for u in drive)s = sum(u["duration"] for u in drive)k = sum(u["segments_est"] for u in drive)@@ -293,15 +316,17 @@ def _avatar(b: dict) -> str | None:def _code(b: dict) -> str | None:if not (b.get("production_plan") or {}).get("code"):return None- return T("**动效画面**:`rea-video code-remake <报告目录>` 会按测得的版式和动效写出一个能改的工程和第一版成片,改文字和数据后重跑;每段画面元素和动效时间见下方「代码合成」",- "**Motion graphics**: `rea-video code-remake <report dir>` writes an editable project and a first cut from the measured layout and motion; change the text and data and rerun; elements and timing per scene under “Code build” below")+ return T("**动效画面**:让 agent 跑 `rea-video code-remake` 出一版能改的工程,在它上面换文字和画面,不要从零写;"+ "第一版只是起点,和原片差在哪见「代码合成」",+ "**Motion graphics**: have the agent run `rea-video code-remake` for an editable first version and change the text and pictures "+ "on top of it rather than starting from scratch; the first version is only a start, where it differs from the original is under “Code build”")def _local(b: dict) -> str | None:if not (b.get("production_plan") or {}).get("local"):return None- return T("**静图推拉**:换成自己的图,推拉方向和速度用下方「本地重建」里测得的数;`rea-video remake` 会按这些数自动做出来",- "**Stills with moves**: swap in your images and use the measured direction and speed under “Local rebuild” below; `rea-video remake` builds them from those numbers")+ return T("**静图推拉**:换成自己的图,`rea-video remake` 会按原片的推拉方向和速度自动做出来",+ "**Stills with moves**: swap in your images; `rea-video remake` moves them the way the original does")def _footage(b: dict) -> str | None:@@ -319,12 +344,14 @@ def _voice(b: dict) -> str | None:src = _src(b, "voice")k = len(entities.script(b))acted = performance.table(b)[0]- bits = [T("原片是 {s}", "the original is {s}", s=src)] if src else []+ src = src.strip()+ 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 in the script table under “Sound”, with the pace and pauses of each", k=k))+ bits.append(T("{k} 句台词和每句的语速在「声音」的脚本表", "{k} lines with their pace in the script table under “Sound”", k=k))if acted:bits.append(T("语气照「表演与情绪」", "delivery per “Acting and emotion”"))- return (T("**人声**:", "**Voice**: ") + T(";", "; ").join(bits)) if bits else None+ return T("**配音**:", "**Voice**: ") + T(";", "; ").join(bits)def _edit_detail(b: dict) -> list[str]:@@ -344,11 +371,9 @@ def _edit_detail(b: dict) -> list[str]:def _edit(b: dict) -> str:- detail = _edit_detail(b)trans = {k: v for k, v in ((b.get("summary") or {}).get("transitions") or {}).items() if k not in ("start", "cut")}return (T("**剪辑**:按分镜表的顺序和时长剪,{c}", "**Edit**: follow the order and lengths in the shot list; {c}", c=_cut(b))- + (T(";", "; ") + T(";", "; ").join(detail) if detail else "")- + (T(";有 {n} 处不是硬切,位置见下方「剪辑」", "; {n} transitions are not hard cuts, see “Edit” below", n=sum(trans.values())) if trans else ""))+ + (T(";{n} 处转场在「剪辑」", "; {n} transitions under “Edit”", n=sum(trans.values())) if trans else ""))def _packaging(b: dict) -> str | None:@@ -357,15 +382,21 @@ def _packaging(b: dict) -> str | None:subs = [c for c in (b.get("packaging") or {}).get("text_cues") or [] if c.get("kind") == "subtitle"]if not pk and not subs:return None- first = next((x for x in pk if x.startswith((T("字幕", "Subtitle"), T("花字", "Styled"), T("标题", "Title")))), "")- if not first and not subs:- return T("**字幕和花字**:时间和样式见「剪辑包装层」", "**Subtitles and styled text**: timing and style under “Packaging layer”")- out = T("**字幕和花字**:{p}", "**Subtitles and styled text**: {p}", p=first) if first else T("**字幕和花字**:", "**Subtitles and styled text**: ")+ bits = []if subs and files.get("srt"):- out += (T(";", "; ") if first else "") + T("字幕时间轴存成了 `{f}`(标准 SRT),能导入 SRT 的剪辑软件都能直接用,换成自己的话即可",- "the subtitle timing is saved as `{f}` (standard SRT), which any editor that imports SRT can use; replace the words",- f=files["srt"])- return out + T(";其余花字、贴纸的时间和样式见「剪辑包装层」", "; the other styled text and stickers, with timing and style, under “Packaging layer”")+ sub = next((x for x in pk if x.startswith(T("字幕", "Subtitle"))), "")+ style = _first(sub) if sub else ""+ style = T("、", ", ").join(w for w in re.split(r"[、,]\s*", style) if not re.search(r"字高|height", w))+ bits.append(T("字幕导入 `{f}` 换成自己的话", "import `{f}` and replace the words", f=files["srt"])+ + (T(",样式:{s}", ", style: {s}", s=style) if style else ""))+ # counts only ("花字 5 处"), as the verdict states them; what each one is stays under “Packaging layer”+ verdict = str((b.get("summary") or {}).get("verdict") or "")+ rest = [x.strip() for x in re.split(r"[、,]\s*", verdict.split(T("剪辑包装:", "editing package: "))[-1])+ if x.strip().startswith((T("花字", "styled"), T("标题", "title"), T("贴纸", "sticker"))) and re.search(r"\d", x)] if T("剪辑包装:", "editing package: ") in verdict else []+ if rest:+ bits.append(T("、", ", ").join(rest))+ bits.append(T("时间和样式在「剪辑包装层」", "timing and style under “Packaging layer”"))+ return T("**字幕和花字**:", "**Subtitles and styled text**: ") + T(";", "; ").join(bits)def _music(b: dict) -> str | None:@@ -390,19 +421,19 @@ def _music(b: dict) -> str | None:return T("**配乐**:{x};动作是踩着这首歌编的,用原曲(商用先确认版权)或同 BPM、重拍位置一样的曲子,生成和拼回都对着它","**Music**: {x}; the moves were set to this song, so use it (check the rights for commercial use) or one at the same BPM with the ""accents in the same places, and generate and assemble against it", x=x)- return T("**配乐**:{x};找同速度、同情绪的曲子,风格和段落见「声音」", "**Music**: {x}; find a track at the same tempo and mood, style and sections under “Sound”", x=x)+ return T("**配乐**:找同速度、同情绪的曲子({x})", "**Music**: find a track at the same tempo and mood ({x})", x=x)def _sfx(b: dict) -> str | None:sfx = [e for e in (b.get("audio_plan") or {}).get("sfx_merged", []) if not e.get("in_scene")]if not sfx:return None- return T("**音效**:{k} 处,时间点和各自卡在哪个画面事件上见「声音」,每处都能先试听", "**Sound effects**: {k}, with the time and the picture event each one hits under “Sound”; each can be played first",+ return T("**音效**:{k} 处,按「声音」里的时间点从音效库找同类的放上", "**Sound effects**: {k}; place similar ones from a library at the times under “Sound”",k=len(sfx))def _assemble() -> str:- return T("**拼回去对照**:拍好或生成好的镜头交给 agent,用 `rea-video remake` 拼回原时间线,还没做的镜头先用原片占位,会出一条和原片左右并排的对比片",+ return T("**拼回对照**:做好的镜头交给 agent 跑 `rea-video remake`,拼回原时间线(没做的先用原片占位),出一条和原片并排的对比片","**Put it together and compare**: hand the shots you made to the agent; `rea-video remake` places them on the original timeline, keeps the original where yours are missing, and renders a side-by-side comparison with the original")@@ -428,7 +459,7 @@ def steps(b: dict, kind: str, also: str | None = None) -> list[str]:order = [{"content": content, "material": mat}.get(x, x) if isinstance(x, str) else x for x in spec] if spec else Noneif order is None:if live:- order = [content, mat, _shoot, _drive, _voice, _edit, _packaging, _music, _sfx]+ order = [content, mat, _shoot, _generate, _drive, _voice, _edit, _packaging, _music, _sfx]else: # a few live shots inside a generated video get one pointer; a real live share gets the full shoot stepsshoot = _shoot if also in _LIVE_KINDS or kind in _LIVE_KINDS else _shoot_feworder = [content, mat, _generate, _drive, _avatar, shoot, _code, _local, _voice, _edit, _packaging, _music, _sfx]@@ -447,8 +478,8 @@ def md(b: dict) -> list[str]:if not ks:return []main = ks[0][0]- L = [T("这条属于「{k}」。下面每一步的数都是从这条原片测出来的,照着做,做完拿来对照。",- "This is a {k}. Every number in the steps below was measured on the original; follow them and check yours against it.", k=NAME_ZH[main])]+ L = [T("这条属于「{k}」。按下面的顺序做,每步要的细节在后面对应的小节里。",+ "This is a {k}. Do the steps in this order; the detail for each is in the matching subsection below.", k=NAME_ZH[main])]if len(ks) > 1:L[0] += T("另有 {p:.0%} 的时长是「{k}」,步骤里一起列了。", " {p:.0%} of the time is a {k}; its steps are included.", p=ks[1][1], k=NAME_ZH[ks[1][0]])L.append("")diff --git a/rea_video/production.py b/rea_video/production.pyindex 54ab3eb..5683ab9 100644--- a/rea_video/production.py+++ b/rea_video/production.py@@ -141,6 +141,28 @@ def code_motion_md(scenes: list[dict]) -> list[str]:return L+def model_facts(model_id: str | None) -> str:+ """What the plan was built on, in one line: per-call length, multi-shot, reference inputs, native sound, and where+ the facts come from and when they were checked (a model changes; the reader should see how fresh this is)."""+ m = Planner().models.get(model_id or "")+ if not m:+ return T("能力地图里没有这个模型,按通用规则排", "not in the capability map; planned on generic rules")+ 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")+ bits = [T("单次 ≤{s:g} 秒", "≤{s:g} s per call", s=d["max"]) if d.get("max") else "",+ T("一次可出多个镜头", "several shots per call") if "video.multi_shot" in prim else T("一次一个镜头", "one shot per call"),+ (T("能吃参考视频", "takes reference video") + (T("({n} 段", " ({n} clips", n=refs["video"]) if refs.get("video") else "")+ + (T(",总长 ≤{s:g} 秒", ", ≤{s:g} s in all", s=rv) if rv else "") + (T(")", ")") if refs.get("video") else ""))+ if "video.reference_video" in prim else T("不吃参考视频", "no reference video"),+ T("参考图 ≤{n} 张", "≤{n} reference images", n=refs["image"]) if refs.get("image") else "",+ T("首尾帧", "first / last frame") if "video.i2v_first_last" in prim else "",+ T("能直接出声", "native sound") if (m.get("audio") or {}).get("native") else ""]+ v = m.get("verified") or {}+ src = T("本地补充的资料", "your own entry") if m.get("local") else T("能力地图", "capability map")+ return T(",", ", ").join(x for x in bits if x) + T("({src},核实于 {d})", " ({src}, checked {d})", src=src, d=v.get("date") or "?")++# ---------------------------------------------------------------- model choicedef pick_model(planner: Planner, engine: str) -> tuple[dict | None, dict | None]:"""-> (the user's engine as a capability entry, the model the generation units are planned for).@@ -176,7 +198,12 @@ def prompting_md(notes: dict, full: bool = False) -> list[str]:def _limits(m: dict | None) -> dict:lim = (m or {}).get("limits") or {}d = lim.get("duration_s") or {}- return {"max": float(d.get("max") or 10), "min": float(d.get("min") or 0), "refs": lim.get("refs") or {},+ 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)),"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", []),@@ -190,9 +217,11 @@ def _limits(m: dict | None) -> dict: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": "多参考生成"},+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"})+ "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 eachdef _fed(u: dict) -> str:@@ -265,6 +294,23 @@ def _inputs(seg: list[dict], lim: dict, refs: list[dict], prev_id: str | None, preturn 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 editingdef 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@@ -280,7 +326,7 @@ 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) -> list[list[dict]]:+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 inbetween them (UI, screenshots, stills) do not break a run: the generated shots are produced back to backand the inserts are placed in the edit, which is how a talk-plus-UI video is usually made."""@@ -295,7 +341,7 @@ def _runs(shots: list[dict], same_scene, labels: tuple, skip: set[int] | None =runs.append(cur)cur, gap = [], Falsecontinue- joinable = cur and same_scene(cur[-1], r) and (gap or r.get("transition_in") in ("cut", "jump", "flash"))+ 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 = []@@ -331,6 +377,47 @@ def _split_run(run: list[dict], lim: dict, hard: dict, unit_min: float) -> list[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."""@@ -352,7 +439,7 @@ def _style_line(shots: list[dict], aspect_ratio: str) -> str: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) -> dict:+ 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 generatedranges: list[list[float]] = []@@ -378,7 +465,21 @@ def _unit(seg: list[dict], k: int, lim: dict, model: dict | None, style: str, ca"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- if lim["ref_video"] and (not lim.get("exclusive") or product or people):+ # 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)@@ -386,20 +487,28 @@ def _unit(seg: list[dict], k: int, lim: dict, model: dict | None, style: str, ca+ T(":参考动作、运镜和剪辑节奏(只作参考,不复制画面)",": reference for action, camera movement and cutting rhythm (reference only, do not copy the picture)"), "user": False})cont, chained = None, False- if 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:+ 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"]), Trueelif 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 "")- head = [style]+ 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:+ 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:+ 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.0for i, r in enumerate(seg, 1):@@ -415,10 +524,14 @@ def _unit(seg: list[dict], k: int, lim: dict, model: dict | None, style: str, ca"how": performance.ROUTE_ZH[performance.route_kind(act, r["base"]["label"])]})a, z = acc, acc + r["duration"]acc = z- 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)+ # 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} ({a:.1f}-{z:.1f}s): {en}" if len(seg) > 1 else en)+ 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 = 1if len(seg) == 1 and dur > lim["max"]:parts = int(-(-dur // lim["max"]))@@ -429,11 +542,15 @@ def _unit(seg: list[dict], k: int, lim: dict, model: dict | None, style: str, ca"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 "",+ "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- unit["method"], unit["inputs"] = _inputs(seg, lim, refs, prev_unit["id"] if chained else None, parts)+ 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"] = missingif parts > 1:@@ -561,10 +678,15 @@ def production_plan(b: dict, out: Path, engine: str = "seedance2.0") -> dict:motion = dance.motion_indices(b) # the moves are the point: driven from the source motion, not generated from framesunits: list[dict] = []- for run in _runs(shots, same_scene, GEN_LABELS, skip=set(reused) | motion):- for segm in _split_run(run, lim, hard, unit_min):+ # 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))+ 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}"@@ -574,7 +696,7 @@ def production_plan(b: dict, out: Path, engine: str = "seedance2.0") -> dict: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}, "units": units}+ "rules": {"hardcut_s": hard, "same_scene_distance": thr, "mode": "remix" if remix else "frames", "cap_s": cap}, "units": units}gen_shots = sum(len(u["shots"]) for u in units)if units:calls = sum(u["calls"] for u in units)@@ -779,10 +901,17 @@ def report_md(plan: dict) -> list[str]:L += [f"- {plan['engine_note']}"]if plan["units"]:lim = plan["model_limits"]- 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["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"):diff --git a/rea_video/remake.py b/rea_video/remake.pyindex 956921b..2ff2822 100644--- a/rea_video/remake.py+++ b/rea_video/remake.py@@ -134,6 +134,47 @@ def overlay_cues(b: dict, spans: list[tuple[float, float]]) -> tuple[list[dict],return cues, stickers+def unit_shots(b: dict, results: dict, udir: Path, size: tuple[int, int], fps: float) -> dict:+ """Generation-unit clips (one call made several shots: results keyed "G2", or "G4-1", "G4-2" for the parts of a+ long shot) -> one clip per shot. The parts are fitted to their lengths and joined; the shots are then cut at the+ source's own cut points, because the model was given the source stretch and follows its timing.+ A unit is used only when every part of it came back."""+ by_unit: dict[str, list[dict]] = {}+ for v in results.values():+ if isinstance(v, dict) and v.get("unit"):+ by_unit.setdefault(v["unit"], []).append(v)+ if not by_unit:+ return {}+ by_index = {r["index"]: r for r in b["shots"]}+ out: dict[str, dict] = {}+ udir.mkdir(parents=True, exist_ok=True)+ for uid, got in by_unit.items():+ got.sort(key=lambda v: v.get("part", 1))+ if len(got) < int(got[0].get("parts") or 1) or not all(v.get("video") and Path(v["video"]).is_file() for v in got):+ continue+ fitted = []+ for v in got:+ f = udir / f"{uid}_p{v.get('part', 1)}.mp4"+ _fit_clip(Path(v["video"]), f, float(v["trim_to"]), size, fps)+ fitted.append(f)+ whole = fitted[0]+ if len(fitted) > 1:+ lst = udir / f"{uid}.txt"+ lst.write_text("".join(f"file '{f.resolve()}'\n" for f in fitted), encoding="utf-8")+ whole = udir / f"{uid}.mp4"+ _ff(["-f", "concat", "-safe", "0", "-i", str(lst), "-c", "copy", str(whole)])+ t = 0.0+ for i in got[0].get("shots") or []:+ r = by_index.get(i)+ if not r:+ continue+ clip = udir / f"shot_{int(i):03d}.mp4"+ _original_segment(whole, clip, t, r["duration"], size, fps)+ out[str(i)] = {"video": str(clip), "unit": uid}+ t += r["duration"]+ return out++def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = None, overlays: bool = False,code_video: Path | None = None, extra: dict | None = None) -> str:"""code_video: a remake of the code-rendered shots on the original timeline (`code-remake`), cut in for them.@@ -143,7 +184,6 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = Nojobs_path = results_path.with_name("jobs.json")jobs = {j["shot"]: j for j in read_json(jobs_path)["jobs"]} if jobs_path.is_file() else {}results = read_json(results_path).get("results", {}) if results_path.is_file() else {}- results = {**results, **{str(k): v for k, v in (extra or {}).items()}}out_dir = out_dir or results_path.parentseg_dir = out_dir / "segments"seg_dir.mkdir(parents=True, exist_ok=True)@@ -153,6 +193,9 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = Now, h = h, ww, h = w - w % 2, h - h % 2fps = float(b["source"]["fps"]) if b["source"]["fps"] and b["source"]["fps"] <= 60 else 30.0+ results = {**results, **{str(k): v for k, v in (extra or {}).items()}}+ # unit clips (one call, several shots) become per-shot clips; a shot's own clip, given later, still wins+ results = {**unit_shots(b, results, seg_dir / "units", (w, h), fps), **{k: v for k, v in results.items() if not (isinstance(v, dict) and v.get("unit"))}}parts, legend = [], []for sh in b["shots"]:dur = sh["duration"]@@ -223,28 +266,75 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = NoGENERATED = ("ai_video", "cg_3d", "anim_2d", "stop_motion", "avatar")-def _next_step(sh: dict) -> str:+def _asset_words(a) -> str:+ """One thing the user has to bring, in words: kind, where in the frame, what it is."""+ if not isinstance(a, dict):+ return str(a)+ bits = [a.get("where") or "", a.get("description") or ""]+ extra = ",".join(x for x in bits if x)+ return (a.get("kind_zh") or a.get("kind") or "") + (f"({extra})" if extra else "")+++def _needs(sh: dict) -> list[str]:+ """What the user must supply for this shot, minus the shot itself (a live-action shot is its own footage)."""+ lab = sh["base"]["label"]+ out = []+ for a in (sh.get("replication") or {}).get("user_assets") or []:+ if isinstance(a, dict) and lab == "live_action" and a.get("kind") == "real_footage":+ continue+ w = _asset_words(a)+ if w and w not in out:+ out.append(w)+ return out+++def _next_step(sh: dict, plan: dict | None = None) -> str:"""What still has to happen for a shot that is showing the original."""from .i18n import Tlab = sh["base"]["label"]- need = (sh.get("replication") or {}).get("user_assets") or []+ plan = plan or {}+ need = _needs(sh)+ tail = T("(要准备:{a})", " (bring: {a})", a="、".join(need)) if need else ""+ unit = next((u for u in plan.get("units") or [] if sh["index"] in u.get("shots", [])), None)+ scene = next((s for s in plan.get("shoot") or [] if sh["index"] in s.get("shots", [])), None)if (sh.get("replication") or {}).get("executor") == "motion_drive":return T("动作驱动:rea-video drive 出驱动视频,按报告「动作驱动」的路线逐段生成,再 drive --join","motion drive: rea-video drive for the drive clips, generate each segment by a route under “Motion drive”, then drive --join")if lab in GENERATED:+ if unit:+ return T("生成 {u}:用报告「生成单元」{u} 的提示词生成", "generate {u}: use the prompt of generation unit {u} in the report", u=unit["id"]) + tailreturn T("生成:用报告「生成单元」的提示词在网页上手动生成,或 remake-plan + remake-run(计费,先 --dry-run)",- "generate: paste the report's generation-unit prompt into a video model, or remake-plan + remake-run (paid; --dry-run first)")+ "generate: paste the report's generation-unit prompt into a video model, or remake-plan + remake-run (paid; --dry-run first)") + tailif lab == "live_action":- return T("拍摄:按报告的拍摄方案拍", "shoot it: follow the report's shooting plan") + (- T("(要用到:{a})", " (needs: {a})", a="、".join(str(a) for a in need)) if need else "")+ if scene:+ return T("拍摄 {s}:按报告「拍摄场次」{s} 拍", "shoot {s}: follow shooting scene {s} in the report", s=scene["id"]) + tail+ return T("拍摄:按报告的拍摄方案拍", "shoot it: follow the report's shooting plan") + tailif lab == "screen_capture":return T("录屏:按原片的操作重录一遍", "record the screen: redo the same steps")if lab == "film_footage":return T("影视片段:找到原片对应片段(有版权),或换成自己拍的", "film clip: find it in the source (rights apply) or shoot your own")if lab == "code_render":return T("代码渲染:rea-video code-remake 没跑成,先单独跑它看报错", "code render: code-remake did not run; run it alone to see why")- return T("提供素材", "provide the footage")+ return T("提供素材", "provide the footage") + tail+++CODE_DRAFT = 0.6 # a redrawn scene scoring below this against the source is a starting point, not a finished shot+++def _code_scores(out: Path) -> list[dict]:+ """Per-scene scores of the code redraw against the source (code/compare/compare.json), if it was scored."""+ p = out / "code" / "compare" / "compare.json"+ return (read_json(p).get("scenes") or []) if p.is_file() else []+++def _code_score(scores: list[dict], sh: dict) -> dict | None:+ best, ov = None, 0.0+ for sc in scores:+ o = min(sh["end"], sc["end"]) - max(sh["start"], sc["start"])+ if o > ov:+ best, ov = sc, o+ return bestdef remake(out: Path, code: bool = True, overlays: bool = True) -> dict:@@ -278,25 +368,51 @@ def remake(out: Path, code: bool = True, overlays: bool = True) -> dict:how = dict(log["legend"])HOW = {"generated": T("生成 / 你的素材", "generated / your footage"), "code": T("代码重画", "redrawn in code"),"local_still": T("静图按测得的运动重建", "still rebuilt with the measured move"), "original": T("原片占位", "original as stand-in")}+ plan = b.get("production_plan") or {}+ scores = _code_scores(out)rows, todo = [], []for sh in b["shots"]:h = how.get(sh["index"], "original")- nxt = _next_step(sh) if h == "original" else ""+ nxt = _next_step(sh, plan) if h == "original" else ""+ if h == "code":+ sc = _code_score(scores, sh)+ if sc and sc.get("score") is not None and sc["score"] < CODE_DRAFT:+ h = "code_draft"+ nxt = T("代码重画只是初稿(和原片对比 {p:.0%}):在 `code/spec.json` 里改,或照报告「代码合成」重写;{adv}",+ "the code redraw is a first draft ({p:.0%} match): edit `code/spec.json` or rewrite it from “Code composition”; {adv}",+ p=sc["score"], adv=";".join(sc.get("advice") or []) or T("对照 compare.mp4 看差在哪", "compare with compare.mp4"))+ need = _needs(sh)+ if need:+ nxt += T(";直接换成你的:{a}", "; use your own: {a}", a="、".join(need))rows.append({"shot": sh["index"], "start": sh["start"], "end": sh["end"], "label": sh["base"]["label"], "now": h, "next": nxt})if nxt:todo.append(sh["index"])- done = sum(r["end"] - r["start"] for r in rows if r["now"] != "original")+ done = sum(r["end"] - r["start"] for r in rows if r["now"] not in ("original", "code_draft"))total = sum(r["end"] - r["start"] for r in rows) or 1.0- L = [T("# 复刻进度", "# Remake status"), "",- T(f"已经替换 {done / total:.0%} 时长;成片 `remake/{Path(log['remake']).name}`,左右对比 `remake/compare.mp4`。",- f"{done / total:.0%} of the running time replaced; video `remake/{Path(log['remake']).name}`, side by side `remake/compare.mp4`."), "",- T("拿到新的镜头视频(生成的或用户自己的)就写进 `remake/mine.json`:`{\"results\": {\"镜头号\": {\"video\": \"绝对路径\"}}}`,再跑一次 `rea-video remake <目录>`。",- "When a clip comes in (generated or the user's own), add it to `remake/mine.json`: `{\"results\": {\"<shot>\": {\"video\": \"<absolute path>\"}}}`, then run `rea-video remake <folder>` again."),- "", T("| 镜头 | 时间 | 画面类型 | 现在 | 还要做 |", "| Shot | Time | Picture | Now | To do |"), "|---|---|---|---|---|"]+ HOW["code_draft"] = T("代码重画(初稿)", "redrawn in code (draft)")from .classify import LABEL_ZH+ from .i18n import shot_ids+ # the same job for several shots is one line: one generation unit, one shooting scene+ groups: dict[str, list[int]] = {}+ for r in rows:+ if r["next"]:+ groups.setdefault(r["next"], []).append(r["shot"])+ L = [T("# 复刻进度", "# Remake status"), "",+ T(f"已经做好 {done / total:.0%} 时长;成片 `remake/{Path(log['remake']).name}`,左右对比 `remake/compare.mp4`(没做的镜头先用原片占位)。",+ f"{done / total:.0%} of the running time is done; video `remake/{Path(log['remake']).name}`, side by side `remake/compare.mp4` (shots not done yet show the original)."), ""]+ if groups:+ L += [T("## 还要做", "## Still to do"), ""]+ for k, (what, shots_) in enumerate(groups.items(), 1):+ secs = sum(r["end"] - r["start"] for r in rows if r["shot"] in shots_)+ L.append(T("{k}. {w}(镜头 {s},共 {t:.1f}s)", "{k}. {w} (shots {s}, {t:.1f}s)", k=k, w=what, s=shot_ids(shots_), t=secs))+ L.append("")+ L += [T("拿到新的镜头视频(生成的或用户自己的)就写进 `remake/mine.json`:`{\"results\": {\"镜头号\": {\"video\": \"绝对路径\"}}}`,再跑一次 `rea-video remake <目录>`。",+ "When a clip comes in (generated or the user's own), add it to `remake/mine.json`: `{\"results\": {\"<shot>\": {\"video\": \"<absolute path>\"}}}`, then run `rea-video remake <folder>` again."),+ "", T("## 逐镜", "## Shot by shot"), "",+ T("| 镜头 | 时间 | 画面类型 | 现在 |", "| Shot | Time | Picture | Now |"), "|---|---|---|---|"]for r in rows:- L.append(f"| #{r['shot']} | {r['start']:.1f}–{r['end']:.1f}s | {LABEL_ZH.get(r['label'], r['label'])} | {HOW[r['now']]} | {r['next'] or '—'} |")+ L.append(f"| #{r['shot']} | {r['start']:.1f}–{r['end']:.1f}s | {LABEL_ZH.get(r['label'], r['label'])} | {HOW[r['now']]} |")(rdir / "status.md").write_text("\n".join(L) + "\n", encoding="utf-8")write_json(rdir / "status.json", {"replaced_share": round(done / total, 3), "shots": rows})res.update({"remake": log["remake"], "compare": log["compare"], "status": str(rdir / "status.md"),diff --git a/rea_video/report.py b/rea_video/report.pyindex 63208c8..d57dd85 100644--- a/rea_video/report.py+++ b/rea_video/report.py@@ -204,11 +204,18 @@ def _readers(b: dict) -> str:if any(r["base"]["decided_by"] == "user" for r in b["shots"]):bits.append(T("用户纠正", "user corrections"))out = " + ".join(bits)- if status in ("failed", "not_configured"):+ if status in ("failed", "not_configured") and not rv.get("shots"):out += T("(AI 看图没有生效,只靠工具)", " (AI image reading did not run; tools only)")return out+def _unseen(b: dict) -> bool:+ """Nobody (no VLM, no reviewer, no user) looked at the picture: the kind of each shot is pixel statistics only."""+ info, rv = b["analysis"]["vlm"], b["analysis"].get("review") or {}+ looked = (info.get("status") or ("ok" if info.get("used") else "off")) in ("ok", "partial")+ return not looked and not rv.get("shots") and not any(r["base"]["decided_by"] == "user" for r in b["shots"])++def _mmss(sec: float) -> str:sec = float(sec or 0)return f"{int(sec // 60)}:{int(sec % 60):02d}"@@ -233,6 +240,12 @@ def _head_md(b: dict) -> list[str]:L += ["", T("- {d} · {o} {ar} · {n} 个镜头,平均 {avg} 秒一个", "- {d} · {o} {ar} · {n} shots, {avg}s each on average",d=_mmss(src["duration"]), o=orient, ar=src["aspect_ratio"], n=s["shots"], avg=f"{float(s['avg_shot_s']):.1f}"),T("- 判断可靠度 {c:.0%},依据:{by}", "- Confidence {c:.0%}, based on: {by}", c=s["confidence"], by=_readers(b))]+ if _unseen(b):+ L.append(T("- ⚠️ **画面还没有人看过**:实拍 / AI / 3D / 代码渲染只靠像素统计,平台转码后经常整体判错。"+ "先开 VLM 或让 agent 看图复核(`rea-video review`),再按这份报告去复刻",+ "- ⚠️ **Nobody has looked at the picture yet**: live action / AI / 3D / code render come from pixel statistics only and are "+ "often wrong across the board after platform transcoding. Turn on a VLM or have an agent review the shots "+ "(`rea-video review`) before remaking from this report"))qs = entities.open_questions(b)if qs:L.append(T("- ⚠️ 有 {n} 处拿不准,见「不确定点」", "- ⚠️ {n} points are uncertain, see “Open questions”", n=len(qs)))@@ -430,12 +443,22 @@ def _edit_md(b: dict) -> list[str]:return L+def _units_needed(b: dict) -> bool:+ """Shots a video model has to make (generated, or driven from the source motion)."""+ p = b.get("production_plan") or {}+ return bool(p.get("units") or p.get("drive"))++def _plan_md(b: dict) -> list[str]:"""The remake as one section: a short checklist, then the detail of each step in the same order."""from .production import report_partsplan = b.get("production_plan") or {}parts = report_parts(plan) if plan else {}+ chosen = bool(b.get("engine_chosen"))+ 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)steps: list[str] = []subs: list[str] = []@@ -466,7 +489,14 @@ def _plan_md(b: dict) -> list[str]:pre = parts.get("pre", [])if pre: # grouping rules, the model's prompt conventions, the input primer: needed when writing prompts, not to follow the stepspre = ["", f'<details class="ref"><summary>{html.escape(T("写提示词前看:分组规则、模型写法、能喂哪些输入", "Before writing prompts: grouping, the model's conventions, what it takes as input"))}</summary>', ""] + pre + ["", "</details>", ""]- sub(T("AI 生成", "AI generation"), [f"**{plan['summary'].split(T(';', '; '))[0]}**", ""] + pre + parts["units"])+ 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"])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"])@@ -492,9 +522,24 @@ def _plan_md(b: dict) -> list[str]:steps.append(T("**声音**:见「声音」,每处音效都能先试听", "**Sound**: see “Sound”; every effect can be played first"))steps.append(T("**对照检查**:成片和原片并排看一遍:镜头长短、字幕位置、音乐起落对不对得上","**Compare**: watch yours next to the original: shot lengths, subtitle positions, where the music comes in and drops"))- head = ["", T("## 自己复刻:按这个顺序做", "## Remake it yourself: do it in this order"), "",- T("复刻的是做法和节奏,不是照抄画面:保留每一段在讲什么,换成自己的内容和素材。",- "Copy the method and the rhythm, not the pictures: keep what each part does and fill it with your own content and material."), ""]+ from .production import model_facts++ head = ["", T("# 第二部分 · 复刻方案", "# Part two · Remake plan"), ""]+ if chosen and plan.get("units"):+ 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"))), ""]+ elif _units_needed(b):+ head += [T("> 还没选视频模型。AI 镜头怎么分段、一次能出多长、能不能直接拿原片当参考、提示词怎么写,每个模型都不一样,"+ "所以这部分要按你实际用的模型来排:告诉 agent 你用哪个模型或平台(即梦 / Seedance、可灵、Veo、海螺……),"+ "它会查这个模型的最新资料,跑 `rea-video plan <拆解目录> --model <模型>` 把方案补进来。",+ "> No video model chosen yet. How the AI shots are grouped, how long one call can be, whether the source can be fed as a "+ "reference and how prompts are written all differ by model, so this part is planned for the model you will use: tell the "+ "agent which model or platform (Seedance, Kling, Veo, Hailuo…); it looks the model up and runs "+ "`rea-video plan <folder> --model <model>` to fill this in."), ""]+ head += [T("## 自己复刻:按这个顺序做", "## Remake it yourself: do it in this order"), "",+ T("复刻的是做法和节奏,不是照抄画面:保留每一段在讲什么,换成自己的内容和素材。",+ "Copy the method and the rhythm, not the pictures: keep what each part does and fill it with your own content and material."), ""]guide = playbook.md(b)if guide:return head + guide + subs@@ -920,7 +965,6 @@ def _clock(t: float) -> str:def _shotlist_md(b: dict) -> list[str]:- units = _unit_of(b)told = narrative.shot_roles(b)rows = []for r in b["shots"]:@@ -932,13 +976,13 @@ def _shotlist_md(b: dict) -> list[str]:pic = a.get("first_frame") or a.get("sheet") # one frame reads at thumbnail size; the contact sheet is in the appendixrows.append([r["index"], f"![#{r['index']}]({pic})" if pic else "—", _clock(r["start"]), f"{r['duration']:.1f}s", *([says[:48] + ("…" if len(says) > 48 else "") or "—"] if told else []),desc[:40] + ("…" if len(desc) > 40 else "") or "—", CAMERA_ZH.get(r["features"].get("camera", "unknown"), "—"), _layers(r),- f"{base['label_zh']} {base['confidence']:.0%}", _origin(r, brief=True), _route(r, units)])+ f"{base['label_zh']} {base['confidence']:.0%}", _origin(r, brief=True)])return ["", T("## 分镜表", "## Shot list"), "",T("「画面」「运镜」「叠加层」是画面里看得到的;「制作方式」「素材来源」是工具推断的,依据见附录逐镜取证。","Picture, Camera and Overlays are what is visible on screen; Made with and Material are the tools' inference, with the basis in the shot-by-shot appendix.")] + _table(["#", T("截图", "Frames"), T("时间", "Time"), T("时长", "Length"), *([T("在讲什么", "What it says")] if told else []),T("画面", "Picture"), T("运镜", "Camera"), T("叠加层", "Overlays"),- T("制作方式(推断)", "Made with (inferred)"), T("素材来源(推断)", "Material (inferred)"), T("复刻", "Remake")], rows)+ T("制作方式(推断)", "Made with (inferred)"), T("素材来源(推断)", "Material (inferred)")], rows)def _questions_md(b: dict) -> list[str]:@@ -1035,8 +1079,12 @@ def _appendix_md(b: dict) -> list[str]:def markdown(b: dict) -> str:# what it is and why it works, how it is told and cut, how to remake it, then the reference detail- L = (_head_md(b) + _highlights_md(b) + _layers_md(b) + _content_md(b, user=True) + _shotlist_md(b) + _plan_md(b)- + _cast_md(b) + _visual_md(b, user=True) + packaging_md(b) + _audio_md(b) + _questions_md(b) + _appendix_md(b))+ # part one is the breakdown (what is there and how it was made, the same whatever model you use); part two is the+ # remake, planned for one model; the reference detail closes the report+ part1 = ["", T("# 第一部分 · 拆解:这条视频的结构", "# Part one · Breakdown: how this video is built"), ""]+ L = (_head_md(b) + part1 + _highlights_md(b) + _layers_md(b) + _content_md(b, user=True) + _shotlist_md(b)+ + _cast_md(b) + _visual_md(b, user=True) + packaging_md(b) + _audio_md(b) + _questions_md(b)+ + _plan_md(b) + _appendix_md(b))return re.sub(r"\n{3,}", "\n\n", "\n".join(L)).strip() + "\n"diff --git a/rea_video/speech.py b/rea_video/speech.pyindex 6570044..d6804d6 100644--- a/rea_video/speech.py+++ b/rea_video/speech.py@@ -246,6 +246,8 @@ def transcribe(audio: str | Path, language: str | None = None, threads: int = 2,got = [dict(ln, speaker=who) for ln in got] if who else gotif emotion: # SenseVoice hears it per stretch; every sentence cut from the stretch shares itgot = [dict(ln, emotion=emotion) for ln in got]+ if heard:+ got = [dict(ln, lang=heard) for ln in got]lines += gotif heard:langs.append(heard)@@ -254,3 +256,65 @@ def transcribe(audio: str | Path, language: str | None = None, threads: int = 2,return {"ok": False, "reason": f"{type(exc).__name__}: {str(exc)[:120]}"}return {"ok": True, "engine": engine, "language": "bn" if lang == "bn" else (max(set(langs), key=langs.count) if langs else ""),"lines": lines}+++CJK = re.compile(r"[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]")+SCRIPT_OF = {"zh": "han", "yue": "han", "ja": "kana", "ko": "hangul", "en": "latin"}+++def _size(text: str) -> int:+ """How much was said: CJK / kana / hangul characters, plus Latin-script words."""+ return len(CJK.findall(text)) + len(re.findall(r"[A-Za-z\u00c0-\u024f\u0980-\u09ff]+", CJK.sub(" ", text)))+++def _script(text: str) -> str:+ if re.search(r"[\u3040-\u30ff]", text):+ return "kana"+ if re.search(r"[\uac00-\ud7af]", text):+ return "hangul"+ if re.search(r"[\u3400-\u9fff]", text):+ return "han"+ return "latin"+++def settle(heard: dict, voice: dict, duration: float, on_stem: bool = False) -> bool:+ """Drop what the recognizer guessed and say whether there is speech after all.++ Over music or effects a recognizer still writes something: one syllable, often in another language+ ("あ。" in an English film, "Okay." over a song). A line of three words or more, written in the video's+ language, is speech. When enough such lines come back the track has speech even if the signal-level detector+ missed it (narration mixed under a loud score): voice is then rewritten from the transcript and True is returned.+ Short lines are kept only when there is speech and they are in its language.+ The other way round: the signal detector also fires on sounds in the voice band (unboxing, rustling, a crowd).+ When the recognizer, run on the separated vocal stem, hears not a single word, a spoken voice is not there."""+ lines = heard.get("lines") or []+ if not heard.get("ok"):+ return False+ if not lines:+ if on_stem and voice.get("present") and not voice.get("sung"):+ voice.update(present=False, detected_by="speech_recognition", unheard_ratio=voice.get("ratio"), ratio=0.0,+ unheard_segments=voice.get("segments") or [], segments=[])+ return False+ scripts = [_script(ln.get("text", "")) for ln in lines]+ weight: dict[str, int] = {}+ for ln, sc in zip(lines, scripts):+ weight[sc] = weight.get(sc, 0) + _size(ln.get("text", ""))+ main = SCRIPT_OF.get(heard.get("language") or "") or max(weight, key=weight.get)++ def native(sc: str) -> bool:+ return sc == main or (main == "kana" and sc == "han") # Japanese lines may be all kanji++ real = [ln for ln, sc in zip(lines, scripts) if _size(ln.get("text", "")) >= 3 and native(sc)]+ said = sum(ln["end"] - ln["start"] for ln in real)+ turned = False+ if not voice.get("present") and len(real) >= 3 and said >= max(8.0, 0.04 * duration):+ # sentences are talk unless the vocal stem says otherwise (decompose re-measures on these stretches only)+ voice.update(present=True, ratio=round(said / max(duration, 1e-6), 3),+ segments=[[ln["start"], ln["end"]] for ln in real][:80], detected_by="speech_recognition",+ style="speech", sung=False, style_measured_on="speech_recognition")+ turned = True+ keep = [ln for ln, sc in zip(lines, scripts) if native(sc) or _size(ln.get("text", "")) >= 6] if voice.get("present") else []+ if len(keep) < len(lines):+ heard["dropped"] = len(lines) - len(keep)+ heard["lines"] = keep+ return turneddiff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.mdindex fdc8d1d..c177e48 100644--- a/skills/rea-video/SKILL.md+++ b/skills/rea-video/SKILL.md@@ -96,7 +96,14 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复## 3. 复刻(需要时)-用户要自己动手做时,先给报告「自己复刻」开头的「照着做」步骤(按视频类型排的顺序,内容全是这条原片的测量值),不要先讲模型规则和输入表。+报告分两部分:第一部分是拆解(结构,和用什么模型无关),第二部分是复刻方案(按一个模型排)。拆解不要因为复刻去合并镜头。++有 AI 镜头时,复刻方案要按用户实际用的模型来排:+1. 先问用户用哪个模型或平台(即梦 / Seedance、可灵、Veo、海螺……),不要替用户选。+2. 方案按这个模型的最新实际情况来:`rea-video models <id>` 看能力地图里的资料和核实日期,再上网核对它最新的官方文档和更新(有没有新版本,单次时长、参考视频 / 参考图的数量和时长、一次多镜头、首尾帧、原生音频、提示词写法有没有变)。能力地图里没有、或和最新资料不一致的,按能力地图的格式写进 `~/.rea-video/capabilities/models/<id>.yaml`(同 id 会覆盖自带的),写上来源和核实日期。+3. `rea-video plan out/ref --model <id>`:按这个模型重出报告第二部分,能吃参考视频的模型会把原片对应段擦掉字幕切好放在 `remake/refs/`。++用户要自己动手做时,先给报告第二部分「照着做」的步骤,不要先讲模型规则和输入表。先跑 `rea-video remake out/ref`:能自动做的镜头先做掉(代码渲染重画、静图重建),其余原片占位,拼回原时间线,`remake/status.md` 逐镜写了还要做什么;拿到新镜头写进 `remake/mine.json` 再跑一次。细节见 `references/remake.md`;可用的工具和方式(capsule-cinema、ChatCut、自己动手)和各自的特点列在 `references/remake-tools.md`。在本工具里直接跑:AI 镜头走 capsule-cinema(会计费,先 `rea-video remake-run --dry-run` 并征得用户同意);实拍给拍摄方案;舞蹈 / 动作镜头用 `rea-video drive out/ref` 出驱动视频(见 `references/remake.md`);代码渲染先跑 `rea-video code-remake out/ref` 出第一版(可改的工程 + 成片 + 打分),在它上面改,不要从零写;用户自己的素材用 `rea-video assemble` 拼回原时间线。代码渲染和用户自己的素材也可以在 ChatCut 里做。diff --git a/skills/rea-video/references/output-template.md b/skills/rea-video/references/output-template.mdindex 9690fa8..cbff578 100644--- a/skills/rea-video/references/output-template.md+++ b/skills/rea-video/references/output-template.md@@ -2,15 +2,17 @@## 原则-- 先给一句话结论(这条视频是怎么做出来的),再用两三行说内容和角色(讲什么、主要角色 / 场景 / 商品,`report.md`「角色、场景与道具」一节),再给**复刻方案**(`breakdown.json` 的 `production_plan`,报告里「复刻方案」一节),然后才是分镜表。-- 复刻方案先给「照着做」:报告「自己复刻」开头(拆片包 `video/remake.md`「照着做」)已按视频类型(口播、桌拍、AI 短片、卡点混剪等 15 类)排好步骤,每步都是这条原片的测量值和本工具的文件 / 命令,原样转述,不添加测量之外的经验数字;类型判错时说明,按正确类型的顺序给。-- 然后按实际制作的组织方式写,不按剪辑镜头逐个写:+- 回复和报告一样分两块,不混在一起:+ - **拆解**:一句话结论(这条视频是怎么做出来的),两三行内容和角色(讲什么、主要角色 / 场景 / 商品),分镜结构,剪辑包装,声音,真实素材,不确定点。逐镜写,不按生成方式合并镜头。+ - **复刻方案**:按用户选的模型(报告第二部分,`rea-video plan` 出的)。用户还没选、又有 AI 镜头时,先问用哪个模型,不要替他选一个出方案。+- 复刻方案先给「照着做」:报告第二部分开头(拆片包 `video/remake.md`「照着做」)已按视频类型排好步骤,原样转述,保持简短:每步一句,用户照着就能动手,测量数字留在报告小节里;类型判错时说明,按正确类型的顺序给。写明方案是按哪个模型的哪些能力排的(报告第二部分第一句)。+- 有 AI 生成镜头时提醒一句:报告里的提示词是通用结构,生成前按这个模型的官方提示词指南或对应的提示词 skill 再改一遍。+- 复刻方案按实际制作的组织方式写,不按剪辑镜头逐个写:- AI 镜头 → **生成单元**:几个连续镜头一次生成、用哪个模型、参考素材(`@图片` 产品/人物、`@视频` 原片片段)、合并后的多镜头提示词、单元之间怎么衔接。默认引擎不支持一次多镜头时,照抄 `engine_note`,说明换模型能省几次调用。- 实拍镜头 → **拍摄场次**:哪些镜头是同一场景、同一机位,一起拍;每个场景的布光;先大景别后特写。分镜表本身仍然逐镜写细。- 有人在演的镜头 → 写清每镜的情绪和表演怎么还原(报告「表演与情绪」:表情、动作、语气,以及是首帧定表情、先配音再驱动、表演迁移还是演员照着演)。- 代码渲染 → 几段代码合成,每镜写清画面元素和动效(报告「代码合成」一节的逐镜动效时间轴:元素位置、出现时间、方向、快慢、色值,元素截图在 `shots/`);静图推拉 → 本地重建。- 提示词缺失(未开 VLM)时,你看图补写:`rea-video review` 的答案里每镜填 `replication.image_prompt / video_prompt / video_prompt_en`,`apply-review` 后生成单元会自动带上。-- 然后写剪辑包装(字幕样式和时间轴文件、花字 / 贴纸清单、音效卡点)、声音拆解、真实素材清单,最后写不确定点。- 报告文件路径(`report.html`)写给用户。有代码渲染镜头、用户要复刻时,告诉用户复刻要用整个报告目录(`shots/` 里的元素截图和关键帧条、`packaging/` 里的字幕文件),只给 HTML 或 PDF 会缺单张截图。不要把 breakdown.json 整段贴进对话。## 语言diff --git a/skills/rea-video/references/remake.md b/skills/rea-video/references/remake.mdindex 8a52804..17d3522 100644--- a/skills/rea-video/references/remake.md+++ b/skills/rea-video/references/remake.md@@ -19,7 +19,7 @@## 各类镜头怎么复刻-- **AI 类镜头**:用原镜头首尾帧加 VLM 提示词,通过 [capsule-cinema](https://github.com/JuneYaooo/capsule-cinema) 生成(会计费,先 `--dry-run`,并征得用户同意)。+- **AI 类镜头**:模型能吃参考视频时(Seedance、Kling 等),默认「参考原片改写」:原片里连着的 AI 镜头连成一段,每段一次生成(不超过模型单次上限),这段原片擦掉字幕后当 `@视频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,17 +30,18 @@- **表演和情绪**:报告「表演与情绪」一节逐镜写了情绪、表情、动作和语气,生成单元的提示词里已经带上表情和动作。改写提示词时保留看得见的表情和动作,不要换成「开心」「难过」这类词,也不要把幅度写大;有台词的镜头先做有语气的配音,再让画面跟着声音演。- **声音**:TTS(按脚本表里每句的语气)、BGM(按 BPM / 调性 / 情绪)、音效(按时间点)三条轨分别准备。- **剪辑包装(字幕、花字、贴纸)**:不进生成。生成模型只出干净的人和画面,包装层最后按「剪辑包装层」的时间轴叠上去,这样字不会被模型画糊,换文案时也只改包装层。- - 首尾帧上带着原片字幕的,`remake-plan` 的任务里有 `overlays_in_frames` 和警告:先擦掉字再当参考图,否则生成画面会照抄原字幕。+ - 参考视频由 `remake-plan` 切好放在 `remake/refs/`,字幕、花字和常驻文字已经擦掉;首尾帧路线的任务里有 `overlays_in_frames` 警告,先擦掉字再当参考图。+ - 用户自己的商品图、人物图写进 `remake/refs.json`(`{"@图片1": "绝对路径"}`),没给的那句参考会从提示词里去掉。- 换文案时,花字和贴纸按报告里的「按台词定位」放到新文案的对应句子上,不沿用原秒数;「常驻图层」整段叠一次。**用户自己拍的素材、或在网页上手动生成的视频,拼回原时间线**(不需要 capsule-cinema):1. 按分镜表(`report.md` 的镜头号和时长)把素材对应到镜头。一条长素材覆盖多个镜头时,先用 ffmpeg 按动作切开;拿不准对应关系时给用户看截图确认。-2. 写进 `out/ref/remake/mine.json`:`{"results": {"<镜头号>": {"video": "<素材绝对路径>"}, ...}}`。手动生成的「生成单元」视频覆盖多个镜头时,同样先按单元提示词里的「镜头i(a–b s)」时间切开再填。+2. 写进 `out/ref/remake/mine.json`:`{"results": {"<镜头号>": {"video": "<素材绝对路径>"}, ...}}`。手动生成的「生成单元」视频覆盖多个镜头时,写成 `{"G2": {"unit": "G2", "shots": [4, 5, 6], "video": "<路径>", "trim_to": <单元秒数>}}`,`remake` 会按原片切点拆回各个镜头。3. `rea-video remake out/ref`:每段素材整段变速塞进原镜头时长(最多快 3 倍、慢 1.25 倍,超出部分再裁),切点和原片对齐,没填的镜头暂时用原片占位,声音沿用原片;输出 `remake/remake.mp4`、左右对比的 `remake/compare.mp4` 和 `remake/status.md`。告诉用户哪些镜头还是原片占位、声音还要换。只想拼不想重画代码镜头时用 `rea-video assemble out/ref/breakdown.json <results.json 路径>`。- 字幕叠回(`remake` 默认叠,`assemble` 要加 `--overlays`):把测得的字幕 / 花字 / 标题按原样式叠到换掉的镜头上(原片占位的镜头本来就有字,不重复叠)。字体是通用无衬线体,颜色和底框是测量值,可能和原片有出入;贴纸只在 `assemble_log.json` 的 `stickers_to_add` 里列出来,要自己找素材贴。-**自动生成的限制**:`remake-plan` 和 capsule-cinema 目前还是一个镜头调一次模型;报告里「生成单元」的多镜头提示词要用户手动贴到支持多镜头的模型(如即梦 / Seedance 2.5)上用。向用户说明这一点,并给出两种做法的调用次数。+**自动生成**:`remake-plan` 照报告第二部分的方案出任务(用户选的模型、这个模型的真实上限),一个单元一次调用(参考视频 + 参考图 + 提示词),`remake-run` 交给 capsule-cinema 跑完,`remake` 按原片切点拆回各镜头。方案不迁就执行端:capsule-cinema 还没接的模型会在 `remake-run` 时报错,这时把单元提示词和 `remake/refs/` 里的参考视频交给用户在模型自己的平台上生成。## 对接 capsule-cinema@@ -48,8 +49,8 @@```bashCC=$CAPSULE_CINEMA_ROOT # capsule-cinema 仓库路径-rea-video remake-plan out/ref/breakdown.json --capsule-root $CC --engine seedance2.0 # 也可以 --mode image_to_video / --labels ai_video-rea-video remake-run out/ref/remake/jobs.json --dry-run # 先给用户看任务和费用+rea-video remake-plan out/ref/breakdown.json --capsule-root $CC --engine seedance2.0 # 参考原片改写;--labels ai_video 只做 AI 镜头+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.mp4rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name xxx [--write-capsule]