Skip to content

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

剪辑包装跟着台词走:花字、标题、贴纸标出落在哪句字幕上,跨切镜的常驻图层单独列出 - 复刻任务标出带原片字幕的参考帧,提醒先擦掉再生成;复刻方案说明包装层不进提示词 - assemble --overlays 把测得的字幕、花字、标题叠回换掉的镜头,贴纸列在 assemble_log.json - 竖排小字按竖排导出 ASS,字号不超过测得的文字框

junee9a3f0d590c4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0b0fc7b..15e568d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,19 @@
# 更新记录
+## 剪辑包装跟着台词走
+
+口播、带货这类片子,画面里的字幕、花字、贴纸大多跟着说的话出现。这一版把包装层和台词对上,复刻时生成模型只出干净的画面,包装层后叠。
+
+**拆解**
+- 按台词定位:花字、标题、贴纸落在哪句字幕上,句中第几秒,有没有重复句里的词(「五折」花字落在「全场五折」这句上)。换文案时按句子放,不按原秒数。只认说话那一条字幕;画面里的字、OCR 杂讯不参与。
+- 常驻图层:跨切镜不变的免责声明、标题栏、角标单独列出,同一段文字多次出现合成一个,复刻时整段叠一次。
+- 竖排小字导出 ASS 时按竖排输出,字号不超过测得的文字框。
+
+**复刻**
+- `remake-plan`:首尾帧上带着原片字幕、花字或贴纸的镜头,任务里标出 `overlays_in_frames` 并提醒先擦掉再生成,`--dry-run` 会打印出来。
+- 复刻方案里,生成单元镜头上有包装层时多一条说明:包装层不写进提示词,生成后叠回。
+- `assemble --overlays`:把测得的字幕、花字、标题按原样式叠到换掉的镜头上,原片占位的镜头不重复叠;贴纸列在 `assemble_log.json` 里。
+
## 切点检测
剪辑节奏复刻靠切点。切点漏了,镜头时长、卡点、复刻时间轴都会跟着偏。这一版重写了切点判断,复刻时生成片段按整段变速对齐原镜头。
diff --git a/docs/cli.md b/docs/cli.md
index 904f7b8..46020f1 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -71,12 +71,13 @@ rea-video stems ref.mp4 -o out/ref
CC=~/code/github/capsule-cinema # capsule-cinema 仓库;也可以设 CAPSULE_CINEMA_ROOT,或 rea-video prefs capsule_root $CC 设一次,之后不用再带 --capsule-root
rea-video remake-plan out/ref/breakdown.json --capsule-root $CC # AI 类镜头 → 首尾帧生成任务
rea-video remake-run out/ref/remake/jobs.json # 调 capsule-cinema 生成(会计费,可先 --dry-run)
-rea-video assemble out/ref/breakdown.json out/ref/remake/results.json # 按原时间线拼回 + 对比片
+rea-video assemble out/ref/breakdown.json out/ref/remake/results.json # 按原时间线拼回 + 对比片;加 --overlays 把字幕和花字叠回换掉的镜头
rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name my_remake
```
- 静态图推拉和静帧:不调模型,本地用测得的缩放和平移参数精确重建。
- 代码渲染和录屏:报告给出文字轨和版式,用 Remotion 重建。
+- 字幕、花字、贴纸:不进生成提示词。参考帧上带着原字幕的镜头,`remake-plan` 会提醒先擦掉;生成完用 `assemble --overlays` 叠回。
- `capsule-draft`:通过 capsule-cinema 自带的 `tool_factory` 注入拆解结果,生成可复用的配方草稿,不需要改 capsule-cinema 的代码。
见 [capsule-cinema.md](capsule-cinema.md)。
diff --git a/rea_video/cli.py b/rea_video/cli.py
index deda90d..da0a16f 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -219,7 +219,7 @@ def cmd_capsule_draft(args) -> int:
def cmd_assemble(args) -> int:
from .remake import assemble
- print(assemble(Path(args.breakdown), Path(args.results), Path(args.out) if args.out else None))
+ print(assemble(Path(args.breakdown), Path(args.results), Path(args.out) if args.out else None, overlays=args.overlays))
return 0
@@ -477,6 +477,8 @@ def main(argv: list[str] | None = None) -> int:
a.add_argument("breakdown")
a.add_argument("results", help="remake-run 输出的 results.json(或自己写的同格式文件)")
a.add_argument("-o", "--out")
+ a.add_argument("--overlays", action="store_true",
+ help="把测得的字幕 / 花字 / 标题按原样式叠回换掉的镜头(保留原片的镜头本来就有);贴纸只列出来,要自己找素材")
a.set_defaults(func=cmd_assemble)
t = sub.add_parser("tiles", help="按时间抽帧拼图,近距离检查某一段(agent 复核用)")
diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.py
index 99e507d..06bb453 100644
--- a/rea_video/integrations/capsule_cinema.py
+++ b/rea_video/integrations/capsule_cinema.py
@@ -14,6 +14,8 @@ from datetime import datetime
from pathlib import Path
from ..classify import LABEL_ZH
+from ..i18n import T, join, semi
+from ..packaging import overlays_at
from ..util import fmt_time, write_json
FORMAT_MAP = {"口播": "short_video", "剧情": "story", "商品展示": "product_showcase", "知识讲解": "explainer",
@@ -250,11 +252,21 @@ def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path, engine: str | Non
params.update({"start_image_path": first, "end_image_path": last})
elif gen_type == "image_to_video":
params["image_path"] = first
+ warn = ["原镜头是真实素材:生成结果只是近似,建议换成你自己的素材"] if rep.get("user_assets") else []
+ # the first / last frames go to the model as-is: subtitles or stickers burned into them get copied into the clip
+ used = [(sh["start"], sh["start"] + 0.15)] + ([(sh["end"] - 0.15, sh["end"])] if gen_type == "first_last_frame" else [])
+ layers = list(dict.fromkeys(k for a, z in used for k in overlays_at(b.get("packaging"), a, z)))
+ if layers:
+ warn.append(T("参考帧上带着原片的{k}:直接给模型,生成画面多半会带上这些字;先擦掉(剪映去字幕 / 图像模型擦除)再生成,"
+ "包装层最后用 assemble --overlays 叠回",
+ "the reference frames carry the source's {k}: handed to the model as-is, the clip will likely copy them; "
+ "erase them first (subtitle removal / image inpainting), then lay the packaging back on with assemble --overlays",
+ k=join(layers)))
jobs.append({"shot": sh["index"], "id": sh["id"], "executor": "capsule_cinema", "label": lab,
"tool": "UniversalVideoGenerationTool", "params": params, "trim_to": sh["duration"],
"prompt_source": "vlm" if cap.get("prompt") else "fallback",
- "user_assets": rep.get("user_assets", []),
- "warning": "原镜头是真实素材:生成结果只是近似,建议换成你自己的素材" if rep.get("user_assets") else ""})
+ "user_assets": rep.get("user_assets", []), "overlays_in_frames": layers,
+ "warning": semi().join(warn)})
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})
diff --git a/rea_video/integrations/run_remake.py b/rea_video/integrations/run_remake.py
index 37361c3..c8fc7f3 100644
--- a/rea_video/integrations/run_remake.py
+++ b/rea_video/integrations/run_remake.py
@@ -72,6 +72,8 @@ def main() -> None:
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))
+ if j.get("warning"):
+ print(f" ! {j['warning']}")
return
sys.path.insert(0, str(root / "lib"))
diff --git a/rea_video/packaging.py b/rea_video/packaging.py
index 48d4945..475f96c 100644
--- a/rea_video/packaging.py
+++ b/rea_video/packaging.py
@@ -1174,6 +1174,135 @@ def anchored_sfx(path: str | Path, events: list[dict], known: list[dict]) -> lis
return out
+# ----------------------------------------------------------------------------- speech anchors / persistent layers
+
+ANCHOR_KINDS = ("huazi", "title", "label", "counter")
+ANCHOR_BEFORE, ANCHOR_AFTER = 0.5, 1.0 # an element popping in just before a line starts / just after it ends still belongs to it
+
+
+def speech_lines(cues: list[dict]) -> list[dict]:
+ """The subtitle lane carrying the spoken lines: the one with the most different lines (a filing number or a
+ watermark repeats one text; OCR noise in a picture rarely forms 3+ distinct lines in one lane)."""
+ lanes: dict = {}
+ for c in cues:
+ if c["kind"] == "subtitle" and not c.get("part_of_picture"):
+ lanes.setdefault(c.get("lane"), []).append(c)
+ best = max(lanes.values(), key=lambda cs: (len({_norm(c["text"]) for c in cs}), sum(c["t1"] - c["t0"] for c in cs)), default=[])
+ return sorted(best, key=lambda c: c["t0"]) if len({_norm(c["text"]) for c in best}) >= 3 else []
+
+
+def cjk_count(s: str) -> int:
+ return sum(1 for ch in s if "\u3040" <= ch <= "\u9fff" or "\uac00" <= ch <= "\ud7af")
+
+
+def _shared_word(a: str, b: str) -> str | None:
+ """Longest run of characters both texts share: 2+ CJK characters or 4+ latin / digits."""
+ a, b = _norm(a), _norm(b)
+ if not a or not b:
+ return None
+ m = SequenceMatcher(None, a, b, autojunk=False).find_longest_match(0, len(a), 0, len(b))
+ w = a[m.a:m.a + m.size]
+ return w if m.size >= (2 if cjk_count(w) else 4) else None
+
+
+def line_anchor(t: float, text: str, lines: list[dict]) -> dict | None:
+ """Which spoken line an element entering at t belongs to. A shared word with a nearby line wins over plain timing
+ (a 花字 repeating the keyword is placed on that word); otherwise the line being spoken, else the one just
+ finished, else the one about to start."""
+ near = [ln for ln in lines if ln["t0"] - ANCHOR_BEFORE <= t <= ln["t1"] + ANCHOR_AFTER]
+ if not near:
+ return None
+ word_hits = [(ln, w) for ln in near if text and (w := _shared_word(text, ln["text"]))]
+ if word_hits:
+ ln, word = max(word_hits, key=lambda x: (len(x[1]), -abs(t - x[0]["t0"])))
+ else:
+ word = None
+ during = [ln for ln in near if ln["t0"] - 0.15 <= t < ln["t1"]]
+ after = [ln for ln in near if ln["t1"] <= t]
+ ln = during[-1] if during else (after[-1] if after else near[0])
+ if ln["t0"] - 0.15 <= t < ln["t1"]:
+ rel, dt = "during", t - ln["t0"]
+ elif t >= ln["t1"]:
+ rel, dt = "after", t - ln["t1"]
+ else:
+ rel, dt = "before", ln["t0"] - t
+ return {"line": ln["id"], "text": ln["text"], "rel": rel, "dt": round(max(0.0, dt), 2), "word": word}
+
+
+def anchor_layers(cues: list[dict], stickers: list[dict], cuts: list[float], min_persist_s: float = 2.0) -> None:
+ """Tie each 花字 / title / sticker to the spoken line it lands on, so a remake with new wording moves it with its
+ line instead of keeping the old second; mark layers that stay on across cuts (a disclaimer, a title bar, a
+ corner badge) as persistent, to be laid on once rather than generated shot by shot.
+
+ 「文字标注」 also catches text inside the picture (packaging, UI, OCR noise), so a label is anchored only when it
+ repeats a word of the line, and a non-CJK persistent text only when it is read the same way at least twice."""
+ for e in cues + stickers:
+ e.pop("anchor", None)
+ e.pop("persistent", None)
+ lines = speech_lines(cues)
+ texts = [c for c in cues if c["kind"] in ANCHOR_KINDS and not c.get("part_of_picture")]
+ stk = [s for s in stickers if not s.get("in_picture") and s.get("confidence") != "low"]
+ for e in texts + stk:
+ if not lines or e["t1"] - e["t0"] > 6.0: # a long-lived layer is not "said" by the line it starts on
+ continue
+ text = e.get("text") or ""
+ a = line_anchor(e["t0"], text, lines)
+ if a and a["word"] and len(a["word"]) < 0.5 * len(_norm(text)):
+ a["word"] = None # two shared characters out of a long text is chance, not the keyword
+ if a and (e.get("kind") != "label" or a["word"]):
+ e["anchor"] = a
+ spans = [e for e in texts + stk
+ if e["t1"] - e["t0"] >= min_persist_s and any(e["t0"] + 0.2 < t < e["t1"] - 0.2 for t in cuts)]
+ for e in spans:
+ text = e.get("text") or ""
+ same = [o for o in spans if text and _similar(o.get("text") or "", text) >= 0.7]
+ if not text or cjk_count(text) >= 2 or len(same) >= 2:
+ e["persistent"] = {"cuts": sum(1 for t in cuts if e["t0"] + 0.2 < t < e["t1"] - 0.2)}
+
+
+def persistent_groups(elems: list[dict]) -> list[dict]:
+ """Persistent layers with the same text (one disclaimer re-laid after each transition) as one group."""
+ groups: list[dict] = []
+ for e in sorted((e for e in elems if e.get("persistent")), key=lambda e: e["t0"]):
+ text = e.get("text") or ""
+ g = next((g for g in groups if text and _similar(g["text"], text) >= 0.7), None)
+ if g:
+ g["t1"] = max(g["t1"], e["t1"])
+ g["n"] += 1
+ else:
+ groups.append({"text": text, "name": layer_name(e), "t0": e["t0"], "t1": e["t1"], "n": 1})
+ return groups
+
+
+def overlays_at(pack: dict | None, t0: float, t1: float) -> list[str]:
+ """Kinds of post-production layer on screen anywhere in [t0, t1] (subtitles, 花字, stickers ...), excluding words
+ that are the picture's own content. Used to warn when a frame handed to a generator carries them."""
+ if not pack:
+ return []
+ kinds = []
+ for c in pack.get("text_cues", []):
+ if c["kind"] != "scene" and not c.get("part_of_picture") and min(t1, c["t1"]) > max(t0, c["t0"]):
+ kinds.append(c.get("kind_zh") or c["kind"])
+ for s in pack.get("stickers", []):
+ if not s.get("in_picture") and s.get("confidence") != "low" and min(t1, s["t1"]) > max(t0, s["t0"]):
+ kinds.append(T("贴纸", "sticker"))
+ return list(dict.fromkeys(kinds))
+
+
+def anchor_text(a: dict) -> str:
+ """「line」 + where in it, for the report and summary."""
+ line = T("「{t}」", "\"{t}\"", t=a["text"].replace("/", " ")[:18])
+ pos = {"during": T("{l}开始后 {d:.1f}s", "{d:.1f}s into {l}"), "after": T("{l}说完后 {d:.1f}s", "{d:.1f}s after {l}"),
+ "before": T("{l}开始前 {d:.1f}s", "{d:.1f}s before {l}")}[a["rel"]].format(l=line, d=a["dt"])
+ return pos + (T(",对上「{w}」", ", on \"{w}\"", w=a["word"]) if a.get("word") else "")
+
+
+def layer_name(e: dict) -> str:
+ if e.get("text"):
+ return T("{k}「{t}」", "{k} \"{t}\"", k=e.get("kind_zh", ""), t=e["text"].replace("/", " ")[:14])
+ return str(e.get("what") or e.get("kind_zh") or T("贴纸", "sticker"))[:24]
+
+
# ----------------------------------------------------------------------------- top level
def analyze(path: str | Path, info: VideoInfo, cuts: list[float], out_dir: Path | None = None, ocr: bool = True) -> dict:
@@ -1282,14 +1411,23 @@ def to_ass(cues: list[dict], width: int, height: int) -> str:
if c["kind"] == "scene":
continue
st = c.get("style") or {}
- size = max(12, int(round(c["line_h"] * height * 0.95)))
+ x, y, w, h = c["bbox"]
+ rows = c["text"].split("/")
+ # a narrow tall box is a vertical column of characters; otherwise the text must fit the measured box width
+ vertical = len(rows) == 1 and len(_norm(rows[0])) > 1 and h * height > 2 * w * width
+ size = c["line_h"] * height * 0.95
+ if vertical:
+ size = w * width * 0.95
+ else:
+ em = max(sum(1.0 if cjk_count(ch) else 0.55 for ch in r) for r in rows)
+ size = min(size, w * width * 1.05 / max(1.0, em))
+ size = max(12, int(round(size)))
name = f"{c['kind']}_{len(styles) + 1}"
box = st.get("box")
- outline = max(0, int(round(st.get("stroke_ratio", 0.0) * c["line_h"] * height))) if st.get("stroke") else 0
+ outline = max(0, int(round(st.get("stroke_ratio", 0.0) * size / 0.95))) if st.get("stroke") else 0
styles[name] = (f"Style: {name},Sans,{size},{_ass_color(st.get('fill'), '#ffffff')},&H0000FFFF,"
f"{_ass_color(st.get('box_color') if box else st.get('stroke'), '#000000')},{_ass_color(st.get('box_color'), '#000000')},"
f"{-1 if st.get('weight', 0) > 0.2 else 0},0,0,0,100,100,0,{-c['angle']:.0f},{3 if box else 1},{outline if not box else 8},0,5,0,0,0,1")
- x, y, w, h = c["bbox"]
tags = f"\\pos({(x + w / 2) * width:.0f},{(y + h / 2) * height:.0f})"
ak = (c.get("anim_in") or {}).get("kind")
if ak == "pop":
@@ -1297,7 +1435,8 @@ def to_ass(cues: list[dict], width: int, height: int) -> str:
elif ak == "fade" or (c.get("anim_out") or {}).get("kind") == "fade_out":
tags += "\\fad(200,200)"
# OCR text is literal: "{...}" would be read as override tags and "\\" as an escape
- text = c["text"].replace("\\", "\").replace("{", "{").replace("}", "}").replace("/", "\\N")
+ text = c["text"].replace("\\", "\").replace("{", "{").replace("}", "}")
+ text = "\\N".join(text) if vertical else text.replace("/", "\\N")
events.append(f"Dialogue: {0 if c['kind'] == 'subtitle' else 1},{_ts(c['t0'], '.')[1:-1]},{_ts(c['t1'], '.')[1:-1]},{name},,0,0,0,,{{{tags}}}{text}")
return "\n".join(head + list(styles.values()) + ["", "[Events]",
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"] + events) + "\n"
@@ -1381,6 +1520,16 @@ def summary_lines(pack: dict, sfx_align: dict | None = None) -> list[str]:
on = sfx_align.get("sfx_on", {})
if on:
L.append(T("音效卡点:", "SFX hits on: ") + join(T("{k} {v} 处", "{k} ×{v}", k=EVENT_ZH.get(k, k), v=v) for k, v in sorted(on.items(), key=lambda kv: -kv[1])))
+ elems = [c for c in cues if c["kind"] in ANCHOR_KINDS and not c.get("part_of_picture")] + st
+ anchored = sorted((e for e in elems if e.get("anchor")), key=lambda e: (not e["anchor"].get("word"), e["t0"]))
+ if anchored:
+ L.append(T("按台词定位 {n} 处(换文案时跟着这句话走,不按原秒数放):", "Placed by spoken line ×{n} (with new wording they follow the line, not the old second): ", n=len(anchored))
+ + join(f"{layer_name(e)} → {anchor_text(e['anchor'])}" for e in anchored[:3]) + (T("等", " …") if len(anchored) > 3 else ""))
+ groups = persistent_groups(elems)
+ if groups:
+ L.append(T("常驻图层 {n} 个(跨切镜不变,复刻时整段叠一次,不进逐镜生成):", "{n} persistent layers (unchanged across cuts: lay each on once for its span, not per shot): ", n=len(groups))
+ + join(f"{g['name']} {g['t0']:.1f}–{g['t1']:.1f}s" + (T("({k} 段)", " ({k} spans)", k=g["n"]) if g["n"] > 1 else "") for g in groups[:4])
+ + (T("等", " …") if len(groups) > 4 else ""))
return L
@@ -1550,6 +1699,7 @@ def finalize_pack(breakdown: dict, out: Path) -> dict | None:
if all(abs(e["t"] - k) >= 0.12 for k in known):
sfx.append(dict(e, confidence="low"))
sfx.sort(key=lambda e: float(e.get("t", 0)))
+ anchor_layers(cues, stickers, cuts)
events = visual_events(cues, stickers, cuts)
pack["sfx_alignment"] = align_sfx(sfx, events)
pack["summary_zh"] = summary_lines({**pack, "stickers": stickers}, pack["sfx_alignment"])
@@ -1568,7 +1718,7 @@ def finalize_pack(breakdown: dict, out: Path) -> dict | None:
(d / "overlays.ass").write_text(to_ass([c for c in cues if not c.get("part_of_picture")], w, h), encoding="utf-8")
pack["files"]["ass"] = "packaging/overlays.ass"
timeline = {"text": [{k: c.get(k) for k in ("id", "kind", "kind_zh", "t0", "t1", "text", "bbox", "style", "style_zh", "anim_in",
- "anim_out", "mid_motion", "follows", "part_of_picture")} for c in cues],
+ "anim_out", "mid_motion", "follows", "part_of_picture", "anchor", "persistent")} for c in cues],
"stickers": stickers,
"sfx": [{k: e.get(k) for k in ("t", "type", "description", "source", "confidence", "on")} for e in sfx]}
from .util import write_json
diff --git a/rea_video/production.py b/rea_video/production.py
index 0d20019..aa55bed 100644
--- a/rea_video/production.py
+++ b/rea_video/production.py
@@ -417,6 +417,13 @@ def production_plan(b: dict, out: Path, engine: str = "seedance2.0") -> dict:
if lim["native_audio"]:
plan["audio_note"] = T("模型可以同时生成动作音效和环境声", "the model can generate action sound effects and ambience along with the picture") + \
(semi() + T("口播建议单独 TTS 再混进去,方便改文案和卡时间", "voice-over is better done as separate TTS and mixed in, so copy and timing stay editable") if voice else "")
+ from .packaging import overlays_at
+
+ on_gen = list(dict.fromkeys(k for u in units for a, z in u["ranges"] for k in overlays_at(b.get("packaging"), a, z)))
+ if on_gen: # generated picture stays clean; the packaging is laid on afterwards, so a new wording can move it
+ plan["overlay_note"] = T("生成单元镜头上的{k}属于后期包装,不写进提示词;参考帧上带着的先擦掉,生成后按「剪辑包装层」的时间轴叠回(assemble --overlays)",
+ "the {k} on the generated shots is post-production packaging: keep it out of the prompts, erase it from reference frames, "
+ "and lay it back on from the packaging timeline after generation (assemble --overlays)", k=join(on_gen))
plan["shoot"] = _setups(shots, sig, thr, b)
code, cur = [], []
for r in shots + [None]:
@@ -516,6 +523,8 @@ def report_md(plan: dict) -> list[str]:
mx=lim["max"], p=plan["rules"]["hardcut_s"]["prefer"], m=plan["rules"]["hardcut_s"]["max"])]
if plan.get("audio_note"):
L.append(T("- 声音:{a}", "- Audio: {a}", a=plan["audio_note"]))
+ if plan.get("overlay_note"):
+ L.append(T("- 包装层:{a}", "- Packaging: {a}", a=plan["overlay_note"]))
L += ["", T("### 生成单元", "### Generation units"), "",
T("| 单元 | 镜头 | 时间 | 时长 | 方式 | 衔接 |", "| Unit | Shots | Time | Duration | Mode | Continuity |"), "|---|---|---|---|---|---|"]
mode_zh = LangDict({"multi_shot": "一次多镜头", "single": "单镜", "split": "超长切段"},
diff --git a/rea_video/remake.py b/rea_video/remake.py
index 970cfd1..2d62bf3 100644
--- a/rea_video/remake.py
+++ b/rea_video/remake.py
@@ -4,6 +4,8 @@
- still_motion / static_hold shots -> rebuilt locally from one image using the measured
zoom/pan (deterministic, no model call)
- everything else -> original footage kept (marked in the compare video)
+- with overlays=True, the measured subtitles / 花字 / titles are laid back on over the replaced shots only (kept
+ original footage already carries them)
Outputs remake.mp4 (original audio) and compare.mp4 (original | remake side by side)."""
from __future__ import annotations
@@ -17,8 +19,8 @@ import cv2
from .util import LOG, read_json
-def _ff(args: list[str]) -> None:
- subprocess.run(["ffmpeg", "-v", "error", "-y", *args], check=True)
+def _ff(args: list[str], cwd: Path | None = None) -> None:
+ subprocess.run(["ffmpeg", "-v", "error", "-y", *args], check=True, cwd=cwd)
def render_still_motion(image: Path, out: Path, duration: float, size: tuple[int, int], fps: float,
@@ -92,7 +94,47 @@ def _original_segment(src: Path, out: Path, start: float, duration: float, size:
return out
-def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = None) -> str:
+def replaced_spans(b: dict, legend: list[tuple]) -> list[tuple[float, float]]:
+ """Time spans of shots no longer showing the original picture, adjacent ones merged."""
+ shots = {sh["index"]: sh for sh in b["shots"]}
+ spans: list[list[float]] = []
+ for i, how in legend:
+ if how == "original":
+ continue
+ a, z = shots[i]["start"], shots[i]["end"]
+ if spans and abs(spans[-1][1] - a) < 1e-3:
+ spans[-1][1] = z
+ else:
+ spans.append([a, z])
+ return [(a, z) for a, z in spans]
+
+
+def overlay_cues(b: dict, spans: list[tuple[float, float]]) -> tuple[list[dict], list[dict]]:
+ """Text layers to lay back on, clipped to the replaced spans, and the stickers there that need an asset by hand.
+ A layer cut by a span edge loses its entrance animation, so it does not pop in again mid-line."""
+ from .packaging import ANCHOR_KINDS, cjk_count, speech_lines
+
+ pack = b.get("packaging") or {}
+ speech = {c["id"] for c in speech_lines(pack.get("text_cues", [])) if c.get("id")}
+ cues, stickers = [], []
+ for c in pack.get("text_cues", []):
+ if c["kind"] == "scene" or c.get("part_of_picture"):
+ continue
+ # spoken lines and styled text go back on; other OCR reads only when they hold real words, not "8uXrH"-like noise
+ if not (c.get("id") in speech or (c["kind"] in ANCHOR_KINDS and c["kind"] != "label") or cjk_count(c.get("text", "")) >= 2):
+ continue
+ for a, z in spans:
+ lo, hi = max(c["t0"], a), min(c["t1"], z)
+ if hi - lo >= 0.1:
+ cues.append({**c, "t0": lo, "t1": hi, **({"anim_in": None} if lo > c["t0"] + 1e-3 else {}),
+ **({"anim_out": None} if hi < c["t1"] - 1e-3 else {})})
+ for st in pack.get("stickers", []):
+ if not st.get("in_picture") and st.get("confidence") != "low" and any(min(st["t1"], z) - max(st["t0"], a) >= 0.1 for a, z in spans):
+ stickers.append({k: st.get(k) for k in ("id", "kind_zh", "what", "t0", "t1", "bbox", "image")})
+ return cues, stickers
+
+
+def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = None, overlays: bool = False) -> str:
b = read_json(breakdown_path)
bdir = breakdown_path.parent
jobs_path = results_path.with_name("jobs.json")
@@ -130,6 +172,22 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = No
lst.write_text("".join("file '" + str(p.resolve()).replace("'", "'\\''") + "'\n" for p in parts), encoding="utf-8")
silent = out_dir / "remake_silent.mp4"
_ff(["-f", "concat", "-safe", "0", "-i", str(lst), "-c", "copy", str(silent)])
+ overlay_log: dict = {}
+ if overlays:
+ from .packaging import to_ass
+
+ cues, stickers = overlay_cues(b, replaced_spans(b, legend))
+ overlay_log = {"text": len(cues), "stickers_to_add": stickers}
+ if cues:
+ (out_dir / "overlays_remake.ass").write_text(to_ass(cues, w, h), encoding="utf-8")
+ try: # relative name + cwd: no filter-string escaping of the path
+ _ff(["-i", silent.name, "-vf", "ass=overlays_remake.ass", "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p",
+ "remake_overlaid.mp4"], cwd=out_dir)
+ silent = out_dir / "remake_overlaid.mp4"
+ overlay_log["ass"] = str(out_dir / "overlays_remake.ass")
+ except subprocess.CalledProcessError as exc: # ffmpeg built without libass
+ overlay_log["error"] = f"ffmpeg ass filter failed ({exc.returncode}); overlays_remake.ass can be burned in another editor"
+ LOG.warning(overlay_log["error"])
final = out_dir / "remake.mp4"
if b["source"].get("has_audio"):
_ff(["-i", str(silent), "-i", str(src), "-map", "0:v", "-map", "1:a?", "-c:v", "copy", "-c:a", "aac", "-shortest", str(final)])
@@ -148,7 +206,7 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = No
except subprocess.CalledProcessError:
if not with_text:
raise
- (out_dir / "assemble_log.json").write_text(json.dumps({"legend": legend, "remake": str(final), "compare": str(compare)},
- ensure_ascii=False, indent=2), encoding="utf-8")
+ log = {"legend": legend, "remake": str(final), "compare": str(compare), **({"overlays": overlay_log} if overlays else {})}
+ (out_dir / "assemble_log.json").write_text(json.dumps(log, ensure_ascii=False, indent=2), encoding="utf-8")
LOG.info("remake -> %s ; compare -> %s", final, compare)
- return json.dumps({"remake": str(final), "compare": str(compare), "legend": legend}, ensure_ascii=False)
+ return json.dumps(log, ensure_ascii=False)
diff --git a/rea_video/report.py b/rea_video/report.py
index 4e87563..fff0d12 100644
--- a/rea_video/report.py
+++ b/rea_video/report.py
@@ -14,6 +14,7 @@ from pathlib import Path
from . import aspects, entities
from .classify import LABEL_ZH
from .i18n import LangDict, T, join, lang, semi
+from .packaging import layer_name, anchor_text
from .production import report_md as production_md
from .util import fmt_time
from .visual import LABEL_COLOR
@@ -421,6 +422,11 @@ def packaging_md(b: dict) -> list[str]:
if dropped:
L.append(T("- 另有 {n} 处画面里突然出现的东西没算作贴纸(3D/动画/版式画面里元素本来就会出现)",
"- {n} more things that pop up in the picture were not counted as stickers (elements appear on their own in 3D / animation / layout shots)", n=len(dropped)))
+ anchored = sorted((e for e in cues + stickers if e.get("anchor")), key=lambda e: e["t0"])
+ if anchored:
+ rows = [[f"{e['t0']:.2f}s", layer_name(e), anchor_text(e["anchor"])] for e in anchored[:80]]
+ L += _table([T("时间", "Time"), T("元素", "Layer"), T("跟哪句台词", "Spoken line")], rows,
+ fold_title=T("按台词定位({n} 处,复刻换文案时按这句话放,不按原秒数)", "placed by spoken line ({n}; with new wording place each on its line, not the old second)", n=len(anchored)))
if pack.get("vlm_text_effects"):
fx = pack["vlm_text_effects"][:20]
L += ["", f"<details><summary>{html.escape(T('VLM 看到的文字特效({n})', 'Text effects seen by the VLM ({n})', n=len(fx)))}</summary>", ""]
diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.md
index 8b23b85..4d5753d 100644
--- a/skills/rea-video/SKILL.md
+++ b/skills/rea-video/SKILL.md
@@ -72,6 +72,7 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复
- 贴纸:标了「需要看图确认」的,看 `packaging/sticker_XX.jpg` 和 `review_tasks.json` 里的 `frame_cmd`,在 `review_answers.json` 的 `packaging.stickers` 里填 `is_overlay` 和 `what`;工具漏掉的写进 `packaging.missed`。3D / 动画 / 版式画面里突然出现的物体工具不算贴纸,你看到是后期贴的再补。
- 花字和标签分错类时在 `packaging.text` 里改 `kind`。
- 音效「对应画面」一列是按时间就近对齐的,没开 VLM 时补出的候选(来源 `deterministic_anchored`)实测只有约四成是真音效,写成"可能"。
+ - 「按台词定位」是花字 / 标题 / 贴纸落在哪句字幕上(句中第几秒、对上哪个词),「常驻图层」是跨切镜不变的免责声明、标题栏、角标。只在有字幕时才有;定位按时间推的,看图觉得不对就在回复里说明。
8. 第 3、5、6、7 步改了 `review_answers.json` 的,改完**再跑一次** `rea-video apply-review out/ref --by <你的名字>`,否则这些修改进不了报告。
9. 如果你的判断和工具不同,以你的复核为准,在回复里写明理由;有价值的话,建议用户把这条视频加进评测集(仓库 `docs/dev/evaluation.md`)。
diff --git a/skills/rea-video/references/output-template.md b/skills/rea-video/references/output-template.md
index 1b578b6..d8e1cf6 100644
--- a/skills/rea-video/references/output-template.md
+++ b/skills/rea-video/references/output-template.md
@@ -29,7 +29,7 @@
**拍法、打光与剪辑**(有实拍镜头时写,对应 `rea-video summary` 末尾的取景 / 机位 / 打光 / 剪辑 / 形式几行):视频形式(口播/桌拍/vlog)、景别和机位角度、手持还是支架、机位/场景数;布光方案(主光方向和高度、光比、软硬、色温、有无补光/轮廓光、画面里的光源);剪辑手法(跳切剪气口、推近切、插入截图/录屏的比例);给一份复刻器材清单。测量值和你看图的结论冲突时写明依据。
-**剪辑包装**:字幕(几句、位置、颜色 / 描边 / 底框、关键词高亮、入场方式,SRT/ASS 文件路径);花字、标题、章节牌、跟随标签(时间、文字、样式、动画);贴纸 / GIF / 表情包 / 画中画(时间、位置、贴的是什么、是否循环);哪些音效卡在文字弹出或贴纸出现上。工具没测到、你看图补的写明。
+**剪辑包装**:字幕(几句、位置、颜色 / 描边 / 底框、关键词高亮、入场方式,SRT/ASS 文件路径);花字、标题、章节牌、跟随标签(时间、文字、样式、动画);贴纸 / GIF / 表情包 / 画中画(时间、位置、贴的是什么、是否循环);哪些音效卡在文字弹出或贴纸出现上;花字 / 贴纸跟哪句台词(「按台词定位」)、哪些是常驻图层。工具没测到、你看图补的写明。
**声音**:人声(TTS 还是真人、音色,台词见报告脚本表)/ BGM(歌名猜测、风格、BPM、调性、来源与版权风险、段落)/ 音效(时间点 → 对应画面事件)/ 混音(是否压低音乐)。报告「声音」一节每一项是一张卡,照着抄即可。
diff --git a/skills/rea-video/references/remake.md b/skills/rea-video/references/remake.md
index d550cd9..518e858 100644
--- a/skills/rea-video/references/remake.md
+++ b/skills/rea-video/references/remake.md
@@ -7,12 +7,16 @@
- **代码渲染**:用 Remotion 重建。把报告「代码合成」一节(每镜做法、逐镜动效时间轴、色值)连同 `shots/` 里的元素截图、关键帧条和 `packaging/overlays.ass` 一起交给写代码的人或 LLM;按时间轴的时间和位置写动画,按截图重画图形,图标 / Logo / 插画这类画不出来的直接抠图用。
- **真实素材**:列清单让用户提供。
- **声音**:TTS、BGM(按 BPM / 调性 / 情绪)、音效(按时间点)三条轨分别准备。
+- **剪辑包装(字幕、花字、贴纸)**:不进生成。生成模型只出干净的人和画面,包装层最后按「剪辑包装层」的时间轴叠上去,这样字不会被模型画糊,换文案时也只改包装层。
+ - 首尾帧上带着原片字幕的,`remake-plan` 的任务里有 `overlays_in_frames` 和警告:先擦掉字再当参考图,否则生成画面会照抄原字幕。
+ - 换文案时,花字和贴纸按报告里的「按台词定位」放到新文案的对应句子上,不沿用原秒数;「常驻图层」整段叠一次。
**用户自己拍的素材、或在网页上手动生成的视频,拼回原时间线**(不需要 capsule-cinema):
1. 按分镜表(`report.md` 的镜头号和时长)把素材对应到镜头。一条长素材覆盖多个镜头时,先用 ffmpeg 按动作切开;拿不准对应关系时给用户看截图确认。
2. 写一个 `results.json`:`{"results": {"<镜头号>": {"video": "<素材绝对路径>"}, ...}}`。手动生成的「生成单元」视频覆盖多个镜头时,同样先按单元提示词里的「镜头i(a–b s)」时间切开再填。
3. `rea-video assemble out/ref/breakdown.json <results.json 路径>`:每段生成素材整段变速塞进原镜头时长(最多快 3 倍、慢 1.25 倍,超出部分再裁),切点和原片对齐,没填的镜头暂时用原片占位,声音沿用原片;输出 `remake.mp4` 和左右对比的 `compare.mp4`。告诉用户哪些镜头还是原片占位、声音还要换。
+ - 加 `--overlays`:把测得的字幕 / 花字 / 标题按原样式叠到换掉的镜头上(原片占位的镜头本来就有字,不重复叠)。字体是通用无衬线体,颜色和底框是测量值,可能和原片有出入;贴纸只在 `assemble_log.json` 的 `stickers_to_add` 里列出来,要自己找素材贴。
**自动生成的限制**:`remake-plan` 和 capsule-cinema 目前还是一个镜头调一次模型;报告里「生成单元」的多镜头提示词要用户手动贴到支持多镜头的模型(如即梦 / Seedance 2.5)上用。向用户说明这一点,并给出两种做法的调用次数。
diff --git a/tests/test_packaging.py b/tests/test_packaging.py
index 5ca32b1..fc0abc0 100644
--- a/tests/test_packaging.py
+++ b/tests/test_packaging.py
@@ -130,6 +130,45 @@ def test_sfx_alignment():
assert res["events_with_sfx"]["sticker_out"] == {"with_sfx": 0, "total": 1}
+def _sub(i, t0, t1, text, lane=2):
+ return {"id": f"text_{i:03d}", "kind": "subtitle", "kind_zh": "字幕", "text": text, "t0": t0, "t1": t1, "lane": lane}
+
+
+def test_speech_anchors_and_persistent_layers():
+ lines = [_sub(1, 0.0, 1.8, "这俩口红有啥区别"), _sub(2, 1.8, 3.8, "现在双11全场五折"), _sub(3, 4.0, 5.5, "给你安排上"),
+ _sub(4, 6.0, 7.0, "错过就没有了")]
+ filing = [_sub(10 + k, t, t + 1.5, "粤G妆网备字2026", lane=6) for k, t in enumerate((0.0, 3.0, 6.0))] # one text repeated
+ cues = lines + filing + [
+ {"id": "text_020", "kind": "huazi", "kind_zh": "花字", "text": "五折", "t0": 3.2, "t1": 3.6}, # repeats a word of line 2
+ {"id": "text_021", "kind": "huazi", "kind_zh": "花字", "text": "冲!", "t0": 5.7, "t1": 6.2}, # just after line 3
+ {"id": "text_022", "kind": "label", "kind_zh": "文字标注", "text": "8uXrH", "t0": 2.0, "t1": 2.3}, # picture text: no shared word
+ {"id": "text_023", "kind": "label", "kind_zh": "文字标注", "text": "使用效果因人而异", "t0": 0.0, "t1": 7.0}, # disclaimer across cuts
+ {"id": "text_024", "kind": "label", "kind_zh": "文字标注", "text": "Q8xZ", "t0": 1.0, "t1": 6.5}] # noise seen once
+ stickers = [{"id": "sticker_01", "kind": "static_sticker", "kind_zh": "静态贴纸", "t0": 4.1, "t1": 4.9, "confidence": "medium"}]
+ cuts = [2.0, 4.0, 6.0]
+ assert [c["id"] for c in P.speech_lines(cues)] == ["text_001", "text_002", "text_003", "text_004"]
+ P.anchor_layers(cues, stickers, cuts)
+ by = {c["id"]: c for c in cues}
+ assert by["text_020"]["anchor"]["line"] == "text_002" and by["text_020"]["anchor"]["word"] == "五折"
+ assert by["text_021"]["anchor"] == {"line": "text_003", "text": "给你安排上", "rel": "after", "dt": 0.2, "word": None}
+ assert stickers[0]["anchor"]["line"] == "text_003" and stickers[0]["anchor"]["rel"] == "during"
+ assert "anchor" not in by["text_022"] and "anchor" not in by["text_023"]
+ assert by["text_023"]["persistent"] == {"cuts": 3} and "persistent" not in by["text_024"]
+ lines_out = P.summary_lines({"text_cues": [c for c in cues if c["kind"] != "subtitle"], "stickers": stickers})
+ assert any("按台词定位 3 处" in l for l in lines_out)
+ assert any(l.startswith("常驻图层 1 个") and "使用效果因人而异" in l for l in lines_out)
+ P.anchor_layers(cues, [], []) # a re-run drops stale marks
+ assert not any(c.get("persistent") for c in cues)
+
+
+def test_overlays_at_skips_picture_text():
+ pack = {"text_cues": [{"kind": "subtitle", "kind_zh": "字幕", "t0": 0.0, "t1": 2.0},
+ {"kind": "label", "kind_zh": "文字标注", "t0": 0.0, "t1": 2.0, "part_of_picture": True}],
+ "stickers": [{"t0": 1.0, "t1": 3.0, "confidence": "low"}]}
+ assert P.overlays_at(pack, 0.0, 0.15) == ["字幕"]
+ assert P.overlays_at(pack, 2.5, 2.6) == [] and P.overlays_at(None, 0, 1) == []
+
+
def test_ass_export():
cues = [{"kind": "subtitle", "text": "a/b", "t0": 1.0, "t1": 2.5, "bbox": [0.2, 0.8, 0.6, 0.08], "line_h": 0.035, "angle": 0.0,
"style": {"fill": "#ffffff", "stroke": "#000000", "stroke_ratio": 0.05}, "anim_in": {"kind": "pop"}},
@@ -137,6 +176,12 @@ def test_ass_export():
ass = P.to_ass(cues, 1080, 1920)
assert "Dialogue: 0,0:00:01.00,0:00:02.50" in ass and "a\\Nb" in ass and "\\fscx60" in ass
assert ass.count("Dialogue:") == 1 # scene text is not exported
+ side = [{"kind": "label", "text": "效果因人而异", "t0": 0, "t1": 3, "bbox": [0.01, 0.8, 0.026, 0.08], "line_h": 0.08, "angle": 0.0, "style": {}},
+ {"kind": "huazi", "text": "双十一福利五折", "t0": 0, "t1": 3, "bbox": [0.3, 0.5, 0.4, 0.05], "line_h": 0.08, "angle": 0.0, "style": {}}]
+ ass = P.to_ass(side, 720, 1280)
+ assert "效\\N果\\N因" in ass # a narrow tall box is vertical text
+ sizes = [int(l.split(",")[2]) for l in ass.splitlines() if l.startswith("Style:")]
+ assert sizes[0] <= 19 and sizes[1] * 7 <= 0.4 * 720 * 1.06 # each fits its measured box
def test_clean_region():
diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py
index 2561ef4..6e4725b 100644
--- a/tests/test_pipeline.py
+++ b/tests/test_pipeline.py
@@ -9,7 +9,7 @@ from rea_video.classify import LABELS, deterministic, fuse, top
from rea_video.integrations.capsule_cinema import build_remake_jobs, export_capsule_analysis
from rea_video.media import video_info
from rea_video.pipeline import decompose, finalize
-from rea_video.remake import assemble
+from rea_video.remake import assemble, overlay_cues, replaced_spans
from rea_video.shots import build_track, detect_shots
ROOT = Path(__file__).resolve().parents[1]
@@ -98,12 +98,30 @@ def test_remake_jobs_and_assemble(breakdown, tmp_path):
assert execs == ["local_ffmpeg", "local_ffmpeg", "keep_original"], execs
results = jobs_path.with_name("results.json")
results.write_text(json.dumps({"results": {}}))
- res = json.loads(assemble(out / "breakdown.json", results))
+ res = json.loads(assemble(out / "breakdown.json", results, overlays=True))
assert Path(res["remake"]).is_file() and Path(res["compare"]).is_file()
+ assert res["overlays"]["text"] == 0 # OCR off in this fixture: nothing to lay on, and nothing breaks
info = video_info(res["remake"])
assert abs(info.duration - b["source"]["duration"]) < 0.2
+def test_overlays_follow_replaced_shots_only():
+ b = {"shots": [{"index": 1, "start": 0.0, "end": 2.0}, {"index": 2, "start": 2.0, "end": 5.0}, {"index": 3, "start": 5.0, "end": 6.0}],
+ "packaging": {"text_cues": [
+ {"kind": "subtitle", "text": "跨两镜", "t0": 1.0, "t1": 3.0, "anim_in": {"kind": "pop"}},
+ {"kind": "huazi", "text": "WOW", "t0": 2.5, "t1": 3.5, "anim_in": {"kind": "pop"}},
+ {"kind": "label", "text": "界面字", "t0": 2.5, "t1": 3.0, "part_of_picture": True},
+ {"kind": "subtitle", "text": "原片里", "t0": 5.2, "t1": 5.8}],
+ "stickers": [{"id": "sticker_01", "t0": 3.0, "t1": 4.0, "confidence": "medium"}]}}
+ spans = replaced_spans(b, [(1, "original"), (2, "generated"), (3, "original")])
+ assert spans == [(2.0, 5.0)]
+ cues, stickers = overlay_cues(b, spans)
+ assert [(c["text"], c["t0"], c["t1"]) for c in cues] == [("跨两镜", 2.0, 3.0), ("WOW", 2.5, 3.5)]
+ assert cues[0]["anim_in"] is None and cues[1]["anim_in"] == {"kind": "pop"} # a clipped line does not pop in again
+ assert [s["id"] for s in stickers] == ["sticker_01"]
+ assert replaced_spans(b, [(1, "generated"), (2, "local_still"), (3, "original")]) == [(0.0, 5.0)]
+
+
def test_english_report_has_no_chinese(media, tmp_path):
import re