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

Check VLM settings before a run (#38)

Salman Biswas28fcaa82eefd
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 2555ac9..fec3770 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -45,6 +45,16 @@ def _ocr_lang(args) -> None:
os.environ["REA_OCR_LANG"] = lang
+def _check_vlm_config() -> None:
+ """Fail fast on a misconfigured VLM: a typo in REA_VLM_MEDIA must not silently run text-only."""
+ from .vlm import VLMConfig
+
+ try:
+ VLMConfig.from_env()
+ except ValueError as exc:
+ raise SystemExit(f"rea-video: {exc}")
+
+
def cmd_decompose(args) -> int:
from .pipeline import decompose
@@ -55,6 +65,8 @@ def cmd_decompose(args) -> int:
meta = read_json(Path(args.meta)) if args.meta else None
use_vlm = args.vlm or (pref("vlm") == "on" and not args.no_vlm)
+ if use_vlm:
+ _check_vlm_config()
stems = not args.no_stems and pref("stems", "on") == "on"
lang = args.lang or pref("lang", "zh")
if lang not in LANGS:
@@ -147,6 +159,8 @@ def cmd_eval(args) -> int:
_ocr_lang(args)
+ if args.vlm:
+ _check_vlm_config()
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))
diff --git a/rea_video/vlm.py b/rea_video/vlm.py
index 012d4e8..d8598b6 100644
--- a/rea_video/vlm.py
+++ b/rea_video/vlm.py
@@ -45,7 +45,9 @@ class VLMConfig:
@classmethod
def from_env(cls) -> "VLMConfig | None":
"""First complete config wins; later configs on the same endpoint and key add their
- models as fallbacks (capsule-cinema keeps one model in VIDEO_ANALYSIS_* and a list in GEMINI3_*)."""
+ models as fallbacks (capsule-cinema keeps one model in VIDEO_ANALYSIS_* and a list in GEMINI3_*).
+ A malformed value raises ValueError naming the variable: a typo must fail fast here, not
+ silently run the VLM with no media (bad REA_VLM_MEDIA) or crash mid-run (bad timeout)."""
cfg: VLMConfig | None = None
for prefix, mkey in (("REA_VLM", "REA_VLM_MODEL"), ("VIDEO_ANALYSIS", "VIDEO_ANALYSIS_MODEL_NAME"), ("GEMINI3", "GEMINI3_MODEL_NAME")):
base, key = os.getenv(f"{prefix}_BASE_URL", "").rstrip("/"), os.getenv(f"{prefix}_API_KEY", "")
@@ -54,10 +56,8 @@ class VLMConfig:
continue
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"),
- video_part=os.getenv("REA_VLM_VIDEO_PART", "").strip().lower(),
- reasoning_effort=os.getenv("REA_VLM_REASONING_EFFORT", "").strip().lower())
+ timeout=_timeout_from_env(), media=_media_from_env(),
+ video_part=_video_part_from_env(), reasoning_effort=_effort_from_env())
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
@@ -67,6 +67,39 @@ class VLMConfig:
return f"{','.join(self.models)} @ {host}"
+def _timeout_from_env() -> float:
+ var = "REA_VLM_TIMEOUT" if os.getenv("REA_VLM_TIMEOUT") is not None else "VIDEO_ANALYSIS_TIMEOUT_SECONDS"
+ raw = os.getenv(var, "180")
+ try:
+ timeout = float(raw)
+ except (TypeError, ValueError):
+ raise ValueError(f"{var} must be seconds (a number), got {raw!r}") from None
+ if not timeout > 0:
+ raise ValueError(f"{var} must be more than 0 seconds, got {raw!r}")
+ return timeout
+
+
+def _media_from_env() -> str:
+ media = os.getenv("REA_VLM_MEDIA", "both")
+ if media not in ("both", "video", "frames"):
+ raise ValueError(f"REA_VLM_MEDIA must be both, video or frames, got {media!r}")
+ return media
+
+
+def _video_part_from_env() -> str:
+ part = os.getenv("REA_VLM_VIDEO_PART", "").strip().lower()
+ if part and part not in ("image_url", "video_url"):
+ raise ValueError(f"REA_VLM_VIDEO_PART must be image_url or video_url, got {part!r}")
+ return part
+
+
+def _effort_from_env() -> str:
+ effort = os.getenv("REA_VLM_REASONING_EFFORT", "").strip().lower()
+ if effort and effort not in ("low", "medium", "high"):
+ raise ValueError(f"REA_VLM_REASONING_EFFORT must be low, medium or high, got {effort!r}")
+ return effort
+
+
SETUP_HINT = ("建议配置 VLM(任意 OpenAI 兼容的多模态模型,如 Gemini / GPT-4o / 豆包 / Qwen-VL):"
"设置 REA_VLM_BASE_URL、REA_VLM_API_KEY、REA_VLM_MODEL(可写多个模型逗号分隔做备选),再加 --vlm 重跑")
SETUP_HINT_EN = ("configure a VLM (any OpenAI-compatible multimodal model, e.g. Gemini / GPT-4o / Doubao / Qwen-VL): "
diff --git a/tests/test_review.py b/tests/test_review.py
index f5a6d67..84ebef9 100644
--- a/tests/test_review.py
+++ b/tests/test_review.py
@@ -1,6 +1,8 @@
"""Agent-as-VLM: review tasks -> answers -> fused breakdown."""
import json
+import pytest
+
from rea_video.cli import main
from rea_video.pipeline import decompose
from rea_video.vlm import VLMConfig
@@ -67,6 +69,56 @@ def test_vlm_config_merges_fallback_models_on_same_endpoint(monkeypatch):
assert VLMConfig.from_env().models == ["m1"]
+def test_vlm_config_rejects_bad_values(monkeypatch):
+ def cfg(**overrides):
+ for k in ("REA_VLM_BASE_URL", "REA_VLM_API_KEY", "REA_VLM_MODEL", "REA_VLM_TIMEOUT",
+ "REA_VLM_MEDIA", "REA_VLM_VIDEO_PART", "REA_VLM_REASONING_EFFORT",
+ "VIDEO_ANALYSIS_BASE_URL", "VIDEO_ANALYSIS_API_KEY", "VIDEO_ANALYSIS_MODEL_NAME",
+ "VIDEO_ANALYSIS_TIMEOUT_SECONDS",
+ "GEMINI3_BASE_URL", "GEMINI3_API_KEY", "GEMINI3_MODEL_NAME"):
+ monkeypatch.delenv(k, raising=False)
+ monkeypatch.setenv("REA_VLM_BASE_URL", "https://x.test/v1")
+ monkeypatch.setenv("REA_VLM_API_KEY", "k")
+ monkeypatch.setenv("REA_VLM_MODEL", "m1")
+ for k, v in overrides.items():
+ monkeypatch.setenv(k, v)
+ return VLMConfig.from_env()
+
+ # valid values still load
+ c = cfg(REA_VLM_TIMEOUT="30", REA_VLM_MEDIA="frames", REA_VLM_VIDEO_PART="video_url",
+ REA_VLM_REASONING_EFFORT="low")
+ assert (c.timeout, c.media, c.video_part, c.reasoning_effort) == (30.0, "frames", "video_url", "low")
+ # a bad timeout used to crash decompose with a bare ValueError; bad media silently sent the VLM
+ # text only (no frames, no clip); bad effort / video_part were passed on silently
+ for bad, var in (({"REA_VLM_TIMEOUT": "abc"}, "REA_VLM_TIMEOUT"),
+ ({"REA_VLM_TIMEOUT": "0"}, "REA_VLM_TIMEOUT"),
+ ({"REA_VLM_TIMEOUT": "-5"}, "REA_VLM_TIMEOUT"),
+ ({"REA_VLM_TIMEOUT": "nan"}, "REA_VLM_TIMEOUT"),
+ ({"VIDEO_ANALYSIS_TIMEOUT_SECONDS": "soon"}, "VIDEO_ANALYSIS_TIMEOUT_SECONDS"),
+ ({"REA_VLM_MEDIA": "frame"}, "REA_VLM_MEDIA"),
+ ({"REA_VLM_VIDEO_PART": "clip"}, "REA_VLM_VIDEO_PART"),
+ ({"REA_VLM_REASONING_EFFORT": "ultra"}, "REA_VLM_REASONING_EFFORT")):
+ with pytest.raises(ValueError, match=var):
+ cfg(**bad)
+
+
+def test_vlm_commands_fail_fast_on_bad_config(monkeypatch, tmp_path):
+ for k in ("REA_VLM_BASE_URL", "REA_VLM_API_KEY", "REA_VLM_MODEL", "REA_VLM_TIMEOUT",
+ "REA_VLM_MEDIA", "REA_VLM_VIDEO_PART", "REA_VLM_REASONING_EFFORT",
+ "VIDEO_ANALYSIS_BASE_URL", "VIDEO_ANALYSIS_API_KEY", "VIDEO_ANALYSIS_MODEL_NAME",
+ "GEMINI3_BASE_URL", "GEMINI3_API_KEY", "GEMINI3_MODEL_NAME"):
+ monkeypatch.delenv(k, raising=False)
+ monkeypatch.setenv("REA_VLM_BASE_URL", "https://x.test/v1")
+ monkeypatch.setenv("REA_VLM_API_KEY", "k")
+ monkeypatch.setenv("REA_VLM_MODEL", "m1")
+ monkeypatch.setenv("REA_VLM_MEDIA", "frame")
+ # the video / labels files do not exist: the config error must fire before either is read
+ with pytest.raises(SystemExit, match="REA_VLM_MEDIA"):
+ main(["decompose", str(tmp_path / "nope.mp4"), "--vlm"])
+ with pytest.raises(SystemExit, match="REA_VLM_MEDIA"):
+ main(["eval", str(tmp_path / "labels.yaml"), "--vlm"])
+
+
def test_two_of_three_beat_one_confident_model():
from rea_video.classify import LABELS, fuse