Skip to content

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

Add pluggable aspects framework (framing/camera/lighting/editing/format) and face detection

june3b75094b8d69
diff --git a/README.md b/README.md
index 5e7cc9e..284ff88 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# rea-video — Reverse Engineer Any Video
-> 拿到一条视频,逐镜头判断它**是怎么做出来的**:实拍、AI 生成、3D 渲染、代码渲染、录屏、静态图推拉,还是混合;字幕和贴片是不是后期叠加的;**哪些是用户真实素材**(实拍、截图、录屏、照片);**声音怎么做的**(人声、BGM 的 BPM/调性/段落、音效、是否卡点),以及**音乐/人声/音效是 AI 生成的还是现成的**(先看视频形式:AI 音乐 MV 多为 AI 歌,普通配乐多为曲库)。每个结论都附可复查的证据。然后对其中的 AI 类镜头,交给 [capsule-cinema](https://github.com/JuneYaooo/cheap-claude-video) 复刻。
+> 拿到一条视频,逐镜头判断它**是怎么做出来的**:实拍、AI 生成、3D 渲染、代码渲染、录屏、静态图推拉,还是混合;字幕和贴片是不是后期叠加的;**哪些是用户真实素材**(实拍、截图、录屏、照片);**声音怎么做的**(人声、BGM 的 BPM/调性/段落、音效、是否卡点),以及**音乐/人声/音效是 AI 生成的还是现成的**(先看视频形式:AI 音乐 MV 多为 AI 歌,普通配乐多为曲库)。实拍镜头(口播、桌拍、开箱、vlog)还会按维度拆**怎么拍、怎么打光、怎么剪**:形式、景别和机位角度、手持还是支架、机位数,主光方向/光比/软硬/色温/轮廓光,剪气口、跳切和插入素材的节奏,并给出拍摄方案和器材清单;维度可插拔(`rea_video/aspects/`)。每个结论都附可复查的证据。然后对其中的 AI 类镜头,交给 [capsule-cinema](https://github.com/JuneYaooo/cheap-claude-video) 复刻。
**给 Agent 用**:`scripts/install_skill.sh` 会把 [`skills/rea-video`](skills/rea-video/SKILL.md) 链接到 Claude Code、Codex 等 agent 的 skills 目录。Agent 会按 Skill 里的流程拆解、复核低置信镜头、按模板交付。
diff --git a/eval/RESULTS.md b/eval/RESULTS.md
index 8c442cd..41f22ed 100644
--- a/eval/RESULTS.md
+++ b/eval/RESULTS.md
@@ -153,3 +153,62 @@ rea-video --env-file $CAPSULE_CINEMA_ROOT/.env eval eval/labels.yaml -o out/eval
- 注意:这条规则是在这三组数据上选出来的,三组都不再是"没见过的视频"。需要一批新视频复核,用户纠正导出的样本(`rea-video memory --export-labels`)可以作为来源。
- labels 0.999 / holdout 0.996 / holdout2 0.998(不开 VLM 的回归)不变。
- 新增用户记忆(`rea_video/memory.py`,存在 `~/.rea-video`):`correct` 记录纠正并立即改结论,同一文件再拆时自动套用;同类纠正出现 2 次以上,会在复核任务和 `summary` 里提示;`prefs` 记默认参数和自由文字偏好;`memory --export-labels` 导出评测样本。评测(`rea-video eval`)不读用户记忆。
+
+## 2026-10-30:实拍口播(夜景 / 室内)+ 拍法与打光
+
+新数据:`eval/koubo.yaml`(2 条抖音转码口播,人工逐镜标注,**开发集**:规则是看着这两条调的)。
+
+问题(改前,不开 VLM):夜景公交站口播被判成「3D 渲染 82%」,人声判成 TTS;室内贴脸口播 33% 判成 3D。原因:
+1. 转码把夜景暗部压成近黑平坦块、墙面和黑衣服也是平坦块,「平坦块多 / 用色少」被当成渲染特征。
+2. **人脸检测一直没生效**:OpenCV 5.0 去掉了 `CascadeClassifier`,旧代码异常被吞掉,所有视频 faces=0(不只是这两条)。
+3. Gemini 其实判对了(实拍 1.0),但「只有一个看图来源时必须在工具前两名里」把它挡掉了。
+4. 人声来源跟着画面错:实拍占比 0% → 按「后期配音」判成 TTS。
+
+改动:
+- `rea_video/faces.py`:YuNet 人脸检测(230 KB,首次自动下载),带五官关键点;没有模型时退回 Haar。
+- 特征新增 `dark_ratio / dark_std / dark_flat / flat_lit / face_presence / face_area`。
+- `classify.lowlight_photo`:大面积近黑但带颗粒(渲染的黑底是纯色)、亮部不平坦、有人脸 → 只按亮部算渲染纹理;`video_context.native30` 也把这类镜头算进来。
+- 大人脸(占画面 ≥6%、≥50% 帧出现)→ 渲染纹理分 ×0.4;评测集里卡通/毛绒/插画脸都 <6%。
+- OCR 读到 ≥5 行小字号文字 → 界面/文档截图,3D 降权(评测集里 3D 镜头最多 2 行)。
+- 手持/移动机位时数字人分 ×0.3。
+- `_vlm_gate`:看图来源判 实拍/AI/数字人、且镜头有大人脸或是弱光人物时,可以不在工具前两名里;工具对「渲染」有把握不再挡它(工具的把握只保护 AI/实拍轴)。转码 + 非原生 30fps 不改判实拍的保护不变。
+- 新模块 `rea_video/cinematography.py`(同日改为 `rea_video/aspects/` 框架,见下一节):逐镜测景别、主光左右/上下、光比、软硬、色温、背景虚化、点光源;整片汇总布光方案(夜景环境光 / 正面柔光 / 侧前主光+补光 / 单侧硬光)、器材清单、机位数、跳切/推近切、插入素材占比。VLM 提示词和 review 模板加了 cinematography(机位角度、光源、眼神光、轮廓光)和 shooting。
+- 实拍镜头的复刻路线改成拍摄方案(`replication.shoot`),AI 近似降为备选。
+- 评测加 `cine:`(景别、布光)和 `audio.voice_source` 检查。
+
+结果(按时长加权的制作方式准确率;VLM = gemini-3.1-pro-preview,agent = Claude 看图复核):
+
+| 组合 | koubo_night_street | koubo_indoor_closeup |
+|---|---|---|
+| 改前 · 只用工具 | ≈0.05(3D 82%,只有黑底文字卡对) | ≈0.65(33% 判成 3D) |
+| 改后 · 只用工具 | 0.51 | 0.99 |
+| 改后 · + VLM | 0.78 | 0.99 |
+| 改后 · + agent | 0.93 | 1.00 |
+| 改后 · + VLM + agent | **0.98** | **0.99** |
+
+- 拍法/打光(主景别、布光方案)四种组合都是 2/2:夜景 → 「夜景/弱光环境光,没有专门补光」,室内 → 「正面柔光(平光)」。人声来源(真人):只用工具 1/2,开 VLM 或 agent 后 2/2。
+- 只用工具时夜景 0.51:剩下的主要是「实拍还是 AI」二选一(转码后按设计标「待确认」),要靠 VLM / agent 看图定。
+- Gemini 的拍法描述和 agent 有出入(夜景站姿镜头 Gemini 说硬光、无轮廓光,agent 看到身后路灯的头发亮边),报告里测量值和看图结果并列,不融合。
+- 回归 1(四组旧评测集全部重新解码,人脸和新特征生效后再分类):labels 0.999 / holdout 0.996 / holdout2 0.998 / articles 0.886,真实素材 0.976 / 0.996 / 0.981 / 1.0,逐条视频**与改前完全一致**;新规则在旧数据上触发了 9 次弱光、7 次大人脸、1 次小字截图,没有改错任何镜头。
+- 回归 2(zcode 盲测缓存的 Gemini + agent 答案,用新规则重新融合;另做一版把答案挂到带人脸特征的重新解码结果上):holdout / holdout2 / articles 的 工具 / +VLM / +agent / 都开 = 0.996/0.996/0.996/0.996、0.998/0.998/0.998/0.998、0.886/0.996/1.000/0.988,和上一节一致。
+ 中途一版「人物例外」不限范围时,holdout2 +VLM 掉到 0.991(dual_role_realcat 的 AI 人物被 Gemini 判成数字人并越过工具前两名),已收紧为「工具前两名里有渲染类标签时才放行」,并加了测试。
+- 局限:两条口播都是同一个博主、都是开发集;软硬光和补光在转码夜景上偏保守;机位(手持 vs 支架)只靠运动统计,夜景里支架拍的半身镜头和手持自拍混在一起,没有标真值。需要更多不同博主、室内补光(环形灯/柔光箱)的口播做留出验证。
+
+## 2026-10-30:拍法分析改成可插拔维度(aspects),去掉只认人脸的限制
+
+动机:上一版的拍法 / 打光只认人脸,桌拍、商品、手部这类没有人脸的实拍拆不了;拍法逻辑散在 pipeline / vlm / review / report / eval 各处,加一项分析要改五个地方。
+
+改动:
+- `rea_video/aspects/`:每个维度(`framing` 取景、`camera` 机位、`lighting` 打光、`editing` 剪辑、`format` 形式)一个模块,统一走 测量 → 看图提问 → 逐镜解读 → 整片汇总 → 评测。VLM 提示词、`review_answers.json` 模板、报告「拍法、打光与剪辑」一节、`eval` 的 `aspects:` 校验都从注册表生成。说明见 `skills/rea-video/references/aspects.md`。
+- 主体(`aspects/subject.py`):人脸 → 画面最清晰的区域(细节能量最高的连通块)→ 画面中心。打光、景别、机位聚类都在主体上测;没有人脸时景别标「估算」。
+- 打光布光方案改成规则表 `lighting.SETUPS`(新增「逆光」),器材按「人物 / 物品」两套给。
+- 剪辑新增「切点落在说话停顿处的比例」(剪气口)。
+- 形式:人物口播 / 桌拍(物品为主体 + 固定或俯拍)/ 手持拍物品(开箱、带货、第一视角)/ vlog / 其他;看图结论优先。
+- 测量、VLM、agent 三个来源逐项并列(`fields` 表),`prefer="seen"` 的项以看图为准,其余以测量为准,不做平均。旧的 `cinematography` 答案仍可读。
+- 分类规则里这次加的阈值集中到 `classify.RULES`,注释写明来源分布,不再引用具体样片。
+
+结果:
+- 口播两条(工具 / +VLM / +agent / 都开):夜景 0.51 / 0.78 / 0.93 / 0.98,室内 0.99 / 0.99 / 1.00 / 0.99,与重构前一致;`framing.shot_size`、`lighting.setup`、`format.format` 四种组合都是 2/2。
+- 回归:四组旧评测集重新解码后 labels 0.999 / holdout 0.996 / holdout2 0.998 / articles 0.886,逐条与改前一致;zcode 缓存答案重新融合的 12 个组合数字也一致。
+- 无人脸实拍:`art_v11_tiktok_original`(第一视角手持拍榨汁杯)走「清晰区域」路径,测得正面柔光、中性色温、下方台面反光、手持,和画面一致。它的形式起初被判成 vlog,于是加了「手持拍物品」一类(**看着这条加的**,算开发集)。新增目测标注 `aspects.format`:art_v11 → product,douyin_live_breakfast / douyin_live_street → talking_head,3/3。
+- 还缺:俯拍桌面(固定机位、顶拍)的真样本,「桌拍」分支目前只有单元测试覆盖;室内补光灯口播、多人访谈也都还没有样本。
diff --git a/eval/articles.yaml b/eval/articles.yaml
index 2d5a701..14e0801 100644
--- a/eval/articles.yaml
+++ b/eval/articles.yaml
@@ -26,6 +26,7 @@ videos:
path: eval/media/articles/v10.mp4
label: [code_render, screen_capture, still_motion]
- id: art_v11_tiktok_original # a2 TikTok 带货原片:手机实拍(真实厨房、真手、男声口播)
+ aspects: {format: {format: product}} # 目测 2026-10-30:第一视角手持,手拿食材放进榨汁杯,无人脸
path: eval/media/articles/v11.mp4
label: live_action
real_material: true
diff --git a/eval/holdout.yaml b/eval/holdout.yaml
index 052db74..9166ed6 100644
--- a/eval/holdout.yaml
+++ b/eval/holdout.yaml
@@ -14,6 +14,7 @@ videos:
path: ${CAPSULE}/output/dual_role_social_account_doctor_20260930/h3/realcat_s1_seed9300101.mp4
label: ai_video
- id: douyin_live_breakfast
+ aspects: {format: {format: talking_head}} # 目测 2026-10-30:坐着边吃边对镜头说话
audio: {voice: true}
real_material: true
path: ${CAPSULE}/output/plot_mining/videos/7690489550460562426.mp4
diff --git a/eval/koubo.yaml b/eval/koubo.yaml
new file mode 100644
index 0000000..99035f0
--- /dev/null
+++ b/eval/koubo.yaml
@@ -0,0 +1,54 @@
+# 实拍口播评测集:真人出镜、手机拍摄、抖音转码,带截图/录屏插入与花字
+# 视频不入库(eval/media/ 已 gitignore):用 TikHub 按分享链接下载 1080p(capsule-cinema/.claude/skills/account-diagnostic/tikhub,
+# douyin douyin_app_v3_fetch_one_video_by_share_url → aweme_detail.video.bit_rate[0].play_addr.url_list[0])
+# 真值来源:人工逐镜目测(2026-10-30,按 decompose 切出的镜头逐个看首尾帧)。
+# 叠了大块截图的人物镜头底层仍是实拍,截图类标签也接受;黑底文字卡是代码渲染。
+# aspects:拍法/打光真值 {维度: {字段: 可接受值}},也是目测(存疑处没有标;夜景那条没标机位,因为支架拍和手持自拍都有)。
+videos:
+ - id: koubo_night_street
+ path: eval/media/chenpangyi_koubo.mp4
+ source: 抖音 陈胖一《新号做出100万+播放的公式邪修!》https://v.douyin.com/U0tc1sxj1q8/ ;夜晚公交站边喝酒边讲,路灯环境光
+ segments:
+ - [0.00, 1.27, live_action]
+ - [1.27, 4.07, [live_action, screen_capture, code_render]]
+ - [4.07, 11.17, [screen_capture, code_render, static_hold, live_action]]
+ - [11.17, 13.10, [code_render, static_hold, still_motion]]
+ - [13.10, 14.93, [screen_capture, code_render, still_motion]]
+ - [14.93, 25.77, live_action]
+ - [25.77, 28.07, [live_action, screen_capture, code_render]]
+ - [28.07, 40.27, live_action]
+ - [40.27, 45.27, [live_action, screen_capture, code_render]]
+ - [45.27, 59.70, live_action]
+ - [59.70, 68.30, [live_action, screen_capture, code_render]]
+ - [68.30, 69.80, live_action]
+ - [69.80, 76.20, [live_action, screen_capture, code_render]]
+ - [76.20, 78.87, live_action]
+ - [78.87, 82.07, [live_action, screen_capture, code_render]]
+ - [82.07, 89.77, live_action]
+ - [89.77, 91.23, [screen_capture, code_render, live_action]]
+ - [91.23, 94.60, live_action]
+ - [94.60, 96.23, [live_action, screen_capture, static_hold]]
+ - [96.23, 99.57, live_action]
+ - [99.57, 100.70, [live_action, code_render]]
+ - [100.70, 140.43, live_action]
+ - [140.43, 145.43, [code_render, static_hold]]
+ - [145.43, 166.07, live_action]
+ - [166.07, 167.34, [code_render, static_hold]]
+ real_material: [[0.00, 140.43, true], [140.43, 145.43, false], [145.43, 166.07, true]]
+ audio: {voice: true, music: true, voice_source: human_recording}
+ aspects: {framing: {shot_size: [大特写, 特写, 近景]}, lighting: {setup: ambient_low_light}, format: {format: talking_head}}
+
+ - id: koubo_indoor_closeup
+ path: eval/media/chenpangyi_indoor.mp4
+ source: 抖音 陈胖一《改命邪修!写《人生简历》投递给AI!》https://v.douyin.com/G4wyC9YPCV8/ ;室内贴脸口播,暖色墙,大面积柔光
+ segments:
+ - [0.00, 16.20, live_action]
+ - [16.20, 18.47, [screen_capture, live_action, code_render]]
+ - [18.47, 71.60, live_action]
+ - [71.60, 76.07, [screen_capture, code_render, live_action]]
+ - [76.07, 121.53, live_action]
+ - [121.53, 122.70, [ai_video, cg_3d, still_motion, static_hold, live_action]]
+ - [122.70, 174.07, live_action]
+ real_material: [[0.00, 121.53, true], [122.70, 174.07, true]]
+ audio: {voice: true, music: true, voice_source: human_recording}
+ aspects: {framing: {shot_size: [大特写, 特写]}, lighting: {setup: [soft_front, key_fill]}, format: {format: talking_head}}
diff --git a/eval/labels.yaml b/eval/labels.yaml
index 7777cce..5c8079a 100644
--- a/eval/labels.yaml
+++ b/eval/labels.yaml
@@ -98,6 +98,7 @@ videos:
source: 抖音下载,文件带 AIGC 隐式标识 Label=1
- id: douyin_live_street
+ aspects: {format: {format: talking_head}} # 目测 2026-10-30
real_material: true
path: ${CAPSULE}/output/plot_mining/videos/7691668930338992100.mp4
label: live_action
diff --git a/rea_video/aspects/__init__.py b/rea_video/aspects/__init__.py
new file mode 100644
index 0000000..1817933
--- /dev/null
+++ b/rea_video/aspects/__init__.py
@@ -0,0 +1,200 @@
+"""Production aspects: how a video was shot, lit and cut, as pluggable analyses (see base.py for the contract).
+
+Registered in dependency order: framing and camera feed format; editing feeds format. To add an aspect, write a
+module with an Aspect subclass, call register() at import, and import it below. The pipeline, VLM prompt, review
+template, report and eval pick it up from REGISTRY."""
+from __future__ import annotations
+
+import html
+import json
+
+from . import framing, camera, lighting, editing, fmt # noqa: F401 (registration order matters)
+from .base import FILMED, PHOTOGRAPHIC, REGISTRY, ShotCtx, get
+from .subject import subject
+
+__all__ = ["REGISTRY", "measure_shot", "finalize", "prompt_block", "review_template", "review_guide", "clean_answers",
+ "summary_lines", "check", "shot_text", "report_md", "report_html", "shooting_plan"]
+
+
+# ---------------------------------------------------------------- per shot ---------------------------------------
+
+def measure_shot(frames: list, faces: dict, features: dict, duration: float) -> dict:
+ """faces: faces.shot_faces() output (picked frame indexes with their main face)."""
+ picked = [p for p in faces.get("frames", []) if p["i"] < len(frames)] or [{"i": i, "face": None} for i in range(0, len(frames), max(1, len(frames) // 6))]
+ fr = [frames[p["i"]] for p in picked]
+ subs = [subject(frames[p["i"]], p.get("face")) for p in picked]
+ ctx = ShotCtx(frames=fr, subjects=subs, features=features, duration=duration)
+ out = {}
+ for a in REGISTRY:
+ m = a.measure(ctx)
+ if m:
+ out[a.key] = {"measured": m}
+ return out
+
+
+# ---------------------------------------------------------------- questions for image readers --------------------
+
+def _fields(video: bool) -> dict[str, dict[str, str]]:
+ out = {}
+ for a in REGISTRY:
+ fs = a.video_fields if video else a.shot_fields
+ if fs:
+ out[a.key] = {f.key: f.question for f in fs}
+ return out
+
+
+def prompt_block(video: bool = False, indent: int = 2) -> str:
+ """JSON skeleton for the VLM prompt, braces doubled for str.format()."""
+ txt = json.dumps(_fields(video), ensure_ascii=False, indent=indent)
+ txt = txt.replace("{", "{{").replace("}", "}}")
+ return "\n".join((" " * indent + l if i else l) for i, l in enumerate(txt.splitlines()))
+
+
+def review_template(video: bool = False) -> dict:
+ return {k: {f: "" for f in v} for k, v in _fields(video).items()}
+
+
+def review_guide() -> str:
+ lines = []
+ for a in REGISTRY:
+ for f in a.shot_fields:
+ lines.append(f" {a.key}.{f.key}({f.zh}):{f.question}")
+ return "\n".join(lines)
+
+
+def clean_answers(d, video: bool = False) -> dict:
+ """Keep only known aspect fields with non-empty string answers."""
+ if not isinstance(d, dict):
+ return {}
+ out = {}
+ for k, fields in _fields(video).items():
+ sub = d.get(k) if isinstance(d.get(k), dict) else {}
+ vals = {f: str(sub[f]).strip() for f in fields if str(sub.get(f, "") or "").strip()}
+ if vals:
+ out[k] = vals
+ return out
+
+
+# ---------------------------------------------------------------- per video ---------------------------------------
+
+def finalize(b: dict) -> dict:
+ """Interpret every shot, then summarise per aspect. Needs base labels (call after fusion)."""
+ for r in b["shots"]:
+ asp = r.setdefault("aspects", {})
+ if r["base"]["label"] not in PHOTOGRAPHIC:
+ for v in asp.values():
+ v.pop("result", None)
+ continue
+ for a in REGISTRY:
+ res = a.interpret(r)
+ if res:
+ asp.setdefault(a.key, {})["result"] = res
+ b["aspects"] = {}
+ for a in REGISTRY:
+ s = a.summarize(b["shots"], b)
+ if s:
+ b["aspects"][a.key] = s
+ b["shooting_plan"] = shooting_plan(b)
+ return b["aspects"]
+
+
+def shooting_plan(b: dict) -> dict:
+ """How to film it again: format, framing, camera, lighting set-up with gear, editing rules."""
+ A = b.get("aspects") or {}
+ if not (A.get("lighting") or {}).get("filmed"):
+ return {}
+ fr, cam, li, ed, fo = (A.get(k) or {} for k in ("framing", "camera", "lighting", "editing", "format"))
+ steps = []
+ if fo:
+ steps.append(f"形式:{fo['lines'][0].split(':', 1)[1].split('(')[0]}")
+ if fr.get("result", {}).get("shot_size"):
+ steps.append(f"取景:以{fr['result']['shot_size']}为主" + (f",{fr['result']['camera_angle']}" if fr["result"].get("camera_angle") else ""))
+ if cam.get("lines"):
+ steps.append(cam["lines"][0])
+ st = li.get("setup") or {}
+ if st:
+ steps.append(f"布光:{st['name']}——{st['detail']}")
+ if ed.get("lines"):
+ steps.append(ed["lines"][0])
+ return {"steps": steps, "gear": st.get("gear", [])}
+
+
+def summary_lines(b: dict) -> list[str]:
+ out = []
+ for a in REGISTRY:
+ out += (b.get("aspects") or {}).get(a.key, {}).get("lines", [])
+ return out
+
+
+def check(gt: dict, b: dict) -> dict[str, bool]:
+ """gt: {aspect: {field: accepted value(s)}}."""
+ out = {}
+ for k, want in (gt or {}).items():
+ a = get(k)
+ if a:
+ for f, ok in a.check(want, (b.get("aspects") or {}).get(k) or {}).items():
+ out[f"{k}.{f}"] = ok
+ return out
+
+
+def shot_text(r: dict) -> str:
+ asp = r.get("aspects") or {}
+ fr, cam, li = ((asp.get(k) or {}).get("result") or {} for k in ("framing", "camera", "lighting"))
+ parts = [fr.get("shot_size"), fr.get("camera_angle"), cam.get("support_zh"),
+ li.get("setup_name"), li.get("key_direction") and f"主光{li['key_direction']}", li.get("ratio") and f"光比{li['ratio']}",
+ li.get("quality")]
+ return ";".join(p for p in parts if p)
+
+
+# ---------------------------------------------------------------- report -----------------------------------------
+
+def _src(row: dict) -> str:
+ bits = []
+ if row.get("measured") not in (None, ""):
+ bits.append(f"测量:{row['measured']}")
+ if row.get("vlm"):
+ bits.append(f"VLM:{row['vlm']}")
+ if row.get("agent"):
+ bits.append(f"看图:{row['agent']}")
+ return ";".join(bits)
+
+
+def report_md(b: dict) -> list[str]:
+ A = b.get("aspects") or {}
+ if not any(A.get(a.key) for a in REGISTRY):
+ return []
+ li = A.get("lighting") or {}
+ L = ["", "## 拍法、打光与剪辑", ""]
+ L += [f"- {x}" for x in summary_lines(b)]
+ plan = b.get("shooting_plan") or {}
+ if plan:
+ L += ["", "**复刻拍摄方案**", ""] + [f"{i}. {s}" for i, s in enumerate(plan["steps"], 1)]
+ if plan.get("gear"):
+ L += ["", "器材:"] + [f"- {g}" for g in plan["gear"]]
+ if (li.get("setup") or {}).get("notes"):
+ L += [f"- 注意:{n}" for n in li["setup"]["notes"]]
+ rows = [(a, r) for a in REGISTRY for r in (A.get(a.key) or {}).get("fields", [])]
+ if rows:
+ L += ["", "| 维度 | 项目 | 结论 | 来源 |", "|---|---|---|---|"]
+ for a, r in rows:
+ L.append(f"| {a.title} | {r['zh']} | {str(r['final']).replace('|', '/')} | {_src(r).replace('|', '/')} |")
+ L += ["", "- 说明:光比、软硬、色温、景别由主体像素测得(有人脸用人脸,没有用画面清晰区域,后者是估算);平台转码会压暗部,软硬和补光偏保守;"
+ "机位角度、光源种类、眼神光、轮廓光以看图结果为准。测量和看图不一致时两者都列出。"]
+ return L
+
+
+def report_html(b: dict) -> str:
+ A = b.get("aspects") or {}
+ if not any(A.get(a.key) for a in REGISTRY):
+ return ""
+ esc = html.escape
+ items = "".join(f"<li>{esc(x)}</li>" for x in summary_lines(b))
+ plan = b.get("shooting_plan") or {}
+ plan_html = ""
+ if plan:
+ plan_html = ("<h4>复刻拍摄方案</h4><ol>" + "".join(f"<li>{esc(s)}</li>" for s in plan["steps"]) + "</ol>"
+ + ("<h4>器材</h4><ul>" + "".join(f"<li>{esc(g)}</li>" for g in plan.get("gear", [])) + "</ul>" if plan.get("gear") else ""))
+ rows = "".join(f"<tr><td>{esc(a.title)}</td><td>{esc(r['zh'])}</td><td>{esc(str(r['final']))}</td><td class='muted'>{esc(_src(r))}</td></tr>"
+ for a in REGISTRY for r in (A.get(a.key) or {}).get("fields", []))
+ table = f"<table style='width:100%;font-size:13px;border-collapse:collapse'>{rows}</table>" if rows else ""
+ return f"<section class='shot'><h3 style='margin:4px 0'>拍法、打光与剪辑</h3><ul>{items}</ul>{plan_html}{table}</section>"
diff --git a/rea_video/aspects/base.py b/rea_video/aspects/base.py
new file mode 100644
index 0000000..ef4b266
--- /dev/null
+++ b/rea_video/aspects/base.py
@@ -0,0 +1,163 @@
+"""Aspect framework: one production question ("how was it lit?", "how was it framed?") end to end.
+
+An aspect owns every step for its question, so adding a new one (composition, wardrobe, props, colour grade ...)
+means adding one module and registering it, without touching the pipeline, prompts, review, report or eval:
+
+ measure(ctx) per shot, deterministic, from pixels / features -> rec["aspects"][key]["measured"]
+ shot_fields questions the VLM and the reviewing agent answer per shot (what pixels cannot settle)
+ video_fields questions about the whole video (whole-video VLM pass, review answers "aspects")
+ interpret(shot) per-shot reading in plain words -> rec["aspects"][key]["result"]
+ summarize(shots, b) video-level result: `result` (comparable values for eval), `lines`, `fields`, extras
+ check(gt, summary) eval: {field: accepted value(s)} against summary["result"]
+
+Sources are kept apart and shown side by side: `measured` (tools), `vlm`, `agent`. A field marked
+`prefer="seen"` takes the image readers' answer (agent before VLM); `prefer="measured"` keeps the measurement and
+lists what the readers said next to it. Nothing is averaged across sources."""
+from __future__ import annotations
+
+from collections import Counter
+from dataclasses import dataclass, field
+
+import numpy as np
+
+# shots whose picture is photographic enough for camera / light analysis. Live action gets a shooting plan; AI, 3D
+# and avatar shots get the same measurements as a description of the picture (useful for generation prompts).
+PHOTOGRAPHIC = ("live_action", "avatar", "ai_video", "cg_3d")
+FILMED = ("live_action", "avatar")
+
+
+@dataclass
+class Field:
+ key: str
+ zh: str
+ question: str # shown to the VLM / reviewer; empty = measured only
+ prefer: str = "measured" # "measured" | "seen"
+
+
+@dataclass
+class ShotCtx:
+ """Everything an aspect may measure from, for one shot."""
+ frames: list # sampled BGR frames (analysis width)
+ subjects: list # per sampled frame: subject dict or None (see aspects.subject)
+ features: dict # forensic features of the shot (motion, texture, ...)
+ duration: float
+
+
+@dataclass
+class Aspect:
+ key: str = ""
+ title: str = ""
+ shot_fields: list[Field] = field(default_factory=list)
+ video_fields: list[Field] = field(default_factory=list)
+
+ # ---- per shot ----------------------------------------------------------------------------
+ def measure(self, ctx: ShotCtx) -> dict:
+ return {}
+
+ def interpret(self, shot: dict) -> dict:
+ """Plain-language reading of one shot; default: measured values + what the readers saw."""
+ return {}
+
+ # ---- per video ---------------------------------------------------------------------------
+ def summarize(self, shots: list[dict], b: dict) -> dict:
+ return {}
+
+ def check(self, gt: dict, summary: dict) -> dict[str, bool]:
+ res = (summary or {}).get("result") or {}
+ out = {}
+ for k, want in gt.items():
+ acc = want if isinstance(want, list) else [want]
+ out[k] = res.get(k) in acc
+ return out
+
+
+REGISTRY: list[Aspect] = []
+
+
+def register(a: Aspect) -> Aspect:
+ if not any(x.key == a.key for x in REGISTRY):
+ REGISTRY.append(a)
+ return a
+
+
+def get(key: str) -> Aspect | None:
+ return next((a for a in REGISTRY if a.key == key), None)
+
+
+# ---------------------------------------------------------------- what the image readers said ----
+
+def seen(shot: dict, aspect: str, field_key: str) -> dict[str, str]:
+ """{"agent": ..., "vlm": ...} for one field of one shot. Also reads the older flat `cinematography` answers."""
+ out = {}
+ for src, rk in (("agent", "review"), ("vlm", "vlm")):
+ r = shot.get(rk) or {}
+ v = ((r.get("aspects") or {}).get(aspect) or {}).get(field_key) or (r.get("cinematography") or {}).get(field_key)
+ if v and str(v).strip() not in ("不适用", "unknown", "无法判断"):
+ out[src] = str(v).strip()
+ return out
+
+
+def video_seen(b: dict, aspect: str, field_key: str) -> dict[str, str]:
+ out = {}
+ rv = ((b.get("review_aspects") or {}).get(aspect) or {}).get(field_key)
+ if rv:
+ out["agent"] = str(rv)
+ wv = ((((b.get("whole_video_vlm") or {}).get("aspects") or {}).get(aspect) or {}).get(field_key))
+ if wv:
+ out["vlm"] = str(wv)
+ return out
+
+
+def pick(sources: dict[str, str], measured=None, prefer: str = "measured"):
+ """Final value of a field from its sources."""
+ if prefer == "seen":
+ return sources.get("agent") or sources.get("vlm") or measured
+ return measured if measured is not None else (sources.get("agent") or sources.get("vlm"))
+
+
+def mode_seen(shots: list[dict], aspect: str, field_key: str) -> dict[str, str]:
+ """Most common answer per source across shots, weighted by duration."""
+ out = {}
+ for src in ("agent", "vlm"):
+ c: Counter = Counter()
+ for r in shots:
+ v = seen(r, aspect, field_key).get(src)
+ if v:
+ c[v] += r["duration"]
+ if c:
+ out[src] = c.most_common(1)[0][0]
+ return out
+
+
+def field_table(aspect: Aspect, shots: list[dict], b: dict, measured: dict) -> list[dict]:
+ """One row per field: measured value, what the VLM / agent said, final value."""
+ rows = []
+ for f in aspect.shot_fields + aspect.video_fields:
+ src = {**mode_seen(shots, aspect.key, f.key), **video_seen(b, aspect.key, f.key)} if f in aspect.shot_fields \
+ else video_seen(b, aspect.key, f.key)
+ m = measured.get(f.key)
+ final = pick(src, m, f.prefer)
+ if final is None:
+ continue
+ rows.append({"key": f.key, "zh": f.zh, "measured": m, "vlm": src.get("vlm"), "agent": src.get("agent"), "final": final})
+ return rows
+
+
+def weighted_median(pairs: list[tuple[float, float]]) -> float | None:
+ """(value, weight) pairs -> weighted median."""
+ pairs = [(v, w) for v, w in pairs if v is not None]
+ if not pairs:
+ return None
+ pairs.sort()
+ cw = np.cumsum([w for _, w in pairs])
+ return float(pairs[int(np.searchsorted(cw, cw[-1] / 2))][0])
+
+
+def weighted_mode(pairs: list[tuple[str, float]]) -> tuple[str | None, dict[str, float]]:
+ c: Counter = Counter()
+ for v, w in pairs:
+ if v:
+ c[v] += w
+ tot = sum(c.values()) or 1.0
+ share = {k: round(v / tot, 3) for k, v in c.most_common()}
+ return (c.most_common(1)[0][0] if c else None), share
diff --git a/rea_video/aspects/camera.py b/rea_video/aspects/camera.py
new file mode 100644
index 0000000..e706d81
--- /dev/null
+++ b/rea_video/aspects/camera.py
@@ -0,0 +1,59 @@
+"""Camera: how the camera was held and moved, which lens / device.
+
+Support and movement come from the global-motion fit already computed for every shot (features.motion_summary):
+jittery translation = handheld, smooth translation = moving rig or careful handheld, none = fixed. Lens and device
+are the image readers' call (perspective distortion, depth of field, picture quality)."""
+from __future__ import annotations
+
+from .base import FILMED, PHOTOGRAPHIC, Aspect, Field, ShotCtx, field_table, register, seen, weighted_mode
+
+SUPPORT = {"handheld_like": "handheld", "smooth_move": "moving", "static": "fixed", "static_with_subject_motion": "fixed",
+ "planar_zoom_pan": "fixed"}
+SUPPORT_ZH = {"handheld": "手持", "moving": "移动机位(稳定器/手持平移)", "fixed": "固定机位(三脚架/支架/放在桌上)"}
+
+
+class Camera(Aspect):
+ def __init__(self):
+ super().__init__(key="camera", title="机位", shot_fields=[
+ Field("camera_support", "拍摄方式", "手持自拍(前置镜头)|他人手持|三脚架/支架固定|稳定器|桌面俯拍支架|无法判断", prefer="seen"),
+ Field("lens", "镜头", "手机前置广角|手机后置主摄|手机长焦|相机人像/长焦|无法判断(依据:透视变形、背景虚化)", prefer="seen"),
+ ], video_fields=[
+ Field("setups", "机位/场景", "一共几个场景、几个机位,各拍什么", prefer="seen"),
+ Field("gear_guess", "推测设备", "手机/相机档次、稳定器、麦克风(领夹麦/机顶麦)、补光灯等,写依据", prefer="seen"),
+ ])
+
+ def measure(self, ctx: ShotCtx) -> dict:
+ f = ctx.features
+ cam = f.get("camera")
+ move = None
+ z, pan = f.get("zoom_per_s", 0.0) or 0.0, f.get("pan_px_per_s", 0.0) or 0.0
+ if abs(z) > 0.01:
+ move = "推" if z > 0 else "拉"
+ elif pan > 6:
+ move = "摇/移"
+ return {"support": SUPPORT.get(cam), "motion": cam, "move": move,
+ "shake": round(float(f.get("sign_flip_rate", 0.0) or 0.0), 3)}
+
+ def interpret(self, shot: dict) -> dict:
+ m = ((shot.get("aspects") or {}).get(self.key) or {}).get("measured") or {}
+ s = seen(shot, self.key, "camera_support")
+ return {"support": m.get("support"), "support_zh": s.get("agent") or s.get("vlm") or SUPPORT_ZH.get(m.get("support")),
+ "move": m.get("move")}
+
+ def summarize(self, shots: list[dict], b: dict) -> dict:
+ main = [r for r in shots if r["base"]["label"] in FILMED] or [r for r in shots if r["base"]["label"] in PHOTOGRAPHIC]
+ if not main:
+ return {}
+ res = {r["index"]: (r.get("aspects") or {}).get(self.key, {}).get("result") or {} for r in main}
+ sup, shares = weighted_mode([(res[r["index"]].get("support"), r["duration"]) for r in main])
+ # "mixed" when a second way of holding the camera covers a real part of the video
+ second = sorted(shares.items(), key=lambda kv: -kv[1])[1:2]
+ support = "mixed" if second and second[0][1] >= 0.3 else sup
+ moves, _ = weighted_mode([(res[r["index"]].get("move"), r["duration"]) for r in main])
+ text = "、".join(f"{SUPPORT_ZH.get(k, k)} {v:.0%}" for k, v in shares.items())
+ lines = [f"机位:{text or '未测出'}" + (f";常见运镜 {moves}" if moves else "")]
+ return {"result": {"support": support}, "support_shares": shares, "lines": lines,
+ "fields": field_table(self, main, b, {"camera_support": SUPPORT_ZH.get(support, "混合:" + text) if support else None})}
+
+
+register(Camera())
diff --git a/rea_video/aspects/editing.py b/rea_video/aspects/editing.py
new file mode 100644
index 0000000..12e953f
--- /dev/null
+++ b/rea_video/aspects/editing.py
@@ -0,0 +1,117 @@
+"""Editing: pace, camera positions, how filmed shots are joined, how much is inserted material.
+
+ camera positions filmed shots clustered by the colour layout of their background (subject masked out)
+ jump cut two consecutive filmed shots from the same position at the same scale (pauses / fluffs cut out)
+ punch-in same position, subject >= 1.2x bigger or smaller (a crop to change rhythm)
+ cuts in pauses share of cuts between filmed shots that land in a gap of the voice track (cutting on breaths)
+ insert share time not covered by filmed shots: screenshots, recordings, cards, stock, AI shots"""
+from __future__ import annotations
+
+import cv2
+import numpy as np
+
+from .base import FILMED, Aspect, Field, ShotCtx, field_table, register
+
+SAME_POSITION = 18.0 # mean |diff| of 0..255 BGR cells of the 6x10 background layout
+
+
+def bg_signature(bgr: np.ndarray, subj: dict | None) -> list[float]:
+ small = cv2.resize(bgr, (6, 10), interpolation=cv2.INTER_AREA).astype(np.float32)
+ keep = np.ones((10, 6), bool)
+ if subj and subj["kind"] != "frame":
+ bx, by, bw, bh = subj["box"]
+ grow = 0.5 if subj["kind"] == "face" else 0.1
+ x0, y0 = max(0, int((bx - grow * bw) * 6)), max(0, int((by - 0.3 * bh) * 10))
+ x1 = min(6, int(np.ceil((bx + (1 + grow) * bw) * 6)))
+ y1 = 10 if subj["kind"] == "face" else min(10, int(np.ceil((by + 1.1 * bh) * 10)))
+ keep[y0:y1, x0:x1] = False
+ small[~keep] = -1
+ return [round(float(v), 1) for v in small.ravel()]
+
+
+def _dist(a: list[float], b: list[float]) -> float:
+ pairs = [(x, y) for x, y in zip(a or [], b or []) if x >= 0 and y >= 0]
+ return float(np.mean([abs(x - y) for x, y in pairs])) if len(pairs) >= 8 else 1e9
+
+
+def _scale(r: dict) -> float | None:
+ m = ((r.get("aspects") or {}).get("framing") or {}).get("measured") or {}
+ return m.get("face_h") or (m.get("area") ** 0.5 if m.get("area") else None)
+
+
+def _in_gap(t: float, segs: list, tol: float = 0.25) -> bool:
+ for a, b in segs:
+ if a + tol < t < b - tol:
+ return False
+ return True
+
+
+class Editing(Aspect):
+ def __init__(self):
+ super().__init__(key="editing", title="剪辑", video_fields=[
+ Field("editing", "剪辑手法", "剪气口/跳切、推近放大、多机位切换、插入截图/素材的节奏、转场、卡点", prefer="seen"),
+ ])
+
+ def measure(self, ctx: ShotCtx) -> dict:
+ if not ctx.frames:
+ return {}
+ i = len(ctx.frames) // 2
+ return {"bg_signature": bg_signature(ctx.frames[i], ctx.subjects[i] if i < len(ctx.subjects) else None)}
+
+ def summarize(self, shots: list[dict], b: dict) -> dict:
+ total = sum(r["duration"] for r in shots) or 1.0
+ filmed = [r for r in shots if r["base"]["label"] in FILMED]
+ f_dur = sum(r["duration"] for r in filmed)
+ out = {"cuts_per_min": round(max(0, len(shots) - 1) / (total / 60), 1), "avg_shot_s": round(total / max(1, len(shots)), 2),
+ "filmed_share": round(f_dur / total, 3), "insert_share": round(1 - f_dur / total, 3)}
+ if not filmed:
+ out["lines"] = [f"剪辑:每分钟 {out['cuts_per_min']} 刀,平均镜头 {out['avg_shot_s']}s;没有实拍镜头"]
+ out["result"] = {}
+ return out
+ centers: list[list[float]] = []
+ pos = {}
+ for r in filmed:
+ sig = ((r.get("aspects") or {}).get(self.key) or {}).get("measured", {}).get("bg_signature") or []
+ d = [(_dist(sig, c), i) for i, c in enumerate(centers)]
+ best = min(d) if d else (1e9, -1)
+ if best[0] > SAME_POSITION:
+ centers.append(sig)
+ pos[r["index"]] = len(centers) - 1
+ else:
+ pos[r["index"]] = best[1]
+ share: dict[int, float] = {}
+ for r in filmed:
+ share[pos[r["index"]]] = share.get(pos[r["index"]], 0.0) + r["duration"]
+ n_pos = sum(1 for v in share.values() if v / f_dur >= 0.08)
+ jump = punch = in_gap = joins = 0
+ voice = ((b.get("audio") or {}).get("voice") or {}).get("segments") or []
+ for prev, cur in zip(shots, shots[1:]):
+ if prev["base"]["label"] not in FILMED or cur["base"]["label"] not in FILMED:
+ continue
+ joins += 1
+ if voice and _in_gap(cur["start"], voice):
+ in_gap += 1
+ if pos.get(prev["index"]) != pos.get(cur["index"]):
+ continue
+ s0, s1 = _scale(prev), _scale(cur)
+ if s0 and s1 and max(s0, s1) / min(s0, s1) >= 1.2:
+ punch += 1
+ else:
+ jump += 1
+ out.update(positions=n_pos, position_shares=sorted((round(v / f_dur, 3) for v in share.values()), reverse=True)[:5],
+ avg_filmed_shot_s=round(f_dur / len(filmed), 2), jump_cuts=jump, punch_ins=punch,
+ filmed_joins=joins, cuts_in_pauses=round(in_gap / joins, 3) if joins and voice else None,
+ beat_synced=bool((b.get("audio") or {}).get("beat_synced_edit")))
+ line = (f"剪辑:每分钟 {out['cuts_per_min']} 刀,实拍镜头平均 {out['avg_filmed_shot_s']}s;机位/场景 {n_pos} 个;"
+ f"同机位跳切 {jump} 处、推近切 {punch} 处;插入画面(截图/录屏/卡片/素材)占 {out['insert_share']:.0%}")
+ if out["cuts_in_pauses"] is not None and joins >= 3:
+ line += f";{out['cuts_in_pauses']:.0%} 的切点落在说话停顿处" + ("(剪气口)" if out["cuts_in_pauses"] >= 0.6 else "")
+ if out["beat_synced"]:
+ line += ";切镜卡在音乐节拍上"
+ out["lines"] = [line]
+ out["result"] = {"positions": n_pos, "jump_cuts": jump > 0}
+ out["fields"] = field_table(self, filmed, b, {})
+ return out
+
+
+register(Editing())
diff --git a/rea_video/aspects/fmt.py b/rea_video/aspects/fmt.py
new file mode 100644
index 0000000..cbb4cdb
--- /dev/null
+++ b/rea_video/aspects/fmt.py
@@ -0,0 +1,60 @@
+"""Format: what kind of filmed video this is, so the shooting plan speaks the right language.
+
+ talking_head a face is the subject of most filmed time and someone speaks (口播 / 访谈 / vlog 自拍)
+ desk no face as the subject, in-focus hands / objects, fixed camera, often shot from above (桌拍 / 教程)
+ product no face as the subject, objects / hands, handheld camera (开箱 / 带货 / 第一视角 POV)
+ vlog people or places, handheld, several places
+ other
+The image readers' answer to `format` wins when present."""
+from __future__ import annotations
+
+from .base import FILMED, Aspect, Field, field_table, register, video_seen
+
+FORMAT_ZH = {"talking_head": "人物口播", "desk": "桌面/物品拍摄(桌拍)", "product": "手持拍物品(开箱/带货/第一视角)",
+ "vlog": "vlog 随拍", "other": "其他实拍"}
+
+
+class Format(Aspect):
+ def __init__(self):
+ super().__init__(key="format", title="形式", video_fields=[
+ Field("format", "视频形式", "单人口播|访谈|桌面俯拍/开箱/教程|vlog 跟拍|商品展示|剧情|无实拍", prefer="seen"),
+ ])
+
+ def summarize(self, shots: list[dict], b: dict) -> dict:
+ filmed = [r for r in shots if r["base"]["label"] in FILMED]
+ f_dur = sum(r["duration"] for r in filmed)
+ if not filmed or f_dur < 0.2 * (sum(r["duration"] for r in shots) or 1):
+ return {}
+
+ def share(pred) -> float:
+ return sum(r["duration"] for r in filmed if pred(r)) / f_dur
+
+ def asp(r, k):
+ return ((r.get("aspects") or {}).get(k) or {}).get("result") or {}
+
+ face = share(lambda r: asp(r, "framing").get("subject") == "face")
+ focus = share(lambda r: asp(r, "framing").get("subject") == "focus")
+ from_above = share(lambda r: any(w in (asp(r, "framing").get("camera_angle") or "") for w in ("顶拍", "俯拍")))
+ fixed = share(lambda r: asp(r, "camera").get("support") == "fixed")
+ handheld = share(lambda r: asp(r, "camera").get("support") in ("handheld", "moving"))
+ speech = bool(((b.get("audio") or {}).get("voice") or {}).get("present"))
+ positions = ((b.get("aspects") or {}).get("editing") or {}).get("positions") or 1
+ if face >= 0.5 and speech:
+ kind = "talking_head"
+ elif focus >= 0.5 and (from_above >= 0.3 or fixed >= 0.5):
+ kind = "desk"
+ elif focus >= 0.5 and handheld >= 0.5:
+ kind = "product"
+ elif handheld >= 0.5 and positions >= 2:
+ kind = "vlog"
+ else:
+ kind = "other"
+ seen = video_seen(b, self.key, "format")
+ lines = [f"形式:{FORMAT_ZH[kind]}(人脸为主体 {face:.0%}、物品/手为主体 {focus:.0%}、手持 {handheld:.0%})"
+ + (f";看图判断:{seen.get('agent') or seen.get('vlm')}" if seen else "")]
+ return {"result": {"format": kind}, "shares": {"face": round(face, 3), "focus": round(focus, 3), "from_above": round(from_above, 3),
+ "fixed": round(fixed, 3), "handheld": round(handheld, 3)},
+ "lines": lines, "fields": field_table(self, filmed, b, {"format": FORMAT_ZH[kind]})}
+
+
+register(Format())
diff --git a/rea_video/aspects/framing.py b/rea_video/aspects/framing.py
new file mode 100644
index 0000000..a95a102
--- /dev/null
+++ b/rea_video/aspects/framing.py
@@ -0,0 +1,85 @@
+"""Framing: shot size, where the subject sits, camera angle.
+
+Shot size is measured from the face height when there is a face (reliable), else estimated from the in-focus
+subject's area (rough: a hand on a desk and a product close-up can both fill the frame); camera angle comes from
+the image readers."""
+from __future__ import annotations
+
+import numpy as np
+
+from .base import FILMED, PHOTOGRAPHIC, Aspect, Field, ShotCtx, field_table, register, seen, weighted_mode
+
+# face height / frame height
+FACE_SIZES = [(0.40, "大特写"), (0.25, "特写"), (0.14, "近景"), (0.08, "中景"), (0.04, "全景"), (0.0, "远景")]
+# in-focus subject area / frame area
+AREA_SIZES = [(0.45, "特写"), (0.22, "近景"), (0.08, "中景"), (0.0, "全景")]
+
+
+def size_from(table, v: float | None) -> str | None:
+ if v is None:
+ return None
+ return next(name for th, name in table if v >= th)
+
+
+def shot_size(face_h: float | None) -> str | None:
+ return size_from(FACE_SIZES, face_h)
+
+
+class Framing(Aspect):
+ def __init__(self):
+ super().__init__(key="framing", title="取景", shot_fields=[
+ Field("shot_size", "景别", "特写|近景|中景|全景|远景(按画面主体,人物按头肩/半身/全身)"),
+ Field("camera_angle", "机位角度", "平视|略俯拍|俯拍|顶拍(正上方俯拍桌面)|略仰拍|仰拍", prefer="seen"),
+ Field("composition", "构图", "主体位置与留白(居中/三分线/对称/框中框),竖屏还是横屏", prefer="seen"),
+ ])
+
+ def measure(self, ctx: ShotCtx) -> dict:
+ subs = [s for s in ctx.subjects if s]
+ if not subs:
+ return {}
+ kinds = [s["kind"] for s in subs]
+ kind = max(set(kinds), key=kinds.count)
+ use = [s for s in subs if s["kind"] == kind]
+ hs = [s["box"][3] for s in use]
+ cx = float(np.median([s["box"][0] + s["box"][2] / 2 for s in use]))
+ cy = float(np.median([s["box"][1] + s["box"][3] / 2 for s in use]))
+ area = float(np.median([s["area"] for s in use]))
+ out = {"subject": kind, "subject_share": round(len(use) / max(1, len(ctx.subjects)), 3),
+ "center_x": round(cx, 3), "center_y": round(cy, 3), "area": round(area, 3)}
+ if kind == "face":
+ fh = float(np.median(hs))
+ out.update(face_h=round(fh, 3), face_h_spread=round(float(np.std(hs)), 3), shot_size=shot_size(fh),
+ headroom=round(float(np.median([s["box"][1] for s in use])), 3))
+ elif kind == "focus":
+ out["shot_size"] = size_from(AREA_SIZES, area)
+ out["shot_size_rough"] = True
+ out["position"] = "居中" if abs(cx - 0.5) < 0.12 else ("偏左" if cx < 0.5 else "偏右")
+ return out
+
+ def interpret(self, shot: dict) -> dict:
+ m = ((shot.get("aspects") or {}).get(self.key) or {}).get("measured") or {}
+ s = seen(shot, self.key, "shot_size")
+ size = m.get("shot_size") if m.get("subject") == "face" else (s.get("agent") or s.get("vlm") or m.get("shot_size"))
+ ang = seen(shot, self.key, "camera_angle")
+ return {"shot_size": size, "camera_angle": ang.get("agent") or ang.get("vlm"), "position": m.get("position"),
+ "subject": m.get("subject")}
+
+ def summarize(self, shots: list[dict], b: dict) -> dict:
+ main = [r for r in shots if r["base"]["label"] in FILMED] or [r for r in shots if r["base"]["label"] in PHOTOGRAPHIC]
+ if not main:
+ return {}
+ tot = sum(r["duration"] for r in main)
+ res = {r["index"]: (r.get("aspects") or {}).get(self.key, {}).get("result") or {} for r in main}
+ size, sizes = weighted_mode([(res[r["index"]].get("shot_size"), r["duration"]) for r in main])
+ angle, angles = weighted_mode([(res[r["index"]].get("camera_angle"), r["duration"]) for r in main])
+ subj, subjects = weighted_mode([(res[r["index"]].get("subject"), r["duration"]) for r in main])
+ lines = [f"取景:景别 " + ("、".join(f"{k} {v:.0%}" for k, v in list(sizes.items())[:3] if v >= 0.01) or "未测出")
+ + (f";机位角度 {angle}" if angle else "")
+ + {"face": ";主体是人脸(按脸高算景别)", "focus": ";主体是画面清晰区域(没有人脸,景别为估算)",
+ "frame": ";没找到明确主体"}.get(subj, "")]
+ return {"result": {"shot_size": size, "camera_angle": angle, "subject": subj},
+ "shot_sizes": sizes, "angles": angles, "subjects": subjects, "seconds": round(tot, 2), "lines": lines,
+ "fields": field_table(self, main, b, {"shot_size": size})}
+
+
+register(Framing())
diff --git a/rea_video/aspects/lighting.py b/rea_video/aspects/lighting.py
new file mode 100644
index 0000000..4c11e45
--- /dev/null
+++ b/rea_video/aspects/lighting.py
@@ -0,0 +1,228 @@
+"""Lighting: where the key light comes from, how strong against the shadow side, how soft, what colour, what else
+is lit; then a named set-up with gear to rebuild it.
+
+Measured on the frame's subject (aspects.subject): the face split at the nose, or the in-focus region split at its
+centre. In linear light:
+ ratio brighter half / darker half (light ratio; 2:1 = one stop)
+ key_side which half of the picture is brighter
+ top_bottom upper / lower part of the subject (light from above vs from below: screens, desk bounce)
+ transition width of the lit -> shadow ramp across the subject (narrow = hard light); only when ratio >= 1.4
+ subject_luma / bg_luma / dark_share / point_lights exposure, separation, low light, visible lamps
+ warmth / bg_warmth Lab b* of subject and lit background (mixed colour temperatures)
+ bg_blur background sharpness / subject sharpness (shallow depth of field)
+The set-up table (SETUPS) maps these to a named set-up; add rows there for new lighting styles. Rim light, catchlight
+shape and the actual light source are the image readers' call. Platform transcodes crush shadows: hardness and
+fill are the least reliable measurements."""
+from __future__ import annotations
+
+import math
+
+import cv2
+import numpy as np
+
+from .base import FILMED, PHOTOGRAPHIC, Aspect, Field, ShotCtx, field_table, register, seen, weighted_median, weighted_mode
+
+MEASURES = ("ratio", "top_bottom", "transition", "subject_luma", "bg_luma", "dark_share", "warmth", "bg_warmth", "bg_blur", "point_lights")
+
+
+def _lin(gray: np.ndarray) -> np.ndarray:
+ return (gray.astype(np.float32) / 255.0) ** 2.2
+
+
+def _px(x0: float, y0: float, x1: float, y1: float, w: int, h: int) -> tuple[int, int, int, int]:
+ return max(0, int(x0 * w)), max(0, int(y0 * h)), min(w, int(x1 * w)), min(h, int(y1 * h))
+
+
+def frame_light(bgr: np.ndarray, subj: dict) -> dict | None:
+ """Lighting measurements of one frame around its subject."""
+ h, w = bgr.shape[:2]
+ bx, by, bw, bh = subj["box"]
+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
+ lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)
+ lm = subj.get("landmarks")
+ if subj["kind"] == "face": # skin band below the hairline, inside the cheeks; split at the nose
+ x0, y0, x1, y1 = _px(bx + 0.12 * bw, by + 0.25 * bh, bx + 0.88 * bw, by + 0.92 * bh, w, h)
+ mid = lm[2][0] if lm else bx + bw / 2
+ bg_box = (bx - 0.6 * bw, by - 0.4 * bh, bx + 1.6 * bw, 1.0) # head and shoulders
+ else:
+ x0, y0, x1, y1 = _px(bx, by, bx + bw, by + bh, w, h)
+ mid = bx + bw / 2
+ bg_box = (bx - 0.1 * bw, by - 0.1 * bh, bx + 1.1 * bw, by + 1.1 * bh)
+ xm = int(mid * w)
+ if x1 - x0 < 12 or y1 - y0 < 12 or not (x0 + 4 < xm < x1 - 4):
+ return None
+ region = gray[y0:y1, x0:x1]
+ lmean = float(_lin(gray[y0:y1, x0:xm]).mean()) + 1e-4
+ rmean = float(_lin(gray[y0:y1, xm:x1]).mean()) + 1e-4
+ ratio = max(lmean, rmean) / min(lmean, rmean)
+ key_side = "left" if lmean > rmean else "right"
+ top = float(_lin(gray[y0:int(y0 + 0.35 * (y1 - y0)), x0:x1]).mean()) + 1e-4
+ bottom = float(_lin(gray[int(y0 + 0.65 * (y1 - y0)):y1, x0:x1]).mean()) + 1e-4
+ transition = None
+ if ratio >= 1.4:
+ prof = _lin(gray[y0 + (y1 - y0) // 4: y0 + 3 * (y1 - y0) // 4, x0:x1]).mean(axis=0)
+ k = max(3, (len(prof) // 12) | 1)
+ prof = np.convolve(prof, np.ones(k) / k, mode="valid")
+ if len(prof) > 8:
+ p = prof if key_side == "right" else prof[::-1] # rise from shadow to lit
+ lo, hi = float(np.percentile(p, 10)), float(np.percentile(p, 90))
+ if hi - lo > 1e-3:
+ transition = max(0, int(np.argmax(p >= lo + 0.8 * (hi - lo))) - int(np.argmax(p >= lo + 0.2 * (hi - lo)))) / len(p)
+ mask = np.ones((h, w), bool)
+ a0, b0, a1, b1 = _px(*bg_box, w, h)
+ mask[b0:b1, a0:a1] = False
+ has_bg = mask.mean() > 0.12
+ lap = np.abs(cv2.Laplacian(gray, cv2.CV_32F))
+ subj_sharp = float(lap[y0:y1, x0:x1].mean()) + 1e-3
+ out = {"ratio": ratio, "key_side": key_side, "top_bottom": top / bottom, "transition": transition,
+ "subject_luma": float(np.median(region)), "dark_share": float((gray < 28).mean()),
+ "warmth": float(lab[y0:y1, x0:x1, 2].astype(np.float32).mean() - 128),
+ "bg_luma": None, "bg_warmth": None, "bg_blur": None, "point_lights": 0}
+ if has_bg:
+ out["bg_luma"] = float(np.median(gray[mask]))
+ out["bg_blur"] = float(lap[mask].mean()) / subj_sharp
+ lit_bg = mask & (gray > 50)
+ if lit_bg.sum() > 200:
+ out["bg_warmth"] = float(lab[..., 2][lit_bg].astype(np.float32).mean() - 128)
+ hot = ((gray > 235) & mask).astype(np.uint8)
+ n, _, stats, _ = cv2.connectedComponentsWithStats(hot, connectivity=8)
+ out["point_lights"] = int(sum(1 for i in range(1, n) if 2 <= stats[i, cv2.CC_STAT_AREA] <= 0.004 * h * w))
+ return out
+
+
+def words(m: dict) -> dict:
+ """Plain-language reading of measurements (one shot, or a video's medians)."""
+ if not m or m.get("ratio") is None:
+ return {}
+ r, side = m["ratio"], {"left": "画面左侧", "right": "画面右侧"}.get(m.get("key_side"), "?")
+ key = "正面(光从镜头方向来,主体两侧亮度接近)" if r < 1.35 else (f"{side}偏前方" if r < 2.5 else f"{side}(侧光)")
+ tb = m.get("top_bottom") or 1.0
+ vert = "从下往上(屏幕/桌面反光/低位光源)" if tb < 0.85 else ("从上往下(顶灯/路灯/高位光源)" if tb > 1.35 else "与主体同高")
+ tr = m.get("transition")
+ quality = (("柔光(几乎没有明暗分界)" if r < 1.35 else "无法判断") if tr is None
+ else "柔光(明暗过渡宽)" if tr >= 0.32 else "硬光(明暗分界清楚)" if tr <= 0.16 else "中等柔度")
+ warm = m.get("warmth") or 0.0
+ ct = "偏暖(约 3000–4000K)" if warm > 14 else ("偏冷(日光/冷白 LED)" if warm < 4 else "中性(约 5000K)")
+ blur = m.get("bg_blur")
+ depth = None if blur is None else ("背景明显虚化(浅景深/人像模式)" if blur < 0.45 else "背景略虚" if blur < 0.8 else "背景清晰")
+ sep = None
+ if m.get("bg_luma") is not None and m.get("subject_luma") is not None:
+ d = m["subject_luma"] - m["bg_luma"]
+ sep = "主体比背景亮" if d > 25 else ("背景比主体亮(逆光/背景灯更亮)" if d < -25 else "主体和背景亮度接近")
+ low = (m.get("subject_luma", 255) < 95 and (m.get("dark_share") or 0) > 0.25) or (m.get("bg_luma") is not None and m["bg_luma"] < 35)
+ return {"key_direction": key, "vertical": vert, "ratio": f"约 {r:.1f}:1(相差 {math.log2(max(r, 1.0)):.1f} 档)",
+ "quality": quality, "color_temp": ct, "depth": depth, "separation": sep, "low_light": bool(low),
+ "mixed_color": m.get("bg_warmth") is not None and abs(m["bg_warmth"] - warm) > 10,
+ "point_lights": int(m.get("point_lights") or 0)}
+
+
+# Lighting set-ups, first match wins. `when(m, w)` gets the measurements and their reading.
+# gear: per subject kind ("face" = people, "other" = desk / product / hands).
+SETUPS = [
+ {"key": "ambient_low_light", "name": "夜景/弱光环境光,没有专门补光",
+ "when": lambda m, w: w["low_light"],
+ "detail": "主光来自环境(路灯、招牌、室内顶灯、屏幕),主体偏暗、反差由环境决定",
+ "gear": {"face": ["手机夜景/人像模式,找一盏路灯或招牌做主光,人站在灯斜下方", "想更干净:镜头旁加一个低亮度暖色 LED 小灯(3200K)"],
+ "other": ["找一处有台灯/氛围灯的位置,把物品放在灯下", "想更干净:加一盏低亮度 LED 小灯从侧上方照物品"]}},
+ {"key": "back_lit", "name": "逆光/背景比主体亮",
+ "when": lambda m, w: m.get("bg_luma") is not None and m["bg_luma"] - m.get("subject_luma", 0) > 40,
+ "detail": "背景(窗户、天空、亮墙)比主体亮,主体靠反光或曝光补偿",
+ "gear": {"face": ["背对窗户坐,或在镜头侧加反光板/补光灯把脸提亮"], "other": ["物品背对窗户,正面放反光板或白卡补光"]}},
+ {"key": "soft_front", "name": "正面柔光(平光)",
+ "when": lambda m, w: m["ratio"] < 1.35,
+ "detail": "大面积光从镜头方向来,主体上几乎没有阴影:面朝窗户、环形灯,或大柔光箱放在镜头后方",
+ "gear": {"face": ["环形灯(18 寸)或带柔光罩的 LED 平板灯,放在手机正后方略高处", "或白天面朝窗户,窗户在镜头后面"],
+ "other": ["桌面正上方/镜头后方放一盏大柔光灯(或两盏左右对称 45°)", "白色桌面或白卡反光,阴影会更淡"]}},
+ {"key": "key_fill", "name": "侧前方主光 + 补光(标准布光)",
+ "when": lambda m, w: m["ratio"] < 2.5,
+ "detail": "主光在主体一侧斜前方,另一侧有补光或反光板把阴影提亮",
+ "gear": {"face": ["主光:LED + 柔光箱/柔光伞,人物 45° 侧前方、略高于眼睛", "补光:另一侧反光板或低亮度小灯", "可选:背后加轮廓灯"],
+ "other": ["主光:LED + 柔光箱从桌面一侧 45° 斜上方打", "另一侧白卡/反光板补光", "可选:后方加一盏轮廓灯勾边"]}},
+ {"key": "hard_side", "name": "单侧主光,补光很弱(明暗对比强)",
+ "when": lambda m, w: True,
+ "detail": "主光在一侧,另一侧明显暗下去,接近伦勃朗光/侧光",
+ "gear": {"face": ["一盏 LED + 柔光箱放在人物侧面 60–90°", "不补光,或用黑旗压暗另一侧"],
+ "other": ["一盏灯从侧面低角度打,制造长影子", "另一侧不补光或用黑卡吸光"]}},
+]
+
+
+def setup_for(m: dict, w: dict, subject_kind: str = "face") -> dict:
+ if not w:
+ return {}
+ s = next(s for s in SETUPS if s["when"](m, w))
+ notes = []
+ if w["vertical"].startswith("从下往上"):
+ notes.append("主体下半部偏亮:可能有来自下方的光(屏幕、桌面反光)")
+ if w["mixed_color"]:
+ notes.append("主体和背景色温不一致:混合光源(例如暖色灯 + 冷色窗光/屏幕)")
+ if w.get("depth"):
+ notes.append(w["depth"])
+ return {"key": s["key"], "name": s["name"], "detail": s["detail"], "notes": notes,
+ "gear": s["gear"]["face" if subject_kind == "face" else "other"]}
+
+
+class Lighting(Aspect):
+ def __init__(self):
+ super().__init__(key="lighting", title="打光", shot_fields=[
+ Field("location", "场景", "室内|户外;白天|夜晚;具体场景(卧室/办公室/桌面/街边/车内…)", prefer="seen"),
+ Field("key_light", "主光", "主光方向与高度(如:画面左前方 45° 略高)及光源(窗户/环形灯/柔光箱/台灯/路灯/屏幕/顶灯)", prefer="seen"),
+ Field("light_quality", "软硬", "柔光|硬光|混合,依据(阴影边缘、投影)"),
+ Field("fill_light", "补光", "有无补光/反光板,暗部多暗", prefer="seen"),
+ Field("rim_light", "轮廓光", "有无轮廓光/背景灯(头发、肩膀、物体边缘的亮边)", prefer="seen"),
+ Field("catchlight", "眼神光", "眼神光形状(方形=柔光箱/窗,圆环=环形灯,点状=小灯/路灯,无);没有人脸写不适用", prefer="seen"),
+ Field("practicals", "可见光源", "画面里能看到的光源(台灯、灯带、路灯、招牌、屏幕)", prefer="seen"),
+ Field("color_temp", "色温", "暖|中性|冷|混合(主体和背景是否不同色温)"),
+ Field("lighting_setup", "布光方案", "一句话布光方案(如:环形灯正面平光 + 暖色背景灯;两盏柔光箱 45° 夹打桌面)", prefer="seen"),
+ ], video_fields=[
+ Field("lighting_overall", "整体布光", "整片的布光方案:主光、补光、轮廓光、环境光、色温;不同场景分别写", prefer="seen"),
+ ])
+
+ def measure(self, ctx: ShotCtx) -> dict:
+ per, kinds = [], []
+ for f, s in zip(ctx.frames, ctx.subjects):
+ if s and s["kind"] != "frame":
+ m = frame_light(f, s)
+ if m:
+ per.append(m)
+ kinds.append(s["kind"])
+ if not per:
+ return {}
+ out = {"subject": max(set(kinds), key=kinds.count), "frames": len(per)}
+ for k in MEASURES:
+ vals = [m[k] for m in per if m.get(k) is not None]
+ if vals:
+ out[k] = round(float(np.median(vals)), 3)
+ sides = [m["key_side"] for m in per]
+ out["key_side"] = max(set(sides), key=sides.count)
+ return out
+
+ def interpret(self, shot: dict) -> dict:
+ m = ((shot.get("aspects") or {}).get(self.key) or {}).get("measured") or {}
+ w = words(m)
+ if not w:
+ return {}
+ st = setup_for(m, w, m.get("subject", "face"))
+ return {**w, "setup": st.get("key"), "setup_name": st.get("name")}
+
+ def summarize(self, shots: list[dict], b: dict) -> dict:
+ filmed = [r for r in shots if r["base"]["label"] in FILMED]
+ main = [r for r in (filmed or [r for r in shots if r["base"]["label"] in PHOTOGRAPHIC])
+ if ((r.get("aspects") or {}).get(self.key) or {}).get("measured", {}).get("ratio") is not None]
+ if not main:
+ return {}
+ ms = [(r["aspects"][self.key]["measured"], r["duration"]) for r in main]
+ med = {k: weighted_median([(m.get(k), w) for m, w in ms]) for k in MEASURES}
+ med["key_side"], _ = weighted_mode([(m.get("key_side"), w) for m, w in ms])
+ kind, _ = weighted_mode([(m.get("subject"), w) for m, w in ms])
+ w = words(med)
+ st = setup_for(med, w, kind or "face")
+ lines = [f"打光:{st['name']}。主光 {w['key_direction']},{w['vertical']};光比 {w['ratio']};{w['quality']};色温{w['color_temp']}"
+ + (f";{';'.join(st['notes'])}" if st.get("notes") else "")]
+ if not filmed:
+ lines.append("(画面不是实拍:以上是画面里的光影,用于写生成提示词,不是拍摄方案)")
+ return {"result": {"setup": st["key"]}, "measured": {k: (round(v, 3) if isinstance(v, float) else v) for k, v in med.items()},
+ "words": w, "setup": st, "filmed": bool(filmed), "lines": lines,
+ "fields": field_table(self, main, b, {"light_quality": w["quality"], "color_temp": w["color_temp"]})}
+
+
+register(Lighting())
diff --git a/rea_video/aspects/subject.py b/rea_video/aspects/subject.py
new file mode 100644
index 0000000..0fdafcf
--- /dev/null
+++ b/rea_video/aspects/subject.py
@@ -0,0 +1,42 @@
+"""The subject of a frame, the region that framing and lighting are measured on.
+
+1. A face (YuNet, with landmarks): talking heads, vlogs, interviews.
+2. Otherwise the in-focus region: where fine detail concentrates (hands and products on a desk, food, objects).
+ Out-of-focus background and flat surfaces carry little Laplacian energy, so the sharpest blob is what the
+ camera was focused on.
+3. Otherwise the centre of the frame (flat or uniformly sharp pictures).
+
+Returned box coordinates are fractions of the frame (x, y, w, h)."""
+from __future__ import annotations
+
+import cv2
+import numpy as np
+
+
+def salient_box(bgr: np.ndarray) -> list[float] | None:
+ h, w = bgr.shape[:2]
+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY).astype(np.float32)
+ energy = np.abs(cv2.Laplacian(gray, cv2.CV_32F))
+ energy = cv2.GaussianBlur(energy, (0, 0), max(w, h) / 30)
+ if float(energy.max()) <= 1e-3:
+ return None
+ thr = np.percentile(energy, 80)
+ mask = (energy >= thr).astype(np.uint8)
+ n, lab, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)
+ if n <= 1:
+ return None
+ # the component holding the most energy, not just the largest
+ best = max(range(1, n), key=lambda i: float(energy[lab == i].sum()))
+ x, y, bw, bh = (int(v) for v in stats[best, :4])
+ if bw * bh > 0.85 * w * h or bw * bh < 0.01 * w * h:
+ return None
+ return [x / w, y / h, bw / w, bh / h]
+
+
+def subject(bgr: np.ndarray, face: dict | None) -> dict:
+ if face:
+ return {"kind": "face", "box": face["box"], "landmarks": face.get("landmarks"), "area": face["area"]}
+ box = salient_box(bgr)
+ if box:
+ return {"kind": "focus", "box": box, "landmarks": None, "area": box[2] * box[3]}
+ return {"kind": "frame", "box": [0.2, 0.2, 0.6, 0.6], "landmarks": None, "area": 0.36}
diff --git a/rea_video/classify.py b/rea_video/classify.py
index eb7df7b..e0c0c7f 100644
--- a/rea_video/classify.py
+++ b/rea_video/classify.py
@@ -51,6 +51,30 @@ def _norm(d: dict[str, float]) -> dict[str, float]:
return {k: max(v, 0.0) / s for k, v in d.items()}
+# Photographic-picture guards: platform transcodes make real footage look "rendered" (flat blocks, small palette).
+# Each guard needs evidence a render cannot fake easily. Thresholds were measured over every shot of eval/*.yaml
+# (labels, holdout, holdout2, articles, koubo); see eval/RESULTS.md 2026-10-30 for the distributions.
+RULES = {
+ # dim footage: near-black blocks that still carry grain (a rendered dark background is one exact colour,
+ # block std 0), lit parts not flat, and a face on screen (dark UI / 3D on black have no face)
+ "lowlight": {"dark_ratio": 0.15, "dark_std": 0.3, "dark_flat_max": 0.65, "flat_lit_max": 0.3, "faces": 0.5},
+ # a face held through the shot: cartoon / plush / illustrated faces in eval cover < 6% of the frame
+ "big_face": {"area": 0.06, "presence": 0.5, "graphic_factor": 0.4},
+ # lines of small OCR text (glyph height < 2% of the frame): 3D shots carry <= 2, screenshots 5-14
+ "ui_text": {"height": 0.02, "mid": 4.5, "width": 0.7},
+ # an avatar is a fixed frame; a moving / shaking camera argues for someone filming
+ "avatar_moving_camera": 0.3,
+}
+
+
+def lowlight_photo(f: dict, faces: float = 0.0) -> bool:
+ """Dim footage with a person in it (see RULES["lowlight"]): crushed shadows shrink the palette and add flat
+ blocks, so the "rendered texture" cues do not apply."""
+ r = RULES["lowlight"]
+ return (f.get("dark_ratio", 0.0) > r["dark_ratio"] and f.get("dark_std", 0.0) > r["dark_std"]
+ and f.get("dark_flat", 1.0) < r["dark_flat_max"] and f.get("flat_lit", 1.0) < r["flat_lit_max"] and faces >= r["faces"])
+
+
PLATFORM_TRANSCODES = ("WeChat transcode", "WeChat Channels", "Douyin/TikTok", "Douyin", "Kuaishou", "Xiaohongshu")
@@ -64,7 +88,8 @@ def video_context(shots: list[dict], provenance: dict | None, fps: float | None)
photo_dur = native_dur = 0.0
for r in shots:
f = r.get("features") or {}
- if f.get("palette95", 0) < 100 or f.get("flat_ratio", 1) > 0.2 or f.get("dup_ratio", 0) > 0.85:
+ photo_like = (f.get("palette95", 0) >= 100 and f.get("flat_ratio", 1) <= 0.2) or lowlight_photo(f, r.get("faces", 0.0))
+ if not photo_like or f.get("dup_ratio", 0) > 0.85:
continue # rendered graphics or frozen frames say nothing about camera cadence
d = float(r.get("duration", 0))
photo_dur += d
@@ -111,10 +136,36 @@ def deterministic(f: dict, overlay: dict | None = None, text: dict | None = None
# flat colour blocks and a small palette are the most robust "rendered" cues; the
# noise estimate is unreliable on text-heavy frames (glyph edges look like noise).
graphic = (0.45 * _sig((flat - 0.20) / 0.05) + 0.35 * _sig((70 - pal) / 15) + 0.20 * _sig((axis - 0.33) / 0.03))
+ lowlight = lowlight_photo(f, faces)
+ facts["lowlight"] = lowlight
+ if lowlight:
+ # judge texture on the lit part only; the palette is small because the shadows are crushed
+ lit_graphic = 0.75 * _sig((f.get("flat_lit", 0) - 0.20) / 0.05) + 0.25 * _sig((axis - 0.33) / 0.03)
+ if lit_graphic < graphic:
+ ev.append(f"低照度画面:{f.get('dark_ratio', 0):.0%} 的区域接近全黑但带颗粒(不是纯色底),亮部平坦块只有 {f.get('flat_lit', 0):.0%}、"
+ f"且有人脸:平坦块/少色是暗部被压缩造成的,不按渲染特征算")
+ graphic = lit_graphic
+ # a large face held through the shot is a photographic picture: plain walls and dark clothes make flat blocks
+ # after a platform transcode (RULES["big_face"])
+ bf = RULES["big_face"]
+ big_face = faces >= bf["presence"] and f.get("face_area", 0.0) >= bf["area"] and family in ("dynamic", "mostly_static")
+ facts["big_face"] = big_face
+ facts["face_area"] = round(f.get("face_area", 0.0), 3) if faces >= 0.3 else 0.0
+ if big_face and graphic > 0.25:
+ ev.append(f"人脸占画面 {f.get('face_area', 0):.0%}、{faces:.0%} 的采样帧都有:是人物近景画面,平坦色块多来自墙面/衣服,渲染特征降权")
+ graphic *= bf["graphic_factor"]
# (overlay text is a separate layer, so OCR coverage does not count toward the base)
photo = 1.0 - graphic
# fine high-frequency detail on flat ground = small text / UI (screenshots, docs, code cards)
text_like = _sig((noise - 0.8) / 0.2) * _sig((flat - 0.4) / 0.08)
+ # many lines of small OCR text = an interface / document screenshot; the noise cue above misses them on
+ # platform transcodes, which smooth glyph edges (RULES["ui_text"])
+ ut = RULES["ui_text"]
+ small_lines = sum(1 for tr in (text or {}).get("tracks", []) if tr.get("text_height", 1.0) < ut["height"])
+ ui_text = _sig((small_lines - ut["mid"]) / ut["width"])
+ facts["ui_text"] = round(ui_text, 3)
+ if ui_text > 0.5:
+ ev.append(f"OCR 读到 {small_lines} 行小字号文字:画面里有界面/文档截图")
# background pixels exactly unchanged while something moves = 2D compositing (code/MG)
rsb = _sig((zero - 0.94) / 0.015) * _sig((0.1 - tnoise) / 0.03)
facts["graphic_score"] = round(graphic, 3)
@@ -215,13 +266,16 @@ def deterministic(f: dict, overlay: dict | None = None, text: dict | None = None
ui_gray = _sig((0.04 - f.get("saturation", 0.3)) / 0.01) * _sig((20 - pal) / 3)
facts["ui_gray"] = round(ui_gray, 3)
s["code_render"] += 1.5 * graphic * (0.3 + 1.2 * rsb + 1.0 * text_like + 0.8 * ui_gray) * axis_f
- s["cg_3d"] += 1.5 * graphic * max(0.0, 1.1 - rsb - 0.8 * text_like) * (1 - 0.8 * ui_gray)
+ s["cg_3d"] += 1.5 * graphic * max(0.0, 1.1 - rsb - 0.8 * text_like) * (1 - 0.8 * ui_gray) * (1 - 0.8 * ui_text)
+ s["screen_capture"] += 1.2 * graphic * ui_text
if ui_gray > 0.5 and graphic > 0.6:
ev.append(f"画面几乎无彩色(饱和度 {f.get('saturation', 0):.2f})、只用 {pal} 种颜色:界面/文档类平面画面,不是有光影的 3D 渲染")
s["screen_capture"] += 1.2 * graphic * text_like * (0.3 + _sig((0.12 - f.get("saturation", 0.3)) / 0.04))
s["live_action"] += 1.5 * photo * live_hint
s["ai_video"] += 1.5 * photo * (1 - live_hint) * (1.4 if pulldown else 1.0)
- s["avatar"] += 0.6 * photo * (1 if faces > 0.6 else 0.1) * (1.0 if speech else 0.4) * (1 - live_hint)
+ # a talking-head avatar is a fixed frame; a shaking handheld camera argues for a person filming
+ moving_cam = RULES["avatar_moving_camera"] if f.get("camera") in ("handheld_like", "smooth_move") else 1.0
+ s["avatar"] += 0.6 * photo * (1 if faces > 0.6 else 0.1) * (1.0 if speech else 0.4) * (1 - live_hint) * moving_cam
if pulldown:
s["cg_3d"] *= 1.2
if gen_tags:
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 5dbedce..b179ec1 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -183,6 +183,7 @@ def cmd_summary(args) -> int:
prov = b.get("provenance", {})
if prov.get("aigc") or prov.get("hints"):
lines.append(f"元数据: aigc={prov.get('aigc')} hints={prov.get('hints')}")
+ from .aspects import shot_text
from .memory import hint_for, patterns
pats = patterns()
@@ -198,7 +199,10 @@ def cmd_summary(args) -> int:
+ (" ← 低置信,需要复核" if base["confidence"] < 0.6 else "")
+ (f" ← {base['uncertain']}" if base.get("uncertain") else "")
+ (" ← 用户纠正过素材来源" if (r.get("material") or {}).get("user_corrected") else "")
- + (f" ← {past}" if past else ""))
+ + (f" ← {past}" if past else "")
+ + (f" | {shot_text(r)}" if r["base"]["label"] in ("live_action", "avatar") and shot_text(r) else ""))
+ if s.get("aspects"):
+ lines += [""] + s["aspects"]
a = b.get("audio", {})
if a.get("has_audio"):
mu = a.get("music", {})
diff --git a/rea_video/evaluate.py b/rea_video/evaluate.py
index 4e7dd2f..9fea58f 100644
--- a/rea_video/evaluate.py
+++ b/rea_video/evaluate.py
@@ -63,6 +63,9 @@ def audio_check(gt: dict, b: dict) -> dict:
if gt.get("music_source"):
ms = (b.get("sound_sources") or {}).get("music") or {}
out["music_source"] = ms.get("leaning") == gt["music_source"]
+ if gt.get("voice_source"):
+ vs = (b.get("sound_sources") or {}).get("voice") or {}
+ out["voice_source"] = vs.get("leaning") == gt["voice_source"]
if gt.get("key"):
k = (a.get("music") or {}).get("key") or {}
out["key"] = f"{k.get('tonic')} {k.get('mode')}" == gt["key"]
@@ -91,6 +94,7 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
tot_dur = ok_dur = 0.0
real_tot = real_ok = 0.0
audio_hits: dict[str, list[bool]] = {}
+ aspect_hits: dict[str, list[bool]] = {}
for entry in spec["videos"]:
path = _expand(entry["path"])
if not Path(path).is_file():
@@ -156,6 +160,12 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
row["audio"] = audio_check(entry["audio"], b)
for k, v in row["audio"].items():
audio_hits.setdefault(k, []).append(v)
+ if entry.get("aspects"):
+ from .aspects import check as aspect_check
+
+ row["aspects"] = aspect_check(entry["aspects"], b)
+ for k, v in row["aspects"].items():
+ aspect_hits.setdefault(k, []).append(v)
if "cuts" in entry:
row["cut_f1"] = boundary_f1([s["start"] for s in b["shots"][1:]], entry["cuts"], tol=float(entry.get("cut_tolerance", 0.1)))
if entry.get("image_source"):
@@ -173,6 +183,8 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
summary["real_material_per_video"] = {r["id"]: r["real_material_accuracy"] for r in rows if "real_material_accuracy" in r}
if audio_hits:
summary["audio"] = {k: f"{sum(v)}/{len(v)}" for k, v in audio_hits.items()}
+ if aspect_hits:
+ summary["aspects"] = {k: f"{sum(v)}/{len(v)}" for k, v in aspect_hits.items()}
cuts = [r["cut_f1"]["f1"] for r in rows if "cut_f1" in r]
if cuts:
summary["cut_f1_mean"] = round(sum(cuts) / len(cuts), 3)
diff --git a/rea_video/faces.py b/rea_video/faces.py
new file mode 100644
index 0000000..c952649
--- /dev/null
+++ b/rea_video/faces.py
@@ -0,0 +1,107 @@
+"""Face detection for shot analysis: YuNet (OpenCV FaceDetectorYN, ~230 KB ONNX, downloaded once to
+$REA_VIDEO_MODELS) with five landmarks per face. Falls back to a Haar cascade on OpenCV builds that still ship
+it. YuNet also fires on cartoon / plush / illustrated faces: a face means "a character is on screen", not
+"this is live action"."""
+from __future__ import annotations
+
+import logging
+import os
+import urllib.request
+import uuid
+from pathlib import Path
+
+import cv2
+import numpy as np
+
+LOG = logging.getLogger(__name__)
+MODEL_NAME = "face_detection_yunet_2023mar.onnx"
+MODEL_URL = f"https://github.com/opencv/opencv_zoo/raw/main/models/face_detection_yunet/{MODEL_NAME}"
+MODEL_BYTES = 232_589
+MIN_AREA = 0.02 # a face must cover >= 2% of the frame to count
+
+_DET = None # cv2.FaceDetectorYN | "haar" cascade | False (unavailable)
+
+
+def _models_dir() -> Path:
+ return Path(os.getenv("REA_VIDEO_MODELS", str(Path.home() / ".cache/rea-video/models"))).expanduser()
+
+
+def _ensure_model() -> Path | None:
+ p = _models_dir() / MODEL_NAME
+ if p.is_file() and p.stat().st_size == MODEL_BYTES:
+ return p
+ p.parent.mkdir(parents=True, exist_ok=True)
+ tmp = p.with_name(f"{p.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part")
+ try:
+ LOG.info("downloading face model %s -> %s", MODEL_NAME, p)
+ urllib.request.urlretrieve(MODEL_URL, tmp)
+ if tmp.stat().st_size != MODEL_BYTES:
+ raise OSError(f"incomplete download: {tmp.stat().st_size} bytes")
+ tmp.replace(p)
+ return p
+ except Exception as exc: # offline: fall back to Haar if this OpenCV has it
+ LOG.warning("face model download failed (%s); face detection falls back to Haar or is skipped", str(exc)[:120])
+ return None
+ finally:
+ tmp.unlink(missing_ok=True)
+
+
+def _detector():
+ global _DET
+ if _DET is not None:
+ return _DET
+ _DET = False
+ model = _ensure_model() if hasattr(cv2, "FaceDetectorYN") else None
+ if model:
+ try:
+ _DET = ("yunet", cv2.FaceDetectorYN.create(str(model), "", (320, 320), 0.6, 0.3, 50))
+ return _DET
+ except Exception as exc: # pragma: no cover
+ LOG.warning("YuNet failed to load: %s", exc)
+ if hasattr(cv2, "CascadeClassifier"):
+ try:
+ c = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") # type: ignore[attr-defined]
+ if not c.empty():
+ _DET = ("haar", c)
+ except Exception: # pragma: no cover
+ pass
+ if not _DET:
+ LOG.warning("no face detector available: face-based evidence and shot-size measurement are skipped")
+ return _DET
+
+
+def detect(frame: np.ndarray) -> list[dict]:
+ """Faces in one BGR frame, largest first: {box: [x, y, w, h] in 0..1, area, score, landmarks: 5x[x, y] in 0..1 | None}."""
+ det = _detector()
+ if not det:
+ return []
+ kind, d = det
+ h, w = frame.shape[:2]
+ out = []
+ if kind == "yunet":
+ d.setInputSize((w, h))
+ _, faces = d.detect(frame)
+ for f in (faces if faces is not None else []):
+ x, y, fw, fh = (float(v) for v in f[:4])
+ lm = [[float(f[4 + 2 * i]) / w, float(f[5 + 2 * i]) / h] for i in range(5)] # r-eye, l-eye, nose, r-mouth, l-mouth
+ out.append({"box": [x / w, y / h, fw / w, fh / h], "area": fw * fh / (w * h), "score": float(f[14]), "landmarks": lm})
+ else:
+ g = cv2.equalizeHist(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY))
+ for (x, y, fw, fh) in d.detectMultiScale(g, scaleFactor=1.15, minNeighbors=5, minSize=(32, 32)):
+ out.append({"box": [x / w, y / h, fw / w, fh / h], "area": fw * fh / (w * h), "score": 1.0, "landmarks": None})
+ out = [f for f in out if f["area"] >= MIN_AREA]
+ return sorted(out, key=lambda f: -f["area"])
+
+
+def shot_faces(frames: list[np.ndarray], max_frames: int = 6) -> dict:
+ """Face summary over a shot's sampled frames: presence ratio and the main face per sampled frame."""
+ if not frames:
+ return {"presence": 0.0, "frames": []}
+ step = max(1, len(frames) // max_frames)
+ picked = list(range(0, len(frames), step))[:max_frames]
+ per = []
+ for i in picked:
+ fs = detect(frames[i])
+ per.append({"i": i, "face": fs[0] if fs else None, "count": len(fs)})
+ hits = sum(1 for p in per if p["face"])
+ return {"presence": hits / len(per), "frames": per}
diff --git a/rea_video/features.py b/rea_video/features.py
index 7595aa8..8b86d6c 100644
--- a/rea_video/features.py
+++ b/rea_video/features.py
@@ -57,6 +57,15 @@ def spatial_features(bgr: np.ndarray) -> dict:
blocks = gray[: bh * 8, : bw * 8].reshape(bh, 8, bw, 8).astype(np.float32)
bstd = blocks.std(axis=(1, 3))
flat_ratio = float((bstd < 0.6).mean())
+ # low-light split: transcoded night footage crushes shadows into flat near-black blocks, which reads as a
+ # "rendered" flat palette. A rendered dark background is one exact colour (std 0); crushed shadows keep grain.
+ bmean = blocks.mean(axis=(1, 3))
+ dark = bmean < 28
+ lit = ~dark
+ dark_ratio = float(dark.mean())
+ dark_std = float(np.median(bstd[dark])) if dark.any() else 0.0
+ dark_flat = float((bstd[dark] < 0.6).mean()) if dark.any() else 0.0
+ flat_lit = float((bstd[lit] < 0.6).mean()) if lit.any() else 0.0
# palette size: number of 4-bit-per-channel colours covering 95% of pixels
q = (bgr >> 4).astype(np.int32)
codes = (q[..., 0] << 8) | (q[..., 1] << 4) | q[..., 2]
@@ -79,6 +88,10 @@ def spatial_features(bgr: np.ndarray) -> dict:
return {
"noise_sigma": noise_sigma(gray),
"flat_ratio": flat_ratio,
+ "dark_ratio": dark_ratio,
+ "dark_std": dark_std,
+ "dark_flat": dark_flat,
+ "flat_lit": flat_lit,
"palette95": palette95,
"edge_density": edge_density,
"axis_edge_ratio": axis,
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 26c1bbf..82c812e 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -12,7 +12,7 @@ from . import SCHEMA, __version__
from .assets import detect_embedded, material_summary
from .audio import analyze_audio, merge_audio_with_vlm
from .sound_source import MUSIC_ZH, classify_sound_sources, per_clip_audio
-from .classify import LABEL_ZH, deterministic, fuse, video_context, image_source_guess, overlay_layers, top, verdict_text
+from .classify import LABEL_ZH, RULES, deterministic, fuse, video_context, image_source_guess, overlay_layers, top, verdict_text
from .features import collect_samples, shot_features
from .media import cut_clip, extract_frame, require_tools, video_info
from .overlay import ocr_frames, persistent_template, static_overlays, summarize_text
@@ -20,7 +20,9 @@ from .plan import Planner
from .probe import provenance
from .shots import build_track, detect_shots
from .util import LOG, fmt_time, round_floats, write_json
-from .visual import face_presence, shot_sheet, storyboard
+from . import aspects
+from .faces import shot_faces
+from .visual import shot_sheet, storyboard
from .vlm import SHOT_PROMPT, WHOLE_PROMPT, VLMClient, VLMConfig, normalize_shot_result, shot_hints, vlm_note
@@ -74,7 +76,12 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
ov = static_overlays(smp.frames)
text = summarize_text(ocr_frames(smp.frames, smp.frame_times)) if ocr else {"tracks": [], "text_coverage": 0.0, "items": []}
embedded = detect_embedded(smp.frames, text.get("items"))
- faces = face_presence(smp.frames)
+ fd = shot_faces(smp.frames)
+ faces = fd["presence"]
+ areas = [p["face"]["area"] for p in fd["frames"] if p.get("face")]
+ feats["face_presence"] = faces
+ feats["face_area"] = float(np.median(areas)) if areas else 0.0
+ asp = aspects.measure_shot(smp.frames, fd, feats, s.duration)
probs, evidence, facts = deterministic(feats, ov, text, faces, audio, prov, fps=info.fps)
layers = overlay_layers(ov, text, template)
sid = f"shot_{s.index:03d}"
@@ -83,7 +90,7 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
extract_frame(video, max(s.start, s.end - min(0.08, s.duration / 4)), out / "shots" / f"{sid}_last.jpg", width=min(1080, info.width or 1080))
rec = {
"id": sid, **s.to_dict(), "features": round_floats(feats), "faces": round(faces, 3),
- "overlay": round_floats(ov), "text": text, "layers": layers, "embedded_assets": round_floats(embedded),
+ "aspects": round_floats(asp), "overlay": round_floats(ov), "text": text, "layers": layers, "embedded_assets": round_floats(embedded),
"deterministic": {"probs": round_floats(probs), "evidence": evidence, "facts": facts},
"assets": {"sheet": f"shots/{sid}.jpg", "first_frame": f"shots/{sid}_first.jpg", "last_frame": f"shots/{sid}_last.jpg"},
"vlm": None,
@@ -233,13 +240,22 @@ def _vlm_gate(rec: dict, vprobs: dict | None, vctx: dict) -> dict | None:
ranked = sorted(rec["deterministic"]["probs"].items(), key=lambda kv: -kv[1])
(d, dp), (_, sp) = ranked[0], ranked[1]
v = top(vprobs)[0]
- if v not in (d, ranked[1][0]): # it must back one of the tools' two best guesses
+ # a photographic answer on a shot with a person in it (a big face, a dim shot with a face, or a face over
+ # RULES["big_face"]["area"]) overrides texture cues that rank "rendered" first: plain walls, crushed shadows and
+ # screenshots pasted over the person all look flat after a transcode
+ # Only when the tools' top two include a rendered label: inside the AI / live / avatar axis the tools' frame-rate
+ # evidence still decides (eval holdout2 dual_role_realcat: Gemini calls an AI presenter "avatar").
+ rendered_top = d not in AI_LIVE_AXIS or ranked[1][0] not in AI_LIVE_AXIS
+ person = (v in AI_LIVE_AXIS and rendered_top
+ and bool(facts.get("big_face") or facts.get("lowlight") or facts.get("face_area", 0) >= RULES["big_face"]["area"]))
+ if v not in (d, ranked[1][0]) and not person: # it must back one of the tools' two best guesses
return None
- if d in AI_LIVE_AXIS or v in AI_LIVE_AXIS:
+ # the tools' confidence only protects the AI / live axis (frame-rate evidence), not a "rendered" texture call
+ if (d in AI_LIVE_AXIS or v in AI_LIVE_AXIS) and not (person and d not in AI_LIVE_AXIS):
if dp >= 0.65 and dp - sp >= 0.25: # tools are sure: frame-rate evidence beats "looks real / looks like a presenter"
return None
- if v == "live_action" and facts.get("transcode_degraded") and not vctx.get("native30"):
- return None # transcoded 24fps-source footage never becomes live action on looks alone
+ if v == "live_action" and facts.get("transcode_degraded") and not vctx.get("native30"):
+ return None # transcoded 24fps-source footage never becomes live action on looks alone
return vprobs
@@ -369,6 +385,14 @@ def finalize(breakdown: dict, out: Path, engine: str = "seedance2.0") -> dict:
sb_items.append((img, r["base"]["label"], f"#{r['index']} {r['base']['label']} {r['base']['confidence']:.0%}", r["start"], r["end"]))
storyboard(sb_items, out / "storyboard.jpg")
+ aspects.finalize(breakdown)
+ breakdown["aspects"] = round_floats(breakdown["aspects"])
+ summary["aspects"] = aspects.summary_lines(breakdown)
+ for rec in shot_records: # filmed shots: rebuild by shooting, with this shot's framing / camera / light
+ if rec["base"]["label"] == "live_action":
+ res = {k: v.get("result") for k, v in (rec.get("aspects") or {}).items() if v.get("result")}
+ rec["replication"]["shoot"] = {"summary": aspects.shot_text(rec), **res}
+
breakdown["audio_plan"] = merge_audio_with_vlm(audio, breakdown.get("whole_video_vlm"))
srcs = classify_sound_sources(breakdown)
breakdown["sound_sources"] = srcs
diff --git a/rea_video/plan.py b/rea_video/plan.py
index b025608..839e01c 100644
--- a/rea_video/plan.py
+++ b/rea_video/plan.py
@@ -22,7 +22,7 @@ LABEL_ROUTE = {
}
NOTE = {
"ai_video": "原片为 AI 生成:取原镜头首尾帧做首尾帧生成,可高度还原构图与动作;换主体时先用图像模型改首帧",
- "live_action": "原片为实拍:可用 AI 图生视频近似复刻(以首帧为参考),高保真需要重新拍摄",
+ "live_action": "原片为实拍:按拍摄方案(景别/机位/打光)重新拍摄;没有拍摄条件时才用 AI 图生视频近似(以首帧为参考)",
"avatar": "数字人口播:先克隆/合成配音,再用数字人模型由人像 + 音频驱动",
"cg_3d": "3D 渲染:可用首尾帧 AI 生成近似;需要精确多角度时走 3D 建模 + Blender 渲染",
"code_render": "代码渲染:用 Remotion/HTML 按文字轨与版式重建,100% 可控,不需要生成模型",
@@ -79,7 +79,7 @@ class Planner:
}
if not prompt:
plan["capsule"]["prompt_missing"] = "未运行 VLM,缺少视频提示词;请用 --vlm 重新拆解或手动补写"
- elif executor == "local_ffmpeg":
+ if executor == "local_ffmpeg":
m = shot.get("features", {})
plan["local"] = {"zoom_per_s": m.get("zoom_per_s", 0.0), "pan_px_per_s": m.get("pan_px_per_s", 0.0),
"pan_dir_deg": m.get("pan_dir_deg", 0.0), "analysis_width": 480, "duration": round(dur, 3)}
diff --git a/rea_video/report.py b/rea_video/report.py
index 072f13e..0f86137 100644
--- a/rea_video/report.py
+++ b/rea_video/report.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import html
from pathlib import Path
+from . import aspects
from .classify import LABEL_ZH
from .util import fmt_time
from .visual import LABEL_COLOR
@@ -48,6 +49,7 @@ def markdown(b: dict) -> str:
"", "![storyboard](storyboard.jpg)", "", "## 制作方式占比", "", "| 底层画面 | 时长 | 占比 |", "|---|---|---|"]
for m in s["production_mix"]:
L.append(f"| {m['label_zh']} | {m['seconds']}s | {m['ratio']:.0%} |")
+ L += aspects.report_md(b)
prov = b.get("provenance", {})
if prov.get("hints") or prov.get("encoder"):
L += ["", "## 元数据线索", ""]
@@ -157,6 +159,9 @@ def markdown(b: dict) -> str:
v = r.get("vlm") or r.get("review") or {}
if v.get("description"):
L.append(f"- 画面:{v['description']}")
+ cl = aspects.shot_text(r) if r["base"]["label"] in aspects.PHOTOGRAPHIC else ""
+ if cl:
+ L.append(f"- 拍法/打光:{cl}")
intrinsic = base["label"] in ("code_render", "screen_capture")
for tr in r.get("text", {}).get("tracks", [])[:4]:
kind = "画面内容文字" if intrinsic else KIND_ZH.get(tr["kind"], tr["kind"])
@@ -219,6 +224,7 @@ img.sb{{max-width:100%;border-radius:8px}} .real{{background:#0d9488;color:#fff;
{esc(s.get('vlm') or vlm_note(b['analysis']['vlm'], b['analysis'].get('review')))}</p>
<div class="mix">{mix}</div>
<img class="sb" src="storyboard.jpg">
+{aspects.report_html(b)}
{_sound_html(b)}
{''.join(rows)}
</main></body></html>"""
diff --git a/rea_video/review.py b/rea_video/review.py
index ac6e6e2..0c79064 100644
--- a/rea_video/review.py
+++ b/rea_video/review.py
@@ -8,6 +8,7 @@ import re
import time
from .classify import LABEL_ZH, LABELS, top
+from . import aspects
from .vlm import SHOT_PROMPT, shot_hints
AGENT_WEIGHT = 0.85 # agent answers are softened toward uniform before fusion
@@ -17,6 +18,7 @@ ASSET_KINDS = ("real_footage", "photo", "screenshot", "screen_recording", "produ
# category definitions, taken from the VLM prompt so both paths ask the same question
LABEL_GUIDE = re.search(r"底层画面类别.*?\n\n", SHOT_PROMPT, re.S).group(0).strip()
CONFUSIONS = re.search(r"注意区分:.*?\n\n", SHOT_PROMPT, re.S).group(0).strip()
+ASPECT_GUIDE = aspects.review_guide()
INSTRUCTIONS = f"""你是这次的 VLM:逐个镜头看图,判断「底层画面」的制作方式,把答案写进 review_answers.json,然后运行
rea-video apply-review <输出目录> --by <你的名字>
@@ -36,7 +38,13 @@ INSTRUCTIONS = f"""你是这次的 VLM:逐个镜头看图,判断「底层画
每个镜头要填:label_probs(8 类,和为 1)、image_source({"|".join(IMAGE_SOURCES)})、evidence(看到的具体证据)、
description(主体、动作、场景、运镜)、embedded_assets(画面里的真实素材:截图、照片、实拍片段、Logo,
-kind 取 {"|".join(ASSET_KINDS)},is_real_material 为 true/false)。"""
+kind 取 {"|".join(ASSET_KINDS)},is_real_material 为 true/false)。
+
+实拍/写实镜头再填 aspects(怎么拍、怎么打光;纯图形/界面画面不填),像素测不出的部分靠你看:
+{ASPECT_GUIDE}
+工具已经测了景别、主体光比、主光左右/上下、软硬、色温、背景虚化(见每镜 aspects),你主要补:机位角度、
+拍摄方式(自拍/支架)、主光是什么光源、眼神光、轮廓光/背景灯、画面里可见的光源;和测量冲突时写明依据。
+最后在答案顶层的 aspects 里写整片:机位/场景、推测设备、整体布光、剪辑手法、视频形式。"""
def _priority(rec: dict, ctx: dict) -> tuple[str, list[str]]:
@@ -78,6 +86,7 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
"second": [alt[0][0], round(alt[0][1], 3)] if alt else None,
"evidence": rec["deterministic"]["evidence"][:6]},
"hints": shot_hints(rec["features"], rec["deterministic"]["facts"], dl, dp),
+ "aspects": {k: v["result"] for k, v in (rec.get("aspects") or {}).items() if v.get("result")},
"images": {"sheet": rec["assets"]["sheet"], "first": rec["assets"]["first_frame"], "last": rec["assets"]["last_frame"]},
"zoom_cmd": f"rea-video tiles {video} --start {rec['start']:.2f} --end {rec['end']:.2f} --every 0.2 "
f"-o {out_dir}/check_{rec['id']}.jpg",
@@ -88,7 +97,9 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
"shots": shots}
answers = {"by": "", "shots": [{"id": s["id"], "time": f"{s['start']:.2f}-{s['end']:.2f}",
"label_probs": {k: 0 for k in LABELS}, "image_source": "unknown",
- "evidence": [], "description": "", "embedded_assets": []} for s in shots]}
+ "evidence": [], "description": "", "embedded_assets": [],
+ "aspects": aspects.review_template()} for s in shots],
+ "aspects": aspects.review_template(video=True)}
return tasks, answers
@@ -116,7 +127,7 @@ def _clean(ans: dict) -> tuple[dict | None, str | None]:
"is_real_material": bool(e.get("is_real_material", e["kind"] != "ai_image"))})
return {"label_probs": soft, "raw_probs": {k: round(v / total, 3) for k, v in vals.items()}, "image_source": src,
"evidence": [str(x) for x in (ans.get("evidence") or [])][:8], "description": str(ans.get("description", "")),
- "embedded_assets": assets}, None
+ "embedded_assets": assets, "aspects": aspects.clean_answers(ans.get("aspects"))}, None
def apply_answers(breakdown: dict, answers: dict, by: str | None = None) -> dict:
@@ -139,6 +150,9 @@ def apply_answers(breakdown: dict, answers: dict, by: str | None = None) -> dict
rec["review"] = clean
applied.append(sid)
changes.append((sid, before))
+ whole = aspects.clean_answers(answers.get("aspects"), video=True)
+ if whole:
+ breakdown["review_aspects"] = whole
breakdown.setdefault("analysis", {})["review"] = {"by": by, "shots": len(applied), "of": len(breakdown["shots"]),
"time": time.strftime("%Y-%m-%d %H:%M"), "problems": problems}
return {"applied": applied, "problems": problems, "before": dict(changes)}
diff --git a/rea_video/vlm.py b/rea_video/vlm.py
index 19602f9..e8fbcbb 100644
--- a/rea_video/vlm.py
+++ b/rea_video/vlm.py
@@ -172,6 +172,8 @@ SHOT_PROMPT = """你是视频制作逆向工程专家。判断这个镜头的「
- still_motion:一张静态图片做推拉摇移(Ken Burns),画面内部无独立运动
- static_hold:静帧定格(图片或卡片停留不动)
+如果画面是实拍或写实画面,再拆「怎么拍、怎么打光」(aspects 里各项),纯图形/文字/界面画面这些字段写"不适用"。
+
另外判断画面里有没有「引入的真实素材」:实拍片段、真实照片、商品实拍图、品牌 Logo、网页/App 截图或录屏。
它们通常是用户自己提供的素材,复刻时不能用模型生成替代,请在 embedded_assets 里逐个列出。
@@ -192,6 +194,7 @@ AI 生成的写实视频与实拍(看手、文字、背景细节、物理)
"camera_move": "固定|推|拉|摇|移|跟|环绕|手持",
"style": "画风/质感关键词",
"overlay_text": ["后期叠加在画面上的文字(字幕/标题),不含场景里的实物文字"],
+ "aspects": <<SHOT_ASPECTS>>,
"material_origin": "real|ai_generated|rendered|mixed(画面主要来自真实素材 / AI 生成 / 制作方渲染 / 混合)",
"embedded_assets": [{{"kind": "real_footage|photo|screenshot|screen_recording|product_photo|logo|ai_image", "description": "是什么、在画面哪里", "is_real_material": true}}],
"replication": {{
@@ -228,11 +231,18 @@ WHOLE_PROMPT = """你是短视频拆解专家。完整观看并**仔细收听**
"ambience": "环境声(街道、室内、无)",
"mix": "人声/BGM/音效的音量关系,是否有人声出现时压低音乐(ducking)",
"subtitles": {{"present": true, "style": "字体/描边/颜色/位置/逐字高亮等"}},
+ "aspects": <<VIDEO_ASPECTS>>,
"overall_production": "整体制作方式判断(实拍/AI生成/代码渲染/混合)与理由",
"warnings": []
}}"""
+from .aspects import prompt_block as _aspect_block # noqa: E402
+
+SHOT_PROMPT = SHOT_PROMPT.replace("<<SHOT_ASPECTS>>", _aspect_block(video=False))
+WHOLE_PROMPT = WHOLE_PROMPT.replace("<<VIDEO_ASPECTS>>", _aspect_block(video=True))
+
+
def shot_hints(features: dict, facts: dict, det_top: str, det_prob: float) -> str:
keys = ["noise_sigma", "temporal_noise", "flat_ratio", "palette95", "dup_ratio", "camera", "kenburns_score", "local_motion_ratio"]
parts = [f"{k}={features.get(k):.3g}" if isinstance(features.get(k), float) else f"{k}={features.get(k)}" for k in keys]
diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.md
index 024f79f..e5fd92c 100644
--- a/skills/rea-video/SKILL.md
+++ b/skills/rea-video/SKILL.md
@@ -11,7 +11,8 @@ description: 逆向拆解一条视频是怎么做出来的——逐镜头判断
2. **上面叠了什么?**字幕、标题、文字标注、贴片、版式模板。
3. **哪些是用户真实素材?**实拍、照片、截图、录屏、商品图、Logo。复刻时这些不能用模型生成替代,必须标出来。
4. **声音怎么做的?**人声(TTS 还是真人)、BGM(风格 / BPM / 调性 / 段落)、音效(时间点、类型、对应哪个画面事件),以及切镜是否卡在节拍上。**重点是来源:AI 生成的还是现成的。**先看视频形式——AI 音乐 MV(整片是一首唱出来的歌)大概率是 AI 歌;普通视频配乐大概率是现成曲库,但 AI 工作流的视频 BGM 也常是 Suno 生成,必须标"待确认"并给确认方法。
-5. **怎么复刻?**每镜给出路线和工具,AI 类镜头可以交给 capsule-cinema 生成。
+5. **实拍的话,怎么拍、怎么打光、怎么剪?**景别、机位、自拍还是支架;主光方向/软硬/光比/色温、有无补光和轮廓光;跳切、推近切、插入素材的节奏。
+6. **怎么复刻?**每镜给出路线和工具;实拍镜头给拍摄方案(布光 + 器材清单),不是只写"用 AI 近似",AI 类镜头可以交给 capsule-cinema 生成。
核心原则:**每个结论都要有证据,确定不了就如实写"待确认"并说明还缺什么。**宁可写"实拍还是 AI 待确认(倾向 AI 70%)",也不要编一个确定的答案。
@@ -76,8 +77,12 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复
- 必要时抽帧细看:`rea-video tiles ref.mp4 --start 12.3 --end 13.1 --every 0.1 -o out/ref/check.jpg`。
- 按 `references/taxonomy.md` 的"易混对照表"逐条核对。
3. 声音按 `references/audio.md` 复核:先听 `stems/vocals.wav`(人声干声)和 `stems/music.wav`(配乐),再看 `rea-video summary` 里的"声音来源"一行(视频类型 → 人声 / 音乐 / 音效来源)。信号层面检出的音效只是**低置信候选**,音效清单以 VLM 听到的为准;没开 VLM 时要说明"轻音效可能漏检"。
-4. 真实素材按 `references/materials.md` 复核:代码模板里嵌入的截图和照片,确定性检测能找出大部分,但**暗色、半透明的背景照片会漏**。
-5. 如果你的判断和工具不同,以你的复核为准,在回复里写明理由;有价值的话,把这条视频按 `references/evaluation.md` 加进评测集。
+4. **实拍(口播 / 桌拍 / vlog / 商品)**:`rea-video summary` 末尾按维度列出「取景 / 机位 / 打光 / 剪辑 / 形式」(`report.md`「拍法、打光与剪辑」一节,含复刻拍摄方案和器材)。
+ 工具在画面主体上测量:有人脸用人脸,没有人脸(桌拍、商品、手)用画面里最清晰的区域,后者的景别是估算。
+ 看图时在 `review_answers.json` 每镜的 `aspects` 和顶层 `aspects` 里补像素测不出的:机位角度、自拍还是支架、主光是什么光源、眼神光、轮廓光/背景灯、画面里的光源、推测设备、视频形式。报告里测量、VLM、看图三个来源并列,不平均。
+ 注意:平台转码会压暗部,软硬和补光的测量偏保守。AI / 3D 画面也会给光影描述,但标明「不是拍摄方案」,只用于写生成提示词。
+5. 真实素材按 `references/materials.md` 复核:代码模板里嵌入的截图和照片,确定性检测能找出大部分,但**暗色、半透明的背景照片会漏**。
+6. 如果你的判断和工具不同,以你的复核为准,在回复里写明理由;有价值的话,把这条视频按 `references/evaluation.md` 加进评测集。
### 看不了图时的规则(重要)
@@ -143,6 +148,8 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复
| 文件带 GB 45438 AIGC 隐式标识 Label=1 | 声明为 AI 生成(只说明整片声明过,具体镜头仍要逐个判断) |
| 浅色面板内有大量小字号文字 | 嵌入的界面截图 → 真实素材 |
| 人声间隙里仍有响亮且有音调的声音 | 有 BGM 垫底 |
+| 大面积近黑但带颗粒、亮部不平坦、有人脸 | 夜景/弱光实拍(转码压暗部造成的平坦块不是渲染特征) |
+| 人脸占画面 ≥6%、整镜都在、说话 | 人物近景实拍或数字人;墙面/衣服的平坦块不算渲染证据 |
## 5. 不要做的事
diff --git a/skills/rea-video/references/aspects.md b/skills/rea-video/references/aspects.md
new file mode 100644
index 0000000..4008656
--- /dev/null
+++ b/skills/rea-video/references/aspects.md
@@ -0,0 +1,17 @@
+# 拍法分析维度(aspects):怎么扩展
+
+每个维度是 `rea_video/aspects/` 下的一个模块,负责一个问题的全流程,加新维度不用改流水线、提示词、复核模板、报告或评测:
+
+| 步骤 | 方法 | 产出 |
+|---|---|---|
+| 逐镜测量 | `measure(ctx)`:`ctx.frames` 采样帧、`ctx.subjects` 每帧主体(人脸 / 清晰区域 / 画面中心)、`ctx.features` 运动和纹理特征 | `shot.aspects.<key>.measured` |
+| 看图提问 | `shot_fields` / `video_fields`:`Field(key, 中文名, 问题, prefer)` | 自动进 VLM 提示词和 `review_answers.json` |
+| 逐镜解读 | `interpret(shot)` | `shot.aspects.<key>.result` |
+| 整片汇总 | `summarize(shots, b)`:返回 `result`(可评测的值)、`lines`(摘要行)、`fields`(测量 / VLM / 看图 / 结论对照表) | `breakdown.aspects.<key>` |
+| 评测 | `check(gt, summary)`,默认比较 `result` 里的字段 | `eval/*.yaml` 里写 `aspects: {<key>: {<字段>: 可接受值}}` |
+
+`prefer="seen"` 的字段以看图结论为准(agent 优先于 VLM),`prefer="measured"` 以测量为准、看图结论并列显示。
+
+现有维度:`framing` 取景(景别、机位角度、构图)、`camera` 机位(手持/固定、运镜、镜头、设备)、`lighting` 打光(主光方向、光比、软硬、色温、布光方案 + 器材,规则表 `SETUPS` 可加行)、`editing` 剪辑(节奏、机位数、跳切、推近切、剪气口、插入占比)、`format` 形式(口播 / 桌拍 / 手持拍物品 / vlog)。
+
+新增维度:写一个 `Aspect` 子类,模块末尾 `register(...)`,在 `aspects/__init__.py` 里按依赖顺序 import。要用别的维度结果的(如 `format` 用 `editing`),放在它们后面。
diff --git a/skills/rea-video/references/output-template.md b/skills/rea-video/references/output-template.md
index d839571..b39d901 100644
--- a/skills/rea-video/references/output-template.md
+++ b/skills/rea-video/references/output-template.md
@@ -8,6 +8,8 @@
|---|---|---|---|---|---|---|
| 1 | 0:00–0:02.5 | AI 视频(86%) | AI 生成 | 字幕、标题 | 24→30 重复帧;手指形变 | capsule-cinema 首尾帧 |
+**拍法、打光与剪辑**(有实拍镜头时写,对应 `rea-video summary` 末尾的取景 / 机位 / 打光 / 剪辑 / 形式几行):视频形式(口播/桌拍/vlog)、景别和机位角度、手持还是支架、机位/场景数;布光方案(主光方向和高度、光比、软硬、色温、有无补光/轮廓光、画面里的光源);剪辑手法(跳切剪气口、推近切、插入截图/录屏的比例);给一份复刻器材清单。测量值和你看图的结论冲突时写明依据。
+
**声音**:人声(TTS 还是真人、音色)/ BGM(风格、BPM、调性、来源、段落)/ 音效(时间点 → 对应画面事件)/ 混音(是否压低音乐)。
**需要你提供的真实素材**:镜头 #4 中部的 GitHub 页面截图……
diff --git a/tests/test_aspects.py b/tests/test_aspects.py
new file mode 100644
index 0000000..ae97864
--- /dev/null
+++ b/tests/test_aspects.py
@@ -0,0 +1,164 @@
+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_new_and_legacy_answers():
+ r = {"vlm": {"cinematography": {"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