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

Improve robustness of decoding, VLM calls and provenance checks

june210aee8e1a9b
diff --git a/rea_video/audio.py b/rea_video/audio.py
index f8f8a50..686dd5f 100644
--- a/rea_video/audio.py
+++ b/rea_video/audio.py
@@ -525,8 +525,8 @@ def merge_audio_with_vlm(audio: dict, whole: dict | None) -> dict:
music = audio.get("music", {})
plan = []
if voice.get("present") or n.get("type") in ("tts", "human", "mixed"):
- plan.append({"track": "voice", "rule": "A01-narration" if n.get("type") != "human" else "A01-narration",
- "what": (T("TTS 旁白", "TTS voice-over") if n.get('type') == 'tts' else (T("真人口播/对白", "human talking head / dialogue") if n.get('type') == 'human' else T("人声", "voice"))
+ plan.append({"track": "voice", "rule": "A01-narration",
+ "what": ((T("TTS 旁白", "TTS voice-over") if n.get('type') == 'tts' else T("真人口播/对白", "human talking head / dialogue") if n.get('type') == 'human' else T("人声", "voice"))
+ f"{T(',', ', ')}{n.get('voice') or voice.get('gender_hint') or ''}{T(',', ', ')}{n.get('style') or ''}").strip(T(",", ", ")),
"how": T("capsule-cinema DoubaoTTSTool / UniversalTTSTool(或 MiniMax 克隆音色);需要卡原时间窗时用时长可控 TTS",
"capsule-cinema DoubaoTTSTool / UniversalTTSTool (or a MiniMax cloned voice); use duration-controlled TTS when it must fit the original time window"),
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 75247c2..ad89f14 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -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)
+ packaging=not args.no_packaging, lang=lang, 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))
@@ -425,6 +425,7 @@ def main(argv: list[str] | None = None) -> int:
d.add_argument("--no-packaging", action="store_true", help="跳过剪辑包装层(整片字幕时间轴、花字、贴纸/动图、音效卡点);省掉约每分钟 30–50 秒")
d.add_argument("--lang", choices=LANGS, help="报告、结论和 VLM 描述的语言:zh(默认)/ en;按用户提问的语言选,也可用 prefs lang 设成默认")
d.add_argument("--workers", type=int, default=3)
+ 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-stems", action="store_true", help="不做人声/配乐分离(默认会输出 stems/original.wav、vocals.wav、music.wav)")
diff --git a/rea_video/entities.py b/rea_video/entities.py
index b73ddfb..f2e7cc8 100644
--- a/rea_video/entities.py
+++ b/rea_video/entities.py
@@ -110,7 +110,10 @@ def open_questions(b: dict) -> list[str]:
"""What a reader should verify by eye / ear, collected from every part of the breakdown. Ordered: picture, material, audio, packaging."""
q: list[str] = []
s = b.get("summary") or {}
- if s.get("vlm") and any(k in str(s["vlm"]) for k in ("失败", "未配置", "未开", "failed", "not configured", "off")):
+ vlm = (b.get("analysis") or {}).get("vlm") or {}
+ status = vlm.get("status") or ("ok" if vlm.get("used") else "off")
+ reviewed = ((b.get("analysis") or {}).get("review") or {}).get("shots")
+ if s.get("vlm") and status in ("off", "not_configured", "failed") and not reviewed:
q.append(T("VLM 没有生效({v}):实拍 / AI / 3D 的区分只靠信号取证,建议配置多模态模型后加 --vlm 重跑,或由 agent 看图复核",
"The VLM did not run ({v}): live action / AI / 3D is decided by signal forensics alone; configure a multimodal model and rerun with --vlm, or have an agent review the frames", v=s["vlm"]))
for r in b.get("shots", []):
@@ -127,6 +130,11 @@ def open_questions(b: dict) -> list[str]:
unsure = sorted({it.get("kind_zh", "") for it in (r.get("material") or {}).get("items", []) if it.get("real_material") is None})
if unsure:
q.append(tag + T(":{k} 是真实素材还是生成的,待确认", ": {k}: real material or generated, to confirm", k=join(unsure)))
+ if (b.get("audio") or {}).get("has_audio") and not vlm.get("whole_ok"):
+ # an image review covers the picture; the soundtrack is only heard by a model that takes video
+ q.append(T("声音没有模型听过{r}:旁白是 TTS 还是真人、音效清单只来自信号检测,人声和音乐下面的轻音效可能漏检。请听 stems/ 里的干声和配乐核对,或配置能读视频的 VLM 后加 --vlm 重跑",
+ "No model listened to the soundtrack{r}: TTS versus human narration and the sound-effect list come from signal detection alone, and quiet effects under voice and music may be missed. Listen to the stems/ files to check, or configure a VLM that reads video and rerun with --vlm",
+ r=T("(看图复核只看画面)", " (the image review covers the picture only)") if reviewed else ""))
src = b.get("sound_sources") or {}
for k, name in (("music", T("背景音乐", "music")), ("voice", T("人声", "voice"))):
v = src.get(k) or {}
diff --git a/rea_video/faces.py b/rea_video/faces.py
index 164353f..af2c442 100644
--- a/rea_video/faces.py
+++ b/rea_video/faces.py
@@ -6,14 +6,13 @@ from __future__ import annotations
import logging
import os
-import urllib.request
import uuid
from pathlib import Path
import cv2
import numpy as np
-from .util import sha256_file
+from .util import fetch, sha256_file
LOG = logging.getLogger(__name__)
MODEL_NAME = "face_detection_yunet_2023mar.onnx"
@@ -37,7 +36,7 @@ def _ensure_model() -> Path | None:
tmp = p.with_name(f"{p.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part")
try:
LOG.info("downloading face model %s -> %s", MODEL_NAME, p)
- urllib.request.urlretrieve(MODEL_URL, tmp)
+ fetch(MODEL_URL, tmp)
if sha256_file(tmp) != MODEL_SHA256:
raise OSError("checksum mismatch")
tmp.replace(p)
diff --git a/rea_video/media.py b/rea_video/media.py
index fd48ead..cac95d2 100644
--- a/rea_video/media.py
+++ b/rea_video/media.py
@@ -187,7 +187,8 @@ def iter_frames(
vf.append(f"scale={w}:{h}:flags=area")
cmd = ["ffmpeg", "-v", "error", "-nostdin"]
if start is not None and start > 0:
- cmd += ["-ss", f"{start:.4f}"]
+ # half a frame early: a start rounded to just past a frame's timestamp would drop that frame
+ cmd += ["-ss", f"{max(start - 0.5 / info.fps, 0.0) if info.fps > 0 else start:.4f}"]
cmd += ["-i", str(path)]
if duration is not None:
cmd += ["-t", f"{max(duration, 0.01):.4f}"]
@@ -214,6 +215,11 @@ def iter_frames(
err = errf.read()[-4000:].decode(errors="ignore")
if err.strip():
raise MediaError(f"ffmpeg decoded no frames: {err.strip()[:300]}")
+ elif proc.wait() != 0:
+ # the stream ended early (a damaged file): what was read is analysed, but say that it is not all of it
+ errf.seek(0)
+ err = errf.read()[-4000:].decode(errors="ignore").strip()
+ LOG.warning("ffmpeg stopped after %d frames of %s: %s", count, Path(path).name, err[:300] or f"exit {proc.returncode}")
finally:
proc.stdout.close()
proc.kill()
@@ -230,19 +236,25 @@ def extract_frame(path: str | Path, t: float, out_path: str | Path, width: int |
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)
+ _run_ffmpeg(cmd, f"frame at {t:.2f}s")
return out_path
+def _run_ffmpeg(cmd: list[str], what: str) -> None:
+ got = subprocess.run(cmd, capture_output=True)
+ if got.returncode != 0:
+ raise MediaError(f"ffmpeg failed ({what}): {got.stderr.decode(errors='ignore').strip()[-300:] or got.returncode}")
+
+
def cut_clip(path: str | Path, start: float, duration: float, out_path: str | Path, width: int = 480,
audio: bool = False, crf: int = 28) -> Path:
out_path = Path(out_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
cmd = ["ffmpeg", "-v", "error", "-y", "-ss", f"{max(start, 0):.4f}", "-i", str(path), "-t", f"{duration:.4f}",
- "-vf", f"scale={width}:-2", "-c:v", "libx264", "-preset", "veryfast", "-crf", str(crf), "-pix_fmt", "yuv420p"]
+ "-vf", f"scale='min({width},iw)':-2", "-c:v", "libx264", "-preset", "veryfast", "-crf", str(crf), "-pix_fmt", "yuv420p"]
cmd += ["-c:a", "aac", "-b:a", "64k"] if audio else ["-an"]
cmd += ["-movflags", "+faststart", str(out_path)]
- subprocess.run(cmd, check=True)
+ _run_ffmpeg(cmd, f"clip {start:.2f}s +{duration:.2f}s")
return out_path
diff --git a/rea_video/overlay.py b/rea_video/overlay.py
index c36fe04..7a0f025 100644
--- a/rea_video/overlay.py
+++ b/rea_video/overlay.py
@@ -9,14 +9,13 @@ from __future__ import annotations
import hashlib
import os
-import urllib.request
import uuid
from pathlib import Path
import cv2
import numpy as np
-from .util import LOG, OCR_LANGS
+from .util import LOG, OCR_LANGS, fetch
# Recognition models for languages other than the bundled Chinese/English one. Detection stays the bundled
# model, which finds Japanese text lines fine; only the recognizer's character set has to change. The ONNX
@@ -61,7 +60,7 @@ def rec_model(lang: str) -> Path:
LOG.info("downloading OCR model %s -> %s", name, p)
tmp = p.with_name(f"{p.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part")
try:
- urllib.request.urlretrieve(url, tmp)
+ fetch(url, tmp)
if _sha256(tmp) != sha:
raise OSError(f"checksum mismatch for {name}")
tmp.replace(p)
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 7c27caf..84b409c 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -216,9 +216,6 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
first, last = unit[0], unit[-1]
span = last["end"] - first["start"]
media = []
- if cfg.media in ("both", "video"):
- clip = cut_clip(video, first["start"], min(span, 12.0), out / "clips" / f"{first['id']}.mp4", width=480)
- media.append((clip, "video/mp4"))
if cfg.media in ("both", "frames"):
mid = unit[len(unit) // 2]
media += [(out / first["assets"]["first_frame"], "image/jpeg"), (out / mid["assets"]["sheet"], "image/jpeg"),
@@ -231,6 +228,9 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
prompt += prompt_lang_note()
fallback = None
try:
+ if cfg.media in ("both", "video"): # a clip that fails to encode costs this unit its video, not the run
+ clip = cut_clip(video, first["start"], min(span, 12.0), out / "clips" / f"{first['id']}.mp4", width=480)
+ media.insert(0, (clip, "video/mp4"))
raw = client.ask_json(prompt, media)
except Exception as exc: # keep going; deterministic result stands
raw = None
@@ -263,7 +263,7 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
vlm_info["errors"].append(f"whole: {str(exc)[:160]}")
asked = [r for u in units for r in u]
ok_shots = sum(1 for r in asked if r.get("vlm"))
- vlm_info.update(ok_shots=ok_shots, asked_shots=len(asked), calls=len(units), whole_ok=whole is not None)
+ vlm_info.update(ok_shots=ok_shots, asked_shots=len(asked), total_shots=len(shot_records), calls=len(units), whole_ok=whole is not None)
if ok_shots == len(asked) and (whole is not None or not whole_vlm):
vlm_info.update(used=True, status="ok")
elif ok_shots or whole is not None:
diff --git a/rea_video/probe.py b/rea_video/probe.py
index c962549..19f80d8 100644
--- a/rea_video/probe.py
+++ b/rea_video/probe.py
@@ -22,7 +22,7 @@ SIGNATURES: list[tuple[str, str, str]] = [
(r"\bveo\b|google.*(deepmind|veo)|synthid", "generator", "Google Veo"),
(r"\bsora\b|openai", "generator", "OpenAI Sora"),
(r"runway|gen-?4", "generator", "Runway"),
- (r"pika", "generator", "Pika"),
+ (r"pika(?:[ ._-]?(?:labs|art|ai))?(?![a-z])", "generator", "Pika"),
(r"vidu|shengshu|生数", "generator", "Vidu"),
(r"pixverse", "generator", "PixVerse"),
(r"luma|dream ?machine", "generator", "Luma"),
@@ -52,6 +52,10 @@ CAMERA_KEYS = ("com.apple.quicktime.make", "com.apple.quicktime.model", "make",
AIGC_KEYS = ("aigc", "ai_generated", "aigc_label", "contentproducer", "produceid")
+FREE_TEXT_KEYS = {"title", "description", "comment", "synopsis", "summary", "lyrics", "keywords", "subject", "purl",
+ "artist", "album", "album_artist", "show", "episode_id", "genre", "copyright"}
+
+
def _flatten_tags(raw: dict) -> dict[str, str]:
tags: dict[str, str] = {}
for k, v in (raw.get("format", {}).get("tags") or {}).items():
@@ -152,13 +156,22 @@ def provenance(info: VideoInfo) -> dict:
if aigc.get("label") == "1":
hints["generator"].append(T("AIGC 标识({m})", "AIGC label ({m})", m=aigc.get('meaning')))
- blob = " ".join(f"{k}={v}" for k, v in tags.items() if "aigc" not in k.lower())
+ # tags a tool writes about itself (encoder, handler, software ...) versus text a person typed (title,
+ # description, comment ...): a generator named in typed text is what the video is about, not how it was made
+ typed = {k for k in tags if k.lower().split(".", 1)[-1] in FREE_TEXT_KEYS}
+ blob = " ".join(f"{k}={v}" for k, v in tags.items() if "aigc" not in k.lower() and k not in typed)
+ prose = " ".join(tags[k] for k in typed if "aigc" not in k.lower())
raw_bytes = _scan_bytes(path)
strings = _printable_strings(raw_bytes)
for pattern, cat, label in SIGNATURES:
- if re.search(pattern, blob, re.I):
+ # a name must start a word: "vidu" is not in "individual", "resolve" not in "unresolved"
+ starts = rf"(?<![a-z0-9])(?:{pattern})"
+ if re.search(starts, blob, re.I) or (cat != "generator" and re.search(starts, prose, re.I)):
hints[cat].append(label)
evidence.append({"kind": f"{cat}_signature", "detail": T("元数据包含 {l}", "Metadata contains {l}", l=label), "weight": "medium"})
+ elif cat == "generator" and re.search(starts, prose, re.I):
+ # shown in the report only: it moves no score and does not pair with a C2PA manifest
+ evidence.append({"kind": "generator_text", "detail": T("标题/描述里提到 {l}", "Title / description mentions {l}", l=label), "weight": "weak"})
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); 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)
diff --git a/rea_video/stems.py b/rea_video/stems.py
index d4d43c9..76667d1 100644
--- a/rea_video/stems.py
+++ b/rea_video/stems.py
@@ -9,13 +9,12 @@ from __future__ import annotations
import logging
import os
import subprocess
-import urllib.request
import uuid
from pathlib import Path
import numpy as np
-from .util import sha256_file
+from .util import fetch, sha256_file
LOG = logging.getLogger(__name__)
SR = 44100
@@ -45,7 +44,7 @@ def ensure_model(force: bool = False) -> Path:
# per-process temp name: several decompose runs may download at the same time
tmp = p.with_name(f"{p.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part")
try:
- urllib.request.urlretrieve(MODEL_URL, tmp)
+ fetch(MODEL_URL, tmp)
if sha256_file(tmp) != MODEL_SHA256:
raise OSError(f"checksum mismatch for {MODEL_NAME} ({tmp.stat().st_size} bytes); delete it and retry")
tmp.replace(p) # atomic: readers see the old file or the complete new one
diff --git a/rea_video/util.py b/rea_video/util.py
index b9d2c8a..4d919f3 100644
--- a/rea_video/util.py
+++ b/rea_video/util.py
@@ -68,6 +68,15 @@ def _json_default(value: Any) -> Any:
return str(value)
+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
+ import urllib.request
+
+ with urllib.request.urlopen(url, timeout=timeout) as resp, open(dest, "wb") as f:
+ shutil.copyfileobj(resp, f, 1 << 20)
+
+
def sha256_file(path: Path) -> str:
import hashlib
diff --git a/rea_video/vlm.py b/rea_video/vlm.py
index ab3058b..229cb9a 100644
--- a/rea_video/vlm.py
+++ b/rea_video/vlm.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import base64
import copy
import hashlib
+import http.client
import json
import os
import re
@@ -80,13 +81,17 @@ def _vlm_note(info: dict) -> str:
from .i18n import T
status = info.get("status") or ("ok" if info.get("used") else "off")
+ asked, total = info.get("asked_shots", 0), info.get("total_shots", 0)
+ # more shots than the call cap: the rest never went to the VLM, which "active" alone would hide
+ capped = T(";只送了 {a}/{n} 个镜头,其余只靠确定性取证(--max-vlm-shots 可调)",
+ "; only {a}/{n} shots were sent, the rest rely on deterministic forensics (raise --max-vlm-shots)", a=asked, n=total) if 0 < asked < total else ""
if status == "ok":
- return T("VLM 已生效({m})", "VLM active ({m})", m=info.get("model", ""))
+ return T("VLM 已生效({m})", "VLM active ({m})", m=info.get("model", "")) + capped
if status == "partial":
return T("VLM 部分生效({m}:{ok}/{asked} 个镜头有结果,整片分析{w});失败的镜头只靠确定性取证",
"VLM partly active ({m}: {ok}/{asked} shots answered, whole-video pass {w}); failed shots rely on deterministic forensics only",
m=info.get("model", ""), ok=info.get("ok_shots", 0), asked=info.get("asked_shots", 0),
- w=(T("有", "succeeded") if info.get("whole_ok") else T("失败", "failed")))
+ w=(T("有", "succeeded") if info.get("whole_ok") else T("失败", "failed"))) + capped
limited = T("实拍/AI/3D 的区分只靠像素统计,可信度有限", "live action / AI / 3D are told apart from pixel statistics only, so confidence is limited")
if status == "failed":
err = (info.get("errors") or [""])[0]
@@ -118,6 +123,7 @@ def parse_json(text: str) -> dict:
class VLMClient:
# after this many requests in a row fail on every model, stop calling the service for this run
MAX_DEAD_REQUESTS = 2
+ REQUEST_ERRORS = (400, 413, 415, 422) # the endpoint rejects this request's content, not the service being down
def __init__(self, cfg: VLMConfig, cache_dir: Path | None = None):
self.cfg = cfg
@@ -164,13 +170,20 @@ class VLMClient:
h.update(mime.encode())
h.update(hashlib.sha1(p.read_bytes()).digest())
key = h.hexdigest()
- if self.cache_dir and (self.cache_dir / f"{key}.json").is_file():
- return json.loads((self.cache_dir / f"{key}.json").read_text(encoding="utf-8"))
+ cached = self.cache_dir / f"{key}.json" if self.cache_dir else None
+ if cached and cached.is_file():
+ try:
+ got = json.loads(cached.read_text(encoding="utf-8"))
+ if isinstance(got, dict):
+ return got
+ except (OSError, ValueError):
+ 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})
last: Exception | None = None
+ refused = False
for model in list(self.models):
for attempt in range(2):
try:
@@ -179,20 +192,45 @@ class VLMClient:
out = parse_json(text)
out["_model"] = model
out["_seconds"] = round(time.time() - t, 1)
- 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 cached:
+ tmp = cached.with_name(f"{cached.name}.{os.getpid()}.{threading.get_ident()}.part")
+ tmp.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
+ tmp.replace(cached)
with self._lock: # shots run in a thread pool
+ self.dead_requests = 0
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:
+ except urllib.error.HTTPError as exc:
+ try:
+ why = exc.read()[:300].decode(errors="ignore").strip()
+ except Exception:
+ why = ""
+ 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:
+ # 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
+ break
+ if exc.code == 429:
+ try:
+ wait = float(exc.headers.get("Retry-After") or 5)
+ except (TypeError, ValueError):
+ wait = 5.0
+ time.sleep(min(max(wait, 1.0), 30.0))
+ elif 400 <= exc.code < 500 and exc.code != 408:
+ break # bad key, unknown model: retrying this model changes nothing, the next one may answer
+ else:
+ time.sleep(1.5)
+ except (OSError, http.client.HTTPException, ValueError, KeyError) as exc:
last = exc
LOG.warning("VLM %s attempt %d failed: %s", model, attempt + 1, str(exc)[:200])
time.sleep(1.5)
- if not isinstance(last, (ValueError, KeyError)): # transport/server errors, not a bad answer
- self.dead_requests += 1
+ if not refused and not isinstance(last, (ValueError, KeyError)): # transport/server errors, not a bad answer
+ with self._lock:
+ self.dead_requests += 1
raise RuntimeError(f"all VLM models failed: {last}")
@@ -416,9 +454,38 @@ def normalize_shot_result(raw: dict) -> dict:
clean[k] = 0.0
total = sum(clean.values()) or 1.0
raw["label_probs"] = {k: v / total for k, v in clean.items()}
+ # the answer is cached, so a wrong type here would break the report on every later run, not only this one
+ for k in _SHOT_TEXT:
+ if k in raw and not isinstance(raw[k], str):
+ raw[k] = _text(raw[k])
+ for k in ("embedded_assets", "ai_edits", "segments"):
+ if k in raw:
+ raw[k] = [e for e in raw[k] if isinstance(e, dict)] if isinstance(raw[k], list) else []
+ if "overlay_text" in raw:
+ v = raw["overlay_text"]
+ raw["overlay_text"] = [_text(e) for e in (v if isinstance(v, list) else [v]) if e not in (None, "", [], {})]
+ for k in ("aspects", "replication"):
+ if k in raw and not isinstance(raw[k], dict):
+ del raw[k]
+ if "replication" in raw:
+ raw["replication"] = {k: v if isinstance(v, str) else _text(v) for k, v in raw["replication"].items()}
return raw
+_SHOT_TEXT = ("description", "style", "generator_guess", "image_source", "shot_size", "camera_move", "material_origin")
+
+
+def _text(v) -> str:
+ """A model's stray list / number / null where a sentence was asked for, as one string."""
+ if v is None:
+ return ""
+ if isinstance(v, (list, tuple)):
+ return ";".join(_text(e) for e in v if e not in (None, ""))
+ if isinstance(v, dict):
+ return json.dumps(v, ensure_ascii=False)
+ return str(v)
+
+
def prompt_lang_note() -> str:
"""Appended to SHOT_PROMPT / WHOLE_PROMPT: free-text answers follow the report language (enum values stay as given)."""
from .i18n import lang
diff --git a/tests/test_ocr_lang.py b/tests/test_ocr_lang.py
index c9b40e5..45276fb 100644
--- a/tests/test_ocr_lang.py
+++ b/tests/test_ocr_lang.py
@@ -53,7 +53,7 @@ def test_cached_model_with_matching_checksum_is_not_downloaded(monkeypatch, tmp_
name, _url, _sha = overlay._REC_MODELS["ja"]
(tmp_path / name).write_bytes(b"model")
monkeypatch.setitem(overlay._REC_MODELS, "ja", (name, "http://invalid", overlay._sha256(tmp_path / name)))
- monkeypatch.setattr(overlay.urllib.request, "urlretrieve", lambda *a: pytest.fail("should not download"))
+ monkeypatch.setattr(overlay, "fetch", lambda *a: pytest.fail("should not download"))
assert overlay.rec_model("ja") == tmp_path / name
diff --git a/tests/test_report.py b/tests/test_report.py
index f7a3d75..11a779d 100644
--- a/tests/test_report.py
+++ b/tests/test_report.py
@@ -145,3 +145,19 @@ def test_open_questions_collects_everything(breakdown):
b["sound_sources"] = {"music": {"source": "unknown", "source_zh": "来源待确认", "probs": {"a": 0.5, "b": 0.5}, "how_to_confirm": ["听歌识曲"]}}
qs = open_questions(b)
assert any("工具判 A" in q for q in qs) and any("#2" in q and "40%" in q for q in qs) and any("听歌识曲" in q for q in qs)
+
+
+def test_open_questions_say_when_nobody_heard_the_sound(breakdown):
+ b, _ = breakdown
+ set_lang("zh")
+ b = json.loads(json.dumps(b))
+ b["audio"] = dict(b.get("audio") or {}, has_audio=True)
+ b["analysis"]["vlm"] = {"status": "off", "used": False}
+ b["analysis"]["review"] = {"shots": 3, "of": 3, "by": "agent"}
+ qs = open_questions(b)
+ assert any("声音没有模型听过" in q and "看图复核只看画面" in q for q in qs) and not any("VLM 没有生效" in q for q in qs)
+ b["analysis"]["vlm"] = {"status": "ok", "used": True, "whole_ok": True}
+ assert not any("声音没有模型听过" in q for q in open_questions(b))
+ b["audio"]["has_audio"] = False
+ b["analysis"]["vlm"] = {"status": "off", "used": False}
+ assert not any("声音没有模型听过" in q for q in open_questions(b))
diff --git a/tests/test_robustness.py b/tests/test_robustness.py
index d989626..625b8a9 100644
--- a/tests/test_robustness.py
+++ b/tests/test_robustness.py
@@ -133,3 +133,118 @@ def test_variable_frame_rate_cuts_use_real_timestamps(tmp_path):
shots = detect_shots(build_track(str(vfr), video_info(vfr)))
assert [round(s.start, 2) for s in shots] == [0.0, 2.0, 4.0]
assert abs(shots[-1].end - 6.0) < 0.05
+
+
+def _tagged(tmp_path, **tags) -> Path:
+ p = tmp_path / "t.mp4"
+ meta = [x for k, v in tags.items() for x in ("-metadata", f"{k}={v}")]
+ _ff("-f", "lavfi", "-i", "testsrc2=size=64x64:rate=5", "-t", "1", *meta, str(p))
+ return p
+
+
+def test_generator_named_in_typed_text_is_not_a_signature(tmp_path):
+ p = _tagged(tmp_path, title="pikachu on the runway", description="Each individual clip compared with OpenAI Sora", comment="unresolved")
+ prov = provenance(video_info(p))
+ assert not prov["hints"].get("generator") and "DaVinci Resolve" not in prov["hints"].get("editor", [])
+ assert any(e["kind"] == "generator_text" for e in prov["evidence"])
+
+
+def test_generator_named_by_the_encoder_is_a_signature(tmp_path):
+ p = tmp_path / "t.mp4"
+ _ff("-f", "lavfi", "-i", "testsrc2=size=64x64:rate=5", "-t", "1", "-metadata:s:v", "handler_name=KlingAI video", str(p))
+ assert "Kling" in provenance(video_info(p))["hints"].get("generator", [])
+
+
+def test_shot_decode_starts_on_the_shot_first_frame(tmp_path):
+ import numpy as np
+
+ from rea_video.media import iter_frames
+
+ p = tmp_path / "ramp.mp4" # every frame is a flat grey of its own level, so the level read back names the frame
+ _ff("-f", "lavfi", "-i", "color=black:size=64x64:rate=30000/1001,geq=lum='16+4*N':cb=128:cr=128", "-t", "2", "-pix_fmt", "yuv420p", str(p))
+ info = video_info(p)
+ level = [round(float(np.mean(f))) for f in iter_frames(p, info, width=64, gray=True)]
+ assert len(set(level[:50])) == 50
+ for k in range(1, 50): # a third of these start times round to just past the frame's timestamp
+ first = next(iter_frames(p, info, width=64, start=k / info.fps, duration=0.2, gray=True))
+ assert level.index(round(float(np.mean(first)))) == k, k
+
+
+def test_normalize_shot_result_coerces_text_fields():
+ r = normalize_shot_result({"label_probs": {"ai_video": 1}, "description": ["a cat", "jumps"], "style": None, "embedded_assets": "logo",
+ "ai_edits": [{"kind": "face_swap"}, "x"], "overlay_text": "SALE", "replication": {"video_prompt": ["a", "b"]},
+ "aspects": "n/a"})
+ assert isinstance(r["description"], str) and "a cat" in r["description"] and r["style"] == ""
+ assert r["embedded_assets"] == [] and r["ai_edits"] == [{"kind": "face_swap"}] and r["overlay_text"] == ["SALE"]
+ assert isinstance(r["replication"]["video_prompt"], str) and "aspects" not in r
+
+
+def _http_error(code, body=b'{"error": "video input is not supported"}', headers=None):
+ import io
+ import urllib.error
+
+ return urllib.error.HTTPError("https://example.invalid/v1", code, "err", headers or {}, io.BytesIO(body))
+
+
+def test_rejected_request_is_not_retried_and_does_not_stop_the_vlm(monkeypatch):
+ c = VLMClient(VLMConfig("https://example.invalid/v1", "k", ["m1"]))
+ calls = []
+
+ def fake_urlopen(req, timeout):
+ calls.append(1)
+ raise _http_error(400)
+
+ monkeypatch.setattr("rea_video.vlm.urllib.request.urlopen", fake_urlopen)
+ monkeypatch.setattr("rea_video.vlm.time.sleep", lambda s: None)
+ for _ in range(3):
+ with pytest.raises(RuntimeError, match="not supported"):
+ c.ask_json("p", [])
+ assert len(calls) == 3 and not c.gave_up
+
+
+def test_server_errors_still_stop_the_vlm(monkeypatch):
+ c = VLMClient(VLMConfig("https://example.invalid/v1", "k", ["m1"]))
+ monkeypatch.setattr("rea_video.vlm.urllib.request.urlopen", lambda req, timeout: (_ for _ in ()).throw(_http_error(503)))
+ monkeypatch.setattr("rea_video.vlm.time.sleep", lambda s: None)
+ for _ in range(2):
+ with pytest.raises(RuntimeError):
+ c.ask_json("p", [])
+ assert c.gave_up
+
+
+def test_truncated_cache_file_is_asked_again(tmp_path, monkeypatch):
+ import io
+ import json
+
+ c = VLMClient(VLMConfig("https://example.invalid/v1", "k", ["m1"]), tmp_path)
+
+ class R(io.BytesIO):
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ monkeypatch.setattr("rea_video.vlm.urllib.request.urlopen",
+ lambda req, timeout: R(json.dumps({"choices": [{"message": {"content": '{"ok": 1}'}}]}).encode()))
+ assert c.ask_json("p", [])["ok"] == 1
+ (cached,) = tmp_path.glob("*.json")
+ cached.write_text('{"ok": ', encoding="utf-8")
+ assert c.ask_json("p", [])["ok"] == 1
+ assert json.loads(cached.read_text(encoding="utf-8"))["ok"] == 1 and not list(tmp_path.glob("*.part"))
+
+
+def test_failed_clip_is_one_line_not_a_traceback(tmp_path):
+ from rea_video.media import MediaError, cut_clip
+
+ with pytest.raises(MediaError):
+ cut_clip(tmp_path / "missing.mp4", 0, 1, tmp_path / "c.mp4")
+
+
+def test_vlm_note_says_when_shots_were_left_out():
+ from rea_video.i18n import set_lang
+ from rea_video.vlm import vlm_note
+
+ 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})
diff --git a/tests/test_security.py b/tests/test_security.py
index 9b6e43a..fa5d14d 100644
--- a/tests/test_security.py
+++ b/tests/test_security.py
@@ -63,7 +63,7 @@ def test_face_model_checksum_rejects_tampered_download(tmp_path, monkeypatch):
from rea_video import faces
monkeypatch.setenv("REA_VIDEO_MODELS", str(tmp_path))
- monkeypatch.setattr(faces.urllib.request, "urlretrieve", lambda url, dst: open(dst, "wb").write(b"evil"))
+ monkeypatch.setattr(faces, "fetch", lambda url, dst: open(dst, "wb").write(b"evil"))
assert faces._ensure_model() is None
assert list(tmp_path.iterdir()) == []
diff --git a/tests/test_stems.py b/tests/test_stems.py
index 7364ae3..e09f412 100644
--- a/tests/test_stems.py
+++ b/tests/test_stems.py
@@ -20,7 +20,7 @@ def test_ensure_model_rejects_partial_download_and_leaves_no_temp(tmp_path, monk
import pytest
monkeypatch.setenv("REA_VIDEO_MODELS", str(tmp_path))
- monkeypatch.setattr(S.urllib.request, "urlretrieve", lambda url, dst: open(dst, "wb").write(b"x" * 10))
+ monkeypatch.setattr(S, "fetch", lambda url, dst: open(dst, "wb").write(b"x" * 10))
with pytest.raises(OSError):
S.ensure_model()
assert list(tmp_path.iterdir()) == []
@@ -36,7 +36,7 @@ def test_ensure_model_uses_unique_temp_names(tmp_path, monkeypatch):
with open(dst, "wb") as f:
f.write(b"model")
- monkeypatch.setattr(S.urllib.request, "urlretrieve", fake)
+ monkeypatch.setattr(S, "fetch", fake)
S.ensure_model(force=True)
S.ensure_model(force=True)
assert len(set(seen)) == 2 and (tmp_path / S.MODEL_NAME).read_bytes() == b"model"