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

Keep tests local

june594a50bc7c77
diff --git a/.gitignore b/.gitignore
index 4812425..6fa6b20 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,3 +17,4 @@ eval/code_videos_holdout.yaml
eval/particles.yaml
eval/codegen/
scripts/roundtrip_compare.py
+tests/
diff --git a/AGENTS.md b/AGENTS.md
index dda8dc1..ffa77fb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,7 +6,7 @@
- `skills/rea-video/`:给 agent 用的 skill(流程 + references),只写怎么用,不放开发文档
- `rea_video/`:CLI 和拆解逻辑;模型能力地图在 `rea_video/capabilities/`,capsule-cinema 对接脚本在 `rea_video/integrations/`
- `docs/`:给人看的文档;`docs/dev/` 是开发文档(扩充评测集、加拍法维度)
- - `eval/`、`tests/`:评测集和测试
+ - `eval/`:评测集;`tests/`:本地测试,已在 .gitignore 里,不进仓库
- 开发约定:
- 开发环境:`pip install -e ".[ocr,dev]"`(dev 带 pytest 和 jsonschema,测试和能力地图校验要用)
- 规则改动后跑 `python3 -m pytest -q` 和 `rea-video eval eval/labels.yaml` / `eval/holdout*.yaml`,结果更新到 `eval/RESULTS.md`
diff --git a/tests/conftest.py b/tests/conftest.py
deleted file mode 100644
index cc41897..0000000
--- a/tests/conftest.py
+++ /dev/null
@@ -1,75 +0,0 @@
-import subprocess
-import sys
-from pathlib import Path
-
-import cv2
-import numpy as np
-import pytest
-
-ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(ROOT))
-
-
-def _photo_like(w: int, h: int, seed: int) -> np.ndarray:
- """Photographic-looking still: smooth multi-scale texture + sensor-like noise."""
- rng = np.random.default_rng(seed)
- img = np.zeros((h, w, 3), np.float32)
- for scale, amp in ((8, 90), (32, 40), (128, 20)):
- small = rng.random((max(2, h // scale), max(2, w // scale), 3)).astype(np.float32)
- img += cv2.resize(small, (w, h), interpolation=cv2.INTER_CUBIC) * amp
- img = cv2.GaussianBlur(img, (0, 0), 1.2) + rng.normal(0, 3.0, img.shape)
- return np.clip(img, 0, 255).astype(np.uint8)
-
-
-def _write(frames, path: Path, fps: int = 30) -> Path:
- h, w = frames[0].shape[:2]
- p = subprocess.Popen(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{w}x{h}", "-r", str(fps),
- "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "16", str(path)], stdin=subprocess.PIPE)
- for f in frames:
- p.stdin.write(f.tobytes())
- p.stdin.close()
- assert p.wait() == 0 and path.stat().st_size > 0, f"ffmpeg failed to write {path}"
- return path
-
-
[email protected](scope="session")
-def media(tmp_path_factory):
- d = tmp_path_factory.mktemp("media")
- w, h, fps = 360, 640, 30
- out = {}
- # 1) static photo hold, 2 s
- still = _photo_like(w, h, 1)
- out["static"] = _write([still] * (2 * fps), d / "static.mp4")
- # 2) Ken Burns: zoom in 4%/s on another photo, 3 s
- base = _photo_like(int(w * 1.3), int(h * 1.3), 2)
- frames = []
- for i in range(3 * fps):
- s = 1.0 + 0.04 * i / fps
- M = cv2.getRotationMatrix2D((base.shape[1] / 2, base.shape[0] / 2), 0, s)
- warped = cv2.warpAffine(base, M, (base.shape[1], base.shape[0]), flags=cv2.INTER_CUBIC)
- y0, x0 = (base.shape[0] - h) // 2, (base.shape[1] - w) // 2
- frames.append(np.ascontiguousarray(warped[y0:y0 + h, x0:x0 + w]))
- out["kenburns"] = _write(frames, d / "kenburns.mp4")
- # 3) code-render style: flat background, a card sliding in, text-like bars, 3 s
- frames = []
- for i in range(3 * fps):
- f = np.full((h, w, 3), (59, 41, 30), np.uint8)
- x = int(min(40, -200 + i * 12))
- cv2.rectangle(f, (x, 200), (x + 280, 360), (245, 245, 245), -1)
- for k in range(4):
- cv2.rectangle(f, (x + 20, 220 + k * 30), (x + 20 + 200 - k * 30, 236 + k * 30), (60, 60, 60), -1)
- cv2.putText(f, "REA VIDEO", (40, 120), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (80, 200, 250), 3, cv2.LINE_8)
- frames.append(f)
- out["code"] = _write(frames, d / "code.mp4")
- # 4) concatenation with known cuts at 2.0 and 5.0 s
- cat = d / "concat.txt"
- cat.write_text("".join(f"file '{out[k]}'\n" for k in ("static", "kenburns", "code")))
- out["edit"] = d / "edit.mp4"
- subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", str(cat), "-c", "copy", str(out["edit"])], check=True)
- return out
-
-
[email protected](autouse=True)
-def _isolated_memory(tmp_path, monkeypatch):
- """Never read or write the real ~/.rea-video during tests."""
- monkeypatch.setenv("REA_VIDEO_HOME", str(tmp_path / "rea_home"))
diff --git a/tests/test_aspects.py b/tests/test_aspects.py
deleted file mode 100644
index 2c77c2a..0000000
--- a/tests/test_aspects.py
+++ /dev/null
@@ -1,184 +0,0 @@
-import numpy as np
-
-from rea_video import aspects
-from rea_video.aspects import REGISTRY, check, clean_answers, finalize, measure_shot, prompt_block, review_template
-from rea_video.aspects.base import seen
-from rea_video.aspects.framing import shot_size
-from rea_video.aspects.lighting import frame_light, setup_for, words
-from rea_video.aspects.subject import salient_box
-from rea_video.classify import deterministic, lowlight_photo
-from rea_video.pipeline import _vlm_gate
-
-FACE_BOX = [0.25, 0.25, 0.5, 0.3]
-LANDMARKS = [[0.4, 0.33], [0.6, 0.33], [0.5, 0.4], [0.42, 0.48], [0.58, 0.48]]
-
-
-def _frame(left: int, right: int, bg: int = 120, box=FACE_BOX, h: int = 640, w: int = 360, warm: int = 0, texture: bool = False):
- rng = np.random.default_rng(0)
- img = np.full((h, w, 3), bg, np.float32)
- x0, y0, x1, y1 = int(box[0] * w), int(box[1] * h), int((box[0] + box[2]) * w), int((box[1] + box[3]) * h)
- xm = (x0 + x1) // 2
- img[y0:y1, x0:xm] = left
- img[y0:y1, xm:x1] = right
- if texture: # fine detail inside the subject = what the camera focused on
- img[y0:y1, x0:x1] += rng.normal(0, 25, (y1 - y0, x1 - x0, 3))
- img[..., 0] -= warm
- img[..., 2] += warm
- img += rng.normal(0, 2, img.shape)
- return np.clip(img, 0, 255).astype(np.uint8)
-
-
-def _face(box=FACE_BOX):
- return {"box": box, "area": box[2] * box[3], "score": 0.9, "landmarks": LANDMARKS}
-
-
-def test_registry_order_and_prompt():
- keys = [a.key for a in REGISTRY]
- assert keys[:3] == ["framing", "camera", "lighting"] and keys.index("editing") < keys.index("format")
- p = prompt_block()
- assert '"lighting"' in p and "{{" in p # braces doubled for str.format
- from rea_video.vlm import SHOT_PROMPT, WHOLE_PROMPT
- assert '"key_light"' in SHOT_PROMPT.format(hints="") and '"gear_guess"' in WHOLE_PROMPT.format(shots="")
-
-
-def test_review_template_and_clean():
- t = review_template()
- assert "lighting" in t and "key_light" in t["lighting"]
- ans = clean_answers({"lighting": {"key_light": " 左前方窗户 ", "bogus": "x", "rim_light": ""}, "nope": {"a": 1}})
- assert ans == {"lighting": {"key_light": "左前方窗户"}}
-
-
-def test_shot_size_thresholds():
- assert shot_size(0.5) == "大特写" and shot_size(0.3) == "特写" and shot_size(0.18) == "近景" and shot_size(None) is None
-
-
-def test_face_side_light():
- m = frame_light(_frame(200, 90), {"kind": "face", "box": FACE_BOX, "landmarks": LANDMARKS})
- assert m["key_side"] == "left" and m["ratio"] > 2.5
- assert m["transition"] is not None and m["transition"] < 0.2
- w = words(m)
- assert "画面左侧" in w["key_direction"]
- assert setup_for(m, w)["key"] == "hard_side"
-
-
-def test_flat_front_warm():
- m = frame_light(_frame(170, 168, warm=25), {"kind": "face", "box": FACE_BOX, "landmarks": LANDMARKS})
- w = words(m)
- assert w["key_direction"].startswith("正面") and w["color_temp"].startswith("偏暖")
- assert setup_for(m, w)["key"] == "soft_front"
-
-
-def test_low_light_and_back_light_setups():
- m = {"ratio": 1.8, "key_side": "left", "top_bottom": 1.5, "transition": 0.25, "subject_luma": 70, "bg_luma": 18,
- "dark_share": 0.55, "warmth": 18, "bg_warmth": 5, "bg_blur": 0.6, "point_lights": 3}
- s = setup_for(m, words(m))
- assert s["key"] == "ambient_low_light" and any("混合光源" in n for n in s["notes"])
- m2 = {**m, "subject_luma": 90, "bg_luma": 200, "dark_share": 0.0}
- assert setup_for(m2, words(m2))["key"] == "back_lit"
-
-
-def test_desk_shot_without_face():
- """No face: the in-focus region is the subject; lighting and framing still measured, gear for objects."""
- box = [0.2, 0.35, 0.6, 0.3]
- img = _frame(190, 110, bg=90, box=box, texture=True)
- sb = salient_box(img)
- assert sb is not None and abs((sb[0] + sb[2] / 2) - 0.5) < 0.15 # found the textured block
- feats = {"camera": "static", "zoom_per_s": 0.0, "pan_px_per_s": 0.0}
- asp = measure_shot([img] * 6, {"presence": 0.0, "frames": [{"i": i, "face": None} for i in range(6)]}, feats, 3.0)
- assert asp["framing"]["measured"]["subject"] == "focus"
- assert asp["lighting"]["measured"]["subject"] == "focus" and asp["lighting"]["measured"]["ratio"] > 1.4
- assert asp["camera"]["measured"]["support"] == "fixed"
- m = asp["lighting"]["measured"]
- st = setup_for(m, words(m), "focus")
- from rea_video.aspects.lighting import SETUPS
- assert st["gear"] == next(s for s in SETUPS if s["key"] == st["key"])["gear"]["other"] # object gear, not people gear
-
-
-def _rec(i, start, dur, face_h, sig, label="live_action", support="handheld"):
- return {"index": i, "start": start, "end": start + dur, "duration": dur, "base": {"label": label},
- "features": {"camera": "handheld_like"},
- "aspects": {"framing": {"measured": {"subject": "face", "face_h": face_h, "shot_size": shot_size(face_h), "position": "居中"}},
- "camera": {"measured": {"support": support}},
- "lighting": {"measured": {"subject": "face", "ratio": 1.2, "key_side": "left", "top_bottom": 1.0,
- "subject_luma": 150, "bg_luma": 140, "dark_share": 0.0, "warmth": 10}},
- "editing": {"measured": {"bg_signature": sig}}}}
-
-
-def test_video_summary_and_check():
- a, b2 = [100.0] * 60, [20.0] * 60
- shots = [_rec(1, 0, 4, 0.3, a), _rec(2, 4, 3, 0.31, a), _rec(3, 7, 3, 0.42, a),
- {**_rec(4, 10, 2, 0.3, a, label="screen_capture"), "aspects": {}}, _rec(5, 12, 4, 0.3, b2)]
- b = {"shots": shots, "audio": {"voice": {"present": True, "segments": [[0, 3.9], [4.2, 6.9], [7.3, 16]]}}}
- finalize(b)
- A = b["aspects"]
- assert A["editing"]["jump_cuts"] == 1 and A["editing"]["punch_ins"] == 1 and A["editing"]["positions"] == 2
- assert A["camera"]["result"]["support"] == "handheld"
- assert A["format"]["result"]["format"] == "talking_head"
- assert A["lighting"]["result"]["setup"] == "soft_front"
- assert b["shooting_plan"]["gear"]
- assert check({"lighting": {"setup": ["soft_front", "key_fill"]}, "framing": {"shot_size": "特写"}}, b) == {
- "lighting.setup": True, "framing.shot_size": True}
- assert any(l.startswith("打光") for l in aspects.summary_lines(b))
- assert aspects.report_md(b) and aspects.report_html(b)
-
-
-def test_seen_reads_review_and_vlm_answers():
- r = {"vlm": {"aspects": {"lighting": {"key_light": "路灯"}}}, "review": {"aspects": {"lighting": {"key_light": "窗户"}}}}
- assert seen(r, "lighting", "key_light") == {"agent": "窗户", "vlm": "路灯"}
-
-
-def _night_features() -> dict:
- # dim street shot: crushed shadows, small palette, a big face (eval/koubo.yaml night_street #31)
- return {"noise_sigma": 0.04, "flat_ratio": 0.59, "palette95": 19, "axis_edge_ratio": 0.37, "saturation": 0.7, "luma": 23,
- "dup_ratio": 0.01, "dup_period": 1, "dup_regularity": 0.5, "moving_pair_ratio": 0.79, "zero_pixel_ratio": 0.7,
- "temporal_noise": 0.46, "pair_mad_p90": 3.8, "start_end_mad": 23, "camera": "static_with_subject_motion",
- "dark_ratio": 0.71, "dark_std": 0.4, "dark_flat": 0.55, "flat_lit": 0.1, "face_presence": 1.0, "face_area": 0.12}
-
-
-def test_dim_presenter_not_rendered():
- f = _night_features()
- assert lowlight_photo(f, 1.0)
- probs, _, facts = deterministic(f, faces=1.0, ctx={"transcoded": True, "platform": ["Douyin/TikTok"], "native30": True})
- assert facts["graphic_score"] < 0.3 and max(probs, key=probs.get) in ("live_action", "ai_video", "avatar")
- probs2, _, facts2 = deterministic({**f, "face_presence": 0.0, "face_area": 0.0}, faces=0.0, ctx={"transcoded": True})
- assert facts2["graphic_score"] > 0.6 and max(probs2, key=probs2.get) in ("cg_3d", "code_render")
-
-
-def test_dark_render_on_exact_black_is_not_lowlight():
- assert not lowlight_photo({**_night_features(), "dark_std": 0.0, "dark_flat": 0.95}, 1.0)
-
-
-def test_vlm_person_exception():
- rec = {"deterministic": {"probs": {"cg_3d": 0.6, "code_render": 0.2, "live_action": 0.1, "ai_video": 0.1},
- "facts": {"big_face": True, "transcode_degraded": True}}}
- v = {"live_action": 1.0}
- assert _vlm_gate(rec, v, {"native30": True}) == v
- rec["deterministic"]["facts"]["big_face"] = False
- assert _vlm_gate(rec, v, {"native30": True}) is None
-
-
-def test_person_exception_stays_out_of_ai_live_axis():
- # eval holdout2 dual_role_realcat: tools say AI then live; Gemini says avatar -> keep the tools' axis call
- rec = {"deterministic": {"probs": {"ai_video": 0.64, "live_action": 0.2, "avatar": 0.05, "cg_3d": 0.11},
- "facts": {"big_face": True, "lowlight": True, "face_area": 0.07}}}
- assert _vlm_gate(rec, {"avatar": 1.0}, {"native30": False}) is None
-
-
-def test_agent_review_alone_may_leave_the_tools_top_two():
- # eval daihuo: a camera filming a real phone screen reads as 3D / code render after a transcode
- det = {"cg_3d": 0.44, "code_render": 0.24, "ai_video": 0.14, "live_action": 0.1, "screen_capture": 0.08}
- rec = {"deterministic": {"probs": det, "facts": {"transcode_degraded": True}}}
- seen = {"live_action": 0.93, "screen_capture": 0.07}
- assert _vlm_gate(rec, seen, {"native30": False}) is None # the VLM alone: ignored
- rec["review"] = {"label_probs": seen}
- assert _vlm_gate(rec, seen, {"native30": False}) == seen # an agent review alone: heard
- rec["vlm"] = {"label_probs": seen}
- assert _vlm_gate(rec, seen, {"native30": False}) == seen # both readers: _majority decides, gate passes
- # ... but not when fusing would land on a label nobody picked
- det2 = {"code_render": 0.36, "ai_video": 0.22, "cg_3d": 0.12, "still_motion": 0.02, "live_action": 0.1, "screen_capture": 0.18}
- rec2 = {"deterministic": {"probs": det2, "facts": {}}, "review": {"label_probs": {"still_motion": 0.7}}}
- weak = {"still_motion": 0.7, "screen_capture": 0.1, "code_render": 0.05, "ai_video": 0.05, "live_action": 0.05, "static_hold": 0.05}
- from rea_video.classify import decide, fuse
-
- assert decide(fuse(det2, weak, "dynamic"))[0] == "screen_capture" # neither the tools' nor the agent's pick
- assert _vlm_gate(rec2, weak, {"native30": False}) is None
diff --git a/tests/test_asr_lang.py b/tests/test_asr_lang.py
deleted file mode 100644
index 56e4526..0000000
--- a/tests/test_asr_lang.py
+++ /dev/null
@@ -1,152 +0,0 @@
-"""--asr-lang bn: the Bengali streaming model is chosen, checked, unpacked and decoded; auto stays SenseVoice."""
-import hashlib
-import io
-import os
-import sys
-import tarfile
-import types
-
-import numpy as np
-import pytest
-
-from rea_video import speech
-
-
-def fake_sherpa(monkeypatch, tmp_path):
- """sherpa_onnx stand-in: records which recognizer is built and what each stream is fed."""
- made, streams = [], []
-
- class Stream:
- def __init__(self):
- self.fed, self.finished, self.decoded = [], False, False
- self.result = types.SimpleNamespace(text="", lang="")
-
- def accept_waveform(self, sr, samples):
- self.fed.append(len(samples))
-
- def input_finished(self):
- self.finished = True
-
- class OnlineRecognizer:
- @classmethod
- def from_transducer(cls, **kwargs):
- made.append(("online", kwargs))
- return cls()
-
- def create_stream(self):
- streams.append(Stream())
- return streams[-1]
-
- def is_ready(self, st):
- return st.finished and not st.decoded
-
- def decode_stream(self, st):
- st.decoded = True
-
- def get_result(self, st):
- return " আমি ভাত খাই " if st.decoded else ""
-
- class OfflineRecognizer:
- @classmethod
- def from_sense_voice(cls, **kwargs):
- made.append(("offline", kwargs))
- return cls()
-
- def create_stream(self):
- streams.append(Stream())
- return streams[-1]
-
- def decode_stream(self, st):
- st.result = types.SimpleNamespace(text="大家好", lang="<|zh|>")
-
- monkeypatch.setitem(sys.modules, "sherpa_onnx", types.SimpleNamespace(OnlineRecognizer=OnlineRecognizer,
- OfflineRecognizer=OfflineRecognizer))
- monkeypatch.setattr(speech, "available", lambda: True)
- monkeypatch.setattr(speech, "extract_audio", lambda audio, sr: np.zeros(sr * 3, np.float32))
- monkeypatch.setattr(speech, "_stretches", lambda x, vad: [(0.5, np.zeros(speech.SR * 2, np.float32))])
- monkeypatch.setattr(speech, "ensure_bn_models", lambda: (tmp_path / "bn", tmp_path / "vad.onnx"))
- monkeypatch.setattr(speech, "ensure_models", lambda: (tmp_path / "sv.onnx", tmp_path / "tokens.txt", tmp_path / "vad.onnx"))
- return made, streams
-
-
-def test_default_language_is_auto(monkeypatch):
- monkeypatch.delenv("REA_ASR_LANG", raising=False)
- assert speech.asr_lang() == "auto"
-
-
-def test_unknown_language_is_rejected(monkeypatch):
- monkeypatch.setenv("REA_ASR_LANG", "hi")
- with pytest.raises(ValueError):
- speech.asr_lang()
-
-
-def test_bn_uses_the_bengali_streaming_model(monkeypatch, tmp_path, fake_sherpa):
- made, streams = fake_sherpa
- monkeypatch.setenv("REA_ASR_LANG", "bn")
- res = speech.transcribe(tmp_path / "x.wav")
- assert res == {"ok": True, "engine": "zipformer-bn-vosk (sherpa-onnx)", "language": "bn",
- "lines": [{"start": 0.5, "end": 2.5, "text": "আমি ভাত খাই"}]}
- kind, kwargs = made[0]
- assert kind == "online" and len(made) == 1
- assert {k: kwargs[k] for k in ("tokens", "encoder", "decoder", "joiner")} == {
- n: str(tmp_path / "bn" / f"{n}{'.txt' if n == 'tokens' else '.onnx'}") for n in ("tokens", "encoder", "decoder", "joiner")}
- # the stretch, then silence so the streaming encoder lets go of its last frames, then end of input
- assert streams[0].fed == [speech.SR * 2, int(speech.TAIL_PAD_S * speech.SR)] and streams[0].finished
-
-
-def test_auto_keeps_sensevoice_and_an_explicit_language_wins(monkeypatch, tmp_path, fake_sherpa):
- made, _ = fake_sherpa
- monkeypatch.delenv("REA_ASR_LANG", raising=False)
- res = speech.transcribe(tmp_path / "x.wav")
- assert res["engine"] == "sensevoice-small-int8 (sherpa-onnx)" and res["language"] == "zh" and res["lines"][0]["text"] == "大家好"
- assert made[-1][0] == "offline" and made[-1][1]["language"] == ""
- assert speech.transcribe(tmp_path / "x.wav", language="bn")["language"] == "bn" and made[-1][0] == "online"
-
-
-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_bengali_model_is_checked_and_only_the_needed_files_are_unpacked(monkeypatch, tmp_path):
- monkeypatch.setenv("REA_VIDEO_MODELS", str(tmp_path))
- d = speech.BN_MODEL_DIR
- arc = _archive({**{f"{d}/{n}": n.encode() for n in speech.BN_MODEL_FILES},
- f"{d}/test_wavs/0.wav": b"wav", f"{d}/bpe.model": b"bpe", "../escape.txt": b"x"})
- served = {speech.VAD_NAME: b"vad", f"{d}.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_bn_models()
- assert sorted(p.name for p in tmp_path.iterdir()) == [speech.VAD_NAME]
- monkeypatch.setattr(speech, "BN_ARCHIVE_SHA256", hashlib.sha256(arc).hexdigest())
- model, vad = speech.ensure_bn_models()
- assert sorted(p.name for p in model.iterdir()) == sorted(speech.BN_MODEL_FILES)
- assert (model / "encoder.onnx").read_bytes() == b"encoder.onnx" and vad.read_bytes() == b"vad"
- assert sorted(p.name for p in tmp_path.iterdir()) == sorted([d, speech.VAD_NAME]) # SenseVoice is not fetched for Bengali
- assert not (tmp_path.parent / "escape.txt").exists()
- monkeypatch.setattr(speech, "fetch", lambda *a, **k: pytest.fail("should not download again"))
- speech.ensure_bn_models()
-
-
-def test_flag_and_pref_set_the_language(monkeypatch, tmp_path):
- from rea_video import cli, memory
-
- monkeypatch.setenv("REA_VIDEO_HOME", str(tmp_path))
- monkeypatch.setenv("REA_ASR_LANG", "auto") # recorded first, so whatever _asr_lang writes is undone after the test
- monkeypatch.delenv("REA_ASR_LANG")
- cli._asr_lang(types.SimpleNamespace(asr_lang=None))
- assert "REA_ASR_LANG" not in os.environ # no flag, no pref: transcribe falls back to auto
- memory.set_pref("asr_lang", "bn")
- cli._asr_lang(types.SimpleNamespace(asr_lang=None))
- assert os.environ["REA_ASR_LANG"] == "bn"
- cli._asr_lang(types.SimpleNamespace(asr_lang="auto")) # the flag beats the pref
- assert os.environ["REA_ASR_LANG"] == "auto"
- with pytest.raises(ValueError):
- memory.set_pref("asr_lang", "hi")
diff --git a/tests/test_audio.py b/tests/test_audio.py
deleted file mode 100644
index f71cfef..0000000
--- a/tests/test_audio.py
+++ /dev/null
@@ -1,150 +0,0 @@
-import subprocess
-import wave
-
-import numpy as np
-import pytest
-
-from rea_video.audio import analyze_audio
-
-SR = 22050
-
-
-def _write_av(tmp_path, y: np.ndarray, name: str):
- wav = tmp_path / f"{name}.wav"
- with wave.open(str(wav), "wb") as w:
- w.setnchannels(1)
- w.setsampwidth(2)
- w.setframerate(SR)
- w.writeframes((np.clip(y, -1, 1) * 32767).astype(np.int16).tobytes())
- mp4 = tmp_path / f"{name}.mp4"
- subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", f"color=c=gray:s=160x90:d={len(y) / SR:.2f}",
- "-i", str(wav), "-shortest", "-c:v", "libx264", "-c:a", "aac", str(mp4)], check=True)
- return mp4
-
-
-def _music(dur=12.0, bpm=120.0):
- t = np.arange(int(dur * SR)) / SR
- y = 0.08 * sum(np.sin(2 * np.pi * f * t) for f in (261.63, 329.63, 392.0, 523.25)) # C major chord bed
- rng = np.random.default_rng(0)
- for k in np.arange(0, dur, 60 / bpm): # kick + hat on every beat
- i = int(k * SR)
- n = int(0.08 * SR)
- env = np.exp(-np.arange(n) / (0.015 * SR))
- y[i:i + n] += 0.5 * env * np.sin(2 * np.pi * 70 * np.arange(n) / SR)
- y[i:i + n // 3] += 0.15 * rng.normal(size=n // 3) * env[: n // 3]
- return y
-
-
[email protected](scope="module")
-def music_mp4(tmp_path_factory):
- return _write_av(tmp_path_factory.mktemp("a"), _music(), "music")
-
-
-def test_music_tempo_key(music_mp4):
- a = analyze_audio(str(music_mp4))
- m = a["music"]
- assert m["present"] and not a["voice"]["present"]
- cands = [m["tempo_bpm"]] + m["tempo_alternatives"]
- assert any(abs(c - 120) < 4 for c in cands), cands
- assert m["key"]["tonic"] == "C" and m["key"]["mode"] == "major"
-
-
-def test_cut_on_beat(music_mp4):
- cuts = [2.0, 4.0, 6.0, 8.0, 10.0] # on the 120 BPM grid
- a = analyze_audio(str(music_mp4), cut_times=cuts)
- assert a["cuts_on_beat_ratio"] >= 0.8 and a["beat_synced_edit"]
-
-
-def test_isolated_sfx_in_silence(tmp_path):
- y = np.zeros(int(6 * SR))
- for t0 in (1.0, 2.5, 4.0): # three "dings" in an otherwise quiet track
- n = int(0.3 * SR)
- tt = np.arange(n) / SR
- y[int(t0 * SR):int(t0 * SR) + n] += 0.6 * np.exp(-tt / 0.08) * np.sin(2 * np.pi * 1800 * tt)
- y += 0.002 * np.random.default_rng(1).normal(size=len(y))
- a = analyze_audio(str(_write_av(tmp_path, y, "sfx")))
- ts = [e["t"] for e in a["sfx"]["events"]]
- assert all(any(abs(t - t0) < 0.08 for t in ts) for t0 in (1.0, 2.5, 4.0)), ts
- assert not a["music"]["present"]
-
-
-def test_held_tone_has_no_beat_or_sfx(tmp_path):
- """A pure 440 Hz tone is a music-like bed with nothing percussive: no tempo, no sound effects."""
- t = np.arange(int(12 * SR)) / SR
- r = analyze_audio(str(_write_av(tmp_path, 0.3 * np.sin(2 * np.pi * 440 * t), "tone")))
- assert r["music"].get("tempo_bpm") is None and not r["music"]["present"]
- assert abs(r["music"]["steady_tone"]["hz"] - 440) < 25
- assert r["sfx"]["count"] == 0
-
-
-def test_held_chord_is_still_music(tmp_path):
- """A sustained pad (several notes, no drums) is music, not a test tone."""
- t = np.arange(int(12 * SR)) / SR
- y = 0.08 * sum(np.sin(2 * np.pi * f * t) for f in (261.63, 329.63, 392.0, 523.25))
- r = analyze_audio(str(_write_av(tmp_path, y, "pad")))
- assert r["music"]["present"] and not r["music"].get("steady_tone")
-
-
[email protected]("name", ["hum50", "hum100_peak", "square", "tone_in_hiss"])
-def test_held_tones_beyond_a_clean_sine_are_not_music(tmp_path, name):
- """Mains hum (with harmonics, sometimes peaking at 100 Hz), a square-wave buzzer, and a tone under hiss
- are each one held pitch: not music and no tempo."""
- t = np.arange(int(12 * SR)) / SR
- rng = np.random.default_rng(0)
- y, hz = {
- "hum50": (sum(0.2 * 0.6 ** k * np.sin(2 * np.pi * 50 * (k + 1) * t) for k in range(5)), 50),
- "hum100_peak": (0.05 * np.sin(2 * np.pi * 50 * t) + 0.2 * np.sin(2 * np.pi * 100 * t)
- + 0.1 * np.sin(2 * np.pi * 150 * t) + 0.01 * rng.normal(size=len(t)), 50),
- "square": (0.2 * np.sign(np.sin(2 * np.pi * 440 * t)), 440),
- "tone_in_hiss": (0.3 * np.sin(2 * np.pi * 440 * t) + 0.03 * rng.normal(size=len(t)), 440),
- }[name]
- r = analyze_audio(str(_write_av(tmp_path, y, name)))
- assert not r["music"]["present"] and r["music"].get("tempo_bpm") is None
- assert abs(r["music"]["steady_tone"]["hz"] - hz) < 0.05 * hz + 3
-
-
-def test_two_held_notes_are_still_music(tmp_path):
- """A held fifth (C + G) is harmony, not a single tone with harmonics."""
- t = np.arange(int(12 * SR)) / SR
- y = 0.15 * (np.sin(2 * np.pi * 261.63 * t) + np.sin(2 * np.pi * 392.0 * t))
- r = analyze_audio(str(_write_av(tmp_path, y, "fifth")))
- assert r["music"]["present"] and not r["music"].get("steady_tone")
-
-
-def test_pad_without_drums_reports_no_tempo(tmp_path):
- """A sustained chord with no percussion is music, but there is no beat to count."""
- t = np.arange(int(12 * SR)) / SR
- y = 0.08 * sum(np.sin(2 * np.pi * f * t) for f in (261.63, 329.63, 392.0, 523.25))
- r = analyze_audio(str(_write_av(tmp_path, y, "pad_nobeat")))
- assert r["music"]["present"] and r["music"].get("no_beat") and r["music"].get("tempo_bpm") is None
-
-
-def test_beat_survives_percussive_floor(music_mp4):
- r = analyze_audio(str(music_mp4))
- assert not r["music"].get("no_beat") and r["music"].get("tempo_bpm")
-
-
-def _syllables(pitches_hz, syl=0.25, gap=0.05, seed=0):
- """One voice: the same harmonic timbre throughout, a gliding pitch per syllable, short gaps between."""
- rng = np.random.default_rng(seed)
- out = []
- for f in pitches_hz:
- t = np.arange(int(syl * SR)) / SR
- glide = f * (1 + rng.uniform(-0.15, 0.15) * t / syl)
- ph = 2 * np.pi * np.cumsum(glide) / SR
- y = sum((0.7 ** k) * np.sin((k + 1) * ph) for k in range(8))
- out += [y * np.hanning(len(t)), np.zeros(int(gap * SR))]
- y = np.concatenate(out)
- return 0.3 * y / np.abs(y).max()
-
-
-def test_vocal_repetition_separates_narration_from_repeated_lines():
- from rea_video.audio import N_FFT, vocal_repetition
-
- freqs = np.fft.rfftfreq(N_FFT, 1 / SR)
- rng = np.random.default_rng(1)
- speech = _syllables(rng.uniform(110, 190, 100)) # 30 s, the pitch never retraces a line
- line = rng.choice([220.0, 246.9, 261.6, 293.7, 329.6, 349.2, 392.0], 26)
- song = _syllables(np.tile(line, 4), syl=0.25, gap=0.05) # an ~8 s line sung four times
- assert vocal_repetition(speech, freqs) <= 0.1
- assert vocal_repetition(song, freqs) > 0.3
diff --git a/tests/test_code_remake.py b/tests/test_code_remake.py
deleted file mode 100644
index bfde760..0000000
--- a/tests/test_code_remake.py
+++ /dev/null
@@ -1,90 +0,0 @@
-"""A first code remake built from the measured scenes: motion of the drawn layer, the redraw renderer and the
-whole loop (write the project, match each scene, render, score)."""
-import json
-
-import cv2
-import numpy as np
-
-from rea_video.code_remake import code_remake
-from rea_video.layers import scene_motion, step_motion
-from rea_video.redraw import Redraw
-
-
-def _dots(seed=0, cx=240, cy=135, n=1200):
- rng = np.random.default_rng(seed)
- img = np.zeros((270, 480, 3), np.uint8)
- for _ in range(n):
- a, r = rng.uniform(0, 2 * np.pi), rng.uniform(0, 1) ** 0.5
- cv2.circle(img, (int(cx + 90 * r * np.cos(a)), int(cy + 60 * r * np.sin(a))), 1, (230, 220, 60), -1)
- return img
-
-
-def _video(path, frames, fps=8):
- vw = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (frames[0].shape[1], frames[0].shape[0]))
- for f in frames:
- vw.write(f)
- vw.release()
- return path
-
-
-def test_step_motion_reads_zoom_rotation_and_pan():
- g = cv2.cvtColor(_dots(), cv2.COLOR_BGR2GRAY)
- M = cv2.getRotationMatrix2D((240, 135), -2, 1.03) # OpenCV turns anticlockwise for positive angles
- M[0, 2] += 4
- s, rot, px, py, drift = step_motion(g, cv2.warpAffine(g, M, (480, 270)), g > 0)
- assert abs(s - 1.03) < 0.01 and abs(rot - 2) < 0.3 and abs(px - 4 / 480) < 0.003 and abs(py) < 0.003
- assert drift < 0.002
- m = scene_motion([[1.03, 2.0, 0.01, 0.0, 0.001]] * 4, 0.25)
- assert abs(m["rotate"] - 8.0) < 1e-6 and m["zoom"] > 0.1 and abs(m["pan"][0] - 0.04) < 1e-6
- assert scene_motion([], 0.25) == {}
- assert step_motion(g, g, np.zeros_like(g, bool)) is None # nothing drawn to follow
-
-
-def _spec(tmp_path, scenes):
- spec = {"size": [320, 180], "fps": 10, "duration": 4.0, "bloom": 0, "scenes": scenes}
- (tmp_path / "spec.json").write_text(json.dumps(spec))
- return tmp_path / "spec.json"
-
-
-def _points(tmp_path, name, xy):
- rows = [[x, y, 255, 255, 255, 1.0] for x, y in xy]
- (tmp_path / name).write_text(json.dumps({"points": rows}))
- return name
-
-
-def test_redraw_places_particles_steadily_and_morphs_between_scenes(tmp_path):
- left = _points(tmp_path, "a.json", [(0.2 + 0.001 * i, 0.5) for i in range(50)])
- right = _points(tmp_path, "b.json", [(0.8 - 0.001 * i, 0.5) for i in range(50)])
- still = {"zoom": 0, "rotate": 0, "pan": [0, 0], "drift": 0, "twinkle": 0}
- spec = _spec(tmp_path, [
- {"id": "s1", "start": 0, "end": 2, "draw": "points", "points": left, "count": 50, "dot": 1, "gain": 1, "motion": still},
- {"id": "s2", "start": 2, "end": 4, "draw": "points", "points": right, "count": 50, "dot": 1, "gain": 1,
- "motion": still, "enter": "morph", "enter_s": 1.0}])
- rd = Redraw(spec)
- a, b = rd.frame(0.5), rd.frame(0.6)
- assert np.array_equal(a, b) # no motion asked for: nothing flickers
- xcentre = lambda f: float(np.nonzero(f.max(axis=2) > 40)[1].mean()) / f.shape[1] # noqa: E731
- assert abs(xcentre(a) - 0.22) < 0.03
- assert 0.35 < xcentre(rd.frame(2.5)) < 0.65 # half way through the morph
- assert abs(xcentre(rd.frame(3.5)) - 0.78) < 0.03
- assert rd.frame(5.0).max() == 0 # past the last scene
-
-
-def test_code_remake_writes_a_project_that_lines_up_with_the_original(tmp_path):
- frames = [_dots(i % 2) for i in range(24)] + [_dots(i % 2, cx=360) for i in range(24)]
- video = _video(tmp_path / "v.mp4", frames)
- out = tmp_path / "out"
- out.mkdir()
- shot = {"index": 1, "start": 0.0, "end": 6.0, "deterministic": {"probs": {"code_render": 0.9},
- "facts": {"fine_dark": 0.9}}}
- b = {"source": {"path": str(video), "width": 480, "height": 270, "fps": 8, "duration": 6.0}, "shots": [shot]}
- (out / "breakdown.json").write_text(json.dumps(b))
- res = code_remake(out)
- spec = json.loads((out / "code" / "spec.json").read_text())
- assert [s["draw"] for s in spec["scenes"]] == ["points", "points"] and spec["scenes"][1]["enter"] == "morph"
- assert (out / "code" / "render.py").exists() and (out / "code" / "remake.mp4").exists()
- assert res["compare"]["score"] > 0.6
- spec["scenes"][0]["gain"] = 2.0 # an edit is kept on the next run
- (out / "code" / "spec.json").write_text(json.dumps(spec))
- assert code_remake(out, render=False)["kept"]
- assert json.loads((out / "code" / "spec.json").read_text())["scenes"][0]["gain"] == 2.0
diff --git a/tests/test_code_render.py b/tests/test_code_render.py
deleted file mode 100644
index c90d6d7..0000000
--- a/tests/test_code_render.py
+++ /dev/null
@@ -1,118 +0,0 @@
-"""Code-drawn pictures beyond particles: gradients, glass cards, neon, procedural colour fields, grain over flat design.
-They have no material texture, which separates them from footage, AI video and 3D renders."""
-import cv2
-import numpy as np
-
-from rea_video.classify import deterministic
-from rea_video.features import spatial_features
-from rea_video.plan import code_style
-from rea_video.shots import _steady_morph
-
-
-def _feat(img):
- f = spatial_features(img)
- # whole-frame motion, no frozen background: the case where a rendered picture is easily taken for a 3D render
- f.update({"dup_ratio": 0.0, "moving_pair_ratio": 1.0, "camera": "static", "temporal_noise": 0.5, "zero_pixel_ratio": 0.6})
- return f
-
-
-def _gradient_blobs(shift=0.0):
- yy, xx = np.mgrid[0:480, 0:270].astype(np.float32)
- img = np.zeros((480, 270, 3), np.float32) + (255, 230, 240)
- for colour, x, y in (((107, 107, 255), 60, 120), ((255, 150, 77), 200, 250), ((61, 217, 255), 90, 400)):
- a = 0.85 * np.exp(-((xx - x - shift) ** 2 + (yy - y) ** 2) / (2 * 70.0 ** 2))[..., None]
- img = img * (1 - a) + np.array(colour, np.float32) * a
- return img.astype(np.uint8)
-
-
-def _neon():
- img = np.full((480, 270, 3), (12, 2, 8), np.uint8)
- glow = np.zeros_like(img)
- cv2.putText(glow, "AI", (50, 270), cv2.FONT_HERSHEY_DUPLEX, 4, (214, 43, 255), 8, cv2.LINE_AA)
- img = cv2.add(img, cv2.GaussianBlur(glow, (0, 0), 8))
- return cv2.add(img, glow)
-
-
-def _grain_poster(seed=0):
- img = np.full((480, 270, 3), (196, 220, 232), np.uint8)
- cv2.circle(img, (135, 170), 100, (61, 85, 200), -1, cv2.LINE_AA)
- img[330:] = (71, 48, 45)
- noise = np.random.default_rng(seed).normal(0, 2, img.shape[:2])[..., None] # rendered posters measure sigma ~0.6; sigma >= 3 is not seen through
- return np.clip(img + noise, 0, 255).astype(np.uint8)
-
-
-def _textured_photo(seed=0):
- rng = np.random.default_rng(seed)
- yy, xx = np.mgrid[0:480, 0:270]
- shade = 90 + 80 * np.cos(xx / 60.0) * np.sin(yy / 90.0) # lit surfaces
- fabric = cv2.GaussianBlur(rng.normal(0, 14, (480, 270)), (0, 0), 0.8) # material texture
- base = np.clip(shade + fabric, 0, 255)
- return np.dstack([base * 0.8, base * 0.9, base]).astype(np.uint8)
-
-
-def test_vector_fills_are_code_render():
- for name, img in (("gradient", _gradient_blobs()), ("neon", _neon()), ("grain", _grain_poster())):
- f = _feat(img)
- probs, ev, facts = deterministic(f)
- assert facts["vector_fill"] > 0.5, (name, f["tex_fine"], facts)
- assert max(probs, key=probs.get) == "code_render", (name, probs)
- assert any("纹理" in e for e in ev)
-
-
-def _ink_lines(seed=0):
- rng = np.random.default_rng(seed)
- img = np.full((480, 270, 3), (240, 247, 250), np.uint8)
- for _ in range(150): # generative flow strokes on paper
- x, y = rng.uniform(0, 270), rng.uniform(0, 480)
- pts = []
- for _ in range(30):
- a = np.sin(x / 40.0) * 2 + np.cos(y / 55.0)
- x, y = x + 2 * np.cos(a), y + 2 * np.sin(a)
- pts.append((int(x), int(y)))
- cv2.polylines(img, [np.array(pts, np.int32)], False, (90, 60, 40), 1, cv2.LINE_AA)
- return img
-
-
-def test_line_art_on_light_ground_is_code_render():
- f = _feat(_ink_lines())
- probs, ev, facts = deterministic(f)
- assert facts["fine_light"] > 0.5, {k: f[k] for k in ("light_ratio", "ink_ratio", "ink_smooth", "ink_peaks")}
- assert max(probs, key=probs.get) == "code_render"
-
-
-def test_grainy_dark_ground_is_not_neon():
- img = _neon().astype(np.float32)
- img += np.random.default_rng(1).normal(0, 4, img.shape[:2])[..., None] * (img.mean(2, keepdims=True) < 40)
- f = _feat(np.clip(img, 0, 255).astype(np.uint8))
- assert f["dark_flat"] < 0.5
- _, _, facts = deterministic(f)
- assert facts["vector_fill"] < 0.3
-
-
-def test_textured_picture_is_not_vector():
- f = _feat(_textured_photo())
- assert f["tex_fine"] > 0.15
- probs, _, facts = deterministic(f)
- assert facts["vector_fill"] < 0.2
- assert probs["code_render"] < 0.3
-
-
-def test_code_style_names_the_build():
- def shot(facts, texts=()):
- return {"deterministic": {"facts": facts}, "text": {"tracks": [{"kind": "title", "texts": list(texts)}], "text_coverage": 0.01,
- "items": [{"text": t, "conf": 0.95} for t in texts]}}
- assert code_style(shot({"fine_dark": 0.9})) == "particles"
- assert code_style(shot({"fine_light": 0.9})) == "lineart"
- assert code_style(shot({"vector_kind": "neon"})) == "neon"
- assert code_style(shot({"vector_kind": "gradient"})) == "gradient"
- assert code_style(shot({}, ["82", "610", "470", "抖音"])) == "data"
- assert code_style(shot({})) == "shapes"
- assert code_style(shot({}, ["000", "0", "00"])) == "shapes" # zeros read off shapes are OCR noise
-
-
-def test_colour_morph_is_not_a_dissolve():
- morph = [cv2.cvtColor(_gradient_blobs(3.0 * t), cv2.COLOR_BGR2GRAY) for t in range(40)]
- assert _steady_morph(morph, 20, 4)
- a, b = morph[0], cv2.cvtColor(_neon(), cv2.COLOR_BGR2GRAY)
- fade = [a] * 16 + [(a * (1 - w) + b * w).astype(np.uint8) for w in np.linspace(0, 1, 9)] + [b] * 16
- assert not _steady_morph(fade, 20, 4)
diff --git a/tests/test_coverage_ext.py b/tests/test_coverage_ext.py
deleted file mode 100644
index ec67aea..0000000
--- a/tests/test_coverage_ext.py
+++ /dev/null
@@ -1,75 +0,0 @@
-"""New coverage: 2D animation / stop motion, AI edits on filmed shots, colour grade, more lighting set-ups."""
-import cv2
-import numpy as np
-
-from rea_video.aspects.grade import frame_grade, words
-from rea_video.aspects.lighting import setup_for, words as lwords
-from rea_video.classify import LABELS, decide, fuse
-from rea_video.pipeline import _vlm_gate
-from rea_video.plan import Planner
-from rea_video.review import _clean
-
-
-def _gradient(shadow_bgr=(0, 0, 0), high_bgr=(0, 0, 0), black=0):
- g = np.tile(np.linspace(black, 255, 256, dtype=np.float32), (120, 1))
- img = np.stack([g, g, g], -1)
- t = (g / 255.0)[..., None]
- img = img + (1 - t) * np.array(shadow_bgr, np.float32) + t * np.array(high_bgr, np.float32)
- return np.clip(img, 0, 255).astype(np.uint8)
-
-
-def test_grade_looks():
- assert words(frame_grade(_gradient()))["look"] == "黑白"
- teal_orange = _gradient(shadow_bgr=(40, 20, -10), high_bgr=(-30, 0, 25))
- assert words(frame_grade(teal_orange))["look"].startswith("青橙")
- lifted = frame_grade(_gradient(black=60))
- assert words(lifted)["black"].startswith("黑位抬高")
-
-
-def test_grade_ignores_coloured_objects():
- img = _gradient(high_bgr=(-10, 0, 10))
- img[:, :60] = (180, 60, 10) # a saturated blue object in the dark part
- assert not words(frame_grade(img))["look"].startswith("青橙")
-
-
-def _m(**kw):
- m = {"ratio": 1.2, "key_side": "left", "top_bottom": 1.0, "transition": None, "subject_luma": 150, "bg_luma": 140,
- "dark_share": 0.05, "warmth": 8, "bg_warmth": 8, "bg_blur": 0.6, "point_lights": 0, "bg_std": 30}
- m.update(kw)
- return m
-
-
-def test_lighting_new_setups():
- m = _m(ratio=3.0, transition=0.1)
- assert setup_for(m, lwords(m), "face", "户外 白天 街边")["key"] == "outdoor_sun"
- assert setup_for(m, lwords(m), "face", "室内 卧室")["key"] != "outdoor_sun"
- m = _m(bg_luma=200, subject_luma=150)
- assert setup_for(m, lwords(m), "face", "户外 海边")["key"] == "outdoor_backlit"
- m = _m(bg_luma=10, subject_luma=130, dark_share=0.6, ratio=2.0)
- assert setup_for(m, lwords(m), "face")["key"] == "low_key"
- m = _m()
- assert setup_for(m, lwords(m), "face", None, {"mean_l": 80, "dark_share": 0.0})["key"] == "high_key"
- assert setup_for(m, lwords(m), "face", None, {"mean_l": 50, "bright_sat": 0.7, "hue_bins": 3})["key"] == "colored_ambient"
- m = _m(bg_std=5)
- assert setup_for(m, lwords(m), "other")["key"] == "product_still"
- # the koubo night street keeps its call
- m = _m(ratio=1.83, transition=0.33, subject_luma=71, bg_luma=23, dark_share=0.55)
- assert setup_for(m, lwords(m), "face", None, {"mean_l": 20, "bright_sat": 0.1, "hue_bins": 0})["key"] == "ambient_low_light"
-
-
-def test_unmeasured_labels_come_from_readers():
- assert "anim_2d" in LABELS and "stop_motion" in LABELS
- det = {k: 0.02 for k in LABELS}
- det.update({"code_render": 0.5, "cg_3d": 0.3})
- rec = {"deterministic": {"probs": det, "facts": {}}}
- seen = {"anim_2d": 0.85, "code_render": 0.15}
- assert _vlm_gate(rec, seen, {}) == seen # the tools cannot back a label they cannot score
- assert decide(fuse(det, seen, "dynamic"))[0] == "anim_2d"
-
-
-def test_ai_edits_become_post_steps():
- ans, err = _clean({"label_probs": {"live_action": 1}, "ai_edits": [{"kind": "face_swap", "evidence": "下巴边缘闪烁"}, {"kind": "x"}]})
- assert err is None and ans["ai_edits"] == [{"kind": "face_swap", "evidence": "下巴边缘闪烁"}]
- steps = Planner().edit_steps(ans["ai_edits"] + [{"kind": "lip_sync"}])
- assert [s["kind_zh"] for s in steps] == ["换脸", "对口型/改台词"]
- assert steps[0]["rule"] == "R12-owned-footage-edit" and "(" in steps[0]["how"]
diff --git a/tests/test_evaluate.py b/tests/test_evaluate.py
deleted file mode 100644
index 9911f4c..0000000
--- a/tests/test_evaluate.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""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
- assert all(v["accuracy"] == 1.0 and "errors" not in v for v in s["by_resolution"].values())
- assert sum(v["shots"] for v in s["by_camera"].values()) == sum(v["shots"] for v in s["by_resolution"].values())
-
- 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]
-
-
-def test_resolution_buckets_and_error_slices():
- assert E.resolution_bucket({"width": 1080, "height": 1920}) == "1080p"
- assert E.resolution_bucket({"width": 720, "height": 1280}) == "720p"
- assert E.resolution_bucket({"width": 480, "height": 854}) == "<=480p"
- assert E.resolution_bucket({"width": 2160, "height": 3840}) == ">1080p" and E.resolution_bucket({}) == "unknown"
- sl = {}
- E._add_slice(sl, "handheld_like", 3.0, True, "live_action", "live_action")
- E._add_slice(sl, "handheld_like", 1.0, False, "live_action", "ai_video")
- t = E._slice_table(sl)["handheld_like"]
- assert t["accuracy"] == 0.75 and t["wrong_shots"] == 1 and t["errors"] == {"live_action->ai_video": 1.0}
diff --git a/tests/test_film.py b/tests/test_film.py
deleted file mode 100644
index a1958ec..0000000
--- a/tests/test_film.py
+++ /dev/null
@@ -1,102 +0,0 @@
-import numpy as np
-
-from rea_video.classify import UNMEASURED, deterministic, fuse, group_of, video_context
-from rea_video.features import intersect_box, photo_letterbox, picture_box
-from rea_video.pipeline import _ai_or_live_doubt, _vlm_gate
-from rea_video.production import footage_runs
-
-PHOTO = {"noise_sigma": 0.5, "temporal_noise": 1.2, "flat_ratio": 0.02, "palette95": 220, "axis_edge_ratio": 0.2,
- "dup_ratio": 0.2, "dup_period": 5, "dup_regularity": 0.6, "moving_pair_ratio": 1.0, "zero_pixel_ratio": 0.1,
- "camera": "smooth_move", "saturation": 0.3}
-
-
-def _letterboxed(seed: int, h: int = 852, w: int = 480, top: int = 300, ph: int = 270) -> np.ndarray:
- rng = np.random.default_rng(seed)
- f = np.zeros((h, w, 3), np.uint8)
- f[top:top + ph] = rng.integers(30, 255, (ph, w, 3), dtype=np.uint8)
- f[top - 60:top - 40, 150:330] = 230 # a title line in the top bar
- return f
-
-
-def test_picture_box_finds_a_film_letterboxed_into_a_vertical_frame():
- frames = [_letterboxed(i) for i in range(4)]
- box = picture_box(frames)
- assert box is not None
- x, y, bw, bh = box["box"]
- assert x == 0 and bw == 1.0 and abs(y - 300 / 852) < 0.01 and abs(bh - 270 / 852) < 0.01
- assert 1.7 < box["aspect"] < 1.85
- assert photo_letterbox(frames) is not None
-
-
-def test_no_box_on_full_frame_pictures_or_rendered_cards():
- rng = np.random.default_rng(0)
- full = [rng.integers(30, 255, (270, 480, 3), dtype=np.uint8) for _ in range(3)]
- assert picture_box(full) is None
- card = [np.zeros((852, 480, 3), np.uint8) for _ in range(3)]
- for f in card:
- f[300:570] = (40, 120, 220) # one flat colour: a rendered card, not a film clip
- assert photo_letterbox(card) is None
-
-
-def test_intersect_box():
- assert intersect_box(None, None) is None
- assert intersect_box((0, 0.3, 1, 0.4), None) == (0, 0.3, 1, 0.4)
- x, y, w, h = intersect_box((0, 0.3, 1, 0.4), (0, 0, 0.8, 1))
- assert (x, y) == (0, 0.3) and abs(w - 0.8) < 1e-9 and abs(h - 0.4) < 1e-9
-
-
-def test_film_hints_are_evidence_not_a_verdict():
- f = dict(PHOTO, picture_box=[0, 0.35, 1, 0.31], picture_aspect=1.78)
- probs, ev, facts = deterministic(f, fps=30.0)
- assert set(facts["film_hints"]) == {"letterbox", "source_24"}
- assert any("影视片段线索" in e or "Film / TV footage hints" in e for e in ev)
- assert max(probs, key=probs.get) != "film_footage" # the tools never call it on hints alone
- assert probs["film_footage"] > 0.05
-
-
-def test_24fps_alone_is_not_a_film_hint():
- _, _, facts = deterministic(PHOTO, fps=30.0)
- assert facts["film_hints"] == []
-
-
-def test_tool_only_run_flags_film_hints_as_to_confirm():
- f = dict(PHOTO, picture_box=[0, 0.35, 1, 0.31], picture_aspect=1.78)
- _, _, facts = deterministic(f, fps=30.0)
- doubt = _ai_or_live_doubt("ai_video", facts, {}, {}, seen=False)
- assert doubt and ("影视片段" in doubt or "film / TV" in doubt)
-
-
-def test_film_footage_is_filmed_and_left_to_image_readers():
- assert group_of("film_footage") == "live_action"
- assert "film_footage" in UNMEASURED
- det = {"ai_video": 0.6, "live_action": 0.3, "film_footage": 0.0}
- det = {**{k: 0.01 for k in ("avatar", "cg_3d", "code_render", "screen_capture", "still_motion", "static_hold", "anim_2d", "stop_motion")}, **det}
- rec = {"deterministic": {"probs": det, "facts": {"pulldown": "24→30"}}}
- seen = {"film_footage": 0.85, "ai_video": 0.1, "live_action": 0.05}
- assert _vlm_gate(rec, seen, {}) == seen # not dropped for missing from the tools' top two
- out = fuse(det, seen, "dynamic")
- assert max(out, key=out.get) == "film_footage"
-
-
-def test_video_context_film_share():
- shots = [{"duration": 3.0, "features": dict(PHOTO, picture_box=[0, 0.35, 1, 0.31], picture_aspect=1.78)},
- {"duration": 1.0, "features": dict(PHOTO)}]
- assert video_context(shots, None, 30.0)["film_hint_share"] == 0.75
-
-
-def test_footage_runs_group_contiguous_film_shots():
- def shot(i, label):
- return {"index": i, "start": i, "end": i + 1, "base": {"label": label}}
- runs = footage_runs([shot(1, "film_footage"), shot(2, "film_footage"), shot(3, "live_action"), shot(4, "film_footage")])
- assert [r["shots"] for r in runs] == [[1, 2], [4]]
- assert (runs[0]["start"], runs[0]["end"]) == (1, 3)
-
-
-def test_reader_picks_film_over_live_action_inside_the_filmed_group():
- det = {k: 0.01 for k in ("avatar", "cg_3d", "code_render", "screen_capture", "still_motion", "static_hold", "anim_2d", "stop_motion")}
- det.update(live_action=0.6, ai_video=0.25, film_footage=0.0)
- out = fuse(det, {"film_footage": 0.85, "live_action": 0.1, "ai_video": 0.05}, "dynamic")
- assert max(out, key=out.get) == "film_footage"
- # and a reader who saw self-shot footage keeps live action
- out = fuse(det, {"live_action": 0.85, "film_footage": 0.1, "ai_video": 0.05}, "dynamic")
- assert max(out, key=out.get) == "live_action"
diff --git a/tests/test_fusion_groups.py b/tests/test_fusion_groups.py
deleted file mode 100644
index 9d77e65..0000000
--- a/tests/test_fusion_groups.py
+++ /dev/null
@@ -1,86 +0,0 @@
-"""Fusion by group first, real material vs references, scene text, 24p cameras, disputes."""
-from rea_video.assets import material_summary
-from rea_video.classify import decide, drop_scene_text, fuse
-from rea_video.overlay import summarize_text
-from rea_video.pipeline import _ai_or_live_doubt, _majority
-
-
-def test_split_generated_votes_still_beat_live():
- # qing_mv #26: tools say AI video, the agent says avatar / AI video, the VLM says live action
- det = {"live_action": 0.13, "ai_video": 0.44, "avatar": 0.06, "cg_3d": 0.27, "code_render": 0.07, "screen_capture": 0.01,
- "still_motion": 0.01, "static_hold": 0.01}
- seen = {"live_action": 0.475, "ai_video": 0.225, "avatar": 0.243} # VLM and agent averaged
- rec = {"deterministic": {"probs": det}, "vlm": {"label_probs": {"live_action": 0.95, "ai_video": 0.05}},
- "review": {"label_probs": {"ai_video": 0.4, "avatar": 0.49}}}
- assert _majority(rec) == "ai_video" # the agent's "avatar" is a vote for the tools' "generated"
- assert decide(fuse(det, seen, "dynamic", majority=_majority(rec)))[0] == "ai_video"
- label, conf = decide(fuse(det, seen, "dynamic")) # even without the majority rule
- assert label == "ai_video" and conf > 0.55
-
-
-def test_frozen_constraint_survives_grouping():
- det = {"static_hold": 0.7, "ai_video": 0.2, "avatar": 0.1}
- assert decide(fuse(det, {"ai_video": 0.5, "avatar": 0.3, "static_hold": 0.2}, "frozen"))[0] == "static_hold"
-
-
-def test_products_in_ai_pictures_are_references():
- vlm = {"embedded_assets": [{"kind": "product_photo", "description": "杯子", "is_real_material": True},
- {"kind": "logo", "description": "杯身 Logo", "is_real_material": True}]}
- m = material_summary("ai_video", None, [], vlm)
- assert not m["has_real_material"] and m["origin"] == "ai_generated"
- assert [r["kind_zh"] for r in m["references"]] == ["商品参考图", "Logo/品牌参考"]
-
-
-def test_clip_inside_ui_is_embedded_but_not_called_footage():
- vlm = {"embedded_assets": [{"kind": "real_footage", "description": "播放器里的参考视频", "is_real_material": True}]}
- m = material_summary("code_render", None, [], vlm)
- assert m["has_real_material"] and m["items"][0]["kind_zh"] == "嵌入视频片段" and m["references"] == []
-
-
-def test_scene_text_dropped_by_vlm_list_and_by_drift():
- layers = [{"kind": "subtitle", "texts": ["mophyrichods", "mophyriohocs"], "drift": None},
- {"kind": "label", "texts": ["这个榨汁杯真的绝了"], "drift": 0.0}]
- keep, dropped = drop_scene_text(layers, "ai_video", ["这个榨汁杯真的绝了"])
- assert [l["texts"][0] for l in keep] == ["这个榨汁杯真的绝了"] and dropped[0] == "mophyrichods"
- keep, _ = drop_scene_text(layers, "code_render", []) # rendered frames: text is the content, leave it
- assert len(keep) == 2
- # no VLM: words that move across the frame sit on an object
- items = [{"band": "middle", "t": t, "text": "Almond", "angle": 0, "bbox": [0.2 + 0.1 * i, 0.5, 0.2, 0.03]}
- for i, t in enumerate((0.0, 0.5, 1.0))]
- tr = summarize_text(items)["tracks"]
- assert tr[0]["drift"] >= 0.2
- keep, dropped = drop_scene_text([dict(tr[0], texts=tr[0]["texts"])], "live_action", None)
- assert keep == [] and dropped == ["Almond"]
-
-
-def test_24p_camera_doubt():
- facts = {"pulldown": "24→30", "transcode_degraded": False}
- assert "24p" in _ai_or_live_doubt("ai_video", facts, {}, {}, seen_live=0.8)
- assert _ai_or_live_doubt("ai_video", facts, {}, {}, seen_live=0.1) is None # a reader looked and saw AI
- assert "看图确认" in _ai_or_live_doubt("ai_video", facts, {}, {}, seen=False) # nobody looked yet
- assert _ai_or_live_doubt("ai_video", facts, {"hints": {"generator": ["AIGC"]}}, {}, seen=False) is None
- assert _ai_or_live_doubt("ai_video", facts, {"aigc": True}, {}, seen_live=0.8) is None
-
-
-def test_reader_backing_tools_runner_up_wins_three_way_split():
- det = {"cg_3d": 0.5, "ai_video": 0.2, "live_action": 0.13, "code_render": 0.12, "avatar": 0.02, "screen_capture": 0.01,
- "still_motion": 0.01, "static_hold": 0.01}
- rec = {"deterministic": {"probs": det}, "vlm": {"label_probs": {"live_action": 0.95, "cg_3d": 0.05}},
- "review": {"label_probs": {"ai_video": 0.74, "cg_3d": 0.1, "live_action": 0.06}}}
- assert _majority(rec) == "ai_video"
- seen = {"live_action": 0.5, "ai_video": 0.37, "cg_3d": 0.08}
- assert decide(fuse(det, seen, "dynamic", majority=_majority(rec)))[0] == "ai_video"
-
-
-def test_agent_review_dispute_flags_ai_live_disagreement():
- # keaton shot_001: tools say ai_video (dark static talking head), the agent review says
- # live action; the fusion follows the tools by design (eval-calibrated), but the
- # disagreement must surface as a dispute flag instead of hiding behind the label
- from rea_video.pipeline import _agent_review_dispute
-
- note = _agent_review_dispute("ai_video", None, {"live_action": 0.9, "ai_video": 0.05}, False, "fused_agent")
- assert note and "看图复核" in note
- # agreement: no flag
- assert _agent_review_dispute("ai_video", None, {"ai_video": 0.9}, True, "fused_agent") is None
- # an existing VLM answer means the VLM disputed flag owns this case: stay out of it
- assert _agent_review_dispute("ai_video", {"live_action": 0.9}, {"live_action": 0.9}, False, "fused_agent") is None
diff --git a/tests/test_i18n.py b/tests/test_i18n.py
deleted file mode 100644
index 2c9ad4e..0000000
--- a/tests/test_i18n.py
+++ /dev/null
@@ -1,60 +0,0 @@
-import re
-
-from rea_video.i18n import LangDict, T, join, set_lang
-from rea_video.classify import LABEL_ZH
-
-
-def test_T_and_langdict_follow_language():
- try:
- set_lang("zh")
- assert T("实拍", "live action") == "实拍"
- assert LABEL_ZH["ai_video"] == "AI 生成视频"
- assert join(["a", "b"]) == "a、b"
- set_lang("en")
- assert T("实拍", "live action") == "live action"
- assert T("{n} 个镜头", "{n} shots", n=3) == "3 shots"
- assert T("只有中文") == "只有中文" # no English yet: falls back
- assert LABEL_ZH["ai_video"] == "AI-generated video"
- assert dict(LABEL_ZH.items())["cg_3d"] == "3D render"
- assert join(["a", "b"]) == "a, b"
- d = LangDict({"x": "甲"}, en={})
- assert d["x"] == "甲" and "x" in d and len(d) == 1
- finally:
- set_lang("zh")
-
-
-def test_unknown_language_rejected():
- import pytest
-
- with pytest.raises(ValueError):
- set_lang("fr")
-
-
-def test_image_labels_follow_language():
- from rea_video.visual import LABEL_SHORT
-
- try:
- set_lang("en")
- assert LABEL_SHORT["code_render"] == "Code render"
- assert not any(re.search(r"[㐀-鿿]", v) for v in LABEL_SHORT.values())
- set_lang("zh")
- assert LABEL_SHORT["code_render"] == "代码渲染"
- finally:
- set_lang("zh")
-
-
-def test_summary_without_tempo_prints_no_bpm(tmp_path, capsys):
- import json
-
- from rea_video.cli import main
-
- b = {"lang": "en", "source": {"filename": "x.mp4", "duration": 1.0, "width": 16, "height": 16, "fps": 1.0},
- "summary": {"verdict": "x", "confidence": 1.0, "vlm": "none"}, "shots": [],
- "audio": {"has_audio": True, "voice": {"present": True, "ratio": 0.8}, "music": {"present": False, "ratio": 0.0, "segments": []}}}
- p = tmp_path / "breakdown.json"
- p.write_text(json.dumps(b), encoding="utf-8")
- try:
- assert main(["summary", str(p)]) == 0
- finally:
- set_lang("zh")
- assert "NoneBPM" not in capsys.readouterr().out
diff --git a/tests/test_layers.py b/tests/test_layers.py
deleted file mode 100644
index 544933b..0000000
--- a/tests/test_layers.py
+++ /dev/null
@@ -1,149 +0,0 @@
-"""The drawn layer of rendered shots: scenes, cut-outs, samples and remake scores, on dark and light grounds."""
-import cv2
-import numpy as np
-
-from rea_video.layers import compare, cutout, layer_mask, layout, measure, sample_points, scene_frames, split_scenes
-from rea_video.production import layer_scenes_md
-
-
-def _dots(seed=0, cx=240, light=False):
- """Dots on an ellipse: light dots on black, or dark dots on white."""
- rng = np.random.default_rng(seed)
- img = np.full((270, 480, 3), 245 if light else 0, np.uint8)
- for _ in range(1500):
- a, r = rng.uniform(0, 2 * np.pi), rng.uniform(0, 1) ** 0.5
- cv2.circle(img, (int(cx + 90 * r * np.cos(a)), int(135 + 60 * r * np.sin(a))), 1,
- (60, 40, 30) if light else (230, 220, 60), -1)
- return img
-
-
-def _strokes(x0, light=True):
- """A small line chart: a few strokes in one half of the frame."""
- img = np.full((270, 480, 3), 245 if light else 10, np.uint8)
- ink = (40, 40, 40) if light else (240, 240, 240)
- pts = np.array([[x0 + 20 * i, 200 - int(60 * np.sin(i / 2))] for i in range(9)], np.int32)
- cv2.polylines(img, [pts], False, ink, 2)
- cv2.line(img, (x0, 220), (x0 + 170, 220), ink, 1)
- return img
-
-
-def _glow(img, colour=(140, 120, 40), radius=150):
- yy, xx = np.mgrid[0:img.shape[0], 0:img.shape[1]]
- g = np.exp(-((xx - 240) ** 2 + (yy - 135) ** 2) / (2 * (radius / 2) ** 2))
- return np.clip(img.astype(np.float32) + g[..., None] * np.array(colour, np.float32), 0, 255).astype(np.uint8)
-
-
-def _video(path, frames, fps=4):
- vw = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (frames[0].shape[1], frames[0].shape[0]))
- for f in frames:
- vw.write(f)
- vw.release()
- return path
-
-
-def test_layer_follows_the_drawing_on_either_ground():
- for img in (_glow(_dots()), _dots(light=True)):
- m = measure(img)
- assert abs(m["centre"][0] - 0.5) < 0.05 and abs(m["centre"][1] - 0.5) < 0.05
- assert m["box"][0] > 0.25 and m["box"][2] < 0.75 # the ellipse spans x 150-330 of 480
- xs = np.array([p[0] for p in sample_points(img, 500)])
- assert len(xs) == 500 and xs.min() > 0.25 and xs.max() < 0.75
- assert measure(_glow(_dots()))["glow"]["radius"] > 0.05
- assert measure(_dots(light=True))["ground"] in ("#f5f5f5", "#f4f4f4")
- m = measure(_strokes(40))
- assert m["box"][2] < 0.5 # the chart sits in the left half
- assert not sample_points(_dots(), 50, text_boxes=[[0.0, 0.0, 1.0, 1.0]]) # text boxes are blanked
- rgba = cutout(_dots(light=True))
- assert rgba.shape[2] == 4 and rgba[..., 3][0, 0] == 0 and rgba[..., 3].max() > 0
-
-
-def test_split_scenes_finds_a_rearrangement_without_a_cut():
- for a, b in ((_dots(cx=120), _dots(cx=360)), (_strokes(20), _strokes(280))):
- frames = [a] * 20 + [b] * 20
- maps = np.array([layout(layer_mask(f)).ravel() for f in frames])
- times = np.arange(40) * 0.25
- sc = split_scenes(maps, times, 0.0, 10.0)
- assert len(sc) == 2 and abs(sc[0][1] - 5.0) <= 0.25
- assert split_scenes(maps[:20], times[:20], 0.0, 5.0) == [(0.0, 5.0)]
-
-
-def test_compare_ranks_remakes_and_ignores_the_ground_colour(tmp_path):
- ref = _video(tmp_path / "ref.mp4", [_glow(_dots())] * 12)
- good = _video(tmp_path / "good.mp4", [_dots(1, light=True)] * 12) # same shape, dark on a light ground
- bad = np.full((270, 480, 3), 230, np.uint8)
- cv2.circle(bad, (420, 60), 30, (40, 40, 40), -1)
- bad = _video(tmp_path / "bad.mp4", [bad] * 12)
- g = compare(str(ref), str(good), out=tmp_path / "cmp")
- b = compare(str(ref), str(bad))
- assert g["score"] > 0.6 > b["score"]
- assert (tmp_path / "cmp" / "compare_worst.jpg").exists() and (tmp_path / "cmp" / "compare.json").exists()
- assert compare(str(ref), str(ref))["score"] > 0.99
-
-
-def test_scene_frames_covers_rendered_shots_and_clears_old_files(tmp_path):
- video = _video(tmp_path / "v.mp4", [_strokes(20)] * 20 + [_strokes(280)] * 20)
- shot = {"index": 1, "start": 0.0, "end": 10.0, "deterministic": {"probs": {"code_render": 0.9, "cg_3d": 0.1}}}
- b = {"source": {"path": str(video)}, "shots": [shot]}
- out = tmp_path / "out"
- stale = out / "frames" / "points" / "scene_09.json"
- stale.parent.mkdir(parents=True)
- stale.write_text("{}")
- res = scene_frames(out, breakdown=b)
- assert [s["id"] for s in res["scenes"]] == ["scene_01", "scene_02"] and not stale.exists()
- sc = res["scenes"][0]
- assert sc["measure"]["box"][2] < 0.5 and sc["track"]
- assert (out / sc["points"]).exists() and (out / sc["frames"]["layer"]).exists()
- shot["base"] = {"label": "cg_3d"} # relabelled after review: nothing left to write, no empty folder
- assert scene_frames(out, breakdown=b)["scenes"] == []
- assert not (out / "frames").exists()
-
-
-def test_layer_step_failure_keeps_the_breakdown(tmp_path, monkeypatch):
- import rea_video.layers as layers
- from rea_video.pipeline import decompose
-
- def boom(*a, **k):
- raise RuntimeError("decode failed")
-
- monkeypatch.setattr(layers, "scene_frames", boom)
- video = _video(tmp_path / "dots.mp4", [_dots(i % 3) for i in range(24)], fps=8)
- out = tmp_path / "o"
- b = decompose(video, out, use_vlm=False, ocr=False, stems=False, asr=False, speakers=False)
- assert "layer_scenes" not in b
- assert (out / "report.html").exists() and (out / "breakdown.json").exists()
-
-
-def test_scene_table_follows_the_shot_labels(tmp_path):
- from rea_video.memory import correct
- from rea_video.pipeline import decompose, finalize
-
- video = _video(tmp_path / "dots.mp4", [_dots(i % 3) for i in range(24)], fps=8)
- out = tmp_path / "o"
- b = decompose(video, out, use_vlm=False, ocr=False, stems=False, asr=False, speakers=False)
- assert b.get("layer_scenes", {}).get("count", 0) >= 1
- assert b["production_plan"].get("layer_scenes")
- assert "画面场景" in (out / "video" / "remake.md").read_text(encoding="utf-8")
- correct(b, label="cg_3d", shots="1", record=False) # the user says it is a 3D render after all
- finalize(b, out)
- assert not b["production_plan"].get("layer_scenes")
-
-
-def test_scene_table_text():
- md = "\n".join(layer_scenes_md([{"id": "scene_01", "shot": 1, "start": 0.0, "end": 5.2, "points": "frames/points/scene_01.json",
- "measure": {"ground": "#000000", "glow": {"colour": "#507c87", "centre": [0.5, 0.52], "radius": 0.15},
- "colours": [{"hex": "#4e747c"}], "pieces": 286, "box": [0.4, 0.03, 0.6, 0.78]}}]))
- assert "| scene_01 | #1 | 0.0–5.2s | #000000 | #507c87" in md and "rea-video compare" in md and "scene_XX_layer.png" in md
- assert layer_scenes_md([]) == []
-
-
-def test_compare_says_what_to_change(tmp_path):
- moving = [_glow(_dots(0, cx=100 + 15 * i)) for i in range(24)]
- ref = _video(tmp_path / "ref.mp4", moving)
- late = compare(str(ref), str(_video(tmp_path / "late.mp4", [moving[0]] * 4 + moving[:-4])))
- assert late["offset"]["seconds"] == 1.0 and late["advice"] == [] # lined up first, nothing else is off
- still = _video(tmp_path / "still.mp4", [_glow(_dots())] * 12)
- left = compare(str(still), str(_video(tmp_path / "left.mp4", [_glow(_dots(cx=150))] * 12)))
- assert "offset" not in left and any("偏左" in a for a in left["advice"])
- pale = compare(str(still), str(_video(tmp_path / "pale.mp4", [_dots(light=True)] * 12)))
- assert any(a.startswith("底色") and "偏亮" in a for a in pale["advice"])
- assert compare(str(still), str(still))["advice"] == []
diff --git a/tests/test_memory.py b/tests/test_memory.py
deleted file mode 100644
index e576f99..0000000
--- a/tests/test_memory.py
+++ /dev/null
@@ -1,142 +0,0 @@
-"""User memory: corrections fix the breakdown, persist, re-apply, and surface as hints; prefs set defaults."""
-import json
-
-import pytest
-import yaml
-
-from rea_video.cli import main
-from rea_video.memory import load_corrections, patterns
-from rea_video.pipeline import _vlm_gate, decompose
-
-
[email protected]("bounds, expected", [
- ({"end": 2.0}, ["shot_001"]),
- ({"start": 2.0, "end": 4.0}, ["shot_002"]),
- ({"start": 4.0}, ["shot_003"]),
- ({}, ["shot_001", "shot_002", "shot_003"]),
- ({"shots": "2"}, ["shot_002"]),
-])
-def test_correction_bounds_only_modify_and_remember_selected_shots(bounds, expected):
- from rea_video.memory import correct, reapply
-
- def breakdown():
- return {"source": {"filename": "example.mp4", "duration": 6.0, "sha256_head": "example"},
- "shots": [{"id": f"shot_{i + 1:03d}", "start": i * 2.0, "end": (i + 1) * 2.0,
- "duration": 2.0, "base": {"label": "live_action", "confidence": 0.8},
- "deterministic": {"probs": {"live_action": 1.0}, "facts": {}}}
- for i in range(3)]}
-
- b = breakdown()
- correct(b, label="ai_video", **bounds)
- assert [s["id"] for s in b["shots"] if "user" in s] == expected
- assert [c["shot"] for c in load_corrections()] == expected
- fresh = breakdown()
- reapply(fresh)
- assert [s["id"] for s in fresh["shots"] if "user" in s] == expected
-
-
-def test_empty_end_only_correction_does_not_change_memory():
- from rea_video.memory import correct
-
- b = {"source": {"filename": "example.mp4", "duration": 2.0, "sha256_head": "example"},
- "shots": [{"id": "shot_001", "start": 0.0, "end": 2.0, "duration": 2.0,
- "base": {"label": "live_action", "confidence": 0.8},
- "deterministic": {"probs": {"live_action": 1.0}, "facts": {}}}]}
- with pytest.raises(ValueError, match="没有选中任何镜头"):
- correct(b, label="ai_video", end=0.0)
- assert "user" not in b["shots"][0]
- assert load_corrections() == []
-
-
-def test_correction_fixes_breakdown_and_is_remembered(media, tmp_path, capsys):
- out = tmp_path / "o"
- b = decompose(media["code"], out, use_vlm=False, ocr=False, workers=1, stems=False)
- first = b["shots"][0]["base"]["label"]
- assert first != "ai_video"
- assert main(["correct", str(out), "--shots", "1", "--label", "ai_video", "--real", "no", "--note", "这是 AI 生成的"]) == 0
- assert "已纠正 1 个镜头" in capsys.readouterr().out
- b2 = json.loads((out / "breakdown.json").read_text(encoding="utf-8"))
- s0 = b2["shots"][0]
- assert s0["base"]["label"] == "ai_video" and s0["base"]["decided_by"] == "user" and s0["base"]["confidence"] == 1.0
- assert s0["base"]["evidence"][0].startswith("[用户纠正]") and not s0["material"]["has_real_material"]
- assert "AI 生成视频" in b2["summary"]["verdict"]
- (c,) = load_corrections()
- assert c["before"] == first and c["label"] == "ai_video" and c["tool"] == first and c["note"] == "这是 AI 生成的"
-
- # the same file decomposed again gets the correction back
- b3 = decompose(media["code"], tmp_path / "o2", use_vlm=False, ocr=False, workers=1, stems=False)
- assert b3["shots"][0]["base"]["label"] == "ai_video"
- # ...but evaluation runs never see user corrections
- b4 = decompose(media["code"], tmp_path / "o3", use_vlm=False, ocr=False, workers=1, stems=False, memory=False)
- assert b4["shots"][0]["base"]["label"] == first
-
- # re-correcting the same file + shot counts once (latest wins)
- main(["correct", str(tmp_path / "o3"), "--shots", "1", "--label", "ai_video"])
- assert patterns()[0]["count"] == 1
-
- capsys.readouterr()
- assert main(["memory"]) == 0
- printed = capsys.readouterr().out
- assert "纠正:" in printed and "→ 用户「AI 生成视频」" in printed
- labels = tmp_path / "user_labels.yaml"
- assert main(["memory", "--export-labels", str(labels)]) == 0
- spec = yaml.safe_load(labels.read_text(encoding="utf-8"))
- assert spec["videos"][0]["segments"][0][2] == "ai_video"
-
-
-def test_prefs_set_defaults_and_validate(capsys):
- assert main(["prefs", "engine", "kling2.1"]) == 0
- assert main(["prefs", "vlm", "maybe"]) == 2
- assert main(["prefs", "colour", "red"]) == 2
- assert main(["prefs", "colour"]) == 2
- assert main(["prefs", "reviewer=june"]) == 0
- capsys.readouterr()
- assert main(["prefs", "reviewer"]) == 0 and capsys.readouterr().out.strip() == "june"
- assert main(["prefs", "--note", "报告尽量短"]) == 0
- capsys.readouterr()
- assert main(["prefs"]) == 0
- printed = capsys.readouterr().out
- assert "engine = kling2.1" in printed and "说明 1: 报告尽量短" in printed
- assert main(["prefs", "engine", "--unset"]) == 0
- capsys.readouterr()
- main(["memory"])
- assert "报告尽量短" in capsys.readouterr().out
-
-
-def test_single_image_reader_cannot_flip_ai_vs_live_axis():
- from rea_video.classify import LABELS
-
- def p(**kw):
- rest = (1 - sum(kw.values())) / (len(LABELS) - len(kw))
- return {k: kw.get(k, rest) for k in LABELS}
-
- def rec(det, facts=None):
- return {"deterministic": {"probs": det, "facts": facts or {}}, "vlm": {"label_probs": {}}}
-
- vlm_avatar = p(avatar=0.9)
- assert _vlm_gate(rec(p(ai_video=0.9, avatar=0.03)), vlm_avatar, {}) is None # tools sure + not in top-2
- assert _vlm_gate(rec(p(ai_video=0.74, cg_3d=0.1)), p(cg_3d=0.95), {}) is None # tools sure on AI axis
- assert _vlm_gate(rec(p(cg_3d=0.56, code_render=0.36)), p(code_render=0.8), {}) # 3D vs code: VLM helps
- assert _vlm_gate(rec(p(cg_3d=0.51, ai_video=0.18, code_render=0.12)), p(code_render=0.8), {}) # rendered subtype: reader picks
- assert _vlm_gate(rec(p(ai_video=0.3, live_action=0.25, cg_3d=0.2)), p(avatar=0.9), {}) is None # not for generated subtypes
- assert _vlm_gate(rec(p(ai_video=0.46, live_action=0.38), {"transcode_degraded": True, "pulldown": "24→30"}),
- p(live_action=0.85), {"native30": False}) is None # 24fps transcode never -> live
- assert _vlm_gate(rec(p(ai_video=0.46, live_action=0.38), {"transcode_degraded": True, "native_cadence": True}),
- p(live_action=0.85), {"native30": False}) # this shot has camera cadence: the reader decides
- assert _vlm_gate(rec(p(ai_video=0.46, live_action=0.38), {"transcode_degraded": True}),
- p(live_action=0.85), {"native30": True})
- agent_only = {"deterministic": {"probs": p(ai_video=0.9, avatar=0.03), "facts": {}}, "review": {"label_probs": vlm_avatar}}
- assert _vlm_gate(agent_only, vlm_avatar, {}) is None # same rule for a lone agent
- both = dict(agent_only, vlm={"label_probs": vlm_avatar})
- assert _vlm_gate(both, vlm_avatar, {}) is vlm_avatar # two readers: _majority decides
-
-
-def test_repeated_pattern_becomes_review_hint(media, tmp_path):
- from rea_video.memory import hint_for
-
- cs = [{"video_key": f"v{i}", "shot": "shot_001", "before": "cg_3d", "tool": "cg_3d", "label": "ai_video",
- "vlm": "cg_3d", "review": None, "context": {"transcoded": True}} for i in range(2)]
- (p,) = patterns(cs)
- assert p["count"] == 2 and p["vlm_wrong"] == 2 and p["transcoded"] == 2
- assert "用户过去 2 次" in hint_for("cg_3d", [p]) and hint_for("ai_video", [p]) is None
- assert hint_for("cg_3d", patterns(cs[:1])) is None # one correction is not a pattern yet
diff --git a/tests/test_motion.py b/tests/test_motion.py
deleted file mode 100644
index 6584b1a..0000000
--- a/tests/test_motion.py
+++ /dev/null
@@ -1,144 +0,0 @@
-"""Element motion timeline of code-rendered shots, flash cuts, counters and dark text on light grounds."""
-import cv2
-import numpy as np
-
-from conftest import _write
-from rea_video.media import video_info
-from rea_video.motion import event_line, motion_events, palette
-from rea_video.packaging import _NUMERIC, _norm, text_style
-from rea_video.shots import build_track, detect_shots
-
-
-def _close(a, b, tol=6):
- return all(abs(int(a[i:i + 2], 16) - int(b[i:i + 2], 16)) <= tol for i in (1, 3, 5))
-
-
-def _staggered(n=90):
- """Three cards pop in 0.5 s apart from 0.2 s, then a bar grows left to right from 1.5 s to 2.5 s."""
- frames = []
- for i in range(n):
- f = np.full((640, 360, 3), (240, 240, 240), np.uint8)
- for k, colour in enumerate([(60, 60, 230), (60, 200, 60), (230, 120, 40)]):
- if i >= 6 + 15 * k:
- cv2.rectangle(f, (40 + 110 * k, 120), (120 + 110 * k, 220), colour, -1)
- if i >= 45:
- w = int(280 * min(1.0, (i - 45) / 30))
- cv2.rectangle(f, (40, 400), (40 + max(1, w), 430), (30, 30, 30), -1)
- frames.append(f)
- return frames
-
-
-def test_events_time_place_colour(tmp_path):
- p = str(_write(_staggered(), tmp_path / "s.mp4"))
- r = motion_events(p, video_info(p), 0.0, 3.0)
- ev = r["events"]
- cards = [e for e in ev if e["box"][1] < 0.4]
- assert len(cards) == 3
- assert [round(e["t0"], 1) for e in cards] == [0.2, 0.7, 1.2]
- assert _close(cards[0]["colour"], "#e63c3c")
- bar = [e for e in ev if e["box"][1] > 0.55]
- assert len(bar) == 1 and bar[0]["sweep"] == "right" and abs(bar[0]["t0"] - 1.5) < 0.15
- assert "向右展开" in event_line(bar[0])
- assert r["sequences"] and r["sequences"][0]["n"] == 3 and abs(r["sequences"][0]["interval"] - 0.5) < 0.1
-
-
-def test_palette_background():
- f = np.full((200, 100, 3), (231, 241, 246), np.uint8)
- f[80:120, 20:80] = (54, 89, 254)
- pal = palette(f)
- assert _close(pal["background"], "#f6f1e7")
- assert any(_close(c["hex"], "#fe5936") for c in pal["colours"])
-
-
-def test_flash_cut_and_light_shot_not_a_fade(tmp_path):
- frames = [np.full((360, 200, 3), 20, np.uint8) for _ in range(30)]
- for i in range(30): # cut into a shot that opens on a grey flash decaying over 0.2 s
- f = np.full((360, 200, 3), 20, np.uint8)
- cv2.circle(f, (100, 180), 40, (200, 200, 60), -1)
- f = cv2.addWeighted(f, 1.0, np.full_like(f, 160), max(0.0, 1 - i / 6), 0)
- frames.append(f)
- for i in range(30): # hard cut to a white page with a title: a shot, not a fade through white
- f = np.full((360, 200, 3), 255, np.uint8)
- cv2.putText(f, "TITLE", (40, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (40, 40, 40), 2)
- frames.append(f)
- p = str(_write(frames, tmp_path / "c.mp4"))
- shots = detect_shots(build_track(p, video_info(p)))
- assert [round(s.start, 1) for s in shots] == [0.0, 1.0, 2.0]
- assert shots[1].transition_in == "flash" and 0.1 <= shots[1].flash_s <= 0.4
- assert shots[2].transition_in == "cut"
-
-
-def test_numbers_are_counters_and_dark_text_is_not_outlined():
- assert all(_NUMERIC.fullmatch(_norm(t)) for t in ["820", "4.7%", "12,840", "3.6万", "+4"])
- assert not _NUMERIC.fullmatch(_norm("抖音"))
- f = np.full((120, 400, 3), 255, np.uint8)
- cv2.putText(f, "ABOOD", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (40, 40, 40), 5)
- st = text_style(f, (20, 30, 300, 90), rendered=True)
- assert st and st["fill_name"] in ("黑", "灰") and "stroke" not in st
-
-
-def test_outlined_subtitle_on_bright_footage_keeps_its_outline():
- """The rendered-picture corrections stay off for footage: white text with a dark outline over a bright scene."""
- f = np.full((120, 400, 3), 235, np.uint8)
- cv2.putText(f, "ABOOD", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (20, 20, 20), 12)
- cv2.putText(f, "ABOOD", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 4)
- st = text_style(f, (14, 26, 310, 94))
- assert st and st["fill_name"] == "白" # not swapped to dark text, as the rendered rules would on a light ground
-
-
-def test_element_crops_numbered_like_the_timeline(tmp_path):
- from pathlib import Path
-
- from rea_video.motion import element_crops
-
- p = str(_write(_staggered(), tmp_path / "s.mp4"))
- info = video_info(p)
- m = motion_events(p, info, 0.0, 3.0)
- sheet = element_crops(p, info, 0.0, 3.0, m, tmp_path / "shots", "shot_001", 360)
- assert sheet == "shots/shot_001_elements.jpg" and (tmp_path / sheet).is_file()
- for k, e in enumerate(m["events"], 1):
- assert e["crop"] == f"shots/shot_001_el_{k:02d}.jpg"
- im = cv2.imread(str(tmp_path / e["crop"]))
- assert im is not None and im.shape[0] > 10
- assert "[截图](shots/shot_001_el_01.jpg)" in event_line(m["events"][0])
- assert Path(tmp_path / "shots").is_dir()
-
-
-def test_text_style_is_repeatable():
- """Colour clustering must not depend on OpenCV's RNG state (other calls, other threads)."""
- from concurrent.futures import ThreadPoolExecutor
-
- rng = np.random.default_rng(5)
- f = np.clip(rng.normal(120, 40, (120, 400, 3)), 0, 255).astype(np.uint8)
- cv2.putText(f, "ABOOD", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (30, 30, 200), 9)
- cv2.putText(f, "ABOOD", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (250, 250, 250), 3)
-
- def run(_):
- cv2.randu(np.zeros((50, 50), np.uint8), 0, 255) # disturb the RNG
- return text_style(f, (14, 26, 310, 94)), palette(f)
-
- first = run(0)
- with ThreadPoolExecutor(4) as pool:
- assert all(r == first for r in pool.map(run, range(12)))
-
-
-def test_style_vote_ties_do_not_depend_on_hash_seed():
- """Python randomises str hashing per process; a tie broken by set order would give different colours per run."""
- import subprocess
- import sys
-
- code = ("from rea_video.packaging import merge_style;"
- "print(merge_style([{'fill_name':'棕','fill':'#a0522d'},{'fill_name':'橙','fill':'#ff8800'}]))")
- outs = {subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
- env={**__import__("os").environ, "PYTHONHASHSEED": str(seed)}).stdout for seed in range(6)}
- assert len(outs) == 1 and "棕" in outs.pop()
-
-
-def test_thin_label_with_a_shadow_reads_as_its_letters():
- """Small glowing labels on a rendered picture: one-pixel strokes and a dark drop shadow, on a dim coloured ground."""
- f = np.zeros((120, 400, 3), np.uint8)
- f[:] = (20, 40, 60) # dim brown ground
- cv2.putText(f, "STOMACH 22", (31, 71), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (5, 5, 5), 2, cv2.LINE_AA) # shadow
- cv2.putText(f, "STOMACH 22", (30, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (200, 200, 140), 1, cv2.LINE_AA)
- st = text_style(f, (28, 52, 180, 76), rendered=True)
- assert st and st["fill_name"] in ("青", "白", "cyan", "white"), st
diff --git a/tests/test_ocr_lang.py b/tests/test_ocr_lang.py
deleted file mode 100644
index 12e7102..0000000
--- a/tests/test_ocr_lang.py
+++ /dev/null
@@ -1,138 +0,0 @@
-import sys
-import types
-
-import pytest
-
-from rea_video import overlay
-
-
-def fake_rapidocr(monkeypatch):
- calls = []
-
- class RapidOCR:
- def __init__(self, **kwargs):
- calls.append(kwargs)
-
- monkeypatch.setitem(sys.modules, "rapidocr_onnxruntime", types.SimpleNamespace(RapidOCR=RapidOCR))
- monkeypatch.setattr(overlay, "_OCR", {})
- return calls
-
-
-def test_default_language_is_zh(monkeypatch):
- monkeypatch.delenv("REA_OCR_LANG", raising=False)
- assert overlay.ocr_lang() == "zh"
-
-
-def test_unknown_language_is_rejected(monkeypatch):
- monkeypatch.setenv("REA_OCR_LANG", "fr")
- with pytest.raises(ValueError):
- overlay.ocr_lang()
-
-
-def test_zh_uses_bundled_model(monkeypatch, fake_rapidocr):
- monkeypatch.setenv("REA_OCR_LANG", "zh")
- assert overlay.get_ocr() is overlay.get_ocr()
- assert fake_rapidocr == [{}]
-
-
-def test_ja_uses_japanese_recognizer(monkeypatch, tmp_path, fake_rapidocr):
- model = tmp_path / "japan.onnx"
- model.write_bytes(b"x")
- monkeypatch.setenv("REA_OCR_REC_MODEL", str(model))
- monkeypatch.setenv("REA_OCR_LANG", "ja")
- overlay.get_ocr()
- monkeypatch.setenv("REA_OCR_LANG", "zh")
- overlay.get_ocr()
- assert fake_rapidocr == [{"rec_model_path": str(model)}, {}] # one instance per language
-
-
-def test_ko_uses_korean_recognizer_without_angle_classifier(monkeypatch, tmp_path, fake_rapidocr):
- model = tmp_path / "korean.onnx"
- model.write_bytes(b"x")
- monkeypatch.setenv("REA_OCR_REC_MODEL", str(model))
- monkeypatch.setenv("REA_OCR_LANG", "ko")
- overlay.get_ocr()
- monkeypatch.setenv("REA_OCR_LANG", "ja")
- overlay.get_ocr()
- # the classifier flips Hangul lines upside down, so only ko turns it off
- assert fake_rapidocr == [{"rec_model_path": str(model), "use_cls": False}, {"rec_model_path": str(model)}]
-
-
-def test_ko_model_is_pinned():
- name, url, sha = overlay._REC_MODELS["ko"]
- assert url.startswith("https://") and url.endswith("/" + name)
- assert len(sha) == 64 and int(sha, 16) >= 0
-
-
-def test_rapidocr3_turns_off_angle_classifier_for_ko(monkeypatch, tmp_path):
- made = []
-
- class RapidOCR:
- def __init__(self, params=None):
- made.append(params)
-
- monkeypatch.setitem(sys.modules, "rapidocr_onnxruntime", None) # import raises ImportError
- monkeypatch.setitem(sys.modules, "rapidocr", types.SimpleNamespace(RapidOCR=RapidOCR))
- monkeypatch.setattr(overlay, "_OCR", {})
- model = tmp_path / "korean.onnx"
- model.write_bytes(b"x")
- monkeypatch.setenv("REA_OCR_REC_MODEL", str(model))
- monkeypatch.setenv("REA_OCR_LANG", "ko")
- overlay.get_ocr()
- monkeypatch.setenv("REA_OCR_LANG", "zh")
- overlay.get_ocr()
- assert made[0]["Rec.model_path"] == str(model) and made[0]["Global.use_cls"] is False
- assert "Global.use_cls" not in made[1] # other languages keep rapidocr's default
-
-
-def test_cached_model_with_matching_checksum_is_not_downloaded(monkeypatch, tmp_path):
- monkeypatch.delenv("REA_OCR_REC_MODEL", raising=False)
- monkeypatch.setenv("REA_VIDEO_MODELS", str(tmp_path))
- 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, "fetch", lambda *a: pytest.fail("should not download"))
- assert overlay.rec_model("ja") == tmp_path / name
-
-
-def test_ocr_lang_pref_is_validated(monkeypatch, tmp_path):
- from rea_video import memory
-
- monkeypatch.setenv("REA_VIDEO_HOME", str(tmp_path))
- with pytest.raises(ValueError):
- memory.set_pref("ocr_lang", "fr")
-
-
-def test_rapidocr3_is_used_when_rapidocr_onnxruntime_is_missing(monkeypatch, tmp_path):
- import numpy as np
-
- made = []
-
- class Output:
- boxes = np.array([[[0, 0], [10, 0], [10, 5], [0, 5]]], dtype=np.float32)
- txts = ("字幕",)
- scores = (0.9,)
- elapse = 0.1
-
- class RapidOCR:
- def __init__(self, params=None):
- made.append(params)
-
- def __call__(self, img):
- return Output() if img is not None else types.SimpleNamespace(boxes=None, txts=None, scores=None, elapse=0.0)
-
- monkeypatch.setitem(sys.modules, "rapidocr_onnxruntime", None) # import raises ImportError
- monkeypatch.setitem(sys.modules, "rapidocr", types.SimpleNamespace(RapidOCR=RapidOCR))
- monkeypatch.setattr(overlay, "_OCR", {})
- model = tmp_path / "japan.onnx"
- model.write_bytes(b"x")
- monkeypatch.setenv("REA_OCR_REC_MODEL", str(model))
- monkeypatch.setenv("REA_OCR_LANG", "ja")
- ocr = overlay.get_ocr()
- assert made[0]["Rec.model_path"] == str(model)
- res, _ = ocr(np.zeros((5, 10, 3), np.uint8))
- assert res == [[[[0.0, 0.0], [10.0, 0.0], [10.0, 5.0], [0.0, 5.0]], "字幕", 0.9]]
- assert ocr(None)[0] is None # nothing found: same as rapidocr-onnxruntime
- for box, text, conf in res: # the shape overlay / packaging iterate over
- assert len(box) == 4 and text == "字幕" and conf == 0.9
diff --git a/tests/test_packaging.py b/tests/test_packaging.py
deleted file mode 100644
index 078a7ab..0000000
--- a/tests/test_packaging.py
+++ /dev/null
@@ -1,307 +0,0 @@
-"""Packaging layer: subtitle timeline + style, 花字, stickers / GIFs, SFX alignment, exports."""
-import cv2
-import numpy as np
-import pytest
-
-from conftest import _photo_like, _write
-from rea_video import packaging as P
-from rea_video.media import video_info
-
-W, H, FPS = 360, 640, 30
-
-
-def _outlined(img, text, org, scale, color, thick, outline=(0, 0, 0)):
- # the outline is the text stamped around the glyph (OpenCV 5 ignores thickness for anti-aliased text)
- r = max(2, int(round(3 * scale)))
- for dx in (-r, 0, r):
- for dy in (-r, 0, r):
- if dx or dy:
- cv2.putText(img, text, (org[0] + dx, org[1] + dy), cv2.FONT_HERSHEY_DUPLEX, scale, outline, thick, cv2.LINE_AA)
- cv2.putText(img, text, org, cv2.FONT_HERSHEY_DUPLEX, scale, color, thick, cv2.LINE_AA)
-
-
-def _emoji(frame_no: int) -> np.ndarray:
- """A 2-frame looping 'GIF': a yellow face whose mouth opens / closes every 0.2 s, with a white sticker rim."""
- s = np.zeros((96, 96, 3), np.uint8)
- cv2.circle(s, (48, 48), 46, (255, 255, 255), -1)
- cv2.circle(s, (48, 48), 40, (40, 210, 250), -1)
- cv2.circle(s, (34, 38), 6, (30, 30, 30), -1)
- cv2.circle(s, (62, 38), 6, (30, 30, 30), -1)
- if (frame_no // 6) % 2:
- cv2.ellipse(s, (48, 64), (16, 12), 0, 0, 360, (30, 30, 160), -1)
- else:
- cv2.line(s, (32, 64), (64, 64), (30, 30, 30), 4)
- return s
-
-
-def _paste(f, s, x, y):
- mask = s.sum(axis=2) > 0
- f[y:y + s.shape[0], x:x + s.shape[1]][mask] = s[mask]
-
-
[email protected](scope="module")
-def packed(tmp_path_factory):
- d = tmp_path_factory.mktemp("pack")
- rng = np.random.default_rng(3)
- shot_a = np.clip(_photo_like(W + 120, H, 11).astype(np.int16) + 70, 0, 255).astype(np.uint8) # light enough for a black outline
- shot_b = np.clip(_photo_like(W + 120, H, 12).astype(np.int16) + 70, 0, 255).astype(np.uint8)
- frames = []
- for i in range(6 * FPS):
- t = i / FPS
- src = shot_a if t < 3.0 else shot_b
- off = int(40 * (t % 3.0) / 3.0) # slow pan: live-ish background, never still
- f = np.ascontiguousarray(src[:, off:off + W]).copy()
- f = np.clip(f.astype(np.int16) + rng.normal(0, 2, f.shape).astype(np.int16), 0, 255).astype(np.uint8)
- # subtitles: two lines in a fixed bottom lane, white with a black outline
- if 0.5 <= t < 2.0:
- _outlined(f, "HELLO WORLD", (70, 560), 0.9, (255, 255, 255), 2)
- elif 2.0 <= t < 3.5:
- _outlined(f, "SECOND LINE", (70, 560), 0.9, (255, 255, 255), 2)
- elif 3.5 <= t < 5.5:
- _outlined(f, "THIRD ONE", (90, 560), 0.9, (255, 255, 255), 2)
- # looping GIF sticker, appears and leaves mid-shot
- if 1.0 <= t < 2.4:
- _paste(f, _emoji(i), 230, 90)
- # 花字: big yellow word that pops in (scales up over 0.2 s)
- if 4.0 <= t < 5.2:
- k = min(1.0, 0.4 + 0.6 * (t - 4.0) / 0.2)
- _outlined(f, "WOW!", (int(120 - 30 * (k - 1)), 300), 2.2 * k, (0, 230, 255), 5)
- frames.append(f)
- path = _write(frames, d / "pack.mp4", fps=FPS)
- info = video_info(path)
- return P.analyze(path, info, cuts=[3.0], out_dir=d, ocr=True), d
-
-
-def _ocr_ok():
- from rea_video.overlay import get_ocr
- return get_ocr() is not None
-
-
[email protected](not _ocr_ok(), reason="rapidocr not installed")
-def test_subtitle_timeline(packed):
- pack, _ = packed
- subs = [c for c in pack["text_cues"] if c["kind"] == "subtitle"]
- texts = [P._norm(c["text"]) for c in subs]
- assert any("helloworld" in t for t in texts) and any("secondline" in t for t in texts)
- hello = next(c for c in subs if "helloworld" in P._norm(c["text"]))
- assert abs(hello["t0"] - 0.5) <= 0.25 and abs(hello["t1"] - 2.0) <= 0.25
- st = hello["style"]
- assert st.get("fill_name") == "白" and st.get("stroke_name") == "黑"
- srt = P.to_srt(pack["text_cues"])
- assert "HELLOWORLD" in srt.upper().replace(" ", "") and "-->" in srt
-
-
[email protected](not _ocr_ok(), reason="rapidocr not installed")
-def test_huazi_pop(packed):
- pack, _ = packed
- wow = [c for c in pack["text_cues"] if "wow" in P._norm(c["text"])]
- assert wow, [c["text"] for c in pack["text_cues"]]
- c = wow[0]
- assert c["kind"] == "huazi", c
- assert c["style"].get("fill_name") == "黄"
- assert abs(c["t0"] - 4.0) <= 0.25
-
-
-# without OCR the subtitle band is not recognized as text and shows up as a second "sticker"
[email protected](not _ocr_ok(), reason="rapidocr not installed")
-def test_gif_sticker(packed):
- pack, d = packed
- st = [s for s in pack["stickers"] if s["t0"] < 2.0 and s["t1"] > 1.2]
- assert st, pack["stickers"]
- s = st[0]
- assert s["kind"] == "animated_sticker" and s["looping"]
- assert abs(s["t0"] - 1.0) <= 0.2 and abs(s["t1"] - 2.4) <= 0.3
- x, y, w, h = s["bbox"]
- assert abs((x + w / 2) - (230 + 48) / W) < 0.08 and abs((y + h / 2) - (90 + 48) / H) < 0.06
- assert (d / s["image"]).exists()
- # nothing else is called a sticker: the subtitles and the 花字 are text, the pan is the picture
- assert len(pack["stickers"]) == 1, pack["stickers"]
-
-
-def test_sfx_alignment():
- cues = [{"id": "text_001", "kind": "huazi", "kind_zh": "花字", "text": "WOW", "t0": 4.0, "t1": 5.0}]
- stickers = [{"id": "sticker_01", "kind_zh": "动态贴纸/GIF", "t0": 1.0, "t1": 2.4, "disappears_mid_shot": True}]
- ev = P.visual_events(cues, stickers, [3.0])
- sfx = [{"t": 4.05, "type": "pop"}, {"t": 1.02, "type": "pop"}, {"t": 3.01, "type": "whoosh"}, {"t": 0.3, "type": "ding"}]
- res = P.align_sfx(sfx, ev)
- assert sfx[0]["on"]["type"] == "huazi_in" and sfx[1]["on"]["type"] == "sticker_in" and sfx[2]["on"]["type"] == "cut"
- assert "on" not in sfx[3]
- assert res["events_with_sfx"]["huazi_in"] == {"with_sfx": 1, "total": 1}
- assert res["events_with_sfx"]["sticker_out"] == {"with_sfx": 0, "total": 1}
-
-
-def _sub(i, t0, t1, text, lane=2):
- return {"id": f"text_{i:03d}", "kind": "subtitle", "kind_zh": "字幕", "text": text, "t0": t0, "t1": t1, "lane": lane}
-
-
-def test_speech_anchors_and_persistent_layers():
- lines = [_sub(1, 0.0, 1.8, "这俩口红有啥区别"), _sub(2, 1.8, 3.8, "现在双11全场五折"), _sub(3, 4.0, 5.5, "给你安排上"),
- _sub(4, 6.0, 7.0, "错过就没有了")]
- filing = [_sub(10 + k, t, t + 1.5, "粤G妆网备字2026", lane=6) for k, t in enumerate((0.0, 3.0, 6.0))] # one text repeated
- cues = lines + filing + [
- {"id": "text_020", "kind": "huazi", "kind_zh": "花字", "text": "五折", "t0": 3.2, "t1": 3.6}, # repeats a word of line 2
- {"id": "text_021", "kind": "huazi", "kind_zh": "花字", "text": "冲!", "t0": 5.7, "t1": 6.2}, # just after line 3
- {"id": "text_022", "kind": "label", "kind_zh": "文字标注", "text": "8uXrH", "t0": 2.0, "t1": 2.3}, # picture text: no shared word
- {"id": "text_023", "kind": "label", "kind_zh": "文字标注", "text": "使用效果因人而异", "t0": 0.0, "t1": 7.0}, # disclaimer across cuts
- {"id": "text_024", "kind": "label", "kind_zh": "文字标注", "text": "Q8xZ", "t0": 1.0, "t1": 6.5}] # noise seen once
- stickers = [{"id": "sticker_01", "kind": "static_sticker", "kind_zh": "静态贴纸", "t0": 4.1, "t1": 4.9, "confidence": "medium"}]
- cuts = [2.0, 4.0, 6.0]
- assert [c["id"] for c in P.speech_lines(cues)] == ["text_001", "text_002", "text_003", "text_004"]
- P.anchor_layers(cues, stickers, cuts)
- by = {c["id"]: c for c in cues}
- assert by["text_020"]["anchor"]["line"] == "text_002" and by["text_020"]["anchor"]["word"] == "五折"
- assert by["text_021"]["anchor"] == {"line": "text_003", "text": "给你安排上", "rel": "after", "dt": 0.2, "word": None}
- assert stickers[0]["anchor"]["line"] == "text_003" and stickers[0]["anchor"]["rel"] == "during"
- assert "anchor" not in by["text_022"] and "anchor" not in by["text_023"]
- assert by["text_023"]["persistent"] == {"cuts": 3} and "persistent" not in by["text_024"]
- lines_out = P.summary_lines({"text_cues": [c for c in cues if c["kind"] != "subtitle"], "stickers": stickers})
- assert any("按台词定位 3 处" in l for l in lines_out)
- assert any(l.startswith("常驻图层 1 个") and "使用效果因人而异" in l for l in lines_out)
- P.anchor_layers(cues, [], []) # a re-run drops stale marks
- assert not any(c.get("persistent") for c in cues)
-
-
-def test_overlays_at_skips_picture_text():
- pack = {"text_cues": [{"kind": "subtitle", "kind_zh": "字幕", "t0": 0.0, "t1": 2.0},
- {"kind": "label", "kind_zh": "文字标注", "t0": 0.0, "t1": 2.0, "part_of_picture": True}],
- "stickers": [{"t0": 1.0, "t1": 3.0, "confidence": "low"}]}
- assert P.overlays_at(pack, 0.0, 0.15) == ["字幕"]
- assert P.overlays_at(pack, 2.5, 2.6) == [] and P.overlays_at(None, 0, 1) == []
-
-
-def test_ass_export():
- cues = [{"kind": "subtitle", "text": "a/b", "t0": 1.0, "t1": 2.5, "bbox": [0.2, 0.8, 0.6, 0.08], "line_h": 0.035, "angle": 0.0,
- "style": {"fill": "#ffffff", "stroke": "#000000", "stroke_ratio": 0.05}, "anim_in": {"kind": "pop"}},
- {"kind": "scene", "text": "x", "t0": 0, "t1": 1, "bbox": [0, 0, 0.1, 0.1], "line_h": 0.02, "angle": 0.0, "style": {}}]
- ass = P.to_ass(cues, 1080, 1920)
- assert "Dialogue: 0,0:00:01.00,0:00:02.50" in ass and "a\\Nb" in ass and "\\fscx60" in ass
- assert ass.count("Dialogue:") == 1 # scene text is not exported
- side = [{"kind": "label", "text": "效果因人而异", "t0": 0, "t1": 3, "bbox": [0.01, 0.8, 0.026, 0.08], "line_h": 0.08, "angle": 0.0, "style": {}},
- {"kind": "huazi", "text": "双十一福利五折", "t0": 0, "t1": 3, "bbox": [0.3, 0.5, 0.4, 0.05], "line_h": 0.08, "angle": 0.0, "style": {}}]
- ass = P.to_ass(side, 720, 1280)
- assert "效\\N果\\N因" in ass # a narrow tall box is vertical text
- sizes = [int(l.split(",")[2]) for l in ass.splitlines() if l.startswith("Style:")]
- assert sizes[0] <= 19 and sizes[1] * 7 <= 0.4 * 720 * 1.06 # each fits its measured box
-
-
-def test_clean_region():
- st = [{"bbox": [0.6, 0.1, 0.3, 0.15], "t0": 1.0, "t1": 3.0, "confidence": "medium", "appears_mid_shot": True}]
- x, y, w, h = P.clean_region(st, 1.0, 3.0)
- assert w * h >= 0.45 and (x + w <= 0.6 + 1e-6 or y >= 0.25 - 1e-6) # the band avoids the sticker
- assert P.clean_region(st, 5.0, 8.0) is None # not on this shot
- assert P.clean_region([dict(st[0], confidence="low")], 1.0, 3.0) is None # unconfirmed: leave the shot alone
- # only survived a cut (no pop-in, no loop): may be content both shots share, keep the full frame
- cut_only = dict(st[0], appears_mid_shot=False, crosses_cut=True, looping=False)
- assert P.clean_region([cut_only], 1.0, 3.0) is None
- assert P.clean_region([dict(cut_only, looping=True)], 1.0, 3.0) is not None # a looping GIF is a pasted layer
-
-
-def test_review_overrides_stickers_and_kinds():
- pack = {"text_cues": [{"id": "text_001", "kind": "label", "kind_zh": "文字标注", "text": "WOW", "t0": 1, "t1": 2}],
- "stickers": [{"id": "sticker_01", "kind": "static_sticker", "kind_zh": "静态贴纸/图片", "t0": 1, "t1": 2,
- "bbox": [0.1, 0.1, 0.2, 0.2], "confidence": "low"},
- {"id": "sticker_02", "kind": "animated_sticker", "kind_zh": "动态贴纸/GIF", "t0": 3, "t1": 4,
- "bbox": [0.5, 0.5, 0.2, 0.2], "confidence": "low"}],
- "review": {"by": "claude", "text": {"text_001": "huazi"},
- "stickers": {"sticker_01": {"is_overlay": False, "what": ""}, "sticker_02": {"is_overlay": True, "what": "猫猫表情包"}},
- "missed": [{"t0": 6, "t1": 7, "what": "GIF 动图", "where": "右下"}]}}
- P.apply_review(pack)
- assert pack["text_cues"][0]["kind"] == "huazi"
- s1, s2, s3 = pack["stickers"]
- assert s1["in_picture"] and s2["confidence"] == "confirmed" and s2["what"] == "猫猫表情包"
- assert s3["source"] == "agent" and s3["kind"] == "animated_sticker"
- rec = {"start": 0.0, "end": 8.0}
- kinds = [l["kind"] for l in P.shot_layers(pack, rec, "cg_3d")]
- # confirmed stickers stay even on a 3D picture; the rejected one is gone
- assert kinds.count("animated_sticker") == 2 and "static_sticker" not in kinds and "huazi" in kinds
-
-
-def test_pipeline_writes_packaging(tmp_path, media):
- from rea_video.pipeline import decompose
-
- b = decompose(media["edit"], tmp_path / "edit", use_vlm=False, ocr=False, stems=False, memory=False)
- pk = b["packaging"]
- assert pk["version"] >= 1 and (tmp_path / "edit" / pk["files"]["timeline"]).is_file()
- # the code-render card sliding in is the picture's own content, not a sticker
- assert not [s for s in pk["stickers"] if not s.get("in_picture")]
- md = (tmp_path / "edit" / "report.md").read_text(encoding="utf-8")
- assert "剪辑包装层" in md
-
-
-def test_numbered_labels_split_per_shot():
- """SHOT 01 … SHOT 03 at one place: three labels (not one cue spanning the video), and not a subtitle lane."""
- from rea_video.packaging import build_cues, classify_cues
-
- items = []
- for k in range(30):
- t = k * 0.5
- n = 1 + int(t // 5)
- text = f"SHOT 0{n}" if k != 4 else "SHOT 07" # one frame misread stays inside its run
- items.append({"t": t, "text": text, "conf": 0.95, "bbox": [0.4, 0.48, 0.2, 0.03], "angle": 0.0, "style": None})
- cues = build_cues(items, 0.5)
- assert [c["text"] for c in cues] == ["SHOT 01", "SHOT 02", "SHOT 03"]
- assert cues[1]["t0"] == 5.0
- for c in cues:
- c.update(style={}, t1=c["t1"])
- classify_cues(cues, 15.0)
- assert all(c["kind"] == "label" for c in cues)
-
-
-def test_page_text_in_a_screenshot_is_not_a_subtitle():
- """Words of a page at one height (tabs, a file list) change like a subtitle track but sit among other lines of
- the same size and are scattered left to right; the caption band under the screenshot stays a subtitle."""
- from rea_video.packaging import classify_cues
-
- def cue(i, t0, t1, x, y, w, text, h=0.025):
- return {"id": f"t{i}", "t0": t0, "t1": t1, "bbox": [x, y, w, h], "line_h": h, "angle": 0.0, "drift": 0.0,
- "samples": 3, "text": text, "style": {}}
-
- cues, i = [], 0
- captions = ["这条才发二十一分钟", "就被判九成扑街", "封面顺序反了", "带钩子那张埋在第三张", "先别删拿它查查"]
- words = ["docs", "Code", "main", "Pull requests", "README"]
- for k in range(5):
- t0, t1 = 2.0 * k, 2.0 * k + 1.6
- cues.append(cue(i := i + 1, t0, t1, 0.5 - 0.04 * len(captions[k]) / 2, 0.875, 0.04 * len(captions[k]), captions[k], 0.033))
- # one page word on the lane at y≈0.40, at a different place each time, with the page's other lines around it
- cues.append(cue(i := i + 1, t0, t1, [0.1, 0.9, 0.1, 0.6, 0.3][k], 0.39, 0.08, words[k]))
- for j, dy in enumerate((-0.06, -0.03, 0.03, 0.06)):
- cues.append(cue(i := i + 1, t0, t1, 0.05, 0.39 + dy, 0.5, f"2 weeks ago {k}{j}"))
- classify_cues(cues, 10.0)
- kinds = {c["text"]: c["kind"] for c in cues}
- assert all(kinds[t] == "subtitle" for t in captions)
- assert all(kinds[t] == "scene" for t in words)
-
-
-def test_counter_ticking_every_frame_stays_one_cue():
- from rea_video.packaging import build_cues
-
- items = [{"t": k * 0.5, "text": f"第{k}名", "conf": 0.9, "bbox": [0.4, 0.1, 0.2, 0.03], "angle": 0.0, "style": None}
- for k in range(10)]
- assert len(build_cues(items, 0.5)) == 1
-
-
-def test_low_confidence_sfx_are_counted_as_possible():
- from rea_video.packaging import align_sfx
-
- events = [{"t": 1.0, "type": "text_in", "what": "A", "ref": "text_001"}, {"t": 2.0, "type": "text_in", "what": "B", "ref": "text_002"}]
- al = align_sfx([{"t": 1.02, "source": "vlm"}, {"t": 2.01, "source": "deterministic_anchored", "confidence": "low"}], events)
- assert al["sfx_on"] == {"text_in": 1} and al["sfx_on_possible"] == {"text_in": 1}
-
-
-def test_settle_cues_draws_each_text_once():
- def cue(text, t0, t1, box):
- return {"kind": "label", "text": text, "t0": t0, "t1": t1, "bbox": box, "line_h": 0.04, "angle": 0.0, "style": {}}
- block = [0.40, 0.66, 0.20, 0.13]
- cues = [cue("第一站胃/STOMACH·胃酸很强", 1.0, 3.0, block), # the block read whole
- cue("STOMACH·胃酸很强", 0.5, 5.0, [0.40, 0.71, 0.20, 0.04]), # and one of its lines on its own
- cue("第一站胃", 6.0, 7.0, [0.45, 0.66, 0.08, 0.04]),
- cue("肠壁上长满了绒毛", 10.0, 13.1, [0.38, 0.84, 0.24, 0.06]), # a line handing over to the next in place
- cue("药物从这里钻进血管", 13.0, 16.0, [0.37, 0.84, 0.27, 0.06]),
- cue("SMALL INTESTINE", 10.0, 16.0, [0.39, 0.70, 0.21, 0.04])] # a label above them stays
- got = [(c["text"], c["t0"], c["t1"]) for c in P.settle_cues(cues)]
- assert ("第一站胃/STOMACH·胃酸很强", 1.0, 3.0) in got
- assert ("STOMACH·胃酸很强", 0.5, 1.0) in got and ("STOMACH·胃酸很强", 3.0, 5.0) in got # gives way while the block shows
- assert ("第一站胃", 6.0, 7.0) in got # not on screen with the block: untouched
- assert ("肠壁上长满了绒毛", 10.0, 13.0) in got and ("药物从这里钻进血管", 13.0, 16.0) in got
- assert ("SMALL INTESTINE", 10.0, 16.0) in got
- assert P.to_ass(cues, 960, 544).count("Dialogue:") == len(got)
diff --git a/tests/test_particles.py b/tests/test_particles.py
deleted file mode 100644
index 6d3c89c..0000000
--- a/tests/test_particles.py
+++ /dev/null
@@ -1,89 +0,0 @@
-"""Particle / point-cloud graphics on black: rendered by code, not 3D, AI or night footage."""
-import cv2
-import numpy as np
-
-from rea_video.classify import deterministic
-from rea_video.features import spatial_features
-from rea_video.plan import code_scene
-from rea_video.production import lit_colours, report_md
-
-
-def _particles(seed=0):
- rng = np.random.default_rng(seed)
- img = np.zeros((270, 480, 3), np.uint8)
- for _ in range(1500): # glowing dots sampled on an ellipse, like a particle organ
- a = rng.uniform(0, 2 * np.pi)
- r = rng.uniform(0, 1) ** 0.5
- x, y = int(240 + 90 * r * np.cos(a)), int(135 + 60 * r * np.sin(a))
- cv2.circle(img, (x, y), 1, (230, 220, 60), -1)
- return img
-
-
-def _shaded():
- img = np.zeros((270, 480, 3), np.uint8)
- yy, xx = np.mgrid[0:270, 0:480]
- d = np.sqrt((xx - 240) ** 2 + (yy - 135) ** 2)
- ball = np.clip(255 * (1 - d / 90), 0, 255).astype(np.uint8) # a smoothly shaded sphere on black
- img[..., 1] = ball
- img[..., 2] = ball
- return img
-
-
-def _feat(img):
- f = spatial_features(img)
- f.update({"dup_ratio": 0.0, "moving_pair_ratio": 1.0, "camera": "smooth_move", "temporal_noise": 0.5, "zero_pixel_ratio": 0.6})
- return f
-
-
-def test_fine_dark_separates_particles_from_shaded_surfaces():
- fp, fs = _feat(_particles()), _feat(_shaded())
- assert fp["lit_smooth"] < 0.3 and fp["lit_peaks"] > 4
- assert fs["lit_smooth"] > 0.5
- probs, ev, facts = deterministic(fp)
- assert facts["fine_dark"] > 0.5
- assert max(probs, key=probs.get) == "code_render"
- assert any("粒子" in e for e in ev)
- _, _, facts_s = deterministic(fs)
- assert facts_s["fine_dark"] < 0.1
-
-
-def test_code_scene_and_report_table(tmp_path):
- cv2.imwrite(str(tmp_path / "a.jpg"), _particles())
- assert lit_colours([tmp_path / "a.jpg"])[0] in ("青", "白")
- shot = {"deterministic": {"facts": {"fine_dark": 0.9}}, "features": {"camera": "smooth_move", "zoom_per_s": 0.05},
- "review": {"description": "青色粒子拼成的胶囊"},
- "text": {"tracks": [{"kind": "subtitle", "texts": ["字幕"]}, {"kind": "title", "texts": ["第一站·胃", "ECOPSWOE"]}],
- "items": [{"text": "第一站·胃", "conf": 0.99}, {"text": "ECOPSWOE", "conf": 0.55}, {"text": "字幕", "conf": 0.99}]}}
- sc = code_scene(shot)
- assert sc["particles"] and sc["picture"] == "青色粒子拼成的胶囊"
- assert sc["on_screen_text"] == ["第一站·胃"] # subtitles and low-confidence OCR are left out
- assert "推近" in sc["move"]
- plan = {"summary": "x", "units": [], "shoot": [], "local": [], "avatar": [],
- "code": [{"id": "段1", "shots": [1], "start": 0, "end": 3, "screen_capture": [],
- "scenes": [{"shot": 1, "start": 0.0, "end": 3.0, **sc, "colours": ["青"]}]}]}
- md = "\n".join(report_md(plan))
- assert "Three.js" in md and "| #1 | 0.0–3.0s | 粒子/点云 | 青色粒子拼成的胶囊 |" in md
-
-
-def _halo(img, colour=(140, 120, 40), radius=150):
- """Lay a large soft glow behind the picture."""
- yy, xx = np.mgrid[0:img.shape[0], 0:img.shape[1]]
- g = np.exp(-((xx - 240) ** 2 + (yy - 135) ** 2) / (2 * (radius / 2) ** 2))
- return np.clip(img.astype(np.float32) + g[..., None] * np.array(colour, np.float32), 0, 255).astype(np.uint8)
-
-
-def test_a_smooth_background_does_not_hide_fine_graphics():
- f = _feat(_halo(_particles()))
- assert f["lit_smooth"] > 0.3 # on the plain picture the glow makes the lit part look shaded
- assert f["detail_smooth"] < 0.3 and f["detail_peaks"] > 4 # the same bounds hold once the glow is taken out
- probs, ev, facts = deterministic(f)
- assert facts["fine_dark"] > 0.5 and max(probs, key=probs.get) == "code_render"
- assert any("平滑背景" in e for e in ev)
- _, _, facts_s = deterministic(_feat(_halo(_shaded()))) # a shaded ball on a glow stays a shaded surface
- assert facts_s["fine_dark"] < 0.1
- # big soft lights on a glow (night street, bokeh) are not fine graphics
- img = np.zeros((270, 480, 3), np.uint8)
- for x, y in [(100, 80), (220, 150), (330, 100), (400, 200)]:
- cv2.circle(img, (x, y), 14, (200, 210, 230), -1)
- _, _, facts_l = deterministic(_feat(_halo(cv2.GaussianBlur(img, (0, 0), 3))))
- assert facts_l["fine_dark"] < 0.5
diff --git a/tests/test_performance.py b/tests/test_performance.py
deleted file mode 100644
index 2787364..0000000
--- a/tests/test_performance.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""Acting and emotion: what readers report per shot, and how it reaches the remake prompts, the script and the report."""
-import json
-
-from rea_video import performance
-from rea_video.i18n import set_lang
-from rea_video.plan import with_acting
-from rea_video.production import production_plan
-from rea_video.review import _clean
-from rea_video.vlm import SHOT_PROMPT, normalize_shot_result
-
-from tests.test_production import KITCHEN, _b, _shot
-
-ACT = {"who": "A", "emotion": "委屈", "intensity": "low", "face": "眼眶微红,嘴角轻轻下压", "body": "低头,手指绞着衣角",
- "arc": [{"t": 1.5, "state": "抬眼看镜头,下巴微微发抖"}, {"t": "bad", "state": "停顿"}], "voice": "", "key": True}
-
-
-def test_clean_keeps_visible_cues_and_drops_empty_answers():
- p = performance.clean(ACT)
- assert p["intensity"] == "low" and p["key"] is True
- assert [a["t"] for a in p["arc"]] == [0.0, 1.5] # a bad time is kept at 0, the list stays in order
- assert performance.clean({"who": "A", "emotion": "", "face": "", "arc": []}) is None
- assert performance.clean("开心") is None
- assert performance.clean({"emotion": "开心", "intensity": "强"})["intensity"] == "high"
-
-
-def test_prompt_line_writes_the_face_not_the_emotion_word():
- set_lang("zh")
- line = performance.prompt_line(performance.clean(ACT))
- assert "眼眶微红" in line and "开头停顿,1.5 秒时抬眼看镜头" in line and "幅度很小" in line
- assert "委屈" not in line # the emotion word stays in the report, not in the prompt
- assert performance.image_line(performance.clean(ACT)) == "表情:停顿" # the face at frame one when the arc starts there
-
-
-def test_with_acting_adds_once():
- act = performance.clean(ACT)
- assert with_acting("她站在窗边。", act).startswith("她站在窗边。表演")
- assert with_acting("她眼眶微红,嘴角轻轻下压,站在窗边", act) == "她眼眶微红,嘴角轻轻下压,站在窗边"
- assert with_acting("", act) == "" and with_acting("她站在窗边", None) == "她站在窗边"
-
-
-def test_route_by_what_carries_the_acting():
- act = performance.clean(ACT)
- assert performance.route_kind(act, "live_action") == "shoot"
- assert performance.route_kind(act, "ai_video") == "first_frame"
- assert performance.route_kind(dict(act, voice="压低声音,句尾带哭腔"), "ai_video") == "voice"
- assert performance.route_kind(dict(act, intensity="high"), "ai_video") == "transfer"
-
-
-def test_review_answer_and_vlm_answer_carry_performance():
- assert '"performance"' in SHOT_PROMPT
- SHOT_PROMPT.format(hints="") # the guide's braces are escaped for str.format
- clean, err = _clean({"label_probs": {"ai_video": 1}, "performance": ACT})
- assert not err and clean["performance"]["face"] == ACT["face"]
- assert normalize_shot_result({"label_probs": {"ai_video": 1}, "performance": "开心"})["performance"] is None
-
-
-def test_generation_unit_prompt_and_report_use_the_acting(tmp_path):
- set_lang("zh")
- shots = [_shot(1, 0.0, 2.0, "ai_video", KITCHEN, tmp_path), _shot(2, 2.0, 2.0, "ai_video", KITCHEN, tmp_path)]
- shots[1]["review"] = {"performance": performance.clean(dict(ACT, voice="压低声音,句尾带哭腔"))}
- b = _b(shots)
- plan = production_plan(b, tmp_path)
- u = plan["units"][0]
- assert "镜头2(2.0–4.0s):镜头 2 的动作。表演(幅度很小,几乎看不出):眼眶微红" in u["prompt"]
- assert u["acting"][0]["shot"] == 2 and u["acting"][0]["how"] == "先配音再驱动"
- b["production_plan"] = plan
- rows, kinds = performance.table(b)
- assert rows[0][0] == "#2" and "委屈(轻) ★看点" == rows[0][2] and kinds == ["voice"]
- from rea_video.entities import script
-
- b["whole_video_vlm"] = {"narration": {"lines": [{"start": 2.2, "end": 3.5, "speaker": "A", "text": "我没有"},
- {"start": 0.2, "end": 1.0, "speaker": "A", "text": "你听我说", "delivery": "急促"}]}}
- assert [ln.get("delivery") for ln in script(b)] == ["压低声音,句尾带哭腔", "急促"]
- json.dumps(plan, ensure_ascii=False)
-
-
-def test_english_prompt_gets_english_acting_only(tmp_path):
- set_lang("zh")
- act = performance.clean(ACT)
- assert act["en"] == "" and performance.prompt_line_en(act) == "" # Chinese cues never go into the English prompt
- assert with_acting("She stands by the window.", act, en=True) == "She stands by the window."
- act_en = performance.clean(dict(ACT, en="eyes slightly red, mouth corners pressed down; at 1.5s she looks up"))
- line = with_acting("She stands by the window", act_en, en=True)
- assert line == "She stands by the window. Acting (very subtle, barely visible): eyes slightly red, mouth corners pressed down; at 1.5s she looks up"
- assert performance.clean(dict(ACT, en="眼眶微红"))["en"] == "" # a non-English "en" is dropped
- english = performance.clean({"face": "brows drawn together", "arc": [{"t": 0.5, "state": "glances away"}], "intensity": "mid"})
- assert performance.prompt_line_en(english) == "Acting (moderate, not exaggerated): brows drawn together; at 0.5s glances away"
- shots = [_shot(1, 0.0, 2.0, "ai_video", KITCHEN, tmp_path), _shot(2, 2.0, 2.0, "ai_video", KITCHEN, tmp_path)]
- shots[1]["review"] = {"performance": act_en}
- u = production_plan(_b(shots), tmp_path)["units"][0]
- assert "Shot 2 (2.0-4.0s): shot 2. Acting (very subtle" in u["prompt_en"] and "眼眶" not in u["prompt_en"]
diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py
deleted file mode 100644
index 85ba09b..0000000
--- a/tests/test_pipeline.py
+++ /dev/null
@@ -1,166 +0,0 @@
-import json
-import subprocess
-import sys
-from pathlib import Path
-
-import pytest
-
-from rea_video.classify import LABELS, deterministic, fuse, top
-from rea_video.integrations.capsule_cinema import build_remake_jobs, export_capsule_analysis
-from rea_video.media import video_info
-from rea_video.pipeline import decompose, finalize
-from rea_video.remake import assemble, overlay_cues, replaced_spans
-from rea_video.shots import build_track, detect_shots
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-def test_capabilities_valid():
- r = subprocess.run([sys.executable, str(ROOT / "scripts/validate_capabilities.py")], capture_output=True, text=True)
- assert r.returncode == 0, r.stdout + r.stderr
-
-
-def test_shot_boundaries(media):
- info = video_info(media["edit"])
- shots = detect_shots(build_track(str(media["edit"]), info))
- starts = [round(s.start, 2) for s in shots[1:]]
- assert len(shots) == 3, starts
- assert abs(starts[0] - 2.0) < 0.07 and abs(starts[1] - 5.0) < 0.07
-
-
[email protected](scope="module")
-def breakdown(media, tmp_path_factory):
- out = tmp_path_factory.mktemp("out") / "edit"
- return decompose(media["edit"], out, use_vlm=False, ocr=False, stems=False), out
-
-
-def test_labels(breakdown):
- b, _ = breakdown
- labels = [s["base"]["label"] for s in b["shots"]]
- assert labels == ["static_hold", "still_motion", "code_render"], labels
-
-
-def test_kenburns_measured(breakdown):
- b, _ = breakdown
- km = b["shots"][1]["features"]
- assert 0.025 < km["zoom_per_s"] < 0.06, km["zoom_per_s"]
- assert km["camera"] == "planar_zoom_pan"
-
-
-def test_outputs_and_schema(breakdown):
- b, out = breakdown
- for name in ("breakdown.json", "report.md", "report.html", "storyboard.jpg"):
- assert (out / name).is_file(), name
- assert b["schema"] == "rea_video.breakdown.v1"
- assert abs(sum(m["ratio"] for m in b["summary"]["production_mix"]) - 1.0) < 0.01
- for s in b["shots"]:
- assert set(s["base"]["probs"]) == set(LABELS)
- assert s["replication"]["rule"].startswith("R")
-
-
-def test_finalize_idempotent(breakdown):
- b, out = breakdown
- again = finalize(json.loads((out / "breakdown.json").read_text()), out)
- assert [s["base"]["label"] for s in again["shots"]] == [s["base"]["label"] for s in b["shots"]]
-
-
-def test_fuse_respects_frozen():
- det = {k: 0.0 for k in LABELS} | {"static_hold": 0.9, "code_render": 0.1}
- vlm = {k: 0.0 for k in LABELS} | {"ai_video": 0.9, "static_hold": 0.1}
- lab, _ = top(fuse(det, vlm, "frozen"))
- assert lab == "static_hold"
-
-
-def test_vlm_can_override_camera_like():
- f = {"noise_sigma": 0.5, "temporal_noise": 0.8, "flat_ratio": 0.05, "palette95": 200, "axis_edge_ratio": 0.2,
- "dup_ratio": 0.0, "zero_pixel_ratio": 0.5, "camera": "smooth_move", "kenburns_score": 0.0, "moving_pair_ratio": 0.9}
- det, _, facts = deterministic(f)
- vlm = {k: 0.0 for k in LABELS} | {"live_action": 0.95, "ai_video": 0.05}
- assert top(fuse(det, vlm, facts["temporal_family"]))[0] == "live_action"
-
-
-def test_capsule_export(breakdown, tmp_path):
- b, _ = breakdown
- p = export_capsule_analysis(b, tmp_path / "capsule_analysis.json")
- data = json.loads(p.read_text())
- for key in ("summary", "source_profile", "segments", "capsule_recipe", "execution_strategy", "content_scope"):
- assert key in data
- cs = data["content_scope"]
- assert cs["schema_version"] == "capsule.content_scope.v1" and cs["series_fixed"] and cs["episode_variable"]
- assert data["execution_strategy"]["mode"] == "review_required"
-
-
-def test_remake_jobs_and_assemble(breakdown, tmp_path):
- b, out = breakdown
- jobs_path = build_remake_jobs(b, out, capsule_root=tmp_path / "capsule", engine="seedance2.0")
- jobs = json.loads(jobs_path.read_text())["jobs"]
- execs = [j["executor"] for j in jobs]
- assert execs == ["local_ffmpeg", "local_ffmpeg", "keep_original"], execs
- results = jobs_path.with_name("results.json")
- results.write_text(json.dumps({"results": {}}))
- res = json.loads(assemble(out / "breakdown.json", results, overlays=True))
- assert Path(res["remake"]).is_file() and Path(res["compare"]).is_file()
- assert res["overlays"]["text"] == 0 # OCR off in this fixture: nothing to lay on, and nothing breaks
- info = video_info(res["remake"])
- assert abs(info.duration - b["source"]["duration"]) < 0.2
-
-
-def test_overlays_follow_replaced_shots_only():
- b = {"shots": [{"index": 1, "start": 0.0, "end": 2.0}, {"index": 2, "start": 2.0, "end": 5.0}, {"index": 3, "start": 5.0, "end": 6.0}],
- "packaging": {"text_cues": [
- {"kind": "subtitle", "text": "跨两镜", "t0": 1.0, "t1": 3.0, "anim_in": {"kind": "pop"}},
- {"kind": "huazi", "text": "WOW", "t0": 2.5, "t1": 3.5, "anim_in": {"kind": "pop"}},
- {"kind": "label", "text": "界面字", "t0": 2.5, "t1": 3.0, "part_of_picture": True},
- {"kind": "subtitle", "text": "原片里", "t0": 5.2, "t1": 5.8}],
- "stickers": [{"id": "sticker_01", "t0": 3.0, "t1": 4.0, "confidence": "medium"}]}}
- spans = replaced_spans(b, [(1, "original"), (2, "generated"), (3, "original")])
- assert spans == [(2.0, 5.0)]
- cues, stickers = overlay_cues(b, spans)
- assert [(c["text"], c["t0"], c["t1"]) for c in cues] == [("跨两镜", 2.0, 3.0), ("WOW", 2.5, 3.5)]
- assert cues[0]["anim_in"] is None and cues[1]["anim_in"] == {"kind": "pop"} # a clipped line does not pop in again
- assert [s["id"] for s in stickers] == ["sticker_01"]
- assert replaced_spans(b, [(1, "generated"), (2, "local_still"), (3, "original")]) == [(0.0, 5.0)]
-
-
-def test_english_report_has_no_chinese(media, tmp_path):
- import re
-
- from rea_video.i18n import set_lang
-
- try:
- b = decompose(media["edit"], tmp_path / "en", use_vlm=False, ocr=False, stems=False, lang="en")
- assert b["lang"] == "en"
- assert b["shots"][0]["base"]["label_zh"] == "static hold"
- cjk = re.compile(r"[一-鿿]")
- for name in ("report.md", "report.html"):
- bad = [l for l in (tmp_path / "en" / name).read_text().splitlines() if cjk.search(l)]
- assert not bad, f"{name} still has Chinese lines:\n" + "\n".join(bad[:20])
- # the same breakdown rendered again in Chinese
- b["lang"] = "zh"
- again = finalize(b, tmp_path / "en")
- assert again["shots"][0]["base"]["label_zh"] == "静帧停留"
- finally:
- set_lang("zh")
-
-
-def test_remake_does_every_shot_it_can_and_says_what_is_left(breakdown, tmp_path):
- from rea_video.remake import remake
-
- b, out = breakdown
- res = remake(out)
- st = json.loads((out / "remake" / "status.json").read_text())
- assert [r["now"] for r in st["shots"]] == ["local_still", "local_still", "code"], st
- assert res["replaced_share"] == 1.0 and res["to_do"] == [] and (out / "code" / "spec.json").is_file()
- assert Path(res["remake"]).is_file() and "代码重画" in (out / "remake" / "status.md").read_text()
- # a clip handed in for a shot is cut in on the next run
- clip = out / "remake" / "segments" / "shot_002.mp4"
- (out / "remake" / "mine.json").write_text(json.dumps({"results": {"1": {"video": str(clip)}}}))
- remake(out, code=False)
- now = [r["now"] for r in json.loads((out / "remake" / "status.json").read_text())["shots"]]
- assert now[0] == "generated" and now[2] == "code" # the earlier code render is reused
-
-
-def test_video_md_names_the_next_commands(breakdown):
- b, out = breakdown
- text = (out / "VIDEO.md").read_text(encoding="utf-8")
- assert "rea-video remake" in text and "code-remake" in text
diff --git a/tests/test_playbook.py b/tests/test_playbook.py
deleted file mode 100644
index c516042..0000000
--- a/tests/test_playbook.py
+++ /dev/null
@@ -1,75 +0,0 @@
-"""Video type and the hands-on remake steps, on hand-made breakdowns (no media needed)."""
-from __future__ import annotations
-
-import pytest
-
-from rea_video import playbook
-from rea_video.i18n import set_lang
-
-
-def _b(mix: dict[str, float], fmt: str = "", sound: str = "", avg: float = 2.5, shots: int = 8, voice: float = 0.0,
- beat: bool = False, music: bool = True, subs: int = 0, chars: list | None = None, refs: list | None = None) -> dict:
- return {
- "summary": {"production_mix": [{"label": k, "ratio": v} for k, v in mix.items()], "avg_shot_s": avg, "shots": shots},
- "source": {"width": 1080, "height": 1920, "aspect_ratio": "9:16", "duration": shots * avg},
- "aspects": {"format": {"result": {"format": fmt}}} if fmt else {},
- "sound_sources": {"format_context": {"video_type": sound}},
- "audio": {"voice": {"present": voice > 0, "ratio": voice}, "music": {"present": music, "tempo_bpm": 120.0}, "beat_synced_edit": beat},
- "packaging": {"text_cues": [{"kind": "subtitle"}] * subs, "files": {"srt": "packaging/subtitles.srt"}},
- "production_plan": {"calls": 3, "model_name": "Seedance 2.0", "units": [{}, {}, {}]},
- "review_cast": {"characters": chars or []} if chars else {},
- "shots": [{"index": 1, "start": 0.0, "end": avg, "duration": avg, "material": {"references": refs or []}}],
- }
-
-
[email protected]("b,want", [
- (_b({"live_action": 1.0}, fmt="talking_head", voice=0.8), "talking_head"),
- (_b({"live_action": 1.0}, fmt="desk"), "desk"),
- (_b({"live_action": 1.0}, fmt="vlog"), "vlog"),
- (_b({"ai_video": 1.0}, sound="music_mv"), "ai_mv"),
- (_b({"ai_video": 1.0}, refs=[{"kind": "product_photo"}]), "ai_product"),
- (_b({"ai_video": 1.0}, shots=20, voice=0.5), "ai_drama"),
- (_b({"ai_video": 1.0}, shots=5), "ai_clip"),
- (_b({"cg_3d": 1.0}), "animation"),
- (_b({"avatar": 1.0}), "avatar"),
- (_b({"code_render": 1.0}), "explainer"),
- (_b({"screen_capture": 1.0}), "screen"),
- (_b({"still_motion": 0.7, "static_hold": 0.3}), "slideshow"),
- (_b({"film_footage": 1.0}), "film"),
- (_b({"live_action": 1.0}, fmt="vlog", avg=0.9, shots=40), "beat"),
-])
-def test_type(b, want):
- assert playbook.kinds(b)[0][0] == want
-
-
-def test_second_type_listed_when_it_covers_a_quarter():
- ks = playbook.kinds(_b({"live_action": 0.7, "code_render": 0.3}, fmt="talking_head", voice=0.6))
- assert [k for k, _ in ks] == ["talking_head", "explainer"]
- assert len(playbook.kinds(_b({"live_action": 0.85, "code_render": 0.15}, fmt="talking_head", voice=0.6))) == 1
-
-
[email protected]("lang", ["zh", "en"])
[email protected]("kind", ["talking_head", "desk", "vlog", "live_drama", "ai_drama", "ai_product", "ai_mv", "avatar",
- "ai_clip", "animation", "film", "explainer", "screen", "slideshow", "beat"])
-def test_every_kind_renders_steps(kind, lang):
- set_lang(lang)
- try:
- lines = playbook.steps(_b({"ai_video": 1.0}, voice=0.5, subs=3), kind)
- assert lines and all("{" not in x for x in lines)
- assert "rea-video remake" in lines[-1]
- finally:
- set_lang("zh")
-
-
-def test_steps_only_carry_what_was_measured():
- set_lang("zh")
- b = _b({"live_action": 1.0}, fmt="talking_head", voice=0.8, shots=1, avg=16.0, subs=5)
- b["aspects"]["lighting"] = {"lines": ["打光:正面柔光(平光)。色温中性(约 5000K)"]}
- b["aspects"]["editing"] = {"lines": ["剪辑:每分钟 0.0 刀,实拍镜头平均 16.0s;机位/场景 1 个;同机位跳切 0 处、推近切 0 处"]}
- b["shooting_plan"] = {"gear": ["环形灯放在手机正后方略高处"]}
- md = "\n".join(playbook.md(b))
- assert "人物口播" in md and "subtitles.srt" in md and "一镜到底" in md
- assert "约 5000K" in md and "环形灯放在手机正后方略高处" in md
- assert "0 处" not in md and "机位/场景 1 个" not in md
- no_subs = "\n".join(playbook.md(_b({"live_action": 1.0}, fmt="talking_head", voice=0.8)))
- assert "subtitles.srt" not in no_subs and "布光" not in no_subs # nothing measured, no step
diff --git a/tests/test_production.py b/tests/test_production.py
deleted file mode 100644
index 401e86d..0000000
--- a/tests/test_production.py
+++ /dev/null
@@ -1,204 +0,0 @@
-"""Production plan: AI shots grouped into generation units, filmed shots into shooting setups."""
-import re
-from pathlib import Path
-
-import cv2
-import numpy as np
-
-from rea_video.i18n import set_lang
-from rea_video.plan import Planner
-from rea_video.production import _limits, _split_run, pick_model, production_plan
-
-KITCHEN = (40, 90, 160)
-STUDIO = (200, 60, 30)
-
-
-def _shot(i, start, dur, label, color, out: Path, trans="cut", product=False, prompt=None, size="中景"):
- for k in ("first", "last"):
- img = np.full((160, 90, 3), color, np.uint8)
- cv2.circle(img, (45, 80), 20 + 5 * (k == "last"), (255, 255, 255), -1)
- cv2.imwrite(str(out / f"s{i}_{k}.jpg"), img)
- items = [{"kind": "product_photo", "real_material": True}] if product else []
- return {"index": i, "id": f"shot_{i:03d}", "start": start, "end": start + dur, "duration": dur, "transition_in": trans,
- "assets": {"first_frame": f"s{i}_first.jpg", "last_frame": f"s{i}_last.jpg"},
- "base": {"label": label, "label_zh": label}, "material": {"items": items}, "faces": 0.0,
- "vlm": {"replication": {"video_prompt": prompt or f"镜头 {i} 的动作", "video_prompt_en": f"shot {i}"}},
- "aspects": {"framing": {"result": {"shot_size": size}}, "camera": {"result": {"support_zh": "手持"}}}}
-
-
-def _b(shots):
- return {"shots": shots, "source": {"aspect_ratio": "9:16"}, "audio": {"voice": {"present": True}}}
-
-
-def test_named_model_is_planned_for():
- # a model the map knows is planned for as named, shot by shot when it cannot do multi-shot
- eng, model = pick_model(Planner(), "luma-ray3.2")
- assert eng["id"] == model["id"] == "luma-ray3.2" and "video.multi_shot" not in model["primitives"]
- # Seedance 2.0 writes several shots in one call (numbered shots in the prompt)
- eng, model = pick_model(Planner(), "seedance2.0")
- assert eng["id"] == model["id"] == "seedance-2.0"
- # a name the map does not have falls back to a multi-shot model
- eng, model = pick_model(Planner(), "no-such-model")
- assert eng is None and "video.multi_shot" in model["primitives"]
-
-
-def test_plan_carries_the_models_prompt_notes(tmp_path):
- from rea_video.production import report_md
-
- shots = [_shot(1, 0.0, 3.0, "ai_video", KITCHEN, tmp_path), _shot(2, 3.0, 3.0, "ai_video", KITCHEN, tmp_path)]
- plan = production_plan(_b(shots), tmp_path, engine="hailuo-2.3")
- assert plan["model"] == "hailuo-2.3" and [u["shots"] for u in plan["units"]] == [[1], [2]] # no multi-shot: one call per shot
- assert "[Push in]" in plan["prompting"]["camera"]
- plan["summary"] = ""
- assert "[Push in]" in "\n".join(report_md(plan))
- every = Planner()
- assert set(every.prompting) <= set(every.models) and every.keyframe_notes
-
-
-def test_split_respects_hardcut_cap():
- lim = {"max": 30.0, "multi_shot": True}
- hard = {"prefer": 8, "max": 10}
- run = [{"duration": d} for d in (1.8, 1.0, 0.9, 2.5, 2.8, 5.5, 4.3, 2.2)]
- units = _split_run(run, lim, hard, 4.0)
- assert all(sum(r["duration"] for r in u) <= 10 for u in units if len(u) > 1)
- assert len(units) == 3
- assert [len(u) for u in _split_run(run, {"max": 15.0, "multi_shot": False}, hard, 4.0)] == [1] * 8
-
-
-def test_units_scene_product_and_continuity(tmp_path):
- shots = [_shot(1, 0.0, 2.0, "ai_video", KITCHEN, tmp_path, product=True),
- _shot(2, 2.0, 2.0, "ai_video", KITCHEN, tmp_path),
- _shot(3, 4.0, 3.0, "ai_video", KITCHEN, tmp_path),
- _shot(4, 7.0, 3.0, "ai_video", STUDIO, tmp_path), # new scene -> new unit
- _shot(5, 10.0, 2.0, "ai_video", STUDIO, tmp_path, trans="dissolve"), # transition -> new unit
- _shot(6, 12.0, 40.0, "ai_video", STUDIO, tmp_path)] # longer than the model allows
- plan = production_plan(_b(shots), tmp_path)
- units = plan["units"]
- assert [u["shots"] for u in units] == [[1, 2, 3], [4], [5], [6]]
- assert units[0]["mode"] == "multi_shot" and "镜头2(2.0–4.0s)" in units[0]["prompt"]
- assert all(any(r["tag"] == "@图片1" for r in u["refs"]) for u in units) # product referenced everywhere
- assert units[1]["continuity"].startswith("首帧:") # scene changed: no tail-frame hand-over
- assert units[2]["continuity"].startswith("首帧:") # dissolve: own unit, not a continuation
- assert units[3]["mode"] == "split" and units[3]["calls"] == 3
- assert plan["calls"] == 6 and not plan.get("engine_note") # Seedance 2.0: 15 s per call, so the 40 s shot takes 3 calls
-
-
-def test_shooting_setups_group_non_adjacent(tmp_path):
- shots = [_shot(1, 0.0, 2.0, "live_action", KITCHEN, tmp_path, size="中景"),
- _shot(2, 2.0, 2.0, "live_action", STUDIO, tmp_path, size="近景"),
- _shot(3, 4.0, 2.0, "live_action", KITCHEN, tmp_path, size="特写"),
- _shot(4, 6.0, 2.0, "live_action", KITCHEN, tmp_path, size="中景")]
- plan = production_plan(_b(shots), tmp_path)
- assert plan["units"] == []
- scenes = {tuple(s["shots"]) for s in plan["shoot"]}
- assert scenes == {(1, 3, 4), (2,)}
- kitchen = next(s for s in plan["shoot"] if s["shots"] == [1, 3, 4])
- assert [st["shot_size"] for st in kitchen["setups"]] == ["中景", "特写"] # wide before close
- assert kitchen["setups"][0]["shots"] == [1, 4]
-
-
-def test_limits_reads_capabilities():
- m = Planner().models["kling-3.0"]
- lim = _limits(m)
- assert lim["max"] == 15 and lim["min"] == 3 and lim["multi_shot"]
-
-
-def test_review_answers_carry_prompts():
- from rea_video.plan import shot_prompts
- from rea_video.review import _clean
-
- ans, err = _clean({"label_probs": {"ai_video": 1}, "replication": {"video_prompt": "手倒牛奶", "image_prompt": " ", "x": "y"}})
- assert err is None and ans["replication"] == {"video_prompt": "手倒牛奶"}
- shot = {"vlm": {"replication": {"video_prompt": "VLM 版", "video_prompt_en": "en"}}, "review": ans}
- assert shot_prompts(shot) == {"video_prompt": "手倒牛奶", "video_prompt_en": "en"} # agent wins, VLM fills gaps
-
-
-def test_inserts_do_not_split_a_generation(tmp_path):
- # talk shots in one scene, UI inserts cut in between: generate the talk shots back to back
- shots = [_shot(1, 0.0, 1.5, "code_render", STUDIO, tmp_path),
- _shot(2, 1.5, 2.0, "ai_video", KITCHEN, tmp_path),
- _shot(3, 3.5, 2.0, "code_render", STUDIO, tmp_path),
- _shot(4, 5.5, 1.5, "ai_video", KITCHEN, tmp_path),
- _shot(5, 7.0, 2.0, "screen_capture", STUDIO, tmp_path),
- _shot(6, 9.0, 2.5, "ai_video", KITCHEN, tmp_path)]
- plan = production_plan(_b(shots), tmp_path)
- (u,) = plan["units"]
- assert u["shots"] == [2, 4, 6] and u["duration"] == 6.0 and len(u["ranges"]) == 3
- assert "镜头2(2.0–3.5s)" in u["prompt"] # generation-relative times
- assert "1 个代码工程(3 段)" in plan["summary"]
-
-
-def test_framing_goes_into_capsule_prompt():
- from rea_video.plan import _with_framing, framing_words
-
- shot = {"aspects": {"framing": {"result": {"shot_size": "近景", "camera_angle": "略俯拍"},
- "measured": {"subject": "face", "center_x": 0.3, "center_y": 0.7}},
- "camera": {"measured": {"move": "推"}}},
- "vlm": {"replication": {"video_prompt": "女生在厨房切菜"}}}
- zh, en = framing_words(shot)
- assert zh == "近景,略俯拍,主体在画面下部左侧,镜头推"
- assert en == "medium close-up, slightly high angle, subject in the lower left of the frame, camera push-in"
- assert _with_framing("女生在厨房切菜", zh) == zh + "。女生在厨房切菜"
- assert _with_framing("近景,略俯拍,主体在画面下部左侧,镜头推,切菜", zh).startswith("近景,略俯拍,主体") # nothing added twice
- assert _with_framing("", zh) == ""
-
-
-def test_english_engine_note_has_no_chinese(tmp_path):
- set_lang("en")
- try:
- plan = production_plan(_b([_shot(1, 0.0, 3.0, "ai_video", KITCHEN, tmp_path)]), tmp_path, engine="no-such-model")
- finally:
- set_lang("zh")
- note = plan["engine_note"]
- assert "no-such-model" in note and "1 call in total" in note
- assert not re.search(r"[\u3000-\u303f\u4e00-\u9fff\uff00-\uffef]", note + plan["model_name"])
-
-
-def test_each_unit_says_what_to_feed_the_model(tmp_path):
- from rea_video.production import _inputs, report_md
-
- set_lang("zh")
- kinds = lambda u: {x["kind"]: x["need"] for x in u["inputs"]} # noqa: E731
- # Seedance 2.0 takes frames or references, not both. A product to keep: every unit goes by reference,
- # the first frame only rides along as one more reference image, no last frame
- shots = [_shot(1, 0.0, 2.0, "ai_video", KITCHEN, tmp_path, product=True),
- _shot(2, 2.0, 2.0, "ai_video", KITCHEN, tmp_path),
- _shot(3, 7.0, 4.0, "ai_video", STUDIO, tmp_path)]
- plan = production_plan(_b(shots), tmp_path)
- multi, single = plan["units"]
- assert multi["method"] == single["method"] == "reference"
- assert kinds(multi) == {"text": "yes", "first_frame": "opt", "last_frame": "no", "ref_image": "yes", "ref_video": "opt"}
- assert kinds(single)["last_frame"] == "no" and "@图片2 作为首帧" in next(x["source"] for x in single["inputs"] if x["kind"] == "first_frame")
- # nothing to keep consistent: first / last frames, and no reference clip beside them
- moving = [_shot(4, 0.0, 4.0, "ai_video", STUDIO, tmp_path)]
- moving[0]["features"] = {"camera": "smooth_move"}
- (u,) = production_plan({**_b(moving), "audio": {}}, tmp_path)["units"]
- assert u["method"] == "first_last" and kinds(u) == {"text": "yes", "first_frame": "yes", "last_frame": "opt", "ref_video": "no"}
- assert "s4_last.jpg" in next(x["source"] for x in u["inputs"] if x["kind"] == "last_frame") and not u["refs"]
- md = "\n".join(report_md(plan))
- assert "| 首帧图 | 建议 |" in md and "| 尾帧图 | 不用 |" in md and "| 参考视频 | 建议 |" in md
- # a text-only model: nothing but the prompt, and the reader is told why there is no reference video
- t2v = {"max": 10.0, "first_frame": False, "first_last": False, "ref_video": False}
- method, inp = _inputs([shots[2]], t2v, [], None, 1)
- assert method == "t2v" and {x["kind"]: x["need"] for x in inp} == {"text": "yes", "ref_video": "no"}
- # chained to the previous unit: the first frame is that unit's last frame
- _, inp = _inputs([shots[1]], t2v | {"first_frame": True}, [], "G1", 1)
- assert "G1" in next(x["source"] for x in inp if x["kind"] == "first_frame")
-
-
-def test_framing_words_follow_the_report_language():
- from rea_video.aspects.vocab import canon, show
- from rea_video.plan import framing_words
-
- # a breakdown measured in Chinese, a report written in English: no Chinese option words leak through
- shot = {"aspects": {"framing": {"result": {"shot_size": "中景", "camera_angle": "顶拍(正上方俯拍桌面)"}},
- "camera": {"measured": {"move": "摇/移"}}}}
- set_lang("en")
- try:
- assert show("中景") == "medium shot" and show("拉/摇/移") == "pull-out / pan / track" and show("固定(主体在动)") == "static"
- loc, en = framing_words(shot)
- assert loc == en == "medium shot, top-down, camera pan / track"
- finally:
- set_lang("zh")
- assert show("medium shot") == "中景" and show("顶拍(正上方俯拍桌面)") == "顶拍(正上方俯拍桌面)"
- assert canon("Close-up") == canon("特写") == "特写"
diff --git a/tests/test_prosody.py b/tests/test_prosody.py
deleted file mode 100644
index 5860971..0000000
--- a/tests/test_prosody.py
+++ /dev/null
@@ -1,51 +0,0 @@
-"""Measured delivery per line: rate, pitch, loudness, pauses and the emotion the recognizer hears, merged into the script."""
-import numpy as np
-
-from rea_video import prosody
-from rea_video.audio import speaks_in
-from rea_video.entities import script
-from rea_video.i18n import set_lang
-
-SR = 16000
-
-
-def _tone(hz: float, s: float, amp: float = 0.3) -> np.ndarray:
- return (amp * np.sin(2 * np.pi * hz * np.arange(int(s * SR)) / SR)).astype(np.float32)
-
-
-def test_measure_rate_pitch_level_and_pause():
- x = np.concatenate([_tone(200, 1.0), np.zeros(SR, np.float32), _tone(200, 1.0), _tone(320, 1.0, 0.9)])
- lines = [{"start": 0.0, "end": 1.0, "text": "你好你好你好", "speaker": "A"},
- {"start": 2.0, "end": 3.0, "text": "还好", "speaker": "A"},
- {"start": 3.0, "end": 4.0, "text": "one two three four", "speaker": "A"}]
- m = prosody.measure(x, SR, lines)
- assert m[0]["rate"] == 6.0 and m[1]["rate"] == 2.0 and m[2]["unit"] == "en" and m[2]["rate"] == 4.0
- assert abs(m[0]["f0_hz"] - 200) < 5 and m[0]["range_st"] < 1
- assert m[1]["pause_before"] == 1.0 and "pause_before" not in m[2]
- assert m[2]["pitch_rel_st"] >= 7 and m[2]["level_rel"] >= 8 # the high, loud line stands out
- assert prosody.measure(None, SR, lines, pitch=False)[0] == {"unit": "zh", "rate": 6.0} # the mix: timings only
-
-
-def test_describe_names_what_stands_out():
- set_lang("zh")
- got = prosody.describe({"unit": "zh", "rate": 7.1, "pitch_rel_st": -7.2, "pause_before": 0.8, "range_st": 6.0}, "angry")
- assert got == "实测:语速快(7.1 字/秒),比这人别的句子低,句前停 0.8 秒;语音模型听着偏生气"
- assert "句前停" not in prosody.describe({"unit": "zh", "rate": 5.0, "pause_before": 0.8}, pause=False)
- assert prosody.describe({}, "") == ""
- assert prosody.emotion_tag("<|HAPPY|>") == "happy" and prosody.emotion_tag("<|NEUTRAL|>") == "" and prosody.emotion_tag(None) == ""
-
-
-def test_script_carries_the_measured_delivery():
- set_lang("zh")
- heard = [{"start": 0.1, "end": 3.0, "text": "你信不信", "emotion": "happy",
- "prosody": {"unit": "zh", "rate": 7.0, "pause_before": 1.0}}]
- b = {"shots": [], "speech": {"ok": True, "lines": heard}}
- assert script(b)[0]["delivery"] == "实测:语速快(7.0 字/秒),句前停 1.0 秒;语音模型听着偏开心"
- # a reader's line borrows the measure of the transcribed line under it; its own rough timing gives no pause
- b["whole_video_vlm"] = {"narration": {"lines": [{"start": 0.3, "end": 2.8, "text": "你信不信", "delivery": "挑衅"}]}}
- assert script(b)[0]["delivery"] == "挑衅;实测:语速快(7.0 字/秒);语音模型听着偏开心"
-
-
-def test_shot_clip_gets_sound_only_where_someone_speaks():
- audio = {"voice": {"segments": [[1.0, 2.0]]}}
- assert speaks_in(audio, 0.0, 1.5) and not speaks_in(audio, 1.9, 4.0) and not speaks_in({"has_audio": False}, 0, 9)
diff --git a/tests/test_report.py b/tests/test_report.py
deleted file mode 100644
index 4252784..0000000
--- a/tests/test_report.py
+++ /dev/null
@@ -1,241 +0,0 @@
-"""Report structure: reading order, cast / script / music cards, folded detail, and the HTML rendered from the Markdown."""
-import json
-import re
-
-import pytest
-
-from rea_video.entities import cast, clean_cast, open_questions, script
-from rea_video.i18n import set_lang
-from rea_video.pipeline import decompose, finalize
-from rea_video.report import html_report, markdown
-from rea_video.review import apply_answers, build_tasks
-
-CAST = {"style": "扁平 UI,深色底",
- "characters": [{"id": "A", "name": "小黄", "kind": "cartoon", "look": "黄色圆滚滚的小河马,粉色连体衣,斜挎粉包", "role": "主角", "voice": "", "shots": [1, 2, 3]},
- {"id": "B", "name": "旁白", "kind": "person", "look": "", "role": "旁白", "voice": "青年男声", "shots": []},
- {"name": "", "look": "", "kind": "bogus"}],
- "scenes": [{"id": "S1", "where": "城市街道", "when": "白天", "look": "虚化街景,暖日光", "shots": [1, 2]}],
- "props": [{"name": "粉色小挎包", "note": "角色一直背着", "shots": [1, 3]}, {"note": "no name"}]}
-
-
[email protected](scope="module")
-def breakdown(media, tmp_path_factory):
- out = tmp_path_factory.mktemp("rep") / "edit"
- b = decompose(media["edit"], out, use_vlm=False, ocr=False, stems=False)
- return b, out
-
-
-def _with_vlm(b: dict) -> dict:
- b = json.loads(json.dumps(b))
- b["whole_video_vlm"] = {
- "summary": "测试视频", "format": "知识讲解", "hook": "开头一张静帧", "overall_production": "代码渲染 + 静图",
- "segments": [{"start": 0, "end": 2, "beat": "铺垫", "copy": "你好", "audio": "音乐"}],
- "narration": {"type": "tts", "voice": "女声", "lines": [{"start": 0.0, "end": 1.0, "speaker": "A", "text": "你好"}, {"start": 1.0, "end": 2.0, "text": "再见"}]},
- "music": {"present": True, "style": "轻快", "genre": "pop", "mood": "开心", "instruments": ["钢琴"], "has_vocals": False,
- "song_guess": "测试歌", "source_guess": "stock_library", "ending": "fade_out"},
- "sfx": [], "ambience": "无", "mix": "人声在上", "subtitles": {"present": False}, **CAST}
- # the synthetic clip is silent; give it a measured audio layer so the voice / music cards render
- b["audio"] = {"has_audio": True, "rms_dbfs": -20.0, "peak_dbfs": -3.0, "voice": {"present": True, "ratio": 0.4, "f0_median_hz": 210.0, "gender_hint": "female"},
- "music": {"present": True, "ratio": 0.9, "start": 0.0, "end": 7.5, "tempo_bpm": 120.0, "tempo_alternatives": [60.0], "key": {"tonic": "C", "mode": "major", "confidence": 0.8},
- "section_changes": [4.0]}, "cuts_on_beat_ratio": 0.5, "cuts_on_beat_chance": 0.3, "beat_synced_edit": True}
- b["audio_plan"] = {"sfx_merged": [{"t": 1.0, "type": "pop", "description": "弹出音", "source": "vlm", "on": {"what": "文字弹出"}}], "plan": [], "mix": ""}
- return b
-
-
-def test_clean_cast_validates():
- c = clean_cast(CAST)
- assert [x["id"] for x in c["characters"]] == ["A", "B"] # the entry without name / look is dropped
- assert c["characters"][0]["shots"] == [1, 2, 3] and c["scenes"][0]["where"] == "城市街道"
- assert [p["name"] for p in c["props"]] == ["粉色小挎包"]
- assert clean_cast(None) == {} and clean_cast({"characters": [{}]}) == {}
-
-
-def test_cast_prefers_review_and_falls_back(breakdown):
- b, _ = breakdown
- set_lang("zh")
- c = cast(b)
- assert c["source"] is None and c["characters"] == []
- v = _with_vlm(b)
- assert cast(v)["source"] == "vlm" and cast(v)["style"] == "扁平 UI,深色底"
- v["review_cast"] = {"characters": [{"id": "X", "name": "复核角色", "kind": "person", "look": "看图填的", "shots": [2]}], "scenes": [], "props": [], "style": ""}
- c = cast(v)
- assert c["source"] == "review" and c["characters"][0]["name"] == "复核角色"
- assert c["props"][0]["name"] == "粉色小挎包" # review left props empty → VLM props stay
- rows = script(v)
- assert [r["speaker"] for r in rows] == ["A", ""] and rows[1]["text"] == "再见"
-
-
-def test_markdown_reading_order_and_cards(breakdown):
- b, _ = breakdown
- set_lang("zh")
- md = markdown(_with_vlm(b))
- heads = [l for l in md.splitlines() if l.startswith("## ")]
- want = ["## 一眼看懂:画面、包装、声音三层", "## 内容与结构", "## 分镜表", "## 自己复刻:按这个顺序做", "## 角色、场景与道具", "## 声音",
- "## 不确定点", "## 附录"]
- idx = [heads.index(h) for h in want]
- assert idx == sorted(idx), heads
- assert md.index("## 内容与结构") < md.index("## 自己复刻") < md.index("### 剪辑") < md.index("### 逐镜取证")
- # cast table, scene table, props
- assert re.search(r"\| A \| 小黄 \| 卡通形象 \| 黄色圆滚滚的小河马.*\| #1–#3 \|", md)
- assert "| S1 | 城市街道 | 白天 |" in md and "- 粉色小挎包(镜头 #1、#3):角色一直背着" in md
- # script and music card
- assert "**脚本**(TTS 合成,女声)" in md and "| 0.0–1.0s | A | 你好 |" in md and "| 1.0–2.0s | 旁白 | 再见 |" in md
- assert "- 歌曲:测试歌" in md and "- 风格:轻快;pop;开心;钢琴;纯音乐" in md
- # per-shot forensics folded, one per shot; no internal rule ids in prose
- assert md.count('<details class="ref"><summary>#') == len(b["shots"])
- assert not re.search(r"\bR\d\d-[a-z]|\bS0\d\b|A0\d\)", md), "rule ids leaked into the report"
- assert "capsule_cinema" not in md and "code_render_spec" not in md
-
-
-def test_markdown_without_vlm_still_complete(breakdown):
- b, _ = breakdown
- set_lang("zh")
- md = markdown(b)
- assert "这次没有分析整片内容" in md and "这次没有整理出角色" in md and "## 不确定点" in md
- assert "review_answers.json" not in md # users are not told to edit agent files
- set_lang("en")
- try:
- md_en = markdown(b)
- assert "## Cast, scenes and props" in md_en and "## Open questions" in md_en and '<details class="ref"><summary>#1 ' in md_en
- finally:
- set_lang("zh")
-
-
-def test_english_markdown_has_no_chinese_punctuation(media, tmp_path):
- try:
- md_en = markdown(decompose(media["edit"], tmp_path / "edit", use_vlm=False, ocr=False, stems=False, lang="en"))
- finally:
- set_lang("zh")
- assert "Inference: " in md_en and "Visible on screen" in md_en
- assert not re.findall(r"[():,、;]", md_en)
-
-
-def test_shot_detail_separates_seen_from_inferred(breakdown):
- b, _ = breakdown
- set_lang("zh")
- v = _with_vlm(b)
- v["shots"][0]["base"]["seen"] = ["[VLM] 手指数量不对"]
- v["shots"][0]["base"]["measured"] = ["24fps 源"]
- md = markdown(v)
- start = md.index('<details class="ref"><summary>#1')
- first = md[start:md.index("</details>", start)]
- seen_at, made_at = first.index("**画面里看得到的**"), first.index("**工具推断的制作方式**")
- assert seen_at < first.index("[VLM] 手指数量不对") < made_at < first.index("24fps 源")
- assert "「制作方式」「素材来源」是工具推断的" in md
-
-
-def test_html_is_rendered_from_markdown(breakdown):
- b, _ = breakdown
- set_lang("zh")
- h = html_report(_with_vlm(b))
- for tag in ("ul", "ol", "table", "section", "details", "pre"):
- assert h.count(f"<{tag}") == h.count(f"</{tag}>"), tag
- assert "<div class='mix'>" in h and h.count("<h2>") >= 7
- assert "<td>小黄</td>" in h and "<img" in h
- # no raw Markdown left behind
- body = h.split("<main>")[1]
- assert not re.search(r"^(\| |- |\*\*|#{1,3} )", body, re.M), "unrendered markdown in HTML"
- assert "<!--mix-->" not in h and "<!--stems-->" not in h
-
-
-def test_review_cast_flows_into_report(breakdown):
- b, out = breakdown
- set_lang("zh")
- b = json.loads(json.dumps(b))
- _, answers = build_tasks(b, out)
- assert "cast" in answers and answers["cast"]["characters"][0]["id"] == "A"
- answers["cast"] = CAST
- apply_answers(b, answers, by="tester")
- assert b["review_cast"]["by"] == "tester" and len(b["review_cast"]["characters"]) == 2
- b = finalize(b, out)
- md = (out / "report.md").read_text(encoding="utf-8")
- assert "| A | 小黄 |" in md
-
-
-def test_open_questions_collects_everything(breakdown):
- b, _ = breakdown
- set_lang("zh")
- b = json.loads(json.dumps(b))
- b["shots"][0]["base"]["disputed"] = "工具判 A、VLM 判 B"
- b["shots"][1]["base"]["confidence"] = 0.4
- 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("声音没有 AI 听过" in q and "复核只看了画面" in q and "--vlm" not 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("声音没有 AI 听过" in q for q in open_questions(b))
- b["audio"]["has_audio"] = False
- b["analysis"]["vlm"] = {"status": "off", "used": False}
- assert not any("声音没有 AI 听过" in q for q in open_questions(b))
-
-
-def test_narrative_line_from_review_and_whole_video(breakdown):
- from rea_video import narrative
-
- b, out = breakdown
- set_lang("zh")
- b = json.loads(json.dumps(b))
- assert "这次没有整理出叙事线" in markdown(b) and "在讲什么" not in "".join(l for l in markdown(b).split("\n") if l.startswith("| #"))
- last = b["shots"][-1]
- b["whole_video_vlm"] = {"segments": [{"start": 0, "end": b["shots"][0]["end"], "role": "抓注意", "beat": "用一张静帧提问"},
- {"start": b["shots"][0]["end"], "end": last["end"], "role": "info", "beat": "逐条讲解"}]}
- told = narrative.shot_roles(b)
- assert told[1]["role"] == "hook" and told[1]["source"] == "vlm" and told[last["index"]]["role"] == "info"
- tasks, answers = build_tasks(b, str(out))
- assert "narrative" in answers["shots"][0] and "抓注意" in tasks["instructions"]
- for a, r in zip(answers["shots"], b["shots"]):
- a["label_probs"] = {r["base"]["label"]: 1.0}
- answers["shots"][-1]["narrative"] = {"role": "给结论", "point": "一句话收束观点"}
- answers["shots"][0]["narrative"] = {"role": "nonsense", "point": ""}
- apply_answers(b, answers, by="tester")
- b = finalize(b, out)
- assert b["shots"][-1]["narrative"] == {"role": "payoff", "point": "一句话收束观点", "role_zh": "给结论", "source": "agent"}
- assert b["shots"][0]["narrative"]["source"] == "vlm" # an empty review answer leaves the VLM's reading in place
- assert b["narrative"][0]["role"] == "hook" and b["narrative"][-1]["shots"] == [last["index"]]
- md = (out / "report.md").read_text(encoding="utf-8")
- assert "**叙事线**" in md and "给结论" in md and "一句话收束观点" in md
- assert "在讲什么" in next(l for l in md.split("\n") if l.startswith("| # "))
- set_lang("en")
- try:
- assert narrative.shot_roles(b)[last["index"]]["role_zh"] == "deliver the conclusion"
- finally:
- set_lang("zh")
-
-
-def test_shot_numbers_read_as_ranges():
- from rea_video.i18n import shot_ids
-
- assert shot_ids([1, 2, 3, 5, 8, 9, 10, 11, 13]) == "#1–#3、#5、#8–#11、#13"
- assert shot_ids([4, 5]) == "#4、#5" and shot_ids([]) == "—"
-
-
-def test_reviewer_is_named_not_called_human():
- from rea_video.report import _readers
-
- b = {"analysis": {"vlm": {}, "review": {"shots": 3, "by": "claude"}}, "shots": [{"base": {"decided_by": "fused_agent"}}]}
- assert _readers(b) == "工具测量 + AI 助手看图复核 3 镜"
- b["analysis"]["review"]["by"] = "小王"
- assert _readers(b) == "工具测量 + 小王 看图复核 3 镜"
-
-
-def test_reader_report_says_each_thing_once(breakdown): # noqa: F811
- b, _ = breakdown
- set_lang("zh")
- v = _with_vlm(b)
- v["review_story"] = {"summary": "一句话说清楚", "hook": "0–2 秒先放结果", "highlights": ["先给结果再讲方法"]}
- v["summary"]["aspects"] = ["剪辑:每分钟 30 刀,平均 2.0s"]
- md = markdown(v)
- assert md.count("一句话说清楚") == 1 and md.count("0–2 秒先放结果") == 1 and md.count("先给结果再讲方法") == 1
- assert md.index("## 核心看点") < md.index("## 一眼看懂") < md.index("## 自己复刻")
- assert md.count("每分钟 30 刀") == 1 and "### 剪辑" in md # the cutting numbers live under the remake step only
- assert "复刻拍摄方案" not in md and "assemble --overlays" not in md # no second shooting plan, no CLI flags
diff --git a/tests/test_review.py b/tests/test_review.py
deleted file mode 100644
index 96c1e0b..0000000
--- a/tests/test_review.py
+++ /dev/null
@@ -1,217 +0,0 @@
-"""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
-
-
-def test_review_roundtrip_overrides_and_reports(media, tmp_path, capsys):
- out = tmp_path / "o"
- b = decompose(media["code"], out, use_vlm=False, ocr=False, workers=1, stems=False)
- assert b["shots"][0]["base"]["label"] != "live_action"
- assert main(["review", str(out)]) == 0
- tasks = json.loads((out / "review_tasks.json").read_text(encoding="utf-8"))
- assert tasks["shots"] and "label_probs" in tasks["instructions"]
- assert (out / tasks["shots"][0]["images"]["sheet"]).is_file()
- # lean task file: the sheet already holds first/last frames, zoom command is one template, rows are one line each
- assert set(tasks["shots"][0]["images"]) <= {"sheet", "strip"}
- assert "{start}" in tasks["zoom_cmd"] and "zoom_cmd" not in tasks["shots"][0]
- assert all(line.startswith(" {\"id\"") for line in (out / "review_tasks.json").read_text(encoding="utf-8").splitlines()
- if '"id":"shot_' in line and line.startswith(" "))
- ans = json.loads((out / "review_answers.json").read_text(encoding="utf-8"))
- assert all(a["label_probs"] == {} for a in ans["shots"])
- first = ans["shots"][0]
- ranked = sorted(b["shots"][0]["deterministic"]["probs"].items(), key=lambda kv: -kv[1])
- second = ranked[1][0] # a lone reader may pick the tools' runner-up (but not a label they rule out)
- first["label_probs"].update({second: 0.9, ranked[0][0]: 0.1})
- first["evidence"] = ["真实的手和厨房"]
- first["description"] = "手持拍摄厨房台面"
- ans["shots"].append({"id": "shot_999", "label_probs": {"ai_video": 1}})
- (out / "review_answers.json").write_text(json.dumps(ans, ensure_ascii=False), encoding="utf-8")
- capsys.readouterr()
- assert main(["apply-review", str(out), "--by", "tester"]) == 0
- printed = capsys.readouterr().out
- assert "shot_999" in printed and "改判" in printed
- b2 = json.loads((out / "breakdown.json").read_text(encoding="utf-8"))
- s0 = b2["shots"][0]
- assert s0["base"]["label"] == second and s0["base"]["decided_by"] == "fused_agent"
- assert any(e.startswith("[tester 看图]") for e in s0["base"]["evidence"])
- assert "tester 看图复核 1/" in b2["summary"]["vlm"]
- md = (out / "report.md").read_text(encoding="utf-8")
- # a named reviewer is named; an AI assistant is never passed off as a person checking the shots
- assert "tester 看图复核 1 镜" in md and "人工复核" not in md and "手持拍摄厨房台面" in md
- # unanswered shots (empty probs) are skipped silently: one count line, not one line per shot
- assert ("没作答、已跳过" in printed) == (len(b2["shots"]) > 1) and "shot_002: label_probs" not in printed
- # unanswered shots are not applied
- assert all("review" not in r for r in b2["shots"][1:])
- # a lone reader cannot push a code-render shot to live action: it is outside the tools' top two
- if "live_action" not in (ranked[0][0], second):
- ans["shots"][0]["label_probs"] = {"live_action": 1}
- (out / "review_answers.json").write_text(json.dumps(ans, ensure_ascii=False), encoding="utf-8")
- main(["apply-review", str(out), "--by", "tester"])
- assert json.loads((out / "breakdown.json").read_text(encoding="utf-8"))["shots"][0]["base"]["label"] != "live_action"
-
-
-def test_vlm_config_merges_fallback_models_on_same_endpoint(monkeypatch):
- for k in ("REA_VLM_BASE_URL", "REA_VLM_API_KEY", "REA_VLM_MODEL"):
- monkeypatch.delenv(k, raising=False)
- monkeypatch.setenv("VIDEO_ANALYSIS_BASE_URL", "https://x.test/v1")
- monkeypatch.setenv("VIDEO_ANALYSIS_API_KEY", "k")
- monkeypatch.setenv("VIDEO_ANALYSIS_MODEL_NAME", "m1")
- monkeypatch.setenv("GEMINI3_BASE_URL", "https://x.test/v1/")
- monkeypatch.setenv("GEMINI3_API_KEY", "k")
- monkeypatch.setenv("GEMINI3_MODEL_NAME", "m1,m2,m3")
- assert VLMConfig.from_env().models == ["m1", "m2", "m3"]
- monkeypatch.setenv("GEMINI3_API_KEY", "other")
- 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
-
- def p(**kw):
- rest = (1 - sum(kw.values())) / (len(LABELS) - len(kw))
- return {k: kw.get(k, rest) for k in LABELS}
-
- det = p(ai_video=0.46, live_action=0.38)
- vlm_and_agent_avg = p(live_action=0.48, ai_video=0.39) # VLM says live 0.85, agent says AI 0.72
- assert max(fuse(det, vlm_and_agent_avg, "dynamic").items(), key=lambda kv: kv[1])[0] == "live_action"
- out = fuse(det, vlm_and_agent_avg, "dynamic", majority="ai_video")
- assert max(out, key=out.get) == "ai_video"
- # hard constraints still win: a frozen shot is never a generated video
- frozen = fuse(p(static_hold=0.6), p(ai_video=0.9), "frozen", majority="ai_video")
- assert max(frozen, key=frozen.get) == "static_hold" or frozen["ai_video"] < 0.5
-
-
-def test_split_suggestion_kept_when_valid_and_dropped_when_empty():
- from rea_video.review import _clean
-
- ok, err = _clean({"id": "shot_001", "label_probs": {"ai_video": 1.0},
- "split_suggestion": {"cuts": [12.5, 40], "labels": ["code_render", "live_action"], "note": "n"}})
- assert err is None and ok["split_suggestion"]["cuts"] == [12.5, 40.0]
- assert ok["split_suggestion"]["labels"] == ["code_render", "live_action"]
- bad, err2 = _clean({"id": "shot_001", "label_probs": {"ai_video": 1.0}, "split_suggestion": {"cuts": []}})
- assert err2 is None and not bad.get("split_suggestion")
-
-
-def test_split_suggestion_rejects_malformed_input_instead_of_raising():
- from rea_video.review import _clean
-
- base = {"id": "shot_001", "label_probs": {"ai_video": 1.0}}
- for sp in ({"cuts": "12.5"}, {"cuts": ["abc"]}, {"cuts": [1, None]}, {"cuts": [5.0], "labels": "live_action"},
- {"cuts": [3.0], "labels": ["bogus_label"]}):
- clean, err = _clean({**base, "split_suggestion": sp})
- assert clean is None and err and "split_suggestion" in err, sp
- # cuts come back sorted, labels stay as given
- ok, err = _clean({**base, "split_suggestion": {"cuts": [40, 12.5], "labels": ["code_render", "live_action", "code_render"]}})
- assert err is None and ok["split_suggestion"]["cuts"] == [12.5, 40.0]
-
-
-def test_apply_review_reports_malformed_answers_instead_of_raising():
- from rea_video.review import _clean, apply_answers
-
- b = {"shots": [{"id": "shot_001", "index": 1, "base": {"label": "live_action"},
- "deterministic": {"probs": {"live_action": 0.9}}}], "analysis": {}}
- # each malformed shape used to crash apply-review with a traceback; the answers file is
- # written by an agent, so one bad entry must be reported and the rest still applied
- log = apply_answers(b, {"shots": [
- {"id": "shot_001", "label_probs": {"live_action": 1.0}, "evidence": "a hand-held shot"},
- "shot_001",
- {"id": ["shot_001"], "label_probs": {"live_action": 1.0}},
- {"id": "shot_001", "label_probs": ["live_action"]},
- {"id": "shot_999", "label_probs": {"live_action": 1.0}},
- ], "story": ["not", "a", "dict"]})
- assert log["applied"] == ["shot_001"] # the good answer still lands
- assert b["shots"][0]["review"]["evidence"] == ["a hand-held shot"] # a bare string stays one item, not one char per line
- assert len(log["problems"]) == 4 and any("shot_999" in p for p in log["problems"])
- assert log["unanswered"] == []
- # the whole file being the wrong shape, and shots not being a list, are problems too
- assert apply_answers(b, ["shot_001"])["problems"] == ["答案文件不是一个对象"]
- assert apply_answers(b, {"shots": {"shot_001": {}}})["problems"] == ["shots 不是一个列表,跳过"]
- # and _clean itself rejects a non-dict label_probs instead of raising
- clean, err = _clean({"id": "shot_001", "label_probs": ["live_action"]})
- assert clean is None and "label_probs" in err
-
-
-def test_packaging_only_answers_count_as_applied(media, tmp_path, capsys):
- out = tmp_path / "p"
- b = decompose(media["code"], out, use_vlm=False, ocr=False, workers=1, stems=False)
- if not b.get("packaging"):
- b["packaging"] = {"text_cues": [], "stickers": []}
- (out / "breakdown.json").write_text(json.dumps(b, ensure_ascii=False), encoding="utf-8")
- ans = tmp_path / "a.json"
- ans.write_text(json.dumps({"shots": [], "packaging": {"text": [{"id": "text_001", "kind": "scene"}]}}), encoding="utf-8")
- assert main(["apply-review", str(out), str(ans), "--by", "tester"]) == 0
- assert json.loads((out / "breakdown.json").read_text(encoding="utf-8"))["packaging"]["review"]["text"] == {"text_001": "scene"}
- empty = tmp_path / "e.json"
- empty.write_text(json.dumps({"shots": []}), encoding="utf-8")
- assert main(["apply-review", str(out), str(empty), "--by", "tester"]) == 1
-
-
-def test_english_review_asks_for_english_prompts(media, tmp_path):
- from rea_video.review import build_tasks
-
- from rea_video.i18n import set_lang
-
- try:
- b = decompose(media["code"], tmp_path / "en", use_vlm=False, ocr=False, workers=1, stems=False, lang="en")
- finally:
- set_lang("zh")
- tasks, _ = build_tasks(b, str(tmp_path / "en"))
- assert "中文图像提示词" not in tasks["instructions"] and "英文图像提示词" in tasks["instructions"]
- b["lang"] = "zh"
- tasks, _ = build_tasks(b, str(tmp_path / "en"))
- assert "中文图像提示词" in tasks["instructions"] and "<PROMPT_LANG>" not in tasks["instructions"]
diff --git a/tests/test_robustness.py b/tests/test_robustness.py
deleted file mode 100644
index 1db299d..0000000
--- a/tests/test_robustness.py
+++ /dev/null
@@ -1,350 +0,0 @@
-"""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")
-
-
-def test_tiles_rejects_bad_numbers(fps10, tmp_path, capsys):
- import argparse
- import json
-
- from rea_video.cli import cmd_tiles
-
- def args(**kw):
- base = {"video": str(fps10), "start": 0.0, "end": None, "every": 0.5,
- "cols": 6, "cell": 320, "max": 48, "out": str(tmp_path / "t.jpg")}
- base.update(kw)
- return argparse.Namespace(**base)
-
- # --every 0 used to raise ZeroDivisionError, --cols 0 ValueError, --cell 0 a PIL error,
- # and --max 0 / --end <= --start silently printed an empty result with exit 0
- for bad in ({"every": 0}, {"every": -0.5}, {"start": -1}, {"cols": 0}, {"max": 0},
- {"cell": 0}, {"end": 0.0}, {"start": 1.0, "end": 1.0}, {"start": 5.0}):
- with pytest.raises(SystemExit) as exc:
- cmd_tiles(args(**bad))
- assert "rea-video: --" in str(exc.value)
- assert capsys.readouterr().out == "" # a clean one-line error, not a traceback
- assert cmd_tiles(args()) == 0
- printed = json.loads(capsys.readouterr().out)
- assert len(printed["tiles"]) == 1 and len(printed["times"]) == 4
- assert Path(printed["tiles"][0]).is_file()
-
-
-def test_relocalize_rewrites_stored_labels():
- from rea_video.i18n import set_lang
- from rea_video.packaging import relocalize
-
- pack = {"text_cues": [{"kind": "subtitle", "kind_zh": "字幕", "line_h": 0.05,
- "style": {"fill_name": "白", "stroke": True, "stroke_name": "黑"}, "style_zh": "白字、黑描边",
- "anim_in": {"kind": "pop", "kind_zh": "缩放弹出"}}],
- "stickers": [{"kind": "static_sticker", "kind_zh": "静态贴纸/图片", "source": "pixels"},
- {"kind": "static_sticker", "kind_zh": "一只猫的贴纸", "source": "vlm"}]}
- try:
- set_lang("en")
- relocalize(pack, 1920)
- finally:
- set_lang("zh")
- c = pack["text_cues"][0]
- assert c["kind_zh"] == "subtitle" and c["anim_in"]["kind_zh"] == "scale pop"
- assert c["style"]["fill_name"] == "white" and "black outline" in c["style_zh"] and "line height" in c["style_zh"]
- assert pack["stickers"][0]["kind_zh"] == "static sticker / image"
- assert pack["stickers"][1]["kind_zh"] == "一只猫的贴纸" # free text from the VLM is kept
-
-
-def test_variable_frame_rate_cuts_use_real_timestamps(tmp_path):
- """30 fps + 10 fps + 30 fps segments, 2 s each: cuts at 2 s and 4 s, not at frame / average-fps."""
- from rea_video.shots import build_track, detect_shots
-
- srcs = ["testsrc2=s=160x120:r=30:d=2", "mandelbrot=s=160x120:r=10", "testsrc2=s=160x120:r=30:d=2"]
- for k, src in enumerate(srcs):
- vf = ["-vf", "hue=h=180,vflip"] if k == 2 else []
- subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", src, "-t", "2", *vf, "-c:v", "libx264",
- "-pix_fmt", "yuv420p", "-video_track_timescale", "90000", str(tmp_path / f"{k}.mp4")], check=True)
- (tmp_path / "list.txt").write_text("".join(f"file {k}.mp4\n" for k in range(3)))
- vfr = tmp_path / "vfr.mp4"
- subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "concat", "-i", str(tmp_path / "list.txt"), "-c", "copy", str(vfr)], check=True)
- 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})
-
-
-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_security.py b/tests/test_security.py
deleted file mode 100644
index fa5d14d..0000000
--- a/tests/test_security.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""Hardening: report HTML escaping, env loading, remake path handling."""
-import json
-import subprocess
-import sys
-from pathlib import Path
-
-from rea_video.report import _inline, _md_to_html
-
-
-def test_inline_blocks_attribute_injection_and_bad_schemes():
- assert "onerror=\"" not in _inline('![a](x"onerror="alert(1))')
- assert "<a" not in _inline("[x](javascript:alert(1))")
- assert "<a" not in _inline("[x](JavaScript:alert(1))")
- assert '<a href="https://a.com/b">ok</a>' in _inline("[ok](https://a.com/b)")
- assert '<img src="frames/shot_001.jpg"' in _inline("![s](frames/shot_001.jpg)")
-
-
-def test_raw_html_lines_only_for_our_own_tags():
- b = {"summary": {"production_mix": []}}
- out = _md_to_html(["- VLM 说明", "<img src=x onerror=alert(1)>", "<details><summary>镜头</summary>", "</details>"], b)
- assert "<img src=x" not in out and "&lt;img src=x" in out
- assert "<details><summary>镜头</summary>" in out
-
-
-def test_cwd_env_is_not_loaded(tmp_path, monkeypatch):
- from rea_video import cli
-
- (tmp_path / ".env").write_text("REA_TEST_FROM_CWD=1\n")
- monkeypatch.chdir(tmp_path)
- monkeypatch.delenv("REA_TEST_FROM_CWD", raising=False)
- monkeypatch.setattr("rea_video.memory.pref", lambda k: None)
- cli._env(type("A", (), {"env_file": None})())
- import os
- assert "REA_TEST_FROM_CWD" not in os.environ
-
-
-RUN_REMAKE = Path(__file__).resolve().parent.parent / "rea_video/integrations/run_remake.py"
-
-
-def _run_remake(jobs: Path, root: Path, *extra: str) -> subprocess.CompletedProcess:
- return subprocess.run([sys.executable, str(RUN_REMAKE), "--jobs", str(jobs), "--capsule-root", str(root), "--dry-run", *extra],
- capture_output=True, text=True)
-
-
-def test_run_remake_rejects_foreign_capsule_root_and_output_dir(tmp_path):
- root = tmp_path / "capsule"
- job = {"executor": "capsule_cinema", "shot": 1, "label": "ai_video",
- "params": {"prompt": "p", "output_dir": str(root / "output/x")}}
- jobs = tmp_path / "jobs.json"
- jobs.write_text(json.dumps({"capsule_root": str(tmp_path / "evil"), "run_dir": "r", "jobs": [job]}))
- r = _run_remake(jobs, root)
- assert r.returncode != 0 and "capsule_root" in r.stderr
- job["params"]["output_dir"] = str(tmp_path / "elsewhere")
- jobs.write_text(json.dumps({"capsule_root": str(root), "run_dir": "r", "jobs": [job]}))
- r = _run_remake(jobs, root)
- assert r.returncode != 0 and "output_dir" in r.stderr
- job["params"]["output_dir"] = str(root / "output/x")
- jobs.write_text(json.dumps({"capsule_root": str(root), "run_dir": "r", "jobs": [job]}))
- assert _run_remake(jobs, root).returncode == 0
-
-
-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, "fetch", lambda url, dst: open(dst, "wb").write(b"evil"))
- assert faces._ensure_model() is None
- assert list(tmp_path.iterdir()) == []
-
-
-def test_run_remake_only_accepts_shot_ids(tmp_path):
- root = tmp_path / "capsule"
- jobs_list = [{"executor": "capsule_cinema", "shot": i, "label": "ai_video",
- "params": {"prompt": f"p{i}", "output_dir": str(root / f"output/{i}")}} for i in (1, 3)]
- jobs = tmp_path / "jobs.json"
- jobs.write_text(json.dumps({"capsule_root": str(root), "run_dir": "r", "jobs": jobs_list}))
- for only in ("3", "shot_003", "SHOT_3"):
- r = _run_remake(jobs, root, "--only", only)
- assert r.returncode == 0 and r.stdout.startswith("1 generation job") and '"p3"' in r.stdout, (only, r.stderr)
- for bad in ("abc", "7"):
- r = _run_remake(jobs, root, "--only", bad)
- assert r.returncode != 0 and "--only" in r.stderr
diff --git a/tests/test_shots.py b/tests/test_shots.py
deleted file mode 100644
index a9e945c..0000000
--- a/tests/test_shots.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""Shot boundaries in talking-head and fast-cut edits: jump cuts, brief flashes, very short inserts."""
-import cv2
-import numpy as np
-
-from rea_video.media import video_info
-from rea_video.remake import fit_speed
-from rea_video.shots import build_track, detect_shots
-from tests.conftest import _photo_like, _write
-
-W, H = 360, 640
-
-
-def _speaker(bg: np.ndarray, x: int, y: int, t: int, rng) -> np.ndarray:
- """A person in front of a fixed background, swaying slightly from frame to frame."""
- f = bg.copy()
- sway = int(round(3 * np.sin(t / 6)))
- cv2.ellipse(f, (x + sway, y + 360), (130, 220), 0, 180, 360, (40, 40, 50), -1) # shoulders
- cv2.circle(f, (x + sway, y + 190), 70, (120, 150, 200), -1) # head
- cv2.circle(f, (x + sway - 25, y + 175), 8, (30, 30, 30), -1)
- cv2.circle(f, (x + sway + 25, y + 175), 8, (30, 30, 30), -1)
- noise = rng.normal(0, 2.0, f.shape)
- return np.clip(f.astype(np.float32) + noise, 0, 255).astype(np.uint8)
-
-
-def test_jump_cut_found_and_brief_flash_ignored(tmp_path):
- rng = np.random.default_rng(1)
- bg = _photo_like(W, H, 3)
- frames = [_speaker(bg, 180, 160, t, rng) for t in range(45)]
- # jump cut: same camera and background, the speaker is suddenly further left and lower
- frames += [_speaker(bg, 120, 210, t, rng) for t in range(45, 120)]
- for k, gain in ((75, 90.0), (76, 25.0)): # a two-frame light flash inside the second take
- frames[k] = np.clip(frames[k].astype(np.float32) + gain, 0, 255).astype(np.uint8)
- p = str(_write(frames, tmp_path / "jump.mp4"))
- shots = detect_shots(build_track(p, video_info(p)))
- assert [round(s.start, 2) for s in shots] == [0.0, 1.5]
-
-
-def test_short_insert_between_two_hard_cuts_is_kept(tmp_path):
- a, b, c = (_photo_like(W, H, s) for s in (11, 12, 13))
- frames = [a] * 30 + [b] * 4 + [c] * 30 # a 4-frame insert, the kind a fast edit or a cover frame makes
- p = str(_write(frames, tmp_path / "insert.mp4"))
- shots = detect_shots(build_track(p, video_info(p)))
- assert [s.start_frame for s in shots] == [0, 30, 34]
-
-
-def test_generated_clip_is_retimed_to_the_shot():
- assert fit_speed(4.0, 1.25) == 3.0 # a 1.25 s shot from a 4 s minimum generation: whole clip, capped speed-up
- assert abs(fit_speed(5.0, 2.5) - 2.0) < 1e-9
- assert abs(fit_speed(2.0, 4.0) - 0.8) < 1e-9 # too short: slowed a little, the rest held
- assert fit_speed(0.0, 2.0) == 1.0
-
-
-def _drift(img: np.ndarray, t: int) -> np.ndarray:
- return np.roll(img, t // 3, axis=1) # slow camera drift
-
-
-def test_wipe_transition_is_a_boundary(tmp_path):
- a = _photo_like(W, H, 21)
- b = np.clip(_photo_like(W, H, 22).astype(np.int16) + 50, 0, 255).astype(np.uint8) # another shot, another tone
- frames = [_drift(a, t) for t in range(60)]
- for k in range(1, 13): # 0.4 s wipe from the left
- f = _drift(a, 60 + k).copy()
- x = int(W * k / 12)
- f[:, :x] = _drift(b, k)[:, :x]
- frames.append(f)
- frames += [_drift(b, t) for t in range(13, 73)]
- p = str(_write(frames, tmp_path / "wipe.mp4"))
- shots = detect_shots(build_track(p, video_info(p)))
- assert len(shots) == 2 and shots[1].transition_in == "wipe" and 62 <= shots[1].start_frame <= 70
-
-
-def test_pan_across_one_picture_is_not_a_wipe(tmp_path):
- a = _photo_like(W * 3, H, 23)
- frames = [a[:, 6 * t:6 * t + W] for t in range(110)] # one long pan: the view keeps changing, no new shot
- p = str(_write(frames, tmp_path / "pan.mp4"))
- assert len(detect_shots(build_track(p, video_info(p)))) == 1
-
-
-def test_low_frame_rate_cuts_one_frame_apart(tmp_path):
- a, b, c = (_photo_like(W, H, s) for s in (31, 32, 33))
- p = str(_write([a] * 20 + [b] + [c] * 20, tmp_path / "lowfps.mp4", fps=10))
- assert detect_shots(build_track(p, video_info(p))) # 10 fps: a one-frame shot between two cuts does not crash
diff --git a/tests/test_sound_source.py b/tests/test_sound_source.py
deleted file mode 100644
index dd42ef9..0000000
--- a/tests/test_sound_source.py
+++ /dev/null
@@ -1,66 +0,0 @@
-from rea_video.sound_source import classify_sound_sources
-
-
-def _b(music=True, voice=True, whole=None, meta=None, clip=None, labels=("ai_video",) * 4, ending_curve=None, sfx=None):
- shots = [{"base": {"label": l}, "duration": 5.0} for l in labels]
- ec = ending_curve or [0.0] * 40
- return {
- "source": {"duration": 20.0, "path": "x.mp4"}, "shots": shots, "provenance": {},
- "audio": {"has_audio": True, "energy_curve": ec,
- "music": {"present": music, "ratio": 0.95 if music else 0, "start": 0.0, "end": 20.0},
- "voice": {"present": voice, "ratio": 0.6 if voice else 0}},
- "whole_video_vlm": whole or {}, "platform_meta": meta or {}, "per_clip_audio": clip or {},
- "audio_plan": {"sfx_merged": sfx or []},
- }
-
-
-def test_mv_with_lyrics_about_content_is_ai():
- w = {"format": "MV", "music": {"present": True, "has_vocals": True, "lyrics_match_content": True}, "narration": {"type": "none"}}
- r = classify_sound_sources(_b(whole=w))
- assert r["format_context"]["music_mv"] and r["music"]["source"] == "ai_generated"
-
-
-def test_ordinary_bgm_hard_cut_is_library():
- w = {"format": "知识讲解", "music": {"present": True, "has_vocals": False}, "narration": {"type": "tts"}}
- r = classify_sound_sources(_b(whole=w, ending_curve=[0.0] * 40))
- assert r["music"]["leaning"] == "existing_library" and r["music"]["ending"] == "hard_cut"
-
-
-def test_platform_music_title_wins():
- meta = {"music": {"title": "某热门歌", "author": "某歌手", "is_original": False, "popular": True}}
- r = classify_sound_sources(_b(meta=meta))
- assert r["music"]["leaning"] == "popular_song"
-
-
-def test_native_clip_audio_means_ai_sfx_and_voice():
- clip = {"ratio": 2.4, "resets_at_cuts": True, "at_cuts_db": 20.0, "within_shots_db": 8.0}
- r = classify_sound_sources(_b(music=False, clip=clip))
- assert r["sfx"]["leaning"] == "ai_native"
- assert r["voice"]["leaning"] == "ai_video_native"
-
-
-def test_editor_sfx_synced_to_cuts():
- sfx = [{"t": 1.0, "sync_with": "cut"}, {"t": 2.0, "sync_with": "text_pop"}, {"t": 3.0, "sync_with": "none"}]
- r = classify_sound_sources(_b(sfx=sfx, labels=("code_render",) * 4))
- assert r["sfx"]["leaning"] == "library_editor"
-
-
-def test_sung_vocals_without_vlm_lean_ai_but_tts_narration_does_not():
- b = _b()
- b["audio"]["voice"].update({"style": "singing", "sung": True, "sustained_note_ratio": 0.44})
- r = classify_sound_sources(b)
- assert r["format_context"]["music_mv_maybe"] and r["music"]["leaning"] == "ai_generated"
- b = _b()
- b["audio"]["voice"].update({"style": "speech", "sung": False, "sustained_note_ratio": 0.15})
- r = classify_sound_sources(b)
- assert not r["format_context"]["music_mv_maybe"] and r["music"]["leaning"] == "existing_library"
-
-
-def test_prior_alone_is_only_a_leaning():
- # no VLM, no platform tag: an instrumental bed under narration leans library but is not called library
- r = classify_sound_sources(_b(ending_curve=[0.0] * 40))
- assert r["music"]["leaning"] == "existing_library" and r["music"]["source"] == "unknown"
- assert "待确认" in r["summary_zh"] or "to confirm" in r["summary_zh"]
- w = {"music": {"present": True, "has_vocals": False, "source_guess": "ai_generated"}, "narration": {"type": "tts"}}
- r = classify_sound_sources(_b(whole=w))
- assert r["music"]["leaning"] == "ai_generated" # heard as AI: beats the library prior and the hard-cut ending
diff --git a/tests/test_speakers.py b/tests/test_speakers.py
deleted file mode 100644
index 973fd2c..0000000
--- a/tests/test_speakers.py
+++ /dev/null
@@ -1,106 +0,0 @@
-"""Speaker separation: grouping, merging, turn bookkeeping and how the result reaches the script and the report.
-No model is loaded: voices are made-up unit vectors."""
-import numpy as np
-
-from rea_video import speakers
-from rea_video.entities import script
-from rea_video.report import _speakers_md
-from rea_video.speech import SR, _by_speaker
-
-
-def _voice(axis: int, rng, spread: float = 0.12, dim: int = 16) -> np.ndarray:
- v = rng.normal(0, spread, dim)
- v[axis] += 1.0
- return (v / np.linalg.norm(v)).astype(np.float32)
-
-
-def test_pieces_of_three_voices_group_into_three():
- rng = np.random.default_rng(0)
- truth = [0, 1, 2, 0, 1, 2, 0, 0, 1, 2, 2, 1] * 3
- V = np.stack([_voice(k, rng) for k in truth])
- labels = speakers._settle(V, speakers.group_pieces(V))
- assert len(set(labels.tolist())) == 3
- for k in range(3): # every true voice sits in one group
- assert len({labels[i] for i, t in enumerate(truth) if t == k}) == 1
- # a named head count is honoured
- assert len(set(speakers.group_pieces(V, k=2).tolist())) == 2
-
-
-def test_one_voice_split_three_ways_is_merged_step_by_step_and_a_stray_moment_folded():
- # voice A arrives as three groups (0, 1, 2): 0-1 and 1-2 sound alike, 0-2 only after the first merge
- # voice B is group 3; group 4 is 0.8 s of something nearer to B than to anything else
- turns = [(0, 6, 0), (6, 12, 1), (12, 18, 2), (18, 30, 3), (30, 30.8, 4), (31, 37, 0)]
- base = {0: [1.0, 0.0, 0.0], 1: [0.8, 0.6, 0.0], 2: [0.45, 0.9, 0.0], 3: [0.0, 0.0, 1.0], 4: [0.0, 0.5, 0.86]}
-
- def measure(ranges):
- if not ranges:
- return None
- groups = {s for a, b, s in turns for x, y in ranges if a <= x and y <= b}
- v = np.sum([base[g] for g in groups], axis=0).astype(np.float32)
- return v / np.linalg.norm(v)
-
- out = speakers.regroup(turns, measure)
- assert len({s for _, _, s in out}) == 2
- assert len({s for a, _, s in out if a < 18 or a >= 31}) == 1 # all of A together
- assert {s for a, _, s in out if a == 30} == {s for a, _, s in out if a == 18} # the stray moment went to B
- # asked for a fixed number of speakers: nothing is merged
- assert speakers.regroup(turns, measure, fixed=True) == turns
-
-
-def test_turns_are_numbered_by_first_appearance_and_joined_across_short_gaps():
- turns = speakers._tidy([(5.0, 7.0, 9), (0.0, 2.0, 4), (2.2, 4.0, 4), (7.0, 7.1, 4), (6.5, 9.0, 4)])
- assert [(t["speaker"], t["start"], t["end"]) for t in turns] == [("S1", 0.0, 4.0), ("S2", 5.0, 7.0), ("S1", 6.5, 9.0)]
- assert speakers.overlaps(turns) == [[6.5, 7.0]]
- assert speakers.speaker_at(turns, 5.0, 6.4) == "S2" and speakers.speaker_at(turns, 20, 21) == ""
- # one stretch of speech 3.0-8.0 holds a change of speaker: cut in the middle of the gap between the turns
- assert speakers.change_points(turns[:2], 3.0, 8.0) == [4.5]
- assert speakers.change_points(turns[:2], 3.0, 4.6) == [] # the second piece would be too short to recognise
-
-
-def test_speech_is_cut_at_the_speaker_change():
- turns = [{"start": 0.0, "end": 2.0, "speaker": "S1"}, {"start": 2.0, "end": 5.0, "speaker": "S2"}]
- stretch = (0.0, np.zeros(5 * SR, np.float32))
- pieces = _by_speaker([stretch], turns)
- assert [(round(t, 2), len(x)) for t, x in pieces] == [(0.0, 2 * SR), (2.0, 3 * SR)]
- assert _by_speaker([stretch], None) == [stretch]
-
-
-def test_voices_take_the_names_a_viewer_gave_them():
- who = {"speakers": [{"id": "S1"}, {"id": "S2"}, {"id": "S3"}],
- "turns": [{"start": 0, "end": 4, "speaker": "S1"}, {"start": 4, "end": 9, "speaker": "S2"},
- {"start": 9, "end": 10, "speaker": "S3"}, {"start": 10, "end": 14, "speaker": "S1"}]}
- lines = [{"start": 0, "end": 4, "speaker": "店主", "text": "a"}, {"start": 4, "end": 9, "speaker": "顾客", "text": "b"},
- {"start": 9, "end": 10.2, "speaker": "顾客", "text": "c"}, {"start": 10.2, "end": 14, "speaker": "店主", "text": "d"}]
- speakers.name_speakers(who, lines)
- assert [sp.get("name") for sp in who["speakers"]] == ["店主", "顾客", None] # 顾客 is taken by the voice it fits best
-
-
-def _breakdown() -> dict:
- return {"speakers": {"ok": True, "count": 2, "tracks": {"S1": "voice_S1.wav", "S2": "voice_S2.wav"}, "overlaps": [[3.8, 4.1]],
- "speakers": [{"id": "S1", "seconds": 8.0, "share": 0.62, "turns": 2, "first": 0.0, "f0_median_hz": 120.0,
- "gender_hint": "male"},
- {"id": "S2", "seconds": 5.0, "share": 0.38, "turns": 1, "first": 4.0, "name": "顾客"}],
- "turns": [{"start": 0, "end": 4, "speaker": "S1"}, {"start": 4, "end": 9, "speaker": "S2"},
- {"start": 9, "end": 13, "speaker": "S1"}]},
- "speech": {"ok": True, "lines": [{"start": 0.2, "end": 3.9, "text": "欢迎光临", "speaker": "S1"},
- {"start": 4.1, "end": 8.8, "text": "这个怎么卖", "speaker": "S2"}]}}
-
-
-def test_script_and_report_name_the_separated_voices():
- b = _breakdown()
- rows = script(b)
- assert [(r["speaker"], r["voice"]) for r in rows] == [("说话人 1", "S1"), ("顾客", "S2")]
- md = "\n".join(_speakers_md(b))
- assert "2 个声音" in md and "stems/voice_S1.wav" in md and "顾客" in md and "同时说话" in md
- # a VLM script keeps its own names and gains the voice id
- b["whole_video_vlm"] = {"narration": {"lines": [{"start": 0.0, "end": 4.0, "speaker": "店主", "text": "欢迎光临"}]}}
- assert script(b) == [{"start": 0.0, "end": 4.0, "speaker": "店主", "text": "欢迎光临", "voice": "S1"}]
- # one voice only: nothing to tell apart, nothing printed
- b["speakers"]["speakers"] = b["speakers"]["speakers"][:1]
- b["speakers"]["count"] = 1
- assert _speakers_md(b) == [] and "voice" not in script({**b, "whole_video_vlm": {}})[0]
-
-
-def test_diarize_without_the_extra_says_so(monkeypatch, tmp_path):
- monkeypatch.setattr(speakers, "available", lambda: False)
- assert speakers.diarize(tmp_path / "none.wav") == {"ok": False, "reason": "not_installed"}
diff --git a/tests/test_speech.py b/tests/test_speech.py
deleted file mode 100644
index c28880c..0000000
--- a/tests/test_speech.py
+++ /dev/null
@@ -1,61 +0,0 @@
-"""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))
diff --git a/tests/test_stems.py b/tests/test_stems.py
deleted file mode 100644
index e09f412..0000000
--- a/tests/test_stems.py
+++ /dev/null
@@ -1,42 +0,0 @@
-import numpy as np
-
-from rea_video import stems as S
-
-
-def test_stft_roundtrip_matches_input():
- rng = np.random.default_rng(0)
- x = (rng.standard_normal((2, S.CHUNK)) * 0.1).astype(np.float32)
- y = S._istft(S._stft(x))
- mid = slice(S.TRIM, -S.TRIM)
- err = np.abs(y[:, mid] - x[:, mid]).std() / x.std()
- assert y.shape == x.shape and err < 0.02 # only the top bins above DIM_F are dropped
-
-
-def test_extract_stems_without_audio(tmp_path):
- assert S.extract_stems(tmp_path / "missing.mp4", tmp_path)["ok"] is False
-
-
-def test_ensure_model_rejects_partial_download_and_leaves_no_temp(tmp_path, monkeypatch):
- import pytest
-
- monkeypatch.setenv("REA_VIDEO_MODELS", str(tmp_path))
- 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()) == []
-
-
-def test_ensure_model_uses_unique_temp_names(tmp_path, monkeypatch):
- monkeypatch.setenv("REA_VIDEO_MODELS", str(tmp_path))
- seen = []
- monkeypatch.setattr(S, "MODEL_SHA256", __import__("hashlib").sha256(b"model").hexdigest())
-
- def fake(url, dst):
- seen.append(dst.name)
- with open(dst, "wb") as f:
- f.write(b"model")
-
- 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"
diff --git a/tests/test_transcode.py b/tests/test_transcode.py
deleted file mode 100644
index 0977c1f..0000000
--- a/tests/test_transcode.py
+++ /dev/null
@@ -1,139 +0,0 @@
-from rea_video.classify import deterministic, video_context
-
-PHOTO = {"noise_sigma": 0.5, "temporal_noise": 1.2, "flat_ratio": 0.02, "palette95": 220, "axis_edge_ratio": 0.2,
- "dup_ratio": 0.0, "moving_pair_ratio": 1.0, "zero_pixel_ratio": 0.1, "camera": "smooth_move", "saturation": 0.3}
-PROV_WECHAT = {"hints": {"platform": ["WeChat transcode"], "generator": [], "camera": []}}
-PROV_DOUYIN = {"hints": {"platform": ["Douyin/TikTok"], "generator": [], "camera": []}}
-
-
-def _shots(dup):
- return [{"duration": 3.0, "features": dict(PHOTO, dup_ratio=dup)} for _ in range(3)]
-
-
-def test_video_context_native30_only_without_pulldown():
- assert video_context(_shots(0.0), PROV_WECHAT, 30.0)["native30"] is True
- assert video_context(_shots(0.2), PROV_WECHAT, 30.0)["native30"] is False
- assert video_context(_shots(0.0), PROV_WECHAT, 24.0)["native30"] is False
-
-
-def test_transcoded_phone_footage_is_not_called_ai():
- ctx = video_context(_shots(0.0), PROV_WECHAT, 30.0)
- probs, ev, facts = deterministic(PHOTO, provenance=PROV_WECHAT, fps=30.0, ctx=ctx)
- assert probs["live_action"] > probs["ai_video"]
- assert facts["transcode_degraded"]
-
-
-def test_transcoded_ai_with_pulldown_stays_ai():
- f = dict(PHOTO, dup_ratio=0.2, dup_period=5, dup_regularity=0.6)
- ctx = video_context(_shots(0.2), PROV_WECHAT, 30.0)
- probs, _, _ = deterministic(f, provenance=PROV_WECHAT, fps=30.0, ctx=ctx)
- assert probs["ai_video"] > probs["live_action"]
-
-
-def test_gray_ui_is_not_3d():
- ui = {"noise_sigma": 0.1, "temporal_noise": 0.2, "flat_ratio": 0.65, "palette95": 3, "axis_edge_ratio": 0.27,
- "dup_ratio": 0.2, "moving_pair_ratio": 1.0, "zero_pixel_ratio": 0.9, "saturation": 0.006}
- probs, _, facts = deterministic(ui)
- assert facts["ui_gray"] > 0.5 and probs["code_render"] > probs["cg_3d"]
-
-
-def test_transcoded_ai_or_live_without_decisive_evidence_is_flagged():
- from rea_video.pipeline import _ai_or_live_doubt
-
- t = {"transcode_degraded": True, "pulldown": "24→30"}
- assert _ai_or_live_doubt("ai_video", t, {}, {}) and _ai_or_live_doubt("live_action", t, {}, {"native30": False})
- assert _ai_or_live_doubt("ai_video", t, {"aigc": {"label": "1"}}, {}) is None # AIGC label settles it
- assert _ai_or_live_doubt("live_action", {"transcode_degraded": True}, {}, {"native30": True}) is None # phone camera
- assert _ai_or_live_doubt("ai_video", {"pulldown": "24→30"}, {}, {}) is None # not transcoded: noise evidence works
- assert _ai_or_live_doubt("cg_3d", t, {}, {}) is None
-
-
-def test_native_cadence_is_per_shot():
- # mixed edit: AI opener with 24->30 pulldown, then phone footage without; the whole-file flag is off
- shots = _shots(0.2)[:2] + _shots(0.0)
- ctx = video_context(shots, PROV_DOUYIN, 30.0)
- assert ctx["native30"] is False
- _, _, live = deterministic(dict(PHOTO, noise_sigma=0.4, sharp_period_ac=0.6), provenance=PROV_DOUYIN, fps=30.0, ctx=ctx)
- assert live["native_cadence"] is True # GOP sharpness rhythm of a re-encode does not count against it
- _, _, ai = deterministic(dict(PHOTO, dup_ratio=0.2, dup_period=5, dup_regularity=0.6), provenance=PROV_DOUYIN, fps=30.0, ctx=ctx)
- assert ai["native_cadence"] is False and ai["pulldown"] == "24→30"
- _, _, f24 = deterministic(PHOTO, provenance=PROV_DOUYIN, fps=24.0, ctx=ctx)
- assert f24["native_cadence"] is False
-
-
-def test_reviewer_live_call_passes_on_shot_with_camera_cadence():
- from rea_video.pipeline import _ai_or_live_doubt, _vlm_gate
-
- live = {"live_action": 0.9, "ai_video": 0.1}
- rec = {"deterministic": {"probs": {"ai_video": 0.47, "live_action": 0.39, "cg_3d": 0.1, "avatar": 0.04},
- "facts": {"transcode_degraded": True, "native_cadence": True, "pulldown": None}},
- "review": {"label_probs": live}}
- assert _vlm_gate(rec, live, {"native30": False}) == live
- rec["deterministic"]["facts"].update(native_cadence=False, pulldown="24→30")
- assert _vlm_gate(rec, live, {"native30": False}) is None
- # and the verdict is not flagged "to confirm" once the shot has cadence and a reader saw filmed footage
- t = {"transcode_degraded": True, "native_cadence": True}
- assert _ai_or_live_doubt("live_action", t, {}, {"native30": False}, seen_live=0.9) is None
- assert _ai_or_live_doubt("live_action", t, {}, {"native30": False}, seen_live=0.0) # tools alone: still to confirm
- assert "24fps" in _ai_or_live_doubt("live_action", {"transcode_degraded": True, "pulldown": "24→30"}, {}, {"native30": False})
-
-
-def test_reader_decides_when_tools_are_undecided():
- from rea_video.pipeline import _vlm_gate
-
- live = {"live_action": 0.9, "ai_video": 0.1}
- facts = {"transcode_degraded": True, "native_cadence": True}
- rec = {"deterministic": {"probs": {"cg_3d": 0.35, "ai_video": 0.27, "live_action": 0.22, "code_render": 0.09}, "facts": facts},
- "vlm": {"label_probs": live}}
- assert _vlm_gate(rec, live, {"native30": False}) == live # 3D 0.35 / AI 0.27 / live 0.22 is no call
- rec["deterministic"]["probs"] = {"cg_3d": 0.45, "ai_video": 0.27, "live_action": 0.22, "code_render": 0.06}
- assert _vlm_gate(rec, live, {"native30": False}) is None # a 0.45 lead is a call: live must be in the top two
- rec["deterministic"]["probs"] = {"cg_3d": 0.35, "ai_video": 0.3, "live_action": 0.12, "code_render": 0.23}
- assert _vlm_gate(rec, live, {"native30": False}) is None # the reader's pick trails by too much
- # an agent review alone may still make that call when fusing lands on its pick (see test_aspects)
- rec = {"deterministic": rec["deterministic"], "review": {"label_probs": live}}
- assert _vlm_gate(rec, live, {"native30": False}) == live
-
-
-def test_sharpness_rhythm_alone_is_weak_evidence():
- # a re-encode with its platform tags stripped: no duplicate frames, only a sharpness rhythm
- f = dict(PHOTO, noise_sigma=0.5, sharp_period_ac=0.68, sharp_period=4)
- probs, ev, facts = deterministic(f, provenance={}, fps=30.0, ctx={})
- assert facts["pulldown"] == "interpolated"
- assert not any("重复帧呈" in e or "Duplicate frames follow" in e for e in ev) # no "duplicate frames" claim at 0%
- dup, _, _ = deterministic(dict(PHOTO, dup_ratio=0.2, dup_period=5, dup_regularity=0.6), provenance={}, fps=30.0, ctx={})
- assert probs["ai_video"] < dup["ai_video"] # weaker than real 24->30 duplicate frames
-
-
-def test_reviewer_overrides_sharpness_rhythm_only_call():
- from rea_video.pipeline import _ai_or_live_doubt, _vlm_gate
-
- live = {"live_action": 0.9, "ai_video": 0.1}
- rec = {"deterministic": {"probs": {"ai_video": 0.86, "live_action": 0.05, "cg_3d": 0.05, "avatar": 0.04},
- "facts": {"pulldown": "interpolated"}},
- "review": {"label_probs": live}}
- assert _vlm_gate(rec, live, {}) == live
- rec["deterministic"]["facts"]["pulldown"] = "24→30"
- assert _vlm_gate(rec, live, {}) is None # duplicate-frame pulldown still protects the tools' call
- assert _ai_or_live_doubt("ai_video", {"pulldown": "interpolated"}, {}, {})
- assert _ai_or_live_doubt("ai_video", {"pulldown": "interpolated"}, {"hints": {"generator": ["Kling"]}}, {}) is None
-
-
-def test_transcoded_native30_shot_counts_as_phone_footage():
- # native 30fps file, this shot has no duplicate frames, platform transcode wiped the noise
- ctx = video_context(_shots(0.0), PROV_DOUYIN, 30.0)
- f = dict(PHOTO, noise_sigma=0.45, temporal_noise=0.5, zero_pixel_ratio=0.6, camera="static")
- probs, _, facts = deterministic(f, provenance=PROV_DOUYIN, fps=30.0, ctx=ctx)
- assert facts["transcode_degraded"] and facts["native_cadence"]
- assert probs["live_action"] > probs["ai_video"]
-
-
-def test_clean_picture_alone_is_not_enough_for_ai_without_an_image_reader():
- from rea_video.pipeline import _ai_or_live_doubt
-
- clean = {"pulldown": None, "transcode_degraded": False}
- # 30 fps download whose platform tags are gone: only "little noise" says AI
- assert _ai_or_live_doubt("ai_video", clean, {}, {"fps": 30.0}, seen=False)
- assert _ai_or_live_doubt("ai_video", clean, {}, {"fps": 30.0}, seen=True) is None # an image reader looked
- assert _ai_or_live_doubt("ai_video", clean, {}, {"fps": 24.0}, seen=False) is None # native 24 fps: generator rate
- assert _ai_or_live_doubt("ai_video", clean, {"hints": {"generator": ["Kling"]}}, {"fps": 30.0}, seen=False) is None
diff --git a/tests/test_transitions.py b/tests/test_transitions.py
deleted file mode 100644
index e740642..0000000
--- a/tests/test_transitions.py
+++ /dev/null
@@ -1,173 +0,0 @@
-"""Transitions: what kind, which way, how long; and the cases that must stay one shot."""
-import cv2
-import numpy as np
-
-from rea_video import transitions
-from rea_video.media import video_info
-from rea_video.report import transition_text
-from rea_video.shots import build_track, detect_shots
-from rea_video.videomd import _transition_in
-from tests.conftest import _photo_like, _write
-
-W, H, FPS = 360, 640, 30
-
-
-def _drift(img: np.ndarray, t: int) -> np.ndarray:
- return np.roll(img, t // 3, axis=1) # slow camera drift
-
-
-def _two(seed: int) -> tuple[np.ndarray, np.ndarray]:
- a = _photo_like(W, H, seed)
- b = np.clip(_photo_like(W, H, seed + 1).astype(np.int16) + 45, 0, 255).astype(np.uint8) # another shot, another tone
- return a, b
-
-
-def _clip(a: np.ndarray, b: np.ndarray, middle: list[np.ndarray], hold: int = 60) -> list[np.ndarray]:
- """a drifting up to where the transition frames pick it up, the transition, b drifting on."""
- return [_drift(a, t - hold) for t in range(hold)] + middle + [_drift(b, t) for t in range(hold)]
-
-
-def _shots(frames, tmp_path, name: str):
- p = str(_write(frames, tmp_path / f"{name}.mp4", FPS))
- return detect_shots(build_track(p, video_info(p)))
-
-
-def test_push_slide_has_kind_direction_and_length(tmp_path):
- a, b = _two(41)
- mid = []
- for k in range(1, 13): # 0.4 s: both pictures travel left, the new one coming in from the right
- d = int(W * k / 13)
- mid.append(np.concatenate([a[:, d:], b[:, :d]], axis=1))
- shots = _shots(_clip(a, b, mid), tmp_path, "push")
- assert len(shots) == 2
- tr = shots[1].to_dict()["transition"]
- assert tr["type"] == "slide" and tr["mode"] == "push" and tr["direction"] == "left"
- assert 0.25 <= tr["duration"] <= 0.6 and 1.9 <= tr["start"] <= 2.1
- assert "推移" in transition_text(tr) and "向左" in transition_text(tr)
- assert _transition_in(shots[1].to_dict())["type"] == "slide"
-
-
-def test_iris_wipe_opens_from_the_centre(tmp_path):
- a, b = _two(43)
- yy, xx = np.mgrid[0:H, 0:W]
- rad = np.hypot(xx - W / 2, yy - H / 2)
- mid = [np.where((rad < rad.max() * k / 16)[..., None], b, a) for k in range(1, 16)]
- shots = _shots(_clip(a, b, mid), tmp_path, "iris")
- assert len(shots) == 2 and shots[1].transition_in == "wipe"
- assert shots[1].transition.get("direction") == "center_out"
-
-
-def test_fade_through_black_is_one_transition(tmp_path):
- a, b = _two(45)
- black = np.zeros_like(a)
- mid = [cv2.addWeighted(a, 1 - k / 8, black, k / 8, 0) for k in range(1, 8)] + [black] * 5 \
- + [cv2.addWeighted(b, k / 8, black, 1 - k / 8, 0) for k in range(1, 8)]
- shots = _shots(_clip(a, b, mid), tmp_path, "fade")
- assert len(shots) == 2 and shots[1].transition_in == "fade" and shots[1].transition["via"] == "black"
- assert shots[1].to_dict()["transition"]["duration"] >= 0.4
-
-
-def test_whip_pan_hides_the_cut(tmp_path):
- a, b = _two(47)
- mid = []
- for k in range(12): # the old shot streaks off to the left, the new one streaks in and settles
- u = (k + 0.5) / 12
- src, pos = (a, u * u * 4 * W * 0.6) if u < 0.5 else (b, -(1 - u) ** 2 * 4 * W * 0.6)
- f = np.roll(src, -int(pos), axis=1)
- n = max(3, int(60 * np.sin(np.pi * u)))
- mid.append(cv2.blur(f, (n, 1)))
- shots = _shots(_clip(a, b, mid), tmp_path, "whip")
- assert len(shots) == 2 and shots[1].transition_in == "whip"
-
-
-def test_dissolve_inside_a_letterboxed_picture(tmp_path):
- a, b = _two(49)
- bar = int(H * 0.32)
-
- def boxed(f: np.ndarray) -> np.ndarray:
- g = f.copy()
- g[:bar] = 0
- g[H - bar:] = 0
- return g
-
- mid = [cv2.addWeighted(a, 1 - k / 16, b, k / 16, 0) for k in range(1, 16)]
- frames = [boxed(f) for f in _clip(a, b, mid)]
- p = str(_write(frames, tmp_path / "boxed.mp4", FPS))
- track = build_track(p, video_info(p))
- y0, y1, _, _ = transitions.crop_box(track.thumbs)
- h = track.thumbs[0].shape[0]
- assert 0.25 * h < y0 < 0.4 * h and 0.6 * h < y1 < 0.75 * h # the bars are left out
- shots = detect_shots(track)
- assert len(shots) == 2 and shots[1].transition_in == "dissolve"
- assert 0.3 <= shots[1].to_dict()["transition"]["duration"] <= 0.7
-
-
-def test_plain_cut_carries_no_transition_details(tmp_path):
- a, b = _two(51)
- shots = _shots(_clip(a, b, []), tmp_path, "cut")
- assert len(shots) == 2 and shots[1].transition_in == "cut" and "transition" not in shots[1].to_dict()
- assert _transition_in(shots[1].to_dict()) == {}
-
-
-def test_light_change_and_a_hold_pan_hold_stay_one_shot(tmp_path):
- a = _photo_like(W * 2, H, 53)
- # the lamp comes up over half a second: same scene, brighter
- lit = [np.clip(a[:, :W].astype(np.float32) * (1 + 0.6 * min(1.0, max(0.0, (t - 50) / 15))), 0, 255).astype(np.uint8)
- for t in range(120)]
- assert len(_shots(lit, tmp_path, "lamp")) == 1
- # hold, a slow pan across the same wide picture, hold: movement, not a new shot
- pan = [a[:, :W]] * 40 + [a[:, 4 * t:4 * t + W] for t in range(1, 40)] + [a[:, 160:160 + W]] * 40
- assert len(_shots(pan, tmp_path, "pan")) == 1
-
-
-def test_edge_composition_directions():
- a = np.zeros((8, 10), np.float32)
- b = np.ones((8, 10), np.float32)
- left = transitions._compose(a, b, "wipe", "left", 3) # the edge travels left: the new picture grows from the right
- assert left[:, :7].sum() == 0 and left[:, 7:].all()
- down = transitions._compose(a, b, "wipe", "down", 2) # the edge travels down: the new picture grows from the top
- assert down[:2].all() and down[2:].sum() == 0
- ramp = np.tile(np.arange(10, dtype=np.float32), (8, 1))
- push = transitions._compose(ramp, ramp + 100, "push", "left", 4)
- assert push[0].tolist() == [4, 5, 6, 7, 8, 9, 100, 101, 102, 103]
-
-
-def test_push_in_on_a_page_stays_one_shot(tmp_path):
- page = np.full((H * 3, W * 3, 3), 245, np.uint8)
- rng = np.random.default_rng(5)
- for _ in range(140): # a page of blocks and lines
- x, y = int(rng.integers(0, W * 3 - 120)), int(rng.integers(0, H * 3 - 40))
- cv2.rectangle(page, (x, y), (x + int(rng.integers(30, 120)), y + int(rng.integers(8, 40))),
- tuple(int(c) for c in rng.integers(30, 220, 3)), -1)
-
- def view(scale: float) -> np.ndarray:
- w, h = int(W * 3 / scale), int(H * 3 / scale)
- x0, y0 = (W * 3 - w) // 2, (H * 3 - h) // 2
- return cv2.resize(page[y0:y0 + h, x0:x0 + w], (W, H), interpolation=cv2.INTER_AREA)
-
- frames = [view(1.0)] * 45 + [view(1.0 + 1.6 * k / 18) for k in range(1, 18)] + [view(2.6)] * 45
- assert len(_shots(frames, tmp_path, "pushin")) == 1
-
-
-def test_still_background_is_not_a_border():
- rng = np.random.default_rng(7)
- back = cv2.resize(rng.integers(0, 255, (20, 12)).astype(np.uint8), (96, 170), interpolation=cv2.INTER_CUBIC)
- thumbs = []
- for t in range(60): # one shot: only a small figure moves in front of a still, detailed background
- f = back.copy()
- cv2.circle(f, (40 + t // 4, 80), 12, 255, -1)
- thumbs.append(f)
- assert transitions.crop_box(thumbs) == (0, 170, 0, 96)
- boxed = [np.pad(f[40:130], ((40, 40), (0, 0))) for f in thumbs] # the same picture between plain black bars
- y0, y1, _, _ = transitions.crop_box(boxed)
- assert (y0, y1) == (40, 130)
-
-
-def test_a_labelled_cut_inside_a_transition_counts_as_found():
- from rea_video.evaluate import boundary_f1
-
- # the detector puts a half-second wipe at 10.0 (9.8-10.3); the labeller marked 10.25
- assert boundary_f1([10.0], [10.25])["tp"] == 0
- assert boundary_f1([10.0], [10.25], spans=[(9.8, 10.3)])["tp"] == 1
- assert boundary_f1([10.0, 12.0], [10.25, 12.05], spans=[(9.8, 10.3), None]) | {} == {
- "precision": 1.0, "recall": 1.0, "f1": 1.0, "tp": 2, "fp": 0, "fn": 0}
diff --git a/tests/test_videomd.py b/tests/test_videomd.py
deleted file mode 100644
index 06f9db9..0000000
--- a/tests/test_videomd.py
+++ /dev/null
@@ -1,240 +0,0 @@
-"""VIDEO.md, the package a model reads: a small card, a map, one line per shot, one file per shot, all consistent."""
-import json
-import re
-
-import videomd as spec
-
-from rea_video import videomd
-from rea_video.i18n import set_lang
-from rea_video.report import write_reports
-
-from test_report import _with_vlm, breakdown # noqa: F401 (fixture)
-
-
-def test_package_levels_and_map(breakdown, tmp_path): # noqa: F811
- b, out = breakdown
- set_lang("zh")
- write_reports(_with_vlm(b), out)
- card, body = spec.read_file(out / videomd.ENTRY)
- # L0: the card is small and says what the video is and how sure
- assert card["videomd"] == videomd.VERSION and card["generator"]["name"] == "rea-video" and card["shots"] == len(b["shots"]) and card["description"]
- assert videomd.tokens(json.dumps(card, ensure_ascii=False)) < 300
- assert abs(sum(card["made_mix"].values()) - 1) < 0.02
- # L1: every file the map names exists; sizes are given so a reader can choose
- rows = [x["path"] for x in spec.read(out)["map"]]
- assert "video/timeline.md" in rows and "video/shots/*.md" in rows and "breakdown.json" in rows
- assert card["name"] == videomd.slug(card["name"]) and len(card["description"]) <= 1024
- for p in out.glob("video/*.md"):
- fm, text = spec.read_file(p)
- assert fm["videomd"] == videomd.VERSION and fm["tokens"] > 0 and "<details>" not in text
- assert len(list((out / "video" / "shots").glob("*.md"))) == len(b["shots"])
-
-
-def test_timeline_lines_parse_and_mark_inference(breakdown): # noqa: F811
- b, out = breakdown
- set_lang("zh")
- write_reports(_with_vlm(b), out)
- pkg = videomd.read(out)
- tl = pkg["timeline"]
- assert [x["shot"] for x in tl] == [r["index"] for r in b["shots"]]
- for x, r in zip(tl, b["shots"]):
- assert abs(x["start"] - r["start"]) < 0.06 and x["made~"].startswith(r["base"]["label_zh"])
- assert set(x) - {"shot", "start", "end"} <= set(videomd.KEYS)
- # the per-shot front matter is the machine view of the same verdict
- for r in b["shots"]:
- fm = pkg["shots"][r["index"]]
- assert fm["inferred"]["made"] == r["base"]["label"] and fm["frames"].get("sheet") == r["assets"]["sheet"]
-
-
-def test_shot_line_escapes_separators():
- assert videomd._one_line("a | b|c\nd") == "a / b/c d"
- assert videomd.slug("Salted_Egg 最终版") == "salted-egg" and videomd.slug("最终版") == "video"
-
-
-def test_rewrite_drops_stale_shot_files(breakdown, tmp_path): # noqa: F811
- b, out = breakdown
- set_lang("zh")
- (out / "video" / "shots").mkdir(parents=True, exist_ok=True)
- (out / "video" / "shots" / "99.md").write_text("old", encoding="utf-8")
- videomd.write(b, out)
- assert not (out / "video" / "shots" / "99.md").exists()
-
-
-def test_neutral_ids_in_the_package(breakdown): # noqa: F811
- b, out = breakdown
- set_lang("zh")
- write_reports(_with_vlm(b), out)
- pkg = videomd.read(out)
- assert set(pkg["card"]["readers"]) <= {"tools", "model", "agent", "human"}
- for fm in pkg["shots"].values():
- assert fm["inferred"]["decided_by"] in {"tools", "model", "agent", "human"} and "huazi" not in fm.get("overlays", [])
-
-
-def test_english_package(breakdown, tmp_path): # noqa: F811
- b, _ = breakdown
- out = tmp_path / "en"
- out.mkdir()
- try:
- set_lang("en")
- videomd.write(b, out)
- finally:
- set_lang("zh")
- _, body = spec.read_file(out / videomd.ENTRY)
- # the package's own words follow the language (the verdict keeps the language the breakdown was made in)
- assert "## Map" in body and "## How to read" in body and "Each line is `path | ~tokens |" in body
-
-
-def test_check_accepts_a_written_package_and_names_what_breaks(breakdown, tmp_path): # noqa: F811
- import shutil
-
- b, out = breakdown
- set_lang("zh")
- write_reports(_with_vlm(b), out)
- assert videomd.check(out) == []
- bad = tmp_path / "bad"
- shutil.copytree(out, bad)
- p = bad / "video" / "shots" / "01.md"
- p.write_text(p.read_text(encoding="utf-8").replace("made: ", "made: not_a_label # ", 1), encoding="utf-8")
- (bad / "video" / "shots" / "02.md").unlink()
- errs = videomd.check(bad)
- assert any("01.md" in e and "made" in e for e in errs) and any("02.md missing" in e for e in errs)
-
-
-def test_pdf_needs_a_report_and_a_browser(tmp_path, monkeypatch):
- import pytest
-
- from rea_video import pdf
-
- with pytest.raises(RuntimeError, match="report.html"):
- pdf.write_pdf(tmp_path)
- (tmp_path / "report.html").write_text("<details><summary>x</summary>y</details>", encoding="utf-8")
- monkeypatch.setattr(pdf, "find_browser", lambda: None)
- with pytest.raises(RuntimeError, match="Chrome"):
- pdf.write_pdf(tmp_path)
- assert not (tmp_path / ".report_print.html").exists()
-
-
-def test_sound_effects_are_cut_for_listening(tmp_path):
- import subprocess
-
- from rea_video.report import _inline
- from rea_video.stems import cut_sfx
-
- src = tmp_path / "tone.wav"
- subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i", "sine=f=880:d=3", str(src)], check=True)
- sfx = [{"t": 0.5, "dur": 0.1}, {"t": 2.2, "dur": 0.4}]
- assert cut_sfx(src, sfx, tmp_path) == 2 and sfx[1]["clip"] == "sfx/sfx_02.wav" and (tmp_path / "sfx/sfx_02.wav").is_file()
- assert cut_sfx(tmp_path / "missing.mp4", sfx, tmp_path) == 0 and "clip" not in sfx[0] # stale clips go away
- assert '<audio controls preload="none" src="sfx/sfx_01.wav"' in _inline("[试听](sfx/sfx_01.wav)")
- assert '<a href="https://x.org/a">' in _inline("[x](https://x.org/a)")
-
-
-def test_effects_found_on_their_own_track(tmp_path):
- import subprocess
-
- import numpy as np
-
- from rea_video import effects
-
- sr = effects.SR
- y = np.zeros(sr * 4, np.float32)
- for t in (0.5, 1.6, 3.0): # three short bursts on a silent effects track
- a = int(t * sr)
- y[a:a + int(0.05 * sr)] = np.random.default_rng(1).normal(0, 0.3, int(0.05 * sr))
- y[int(1.75 * sr):int(1.8 * sr)] = 0.2 # a second attack right after the second burst: the same effect
- p = tmp_path / "effects.wav"
- subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "f32le", "-ar", str(sr), "-ac", "1", "-i", "-", str(p)], input=y.tobytes(), check=True)
- ev = effects.detect(p)
- assert [round(e["t"], 1) for e in ev] == [0.5, 1.6, 3.0]
- assert all(e["source"] == "effects_stem" and e["type"] in ("click", "pop", "ding", "whoosh", "impact", "other") for e in ev)
-
-
-def test_effects_separation_degrades_without_a_model(tmp_path, monkeypatch):
- import sys
- import types
-
- from rea_video import effects
-
- monkeypatch.setitem(sys.modules, "onnxruntime", types.SimpleNamespace(InferenceSession=lambda *a, **k: None))
- monkeypatch.setattr(effects, "ensure_model", lambda: (_ for _ in ()).throw(OSError("offline")))
- got = effects.extract_effects(tmp_path / "x.wav", tmp_path)
- assert got["ok"] is False and "offline" in got["reason"]
-
-
-def test_the_same_effect_used_twice_is_one_sound(tmp_path):
- import subprocess
-
- import numpy as np
-
- from rea_video import effects
-
- sr = effects.SR
- t = np.arange(int(0.3 * sr)) / sr
- ding = (np.sin(2 * np.pi * 1568 * t) * np.exp(-t / 0.08)).astype(np.float32) * 0.5
- noise = np.random.default_rng(2).normal(0, 0.3, int(0.3 * sr)).astype(np.float32) * np.exp(-t / 0.08).astype(np.float32)
- y = np.zeros(sr * 5, np.float32)
- for at, s in ((0.5, ding), (1.5, noise), (3.0, ding)):
- y[int(at * sr):int(at * sr) + len(s)] += s
- p = tmp_path / "effects.wav"
- subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "f32le", "-ar", str(sr), "-ac", "1", "-i", "-", str(p)], input=y.tobytes(), check=True)
- ev = effects.detect(p)
- groups = effects.group(ev, p)
- assert [len(g["members"]) for g in groups] == [2, 1] # the ding twice, the noise burst once
- assert [round(ev[i]["t"], 1) for i in groups[0]["members"]] == [0.5, 3.0]
-
-
-def test_a_sound_that_never_lands_on_an_edit_is_the_pictures_own(breakdown, tmp_path): # noqa: F811
- from rea_video.report import _audio_md
-
- b, _ = breakdown
- set_lang("zh")
- b = dict(b, audio=dict(b.get("audio") or {}, has_audio=True))
- b["audio_plan"] = {"sfx_merged": [{"t": 1.0, "type": "pop", "group": "F1", "in_scene": False, "on": {"what": "字幕出现"}, "clip": "sfx/sfx_01.wav"},
- {"t": 2.5, "type": "ding", "group": "F2", "in_scene": True, "clip": "sfx/sfx_02.wav"}],
- "sfx_groups": [{"id": "F1", "rep": 0, "type": "pop", "count": 1, "times": [1.0], "in_scene": False},
- {"id": "F2", "rep": 1, "type": "ding", "count": 1, "times": [2.5], "in_scene": True}]}
- md = "\n".join(_audio_md(b))
- assert "F1" in md and "F2" not in md and "画面自带" not in md # the picture's own sound is left out of the report
-
-
-def test_a_sound_on_a_cut_is_added_only_when_it_stands_alone():
- from rea_video.pipeline import _placed_in_edit
-
- assert _placed_in_edit({"on": {"type": "subtitle_in"}, "level_db": -40, "bed_db": -40}) # lands on a text pop
- assert _placed_in_edit({"on": {"type": "cut"}, "level_db": -17, "bed_db": -180}) # a ding over silence on a cut
- assert not _placed_in_edit({"on": {"type": "cut"}, "level_db": -37, "bed_db": -53}) # the live sound jumping at a cut
- assert not _placed_in_edit({"on": {"type": "cut"}, "level_db": -9, "bed_db": -37}) # a lid twisted on a generated cut
- assert not _placed_in_edit({"level_db": -10, "bed_db": -90}) # on nothing at all
-
-
-def test_silent_stems_mean_no_effects_and_no_music(breakdown, tmp_path): # noqa: F811
- """A near-silent accompaniment stem drops the mix's beat guess; an effects track with nothing on it means no effects."""
- import numpy as np
-
- from rea_video.pipeline import finalize
-
- b, out = breakdown
- set_lang("zh")
- b["audio"] = {"has_audio": True, "music": {"present": True, "tempo_bpm": 120.0}, "voice": {"present": True},
- "sfx": {"events": [{"t": 1.0, "type": "pop", "source": "deterministic", "confidence": "low"}]}}
- b["stems"] = {"ok": True, "level_db": {"mix": -17.0, "vocals": -17.0, "music": -60.0, "effects": -103.0}}
- fx = out / "stems" / "effects.wav"
- fx.parent.mkdir(parents=True, exist_ok=True)
- import subprocess
- subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "f32le", "-ar", "48000", "-ac", "1", "-i", "-", str(fx)],
- input=np.zeros(48000 * 3, np.float32).tobytes(), check=True)
- b = finalize(b, out)
- assert not b["audio"]["music"]["present"]
- assert not [e for e in b["audio_plan"]["sfx_merged"] if not e.get("in_scene")]
-
-
-def test_transitions_are_written_with_spec_ids(breakdown): # noqa: F811
- b, out = breakdown
- set_lang("zh")
- b["shots"][1]["transition_in"] = "dissolve"
- write_reports(_with_vlm(b), out)
- pkg = spec.read(out)
- assert pkg["shots"][b["shots"][1]["index"]]["transition_in"] == {"type": "dissolve"}
- assert pkg["timeline"][1]["transition"] == "叠化"
- assert "transition_in" not in pkg["shots"][b["shots"][0]["index"]] or b["shots"][0].get("transition_in") not in (None, "cut")
- assert videomd.check(out) == []
diff --git a/tests/test_vlm_cache.py b/tests/test_vlm_cache.py
deleted file mode 100644
index 335c82c..0000000
--- a/tests/test_vlm_cache.py
+++ /dev/null
@@ -1,61 +0,0 @@
-"""Cached answers must belong to the requested model configuration."""
-import json
-
-import pytest
-
-from rea_video.vlm import VLMClient, VLMConfig
-
-
[email protected]("change", ["model", "model_order", "endpoint", "max_tokens"])
-def test_changed_request_does_not_reuse_cached_answer(tmp_path, monkeypatch, change):
- calls = []
-
- def post(self, model, content, max_tokens):
- calls.append((self.cfg.base_url, model, max_tokens))
- return json.dumps({"answer": len(calls)})
-
- monkeypatch.setattr(VLMClient, "_post", post)
- media = tmp_path / "frame.jpg"
- media.write_bytes(b"same media")
- cache = tmp_path / "cache"
- original = VLMConfig("https://first.example/v1", "test", ["first", "fallback"])
- first = VLMClient(original, cache).ask_json("describe", [(media, "image/jpeg")])
- assert first["answer"] == 1
-
- cfg = VLMConfig(original.base_url, original.api_key, list(original.models))
- max_tokens = 4096
- if change == "model":
- cfg.models = ["second"]
- elif change == "model_order":
- cfg.models.reverse()
- elif change == "endpoint":
- cfg.base_url = "https://second.example/v1"
- else:
- max_tokens = 8192
- client = VLMClient(cfg, cache)
- result = client.ask_json("describe", [(media, "image/jpeg")], max_tokens=max_tokens)
- assert result["answer"] == 2
- assert len(calls) == 2
- # The identical request still hits the cache, including from a new client.
- assert VLMClient(cfg, cache).ask_json("describe", [(media, "image/jpeg")], max_tokens=max_tokens) == result
- assert len(calls) == 2
-
-
-def test_fallback_reordering_preserves_cache_hit(tmp_path, monkeypatch):
- calls = []
-
- def post(self, model, content, max_tokens):
- calls.append(model)
- if model == "down":
- raise ValueError("unavailable")
- return '{"answer": "ok"}'
-
- monkeypatch.setattr(VLMClient, "_post", post)
- monkeypatch.setattr("rea_video.vlm.time.sleep", lambda seconds: None)
- cfg = VLMConfig("https://first.example/v1", "test", ["down", "working"])
- client = VLMClient(cfg, tmp_path / "cache")
- result = client.ask_json("describe", [])
- assert client.models == ["working", "down"]
- assert calls == ["down", "down", "working"]
- assert client.ask_json("describe", []) == result
- assert len(calls) == 3
diff --git a/tests/test_vlm_mock.py b/tests/test_vlm_mock.py
deleted file mode 100644
index efbf3bb..0000000
--- a/tests/test_vlm_mock.py
+++ /dev/null
@@ -1,141 +0,0 @@
-"""End-to-end VLM path against a local fake OpenAI-compatible server."""
-import json
-import threading
-from http.server import BaseHTTPRequestHandler, HTTPServer
-
-import pytest
-
-from rea_video.pipeline import decompose
-
-CANNED = {
- "label_probs": {"live_action": 0.05, "ai_video": 0.05, "avatar": 0, "cg_3d": 0, "code_render": 0.8, "screen_capture": 0.1,
- "still_motion": 0, "static_hold": 0},
- "image_source": "graphic", "evidence": ["扁平底色上的卡片滑入,文字边缘锐利"], "generator_guess": "Remotion",
- "description": "深色背景上白色卡片从左侧滑入", "shot_size": "全景", "camera_move": "固定", "style": "扁平 UI",
- "overlay_text": ["REA VIDEO"],
- "replication": {"image_prompt": "深色背景,白色圆角卡片", "video_prompt": "白色卡片从左侧滑入后停在画面中央", "video_prompt_en": "a white card slides in"},
-}
-
-
-class Handler(BaseHTTPRequestHandler):
- seen = []
- user_agents = []
-
- def do_POST(self): # noqa: N802
- body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
- Handler.seen.append(body)
- Handler.user_agents.append(self.headers.get("User-Agent", ""))
- text = body["messages"][0]["content"][-1]["text"]
- payload = CANNED if "label_probs" in text else {"summary": "测试视频", "format": "知识讲解", "segments": []}
- resp = {"choices": [{"message": {"content": "```json\n" + json.dumps(payload, ensure_ascii=False) + "\n```"}}]}
- data = json.dumps(resp).encode()
- self.send_response(200)
- self.send_header("Content-Type", "application/json")
- self.send_header("Content-Length", str(len(data)))
- self.end_headers()
- self.wfile.write(data)
-
- def log_message(self, *a):
- pass
-
-
-def fake_server(monkeypatch):
- srv = HTTPServer(("127.0.0.1", 0), Handler)
- threading.Thread(target=srv.serve_forever, daemon=True).start()
- monkeypatch.setenv("REA_VLM_BASE_URL", f"http://127.0.0.1:{srv.server_port}/v1")
- monkeypatch.setenv("REA_VLM_API_KEY", "test")
- monkeypatch.setenv("REA_VLM_MODEL", "fake-model")
- yield Handler
- srv.shutdown()
-
-
-def test_vlm_fusion_end_to_end(media, tmp_path, fake_server):
- b = decompose(media["code"], tmp_path / "o", use_vlm=True, ocr=False, workers=1, stems=False)
- assert fake_server.user_agents and all(ua.startswith("rea-video/") for ua in fake_server.user_agents)
- assert b["analysis"]["vlm"]["used"] and not b["analysis"]["vlm"]["errors"]
- s = b["shots"][0]
- assert s["base"]["decided_by"] == "fused" and s["base"]["label"] == "code_render"
- assert s["replication"]["executor"] == "code_render_spec"
- assert b["whole_video_vlm"]["summary"] == "测试视频"
- # the shot request carried a video clip and keyframes as data URIs
- parts = fake_server.seen[0]["messages"][0]["content"]
- kinds = [p["image_url"]["url"].split(";")[0] for p in parts if p["type"] == "image_url"]
- assert kinds[0] == "data:video/mp4" and "data:image/jpeg" in kinds
- # cache hit on second run: no new requests
- n = len(fake_server.seen)
- decompose(media["code"], tmp_path / "o", use_vlm=True, ocr=False, workers=1, stems=False)
- assert len(fake_server.seen) == n
-
-
-class Down(BaseHTTPRequestHandler):
- def do_POST(self): # noqa: N802
- self.rfile.read(int(self.headers["Content-Length"]))
- data = b'{"error":{"message":"model temporarily unavailable"}}'
- self.send_response(503)
- self.send_header("Content-Length", str(len(data)))
- self.end_headers()
- self.wfile.write(data)
-
- def log_message(self, *a):
- pass
-
-
-def test_vlm_all_calls_failing_is_reported_as_not_used(media, tmp_path, monkeypatch):
- srv = HTTPServer(("127.0.0.1", 0), Down)
- threading.Thread(target=srv.serve_forever, daemon=True).start()
- monkeypatch.setenv("REA_VLM_BASE_URL", f"http://127.0.0.1:{srv.server_port}/v1")
- monkeypatch.setenv("REA_VLM_API_KEY", "test")
- monkeypatch.setenv("REA_VLM_MODEL", "fake-model")
- monkeypatch.setattr("rea_video.vlm.time.sleep", lambda s: None)
- try:
- b = decompose(media["code"], tmp_path / "o", use_vlm=True, ocr=False, workers=1, stems=False)
- finally:
- srv.shutdown()
- v = b["analysis"]["vlm"]
- assert v["requested"] and not v["used"] and v["status"] == "failed" and v["errors"]
- assert "全部调用失败" in b["summary"]["vlm"]
- assert all(s["base"]["decided_by"] == "deterministic" for s in b["shots"])
- assert "全部调用失败" in (tmp_path / "o" / "report.md").read_text(encoding="utf-8")
-
-
-def test_vlm_off_suggests_setup_but_still_runs(media, tmp_path):
- b = decompose(media["code"], tmp_path / "o", use_vlm=False, ocr=False, workers=1, stems=False)
- assert b["analysis"]["vlm"]["status"] == "off" and "REA_VLM_BASE_URL" in b["summary"]["vlm"]
- assert b["summary"]["production_mix"]
-
-
-class FirstModelDown(Handler):
- calls = []
-
- def do_POST(self): # noqa: N802
- n = int(self.headers["Content-Length"])
- body = json.loads(self.rfile.read(n))
- FirstModelDown.calls.append(body["model"])
- if body["model"] == "down-model":
- self.send_response(503)
- self.send_header("Content-Length", "0")
- self.end_headers()
- return
- payload = CANNED if "label_probs" in body["messages"][0]["content"][-1]["text"] else {"summary": "x", "segments": []}
- data = json.dumps({"choices": [{"message": {"content": json.dumps(payload, ensure_ascii=False)}}]}).encode()
- self.send_response(200)
- self.send_header("Content-Length", str(len(data)))
- self.end_headers()
- self.wfile.write(data)
-
-
-def test_vlm_falls_back_and_sticks_to_working_model(media, tmp_path, monkeypatch):
- srv = HTTPServer(("127.0.0.1", 0), FirstModelDown)
- threading.Thread(target=srv.serve_forever, daemon=True).start()
- monkeypatch.setenv("REA_VLM_BASE_URL", f"http://127.0.0.1:{srv.server_port}/v1")
- monkeypatch.setenv("REA_VLM_API_KEY", "test")
- monkeypatch.setenv("REA_VLM_MODEL", "down-model,good-model")
- monkeypatch.setattr("rea_video.vlm.time.sleep", lambda s: None)
- try:
- b = decompose(media["code"], tmp_path / "o", use_vlm=True, ocr=False, workers=1, stems=False)
- finally:
- srv.shutdown()
- assert b["analysis"]["vlm"]["status"] == "ok"
- # the dead model is tried on the first request only
- assert FirstModelDown.calls.count("down-model") == 2 and FirstModelDown.calls[-1] == "good-model"
diff --git a/tests/test_vlm_take.py b/tests/test_vlm_take.py
deleted file mode 100644
index 6768d39..0000000
--- a/tests/test_vlm_take.py
+++ /dev/null
@@ -1,108 +0,0 @@
-"""Jump-cut pieces of one take share one VLM call; the call budget goes where the pixels are least sure."""
-import json
-import threading
-from http.server import BaseHTTPRequestHandler, HTTPServer
-
-import numpy as np
-import pytest
-
-from rea_video.overlay import shot_ocr_frames, shot_ocr_items
-from rea_video.pipeline import decompose, vlm_units
-from rea_video.vlm import take_results
-from tests.conftest import _photo_like, _write
-from tests.test_shots import H, W, _speaker
-
-
-def _rec(i, start, end, trans="cut", sure=0.9):
- return {"index": i, "id": f"shot_{i:03d}", "start": start, "end": end, "duration": end - start, "transition_in": trans,
- "deterministic": {"probs": {"live_action": sure, "ai_video": 1 - sure}}}
-
-
-def test_jump_pieces_form_one_unit_up_to_the_clip_limit():
- recs = [_rec(1, 0, 2, "start"), _rec(2, 2, 4, "jump"), _rec(3, 4, 6, "jump"), _rec(4, 6, 8, "cut"),
- _rec(5, 8, 15, "jump"), _rec(6, 15, 21, "jump")]
- units = vlm_units(recs, 60)
- assert [[r["index"] for r in u] for u in units] == [[1, 2, 3], [4, 5], [6]] # 4+5 is 9 s; adding 6 would be 15 s
-
-
-def test_call_budget_goes_to_uncertain_long_units_in_time_order():
- recs = [_rec(1, 0, 1, "start", 0.95), _rec(2, 1, 5, "cut", 0.5), _rec(3, 5, 6, "cut", 0.55), _rec(4, 6, 9, "cut", 0.9)]
- assert [u[0]["index"] for u in vlm_units(recs, 2)] == [2, 3]
-
-
-def test_take_answer_is_split_per_piece():
- raw = {"label_probs": {"live_action": 1}, "description": "整段", "replication": {"image_prompt": "首帧", "video_prompt": "整段动作"},
- "segments": [{"description": "拆开盒子", "replication": {"video_prompt": "双手拆开纸盒"}},
- {"description": "拿出杯子", "replication": {"video_prompt": "从盒里拿出水杯"}}]}
- a, b = take_results(raw, 2)
- assert a["description"] == "拆开盒子" and b["replication"]["video_prompt"] == "从盒里拿出水杯"
- assert a["replication"]["image_prompt"] == "首帧" and "segments" not in a # shared fields stay, pieces do not leak
- c, d = take_results({"description": "整段", "segments": [{"description": "只有一段"}]}, 2) # wrong count: shared answer
- assert c["description"] == d["description"] == "整段"
-
-
-def test_shot_text_comes_from_the_whole_video_ocr_pass():
- whole = [{"t": 1.0, "text": "字幕", "conf": 0.9, "bbox": [0.2, 0.8, 0.6, 0.05], "angle": 0.0},
- {"t": 2.0, "text": "下一句", "conf": 0.9, "bbox": [0.2, 0.8, 0.6, 0.05], "angle": 0.0}]
- hits = shot_ocr_items(whole, 0.5, 0.8, 1.6)
- assert [h["text"] for h in hits] == ["字幕"] and hits[0]["band"] == "bottom"
- assert shot_ocr_items(whole, 0.5, 1.6, 1.9) is None # no read inside this shot: read its own frames
- assert shot_ocr_items(whole, 2.5, 0, 3) is None # too sparse (long video): read its own frames
- assert [shot_ocr_frames(d) for d in (0.3, 1.2, 6.0)] == [1, 2, 4]
-
-
-TAKE = {"label_probs": {"live_action": 0.9, "ai_video": 0.1}, "image_source": "photo", "evidence": ["手持轻微抖动"],
- "description": "整条口播", "shot_size": "近景", "camera_move": "固定", "style": "实拍",
- "replication": {"image_prompt": "人物近景", "video_prompt": "人物对镜头说话"}}
-
-
-class Handler(BaseHTTPRequestHandler):
- seen = []
-
- def do_POST(self): # noqa: N802
- body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
- text = body["messages"][0]["content"][-1]["text"]
- Handler.seen.append(text)
- if "label_probs" in text:
- n = text.count("segments 数组") and int(text.split("剪成的 ")[1].split(" 段")[0])
- payload = dict(TAKE, segments=[{"description": f"第{k + 1}段", "replication": {"video_prompt": f"第{k + 1}段动作"}}
- for k in range(n)]) if n else TAKE
- else:
- payload = {"summary": "测试", "segments": []}
- data = json.dumps({"choices": [{"message": {"content": json.dumps(payload, ensure_ascii=False)}}]}).encode()
- self.send_response(200)
- self.send_header("Content-Type", "application/json")
- self.send_header("Content-Length", str(len(data)))
- self.end_headers()
- self.wfile.write(data)
-
- def log_message(self, *a):
- pass
-
-
-def fake_server(monkeypatch):
- Handler.seen = []
- srv = HTTPServer(("127.0.0.1", 0), Handler)
- threading.Thread(target=srv.serve_forever, daemon=True).start()
- monkeypatch.setenv("REA_VLM_BASE_URL", f"http://127.0.0.1:{srv.server_port}/v1")
- monkeypatch.setenv("REA_VLM_API_KEY", "test")
- monkeypatch.setenv("REA_VLM_MODEL", "fake-model")
- yield Handler
- srv.shutdown()
-
-
-def test_jump_cut_take_is_one_vlm_call(tmp_path, fake_server):
- rng = np.random.default_rng(2)
- bg = _photo_like(W, H, 5)
- frames = [_speaker(bg, 180, 160, t, rng) for t in range(45)]
- frames += [_speaker(bg, 120, 210, t, rng) for t in range(45, 90)]
- frames += [_speaker(bg, 200, 150, t, rng) for t in range(90, 135)]
- p = _write(frames, tmp_path / "take.mp4")
- b = decompose(p, tmp_path / "o", use_vlm=True, whole_vlm=False, ocr=False, workers=1, stems=False, packaging=False, memory=False)
- shots = b["shots"]
- assert [s["transition_in"] for s in shots] == ["start", "jump", "jump"]
- assert sum("label_probs" in t for t in fake_server.seen) == 1 # one look at the whole take
- assert [s["vlm"]["description"] for s in shots] == ["第1段", "第2段", "第3段"]
- assert all(s["vlm"]["take"]["shots"] == [1, 2, 3] for s in shots)
- assert b["analysis"]["vlm"]["calls"] == 1 and b["analysis"]["vlm"]["ok_shots"] == 3