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

fix: 拆解健壮性——误判 Veo、低帧率崩溃、坏视频卡死、VLM 坏答案、复刻引擎被重置

june152428c59b60
diff --git a/eval/RESULTS.md b/eval/RESULTS.md
index 66080ff..0cee842 100644
--- a/eval/RESULTS.md
+++ b/eval/RESULTS.md
@@ -399,3 +399,26 @@ issue #8 的口红带货片(抖音转码,HEVC 1080x1920 30fps,98 秒 38
| + agent 看图复核 | 97.4% → 97.4% | 97.7% → 97.7% | 97.5% → 97.5% |
教程片里「相机拍真实手机屏幕」的镜头有一部分因为镜头自身没有重复帧被 Gemini 的实拍判断纠回来了,剩下的仍是「工具判 3D、看图判实拍」跟了工具(待做)。issue #8 的视频作者未勾选公开,没有加进评测集。
+
+
+## 2026-11-05:健壮性修复(深度审查)
+
+- `probe`:容器字节扫描跳过 mdat(压缩帧数据里随机出现的 `vEo` 等会被认成「Google Veo?」,整片每个镜头 AI +1.0;8 条新编码 mp4 里 2 条中招)。字节里的生成器名只记为 `generator_weak`,不参与打分;C2PA 只有和生成器名同时出现才算 AI 证据(相机也会签 C2PA)。
+- 低帧率(< 12.5fps)视频抽尾帧会越过最后一帧导致 decompose 中止,改为退回取最后一帧;损坏视频解码时 ffmpeg 报错写满管道会卡死,改为写临时文件。
+- 整片 VLM 答案先做结构清洗(`narration` 不是对象、`sfx.t` 写成 `"00:03"` 等不再让 finalize 崩溃,旧缓存也会清洗);`choices` 为空 / `content` 为空时换下一个模型。
+- 复刻引擎写进 breakdown,`apply-review` / `correct` / 评测重算不再重置成 seedance2.0;`remake-plan --engine` 生效。
+- 只用工具的评测复用输出目录时去掉之前 `--vlm` / 复核 / 纠正留下的答案。
+- SRT 时间戳进位、旋转视频的 ASS 分辨率、ASS 文本转义、镜头缩略图改存 uint8(长视频内存约 1/4,切点逐条一致)。
+
+回归(复用缓存特征重新分类):
+
+| 集合 | 只用工具 | 说明 |
+|---|---|---|
+| labels(7 条) | 1.000 | 真实素材 0.958,与 11-04 一致 |
+| holdout(7 条) | 0.995 | 一致 |
+| holdout2(3 条) | 0.995 | 一致 |
+| articles(10 条) | 0.886 | 一致 |
+| koubo(2 条) | 0.755 | 一致 |
+| daihuo(2 条) | 0.464 | 一致;+ Gemini 0.703 / 真实素材 0.926,+ agent 复核 0.975,均与 11-04 一致 |
+
+8 条案例视频的镜头切点在改动前后逐条一致。
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 59eb61b..4d5a0b5 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -8,7 +8,7 @@ import sys
from pathlib import Path
from .util import LOG, OCR_LANGS, load_env_files, read_json, setup_logging
-from .i18n import LANGS, set_lang
+from .i18n import LANGS, T, set_lang
from .classify import LABELS
from .vlm import vlm_note
@@ -20,8 +20,15 @@ def _env(args) -> None:
# 不读当前目录的 .env:在别人的仓库里运行时,它可以改 VLM 地址或 CAPSULE_CINEMA_PYTHON
files = [Path(__file__).resolve().parent.parent / ".env"]
- env_file = getattr(args, "env_file", None) or pref("env_file")
+ explicit = getattr(args, "env_file", None)
+ env_file = explicit or pref("env_file")
if env_file:
+ if not Path(env_file).expanduser().is_file():
+ # silently skipping it made people think the VLM was configured
+ msg = T("找不到配置文件 {p}", "env file not found: {p}", p=env_file)
+ if explicit:
+ raise SystemExit(f"rea-video: {msg}")
+ LOG.warning("%s%s", msg, T("(来自 prefs env_file)", " (from prefs env_file)"))
files.insert(0, Path(env_file))
loaded = load_env_files(files)
if loaded:
@@ -151,10 +158,8 @@ def cmd_remake_plan(args) -> int:
from .integrations.capsule_cinema import build_remake_jobs
bdir = Path(args.breakdown).parent
- from .memory import pref
-
jobs = build_remake_jobs(read_json(Path(args.breakdown)), bdir, capsule_root=Path(args.capsule_root),
- engine=args.engine or pref("engine", "seedance2.0"),
+ engine=args.engine, # None: keep the engine chosen at decompose time
mode=args.mode, labels=args.labels.split(",") if args.labels else None)
print(jobs)
return 0
@@ -410,7 +415,7 @@ def main(argv: list[str] | None = None) -> int:
r = sub.add_parser("remake-plan", help="为 AI 类镜头生成 capsule-cinema 复刻任务")
r.add_argument("breakdown")
r.add_argument("--capsule-root", default=DEFAULT_CAPSULE_ROOT)
- r.add_argument("--engine", help="默认 prefs 里的 engine,否则 seedance2.0")
+ 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")
r.set_defaults(func=cmd_remake_plan)
@@ -488,10 +493,25 @@ def main(argv: list[str] | None = None) -> int:
me.add_argument("--export-labels", metavar="YAML")
me.set_defaults(func=cmd_memory)
+ for sp in sub.choices.values(): # also accept `rea-video decompose x.mp4 --env-file ...`
+ sp.add_argument("--env-file", default=argparse.SUPPRESS, help=argparse.SUPPRESS)
+
args = ap.parse_args(argv)
setup_logging(args.verbose)
_env(args)
- return args.func(args)
+ from .media import MediaError
+
+ try:
+ return args.func(args)
+ except MediaError as exc: # missing ffmpeg / unreadable video: one line, not a traceback
+ hint = ""
+ if "not found on PATH" in str(exc):
+ hint = T("\n安装 ffmpeg:macOS `brew install ffmpeg`,Ubuntu/Debian `sudo apt install ffmpeg`",
+ "\ninstall ffmpeg: macOS `brew install ffmpeg`, Ubuntu/Debian `sudo apt install ffmpeg`")
+ print(f"rea-video: {exc}{hint}", file=sys.stderr)
+ if args.verbose:
+ raise
+ return 2
if __name__ == "__main__":
diff --git a/rea_video/evaluate.py b/rea_video/evaluate.py
index f6d9cbe..c7654f2 100644
--- a/rea_video/evaluate.py
+++ b/rea_video/evaluate.py
@@ -201,6 +201,13 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
from .probe import provenance
b["provenance"] = {k: v for k, v in provenance(video_info(path)).items() if k != "tags"} # signatures evolve
+ if not use_vlm: # tool-only score: drop answers a previous --vlm / review / correct run left in this dir
+ for sh in b["shots"]:
+ for k in ("vlm", "review", "user"):
+ sh.pop(k, None)
+ b.pop("whole_video_vlm", None)
+ b.setdefault("analysis", {})["vlm"] = {"requested": False, "used": False}
+ b["analysis"].pop("review", None)
if b["source"].get("has_audio"): # audio analysis is cheap: always redo with current code
from .audio import analyze_audio
diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.py
index 05e2218..494ecf2 100644
--- a/rea_video/integrations/capsule_cinema.py
+++ b/rea_video/integrations/capsule_cinema.py
@@ -200,10 +200,13 @@ def export_capsule_analysis(b: dict, out_path: Path) -> Path:
return out_path
-def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path, engine: str = "seedance2.0",
+def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path, engine: str | None = None,
mode: str = "first_last_frame", labels: list[str] | None = None) -> Path:
"""Write jobs.json for `rea-video remake-run` (rea_video/integrations/run_remake.py).
- Output dirs live under <capsule_root>/output/ to satisfy capsule-cinema's output guard."""
+ 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
+
labels = 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]
@@ -226,9 +229,13 @@ def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path, engine: str = "se
prompt = cap.get("prompt") or ((sh.get("vlm") or {}).get("description")) or ""
if not prompt:
prompt = f"保持参考图的画面、主体与风格,{CAMERA_ZH.get(sh['features'].get('camera', 'unknown'), '')},自然连贯的动作"
+ eng = engine or cap.get("engine") or "seedance2.0"
+ gen_dur = cap.get("duration", 5)
+ if eng != cap.get("engine"): # planned for another engine: re-fit the clip length to this one's limits
+ lo, hi = CAPSULE_ENGINES.get(eng, (4, 15))
+ 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": cap.get("engine", engine), "aspect_ratio": cap.get("aspect_ratio", "9:16"),
- "duration": cap.get("duration", 5)}
+ "engine": eng, "aspect_ratio": cap.get("aspect_ratio", "9:16"), "duration": gen_dur}
first = str((bdir / sh["assets"]["first_frame"]).resolve())
last = str((bdir / sh["assets"]["last_frame"]).resolve())
if gen_type == "first_last_frame":
@@ -242,5 +249,5 @@ def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path, engine: str = "se
"warning": "原镜头是真实素材:生成结果只是近似,建议换成你自己的素材" if rep.get("user_assets") else ""})
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, "mode": mode, "jobs": jobs})
+ "run_dir": str(run_dir), "engine": engine or b.get("engine") or "seedance2.0", "mode": mode, "jobs": jobs})
return out
diff --git a/rea_video/media.py b/rea_video/media.py
index c095648..c0bd2b3 100644
--- a/rea_video/media.py
+++ b/rea_video/media.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
import shutil
import subprocess
+import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Iterator
@@ -79,6 +80,11 @@ class VideoInfo:
rotation: int
raw: dict
+ @property
+ def display_size(self) -> tuple[int, int]:
+ """(width, height) as shown, after rotation metadata."""
+ return (self.height, self.width) if self.rotation in (90, 270) else (self.width, self.height)
+
@property
def aspect_ratio(self) -> str:
w, h = (self.height, self.width) if self.rotation in (90, 270) else (self.width, self.height)
@@ -168,7 +174,10 @@ def iter_frames(
pix = "gray" if gray else "bgr24"
cmd += ["-an", "-sn", "-vf", ",".join(vf), *([] if fps else passthrough_args()), "-f", "rawvideo", "-pix_fmt", pix, "-"]
frame_bytes = w * h * (1 if gray else 3)
- proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ # stderr goes to a temp file: an unread PIPE fills up (~64 KB of decode errors on a damaged file) and
+ # ffmpeg blocks, so stdout stalls forever
+ errf = tempfile.TemporaryFile()
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=errf)
assert proc.stdout is not None
count = 0
try:
@@ -180,21 +189,28 @@ def iter_frames(
count += 1
yield arr.reshape((h, w)) if gray else arr.reshape((h, w, 3))
if count == 0:
- err = proc.stderr.read().decode(errors="ignore") if proc.stderr else ""
+ proc.wait()
+ errf.seek(0)
+ err = errf.read()[-4000:].decode(errors="ignore")
if err.strip():
raise MediaError(f"ffmpeg decoded no frames: {err.strip()[:300]}")
finally:
proc.stdout.close()
proc.kill()
proc.wait()
+ errf.close()
def extract_frame(path: str | Path, t: float, out_path: str | Path, width: int | None = None) -> Path:
out_path = Path(out_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
vf = ["-vf", f"scale={width}:-2"] if width else []
+ out_path.unlink(missing_ok=True)
cmd = ["ffmpeg", "-v", "error", "-y", "-ss", f"{max(t, 0):.4f}", "-i", str(path), "-frames:v", "1", *vf, "-q:v", "2", str(out_path)]
- subprocess.run(cmd, check=True)
+ if subprocess.run(cmd, capture_output=True).returncode != 0 or not out_path.is_file():
+ # t past the last frame's timestamp (low fps, last shot): take the file's last frame instead
+ cmd = ["ffmpeg", "-v", "error", "-y", "-sseof", "-3", "-i", str(path), "-update", "1", *vf, "-q:v", "2", str(out_path)]
+ subprocess.run(cmd, check=True, capture_output=True)
return out_path
diff --git a/rea_video/packaging.py b/rea_video/packaging.py
index a3f4b05..3f7e033 100644
--- a/rea_video/packaging.py
+++ b/rea_video/packaging.py
@@ -1221,10 +1221,11 @@ def analyze(path: str | Path, info: VideoInfo, cuts: list[float], out_dir: Path
# ----------------------------------------------------------------------------- exports
def _ts(t: float, sep: str = ",") -> str:
- t = max(0.0, t)
- h, rem = divmod(t, 3600)
- m, s = divmod(rem, 60)
- return f"{int(h):02d}:{int(m):02d}:{int(s):02d}{sep}{int(round((s % 1) * 1000)) % 1000:03d}"
+ ms = int(round(max(0.0, t) * 1000)) # round once, then split: 3.9996 -> 00:00:04,000 (not 03,000)
+ h, ms = divmod(ms, 3_600_000)
+ m, ms = divmod(ms, 60_000)
+ s, ms = divmod(ms, 1000)
+ return f"{h:02d}:{m:02d}:{s:02d}{sep}{ms:03d}"
def to_srt(cues: list[dict], kinds=("subtitle",)) -> str:
@@ -1264,7 +1265,8 @@ def to_ass(cues: list[dict], width: int, height: int) -> str:
tags += "\\fscx60\\fscy60\\t(0,180,\\fscx110\\fscy110)\\t(180,260,\\fscx100\\fscy100)"
elif ak == "fade" or (c.get("anim_out") or {}).get("kind") == "fade_out":
tags += "\\fad(200,200)"
- text = c["text"].replace("/", "\\N")
+ # OCR text is literal: "{...}" would be read as override tags and "\\" as an escape
+ text = c["text"].replace("\\", "\").replace("{", "{").replace("}", "}").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"
@@ -1465,12 +1467,15 @@ def finalize_pack(breakdown: dict, out: Path) -> dict | None:
d.mkdir(parents=True, exist_ok=True)
srt = to_srt(cues)
pack["files"] = {}
+ for stale in ("subtitles.srt", "overlays.ass"): # a re-run with no subtitles must not keep the old export
+ (d / stale).unlink(missing_ok=True)
if srt.strip():
(d / "subtitles.srt").write_text(srt, encoding="utf-8")
pack["files"]["srt"] = "packaging/subtitles.srt"
src = breakdown["source"]
+ w, h = (src["height"], src["width"]) if src.get("rotation") in (90, 270) else (src["width"], src["height"]) # as displayed
if cues:
- (d / "overlays.ass").write_text(to_ass([c for c in cues if not c.get("part_of_picture")], src["width"], src["height"]), encoding="utf-8")
+ (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],
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 83db7fa..17ebc07 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -24,7 +24,7 @@ from . import aspects
from .faces import shot_faces
from .visual import LABEL_SHORT, shot_sheet, storyboard
from .i18n import T, join, semi, set_lang
-from .vlm import SHOT_PROMPT, WHOLE_PROMPT, VLMClient, VLMConfig, normalize_shot_result, prompt_lang_note, shot_hints, vlm_note
+from .vlm import SHOT_PROMPT, WHOLE_PROMPT, VLMClient, VLMConfig, normalize_shot_result, normalize_whole, prompt_lang_note, shot_hints, vlm_note
def _sha256_head(path: Path, limit: int = 64 << 20) -> str:
@@ -107,8 +107,9 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
layers = overlay_layers(ov, text, template)
sid = f"shot_{s.index:03d}"
shot_sheet(smp.frames, smp.frame_times, out / "shots" / f"{sid}.jpg")
- extract_frame(video, s.start + min(0.05, s.duration / 4), out / "shots" / f"{sid}_first.jpg", width=min(1080, info.width or 1080))
- extract_frame(video, max(s.start, s.end - min(0.08, s.duration / 4)), out / "shots" / f"{sid}_last.jpg", width=min(1080, info.width or 1080))
+ still_w = min(1080, info.display_size[0] or 1080) # never upscale; rotated video: displayed width
+ extract_frame(video, s.start + min(0.05, s.duration / 4), out / "shots" / f"{sid}_first.jpg", width=still_w)
+ extract_frame(video, max(s.start, s.end - min(0.08, s.duration / 4)), out / "shots" / f"{sid}_last.jpg", width=still_w)
rec = {
"id": sid, **s.to_dict(), "features": round_floats(feats), "faces": round(faces, 3),
"aspects": round_floats(asp), "overlay": round_floats(ov), "text": text, "layers": layers, "embedded_assets": round_floats(embedded),
@@ -162,7 +163,7 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
try:
low = cut_clip(video, 0, info.duration, out / "clips" / "whole_480p.mp4", width=480, audio=True, crf=30)
cuts = ", ".join(f"{r['start']:.2f}" for r in shot_records)
- whole = client.ask_json(WHOLE_PROMPT.format(shots=cuts) + prompt_lang_note(), [(low, "video/mp4")], max_tokens=6000)
+ whole = normalize_whole(client.ask_json(WHOLE_PROMPT.format(shots=cuts) + prompt_lang_note(), [(low, "video/mp4")], max_tokens=6000))
except Exception as exc:
vlm_info["errors"].append(f"whole: {str(exc)[:160]}")
asked = shot_records[:max_shots_vlm]
@@ -363,12 +364,16 @@ def _agent_review_dispute(dt: str, vt: dict | None, rv: dict | None, reviewed: b
return None
-def finalize(breakdown: dict, out: Path, engine: str = "seedance2.0") -> dict:
+def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:
"""(Re)classify every shot from stored features + VLM answers, plan replication,
summarise and write breakdown.json / reports. Safe to call again after the
classifier changes (no re-decoding)."""
out = Path(out)
set_lang(breakdown.get("lang", "zh"))
+ # remember the engine: apply-review / correct / eval call finalize without one and must not reset it
+ engine = breakdown["engine"] = engine or breakdown.get("engine") or "seedance2.0"
+ if breakdown.get("whole_video_vlm") is not None: # older runs stored the raw answer
+ breakdown["whole_video_vlm"] = normalize_whole(breakdown["whole_video_vlm"])
shot_records = breakdown["shots"]
audio = breakdown.get("audio", {})
prov = breakdown.get("provenance", {})
diff --git a/rea_video/probe.py b/rea_video/probe.py
index 423b2c6..e49d483 100644
--- a/rea_video/probe.py
+++ b/rea_video/probe.py
@@ -61,15 +61,44 @@ def _flatten_tags(raw: dict) -> dict[str, str]:
return tags
-def _scan_bytes(path: Path, limit: int = 4 << 20) -> bytes:
+_SKIP_BOXES = {b"mdat", b"free", b"skip", b"wide"}
+
+
+def _scan_bytes(path: Path, limit: int = 8 << 20) -> bytes:
+ """Metadata bytes of an MP4/MOV: every top-level box except mdat (compressed frames contain random
+ ASCII like "vEo"). Other containers fall back to the first / last 4 MB."""
size = path.stat().st_size
+ out: list[bytes] = []
with path.open("rb") as f:
- head = f.read(min(limit, size))
+ pos, total, iso = 0, 0, False
+ while pos + 8 <= size and total < limit:
+ f.seek(pos)
+ hdr = f.read(16)
+ box_size, kind, head = int.from_bytes(hdr[:4], "big"), hdr[4:8], 8
+ if not re.fullmatch(rb"[a-zA-Z0-9 \xa9]{4}", kind):
+ break
+ if box_size == 1 and len(hdr) >= 16:
+ box_size, head = int.from_bytes(hdr[8:16], "big"), 16
+ elif box_size == 0:
+ box_size = size - pos
+ if box_size < head:
+ break
+ iso = iso or kind == b"ftyp"
+ if kind not in _SKIP_BOXES:
+ f.seek(pos)
+ chunk = f.read(min(box_size, limit - total))
+ out.append(chunk)
+ total += len(chunk)
+ pos += box_size
+ if iso:
+ return b"".join(out)
+ f.seek(0)
+ head_bytes = f.read(min(4 << 20, size))
tail = b""
- if size > limit:
- f.seek(max(0, size - limit))
- tail = f.read(limit)
- return head + tail
+ if size > 4 << 20:
+ f.seek(max(0, size - (4 << 20)))
+ tail = f.read(4 << 20)
+ return head_bytes + tail
AIGC_LABEL_ZH = LangDict({"1": "属于 AI 生成合成内容", "2": "可能为 AI 生成合成内容", "3": "疑似 AI 生成合成内容"},
@@ -104,7 +133,7 @@ def provenance(info: VideoInfo) -> dict:
path = Path(info.path)
tags = _flatten_tags(info.raw)
evidence: list[dict] = []
- hints: dict[str, list[str]] = {"generator": [], "editor": [], "renderer": [], "camera": [], "screen": [], "platform": []}
+ hints: dict[str, list[str]] = {"generator": [], "generator_weak": [], "editor": [], "renderer": [], "camera": [], "screen": [], "platform": []}
lower_tags = {k.lower(): v for k, v in tags.items()}
aigc = None
@@ -130,13 +159,18 @@ def provenance(info: VideoInfo) -> dict:
hints[cat].append(label)
evidence.append({"kind": f"{cat}_signature", "detail": T("元数据包含 {l}", "Metadata contains {l}", l=label), "weight": "medium"})
elif cat in ("generator", "renderer", "editor") and re.search(rf"\b(?:{pattern})\b", strings, re.I):
- # weaker: readable string inside container boxes (udta/uuid/xmp)
- hints[cat].append(f"{label}?")
+ # weaker: readable string inside container boxes (udta/uuid/xmp); a generator name here is only a hint
+ # for the report, it does not move the score (short names like "veo" also occur by chance)
+ hints[f"{cat}_weak" if cat == "generator" else cat].append(f"{label}?")
evidence.append({"kind": f"{cat}_bytes", "detail": T("容器内可读字符串出现 {l}", "Readable string {l} found inside the container", l=label), "weight": "weak"})
if b"c2pa" in raw_bytes or b"jumb" in raw_bytes:
- evidence.append({"kind": "c2pa", "detail": T("发现 C2PA/JUMBF 内容凭证盒", "C2PA / JUMBF content-credential box found"), "weight": "strong"})
- hints["generator"].append(T("C2PA 凭证", "C2PA credential"))
+ # cameras (Pixel, Leica ...) sign C2PA too: only a generator named alongside the manifest counts as AI
+ named = hints["generator_weak"]
+ evidence.append({"kind": "c2pa", "detail": T("发现 C2PA/JUMBF 内容凭证盒", "C2PA / JUMBF content-credential box found")
+ + (f"({', '.join(named)})" if named else ""), "weight": "strong" if named else "medium"})
+ if named:
+ hints["generator"].append(T("C2PA 凭证", "C2PA credential") + ":" + ", ".join(n.rstrip("?") for n in named))
if hints["camera"]:
evidence.append({"kind": "camera_tags", "detail": "; ".join(hints["camera"][:4]), "weight": "strong"})
diff --git a/rea_video/review.py b/rea_video/review.py
index 69e531e..df0b169 100644
--- a/rea_video/review.py
+++ b/rea_video/review.py
@@ -5,6 +5,7 @@ into the breakdown so the summary, reports and replication plan reflect what the
from __future__ import annotations
import re
+import shlex
import time
from .classify import LABEL_ZH, LABELS, top
@@ -37,7 +38,7 @@ INSTRUCTIONS = f"""你是这次的 VLM:逐个镜头看图,判断「底层画
{CONFUSIONS}
-每个镜头要填:label_probs(8 类,和为 1)、image_source({"|".join(IMAGE_SOURCES)})、evidence(看到的具体证据)、
+每个镜头要填:label_probs({len(LABELS)} 类,和为 1)、image_source({"|".join(IMAGE_SOURCES)})、evidence(看到的具体证据)、
description(主体、动作、场景、运镜)、embedded_assets(画面里的真实素材:截图、照片、实拍片段、Logo,
kind 取 {"|".join(ASSET_KINDS)},is_real_material 为 true/false)。
某个镜头其实是多刀合并的(暗底图形卡和暗底口播交替时,切点分数低容易被合成一个长镜头)就加 split_suggestion:
@@ -64,6 +65,12 @@ props 道具 / 商品 / Logo(name、note、shots);style 一句整体视觉
- 工具漏掉的贴纸、动图,写进 packaging.missed:{{"t0": 秒, "t1": 秒, "what": "...", "where": "画面位置"}}。"""
+
+def _tiles_cmd(video, t0: float, t1: float, every: float, out: str) -> str:
+ """Shell-ready `rea-video tiles` command (paths quoted: file names often have spaces)."""
+ return (f"rea-video tiles {shlex.quote(str(video))} --start {t0:.2f} --end {t1:.2f} --every {every:g} "
+ f"-o {shlex.quote(out)}")
+
def _priority(rec: dict, ctx: dict) -> tuple[str, list[str]]:
det = (rec.get("deterministic") or {}).get("probs") or {}
probs = sorted(det.items(), key=lambda kv: -kv[1])
@@ -109,8 +116,7 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
"hints": shot_hints(rec["features"], rec["deterministic"]["facts"], dl, dp),
"aspects": {k: v["result"] for k, v in (rec.get("aspects") or {}).items() if v.get("result")},
"images": {"sheet": rec["assets"]["sheet"], "first": rec["assets"]["first_frame"], "last": rec["assets"]["last_frame"]},
- "zoom_cmd": f"rea-video tiles {video} --start {rec['start']:.2f} --end {rec['end']:.2f} --every 0.2 "
- f"-o {out_dir}/check_{rec['id']}.jpg",
+ "zoom_cmd": _tiles_cmd(video, rec["start"], rec["end"], 0.2, f"{out_dir}/check_{rec['id']}.jpg"),
})
pack = breakdown.get("packaging") or {}
pk_tasks, pk_answers = None, None
@@ -119,8 +125,8 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
txt = [c for c in pack.get("text_cues", []) if c["kind"] not in ("subtitle",)]
pk_tasks = {"stickers": [{"id": st["id"], "t0": st["t0"], "t1": st["t1"], "kind_zh": st["kind_zh"], "confidence": st.get("confidence"),
"in_picture": bool(st.get("in_picture")), "image": st.get("image"), "bbox": st["bbox"],
- "frame_cmd": f"rea-video tiles {video} --start {st['t0']:.2f} --end {st['t1']:.2f} --every 0.25 "
- f"-o {out_dir}/check_{st['id']}.jpg"} for st in sts],
+ "frame_cmd": _tiles_cmd(video, st["t0"], st["t1"], 0.25, f"{out_dir}/check_{st['id']}.jpg")}
+ for st in sts],
"text": [{"id": c["id"], "t0": c["t0"], "t1": c["t1"], "text": c["text"], "kind": c["kind"], "style": c.get("style_zh", "")}
for c in txt[:80]]}
pk_answers = {"stickers": [{"id": st["id"], "is_overlay": None, "what": ""} for st in sts],
diff --git a/rea_video/shots.py b/rea_video/shots.py
index 4b6b599..dc6bd20 100644
--- a/rea_video/shots.py
+++ b/rea_video/shots.py
@@ -22,7 +22,7 @@ class FrameTrack:
pix_diff: np.ndarray # mean |diff| of gray thumbs, 0..1
changed: np.ndarray # fraction of thumb pixels that changed noticeably
luma: np.ndarray # mean luma 0..255
- thumbs: list[np.ndarray] = field(repr=False, default_factory=list) # small gray thumbs (for dissolve check)
+ thumbs: list[np.ndarray] = field(repr=False, default_factory=list) # small gray thumbs, uint8 (for dissolve check)
hists: list[np.ndarray] = field(repr=False, default_factory=list)
@property
@@ -83,7 +83,7 @@ def build_track(path: str, info: VideoInfo) -> FrameTrack:
thr = max(6.0, 0.35 * float(min(g.std(), prev_g.std())))
chg.append(float((d > thr).mean()))
luma.append(float(g.mean()))
- thumbs.append(g)
+ thumbs.append(g.astype(np.uint8)) # lossless (gray of uint8 frames); 4x less memory on long videos
hists.append(h)
prev_h, prev_g = h, g
fps = info.fps if info.fps > 0 else 30.0
@@ -149,7 +149,7 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo
for k in sorted({max(2, int(round(fps * 0.12))), max(3, int(round(fps * 0.2))), max(5, int(round(fps * 0.45)))}):
cand = []
for i in range(k, n - k):
- A, B, M = track.thumbs[i - k], track.thumbs[i + k], track.thumbs[i]
+ A, B, M = (track.thumbs[j].astype(np.float32) for j in (i - k, i + k, i))
D = B - A
thr = max(6.0, 0.35 * float(min(A.std(), B.std())))
far = float((np.abs(D) > thr).mean())
@@ -213,7 +213,7 @@ def _mg_beats(track: FrameTrack, boundaries: dict[int, tuple[str, float]], fps:
for (a0, a1), (b0, b1) in zip(runs, runs[1:]):
if any(a1 - 1 <= k <= b0 + 1 for k in boundaries):
continue # already separated by a detected cut/fade
- ta, tb = track.thumbs[(a0 + a1) // 2], track.thumbs[(b0 + b1) // 2]
+ ta, tb = (track.thumbs[j].astype(np.float32) for j in ((a0 + a1) // 2, (b0 + b1) // 2))
thr = max(6.0, 0.35 * float(min(ta.std(), tb.std())))
frac = float((np.abs(ta - tb) > thr).mean())
if frac > 0.12:
diff --git a/rea_video/vlm.py b/rea_video/vlm.py
index 8d43a33..de74cb4 100644
--- a/rea_video/vlm.py
+++ b/rea_video/vlm.py
@@ -14,6 +14,7 @@ import hashlib
import json
import os
import re
+import threading
import time
import urllib.error
import urllib.request
@@ -106,7 +107,10 @@ def parse_json(text: str) -> dict:
m = re.search(r"\{[\s\S]*\}", text)
if not m:
raise ValueError("no JSON object in VLM response")
- return json.loads(m.group(0))
+ out = json.loads(m.group(0))
+ if not isinstance(out, dict):
+ raise ValueError("VLM answer is not a JSON object")
+ return out
class VLMClient:
@@ -118,6 +122,7 @@ class VLMClient:
self.cache_dir = cache_dir
self.dead_requests = 0
self.models = list(cfg.models) # reordered: the last model that answered goes first
+ self._lock = threading.Lock()
host = re.sub(r"^https?://", "", cfg.base_url).split("/")[0].rsplit("@", 1)[-1].split(":")[0]
if cfg.base_url.lower().startswith("http://") and host not in ("localhost", "127.0.0.1", "::1", "[::1]"):
LOG.warning("REA_VLM_BASE_URL 不是 https,API key 会明文发送到 %s", host)
@@ -135,7 +140,15 @@ class VLMClient:
headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.cfg.api_key}"})
with urllib.request.urlopen(req, timeout=self.cfg.timeout) as resp:
data = json.loads(resp.read().decode())
- return data["choices"][0]["message"]["content"]
+ try:
+ content = data["choices"][0]["message"]["content"]
+ except (KeyError, IndexError, TypeError) as exc: # e.g. "choices": [] after a safety block -> try the next model
+ raise ValueError(f"no answer in VLM response: {str(data)[:160]}") from exc
+ if isinstance(content, list): # some gateways return content parts
+ content = "".join(p.get("text", "") for p in content if isinstance(p, dict))
+ if not isinstance(content, str) or not content.strip():
+ raise ValueError("empty VLM answer")
+ return content
def ask_json(self, prompt: str, media: list[tuple[Path, str]], max_tokens: int = 4096) -> dict:
# Use the configured order, not self.models: successful fallbacks reorder
@@ -165,9 +178,10 @@ class VLMClient:
if self.cache_dir:
(self.cache_dir / f"{key}.json").write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
self.dead_requests = 0
- if self.models[0] != model:
- self.models.remove(model)
- self.models.insert(0, model)
+ with self._lock: # shots run in a thread pool
+ if model in self.models and self.models[0] != model:
+ self.models.remove(model)
+ self.models.insert(0, model)
return out
except (urllib.error.URLError, TimeoutError, ValueError, KeyError, json.JSONDecodeError) as exc:
last = exc
@@ -291,8 +305,74 @@ def shot_hints(features: dict, facts: dict, det_top: str, det_prob: float) -> st
return "; ".join(parts)
+def _sec(v) -> float | None:
+ """0.5 / "0.5" / "00:03" / "1:02.5" -> seconds; anything else -> None."""
+ if isinstance(v, bool):
+ return None
+ if isinstance(v, (int, float)):
+ return float(v) if v == v else None
+ if isinstance(v, str):
+ try:
+ parts = [float(x) for x in v.strip().rstrip("s").split(":")]
+ except ValueError:
+ return None
+ if 1 <= len(parts) <= 3:
+ return sum(x * 60 ** i for i, x in enumerate(reversed(parts)))
+ return None
+
+
+_TIME_KEYS = ("t", "t0", "t1", "start", "end")
+
+
+def _items(v) -> list[dict]:
+ """A list of dicts with clean time fields (bad times dropped, not crashing consumers)."""
+ out = []
+ for e in v if isinstance(v, list) else []:
+ if not isinstance(e, dict):
+ continue
+ e = dict(e)
+ for k in _TIME_KEYS:
+ if k in e:
+ sec = _sec(e[k])
+ if sec is None:
+ del e[k]
+ else:
+ e[k] = sec
+ out.append(e)
+ return out
+
+
+def normalize_whole(raw) -> dict | None:
+ """Coerce the whole-video answer to the shape WHOLE_PROMPT asks for, so one malformed field (a model answering
+ "narration": "none", or "t": "00:03") cannot crash finalize -- and keep crashing, since the answer is cached."""
+ if not isinstance(raw, dict):
+ return None
+ w = dict(raw)
+ for k in ("narration", "music", "subtitles", "aspects"):
+ if k in w and not isinstance(w[k], dict):
+ del w[k]
+ for k in ("segments", "sfx", "text_effects", "stickers", "characters", "scenes", "props"):
+ if k in w:
+ w[k] = _items(w[k])
+ for k, sub in (("narration", "lines"), ("music", "segments")):
+ if k in w and sub in w[k]:
+ w[k] = dict(w[k], **{sub: _items(w[k][sub])})
+ for k in ("summary", "format", "hook", "ambience", "mix", "style", "overall_production"):
+ if k in w and w[k] is not None and not isinstance(w[k], str):
+ w[k] = str(w[k])
+ if "warnings" in w and not isinstance(w["warnings"], list):
+ w["warnings"] = [str(w["warnings"])] if w["warnings"] else []
+ return w
+
+
def normalize_shot_result(raw: dict) -> dict:
- probs = raw.get("label_probs") or {}
+ probs = raw.get("label_probs")
+ probs = probs if isinstance(probs, dict) else {}
+ ev = raw.get("evidence")
+ if isinstance(ev, str): # a bare string would otherwise be listed one character per line
+ raw["evidence"] = [ev] if ev.strip() else []
+ elif not isinstance(ev, list):
+ raw["evidence"] = []
clean = {}
for k in LABELS:
try:
diff --git a/tests/test_robustness.py b/tests/test_robustness.py
new file mode 100644
index 0000000..9175860
--- /dev/null
+++ b/tests/test_robustness.py
@@ -0,0 +1,97 @@
+"""Edge cases from the 2026-11 review: low fps, damaged files, malformed VLM answers, engine, exports."""
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from rea_video.media import extract_frame, video_info
+from rea_video.packaging import _ts
+from rea_video.probe import _scan_bytes, provenance
+from rea_video.review import _tiles_cmd
+from rea_video.vlm import VLMClient, VLMConfig, normalize_shot_result, normalize_whole
+
+
+def _ff(*args):
+ subprocess.run(["ffmpeg", "-v", "error", "-y", *args], check=True)
+
+
[email protected](scope="module")
+def fps10(tmp_path_factory) -> Path:
+ p = tmp_path_factory.mktemp("v") / "fps10.mp4"
+ _ff("-f", "lavfi", "-i", "testsrc2=size=160x120:rate=10", "-t", "2", "-pix_fmt", "yuv420p", str(p))
+ return p
+
+
+def test_last_frame_past_final_pts_falls_back(fps10, tmp_path):
+ # 10 fps: end - 0.08 s lies after the last frame's timestamp; used to abort decompose
+ out = extract_frame(fps10, 1.95, tmp_path / "last.jpg", width=160)
+ assert out.is_file() and out.stat().st_size > 0
+
+
+def test_byte_scan_skips_mdat(tmp_path):
+ p = tmp_path / "x.mp4"
+ _ff("-f", "lavfi", "-i", "testsrc2=size=64x64:rate=5", "-t", "1", str(p))
+ raw = p.read_bytes()
+ i = raw.index(b"mdat") + 8
+ p.write_bytes(raw[:i] + b"xxx Veo xxx" + raw[i + 11:]) # random-looking "veo" inside the frame data
+ assert b"Veo" not in _scan_bytes(p)
+ assert not provenance(video_info(p)).get("hints", {}).get("generator")
+
+
+def test_normalize_whole_survives_bad_shapes():
+ w = normalize_whole({"narration": "none", "music": ["x"], "sfx": [{"t": "00:03"}, {"t": None}, "pop"],
+ "segments": [{"start": "1:02.5", "end": "bad"}], "summary": 3})
+ assert "narration" not in w and "music" not in w
+ assert w["sfx"] == [{"t": 3.0}, {}]
+ assert w["segments"] == [{"start": 62.5}]
+ assert w["summary"] == "3"
+ assert normalize_whole("oops") is None
+
+
+def test_merge_audio_with_bad_whole_answer():
+ from rea_video.audio import merge_audio_with_vlm
+
+ w = normalize_whole({"narration": "none", "sfx": [{"t": "00:03"}, {"t": None}]})
+ merge_audio_with_vlm({"has_audio": True, "sfx": {"events": [{"t": 3.1}]}}, w)
+
+
+def test_normalize_shot_result_bad_types():
+ r = normalize_shot_result({"label_probs": [0.5, 0.5], "evidence": "skin texture"})
+ assert r["evidence"] == ["skin texture"] and not any(r["label_probs"].values()) # unusable probs = "no opinion"
+
+
+def test_empty_choices_falls_back_to_next_model(monkeypatch):
+ c = VLMClient(VLMConfig("https://example.invalid/v1", "k", ["m1", "m2"]))
+ calls = []
+
+ def fake_urlopen(req, timeout):
+ import io
+ import json
+
+ model = json.loads(req.data)["model"]
+ calls.append(model)
+ body = {"choices": []} if model == "m1" else {"choices": [{"message": {"content": '{"ok": 1}'}}]}
+
+ class R(io.BytesIO):
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ return R(json.dumps(body).encode())
+
+ monkeypatch.setattr("rea_video.vlm.urllib.request.urlopen", fake_urlopen)
+ monkeypatch.setattr("rea_video.vlm.time.sleep", lambda s: None)
+ assert c.ask_json("p", [])["ok"] == 1
+ assert calls[-1] == "m2"
+
+
+def test_srt_timestamp_carries_into_seconds():
+ assert _ts(3.9996) == "00:00:04,000"
+ assert _ts(59.9997) == "00:01:00,000"
+ assert _ts(1.5, ".") == "00:00:01.500"
+
+
+def test_tiles_cmd_quotes_paths():
+ assert "'/a/my video.mp4'" in _tiles_cmd("/a/my video.mp4", 1, 2, 0.2, "out/c.jpg")