Skip to content

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

Add optional speech recognition and tighten VLM and eval handling

june2e69c2245c20
diff --git a/docs/cli.md b/docs/cli.md
index d063ec1..3eaf08a 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -86,7 +86,7 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name
| 命令 | 作用 |
|---|---|
-| `decompose VIDEO [--vlm] [--no-ocr] [--ocr-lang zh\|ja] [--lang zh\|en] [--no-packaging] [--max-vlm-shots N]` | 拆解,输出 breakdown.json、report.html/md、storyboard.jpg、每镜首尾帧,以及 `packaging/`(字幕 SRT、带样式的 ASS、包装时间轴、贴纸截图);`--lang en` 让结论、报告、`summary` 输出和 VLM 描述都用英文(默认中文;agent 按用户提问的语言选,`rea-video prefs lang en` 可设成默认;breakdown.json 里的 `*_zh` 字段名保留,内容跟报告语言走);`--no-packaging` 跳过包装层(省约每分钟 30–50 秒);`--ocr-lang ja` 用日文识别模型读字幕和花字(首次使用自动下载约 10 MB 到 `$REA_VIDEO_MODELS`,离线时可用 `$REA_OCR_REC_MODEL` 指向本地模型),`rea-video prefs ocr_lang ja` 可设成默认;`--max-vlm-shots N` 是最多发给 VLM 的调用数(默认 60),镜头更多时先看最拿不准的,其余只靠确定性取证,`VLM:` 一行会写明送了多少个 |
+| `decompose VIDEO [--vlm] [--no-ocr] [--ocr-lang zh\|ja] [--lang zh\|en] [--no-packaging] [--max-vlm-shots N] [--no-asr]` | 拆解,输出 breakdown.json、report.html/md、storyboard.jpg、每镜首尾帧,以及 `packaging/`(字幕 SRT、带样式的 ASS、包装时间轴、贴纸截图);`--lang en` 让结论、报告、`summary` 输出和 VLM 描述都用英文(默认中文;agent 按用户提问的语言选,`rea-video prefs lang en` 可设成默认;breakdown.json 里的 `*_zh` 字段名保留,内容跟报告语言走);`--no-packaging` 跳过包装层(省约每分钟 30–50 秒);`--ocr-lang ja` 用日文识别模型读字幕和花字(首次使用自动下载约 10 MB 到 `$REA_VIDEO_MODELS`,离线时可用 `$REA_OCR_REC_MODEL` 指向本地模型),`rea-video prefs ocr_lang ja` 可设成默认;`--max-vlm-shots N` 是最多发给 VLM 的调用数(默认 60),镜头更多时先看最拿不准的,其余只靠确定性取证,`VLM:` 一行会写明送了多少个;装了可选的 `rea-video[asr]` 时会在人声干声上做本地语音识别,带时间的台词写进 `speech.lines` 和报告的脚本表(机器听写,未校对),`--no-asr` 跳过 |
| `review OUT_DIR` | 给能看图的 agent 生成逐镜看图任务(review_tasks.json)和答案模板(review_answers.json) |
| `apply-review OUT_DIR [ANSWERS] [--by NAME] [--lang zh\|en]` | 把 agent 看图的答案和确定性结果融合,重写 breakdown.json 和报告;`--lang` 可以在这一步换报告语言(结论、证据和报告文字重新生成,VLM 已写好的描述和提示词保持原语言) |
| `correct OUT_DIR --shots N --label L [--real yes/no] [--note]` | 用户指出判错:改正结论和报告,并记入记忆(以后同一文件自动套用,同类镜头复核时提示) |
diff --git a/docs/dev/evaluation.md b/docs/dev/evaluation.md
index 1132e40..e5acb47 100644
--- a/docs/dev/evaluation.md
+++ b/docs/dev/evaluation.md
@@ -9,5 +9,5 @@
- `cuts` / `cut_tolerance`:切点真值
- `audio`:`{voice, music, sfx, bpm, key}`
2. 真值要有出处,写在 `source` 字段:生产记录(timeline.json、manifest、cues.py)> 平台 AIGC 标识 > 人工目测(目测的要写"存疑")。
-3. 跑 `rea-video eval eval/xxx.yaml -o out/eval_xxx`。改规则后不需要重新解码:评测会用缓存特征重新分类(`--only id` 只对指定视频重新解码)。
+3. 跑 `rea-video eval eval/xxx.yaml -o out/eval_xxx`。只改分类规则时不用重新解码:评测会用缓存特征重新分类;改了测量视频的代码(解码、切镜、特征、声音、包装)会自动重新解码,不会拿旧特征给新代码打分(`--fresh` 全部重来,`--only id` 只重解指定视频)。清单里的路径找不到时会用 `eval/media/<id>.<扩展名>` 里的备份,仍然缺的会在摘要的 `missing` 里列出。
4. 调规则要防止过拟合:至少保留一组**改规则之后才第一次跑**的留出集,结果写进 `eval/RESULTS.md`。
diff --git a/pyproject.toml b/pyproject.toml
index 56afb64..271b4f0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -25,6 +25,8 @@ ocr = [
"rapidocr-onnxruntime>=1.3,<2; python_version < '3.13'",
"rapidocr>=3.4,<4; python_version >= '3.13'",
]
+# 本地语音识别(SenseVoice,中英日韩粤):没有字幕、没开 VLM 时也能拿到带时间的台词;首次使用下载约 160 MB 模型
+asr = ["sherpa-onnx>=1.12"]
dev = ["pytest>=7", "jsonschema>=4"]
[project.scripts]
diff --git a/rea_video/aspects/base.py b/rea_video/aspects/base.py
index 8011695..4c51702 100644
--- a/rea_video/aspects/base.py
+++ b/rea_video/aspects/base.py
@@ -103,12 +103,19 @@ def get(key: str) -> Aspect | None:
# ---------------------------------------------------------------- what the image readers said ----
+def _fields_of(answers, aspect: str) -> dict:
+ """One aspect's answers. A model sometimes answers a whole aspect with a bare sentence instead of its
+ fields; that reads as "no answer" here, since a stored answer is read again on every later run."""
+ got = answers.get(aspect) if isinstance(answers, dict) else None
+ return got if isinstance(got, dict) else {}
+
+
def seen(shot: dict, aspect: str, field_key: str) -> dict[str, str]:
"""{"agent": ..., "vlm": ...} for one field of one shot. Also reads the older flat `cinematography` answers."""
out = {}
for src, rk in (("agent", "review"), ("vlm", "vlm")):
r = shot.get(rk) or {}
- v = ((r.get("aspects") or {}).get(aspect) or {}).get(field_key) or (r.get("cinematography") or {}).get(field_key)
+ v = _fields_of(r.get("aspects"), aspect).get(field_key) or _fields_of(r, "cinematography").get(field_key)
if v and str(v).strip().lower() not in ("不适用", "unknown", "无法判断", "n/a", "not applicable"):
out[src] = str(v).strip()
return out
@@ -116,10 +123,10 @@ def seen(shot: dict, aspect: str, field_key: str) -> dict[str, str]:
def video_seen(b: dict, aspect: str, field_key: str) -> dict[str, str]:
out = {}
- rv = ((b.get("review_aspects") or {}).get(aspect) or {}).get(field_key)
+ rv = _fields_of(b.get("review_aspects"), aspect).get(field_key)
if rv:
out["agent"] = str(rv)
- wv = ((((b.get("whole_video_vlm") or {}).get("aspects") or {}).get(aspect) or {}).get(field_key))
+ wv = _fields_of(_fields_of(b, "whole_video_vlm").get("aspects"), aspect).get(field_key)
if wv:
out["vlm"] = str(wv)
return out
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 2e4ad46..d7fed02 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -7,7 +7,7 @@ import os
import sys
from pathlib import Path
-from .util import LOG, OCR_LANGS, load_env_files, read_json, setup_logging
+from .util import LOG, OCR_LANGS, load_env_files, read_json, setup_logging, read_image
from .i18n import LANGS, T, set_lang
from .classify import LABELS
from .vlm import vlm_note
@@ -61,7 +61,7 @@ def cmd_decompose(args) -> int:
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,
- packaging=not args.no_packaging, lang=lang, max_shots_vlm=max(1, args.max_vlm_shots))
+ packaging=not args.no_packaging, lang=lang, asr=not args.no_asr, max_shots_vlm=max(1, args.max_vlm_shots))
print(json.dumps({"out": str(out), "verdict": b["summary"]["verdict"], "shots": b["summary"]["shots"],
"confidence": b["summary"]["confidence"], "vlm": b["summary"]["vlm"],
"report": str(out / "report.html")}, ensure_ascii=False, indent=2))
@@ -149,6 +149,10 @@ def cmd_eval(args) -> int:
res = evaluate(Path(args.labels), Path(args.out), use_vlm=args.vlm, ocr=not args.no_ocr, reuse=not args.fresh,
only=set(args.only.split(",")) if args.only else None, stems=args.stems)
print(json.dumps(res["summary"], ensure_ascii=False, indent=2))
+ gone = res["summary"].get("missing")
+ if gone:
+ print("rea-video: " + T("只评了 {n}/{m} 个样本,其余找不到文件:{ids}", "scored {n} of {m} videos, files missing for: {ids}",
+ n=res["summary"]["videos"], m=res["summary"]["videos_listed"], ids=", ".join(gone)), file=sys.stderr)
return 0
@@ -242,7 +246,7 @@ def cmd_tiles(args) -> int:
with tempfile.TemporaryDirectory() as tmpd:
for i, t in enumerate(times):
p = extract_frame(args.video, float(t), Path(tmpd) / f"tile_{i:03d}.jpg", width=args.cell)
- img = cv2.imread(str(p))
+ img = read_image(p)
if img is not None:
frames.append(img)
rows = [frames[i:i + args.cols] for i in range(0, len(frames), args.cols)]
@@ -434,6 +438,7 @@ def main(argv: list[str] | None = None) -> int:
d.add_argument("--max-vlm-shots", type=int, default=60, help="最多发给 VLM 的调用数(默认 60;镜头更多时优先看最拿不准的,其余只靠确定性取证)")
d.add_argument("--engine", help="复刻计划使用的 capsule-cinema 视频引擎(默认 prefs 里的 engine,否则 seedance2.0)")
d.add_argument("--meta", help='平台元数据 JSON,例如 {"music": {"title": "xx", "author": "yy", "is_original": false, "popular": true}}')
+ d.add_argument("--no-asr", action="store_true", help="不做本地语音识别(装了 rea-video[asr] 才会做:在人声干声上识别台词和时间,首次使用下载约 160 MB 模型)")
d.add_argument("--no-stems", action="store_true", help="不做人声/配乐分离(默认会输出 stems/original.wav、vocals.wav、music.wav)")
d.set_defaults(func=cmd_decompose)
diff --git a/rea_video/entities.py b/rea_video/entities.py
index f2e7cc8..e9c9eec 100644
--- a/rea_video/entities.py
+++ b/rea_video/entities.py
@@ -100,6 +100,11 @@ def script(b: dict) -> list[dict]:
rows.append({"start": ln.get("start"), "end": ln.get("end"), "speaker": _s(ln, "speaker", 20), "text": _s(ln, "text", 200)})
if rows:
return rows
+ for ln in ((b.get("speech") or {}).get("lines") or []): # machine transcript: below the VLM's, above segment copy
+ if isinstance(ln, dict) and _s(ln, "text"):
+ rows.append({"start": ln.get("start"), "end": ln.get("end"), "speaker": "", "text": _s(ln, "text", 200), "source": "asr"})
+ if rows:
+ return rows
for seg in w.get("segments") or []:
if isinstance(seg, dict) and _s(seg, "copy"):
rows.append({"start": seg.get("start"), "end": seg.get("end"), "speaker": "", "text": _s(seg, "copy", 200)})
diff --git a/rea_video/evaluate.py b/rea_video/evaluate.py
index af9a649..1460416 100644
--- a/rea_video/evaluate.py
+++ b/rea_video/evaluate.py
@@ -7,7 +7,7 @@ from pathlib import Path
import yaml
from .classify import LABELS
-from .pipeline import PACKAGING_VERSION, decompose, finalize
+from .pipeline import PACKAGING_VERSION, decode_fingerprint, decompose, finalize
from .util import LOG, read_json, round_floats, write_json
@@ -173,7 +173,8 @@ def boundary_f1(pred: list[float], gt: list[float], tol: float = 0.1, ignore: li
used = set()
tp = fp = 0
for p in pred:
- hit = next((i for i, g in enumerate(gt) if i not in used and abs(p - g) <= tol), None)
+ near = [i for i, g in enumerate(gt) if i not in used and abs(p - g) <= tol]
+ hit = min(near, key=lambda i: abs(p - gt[i])) if near else None # the closest true cut, not the first in range
if hit is not None:
used.add(hit)
tp += 1
@@ -193,15 +194,24 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
real_tot = real_ok = 0.0
audio_hits: dict[str, list[bool]] = {}
aspect_hits: dict[str, list[bool]] = {}
+ missing: list[str] = []
for entry in spec["videos"]:
path = _expand(entry["path"])
+ if not Path(path).is_file(): # the listed location is gone: a copy kept under eval/media/<id>.<ext> stands in
+ kept = Path(__file__).resolve().parents[1] / "eval" / "media" / f"{entry['id']}{Path(path).suffix}"
+ path = str(kept) if kept.is_file() else path
if not Path(path).is_file():
LOG.warning("skip %s: missing %s", entry["id"], path)
+ missing.append(entry["id"])
continue
vout = out / entry["id"]
bfile = vout / "breakdown.json"
- if (not only or entry["id"] not in only) and reuse and bfile.is_file() and (not use_vlm or read_json(bfile)["analysis"]["vlm"].get("used")):
- b = read_json(bfile)
+ stored = read_json(bfile) if reuse and bfile.is_file() and (not only or entry["id"] not in only) else None
+ if stored and stored.get("analysis", {}).get("decode_fp") != decode_fingerprint():
+ LOG.info("%s: the measuring code changed since this breakdown was stored, decoding again", entry["id"])
+ stored = None
+ if stored and (not use_vlm or stored["analysis"]["vlm"].get("used")):
+ b = stored
from .media import video_info
from .probe import provenance
@@ -243,7 +253,7 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
b["packaging"] = round_floats(pk)
b = finalize(b, vout) # re-classify with the current rules
else:
- b = decompose(path, vout, use_vlm=use_vlm, ocr=ocr, whole_vlm=False, stems=stems and bool(entry.get("audio")), memory=False)
+ b = decompose(path, vout, use_vlm=use_vlm, ocr=ocr, whole_vlm=False, stems=stems and bool(entry.get("audio")), memory=False, asr=False)
v_tot = v_ok = 0.0
m_tot = m_ok = 0.0
shots = []
@@ -295,7 +305,8 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
tot_dur += v_tot
ok_dur += v_ok
LOG.info("%-28s acc=%s %s", entry["id"], row["accuracy"], b["summary"]["verdict"][:80])
- summary = {"videos": len(rows), "duration_weighted_accuracy": round(ok_dur / tot_dur, 3) if tot_dur else None,
+ # a score over part of the set is not the set's score: say how much of it was there
+ summary = {"videos": len(rows), "videos_listed": len(spec["videos"]), **({"missing": missing} if missing else {}), "duration_weighted_accuracy": round(ok_dur / tot_dur, 3) if tot_dur else None,
"video_accuracy_mean": round(sum(r["accuracy"] for r in rows if r["accuracy"] is not None) / max(1, sum(r["accuracy"] is not None for r in rows)), 3),
"per_video": {r["id"]: r["accuracy"] for r in rows if r["accuracy"] is not None}, "vlm": use_vlm}
if real_tot:
diff --git a/rea_video/motion.py b/rea_video/motion.py
index 5412b8b..fb96256 100644
--- a/rea_video/motion.py
+++ b/rea_video/motion.py
@@ -13,6 +13,7 @@ import cv2
import numpy as np
from .i18n import T
+from .util import write_image
from .media import VideoInfo, iter_frames
W = 180 # analysis width
@@ -437,7 +438,7 @@ def element_crops(path: str | Path, info: VideoInfo, start: float, end: float, m
continue
name = f"{sid}_{tag}_{k:02d}.jpg"
crop = fr[y0:y1, x0:x1]
- cv2.imwrite(str(out_dir / name), crop, [cv2.IMWRITE_JPEG_QUALITY, 94])
+ write_image(out_dir / name, crop, [cv2.IMWRITE_JPEG_QUALITY, 94])
if tag == "ly":
motion["layer"].setdefault("crops", []).append(f"shots/{name}")
else:
@@ -472,5 +473,5 @@ def element_crops(path: str | Path, info: VideoInfo, start: float, end: float, m
sheet[ri * (ch + 26): ri * (ch + 26) + ch + 22, x:x + t.shape[1]] = t
x += t.shape[1] + 4
name = f"{sid}_elements.jpg"
- cv2.imwrite(str(out_dir / name), sheet, [cv2.IMWRITE_JPEG_QUALITY, 90])
+ write_image(out_dir / name, sheet, [cv2.IMWRITE_JPEG_QUALITY, 90])
return f"shots/{name}"
diff --git a/rea_video/packaging.py b/rea_video/packaging.py
index c25f6f3..a34895f 100644
--- a/rea_video/packaging.py
+++ b/rea_video/packaging.py
@@ -32,7 +32,7 @@ import numpy as np
from .media import VideoInfo, extract_frame, iter_frames
from .overlay import get_ocr
-from .util import LOG
+from .util import LOG, read_image, write_image
OCR_FPS = 2.0
OCR_MAX = 240 # OCR calls per video (~0.2 s each)
@@ -1452,13 +1452,13 @@ def analyze(path: str | Path, info: VideoInfo, cuts: list[float], out_dir: Path
for s in stickers:
try:
p = extract_frame(path, (s["t0"] + s["t1"]) / 2, d / f"{s['id']}_frame.jpg", width=720)
- img = cv2.imread(str(p))
+ img = read_image(p)
if img is not None:
H, W = img.shape[:2]
x, y, w, h = s["bbox"]
crop = img[int(y * H):int((y + h) * H), int(x * W):int((x + w) * W)]
if crop.size:
- cv2.imwrite(str(d / f"{s['id']}.jpg"), crop)
+ write_image(d / f"{s['id']}.jpg", crop)
s["image"] = f"packaging/{s['id']}.jpg"
p.unlink(missing_ok=True)
except Exception as exc: # pragma: no cover
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 4a68fb9..71af0f3 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -20,7 +20,7 @@ from .plan import Planner
from .probe import provenance
from .motion import element_crops, motion_events, palette, strip_frames
from .shots import build_track, detect_shots
-from .util import LOG, fmt_time, round_floats, write_json
+from .util import LOG, fmt_time, round_floats, write_json, read_image
from . import aspects
from .faces import shot_faces
from .visual import LABEL_SHORT, shot_sheet, storyboard
@@ -61,9 +61,32 @@ def vlm_units(records: list[dict], max_calls: int) -> list[list[dict]]:
return [units[k] for k in keep]
+# modules that only run in finalize(): a change there needs no new decode. Everything else measures the video.
+_FINALIZE_ONLY = {"classify.py", "report.py", "plan.py", "production.py", "entities.py", "narrative.py", "review.py", "cli.py",
+ "evaluate.py", "remake.py", "memory.py", "i18n.py", "visual.py", "sound_source.py", "__init__.py"}
+_DECODE_FP: str | None = None
+
+
+def decode_fingerprint() -> str:
+ """Hash of the code that measures a video (decode, shots, features, audio, packaging). `rea-video eval`
+ reuses a stored breakdown only while this is unchanged, so a change to the measuring code cannot hide behind
+ features cached from the old code."""
+ global _DECODE_FP
+ if _DECODE_FP is None:
+ import hashlib
+
+ root = Path(__file__).parent
+ h = hashlib.sha1()
+ for f in sorted([*root.glob("*.py"), *root.glob("aspects/*.py")]):
+ if f.name not in _FINALIZE_ONLY or f.parent != root:
+ h.update(f.name.encode() + f.read_bytes())
+ _DECODE_FP = h.hexdigest()[:16]
+ return _DECODE_FP
+
+
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,
- platform_meta: dict | None = None, stems: bool = True, memory: bool = True, packaging: bool = True,
+ platform_meta: dict | None = None, stems: bool = True, memory: bool = True, packaging: bool = True, asr: bool = True,
lang: str = "zh") -> dict:
lang = set_lang(lang)
require_tools()
@@ -258,7 +281,10 @@ 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 = normalize_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")],
+ # a long video has more lines, effects and segments to list: a fixed budget cut
+ # the answer off mid-JSON and the whole pass was paid for and lost
+ max_tokens=int(min(16000, max(6000, 2000 + 100 * info.duration)))))
except Exception as exc:
vlm_info["errors"].append(f"whole: {str(exc)[:160]}")
asked = [r for u in units for r in u]
@@ -272,6 +298,16 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
LOG.warning("VLM: every call failed (%s); result is deterministic only", (vlm_info["errors"] or ["?"])[0])
stem_info: dict = stems_job.result() if stems_job else {}
+ heard: dict = {}
+ if asr and info.has_audio:
+ from . import speech
+
+ if speech.available(): # optional extra; on the vocal stem when there is one, music makes a recognizer invent words
+ on_stem = bool(stem_info.get("ok"))
+ LOG.info("transcribing speech (%s)", "vocal stem" if on_stem else "full mix")
+ heard = dict(speech.transcribe(stem_info["vocals"] if on_stem else video), source="vocals_stem" if on_stem else "mix")
+ else:
+ heard = {"ok": False, "reason": "not_installed"}
breakdown = {
"schema": SCHEMA, "tool": {"name": "rea-video", "version": __version__}, "lang": lang,
"source": {"path": str(video), "filename": video.name, "sha256_head": _sha256_head(video), "width": info.width,
@@ -279,10 +315,11 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
"aspect_ratio": info.aspect_ratio, "has_audio": info.has_audio, "rotation": info.rotation},
"provenance": {k: v for k, v in prov.items() if k != "tags"}, "summary": {},
"audio": round_floats(audio), "global_layers": round_floats(template), "whole_video_vlm": whole,
- "shots": shot_records, "analysis": {"vlm": vlm_info, "ocr": ocr, "seconds": round(time.time() - t0, 1)},
+ "shots": shot_records, "analysis": {"vlm": vlm_info, "ocr": ocr, "seconds": round(time.time() - t0, 1), "decode_fp": decode_fingerprint()},
"assets": {"storyboard": "storyboard.jpg"},
"platform_meta": platform_meta or {},
"stems": {k: (Path(v).name if k in ("original", "vocals", "music") else v) for k, v in stem_info.items()},
+ "speech": heard,
"per_clip_audio": per_clip_audio(str(video), [s.start for s in shots[1:]], info.duration) if info.has_audio else {},
}
if pack is not None:
@@ -706,7 +743,7 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:
import cv2
for r in shot_records:
- img = cv2.imread(str(out / r["assets"]["first_frame"]))
+ img = read_image(out / r["assets"]["first_frame"])
if img is not None:
sb_items.append((img, r["base"]["label"], f"#{r['index']} {LABEL_SHORT.get(r['base']['label'], r['base']['label'])} {r['base']['confidence']:.0%}",
r["start"], r["end"]))
@@ -718,7 +755,7 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:
for rec in shot_records: # breakdowns made before the grade aspect existed: measure it from the saved frames
asp = rec.setdefault("aspects", {})
if rec["base"]["label"] in PHOTOGRAPHIC and not (asp.get("grade") or {}).get("measured"):
- frames = [cv2.imread(str(out / rec["assets"][k])) for k in ("first_frame", "last_frame") if rec.get("assets", {}).get(k)]
+ frames = [read_image(out / rec["assets"][k]) for k in ("first_frame", "last_frame") if rec.get("assets", {}).get(k)]
m = measure_frames([f for f in frames if f is not None])
if m:
asp["grade"] = {"measured": m}
diff --git a/rea_video/production.py b/rea_video/production.py
index 86a4d11..2ecfa6c 100644
--- a/rea_video/production.py
+++ b/rea_video/production.py
@@ -16,6 +16,7 @@ from pathlib import Path
import cv2
+from .util import read_image
from .classify import LABEL_ZH
from .aspects.camera import SUPPORT_ZH
from .plan import CODE_STYLES, Planner, code_scene, shot_prompts
@@ -36,7 +37,7 @@ def _norm(s: str) -> str:
# ---------------------------------------------------------------- scene similarity
def _hist(path: Path):
- im = cv2.imread(str(path))
+ im = read_image(path)
if im is None:
return None
h = cv2.calcHist([cv2.cvtColor(im, cv2.COLOR_BGR2HSV)], [0, 1, 2], None, [18, 4, 4], [0, 180, 0, 256, 0, 256])
@@ -67,7 +68,7 @@ def lit_colours(paths: list[Path], top: int = 3, min_share: float = 0.15) -> lis
votes: dict[tuple, float] = {}
n = 0
for p in paths:
- im = cv2.imread(str(p))
+ im = read_image(p)
if im is None:
continue
hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV).reshape(-1, 3)
diff --git a/rea_video/remake.py b/rea_video/remake.py
index 2d62bf3..1f49274 100644
--- a/rea_video/remake.py
+++ b/rea_video/remake.py
@@ -16,7 +16,7 @@ from pathlib import Path
import cv2
-from .util import LOG, read_json
+from .util import LOG, read_json, read_image
def _ff(args: list[str], cwd: Path | None = None) -> None:
@@ -28,7 +28,7 @@ def render_still_motion(image: Path, out: Path, duration: float, size: tuple[int
analysis_width: int = 480) -> Path:
"""Re-create a Ken Burns move: per-frame similarity transform about the frame centre,
with the zoom rate and pan speed measured during decomposition."""
- img = cv2.imread(str(image))
+ img = read_image(image)
if img is None:
raise FileNotFoundError(image)
w, h = size
diff --git a/rea_video/report.py b/rea_video/report.py
index 71f9428..b48cd87 100644
--- a/rea_video/report.py
+++ b/rea_video/report.py
@@ -205,6 +205,8 @@ def _content_md(b: dict) -> list[str]:
head = T("**脚本**", "**Script**")
if n.get("type") and n.get("type") != "none":
head += T("({t}{v})", " ({t}{v})", t=NARR_ZH.get(n["type"], n["type"]), v=(T(",", ", ") + n["voice"]) if n.get("voice") else "")
+ if lines[0].get("source") == "asr":
+ head += T("(本地语音识别,未校对;同音字和专有名词以画面字幕为准)", " (local speech recognition, unchecked; trust on-screen subtitles for names and homophones)")
L += ["", head]
L += _table([T("时间", "Time"), T("谁", "Who"), T("台词 / 旁白", "Line")],
[[_span(ln["start"], ln["end"]), ln["speaker"] or T("旁白", "narration"), ln["text"]] for ln in lines], fold_title=T("全部 {n} 句", "all {n} lines", n=len(lines)))
diff --git a/rea_video/review.py b/rea_video/review.py
index b8e849b..bbd3cc8 100644
--- a/rea_video/review.py
+++ b/rea_video/review.py
@@ -59,7 +59,7 @@ video_prompt(复刻该镜头的<PROMPT_LANG>视频提示词:先写景别、
最后在答案顶层的 aspects 里写整片:机位/场景、推测设备、整体布光、剪辑手法、视频形式。
每个镜头再填 narrative(这个镜头在讲什么):role 选它在叙事上的作用,point 用一句话写它讲的那一点(去掉具体的人和产品也成立的写法,
-例如"用反常识的数字开场"而不是"说水豚每天睡 12 小时")。先通读 storyboard.jpg 和每镜的 said(这一镜里的字幕)再填,作用是相对整片说的:
+例如"用反常识的数字开场"而不是"说水豚每天睡 12 小时")。先通读 storyboard.jpg 和每镜的 said(这一镜里的字幕;没有字幕时是语音识别听到的话,可能有同音错字)再填,作用是相对整片说的:
{ROLE_GUIDE}
报告会把它连成「叙事线」:复刻时保留这条线,把案例和素材换成自己的。
@@ -122,6 +122,9 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
subs = [c for c in (breakdown.get("packaging") or {}).get("text_cues", []) if c.get("kind") == "subtitle" and c.get("text")]
for rec in breakdown["shots"]:
said[rec["index"]] = " ".join(c["text"] for c in subs if rec["start"] <= (c["t0"] + c["t1"]) / 2 < rec["end"])[:160]
+ if not said[rec["index"]]: # no burned-in subtitles here: what the recognizer heard, when it ran
+ said[rec["index"]] = " ".join(ln["text"] for ln in (breakdown.get("speech") or {}).get("lines") or []
+ if rec["start"] <= (ln["start"] + ln["end"]) / 2 < rec["end"])[:160]
for rec in breakdown["shots"]:
# only the deterministic layer is shown: the agent should judge independently of any VLM answer
ranked = sorted(rec["deterministic"]["probs"].items(), key=lambda kv: -kv[1])
diff --git a/rea_video/speech.py b/rea_video/speech.py
new file mode 100644
index 0000000..15255fb
--- /dev/null
+++ b/rea_video/speech.py
@@ -0,0 +1,172 @@
+"""Local speech-to-text: what is said and when, without a VLM and without burned-in subtitles.
+
+Optional: `pip install "rea-video[asr]"` (sherpa-onnx, which runs on the onnxruntime stack the stems model
+already uses). The recognizer is SenseVoice (Chinese / English / Japanese / Korean / Cantonese); a voice-activity
+detector cuts the track into spoken stretches first, so every line has a start and an end. About 160 MB is
+downloaded on first use. Run it on the separated vocal stem when there is one: music under the voice is what
+makes a recognizer invent words.
+
+The text is a machine transcript. On-screen subtitles and a VLM's transcript outrank it wherever they exist.
+"""
+from __future__ import annotations
+
+import importlib.util
+import os
+import re
+import tarfile
+import uuid
+from pathlib import Path
+
+import numpy as np
+
+from .media import extract_audio
+from .stems import models_dir
+from .util import LOG, fetch, sha256_file
+
+SR = 16000
+BASE_URL = "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models"
+MODEL_DIR = "sherpa-onnx-sense-voice-zh-en-ja-ko-yue-int8-2024-07-17"
+ARCHIVE_SHA256 = "7d1efa2138a65b0b488df37f8b89e3d91a60676e416f515b952358d83dfd347e"
+MODEL_FILES = ("model.int8.onnx", "tokens.txt")
+VAD_NAME = "silero_vad.onnx"
+VAD_SHA256 = "9e2449e1087496d8d4caba907f23e0bd3f78d91fa552479bb9c23ac09cbb1fd6"
+MAX_SENTENCE_S = 6.0 # a longer stretch is shown sentence by sentence
+MAX_LINE_S = 12.0 # a stretch of speech longer than this is split, so one line stays one subtitle-sized thought
+LANGS = ("zh", "en", "ja", "ko", "yue")
+
+
+def available() -> bool:
+ return importlib.util.find_spec("sherpa_onnx") is not None
+
+
+def ensure_models() -> tuple[Path, Path, Path]:
+ """-> (recognizer model, tokens, vad model), downloading and checking them on first use."""
+ root = models_dir()
+ d = root / MODEL_DIR
+ vad = root / VAD_NAME
+ root.mkdir(parents=True, exist_ok=True)
+ if not (vad.is_file() and sha256_file(vad) == VAD_SHA256):
+ tmp = vad.with_name(f"{vad.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part")
+ try:
+ fetch(f"{BASE_URL}/{VAD_NAME}", tmp)
+ if sha256_file(tmp) != VAD_SHA256:
+ raise OSError(f"checksum mismatch for {VAD_NAME}")
+ tmp.replace(vad)
+ finally:
+ tmp.unlink(missing_ok=True)
+ if not all((d / f).is_file() for f in MODEL_FILES):
+ LOG.info("downloading speech model %s (~160 MB) -> %s", MODEL_DIR, d)
+ arc = root / f"{MODEL_DIR}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part"
+ stage = root / f"{MODEL_DIR}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp"
+ try:
+ fetch(f"{BASE_URL}/{MODEL_DIR}.tar.bz2", arc, timeout=120)
+ if sha256_file(arc) != ARCHIVE_SHA256:
+ raise OSError(f"checksum mismatch for {MODEL_DIR}.tar.bz2")
+ stage.mkdir()
+ with tarfile.open(arc, "r:bz2") as tar:
+ for name in MODEL_FILES: # only the two files needed, written under our own names: no archive path is trusted
+ src = tar.extractfile(f"{MODEL_DIR}/{name}")
+ if src is None:
+ raise OSError(f"{name} missing from the model archive")
+ with open(stage / name, "wb") as f:
+ while chunk := src.read(1 << 20):
+ f.write(chunk)
+ if d.exists(): # an incomplete earlier copy
+ for f in d.iterdir():
+ f.unlink()
+ d.rmdir()
+ stage.replace(d)
+ finally:
+ arc.unlink(missing_ok=True)
+ if stage.exists():
+ for f in stage.iterdir():
+ f.unlink()
+ stage.rmdir()
+ return d / MODEL_FILES[0], d / MODEL_FILES[1], vad
+
+
+def _stretches(x: np.ndarray, vad_model: Path) -> list[tuple[float, np.ndarray]]:
+ """Spoken stretches of a 16 kHz mono track: (start second, samples)."""
+ import sherpa_onnx
+
+ cfg = sherpa_onnx.VadModelConfig()
+ cfg.silero_vad.model = str(vad_model)
+ cfg.silero_vad.min_silence_duration = 0.3
+ cfg.silero_vad.min_speech_duration = 0.25
+ cfg.silero_vad.max_speech_duration = MAX_LINE_S
+ cfg.sample_rate = SR
+ vad = sherpa_onnx.VoiceActivityDetector(cfg, buffer_size_in_seconds=60)
+ win = cfg.silero_vad.window_size
+ out: list[tuple[float, np.ndarray]] = []
+
+ def drain() -> None:
+ while not vad.empty():
+ seg = vad.front
+ out.append((seg.start / SR, np.array(seg.samples, dtype=np.float32)))
+ vad.pop()
+
+ for i in range(0, len(x) - win + 1, win):
+ vad.accept_waveform(x[i:i + win])
+ drain()
+ vad.flush()
+ drain()
+ return out
+
+
+def _sentences(start: float, end: float, text: str) -> list[dict]:
+ """One spoken stretch as lines. A long stretch is split at sentence ends, each sentence given its share of
+ the time by length: inside a stretch the times are an estimate, the stretch's own start and end are measured."""
+ parts = [p.strip() for p in re.split(r"(?<=[。!?!?])|(?<=\.)(?=\s)", text) if p and p.strip()]
+ if end - start <= MAX_SENTENCE_S:
+ return [{"start": round(start, 2), "end": round(end, 2), "text": text}]
+ if len(parts) < 2: # one run-on sentence: break at commas into pieces of about MAX_SENTENCE_S
+ clauses = [c for c in re.split(r"(?<=[,,;;])", text) if c.strip()]
+ want = max(1, round(len(text) * MAX_SENTENCE_S / (end - start)))
+ parts = []
+ for c in clauses:
+ if parts and len(parts[-1]) + len(c) <= want:
+ parts[-1] += c
+ else:
+ parts.append(c)
+ parts = [p.strip() for p in parts]
+ if len(parts) < 2:
+ return [{"start": round(start, 2), "end": round(end, 2), "text": text}]
+ total = sum(len(p) for p in parts)
+ out, t = [], start
+ for p in parts:
+ z = t + (end - start) * len(p) / total
+ out.append({"start": round(t, 2), "end": round(z, 2), "text": p, "timing": "estimated"})
+ t = z
+ return out
+
+
+def transcribe(audio: str | Path, language: str = "auto", threads: int = 2) -> dict:
+ """{"ok", "engine", "language", "lines": [{"start", "end", "text"}]}; ok=False with a reason when it cannot run."""
+ if not available():
+ return {"ok": False, "reason": "not_installed"}
+ x = extract_audio(audio, SR)
+ if x is None or len(x) < SR // 2:
+ return {"ok": False, "reason": "no audio"}
+ try:
+ import sherpa_onnx
+
+ model, tokens, vad_model = ensure_models()
+ rec = sherpa_onnx.OfflineRecognizer.from_sense_voice(model=str(model), tokens=str(tokens), num_threads=threads, use_itn=True,
+ language=language if language in LANGS else "")
+ lines, langs = [], []
+ for start, samples in _stretches(x, vad_model):
+ st = rec.create_stream()
+ st.accept_waveform(SR, samples)
+ rec.decode_stream(st)
+ text = (st.result.text or "").strip()
+ if len(text.strip("。,、!?.,!? ")) < 1:
+ continue
+ lines += _sentences(start, start + len(samples) / SR, text)
+ lang = str(getattr(st.result, "lang", "") or "").strip("<|>")
+ if lang:
+ langs.append(lang)
+ except Exception as exc: # offline on first use, a broken wheel: the breakdown goes on without a transcript
+ LOG.warning("speech recognition failed: %s", str(exc)[:200])
+ return {"ok": False, "reason": f"{type(exc).__name__}: {str(exc)[:120]}"}
+ return {"ok": True, "engine": "sensevoice-small-int8 (sherpa-onnx)", "language": max(set(langs), key=langs.count) if langs else "",
+ "lines": lines}
diff --git a/rea_video/util.py b/rea_video/util.py
index 4d919f3..bc78c44 100644
--- a/rea_video/util.py
+++ b/rea_video/util.py
@@ -68,6 +68,29 @@ def _json_default(value: Any) -> Any:
return str(value)
+def read_image(path):
+ """cv2.imread that also opens paths with non-ASCII characters on Windows (imread goes through the ANSI
+ file API there and returns None for a Chinese folder name). None when the file is missing or unreadable."""
+ import cv2
+ import numpy as np
+
+ try:
+ data = np.fromfile(str(path), dtype=np.uint8)
+ except OSError:
+ return None
+ return cv2.imdecode(data, cv2.IMREAD_COLOR) if data.size else None
+
+
+def write_image(path, img, params: list[int] | None = None) -> bool:
+ """cv2.imwrite counterpart of read_image; the format follows the file extension."""
+ import cv2
+
+ ok, buf = cv2.imencode(Path(path).suffix or ".jpg", img, params or [])
+ if ok:
+ buf.tofile(str(path))
+ return bool(ok)
+
+
def fetch(url: str, dest: Path, timeout: float = 60.0) -> None:
"""Download url to dest. The timeout is per read, so a stalled connection raises instead of hanging the run."""
import shutil
diff --git a/rea_video/vlm.py b/rea_video/vlm.py
index f60dbd5..0128b8a 100644
--- a/rea_video/vlm.py
+++ b/rea_video/vlm.py
@@ -6,6 +6,10 @@ Config (first non-empty wins):
GEMINI3_BASE_URL / GEMINI3_API_KEY / GEMINI3_MODEL_NAME (capsule-cinema)
REA_VLM_MODEL may be a comma-separated fallback list.
REA_VLM_MEDIA = both | video | frames (default both: a short clip as data:video/mp4 plus keyframes)
+REA_VLM_VIDEO_PART = image_url | video_url (how a clip is attached; unset: image_url, switching to video_url by
+ itself when the endpoint refuses the first form, as DashScope does)
+REA_VLM_REASONING_EFFORT = low | medium | high (passed through when set; thinking models answer these prompts
+ several times faster and cheaper on low)
"""
from __future__ import annotations
@@ -35,6 +39,8 @@ class VLMConfig:
models: list[str]
timeout: float = 180.0
media: str = "both"
+ video_part: str = "" # "" = find out: image_url first, video_url if that is refused
+ reasoning_effort: str = ""
@classmethod
def from_env(cls) -> "VLMConfig | None":
@@ -49,7 +55,9 @@ class VLMConfig:
if cfg is None:
cfg = cls(base_url=base, api_key=key, models=models,
timeout=float(os.getenv("REA_VLM_TIMEOUT", os.getenv("VIDEO_ANALYSIS_TIMEOUT_SECONDS", "180"))),
- media=os.getenv("REA_VLM_MEDIA", "both"))
+ media=os.getenv("REA_VLM_MEDIA", "both"),
+ video_part=os.getenv("REA_VLM_VIDEO_PART", "").strip().lower(),
+ reasoning_effort=os.getenv("REA_VLM_REASONING_EFFORT", "").strip().lower())
elif prefix != "REA_VLM" and base == cfg.base_url and key == cfg.api_key:
cfg.models += [m for m in models if m not in cfg.models]
return cfg
@@ -130,6 +138,8 @@ 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.video_part = cfg.video_part if cfg.video_part in ("image_url", "video_url") else "image_url"
+ self._part_settled = cfg.video_part in ("image_url", "video_url") # set by the user, or learned from an answer / a second refusal
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]"):
@@ -143,7 +153,8 @@ class VLMClient:
def _post(self, model: str, content: list[dict], max_tokens: int) -> str:
body = json.dumps({"model": model, "messages": [{"role": "user", "content": content}],
- "max_tokens": max_tokens, "temperature": 0.2}).encode()
+ "max_tokens": max_tokens, "temperature": 0.2,
+ **({"reasoning_effort": self.cfg.reasoning_effort} if self.cfg.reasoning_effort else {})}).encode()
# urllib's default "Python-urllib/x.y" gets a 403 from some gateways, which looks like a bad key
req = urllib.request.Request(self.cfg.base_url + "/chat/completions", data=body, method="POST",
headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.cfg.api_key}",
@@ -164,7 +175,8 @@ class VLMClient:
# Use the configured order, not self.models: successful fallbacks reorder
# the latter during a run. Never include the API key in the cache identity.
request = {"prompt": prompt, "base_url": self.cfg.base_url.rstrip("/"),
- "models": self.cfg.models, "max_tokens": max_tokens}
+ "models": self.cfg.models, "max_tokens": max_tokens,
+ **({"reasoning_effort": self.cfg.reasoning_effort} if self.cfg.reasoning_effort else {})}
h = hashlib.sha1(json.dumps(request, sort_keys=True, ensure_ascii=False).encode())
for p, mime in media:
h.update(mime.encode())
@@ -180,8 +192,16 @@ class VLMClient:
pass # a half-written file from an interrupted run: ask again
if self.gave_up:
raise RuntimeError("VLM skipped: service failed on every model for earlier requests")
- content = [{"type": "image_url", "image_url": {"url": _data_uri(p, mime)}} for p, mime in media]
- content.append({"type": "text", "text": prompt})
+ has_video = any(mime.startswith("video/") for _, mime in media)
+ part = self.video_part
+ swapped = False
+
+ def build(video_part: str) -> list[dict]:
+ parts = [{"type": video_part, video_part: {"url": _data_uri(p, mime)}} if mime.startswith("video/")
+ else {"type": "image_url", "image_url": {"url": _data_uri(p, mime)}} for p, mime in media]
+ return parts + [{"type": "text", "text": prompt}]
+
+ content = build(part)
last: Exception | None = None
refused = False
for model in list(self.models):
@@ -198,6 +218,8 @@ class VLMClient:
tmp.replace(cached)
with self._lock: # shots run in a thread pool
self.dead_requests = 0
+ if has_video:
+ self.video_part, self._part_settled = part, True
if model in self.models and self.models[0] != model:
self.models.remove(model)
self.models.insert(0, model)
@@ -210,6 +232,14 @@ class VLMClient:
last = RuntimeError(f"HTTP {exc.code} {exc.reason}: {why}" if why else f"HTTP {exc.code} {exc.reason}")
LOG.warning("VLM %s attempt %d failed: %s", model, attempt + 1, str(last)[:200])
if exc.code in self.REQUEST_ERRORS:
+ if has_video and not self._part_settled and not swapped:
+ # some endpoints take a clip only as a video_url part: try that form once
+ part, swapped = "video_url", True
+ content = build(part)
+ continue
+ if swapped: # refused both ways: this endpoint does not take clips, stop trying the other form
+ with self._lock:
+ self._part_settled = True
# this request is what the endpoint refuses (too large, video not accepted): the same
# bytes will not pass a second time, and other shots are not affected
refused = True
diff --git a/skills/rea-video/references/setup.md b/skills/rea-video/references/setup.md
index 4e7b0f8..3ceb96e 100644
--- a/skills/rea-video/references/setup.md
+++ b/skills/rea-video/references/setup.md
@@ -16,6 +16,20 @@ pip 报 `externally-managed-environment`(Homebrew / 新版 Ubuntu 的系统 Py
在 Python 3.12 及以下手动装了 `[ocr]` 时,OCR 依赖会再装一套 `opencv-python`,和 rea-video 用的 `opencv-python-headless` 抢同一个 `cv2` 目录。装完跑一次:
`pip uninstall -y opencv-python && pip install --force-reinstall --no-deps "opencv-python-headless>=4.8,<5"`(`install_skill.sh` 会自动做)。
+## 本地语音识别(可选)
+
+没有烧录字幕、也没开能听声音的 VLM 时,台词从哪来?装上可选的语音识别:
+
+```bash
+pip install "rea-video[ocr,asr] @ git+https://github.com/JuneYaooo/rea-video" # 已装过就 pip install sherpa-onnx
+```
+
+装了之后 `decompose` 会自动在分离出的人声干声上识别(SenseVoice,中 / 英 / 日 / 韩 / 粤;首次使用下载约 160 MB 模型到 `$REA_VIDEO_MODELS`,默认 `~/.cache/rea-video/models`),
+一分钟的片子几秒钟。结果在 `breakdown.json` 的 `speech.lines`(每句有起止时间),报告「脚本」表和 `review_tasks.json` 每镜的 `said` 会用它。`--no-asr` 可跳过。
+
+这是机器听写,会有同音错字、专有名词听错:画面上有字幕时以字幕为准,VLM 给了台词时报告用 VLM 的;引用台词给用户时注明"语音识别,未校对"。
+长句里逐句的时间是按字数估的(`timing: estimated`),整段的起止是测出来的。没装时 `speech.reason` 是 `not_installed`,其余照常。
+
## VLM 配置(建议,不强制)
**VLM(建议配置,不强制)**:VLM 是能看图/看视频的多模态大模型(Gemini、GPT-4o、豆包、Qwen-VL 等)。不开 VLM,工具只靠像素统计、帧率、OCR、元数据判断,照样能跑完、出报告,但**实拍 / AI / 3D 的区分明显变弱**,音效清单也只有信号层的低置信候选。开了 VLM,工具会把每个镜头的短片段和关键帧发给它,再和确定性结果融合。
diff --git a/tests/test_evaluate.py b/tests/test_evaluate.py
new file mode 100644
index 0000000..ede84e6
--- /dev/null
+++ b/tests/test_evaluate.py
@@ -0,0 +1,45 @@
+"""The scorer behind every published number: label lookup, cut matching, and what it does with missing or stale inputs."""
+import yaml
+
+from rea_video import evaluate as E
+from rea_video.classify import LABELS
+
+
+def test_label_lookup_by_time():
+ entry = {"segments": [[0, 2, "ai_video"], [2, 5, ["live_action", "film_footage"]]]}
+ assert E.gt_at(entry, 1.0) == {"ai_video"} and E.gt_at(entry, 2.0) == {"live_action", "film_footage"}
+ assert E.gt_at(entry, 5.0) is None and E.gt_at({"audio": {}}, 1.0) is None
+ assert E.gt_at({"label": "cg_3d"}, 9.0) == {"cg_3d"}
+
+
+def test_real_material_lookup():
+ assert E.real_at({}, 1.0) is None and E.real_at({"real_material": True}, 1.0) is True
+ assert E.real_at({"real_material": [[0, 2, True], [2, 4, False]]}, 3.0) is False
+ assert E.real_at({"real_material": [[0, 2, True]]}, 3.0) is None
+
+
+def test_cut_matching_counts_each_true_cut_once_and_takes_the_nearest():
+ r = E.boundary_f1([1.0, 2.0, 2.05, 7.0], [1.02, 2.04, 5.0], tol=0.1)
+ assert (r["tp"], r["fp"], r["fn"]) == (2, 2, 1) and r["precision"] == 0.5 and r["recall"] == 0.667
+ # two true cuts inside the tolerance of one prediction: it takes the nearer, leaving the other for the next
+ assert E.boundary_f1([1.08, 1.0], [1.0, 1.09], tol=0.1)["tp"] == 2
+ assert E.boundary_f1([3.0], [], ignore=[3.02])["fp"] == 0
+ assert E.boundary_f1([], [])["f1"] == 1.0
+
+
+def test_missing_files_are_reported_and_stale_breakdowns_are_decoded_again(media, tmp_path, monkeypatch):
+ labels = tmp_path / "labels.yaml"
+ labels.write_text(yaml.safe_dump({"videos": [{"id": "here", "path": str(media["edit"]), "label": list(LABELS)},
+ {"id": "gone", "path": str(tmp_path / "gone.mp4"), "label": "ai_video"}]}), encoding="utf-8")
+ out = tmp_path / "out"
+ s = E.evaluate(labels, out, ocr=False)["summary"]
+ assert s["videos"] == 1 and s["videos_listed"] == 2 and s["missing"] == ["gone"] and s["duration_weighted_accuracy"] == 1.0
+
+ calls = []
+ real = E.decompose
+ monkeypatch.setattr(E, "decompose", lambda *a, **k: calls.append(1) or real(*a, **k))
+ E.evaluate(labels, out, ocr=False)
+ assert calls == [] # same measuring code: the stored breakdown is reused
+ monkeypatch.setattr(E, "decode_fingerprint", lambda: "changed")
+ E.evaluate(labels, out, ocr=False)
+ assert calls == [1]
diff --git a/tests/test_robustness.py b/tests/test_robustness.py
index 625b8a9..5af27f3 100644
--- a/tests/test_robustness.py
+++ b/tests/test_robustness.py
@@ -248,3 +248,77 @@ def test_vlm_note_says_when_shots_were_left_out():
set_lang("zh")
assert "60/200" in vlm_note({"status": "ok", "model": "m", "asked_shots": 60, "total_shots": 200})
assert "/" not in vlm_note({"status": "ok", "model": "m", "asked_shots": 5, "total_shots": 5})
+
+
+def test_whole_aspect_answered_as_a_sentence_does_not_break_the_report():
+ from rea_video.aspects.base import seen, video_seen
+
+ b = {"whole_video_vlm": {"aspects": {"format": "单人口播"}}, "review_aspects": "n/a"}
+ assert video_seen(b, "format", "format") == {}
+ assert seen({"vlm": {"aspects": {"camera": "手持"}}, "review": {"aspects": ["x"]}}, "camera", "angle") == {}
+ assert video_seen({"whole_video_vlm": {"aspects": {"format": {"format": "口播"}}}}, "format", "format") == {"vlm": "口播"}
+
+
+def test_images_read_and_write_under_a_non_ascii_path(tmp_path):
+ import numpy as np
+
+ from rea_video.util import read_image, write_image
+
+ p = tmp_path / "对标视频" / "首帧.jpg"
+ p.parent.mkdir()
+ assert write_image(p, np.full((8, 8, 3), 200, np.uint8)) and read_image(p).shape == (8, 8, 3)
+ assert read_image(tmp_path / "missing.jpg") is None
+
+
+def test_clip_is_resent_as_video_url_when_the_first_form_is_refused(monkeypatch, tmp_path):
+ import io
+ import json
+
+ clip = tmp_path / "c.mp4"
+ clip.write_bytes(b"not really a video")
+ c = VLMClient(VLMConfig("https://example.invalid/v1", "k", ["m1"]))
+ kinds = []
+
+ class R(io.BytesIO):
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def fake_urlopen(req, timeout):
+ body = json.loads(req.data)
+ kind = body["messages"][0]["content"][0]["type"]
+ kinds.append(kind)
+ assert "reasoning_effort" not in body
+ if kind == "image_url":
+ raise _http_error(400, b"The image format is illegal")
+ return R(json.dumps({"choices": [{"message": {"content": '{"ok": 1}'}}]}).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", [(clip, "video/mp4")])["ok"] == 1
+ assert c.ask_json("p2", [(clip, "video/mp4")])["ok"] == 1
+ assert kinds == ["image_url", "video_url", "video_url"] # learned once, not rediscovered per shot
+
+
+def test_reasoning_effort_is_passed_through_when_set(monkeypatch):
+ import io
+ import json
+
+ seen = []
+
+ class R(io.BytesIO):
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def fake_urlopen(req, timeout):
+ seen.append(json.loads(req.data).get("reasoning_effort"))
+ return R(json.dumps({"choices": [{"message": {"content": '{"ok": 1}'}}]}).encode())
+
+ monkeypatch.setattr("rea_video.vlm.urllib.request.urlopen", fake_urlopen)
+ VLMClient(VLMConfig("https://example.invalid/v1", "k", ["m1"], reasoning_effort="low")).ask_json("p", [])
+ assert seen == ["low"]
diff --git a/tests/test_speech.py b/tests/test_speech.py
new file mode 100644
index 0000000..c28880c
--- /dev/null
+++ b/tests/test_speech.py
@@ -0,0 +1,61 @@
+"""Local speech recognition: optional, checksummed model, sentence timing, and where the transcript is used."""
+import hashlib
+import io
+import json
+import tarfile
+
+import pytest
+
+from rea_video import speech
+from rea_video.entities import script
+
+
+def test_long_stretch_is_split_into_sentences_with_estimated_times():
+ rows = speech._sentences(10.0, 20.0, "今天教大家做视频。先保存图片!然后打开工具")
+ assert [r["text"] for r in rows] == ["今天教大家做视频。", "先保存图片!", "然后打开工具"]
+ assert rows[0]["start"] == 10.0 and rows[-1]["end"] == 20.0 and all(r["timing"] == "estimated" for r in rows)
+ assert all(a["end"] == b["start"] for a, b in zip(rows, rows[1:]))
+ assert speech._sentences(1.0, 4.0, "短句。也短。") == [{"start": 1.0, "end": 4.0, "text": "短句。也短。"}]
+
+
+def test_transcribe_without_the_extra_says_so(monkeypatch, tmp_path):
+ monkeypatch.setattr(speech, "available", lambda: False)
+ assert speech.transcribe(tmp_path / "x.wav") == {"ok": False, "reason": "not_installed"}
+
+
+def _archive(files: dict) -> bytes:
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w:bz2") as tar:
+ for name, data in files.items():
+ info = tarfile.TarInfo(name)
+ info.size = len(data)
+ tar.addfile(info, io.BytesIO(data))
+ return buf.getvalue()
+
+
+def test_models_are_checked_and_only_the_needed_files_are_unpacked(monkeypatch, tmp_path):
+ monkeypatch.setenv("REA_VIDEO_MODELS", str(tmp_path))
+ arc = _archive({f"{speech.MODEL_DIR}/model.int8.onnx": b"model", f"{speech.MODEL_DIR}/tokens.txt": b"tok",
+ f"{speech.MODEL_DIR}/test_wavs/zh.wav": b"wav", "../escape.txt": b"x"})
+ served = {speech.VAD_NAME: b"vad", f"{speech.MODEL_DIR}.tar.bz2": arc}
+ monkeypatch.setattr(speech, "fetch", lambda url, dst, timeout=60: open(dst, "wb").write(served[url.rsplit("/", 1)[-1]]))
+ monkeypatch.setattr(speech, "VAD_SHA256", hashlib.sha256(b"vad").hexdigest())
+ with pytest.raises(OSError): # the archive does not match the pinned checksum
+ speech.ensure_models()
+ assert sorted(p.name for p in tmp_path.iterdir()) == [speech.VAD_NAME]
+ monkeypatch.setattr(speech, "ARCHIVE_SHA256", hashlib.sha256(arc).hexdigest())
+ model, tokens, vad = speech.ensure_models()
+ assert model.read_bytes() == b"model" and tokens.read_bytes() == b"tok" and vad.read_bytes() == b"vad"
+ assert sorted(p.name for p in model.parent.iterdir()) == ["model.int8.onnx", "tokens.txt"]
+ assert sorted(p.name for p in tmp_path.iterdir()) == sorted([speech.MODEL_DIR, speech.VAD_NAME]) and not (tmp_path.parent / "escape.txt").exists()
+ monkeypatch.setattr(speech, "fetch", lambda *a, **k: pytest.fail("should not download again"))
+ speech.ensure_models()
+
+
+def test_script_uses_the_transcript_below_the_vlm_and_above_segment_copy():
+ heard = {"ok": True, "lines": [{"start": 0.1, "end": 2.0, "text": "大家好"}]}
+ b = {"speech": heard, "whole_video_vlm": {"segments": [{"start": 0, "end": 2, "copy": "分段文案"}]}}
+ assert script(b) == [{"start": 0.1, "end": 2.0, "speaker": "", "text": "大家好", "source": "asr"}]
+ b["whole_video_vlm"]["narration"] = {"lines": [{"start": 0, "end": 2, "speaker": "A", "text": "模型听到的"}]}
+ assert script(b)[0]["text"] == "模型听到的"
+ json.dumps(script(b))