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 格式输出。
Python agent-skillsai-videoaigc-detectionclaude-codecodexffmpegprompt-engineeringremotionreverse-engineeringshort-videoshot-detectionsubtitlesvideo-analysisvideo-breakdownvideo-editingvideo-generationvideomdvlm
Initial commit: rea-video video breakdown toolkit
june64a2a313dffd
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..2f67b37--- /dev/null+++ b/.gitignore@@ -0,0 +1,10 @@+.cache/+out/+__pycache__/+*.egg-info/+.pytest_cache/+.venv/+*.pyc+eval/media/+.tmp_v06/+.v08tmp/diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000..6ff5a0c--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,8 @@+# rea-video:给 Agent 的说明++- 用户要拆解视频、判断制作方式、标真实素材、拆音乐音效、复刻时,**先读 `skills/rea-video/SKILL.md`**,按里面的流程做,并复核低置信镜头。+- 开发约定:+ - 拆解逻辑在 `rea_video/`+ - 规则改动后跑 `python3 -m pytest -q` 和 `rea-video eval eval/labels.yaml` / `eval/holdout*.yaml`,结果更新到 `eval/RESULTS.md`+ - 模型能力地图在 `capabilities/`,改完跑 `python3 scripts/validate_capabilities.py --matrix`+- 不要提交任何密钥;VLM 配置通过 `--env-file` 读取。diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 0000000..6ff5a0c--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,8 @@+# rea-video:给 Agent 的说明++- 用户要拆解视频、判断制作方式、标真实素材、拆音乐音效、复刻时,**先读 `skills/rea-video/SKILL.md`**,按里面的流程做,并复核低置信镜头。+- 开发约定:+ - 拆解逻辑在 `rea_video/`+ - 规则改动后跑 `python3 -m pytest -q` 和 `rea-video eval eval/labels.yaml` / `eval/holdout*.yaml`,结果更新到 `eval/RESULTS.md`+ - 模型能力地图在 `capabilities/`,改完跑 `python3 scripts/validate_capabilities.py --matrix`+- 不要提交任何密钥;VLM 配置通过 `--env-file` 读取。diff --git a/README.md b/README.mdnew file mode 100644index 0000000..5e7cc9e--- /dev/null+++ b/README.md@@ -0,0 +1,188 @@+# rea-video — Reverse Engineer Any Video++> 拿到一条视频,逐镜头判断它**是怎么做出来的**:实拍、AI 生成、3D 渲染、代码渲染、录屏、静态图推拉,还是混合;字幕和贴片是不是后期叠加的;**哪些是用户真实素材**(实拍、截图、录屏、照片);**声音怎么做的**(人声、BGM 的 BPM/调性/段落、音效、是否卡点),以及**音乐/人声/音效是 AI 生成的还是现成的**(先看视频形式:AI 音乐 MV 多为 AI 歌,普通配乐多为曲库)。每个结论都附可复查的证据。然后对其中的 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 里的流程拆解、复核低置信镜头、按模板交付。++灵感来自 [REA(Reverse Engineer Anything)](https://github.com/morluto/rea):从现象追到实现,结论附证据,用可测量的方式验证。++## 安装++需要 Python ≥ 3.10 和 ffmpeg(macOS:`brew install ffmpeg`;Ubuntu:`apt install ffmpeg`)。++```bash+git clone <本仓库> && cd rea-video+pip install -e ".[ocr]" # numpy / opencv / pillow / pyyaml / onnxruntime + 可选 OCR+rea-video --help+bash scripts/install_skill.sh # 可选:装 CLI 并把 skill 链接到 ~/.claude/skills、~/.codex/skills、~/.agents/skills+```++首次拆解会自动下载约 67 MB 的人声分离模型(`~/.cache/rea-video/models`)。一条 30 秒视频不开 VLM 约 1 分钟出结果。++装好 skill 后,在 Claude Code / Codex / zcode 里直接说"帮我拆解这条视频 xxx.mp4,看看是不是 AI 做的"即可,agent 会按 [SKILL.md](skills/rea-video/SKILL.md) 的流程跑:先看记忆 → 拆解 → 看图复核 → 按模板交付。++## 快速开始++```bash++# 1. 只做确定性取证(离线、免费)+rea-video decompose ref.mp4 -o out/ref++# 2. 加 VLM(建议,不强制):让多模态大模型看画面,实拍/AI/3D 判断更准+# 任意 OpenAI 兼容的多模态模型都行,模型可写多个做备选+export REA_VLM_BASE_URL=https://.../v1 REA_VLM_API_KEY=... REA_VLM_MODEL=gemini-2.5-pro,gpt-4o+rea-video decompose ref.mp4 -o out/ref --vlm+# 或复用 capsule-cinema 的配置:rea-video --env-file ~/code/github/capsule-cinema/.env decompose ref.mp4 -o out/ref --vlm+# VLM 调用全部失败时不会中断,报告和 `rea-video summary` 的 "VLM:" 一行会写明"全部调用失败,等同未开"++open out/ref/report.html++# 3. 没有 VLM,但 agent 自己能看图(zcode、Claude Code 等多模态 agent):让 agent 当 VLM+rea-video review out/ref # 生成逐镜看图任务和答案模板+rea-video apply-review out/ref --by zcode # agent 填完答案后并入结论和报告++# 4. 用户纠正和偏好会被记住(存在 ~/.rea-video,可用 REA_VIDEO_HOME 改位置)+rea-video correct out/ref --shots 3 --label still_motion --note "这是定格动画"+rea-video prefs vlm on && rea-video prefs --note "报告尽量短"+rea-video memory++# 只剥离声音:stems/original.wav(原声)、vocals.wav(人声干声)、music.wav(配乐)+rea-video stems ref.mp4 -o out/ref+```++输出示例(混合片):++```+结论:混合制作:代码/模板渲染 59% + AI 生成视频 41%;叠加层:字幕、标题(代码/剪辑软件合成)+#1 00:00.000 1.38s 代码/模板渲染 → R01 Remotion 重建+#2 00:01.375 2.50s AI 生成视频(24fps 源、无传感器噪声…)→ R07 首尾帧生成(capsule-cinema)+...+```++## 效果(截至 2026-10-30)++详细方法见 [docs/decompose.md](docs/decompose.md),全部数字和复现命令见 [eval/RESULTS.md](eval/RESULTS.md)。++**制作方式判断**(按时长加权的镜头准确率)。标注集:labels(调参集)、holdout + holdout2(16 条留出视频)、articles(10 条微信转码视频,开发集):++| 配置 | labels | holdout | holdout2 | articles |+|---|---|---|---|---|+| 只用工具(离线、免费) | 99.9% | 99.6% | 99.8% | 88.6% |+| + VLM(Gemini 3.1 Pro) | — | 99.6% | 99.8% | 99.6% |+| + agent 看图复核(zcode) | — | 99.6% | 99.8% | 100% |+| + VLM + agent | — | 99.6% | 99.8% | 98.8% |++- 平时拍的、没转码的视频,只用工具就基本够;**平台下载的转码视频**(微信/抖音/TikTok)噪点证据被抹掉,看图(VLM 或能看图的 agent)能把 88.6% 提到 99% 以上。+- 拿不准时会说拿不准:转码视频里,既没有 AIGC 标识、也没有手机原生 30fps 证据的"AI / 实拍"镜头,置信度封顶 0.7,结论写"证据不足,待确认"。+- **真实素材**(实拍、截图、录屏、照片):97.6% / 99.6% / 98.1%(labels / holdout / holdout2),articles 100%。+- **切点**:F1 1.0。++**换一个 agent 只靠 Skill 盲测**([eval/agent_test](eval/agent_test/README.md)):zcode(GLM,能看图)不改代码、不上网,13 条文章视频按人工评分 19/22,只用工具 18/22,上一代流程 14/22;16 条留出视频里完成的 15 条有 14 条结论正确(1 条因 zcode 自身报错中断)。开 VLM + 看图复核时,每条视频约 6–20 分钟。++**声音**:默认剥成原声 / 人声干声 / 配乐三条轨(UVR MDX-Net,TTS + BGM 分离 SDR ≈ 19.7 dB);人声、BGM 有无,以及 BPM、调性在带真值的样本上全对。音乐来源(AI 生成还是曲库)只对了 2/5:AI 工作流里 Suno 生成的垫底 BGM 会被判成"倾向曲库"。混音里的音效只能靠 VLM 听。++**局限**:+- 样本少:带制作方式标注的视频共 41 条(调参 15、留出 16、转码开发集 10),实拍和定格动画尤其少。最近几条融合规则就是在这些数据上选出来的,需要新视频复核。可以用 `rea-video memory --export-labels` 把用户纠正过的视频导出成新的评测样本。+- 转码后的"实拍还是 AI"仍然是最难的一类:现在只能如实标"待确认",还不能判得更准。+- 单开 VLM 时,Gemini 会很自信地把卡通 AI 判成 3D、把文字卡片判成截图;工具已做限制(只有一个看图来源时,不能推翻工具有把握的 AI / 实拍判断)。VLM 服务不稳定时会自动换备用模型,全部失败也不会中断。++## 和 capsule-cinema 一起复刻++```bash+CC=~/code/github/capsule-cinema; PY=$CC/.venv/bin/python+rea-video remake-plan out/ref/breakdown.json --capsule-root $CC # AI 类镜头 → 首尾帧生成任务+$PY integrations/capsule_cinema/run_remake.py --jobs out/ref/remake/jobs.json # 调 capsule-cinema 生成(会计费,可先 --dry-run)+rea-video assemble out/ref/breakdown.json out/ref/remake/results.json # 按原时间线拼回 + 对比片+$PY integrations/capsule_cinema/to_capsule.py --breakdown out/ref/breakdown.json --capsule-root $CC --capsule-name my_remake+```++- 静态图推拉和静帧:不调模型,本地用测得的缩放和平移参数精确重建。+- 代码渲染和录屏:报告给出文字轨和版式,用 Remotion 重建。+- `to_capsule.py`:通过 capsule-cinema 自带的 `tool_factory` 注入拆解结果,生成可复用的配方草稿,不需要改 capsule-cinema 的代码。++见 [integrations/capsule_cinema/README.md](integrations/capsule_cinema/README.md)。++## 命令++| 命令 | 作用 |+|---|---|+| `decompose VIDEO [--vlm] [--no-ocr]` | 拆解,输出 breakdown.json、report.html/md、storyboard.jpg、每镜首尾帧 |+| `review OUT_DIR` | 给能看图的 agent 生成逐镜看图任务(review_tasks.json)和答案模板(review_answers.json) |+| `apply-review OUT_DIR [ANSWERS] [--by NAME]` | 把 agent 看图的答案和确定性结果融合,重写 breakdown.json 和报告 |+| `correct OUT_DIR --shots N --label L [--real yes/no] [--note]` | 用户指出判错:改正结论和报告,并记入记忆(以后同一文件自动套用,同类镜头复核时提示) |+| `prefs [KEY VALUE] [--note TEXT]` | 用户偏好:默认引擎、是否默认开 VLM、VLM 配置文件、复核者名字、给 agent 的自由文字说明 |+| `memory [--export-labels YAML]` | 看记住了什么(偏好、常见纠正类型);把纠正导出成评测样本 |+| `probe VIDEO` | 只看元数据线索(拍摄设备、AIGC 隐式标识、C2PA、编辑器签名) |+| `summary breakdown.json` | 紧凑打印结论,标出需要复核的低置信镜头 |+| `tiles VIDEO --start --end --every` | 按时间抽帧拼图,近距离复核 |+| `eval labels.yaml` | 在带标注的样本上评测准确率和切点 F1 |+| `capsule breakdown.json` | 导出 capsule-cinema 的视频分析 JSON |+| `remake-plan` / `assemble` | 生成复刻任务、拼回成片 |++## 工作流(设计目标;目前完成到拆解和 AI 镜头复刻)++```+Ingest ─► Decompose ─► Video IR ─► Plan ─► Reconstruct ─► Verify ─► Remix+ 导入 拆解/拉片 源码 路由 重建 差分验证 批量改写+```++| 阶段 | 状态 |+|---|---|+| Ingest、Decompose、Video IR(`breakdown.json`) | 已可用,即本仓库主体 |+| Plan | 已可用:每镜给出复刻路线;AI 类镜头生成 capsule-cinema 任务 |+| Reconstruct | 部分可用:AI 镜头交给 capsule-cinema,静态图推拉本地重建;代码层只给出文字轨和版式,还不生成 Remotion 工程 |+| Verify | 部分可用:`assemble` 拼回成片并输出对比视频;自动打分还没做 |+| Remix | 未开始 |++1. **Ingest(导入)**:probe、抽帧、分离音轨。+2. **Decompose(拆解)**:确定性 CV 和 VLM 分工。CV 负责精确的时间和位置:切镜、OCR 轨迹、分割、相机运动、节拍、字级对齐;VLM 负责语义:镜头意图、表演、风格。+3. **Video IR(源码)**:时间线 → 轨道 → 片段。每个片段标注渲染方式(`code` / `gen` / `footage` / `audio`),并附参数、证据和 unknowns。+4. **Plan(路由)**:读取 [能力地图](capabilities/README.md),把每个生成单元路由到原语和模型,输出 Shot Recipe,包含成本预估和需要用户确认的节点。+5. **Reconstruct(重建)**:代码层用 Remotion 等渲染,生成层调用模型,音频层用 TTS、音乐、音效,最后合成。+6. **Verify(验证)**:检查切点对齐、OCR 文本一致性、布局 IoU、感知相似度、主体一致性、运动轨迹、节拍和口型,输出 scorecard,由 agent 循环修复得分最差的镜头。+7. **Remix(改写)**:换人、换货、换文案、换语言、换画幅时,只重新渲染受影响的层。++## 两种模式++- **fidelity(高保真复刻)**:目标是结构、节奏、运镜、文字和动效逐项对齐,用分数说话。+- **adapt(创意改编)**:保留原片"为什么有效"的关系,比如钩子、揭示、节奏,内容按新主题重写。++两种模式可以按层混用。例如节奏和运镜走 fidelity,人物和文案走 adapt。++## 和同类方案的区别++详见 [docs/vs-hypit.md](docs/vs-hypit.md)。一句话:Hypit 擅长"导演式改编口播类视频",OiiOii 擅长"一键托管复刻"。rea-video 要做的是**有证据、能验证、能路由到任何模型**的逆向工程。++## 仓库结构++```+rea_video/ 拆解管线(media/probe/shots/features/overlay/audio/classify/vlm/pipeline/report/plan/remake)+integrations/ capsule-cinema 对接脚本(在 capsule-cinema 的 Python 环境里运行)+eval/ 评测标注与结果+tests/ 单测(合成视频 + 假 VLM 服务器)+capabilities/ 模型能力地图(指令集手册)+ primitives.yaml 生成与分析原语定义、验证指标+ models/*.yaml 每个模型的能力、边界、价格、许可、来源、验证日期+ routing.yaml 拆分规则 + 镜头路由规则+ schema.json 模型条目的 JSON Schema+docs/ 设计文档+scripts/ 校验脚本等工具+```++校验能力地图:++```bash+python3 scripts/validate_capabilities.py+```++## Roadmap++- **P0 能力地图**:`capabilities/` 加校验(已完成 v0)。+- **P0.5 拆解**:逐镜头判断制作方式 + VLM / agent 看图融合 + 用户记忆 + capsule-cinema 复刻对接(已完成,本仓库主体)。+- **P1 MVP**:处理"动效、文字类短视频",输出 Remotion 工程,做逐帧验证。用合成数据做基准:随机生成已知源码的 Remotion 视频,测试能还原多少。+- **P2 混合**:实拍镜头走生成路由,代码层叠加,加入 Shot Recipe 和成本控制。+- **P3 改写和规模化**:批量 Remix;能力探针自动刷新;导出剪映草稿和 OTIO。++## 合法使用++rea-video 用于学习视频的结构、节奏和制作方法,并用**你有权使用的素材**重新制作。请勿直接搬运他人的画面、音乐、角色或肖像。投放时请遵守平台规则和当地的 AI 生成内容标识要求。diff --git a/capabilities/MATRIX.md b/capabilities/MATRIX.mdnew file mode 100644index 0000000..8e9c622--- /dev/null+++ b/capabilities/MATRIX.md@@ -0,0 +1,131 @@+# 能力矩阵(自动生成,请勿手改)++由 `python3 scripts/validate_capabilities.py --matrix` 根据 `capabilities/` 生成。+置信度:● high ◐ medium ○ low。已关停的模型不列出。++| 原语 | 名称 | 可用模型 |+|---|---|---|+| `analyze.video_understanding` | 视频语义理解 | ◐ `doubao-seed-2.0-pro`、◐ `gemini-3.1-pro`、◐ `gemini-3.5-flash`、◐ `pegasus-1.5`、◐ `qwen3.5-397b-a17b` |+| `analyze.shot_boundary` | 切镜检测 | ● `pyscenedetect`、● `transnetv2` |+| `analyze.asr_word_align` | 语音识别 + 字级对齐 | ◐ `funasr-sensevoice`、● `whisperx` |+| `analyze.ocr_text_track` | 画面文字识别与轨迹 | ● `paddleocr` |+| `analyze.segmentation` | 分割与跟踪 | ◐ `sam-video` |+| `analyze.matting` | 视频抠像(alpha) | ◐ `matanyone-2`、◐ `robust-video-matting`、◐ `volcengine-matting` |+| `analyze.camera_motion` | 相机运动反解 | ◐ `megasam` |+| `analyze.audio_separation` | 音频分轨 | ● `demucs` |+| `analyze.beat_tempo` | 节拍与段落分析 | ◐ `librosa-madmom` |+| `analyze.image_layer_decompose` | 单帧图层分解 | ◐ `seedream-5.0` |+| `image.t2i` | 文生图 | ◐ `flux-3`、● `gpt-image-2.5`、◐ `kling-o3-image`、◐ `nano-banana-2.1`、◐ `qwen-image-3.0-pro`、◐ `seedream-5.0` |+| `image.edit_multi_ref` | 多参考图像编辑/合成 | ◐ `flux-3`、● `gpt-image-2.5`、◐ `kling-o3-image`、◐ `nano-banana-2.1`、◐ `qwen-image-3.0-pro`、◐ `seedream-5.0` |+| `image.text_render` | 画内文字渲染 | ◐ `flux-3`、● `gpt-image-2.5`、◐ `nano-banana-2.1`、◐ `qwen-image-3.0-pro`、◐ `seedream-5.0` |+| `image.storyboard_series` | 分镜组图 | ◐ `kling-o3-image` |+| `image.tryon` | 虚拟试穿 | ◐ `fashn-v1.6`、◐ `kling-kolors-tryon` |+| `video.t2v` | 文生视频 | ◐ `gemini-omni-flash`、◐ `hailuo-2.3`、◐ `hunyuanvideo-1.5`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-o3`、◐ `ltx-2.5`、○ `luma-ray3.2`、◐ `minimax-h3`、◐ `pixverse-v6`、◐ `runway-gen-4.5`、◐ `seedance-2.0`、● `seedance-2.5`、◐ `veo-3.1`、◐ `vidu-q3`、● `wan-2.2`、◐ `wan-3.0` |+| `video.i2v_first_frame` | 图生视频(首帧) | ◐ `gemini-omni-flash`、◐ `hailuo-2.3`、◐ `hunyuanvideo-1.5`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-o3`、◐ `ltx-2.5`、○ `luma-ray3.2`、◐ `minimax-h3`、◐ `pixverse-v6`、◐ `runway-gen-4.5`、◐ `seedance-2.0`、● `seedance-2.5`、◐ `veo-3.1`、◐ `vidu-q3`、● `wan-2.2`、◐ `wan-3.0` |+| `video.i2v_first_last` | 首尾帧生成 | ◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-o3`、◐ `minimax-h3`、◐ `pixverse-v6`、◐ `seedance-2.0`、● `seedance-2.5`、◐ `veo-3.1` |+| `video.keyframes` | 多关键帧控制 | ◐ `kling-4.0`、◐ `runway-gen-4.5` |+| `video.multi_reference` | 多参考生视频(主体一致) | ◐ `gemini-omni-flash`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-o3`、◐ `minimax-h3`、◐ `pixverse-v6`、◐ `seedance-2.0`、● `seedance-2.5`、◐ `veo-3.1`、◐ `vidu-q3` |+| `video.reference_video` | 参考视频生成(动作/运镜/特效迁移) | ◐ `gemini-omni-flash`、◐ `kling-4.0`、◐ `kling-o3`、◐ `pixverse-v6`、◐ `seedance-2.0`、● `seedance-2.5` |+| `video.reference_audio` | 参考音频生成 | ◐ `gemini-omni-flash`、◐ `ltx-2.5`、● `seedance-2.5` |+| `video.multi_shot` | 单次多镜头 | ◐ `kling-3.0`、◐ `kling-o3`、◐ `ltx-2.5`、◐ `pixverse-v6`、● `seedance-2.5` |+| `video.extend` | 续写延长 | ● `seedance-2.5`、◐ `veo-3.1` |+| `video.edit_v2v` | 视频编辑(保留运动) | ◐ `gemini-omni-flash`、◐ `kling-4.0`、◐ `kling-o3`、◐ `ltx-2.5`、○ `luma-ray3.2`、○ `runway-aleph-2`、◐ `runway-gen-4.5`、◐ `seedance-2.0`、● `seedance-2.5`、◐ `wan-2.2-animate`、○ `wan-2.7-edit` |+| `video.camera_control` | 运镜与镜头参数控制 | ◐ `gemini-omni-flash`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `pixverse-v6`、○ `runway-aleph-2`、◐ `runway-gen-4.5`、● `seedance-2.5` |+| `video.native_audio` | 音画同出 | ◐ `gemini-omni-flash`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `ltx-2.5`、○ `luma-ray3.2`、◐ `minimax-h3`、◐ `pixverse-v6`、◐ `runway-gen-4.5`、◐ `seedance-2.0`、● `seedance-2.5`、◐ `veo-3.1`、◐ `vidu-q3`、◐ `wan-3.0` |+| `motion.transfer` | 动作迁移 | ◐ `kling-motion-control`、◐ `runway-gen-4.5`、◐ `wan-2.2-animate` |+| `avatar.audio_driven` | 音频驱动数字人 | ◐ `kling-avatar-v2`、◐ `ltx-2.3-lipsync`、◐ `omnihuman-2.0` |+| `lipsync.redub` | 口型重配 | ◐ `sync-3` |+| `threed.image_to_3d` | 图生 3D | ◐ `hunyuan-3d`、◐ `rodin-gen-2.5`、◐ `tripo-p1` |+| `audio.tts` | 语音合成 | ◐ `cosyvoice-3`、○ `doubao-tts`、● `elevenlabs-v3`、● `indextts-2`、● `minimax-speech-2.8`、◐ `qwen3-tts` |+| `audio.voice_clone` | 音色克隆 | ◐ `cosyvoice-3`、○ `doubao-tts`、● `elevenlabs-v3`、● `indextts-2`、● `minimax-speech-2.8`、◐ `qwen3-tts` |+| `audio.tts_duration_control` | 时长可控配音 | ● `indextts-2` |+| `audio.music_gen` | 音乐生成 | ◐ `lyria-3-pro`、◐ `minimax-music-2.5`、◐ `suno-v5.5` |+| `audio.sfx_gen` | 文生音效 | ◐ `elevenlabs-sfx` |+| `audio.v2a_foley` | 视频生音效(Foley) | ● `hunyuanvideo-foley`、● `mmaudio` |+| `render.code_graphics` | 代码渲染动效 | ◐ `html-gsap-playwright`、● `motion-canvas`、● `remotion` |+| `render.web_capture` | 网页/界面录制 | ◐ `html-gsap-playwright` |+| `render.3d_scene` | 3D 场景渲染 | ● `blender` |+| `render.compose` | 合成与编码 | ● `ffmpeg`、● `remotion` |+| `post.upscale` | 视频超分 | ◐ `flashvsr`、◐ `real-esrgan`、◐ `seedvr2`、◐ `topaz-video` |+| `post.frame_interp` | 补帧 | ● `rife`、◐ `topaz-video` |++## 模型一览++| 模型 | 厂商 | 类别 | 状态 | 时长上限(s) | 原生音频 | 商用 | 验证依据 |+|---|---|---|---|---|---|---|---|+| Demucs(htdemucs) | Meta(开源) | analysis | ga | | | 是 | knowledge 2026-10-29 |+| Doubao Seed 2.0 Pro(豆包) | ByteDance | analysis | ga | | | 是 | third-party 2026-10-29 |+| FunASR / SenseVoice | Alibaba(开源) | analysis | ga | | | 有条件 | knowledge 2026-10-29 |+| Gemini 3.1 Pro | Google | analysis | ga | 10800 | | 是 | third-party 2026-10-29 |+| Gemini 3.5 Flash | Google | analysis | ga | 10800 | | 是 | third-party 2026-10-29 |+| librosa / madmom | 开源 | analysis | ga | | | 是 | knowledge 2026-10-29 |+| MatAnyone 2 | 学术开源 | analysis | ga | | | 有条件 | third-party 2026-10-29 |+| MegaSaM | 学术开源(CVPR 2025) | analysis | ga | | | 有条件 | vendor 2026-10-29 |+| PaddleOCR | Baidu(开源) | analysis | ga | | | 是 | knowledge 2026-10-29 |+| Twelve Labs Pegasus 1.5 | Twelve Labs | analysis | ga | 7200 | | 是 | third-party 2026-10-29 |+| PySceneDetect | 开源 | analysis | ga | | | 是 | knowledge 2026-10-29 |+| Qwen3.5 397B-A17B(开源) | Alibaba | analysis | ga | | | 有条件 | third-party 2026-10-29 |+| RobustVideoMatting(RVM) | 开源 | analysis | ga | | | 有条件 | knowledge 2026-10-29 |+| SAM 系列(SAM 2 / SAM 3) | Meta(开源) | analysis | ga | | | 有条件 | knowledge 2026-10-29 |+| TransNetV2 | 开源 | analysis | ga | | | 是 | knowledge 2026-10-29 |+| 火山引擎人像视频抠像 | ByteDance | analysis | ga | | | 是 | third-party 2026-10-29 |+| WhisperX | 开源 | analysis | ga | | | 是 | knowledge 2026-10-29 |+| CosyVoice 3(开源)/ 百炼 CosyVoice v3.5 | Alibaba | audio | ga | | | 有条件 | third-party 2026-10-29 |+| 豆包语音合成 / 声音复刻(火山引擎) | ByteDance | audio | ga | | | 是 | third-party 2026-10-29 |+| ElevenLabs Sound Effects | ElevenLabs | audio | ga | 30 | | 是 | third-party 2026-10-29 |+| ElevenLabs Eleven v3 | ElevenLabs | audio | ga | | | 是 | third-party 2026-10-29 |+| HunyuanVideo-Foley | Tencent | audio | ga | | | 有条件 | third-party 2026-10-29 |+| IndexTTS2 / IndexTTS 2.5(开源,B 站) | Bilibili | audio | ga | | | 有条件 | vendor 2026-10-29 |+| Lyria 3 Pro | Google | audio | ga | 180 | | 是 | third-party 2026-10-29 |+| MiniMax Music 2.5 | MiniMax | audio | ga | 240 | | 是 | third-party 2026-10-29 |+| MiniMax Speech 2.8(Turbo / HD) | MiniMax | audio | ga | | | 是 | user 2026-10-29 |+| MMAudio | 学术开源 | audio | ga | 8 | | 否 | third-party 2026-10-29 |+| Qwen3-TTS(开源 1.7B / 0.6B) | Alibaba | audio | ga | | | 是 | third-party 2026-10-29 |+| Suno v5.5 | Suno | audio | ga | | | 有条件 | third-party 2026-10-29 |+| FASHN Virtual Try-On v1.6 | FASHN | character | ga | | | 是 | third-party 2026-10-29 |+| Kling Avatar v2 | Kuaishou | character | ga | | | 是 | third-party 2026-10-29 |+| Kling Kolors Virtual Try-On v1.5 | Kuaishou | character | ga | | | 是 | third-party 2026-10-29 |+| Kling Motion Control(2.6 / 3.0) | Kuaishou | character | ga | | | 是 | third-party 2026-10-29 |+| LTX 2.3 Lipsync | Lightricks | character | ga | | | 有条件 | third-party 2026-10-29 |+| OmniHuman 2.0 | ByteDance | character | ga | | | 是 | third-party 2026-10-29 |+| Sync 3(Sync Labs) | Sync Labs | character | ga | | | 是 | third-party 2026-10-29 |+| Wan 2.2 Animate(含 animate-mix 换人) | Alibaba | character | ga | | | 是 | third-party 2026-10-29 |+| FLUX 3 Image | Black Forest Labs | image | ga | | | 是 | third-party 2026-10-29 |+| GPT Image 2.5 | OpenAI | image | ga | | | 是 | user 2026-10-29 |+| Kling O3 Image | Kuaishou | image | ga | | | 是 | third-party 2026-10-29 |+| Nano Banana 2.1 | Google | image | ga | | | 是 | third-party 2026-10-29 |+| Qwen Image 3.0 Pro | Alibaba | image | ga | | | 是 | third-party 2026-10-29 |+| Seedream 5.0(Pro / Lite) | ByteDance Seed | image | ga | | | 是 | third-party 2026-10-29 |+| FlashVSR | 学术开源 | post | ga | | | 有条件 | third-party 2026-10-29 |+| Real-ESRGAN | 开源 | post | ga | | | 是 | third-party 2026-10-29 |+| RIFE | 开源 | post | ga | | | 是 | knowledge 2026-10-29 |+| SeedVR2 | ByteDance Seed(开源) | post | ga | | | 有条件 | third-party 2026-10-29 |+| Topaz Video(含 Starlight 系列) | Topaz Labs | post | ga | | | 是 | third-party 2026-10-29 |+| Blender | 开源 | render | ga | | | 是 | knowledge 2026-10-29 |+| FFmpeg | 开源 | render | ga | | | 是 | knowledge 2026-10-29 |+| HTML + GSAP + Playwright 录制 | 开源组合 | render | ga | | | 是 | knowledge 2026-10-29 |+| Motion Canvas | 开源 | render | ga | | | 是 | knowledge 2026-10-29 |+| Remotion | Remotion(开源,商用需许可) | render | ga | | | 有条件 | knowledge 2026-10-29 |+| Hunyuan 3D(3.x) | Tencent | threed | ga | | | 是 | third-party 2026-10-29 |+| Rodin Gen-2.5 | Hyper3D / Deemos | threed | ga | | | 是 | third-party 2026-10-29 |+| Tripo P1 | Tripo | threed | ga | | | 是 | third-party 2026-10-29 |+| Gemini Omni Flash | Google | video | ga | 8 | 是 | 是 | third-party 2026-10-29 |+| Hailuo 2.3 / 2.3 Fast(海螺) | MiniMax | video | ga | 10 | 是 | 是 | third-party 2026-10-29 |+| HunyuanVideo 1.5(开源) | Tencent | video | ga | | | 有条件 | third-party 2026-10-29 |+| Kling 3.0(含 Turbo) | Kuaishou | video | ga | 15 | 是 | 是 | third-party 2026-10-29 |+| Kling 4.0(可灵 4.0,含 Flash) | Kuaishou | video | preview | 30 | 是 | 是 | third-party 2026-10-29 |+| Kling O3(Omni) | Kuaishou | video | ga | 15 | 否 | 是 | third-party 2026-10-29 |+| LTX-2.5(开源) | Lightricks | video | ga | | 是 | 有条件 | third-party 2026-10-29 |+| Luma Ray3.2 / Modify | Luma AI | video | ga | 10 | 是 | 是 | third-party 2026-10-29 |+| MiniMax H3 / H3 Max | MiniMax | video | ga | 15 | 是 | 有条件 | third-party 2026-10-29 |+| PixVerse V6 | PixVerse(爱诗科技) | video | ga | 15 | 是 | 是 | third-party 2026-10-29 |+| Runway Aleph 2 | Runway | video | ga | | | 是 | third-party 2026-10-29 |+| Runway Gen-4.5(含 Act-Two) | Runway | video | ga | 10 | 是 | 是 | third-party 2026-10-29 |+| Seedance 2.0(含 Mini / Fast) | ByteDance Seed | video | ga | 15 | 是 | 是 | third-party 2026-10-29 |+| Seedance 2.5 | ByteDance Seed | video | ga | 30 | 是 | 是 | vendor 2026-10-29 |+| Sora 2 / Sora 2 Pro | OpenAI | video | shutdown | 20 | | 否 | third-party 2026-10-29 |+| Veo 3.1(含 Lite) | Google | video | ga | 8 | 是 | 是 | third-party 2026-10-29 |+| Vidu Q3 | Shengshu(生数科技) | video | ga | 16 | 是 | 是 | vendor 2026-10-29 |+| Wan 2.2(开源,含 TI2V-5B) | Alibaba | video | ga | | 否 | 是 | third-party 2026-10-29 |+| Wan 2.7 视频编辑 | Alibaba | video | ga | | | 是 | third-party 2026-10-29 |+| Wan 3.0(万相) | Alibaba | video | ga | 10 | 是 | 是 | third-party 2026-10-29 |diff --git a/capabilities/README.md b/capabilities/README.mdnew file mode 100644index 0000000..7c4085a--- /dev/null+++ b/capabilities/README.md@@ -0,0 +1,62 @@+# 能力地图(Capability Map)++> 模型就是 rea-video 的"指令集"。逆向一条视频,就是把每个镜头反推成"在当前模型能力下最可控的一组生成调用或代码渲染"。+> 这里是那本指令集手册:数据化、可校验、带验证日期,并且会过期。++人类可读的总表见 [MATRIX.md](MATRIX.md),由脚本自动生成。++## 三层结构++```+signals(镜头特征,拉片时检测)+ │ routing.yaml+ ▼+primitives(与厂商无关的能力原语) ◄── primitives.yaml+ │ models/*.yaml 中的 primitives 字段+ ▼+models(具体模型/工具,带边界、价格、许可、来源)+```++- **primitives.yaml**:共 43 个原语,覆盖分析、图像、视频、人物驱动、3D、音频、代码渲染、后期,另有 16 个验证指标。路由只认原语,换厂商时规则不用改。+- **models/*.yaml**:每个模型一个条目,按类别分文件:+ - `video`:视频生成与编辑+ - `character`:动作迁移、数字人、口型重配、试穿+ - `image`:图像+ - `audio`:音频+ - `threed`:3D 生成+ - `analysis`:拉片用的 VLM 和确定性工具+ - `render-post`:代码渲染、合成、超分、补帧+- **routing.yaml**:包含以下几部分+ - 信号定义+ - 两级拆分规则(剪辑镜头 → 生成单元 → 分层)+ - 画面路由 R01–R16、音频路由 A01–A05、后期路由+ - 成本策略、确认节点、提示词纪律++## 模型条目字段++| 字段 | 说明 |+|---|---|+| `id` | 全局唯一,小写加连字符 |+| `status` | `ga` / `preview` / `limited` / `deprecated` / `shutdown`;路由器跳过 shutdown |+| `access` | `app` / `api` / `api-aggregator` / `open-weights` |+| `primitives` | 支持的原语 |+| `limits` | 时长、分辨率、参考数量、关键帧数等边界 |+| `cost.usd_per_s` | 相对成本,用于路由排序和预算估算 |+| `license` | `commercial: true / false / conditional`,附说明;`regions_excluded` 列出地区限制 |+| `verified.basis` | 可信度从高到低:`probe`(我们自测)> `user`(用户实测)> `vendor`(官方)> `third-party`(第三方)> `knowledge`(常识或训练知识) |+| `confidence` | `high` / `medium` / `low` |+| `probe_scores` | 探针测试得分,预留,由探针自动写入 |++## 维护流程++1. **新增或更新模型**:编辑对应的 `models/*.yaml`,写明来源链接和 `verified.date`。+2. **校验**:运行 `python3 scripts/validate_capabilities.py --matrix`。脚本检查 schema、引用完整性、"首选模型是否真的支持该原语"、原语空缺和过期条目(超过 90 天)。+3. **用户实测结论**(例如"GPT Image 2.5 的中文字最好"):写进 `strengths`,并把 `basis` 标为 `user`。+4. **模型下线**:把 `status` 改成 `shutdown`,条目保留,同时从路由规则里移除。+5. **探针(P1)**:每个原语一组小测试(`primitives.yaml` 的 `probe` 字段),新模型上线后自动跑,分数写回 `probe_scores`,路由排序会优先参考它。++## 已知待补++- 很多条目的发布月份和细节规格来自第三方汇总,标为 `medium` 或 `low`,需要用探针或官方文档复核。+- Kling 4.0 正式版预计 2026-10 上线,需要复核规格。+- 尚未收录:海外 UGC 数字人平台(HeyGen 等)、Pika、Higgsfield 套件、更多国内图像模型(即梦图片、可图等)、剪映 / CapCut 导出能力。diff --git a/capabilities/models/analysis.yaml b/capabilities/models/analysis.yamlnew file mode 100644index 0000000..14f0085--- /dev/null+++ b/capabilities/models/analysis.yaml@@ -0,0 +1,286 @@+# 分析侧(拉片):VLM 负责语义,确定性工具负责精确的时间与位置+# 原则:VLM 不擅长逐帧精度和计数(video-replicate-studio 实测让 VLM 数手指,14 张只对 7 张),+# 精确量一律交给确定性工具,VLM 只做解释和提示词草稿。++models:+ # ---------- VLM ----------+ - id: gemini-3.1-pro+ name: Gemini 3.1 Pro+ vendor: Google+ category: analysis+ status: ga+ access: [api, app]+ primitives: [analyze.video_understanding]+ limits:+ duration_s: {max: 10800}+ strengths:+ - 视频理解综合第一;最长 3 小时;音画联合理解+ weaknesses:+ - 闭源;时间戳精度未公开,需要用确定性工具校准+ license: {commercial: true}+ sources:+ - https://usefulai.com/models/video-understanding+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: gemini-3.5-flash+ name: Gemini 3.5 Flash+ vendor: Google+ category: analysis+ status: ga+ access: [api, app]+ primitives: [analyze.video_understanding]+ limits:+ duration_s: {max: 10800}+ strengths:+ - 更快更便宜,适合批量的初筛拉片+ weaknesses:+ - 困难的时序推理不如 3.1 Pro+ license: {commercial: true}+ sources:+ - https://usefulai.com/models/video-understanding+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: doubao-seed-2.0-pro+ name: Doubao Seed 2.0 Pro(豆包)+ vendor: ByteDance+ category: analysis+ status: ga+ access: [api]+ primitives: [analyze.video_understanding]+ strengths:+ - 音画分析;综合分接近 Gemini,价格更低+ - 国内可直接调用,适合中文内容+ weaknesses:+ - 最大时长未公开+ license: {commercial: true}+ sources:+ - https://usefulai.com/models/video-understanding+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: pegasus-1.5+ name: Twelve Labs Pegasus 1.5+ vendor: Twelve Labs+ category: analysis+ status: ga+ access: [api]+ primitives: [analyze.video_understanding]+ limits:+ duration_s: {max: 7200}+ strengths:+ - 直接输出带时间戳的摘要、章节和结构化 JSON+ weaknesses:+ - 开放式内容问答较弱+ license: {commercial: true}+ sources:+ - https://usefulai.com/models/video-understanding+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: qwen3.5-397b-a17b+ name: Qwen3.5 397B-A17B(开源)+ vendor: Alibaba+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.video_understanding]+ strengths:+ - 开源权重中视频理解分最高,可私有化部署+ weaknesses:+ - 需要服务器级算力;音频需要单独处理+ license: {commercial: conditional, note: 以模型许可为准}+ sources:+ - https://usefulai.com/models/video-understanding+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ # ---------- 确定性工具 ----------+ - id: pyscenedetect+ name: PySceneDetect+ vendor: 开源+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.shot_boundary]+ strengths:+ - 轻量;内容检测或阈值检测都能快速给出硬切+ weaknesses:+ - 溶解和遮挡转场容易漏检,漏检的切点用 SSIM 二分定位到帧+ license: {commercial: true, note: BSD-3-Clause}+ sources:+ - https://github.com/Breakthrough/PySceneDetect+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: high++ - id: transnetv2+ name: TransNetV2+ vendor: 开源+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.shot_boundary]+ strengths:+ - 学习式切镜检测,对渐变转场比阈值法更稳+ license: {commercial: true, note: MIT}+ sources:+ - https://github.com/soCzech/TransNetV2+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: high++ - id: whisperx+ name: WhisperX+ vendor: 开源+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.asr_word_align]+ strengths:+ - 字级时间对齐;Hypit 用它作为语义时间的基础+ weaknesses:+ - 生造词和陌生专名容易识别错+ - 中文需要单独准备对齐资源+ license: {commercial: true, note: BSD-2-Clause}+ sources:+ - https://github.com/m-bain/whisperX+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: high++ - id: funasr-sensevoice+ name: FunASR / SenseVoice+ vendor: Alibaba(开源)+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.asr_word_align]+ strengths:+ - 中文识别与时间戳强;SenseVoice 同时输出情感和音频事件标签+ license: {commercial: conditional, note: 以模型许可为准}+ sources:+ - https://github.com/modelscope/FunASR+ - https://github.com/FunAudioLLM/SenseVoice+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: medium++ - id: paddleocr+ name: PaddleOCR+ vendor: Baidu(开源)+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.ocr_text_track]+ strengths:+ - 中文 OCR 强,同时给出文字框+ - 逐帧识别后按 IoU 关联,就得到文字轨迹(出现、移动、消失)+ license: {commercial: true, note: Apache 2.0}+ sources:+ - https://github.com/PaddlePaddle/PaddleOCR+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: high++ - id: sam-video+ name: SAM 系列(SAM 2 / SAM 3)+ vendor: Meta(开源)+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.segmentation]+ strengths:+ - 视频目标分割与跟踪;SAM 3 支持文本提示+ license: {commercial: conditional, note: 以各版本许可为准}+ sources:+ - https://github.com/facebookresearch/sam2+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: medium++ - id: matanyone-2+ name: MatAnyone 2+ vendor: 学术开源+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.matting]+ strengths:+ - 基于记忆传播的稳定视频抠像,发丝边缘好;ComfyUI 有节点+ license: {commercial: conditional, note: 以仓库许可为准}+ sources:+ - https://studio.aifilms.ai/blog/matanyone-2-video-matting+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: robust-video-matting+ name: RobustVideoMatting(RVM)+ vendor: 开源+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.matting]+ strengths:+ - 轻量实时人像抠像;video-replicate-studio 在用+ license: {commercial: conditional, note: "GPL-3.0,与闭源产品集成要注意"}+ sources:+ - https://github.com/PeterL1n/RobustVideoMatting+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: medium++ - id: volcengine-matting+ name: 火山引擎人像视频抠像+ vendor: ByteDance+ category: analysis+ status: ga+ access: [api, api-aggregator]+ primitives: [analyze.matting]+ strengths:+ - 托管 API,输出带透明通道的 WEBM/MOV;Hypit 已接入+ license: {commercial: true}+ sources:+ - https://github.com/hypit-ai/hypit/blob/main/packages/provider-hypihub/README.md+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: megasam+ name: MegaSaM+ vendor: 学术开源(CVPR 2025)+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.camera_motion]+ strengths:+ - 从随手拍的动态视频中反解相机位姿与深度,对动态场景鲁棒+ license: {commercial: conditional, note: 以仓库许可为准}+ sources:+ - https://arxiv.org/abs/2412.04463+ verified: {date: 2026-10-29, basis: vendor}+ confidence: medium++ - id: demucs+ name: Demucs(htdemucs)+ vendor: Meta(开源)+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.audio_separation]+ strengths:+ - 人声、鼓、贝斯、其他四轨分离,效果是业界基线+ license: {commercial: true, note: MIT}+ sources:+ - https://github.com/facebookresearch/demucs+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: high++ - id: librosa-madmom+ name: librosa / madmom+ vendor: 开源+ category: analysis+ status: ga+ access: [open-weights]+ primitives: [analyze.beat_tempo]+ strengths:+ - 检测节拍、BPM 和 onset,建立剪辑节奏的节拍锚点+ license: {commercial: true, note: "librosa 为 ISC;madmom 代码 BSD,模型 CC-BY-NC-SA"}+ sources:+ - https://github.com/librosa/librosa+ - https://github.com/CPJKU/madmom+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: mediumdiff --git a/capabilities/models/audio.yaml b/capabilities/models/audio.yamlnew file mode 100644index 0000000..26b99f1--- /dev/null+++ b/capabilities/models/audio.yaml@@ -0,0 +1,230 @@+# 音频:配音 / 克隆 / 音乐 / 音效 / 视频生音效++models:+ - id: minimax-speech-2.8+ name: MiniMax Speech 2.8(Turbo / HD)+ vendor: MiniMax+ category: audio+ release: 2026-06+ status: ga+ access: [api, api-aggregator]+ primitives: [audio.tts, audio.voice_clone]+ strengths:+ - "【用户确认】支持音色克隆"+ - 中文第一梯队,中文是原生优势;支持粤语+ cost: {note: "Turbo 每百万字符 30–60 美元,HD 每百万字符 50–80 美元(2026-07 第三方数据)"}+ license: {commercial: true}+ sources:+ - https://peihuachen.github.io/ai-tools-hub/posts/tts-commercial-open-source-comparison-guide-2026.html+ verified: {date: 2026-10-29, basis: user}+ confidence: high+ notes: 发布月份为估计值++ - id: indextts-2+ name: IndexTTS2 / IndexTTS 2.5(开源,B 站)+ vendor: Bilibili+ category: audio+ release: 2025-09+ status: ga+ access: [open-weights]+ primitives: [audio.tts, audio.voice_clone, audio.tts_duration_control]+ strengths:+ - 自回归 TTS 中少见的显式时长控制,适合把新配音塞进原片时间窗+ - 情感与音色解耦;零样本克隆;中英双语+ weaknesses:+ - 需要自己部署+ license: {commercial: conditional, note: 以仓库许可为准}+ sources:+ - https://arxiv.org/html/2506.21619v2+ - https://arxiv.org/html/2601.03888v3+ verified: {date: 2026-10-29, basis: vendor}+ confidence: high++ - id: qwen3-tts+ name: Qwen3-TTS(开源 1.7B / 0.6B)+ vendor: Alibaba+ category: audio+ release: 2026-01+ status: ga+ access: [open-weights, api]+ primitives: [audio.tts, audio.voice_clone]+ strengths:+ - 3 秒音频即可克隆;支持粤语、四川话、北京话、上海话+ - Apache 2.0;百炼 API 版支持文本指令控制语气+ license: {commercial: true, note: Apache 2.0}+ sources:+ - https://peihuachen.github.io/ai-tools-hub/posts/tts-commercial-open-source-comparison-guide-2026.html+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值;克隆所需音频时长资料说法不一(3 秒或 10–20 秒)++ - id: cosyvoice-3+ name: CosyVoice 3(开源)/ 百炼 CosyVoice v3.5+ vendor: Alibaba+ category: audio+ release: 2025-09+ status: ga+ access: [open-weights, api]+ primitives: [audio.tts, audio.voice_clone]+ strengths:+ - 中文第一梯队;零样本克隆+ cost: {note: "百炼 flash 每万字符 0.8 元,plus 每万字符 1.5 元"}+ license: {commercial: conditional, note: 以仓库许可为准}+ sources:+ - https://peihuachen.github.io/ai-tools-hub/posts/tts-commercial-open-source-comparison-guide-2026.html+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: elevenlabs-v3+ name: ElevenLabs Eleven v3+ vendor: ElevenLabs+ category: audio+ release: 2025-06+ status: ga+ access: [api, app]+ primitives: [audio.tts, audio.voice_clone]+ strengths:+ - 情感表现最好(英文尤其突出);70 多种语言;有配音(dubbing)流程+ - Hypit 已接入+ weaknesses:+ - 没有中文方言;长内容很耗积分+ cost: {note: 每百万字符约 100 美元}+ license: {commercial: true, note: 克隆需要明确授权}+ sources:+ - https://peihuachen.github.io/ai-tools-hub/posts/tts-commercial-open-source-comparison-guide-2026.html+ verified: {date: 2026-10-29, basis: third-party}+ confidence: high++ - id: doubao-tts+ name: 豆包语音合成 / 声音复刻(火山引擎)+ vendor: ByteDance+ category: audio+ status: ga+ access: [api]+ primitives: [audio.tts, audio.voice_clone]+ strengths:+ - 音色自然,方言持续扩展;与 Seedance 同属一个生态+ cost: {note: 每百万字符约 20–50 元}+ license: {commercial: true}+ sources:+ - https://peihuachen.github.io/ai-tools-hub/posts/tts-commercial-open-source-comparison-guide-2026.html+ verified: {date: 2026-10-29, basis: third-party}+ confidence: low++ - id: lyria-3-pro+ name: Lyria 3 Pro+ vendor: Google+ category: audio+ release: 2026-03+ status: ga+ access: [api, app]+ primitives: [audio.music_gen]+ limits:+ duration_s: {max: 180}+ strengths:+ - 有 API;可以从文本或图像生成最长 3 分钟的歌曲+ license: {commercial: true}+ sources:+ - https://aiunpacking.com/guides/ai-audio-music-generation-guide-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: minimax-music-2.5+ name: MiniMax Music 2.5+ vendor: MiniMax+ category: audio+ release: 2026-04+ status: ga+ access: [api, api-aggregator]+ primitives: [audio.music_gen]+ limits:+ duration_s: {max: 240}+ strengths:+ - 4 分钟歌曲,100 多种乐器,可以按段落控制结构;fal.ai 提供 API+ license: {commercial: true}+ sources:+ - https://aiunpacking.com/guides/ai-audio-music-generation-guide-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: suno-v5.5+ name: Suno v5.5+ vendor: Suno+ category: audio+ release: 2026-03+ status: ga+ access: [app]+ primitives: [audio.music_gen]+ strengths:+ - 音乐质量顶级;支持自定义模型和用自己的声音演唱+ weaknesses:+ - 没有官方 API,不适合自动化流水线+ - 免费档不可商用+ license: {commercial: conditional, note: "Pro / Premier 订阅才有商用权"}+ sources:+ - https://aiunpacking.com/guides/ai-audio-music-generation-guide-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: elevenlabs-sfx+ name: ElevenLabs Sound Effects+ vendor: ElevenLabs+ category: audio+ status: ga+ access: [api, app]+ primitives: [audio.sfx_gen]+ limits:+ duration_s: {max: 30}+ strengths:+ - 文生音效,可循环;输出 48kHz WAV+ weaknesses:+ - 不看视频,需要自己按时间码摆放+ license: {commercial: true, note: Starter 及以上档位}+ sources:+ - https://www.creativeainews.com/articles/how-to-add-sound-effects-to-ai-video-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: hunyuanvideo-foley+ name: HunyuanVideo-Foley+ vendor: Tencent+ category: audio+ release: 2025-08+ status: ga+ access: [open-weights, api-aggregator]+ primitives: [audio.v2a_foley]+ strengths:+ - 看视频生成同步音效,48kHz;同步指标最好(DeSync 0.74,MMAudio 为 0.80)+ weaknesses:+ - 需要 8–20GB 显存+ - 许可排除欧盟、英国、韩国(第三方称输出同样受限)+ license: {commercial: conditional, note: 腾讯社区许可}+ regions_excluded: [EU, UK, KR]+ sources:+ - https://github.com/Tencent-Hunyuan/HunyuanVideo-Foley+ - https://www.creativeainews.com/articles/how-to-add-sound-effects-to-ai-video-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: high++ - id: mmaudio+ name: MMAudio+ vendor: 学术开源+ category: audio+ release: 2024-12+ status: ga+ access: [open-weights]+ primitives: [audio.v2a_foley]+ limits:+ duration_s: {max: 8}+ strengths:+ - 约 6GB 显存即可运行+ weaknesses:+ - 权重为 CC-BY-NC 4.0,不能商用+ - 可能生成含糊的类人声;不熟悉的声音处理不好+ license: {commercial: false, note: "代码 MIT,权重 CC-BY-NC 4.0"}+ sources:+ - https://www.creativeainews.com/articles/how-to-add-sound-effects-to-ai-video-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: highdiff --git a/capabilities/models/character.yaml b/capabilities/models/character.yamlnew file mode 100644index 0000000..aa2e4a4--- /dev/null+++ b/capabilities/models/character.yaml@@ -0,0 +1,170 @@+# 人物驱动:动作迁移 / 数字人 / 口型重配 / 虚拟试穿++models:+ - id: kling-motion-control+ name: Kling Motion Control(2.6 / 3.0)+ vendor: Kuaishou+ category: character+ release: 2025-12+ status: ga+ access: [app, api, api-aggregator]+ primitives: [motion.transfer]+ strengths:+ - 把参考视频里的动作迁移到角色图上;第三方视其为动作控制的质量标杆+ - 有技术报告(arXiv 2603.03160)+ weaknesses:+ - 用他人视频驱动时要注意肖像权与版权+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://arxiv.org/html/2603.03160v1+ - https://templix.app/blogs/best-ai-motion-control-and-animation-models-in-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: wan-2.2-animate+ name: Wan 2.2 Animate(含 animate-mix 换人)+ vendor: Alibaba+ category: character+ release: 2025-09+ status: ga+ access: [open-weights, api]+ primitives: [motion.transfer, video.edit_v2v]+ strengths:+ - 开源;可做动作迁移,也可在原视频中换人+ - video-replicate-studio 用 wan2.2-animate-mix 做换人+ weaknesses:+ - 需要本地显卡或付费 API+ license: {commercial: true, note: Apache 2.0(开源权重)}+ sources:+ - https://wanvideogenerator.com/blog/ai-motion-control-kling26-vs-wan22-animate+ - https://github.com/derek-zhuolin/video-replicate-studio+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: omnihuman-2.0+ name: OmniHuman 2.0+ vendor: ByteDance+ category: character+ release: 2026-06+ status: ga+ access: [app, api]+ primitives: [avatar.audio_driven]+ limits:+ audio_s: {min: 4, max: 300}+ strengths:+ - 一张图加一段音频,就能生成单镜长表演+ - 动作随语义和节奏变化;支持多人、非人角色和唱歌+ - 可以用提示词控制姿态、镜头和互动+ weaknesses:+ - 表演好坏主要取决于音频的表现力+ license: {commercial: true, note: BytePlus 条款}+ sources:+ - https://www.eachlabs.ai/blog/best-ai-lip-sync-models-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: kling-avatar-v2+ name: Kling Avatar v2+ vendor: Kuaishou+ category: character+ release: 2026-01+ status: ga+ access: [app, api, api-aggregator]+ primitives: [avatar.audio_driven]+ strengths:+ - 设置简单;Standard 档用于迭代,Pro 档用于成片+ weaknesses:+ - 时长资料未明示+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://www.eachlabs.ai/blog/best-ai-lip-sync-models-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: ltx-2.3-lipsync+ name: LTX 2.3 Lipsync+ vendor: Lightricks+ category: character+ release: 2026-03+ status: ga+ access: [api, open-weights]+ primitives: [avatar.audio_driven]+ limits:+ audio_s: {min: 5, max: 20}+ resolutions: [480p, 1080p]+ strengths:+ - 可固定 seed:用 480p 出草稿,再用同一 seed 出 1080p 成片+ weaknesses:+ - 只适合短片段+ license: {commercial: conditional, note: LTX Community License}+ sources:+ - https://www.eachlabs.ai/blog/best-ai-lip-sync-models-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: sync-3+ name: Sync 3(Sync Labs)+ vendor: Sync Labs+ category: character+ release: 2026-07+ status: ga+ access: [api, api-aggregator]+ primitives: [lipsync.redub]+ limits:+ resolutions: [4K]+ strengths:+ - 先分析整个场景再对口型,能处理转头、阴影、手持镜头和双人镜头+ - 保留原表演;最高 4K 60fps+ weaknesses:+ - 只接受视频和音频两个输入,不能指定遮罩或人脸框+ - 旧版 Lipsync v2 Pro 有 sync_mode(时长不匹配时的处理方式),v3 没有+ license: {commercial: true}+ sources:+ - https://www.eachlabs.ai/blog/best-ai-lip-sync-models-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: fashn-v1.6+ name: FASHN Virtual Try-On v1.6+ vendor: FASHN+ category: character+ release: 2026-03+ status: ga+ access: [api, api-aggregator]+ primitives: [image.tryon]+ limits:+ resolutions: [864x1296]+ strengths:+ - 服装上的印花和文字保持清晰+ - 支持模特图或平铺图作为输入,自动识别服装品类+ weaknesses:+ - 只做图像试穿,视频需要再经过图生视频或动作迁移+ license: {commercial: true}+ sources:+ - https://fal.ai/learn/tools/best-virtual-try-on-apis-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: kling-kolors-tryon+ name: Kling Kolors Virtual Try-On v1.5+ vendor: Kuaishou+ category: character+ release: 2025-06+ status: ga+ access: [app, api, api-aggregator]+ primitives: [image.tryon]+ strengths:+ - 保留模特的姿势、肤色和体型;带商用许可+ weaknesses:+ - 正面模特图配干净的平铺服装图时效果最好+ license: {commercial: true}+ sources:+ - https://fal.ai/learn/tools/best-virtual-try-on-apis-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值diff --git a/capabilities/models/image.yaml b/capabilities/models/image.yamlnew file mode 100644index 0000000..7b26920--- /dev/null+++ b/capabilities/models/image.yaml@@ -0,0 +1,115 @@+# 图像模型(关键帧 / 首帧 / 分镜 / 画内文字)++models:+ - id: gpt-image-2.5+ name: GPT Image 2.5+ vendor: OpenAI+ category: image+ release: 2026-08+ status: ga+ access: [api, app, api-aggregator]+ primitives: [image.t2i, image.edit_multi_ref, image.text_render]+ strengths:+ - "【用户实测】中文字体效果最好、真实感最高,是中文画内文字和写实首帧的首选"+ - 指令遵循稳定;可输出透明背景(PNG/WebP);质量档位可到 xhigh 和 max+ weaknesses:+ - 价格与速度取决于质量档位+ license: {commercial: true}+ sources:+ - https://www.eachlabs.ai/blog/best-ai-image-generation-models-2026+ verified: {date: 2026-10-29, basis: user}+ confidence: high+ notes: 发布月份为估计值;Hypit 目前接入的是 GPT Image 2(通过 HypiHub,2K/4K 部分画幅不可用)++ - id: nano-banana-2.1+ name: Nano Banana 2.1+ vendor: Google+ category: image+ release: 2026-08+ status: ga+ access: [api, app, api-aggregator]+ primitives: [image.t2i, image.edit_multi_ref, image.text_render]+ limits:+ resolutions: [4K]+ strengths:+ - 速度快;画内文字清晰;支持宽幅和全景+ license: {commercial: true}+ sources:+ - https://www.eachlabs.ai/blog/best-ai-image-generation-models-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: seedream-5.0+ name: Seedream 5.0(Pro / Lite)+ vendor: ByteDance Seed+ category: image+ release: 2026-06+ status: ga+ access: [app, api, api-aggregator]+ primitives: [image.t2i, image.edit_multi_ref, image.text_render, analyze.image_layer_decompose]+ strengths:+ - 图层分解:输出背景加若干透明 PNG 层,可以用来逆向一帧的版式+ - 擅长信息图、交互式编辑、写实和多语种文字+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://www.eachlabs.ai/blog/best-ai-image-generation-models-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值;Hypit 接入的是 Seedream 5 Lite++ - id: qwen-image-3.0-pro+ name: Qwen Image 3.0 Pro+ vendor: Alibaba+ category: image+ release: 2026-07+ status: ga+ access: [api]+ primitives: [image.t2i, image.edit_multi_ref, image.text_render]+ strengths:+ - 擅长大段密集文字和长版式;提示词最长 4500 tokens;每次最多 6 张图+ license: {commercial: true}+ sources:+ - https://www.eachlabs.ai/blog/best-ai-image-generation-models-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: flux-3+ name: FLUX 3 Image+ vendor: Black Forest Labs+ category: image+ release: 2026-07+ status: ga+ access: [api, api-aggregator]+ primitives: [image.t2i, image.edit_multi_ref, image.text_render]+ strengths:+ - 可以按包围框精确摆放元素,适合按原片布局复刻版式;多语种文字+ weaknesses:+ - 默认开启网页和图片搜索 grounding+ license: {commercial: true}+ sources:+ - https://www.eachlabs.ai/blog/best-ai-image-generation-models-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: kling-o3-image+ name: Kling O3 Image+ vendor: Kuaishou+ category: image+ release: 2026-03+ status: ga+ access: [app, api]+ primitives: [image.t2i, image.edit_multi_ref, image.storyboard_series]+ limits:+ resolutions: [1K, 2K, 4K]+ strengths:+ - 支持参考图和 element 锁定身份与风格+ - 分镜组图模式适合一次出整套关键帧+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://help.artlist.io/hc/en-us/articles/37026869403933-Kling-3-Model-Family+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值diff --git a/capabilities/models/render-post.yaml b/capabilities/models/render-post.yamlnew file mode 100644index 0000000..b19839d--- /dev/null+++ b/capabilities/models/render-post.yaml@@ -0,0 +1,160 @@+# 代码渲染 / 合成 / 后期++models:+ - id: remotion+ name: Remotion+ vendor: Remotion(开源,商用需许可)+ category: render+ status: ga+ access: [open-weights]+ primitives: [render.code_graphics, render.compose]+ strengths:+ - 用 React 写视频:文字、UI、图表、MG 都能 100% 准确并参数化+ - 官方提供 Agent Skills,可直接配合 Claude Code、Codex 使用+ - 渲染结果确定,可以逐帧和原片做像素级差分+ weaknesses:+ - 照片级画面需要和生成层叠加+ license: {commercial: conditional, note: "个人和小团队免费,公司需购买 Remotion 许可"}+ sources:+ - https://www.tella.com/blog/how-to-use-remotion-agent-skills-with-claude-code+ - https://www.remotion.dev/+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: high++ - id: motion-canvas+ name: Motion Canvas+ vendor: 开源+ category: render+ status: ga+ access: [open-weights]+ primitives: [render.code_graphics]+ strengths:+ - 用 TypeScript 生成器描述动画,适合讲解类动效;MIT 许可+ license: {commercial: true, note: MIT}+ sources:+ - https://motioncanvas.io/+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: high++ - id: html-gsap-playwright+ name: HTML + GSAP + Playwright 录制+ vendor: 开源组合+ category: render+ status: ga+ access: [open-weights]+ primitives: [render.code_graphics, render.web_capture]+ strengths:+ - 适合 UI 演示:直接驱动真实产品页面或重建的界面+ - Hypit 走的也是 HTML 加无头 Chromium 的路线+ license: {commercial: true, note: "GSAP 现已免费(含商用);Playwright 为 Apache 2.0"}+ sources:+ - https://playwright.dev/+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: medium++ - id: blender+ name: Blender+ vendor: 开源+ category: render+ status: ga+ access: [open-weights]+ primitives: [render.3d_scene]+ strengths:+ - 可导入 3D 生成的商品模型,按反解出的相机轨迹渲染转台或白模参考+ license: {commercial: true, note: GPL(输出内容不受限)}+ sources:+ - https://www.blender.org/+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: high++ - id: ffmpeg+ name: FFmpeg+ vendor: 开源+ category: render+ status: ga+ access: [open-weights]+ primitives: [render.compose]+ strengths:+ - 剪切、拼接、叠加、混音、编码,是一切的底座+ license: {commercial: true, note: "LGPL/GPL,取决于编译选项"}+ sources:+ - https://ffmpeg.org/+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: high++ - id: seedvr2+ name: SeedVR2+ vendor: ByteDance Seed(开源)+ category: post+ status: ga+ access: [open-weights, api-aggregator]+ primitives: [post.upscale]+ strengths:+ - 一步扩散视频超分,适合把 480p 草稿放大到 1080p+ license: {commercial: conditional, note: 以仓库许可为准}+ sources:+ - https://upsampler.com/blog/seedvr-vs-flashvsr-ai-video-super-resolution-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: flashvsr+ name: FlashVSR+ vendor: 学术开源+ category: post+ status: ga+ access: [open-weights, api-aggregator]+ primitives: [post.upscale]+ strengths:+ - 面向实时的流式视频超分,速度快+ license: {commercial: conditional, note: 以仓库许可为准}+ sources:+ - https://upsampler.com/blog/seedvr-vs-flashvsr-ai-video-super-resolution-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: topaz-video+ name: Topaz Video(含 Starlight 系列)+ vendor: Topaz Labs+ category: post+ status: ga+ access: [app, api, api-aggregator]+ primitives: [post.upscale, post.frame_interp]+ strengths:+ - 商业超分标杆,可放大到 4K+ license: {commercial: true}+ sources:+ - https://help.scenario.com/articles/2511466273-upscale-your-videos-up-to-4k-with-topaz+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: real-esrgan+ name: Real-ESRGAN+ vendor: 开源+ category: post+ status: ga+ access: [open-weights]+ primitives: [post.upscale]+ strengths:+ - 轻量+ weaknesses:+ - video-replicate-studio 实测 x4plus 有方块伪影,没有采用;不推荐用于生成视频超分+ license: {commercial: true, note: BSD-3-Clause}+ sources:+ - https://github.com/derek-zhuolin/video-replicate-studio+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: rife+ name: RIFE+ vendor: 开源+ category: post+ status: ga+ access: [open-weights]+ primitives: [post.frame_interp]+ strengths:+ - 实时补帧;video-replicate-studio 在用+ license: {commercial: true, note: MIT}+ sources:+ - https://github.com/hzwer/ECCV2022-RIFE+ verified: {date: 2026-10-29, basis: knowledge}+ confidence: highdiff --git a/capabilities/models/threed.yaml b/capabilities/models/threed.yamlnew file mode 100644index 0000000..02beed0--- /dev/null+++ b/capabilities/models/threed.yaml@@ -0,0 +1,52 @@+# 3D 生成(商品多角度一致 / 转台 / 白模参考)++models:+ - id: hunyuan-3d+ name: Hunyuan 3D(3.x)+ vendor: Tencent+ category: threed+ status: ga+ access: [api, open-weights]+ primitives: [threed.image_to_3d]+ strengths:+ - 三者中最稳定,很少出现破面+ - 支持指定视角输入;可选 PBR 材质,4K PBR 纹理需额外付费+ - 最适合高保真商品展示+ license: {commercial: true, note: 托管版可商用;开源权重许可需单独核对}+ sources:+ - https://www.3daistudio.com/blog/rodin-2-5-vs-tripo-vs-hunyuan-3d-comparison+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: rodin-gen-2.5+ name: Rodin Gen-2.5+ vendor: Hyper3D / Deemos+ category: threed+ status: ga+ access: [api, app]+ primitives: [threed.image_to_3d]+ strengths:+ - 5 档质量;接受 2–5 张视角图+ - 可去除原图的烘焙光照;有对称开关,适合车辆等对称物体+ license: {commercial: true}+ sources:+ - https://www.3daistudio.com/blog/rodin-2-5-vs-tripo-vs-hunyuan-3d-comparison+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: tripo-p1+ name: Tripo P1+ vendor: Tripo+ category: threed+ status: ga+ access: [api, app]+ primitives: [threed.image_to_3d]+ strengths:+ - 网格干净(约 2 万面以内),带 PBR 纹理;适合游戏用的低模+ weaknesses:+ - 不适合高保真商品展示+ license: {commercial: true}+ sources:+ - https://www.3daistudio.com/blog/rodin-2-5-vs-tripo-vs-hunyuan-3d-comparison+ verified: {date: 2026-10-29, basis: third-party}+ confidence: mediumdiff --git a/capabilities/models/video.yaml b/capabilities/models/video.yamlnew file mode 100644index 0000000..faa05f1--- /dev/null+++ b/capabilities/models/video.yaml@@ -0,0 +1,492 @@+# 视频生成 / 编辑模型+# 字段说明见 ../README.md;规格大多来自厂商公告或第三方汇总,status/verified/confidence 标明可信度。+# 价格单位 usd_per_s 为第三方列价折算,仅作路由时的相对成本参考。++models:+ - id: seedance-2.5+ name: Seedance 2.5+ vendor: ByteDance Seed+ category: video+ release: 2026-07+ status: ga+ access: [app, api-aggregator]+ primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.multi_reference, video.reference_video, video.reference_audio, video.multi_shot, video.extend, video.edit_v2v, video.camera_control, video.native_audio]+ limits:+ duration_s: {max: 30}+ resolutions: [480p, 720p, 1080p]+ refs: {image: 30, video: 10, audio: 10}+ audio: {native: true}+ strengths:+ - 单次 30 秒,内含多个逻辑连贯的镜头+ - 一次可传 30 图 + 10 视频 + 10 音频参考;支持 clay render(无纹理 3D 白模)、动作、创意参考+ - 时间戳级局部编辑、绿幕换背景、改机位、续写延长(可到数分钟)+ - 国内电商复刻产品(OiiOii、Hypit)的主力模型+ weaknesses:+ - 官方承认复杂动作的物理合理性、多主体互动的稳定性仍有不足+ - 官方未公布最大分辨率;Hypit 的 HypiHub 通道提供 480p/720p/1080p+ cost:+ note: 实测参考:OiiOii 复刻 50 秒电商视频约 40 元(480p 生成后超分到 1080p)+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://seed.bytedance.com/en/blog/one-take-creation-flexible-referencing-introducing-seedance-2-5+ - https://github.com/hypit-ai/hypit/blob/main/packages/provider-hypihub/README.md+ verified: {date: 2026-10-29, basis: vendor}+ confidence: high++ - id: seedance-2.0+ name: Seedance 2.0(含 Mini / Fast)+ vendor: ByteDance Seed+ category: video+ release: 2026-02+ status: ga+ access: [app, api, api-aggregator]+ primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.multi_reference, video.reference_video, video.native_audio, video.edit_v2v]+ limits:+ duration_s: {max: 15}+ resolutions: [720p, 1080p]+ audio: {native: true}+ strengths:+ - 成本低;Mini 720p 被 Hypit 用作 A-roll / B-roll 主力(单条视频总成本约 1.1 美元)+ weaknesses:+ - 单次时长短于 2.5+ cost: {usd_per_s: 0.15, note: "第三方列价约 9.07 美元/分钟"}+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://tech-insider.org/best-ai-video-generator-2026/+ - https://en.wikipedia.org/wiki/Seedance_2.0+ - https://github.com/hypit-ai/hypit+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: kling-4.0+ name: Kling 4.0(可灵 4.0,含 Flash)+ vendor: Kuaishou+ category: video+ release: 2026-10+ status: preview+ access: [app, api, api-aggregator]+ primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.keyframes, video.multi_reference, video.reference_video, video.edit_v2v, video.camera_control, video.native_audio]+ limits:+ duration_s: {min: 3, max: 30}+ resolutions: [720p, 1080p, 4K]+ refs: {image: 10, video: 5, audio: 1, total: 15}+ prompt_tokens: 8000+ keyframes: 10+ audio: {native: true, voice_ref: true}+ strengths:+ - 首尾帧 + 最多 10 张关键帧,复杂运镜和中间状态可控+ - Omni Reference 最多 15 个参考(10 图、5 段视频合计 30 秒、7 个 element)+ - 视频编辑:表情、肢体、机位、风格、背景、角色均可改(最多 5 段输入、合计 30 秒)+ - 立体声,多语种对白与口音;屏幕文字支持多语种和 emoji+ - 画幅 21:9 / 16:9 / 1:1 / 9:16+ weaknesses:+ - Flash 版 3–20 秒、仅 720p、8-bit SDR;10-bit HDR 与续写(最长 2 分钟)为 coming soon+ - 音频参考只能当声音参考+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://fal.ai/learn/tools/what-is-kling-4-0+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: Flash 于 2026-09-28 开放有限早期访问;正式版预计 2026-10 上线,需上线后复核++ - id: kling-3.0+ name: Kling 3.0(含 Turbo)+ vendor: Kuaishou+ category: video+ release: 2026-02+ status: ga+ access: [app, api, api-aggregator]+ primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.multi_reference, video.multi_shot, video.camera_control, video.native_audio]+ limits:+ duration_s: {min: 3, max: 15}+ resolutions: [720p, 1080p, 4K]+ shots_per_generation: 6+ audio: {native: true, voice_ref: true}+ strengths:+ - 单次最多 6 个镜头;起始帧加参考图,保持角色造型和五官+ - Voice ID 跨镜头保持角色声音;复杂物理、快速运动、运镜表现好+ - Turbo Pro 改进了口型与多镜头+ weaknesses:+ - API 价格偏高+ cost: {usd_per_s: 0.34, note: "720p 约 15.12 美元/分钟,1080p 约 20.16 美元/分钟(第三方列价)"}+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://help.artlist.io/hc/en-us/articles/37026869403933-Kling-3-Model-Family+ - https://tech-insider.org/best-ai-video-generator-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: kling-o3+ name: Kling O3(Omni)+ vendor: Kuaishou+ category: video+ release: 2026-03+ status: ga+ access: [app, api, api-aggregator]+ primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.multi_reference, video.multi_shot, video.edit_v2v, video.reference_video]+ limits:+ duration_s: {min: 3, max: 15}+ resolutions: [720p, 1080p, 4K]+ audio: {native: false}+ strengths:+ - 视频改视频:换角色或道具、重新风格化、重打光,保留原动作+ - Element 参考一致性更强;Director Mode 可组合文本、首尾帧、参考图和角色视频+ weaknesses:+ - 编辑在短片段上效果更好+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://help.artlist.io/hc/en-us/articles/37026869403933-Kling-3-Model-Family+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值;音频能力资料未提及++ - id: veo-3.1+ name: Veo 3.1(含 Lite)+ vendor: Google+ category: video+ release: 2025-10+ status: ga+ access: [app, api]+ primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.multi_reference, video.extend, video.native_audio]+ limits:+ duration_s: {max: 8}+ resolutions: [720p, 1080p, 4K]+ refs: {image: 4}+ audio: {native: true}+ strengths:+ - 提示词遵循与真人写实强;企业级(GCP、SLA、SynthID)+ - 支持首尾帧;Ingredients to Video 支持角色、物体、背景或风格参考(仅限 8 秒;参考图数量第三方说法为 3–4 张)+ - 独立的 Extend 变体可以给 2–30 秒的视频追加 7 秒+ weaknesses:+ - 单段只有 4/6/8 秒+ - 价格最高+ cost: {usd_per_s: 0.40, note: "Lite 约 0.08 美元/秒"}+ license: {commercial: true}+ sources:+ - https://tech-insider.org/best-ai-video-generator-2026/+ - https://templix.app/blogs/best-ai-motion-control-and-animation-models-in-2026+ - https://help.artlist.io/hc/en-us/articles/33139656414877-Veo-3-1+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: gemini-omni-flash+ name: Gemini Omni Flash+ vendor: Google+ category: video+ release: 2026-05+ status: ga+ access: [app, api]+ primitives: [video.t2v, video.i2v_first_frame, video.multi_reference, video.reference_video, video.reference_audio, video.edit_v2v, video.camera_control, video.native_audio]+ limits:+ duration_s: {max: 8}+ resolutions: [1080p]+ audio: {native: true}+ strengths:+ - 文本、图像、音频、视频任意组合输入;草图可作为动作引导+ - 对话式多轮编辑,场景状态延续不重置+ - 第三方榜单中文生视频(含音频)排名第一(Elo 约 1233)+ weaknesses:+ - 单段 8 秒+ - 物理一致性仍有瑕疵+ - 输出带 SynthID 和 C2PA 标记+ cost: {usd_per_s: 0.10}+ license: {commercial: true}+ sources:+ - https://www.datacamp.com/blog/gemini-omni+ - https://tech-insider.org/best-ai-video-generator-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: API ID 为 gemini-omni-1.1-flash;Omni Pro 尚未发布++ - id: vidu-q3+ name: Vidu Q3+ vendor: Shengshu(生数科技)+ category: video+ release: 2026-04+ status: ga+ access: [app, api, api-aggregator]+ primitives: [video.t2v, video.i2v_first_frame, video.multi_reference, video.native_audio]+ limits:+ duration_s: {max: 16}+ audio: {native: true}+ strengths:+ - Reference-to-Video 主打多主体一致:主体、环境、服装、道具、风格都可以作为参考+ - 原生音效覆盖环境声、动作音、Foley、情绪音效;内置粒子、流体、转场等 6 类特效+ weaknesses:+ - 参考数量与分辨率未公开+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://www.kosmo.com.my/2026/04/13/shengshu-launches-vidu-q3-reference-to-video-with-expanded-visual-and-audio-capabilities/+ verified: {date: 2026-10-29, basis: vendor}+ confidence: medium++ - id: pixverse-v6+ name: PixVerse V6+ vendor: PixVerse(爱诗科技)+ category: video+ release: 2026-03+ status: ga+ access: [app, api-aggregator]+ primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.multi_reference, video.reference_video, video.multi_shot, video.camera_control, video.native_audio]+ limits:+ duration_s: {max: 15}+ resolutions: [1080p]+ audio: {native: true}+ strengths:+ - 20 多种镜头参数(焦段、光圈、景深、畸变、色差、暗角),适合复刻有特定"镜头感"的片子+ - 多镜头;Hypit 已接入(通过 HypiHub 支持参考视频与首尾帧)+ weaknesses:+ - 通过 HypiHub 时 seed 与 multi-clip 参数不可用+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://wavespeed.ai/blog/posts/pixverse-v6-ai-video-camera-control-vfx-2026/+ - https://github.com/hypit-ai/hypit/blob/main/packages/provider-hypihub/README.md+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: minimax-h3+ name: MiniMax H3 / H3 Max+ vendor: MiniMax+ category: video+ release: 2026-06+ status: ga+ access: [api, api-aggregator, open-weights]+ primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.multi_reference, video.native_audio]+ limits:+ duration_s: {min: 4, max: 15}+ resolutions: [768p, 1080p, 2K]+ audio: {native: true}+ strengths:+ - 第三方榜单前三(H3 Max Elo 约 1227),且列价最低+ - 权重开放(H3-Base 可在本地跑 768p)+ - Hypit 与 video-replicate-studio 均已接入+ weaknesses:+ - 企业配套弱;1080p 下时长受限+ - 2K 需要托管模块+ cost: {usd_per_s: 0.04, note: "H3 Max 约 2.40 美元/分钟;H3 约 7.80 美元/分钟"}+ license: {commercial: conditional, note: MiniMax H3 Community License}+ sources:+ - https://tech-insider.org/best-ai-video-generator-2026/+ - https://www.turingpost.com/p/6-opensource-video-generation-models+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: hailuo-2.3+ name: Hailuo 2.3 / 2.3 Fast(海螺)+ vendor: MiniMax+ category: video+ release: 2025-10+ status: ga+ access: [app, api, api-aggregator]+ primitives: [video.t2v, video.i2v_first_frame]+ limits:+ duration_s: {max: 10}+ resolutions: [768p, 1080p]+ audio: {native: true}+ strengths:+ - 微表情、风格化、动作有提升+ - 便宜(Fast 版 768p 6 秒约 0.19 美元起)+ weaknesses:+ - 1080p 时长更短+ - 失败的生成也会计费+ license: {commercial: true, note: 以平台条款为准}+ sources:+ - https://tech-insider.org/best-ai-video-generator-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: wan-3.0+ name: Wan 3.0(万相)+ vendor: Alibaba+ category: video+ release: 2026-07+ status: ga+ access: [api]+ primitives: [video.t2v, video.i2v_first_frame, video.native_audio]+ limits:+ duration_s: {max: 10}+ resolutions: [1080p]+ audio: {native: true}+ strengths:+ - 第三方榜单第二(Elo 约 1229)+ weaknesses:+ - 只有 API,不开源+ cost: {usd_per_s: 0.20, note: 约 12 美元/分钟}+ license: {commercial: true}+ sources:+ - https://tech-insider.org/best-ai-video-generator-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: wan-2.7-edit+ name: Wan 2.7 视频编辑+ vendor: Alibaba+ category: video+ release: 2026-05+ status: ga+ access: [api]+ primitives: [video.edit_v2v]+ strengths:+ - video-replicate-studio 用于镜头编辑+ license: {commercial: true}+ sources:+ - https://github.com/derek-zhuolin/video-replicate-studio+ verified: {date: 2026-10-29, basis: third-party}+ confidence: low+ notes: 具体能力未细查,需要补充探针++ - id: wan-2.2+ name: Wan 2.2(开源,含 TI2V-5B)+ vendor: Alibaba+ category: video+ release: 2025-07+ status: ga+ access: [open-weights]+ primitives: [video.t2v, video.i2v_first_frame]+ limits:+ resolutions: [720p]+ audio: {native: false}+ strengths:+ - Apache 2.0;TI2V-5B 单张消费级显卡可跑+ - 可自部署、可微调,适合批量低成本生成+ weaknesses:+ - 已不是最新一代+ license: {commercial: true, note: Apache 2.0}+ sources:+ - https://www.turingpost.com/p/6-opensource-video-generation-models+ verified: {date: 2026-10-29, basis: third-party}+ confidence: high++ - id: ltx-2.5+ name: LTX-2.5(开源)+ vendor: Lightricks+ category: video+ release: 2026-04+ status: ga+ access: [open-weights, api]+ primitives: [video.t2v, video.i2v_first_frame, video.reference_audio, video.multi_shot, video.edit_v2v, video.native_audio]+ audio: {native: true}+ strengths:+ - 开源模型中少有的音画同出,支持音频条件生成、编辑、多镜头和超分+ weaknesses:+ - 时长与分辨率资料未明示+ license: {commercial: conditional, note: "LTX-2.x Community License:年收入低于 1000 万美元免费商用"}+ sources:+ - https://www.turingpost.com/p/6-opensource-video-generation-models+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 发布月份为估计值++ - id: hunyuanvideo-1.5+ name: HunyuanVideo 1.5(开源)+ vendor: Tencent+ category: video+ release: 2025-11+ status: ga+ access: [open-weights]+ primitives: [video.t2v, video.i2v_first_frame]+ limits:+ resolutions: [720p, 1080p]+ strengths:+ - 8.3B,约 14GB 显存可跑(需 offload);自带超分模块,可把自身输出放大到 1080p+ weaknesses:+ - 许可排除欧盟、英国、韩国+ license: {commercial: conditional, note: 腾讯社区许可}+ regions_excluded: [EU, UK, KR]+ sources:+ - https://www.turingpost.com/p/6-opensource-video-generation-models+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: runway-gen-4.5+ name: Runway Gen-4.5(含 Act-Two)+ vendor: Runway+ category: video+ release: 2025-12+ status: ga+ access: [app, api]+ primitives: [video.t2v, video.i2v_first_frame, video.keyframes, video.edit_v2v, video.camera_control, motion.transfer, video.native_audio]+ limits:+ duration_s: {max: 10}+ resolutions: [720p]+ audio: {native: true}+ strengths:+ - 控制工具最全:关键帧、运动笔刷、相机路径+ - Act-Two 能把驱动表演迁移到角色图上+ weaknesses:+ - 原生 720p(4K 需要超分)+ - 按积分计费,成本累积快+ license: {commercial: true}+ sources:+ - https://tech-insider.org/best-ai-video-generator-2026/+ - https://templix.app/blogs/best-ai-motion-control-and-animation-models-in-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium++ - id: runway-aleph-2+ name: Runway Aleph 2+ vendor: Runway+ category: video+ release: 2026-06+ status: ga+ access: [app, api, api-aggregator]+ primitives: [video.edit_v2v, video.camera_control]+ strengths:+ - 在已有镜头上改机位、增删物体,并把风格贯穿整个镜头+ weaknesses:+ - 长项目反复编辑的成本高+ license: {commercial: true}+ sources:+ - https://openrouter.ai/runway/aleph-2/api+ - https://www.seedance.tv/blog/best-ai-video-to-video-models-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: low+ notes: 发布月份为估计值++ - id: luma-ray3.2+ name: Luma Ray3.2 / Modify+ vendor: Luma AI+ category: video+ release: 2026-05+ status: ga+ access: [app, api]+ primitives: [video.t2v, video.i2v_first_frame, video.edit_v2v, video.native_audio]+ limits:+ duration_s: {max: 10}+ resolutions: [1080p]+ audio: {native: true}+ strengths:+ - Modify 能替换演员并保留原动作和时序+ - Ray 有"推理式"自我修正,提示词遵循好+ weaknesses:+ - 背景复杂、人多的场景转换效果差+ - 积分价格高+ license: {commercial: true}+ sources:+ - https://tech-insider.org/best-ai-video-generator-2026/+ - https://www.seedance.tv/blog/best-ai-video-to-video-models-2026+ verified: {date: 2026-10-29, basis: third-party}+ confidence: low+ notes: 发布月份为估计值++ - id: sora-2+ name: Sora 2 / Sora 2 Pro+ vendor: OpenAI+ category: video+ release: 2025-09+ status: shutdown+ access: []+ primitives: [video.t2v, video.i2v_first_frame, video.native_audio]+ limits:+ duration_s: {max: 20}+ strengths:+ - 发布时物理表现最好+ weaknesses:+ - App 于 2026-04-26 停止服务,API 于 2026-09-24 关停+ license: {commercial: false, note: 已关停}+ sources:+ - https://tech-insider.org/best-ai-video-generator-2026/+ verified: {date: 2026-10-29, basis: third-party}+ confidence: medium+ notes: 保留此条目,用来说明能力地图必须动态维护;路由器会跳过 status 为 shutdown 的模型diff --git a/capabilities/primitives.yaml b/capabilities/primitives.yamlnew file mode 100644index 0000000..559c470--- /dev/null+++ b/capabilities/primitives.yaml@@ -0,0 +1,332 @@+# rea-video 原语(primitives)+# 原语 = 一种与厂商无关的能力。模型条目通过 primitives 字段声明自己支持哪些原语;+# 路由规则(routing.yaml)只引用原语,再由原语找到候选模型。+# 每个原语声明:输入、输出、何时使用、用哪些指标验证(metrics)、探针测什么(probe)。++version: 0.1.0+updated: 2026-10-29++# ---------------------------------------------------------------- 验证指标+metrics:+ cut_alignment: {name: 切点对齐, desc: "重建片段的切点与原片切点的帧误差 / F1(容差 ±1 帧)"}+ shot_count_match: {name: 镜头数一致, desc: "镜头数量与时长分布的一致性"}+ ocr_text_match: {name: 文字一致, desc: "OCR 识别文本与目标文案的字符级一致率(CER)"}+ layout_iou: {name: 布局 IoU, desc: "文字/元素包围框与目标布局的 IoU(逐帧)"}+ timing_curve_error: {name: 动效曲线误差, desc: "元素位置/缩放/透明度随时间曲线与参考的误差"}+ pixel_similarity: {name: 像素相似度, desc: "SSIM / LPIPS,仅适用于代码层等可精确还原的画面"}+ perceptual_similarity: {name: 感知相似度, desc: "DreamSim / CLIP 相似度,用于生成层"}+ identity_consistency: {name: 主体一致性, desc: "人脸/商品/角色嵌入在镜头内与跨镜头的一致性"}+ motion_trajectory_error: {name: 运动轨迹误差, desc: "关键点/姿态轨迹与参考动作的误差"}+ camera_path_error: {name: 运镜误差, desc: "估计的相机轨迹与参考运镜的差异"}+ beat_alignment: {name: 节拍对齐, desc: "切点/动效事件与音乐节拍的对齐误差"}+ lip_sync: {name: 口型同步, desc: "SyncNet 类 LSE 分数"}+ audio_duration_match: {name: 音频时长匹配, desc: "生成语音与目标时间窗的时长误差"}+ speech_wer: {name: 语音可懂度, desc: "对生成语音做 ASR 后与脚本的字错率"}+ text_render_accuracy: {name: 画内文字准确率, desc: "生成图像/视频里文字(尤其中文)的正确率"}+ human_ab: {name: 人工盲测, desc: "像不像 / 好不好 / 能否投放 的盲测偏好"}++# ---------------------------------------------------------------- 原语+primitives:+ # ===== 分析(拉片)=====+ - id: analyze.video_understanding+ group: analyze+ name: 视频语义理解+ inputs: [video, audio, text]+ output: structured_text+ use_when: 理解镜头意图、表演、风格、叙事结构;生成镜头描述与提示词草稿+ probe: 给定带人工标注的镜头集,测镜头描述准确率、时间定位误差、计数类问题正确率+ - id: analyze.shot_boundary+ group: analyze+ name: 切镜检测+ inputs: [video]+ output: timestamps+ use_when: 所有视频的第一步+ metrics: [cut_alignment]+ probe: 硬切/溶解/遮挡转场混合样本的切点 F1+ - id: analyze.asr_word_align+ group: analyze+ name: 语音识别 + 字级对齐+ inputs: [audio]+ output: transcript_with_word_times+ use_when: 有人声的视频;给字幕、口播、卡点提供词锚点+ probe: 中英混说、方言样本的 CER 与词边界误差+ - id: analyze.ocr_text_track+ group: analyze+ name: 画面文字识别与轨迹+ inputs: [video]+ output: text_tracks+ use_when: 识别字幕、标题、UI 文字及其出现/消失/移动,供代码层重建+ probe: 运动文字、描边文字、复杂背景中文文字的识别率与框精度+ - id: analyze.segmentation+ group: analyze+ name: 分割与跟踪+ inputs: [video, text]+ output: masks+ use_when: 分离主体/商品/背景,测量元素轨迹+ - id: analyze.matting+ group: analyze+ name: 视频抠像(alpha)+ inputs: [video]+ output: video_with_alpha+ use_when: 需要透明前景(人物叠加到新背景、字幕穿插人物后方)+ - id: analyze.camera_motion+ group: analyze+ name: 相机运动反解+ inputs: [video]+ output: camera_trajectory+ use_when: 判断推拉摇移、手持感、3D 运镜,作为生成运镜或 3D 渲染的依据+ - id: analyze.audio_separation+ group: analyze+ name: 音频分轨+ inputs: [audio]+ output: stems+ use_when: 分离人声 / BGM / 音效,分别分析与替换+ - id: analyze.beat_tempo+ group: analyze+ name: 节拍与段落分析+ inputs: [audio]+ output: beat_grid+ use_when: 音乐卡点视频;给剪辑节奏提供节拍锚点+ - id: analyze.image_layer_decompose+ group: analyze+ name: 单帧图层分解+ inputs: [image]+ output: layered_images+ use_when: 把一帧拆成背景 + 透明元素层,用于理解或替换版式++ # ===== 图像 =====+ - id: image.t2i+ group: image+ name: 文生图+ inputs: [text]+ output: image+ use_when: 生成关键帧、角色设定、B-roll 静帧+ metrics: [perceptual_similarity]+ - id: image.edit_multi_ref+ group: image+ name: 多参考图像编辑/合成+ inputs: [image, text]+ output: image+ use_when: 把商品/人物/场景参考合成为首帧;换装换物;保持身份一致+ metrics: [identity_consistency, perceptual_similarity]+ probe: 同一商品在 5 个场景中的外观一致性+ - id: image.text_render+ group: image+ name: 画内文字渲染+ inputs: [text, image]+ output: image+ use_when: 画面中有招牌、包装、海报等实物文字(尤其中文)+ metrics: [text_render_accuracy]+ probe: 20 条中文短语(含生僻字、竖排、混排)渲染正确率+ - id: image.storyboard_series+ group: image+ name: 分镜组图+ inputs: [text, image]+ output: images+ use_when: 一次产出风格一致的多张分镜关键帧供确认+ - id: image.tryon+ group: image+ name: 虚拟试穿+ inputs: [image]+ output: image+ use_when: 服装电商换装:人物图 + 服装图 → 上身图,再进入图生视频+ metrics: [identity_consistency]++ # ===== 视频生成 / 编辑 =====+ - id: video.t2v+ group: video+ name: 文生视频+ inputs: [text]+ output: video+ use_when: 氛围空镜、无特定主体的 B-roll+ metrics: [perceptual_similarity]+ - id: video.i2v_first_frame+ group: video+ name: 图生视频(首帧)+ inputs: [image, text]+ output: video+ use_when: 构图/商品/人物必须准确时,先定首帧再动起来+ metrics: [perceptual_similarity, identity_consistency]+ - id: video.i2v_first_last+ group: video+ name: 首尾帧生成+ inputs: [image, image, text]+ output: video+ use_when: 起止状态都确定的镜头;变装/转场;与上一段尾帧衔接+ metrics: [perceptual_similarity, identity_consistency]+ - id: video.keyframes+ group: video+ name: 多关键帧控制+ inputs: [images, text]+ output: video+ use_when: 复杂运镜或多个中间状态必须命中+ metrics: [perceptual_similarity, camera_path_error]+ - id: video.multi_reference+ group: video+ name: 多参考生视频(主体一致)+ inputs: [images, text]+ output: video+ use_when: 同一角色/商品跨多个镜头一致;多主体同框+ metrics: [identity_consistency]+ probe: 3 个角色参考 × 4 个镜头的身份保持率+ - id: video.reference_video+ group: video+ name: 参考视频生成(动作/运镜/特效迁移)+ inputs: [video, images, text]+ output: video+ use_when: 原片的时间行为(动作节奏、运镜、特效演化)无法用文字和静帧描述时+ metrics: [motion_trajectory_error, camera_path_error]+ - id: video.reference_audio+ group: video+ name: 参考音频生成+ inputs: [audio, images, text]+ output: video+ use_when: 让画面跟随给定音频(音乐节奏、指定声音)+ metrics: [beat_alignment]+ - id: video.multi_shot+ group: video+ name: 单次多镜头+ inputs: [text, images]+ output: video+ use_when: 同角色同场景的连续多个镜头,一次生成以获得一致性与自然转场+ metrics: [cut_alignment, identity_consistency]+ - id: video.extend+ group: video+ name: 续写延长+ inputs: [video, text]+ output: video+ use_when: 超过单次时长上限的连续镜头+ - id: video.edit_v2v+ group: video+ name: 视频编辑(保留运动)+ inputs: [video, images, text]+ output: video+ use_when: 在已有画面上换人/换物/换风格/换背景/重打光,保留原动作与时序+ metrics: [motion_trajectory_error, identity_consistency]+ - id: video.camera_control+ group: video+ name: 运镜与镜头参数控制+ inputs: [text, image, video]+ output: video+ use_when: 需要指定推拉摇移、焦段、景深或改变已有镜头机位+ metrics: [camera_path_error]+ - id: video.native_audio+ group: video+ name: 音画同出+ inputs: [text, images, audio]+ output: video_with_audio+ use_when: 对白/环境声与画面强耦合的镜头+ metrics: [lip_sync, speech_wer]++ # ===== 人物驱动 =====+ - id: motion.transfer+ group: character+ name: 动作迁移+ inputs: [video, image]+ output: video+ use_when: 舞蹈、变装、特定手势、卡点动作需要精确复刻到新角色+ metrics: [motion_trajectory_error, identity_consistency]+ - id: avatar.audio_driven+ group: character+ name: 音频驱动数字人+ inputs: [image, audio, text]+ output: video+ use_when: 正面口播、长时间讲解+ metrics: [lip_sync, identity_consistency]+ - id: lipsync.redub+ group: character+ name: 口型重配+ inputs: [video, audio]+ output: video+ use_when: 已有表演换台词/换语言,只改嘴型+ metrics: [lip_sync]++ # ===== 3D =====+ - id: threed.image_to_3d+ group: threed+ name: 图生 3D+ inputs: [images]+ output: mesh+ use_when: 商品需要多角度一致、转台展示,或给视频模型提供白模参考+ metrics: [identity_consistency]++ # ===== 音频 =====+ - id: audio.tts+ group: audio+ name: 语音合成+ inputs: [text]+ output: audio+ metrics: [speech_wer]+ - id: audio.voice_clone+ group: audio+ name: 音色克隆+ inputs: [audio, text]+ output: audio+ use_when: 使用自己的/授权的音色做旁白或口播+ metrics: [speech_wer]+ - id: audio.tts_duration_control+ group: audio+ name: 时长可控配音+ inputs: [text, audio]+ output: audio+ use_when: 新配音必须塞进原片时间窗(对口型、对画面)+ metrics: [audio_duration_match, speech_wer]+ - id: audio.music_gen+ group: audio+ name: 音乐生成+ inputs: [text, audio]+ output: audio+ use_when: 需要与原片 BPM/情绪/结构相近、但可商用的新配乐+ metrics: [beat_alignment]+ - id: audio.sfx_gen+ group: audio+ name: 文生音效+ inputs: [text]+ output: audio+ - id: audio.v2a_foley+ group: audio+ name: 视频生音效(Foley)+ inputs: [video, text]+ output: audio+ use_when: 给生成画面自动配与动作同步的音效++ # ===== 代码渲染 =====+ - id: render.code_graphics+ group: render+ name: 代码渲染动效+ inputs: [code, data]+ output: video_with_alpha+ use_when: 文字、UI、图表、MG、字幕——需要 100% 准确且可改+ metrics: [ocr_text_match, layout_iou, timing_curve_error, pixel_similarity]+ - id: render.web_capture+ group: render+ name: 网页/界面录制+ inputs: [url, script]+ output: video+ use_when: 产品界面演示:直接驱动真实或重建的 UI 录屏+ - id: render.3d_scene+ group: render+ name: 3D 场景渲染+ inputs: [mesh, camera_trajectory]+ output: video+ use_when: 商品转台、精确运镜、白模参考+ - id: render.compose+ group: render+ name: 合成与编码+ inputs: [video, audio, video_with_alpha]+ output: video+ use_when: 多层叠加、转场、混音、最终编码++ # ===== 后期 =====+ - id: post.upscale+ group: post+ name: 视频超分+ inputs: [video]+ output: video+ use_when: 低分辨率草稿(如 480p)确认后放大到 1080p/4K+ - id: post.frame_interp+ group: post+ name: 补帧+ inputs: [video]+ output: video+ use_when: 帧率不足、慢动作diff --git a/capabilities/routing.yaml b/capabilities/routing.yamlnew file mode 100644index 0000000..9a06a8c--- /dev/null+++ b/capabilities/routing.yaml@@ -0,0 +1,266 @@+# rea-video 路由规则:镜头特征(signals)→ 原语链(route)→ 候选模型(prefer,按优先级)+# 规则只引用原语和模型 id;校验脚本会检查引用完整性和"模型确实支持该原语"。+# 选模型时:跳过 status=shutdown;对 regions_excluded 和 license 做过滤;同等条件按成本排序。++version: 0.1.0+updated: 2026-10-29++modes:+ fidelity: 高保真复刻。结构、节奏、运镜、文字、动效逐项对齐,用 scorecard 衡量+ adapt: 创意改编。保留原片"为什么有效"的关系(钩子、揭示、节奏),内容按新主题重写+ # 两种模式可以按层混用,例如 {rhythm: fidelity, camera: fidelity, people: adapt, copy: adapt}++# ---------------------------------------------------------------- 信号+# 拉片阶段要检测的镜头特征,以及由哪些分析原语提供证据+signals:+ text_or_ui_dominant: {detected_by: [analyze.ocr_text_track, analyze.video_understanding], desc: "文字/UI/图表/MG 是画面主体;字边锐利、像素对齐、轨迹规整"}+ screen_ui: {detected_by: [analyze.video_understanding, analyze.ocr_text_track], desc: 软件或网页界面的操作演示}+ talking_head_frontal: {detected_by: [analyze.video_understanding, analyze.asr_word_align, analyze.camera_motion], desc: 正面口播,机位基本固定}+ dialogue_coupled: {detected_by: [analyze.asr_word_align, analyze.video_understanding], desc: 对白与画面强耦合的非正面镜头(多人对话、边做边说)}+ precise_motion: {detected_by: [analyze.video_understanding, analyze.segmentation, analyze.beat_tempo], desc: 舞蹈、变装、卡点手势等动作本身就是看点}+ garment_change: {detected_by: [analyze.video_understanding], desc: 服装电商的换装或展示}+ physical_text_zh: {detected_by: [analyze.ocr_text_track], desc: 画面中的实物文字(招牌、包装、屏幕),尤其中文}+ product_hero: {detected_by: [analyze.video_understanding, analyze.segmentation], desc: 商品外观或构图必须准确}+ product_multiview: {detected_by: [analyze.video_understanding, analyze.camera_motion], desc: 商品旋转、多角度展示}+ complex_camera: {detected_by: [analyze.camera_motion, analyze.shot_boundary], desc: 复杂运镜、遮挡转场、瞬间变换}+ lens_look: {detected_by: [analyze.video_understanding], desc: 鲜明的焦段、景深、畸变等镜头感}+ recurring_character: {detected_by: [analyze.video_understanding, analyze.segmentation], desc: 同一角色或商品出现在多个镜头}+ owned_footage_edit: {detected_by: [], desc: 用户有权使用的已有素材,只需要换人、换物、换背景}+ redub_only: {detected_by: [analyze.asr_word_align], desc: 表演保留,只换台词或语言}+ ambient_broll: {detected_by: [analyze.video_understanding], desc: 氛围空镜,没有特定主体}+ reusable_footage: {detected_by: [], desc: 用户自有素材可直接复用}+ still_image_motion: {detected_by: [analyze.camera_motion], desc: 整帧是一张静态图做推拉摇移(Ken Burns),可测出缩放/平移参数}+ static_hold: {detected_by: [analyze.shot_boundary], desc: 静帧定格(图片或卡片停留)}++# ---------------------------------------------------------------- 拆分+segmentation:+ levels:+ edit_shot: 剪辑镜头,由切镜检测得到,是客观事实+ generation_unit: 生成单元,即一次模型调用的产物,与剪辑镜头不一一对应+ layer: 同一画面内的纵向分层(代码层 / 生成层 / 素材层 / 字幕层)+ defaults:+ generation_unit_s: {min: 4, max: 15}+ rules:+ - id: S01-merge-multishot+ do: 同角色、同场景的连续镜头,若总时长不超过候选模型上限,就合并为一个生成单元,用 video.multi_shot 一次生成+ why: 一致性和自然转场由模型内部解决+ - id: S02-split-duration+ do: 镜头超过候选模型的单次上限时,在动作停顿处切开,后一段以前一段的尾帧作首帧(video.i2v_first_frame 或 i2v_first_last)+ - id: S03-split-transition+ do: 遮挡转场、变装瞬间、强动作变化点单独切开,用首尾帧或关键帧精确控制+ why: 例如风扇叶遮挡时换装,时机错一点就会穿帮+ - id: S04-vertical-layers+ do: 文字、UI、图形、字幕抽成代码层;底下的画面走生成或素材层;最后合成+ why: 生成模型重绘文字必然出错,代码层 100% 准确且方便修改+ - id: S05-end-state+ do: 每个生成单元的提示词写清"动作过程 + 结束状态",结束状态作为下一单元的衔接条件+ - id: S06-hardcut-guard+ do: 单个生成单元内连续硬切画面不超过约 8 秒(实践经验,超过约 10 秒常出问题)+ - id: S07-long-video+ do: 长视频先按叙事段落切成多段分别处理,再拼接;拼接处检查商品外观一致、字幕与卖点对应、动作衔接++# ---------------------------------------------------------------- 画面路由+rules:+ - id: R01-code-graphics+ layer: overlay+ when: [text_or_ui_dominant]+ route: [render.code_graphics]+ prefer: [remotion, html-gsap-playwright, motion-canvas]+ verify: [ocr_text_match, layout_iou, timing_curve_error, pixel_similarity]+ why: 文字和动效要求像素级准确且可改;生成模型做不到++ - id: R02-screen-demo+ layer: base+ when: [screen_ui]+ route: [render.web_capture, render.code_graphics]+ prefer: [html-gsap-playwright, remotion]+ verify: [ocr_text_match, layout_iou]+ why: 用真实或重建的界面驱动录屏,比生成更准确++ - id: R03-talking-head+ layer: base+ when: [talking_head_frontal]+ route: [audio.voice_clone, avatar.audio_driven]+ prefer: [minimax-speech-2.8, omnihuman-2.0, kling-avatar-v2, ltx-2.3-lipsync]+ alternatives: 短镜头可改用音画同出模型加声音参考(R16)+ verify: [lip_sync, identity_consistency, speech_wer]++ - id: R04-precise-motion+ layer: base+ when: [precise_motion]+ route: [motion.transfer, video.reference_video, video.edit_v2v]+ prefer: [kling-motion-control, wan-2.2-animate, seedance-2.5, kling-o3, runway-gen-4.5]+ verify: [motion_trajectory_error, identity_consistency, beat_alignment]+ why: 动作的时间行为无法用文字和静帧描述+ guard: 参考视频先当证据;只有当时间行为本身就是看点时,才把片段作为模型输入。驱动视频必须有权使用++ - id: R05-garment+ layer: base+ when: [garment_change]+ route: [image.tryon, video.i2v_first_frame, motion.transfer]+ prefer: [fashn-v1.6, kling-kolors-tryon, seedance-2.5, kling-3.0, kling-motion-control]+ verify: [identity_consistency, perceptual_similarity]+ why: 先出试穿图并确认,再动起来,比直接让视频模型换装稳定++ - id: R06-physical-text-zh+ layer: base+ when: [physical_text_zh]+ route: [image.text_render, video.i2v_first_frame]+ prefer: [gpt-image-2.5, qwen-image-3.0-pro, seedream-5.0, seedance-2.5, kling-3.0]+ verify: [text_render_accuracy, ocr_text_match]+ guard: 文字需要长时间清晰稳定、或镜头运动大时,改走 R01 代码叠加(运动中视频模型会扭曲文字)++ - id: R07-product-hero+ layer: base+ when: [product_hero]+ route: [image.edit_multi_ref, video.i2v_first_frame, video.i2v_first_last]+ prefer: [gpt-image-2.5, nano-banana-2.1, seedream-5.0, seedance-2.5, kling-3.0, veo-3.1]+ verify: [identity_consistency, perceptual_similarity]+ why: 先用商品图合成首帧并确认,锁定外观后再生成运动++ - id: R08-product-multiview+ layer: base+ when: [product_multiview]+ route: [threed.image_to_3d, render.3d_scene, video.reference_video]+ prefer: [hunyuan-3d, rodin-gen-2.5, blender, seedance-2.5]+ verify: [identity_consistency, camera_path_error]+ why: 3D 模型保证多角度一致;可以直接渲染,也可以把白模渲染作为 Seedance 2.5 的参考++ - id: R09-complex-camera+ layer: base+ when: [complex_camera]+ route: [video.keyframes, video.i2v_first_last]+ prefer: [kling-4.0, kling-3.0, veo-3.1, runway-gen-4.5, minimax-h3]+ verify: [camera_path_error, cut_alignment]+ guard: 仍不可控时,在遮挡点切开(见 S03)++ - id: R10-lens-look+ layer: base+ when: [lens_look]+ route: [video.camera_control]+ prefer: [pixverse-v6, kling-4.0, runway-gen-4.5, gemini-omni-flash]+ verify: [perceptual_similarity]++ - id: R11-recurring-character+ layer: base+ when: [recurring_character]+ route: [video.multi_reference, video.multi_shot]+ prefer: [seedance-2.5, kling-3.0, kling-o3, vidu-q3, kling-4.0]+ verify: [identity_consistency, cut_alignment]++ - id: R12-owned-footage-edit+ layer: base+ when: [owned_footage_edit]+ route: [video.edit_v2v]+ prefer: [kling-o3, kling-4.0, runway-aleph-2, luma-ray3.2, wan-2.2-animate, seedance-2.5]+ verify: [motion_trajectory_error, identity_consistency]++ - id: R13-redub+ layer: base+ when: [redub_only]+ route: [lipsync.redub]+ prefer: [sync-3]+ verify: [lip_sync, speech_wer]++ - id: R14-ambient-broll+ layer: base+ when: [ambient_broll]+ route: [video.t2v]+ prefer: [minimax-h3, hailuo-2.3, seedance-2.0, wan-2.2, seedance-2.5]+ verify: [perceptual_similarity]+ why: 最便宜的路线,按成本排序++ - id: R15-reuse-footage+ layer: base+ when: [reusable_footage]+ route: [render.compose]+ prefer: [ffmpeg]+ verify: [cut_alignment]++ - id: R17-still-motion+ layer: base+ when: [still_image_motion]+ route: [image.edit_multi_ref, render.compose]+ prefer: [gpt-image-2.5, seedream-5.0, ffmpeg]+ verify: [camera_path_error, perceptual_similarity]+ why: 拆解阶段已测出缩放/平移曲线,用一张图 + 本地 ffmpeg 就能精确复刻运动,不需要视频模型++ - id: R18-static-hold+ layer: base+ when: [static_hold]+ route: [image.edit_multi_ref, render.compose]+ prefer: [gpt-image-2.5, seedream-5.0, ffmpeg]+ verify: [perceptual_similarity]++ - id: R16-dialogue-coupled+ layer: base+ when: [dialogue_coupled]+ route: [video.native_audio, video.multi_reference]+ prefer: [seedance-2.5, kling-3.0, veo-3.1, gemini-omni-flash, kling-4.0]+ verify: [lip_sync, speech_wer, identity_consistency]++# ---------------------------------------------------------------- 音频路由+audio_rules:+ - id: A01-narration+ when: 有旁白或口播+ route: [analyze.asr_word_align, audio.voice_clone, audio.tts]+ prefer: [funasr-sensevoice, whisperx, minimax-speech-2.8, cosyvoice-3, qwen3-tts, elevenlabs-v3]+ verify: [speech_wer]+ note: 中文优先用 MiniMax 克隆;英文情感优先用 ElevenLabs+ - id: A02-fit-time-window+ when: 新配音必须塞进原片时间窗(对口型、对画面)+ route: [audio.tts_duration_control]+ prefer: [indextts-2]+ verify: [audio_duration_match, speech_wer]+ - id: A03-music+ when: 有背景音乐+ route: [analyze.audio_separation, analyze.beat_tempo, audio.music_gen]+ prefer: [demucs, librosa-madmom, lyria-3-pro, minimax-music-2.5]+ verify: [beat_alignment]+ note: 不直接搬运原曲;生成 BPM 和情绪相近的新曲,或使用授权曲库。Suno 没有 API,只适合手动+ - id: A04-sfx+ when: 有动作音效或环境声+ route: [audio.v2a_foley, audio.sfx_gen]+ prefer: [hunyuanvideo-foley, elevenlabs-sfx]+ verify: [beat_alignment]+ note: HunyuanVideo-Foley 的许可排除欧盟、英国、韩国;MMAudio 权重不能商用+ - id: A05-lip-mismatch+ when: 生成画面的口型和新音频不同步+ route: [lipsync.redub]+ prefer: [sync-3]+ verify: [lip_sync]++# ---------------------------------------------------------------- 后期+post_rules:+ - id: P01-upscale+ when: 草稿分辨率低于交付分辨率+ route: [post.upscale]+ prefer: [seedvr2, flashvsr, topaz-video]+ note: 不推荐 Real-ESRGAN 处理生成视频(有方块伪影)+ - id: P02-interp+ when: 帧率不足或需要慢动作+ route: [post.frame_interp]+ prefer: [rife, topaz-video]++# ---------------------------------------------------------------- 成本与确认+cost_policy:+ - 每个生成单元先估算成本(时长 × usd_per_s),汇总后在 G1 由用户确认预算+ - 先出关键帧图或试穿图(便宜),确认后再生成视频(贵)+ - 先以 480p 或 720p 出草稿,确认后超分到交付分辨率(实测可以明显降本)+ - 同一角色的多个镜头优先合并成一次多镜头生成(S01)+ - 已产出的生成单元按(输入哈希 + 模型 + 参数)缓存,改写时只重跑受影响的单元++confirm_gates:+ G1: 需求、模式(fidelity/adapt)、预算与账号+ G2: 分镜表 + 关键帧图 / 试穿图 / 首帧+ G3: 低清草稿成片+ G4: 超分成片与 scorecard++# ---------------------------------------------------------------- 提示词纪律+prompting_rules:+ - 只写想要的内容;不写否定句(写 "no phone" 反而会画出手机)+ - 写清"动作过程 + 结束状态"+ - 每个输入标注职责:身份参考、商品事实、动作或运镜参考、声音参考、台词+ - 避免比喻性措辞,模型会把比喻画成字面上的物体或事件+ - 精确数量(手指比数字等)交给字幕或 MG,不要让模型表演+ - 给表演一个可执行的态度,而不是罗列动作diff --git a/capabilities/schema.json b/capabilities/schema.jsonnew file mode 100644index 0000000..672137a--- /dev/null+++ b/capabilities/schema.json@@ -0,0 +1,66 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/rea-video/capabilities/model.schema.json",+ "title": "rea-video model capability entry",+ "type": "object",+ "required": ["id", "name", "vendor", "category", "status", "access", "primitives", "license", "sources", "verified", "confidence"],+ "additionalProperties": false,+ "properties": {+ "id": {"type": "string", "pattern": "^[a-z0-9][a-z0-9.\\-]*$"},+ "name": {"type": "string"},+ "vendor": {"type": "string"},+ "category": {"enum": ["video", "image", "character", "audio", "threed", "analysis", "render", "post"]},+ "release": {"type": "string", "pattern": "^\\d{4}-\\d{2}$"},+ "status": {"enum": ["ga", "preview", "limited", "deprecated", "shutdown"]},+ "access": {"type": "array", "items": {"enum": ["app", "api", "api-aggregator", "open-weights"]}, "uniqueItems": true},+ "primitives": {"type": "array", "items": {"type": "string"}, "minItems": 1, "uniqueItems": true},+ "limits": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "duration_s": {"$ref": "#/$defs/range"},+ "audio_s": {"$ref": "#/$defs/range"},+ "resolutions": {"type": "array", "items": {"type": "string"}},+ "refs": {+ "type": "object", "additionalProperties": false,+ "properties": {"image": {"type": "integer"}, "video": {"type": "integer"}, "audio": {"type": "integer"}, "total": {"type": "integer"}}+ },+ "keyframes": {"type": "integer"},+ "shots_per_generation": {"type": "integer"},+ "prompt_tokens": {"type": "integer"}+ }+ },+ "audio": {+ "type": "object", "additionalProperties": false,+ "properties": {"native": {"type": "boolean"}, "voice_ref": {"type": "boolean"}}+ },+ "strengths": {"type": "array", "items": {"type": "string"}},+ "weaknesses": {"type": "array", "items": {"type": "string"}},+ "cost": {+ "type": "object", "additionalProperties": false,+ "properties": {"usd_per_s": {"type": ["number", "null"]}, "note": {"type": "string"}}+ },+ "license": {+ "type": "object", "required": ["commercial"], "additionalProperties": false,+ "properties": {"commercial": {"enum": [true, false, "conditional"]}, "note": {"type": "string"}}+ },+ "regions_excluded": {"type": "array", "items": {"type": "string"}},+ "sources": {"type": "array", "items": {"type": "string", "pattern": "^https?://"}, "minItems": 1},+ "verified": {+ "type": "object", "required": ["date", "basis"], "additionalProperties": false,+ "properties": {+ "date": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},+ "basis": {"enum": ["probe", "user", "vendor", "third-party", "knowledge"]}+ }+ },+ "confidence": {"enum": ["high", "medium", "low"]},+ "probe_scores": {"type": "object"},+ "notes": {"type": "string"}+ },+ "$defs": {+ "range": {+ "type": "object", "additionalProperties": false,+ "properties": {"min": {"type": "number"}, "max": {"type": "number"}}+ }+ }+}diff --git a/docs/decompose.md b/docs/decompose.mdnew file mode 100644index 0000000..5c73407--- /dev/null+++ b/docs/decompose.md@@ -0,0 +1,78 @@+# 拆解方法:怎么判断一个镜头是"怎么做出来的"++目标:对每个镜头给出底层画面的制作方式、叠加层、证据和置信度,再给出复刻路线。++## 1. 分类体系++| 标签 | 含义 | 复刻路线(capabilities/routing.yaml) |+|---|---|---|+| `live_action` | 实拍 | R07:AI 图生视频近似,或重新拍摄 |+| `ai_video` | AI 生成视频 | R07:首尾帧 + 提示词,由 capsule-cinema 生成 |+| `avatar` | 数字人口播 | R03:配音克隆 + 数字人 |+| `cg_3d` | 3D 渲染 | R08:3D 建模渲染,或 AI 首尾帧近似 |+| `code_render` | 代码/模板渲染(MG、文字、UI、图表、卡片) | R01:Remotion/HTML 重建 |+| `screen_capture` | 屏幕录制/截图 | R02:真实界面录制 |+| `still_motion` | 静态图 + 推拉摇移 | R17:一张图 + 测得的运动参数,本地精确复刻 |+| `static_hold` | 静帧定格 | R18:一张图 |++叠加层单独列出:字幕、标题、文字标注、图形贴片、版式模板。同一镜头可以是"AI 视频 + 代码字幕"。++## 2. 证据从哪里来++确定性取证负责"可测量"的问题,VLM 负责"看懂"的问题,两者分工明确:++| 问题 | 方法 | 可靠度 |+|---|---|---|+| 哪里切镜 | HSV 直方图距离与像素差分,加局部自适应阈值;变化面积要足够大,元素弹出不算切镜。交叉溶解:中间帧是否为两端帧的线性混合,并用光流排除推拉运动 | 高(两条真值片 F1=1.0,其中一条含 14 处 0.25s 溶解) |+| 画面动没动 | 逐像素完全重复帧的比例、首尾帧差 | 高 |+| 是不是一张图在推拉 | LK 光流拟合相似变换(RANSAC):内点率高、残差小、无局部运动,且运动补偿后几乎没有残余 | 高 |+| 渲染还是拍摄的纹理 | 平坦 8×8 块比例、覆盖 95% 像素所需颜色数、横竖直边比例、Immerkær 噪声 | 高(区分渲染与照片) |+| 2D 合成 / 代码动效 | 背景像素逐帧完全不变、只有局部在动 | 高 |+| 原始帧率 | 重复帧规律(24→30 时约 20%,周期 4–6);插帧导致的清晰度周期起伏;原生 ≥48fps 且无重复帧 | 中高:生成模型输出 24/25fps,手机常拍 60fps |+| 实拍还是 AI 还是 3D | 传感器噪声与时域噪声、手持抖动、帧率指纹,加上 VLM 看破绽(手指、文字、物理、纹理闪烁) | 只有确定性时为中,加 VLM 后为高 |+| 元数据 | 拍摄设备 make/model;GB 45438 AIGC 隐式标识(Label 1/2/3 及服务方编码);C2PA;编辑器/渲染器签名 | 出现时很强;常被平台清除 |+| 叠加层 | 背景在动但像素冻结的边缘簇,加 OCR 文字轨(位置、是否随时间变化、是否水平) | 中高 |+| 音频 | 起音/节拍、切点落在起音上的比例(卡点)、语音调制特征 | 中 |++## 2.1 用户真实素材++素材来源分为四种:AI 生成、制作方渲染、用户真实素材、混合。++- **整帧**:从底层画面标签推出。实拍 = 实拍素材;录屏 = 界面录制/截图;静帧来源是照片或截图 = 真实素材。+- **嵌入**(只在渲染画面里检测):+ - 浅色低饱和面板内,单帧有 ≥6 处小字号文字 → 界面截图(确定是真实素材)+ - 灰度熵高、无平涂色的区域 → 图片或视频片段(真实还是 AI **待确认**)+ - 字幕带不参与检测+- 复刻计划里,真实素材都列在 `user_assets`,复刻时由用户提供,不能用模型生成。++## 2.2 声音++在 STFT 上做 HPSS(中值滤波分离谐波和打击成分):++- **人声**:人声频段 3–8Hz 的音节调制,加上句间停顿;用基频给出男/女声提示。+- **音乐**:人声间隙里仍然响亮且有音调的音乐床,或明显的节拍周期;用起音自相关估 BPM,用 Krumhansl 轮廓估调性,用色度新颖度找段落变化。+- **剪辑**:切点落在节拍或起音上的比例。+- **音效**:确定性层只给人声之外的显著瞬态作为低置信候选,完整清单由 VLM 听出(见 eval/RESULTS.md 的实测)。+- **产物**:`audio`(测量值)、`audio_plan`(合并 VLM 后的声音轨与复刻方案)、`audio.png`(时间轴)。++## 3. 融合++最终概率 ∝ 确定性概率^(0.6×可信度权重) × VLM 概率,再加两条硬约束:++- 画面冻结的镜头不能被判为任何"视频生成"类。+- 整图刚体推拉的镜头不能被判为实拍或数字人。++可信度权重:静帧 1.6、静态图推拉 1.4、代码渲染 1.0,实拍、AI 和 3D 都只有 0.6,所以这三类主要由 VLM 决定。++## 4. 产物++```+out/<name>/+ breakdown.json Video IR(rea_video.breakdown.v1):每镜特征、证据、概率、叠加层、复刻计划+ report.html/md 人读报告+ storyboard.jpg 分镜总览(按制作方式着色)+ shots/ 每镜联系表、首帧、尾帧(首尾帧也是复刻输入)+ clips/, vlm_cache/ VLM 输入片段和缓存(仅 --vlm)+```++`finalize()` 可以只用已存的特征和 VLM 回答重新分类:规则更新后不必重新解码视频,`rea-video eval` 会自动这样做。diff --git a/docs/vs-hypit.md b/docs/vs-hypit.mdnew file mode 100644index 0000000..d84167f--- /dev/null+++ b/docs/vs-hypit.md@@ -0,0 +1,86 @@+# rea-video vs Hypit:学什么,怎么超越++> 分析对象:[hypit-ai/hypit](https://github.com/hypit-ai/hypit) 主分支,2026-10-29 浅克隆阅读+>(README、`skills/hypit/SKILL.md` 及其 references、`packages/`)。++## 1. Hypit 是什么++- 定位:"让 AI Agent 复刻任何爆款视频"。以 `/hypit` Skill 的形式运行在 Claude Code、Codex 等 agent 里。+- 核心是自定义语言 **SVML**(加 SVS 和 SVRun):画面、字幕、B-roll、特效都锚定在**词**上,而不是秒上。最后编译成 HTML 视频,由无头 Chromium 并发渲染(示例用了 64 个进程)。+- 拉片方式:`hypit transcribe` 调用 WhisperX 做字级对齐;`hypit media tile/tiles/frames/boundaries` 生成带时间和字幕标注的帧网格,再由 agent **看图理解**。结论写进 `ANALYSIS.md`(全片解读)和 `TIMELINE.md`(时间码细节)。+- 模型接入分四层:Model(请求语义)、Provider(实现)、Endpoint(账号实例)、Runtime Profile(选择与凭据)。默认网关是 HypiHub,也支持 BYOK。+- 已有的模型包:+ - 视频:Seedance(含 2.5 / Mini)、PixVerse V6 / C1、MiniMax H3、Grok Imagine、Wan+ - 图像:GPT Image 2、Nano Banana、Seedream 5 Lite+ - 语音:ElevenLabs、Fish Audio、MiMo+ - 其他:WhisperX 对齐、火山引擎人像抠像、OpenCV 图像操作+- 示例成本:每条 1.07–1.15 美元,约 2.6 万星。+- 许可:修改版 Apache 2.0。**禁止**未经授权做多租户 SaaS、商业再分发,禁止移除 Logo;产出内容归用户。++## 2. 值得学习的设计++| 设计 | 说明 | rea-video 怎么吸收 |+|---|---|---|+| 语义时间 | 事件锚定在台词或动作上,改词后时间轴自动重排 | IR 支持多种锚点,词锚点是其中之一 |+| 组件化 | 字幕、MG、B-roll 都是可参数化组件,换主播不动字幕 | 代码层用 Remotion 组件,参数暴露进 IR |+| 参考视频"先当证据,再当输入" | 只有当动作、运镜等时间行为无法用文字和静帧描述时,才把原片片段喂给模型 | 写成路由规则(见 `routing.yaml` 的 R04) |+| 输入职责分离 | 角色参考、商品参考、动作参考、声音参考、台词,各自承担明确的职责 | Shot Recipe 中每个输入都要标注职责 |+| 文件即记忆 | BRIEF / TREATMENT / ANALYSIS / TIMELINE / PROGRESS | 采用类似约定,但核心状态放在机器可读的 IR |+| Run/Build 复用和成本计划 | 已产出的素材可以显式复用;花钱前先确认预算 | 生成单元级缓存;先估算成本,再到确认节点 |+| Studio 加时间码评论 | 用户可以在时间轴上评论和调参 | P2 之后做预览和评论,也可以直接导出剪映草稿 |+| 导演经验沉淀在 Skill 里 | 大量图像、视频、声音、字幕方面的 craft 指南 | 我们沉淀为**结构化的能力地图和规则**,加上少量 craft 文档 |++## 3. Hypit 的短板(有证据)++1. **拉片不结构化**+ - 理解主要靠 agent 看帧网格,产物是散文 Markdown,不是机器可读的 IR。+ - 仓库里搜不到 OCR、动效曲线拟合、相机反解、音乐结构分析(`grep ocr|paddle|ssim|lpips` 均无结果)。+ - 文字的精确位置、字体、出入场曲线,全靠 agent 目测。+2. **没有量化验证**+ - "Done means watched":质量靠 agent 和用户观看判断。+ - 和原片之间没有差分指标、回归测试或分数。+3. **改编优先,不追求还原**+ - 文档明确写道:"need not guess the original author's source code or component structure"。+ - 这对创意改编合理,但做不了"高保真复刻",也无法衡量复刻得像不像。+4. **模型覆盖窄**+ - 视频没有 Kling、Veo、Vidu、Runway、Luma、海螺。+ - 没有专门的数字人(OmniHuman)、口型重配(Sync)、动作迁移、虚拟试穿、3D、音乐生成、视频生音效、超分。+5. **没有能力注册表**+ - 模型边界散落在 craft 散文和各 package 文档里。+ - 选模型靠 agent 判断,没有统一的"能力、边界、价格、许可"数据,也没有探针去测边界。+6. **时间主轴偏向语音**+ - 口播、播客、采访、排行榜是强项。+ - 无语音的音乐卡点、产品 MG、电影感短片、舞蹈和变装,没有一等公民的锚点类型(节拍虽然被提到是"同级时间源")。+7. **出口单一**:只能走 Hypit 自身的 HTML/Chromium 管线,没有剪映草稿、OTIO、AE 等导出。+8. **许可限制**:不能拿它做 SaaS 或商业再分发。rea-video 应当 **clean-room 实现、不复制代码**,以便采用宽松许可(例如 MIT,与 REA 一致)。++## 4. rea-video 的超越方案++| # | 方向 | 具体做法 | 对应短板 |+|---|---|---|---|+| A | **结构化逆向** | 确定性 CV(切镜、OCR 轨迹、SAM 分割、相机运动、节拍、字级对齐)加上 VLM 语义。产出 Video IR,每个元素附证据(帧号)、置信度和 unknowns | 1 |+| B | **能力地图 + 路由器 + 探针** | `capabilities/` 数据化记录每个模型;路由规则把镜头特征映射到原语和模型;每个原语一组探针测试,新模型上线自动跑、自动刷新分数 | 4、5 |+| C | **差分验证** | 每镜 scorecard:切点 F1、OCR 文本一致、布局 IoU、SSIM/LPIPS(代码层)、DreamSim/CLIP(生成层)、身份一致性、轨迹误差、节拍和口型对齐。agent 循环修复最差的镜头 | 2 |+| D | **双模式 + 分层保真度** | fidelity / adapt 两种模式,按层设定保真度(结构、节奏、运镜、文字、动效、音乐、人物) | 3 |+| E | **多锚点时间** | 词、节拍、动作事件、绝对帧都是锚点;音乐卡点和 MG 不依赖语音 | 6 |+| F | **更广的覆盖 + 国内生态** | 可灵、即梦 / Seedance、Vidu、海螺、MiniMax 语音、豆包 VLM、GPT Image 2.5 中文字;加上数字人、试穿、3D、Foley、超分 | 4 |+| G | **开放导出** | 导出 Remotion 工程、OTIO,以及剪映草稿(规划中);可考虑与 Hypit SVML 互通 | 7 |+| H | **成本工程** | 镜头级成本预估;先确认关键帧图;480p 草稿后超分;同一角色的多个镜头合并成一次生成 | — |++## 5. 如何证明"比 Hypit 好"++建一个公开的 **rea-video-bench**:++- **素材分类**:+ 1. 口播 UGC+ 2. 播客、采访+ 3. 产品 MG 宣传片(大量文字和 UI)+ 4. 电商实拍带货+ 5. 变装、舞蹈(动作强相关)+ 6. 音乐卡点混剪+ 7. 屏幕录制演示+- **客观指标**:结构还原(镜头数、切点 F1)、文字准确率、节奏和节拍对齐、主体一致性、口型同步、成本、耗时。+- **主观指标**:盲测 A/B,比较像不像、好不好看、能不能投放。+- **合成子集**:随机生成"已知源码"的 Remotion 视频,测量逆向还原率(自带 ground truth)。++Hypit 的优势领域是类别 1 和 2。rea-video 先在类别 3(产品 MG)建立明显优势,再全面对比。diff --git a/eval/RESULTS.md b/eval/RESULTS.mdnew file mode 100644index 0000000..8c442cd--- /dev/null+++ b/eval/RESULTS.md@@ -0,0 +1,155 @@+# 评测结果(v0.2,2026-10-30)++运行配置:**只用确定性取证 + OCR,没开 VLM**(VLM 用来补强"实拍 / AI / 3D"的区分、AI 图和真实照片的区分,以及轻音效)。复现命令见文末。++## 1. 底层画面制作方式(8 类,按镜头时长加权)++| 集合 | 视频数 | 准确率 | 切点 F1 | 独立性 |+|---|---|---|---|---|+| `labels.yaml`(调参集) | 15 | **99.9%** | 1.00(2 条有真值,含 14 处 0.25s 交叉溶解) | 规则在这批样本上设计 |+| `holdout.yaml` | 9 | **99.6%** | — | 首轮错了 2 处,据此加了帧率相关规则,已不完全独立 |+| `holdout2.yaml` | 7 | **99.8%** | — | 制作方式规则定稿后才第一次运行 |++调参集的混淆矩阵(秒):实拍 16.0 全对;AI 视频 141.2 全对;3D 66.5 全对;代码渲染 157.9 对、0.4 错判为 3D;录屏/截图 19.0 全对;静帧 48.2 全对。++## 2. 用户真实素材(镜头里有没有实拍 / 截图 / 录屏 / 照片,按时长加权)++| 集合 | 准确率 | 说明 |+|---|---|---|+| labels | 97.6% | 唯一错误:mediank 的暗色半透明 NASA 背景照片漏检(已知局限) |+| holdout | 99.6% | 首轮有 2 处误报:浅色代码画面的字幕被当成截图;3D 毛发被当成嵌入视频。修复后的结果 |+| holdout2 | 98.1% | **首轮只有 75.6%**:字幕带被当成照片/视频;嵌入图片默认算作"真实"。修复后已不独立。剩余错误:暗色主题网页截图漏检 |++修复内容:+- 文字按单帧计数,避免不同时刻的字幕被累加。+- 字幕带不参与照片/视频判断。+- 嵌入的照片/视频片段默认标为"真实还是 AI 待确认",只有截图和录屏直接算真实素材。+- 3D 画面里只认截图面板。++## 3. 声音++| 项 | 结果 | 真值来源 |+|---|---|---|+| 有无人声 | 5/5 | capsule-cinema 的 tts.py、口播视频 |+| 有无 BGM | 4/4 | bgm.py、bgm_fit.json |+| BPM(±4%,含半速/倍速) | 2/2(110.0 / 112.3 vs 真值 110.15) | bgm_fit.json |+| 调性 | 2/2(D major) | bgm_fit.json |+| 有无音效(≥3 处) | 2/4 | cues.py、素材清单 |+| 音乐来源 | 2/5(见下) | Suno 生成记录、曲库下载记录 |++**音效是确定性层的短板**:在咸鸭蛋的人声 + BGM 混音里,对照 cues.py 的 110 个音效真值,信号特征完全区分不了音效和语音/音乐起音(精度约 0.2,与随机相当)。所以现在只在人声之外、且极其突出的瞬态上给出"低置信候选",**完整的音效清单交给 VLM(Gemini 能听)**。++**音乐来源**按"视频形式先验 + 证据"判断(规则见 `skills/rea-video/references/audio.md`)。不开 VLM、不给平台信息时:++| 视频 | 形式 | 真值 | 判断 |+|---|---|---|---|+| qing_hiphop_mv | AI 说唱 MV(干声副歌重复 0.26) | Suno v6 | AI 生成 52% ✓ |+| mediank_pure_data | 纯配乐 | 曲库 manten diloty | 现成曲库 60% ✓ |+| monkey_wine_v3 / salted_egg / birdnest | TTS 旁白 + BGM(干声副歌重复 0.00) | Suno 生成 | 现成曲库 52% ✗ |++三个错例是**先验本身的局限**:AI 工作流做出来的普通视频,BGM 也常是 Suno 生成的,而 Suno 器乐和曲库器乐从信号上分不开。之前 3/3 是因为"满屏音乐 + 有人声"误把 TTS 旁白当成 MV,属于碰对;现在加了唱/说区分,判断理由对了,准确率反而如实下降。纠正这三条要靠平台音乐标签(`--meta`)或听歌识曲,所以报告里普通配乐一律写"倾向曲库,待确认"。注意唱/说的阈值是看过 qing MV 之后定的,这条属于开发集。++**人声分离**(`stems/`):把咸鸭蛋的一句 TTS 叠在它的 Suno BGM 上(人声高 6 dB),分离 SDR 人声 19.7 dB、配乐 19.7 dB;纯 BGM 漏进人声轨 −42.5 dB。mediank 的键盘音效会落进人声轨(瞬态音效的已知去向)。说唱 MV 在混音上测的持续音高是 0.44,在干声上只有 0.24——混音上的数字被伴奏的长音抬高了,所以现在唱/说一律在干声上测。++## 4. 平台转码视频(OiiOii 文章里的 10 条,开发集)++`eval/articles.yaml`:从两篇公众号文章下载的微信转码版(30fps、二次压缩)。真值来自文章作者说明 + 人工看画面。v0.3 的规则是看过这批视频后加的,所以这是开发集。++| 视频 | 真值 | v0.2 | v0.3 |+|---|---|---|---|+| v11 TikTok 带货原片 | 实拍 | AI 100%(0.0) | 实拍 100%,标"实拍还是 AI 待确认"(1.0) |+| v09 Gemini 发布片 | 2D UI 动效 | 代码 63% + 3D 37%(0.63) | 代码 81% + 3D 19%(0.81) |+| v10 OiiOii 产品片 | 代码 UI 动效 | 代码 78% + 3D 17%(0.83) | 代码 92% + 3D 4%(0.96) |+| v04 推广片原片 | 3D 元素 + 文字动效 | 3D 65% + AI 35%(0.65) | 不变(0.65) |+| 其余 6 条 AI 视频 / 拼屏 | — | 全对 / 0.8 | 不变 |+| **平均** | | **0.79** | **0.92** |++v0.3 的三处修改:+1. 识别平台转码(元数据 `Tencent CAPD MTS` / `Wxmm_` / `vid:v…`)。转码后噪声证据失效,"没有噪声"不再推向 AI;清晰度节奏(会被转码的 GOP 结构伪造)不再当插帧证据。+2. 整片级帧率证据:30fps 文件里,实拍类镜头 ≥70% 时长没有重复帧 → 倾向手机直出(生成模型多输出 24fps,转 30fps 后有 20% 重复帧)。+3. 几乎无彩色、只用个位数颜色的平面画面判为界面/文档,不判 3D。++三个评测集回归:制作方式 99.9% / 99.6% / 99.8% 与 v0.2 完全一致。++### agent 复核(dsh,DeepSeek V4.1 Flash,不能看图)++11 条有真值时:工具全对 5 / 部分对 5 / 错 1;dsh 复核后全对 6 / 部分对 2 / 错 3。dsh 推翻工具 4 次,2 对 2 错,错的两次都是凭像素统计改判画面类型。为此 SKILL.md 增加了"看不了图时不得推翻工具的制作方式判断"。详细见 `out/dsh_articles/REVIEW.md`,复测方法见 `eval/agent_test/README.md`。++## 已知局限++1. 实拍样本只有 3 条(都是 60fps 抖音手机视频);没有真实的 Ken Burns 样本,只在合成视频上测过。+2. 暗色/半透明的背景照片、暗色主题网页截图漏检;实拍或 AI 画面上叠加的商品图和 Logo 不做确定性检测,依赖 VLM。+3. 嵌入图片是真实照片还是 AI 图,确定性层判断不了。+4. VLM 路径只用假服务器测过端到端,还没有在真实 Gemini 上跑过评测。+5. 音乐来源:普通视频里的 AI 生成 BGM 判断不出来(见上);AI MV 样本只有 1 条。++## 复现++```bash+export CAPSULE_CINEMA_ROOT=~/code/github/capsule-cinema+rea-video eval eval/labels.yaml -o out/eval_main+rea-video eval eval/holdout.yaml -o out/eval_hold+rea-video eval eval/holdout2.yaml -o out/eval_hold2+rea-video eval eval/articles.yaml -o out/eval_articles # 视频需先放到 eval/media/articles/+rea-video eval eval/audio_mv.yaml -o out/eval_audio_mv --stems # 只评音频(--stems 先分离人声再测唱/说)+# 加 VLM:+rea-video --env-file $CAPSULE_CINEMA_ROOT/.env eval eval/labels.yaml -o out/eval_main_vlm --vlm+```++## 2026-10-30:第一次用真实 Gemini 跑 VLM,并加入「agent 看图复核」++数据:`eval/articles.yaml`(10 条微信转码视频,**开发集**,规则看过这批视频)。VLM 结果来自 zcode 盲测第 2 轮(`gemini-3.1-pro-preview-pc`,每条都生效),agent 复核来自同一轮 zcode 的 `rea-video review / apply-review` 答案。用缓存结果重新融合,不再调用 API。++| 组合 | VLM 权重 1.0(旧) | VLM 权重 0.7(新) |+|---|---|---|+| 只用确定性取证 | 0.886 | 0.886 |+| + Gemini VLM | 0.888 | 0.888 |+| + agent 看图复核 | 0.988 | **1.000** |+| + VLM + agent | 0.915 | 0.984 |++(按时长加权的准确率;真实素材准确率四种组合都是 1.0)++- Gemini 在 3D / UI 动效类视频上有帮助(v04 0.65→1.0、v08 0.8→1.0、v09 0.81→0.98),但会把卡通 3D 风格的 AI 视频判成 3D 渲染、把画进画面的游戏界面判成录屏(v01 1.0→0.13、v12 1.0→0.56、v13 1.0→0.44),而且置信度给到 0.9–1.0,压过了 24→30 重复帧等帧率证据。+- 改动:融合时 VLM 权重 1.0→0.7(`classify.VLM_WEIGHT`);融合结果必须是确定性层或模型排前两名的类别(修 v01 最后一镜三方都没投却得出"实拍");`review_tasks.json` 只给 agent 看确定性结果,不给 VLM 答案,避免被带偏。+- 只有 10 条开发集视频,权重没有往更低调(0.5 在这批上更高,但怀疑过拟合)。下一步:在 labels / holdout 上跑一次 `--vlm`,确认 0.7 不伤别的视频。+- labels 0.999 / holdout 0.996 / holdout2 0.998 不受影响(这些评测不开 VLM)。++## 2026-10-30:留出集验证(zcode + Gemini VLM + agent 看图复核)++数据:`eval/holdout.yaml`(9 条)+ `eval/holdout2.yaml`(7 条),这 16 条没参与过 VLM 权重和复核流程的调参。zcode 按 JOB.md 盲测(视频改名 h01–h16,对照表在 `out/agent_eval/zcode/runs_holdout/mapping.tsv`),`--vlm`(16/16 生效)+ `review / apply-review`。h09(lulukong_b)zcode 自身报错中断,没写复核,只计工具 + VLM。++| 组合 | holdout | holdout2 | articles(开发集) |+|---|---|---|---|+| 只用确定性取证 | 0.996 | 0.998 | 0.886 |+| + Gemini VLM | 0.989 | 0.965 | 0.888 |+| + agent 看图复核 | 0.996 | 0.968 | 1.000 |+| + VLM + agent(改前) | 0.998 | 0.988 | 0.984 |+| + VLM + agent(加「工具 + 一方看图」多数规则后) | **0.998** | **0.998** | **0.988** |++- 只开 VLM 在留出集上是负收益(holdout2 0.998→0.965):Gemini 把文字卡片判成静帧/截图推拉,把毛绒 AI 角色判成实拍/3D,置信度 0.85–1.0。+- 改前 holdout2 唯一的退步是 lulukong_c 最后一镜:工具判 AI(0.46)、zcode 判 AI(0.83),只有 Gemini 判实拍(0.85),结果却是实拍。原因是 VLM 和 agent 的意见先平均再融合,Gemini 给 AI 只有 0.05,把 zcode 那一票抵掉了。+- 改动:`pipeline._majority` + `classify.fuse(majority=...)`。工具首选和 VLM、agent 中恰好一方一致时,最终类别必须是它(帧冻结等硬约束仍优先)。反过来 VLM 和 agent 一致反对工具时**不**强制:试过三方任意多数,articles 从 0.984 掉到 0.919、dual_role_realcat 1.0→0.83,两个看图模型常把同一画面看错成同一类。+- 「证据不足,待确认」:转码 + 24fps 源 + 无 AIGC 标识的 AI 视频(capybara_a、lulukong_a/b/c)都被标出、置信度封顶 0.7;手机原生 30fps 的实拍(douyin_live_breakfast)、代码/3D 类视频不受影响。+- zcode 的 FINAL 结论:15 条完成的里 14 条制作方式正确;dual_role_realcat 写成"静态图推拉·真实截图 56% + AI 44%"(真值是代码模板卡片 + 真实截图 + AI),真实素材判断对。+- labels 0.999 / holdout 0.996 / holdout2 0.998(不开 VLM 的回归)不变。+- 结论:开 VLM + agent 复核在三组数据上都不低于只用工具,在开发集上大幅更高;只开 VLM、不做 agent 复核时会变差,SKILL.md 里"能看图的 agent 必须做 review"的要求要保留。++## 2026-10-30:只有一个看图来源时加限制;加入用户记忆++问题:只开 VLM、不做 agent 复核时,比只用工具还差(holdout2 0.998→0.965);只有 agent 看图、没有 VLM 时,holdout2 也降到 0.968。++改动(`pipeline._vlm_gate`):只有一个看图来源时(只有 VLM 或只有 agent),它的首选必须在工具前两名里;工具对 AI / 实拍 / 数字人有把握(≥0.65 且领先 ≥0.25)时不采用;转码 24fps 素材、没有手机原生 30fps 证据时,不采用"实拍"。两个来源都有时不受影响,由 `_majority` 决定。++| 组合 | holdout | holdout2 | articles(开发集) |+|---|---|---|---|+| 只用确定性取证 | 0.996 | 0.998 | 0.886 |+| + VLM(改前 → 改后) | 0.989 → **0.996** | 0.965 → **0.998** | 0.888 → **0.996** |+| + agent(改前 → 改后) | 0.996 → 0.996 | 0.968 → **0.998** | 1.000 → 1.000 |+| + VLM + agent | 0.996 | 0.998 | 0.988 |++(holdout 的 VLM + agent 从 0.998 变为 0.996:h09 没有 agent 复核,现在按"只有 VLM"处理。)++- 比较过的其他做法:只在工具没把握时用 VLM(holdout2 0.965)、只要求在前两名里(holdout 0.987)、把 VLM 概率摊平到 0.3(holdout2 0.974)。最终方案是"前两名 + AI/实拍轴保护"。+- 注意:这条规则是在这三组数据上选出来的,三组都不再是"没见过的视频"。需要一批新视频复核,用户纠正导出的样本(`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`)不读用户记忆。diff --git a/eval/agent_test/JOB.md b/eval/agent_test/JOB.mdnew file mode 100644index 0000000..2a50176--- /dev/null+++ b/eval/agent_test/JOB.md@@ -0,0 +1,12 @@+你在 rea-video 仓库的一份副本里(当前目录)。先读 AGENTS.md、skills/rea-video/SKILL.md,以及它引用的 skills/rea-video/references/(taxonomy、audio、materials、output-template)。严格按 SKILL.md 的流程工作。++任务:拆解视频 videos/{V}.mp4。它是从微信公众号文章下载的转码版(30fps、二次压缩),你不知道它是怎么做的,需要你判断。++1. 环境没装好就先按 SKILL.md 第 0 节安装(需要 ffmpeg;可以直接用 `python3 -m rea_video.cli` 代替 `rea-video`)。+2. 运行 decompose,输出到 runs/{V}/。VLM 配置可用时(例如 `--env-file ~/code/github/capsule-cinema/.env`)按 SKILL.md 建议加 `--vlm`;不可用就不开,并在报告里写明。+3. 按 SKILL.md 自己复核。先确认你能不能看图:能看就看 storyboard.jpg、shots/、低置信镜头;看不了就遵守 SKILL.md「看不了图时的规则」。+4. 按 references/output-template.md 的结构写 runs/{V}/AGENT_REPORT.md(中文),必须包含:+ - 一句话结论:制作方式(实拍 / AI 视频 / 数字人 / 3D / 代码渲染 / 录屏截图 / 静态图推拉 / 静帧)及各占比+ - 分镜表、真实素材、声音(人声 / BGM / 音效及来源)、不确定点+ - 最后一行固定格式:`FINAL: <主要制作方式> | <置信度 0-1> | <能否看图: yes/no> | <VLM 是否生效: yes/partial/no>`(以 `rea-video summary` 的 `VLM:` 一行为准,请求了但调用失败算 no)+5. 不要修改代码,不要上网搜索这条视频,不要读当前目录以外的文件。diff --git a/eval/agent_test/README.md b/eval/agent_test/README.mdnew file mode 100644index 0000000..62efe4e--- /dev/null+++ b/eval/agent_test/README.md@@ -0,0 +1,85 @@+# agent 盲测:用 rea-video 拆解文章视频(给 Claude Code 编排用)++目的:检验"另一个 agent 只靠本仓库的 Skill 和工具,能不能把视频怎么做的拆对"。上一轮用的是 dsh(DeepSeek V4.1 Flash),这一轮可以测 zcode 或其他 agent。++被测 agent 只拿到 `JOB.md`,看不到答案;Claude Code 负责准备环境、逐条调用、收集结果、按本文评分。++## 0. 准备(Claude Code 执行)++```bash+REPO=~/code/github/rea-video+BLIND=/tmp/rea-video-blind # 盲测副本:不含 eval/、out/、.cache/(里面有答案)+cd $REPO+pip install -e ".[ocr]" # 需要 ffmpeg;首次分离人声会从 GitHub 下载约 67 MB 模型++# 0.1 确定性回归(不需要 agent)+export CAPSULE_CINEMA_ROOT=~/code/github/capsule-cinema+rea-video eval eval/labels.yaml -o out/eval_main # 期望 duration_weighted_accuracy ≈ 0.999+rea-video eval eval/holdout.yaml -o out/eval_hold # ≈ 0.996+rea-video eval eval/holdout2.yaml -o out/eval_hold2 # ≈ 0.998+rea-video eval eval/articles.yaml -o out/eval_articles # ≈ 0.886(逐条见下表"工具 v0.3"列)+python3 -m pytest -q # 26 passed++# 0.2 盲测副本+rm -rf $BLIND && mkdir -p $BLIND/videos $BLIND/runs+rsync -a --exclude eval --exclude out --exclude .cache --exclude .git $REPO/ $BLIND/+cp $REPO/eval/media/articles/v*.mp4 $BLIND/videos/+```++视频:`eval/media/articles/v01.mp4 … v13.mp4`,编号对照在同目录 `mapping.tsv`(不要给被测 agent)。如果文件丢了,从两篇文章重新下载:+mp.weixin.qq.com/s/s7i_fQmwWo9SbRoV-KDZ9g(a1)、mp.weixin.qq.com/s/aXhPx0eQu9ngYxuyvsFE4Q(a2)。++## 1. 调用被测 agent(每条视频一个新会话)++在 `$BLIND` 目录里启动 agent,把 `JOB.md` 的 `{V}` 换成编号作为任务,例如:++```bash+cd $BLIND+for V in v01 v02 v03 v04 v05 v06 v07 v08 v09 v10 v11 v12 v13; do+ sed "s/{V}/$V/g" $REPO/eval/agent_test/JOB.md > runs/JOB_$V.md+ # 换成 zcode 的非交互调用方式,例如:zcode -p "$(cat runs/JOB_$V.md)" > runs/$V.log 2>&1+done+```++记录每条:耗时、是否成功写出 `runs/vXX/AGENT_REPORT.md`、日志里有没有读 `$BLIND` 以外的文件或上网。+建议 v11、v09、v03、v04 先跑(最能区分好坏),再跑其余。++## 2. 真值与评分++只评有真值的 11 条(v02、v06 真值不确定,只看报告是否把不确定说清楚)。每条主分 0–2:++| 编号 | 文章说明 / 人工看画面 | 2 分(全对) | 1 分(部分对) | 0 分 | 工具 v0.3 | dsh(工具 v0.2) |+|---|---|---|---|---|---|---|+| v01 | a1:OiiOii 复刻成片(视频模型生成) | AI 视频 | — | 其他 | AI ✓ | 2 |+| v02 | a1:原始参考片(铅笔上的定格小人) | 不评分:写明"定格动画还是 AI 待确认"算好 | | | AI | — |+| v03 | a1:直接用视频模型复刻 | 全片 AI(含 AI 生成的铅笔素描过渡、结尾镜头拉远露出桌面) | AI 为主但混进"代码卡/静态图推拉" | 其他 | AI ✓ | 0(判出代码白底卡 + 静态图推拉) |+| v04 | a1:别人的产品推广片,黑底 + 玻璃质感 3D 星星/铬金属 + 文字动效 | 3D 元素 + 代码/MG 文字 | 只说出其一 | 说成录屏/实拍 | 3D 65% + AI 35%(1 分) | 0("无 3D",判成界面 + 录屏) |+| v05 | a1:OiiOii「视频模型 + Coding」成片:模型做立体装饰,代码做文字/按钮/转场,界面是真实产品截图 | 三者都说到 | 说到其中两样 | 一样都没对 | 3D 63% + 代码 22% + AI 12%(1 分) | 1 |+| v06 | a1:吊扇视角换装原片 | 不评分:写明"实拍还是 AI 待确认"算好 | | | AI | — |+| v07 | a1:OiiOii 换成男生版 | AI 视频 | — | 其他 | AI ✓ | 2 |+| v08 | a2:「广告原始 / 广告复刻后」左右拼屏,两边都是 UI 动效 | 拼屏 + 代码/UI 动效 | 只说出拼屏或只说出 UI 动效 | 其他 | 代码 80% + 3D 20%(1 分) | 1(说成录屏) |+| v09 | a2:Google Gemini 发布片原片,2D UI 动效 | 代码/UI 动效,无 3D | 代码为主但带 >15% 3D | 其他 | 代码 81% + 3D 19%(1 分) | 2 |+| v10 | a2:OiiOii 第一版「视频生成 + Coding」 | 代码 UI 动效为主 | 代码为主但带 >15% 3D | 其他 | 代码 92%(2 分) | 2 |+| v11 | a2:TikTok 带货原片,手机实拍(真实厨房、真手、男声口播) | 实拍 | "实拍还是 AI 待确认" | AI | 实拍(2 分) | 0(AI 100% 并调高置信度) |+| v12 | a2:OiiOii 榨汁杯复刻(文件带 AIGC 隐式标识) | AI 视频 | — | 其他 | AI ✓ | 2 |+| v13 | a2:变装换人物(QQ 飞车风,游戏 UI 是画进画面的) | AI 视频 | — | 其他 | AI ✓ | 2 |++满分 22。参考线:工具 v0.3 不经 agent 复核 18;dsh 上一轮 14(当时工具是 v0.2,v11 无论如何拿不到分)。++另外记录这几项(不计入主分,但写进结论):++- **看不了图时有没有乱改**:agent 自己说看不了图、又推翻了工具的制作方式判断,每次记一笔。上一轮 dsh 有 2 次推翻错误。+- **关键细节**:v08 认出左右对照拼屏;v12 引用 AIGC 标识;v13 指出游戏 UI 是画面内容不是叠加层;v05 把界面截图列为真实素材;v11 指出平台转码导致噪声证据失效。+- **声音**:只看有没有把人声 / BGM / 音效说清楚、来源是否标了"待确认";这批视频没有声音真值,不打分。+- **成本与稳定性**:每条耗时、失败重试次数、token 用量(如果能拿到)。++## 3. 结果写法++在 `$REPO/out/agent_eval/<agent 名>/RESULT.md` 写:++1. 总表:编号 | agent 结论(FINAL 行)| 得分 | 工具 v0.3 | 备注+2. 总分、与工具 v0.3 / dsh 的对比+3. 推翻工具的每一次:对还是错、理由是什么+4. 发现的 Skill 或工具问题(可复现的写出视频编号和镜头时间)++把 `runs/` 下的报告一并拷过去:`cp -r $BLIND/runs $REPO/out/agent_eval/<agent 名>/`。diff --git a/eval/articles.yaml b/eval/articles.yamlnew file mode 100644index 0000000..2d5a701--- /dev/null+++ b/eval/articles.yaml@@ -0,0 +1,37 @@+# 两篇 OiiOii 公众号文章里的视频(微信转码版:30fps、二次压缩、元数据带 "Tencent CAPD MTS")+# 来源:mp.weixin.qq.com/s/s7i_fQmwWo9SbRoV-KDZ9g(a1)、mp.weixin.qq.com/s/aXhPx0eQu9ngYxuyvsFE4Q(a2)+# 视频文件不进仓库:放在 eval/media/articles/v01.mp4 … v13.mp4(编号对照见同目录 mapping.tsv)+# 真值 = 文章作者对制作方式的说明 + 人工看画面;v02、v05、v06 真值不确定,不列入+# 注意:v0.3 的转码/3D 规则是看过这批视频后加的,属于开发集,不是留出集+videos:+ - id: art_v01_oiioii_remake # a1 复刻成片:视频模型 + Harness+ path: eval/media/articles/v01.mp4+ label: ai_video+ - id: art_v03_pure_model_remake # a1 直接用视频模型复刻(含 AI 生成的铅笔素描过渡、结尾拉远)+ path: eval/media/articles/v03.mp4+ label: ai_video+ - id: art_v04_promo_original # a1 别人的产品推广片:玻璃质感 3D 元素 + 文字动效+ path: eval/media/articles/v04.mp4+ label: [cg_3d, code_render]+ - id: art_v07_male_swap # a1 换成男生版+ path: eval/media/articles/v07.mp4+ label: ai_video+ - id: art_v08_side_by_side # a2 「广告原始 / 广告复刻后」左右拼屏,两边都是 UI 动效+ path: eval/media/articles/v08.mp4+ label: [code_render, screen_capture]+ - id: art_v09_gemini_original # a2 Google Gemini 发布片:2D UI 动效+ path: eval/media/articles/v09.mp4+ label: [code_render, screen_capture]+ - id: art_v10_oiioii_gen_coding # a2 OiiOii 第一版「视频生成 + Coding」:代码 UI 动效为主+ path: eval/media/articles/v10.mp4+ label: [code_render, screen_capture, still_motion]+ - id: art_v11_tiktok_original # a2 TikTok 带货原片:手机实拍(真实厨房、真手、男声口播)+ path: eval/media/articles/v11.mp4+ label: live_action+ real_material: true+ - id: art_v12_juicer_remake # a2 OiiOii 榨汁杯复刻(带 AIGC 隐式标识)+ path: eval/media/articles/v12.mp4+ label: ai_video+ - id: art_v13_outfit_swap # a2 变装换人物(QQ 飞车风,游戏 UI 是画进画面的)+ path: eval/media/articles/v13.mp4+ label: ai_videodiff --git a/eval/audio_mv.yaml b/eval/audio_mv.yamlnew file mode 100644index 0000000..b5371fc--- /dev/null+++ b/eval/audio_mv.yaml@@ -0,0 +1,6 @@+# 音乐来源(AI 生成 vs 现成)专项:只评音频,不评画面+# 注意:vocal_style 的阈值是看过 qing_hiphop_mv 后定的,属于开发集,不是留出集+videos:+ - id: qing_hiphop_mv+ audio: {music_source: ai_generated, voice: true, music: true} # AI 说唱 MV:Suno chirp-hawk v6 歌曲「和血吞」+ path: ${CAPSULE}/output/qing_hiphop_zeng_guofan/out/qing_hiphop_full.mp4diff --git a/eval/birdnest_plush_sfx.json b/eval/birdnest_plush_sfx.jsonnew file mode 100644index 0000000..367cea0--- /dev/null+++ b/eval/birdnest_plush_sfx.json@@ -0,0 +1 @@+[[0.0, -31, 0.06], [0.286, -31, 0.06], [0.571, -31, 0.06], [0.857, -31, 0.06], [1.142, -31, 0.06], [1.428, -31, 0.06], [1.714, -31, 0.06], [0.186, -31, 0.06], [0.471, -31, 0.06], [0.757, -31, 0.06], [1.042, -31, 0.06], [1.328, -31, 0.06], [1.614, -31, 0.06], [1.899, -31, 0.06], [0.086, -31, 0.06], [0.371, -31, 0.06], [0.657, -31, 0.06], [0.942, -31, 0.06], [1.228, -31, 0.06], [1.514, -31, 0.06], [1.799, -31, 0.06], [0.02, -22, 0.07], [0.3, -34, 1.958], [2.98, -24, 0.38], [3.08, -27, 0.865], [4.952, -32, 0.9], [5.402, -20, 0.07], [5.502, -22, 0.975], [6.432, -26, 0.35], [6.732, -27, 0.6], [6.632, -25, 0.92], [8.181, -22, 0.07], [8.431, -28, 0.6], [8.681, -28, 0.6], [10.021, -26, 0.7], [10.021, -32, 1.0], [13.431, -22, 0.16], [13.851, -22, 0.16], [14.271, -22, 0.16], [14.691, -22, 0.16], [15.365, -24, 0.7], [18.205, -18, 0.16], [18.255, -24, 0.4], [19.789, -24, 0.5], [20.389, -20, 0.07], [22.119, -30, 0.8], [22.619, -26, 0.6], [22.719, -27, 0.865], [23.756, -22, 0.38], [24.006, -28, 0.8], [25.046, -30, 0.7], [25.446, -24, 0.9], [26.517, -30, 0.4], [27.717, -30, 0.4], [28.481, -26, 0.12], [28.571, -26, 0.12], [28.661, -26, 0.12], [28.751, -26, 0.12], [28.841, -26, 0.12], [28.931, -26, 0.12], [29.021, -26, 0.12], [29.111, -26, 0.12], [29.201, -26, 0.12], [29.291, -26, 0.12], [28.811, -20, 0.4], [28.911, -25, 0.25], [29.833, -27, 1.8], [32.489, -24, 0.12], [32.599, -24, 0.12], [32.709, -24, 0.12], [32.819, -24, 0.12], [32.929, -24, 0.12], [33.039, -24, 0.12], [32.829, -30, 0.8], [32.929, -25, 0.92], [35.233, -18, 0.16], [35.363, -26, 0.25], [35.533, -18, 0.16], [35.663, -26, 0.25], [36.653, -20, 0.07], [37.003, -24, 0.5], [36.833, -20, 0.07], [37.183, -24, 0.5], [36.903, -26, 0.92], [37.667, -29, 1.887], [39.417, -24, 0.55], [39.667, -24, 0.5], [40.198, -24, 0.38], [40.398, -24, 0.38], [42.876, -22, 0.38], [43.126, -22, 0.38], [43.776, -28, 0.6], [43.936, -30, 0.8], [44.336, -24, 0.9], [44.386, -25, 0.92], [46.97, -18, 0.07], [47.42, -26, 0.4], [48.18, -26, 0.6], [48.23, -27, 0.6], [48.93, -22, 0.13], [49.38, -24, 0.9], [49.23, -25, 0.07], [50.408, -28, 0.35], [50.808, -32, 0.6], [51.888, -30, 0.7], [52.288, -23, 0.9], [52.338, -22, 1.03], [54.055, -16, 1.4], [54.105, -20, 0.07], [54.155, -22, 1.03], [54.455, -26, 0.6], [54.705, -26, 0.6], [57.162, -16, 0.3], [57.212, -26, 0.42], [59.862, -23, 0.38], [60.402, -23, 0.975], [60.452, -26, 0.6], [61.943, -25, 0.38], [62.163, -25, 0.38], [62.383, -25, 0.38], [63.963, -32, 1.2], [64.263, -28, 0.6]]\ No newline at end of filediff --git a/eval/holdout.yaml b/eval/holdout.yamlnew file mode 100644index 0000000..052db74--- /dev/null+++ b/eval/holdout.yaml@@ -0,0 +1,40 @@+# 留出集:调参时未使用,用来检验规则是否过拟合(标签为人工目测 + capsule-cinema 生产记录)+videos:+ - id: monkey_wine_code_v1+ real_material: false+ path: ${CAPSULE}/output/monkey_wine_v2/monkey_wine_code_v1.mp4+ label: code_render # 扁平矢量风代码动画+ - id: birdnest_plush+ audio: {music_source: ai_generated, voice: true, music: true, sfx: true, bpm: 110.15, key: "D major"}+ real_material: false+ path: ${CAPSULE}/output/birdnest_plush/final.mp4+ label: cg_3d # plush_diorama_science / Blender+ - id: h3_realcat+ real_material: false+ path: ${CAPSULE}/output/dual_role_social_account_doctor_20260930/h3/realcat_s1_seed9300101.mp4+ label: ai_video+ - id: douyin_live_breakfast+ audio: {voice: true}+ real_material: true+ path: ${CAPSULE}/output/plot_mining/videos/7690489550460562426.mp4+ label: live_action+ - id: douyin_capybara_a+ real_material: false+ path: ${CAPSULE}/output/plot_mining/videos/7644950675957597864.mp4+ label: [ai_video, cg_3d]+ - id: douyin_capybara_b+ real_material: false+ path: ${CAPSULE}/output/plot_mining/videos/7678263903595959921.mp4+ label: [ai_video, cg_3d]+ - id: douyin_capybara_c+ real_material: false+ path: ${CAPSULE}/output/plot_mining/videos/7688245085297572258.mp4+ label: [ai_video, cg_3d]+ - id: lulukong_a+ real_material: false+ path: ${CAPSULE}/output/account_fetch/噜噜控_20261028_064018/media/14957471328589846909.mp4+ label: [ai_video, cg_3d]+ - id: lulukong_b+ real_material: false+ path: ${CAPSULE}/output/account_fetch/噜噜控_20261028_064018/media/15003857097291603011.mp4+ label: [ai_video, cg_3d]diff --git a/eval/holdout2.yaml b/eval/holdout2.yamlnew file mode 100644index 0000000..6c8cc2d--- /dev/null+++ b/eval/holdout2.yaml@@ -0,0 +1,39 @@+# 第二留出集:所有规则调整完成后才第一次运行(无任何针对性调参)+videos:+ - id: monkey_wine_code_v2+ real_material: false+ path: ${CAPSULE}/output/monkey_wine_v2/monkey_wine_code_v2.mp4+ label: code_render+ - id: monkey_wine_code_v3+ real_material: false+ path: ${CAPSULE}/output/monkey_wine_v2/monkey_wine_code_v3.mp4+ label: code_render+ - id: dual_role_realcat+ real_material: [[0.0, 1.375, true], [1.375, 3.917, false], [3.917, 5.875, true], [5.875, 8.042, false], [8.042, 11.0, true], [11.0, 12.0, false], [12.0, 13.958, true], [13.958, 16.917, false], [16.917, 19.875, true]]+ path: ${CAPSULE}/output/dual_role_social_account_doctor_20260930/release/social_account_doctor_realcat_v1.mp4+ segments:+ - [0.0, 1.375, [screen_capture, code_render, static_hold]]+ - [1.375, 3.917, ai_video]+ - [3.917, 5.875, [screen_capture, code_render, static_hold]]+ - [5.875, 8.042, ai_video]+ - [8.042, 11.0, [screen_capture, code_render, static_hold]]+ - [11.0, 12.0, ai_video]+ - [12.0, 13.958, [screen_capture, code_render, static_hold]]+ - [13.958, 16.917, ai_video]+ - [16.917, 19.875, [screen_capture, code_render, static_hold]]+ - id: agi_kage+ real_material: true+ path: ${CAPSULE}/output/agi_zhidao/20260915_batch/kage/release/video.mp4+ label: [code_render, screen_capture]+ - id: douyin_capybara_d+ real_material: false+ path: ${CAPSULE}/output/plot_mining/videos/7699786681432737977.mp4+ label: [ai_video, cg_3d]+ - id: douyin_capybara_e+ real_material: false+ path: ${CAPSULE}/output/plot_mining/videos/7700202069185855866.mp4+ label: [ai_video, cg_3d]+ - id: lulukong_c+ real_material: false+ path: ${CAPSULE}/output/account_fetch/噜噜控_20261028_064018/media/15037922538409237557.mp4+ label: [ai_video, cg_3d]diff --git a/eval/labels.yaml b/eval/labels.yamlnew file mode 100644index 0000000..7777cce--- /dev/null+++ b/eval/labels.yaml@@ -0,0 +1,110 @@+# rea-video 评测集:真实制作方式已知的视频(大部分来自 capsule-cinema 的生产记录)+# label 可以是字符串或可接受标签列表;segments: [[start, end, label|list], ...] 覆盖整片+# real_material: 是否引入用户真实素材(实拍/照片/截图/录屏),true/false 或 [[start, end, true|false], ...]+# root 变量:${CAPSULE} = capsule-cinema 仓库路径(环境变量 CAPSULE_CINEMA_ROOT,默认 ~/code/github/capsule-cinema)+videos:+ - id: monkey_wine_v1+ real_material: false+ path: ${CAPSULE}/output/monkey_wine/monkey_wine_final.mp4+ label: static_hold # AI 生成的插画静帧逐张停留+ image_source: ai_image+ cuts: [4.80, 10.12, 15.96, 20.72, 24.88, 29.04, 33.28, 37.80, 43.76]+ source: capsule-cinema 产出,10 张 AI 图按旁白时长拼接++ - id: monkey_wine_v3+ audio: {music_source: ai_generated, voice: true, music: true, sfx: false} # tts.py + bgm.py(Suno 生成的 BGM),无 sfx+ real_material: false+ path: ${CAPSULE}/output/monkey_wine_v3/release/monkey_wine_v3.mp4+ label: ai_video # MiniMax H3 首尾帧生成的"3D 手办"风格 AI 视频 + 代码字幕+ cuts: [7.071, 12.621, 17.307, 23.397, 28.485, 32.493, 38.475, 45.219, 50.379, 57.621, 60.507, 69.087, 77.883, 80.085]+ cut_tolerance: 0.3 # 0.25s xfade 交叉溶解+ source: capsule-cinema work/timeline.json(workflow minimax_h3_lightx2v_v5)++ - id: monkey_wine_v3_clip+ real_material: false+ path: ${CAPSULE}/output/monkey_wine_v3/clips/s01_flf.mp4+ label: ai_video+ source: MiniMax H3 原始输出++ - id: h3_human_clip+ real_material: false+ path: ${CAPSULE}/output/dual_role_social_account_doctor_20260930/h3/human_s1_seed9300101.mp4+ label: ai_video+ source: MiniMax H3 原始输出(写实人物)++ - id: autodl_h3+ real_material: false+ path: ${CAPSULE}/output/channel-tests/autodl-h3.mp4+ label: ai_video+ source: H3 渠道测试输出++ - id: dual_role_human+ real_material: [[0.000, 1.375, true], [1.375, 3.875, false], [3.875, 5.833, true], [5.833, 7.542, false], [7.542, 10.542, true], [10.542, 11.542, false], [11.542, 13.458, true], [13.458, 16.125, false], [16.125, 19.100, true]]+ path: ${CAPSULE}/output/dual_role_social_account_doctor_20260930/release/social_account_doctor_human_v1.mp4+ # human_timeline.json:face=H3 AI 人物;verdict/covers/top9/fixes/github=截图面板+ segments:+ - [0.000, 1.375, [screen_capture, code_render, static_hold]]+ - [1.375, 3.875, ai_video]+ - [3.875, 5.833, [screen_capture, code_render, static_hold]]+ - [5.833, 7.542, ai_video]+ - [7.542, 10.542, [screen_capture, code_render, static_hold]]+ - [10.542, 11.542, ai_video]+ - [11.542, 13.458, [screen_capture, code_render, static_hold]]+ - [13.458, 16.125, ai_video]+ - [16.125, 19.100, [ai_video, screen_capture, code_render, static_hold]]+ source: capsule-cinema dual_role 生产时间线++ - id: github_recording+ real_material: true+ path: ${CAPSULE}/output/capability_test/github_recording.mp4+ label: screen_capture+ source: 真实浏览器滚动录屏++ - id: salted_egg_plush+ audio: {music_source: ai_generated, voice: true, music: true, sfx: true, bpm: 110.15, key: "D major"} # bgm_fit.json(Suno 曲 "Monkey Wine Pop")+ cues.py+ real_material: false+ path: ${CAPSULE}/output/salted_egg_plush/final.mp4+ label: cg_3d # plush_diorama_science:Blender 本地渲染 + 代码字幕+ source: capsule-cinema plush_diorama_science 配方++ - id: murphy_shape+ real_material: false+ path: ${CAPSULE}/output/murphy_shape/build/murphy_shape_B.mp4+ label: [code_render, cg_3d] # 代码渲染的暗色 MG(含 3D 骰子)+ source: capsule-cinema murphys_law_shape 配方++ - id: mediank_pure_data+ audio: {music_source: existing_library, voice: false, music: true, sfx: true} # 曲库 BGM(manten diloty)+ mixkit 键盘音效,无旁白+ real_material: true+ path: ${CAPSULE}/artifacts/video_runs/production/mediank_pure_data_20261004/release/20261004_verified_skills_v1/public/video.mp4+ label: code_render+ source: capsule-cinema mediank 代码渲染++ - id: agi_fly+ real_material: true+ path: ${CAPSULE}/output/agi_zhidao/20260916_fly/release/video.mp4+ label: [code_render, screen_capture]+ source: repo_showcase 代码模板 + 网页截图++ - id: civ_atlas+ path: ${CAPSULE}/output/civ_atlas_flow_25s/release/v1/public/civ_atlas_flow_25s.mp4+ label: [code_render, screen_capture]+ source: repo_signal_grid 代码渲染 + 截图++ - id: douyin_ai_capybara_city+ real_material: false+ path: ${CAPSULE}/output/plot_mining/videos/7655483312324068342.mp4+ label: ai_video+ source: 抖音下载,文件带 AIGC 隐式标识 Label=1++ - id: douyin_live_street+ real_material: true+ path: ${CAPSULE}/output/plot_mining/videos/7691668930338992100.mp4+ label: live_action+ source: 抖音下载,人工判断为手机实拍++ - id: douyin_capybara_home+ real_material: false+ path: ${CAPSULE}/output/plot_mining/videos/7699437052256889275.mp4+ label: [ai_video, cg_3d]+ source: 抖音下载,人工判断为 AI 生成(无标识,存疑)diff --git a/eval/salted_egg_plush_sfx.json b/eval/salted_egg_plush_sfx.jsonnew file mode 100644index 0000000..74ed2ef--- /dev/null+++ b/eval/salted_egg_plush_sfx.json@@ -0,0 +1 @@+[[0.0, -31, 0.06], [0.286, -31, 0.06], [0.571, -31, 0.06], [0.857, -31, 0.06], [1.142, -31, 0.06], [1.428, -31, 0.06], [0.186, -31, 0.06], [0.471, -31, 0.06], [0.757, -31, 0.06], [1.042, -31, 0.06], [1.328, -31, 0.06], [0.086, -31, 0.06], [0.371, -31, 0.06], [0.657, -31, 0.06], [0.942, -31, 0.06], [1.228, -31, 0.06], [0.02, -22, 0.07], [2.77, -22, 0.25], [2.87, -18, 0.15], [2.92, -26, 0.865], [3.73, -31, 0.7], [4.13, -20, 0.07], [4.23, -23, 0.92], [6.511, -28, 0.4], [6.711, -28, 0.6], [7.631, -24, 0.9], [7.731, -27, 0.865], [9.062, -24, 0.38], [10.492, -23, 0.16], [11.458, -29, 2.258], [11.858, -32, 0.8], [13.917, -26, 0.12], [14.197, -26, 0.12], [14.477, -26, 0.12], [14.757, -26, 0.12], [15.36, -25, 0.9], [17.187, -27, 0.5], [17.337, -24, 0.16], [17.537, -24, 0.16], [17.737, -24, 0.16], [19.667, -31, 0.5], [20.307, -27, 0.42], [20.407, -26, 0.07], [20.727, -26, 0.07], [21.047, -26, 0.07], [22.392, -24, 0.16], [22.672, -24, 0.16], [22.952, -24, 0.16], [23.582, -23, 0.16], [23.682, -27, 0.45], [25.342, -21, 0.13], [25.642, -27, 0.865], [27.239, -26, 0.12], [27.359, -26, 0.12], [27.479, -26, 0.12], [27.599, -26, 0.12], [28.359, -25, 0.38], [28.409, -26, 0.55], [29.879, -27, 0.25], [30.279, -28, 0.25], [30.689, -26, 0.7], [33.239, -19, 0.15], [33.289, -24, 0.25], [34.0, -27, 0.12], [34.12, -27, 0.12], [34.24, -27, 0.12], [34.36, -27, 0.12], [34.48, -27, 0.12], [34.639, -28, 1.5], [35.709, -29, 0.42], [36.909, -22, 0.45], [37.359, -25, 0.12], [37.479, -25, 0.12], [37.599, -25, 0.12], [37.719, -25, 0.12], [39.62, -24, 0.07], [39.71, -24, 0.07], [39.8, -24, 0.07], [40.02, -27, 0.865], [40.61, -26, 0.55], [41.21, -23, 0.16], [41.603, -23, 0.38], [41.938, -24, 0.8], [44.238, -22, 0.4], [44.538, -24, 0.16], [44.838, -25, 0.16], [46.4, -28, 1.65], [47.805, -31, 0.7], [48.205, -24, 0.9], [48.305, -26, 0.92], [50.368, -22, 0.25], [50.448, -17, 0.15], [50.508, -22, 0.07], [51.358, -30, 0.8], [51.458, -25, 0.9], [52.998, -24, 0.16], [55.335, -16, 1.4], [55.385, -20, 0.07], [55.435, -22, 1.03], [57.708, -24, 0.1], [59.661, -16, 0.3], [59.711, -25, 0.42], [62.652, -20, 0.15], [62.952, -20, 0.15], [63.252, -20, 0.15], [62.852, -23, 0.9], [63.212, -23, 0.9], [63.262, -26, 0.92], [63.862, -27, 0.6], [64.162, -28, 0.6]]\ No newline at end of filediff --git a/integrations/capsule_cinema/README.md b/integrations/capsule_cinema/README.mdnew file mode 100644index 0000000..82c4cb5--- /dev/null+++ b/integrations/capsule_cinema/README.md@@ -0,0 +1,26 @@+# capsule-cinema 对接++这两个脚本用 **capsule-cinema 自己的 Python 环境**运行(它们会 import capsule-cinema 的 `lib/` 和 `scripts/`,并读取它的 `.env`)。rea-video 本身只依赖 numpy/opencv/pillow/pyyaml。++```bash+CC=~/code/github/capsule-cinema # capsule-cinema 仓库+PY=$CC/.venv/bin/python # 或 python3.12++# 1) 拆解(建议开 VLM,复用 capsule-cinema 的 Gemini 配置)+rea-video --env-file $CC/.env decompose ref.mp4 -o out/ref --vlm++# 2a) 生成胶囊草稿(不改 capsule-cinema 代码;通过 tool_factory 注入 rea-video 的拆解结果)+$PY integrations/capsule_cinema/to_capsule.py --breakdown out/ref/breakdown.json \+ --capsule-root $CC --capsule-name my_ref_remake # 加 --write-capsule 才落盘到 capsules/++# 2b) 复刻 AI 类镜头:生成任务 → 调 capsule-cinema 生成 → 按原时间线拼回并出对比片+rea-video remake-plan out/ref/breakdown.json --capsule-root $CC --engine seedance2.0+$PY integrations/capsule_cinema/run_remake.py --jobs out/ref/remake/jobs.json --dry-run # 先看任务+$PY integrations/capsule_cinema/run_remake.py --jobs out/ref/remake/jobs.json # 真正调用(会产生费用)+rea-video assemble out/ref/breakdown.json out/ref/remake/results.json+```++- AI 视频 / 3D / 实拍 / 数字人镜头:默认用原镜头的**首尾帧 + VLM 提示词**做 `first_last_frame` 生成(`--mode image_to_video` 只用首帧)。+- 静态图推拉、静帧:不调模型,`assemble` 用测得的缩放/平移参数在本地重建。+- 代码渲染、录屏镜头:默认保留原片(`keep_original`),重建请按报告中的文字轨/版式用 Remotion 实现。+- 只复刻部分镜头:`run_remake.py --only 2,5`。diff --git a/integrations/capsule_cinema/run_remake.py b/integrations/capsule_cinema/run_remake.pynew file mode 100644index 0000000..1e36781--- /dev/null+++ b/integrations/capsule_cinema/run_remake.py@@ -0,0 +1,80 @@+#!/usr/bin/env python3+"""Execute rea-video remake jobs with capsule-cinema's video generation tools.++Runs inside capsule-cinema's Python environment (its .env provides API keys).+Writes results.json next to jobs.json; rea-video `assemble` consumes it."""+from __future__ import annotations++import argparse+import json+import sys+import time+from pathlib import Path+++def _video_path(res) -> str | None:+ """Find the generated file in the various result shapes capsule-cinema tools return."""+ if isinstance(res, str):+ return res if res.lower().endswith((".mp4", ".mov", ".webm")) and Path(res).is_file() else None+ if not isinstance(res, dict):+ return None+ for key in ("output_path", "video_path", "local_path", "path", "file_path"):+ v = res.get(key)+ if isinstance(v, str) and Path(v).is_file():+ return v+ for key in ("result", "data", "video"):+ v = _video_path(res.get(key)) if res.get(key) is not None else None+ if v:+ return v+ return None+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("--jobs", required=True)+ ap.add_argument("--only", default="", help="comma-separated shot indices")+ ap.add_argument("--dry-run", action="store_true")+ args = ap.parse_args()++ jobs_path = Path(args.jobs).expanduser().resolve()+ spec = json.loads(jobs_path.read_text(encoding="utf-8"))+ only = {int(x) for x in args.only.split(",") if x.strip()}+ results_path = jobs_path.with_name("results.json")+ results = json.loads(results_path.read_text(encoding="utf-8")) if results_path.is_file() else {"results": {}}++ todo = [j for j in spec["jobs"] if j["executor"] == "capsule_cinema" and (not only or j["shot"] in only)]+ print(f"{len(todo)} generation job(s); run dir {spec['run_dir']}")+ if args.dry_run:+ for j in todo:+ p = dict(j["params"])+ p["prompt"] = p["prompt"][:120] + ("…" if len(p["prompt"]) > 120 else "")+ print(json.dumps({"shot": j["shot"], "label": j["label"], **p}, ensure_ascii=False))+ return++ root = Path(spec["capsule_root"]).expanduser().resolve()+ sys.path.insert(0, str(root / "lib"))+ sys.path.insert(0, str(root / "scripts"))+ from env_loader import load_video_agent_env # noqa: E402++ load_video_agent_env(root)+ from custom_tools.video_generation.video_generation_tool import UniversalVideoGenerationTool # noqa: E402++ tool = UniversalVideoGenerationTool()+ for j in todo:+ Path(j["params"]["output_dir"]).mkdir(parents=True, exist_ok=True)+ t0 = time.time()+ print(f"shot {j['shot']}: {j['params']['generation_type']} via {j['params']['engine']} ...", flush=True)+ try:+ res = tool._run(**j["params"])+ except Exception as exc: # keep going, record the failure+ res = {"error": str(exc)}+ video = _video_path(res)+ results["results"][str(j["shot"])] = {"id": j["id"], "video": video, "raw": res if not video else None,+ "seconds": round(time.time() - t0, 1), "trim_to": j["trim_to"]}+ results_path.write_text(json.dumps(results, ensure_ascii=False, indent=2, default=str), encoding="utf-8")+ print(f" -> {video or res}", flush=True)+ print(f"results: {results_path}")+++if __name__ == "__main__":+ main()diff --git a/integrations/capsule_cinema/to_capsule.py b/integrations/capsule_cinema/to_capsule.pynew file mode 100644index 0000000..9b3a120--- /dev/null+++ b/integrations/capsule_cinema/to_capsule.py@@ -0,0 +1,59 @@+#!/usr/bin/env python3+"""Create a capsule-cinema capsule draft from a rea-video breakdown.++Runs inside capsule-cinema's Python environment. Uses capsule-cinema's own+run_video_to_capsule() and injects rea-video's analysis through its tool_factory hook,+so no capsule-cinema code is modified."""+from __future__ import annotations++import argparse+import json+import os+import sys+from pathlib import Path++REA_ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(REA_ROOT))+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("--breakdown", required=True)+ ap.add_argument("--capsule-root", default=os.getenv("CAPSULE_CINEMA_ROOT", str(Path.home() / "code/github/capsule-cinema")))+ ap.add_argument("--capsule-name", default="")+ ap.add_argument("--capsule-display-name", default="")+ ap.add_argument("--write-capsule", action="store_true")+ ap.add_argument("--overwrite-capsule", action="store_true")+ args = ap.parse_args()++ from rea_video.integrations.capsule_cinema import export_capsule_analysis+ from rea_video.util import read_json++ bpath = Path(args.breakdown).expanduser().resolve()+ b = read_json(bpath)+ analysis_path = export_capsule_analysis(b, bpath.with_name("capsule_analysis.json"))+ analysis = json.loads(analysis_path.read_text(encoding="utf-8"))++ root = Path(args.capsule_root).expanduser().resolve()+ sys.path.insert(0, str(root / "scripts"))+ sys.path.insert(0, str(root / "lib"))+ import analyze_video_to_capsule as a2c # noqa: E402 (loads capsule-cinema env on import)++ class ReaVideoAnalyzer:+ def _run(self, video_path: str, prompt: str = "", analysis_focus: str = "content"):+ return analysis++ result = a2c.run_video_to_capsule(+ source_video_path=b["source"]["path"],+ video_analysis_tool="ReaVideoAnalyzer",+ capsule_name=args.capsule_name,+ capsule_display_name=args.capsule_display_name,+ write_capsule=args.write_capsule,+ overwrite_capsule=args.overwrite_capsule,+ tool_factory=lambda _name: ReaVideoAnalyzer(),+ )+ print(json.dumps(result, ensure_ascii=False, indent=2))+++if __name__ == "__main__":+ main()diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..7cc9f87--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,31 @@+[build-system]+requires = ["setuptools>=64"]+build-backend = "setuptools.build_meta"++[project]+name = "rea-video"+version = "0.1.0"+description = "Reverse engineer any video: shot-level production-method forensics (live action / AI video / code render / mixed) and remake planning."+readme = "README.md"+requires-python = ">=3.10"+license = { text = "MIT" }+dependencies = [+ "numpy>=1.24",+ "opencv-python-headless>=4.8",+ "Pillow>=9.0",+ "PyYAML>=6.0",+ "onnxruntime>=1.16", # 人声/配乐分离(UVR MDX-Net,首次运行自动下载约 67 MB 模型)+]++[project.optional-dependencies]+ocr = ["rapidocr-onnxruntime>=1.3"]+dev = ["pytest>=7", "jsonschema>=4"]++[project.scripts]+rea-video = "rea_video.cli:main"++[tool.setuptools.packages.find]+include = ["rea_video*"]++[tool.pytest.ini_options]+testpaths = ["tests"]diff --git a/rea_video/__init__.py b/rea_video/__init__.pynew file mode 100644index 0000000..48dadaf--- /dev/null+++ b/rea_video/__init__.py@@ -0,0 +1,4 @@+"""rea-video: reverse engineer how a video was made, shot by shot."""++__version__ = "0.1.0"+SCHEMA = "rea_video.breakdown.v1"diff --git a/rea_video/__main__.py b/rea_video/__main__.pynew file mode 100644index 0000000..eb53e2f--- /dev/null+++ b/rea_video/__main__.py@@ -0,0 +1,3 @@+from .cli import main++raise SystemExit(main())diff --git a/rea_video/assets.py b/rea_video/assets.pynew file mode 100644index 0000000..10ea1f0--- /dev/null+++ b/rea_video/assets.py@@ -0,0 +1,230 @@+"""Material provenance: which pixels came from *real, imported material* (camera footage,+photos, screenshots / screen recordings) versus things the maker generated (AI) or+rendered (code / 3D templates).++Full-frame material follows from the base label (live action = real footage, screen+capture = real UI, still image = photo/AI image/graphic). Embedded material is found inside+rendered layouts: rectangles or regions whose texture is photographic (high grey-level+entropy) or that hold dense small UI text (a screenshot pasted into a card)."""+from __future__ import annotations++import cv2+import numpy as np++BLOCK = 16+KIND_ZH = {+ "real_footage": "实拍视频素材", "photo_or_image": "照片/图片素材", "screenshot": "界面截图",+ "screen_recording": "录屏素材", "video_clip": "嵌入视频片段", "ai_generated": "AI 生成", "rendered": "制作方渲染",+ "photo": "真实照片", "ai_image": "AI 生成图", "graphic": "设计图形", "logo": "Logo/品牌标识", "product_photo": "商品实拍图",+}+REAL_KINDS = {"real_footage", "photo_or_image", "screenshot", "screen_recording", "video_clip", "photo", "logo", "product_photo"}+++def _entropy(gray_block: np.ndarray) -> float:+ h = np.bincount((gray_block >> 3).ravel(), minlength=32).astype(np.float64)+ p = h[h > 0] / h.sum()+ return float(-(p * np.log2(p)).sum())+++def block_classes(bgr: np.ndarray) -> dict[str, np.ndarray]:+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)+ h, w = gray.shape+ bh, bw = h // BLOCK, w // BLOCK+ photo = np.zeros((bh, bw), bool)+ flat = np.zeros((bh, bw), bool)+ for by in range(bh):+ for bx in range(bw):+ g = gray[by * BLOCK:(by + 1) * BLOCK, bx * BLOCK:(bx + 1) * BLOCK]+ sd = float(g.std())+ if sd < 2.0:+ flat[by, bx] = True+ elif sd > 6.0 and _entropy(g) > 3.4:+ photo[by, bx] = True+ return {"photo": photo, "flat": flat, "shape": np.array([bh, bw])}+++def _rects(bgr: np.ndarray) -> list[tuple[int, int, int, int]]:+ """Large axis-aligned rectangles (cards, windows, pasted screenshots)."""+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)+ h, w = gray.shape+ edges = cv2.Canny(gray, 40, 120)+ edges = cv2.dilate(edges, np.ones((3, 3), np.uint8))+ cnts, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)+ out = []+ for c in cnts:+ x, y, bw, bh = cv2.boundingRect(c)+ area = bw * bh+ if area < 0.03 * w * h or area > 0.9 * w * h or bw < 0.15 * w or bh < 0.08 * h:+ continue+ fill = cv2.contourArea(cv2.convexHull(c)) / float(area)+ if fill > 0.85:+ out.append((x, y, bw, bh))+ return _nms(out)+++def _light_panels(bgr: np.ndarray) -> list[tuple[int, int, int, int]]:+ """Bright, low-saturation rectangles (pasted web/app screenshots, documents) — these+ often touch the frame edges, so contour-based rectangle search misses them."""+ hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)+ h, w = hsv.shape[:2]+ light = ((hsv[..., 2] > 200) & (hsv[..., 1] < 60)).astype(np.uint8)+ if light.mean() > 0.85: # the whole frame is light: that's the base, not a panel+ return []+ light = cv2.morphologyEx(light, cv2.MORPH_CLOSE, np.ones((15, 15), np.uint8))+ n, _lab, stats, _ = cv2.connectedComponentsWithStats(light, connectivity=8)+ out = []+ for i in range(1, n):+ x, y, bw, bh, area = stats[i]+ if 0.05 * w * h <= bw * bh <= 0.85 * w * h and area / float(bw * bh) > 0.75 and bw > 0.3 * w and bh > 0.1 * h:+ out.append((int(x), int(y), int(bw), int(bh)))+ return out+++def _iou(a, b) -> float:+ ax, ay, aw, ah = a+ bx, by, bw, bh = b+ ix, iy = max(0, min(ax + aw, bx + bw) - max(ax, bx)), max(0, min(ay + ah, by + bh) - max(ay, by))+ inter = ix * iy+ return inter / float(aw * ah + bw * bh - inter + 1e-6)+++def _nms(rects, thr: float = 0.5):+ rects = sorted(rects, key=lambda r: -r[2] * r[3])+ keep = []+ for r in rects:+ if all(_iou(r, k) < thr for k in keep):+ keep.append(r)+ return keep+++def _photo_regions(cls: dict, frame_shape) -> list[tuple[int, int, int, int]]:+ photo = cls["photo"].astype(np.uint8)+ photo = cv2.morphologyEx(photo, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))+ n, _lab, stats, _ = cv2.connectedComponentsWithStats(photo, connectivity=8)+ bh, bw = cls["shape"]+ out = []+ for i in range(1, n):+ x, y, ww, hh, area = stats[i]+ if area >= 0.03 * bh * bw and area / float(ww * hh) > 0.45:+ out.append((x * BLOCK, y * BLOCK, ww * BLOCK, hh * BLOCK))+ return out+++def detect_embedded(frames: list[np.ndarray], ocr_items: list[dict] | None = None) -> list[dict]:+ """Find imported material inside a rendered layout. Returns normalized regions."""+ if not frames:+ return []+ mid = frames[len(frames) // 2]+ h, w = mid.shape[:2]+ cls = block_classes(mid)+ cands = _nms(_rects(mid) + _light_panels(mid) + _photo_regions(cls, mid.shape))+ grays = np.stack([cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(np.float32) for f in frames]) if len(frames) > 2 else None+ found = []+ for x, y, rw, rh in cands:+ if rw * rh > 0.85 * w * h:+ continue+ bx0, by0, bx1, by1 = x // BLOCK, y // BLOCK, max(x // BLOCK + 1, (x + rw) // BLOCK), max(y // BLOCK + 1, (y + rh) // BLOCK)+ photo_frac = float(cls["photo"][by0:by1, bx0:bx1].mean())+ roi = cv2.cvtColor(mid[y:y + rh, x:x + rw], cv2.COLOR_BGR2HSV)+ light = float(np.median(roi[..., 2])) > 170+ sat = float(roi[..., 1].mean() / 255.0)+ nx, ny, nw, nh = x / w, y / h, rw / w, rh / h+ inside = [t for t in (ocr_items or []) if nx <= t["bbox"][0] + t["bbox"][2] / 2 <= nx + nw and ny <= t["bbox"][1] + t["bbox"][3] / 2 <= ny + nh]+ # count per sampled frame (subtitles changing over time must not add up)+ by_t: dict[float, list[dict]] = {}+ for t in inside:+ by_t.setdefault(t.get("t", 0.0), []).append(t)+ texts = max(by_t.values(), key=len) if by_t else []+ small = [t for t in texts if t["bbox"][3] < 0.03]+ moving = False+ if grays is not None:+ inside = grays[:, y:y + rh, x:x + rw].std(axis=0).mean()+ mask = np.ones(grays.shape[1:], bool)+ mask[y:y + rh, x:x + rw] = False+ outside = grays.std(axis=0)[mask].mean() if mask.any() else 0.0+ moving = bool(inside > 4.0 and inside > 2.5 * outside)+ kind, why = None, ""+ text_area = sum(t["bbox"][2] * t["bbox"][3] for t in texts) / max(1e-6, nw * nh)+ if photo_frac >= 0.35 and text_area < 0.2 and not (ny > 0.6 and nh < 0.2): # not a subtitle band+ kind = "video_clip" if moving else "photo_or_image"+ why = f"区域内 {photo_frac:.0%} 的块是照片纹理(灰度熵高、无平涂色)"+ elif (light and sat < 0.3 and len(small) >= 6) or len(small) >= 15:+ kind = "screen_recording" if moving else "screenshot"+ why = f"浅色界面面板内有 {len(texts)} 处文字(其中 {len(small)} 处小字号)"+ if kind:+ certain = kind in ("screenshot", "screen_recording")+ found.append({"kind": kind, "kind_zh": KIND_ZH[kind], "bbox": [round(nx, 3), round(ny, 3), round(nw, 3), round(nh, 3)],+ "area": round(nw * nh, 3), "moving": moving, "evidence": why,+ # an embedded picture/clip may be a real photo or an AI image: needs VLM / human+ "real_material": True if certain else None, "source": "deterministic"})+ return _dedupe(found)+++def _dedupe(found: list[dict]) -> list[dict]:+ """Drop regions mostly contained in a larger region (a thumbnail inside a screenshot is+ part of that screenshot; nested duplicates of the same panel collapse to the larger)."""+ found = sorted(found, key=lambda r: -r["area"])+ keep: list[dict] = []+ for r in found:+ x, y, w, h = r["bbox"]+ contained = False+ for k in keep:+ kx, ky, kw, kh = k["bbox"]+ ix = max(0.0, min(x + w, kx + kw) - max(x, kx))+ iy = max(0.0, min(y + h, ky + kh) - max(y, ky))+ if ix * iy > 0.7 * w * h:+ contained = True+ break+ if not contained:+ keep.append(r)+ return keep+++def material_summary(label: str, image_source: str | None, embedded: list[dict], vlm: dict | None, moving: bool = True) -> dict:+ """Shot-level origin: real (user-supplied) material vs AI-generated vs maker-rendered."""+ items: list[dict] = []+ if label == "live_action":+ items.append({"kind": "real_footage", "region": "full", "real_material": True})+ elif label == "screen_capture":+ items.append({"kind": "screen_recording" if moving and image_source != "screenshot" else "screenshot", "region": "full", "real_material": True})+ elif label in ("static_hold", "still_motion"):+ src = image_source or "unknown"+ if src in ("photo", "screenshot"):+ items.append({"kind": src, "region": "full", "real_material": True})+ elif src == "unknown":+ items.append({"kind": "photo_or_image", "region": "full", "real_material": None})+ full_kinds = {i["kind"] for i in items}+ for e in embedded:+ if e["kind"] in full_kinds:+ continue # already covered by the full-frame item+ items.append({"kind": e["kind"], "region": "embedded", "bbox": e["bbox"], "real_material": e.get("real_material", True), "moving": e.get("moving", False),+ "evidence": e.get("evidence", "")})+ for e in (vlm or {}).get("embedded_assets", []) or []:+ if isinstance(e, dict) and e.get("is_real_material"):+ items.append({"kind": e.get("kind", "photo_or_image"), "region": "embedded", "real_material": True,+ "description": e.get("description", ""), "source": "vlm"})+ vlm_origin = (vlm or {}).get("material_origin")+ real = [i for i in items if i.get("real_material")]+ uncertain = [i for i in items if i.get("real_material") is None]+ if label in ("ai_video", "avatar"):+ base = "ai_generated"+ elif label in ("code_render", "cg_3d"):+ base = "rendered"+ elif label in ("live_action", "screen_capture"):+ base = "real"+ elif image_source == "ai_image":+ base = "ai_generated"+ elif image_source == "graphic":+ base = "rendered"+ elif image_source in ("photo", "screenshot"):+ base = "real"+ else:+ base = "unknown"+ if vlm_origin in ("real", "ai_generated", "rendered", "mixed"):+ base = vlm_origin if base == "unknown" else base+ origin = base+ if real and base in ("ai_generated", "rendered"):+ origin = "mixed"+ zh = {"real": "用户真实素材", "ai_generated": "AI 生成", "rendered": "制作方渲染", "mixed": "混合(含真实素材)", "unknown": "待确认"}[origin]+ return {"origin": origin, "origin_zh": zh, "has_real_material": bool(real), "uncertain": bool(uncertain),+ "items": [dict(i, kind_zh=KIND_ZH.get(i["kind"], i["kind"])) for i in items]}diff --git a/rea_video/audio.py b/rea_video/audio.pynew file mode 100644index 0000000..4d55b22--- /dev/null+++ b/rea_video/audio.py@@ -0,0 +1,494 @@+"""Audio reverse-engineering: voice / music / sound effects, and how they lock to picture.++numpy only (no librosa/scipy):+- HPSS (median-filter harmonic/percussive separation) on an STFT+- voice: syllabic (3-8 Hz) modulation of the voiced speech band, pauses, pitch (f0) range+- music: a continuous harmonic bed that persists through speech pauses and/or a periodic+ beat; tempo + beat grid, key (Krumhansl profiles), section changes (chroma novelty)+- SFX: strong percussive/transient events that are neither speech syllables nor on-grid+ drum hits; coarse type (whoosh / ding / pop / click / impact / typing) and whether they+ coincide with cuts or motion-graphics beats+- edit: do cuts land on beats / onsets?"""+from __future__ import annotations++import numpy as np++from .media import extract_audio++SR = 22050+N_FFT = 1024+HOP = 256+T_HOP = HOP / SR+_KS_MAJOR = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88])+_KS_MINOR = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17])+_NOTES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]+SFX_TYPE_ZH = {"whoosh": "嗖/转场呼啸", "ding": "叮/提示音", "pop": "啵/弹出", "click": "咔哒/点击", "impact": "重击/低频冲击",+ "typing": "打字/连续点击", "hit": "打点/敲击"}+++def _stft(x: np.ndarray) -> np.ndarray:+ if len(x) < N_FFT:+ x = np.pad(x, (0, N_FFT - len(x)))+ n = 1 + (len(x) - N_FFT) // HOP+ idx = np.arange(N_FFT)[None, :] + HOP * np.arange(n)[:, None]+ return np.abs(np.fft.rfft(x[idx] * np.hanning(N_FFT)[None, :], axis=1)).astype(np.float32)+++def _median_filter(a: np.ndarray, size: int, axis: int, chunk: int = 600) -> np.ndarray:+ pad = size // 2+ if axis == 0:+ padded = np.pad(a, ((pad, pad), (0, 0)), mode="edge")+ out = np.empty_like(a)+ for s in range(0, a.shape[0], chunk):+ e = min(a.shape[0], s + chunk)+ win = np.lib.stride_tricks.sliding_window_view(padded[s:e + 2 * pad], size, axis=0)+ out[s:e] = np.median(win, axis=-1)+ return out+ return _median_filter(a.T, size, 0, chunk).T+++def hpss(S: np.ndarray, size: int = 17) -> tuple[np.ndarray, np.ndarray]:+ H = _median_filter(S, size, axis=0)+ P = _median_filter(S, size, axis=1)+ mh = H ** 2 / (H ** 2 + P ** 2 + 1e-12)+ return S * mh, S * (1 - mh)+++def _peaks(env: np.ndarray, min_gap: int, thr: float) -> np.ndarray:+ if len(env) < 3:+ return np.array([], int)+ c = np.where((env[1:-1] > env[:-2]) & (env[1:-1] >= env[2:]) & (env[1:-1] > thr))[0] + 1+ picked: list[int] = []+ for i in c[np.argsort(-env[c])]:+ if all(abs(i - p) >= min_gap for p in picked):+ picked.append(int(i))+ return np.array(sorted(picked), int)+++def _runs(flags: np.ndarray, win_s: float, min_len_s: float = 0.6, merge_gap_s: float = 0.6) -> list[list[float]]:+ segs: list[list[float]] = []+ i, n = 0, len(flags)+ while i < n:+ if flags[i]:+ j = i+ while j < n and flags[j]:+ j += 1+ a, b = i * win_s, j * win_s+ if segs and a - segs[-1][1] <= merge_gap_s:+ segs[-1][1] = b+ else:+ segs.append([a, b])+ i = j+ else:+ i += 1+ return [[round(a, 2), round(b, 2)] for a, b in segs if b - a >= min_len_s]+++def _chroma(S: np.ndarray, freqs: np.ndarray) -> np.ndarray:+ valid = (freqs > 60) & (freqs < 4000)+ pc = (np.round(12 * np.log2(freqs[valid] / 440.0)) + 9) % 12+ C = np.zeros((S.shape[0], 12), np.float32)+ for k in range(12):+ C[:, k] = S[:, valid][:, pc == k].sum(axis=1)+ return C / (C.sum(axis=1, keepdims=True) + 1e-9)+++def _key(chroma_mean: np.ndarray) -> dict:+ best = (-2.0, "C", "major")+ for k in range(12):+ for prof, mode in ((_KS_MAJOR, "major"), (_KS_MINOR, "minor")):+ r = float(np.corrcoef(np.roll(prof, k), chroma_mean)[0, 1])+ if r > best[0]:+ best = (r, _NOTES[k], mode)+ return {"tonic": best[1], "mode": best[2], "confidence": round(best[0], 3)}+++def _f0(x: np.ndarray, segs: list[list[float]], max_frames: int = 240) -> dict:+ """Autocorrelation pitch on voiced frames inside speech segments."""+ frame = int(0.04 * SR)+ lo, hi = int(SR / 400), int(SR / 70)+ f0s = []+ starts = []+ for a, b in segs:+ starts += list(range(int(a * SR), max(int(a * SR), int(b * SR) - frame), frame))+ if not starts:+ return {}+ for s in np.array(starts)[np.linspace(0, len(starts) - 1, num=min(max_frames, len(starts))).astype(int)]:+ seg = x[s:s + frame]+ if len(seg) < frame or np.sqrt(np.mean(seg ** 2)) < 0.01:+ continue+ seg = seg - seg.mean()+ ac = np.correlate(seg, seg, "full")[frame - 1:]+ if ac[0] <= 0:+ continue+ lag = lo + int(np.argmax(ac[lo:hi]))+ if ac[lag] / ac[0] > 0.45:+ f0s.append(SR / lag)+ if len(f0s) < 8:+ return {}+ f = np.array(f0s)+ med = float(np.median(f))+ return {"f0_median_hz": round(med, 1), "f0_cv": round(float(np.std(f) / med), 3),+ "gender_hint": "male" if med < 150 else ("female" if med > 200 else "uncertain")}+++def vocal_style(x: np.ndarray, Sh: np.ndarray, freqs: np.ndarray, voice_segs: list[list[float]], beats: np.ndarray) -> dict:+ """Sung/rapped vocals vs spoken narration.+ - sung notes hold a steady pitch for >= 160 ms; speech glides+ - sung or rapped syllables lock to the beat grid (beats + half beats); narration does not"""+ if not voice_segs:+ return {}+ frame, hop = int(0.04 * SR), int(0.02 * SR)+ lo, hi = int(SR / 500), int(SR / 70)+ f0 = []+ for a, b in voice_segs:+ for s in range(int(a * SR), int(b * SR) - frame, hop):+ seg = x[s:s + frame]+ if np.sqrt(np.mean(seg ** 2)) < 0.01:+ f0.append(0.0)+ continue+ seg = seg - seg.mean()+ ac = np.correlate(seg, seg, "full")[frame - 1:]+ lag = lo + int(np.argmax(ac[lo:hi]))+ f0.append(SR / lag if ac[0] > 0 and ac[lag] / ac[0] > 0.5 else 0.0)+ f0.append(0.0)+ if len(f0) > 6000:+ break+ f = np.array(f0)+ voiced = f > 0+ sustained = 0+ i = 0+ while i < len(f):+ if voiced[i]:+ j = i+ while j + 1 < len(f) and voiced[j + 1] and abs(f[j + 1] - f[j]) / f[j] < 0.03:+ j += 1+ if j - i + 1 >= 8:+ sustained += j - i + 1+ i = j + 1+ else:+ i += 1+ sustained_ratio = sustained / max(1, int(voiced.sum()))+ out = {"sustained_note_ratio": round(float(sustained_ratio), 3)}+ if len(beats) > 8:+ band = (freqs > 300) & (freqs < 3400)+ env = np.maximum(0, np.diff(np.log1p(Sh[:, band].sum(axis=1)), prepend=0))+ inside = np.zeros(len(env), bool)+ for a, b in voice_segs:+ inside[int(a / T_HOP):int(b / T_HOP)] = True+ pk = _peaks(env * inside, min_gap=int(0.08 / T_HOP), thr=float(np.percentile(env[inside], 75)) if inside.any() else 0)+ grid = np.sort(np.concatenate([beats, (beats[:-1] + beats[1:]) / 2]))+ if len(pk) > 10:+ t = pk * T_HOP+ d = np.min(np.abs(t[:, None] - grid[None, :]), axis=1)+ spacing = float(np.median(np.diff(grid))) if len(grid) > 1 else 1.0+ chance = min(1.0, 2 * 0.045 / max(spacing, 1e-3))+ out["onsets_on_beat_ratio"] = round(float((d < 0.045).mean()), 3)+ out["onsets_on_beat_chance"] = round(chance, 3)+ lock = out.get("onsets_on_beat_ratio", 0) > max(0.45, 1.5 * out.get("onsets_on_beat_chance", 1))+ out["sung"] = bool(sustained_ratio > 0.3 or lock)+ out["style"] = "singing" if sustained_ratio > 0.3 else ("rap_or_rhythmic" if lock else "speech")+ return out+++def analyze_audio(path: str, cut_times: list[float] | None = None, visual_marks: list[float] | None = None) -> dict:+ x = extract_audio(path, SR)+ if x is None or len(x) < SR * 0.3:+ return {"has_audio": False}+ dur = len(x) / SR+ S = _stft(x)+ freqs = np.fft.rfftfreq(N_FFT, 1 / SR)+ Sh, Sp = hpss(S)+ frame_db = 10 * np.log10((S ** 2).mean(axis=1) + 1e-12)+ peak_db = float(np.percentile(frame_db, 99))+ silent = frame_db < peak_db - 45++ # ---------------- voice ----------------------------------------------------------------+ band = (freqs > 300) & (freqs < 3400)+ sb = Sh[:, band].sum(axis=1)+ sb_db = 10 * np.log10(sb ** 2 + 1e-12)+ w1 = int(round(0.5 / T_HOP))+ local_max = np.array([sb_db[max(0, i - w1):i + w1].max() for i in range(len(sb_db))])+ dip = sb_db < local_max - 12 # gaps between syllables / phrases+ harm_ratio = (Sh ** 2).sum(axis=1) / ((S ** 2).sum(axis=1) + 1e-12)+ win = int(round(1.0 / T_HOP))+ step = int(round(0.5 / T_HOP))+ speech_w, music_w = [], []+ hb_db = 10 * np.log10(Sh.sum(axis=1) ** 2 + 1e-12)+ perc = np.maximum(0, np.diff(np.log1p(Sp.sum(axis=1)), prepend=0))+ for s in range(0, max(1, len(sb) - win + 1), step):+ seg = sb[s:s + win]+ z = (seg - seg.mean()) / (seg.std() + 1e-9)+ mod = np.abs(np.fft.rfft(z))+ mf = np.fft.rfftfreq(len(z), T_HOP)+ syl = float(mod[(mf > 3) & (mf < 8)].sum() / (mod[(mf > 0.5) & (mf < 20)].sum() + 1e-9))+ voiced = float((~silent[s:s + win]).mean())+ gaps = float(dip[s:s + win].mean())+ speech_w.append(syl > 0.36 and voiced > 0.4 and 0.05 < gaps < 0.85)+ # music bed over ~3 s: what remains in the gaps between words is still loud and tonal+ # (TTS/voice-over leaves near-silence or noisy ambience there); with no gaps at all, the+ # track is continuous and mostly harmonic; or a clear periodic beat+ a, b = max(0, s - win), min(len(hb_db), s + 2 * win)+ g = dip[a:b] & (frame_db[a:b] > peak_db - 45)+ if g.sum() >= 0.08 * (b - a):+ bed = float(np.median(frame_db[a:b][g])) > peak_db - 40 and float(np.median(harm_ratio[a:b][g])) > 0.62+ else:+ bed = float(np.median(harm_ratio[a:b])) > 0.6 and float(np.percentile(frame_db[a:b], 10)) > peak_db - 35+ pe = perc[a:b] - perc[a:b].mean()+ ac = np.correlate(pe, pe, "full")[len(pe) - 1:]+ lo, hi = int(0.3 / T_HOP), min(len(ac) - 1, int(1.0 / T_HOP))+ beat_ac = float(ac[lo:hi].max() / (ac[0] + 1e-9)) if hi > lo and ac[0] > 0 else 0.0+ music_w.append(bool(bed or beat_ac > 0.35))+ speech_w, music_w = np.array(speech_w), np.array(music_w)+ speech_segs = _runs(speech_w, 0.5)+ music_segs = _runs(music_w, 0.5, min_len_s=1.5, merge_gap_s=1.0)+ speech_ratio = float(sum(b - a for a, b in speech_segs) / dur)+ music_ratio = float(sum(b - a for a, b in music_segs) / dur)+ voice = {"present": speech_ratio > 0.1, "ratio": round(speech_ratio, 3), "segments": speech_segs[:80]}+ voice.update(_f0(x, speech_segs))++ # ---------------- music: tempo, beats, key, sections ------------------------------------+ music: dict = {"present": music_ratio > 0.25, "ratio": round(music_ratio, 3), "segments": music_segs[:40]}+ beats = np.array([])+ if music["present"]:+ env = perc - perc.mean()+ ac = np.correlate(env, env, "full")[len(env) - 1:]+ ac /= ac[0] + 1e-9+ lo, hi = int(60 / 190 / T_HOP), int(60 / 60 / T_HOP)+ lag = lo + int(np.argmax(ac[lo:hi])) if hi < len(ac) else 0+ if lag:+ tempo = 60 / (lag * T_HOP)+ if tempo < 75: # prefer the common 75-180 BPM octave+ tempo *= 2+ lag = max(1, lag // 2)+ music["tempo_bpm"] = round(float(tempo), 1)+ music["tempo_alternatives"] = [round(float(tempo) / 2, 1), round(float(tempo) * 2, 1)]+ music["beat_strength"] = round(float(ac[lag]), 3)+ # beat grid: best phase of a comb at the tempo, then snap to local onset peaks+ phase = int(np.argmax([perc[p::lag].sum() for p in range(lag)]))+ grid = np.arange(phase, len(perc), lag)+ snapped = []+ for g in grid:+ a, b = max(0, g - 3), min(len(perc), g + 4)+ snapped.append(a + int(np.argmax(perc[a:b])))+ beats = np.array(snapped) * T_HOP+ in_music = np.zeros_like(beats, bool)+ for a, b in music_segs:+ in_music |= (beats >= a) & (beats <= b)+ beats = beats[in_music]+ music["beats"] = [round(float(b), 3) for b in beats[:400]]+ C = _chroma(Sh, freqs)+ mask = np.zeros(len(C), bool)+ for a, b in music_segs:+ mask[int(a / T_HOP):int(b / T_HOP)] = True+ if mask.sum() > 50:+ music["key"] = _key(C[mask].mean(axis=0))+ # sections: chroma + loudness novelty with a 4 s checkerboard-ish comparison+ blk = int(round(0.5 / T_HOP))+ cb = np.array([C[i:i + blk].mean(axis=0) for i in range(0, len(C) - blk, blk)])+ eb = np.array([hb_db[i:i + blk].mean() for i in range(0, len(C) - blk, blk)])+ k = 8+ nov = np.zeros(len(cb))+ for i in range(k, len(cb) - k):+ a, b = cb[i - k:i].mean(axis=0), cb[i:i + k].mean(axis=0)+ cos = float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-9))+ nov[i] = (1 - cos) * 4 + abs(eb[i - k:i].mean() - eb[i:i + k].mean()) / 12+ pk = _peaks(nov, min_gap=k, thr=max(0.25, float(np.percentile(nov, 90))))+ music["section_changes"] = [round(float(i * 0.5), 2) for i in pk][:20]+ music["start"] = music_segs[0][0] if music_segs else None+ music["end"] = music_segs[-1][1] if music_segs else None++ if voice.get("present") and music.get("present"):+ voice.update(vocal_style(x, Sh, freqs, speech_segs, beats))++ # ---------------- SFX ---------------------------------------------------------------+ hf = freqs > 4000+ onset = perc+ speech_frame = np.zeros(len(onset), bool)+ for a_, b_ in speech_segs:+ speech_frame[int(a_ / T_HOP):int(b_ / T_HOP)] = True+ music_frame = np.zeros(len(onset), bool)+ for a_, b_ in music_segs:+ music_frame[int(a_ / T_HOP):int(b_ / T_HOP)] = True+ w2 = int(round(1.0 / T_HOP))+ loc = np.array([np.percentile(onset[max(0, i - w2):i + w2], 90) for i in range(len(onset))])+ cand = _peaks(onset, min_gap=int(0.06 / T_HOP), thr=0.0)+ beat_frames = (beats / T_HOP).astype(int) if len(beats) else np.array([], int)+ events = []+ for c in cand:+ strength = float(onset[c] / (loc[c] + 1e-6))+ # deterministic SFX detection inside a full mix is weak (validated: ~0.2 precision on+ # capsule-cinema cue sheets), so only keep salient transients that stand out from+ # everything around them and sit in a gap of the voice track; the VLM lists the rest+ if strength < 3.0 or frame_db[c] < peak_db - 30 or speech_frame[c]:+ # inside narration, consonant onsets after pauses look exactly like small SFX+ continue+ if music_frame[c] and strength < 6.0:+ continue # under a music bed only very prominent transients are trusted+ if len(beat_frames) and np.min(np.abs(beat_frames - c)) * T_HOP < 0.05:+ continue+ w = slice(c, min(len(S), c + int(0.12 / T_HOP)))+ spec = S[w].mean(axis=0)+ total = float(spec.sum()) + 1e-9+ hf_ratio = float(spec[hf].sum() / total)+ centroid = float((spec * freqs).sum() / total)+ tonal = float(spec.max() / (spec.mean() + 1e-9))+ j = c+ while j < len(frame_db) - 1 and frame_db[j] > frame_db[c] - 15 and (j - c) * T_HOP < 1.5:+ j += 1+ d = (j - c) * T_HOP+ if d > 0.25 and hf_ratio > 0.25:+ kind = "whoosh"+ elif tonal > 25 and centroid > 1200:+ kind = "ding"+ elif centroid < 350:+ kind = "impact"+ elif d < 0.06 and hf_ratio > 0.3:+ kind = "click"+ elif hf_ratio > 0.2 or tonal > 15:+ kind = "pop"+ else:+ kind = "hit"+ events.append({"t": round(c * T_HOP, 3), "dur": round(d, 3), "type": kind, "strength": round(strength, 1),+ "centroid_hz": int(centroid), "hf_ratio": round(hf_ratio, 3), "source": "deterministic", "confidence": "low"})+ # dense click runs = typing / UI clicks+ ts = np.array([e["t"] for e in events])+ for i, e in enumerate(events):+ if e["type"] in ("click", "pop", "hit") and ((np.abs(ts - e["t"]) < 0.6).sum() >= 4):+ e["type"] = "typing"+ marks = sorted(set((cut_times or []) + (visual_marks or [])))+ synced = 0+ for e in events:+ if marks:+ d = min(abs(e["t"] - m) for m in marks)+ e["sync_with_visual"] = bool(d < 0.12)+ synced += e["sync_with_visual"]+ types: dict[str, int] = {}+ for e in events:+ types[e["type"]] = types.get(e["type"], 0) + 1+ sfx = {"present": len(events) >= 3, "method": "salient transients in voice gaps (low confidence; VLM adds the full list)", "count": len(events), "per_minute": round(len(events) / dur * 60, 1),+ "types": types, "types_zh": {SFX_TYPE_ZH[k]: v for k, v in types.items()},+ "sync_ratio": round(synced / len(events), 3) if events and marks else None, "events": events[:300]}++ # ---------------- editing vs audio -----------------------------------------------------+ out = {+ "has_audio": True, "duration": round(dur, 3),+ "rms_dbfs": round(float(20 * np.log10(np.sqrt(np.mean(x ** 2)) + 1e-9)), 1),+ "peak_dbfs": round(float(20 * np.log10(np.abs(x).max() + 1e-9)), 1),+ "silence_ratio": round(float(silent.mean()), 3),+ "voice": voice, "music": music, "sfx": sfx,+ # compatibility keys used by the classifier / reports+ "speech_likely": voice["present"], "music_likely": music["present"], "tempo_bpm": music.get("tempo_bpm"),+ }+ cuts = np.array([c for c in (cut_times or []) if c > 0.2])+ on = _peaks(onset, min_gap=int(0.1 / T_HOP), thr=float(np.percentile(onset, 80))) * T_HOP+ if len(cuts) and len(on):+ dmin = np.min(np.abs(cuts[:, None] - on[None, :]), axis=1)+ out["cuts_on_onset_ratio"] = round(float((dmin < 0.08).mean()), 3)+ out["cuts_on_onset_chance"] = round(float(min(1.0, len(on) / dur * 0.16)), 3)+ if len(cuts) and len(beats):+ db_ = np.min(np.abs(cuts[:, None] - beats[None, :]), axis=1)+ out["cuts_on_beat_ratio"] = round(float((db_ < 0.07).mean()), 3)+ chance = min(1.0, len(beats) / dur * 0.14)+ out["cuts_on_beat_chance"] = round(float(chance), 3)+ out["beat_synced_edit"] = bool(len(cuts) >= 4 and out["cuts_on_beat_ratio"] > max(0.5, chance * 1.8))+ else:+ out["beat_synced_edit"] = False+ out["energy_curve"] = [round(float(v), 1) for v in frame_db[:: max(1, int(0.5 / T_HOP))]]+ return out+++def merge_audio_with_vlm(audio: dict, whole: dict | None) -> dict:+ """Combine measured audio facts with what the VLM heard; build a replication plan."""+ if not audio.get("has_audio"):+ return {"tracks": [], "plan": []}+ whole = whole or {}+ n = whole.get("narration") or {}+ m = whole.get("music") or {}+ vlm_sfx = [e for e in (whole.get("sfx") or []) if isinstance(e, dict)]+ det_sfx = (audio.get("sfx") or {}).get("events", [])+ sfx = [dict(e, source="vlm") for e in vlm_sfx]+ for e in det_sfx:+ if not any(abs(float(v.get("t", -9)) - e["t"]) < 0.25 for v in vlm_sfx):+ sfx.append(e)+ sfx.sort(key=lambda e: float(e.get("t", 0)))+ voice = audio.get("voice", {})+ music = audio.get("music", {})+ plan = []+ if voice.get("present") or n.get("type") in ("tts", "human", "mixed"):+ plan.append({"track": "voice", "rule": "A01-narration" if n.get("type") != "human" else "A01-narration",+ "what": f"{'TTS 旁白' if n.get('type') == 'tts' else ('真人口播/对白' if n.get('type') == 'human' else '人声')}"+ f",{n.get('voice') or voice.get('gender_hint') or ''},{n.get('style') or ''}".strip(","),+ "how": "capsule-cinema DoubaoTTSTool / UniversalTTSTool(或 MiniMax 克隆音色);需要卡原时间窗时用时长可控 TTS(A02)",+ "segments": voice.get("segments", [])[:40], "lines": n.get("lines", [])[:60],+ "real_material": n.get("type") == "human"})+ if music.get("present") or m.get("present"):+ src = m.get("source_guess") or "unknown"+ plan.append({"track": "music", "rule": "A03-music",+ "what": ";".join(x for x in [m.get("style") or m.get("genre") or "", m.get("mood") or "",+ f"{music.get('tempo_bpm') or m.get('bpm_estimate') or '?'} BPM",+ (f"{music['key']['tonic']} {music['key']['mode']}" if music.get("key") else "")] if x),+ "how": ("疑似知名歌曲,需要授权或换成风格相近的授权曲/生成曲" if src == "popular_song" else+ "capsule-cinema UniversalMusicGenerationTool(Suno)或曲库:按 BPM/调性/情绪选曲,在段落变化点对齐镜头"),+ "segments": music.get("segments", []), "section_changes": music.get("section_changes", []),+ "source_guess": src, "song_guess": m.get("song_guess", ""),+ "beat_synced_cuts": bool(audio.get("beat_synced_edit") or m.get("beat_synced_cuts"))})+ if sfx:+ plan.append({"track": "sfx", "rule": "A04-sfx", "what": f"{len(sfx)} 个音效",+ "how": "按时间点摆放:capsule-cinema SoundEffectsTool / 音效库,或像 plush 配方那样程序合成(音高对齐 BGM 调性)",+ "events": sfx[:200]})+ if whole.get("ambience"):+ plan.append({"track": "ambience", "rule": "A04-sfx", "what": whole["ambience"], "how": "环境声素材或视频生音效模型"})+ return {"sfx_merged": sfx[:300], "plan": plan, "mix": whole.get("mix", "")}+++def refine_with_stems(audio: dict, vocals_wav: str) -> dict:+ """Re-measure the vocal style on the separated dry vocals (no BGM underneath, so pitch tracking is clean)."""+ voice = audio.get("voice") or {}+ segs = voice.get("segments") or []+ if not voice.get("present") or not segs:+ return audio+ x = extract_audio(vocals_wav, SR)+ if x is None or len(x) < SR:+ return audio+ Sh, _ = hpss(_stft(x))+ freqs = np.fft.rfftfreq(N_FFT, 1 / SR)+ beats = np.array((audio.get("music") or {}).get("beats") or [], float)+ st = vocal_style(x, Sh, freqs, segs, beats)+ if st:+ rep = vocal_repetition(x, freqs)+ st["chorus_repeat_share"] = rep+ if rep > 0.1 and st["style"] == "speech": # repeated melodic lines = a song (rap included), narration never repeats+ st["style"], st["sung"] = "rap_or_rhythmic", True+ voice.update(st)+ voice["style_measured_on"] = "vocals_stem"+ return audio+++def vocal_repetition(x: np.ndarray, freqs: np.ndarray, win_s: float = 4.0, min_lag_s: float = 6.0) -> float:+ """Share of 4 s vocal windows whose pitch-class pattern recurs >= 6 s later (choruses / hooks).+ Measured on the dry vocal stem: AI rap MV 0.26, TTS narration 0.00."""+ S = _stft(x)+ C = _chroma(S, freqs)+ e = (S ** 2).sum(axis=1)+ blk = max(1, int(0.25 / T_HOP))+ n = len(C) // blk+ if n < 4 * win_s / 0.25:+ return 0.0+ C = C[:n * blk].reshape(n, blk, 12).mean(axis=1)+ E = 10 * np.log10(e[:n * blk].reshape(n, blk).mean(axis=1) + 1e-12)+ act = E > np.percentile(E, 95) - 30+ W = int(win_s / 0.25)+ feats, idx = [], []+ for i in range(0, n - W, 2):+ if act[i:i + W].mean() < 0.6:+ continue+ f = C[i:i + W].ravel()+ feats.append((f - f.mean()) / (f.std() + 1e-9))+ idx.append(i)+ if len(feats) < 4:+ return 0.0+ F, idx = np.array(feats), np.array(idx)+ sim = F @ F.T / F.shape[1]+ sim[np.abs(idx[:, None] - idx[None, :]) * 0.25 < min_lag_s] = -1+ return round(float((sim.max(axis=1) > 0.6).mean()), 3)diff --git a/rea_video/classify.py b/rea_video/classify.pynew file mode 100644index 0000000..eb7df7b--- /dev/null+++ b/rea_video/classify.py@@ -0,0 +1,307 @@+"""Production-method classification: deterministic forensics + optional VLM, fused.++Base layer labels (what produced the moving picture of the shot):+ live_action 实拍(摄像机/手机拍摄)+ ai_video AI 生成视频(文生/图生/参考生视频)+ avatar 数字人口播(AI 驱动的说话人)+ cg_3d 3D 渲染(Blender/C4D/UE 等)+ code_render 代码/模板渲染(MG、文字、UI、图表、PPT 式卡片)+ screen_capture 屏幕录制/网页截图+ still_motion 静态图片 + 推拉摇移(Ken Burns 图片动效)+ static_hold 静帧停留(图片或卡片定格,无运动)+Overlays (composited on top): subtitle / title / label text, static graphics, layout template.++Deterministic evidence is decisive for *temporal* questions (is anything moving? is the+whole frame a rigid zoom of one still image? exact frozen pixels?) and for *rendered vs+photographic* texture. It is weak for live-action vs AI vs 3D, which the VLM decides;+fusion weights reflect that."""+from __future__ import annotations++import math++LABELS = ["live_action", "ai_video", "avatar", "cg_3d", "code_render", "screen_capture", "still_motion", "static_hold"]+LABEL_ZH = {+ "live_action": "实拍",+ "ai_video": "AI 生成视频",+ "avatar": "数字人口播",+ "cg_3d": "3D 渲染",+ "code_render": "代码/模板渲染",+ "screen_capture": "屏幕录制/截图",+ "still_motion": "静态图 + 推拉动效",+ "static_hold": "静帧停留",+}+IMAGE_SOURCE_ZH = {"ai_image": "AI 生成图", "photo": "真实照片", "graphic": "设计/渲染图形", "screenshot": "截图", "unknown": "未知"}+# how much to trust the deterministic layer per label (VLM weight is 1.0)+DET_WEIGHT = {"static_hold": 1.6, "still_motion": 1.4, "code_render": 1.0, "screen_capture": 0.6,+ "cg_3d": 0.5, "live_action": 0.6, "ai_video": 0.6, "avatar": 0.4}+++# weight of the model's opinion (VLM or an agent's review) relative to the deterministic layer+# calibrated on the first real-Gemini run (eval/articles.yaml, 2026-10-30): 1.0 let a confident+# but wrong VLM override 24fps/transcode evidence on AI videos; 0.7 keeps its gains on 3D / UI shots+VLM_WEIGHT = 0.7+++def _sig(x: float) -> float:+ return 1.0 / (1.0 + math.exp(-x))+++def _norm(d: dict[str, float]) -> dict[str, float]:+ s = sum(max(v, 0.0) for v in d.values()) or 1.0+ return {k: max(v, 0.0) / s for k, v in d.items()}+++PLATFORM_TRANSCODES = ("WeChat transcode", "WeChat Channels", "Douyin/TikTok", "Douyin", "Kuaishou", "Xiaohongshu")+++def video_context(shots: list[dict], provenance: dict | None, fps: float | None) -> dict:+ """Whole-video facts the per-shot classifier needs.+ - transcoded: the file went through a platform re-encode (WeChat / Douyin / TikTok ...). Heavy+ compression wipes sensor noise, so "no noise" is no longer evidence for AI.+ - native30: in a 30 fps file, photographic shots carry no duplicated frames (no 24->30 pulldown).+ Phones record 30 fps natively; video generators mostly emit 24 fps."""+ plat = [h for h in ((provenance or {}).get("hints", {}).get("platform") or []) if h in PLATFORM_TRANSCODES]+ 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:+ continue # rendered graphics or frozen frames say nothing about camera cadence+ d = float(r.get("duration", 0))+ photo_dur += d+ if f.get("dup_ratio", 1) < 0.02 and f.get("sharp_period_ac", 0) < 0.45:+ native_dur += d+ native30 = bool(fps and 29 <= fps <= 31 and photo_dur >= 3 and native_dur / photo_dur >= 0.7)+ return {"transcoded": bool(plat), "platform": plat, "native30": native30,+ "native30_share": round(native_dur / photo_dur, 3) if photo_dur else None}+++def deterministic(f: dict, overlay: dict | None = None, text: dict | None = None, faces: float = 0.0,+ audio: dict | None = None, provenance: dict | None = None, fps: float | None = None,+ ctx: dict | None = None) -> tuple[dict[str, float], list[str], dict]:+ """Return (probabilities, evidence lines in Chinese, derived facts)."""+ ctx = ctx or {}+ ev: list[str] = []+ facts: dict = {}+ noise, tnoise = f.get("noise_sigma", 0), f.get("temporal_noise", 0)+ flat, pal, axis = f.get("flat_ratio", 0), f.get("palette95", 999), f.get("axis_edge_ratio", 0)+ dup, per, reg = f.get("dup_ratio", 0), f.get("dup_period"), f.get("dup_regularity", 0)+ moving = f.get("moving_pair_ratio", 0)+ kb = f.get("kenburns_score", 0)+ zero = f.get("zero_pixel_ratio", 0)+ text_cov = (text or {}).get("text_coverage", 0.0)++ # ---- temporal family ---------------------------------------------------------+ frozen = dup > 0.85 and f.get("pair_mad_p90", 0) < 0.6+ sparse_anim = dup > 0.6 and moving > 0.01+ if frozen and not sparse_anim and f.get("start_end_mad", 0) < 1.0:+ family = "frozen"+ ev.append(f"画面几乎完全静止:{dup:.0%} 的相邻帧逐像素重复,首尾帧差 {f.get('start_end_mad', 0):.2f}")+ elif kb > 0.45:+ family = "planar"+ ev.append(f"整帧按单一刚体变换运动(拟合内点 {f.get('rigid_inlier_ratio', 0):.0%},残差 {f.get('rigid_residual', 0):.2f}px,无局部运动)"+ f"→ 静态图推拉:缩放 {f.get('zoom_per_s', 0) * 100:+.1f}%/s,平移 {f.get('pan_px_per_s', 0):.0f}px/s")+ elif dup > 0.5:+ family = "mostly_static"+ ev.append(f"{dup:.0%} 的相邻帧完全重复,只有局部元素在动(典型的模板/MG 动画或定格后局部动效)")+ else:+ family = "dynamic"+ facts["temporal_family"] = family++ # ---- texture: rendered graphic vs photographic ------------------------------+ # 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))+ # (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)+ # 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)+ facts["text_like"] = round(text_like, 3)+ facts["static_composite"] = round(rsb, 3)+ if graphic > 0.6:+ ev.append(f"纹理呈渲染特征:平坦色块 {flat:.0%}、95% 像素仅用 {pal} 种颜色、横竖直边 {axis:.0%}")+ elif graphic < 0.35:+ ev.append(f"纹理呈照片/视频特征:噪声 σ={noise:.2f}、用色 {pal} 种、平坦块 {flat:.0%}")+ if text_like > 0.6:+ ev.append("平坦底色上有大量细小高频细节(小字号文字/界面),像截图或文档画面")+ if rsb > 0.6 and family != "frozen":+ ev.append(f"背景 {zero:.0%} 像素逐帧完全不变、只有局部元素在动:2D 合成/代码动效特征")++ # ---- frame-rate fingerprints -------------------------------------------------+ pulldown = None+ if 0.12 <= dup <= 0.30 and per in (4, 5, 6) and reg > 0.25:+ pulldown = "24→30"+ elif 0.50 <= dup <= 0.66 and per in (1, 2, 3):+ pulldown = "24→60"+ elif 0.03 <= dup <= 0.10 and per in (5, 6, 7) and reg > 0.25:+ pulldown = "25→30?"+ # platform re-encodes alternate frame quality with their GOP (I/P/B) pattern, which mimics the+ # sharpness rhythm of frame interpolation: only trust this cue on first-generation files+ resampled = (f.get("sharp_alt", 0) > 0.025 or f.get("sharp_period_ac", 0) > 0.45) and not ctx.get("transcoded")+ if resampled and not pulldown and family == "dynamic":+ pulldown = "interpolated"+ ev.append(f"逐帧清晰度呈周期性起伏(周期 {f.get('sharp_period')} 帧,相关 {f.get('sharp_period_ac', 0):.2f}):画面经过插帧/帧率转换,原始帧率更低")+ facts["pulldown"] = pulldown+ if pulldown:+ ev.append(f"重复帧呈 {pulldown} 规律({dup:.0%},周期 {per}):原始素材为 24/25fps 后转码,常见于 AI 生成视频、3D/动画渲染或电影素材")++ live_hint = 0.0+ live_hint += 1.2 * _sig((noise - 0.9) / 0.2)+ live_hint += 0.6 * _sig((tnoise - 0.8) / 0.15)+ live_hint += 0.3 * _sig((0.5 - zero) / 0.1)+ live_hint += 0.6 * (1.0 if f.get("camera") == "handheld_like" else 0.0)+ live_hint += 0.2 * (1.0 if dup < 0.03 else 0.0)+ live_hint -= 0.9 * (1.0 if pulldown else 0.0)+ # generators emit 24/25/30 fps; a native >=48 fps stream with no duplicated frames was+ # most likely captured by a phone/camera (or screen/game capture)+ native_hfr = bool(fps and fps >= 47 and dup < 0.05 and not pulldown)+ if native_hfr:+ live_hint += 1.0+ ev.append(f"原生 {fps:.0f}fps 且几乎无重复帧:生成模型通常输出 24/30fps,高帧率原生素材多为手机/相机拍摄")+ facts["native_hfr"] = native_hfr+ cam_tags = bool((provenance or {}).get("hints", {}).get("camera"))+ if cam_tags:+ live_hint += 1.0+ ev.append("容器元数据含拍摄设备信息(make/model/location)")+ if ctx.get("native30") and dup < 0.02 and not pulldown:+ live_hint += 0.9+ ev.append(f"整片是原生 30fps、实拍类镜头没有 24fps 源的重复帧({ctx.get('native30_share', 0):.0%} 时长):手机直出常见,生成模型多输出 24fps")+ live_hint = min(1.0, max(0.0, live_hint / 2.9))+ gen_tags0 = bool((provenance or {}).get("hints", {}).get("generator"))+ degraded = bool(ctx.get("transcoded") and noise < 0.9)+ facts["transcode_degraded"] = degraded+ if degraded and not pulldown and not gen_tags0 and live_hint < 0.45:+ # compression erased the sensor noise: its absence no longer argues for AI+ live_hint = 0.45+ ev.append("经过平台二次转码(" + "、".join(ctx.get("platform", [])) + "),传感器噪声被压没了:噪声类证据失效,实拍还是 AI 主要看帧率和画面内容")+ if live_hint > 0.6:+ ev.append(f"时域噪声 {tnoise:.2f}、逐像素不变比例 {zero:.0%}:存在传感器噪声,符合实拍")+ gen_tags = bool((provenance or {}).get("hints", {}).get("generator"))+ if gen_tags:+ ev.append("容器元数据包含生成式工具/AIGC 标识:" + ", ".join(provenance["hints"]["generator"][:3]))++ speech = bool((audio or {}).get("speech_likely"))+ if faces > 0.6 and family in ("dynamic", "mostly_static") and f.get("camera") in ("static", "static_with_subject_motion"):+ ev.append(f"{faces:.0%} 的采样帧有正脸且机位固定" + (",音轨有人声" if speech else ""))++ # ---- assemble scores ---------------------------------------------------------+ s = {k: 0.02 for k in LABELS}+ if family == "frozen":+ # a frozen *rendered* card is code/template output; a frozen photo/AI picture is a still hold+ screenshot_like = graphic > 0.45 and axis > 0.42 and text_cov > 0.05+ s["static_hold"] += 3.0 * (1 - graphic)+ s["code_render"] += 3.0 * graphic * (0.5 if screenshot_like else 1.0)+ s["screen_capture"] += 3.0 * graphic * (0.6 if screenshot_like else 0.1)+ elif family == "planar":+ s["still_motion"] += 3.0 * kb * (0.35 if pulldown else 1.0)+ if pulldown:+ ev.append("但运动带有 24fps 源的帧率转换痕迹:更像生成视频里的缓慢推镜,而不是剪辑软件对静图做推拉")+ s["ai_video"] += 1.2+ s["screen_capture"] += 0.5 * graphic * (1 if abs(f.get("zoom_per_s", 0)) < 0.003 else 0.2) # pure scroll+ s["ai_video"] += 0.3+ elif family == "mostly_static":+ s["code_render"] += 1.6 * graphic * (1 + 0.5 * rsb) * (1 - 0.5 * text_like * _sig((0.12 - f.get("saturation", 0.3)) / 0.04))+ s["screen_capture"] += 1.5 * graphic * text_like * (0.3 + _sig((0.12 - f.get("saturation", 0.3)) / 0.04))+ s["static_hold"] += 0.5 * photo+ s["cg_3d"] += 0.4 * graphic * (1 - text_like)+ s["ai_video"] += 0.8 * photo * (1.4 if pulldown else 1.0)+ s["live_action"] += 0.3 * photo * live_hint+ else:+ axis_f = 1.2 if axis > 0.38 else 0.8+ # near-grayscale frames built from a handful of colours are UI / documents (white pages, grey+ # cards, dark editors), not shaded 3D renders: shading spreads colours, product 3D is coloured+ 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)+ 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)+ if pulldown:+ s["cg_3d"] *= 1.2+ if gen_tags:+ s["ai_video"] += 1.0+ s["avatar"] += 0.3+ probs = _norm(s)+ facts["live_hint"] = round(live_hint, 3)+ return probs, ev, facts+++def image_source_guess(f: dict, facts: dict) -> str:+ if facts.get("graphic_score", 0) > 0.6:+ return "graphic"+ if f.get("axis_edge_ratio", 0) > 0.45 and f.get("noise_sigma", 1) < 0.2:+ return "screenshot"+ return "unknown" # photo vs AI image needs the VLM+++def fuse(det: dict[str, float], vlm: dict[str, float] | None, family: str, majority: str | None = None) -> dict[str, float]:+ """majority: the tools' top label when one of the two image readers backs it (see pipeline._majority)."""+ if not vlm:+ return det+ vlm = _norm({k: float(vlm.get(k, 0.0)) for k in LABELS})+ out = {}+ for k in LABELS:+ out[k] = math.exp(DET_WEIGHT[k] * 0.6 * math.log(det.get(k, 1e-4) + 1e-4) + VLM_WEIGHT * math.log(vlm.get(k, 1e-4) + 1e-3))+ # hard temporal constraints: a frozen shot cannot be a generated *video*+ if family == "frozen":+ for k in ("ai_video", "live_action", "avatar", "cg_3d", "still_motion"):+ out[k] *= 0.05+ if family == "planar":+ for k in ("live_action", "avatar"):+ out[k] *= 0.2+ # the answer must be one that some source actually backs (top-2 of the deterministic layer+ # or of the model), not a compromise label nobody voted for+ backed = {k for src in (det, vlm) for k, _ in sorted(src.items(), key=lambda kv: -kv[1])[:2]}+ best = max(out, key=out.get)+ if best not in backed:+ for k in out:+ if k not in backed:+ out[k] *= 0.1+ # two of three sources agree: one overconfident model must not outvote them (hard constraints above still apply)+ if majority and out[majority] > 0 and max(out, key=out.get) != majority:+ for k in out:+ if k != majority:+ out[k] = min(out[k], out[majority] * 0.8)+ return _norm(out)+++def top(probs: dict[str, float]) -> tuple[str, float]:+ k = max(probs, key=probs.get)+ return k, probs[k]+++def overlay_layers(overlay: dict | None, text: dict | None, template: dict | None) -> list[dict]:+ layers: list[dict] = []+ for tr in (text or {}).get("tracks", []):+ if not tr.get("axis_aligned", True) and tr["kind"] != "subtitle":+ continue # tilted text is probably part of the scene+ layers.append({"kind": tr["kind"], "source": "code_or_editor", "band": tr["band"], "texts": tr["texts"],+ "changing": tr["changing"], "y_center": tr.get("y_center")})+ for b in (overlay or {}).get("boxes", []):+ if any(l["band"] == b["band"] and l["kind"] in ("subtitle", "title", "label") for l in layers):+ continue+ layers.append({"kind": "static_graphic", "source": "code_or_editor", "band": b["band"], "bbox": b["bbox"]})+ if template and template.get("frozen_edge_ratio", 0) > 0.25 and template.get("boxes"):+ layers.append({"kind": "layout_template", "source": "code_or_editor", "band": "frame",+ "coverage": round(template.get("frozen_ratio", 0), 3)})+ return layers+++def verdict_text(label: str, image_source: str | None, layers: list[dict]) -> str:+ base = LABEL_ZH[label]+ if label in ("static_hold", "still_motion") and image_source and image_source != "unknown":+ base += f"({IMAGE_SOURCE_ZH.get(image_source, image_source)})"+ kinds = []+ for l in layers:+ name = {"subtitle": "字幕", "title": "标题", "label": "文字标注", "static_graphic": "图形贴片", "layout_template": "版式模板"}.get(l["kind"], l["kind"])+ if name not in kinds:+ kinds.append(name)+ if kinds:+ return f"{base} + 代码/剪辑叠加({'、'.join(kinds)})"+ return basediff --git a/rea_video/cli.py b/rea_video/cli.pynew file mode 100644index 0000000..5dbedce--- /dev/null+++ b/rea_video/cli.py@@ -0,0 +1,386 @@+"""rea-video command line."""+from __future__ import annotations++import argparse+import json+import os+import sys+from pathlib import Path++from .util import LOG, load_env_files, read_json, setup_logging+from .vlm import vlm_note++DEFAULT_CAPSULE_ROOT = os.getenv("CAPSULE_CINEMA_ROOT", str(Path.home() / "code/github/capsule-cinema"))+++def _env(args) -> None:+ from .memory import pref++ files = [Path.cwd() / ".env", Path(__file__).resolve().parent.parent / ".env"]+ env_file = getattr(args, "env_file", None) or pref("env_file")+ if env_file:+ files.insert(0, Path(env_file))+ loaded = load_env_files(files)+ if loaded:+ LOG.debug("env loaded from %s", loaded)+++def cmd_decompose(args) -> int:+ from .pipeline import decompose++ out = Path(args.out) if args.out else Path("out") / Path(args.video).stem+ from .memory import pref++ meta = read_json(Path(args.meta)) if args.meta else None+ use_vlm = args.vlm or (pref("vlm") == "on" and not args.no_vlm)+ stems = not args.no_stems and pref("stems", "on") == "on"+ b = decompose(args.video, out, use_vlm=use_vlm, whole_vlm=not args.no_whole, ocr=not args.no_ocr,+ workers=args.workers, engine=args.engine or pref("engine", "seedance2.0"), platform_meta=meta, stems=stems)+ print(json.dumps({"out": str(out), "verdict": b["summary"]["verdict"], "shots": b["summary"]["shots"],+ "confidence": b["summary"]["confidence"], "vlm": b["summary"]["vlm"],+ "report": str(out / "report.html")}, ensure_ascii=False, indent=2))+ return 0+++def cmd_review(args) -> int:+ """Write review_tasks.json + review_answers.json so a multimodal agent can act as the VLM."""+ from .review import build_tasks++ out = Path(args.out_dir)+ b = read_json(out / "breakdown.json")+ tasks, answers = build_tasks(b, str(out))+ (out / "review_tasks.json").write_text(json.dumps(tasks, ensure_ascii=False, indent=2), encoding="utf-8")+ ans_path = out / "review_answers.json"+ if args.force or not ans_path.is_file():+ ans_path.write_text(json.dumps(answers, ensure_ascii=False, indent=2), encoding="utf-8")+ high = [s for s in tasks["shots"] if s["priority"] == "high"]+ print(f"{len(tasks['shots'])} 个镜头待看图复核,其中 {len(high)} 个优先:" + ", ".join(f"{s['id']}({'; '.join(s['why'])})" for s in high))+ print(f"说明和图片路径:{out / 'review_tasks.json'}")+ print(f"把答案填进:{ans_path}")+ print(f"然后运行:rea-video apply-review {out} --by <你的名字>")+ return 0+++def cmd_apply_review(args) -> int:+ from .pipeline import finalize+ from .review import apply_answers++ out = Path(args.out_dir)+ b = read_json(out / "breakdown.json")+ answers = read_json(Path(args.answers) if args.answers else out / "review_answers.json")+ from .memory import pref++ log = apply_answers(b, answers, by=args.by or pref("reviewer"))+ b = finalize(b, out)+ for p in log["problems"]:+ print(f"跳过 {p}")+ changed = [(r["id"], log["before"][r["id"]], r["base"]["label"]) for r in b["shots"]+ if r["id"] in log["before"] and log["before"][r["id"]] != r["base"]["label"]]+ print(f"已并入 {len(log['applied'])}/{len(b['shots'])} 个镜头;改判 {len(changed)} 个" ++ (":" + ", ".join(f"{i} {a}→{c}" for i, a, c in changed) if changed else ""))+ print(f"结论: {b['summary']['verdict']}")+ print(f"VLM: {b['summary']['vlm']}")+ return 0 if log["applied"] else 1+++def cmd_stems(args) -> int:+ from .stems import extract_stems++ out = Path(args.out) if args.out else Path("out") / Path(args.video).stem+ print(json.dumps(extract_stems(args.video, out), ensure_ascii=False, indent=2))+ return 0+++def cmd_probe(args) -> int:+ from .media import video_info+ from .probe import provenance++ info = video_info(args.video)+ p = provenance(info)+ p.pop("tags", None) if not args.tags else None+ print(json.dumps({"width": info.width, "height": info.height, "fps": info.fps, "duration": info.duration,+ "vcodec": info.vcodec, "aspect_ratio": info.aspect_ratio, "provenance": p}, ensure_ascii=False, indent=2))+ return 0+++def cmd_eval(args) -> int:+ from .evaluate import evaluate++ res = evaluate(Path(args.labels), Path(args.out), use_vlm=args.vlm, ocr=not args.no_ocr, reuse=not args.fresh,+ only=set(args.only.split(",")) if args.only else None, stems=args.stems)+ print(json.dumps(res["summary"], ensure_ascii=False, indent=2))+ return 0+++def cmd_capsule(args) -> int:+ from .integrations.capsule_cinema import export_capsule_analysis++ b = read_json(Path(args.breakdown))+ out = export_capsule_analysis(b, Path(args.out) if args.out else Path(args.breakdown).with_name("capsule_analysis.json"))+ print(out)+ return 0+++def cmd_remake_plan(args) -> int:+ from .integrations.capsule_cinema import build_remake_jobs++ bdir = Path(args.breakdown).parent+ from .memory import pref++ jobs = build_remake_jobs(read_json(Path(args.breakdown)), bdir, capsule_root=Path(args.capsule_root),+ engine=args.engine or pref("engine", "seedance2.0"),+ mode=args.mode, labels=args.labels.split(",") if args.labels else None)+ print(jobs)+ return 0+++def cmd_assemble(args) -> int:+ from .remake import assemble++ print(assemble(Path(args.breakdown), Path(args.results), Path(args.out) if args.out else None))+ return 0+++def cmd_tiles(args) -> int:+ """Time-labelled frame grid for close inspection of a passage."""+ import cv2+ import numpy as np++ from .media import extract_frame, video_info+ from .visual import shot_sheet++ info = video_info(args.video)+ end = args.end if args.end is not None else info.duration+ times = list(np.arange(args.start, end, args.every))[: args.max]+ import tempfile++ frames = []+ with tempfile.TemporaryDirectory() as tmpd:+ for i, t in enumerate(times):+ p = extract_frame(args.video, float(t), Path(tmpd) / f"tile_{i:03d}.jpg", width=args.cell)+ img = cv2.imread(str(p))+ if img is not None:+ frames.append(img)+ rows = [frames[i:i + args.cols] for i in range(0, len(frames), args.cols)]+ paths = []+ for r, row in enumerate(rows):+ out = Path(args.out) if len(rows) == 1 else Path(args.out).with_name(f"{Path(args.out).stem}_{r + 1}{Path(args.out).suffix}")+ shot_sheet(row, [float(t) for t in times[r * args.cols:(r + 1) * args.cols]], out, n=len(row), cell_w=args.cell)+ paths.append(str(out))+ print(json.dumps({"tiles": paths, "times": [round(float(t), 3) for t in times]}, ensure_ascii=False))+ return 0+++def cmd_summary(args) -> int:+ """Compact, agent-friendly view of a breakdown (instead of reading the whole JSON)."""+ b = read_json(Path(args.breakdown))+ s = b["summary"]+ lines = [f"{b['source']['filename']} | {b['source']['duration']}s {b['source']['width']}x{b['source']['height']} {b['source']['fps']}fps",+ f"结论: {s['verdict']}", f"置信度: {s['confidence']}", f"VLM: {s.get('vlm') or vlm_note(b['analysis']['vlm'])}", ""]+ vc = b.get("video_context") or {}+ if vc.get("transcoded"):+ lines.append(f"平台转码: {'、'.join(vc.get('platform', []))}(噪声类证据失效;原生 30fps 无重复帧: {vc.get('native30')})")+ prov = b.get("provenance", {})+ if prov.get("aigc") or prov.get("hints"):+ lines.append(f"元数据: aigc={prov.get('aigc')} hints={prov.get('hints')}")+ from .memory import hint_for, patterns++ pats = patterns()+ for r in b["shots"]:+ base = r["base"]+ alt = sorted(base["probs"].items(), key=lambda kv: -kv[1])[1]+ det = r["deterministic"]["probs"]+ past = None if base["decided_by"] == "user" else hint_for(max(det, key=det.get), pats)+ mat = (r.get("material") or {}).get("origin_zh", "")+ second = "(用户纠正)" if base["decided_by"] == "user" else f"(次选 {alt[0]} {alt[1]:.2f})"+ lines.append(f"#{r['index']:>2} {r['start']:7.2f}-{r['end']:7.2f} {base['label']:<14} {base['confidence']:.2f} {second} "+ f"| 素材:{mat} | 叠加:{','.join(sorted({l['kind'] for l in r.get('layers', [])})) or '-'} | {r['features'].get('camera')}"+ + (" ← 低置信,需要复核" 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 ""))+ a = b.get("audio", {})+ if a.get("has_audio"):+ mu = a.get("music", {})+ lines += ["", f"人声: {a.get('voice', {}).get('present')} ({a.get('voice', {}).get('ratio')}) | 音乐: {mu.get('present')} "+ f"{mu.get('tempo_bpm')}BPM {(mu.get('key') or {}).get('tonic', '')}{(mu.get('key') or {}).get('mode', '')} | "+ f"音效: {len((b.get('audio_plan') or {}).get('sfx_merged', []))} | 卡点: {a.get('beat_synced_edit')}"]+ if (b.get("sound_sources") or {}).get("summary_zh"):+ lines.append("声音来源: " + b["sound_sources"]["summary_zh"])+ if (b.get("stems") or {}).get("ok"):+ lines.append("音轨: stems/original.wav(原声) stems/vocals.wav(人声) stems/music.wav(配乐)")+ print("\n".join(lines))+ return 0+++def cmd_correct(args) -> int:+ """The user says a shot is wrong: fix this breakdown and remember the correction."""+ from .memory import correct+ from .pipeline import finalize++ out = Path(args.out_dir)+ b = read_json(out / "breakdown.json")+ real = None if args.real is None else args.real == "yes"+ try:+ logged = correct(b, label=args.label, real=real, shots=args.shots, start=args.start, end=args.end, note=args.note or "")+ except ValueError as e:+ print(f"错误:{e}", file=sys.stderr)+ return 2+ b = finalize(b, out)+ changed = [f"{c['shot']} {c['before']}→{c['label']}" for c in logged if c.get("label") and c["before"] != c["label"]]+ print(f"已纠正 {len(logged)} 个镜头" + ((":" + ", ".join(changed)) if changed else "") + ",并记入记忆")+ print(f"结论: {b['summary']['verdict']}")+ return 0+++def cmd_prefs(args) -> int:+ from .memory import PREF_KEYS, add_note, load_prefs, remove_note, set_pref++ try:+ if args.note:+ add_note(args.note)+ elif args.remove_note:+ remove_note(args.remove_note)+ elif args.key and args.unset:+ set_pref(args.key, None)+ elif args.key and args.value is not None:+ set_pref(args.key, args.value)+ elif args.key:+ print(load_prefs().get(args.key, ""))+ return 0+ except ValueError as e:+ print(f"错误:{e}", file=sys.stderr)+ return 2+ prefs = load_prefs()+ for k, desc in PREF_KEYS.items():+ print(f"{k:<9} = {prefs.get(k, '(未设置)')} # {desc}")+ for i, n in enumerate(prefs.get("notes", []), 1):+ print(f"说明 {i}: {n}")+ return 0+++def cmd_memory(args) -> int:+ from .memory import export_labels, summary_lines++ if args.export_labels:+ n = export_labels(Path(args.export_labels))+ print(f"已导出 {n} 条视频的纠正到 {args.export_labels}(先把 path 填好,再用 rea-video eval 评测)")+ return 0+ print("\n".join(summary_lines()))+ return 0+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(prog="rea-video", description="逆向拆解视频:逐镜头判断实拍 / AI 生成 / 代码渲染 / 混合,并生成复刻方案")+ ap.add_argument("-v", "--verbose", action="store_true")+ ap.add_argument("--env-file", help="额外的 .env(例如 capsule-cinema/.env,用于 VLM 配置)")+ sub = ap.add_subparsers(dest="cmd", required=True)++ d = sub.add_parser("decompose", help="拆解一条视频")+ d.add_argument("video")+ d.add_argument("-o", "--out")+ d.add_argument("--vlm", action="store_true", help="启用多模态大模型(VLM)看画面逐镜判断;建议开,不开也能跑,只是实拍/AI/3D 的区分更弱")+ d.add_argument("--no-vlm", action="store_true", help="本次不开 VLM(覆盖 prefs 里的 vlm=on)")+ d.add_argument("--no-whole", action="store_true", help="跳过整片结构/文案 VLM 分析")+ d.add_argument("--no-ocr", action="store_true")+ d.add_argument("--workers", type=int, default=3)+ d.add_argument("--engine", help="复刻计划使用的 capsule-cinema 视频引擎(默认 prefs 里的 engine,否则 seedance2.0)")+ d.add_argument("--meta", help='平台元数据 JSON,例如 {"music": {"title": "xx", "author": "yy", "is_original": false, "popular": true}}')+ d.add_argument("--no-stems", action="store_true", help="不做人声/配乐分离(默认会输出 stems/original.wav、vocals.wav、music.wav)")+ d.set_defaults(func=cmd_decompose)++ st = sub.add_parser("stems", help="只把声音剥离成 原声 / 人声 / 配乐 三条轨")+ st.add_argument("video")+ st.add_argument("-o", "--out")+ st.set_defaults(func=cmd_stems)++ p = sub.add_parser("probe", help="只看容器元数据/来源线索")+ p.add_argument("video")+ p.add_argument("--tags", action="store_true")+ p.set_defaults(func=cmd_probe)++ e = sub.add_parser("eval", help="在带标注的样本集上评测拆解准确率")+ e.add_argument("labels", help="labels.yaml")+ e.add_argument("-o", "--out", default="out/eval")+ e.add_argument("--vlm", action="store_true")+ e.add_argument("--no-ocr", action="store_true")+ e.add_argument("--fresh", action="store_true", help="不复用已有拆解结果")+ e.add_argument("--only", default="", help="只重新拆解这些 id(逗号分隔),其余复用缓存并重新分类")+ e.add_argument("--stems", action="store_true", help="对带音频真值的样本做人声分离,并在干声上重测唱/说")+ e.set_defaults(func=cmd_eval)++ c = sub.add_parser("capsule", help="导出 capsule-cinema 的视频分析 JSON(供生成胶囊草稿)")+ c.add_argument("breakdown")+ c.add_argument("-o", "--out")+ c.set_defaults(func=cmd_capsule)++ r = sub.add_parser("remake-plan", help="为 AI 类镜头生成 capsule-cinema 复刻任务")+ r.add_argument("breakdown")+ r.add_argument("--capsule-root", default=DEFAULT_CAPSULE_ROOT)+ r.add_argument("--engine", help="默认 prefs 里的 engine,否则 seedance2.0")+ r.add_argument("--mode", default="first_last_frame", choices=["first_last_frame", "image_to_video", "text_to_video"])+ r.add_argument("--labels", default="", help="只复刻这些底层类别(逗号分隔),默认 ai_video,cg_3d,live_action,avatar")+ r.set_defaults(func=cmd_remake_plan)++ a = sub.add_parser("assemble", help="把复刻结果按原时间线拼回,并输出对比视频")+ a.add_argument("breakdown")+ a.add_argument("results", help="run_remake.py 输出的 results.json")+ a.add_argument("-o", "--out")+ a.set_defaults(func=cmd_assemble)++ t = sub.add_parser("tiles", help="按时间抽帧拼图,近距离检查某一段(agent 复核用)")+ t.add_argument("video")+ t.add_argument("--start", type=float, default=0.0)+ t.add_argument("--end", type=float)+ t.add_argument("--every", type=float, default=0.5)+ t.add_argument("--cols", type=int, default=6)+ t.add_argument("--cell", type=int, default=320)+ t.add_argument("--max", type=int, default=48)+ t.add_argument("-o", "--out", default="out/tiles.jpg")+ t.set_defaults(func=cmd_tiles)++ sm = sub.add_parser("summary", help="紧凑打印拆解结果(低置信镜头会被标出来)")+ sm.add_argument("breakdown")+ sm.set_defaults(func=cmd_summary)++ rv = sub.add_parser("review", help="能看图的 agent 当 VLM:生成逐镜看图任务和答案模板")+ rv.add_argument("out_dir", help="decompose 的输出目录")+ rv.add_argument("--force", action="store_true", help="覆盖已有的 review_answers.json")+ rv.set_defaults(func=cmd_review)++ ar = sub.add_parser("apply-review", help="把 agent 看图的答案并入结论,重写 breakdown.json 和报告")+ ar.add_argument("out_dir")+ ar.add_argument("answers", nargs="?", help="答案文件(默认 <out_dir>/review_answers.json)")+ ar.add_argument("--by", help="复核者名字(写进报告)")+ ar.set_defaults(func=cmd_apply_review)++ co = sub.add_parser("correct", help="用户指出判错:改正这条视频的结论,并记入记忆(以后同类镜头会提示复核)")+ co.add_argument("out_dir", help="decompose 的输出目录")+ co.add_argument("--shots", help="镜头编号,逗号分隔(如 3,5 或 shot_003),all 表示整条;也可用 --start/--end 指定时间段")+ co.add_argument("--start", type=float)+ co.add_argument("--end", type=float)+ co.add_argument("--label", help="正确的底层类别:" + "、".join(["live_action", "ai_video", "avatar", "cg_3d", "code_render", "screen_capture", "still_motion", "static_hold"]))+ co.add_argument("--real", choices=["yes", "no"], help="是否用了用户真实素材")+ co.add_argument("--note", help="用户的原话或理由,例如「这是定格动画,不是 AI」")+ co.set_defaults(func=cmd_correct)++ pf = sub.add_parser("prefs", help="查看 / 设置用户偏好(默认引擎、是否开 VLM、VLM 配置文件、复核者、自由文字说明)")+ pf.add_argument("key", nargs="?")+ pf.add_argument("value", nargs="?")+ pf.add_argument("--unset", action="store_true")+ pf.add_argument("--note", help="追加一条给 agent 看的偏好说明,例如「报告尽量短」")+ pf.add_argument("--remove-note", type=int, metavar="N")+ pf.set_defaults(func=cmd_prefs)++ me = sub.add_parser("memory", help="看记住了什么:偏好、常见纠正类型;可导出为评测样本")+ me.add_argument("--export-labels", metavar="YAML")+ me.set_defaults(func=cmd_memory)++ args = ap.parse_args(argv)+ setup_logging(args.verbose)+ _env(args)+ return args.func(args)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/rea_video/evaluate.py b/rea_video/evaluate.pynew file mode 100644index 0000000..4e7dd2f--- /dev/null+++ b/rea_video/evaluate.py@@ -0,0 +1,182 @@+"""Evaluate decomposition accuracy against labelled videos (eval/labels.yaml)."""+from __future__ import annotations++import os+from pathlib import Path++import yaml++from .classify import LABELS+from .pipeline import decompose, finalize+from .util import LOG, read_json, round_floats, write_json+++def _expand(path: str) -> str:+ root = os.getenv("CAPSULE_CINEMA_ROOT", str(Path.home() / "code/github/capsule-cinema"))+ p = os.path.expanduser(path.replace("${CAPSULE}", root))+ if not os.path.isabs(p): # relative paths are relative to the repo root+ p = str(Path(__file__).resolve().parents[1] / p)+ return p+++def _accept(label) -> set[str]:+ return set(label) if isinstance(label, list) else {label}+++def gt_at(entry: dict, t: float) -> set[str] | None:+ if "segments" in entry:+ for a, b, lab in entry["segments"]:+ if a <= t < b:+ return _accept(lab)+ return None+ if "label" not in entry: # audio-only entry+ return None+ return _accept(entry["label"])+++def real_at(entry: dict, t: float) -> bool | None:+ rm = entry.get("real_material")+ if rm is None:+ return None+ if isinstance(rm, bool):+ return rm+ for a, b, v in rm:+ if a <= t < b:+ return bool(v)+ return None+++def audio_check(gt: dict, b: dict) -> dict:+ a = b.get("audio", {})+ out = {}+ if "voice" in gt:+ out["voice"] = bool(a.get("voice", {}).get("present")) == bool(gt["voice"])+ if "music" in gt:+ out["music"] = bool(a.get("music", {}).get("present")) == bool(gt["music"])+ if "sfx" in gt:+ n = len((b.get("audio_plan") or {}).get("sfx_merged", []))+ out["sfx"] = (n >= 3) == bool(gt["sfx"])+ if gt.get("bpm"):+ est = (a.get("music") or {}).get("tempo_bpm")+ cands = [est] + list((a.get("music") or {}).get("tempo_alternatives", [])) if est else []+ out["bpm"] = any(abs(c - gt["bpm"]) / gt["bpm"] < 0.04 for c in cands)+ 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("key"):+ k = (a.get("music") or {}).get("key") or {}+ out["key"] = f"{k.get('tonic')} {k.get('mode')}" == gt["key"]+ return out+++def boundary_f1(pred: list[float], gt: list[float], tol: float = 0.1) -> dict:+ used = set()+ tp = 0+ for p in pred:+ for i, g in enumerate(gt):+ if i not in used and abs(p - g) <= tol:+ used.add(i)+ tp += 1+ break+ prec = tp / len(pred) if pred else 1.0+ rec = tp / len(gt) if gt else 1.0+ f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0+ return {"precision": round(prec, 3), "recall": round(rec, 3), "f1": round(f1, 3)}+++def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = True, reuse: bool = True, only: set[str] | None = None,+ stems: bool = False) -> dict:+ spec = yaml.safe_load(labels_path.read_text(encoding="utf-8"))+ rows, confusion = [], {g: {p: 0.0 for p in LABELS} for g in LABELS}+ tot_dur = ok_dur = 0.0+ real_tot = real_ok = 0.0+ audio_hits: dict[str, list[bool]] = {}+ for entry in spec["videos"]:+ path = _expand(entry["path"])+ if not Path(path).is_file():+ LOG.warning("skip %s: missing %s", entry["id"], path)+ continue+ vout = out / entry["id"]+ bfile = vout / "breakdown.json"+ if (not only or entry["id"] not in only) and reuse and bfile.is_file() and (not use_vlm or read_json(bfile)["analysis"]["vlm"].get("used")):+ b = read_json(bfile)+ from .media import video_info+ from .probe import provenance++ b["provenance"] = {k: v for k, v in provenance(video_info(path)).items() if k != "tags"} # signatures evolve+ if b["source"].get("has_audio"): # audio analysis is cheap: always redo with current code+ from .audio import analyze_audio++ marks = [t for s in b["shots"] for t in s.get("beats", [])]+ b["audio"] = round_floats(analyze_audio(path, [s["start"] for s in b["shots"][1:]], marks))+ from .sound_source import per_clip_audio++ b["per_clip_audio"] = per_clip_audio(path, [s["start"] for s in b["shots"][1:]], b["source"]["duration"])+ if stems and entry.get("audio"):+ from .audio import refine_with_stems+ from .stems import extract_stems++ voc = vout / "stems" / "vocals.wav"+ if not voc.is_file():+ b["stems"] = extract_stems(path, vout)+ if voc.is_file():+ refine_with_stems(b["audio"], str(voc))+ b = finalize(b, vout) # re-classify with the current rules+ else:+ b = decompose(path, vout, use_vlm=use_vlm, ocr=ocr, whole_vlm=False, stems=stems and bool(entry.get("audio")), memory=False)+ v_tot = v_ok = 0.0+ m_tot = m_ok = 0.0+ shots = []+ for s in b["shots"]:+ mid = (s["start"] + s["end"]) / 2+ acc = gt_at(entry, mid)+ if acc is None:+ continue+ pred = s["base"]["label"]+ hit = pred in acc+ v_tot += s["duration"]+ v_ok += s["duration"] if hit else 0.0+ primary = sorted(acc)[0] if len(acc) > 1 else next(iter(acc))+ confusion[primary if not hit else pred][pred] += s["duration"]+ shots.append({"shot": s["index"], "t": [s["start"], s["end"]], "pred": pred, "conf": s["base"]["confidence"],+ "gt": sorted(acc), "ok": hit})+ gt_real = real_at(entry, mid)+ if gt_real is not None:+ pred_real = bool((s.get("material") or {}).get("has_real_material"))+ m_tot += s["duration"]+ m_ok += s["duration"] if pred_real == gt_real else 0.0+ shots[-1]["real"] = {"gt": gt_real, "pred": pred_real}+ row = {"id": entry["id"], "accuracy": round(v_ok / v_tot, 3) if v_tot else None, "seconds": round(v_tot, 2),+ "verdict": b["summary"]["verdict"], "shots": shots}+ if m_tot:+ row["real_material_accuracy"] = round(m_ok / m_tot, 3)+ real_tot += m_tot+ real_ok += m_ok+ if entry.get("audio"):+ row["audio"] = audio_check(entry["audio"], b)+ for k, v in row["audio"].items():+ audio_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"):+ srcs = {s["base"].get("image_source") for s in b["shots"]}+ row["image_source_ok"] = entry["image_source"] in srcs+ rows.append(row)+ tot_dur += v_tot+ ok_dur += v_ok+ LOG.info("%-28s acc=%s %s", entry["id"], row["accuracy"], b["summary"]["verdict"][:80])+ summary = {"videos": len(rows), "duration_weighted_accuracy": round(ok_dur / tot_dur, 3) if tot_dur else None,+ "video_accuracy_mean": round(sum(r["accuracy"] for r in rows if r["accuracy"] is not None) / max(1, sum(r["accuracy"] is not None for r in rows)), 3),+ "per_video": {r["id"]: r["accuracy"] for r in rows if r["accuracy"] is not None}, "vlm": use_vlm}+ if real_tot:+ summary["real_material_accuracy"] = round(real_ok / real_tot, 3)+ 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()}+ 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)+ result = {"summary": summary, "rows": rows,+ "confusion_seconds": {g: {p: round(v, 1) for p, v in ps.items() if v} for g, ps in confusion.items() if any(ps.values())}}+ write_json(out / "eval_result.json", result)+ return resultdiff --git a/rea_video/features.py b/rea_video/features.pynew file mode 100644index 0000000..7595aa8--- /dev/null+++ b/rea_video/features.py@@ -0,0 +1,278 @@+"""Per-shot forensic features.++Spatial : sensor-like noise, perfectly flat blocks, palette size, axis-aligned edges,+ saturation — separate rendered graphics from photographic images.+Temporal : duplicate frames (and their periodicity, e.g. 24→30 fps conversion typical of+ generator output), exactly-unchanged pixels, temporal noise in still areas.+Motion : global similarity-transform fit (zoom/pan/rotate) with RANSAC, residual+ parallax and local motion — detects "still image + push/pan" (Ken Burns),+ tripod vs handheld, and how much of the frame actually moves."""+from __future__ import annotations++import math+from dataclasses import dataclass, field++import cv2+import numpy as np++from .media import VideoInfo, iter_frames+from .shots import Shot++ANALYSIS_W = 480+_IMMERKAER = np.array([[1, -2, 1], [-2, 4, -2], [1, -2, 1]], dtype=np.float32)+++@dataclass+class ShotSamples:+ frames: list[np.ndarray] = field(default_factory=list) # sampled BGR frames (ANALYSIS_W)+ frame_times: list[float] = field(default_factory=list)+ pair_mad: list[float] = field(default_factory=list) # mean |diff| for every consecutive pair+ pair_zero: list[float] = field(default_factory=list) # fraction of exactly-unchanged pixels+ pair_tnoise: list[float] = field(default_factory=list) # median |diff| over near-still pixels+ motion: list[dict] = field(default_factory=list) # per sampled pair global-motion fit+ sharpness: list[float] = field(default_factory=list) # Laplacian variance of every frame+++def noise_sigma(gray: np.ndarray) -> float:+ """Immerkær fast noise estimate (std of additive noise), computed on non-edge pixels."""+ g = gray.astype(np.float32)+ h, w = g.shape+ if h < 8 or w < 8:+ return 0.0+ conv = np.abs(cv2.filter2D(g, -1, _IMMERKAER))[1:-1, 1:-1]+ gx = cv2.Sobel(g, cv2.CV_32F, 1, 0)[1:-1, 1:-1]+ gy = cv2.Sobel(g, cv2.CV_32F, 0, 1)[1:-1, 1:-1]+ mag = np.hypot(gx, gy)+ mask = mag < np.percentile(mag, 60) # ignore edges/texture, keep smooth areas+ if mask.sum() < 100:+ mask = np.ones_like(mag, dtype=bool)+ return float(math.sqrt(math.pi / 2.0) * conv[mask].mean() / 6.0)+++def spatial_features(bgr: np.ndarray) -> dict:+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)+ h, w = gray.shape+ # flat 8x8 blocks+ bh, bw = h // 8, w // 8+ 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())+ # 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]+ counts = np.bincount(codes.ravel(), minlength=4096)+ counts = np.sort(counts)[::-1]+ cum = np.cumsum(counts) / max(1, counts.sum())+ palette95 = int(np.searchsorted(cum, 0.95) + 1)+ # edges and their orientation+ gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3)+ gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3)+ mag = np.hypot(gx, gy)+ strong = mag > 80+ edge_density = float(strong.mean())+ if strong.sum() > 50:+ ang = np.degrees(np.arctan2(gy[strong], gx[strong])) % 90.0+ axis = float(((ang < 4) | (ang > 86)).mean())+ else:+ axis = 0.0+ hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)+ return {+ "noise_sigma": noise_sigma(gray),+ "flat_ratio": flat_ratio,+ "palette95": palette95,+ "edge_density": edge_density,+ "axis_edge_ratio": axis,+ "saturation": float(hsv[..., 1].mean() / 255.0),+ "luma": float(gray.mean()),+ "contrast": float(gray.std()),+ }+++def global_motion(prev: np.ndarray, nxt: np.ndarray) -> dict | None:+ """Fit a similarity transform prev->nxt from tracked corners."""+ pts = cv2.goodFeaturesToTrack(prev, maxCorners=300, qualityLevel=0.01, minDistance=7, blockSize=7)+ if pts is None or len(pts) < 15:+ return None+ nxt_pts, st, _ = cv2.calcOpticalFlowPyrLK(prev, nxt, pts, None, winSize=(21, 21), maxLevel=3)+ back, st2, _ = cv2.calcOpticalFlowPyrLK(nxt, prev, nxt_pts, None, winSize=(21, 21), maxLevel=3)+ if nxt_pts is None or back is None:+ return None+ fb = np.linalg.norm(pts - back, axis=2).ravel()+ ok = (st.ravel() == 1) & (st2.ravel() == 1) & (fb < 1.0)+ p0, p1 = pts.reshape(-1, 2)[ok], nxt_pts.reshape(-1, 2)[ok]+ if len(p0) < 12:+ return None+ flow = np.linalg.norm(p1 - p0, axis=1)+ M, _inl = cv2.estimateAffinePartial2D(p0, p1, method=cv2.RANSAC, ransacReprojThreshold=1.0, maxIters=2000)+ if M is None:+ return None+ pred = p0 @ M[:, :2].T + M[:, 2]+ resid = np.linalg.norm(pred - p1, axis=1)+ a, b = float(M[0, 0]), float(M[1, 0])+ # photometric residual after warping prev onto next: a still image being zoomed/panned+ # leaves almost nothing; animated content leaves blocks with real change+ h, w = prev.shape+ warped = cv2.warpAffine(prev, M, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)+ mh, mw = int(h * 0.08), int(w * 0.08)+ diff = cv2.absdiff(warped, nxt)[mh:h - mh, mw:w - mw].astype(np.float32)+ bh, bw = diff.shape[0] // 16, diff.shape[1] // 16+ blocks = diff[: bh * 16, : bw * 16].reshape(bh, 16, bw, 16).mean(axis=(1, 3)) if bh and bw else diff+ return {+ "comp_mad": float(diff.mean()),+ "comp_block_p98": float(np.percentile(blocks, 98)),+ "scale": math.hypot(a, b),+ "rot_deg": math.degrees(math.atan2(b, a)),+ "tx": float(M[0, 2]),+ "ty": float(M[1, 2]),+ "flow_median": float(np.median(flow)),+ "flow_p90": float(np.percentile(flow, 90)),+ "resid_median": float(np.median(resid)),+ "inlier_ratio": float((resid < 0.5).mean()),+ "local_ratio": float((resid > 1.5).mean()),+ "n_points": int(len(p0)),+ }+++def collect_samples(path: str, info: VideoInfo, shot: Shot, n_frames: int = 16, n_motion: int = 24) -> ShotSamples:+ total = shot.end_frame - shot.start_frame+ trim = 2 if total > 12 else 0 # skip frames touching the transition+ lo, hi = trim, max(trim + 1, total - trim)+ usable = hi - lo+ keep = set(np.linspace(lo, hi - 1, num=min(n_frames, usable)).round().astype(int).tolist())+ motion_idx = set(np.linspace(lo + 1, hi - 1, num=min(n_motion, max(usable - 1, 0))).round().astype(int).tolist()) if usable > 1 else set()+ out = ShotSamples()+ prev_gray = None+ for i, bgr in enumerate(iter_frames(path, info, ANALYSIS_W, start=shot.start, duration=shot.duration)):+ if i >= total:+ break+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)+ if lo <= i < hi:+ out.sharpness.append(float(cv2.Laplacian(gray, cv2.CV_32F).var()))+ if i in keep:+ out.frames.append(bgr.copy())+ out.frame_times.append(shot.start + i / shot.fps)+ if prev_gray is not None and i - 1 >= lo:+ d = cv2.absdiff(gray, prev_gray)+ out.pair_mad.append(float(d.mean()))+ out.pair_zero.append(float((d == 0).mean()))+ still = d < 6+ out.pair_tnoise.append(float(np.mean(d[still])) if still.any() else 0.0)+ if i in motion_idx:+ m = global_motion(prev_gray, gray)+ if m is not None:+ out.motion.append(m)+ prev_gray = gray+ return out+++def _periodicity(flags: list[bool]) -> dict:+ idx = [i for i, f in enumerate(flags) if f]+ if len(idx) < 3:+ return {"period": None, "regularity": 0.0}+ gaps = np.diff(idx)+ vals, cnt = np.unique(gaps, return_counts=True)+ period = int(vals[np.argmax(cnt)])+ regularity = float(cnt.max() / len(gaps))+ return {"period": period, "regularity": regularity}+++def shot_features(samples: ShotSamples, fps: float) -> dict:+ sp = [spatial_features(f) for f in samples.frames] or [spatial_features(np.zeros((32, 32, 3), np.uint8))]+ agg = {k: float(np.median([s[k] for s in sp])) for k in sp[0]}+ agg["palette95"] = int(agg["palette95"])++ mad = np.array(samples.pair_mad) if samples.pair_mad else np.zeros(1)+ dup = mad < 0.15+ moving_pairs = mad > 0.6+ per = _periodicity(dup.tolist())+ agg.update({+ "pair_mad_median": float(np.median(mad)),+ "pair_mad_p90": float(np.percentile(mad, 90)),+ "dup_ratio": float(dup.mean()),+ "dup_period": per["period"],+ "dup_regularity": per["regularity"],+ "moving_pair_ratio": float(moving_pairs.mean()),+ "zero_pixel_ratio": float(np.median(samples.pair_zero)) if samples.pair_zero else 0.0,+ "temporal_noise": float(np.median(samples.pair_tnoise)) if samples.pair_tnoise else 0.0,+ "spatial_std_noise": float(np.std([s["noise_sigma"] for s in sp])),+ })+ # change between first and last sampled frame (does the shot evolve at all?)+ if len(samples.frames) >= 2:+ a = cv2.cvtColor(samples.frames[0], cv2.COLOR_BGR2GRAY).astype(np.float32)+ b = cv2.cvtColor(samples.frames[-1], cv2.COLOR_BGR2GRAY).astype(np.float32)+ agg["start_end_mad"] = float(np.abs(a - b).mean())+ else:+ agg["start_end_mad"] = 0.0+ agg.update(resampling_signature(samples.sharpness))+ agg.update(motion_summary(samples.motion, fps))+ return agg+++def resampling_signature(sharp: list[float]) -> dict:+ """Frame-rate conversion / interpolation leaves a periodic sharpness pattern (blended or+ synthesized in-between frames are softer). Native camera capture does not."""+ s = np.asarray(sharp, dtype=np.float64)+ if len(s) < 24 or s.mean() <= 0:+ return {"sharp_alt": 0.0, "sharp_period": None, "sharp_period_ac": 0.0}+ alt = float(np.mean(np.abs(s[1:-1] - (s[:-2] + s[2:]) / 2)) / s.mean())+ d = s - np.convolve(s, np.ones(9) / 9, mode="same")+ d = d[5:-5]+ best_lag, best_ac = None, 0.0+ for k in range(2, 7):+ if len(d) > k + 8 and d[:-k].std() > 0 and d[k:].std() > 0:+ ac = float(np.corrcoef(d[:-k], d[k:])[0, 1])+ if ac > best_ac:+ best_lag, best_ac = k, ac+ return {"sharp_alt": alt, "sharp_period": best_lag, "sharp_period_ac": best_ac}+++def motion_summary(motion: list[dict], fps: float) -> dict:+ if not motion:+ return {"motion_pairs": 0, "kenburns_score": 0.0, "camera": "unknown"}+ arr = {k: np.array([m[k] for m in motion]) for k in motion[0]}+ zoom_per_s = (np.median(arr["scale"]) - 1.0) * fps+ tx_s, ty_s = np.median(arr["tx"]) * fps, np.median(arr["ty"]) * fps+ speed = float(math.hypot(tx_s, ty_s))+ flow_med = float(np.median(arr["flow_median"]))+ resid = float(np.median(arr["resid_median"]))+ inl = float(np.median(arr["inlier_ratio"]))+ local = float(np.median(arr["local_ratio"]))+ # consistency of per-pair translation: smooth camera -> consistent; handheld -> noisy+ tx, ty = arr["tx"], arr["ty"]+ mag = np.hypot(tx, ty)+ trans_cv = float(np.std(mag) / (np.mean(mag) + 1e-6))+ sign_flips = float((np.sign(tx[1:]) != np.sign(tx[:-1])).mean()) if len(tx) > 2 else 0.0+ moving = abs(zoom_per_s) > 0.004 or speed > 1.5+ # Ken Burns: the entire frame moves as one rigid plane (zoom/pan) with no parallax or local motion+ comp_p98 = float(np.median(arr["comp_block_p98"])) if "comp_block_p98" in arr else 0.0+ kb = 0.0+ if moving and flow_med > 0.08:+ kb = float(np.clip((inl - 0.80) / 0.17, 0, 1) * np.clip((0.35 - resid) / 0.25, 0, 1) * np.clip((0.06 - local) / 0.05, 0, 1)+ * np.clip(1.2 - trans_cv, 0, 1) ** 0.5 * np.clip((9.0 - comp_p98) / 4.0, 0, 1))+ if flow_med < 0.05 and local < 0.02:+ camera = "static"+ elif not moving:+ camera = "static_with_subject_motion" if local > 0.05 else "static"+ elif kb > 0.5:+ camera = "planar_zoom_pan"+ elif sign_flips > 0.45 and trans_cv > 0.8:+ camera = "handheld_like"+ else:+ camera = "smooth_move"+ return {+ "motion_pairs": len(motion),+ "zoom_per_s": float(zoom_per_s),+ "pan_px_per_s": speed,+ "pan_dir_deg": float(math.degrees(math.atan2(ty_s, tx_s))) if speed > 0 else 0.0,+ "rot_deg_per_s": float(np.median(arr["rot_deg"]) * fps),+ "flow_median": flow_med,+ "flow_p90": float(np.median(arr["flow_p90"])),+ "rigid_inlier_ratio": inl,+ "rigid_residual": resid,+ "local_motion_ratio": local,+ "trans_cv": trans_cv,+ "sign_flip_rate": sign_flips,+ "kenburns_score": kb,+ "comp_block_p98": comp_p98,+ "camera": camera,+ }diff --git a/rea_video/integrations/__init__.py b/rea_video/integrations/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.pynew file mode 100644index 0000000..5c35e74--- /dev/null+++ b/rea_video/integrations/capsule_cinema.py@@ -0,0 +1,246 @@+"""Bridge to capsule-cinema (https://github.com/JuneYaooo/cheap-claude-video).++1. export_capsule_analysis(): converts a rea-video breakdown into the analyzer JSON that+ capsule-cinema's video->capsule pipeline expects (scripts/analyze_video_to_capsule.py),+ so a reusable capsule draft can be produced from an accurate, evidence-backed breakdown.+2. build_remake_jobs(): turns AI-replicable shots (AI video / 3D / live action / avatar)+ into generation jobs for capsule-cinema's UniversalVideoGenerationTool, using the original+ shot's first/last frames and the VLM-derived prompt. Still-image shots are rebuilt locally.+"""+from __future__ import annotations++import re+from datetime import datetime+from pathlib import Path++from ..classify import LABEL_ZH+from ..util import fmt_time, write_json++FORMAT_MAP = {"口播": "short_video", "剧情": "story", "商品展示": "product_showcase", "知识讲解": "explainer",+ "MV": "music_mv", "混剪": "short_video"}+CAMERA_ZH = {"static": "固定机位", "static_with_subject_motion": "固定机位、主体运动", "planar_zoom_pan": "整图推拉/平移",+ "handheld_like": "手持晃动", "smooth_move": "平滑运镜", "unknown": "未知"}+AI_LABELS = ("ai_video", "cg_3d", "live_action", "avatar")+++def _aspect(b: dict) -> str:+ ar = b["source"].get("aspect_ratio", "unknown")+ return ar if ar in ("9:16", "16:9", "1:1") else "unknown"+++def _mmss(t: float) -> str:+ return fmt_time(t)+++def _shot_copy(s: dict) -> str:+ texts = []+ for tr in s.get("text", {}).get("tracks", []):+ if tr["kind"] in ("subtitle", "title"):+ texts += tr["texts"]+ v = s.get("vlm") or {}+ texts += v.get("overlay_text", []) or []+ seen, out = set(), []+ for t in texts:+ if t and t not in seen:+ seen.add(t)+ out.append(t)+ return " / ".join(out[:6])+++def export_capsule_analysis(b: dict, out_path: Path) -> Path:+ s = b["summary"]+ whole = b.get("whole_video_vlm") or {}+ shots = b["shots"]+ mix_txt = "、".join(f"{m['label_zh']} {m['ratio']:.0%}" for m in s["production_mix"])+ segments = []+ literals: list[str] = []+ for sh in shots:+ v = sh.get("vlm") or {}+ f = sh["features"]+ copy = _shot_copy(sh)+ literals += [t for t in copy.split(" / ") if len(t) >= 2]+ motion = CAMERA_ZH.get(f.get("camera", "unknown"), "")+ if sh["base"]["label"] == "still_motion":+ motion += f";缩放 {f.get('zoom_per_s', 0) * 100:+.1f}%/s,平移 {f.get('pan_px_per_s', 0):.0f}px/s"+ segments.append({+ "start_time": _mmss(sh["start"]), "end_time": _mmss(sh["end"]),+ "beat": f"镜头 {sh['index']}({sh['duration']:.1f}s)",+ "visuals": f"[{sh['base']['label_zh']} {sh['base']['confidence']:.0%}] " + (v.get("description") or sh["verdict"]),+ "material": (sh.get("material") or {}).get("origin_zh", ""),+ "motion": motion, "copy": copy,+ "audio": "",+ "reuse_lesson": f"该位置用「{LABEL_ZH[sh['base']['label']]}」制作,时长约 {sh['duration']:.1f}s,{motion}",+ })+ # prefer the VLM's narrative beats (with copy/audio) and attach the production method of+ # the shots they overlap; fall back to one segment per shot+ wsegs = [w for w in (whole.get("segments") or []) if isinstance(w, dict)]+ if wsegs:+ merged = []+ for w in wsegs:+ try:+ a, z = float(w.get("start", 0)), float(w.get("end", 0))+ except (TypeError, ValueError):+ continue+ over = [sh for sh in shots if sh["end"] > a and sh["start"] < z] or shots[:1]+ kinds = "、".join(sorted({sh["base"]["label_zh"] for sh in over}))+ merged.append({"start_time": _mmss(a), "end_time": _mmss(z), "beat": str(w.get("beat", "")),+ "visuals": f"[{kinds}] " + ";".join(((sh.get("vlm") or {}).get("description") or sh["verdict"]) for sh in over[:3]),+ "motion": "、".join(sorted({CAMERA_ZH.get(sh["features"].get("camera", "unknown"), "") for sh in over})),+ "copy": str(w.get("copy", "")), "audio": str(w.get("audio", "")),+ "reuse_lesson": f"这一段({w.get('beat', '')})用「{kinds}」实现"})+ if w.get("copy"):+ literals.append(str(w["copy"]))+ if merged:+ segments = merged+ lens = [x["duration"] for x in shots]+ structure_rules = [+ f"全片约 {s['duration']:.0f}s,{s['shots']} 个镜头,平均每镜 {s['avg_shot_s']}s(最短 {min(lens):.1f}s,最长 {max(lens):.1f}s)",+ f"转场以 {max(s['transitions'], key=s['transitions'].get)} 为主:" + "、".join(f"{k}×{v}" for k, v in s["transitions"].items()),+ ]+ if whole.get("hook"):+ structure_rules.append(f"开头钩子:{whole['hook']}")+ visual_rules = [f"底层画面构成:{mix_txt}"]+ for m in s["production_mix"]:+ if m["label"] == "ai_video":+ visual_rules.append("AI 镜头先定首帧(或首尾帧)再生成视频,单镜 4–8 秒,同一角色跨镜头用参考图保持一致")+ if m["label"] == "code_render":+ visual_rules.append("文字、图表、界面类画面用代码/模板渲染,不交给生成模型")+ if m["label"] in ("still_motion", "static_hold"):+ visual_rules.append("部分镜头是静态图(推拉或定格),用图片 + 本地动效即可,不必生成视频")+ rm = s.get("real_material") or {}+ real_inputs: list[str] = []+ if rm.get("shots"):+ kinds = "、".join(rm.get("kinds", {}).keys())+ visual_rules.append(f"引入用户真实素材({kinds}):约 {rm['ratio']:.0%} 的时长使用真实截图/照片/实拍,"+ "这些画面每期需要用户提供新素材,不能用模型生成替代")+ kind_input = {"界面截图": "screenshots", "录屏素材": "screen_recordings", "实拍视频素材": "real_footage",+ "照片/图片素材": "photos", "真实照片": "photos", "嵌入视频片段": "video_clips", "商品实拍图": "product_photos",+ "Logo/品牌标识": "brand_logo"}+ real_inputs = sorted({kind_input.get(k, "real_assets") for k in rm.get("kinds", {})})+ styles = sorted({(sh.get("vlm") or {}).get("style", "") for sh in shots} - {""})+ if styles:+ visual_rules.append("画风关键词:" + ";".join(styles[:4]))+ copy_rules = []+ if "subtitle" in s.get("overlay_kinds", []) or (whole.get("subtitles") or {}).get("present"):+ copy_rules.append("字幕由后期代码叠加(不要让模型在画面里生成文字)" + (f":{whole['subtitles'].get('style')}" if whole.get("subtitles", {}).get("style") else ""))+ if "title" in s.get("overlay_kinds", []):+ copy_rules.append("顶部有固定标题条,全片保持")+ audio_rules = []+ a = b.get("audio", {})+ n = whole.get("narration") or {}+ if n.get("type"):+ audio_rules.append(f"旁白:{n.get('type')} {n.get('voice', '')}".strip())+ elif a.get("speech_likely"):+ audio_rules.append("有人声旁白/对白")+ if (whole.get("music") or {}).get("style"):+ audio_rules.append(f"BGM:{whole['music']['style']}")+ elif a.get("music_likely"):+ audio_rules.append(f"有背景音乐,约 {a.get('tempo_bpm')} BPM")+ if a.get("beat_synced_edit"):+ audio_rules.append("切镜卡在音乐节拍上")+ mu = a.get("music") or {}+ srcs = b.get("sound_sources") or {}+ if srcs.get("music"):+ audio_rules.append(f"BGM 来源:{srcs['music']['source_zh']}(倾向 {srcs['music']['leaning']});"+ + ("MV 类内容:歌是按内容定制的,每期要重新生成歌" if (srcs.get("format_context") or {}).get("music_mv") else "垫底配乐:按风格/BPM 选曲即可"))+ if mu.get("present") and mu.get("tempo_bpm"):+ key = mu.get("key") or {}+ audio_rules.append(f"BGM 约 {mu['tempo_bpm']} BPM" + (f"、{key.get('tonic')} {key.get('mode')}" if key else "")+ + ";有音高的音效可以对齐 BGM 调性")+ sfx = (b.get("audio_plan") or {}).get("sfx_merged", [])+ if sfx:+ types: dict[str, int] = {}+ for e in sfx:+ types[str(e.get("type", "other"))] = types.get(str(e.get("type", "other")), 0) + 1+ audio_rules.append("音效:" + "、".join(f"{k}×{v}" for k, v in sorted(types.items(), key=lambda kv: -kv[1]))+ + ",按画面事件(切镜/文字弹出/动作)逐点摆放")+ motion_rules = sorted({CAMERA_ZH.get(sh["features"].get("camera", "unknown"), "") for sh in shots} - {""})+ quality_rules = [+ {"id": "rea_production_mix", "type": "manual_qc_required", "severity": "warning",+ "rule": f"复刻时保持各镜头的制作方式与原片一致({mix_txt})"},+ {"id": "rea_ai_artifacts", "type": "manual_qc_required", "severity": "warning",+ "rule": "AI 镜头逐个检查手部、文字、主体形变与闪烁"},+ ]+ content_scope = {+ "schema_version": "capsule.content_scope.v1",+ "series_fixed": ["format_rules", "production_mix", "shot_rhythm", "overlay_style"],+ "episode_variable": ["topic", "subject_facts", "episode_copy", "characters_or_products"] + (["user_supplied_real_assets"] if rm.get("shots") else []),+ "forbidden_reusable_literals": sorted({t.strip() for t in literals if t.strip()}, key=str.casefold)[:80],+ "policies": {"allow_series_fixed_defaults": True, "forbid_episode_specific_defaults": True,+ "active_recipe_examples_must_use_placeholders": True, "current_run_input_may_reuse_literal": True},+ }+ # de-duplicate case-insensitively (capsule-cinema validator requires it)+ seen, uniq = set(), []+ for t in content_scope["forbidden_reusable_literals"]:+ if t.casefold() not in seen:+ seen.add(t.casefold())+ uniq.append(t)+ content_scope["forbidden_reusable_literals"] = uniq+ fmt = FORMAT_MAP.get(str(whole.get("format", "")), "other" if whole else "short_video")+ data = {+ "summary": whole.get("summary") or s["verdict"],+ "source_profile": {"likely_format": fmt, "aspect_ratio": _aspect(b), "target_platform": "", "primary_audience": ""},+ "segments": segments,+ "capsule_recipe": {+ "when_to_use": ["想复用这条参考视频的镜头节奏、制作方式组合与叠加层风格"],+ "when_not_to_use": ["需要与原片逐帧一致的商业复制(版权/肖像风险)"],+ "structure_rules": structure_rules, "copy_rules": copy_rules, "visual_rules": visual_rules,+ "audio_rules": audio_rules, "motion_rules": motion_rules, "quality_rules": quality_rules,+ "default_runtime": {"aspect_ratio": b["source"].get("aspect_ratio")},+ },+ "execution_strategy": {"mode": "review_required", "reason": "由 rea-video 自动逆向拆解生成,需要人工确认后再固化为配方",+ "deterministic_steps": [], "parameterized_inputs": ["topic", "reference_images"] + real_inputs,+ "episode_specific_values": [], "evidence": {"successful_runs": 0, "cross_topic_verified": False}},+ "content_scope": content_scope,+ "warnings": [] if b["analysis"]["vlm"].get("used") else ["未启用 VLM:镜头描述与文案较少,建议用 --vlm 重新拆解"],+ "rea_video": {"verdict": s["verdict"], "production_mix": s["production_mix"], "confidence": s["confidence"],+ "source": b["source"]["path"]},+ }+ write_json(out_path, data)+ return out_path+++def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path, engine: str = "seedance2.0",+ mode: str = "first_last_frame", labels: list[str] | None = None) -> Path:+ """Write jobs.json for integrations/capsule_cinema/run_remake.py.+ Output dirs live under <capsule_root>/output/ to satisfy capsule-cinema's output guard."""+ labels = labels or list(AI_LABELS)+ stamp = datetime.now().strftime("%Y%m%d_%H%M%S")+ slug = re.sub(r"[^A-Za-z0-9_-]+", "_", Path(b["source"]["filename"]).stem)[:40]+ run_dir = capsule_root / "output" / f"rea_remake_{slug}_{stamp}"+ jobs = []+ for sh in b["shots"]:+ lab = sh["base"]["label"]+ rep = sh["replication"]+ if lab in ("still_motion", "static_hold"):+ jobs.append({"shot": sh["index"], "id": sh["id"], "executor": "local_ffmpeg", "label": lab,+ "image": str((bdir / sh["assets"]["first_frame"]).resolve()), "duration": sh["duration"],+ "motion": rep.get("local", {}), "user_assets": rep.get("user_assets", [])})+ continue+ if lab not in labels or rep["executor"] != "capsule_cinema":+ jobs.append({"shot": sh["index"], "id": sh["id"], "executor": "keep_original", "label": lab,+ "reason": rep.get("note", ""), "user_assets": rep.get("user_assets", [])})+ continue+ cap = rep["capsule"]+ gen_type = mode if mode != "first_last_frame" or sh["duration"] >= 1.0 else "image_to_video"+ prompt = cap.get("prompt") or ((sh.get("vlm") or {}).get("description")) or ""+ if not prompt:+ prompt = f"保持参考图的画面、主体与风格,{CAMERA_ZH.get(sh['features'].get('camera', 'unknown'), '')},自然连贯的动作"+ params = {"prompt": prompt, "output_dir": str(run_dir / sh["id"]), "generation_type": gen_type,+ "engine": cap.get("engine", engine), "aspect_ratio": cap.get("aspect_ratio", "9:16"),+ "duration": cap.get("duration", 5)}+ first = str((bdir / sh["assets"]["first_frame"]).resolve())+ last = str((bdir / sh["assets"]["last_frame"]).resolve())+ if gen_type == "first_last_frame":+ params.update({"start_image_path": first, "end_image_path": last})+ elif gen_type == "image_to_video":+ params["image_path"] = first+ jobs.append({"shot": sh["index"], "id": sh["id"], "executor": "capsule_cinema", "label": lab,+ "tool": "UniversalVideoGenerationTool", "params": params, "trim_to": sh["duration"],+ "prompt_source": "vlm" if cap.get("prompt") else "fallback",+ "user_assets": rep.get("user_assets", []),+ "warning": "原镜头是真实素材:生成结果只是近似,建议换成你自己的素材" if rep.get("user_assets") else ""})+ out = bdir / "remake" / "jobs.json"+ write_json(out, {"breakdown": str((bdir / "breakdown.json").resolve()), "capsule_root": str(capsule_root),+ "run_dir": str(run_dir), "engine": engine, "mode": mode, "jobs": jobs})+ return outdiff --git a/rea_video/media.py b/rea_video/media.pynew file mode 100644index 0000000..4b3cf11--- /dev/null+++ b/rea_video/media.py@@ -0,0 +1,205 @@+"""FFmpeg/ffprobe wrappers. Frames are read through an ffmpeg rawvideo pipe so every+codec ffmpeg understands (h264/hevc/vp9/prores...) works the same on macOS and Linux."""+from __future__ import annotations++import json+import shutil+import subprocess+from dataclasses import dataclass+from pathlib import Path+from typing import Iterator++import numpy as np++from .util import LOG+++class MediaError(RuntimeError):+ pass+++_PASSTHROUGH: list[str] | None = None+++def passthrough_args() -> list[str]:+ """`-fps_mode passthrough` on ffmpeg >= 5.1, `-vsync passthrough` before that."""+ global _PASSTHROUGH+ if _PASSTHROUGH is None:+ try:+ out = subprocess.run(["ffmpeg", "-hide_banner", "-version"], capture_output=True, text=True).stdout+ import re as _re+ m = _re.search(r"ffmpeg version n?(\d+)\.(\d+)", out)+ major, minor = (int(m.group(1)), int(m.group(2))) if m else (7, 0)+ except OSError: # pragma: no cover+ major, minor = 7, 0+ _PASSTHROUGH = ["-fps_mode", "passthrough"] if (major, minor) >= (5, 1) else ["-vsync", "passthrough"]+ return list(_PASSTHROUGH)+++def require_tools() -> None:+ for tool in ("ffmpeg", "ffprobe"):+ if not shutil.which(tool):+ raise MediaError(f"{tool} not found on PATH")+++def ffprobe(path: str | Path) -> dict:+ cmd = ["ffprobe", "-v", "error", "-print_format", "json", "-show_format", "-show_streams", str(path)]+ try:+ out = subprocess.run(cmd, check=True, capture_output=True, text=True).stdout+ except subprocess.CalledProcessError as exc: # pragma: no cover - depends on file+ raise MediaError(f"ffprobe failed: {exc.stderr.strip()}") from exc+ return json.loads(out)+++def _ratio(value: str | None) -> float:+ if not value or value in ("0/0", "N/A"):+ return 0.0+ if "/" in value:+ a, b = value.split("/", 1)+ try:+ return float(a) / float(b) if float(b) else 0.0+ except ValueError:+ return 0.0+ try:+ return float(value)+ except ValueError:+ return 0.0+++@dataclass+class VideoInfo:+ path: str+ width: int+ height: int+ fps: float+ duration: float+ nb_frames: int+ vcodec: str+ has_audio: bool+ rotation: int+ raw: dict++ @property+ def aspect_ratio(self) -> str:+ w, h = (self.height, self.width) if self.rotation in (90, 270) else (self.width, self.height)+ if not w or not h:+ return "unknown"+ r = w / h+ for name, val in (("9:16", 9 / 16), ("3:4", 3 / 4), ("6:7", 6 / 7), ("1:1", 1.0), ("4:3", 4 / 3), ("16:9", 16 / 9), ("21:9", 21 / 9)):+ if abs(r - val) / val < 0.04:+ return name+ return f"{w}:{h}"+++def video_info(path: str | Path) -> VideoInfo:+ data = ffprobe(path)+ vstreams = [s for s in data.get("streams", []) if s.get("codec_type") == "video" and not s.get("disposition", {}).get("attached_pic")]+ if not vstreams:+ raise MediaError(f"no video stream in {path}")+ v = vstreams[0]+ fmt = data.get("format", {})+ fps = _ratio(v.get("avg_frame_rate")) or _ratio(v.get("r_frame_rate")) or 30.0+ duration = float(v.get("duration") or fmt.get("duration") or 0.0)+ nb = int(v.get("nb_frames") or 0) or int(round(duration * fps))+ rotation = 0+ for sd in v.get("side_data_list", []) or []:+ if "rotation" in sd:+ try:+ rotation = int(abs(float(sd["rotation"]))) % 360+ except (TypeError, ValueError):+ pass+ if "rotate" in (v.get("tags") or {}):+ try:+ rotation = int(v["tags"]["rotate"]) % 360+ except ValueError:+ pass+ has_audio = any(s.get("codec_type") == "audio" for s in data.get("streams", []))+ return VideoInfo(+ path=str(path), width=int(v.get("width") or 0), height=int(v.get("height") or 0), fps=fps,+ duration=duration, nb_frames=nb, vcodec=str(v.get("codec_name") or ""), has_audio=has_audio,+ rotation=rotation, raw=data,+ )+++def scaled_size(info: VideoInfo, width: int) -> tuple[int, int]:+ """Output size for an ffmpeg `scale=width:-2` (display orientation aware)."""+ w, h = info.width, info.height+ if info.rotation in (90, 270):+ w, h = h, w+ width = min(width, w) if w else width+ width -= width % 2+ height = int(round(h * width / w)) if w else width+ height -= height % 2+ return width, max(2, height)+++def iter_frames(+ path: str | Path,+ info: VideoInfo,+ width: int,+ start: float | None = None,+ duration: float | None = None,+ gray: bool = False,+) -> Iterator[np.ndarray]:+ """Yield decoded frames (BGR uint8, or gray if gray=True) at the requested width.+ Frames are passed through untouched (no fps resampling) so duplicate-frame+ statistics stay meaningful."""+ w, h = scaled_size(info, width)+ cmd = ["ffmpeg", "-v", "error", "-nostdin"]+ if start is not None and start > 0:+ cmd += ["-ss", f"{start:.4f}"]+ cmd += ["-i", str(path)]+ if duration is not None:+ cmd += ["-t", f"{max(duration, 0.01):.4f}"]+ pix = "gray" if gray else "bgr24"+ cmd += ["-an", "-sn", "-vf", f"scale={w}:{h}:flags=area", *passthrough_args(), "-f", "rawvideo", "-pix_fmt", pix, "-"]+ frame_bytes = w * h * (1 if gray else 3)+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ assert proc.stdout is not None+ count = 0+ try:+ while True:+ buf = proc.stdout.read(frame_bytes)+ if len(buf) < frame_bytes:+ break+ arr = np.frombuffer(buf, dtype=np.uint8)+ count += 1+ yield arr.reshape((h, w)) if gray else arr.reshape((h, w, 3))+ if count == 0:+ err = proc.stderr.read().decode(errors="ignore") if proc.stderr else ""+ if err.strip():+ raise MediaError(f"ffmpeg decoded no frames: {err.strip()[:300]}")+ finally:+ proc.stdout.close()+ proc.kill()+ proc.wait()+++def extract_frame(path: str | Path, t: float, out_path: str | Path, width: int | None = None) -> Path:+ out_path = Path(out_path)+ out_path.parent.mkdir(parents=True, exist_ok=True)+ vf = ["-vf", f"scale={width}:-2"] if width else []+ cmd = ["ffmpeg", "-v", "error", "-y", "-ss", f"{max(t, 0):.4f}", "-i", str(path), "-frames:v", "1", *vf, "-q:v", "2", str(out_path)]+ subprocess.run(cmd, check=True)+ return out_path+++def cut_clip(path: str | Path, start: float, duration: float, out_path: str | Path, width: int = 480,+ audio: bool = False, crf: int = 28) -> Path:+ out_path = Path(out_path)+ out_path.parent.mkdir(parents=True, exist_ok=True)+ cmd = ["ffmpeg", "-v", "error", "-y", "-ss", f"{max(start, 0):.4f}", "-i", str(path), "-t", f"{duration:.4f}",+ "-vf", f"scale={width}:-2", "-c:v", "libx264", "-preset", "veryfast", "-crf", str(crf), "-pix_fmt", "yuv420p"]+ cmd += ["-c:a", "aac", "-b:a", "64k"] if audio else ["-an"]+ cmd += ["-movflags", "+faststart", str(out_path)]+ subprocess.run(cmd, check=True)+ return out_path+++def extract_audio(path: str | Path, sr: int = 16000) -> np.ndarray | None:+ cmd = ["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-vn", "-ac", "1", "-ar", str(sr), "-f", "s16le", "-"]+ proc = subprocess.run(cmd, capture_output=True)+ if proc.returncode != 0 or not proc.stdout:+ LOG.debug("no audio extracted: %s", proc.stderr.decode(errors="ignore")[:200])+ return None+ return np.frombuffer(proc.stdout, dtype=np.int16).astype(np.float32) / 32768.0diff --git a/rea_video/memory.py b/rea_video/memory.pynew file mode 100644index 0000000..1e716c1--- /dev/null+++ b/rea_video/memory.py@@ -0,0 +1,273 @@+"""What the tool remembers across runs: user preferences and user corrections.++Stored as plain files in $REA_VIDEO_HOME (default ~/.rea-video):+ prefs.json default flags (engine, vlm, env_file, stems, reviewer) and free-text notes for agents+ corrections.jsonl one line per correction: what the tools / VLM / agent said, what the user says is right++Corrections are used in three ways and never silently change the classifier weights:+ 1. applied to that video at once, and again whenever the same file is decomposed later;+ 2. shown as hints in review tasks and `summary` ("users often correct cg_3d -> ai_video");+ 3. exported as eval labels (`rea-video memory --export-labels`), so rule changes are measured on them.+"""+from __future__ import annotations++import json+import os+import time+from collections import Counter+from pathlib import Path++from .classify import LABEL_ZH, LABELS, top++PREF_KEYS = {+ "engine": "复刻计划默认的视频引擎(decompose / remake-plan 的 --engine)",+ "vlm": "decompose 是否默认开 VLM:on / off",+ "env_file": "默认的 VLM 配置文件(等同每次加 --env-file)",+ "stems": "decompose 是否默认做人声/配乐分离:on / off",+ "reviewer": "apply-review 默认的复核者名字",+}+ON_OFF = ("on", "off")+HINT_MIN = 2 # a correction pattern becomes a hint once it has been seen this many times+++def home() -> Path:+ return Path(os.getenv("REA_VIDEO_HOME", str(Path.home() / ".rea-video"))).expanduser()+++# ---------------- preferences ----------------------------------------------------------------------++def load_prefs() -> dict:+ try:+ return json.loads((home() / "prefs.json").read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {}+++def _save_prefs(prefs: dict) -> None:+ home().mkdir(parents=True, exist_ok=True)+ (home() / "prefs.json").write_text(json.dumps(prefs, ensure_ascii=False, indent=2), encoding="utf-8")+++def set_pref(key: str, value: str | None) -> dict:+ if key not in PREF_KEYS:+ raise ValueError(f"未知偏好 {key}(可选:{', '.join(PREF_KEYS)};自由文字偏好用 prefs --note)")+ if value is not None and key in ("vlm", "stems") and value not in ON_OFF:+ raise ValueError(f"{key} 只能是 on / off")+ if value is not None and key == "env_file":+ value = str(Path(value).expanduser().resolve())+ prefs = load_prefs()+ if value is None:+ prefs.pop(key, None)+ else:+ prefs[key] = value+ _save_prefs(prefs)+ return prefs+++def add_note(text: str) -> dict:+ prefs = load_prefs()+ notes = prefs.setdefault("notes", [])+ if text not in notes:+ notes.append(text)+ _save_prefs(prefs)+ return prefs+++def remove_note(index: int) -> dict:+ prefs = load_prefs()+ notes = prefs.get("notes", [])+ if not 1 <= index <= len(notes):+ raise ValueError(f"没有第 {index} 条偏好说明(共 {len(notes)} 条)")+ notes.pop(index - 1)+ _save_prefs(prefs)+ return prefs+++def pref(key: str, default=None):+ return load_prefs().get(key, default)+++# ---------------- corrections ----------------------------------------------------------------------++def load_corrections() -> list[dict]:+ p = home() / "corrections.jsonl"+ if not p.is_file():+ return []+ out = []+ for line in p.read_text(encoding="utf-8").splitlines():+ try:+ out.append(json.loads(line))+ except ValueError:+ continue+ return out+++def _top(p: dict | None) -> str | None:+ return top(p)[0] if p and sum(p.values()) > 0 else None+++def _select(breakdown: dict, shots: str | None, start: float | None, end: float | None) -> list[dict]:+ recs = breakdown["shots"]+ if shots in (None, "", "all") and start is None:+ return recs+ if start is not None:+ e = end if end is not None else breakdown["source"]["duration"]+ return [r for r in recs if min(r["end"], e) - max(r["start"], start) > 0.5 * r["duration"]]+ want = set()+ for tok in shots.split(","):+ tok = tok.strip()+ want.add(tok if tok.startswith("shot_") else f"shot_{int(tok):03d}")+ return [r for r in recs if r["id"] in want]+++def correct(breakdown: dict, *, label: str | None = None, real: bool | None = None, shots: str | None = None,+ start: float | None = None, end: float | None = None, note: str = "", record: bool = True) -> list[dict]:+ """Mark shots with the user's answer (rec["user"]) and log each correction. Call finalize() afterwards."""+ if label is not None and label not in LABELS:+ raise ValueError(f"未知类别 {label}(可选:{', '.join(LABELS)})")+ if label is None and real is None:+ raise ValueError("至少给出 --label 或 --real")+ recs = _select(breakdown, shots, start, end)+ if not recs:+ raise ValueError("没有选中任何镜头(检查 --shots / --start / --end)")+ ctx = breakdown.get("video_context") or {}+ logged = []+ for r in recs:+ user = dict(r.get("user") or {})+ if label is not None:+ user["label"] = label+ if real is not None:+ user["real_material"] = real+ if note:+ user["note"] = note+ user["time"] = time.strftime("%Y-%m-%d %H:%M")+ entry = {+ "time": user["time"], "video": breakdown["source"]["filename"], "video_key": breakdown["source"].get("sha256_head"),+ "duration": breakdown["source"]["duration"], "shot": r["id"], "start": r["start"], "end": r["end"],+ "before": r["base"]["label"], "before_conf": r["base"]["confidence"],+ "tool": _top(r["deterministic"]["probs"]), "vlm": _top((r.get("vlm") or {}).get("label_probs")),+ "review": _top((r.get("review") or {}).get("label_probs")),+ "real_before": bool((r.get("material") or {}).get("has_real_material")),+ "label": label, "real_material": real, "note": note,+ "context": {"transcoded": ctx.get("transcoded"), "platform": ctx.get("platform"), "native30": ctx.get("native30"),+ "family": r["deterministic"]["facts"].get("temporal_family"),+ "pulldown": r["deterministic"]["facts"].get("pulldown"), "aigc": bool((breakdown.get("provenance") or {}).get("aigc"))},+ }+ r["user"] = user+ logged.append(entry)+ if record:+ home().mkdir(parents=True, exist_ok=True)+ with (home() / "corrections.jsonl").open("a", encoding="utf-8") as f:+ for e in logged:+ f.write(json.dumps(e, ensure_ascii=False) + "\n")+ return logged+++def reapply(breakdown: dict) -> int:+ """Re-attach earlier corrections when the same file is decomposed again (matched by file hash + time)."""+ key = breakdown["source"].get("sha256_head")+ if not key:+ return 0+ n = 0+ for c in load_corrections():+ if c.get("video_key") != key:+ continue+ for r in breakdown["shots"]:+ if min(r["end"], c["end"]) - max(r["start"], c["start"]) > 0.5 * r["duration"]:+ user = dict(r.get("user") or {})+ if c.get("label"):+ user["label"] = c["label"]+ if c.get("real_material") is not None:+ user["real_material"] = c["real_material"]+ if c.get("note"):+ user["note"] = c["note"]+ user["time"] = c["time"]+ r["user"] = user+ n += 1+ return n+++# ---------------- what the corrections teach ---------------------------------------------------------++def patterns(corrections: list[dict] | None = None) -> list[dict]:+ """Label corrections grouped by (tool's label -> user's label), latest correction per shot only."""+ latest = {}+ for c in corrections if corrections is not None else load_corrections():+ if c.get("label"):+ latest[(c.get("video_key"), c["shot"])] = c+ groups: dict[tuple, list] = {}+ for c in latest.values():+ if c["before"] != c["label"]:+ groups.setdefault((c["tool"], c["label"]), []).append(c)+ out = []+ for (tool, right), cs in sorted(groups.items(), key=lambda kv: -len(kv[1])):+ out.append({"tool": tool, "right": right, "count": len(cs), "videos": len({c.get("video_key") for c in cs}),+ "vlm_wrong": sum(1 for c in cs if c.get("vlm") and c["vlm"] != right),+ "review_wrong": sum(1 for c in cs if c.get("review") and c["review"] != right),+ "transcoded": sum(1 for c in cs if (c.get("context") or {}).get("transcoded"))})+ return out+++def hint_for(tool_label: str, pats: list[dict]) -> str | None:+ hits = [p for p in pats if p["tool"] == tool_label and p["count"] >= HINT_MIN]+ if not hits:+ return None+ return ";".join(f"用户过去 {p['count']} 次把工具判的「{LABEL_ZH.get(p['tool'], p['tool'])}」改成「{LABEL_ZH[p['right']]}」"+ for p in hits) + ",请重点核对"+++def summary_lines() -> list[str]:+ prefs = load_prefs()+ cs = load_corrections()+ lines = [f"记忆目录: {home()}"]+ set_prefs = {k: v for k, v in prefs.items() if k in PREF_KEYS}+ lines.append("偏好: " + (",".join(f"{k}={v}" for k, v in set_prefs.items()) if set_prefs else "(未设置)"))+ for i, n in enumerate(prefs.get("notes", []), 1):+ lines.append(f" 说明 {i}: {n}")+ if not cs:+ lines.append("纠正: 还没有记录(用户指出判错时运行 rea-video correct)")+ return lines+ videos = {c.get("video_key") for c in cs}+ lines.append(f"纠正: {len(cs)} 条,涉及 {len(videos)} 条视频")+ for p in patterns(cs):+ extra = [f"VLM 也判错 {p['vlm_wrong']}"] if p["vlm_wrong"] else []+ extra += [f"agent 复核也判错 {p['review_wrong']}"] if p["review_wrong"] else []+ extra += [f"其中转码视频 {p['transcoded']}"] if p["transcoded"] else []+ lines.append(f" 工具「{LABEL_ZH.get(p['tool'], p['tool'])}」→ 用户「{LABEL_ZH[p['right']]}」 {p['count']} 个镜头 / {p['videos']} 条视频"+ + (f"({','.join(extra)})" if extra else ""))+ real = [c for c in cs if c.get("real_material") is not None and c["real_material"] != c.get("real_before")]+ if real:+ lines.append(f" 真实素材判断被纠正 {len(real)} 次(漏标 {sum(1 for c in real if c['real_material'])},"+ f"误标 {sum(1 for c in real if not c['real_material'])})")+ for c in [c for c in cs if c.get("note")][-5:]:+ lines.append(f" 备注({c['video']} {c['shot']}): {c['note']}")+ lines.append("把纠正过的视频导出为评测样本:rea-video memory --export-labels eval/user_labels.yaml")+ return lines+++def export_labels(path: Path) -> int:+ """Write corrected shots as eval segments (only the corrected time ranges are scored)."""+ import yaml++ by_video: dict[str, dict] = {}+ for c in load_corrections():+ v = by_video.setdefault(c.get("video_key") or c["video"], {"video": c["video"], "shots": {}})+ v["shots"][c["shot"]] = {**v["shots"].get(c["shot"], {}), **{k: c[k] for k in ("start", "end")},+ **({"label": c["label"]} if c.get("label") else {}),+ **({"real": c["real_material"]} if c.get("real_material") is not None else {})}+ videos = []+ for key, v in by_video.items():+ shots = sorted(v["shots"].values(), key=lambda s: s["start"])+ entry = {"id": f"user_{Path(v['video']).stem}"[:60], "path": f"<填入 {v['video']} 的路径>", "source": "user_corrections",+ "video_key": key}+ segs = [[round(s["start"], 3), round(s["end"], 3), s["label"]] for s in shots if "label" in s]+ reals = [[round(s["start"], 3), round(s["end"], 3), s["real"]] for s in shots if "real" in s]+ if segs:+ entry["segments"] = segs+ if reals:+ entry["real_material"] = reals+ videos.append(entry)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("# 由 rea-video memory --export-labels 从用户纠正生成;只评纠正过的时间段。path 需要手动填。\n"+ + yaml.safe_dump({"videos": videos}, allow_unicode=True, sort_keys=False), encoding="utf-8")+ return len(videos)diff --git a/rea_video/overlay.py b/rea_video/overlay.pynew file mode 100644index 0000000..e1356e8--- /dev/null+++ b/rea_video/overlay.py@@ -0,0 +1,153 @@+"""Overlay layers: things composited on top of the base picture.++1. Static overlays: pixels that stay frozen while the rest of the shot changes+ (titles, logos, watermarks, layout frames) -> almost always rendered by code/editor.+2. Text (OCR, optional rapidocr): subtitle band, titles, labels; text that changes at a+ fixed band in sync with speech is a subtitle track.+3. Persistent template: regions frozen across *all* shots (layout skins, watermarks)."""+from __future__ import annotations++import cv2+import numpy as np++from .util import LOG++_OCR = None+_OCR_FAILED = False+++def get_ocr():+ global _OCR, _OCR_FAILED+ if _OCR is None and not _OCR_FAILED:+ try:+ from rapidocr_onnxruntime import RapidOCR # type: ignore++ _OCR = RapidOCR()+ except Exception as exc: # pragma: no cover - optional dependency+ LOG.warning("OCR disabled (pip install rapidocr-onnxruntime to enable): %s", exc)+ _OCR_FAILED = True+ return _OCR+++def _boxes_from_mask(mask: np.ndarray, min_area_frac: float = 0.002) -> list[list[int]]:+ h, w = mask.shape+ m = cv2.morphologyEx(mask.astype(np.uint8) * 255, cv2.MORPH_CLOSE, np.ones((9, 9), np.uint8))+ n, _labels, stats, _ = cv2.connectedComponentsWithStats(m, connectivity=8)+ boxes = []+ for i in range(1, n):+ x, y, bw, bh, area = stats[i]+ if area >= min_area_frac * h * w:+ boxes.append([int(x), int(y), int(bw), int(bh)])+ return boxes+++def _band(y_center: float, h: int) -> str:+ r = y_center / h+ if r < 0.22:+ return "top"+ if r > 0.70:+ return "bottom"+ return "middle"+++def static_overlays(frames: list[np.ndarray]) -> dict:+ """Detect frozen, edge-rich regions while the shot's background changes."""+ if len(frames) < 4:+ return {"background_changes": False, "boxes": [], "static_edge_ratio": 0.0}+ grays = np.stack([cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(np.float32) for f in frames])+ std = grays.std(axis=0)+ h, w = std.shape+ moving = std > 6.0+ background_changes = bool(moving.mean() > 0.15)+ edges = cv2.Canny(grays[len(grays) // 2].astype(np.uint8), 60, 160) > 0+ edges = cv2.dilate(edges.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0+ frozen = std < 1.5+ static_edges = frozen & edges+ out = {"background_changes": background_changes, "boxes": [],+ "static_edge_ratio": float(static_edges.sum() / max(1, edges.sum()))}+ if not background_changes:+ return out+ # keep only frozen edge clusters (text/graphics), not large flat frozen areas+ for x, y, bw, bh in _boxes_from_mask(static_edges, 0.0015):+ density = float(static_edges[y:y + bh, x:x + bw].mean())+ if density < 0.06:+ continue+ out["boxes"].append({"bbox": [x / w, y / h, bw / w, bh / h], "band": _band(y + bh / 2, h), "edge_density": density})+ return out+++def ocr_frames(frames: list[np.ndarray], times: list[float], max_frames: int = 4) -> list[dict]:+ ocr = get_ocr()+ if ocr is None or not frames:+ return []+ idx = np.unique(np.linspace(0, len(frames) - 1, num=min(max_frames, len(frames))).round().astype(int))+ results = []+ for i in idx:+ f = frames[i]+ h, w = f.shape[:2]+ scale = 1.0+ if w < 720: # upscale small analysis frames for better CJK recognition+ scale = 720 / w+ f = cv2.resize(f, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)+ try:+ res, _ = ocr(f)+ except Exception as exc: # pragma: no cover+ LOG.debug("ocr failed: %s", exc)+ continue+ for box, text, conf in res or []:+ pts = np.array(box, dtype=np.float32) / scale+ x0, y0 = pts.min(axis=0)+ x1, y1 = pts.max(axis=0)+ ang = float(np.degrees(np.arctan2(pts[1][1] - pts[0][1], pts[1][0] - pts[0][0])))+ results.append({"t": round(times[i], 3), "text": text, "conf": float(conf),+ "bbox": [float(x0 / w), float(y0 / h), float((x1 - x0) / w), float((y1 - y0) / h)],+ "band": _band((y0 + y1) / 2, h), "angle": round(ang, 1)})+ return results+++def summarize_text(items: list[dict]) -> dict:+ """Group OCR hits into tracks: same band + similar x-position."""+ if not items:+ return {"tracks": [], "text_coverage": 0.0}+ tracks: list[dict] = []+ for it in sorted(items, key=lambda d: (d["band"], d["t"])):+ cx = it["bbox"][0] + it["bbox"][2] / 2+ cy = it["bbox"][1] + it["bbox"][3] / 2+ hit = None+ for tr in tracks:+ if tr["band"] == it["band"] and abs(tr["cy"] - cy) < 0.06:+ hit = tr+ break+ if hit is None:+ hit = {"band": it["band"], "cy": cy, "cx": cx, "texts": [], "times": [], "heights": [], "axis_aligned": True}+ tracks.append(hit)+ if it["text"] not in hit["texts"]:+ hit["texts"].append(it["text"])+ hit["times"].append(it["t"])+ hit["heights"].append(it["bbox"][3])+ hit["axis_aligned"] = hit["axis_aligned"] and abs(it["angle"]) < 3+ out = []+ for tr in tracks:+ changing = len(tr["texts"]) > 1+ kind = "subtitle" if tr["band"] == "bottom" and changing else ("title" if tr["band"] == "top" else "label")+ if tr["band"] == "middle" and changing:+ kind = "subtitle"+ out.append({"kind": kind, "band": tr["band"], "texts": tr["texts"][:12], "changing": changing,+ "axis_aligned": tr["axis_aligned"], "text_height": float(np.median(tr["heights"])),+ "y_center": round(tr["cy"], 3)})+ cov = float(sum(i["bbox"][2] * i["bbox"][3] for i in items) / max(1, len({i["t"] for i in items})))+ return {"tracks": out, "text_coverage": cov, "items": items[:80]}+++def persistent_template(frames: list[np.ndarray]) -> dict:+ """Regions frozen across the whole video (sampled across shots)."""+ if len(frames) < 6:+ return {"frozen_ratio": 0.0, "boxes": []}+ grays = np.stack([cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(np.float32) for f in frames])+ std = grays.std(axis=0)+ frozen = std < 2.0+ h, w = std.shape+ edges = cv2.Canny(grays[0].astype(np.uint8), 60, 160) > 0+ boxes = [{"bbox": [x / w, y / h, bw / w, bh / h], "band": _band(y + bh / 2, h)}+ for x, y, bw, bh in _boxes_from_mask(frozen & edges, 0.001)]+ return {"frozen_ratio": float(frozen.mean()), "frozen_edge_ratio": float((frozen & edges).sum() / max(1, edges.sum())), "boxes": boxes[:20]}diff --git a/rea_video/pipeline.py b/rea_video/pipeline.pynew file mode 100644index 0000000..26c1bbf--- /dev/null+++ b/rea_video/pipeline.py@@ -0,0 +1,411 @@+"""decompose(): the end-to-end reverse-engineering pass for one video."""+from __future__ import annotations++import hashlib+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import numpy as np++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 .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+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 .vlm import SHOT_PROMPT, WHOLE_PROMPT, VLMClient, VLMConfig, normalize_shot_result, shot_hints, vlm_note+++def _sha256_head(path: Path, limit: int = 64 << 20) -> str:+ h = hashlib.sha256()+ with path.open("rb") as f:+ h.update(f.read(limit))+ return h.hexdigest()+++def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False, whole_vlm: bool = True,+ ocr: bool = True, workers: int = 3, engine: str = "seedance2.0", max_shots_vlm: int = 60,+ platform_meta: dict | None = None, stems: bool = True, memory: bool = True) -> dict:+ require_tools()+ t0 = time.time()+ video = Path(video).expanduser().resolve()+ out = Path(out_dir).expanduser().resolve()+ (out / "shots").mkdir(parents=True, exist_ok=True)+ info = video_info(video)+ prov = provenance(info)+ LOG.info("video %s %dx%d %.2ffps %.2fs", video.name, info.width, info.height, info.fps, info.duration)++ track = build_track(str(video), info)+ shots = detect_shots(track)+ LOG.info("detected %d shots", len(shots))+ marks = [b / s.fps for s in shots for b in s.beats]+ audio = analyze_audio(str(video), [s.start for s in shots[1:]], marks) if info.has_audio else {"has_audio": False}+ stem_info: dict = {}+ if info.has_audio and stems: # strip the soundtrack: original.wav / vocals.wav / music.wav+ from .audio import refine_with_stems+ from .stems import extract_stems++ LOG.info("separating stems (vocals / music)")+ stem_info = extract_stems(video, out)+ if stem_info.get("ok"):+ refine_with_stems(audio, stem_info["vocals"])++ shot_records: list[dict] = []+ template_frames: list[np.ndarray] = []+ samples_by_shot = {}+ for s in shots:+ smp = collect_samples(str(video), info, s)+ samples_by_shot[s.index] = smp+ if smp.frames:+ template_frames.extend([smp.frames[0], smp.frames[-1]])+ template = persistent_template(template_frames[:60]) if len(shots) >= 2 else {"frozen_ratio": 0.0, "boxes": []}++ for s in shots:+ smp = samples_by_shot[s.index]+ feats = shot_features(smp, info.fps)+ 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)+ 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}"+ shot_sheet(smp.frames, smp.frame_times, out / "shots" / f"{sid}.jpg")+ extract_frame(video, s.start + min(0.05, s.duration / 4), out / "shots" / f"{sid}_first.jpg", width=min(1080, info.width or 1080))+ 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),+ "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,+ }+ shot_records.append(rec)+ dl, dp = top(probs)+ LOG.info("%s %s-%s det=%s(%.0f%%) %s", sid, fmt_time(s.start), fmt_time(s.end), dl, dp * 100, facts.get("temporal_family"))++ # ---------------- VLM pass ------------------------------------------------------+ # "used" means at least one VLM answer actually came back; "status" says why not otherwise.+ vlm_info = {"used": False, "requested": use_vlm, "status": "off"}+ whole = None+ if use_vlm:+ cfg = VLMConfig.from_env()+ if cfg is None:+ LOG.warning("--vlm requested but no VLM config found (REA_VLM_* / VIDEO_ANALYSIS_* / GEMINI3_*); continuing without it")+ vlm_info = {"used": False, "requested": True, "status": "not_configured", "error": "no_config"}+ else:+ client = VLMClient(cfg, out / "vlm_cache")+ vlm_info = {"used": False, "requested": True, "status": "failed", "model": cfg.describe(), "media": cfg.media, "errors": []}++ def run_shot(rec: dict) -> None:+ media = []+ if cfg.media in ("both", "video"):+ clip = cut_clip(video, rec["start"], min(rec["duration"], 12.0), out / "clips" / f"{rec['id']}.mp4", width=480)+ media.append((clip, "video/mp4"))+ if cfg.media in ("both", "frames"):+ media += [(out / rec["assets"]["first_frame"], "image/jpeg"), (out / rec["assets"]["sheet"], "image/jpeg"),+ (out / rec["assets"]["last_frame"], "image/jpeg")]+ dl, dp = top(rec["deterministic"]["probs"])+ prompt = SHOT_PROMPT.format(hints=shot_hints(rec["features"], rec["deterministic"]["facts"], dl, dp))+ try:+ rec["vlm"] = normalize_shot_result(client.ask_json(prompt, media))+ except Exception as exc: # keep going; deterministic result stands+ if cfg.media == "both":+ try:+ frames_only = [m for m in media if m[1] != "video/mp4"]+ rec["vlm"] = normalize_shot_result(client.ask_json(prompt, frames_only))+ rec["vlm"]["_fallback"] = "frames_only"+ return+ except Exception as exc2: # pragma: no cover+ exc = exc2+ vlm_info["errors"].append(f"{rec['id']}: {str(exc)[:160]}")++ with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:+ list(pool.map(run_shot, shot_records[:max_shots_vlm]))+ if whole_vlm:+ try:+ low = cut_clip(video, 0, info.duration, out / "clips" / "whole_480p.mp4", width=480, audio=True, crf=30)+ cuts = ", ".join(f"{r['start']:.2f}" for r in shot_records)+ whole = client.ask_json(WHOLE_PROMPT.format(shots=cuts), [(low, "video/mp4")], max_tokens=6000)+ except Exception as exc:+ vlm_info["errors"].append(f"whole: {str(exc)[:160]}")+ asked = shot_records[:max_shots_vlm]+ ok_shots = sum(1 for r in asked if r.get("vlm"))+ vlm_info.update(ok_shots=ok_shots, asked_shots=len(asked), whole_ok=whole is not None)+ if ok_shots == len(asked) and (whole is not None or not whole_vlm):+ vlm_info.update(used=True, status="ok")+ elif ok_shots or whole is not None:+ vlm_info.update(used=True, status="partial")+ else:+ LOG.warning("VLM: every call failed (%s); result is deterministic only", (vlm_info["errors"] or ["?"])[0])++ breakdown = {+ "schema": SCHEMA, "tool": {"name": "rea-video", "version": __version__},+ "source": {"path": str(video), "filename": video.name, "sha256_head": _sha256_head(video), "width": info.width,+ "height": info.height, "fps": round(info.fps, 3), "duration": round(info.duration, 3), "vcodec": info.vcodec,+ "aspect_ratio": info.aspect_ratio, "has_audio": info.has_audio, "rotation": info.rotation},+ "provenance": {k: v for k, v in prov.items() if k != "tags"}, "summary": {},+ "audio": round_floats(audio), "global_layers": round_floats(template), "whole_video_vlm": whole,+ "shots": shot_records, "analysis": {"vlm": vlm_info, "ocr": ocr, "seconds": round(time.time() - t0, 1)},+ "assets": {"storyboard": "storyboard.jpg"},+ "platform_meta": platform_meta or {},+ "stems": {k: (Path(v).name if k in ("original", "vocals", "music") else v) for k, v in stem_info.items()},+ "per_clip_audio": per_clip_audio(str(video), [s.start for s in shots[1:]], info.duration) if info.has_audio else {},+ }+ if memory:+ from .memory import reapply++ n = reapply(breakdown)+ if n:+ LOG.info("re-applied %d earlier user correction(s) for this file", n)+ finalize(breakdown, out, engine=engine)+ LOG.info("done in %.1fs -> %s", time.time() - t0, out)+ return breakdown+++DOUBT_CAP = 0.7+++def _ai_or_live_doubt(label: str, facts: dict, prov: dict, vctx: dict) -> str | None:+ """On platform-transcoded files only two things settle AI vs live action: an AIGC label (AI) or a+ native-30fps camera signature (live). Without them, cap the confidence and say why.+ 24fps-source pulldown alone is not decisive: AI video, stop motion and cinema cameras all produce it."""+ if label not in ("ai_video", "live_action") or not facts.get("transcode_degraded"):+ return None+ if prov.get("aigc"):+ return None+ if label == "live_action" and vctx.get("native30") and not facts.get("pulldown"):+ return None+ if label == "ai_video":+ return "实拍 / 定格还是 AI 待确认:没有 AIGC 标识;24fps 源痕迹在 AI、定格动画、电影机拍摄里都会出现"+ return "实拍还是 AI 待确认:画面源自 24fps 素材且没有 AIGC 标识,不是手机原生 30fps 的特征"+++def _user_real(material: dict, real: bool) -> None:+ """Apply the user's answer to "does this shot use real (user-supplied) material?"."""+ if real and not material["has_real_material"]:+ material["items"].append({"kind": "user_marked", "kind_zh": "用户标注的真实素材", "region": "unknown", "real_material": True,+ "source": "user"})+ if not real:+ for it in material["items"]:+ if it.get("real_material"):+ it["real_material"] = False+ it["note"] = "用户纠正:不是真实素材"+ material["has_real_material"] = real+ if real and material["origin"] in ("ai_generated", "rendered", "unknown"):+ material["origin"], material["origin_zh"] = "mixed", "混合(含真实素材)"+ if not real and material["origin"] in ("real", "mixed"):+ material["origin"], material["origin_zh"] = "unknown", "待确认(用户说不是真实素材)"+ material["user_corrected"] = True+++def visual_opinion(rec: dict) -> dict | None:+ """What a model saw in the shot: the VLM answer, an agent's review (rea-video apply-review), or both averaged."""+ v, a = rec.get("vlm"), rec.get("review")+ if not (v and a):+ return v or a+ merged = dict(v)+ merged["label_probs"] = {k: (v["label_probs"].get(k, 0.0) + a["label_probs"].get(k, 0.0)) / 2 for k in LABEL_ZH}+ merged["embedded_assets"] = (v.get("embedded_assets") or []) + (a.get("embedded_assets") or [])+ return merged+++AI_LIVE_AXIS = ("ai_video", "live_action", "avatar")+++def _vlm_gate(rec: dict, vprobs: dict | None, vctx: dict) -> dict | None:+ """When only one image reader answered (the VLM, or an agent review, not both), let it decide only where+ image readers have proved reliable. Measured on eval/articles + holdout + holdout2: they fix 3D vs+ code-render vs screen-capture confusions, but on the AI / live-action / avatar axis they are confidently+ wrong, where the tools have frame-rate and container evidence. With both readers, _majority arbitrates.+ Returns the probs to fuse, or None to ignore them."""+ if not vprobs or (rec.get("review") and rec.get("vlm")):+ return vprobs+ facts = rec["deterministic"]["facts"]+ 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+ return None+ if d in AI_LIVE_AXIS or v 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+ return vprobs+++def _majority(rec: dict) -> str | None:+ """The tools' top label when one of the two image readers (VLM, agent review) agrees with it and the other+ does not. Not the reverse: VLM and agent tend to misread the same picture the same way (measured on+ eval/articles.yaml and holdout2), so their agreement against the tools is left to the normal fusion."""+ v, a = ((rec.get(k) or {}).get("label_probs") for k in ("vlm", "review"))+ if not (v and a and sum(v.values()) > 0 and sum(a.values()) > 0):+ return None+ d, tv, ta = top(rec["deterministic"]["probs"])[0], top(v)[0], top(a)[0]+ return d if (tv == d) != (ta == d) else None+++def finalize(breakdown: dict, out: Path, engine: str = "seedance2.0") -> dict:+ """(Re)classify every shot from stored features + VLM answers, plan replication,+ summarise and write breakdown.json / reports. Safe to call again after the+ classifier changes (no re-decoding)."""+ out = Path(out)+ shot_records = breakdown["shots"]+ audio = breakdown.get("audio", {})+ prov = breakdown.get("provenance", {})+ template = breakdown.get("global_layers", {})+ planner = Planner()+ vctx = video_context(shot_records, prov, breakdown["source"].get("fps"))+ breakdown["video_context"] = vctx+ for rec in shot_records:+ probs, evidence, facts = deterministic(rec["features"], rec.get("overlay"), rec.get("text"), rec.get("faces", 0.0), audio, prov,+ fps=breakdown["source"].get("fps"), ctx=vctx)+ rec["deterministic"] = {"probs": round_floats(probs), "evidence": evidence, "facts": facts}+ rec["layers"] = overlay_layers(rec.get("overlay"), rec.get("text"), template)+ # ---------------- fuse + plan ----------------------------------------------------+ video_meta = {"aspect_ratio": breakdown["source"]["aspect_ratio"]}+ for rec in shot_records:+ fam = rec["deterministic"]["facts"].get("temporal_family", "dynamic")+ seen = visual_opinion(rec) or {}+ vprobs = _vlm_gate(rec, seen.get("label_probs"), vctx)+ probs = fuse(rec["deterministic"]["probs"], vprobs, fam, majority=_majority(rec))+ label, conf = top(probs)+ src = seen.get("image_source")+ img_src = src if src and src != "unknown" else image_source_guess(rec["features"], rec["deterministic"]["facts"])+ evidence = (list(rec["deterministic"]["evidence"]) + [f"[VLM] {e}" for e in (rec.get("vlm") or {}).get("evidence", [])[:6]]+ + [f"[{(rec.get('review') or {}).get('_by', 'agent')} 看图] {e}" for e in (rec.get("review") or {}).get("evidence", [])[:6]])+ decided = "fused" if rec.get("vlm") else ("fused_agent" if rec.get("review") else "deterministic")+ user = rec.get("user") or {}+ if user.get("label") in LABEL_ZH: # the user said what this shot is: that is the answer+ label, conf, decided = user["label"], 1.0, "user"+ probs = {k: (1.0 if k == label else 0.0) for k in LABEL_ZH}+ evidence = [f"[用户纠正] 改为{LABEL_ZH[label]}" + (f":{user['note']}" if user.get("note") else "")] + evidence+ rec["base"] = {"label": label, "label_zh": LABEL_ZH[label], "confidence": round(conf, 3), "probs": round_floats(probs),+ "image_source": img_src if label in ("static_hold", "still_motion") else None,+ "generator_guess": seen.get("generator_guess"),+ "decided_by": decided, "evidence": evidence}+ doubt = None if decided == "user" else _ai_or_live_doubt(label, rec["deterministic"]["facts"], prov, vctx)+ if doubt:+ rec["base"]["confidence"] = round(min(conf, DOUBT_CAP), 3)+ rec["base"]["uncertain"] = doubt+ if label in ("code_render", "screen_capture"):+ # text/graphics are the rendered content itself here, not a separate overlay layer+ rec["layers"] = [l for l in rec["layers"] if l["kind"] == "layout_template"]+ # imported real material: full-frame from the base label, embedded regions only where+ # the frame is a rendered layout (photographic bases would trip the region detector)+ rendered_frame = label in ("code_render", "screen_capture", "cg_3d") or (label in ("static_hold", "still_motion") and img_src in ("graphic", "screenshot"))+ embedded = rec.get("embedded_assets", []) if rendered_frame else []+ if label == "cg_3d": # fur/foliage in a 3D render looks photographic; only trust screenshot panels there+ embedded = [e for e in embedded if e["kind"] in ("screenshot", "screen_recording")]+ rec["material"] = material_summary(label, img_src if label in ("static_hold", "still_motion", "screen_capture") else None, embedded,+ seen or None, moving=fam != "frozen")+ if user.get("real_material") is not None:+ _user_real(rec["material"], bool(user["real_material"]))+ rec["verdict"] = verdict_text(label, img_src, rec["layers"])+ if rec["material"]["has_real_material"]:+ kinds = []+ for it in rec["material"]["items"]:+ if it.get("real_material") and it["kind_zh"] not in kinds:+ kinds.append(it["kind_zh"])+ rec["verdict"] += ";引入真实素材(" + "、".join(kinds) + ")"+ rec["replication"] = planner.plan_shot(label, rec, video_meta, engine=engine)++ # ---------------- summary --------------------------------------------------------+ total = sum(r["duration"] for r in shot_records) or 1.0+ mix: dict[str, float] = {}+ for r in shot_records:+ mix[r["base"]["label"]] = mix.get(r["base"]["label"], 0.0) + r["duration"]+ mix_sorted = sorted(mix.items(), key=lambda kv: -kv[1])+ overlay_kinds = sorted({l["kind"] for r in shot_records for l in r["layers"]})+ conf = sum(r["base"]["confidence"] * r["duration"] for r in shot_records) / total+ parts = [f"{LABEL_ZH[k]} {v / total:.0%}" for k, v in mix_sorted]+ kind_zh = {"subtitle": "字幕", "title": "标题", "label": "文字标注", "static_graphic": "图形贴片", "layout_template": "版式模板"}+ verdict = ("混合制作:" if len(mix) > 1 or overlay_kinds else "") + " + ".join(parts)+ unsure = sum(r["duration"] for r in shot_records if r["base"]["label"] in ("ai_video", "live_action")+ and r["base"]["confidence"] < 0.65+ and (r.get("deterministic") or {}).get("facts", {}).get("transcode_degraded"))+ if unsure / total > 0.3 and not any(visual_opinion(r) for r in shot_records):+ verdict += f"(其中 {unsure / total:.0%} 时长实拍还是 AI 待确认:平台转码抹掉了噪声证据,需开 VLM 或人工看画面)"+ doubtful = sum(r["duration"] for r in shot_records if r["base"].get("uncertain"))+ if doubtful / total > 0.3 and not (unsure / total > 0.3 and not any(visual_opinion(r) for r in shot_records)):+ verdict += f"(其中 {doubtful / total:.0%} 时长实拍还是 AI 证据不足,待确认)"+ if overlay_kinds:+ verdict += ";叠加层:" + "、".join(kind_zh.get(k, k) for k in overlay_kinds) + "(代码/剪辑软件合成)"+ real_shots = [r for r in shot_records if r.get("material", {}).get("has_real_material")]+ real_kinds: dict[str, float] = {}+ for r in real_shots:+ for k in {it["kind_zh"] for it in r["material"]["items"] if it.get("real_material")}:+ real_kinds[k] = real_kinds.get(k, 0.0) + r["duration"]+ if real_shots:+ verdict += ";引入用户真实素材:" + "、".join(f"{k}({v:.1f}s)" for k, v in sorted(real_kinds.items(), key=lambda kv: -kv[1]))+ if audio.get("beat_synced_edit"):+ verdict += ";剪辑卡在音乐节拍上"+ summary = {+ "duration": breakdown["source"]["duration"], "shots": len(shot_records), "verdict": verdict,+ "production_mix": [{"label": k, "label_zh": LABEL_ZH[k], "seconds": round(v, 2), "ratio": round(v / total, 3)} for k, v in mix_sorted],+ "overlay_kinds": overlay_kinds, "confidence": round(conf, 3),+ "transitions": {t: sum(1 for r in shot_records if r["transition_in"] == t) for t in sorted({r["transition_in"] for r in shot_records})},+ "avg_shot_s": round(total / max(1, len(shot_records)), 2),+ "real_material": {"shots": [r["index"] for r in real_shots], "seconds": round(sum(r["duration"] for r in real_shots), 2),+ "ratio": round(sum(r["duration"] for r in real_shots) / total, 3),+ "kinds": {k: round(v, 2) for k, v in real_kinds.items()}},+ "vlm": vlm_note(breakdown.get("analysis", {}).get("vlm") or {}, breakdown.get("analysis", {}).get("review")),+ }+ sb_items = []+ import cv2++ for r in shot_records:+ img = cv2.imread(str(out / r["assets"]["first_frame"]))+ if img is not None:+ 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")++ breakdown["audio_plan"] = merge_audio_with_vlm(audio, breakdown.get("whole_video_vlm"))+ srcs = classify_sound_sources(breakdown)+ breakdown["sound_sources"] = srcs+ for t in breakdown["audio_plan"].get("plan", []):+ if t["track"] == "music" and srcs.get("music"):+ lean = srcs["music"]["leaning"]+ t["source"] = srcs["music"]["source_zh"]+ t["how"] = {"ai_generated": "原曲倾向 AI 生成:用 Suno 等(capsule-cinema UniversalMusicGenerationTool)按风格/BPM/调性重新生成,MV 类连歌词一起按新内容写",+ "existing_library": "原曲倾向现成曲库配乐:按 BPM/情绪/调性在曲库检索同类曲,或用 AI 生成相近风格的免版权曲",+ "popular_song": "原曲倾向现成知名歌曲:直接使用有版权风险,需要授权或换成相近风格的曲库/AI 曲"}[lean]+ if t["track"] == "sfx" and srcs.get("sfx"):+ t["source"] = srcs["sfx"]["source_zh"]+ if srcs["sfx"]["leaning"] == "ai_native":+ t["how"] = "原片音效随 AI 视频片段一起生成:复刻时用支持原生音频的视频模型(Seedance 2.x / Veo 3.1 / Kling)直接出声,或视频生音效(HunyuanVideo-Foley)"+ if t["track"] == "voice" and srcs.get("voice"):+ t["source"] = srcs["voice"]["source_zh"]+ from .visual import audio_timeline++ if audio.get("has_audio"):+ audio_timeline(audio, breakdown["audio_plan"].get("sfx_merged", []), [r["start"] for r in shot_records[1:]],+ breakdown["source"]["duration"], out / "audio.png")+ breakdown["assets"]["audio_timeline"] = "audio.png"+ a_parts = []+ if audio.get("voice", {}).get("present"):+ a_parts.append("人声")+ if audio.get("music", {}).get("present"):+ ms = srcs.get("music") or {}+ a_parts.append(f"BGM {audio['music'].get('tempo_bpm', '?')}BPM({ms.get('source_zh', '来源待确认')}"+ + (f",倾向{MUSIC_ZH[ms['leaning']]}" if ms.get("source") == "unknown" else "") + ")")+ n_sfx = len(breakdown["audio_plan"].get("sfx_merged", []))+ if n_sfx:+ a_parts.append(f"音效 {n_sfx} 处")+ if a_parts:+ summary["verdict"] += ";声音:" + " + ".join(a_parts)+ breakdown["summary"] = summary+ write_json(out / "breakdown.json", breakdown)+ from .report import write_reports++ write_reports(breakdown, out)+ return breakdowndiff --git a/rea_video/plan.py b/rea_video/plan.pynew file mode 100644index 0000000..b025608--- /dev/null+++ b/rea_video/plan.py@@ -0,0 +1,89 @@+"""Turn a classified shot into a replication plan: which capability rule applies, which+models are candidates, and how capsule-cinema (or local ffmpeg) would execute it."""+from __future__ import annotations++from pathlib import Path++import yaml++ROOT = Path(__file__).resolve().parent.parent+CAP = ROOT / "capabilities"++# base label -> (routing rule, executor, capsule generation type)+LABEL_ROUTE = {+ "ai_video": ("R07-product-hero", "capsule_cinema", "first_last_frame"),+ "live_action": ("R07-product-hero", "capsule_cinema", "image_to_video"),+ "avatar": ("R03-talking-head", "capsule_cinema", "image_to_video"),+ "cg_3d": ("R08-product-multiview", "capsule_cinema", "first_last_frame"),+ "code_render": ("R01-code-graphics", "code_render_spec", None),+ "screen_capture": ("R02-screen-demo", "code_render_spec", None),+ "still_motion": ("R17-still-motion", "local_ffmpeg", None),+ "static_hold": ("R18-static-hold", "local_ffmpeg", None),+}+NOTE = {+ "ai_video": "原片为 AI 生成:取原镜头首尾帧做首尾帧生成,可高度还原构图与动作;换主体时先用图像模型改首帧",+ "live_action": "原片为实拍:可用 AI 图生视频近似复刻(以首帧为参考),高保真需要重新拍摄",+ "avatar": "数字人口播:先克隆/合成配音,再用数字人模型由人像 + 音频驱动",+ "cg_3d": "3D 渲染:可用首尾帧 AI 生成近似;需要精确多角度时走 3D 建模 + Blender 渲染",+ "code_render": "代码渲染:用 Remotion/HTML 按文字轨与版式重建,100% 可控,不需要生成模型",+ "screen_capture": "录屏/截图:用真实界面录屏或网页截图重建",+ "still_motion": "静态图推拉:用一张图 + 测得的缩放/平移参数在本地 ffmpeg 精确复刻",+ "static_hold": "静帧:一张图定格即可",+}+CAPSULE_ENGINES = {"seedance2.0": (4, 15), "minimax-h3": (4, 15)}+++def _load(name: str):+ with (CAP / name).open(encoding="utf-8") as f:+ return yaml.safe_load(f)+++class Planner:+ def __init__(self) -> None:+ self.routing = _load("routing.yaml")+ self.rules = {r["id"]: r for r in self.routing["rules"]}+ self.models = {}+ for f in sorted((CAP / "models").glob("*.yaml")):+ for m in (yaml.safe_load(f.read_text(encoding="utf-8")) or {}).get("models", []):+ self.models[m["id"]] = m++ def plan_shot(self, label: str, shot: dict, video: dict, engine: str = "seedance2.0") -> dict:+ rule_id, executor, gen_type = LABEL_ROUTE.get(label, ("R14-ambient-broll", "capsule_cinema", "text_to_video"))+ rule = self.rules.get(rule_id, {})+ candidates = [{"id": m, "name": self.models[m]["name"], "status": self.models[m]["status"]}+ for m in rule.get("prefer", []) if m in self.models and self.models[m]["status"] != "shutdown"]+ plan = {"label": label, "rule": rule_id, "route": rule.get("route", []), "candidates": candidates,+ "verify": rule.get("verify", []), "executor": executor, "note": NOTE.get(label, "")}+ dur = float(shot["duration"])+ mat = shot.get("material") or {}+ user_assets = []+ for it in mat.get("items", []):+ if it.get("real_material"):+ where = "整个画面" if it.get("region") == "full" else (+ "画面局部 x{:.0%} y{:.0%} 宽{:.0%} 高{:.0%}".format(*it["bbox"]) if it.get("bbox") else "画面局部")+ user_assets.append({"kind": it["kind"], "kind_zh": it.get("kind_zh", it["kind"]), "where": where,+ "description": it.get("description", ""), "reference": shot.get("assets", {}).get("first_frame")})+ if user_assets:+ plan["user_assets"] = user_assets+ plan["note"] += ";需要用户提供真实素材:" + "、".join(f"{a['kind_zh']}({a['where']})" for a in user_assets)+ if executor == "capsule_cinema":+ lo, hi = CAPSULE_ENGINES.get(engine, (4, 15))+ gen_dur = int(min(hi, max(lo, round(dur + 0.49))))+ rep = (shot.get("vlm") or {}).get("replication") or {}+ prompt = rep.get("video_prompt") or (shot.get("vlm") or shot.get("review") or {}).get("description") or ""+ plan["capsule"] = {+ "engine": engine, "generation_type": gen_type, "duration": gen_dur,+ "trim_to": round(dur, 3), "aspect_ratio": video.get("aspect_ratio", "9:16"),+ "prompt": prompt, "prompt_en": rep.get("video_prompt_en", ""), "image_prompt": rep.get("image_prompt", ""),+ "needs_split": dur > hi,+ }+ if not prompt:+ plan["capsule"]["prompt_missing"] = "未运行 VLM,缺少视频提示词;请用 --vlm 重新拆解或手动补写"+ elif 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)}+ elif executor == "code_render_spec":+ plan["spec"] = {"text_layers": [l for l in shot.get("layers", []) if l["kind"] in ("subtitle", "title", "label")],+ "beats": shot.get("beats", []), "duration": round(dur, 3)}+ return plandiff --git a/rea_video/probe.py b/rea_video/probe.pynew file mode 100644index 0000000..5ee62a1--- /dev/null+++ b/rea_video/probe.py@@ -0,0 +1,149 @@+"""Container-level provenance: camera tags, encoder/editor signatures, AIGC labels, C2PA.++Metadata is strong evidence when present (an iPhone make/model tag means camera footage+entered the pipeline; an AIGC label means a generator declared itself) but it is often+stripped by social platforms, so absence proves nothing."""+from __future__ import annotations++import json+import re+from pathlib import Path++from .media import VideoInfo++# signature -> (category, label). category: generator | editor | renderer | camera | platform+SIGNATURES: list[tuple[str, str, str]] = [+ (r"kling|kuaishou.*ai|可灵", "generator", "Kling"),+ (r"jimeng|dreamina|即梦", "generator", "Jimeng/Dreamina"),+ (r"seedance|doubao.*video", "generator", "Seedance"),+ (r"hailuo|minimax", "generator", "MiniMax/Hailuo"),+ (r"\bveo\b|google.*(deepmind|veo)|synthid", "generator", "Google Veo"),+ (r"\bsora\b|openai", "generator", "OpenAI Sora"),+ (r"runway|gen-?4", "generator", "Runway"),+ (r"pika", "generator", "Pika"),+ (r"vidu|shengshu|生数", "generator", "Vidu"),+ (r"pixverse", "generator", "PixVerse"),+ (r"luma|dream ?machine", "generator", "Luma"),+ (r"wanx|tongyi|万相", "generator", "Wan/Tongyi"),+ (r"capcut|剪映|jianying", "editor", "CapCut/剪映"),+ (r"premiere|adobe", "editor", "Adobe"),+ (r"final ?cut|imovie", "editor", "Apple editor"),+ (r"davinci|resolve", "editor", "DaVinci Resolve"),+ (r"remotion", "renderer", "Remotion"),+ (r"blender", "renderer", "Blender"),+ (r"after ?effects", "renderer", "After Effects"),+ (r"motion ?canvas", "renderer", "Motion Canvas"),+ (r"puppeteer|playwright|headless ?chrom", "renderer", "Headless browser"),+ (r"obs ?studio|\bobs\b", "screen", "OBS"),+ (r"screen ?record|屏幕录制|quicktime player", "screen", "Screen recorder"),+ (r"douyin|抖音|bytedance", "platform", "Douyin"),+ (r"Tencent CAPD MTS|\(T-tech\)", "platform", "WeChat transcode"),+ (r"Wxmm_", "platform", "WeChat Channels"),+ (r"\bvid:v[0-9a-z]{8,}", "platform", "Douyin/TikTok"),+ (r"kuaishou|快手", "platform", "Kuaishou"),+ (r"xiaohongshu|小红书", "platform", "Xiaohongshu"),+]++CAMERA_KEYS = ("com.apple.quicktime.make", "com.apple.quicktime.model", "make", "model", "com.android.manufacturer",+ "com.android.model", "location", "com.apple.quicktime.location.iso6709")+AIGC_KEYS = ("aigc", "ai_generated", "aigc_label", "contentproducer", "produceid")+++def _flatten_tags(raw: dict) -> dict[str, str]:+ tags: dict[str, str] = {}+ for k, v in (raw.get("format", {}).get("tags") or {}).items():+ tags[f"format.{k}"] = str(v)+ for i, s in enumerate(raw.get("streams", [])):+ for k, v in (s.get("tags") or {}).items():+ tags[f"stream{i}.{k}"] = str(v)+ return tags+++def _scan_bytes(path: Path, limit: int = 4 << 20) -> bytes:+ size = path.stat().st_size+ with path.open("rb") as f:+ head = f.read(min(limit, size))+ tail = b""+ if size > limit:+ f.seek(max(0, size - limit))+ tail = f.read(limit)+ return head + tail+++AIGC_LABEL_ZH = {"1": "属于 AI 生成合成内容", "2": "可能为 AI 生成合成内容", "3": "疑似 AI 生成合成内容"}+++def parse_aigc(value: str) -> dict | None:+ """GB 45438-2025 implicit label, e.g. {"Label": "1", "ContentProducer": "...", "ProduceID": "..."}."""+ try:+ data = json.loads(value)+ except (ValueError, TypeError):+ m = re.search(r"\{.*\}", value or "")+ if not m:+ return None+ try:+ data = json.loads(m.group(0))+ except ValueError:+ return None+ if not isinstance(data, dict):+ return None+ label = str(data.get("Label", data.get("label", ""))).strip()+ return {"label": label, "meaning": AIGC_LABEL_ZH.get(label, "未知取值"),+ "content_producer": data.get("ContentProducer", ""), "produce_id": data.get("ProduceID", ""),+ "content_propagator": data.get("ContentPropagator", ""), "propagate_id": data.get("PropagateID", "")}+++def _printable_strings(raw: bytes, min_len: int = 6) -> str:+ return " ".join(m.decode("ascii") for m in re.findall(rb"[\x20-\x7e]{%d,}" % min_len, raw))+++def provenance(info: VideoInfo) -> dict:+ path = Path(info.path)+ tags = _flatten_tags(info.raw)+ evidence: list[dict] = []+ hints: dict[str, list[str]] = {"generator": [], "editor": [], "renderer": [], "camera": [], "screen": [], "platform": []}++ lower_tags = {k.lower(): v for k, v in tags.items()}+ aigc = None+ for key, value in lower_tags.items():+ short = key.split(".", 1)[-1]+ if short in CAMERA_KEYS:+ hints["camera"].append(f"{short}={value}")+ if any(a in short for a in AIGC_KEYS) or re.search(r"\baigc\b", value, re.I):+ aigc = parse_aigc(value) or {"label": "", "meaning": "无法解析", "raw": value[:200]}+ strong = aigc.get("label") in ("1", "2", "3")+ evidence.append({"kind": "aigc_label", "detail": f"AIGC 隐式标识 Label={aigc.get('label')}({aigc.get('meaning')}),"+ f"生成服务方编码 {aigc.get('content_producer') or '—'}", "weight": "strong" if strong else "weak"})+ if aigc.get("label") == "1":+ hints["generator"].append(f"AIGC 标识({aigc.get('meaning')})")++ blob = " ".join(f"{k}={v}" for k, v in tags.items() if "aigc" not in k.lower())+ raw_bytes = _scan_bytes(path)+ strings = _printable_strings(raw_bytes)+ for pattern, cat, label in SIGNATURES:+ if re.search(pattern, blob, re.I):+ hints[cat].append(label)+ evidence.append({"kind": f"{cat}_signature", "detail": f"元数据包含 {label}", "weight": "medium"})+ elif cat in ("generator", "renderer", "editor") and re.search(rf"\b(?:{pattern})\b", strings, re.I):+ # weaker: readable string inside container boxes (udta/uuid/xmp)+ hints[cat].append(f"{label}?")+ evidence.append({"kind": f"{cat}_bytes", "detail": f"容器内可读字符串出现 {label}", "weight": "weak"})++ if b"c2pa" in raw_bytes or b"jumb" in raw_bytes:+ evidence.append({"kind": "c2pa", "detail": "发现 C2PA/JUMBF 内容凭证盒", "weight": "strong"})+ hints["generator"].append("C2PA 凭证")+ if hints["camera"]:+ evidence.append({"kind": "camera_tags", "detail": "; ".join(hints["camera"][:4]), "weight": "strong"})++ encoder = lower_tags.get("format.encoder") or next((v for k, v in lower_tags.items() if k.endswith(".encoder")), "")+ handlers = sorted({v for k, v in lower_tags.items() if k.endswith("handler_name")})+ return {+ "container": info.raw.get("format", {}).get("format_name"),+ "encoder": encoder,+ "handlers": handlers,+ "creation_time": lower_tags.get("format.creation_time", ""),+ "aigc": aigc,+ "hints": {k: sorted(set(v)) for k, v in hints.items() if v},+ "evidence": evidence,+ "tags": tags,+ }diff --git a/rea_video/remake.py b/rea_video/remake.pynew file mode 100644index 0000000..3d9124e--- /dev/null+++ b/rea_video/remake.py@@ -0,0 +1,131 @@+"""Rebuild a video on the original timeline from remake results.++- generated clips (capsule-cinema) -> trimmed / padded to the original shot length+- still_motion / static_hold shots -> rebuilt locally from one image using the measured+ zoom/pan (deterministic, no model call)+- everything else -> original footage kept (marked in the compare video)+Outputs remake.mp4 (original audio) and compare.mp4 (original | remake side by side)."""+from __future__ import annotations++import json+import math+import subprocess+from pathlib import Path++import cv2++from .util import LOG, read_json+++def _ff(args: list[str]) -> None:+ subprocess.run(["ffmpeg", "-v", "error", "-y", *args], check=True)+++def render_still_motion(image: Path, out: Path, duration: float, size: tuple[int, int], fps: float,+ zoom_per_s: float = 0.0, pan_px_per_s: float = 0.0, pan_dir_deg: float = 0.0,+ analysis_width: int = 480) -> Path:+ """Re-create a Ken Burns move: per-frame similarity transform about the frame centre,+ with the zoom rate and pan speed measured during decomposition."""+ img = cv2.imread(str(image))+ if img is None:+ raise FileNotFoundError(image)+ w, h = size+ img = cv2.resize(img, (w, h), interpolation=cv2.INTER_AREA)+ n = max(1, int(round(duration * fps)))+ px_scale = w / float(analysis_width)+ vx = math.cos(math.radians(pan_dir_deg)) * pan_px_per_s * px_scale+ vy = math.sin(math.radians(pan_dir_deg)) * pan_px_per_s * px_scale+ out.parent.mkdir(parents=True, exist_ok=True)+ proc = subprocess.Popen(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{w}x{h}", "-r", f"{fps}",+ "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(out)], stdin=subprocess.PIPE)+ assert proc.stdin is not None+ # the measured motion maps frame t -> t+1; start slightly zoomed in when zooming out so edges never show+ base = 1.0 + max(0.0, -zoom_per_s * duration) + 0.02 + (abs(vx) + abs(vy)) * duration / max(w, h)+ for i in range(n):+ t = i / fps+ s = base * (1.0 + zoom_per_s * t)+ M = cv2.getRotationMatrix2D((w / 2, h / 2), 0, s)+ M[0, 2] += vx * t - vx * duration / 2+ M[1, 2] += vy * t - vy * duration / 2+ frame = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REFLECT)+ proc.stdin.write(frame.tobytes())+ proc.stdin.close()+ proc.wait()+ return out+++def _fit_clip(src: Path, out: Path, duration: float, size: tuple[int, int], fps: float) -> Path:+ w, h = size+ vf = (f"scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},fps={fps},"+ f"tpad=stop_mode=clone:stop_duration={duration:.3f},trim=duration={duration:.3f},setpts=PTS-STARTPTS")+ _ff(["-i", str(src), "-an", "-vf", vf, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(out)])+ return out+++def _original_segment(src: Path, out: Path, start: float, duration: float, size: tuple[int, int], fps: float) -> Path:+ w, h = size+ _ff(["-ss", f"{start:.4f}", "-i", str(src), "-t", f"{duration:.4f}", "-an",+ "-vf", f"scale={w}:{h},fps={fps}", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(out)])+ return out+++def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = None) -> str:+ b = read_json(breakdown_path)+ bdir = breakdown_path.parent+ jobs_path = results_path.with_name("jobs.json")+ jobs = {j["shot"]: j for j in read_json(jobs_path)["jobs"]} if jobs_path.is_file() else {}+ results = read_json(results_path).get("results", {}) if results_path.is_file() else {}+ out_dir = out_dir or results_path.parent+ seg_dir = out_dir / "segments"+ seg_dir.mkdir(parents=True, exist_ok=True)+ src = Path(b["source"]["path"])+ w, h = b["source"]["width"], b["source"]["height"]+ if b["source"].get("rotation") in (90, 270):+ w, h = h, w+ w, h = w - w % 2, h - h % 2+ fps = float(b["source"]["fps"]) if b["source"]["fps"] and b["source"]["fps"] <= 60 else 30.0+ parts, legend = [], []+ for sh in b["shots"]:+ dur = sh["duration"]+ seg = seg_dir / f"{sh['id']}.mp4"+ res = results.get(str(sh["index"])) or {}+ job = jobs.get(sh["index"], {})+ if res.get("video") and Path(res["video"]).is_file():+ _fit_clip(Path(res["video"]), seg, dur, (w, h), fps)+ legend.append((sh["index"], "generated"))+ elif job.get("executor") == "local_ffmpeg" or sh["base"]["label"] in ("still_motion", "static_hold"):+ m = sh["replication"].get("local", {})+ img = bdir / sh["assets"]["first_frame"]+ render_still_motion(img, seg, dur, (w, h), fps, m.get("zoom_per_s", 0.0), m.get("pan_px_per_s", 0.0),+ m.get("pan_dir_deg", 0.0), m.get("analysis_width", 480))+ legend.append((sh["index"], "local_still"))+ else:+ _original_segment(src, seg, sh["start"], dur, (w, h), fps)+ legend.append((sh["index"], "original"))+ parts.append(seg)+ lst = seg_dir / "concat.txt"+ lst.write_text("".join(f"file '{p.resolve()}'\n" for p in parts), encoding="utf-8")+ silent = out_dir / "remake_silent.mp4"+ _ff(["-f", "concat", "-safe", "0", "-i", str(lst), "-c", "copy", str(silent)])+ final = out_dir / "remake.mp4"+ if b["source"].get("has_audio"):+ _ff(["-i", str(silent), "-i", str(src), "-map", "0:v", "-map", "1:a?", "-c:v", "copy", "-c:a", "aac", "-shortest", str(final)])+ else:+ final = silent+ compare = out_dir / "compare.mp4"+ ch = 720 if h >= 720 else h - h % 2+ label = ",drawtext=text='{t}':x=10:y=10:fontcolor=white:box=1:[email protected]"+ for with_text in (True, False): # drawtext needs libfreetype; fall back to plain hstack+ la, lb = (label.format(t="original"), label.format(t="remake")) if with_text else ("", "")+ try:+ _ff(["-i", str(src), "-i", str(final), "-filter_complex",+ f"[0:v]scale=-2:{ch}{la}[a];[1:v]scale=-2:{ch}{lb}[b];[a][b]hstack=inputs=2[v]",+ "-map", "[v]", "-map", "0:a?", "-c:v", "libx264", "-crf", "23", "-pix_fmt", "yuv420p", "-shortest", str(compare)])+ break+ except subprocess.CalledProcessError:+ if not with_text:+ raise+ (out_dir / "assemble_log.json").write_text(json.dumps({"legend": legend, "remake": str(final), "compare": str(compare)},+ ensure_ascii=False, indent=2), encoding="utf-8")+ LOG.info("remake -> %s ; compare -> %s", final, compare)+ return json.dumps({"remake": str(final), "compare": str(compare), "legend": legend}, ensure_ascii=False)diff --git a/rea_video/report.py b/rea_video/report.pynew file mode 100644index 0000000..072f13e--- /dev/null+++ b/rea_video/report.py@@ -0,0 +1,247 @@+"""Human-readable reports (Markdown + standalone HTML) from a breakdown."""+from __future__ import annotations++import html+from pathlib import Path++from .classify import LABEL_ZH+from .util import fmt_time+from .visual import LABEL_COLOR+from .vlm import vlm_note++KIND_ZH = {"subtitle": "字幕", "title": "标题", "label": "文字", "static_graphic": "图形贴片", "layout_template": "版式模板"}+CAMERA_ZH = {"static": "固定", "static_with_subject_motion": "固定(主体在动)", "planar_zoom_pan": "整图推拉/平移",+ "handheld_like": "手持晃动", "smooth_move": "平滑运镜", "unknown": "—"}+++def _layers(rec: dict) -> str:+ ks = []+ for l in rec.get("layers", []):+ k = KIND_ZH.get(l["kind"], l["kind"])+ if k not in ks:+ ks.append(k)+ return "、".join(ks) or "—"+++def _origin(rec: dict) -> str:+ m = rec.get("material") or {}+ if not m:+ return "—"+ kinds = []+ for it in m.get("items", []):+ if it.get("real_material") and it["kind_zh"] not in kinds:+ kinds.append(it["kind_zh"])+ unsure = sorted({it["kind_zh"] for it in m.get("items", []) if it.get("real_material") is None})+ return (m.get("origin_zh", "—") + (f":{'、'.join(kinds)}" if kinds else "")+ + (f";待确认是否真实:{'、'.join(unsure)}" if unsure else ""))+++def markdown(b: dict) -> str:+ s = b["summary"]+ src = b["source"]+ L = [f"# 视频拆解报告:{src['filename']}", "",+ f"**结论**:{s['verdict']}", "",+ f"- 时长 {src['duration']}s · {src['width']}×{src['height']} · {src['fps']}fps · {src['aspect_ratio']}",+ f"- 镜头 {s['shots']} 个,平均 {s['avg_shot_s']}s;转场:" + "、".join(f"{k}×{v}" for k, v in s["transitions"].items()),+ f"- 判断置信度(按时长加权):{s['confidence']:.0%};判定方式:" + ("确定性取证 + VLM 融合" if b["analysis"]["vlm"].get("used") else ("确定性取证 + agent 看图融合" if (b["analysis"].get("review") or {}).get("shots") else "仅确定性取证")),+ f"- {s.get('vlm') or vlm_note(b['analysis']['vlm'], b['analysis'].get('review'))}",+ "", "", "", "## 制作方式占比", "", "| 底层画面 | 时长 | 占比 |", "|---|---|---|"]+ for m in s["production_mix"]:+ L.append(f"| {m['label_zh']} | {m['seconds']}s | {m['ratio']:.0%} |")+ prov = b.get("provenance", {})+ if prov.get("hints") or prov.get("encoder"):+ L += ["", "## 元数据线索", ""]+ if prov.get("encoder"):+ L.append(f"- 编码器:`{prov['encoder']}`")+ for k, v in (prov.get("hints") or {}).items():+ L.append(f"- {k}:{', '.join(v)}")+ a = b.get("audio", {})+ if a.get("has_audio"):+ L += ["", "## 声音拆解", "", "", "",+ f"- 整体响度 {a.get('rms_dbfs')} dBFS,峰值 {a.get('peak_dbfs')} dBFS"]+ v = a.get("voice", {})+ L.append(f"- **人声**:{'有' if v.get('present') else '无/很少'},占 {v.get('ratio', 0):.0%} 时长"+ + (f",基频约 {v.get('f0_median_hz')}Hz({ {'male': '偏男声', 'female': '偏女声'}.get(v.get('gender_hint'), '性别不确定') })" if v.get("f0_median_hz") else ""))+ mu = a.get("music", {})+ if mu.get("present"):+ key = mu.get("key") or {}+ L.append(f"- **背景音乐**:占 {mu.get('ratio', 0):.0%} 时长({mu.get('start')}–{mu.get('end')}s),约 {mu.get('tempo_bpm')} BPM"+ f"(也可能是 {'/'.join(str(t) for t in mu.get('tempo_alternatives', []))})"+ + (f",调性 {key.get('tonic')} {key.get('mode')}(置信 {key.get('confidence')})" if key else "")+ + (f",段落变化点 {', '.join(str(t) + 's' for t in mu.get('section_changes', [])[:8])}" if mu.get("section_changes") else ""))+ else:+ L.append("- **背景音乐**:未检测到持续的音乐床")+ if "cuts_on_beat_ratio" in a:+ L.append(f"- **剪辑与节拍**:{a['cuts_on_beat_ratio']:.0%} 的切点落在节拍上(随机约 {a['cuts_on_beat_chance']:.0%})" + ("→ **卡点剪辑**" if a.get("beat_synced_edit") else ""))+ src = b.get("sound_sources") or {}+ if src:+ L += ["", "**声音来源:AI 生成还是现成素材**", ""]+ if src.get("summary_zh"):+ L.append(f"- **结论**:{src['summary_zh']}")+ st = b.get("stems") or {}+ if st.get("ok"):+ L.append("- **剥离出的音轨**:`stems/original.wav`(原声)、`stems/vocals.wav`(人声干声,瞬态音效也会落在这里)、`stems/music.wav`(配乐 + 环境声)")+ ctx = src.get("format_context", {})+ L.append(f"- 视频形式:{'音乐 MV' if ctx.get('music_mv') else ('疑似带唱歌曲/MV' if ctx.get('music_mv_maybe') else (ctx.get('format') or '普通视频配乐'))}"+ f";AI 画面占 {ctx.get('ai_picture_share', 0):.0%},实拍占 {ctx.get('live_picture_share', 0):.0%}")+ names = {"music": "背景音乐", "voice": "人声", "sfx": "音效"}+ for k in ("music", "voice", "sfx"):+ v = src.get(k)+ if not v:+ continue+ probs = ",".join(f"{kk} {vv:.0%}" for kk, vv in sorted(v["probs"].items(), key=lambda kv: -kv[1]))+ L.append(f"- **{names[k]}**:{v['source_zh']}({probs})")+ for e in v["evidence"]:+ L.append(f" - {e}")+ for h in v.get("how_to_confirm", []):+ L.append(f" - 确认方法:{h}")+ pc = b.get("per_clip_audio") or {}+ if pc.get("ratio") is not None:+ L.append(f"- 逐段原生音频检测:切点处背景声变化 {pc['at_cuts_db']}dB,镜头内 {pc['within_shots_db']}dB(比值 {pc['ratio']})"+ + ("→ 每段画面自带声音" if pc.get("resets_at_cuts") else "→ 声音跨切点连续,是后期整体铺的"))+ plan = b.get("audio_plan", {})+ sfx = plan.get("sfx_merged", [])+ if sfx:+ L += ["", f"**音效**({len(sfx)} 处;来源 vlm=大模型听出,deterministic=信号检测的候选,置信度低)", "",+ "| 时间 | 类型 | 描述 | 对应画面 | 来源 |", "|---|---|---|---|---|"]+ for e in sfx[:40]:+ L.append(f"| {float(e.get('t', 0)):.2f}s | {e.get('type', '')} | {e.get('description', '')} | "+ f"{e.get('sync_with', '切点' if e.get('sync_with_visual') else '')} | {e.get('source', '')} |")+ else:+ L.append("- **音效**:信号层面未检出显著音效(在人声和音乐下面的轻音效需要 VLM 判断,见 --vlm)")+ if plan.get("plan"):+ L += ["", "**声音复刻方案**", ""]+ for t in plan["plan"]:+ L.append(f"- {t['track']}({t['rule']}):{t['what']} → {t['how']}")+ if plan.get("mix"):+ L.append(f"- 混音:{plan['mix']}")+ w = b.get("whole_video_vlm")+ if w:+ L += ["", "## 结构与文案(VLM)", "", f"- 概括:{w.get('summary', '')}", f"- 形式:{w.get('format', '')};钩子:{w.get('hook', '')}"]+ n = w.get("narration") or {}+ L.append(f"- 旁白:{n.get('type', '')} {n.get('voice', '')};音乐:{(w.get('music') or {}).get('style', '')};字幕:{(w.get('subtitles') or {}).get('style', '')}")+ L.append(f"- 整体判断:{w.get('overall_production', '')}")+ for seg in w.get("segments", [])[:30]:+ L.append(f" - {seg.get('start')}–{seg.get('end')}s · {seg.get('beat', '')} · {seg.get('copy', '')}")+ rm = s.get("real_material") or {}+ if rm.get("shots"):+ L += ["", "## 用户真实素材", "",+ f"共 {len(rm['shots'])} 个镜头、{rm['seconds']}s({rm['ratio']:.0%})引入了真实素材,复刻时需要准备对应素材,不能用模型生成替代:", ""]+ for r in b["shots"]:+ for a in r.get("replication", {}).get("user_assets", []):+ L.append(f"- 镜头 #{r['index']}({fmt_time(r['start'])}):{a['kind_zh']},{a['where']}" + (f",{a['description']}" if a.get("description") else ""))+ L += ["", "## 分镜表", "", "| # | 时间 | 时长 | 底层画面 | 置信度 | 素材来源 | 叠加层 | 运镜 | 复刻路线 |", "|---|---|---|---|---|---|---|---|---|"]+ for r in b["shots"]:+ base = r["base"]+ L.append(f"| {r['index']} | {fmt_time(r['start'])} | {r['duration']:.2f}s | {base['label_zh']} | {base['confidence']:.0%} | {_origin(r)} | {_layers(r)} | "+ f"{CAMERA_ZH.get(r['features'].get('camera', 'unknown'), '—')} | {r['replication']['rule']} → {r['replication']['executor']} |")+ L += ["", "## 逐镜详情", ""]+ for r in b["shots"]:+ base = r["base"]+ L += [f"### #{r['index']} {fmt_time(r['start'])}–{fmt_time(r['end'])} · {r['verdict']}", "",+ f"![{r['id']}]({r['assets']['sheet']})", ""]+ probs = sorted(base["probs"].items(), key=lambda kv: -kv[1])[:3]+ L.append("- 概率:" + ",".join(f"{LABEL_ZH[k]} {v:.0%}" for k, v in probs) + f"({base['decided_by']})")+ if base.get("image_source"):+ L.append(f"- 静帧来源:{base['image_source']}")+ L.append(f"- 素材来源:{_origin(r)}")+ for it in (r.get("material") or {}).get("items", []):+ if it.get("real_material") and it.get("evidence"):+ L.append(f" - {it['kind_zh']}:{it['evidence']}")+ if base.get("generator_guess") and base["generator_guess"] != "unknown":+ L.append(f"- 可能的工具:{base['generator_guess']}")+ if r.get("beats"):+ L.append("- 镜头内动效节拍:" + "、".join(f"{t:.2f}s" for t in r["beats"]))+ for e in base["evidence"][:8]:+ L.append(f"- {e}")+ v = r.get("vlm") or r.get("review") or {}+ if v.get("description"):+ L.append(f"- 画面:{v['description']}")+ 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"])+ L.append(f"- 文字轨({kind}/{tr['band']}):" + " / ".join(t[:40] for t in tr["texts"][:4]))+ rep = r["replication"]+ L.append(f"- 复刻:{rep['note']}")+ if rep.get("capsule", {}).get("prompt"):+ L.append(f" - 视频提示词:{rep['capsule']['prompt']}")+ L.append("")+ L += ["## 说明", "",+ "- 确定性取证对「是否在动、是否整图推拉、是否渲染纹理、是否 24→30 帧率转换」很可靠;对实拍 / AI / 3D 的区分要依赖 VLM 与人工复核。",+ "- 元数据经平台转码常被清除,缺失不代表没有。", ""]+ return "\n".join(L)+++def html_report(b: dict) -> str:+ s = b["summary"]+ esc = html.escape+ rows = []+ for r in b["shots"]:+ base = r["base"]+ c = "rgb(%d,%d,%d)" % LABEL_COLOR.get(base["label"], (80, 80, 80))+ ev = "".join(f"<li>{esc(e)}</li>" for e in base["evidence"][:8])+ desc = esc((r.get("vlm") or r.get("review") or {}).get("description", ""))+ prompt = esc(r["replication"].get("capsule", {}).get("prompt", ""))+ intrinsic = base["label"] in ("code_render", "screen_capture")+ texts = "".join(f"<li>{esc('画面内容文字' if intrinsic else KIND_ZH.get(t['kind'], t['kind']))}·{esc(t['band'])}:{esc(' / '.join(x[:40] for x in t['texts'][:4]))}</li>" for t in r.get("text", {}).get("tracks", [])[:4])+ rows.append(f"""+<section class="shot">+ <div class="head"><span class="badge" style="background:{c}">{esc(base['label_zh'])} {base['confidence']:.0%}</span>+ <b>#{r['index']}</b> {fmt_time(r['start'])}–{fmt_time(r['end'])} · {r['duration']:.2f}s · {esc(r['verdict'])}+ {('<span class="real">真实素材</span>') if (r.get('material') or {}).get('has_real_material') else ''}</div>+ <img src="{esc(r['assets']['sheet'])}" loading="lazy">+ <div class="cols"><div><h4>证据</h4><ul>{ev}</ul>{('<h4>文字轨</h4><ul>' + texts + '</ul>') if texts else ''}</div>+ <div><h4>画面</h4><p>{desc or '—'}</p><h4>复刻</h4><p>{esc(r['replication']['rule'])} → {esc(r['replication']['executor'])}<br>{esc(r['replication']['note'])}</p>+ {('<p class="prompt">' + prompt + '</p>') if prompt else ''}</div></div>+</section>""")+ def _rgb(label: str) -> str:+ return "rgb(%d,%d,%d)" % LABEL_COLOR.get(label, (80, 80, 80))++ mix = "".join(f"<div class='bar' style='flex:{m['ratio']};background:{_rgb(m['label'])}' title='{esc(m['label_zh'])}'>{esc(m['label_zh'])} {m['ratio']:.0%}</div>" for m in s["production_mix"])+ return f"""<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<title>拆解:{esc(b['source']['filename'])}</title>+<style>+:root{{--bg:#fafaf9;--fg:#1c1917;--muted:#78716c;--card:#fff;--line:#e7e5e4}}+@media (prefers-color-scheme:dark){{:root{{--bg:#1c1917;--fg:#f5f5f4;--muted:#a8a29e;--card:#292524;--line:#44403c}}}}+body{{margin:0;padding:24px 16px;background:var(--bg);color:var(--fg);font:15px/1.6 -apple-system,"PingFang SC","Noto Sans CJK SC",sans-serif}}+main{{max-width:1100px;margin:auto}} h1{{font-size:22px}} .muted{{color:var(--muted)}}+.mix{{display:flex;height:30px;border-radius:6px;overflow:hidden;margin:12px 0}} .bar{{color:#fff;font-size:12px;padding:6px;white-space:nowrap;overflow:hidden}}+.shot{{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:12px;margin:14px 0}}+.shot img{{max-width:100%;border-radius:6px;margin:8px 0}} .badge{{color:#fff;border-radius:4px;padding:2px 8px;margin-right:8px;font-size:13px}}+.cols{{display:grid;grid-template-columns:1fr 1fr;gap:16px}} @media (max-width:700px){{.cols{{grid-template-columns:1fr}}}}+h4{{margin:6px 0 2px;font-size:13px;color:var(--muted)}} ul{{margin:0;padding-left:18px}} .prompt{{background:var(--bg);padding:8px;border-radius:6px;font-size:13px}}+img.sb{{max-width:100%;border-radius:8px}} .real{{background:#0d9488;color:#fff;border-radius:4px;padding:2px 8px;margin-left:8px;font-size:12px}}+</style></head><body><main>+<h1>视频拆解:{esc(b['source']['filename'])}</h1>+<p><b>结论:</b>{esc(s['verdict'])}</p>+{('<p><b>用户真实素材:</b>' + str(len(s['real_material']['shots'])) + ' 个镜头,' + str(s['real_material']['seconds']) + 's(' + format(s['real_material']['ratio'], '.0%') + ')——复刻时需要自备对应素材</p>') if (s.get('real_material') or {}).get('shots') else ''}+<p class="muted">{b['source']['duration']}s · {b['source']['width']}×{b['source']['height']} · {b['source']['fps']}fps · {s['shots']} 个镜头 · 置信度 {s['confidence']:.0%} ·+{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">+{_sound_html(b)}+{''.join(rows)}+</main></body></html>"""+++def _sound_html(b: dict) -> str:+ esc = html.escape+ src = b.get("sound_sources") or {}+ st = b.get("stems") or {}+ if not src and not st.get("ok"):+ return ""+ parts = ["<section class='shot'><h3 style='margin:4px 0'>声音</h3>"]+ if src.get("summary_zh"):+ parts.append(f"<p><b>{esc(src['summary_zh'])}</b></p>")+ if st.get("ok"):+ for f, name in (("original.wav", "原声"), ("vocals.wav", "人声干声"), ("music.wav", "配乐 + 环境声")):+ parts.append(f"<div>{name}:<audio controls preload='none' src='stems/{f}'></audio></div>")+ if (b.get("assets") or {}).get("audio_timeline") or b.get("audio", {}).get("has_audio"):+ parts.append("<img class='sb' src='audio.png' onerror=\"this.remove()\">")+ parts.append("</section>")+ return "".join(parts)+++def write_reports(b: dict, out: Path) -> None:+ (out / "report.md").write_text(markdown(b), encoding="utf-8")+ (out / "report.html").write_text(html_report(b), encoding="utf-8")diff --git a/rea_video/review.py b/rea_video/review.pynew file mode 100644index 0000000..ac6e6e2--- /dev/null+++ b/rea_video/review.py@@ -0,0 +1,144 @@+"""Agent-as-VLM: a multimodal agent looks at the shot images and answers the same questions+the VLM would. `build_tasks` writes what to look at; `apply_answers` folds the answers back+into the breakdown so the summary, reports and replication plan reflect what the agent saw.+"""+from __future__ import annotations++import re+import time++from .classify import LABEL_ZH, LABELS, top+from .vlm import SHOT_PROMPT, shot_hints++AGENT_WEIGHT = 0.85 # agent answers are softened toward uniform before fusion+IMAGE_SOURCES = ("ai_image", "photo", "graphic", "screenshot", "unknown")+ASSET_KINDS = ("real_footage", "photo", "screenshot", "screen_recording", "product_photo", "logo", "ai_image")++# 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()++INSTRUCTIONS = f"""你是这次的 VLM:逐个镜头看图,判断「底层画面」的制作方式,把答案写进 review_answers.json,然后运行+ rea-video apply-review <输出目录> --by <你的名字>+把你的判断并入结论(会重写 breakdown.json、report.md、report.html)。++怎么看:+1. 先看 storyboard.jpg 建立整体印象;每个镜头看 images 里的 sheet(首/中/尾联系表),需要时运行 zoom_cmd 抽帧细看。+2. priority=high 的镜头(低置信、次选接近、转码后实拍/AI 待确认)一定要看;其余镜头也尽量都答。+3. 只依据画面证据,独立判断(这里不给 VLM 的答案,它会在融合时单独计入)。tool 一栏是确定性取证的结果,可能有误,但帧率类证据(24→30 重复帧)和 AIGC 标识可靠,+ 和画面印象冲突时不要轻易推翻(见 SKILL.md「平台转码视频」)。+4. 看不出就把概率分散开,例如 ai_video 0.55 / live_action 0.45,并在 evidence 写清缺什么证据。+5. 没看过的镜头不要填(保持 label_probs 全 0),apply-review 会跳过它。++{LABEL_GUIDE}++{CONFUSIONS}++每个镜头要填:label_probs(8 类,和为 1)、image_source({"|".join(IMAGE_SOURCES)})、evidence(看到的具体证据)、+description(主体、动作、场景、运镜)、embedded_assets(画面里的真实素材:截图、照片、实拍片段、Logo,+kind 取 {"|".join(ASSET_KINDS)},is_real_material 为 true/false)。"""+++def _priority(rec: dict, ctx: dict) -> tuple[str, list[str]]:+ det = (rec.get("deterministic") or {}).get("probs") or {}+ probs = sorted(det.items(), key=lambda kv: -kv[1])+ label, conf = probs[0] if probs else ("", 1.0)+ why = []+ if conf < 0.65:+ why.append(f"置信度低({conf:.0%})")+ if len(probs) > 1 and probs[0][1] - probs[1][1] < 0.25:+ why.append(f"次选 {LABEL_ZH.get(probs[1][0], probs[1][0])} 接近({probs[1][1]:.0%})")+ facts = (rec.get("deterministic") or {}).get("facts", {})+ if facts.get("transcode_degraded") and label in ("ai_video", "live_action"):+ why.append("平台转码,实拍/AI 待确认")+ return ("high" if why else "normal"), why+++def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:+ """-> (tasks, empty answer template)."""+ video = breakdown["source"]["path"]+ ctx = breakdown.get("video_context") or {}+ from .memory import hint_for, patterns++ pats = patterns()+ shots = []+ for rec in breakdown["shots"]:+ # only the deterministic layer is shown: the agent should judge independently of any VLM answer+ ranked = sorted(rec["deterministic"]["probs"].items(), key=lambda kv: -kv[1])+ alt = ranked[1:2]+ prio, why = _priority(rec, ctx)+ dl, dp = top(rec["deterministic"]["probs"])+ past = hint_for(dl, pats)+ if past:+ prio, why = "high", why + [past]+ shots.append({+ "id": rec["id"], "index": rec["index"], "start": rec["start"], "end": rec["end"], "duration": rec["duration"],+ "priority": prio, "why": why,+ "tool": {"label": dl, "label_zh": LABEL_ZH[dl], "confidence": round(dp, 3),+ "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),+ "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",+ })+ tasks = {"instructions": INSTRUCTIONS, "video": video, "storyboard": "storyboard.jpg",+ "video_context": {k: ctx.get(k) for k in ("transcoded", "platform", "native30") if k in ctx},+ "aigc": (breakdown.get("provenance") or {}).get("aigc"),+ "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]}+ return tasks, answers+++def _clean(ans: dict) -> tuple[dict | None, str | None]:+ probs = ans.get("label_probs") or {}+ bad = [k for k in probs if k not in LABELS]+ if bad:+ return None, f"未知类别 {bad}(可选:{', '.join(LABELS)})"+ vals = {}+ for k in LABELS:+ try:+ vals[k] = max(0.0, float(probs.get(k, 0) or 0))+ except (TypeError, ValueError):+ return None, f"{k} 的概率不是数字"+ total = sum(vals.values())+ if total <= 0:+ return None, "label_probs 全为 0(没作答),跳过"+ u = 1.0 / len(LABELS)+ soft = {k: AGENT_WEIGHT * v / total + (1 - AGENT_WEIGHT) * u for k, v in vals.items()}+ src = ans.get("image_source") if ans.get("image_source") in IMAGE_SOURCES else "unknown"+ assets = []+ for e in ans.get("embedded_assets") or []:+ if isinstance(e, dict) and e.get("kind") in ASSET_KINDS:+ assets.append({"kind": e["kind"], "description": str(e.get("description", "")),+ "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+++def apply_answers(breakdown: dict, answers: dict, by: str | None = None) -> dict:+ """Store answers on the shots (rec["review"]) and return a change log. Call finalize() afterwards."""+ by = by or answers.get("by") or "agent"+ recs = {r["id"]: r for r in breakdown["shots"]}+ applied, problems, changes = [], [], []+ for ans in answers.get("shots") or []:+ sid = ans.get("id")+ if sid not in recs:+ problems.append(f"{sid}: 没有这个镜头")+ continue+ clean, err = _clean(ans)+ if err:+ problems.append(f"{sid}: {err}")+ continue+ clean["_by"] = by+ rec = recs[sid]+ before = rec["base"]["label"]+ rec["review"] = clean+ applied.append(sid)+ changes.append((sid, before))+ 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/shots.py b/rea_video/shots.pynew file mode 100644index 0000000..4b6b599--- /dev/null+++ b/rea_video/shots.py@@ -0,0 +1,237 @@+"""Shot boundary detection: hard cuts, fades through black/white, dissolves.++Works on tiny thumbnails of every frame (cheap) and combines a colour-histogram+distance with a pixel difference so lighting flicker and fast motion do not fire+spurious cuts. Thresholds are adaptive to the local activity level."""+from __future__ import annotations++from dataclasses import dataclass, field++import cv2+import numpy as np++from .media import VideoInfo, iter_frames++THUMB_W = 96+++@dataclass+class FrameTrack:+ fps: float+ hist_dist: np.ndarray # bhattacharyya distance to previous frame (0..1)+ pix_diff: np.ndarray # mean |diff| of gray thumbs, 0..1+ changed: np.ndarray # fraction of thumb pixels that changed noticeably+ luma: np.ndarray # mean luma 0..255+ thumbs: list[np.ndarray] = field(repr=False, default_factory=list) # small gray thumbs (for dissolve check)+ hists: list[np.ndarray] = field(repr=False, default_factory=list)++ @property+ def n(self) -> int:+ return len(self.luma)+++@dataclass+class Shot:+ index: int+ start_frame: int+ end_frame: int # exclusive+ fps: float+ transition_in: str = "cut"+ boundary_score: float = 0.0+ beats: list[int] = field(default_factory=list) # frame indices of MG/slide beat changes inside the shot++ @property+ def start(self) -> float:+ return self.start_frame / self.fps++ @property+ def end(self) -> float:+ return self.end_frame / self.fps++ @property+ def duration(self) -> float:+ return (self.end_frame - self.start_frame) / self.fps++ def to_dict(self) -> dict:+ return {"index": self.index, "start": round(self.start, 3), "end": round(self.end, 3),+ "duration": round(self.duration, 3), "start_frame": self.start_frame, "end_frame": self.end_frame,+ "transition_in": self.transition_in, "boundary_score": round(self.boundary_score, 3),+ "beats": [round(b / self.fps, 3) for b in self.beats]}+++def _hist(bgr: np.ndarray) -> np.ndarray:+ hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)+ h = cv2.calcHist([hsv], [0, 1, 2], None, [16, 4, 4], [0, 180, 0, 256, 0, 256])+ cv2.normalize(h, h, alpha=1.0, norm_type=cv2.NORM_L1)+ return h.flatten().astype(np.float32)+++def build_track(path: str, info: VideoInfo) -> FrameTrack:+ hist_d, pix_d, chg, luma, thumbs, hists = [], [], [], [], [], []+ prev_h = prev_g = None+ for bgr in iter_frames(path, info, THUMB_W):+ g = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY).astype(np.float32)+ h = _hist(bgr)+ if prev_h is None:+ hist_d.append(0.0)+ pix_d.append(0.0)+ chg.append(0.0)+ else:+ d = np.abs(g - prev_g)+ hist_d.append(float(cv2.compareHist(prev_h, h, cv2.HISTCMP_BHATTACHARYYA)))+ pix_d.append(float(d.mean() / 255.0))+ thr = max(6.0, 0.35 * float(min(g.std(), prev_g.std())))+ chg.append(float((d > thr).mean()))+ luma.append(float(g.mean()))+ thumbs.append(g)+ hists.append(h)+ prev_h, prev_g = h, g+ fps = info.fps if info.fps > 0 else 30.0+ return FrameTrack(fps=fps, hist_dist=np.array(hist_d), pix_diff=np.array(pix_d), changed=np.array(chg), luma=np.array(luma),+ thumbs=thumbs, hists=hists)+++def _local_median(x: np.ndarray, radius: int) -> np.ndarray:+ out = np.empty_like(x)+ n = len(x)+ for i in range(n):+ lo, hi = max(0, i - radius), min(n, i + radius + 1)+ window = np.concatenate([x[lo:i], x[i + 1:hi]]) if hi - lo > 1 else x[lo:hi]+ out[i] = np.median(window) if len(window) else 0.0+ return out+++def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: float = 0.30,+ dissolve: bool = True) -> list[Shot]:+ n = track.n+ if n == 0:+ return []+ fps = track.fps+ score = 0.6 * track.hist_dist + 0.4 * np.clip(track.pix_diff * 4.0, 0, 1)+ score[0] = 0.0+ radius = max(4, int(round(fps * 0.5)))+ base = _local_median(score, radius)+ boundaries: dict[int, tuple[str, float]] = {}++ # 1) hard cuts: a spike well above local activity that changes most of the frame+ # (a title popping in over a static layout changes only a region -> not a cut)+ chg = track.changed+ chg_base = _local_median(chg, radius)+ for i in range(1, n):+ s = score[i]+ strong = s > cut_threshold and s > base[i] * 2.5 + 0.06 and chg[i] > 0.25+ relative = chg[i] > 0.45 and chg[i] > chg_base[i] * 3 + 0.2 and s > base[i] * 4 + 0.03+ if strong or relative:+ boundaries[i] = ("cut", float(max(s, chg[i])))++ # 2) fades through black / white: luma dips to an extreme and comes back+ lo_l = min(10.0, float(np.percentile(track.luma, 50)) * 0.35)+ dark = (track.luma < lo_l) | (track.luma > 248)+ i = 0+ while i < n:+ if dark[i]:+ j = i+ while j < n and dark[j]:+ j += 1+ if 0 < i and j < n and (j - i) <= fps * 2.5:+ # boundary at the last extreme frame (next shot starts after fade-in begins)+ mid = j+ if not any(abs(mid - b) < radius for b in boundaries):+ boundaries[mid] = ("fade", 0.5)+ i = j+ else:+ i += 1++ # 3) dissolves / cross-fades: frame i is a linear blend of frames i-k and i+k.+ # (camera or subject motion also changes the picture over 2k frames, but the middle+ # frame of a move is not a blend of its endpoints, so the blend residual separates them)+ if dissolve and n > 2 * fps:+ for k in sorted({max(2, int(round(fps * 0.12))), max(3, int(round(fps * 0.2))), max(5, int(round(fps * 0.45)))}):+ cand = []+ for i in range(k, n - k):+ A, B, M = track.thumbs[i - k], track.thumbs[i + k], track.thumbs[i]+ D = B - A+ thr = max(6.0, 0.35 * float(min(A.std(), B.std())))+ far = float((np.abs(D) > thr).mean())+ if far < 0.15 or float(score[i - k + 1:i + k + 1].max()) >= cut_threshold:+ continue+ denom = float((D * D).sum())+ if denom <= 0:+ continue+ alpha = float(((M - A) * D).sum() / denom)+ if not 0.2 <= alpha <= 0.8:+ continue+ resid = float(np.abs(M - (A + alpha * D)).mean() / (np.abs(D).mean() + 1e-6))+ if resid < 0.20 and not _motion_explains(A, B):+ cand.append((i, resid, far))+ cand.sort(key=lambda t: t[1])+ for i, resid, far in cand:+ if all(abs(i - bnd) > 2 * k for bnd in boundaries):+ boundaries[i] = ("dissolve", round(1 - resid, 3))++ beat_marks = [b for b, _ in _mg_beats(track, boundaries, fps)]++ # assemble shots, enforce minimum length (merge short ones into previous)+ min_len = max(1, int(round(min_shot_s * fps)))+ cuts = sorted(boundaries)+ shots: list[Shot] = []+ start, trans, bscore = 0, "start", 0.0+ for b in cuts + [n]:+ if b - start < min_len and b != n:+ continue+ if b == n and shots and b - start < min_len:+ shots[-1].end_frame = n+ break+ shots.append(Shot(index=len(shots) + 1, start_frame=start, end_frame=b, fps=fps, transition_in=trans, boundary_score=bscore))+ if b < n:+ trans, bscore = boundaries[b]+ start = b+ for shot in shots:+ shot.beats = [b for b in beat_marks if shot.start_frame + min_len <= b <= shot.end_frame - min_len]+ return shots+++def _mg_beats(track: FrameTrack, boundaries: dict[int, tuple[str, float]], fps: float) -> list[tuple[int, tuple[str, float]]]:+ """Find 'holds' (runs of frozen frames >= 0.4 s). Consecutive holds whose frames differ+ over a large area are different beats of a rendered (MG/slide) video."""+ n = track.n+ frozen = track.changed < 0.004+ min_run = max(3, int(round(0.4 * fps)))+ runs: list[tuple[int, int]] = []+ i = 0+ while i < n:+ if frozen[i]:+ j = i+ while j < n and frozen[j]:+ j += 1+ if j - i >= min_run:+ runs.append((i, j))+ i = j+ else:+ i += 1+ out: list[tuple[int, tuple[str, float]]] = []+ for (a0, a1), (b0, b1) in zip(runs, runs[1:]):+ if any(a1 - 1 <= k <= b0 + 1 for k in boundaries):+ continue # already separated by a detected cut/fade+ ta, tb = track.thumbs[(a0 + a1) // 2], track.thumbs[(b0 + b1) // 2]+ thr = max(6.0, 0.35 * float(min(ta.std(), tb.std())))+ frac = float((np.abs(ta - tb) > thr).mean())+ if frac > 0.12:+ # boundary at the start of the transition (end of hold A)+ out.append((a1, ("mg_transition", frac)))+ return out+++def _motion_explains(a: np.ndarray, b: np.ndarray) -> bool:+ """True when b is (mostly) a warped copy of a (zoom/pan/subject motion), i.e. the change+ between them is movement rather than new content fading in."""+ a8 = np.clip(a, 0, 255).astype(np.uint8)+ b8 = np.clip(b, 0, 255).astype(np.uint8)+ flow = cv2.calcOpticalFlowFarneback(a8, b8, None, 0.5, 3, 9, 3, 5, 1.1, 0)+ h, w = a8.shape+ gx, gy = np.meshgrid(np.arange(w, dtype=np.float32), np.arange(h, dtype=np.float32))+ warped = cv2.remap(b8, gx + flow[..., 0], gy + flow[..., 1], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)+ m = 4 # ignore borders+ before = float(np.abs(b8.astype(np.float32) - a8.astype(np.float32))[m:-m, m:-m].mean())+ after = float(np.abs(warped.astype(np.float32) - a8.astype(np.float32))[m:-m, m:-m].mean())+ return after < 0.45 * beforediff --git a/rea_video/sound_source.py b/rea_video/sound_source.pynew file mode 100644index 0000000..50408eb--- /dev/null+++ b/rea_video/sound_source.py@@ -0,0 +1,258 @@+"""Where did each sound come from? AI-generated vs existing material.++music : ai_generated (Suno/Udio/MiniMax Music...) | existing_library (stock/editor library BGM)+ | popular_song (a known commercial track) | unknown+sfx : library_editor (added in the edit from a sound library) | ai_native (generated together+ with an AI video clip, e.g. Seedance/Veo/Kling native audio) | live_sync (camera sound)+voice : tts | ai_video_native (generated with the clip, lip-synced) | human_recording++The audio alone rarely proves AI vs existing, so the decision combines a *format prior*+(an AI music-MV almost always carries an AI song; an ordinary video's BGM is usually a+library track), content evidence (lyrics written about this very video => custom song),+how the music was fitted (hard cut at the end => trimmed library track), platform music+metadata when supplied, per-clip audio resets at cuts (native audio of generated clips), and+the VLM's listening judgement. Every verdict carries probabilities, evidence and the cheapest+way to confirm it."""+from __future__ import annotations++import numpy as np++from .audio import SR, N_FFT, T_HOP, _stft+from .media import extract_audio++MUSIC_ZH = {"ai_generated": "AI 生成音乐", "existing_library": "现成曲库配乐", "popular_song": "现成知名歌曲", "unknown": "待确认"}+SFX_ZH = {"library_editor": "音效库/剪辑软件后期添加", "ai_native": "AI 视频模型随画面生成(原生音频)", "live_sync": "实拍同期声", "unknown": "待确认"}+VOICE_ZH = {"tts": "TTS 配音", "ai_video_native": "AI 视频原生对白(随画面生成)", "human_recording": "真人录音", "unknown": "待确认"}+++def _norm(d: dict) -> dict:+ s = sum(max(0.0, v) for v in d.values()) or 1.0+ return {k: round(max(0.0, v) / s, 3) for k, v in d.items()}+++def per_clip_audio(path: str, cuts: list[float], duration: float) -> dict:+ """Does the background sound (noise floor spectrum) jump at picture cuts? Clips that carry+ their own audio (AI video native sound, camera sound) reset at cuts; a voice-over + BGM+ laid over the whole edit does not."""+ if len(cuts) < 2:+ return {"ratio": None}+ x = extract_audio(path, SR)+ if x is None:+ return {"ratio": None}+ S = _stft(x)+ f = np.fft.rfftfreq(N_FFT, 1 / SR)+ edges = np.geomspace(60, 10000, 25)+ B = np.stack([10 * np.log10((S[:, (f >= a) & (f < b)] ** 2).sum(1) + 1e-12) for a, b in zip(edges[:-1], edges[1:])], 1)+ w = int(0.6 / T_HOP)++ def floor(a, b):+ a, b = max(0, a), min(len(B), b)+ return np.percentile(B[a:b], 15, axis=0) if b - a > 10 else None++ def jump(t):+ c = int(t / T_HOP)+ p, q = floor(c - w, c - 2), floor(c + 2, c + w)+ return None if p is None or q is None else float(np.mean(np.abs(p - q)))++ at = [v for v in (jump(t) for t in cuts) if v is not None]+ bounds = [0.0] + list(cuts) + [duration]+ mids = [(a + b) / 2 for a, b in zip(bounds[:-1], bounds[1:]) if b - a > 1.4]+ within = [v for v in (jump(t) for t in mids) if v is not None]+ if not at or not within:+ return {"ratio": None}+ r = float(np.median(at) / (np.median(within) + 1e-6))+ return {"ratio": round(r, 2), "at_cuts_db": round(float(np.median(at)), 1), "within_shots_db": round(float(np.median(within)), 1),+ "resets_at_cuts": r > 1.6}+++def music_ending(audio: dict, duration: float) -> str:+ m = audio.get("music") or {}+ ec = audio.get("energy_curve") or []+ if not m.get("present") or len(ec) < 8:+ return "unknown"+ end = m.get("end") or 0+ body = np.median(ec[: max(1, len(ec) - 6)])+ tail = ec[-2:]+ if duration - end < 1.0 and min(tail) > body - 6:+ return "hard_cut" # music still at full level when the video stops+ if duration - end < 3.0 and min(ec[-4:]) < body - 15:+ return "ends_with_video" # faded / resolved right at the end of the video+ return "ends_early"+++def classify_sound_sources(b: dict, meta: dict | None = None) -> dict:+ audio = b.get("audio") or {}+ if not audio.get("has_audio"):+ return {}+ whole = b.get("whole_video_vlm") or {}+ wm = whole.get("music") or {}+ nar = whole.get("narration") or {}+ meta = meta or b.get("platform_meta") or {}+ shots = b["shots"]+ dur = b["source"]["duration"]+ labels = [s["base"]["label"] for s in shots]+ ai_share = sum(s["duration"] for s in shots if s["base"]["label"] in ("ai_video", "avatar")) / max(dur, 1e-6)+ live_share = sum(s["duration"] for s in shots if s["base"]["label"] == "live_action") / max(dur, 1e-6)+ music = audio.get("music") or {}+ voice = audio.get("voice") or {}+ clip = b.get("per_clip_audio") or {}+ out: dict = {}++ # ---------------- format context --------------------------------------------------+ fmt = str(whole.get("format", ""))+ has_vocals = wm.get("has_vocals")+ vlm_mv = fmt.upper() == "MV" or "MV" in fmt.upper()+ # without the VLM: wall-to-wall music that also carries a voice, and no separate narration+ # sung vocals sit inside the mix, so HPSS finds only part of them (ratio 0.15+ is enough)+ # the voice must actually be sung/rapped (held pitches or beat-locked syllables), not TTS narration over BGM+ style = voice.get("style")+ sung = bool(voice.get("sung")) or style in ("singing", "rap_or_rhythmic")+ det_mv = bool(sung and music.get("ratio", 0) > 0.85 and voice.get("ratio", 0) > 0.15 and nar.get("type") in (None, "", "none"))+ is_mv = bool(vlm_mv or (has_vocals and music.get("ratio", 0) > 0.8 and nar.get("type") in (None, "", "none")))+ ctx = {"format": fmt or None, "music_mv": is_mv, "vocal_style": style, "music_mv_maybe": (not is_mv) and det_mv and not whole,+ "ai_picture_share": round(ai_share, 3), "live_picture_share": round(live_share, 3)}+ out["format_context"] = ctx++ # ---------------- music -------------------------------------------------------------+ if music.get("present") or wm.get("present"):+ ev: list[str] = []+ p = {"ai_generated": 0.2, "existing_library": 0.6, "popular_song": 0.2}+ if is_mv:+ p = {"ai_generated": 0.6, "existing_library": 0.1, "popular_song": 0.3}+ ev.append("视频形式是音乐 MV(整片是一首带人声的歌):这类内容的歌大概率是 AI 生成的(先验)")+ elif ctx["music_mv_maybe"]:+ p = {"ai_generated": 0.45, "existing_library": 0.25, "popular_song": 0.3}+ ev.append(f"整片音乐不间断,人声是唱的(持续音高占比 {voice.get('sustained_note_ratio', 0):.2f}):像一首带人声的歌/音乐 MV,AI 歌概率高(未开 VLM,按 MV 先验但降权)")+ else:+ ev.append("音乐是给画面垫底的配乐:普通视频的配乐大概率来自现成曲库(先验)")+ if voice.get("present") and style == "speech":+ ev.append(f"人声是说话/旁白而不是唱歌(持续音高占比 {voice.get('sustained_note_ratio', 0):.2f}):属于「旁白 + BGM」的普通视频形式")+ if wm.get("lyrics_match_content") is True:+ p["ai_generated"] += 1.2+ ev.append("歌词唱的正是这条视频的具体内容/角色/商品:为本片定制的歌,几乎只能是 AI 生成或专门创作")+ if wm.get("song_guess"):+ p["popular_song"] += 1.2+ ev.append(f"VLM 认出了歌曲:{wm['song_guess']}")+ sg = wm.get("source_guess")+ if sg in ("ai_generated", "popular_song", "stock_library"):+ key = {"stock_library": "existing_library"}.get(sg, sg)+ p[key] += 0.5+ ev.append(f"VLM 听感判断:{ {'ai_generated': 'AI 生成', 'popular_song': '知名歌曲', 'stock_library': '曲库配乐'}[sg] }")+ mt = (meta.get("music") or {}) if isinstance(meta.get("music"), dict) else {}+ if mt.get("title"):+ original = bool(mt.get("is_original")) or any(k in str(mt.get("title")) for k in ("原声", "original sound"))+ if original:+ p["ai_generated"] += 0.3 if (is_mv or ctx["music_mv_maybe"]) else 0.0+ ev.append(f"平台音乐信息是作者原声「{mt.get('title')}」:不是平台曲库里的现成歌曲")+ p["popular_song"] *= 0.4+ else:+ p["popular_song" if mt.get("popular") else "existing_library"] += 1.5+ ev.append(f"平台音乐信息:「{mt.get('title')}」{('— ' + str(mt.get('author'))) if mt.get('author') else ''}(现成曲目)")+ ending = music_ending(audio, dur)+ if ending == "hard_cut":+ if is_mv or ctx["music_mv_maybe"]: # a sung song cut mid-phrase: a clip of a released song, or just a trimmed AI song+ p["existing_library"] += 0.1+ p["popular_song"] += 0.1+ else:+ p["existing_library"] += 0.35+ p["popular_song"] += 0.15+ ev.append("片尾音乐被硬切断(还在满音量时视频就结束了):常见于截取现成曲目")+ elif ending == "ends_with_video":+ p["ai_generated"] += 0.15+ ev.append("音乐与视频同时收尾:按片长剪辑或定制过(两种来源都可能,弱证据)")+ prov = (b.get("provenance") or {}).get("aigc") or {}+ if prov.get("label") == "1":+ p["ai_generated"] += 0.15+ ev.append("文件带 AIGC 隐式标识(整片声明含 AI 生成内容,音乐可能也在其中,弱证据)")+ probs = _norm(p)+ lab = max(probs, key=probs.get)+ conf = probs[lab]+ out["music"] = {+ "source": lab if conf >= 0.45 else "unknown", "source_zh": MUSIC_ZH[lab if conf >= 0.45 else "unknown"],+ "leaning": lab, "probs": probs, "ending": ending, "evidence": ev,+ "how_to_confirm": [+ "在抖音/小红书原视频页面看音乐标签:显示歌名 → 现成曲目;显示「@作者创作的原声」→ 作者自己上传(MV 类多为 AI 歌)",+ "用汽水音乐/QQ 音乐「听歌识曲」或 ACRCloud 识别:识别得到就是现成歌曲",+ "听:AI 歌常见咬字含糊、高频发虚带金属感、歌词紧扣画面内容;曲库配乐多为无人声、结构标准、片尾被截断或淡出",+ ],+ }++ # ---------------- voice -------------------------------------------------------------+ if voice.get("present") or nar.get("type") not in (None, "", "none"):+ ev = []+ p = {"tts": 0.3, "ai_video_native": 0.1, "human_recording": 0.3}+ nt = nar.get("type")+ if nt == "tts":+ p["tts"] += 1.0+ ev.append("VLM 判断为 TTS 合成音")+ elif nt == "human":+ p["human_recording"] += 0.8+ ev.append("VLM 判断为真人声音")+ if live_share > 0.5:+ p["human_recording"] += 0.8+ ev.append(f"{live_share:.0%} 的画面是实拍:人声多为同期录音或真人配音")+ if ai_share > 0.4 and clip.get("resets_at_cuts"):+ p["ai_video_native"] += 1.0+ ev.append("背景声在每个切点跳变、画面是 AI 视频:人声很可能是视频模型连同画面一起生成的(如 Seedance/Veo/H3 原生音频)")+ elif clip.get("ratio") is not None and not clip.get("resets_at_cuts") and live_share < 0.3:+ p["tts"] += 0.4+ ev.append("人声和背景声跨切点连续:整条旁白是后期单独配上去的(TTS 或真人配音)")+ if voice.get("f0_cv") is not None and voice["f0_cv"] < 0.12:+ p["tts"] += 0.2+ ev.append(f"音高起伏偏平(变异系数 {voice['f0_cv']}),偏向 TTS(弱证据)")+ probs = _norm(p)+ lab = max(probs, key=probs.get)+ out["voice"] = {"source": lab if probs[lab] >= 0.45 else "unknown", "source_zh": VOICE_ZH[lab if probs[lab] >= 0.45 else "unknown"],+ "leaning": lab, "probs": probs, "evidence": ev}++ # ---------------- sfx ---------------------------------------------------------------+ sfx = (b.get("audio_plan") or {}).get("sfx_merged", [])+ if sfx or clip.get("resets_at_cuts"):+ ev = []+ p = {"library_editor": 0.4, "ai_native": 0.2, "live_sync": 0.1}+ synced = [e for e in sfx if e.get("sync_with") in ("cut", "text_pop", "transition") or e.get("sync_with_visual")]+ if sfx and len(synced) / len(sfx) >= 0.4:+ p["library_editor"] += 0.8+ ev.append(f"{len(synced)}/{len(sfx)} 个音效踩在切镜/文字弹出/转场上:剪辑时从音效库添加")+ if clip.get("resets_at_cuts") and ai_share > 0.4:+ p["ai_native"] += 1.0+ ev.append(f"背景声/环境声在切点跳变(切点 {clip.get('at_cuts_db')}dB vs 镜头内 {clip.get('within_shots_db')}dB),且画面是 AI 视频:每段自带的音效/环境声是视频模型原生生成的")+ if live_share > 0.5:+ p["live_sync"] += 1.0+ ev.append("画面以实拍为主:环境声多为同期声")+ if b["source"]["path"] and any(l == "cg_3d" for l in labels) and sfx and not clip.get("resets_at_cuts"):+ ev.append("3D/动画类视频的卡通音效也常由程序合成或音效库添加(例如 capsule-cinema plush 配方用程序合成)")+ probs = _norm(p)+ lab = max(probs, key=probs.get)+ out["sfx"] = {"source": lab if probs[lab] >= 0.45 else "unknown", "source_zh": SFX_ZH[lab if probs[lab] >= 0.45 else "unknown"],+ "leaning": lab, "probs": probs, "evidence": ev}++ # ---------------- one-line answer: video type -> where each sound comes from ---------------+ vt = video_type(ctx, voice, music, clip, ai_share, live_share)+ ctx["video_type"], ctx["video_type_zh"] = vt, VIDEO_TYPE_ZH[vt]+ parts = []+ for k, name in (("voice", "人声"), ("music", "音乐"), ("sfx", "音效")):+ v = out.get(k)+ if v:+ z = {"voice": VOICE_ZH, "music": MUSIC_ZH, "sfx": SFX_ZH}[k][v["leaning"]]+ parts.append(f"{name}{z}" + ("" if v["source"] != "unknown" and v["probs"][v["leaning"]] >= 0.6 else "(倾向,待确认)"))+ out["summary_zh"] = f"视频类型:{VIDEO_TYPE_ZH[vt]} → " + ";".join(parts)+ return out+++VIDEO_TYPE_ZH = {"music_mv": "音乐 MV / 歌曲类(整片是一首唱出来的歌)", "ai_native_audio": "AI 视频原生出声(每段画面自带声音)",+ "live": "实拍(同期声 + 后期配乐)", "narrated": "旁白/口播 + 配乐", "music_bed": "纯配乐(无人声)", "other": "其他"}+++def video_type(ctx: dict, voice: dict, music: dict, clip: dict, ai_share: float, live_share: float) -> str:+ if ctx.get("music_mv") or ctx.get("music_mv_maybe"):+ return "music_mv"+ if clip.get("resets_at_cuts") and ai_share > 0.4:+ return "ai_native_audio"+ if live_share > 0.5:+ return "live"+ if voice.get("present"):+ return "narrated"+ if music.get("present"):+ return "music_bed"+ return "other"diff --git a/rea_video/stems.py b/rea_video/stems.pynew file mode 100644index 0000000..311c737--- /dev/null+++ b/rea_video/stems.py@@ -0,0 +1,141 @@+"""Strip the soundtrack into stems: the original mix, vocals (dry voice / singing) and the rest (BGM + SFX + ambience).++Backend: UVR MDX-Net "Inst HQ 3" (ONNX, ~67 MB, CPU via onnxruntime). The model predicts the instrumental;+vocals = mix - instrumental. Weights come from the public UVR model repo on GitHub and are cached in+$REA_VIDEO_MODELS (default ~/.cache/rea-video/models).+"""+from __future__ import annotations++import logging+import os+import subprocess+import urllib.request+import uuid+from pathlib import Path++import numpy as np++LOG = logging.getLogger(__name__)+SR = 44100+MODEL_NAME = "UVR-MDX-NET-Inst_HQ_3.onnx"+MODEL_URL = f"https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models/{MODEL_NAME}"+N_FFT, HOP, DIM_F, DIM_T = 6144, 1024, 3072, 256+COMPENSATE = 1.022+CHUNK = HOP * (DIM_T - 1)+TRIM = N_FFT // 2+GEN = CHUNK - 2 * TRIM+WINDOW = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N_FFT) / N_FFT)).astype(np.float32) # periodic hann+++def models_dir() -> Path:+ return Path(os.getenv("REA_VIDEO_MODELS", str(Path.home() / ".cache/rea-video/models"))).expanduser()+++MODEL_BYTES = 66_759_214+++def ensure_model(force: bool = False) -> Path:+ p = models_dir() / MODEL_NAME+ if not force and p.is_file() and p.stat().st_size == MODEL_BYTES:+ return p+ p.parent.mkdir(parents=True, exist_ok=True)+ LOG.info("downloading %s (~67 MB) -> %s", MODEL_NAME, p)+ # per-process temp name: several decompose runs may download at the same time+ tmp = p.with_name(f"{p.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part")+ try:+ urllib.request.urlretrieve(MODEL_URL, tmp)+ if tmp.stat().st_size != MODEL_BYTES:+ raise OSError(f"incomplete download: {tmp.stat().st_size} bytes, expected {MODEL_BYTES}")+ tmp.replace(p) # atomic: readers see the old file or the complete new one+ finally:+ tmp.unlink(missing_ok=True)+ return p+++def _session():+ import onnxruntime as ort++ try:+ return ort.InferenceSession(str(ensure_model()), providers=["CPUExecutionProvider"])+ except Exception as e: # corrupted cache (e.g. an older interrupted download): fetch again once+ if "protobuf" not in str(e).lower() and "load model" not in str(e).lower():+ raise+ LOG.warning("cached stem model is unreadable (%s); downloading again", str(e)[:120])+ return ort.InferenceSession(str(ensure_model(force=True)), providers=["CPUExecutionProvider"])+++def load_stereo(path: str | Path) -> np.ndarray | None:+ r = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-vn", "-ac", "2", "-ar", str(SR), "-f", "f32le", "-"],+ capture_output=True)+ if r.returncode != 0 or not r.stdout:+ return None+ return np.frombuffer(r.stdout, np.float32).reshape(-1, 2).T.copy()+++def save_wav(x: np.ndarray, path: Path) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "f32le", "-ar", str(SR), "-ac", "2", "-i", "-",+ "-c:a", "pcm_s16le", str(path)], input=np.clip(x, -1, 1).T.astype(np.float32).tobytes(), check=True)+++def _stft(x: np.ndarray) -> np.ndarray:+ """x [2, CHUNK] -> model input [4, DIM_F, DIM_T] (L re, L im, R re, R im); same as torch.stft(center=True)."""+ xp = np.pad(x, ((0, 0), (N_FFT // 2, N_FFT // 2)), mode="reflect")+ idx = np.arange(DIM_T)[:, None] * HOP + np.arange(N_FFT)[None, :]+ spec = np.fft.rfft(xp[:, idx] * WINDOW, axis=-1) # [2, T, F]+ spec = spec.transpose(0, 2, 1)[:, :DIM_F] # [2, F, T]+ return np.stack([spec.real, spec.imag], axis=1).reshape(4, DIM_F, DIM_T).astype(np.float32)+++def _istft(s: np.ndarray) -> np.ndarray:+ s = s.reshape(2, 2, DIM_F, DIM_T)+ c = s[:, 0] + 1j * s[:, 1]+ c = np.concatenate([c, np.zeros((2, N_FFT // 2 + 1 - DIM_F, DIM_T), c.dtype)], axis=1) # [2, F, T]+ frames = np.fft.irfft(c.transpose(0, 2, 1), n=N_FFT, axis=-1) * WINDOW # [2, T, N_FFT]+ n = N_FFT + HOP * (DIM_T - 1)+ out = np.zeros((2, n), np.float32)+ norm = np.zeros(n, np.float32)+ for t in range(DIM_T):+ out[:, t * HOP:t * HOP + N_FFT] += frames[:, t]+ norm[t * HOP:t * HOP + N_FFT] += WINDOW ** 2+ out = out / np.maximum(norm, 1e-8)+ return out[:, N_FFT // 2:N_FFT // 2 + CHUNK]+++def separate(mix: np.ndarray, batch: int = 1) -> tuple[np.ndarray, np.ndarray]:+ """mix [2, n] -> (vocals, instrumental)."""+ sess = _session()+ n = mix.shape[1]+ pad = GEN - n % GEN+ mp = np.concatenate([np.zeros((2, TRIM), np.float32), mix, np.zeros((2, pad + TRIM), np.float32)], axis=1)+ starts = list(range(0, n + pad, GEN))+ pieces = []+ for i in range(0, len(starts), batch):+ specs = np.stack([_stft(mp[:, s:s + CHUNK]) for s in starts[i:i + batch]])+ outs = sess.run(None, {"input": specs})[0]+ pieces += [_istft(o)[:, TRIM:-TRIM] for o in outs]+ inst = np.concatenate(pieces, axis=1)[:, :n] * COMPENSATE+ return mix - inst, inst+++def _db(x: np.ndarray) -> float:+ return float(20 * np.log10(np.sqrt(np.mean(x ** 2)) + 1e-9))+++def extract_stems(path: str | Path, out_dir: str | Path) -> dict:+ """Write original.wav / vocals.wav / music.wav into out_dir/stems and return a short summary."""+ out = Path(out_dir) / "stems"+ mix = load_stereo(path)+ if mix is None or mix.shape[1] < SR // 2:+ return {"ok": False, "reason": "no audio"}+ save_wav(mix, out / "original.wav")+ try:+ voc, inst = separate(mix)+ except Exception as e: # missing onnxruntime / offline: keep the original track at least+ LOG.warning("stem separation failed: %s", e)+ return {"ok": False, "reason": f"{type(e).__name__}: {e}", "original": str(out / "original.wav")}+ save_wav(voc, out / "vocals.wav")+ save_wav(inst, out / "music.wav")+ return {"ok": True, "model": MODEL_NAME, "original": str(out / "original.wav"), "vocals": str(out / "vocals.wav"),+ "music": str(out / "music.wav"), "level_db": {"mix": round(_db(mix), 1), "vocals": round(_db(voc), 1),+ "music": round(_db(inst), 1)}}diff --git a/rea_video/util.py b/rea_video/util.pynew file mode 100644index 0000000..bb55f93--- /dev/null+++ b/rea_video/util.py@@ -0,0 +1,95 @@+"""Small shared helpers: logging, JSON IO, env loading, time formatting."""+from __future__ import annotations++import json+import logging+import os+import sys+from pathlib import Path+from typing import Any, Iterable++LOG = logging.getLogger("rea_video")+++def setup_logging(verbose: bool = False) -> None:+ level = logging.DEBUG if verbose else logging.INFO+ logging.basicConfig(level=level, format="%(asctime)s %(levelname)s %(message)s", datefmt="%H:%M:%S", stream=sys.stderr)+++def write_json(path: Path, data: Any) -> Path:+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(data, ensure_ascii=False, indent=2, default=_json_default) + "\n", encoding="utf-8")+ return path+++def read_json(path: Path) -> Any:+ return json.loads(Path(path).read_text(encoding="utf-8"))+++def _json_default(value: Any) -> Any:+ try:+ import numpy as np++ if isinstance(value, np.generic):+ return value.item()+ if isinstance(value, np.ndarray):+ return value.tolist()+ except ImportError: # pragma: no cover+ pass+ if isinstance(value, Path):+ return str(value)+ return str(value)+++def load_env_files(paths: Iterable[str | Path]) -> list[str]:+ """Minimal .env loader (KEY=VALUE lines). Existing env vars win. Returns loaded files."""+ loaded: list[str] = []+ for raw in paths:+ if not raw:+ continue+ p = Path(raw).expanduser()+ if not p.is_file():+ continue+ for line in p.read_text(encoding="utf-8", errors="ignore").splitlines():+ line = line.strip()+ if not line or line.startswith("#") or "=" not in line:+ continue+ if line.startswith("export "):+ line = line[len("export "):]+ key, _, value = line.partition("=")+ key = key.strip()+ value = value.strip().strip('"').strip("'")+ if key and key not in os.environ:+ os.environ[key] = value+ loaded.append(str(p))+ return loaded+++def fmt_time(seconds: float) -> str:+ seconds = max(0.0, float(seconds))+ m, s = divmod(seconds, 60)+ return f"{int(m):02d}:{s:06.3f}"+++def clamp(x: float, lo: float, hi: float) -> float:+ return max(lo, min(hi, x))+++def round_floats(obj: Any, nd: int = 4) -> Any:+ if isinstance(obj, float):+ return round(obj, nd)+ if isinstance(obj, dict):+ return {k: round_floats(v, nd) for k, v in obj.items()}+ if isinstance(obj, (list, tuple)):+ return [round_floats(v, nd) for v in obj]+ try:+ import numpy as np++ if isinstance(obj, np.floating):+ return round(float(obj), nd)+ if isinstance(obj, np.integer):+ return int(obj)+ except ImportError: # pragma: no cover+ pass+ return objdiff --git a/rea_video/visual.py b/rea_video/visual.pynew file mode 100644index 0000000..c8fb4ce--- /dev/null+++ b/rea_video/visual.py@@ -0,0 +1,152 @@+"""Contact sheets, storyboard image and face presence."""+from __future__ import annotations++from pathlib import Path++import cv2+import numpy as np+from PIL import Image, ImageDraw, ImageFont++from .util import fmt_time++LABEL_COLOR = {+ "live_action": (46, 160, 67), "ai_video": (217, 70, 239), "avatar": (236, 72, 153), "cg_3d": (14, 165, 233),+ "code_render": (245, 158, 11), "screen_capture": (100, 116, 139), "still_motion": (168, 85, 247),+ "static_hold": (148, 163, 184),+}+_FONT_CANDIDATES = [+ "/System/Library/Fonts/PingFang.ttc", "/System/Library/Fonts/STHeiti Light.ttc", "/System/Library/Fonts/Hiragino Sans GB.ttc",+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc",+ "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",+]+++def _font(size: int):+ for p in _FONT_CANDIDATES:+ if Path(p).is_file():+ try:+ return ImageFont.truetype(p, size)+ except OSError:+ continue+ return ImageFont.load_default()+++def _to_pil(bgr: np.ndarray) -> Image.Image:+ return Image.fromarray(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))+++def shot_sheet(frames: list[np.ndarray], times: list[float], out: Path, n: int = 4, cell_w: int = 240) -> Path | None:+ if not frames:+ return None+ idx = np.unique(np.linspace(0, len(frames) - 1, num=min(n, len(frames))).round().astype(int))+ cells = []+ font = _font(14)+ for i in idx:+ im = _to_pil(frames[i])+ im = im.resize((cell_w, int(im.height * cell_w / im.width)))+ d = ImageDraw.Draw(im)+ label = fmt_time(times[i])+ d.rectangle([0, 0, 72, 18], fill=(0, 0, 0))+ d.text((4, 2), label, fill=(255, 255, 255), font=font)+ cells.append(im)+ h = max(c.height for c in cells)+ sheet = Image.new("RGB", (cell_w * len(cells), h), (20, 20, 20))+ for k, c in enumerate(cells):+ sheet.paste(c, (k * cell_w, 0))+ out.parent.mkdir(parents=True, exist_ok=True)+ sheet.save(out, quality=88)+ return out+++def storyboard(items: list[tuple[np.ndarray, str, str, float, float]], out: Path, cols: int = 6, cell_w: int = 200) -> Path | None:+ """items: (frame, label, title, start, end)."""+ if not items:+ return None+ font = _font(15)+ small = _font(13)+ cells = []+ for frame, label, title, st, en in items:+ im = _to_pil(frame)+ im = im.resize((cell_w, int(im.height * cell_w / im.width)))+ bar = 40+ cell = Image.new("RGB", (cell_w, im.height + bar), (255, 255, 255))+ cell.paste(im, (0, 0))+ d = ImageDraw.Draw(cell)+ color = LABEL_COLOR.get(label, (80, 80, 80))+ d.rectangle([0, im.height, cell_w, im.height + bar], fill=color)+ d.text((6, im.height + 2), title, fill=(255, 255, 255), font=font)+ d.text((6, im.height + 21), f"{fmt_time(st)}–{fmt_time(en)}", fill=(255, 255, 255), font=small)+ cells.append(cell)+ ch = max(c.height for c in cells)+ rows = (len(cells) + cols - 1) // cols+ sheet = Image.new("RGB", (cell_w * min(cols, len(cells)), ch * rows), (240, 240, 240))+ for k, c in enumerate(cells):+ sheet.paste(c, ((k % cols) * cell_w, (k // cols) * ch))+ out.parent.mkdir(parents=True, exist_ok=True)+ sheet.save(out, quality=88)+ return out+++_CASCADE = None+++def face_presence(frames: list[np.ndarray]) -> float:+ """Fraction of frames with a frontal face covering >= 2% of the frame."""+ global _CASCADE+ if not frames:+ return 0.0+ if _CASCADE is None:+ try:+ path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml" # type: ignore[attr-defined]+ _CASCADE = cv2.CascadeClassifier(path)+ except Exception: # pragma: no cover+ _CASCADE = False+ if not _CASCADE or _CASCADE.empty():+ return 0.0+ hits = 0+ for f in frames[:: max(1, len(frames) // 6)]:+ g = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)+ faces = _CASCADE.detectMultiScale(g, scaleFactor=1.15, minNeighbors=5, minSize=(32, 32))+ area = g.shape[0] * g.shape[1]+ if any(w * h >= 0.02 * area for (_x, _y, w, h) in faces):+ hits += 1+ n = len(frames[:: max(1, len(frames) // 6)])+ return hits / max(1, n)+++def audio_timeline(audio: dict, sfx: list[dict], cuts: list[float], duration: float, out: Path, width: int = 1200) -> Path:+ """Lanes: loudness curve, voice, music (+beats), sfx markers, picture cuts."""+ lane_h, top = 26, 24+ lanes = ["响度", "人声", "音乐", "音效", "切镜"]+ h = top + lane_h * len(lanes) + 20+ im = Image.new("RGB", (width, h), (250, 250, 249))+ d = ImageDraw.Draw(im)+ font = _font(13)+ x0 = 52+ sx = (width - x0 - 10) / max(duration, 0.1)+ for i, name in enumerate(lanes):+ y = top + i * lane_h+ d.text((6, y + 5), name, fill=(60, 60, 60), font=font)+ d.line([(x0, y + lane_h - 1), (width - 10, y + lane_h - 1)], fill=(225, 225, 225))+ ec = audio.get("energy_curve") or []+ if ec:+ lo, hi = min(ec), max(ec)+ pts = [(x0 + i * 0.5 * sx, top + lane_h - 3 - (v - lo) / max(1e-6, hi - lo) * (lane_h - 6)) for i, v in enumerate(ec)]+ d.line(pts, fill=(100, 116, 139), width=1)+ for a, b in audio.get("voice", {}).get("segments", []):+ d.rectangle([x0 + a * sx, top + lane_h + 6, x0 + b * sx, top + 2 * lane_h - 6], fill=(37, 99, 235))+ for a, b in audio.get("music", {}).get("segments", []):+ d.rectangle([x0 + a * sx, top + 2 * lane_h + 6, x0 + b * sx, top + 3 * lane_h - 6], fill=(16, 185, 129))+ for bt in audio.get("music", {}).get("beats", [])[:600]:+ d.line([(x0 + bt * sx, top + 2 * lane_h + 2), (x0 + bt * sx, top + 2 * lane_h + 6)], fill=(6, 95, 70))+ for e in sfx:+ t = float(e.get("t", 0))+ c = (234, 88, 12) if e.get("source") == "vlm" else (251, 146, 60)+ d.ellipse([x0 + t * sx - 3, top + 3 * lane_h + 9, x0 + t * sx + 3, top + 3 * lane_h + 15], fill=c)+ for t in cuts:+ d.line([(x0 + t * sx, top + 4 * lane_h + 4), (x0 + t * sx, top + 5 * lane_h - 4)], fill=(30, 30, 30), width=2)+ for s in range(0, int(duration) + 1, max(1, int(duration // 10) or 1)):+ d.text((x0 + s * sx - 4, h - 18), f"{s}s", fill=(120, 120, 120), font=_font(11))+ out.parent.mkdir(parents=True, exist_ok=True)+ im.save(out)+ return outdiff --git a/rea_video/vlm.py b/rea_video/vlm.pynew file mode 100644index 0000000..19602f9--- /dev/null+++ b/rea_video/vlm.py@@ -0,0 +1,254 @@+"""OpenAI-compatible multimodal client (Gemini via proxy, Doubao, GPT, Qwen-VL...).++Config (first non-empty wins):+ REA_VLM_BASE_URL / REA_VLM_API_KEY / REA_VLM_MODEL+ VIDEO_ANALYSIS_BASE_URL / VIDEO_ANALYSIS_API_KEY / VIDEO_ANALYSIS_MODEL_NAME (capsule-cinema)+ GEMINI3_BASE_URL / GEMINI3_API_KEY / GEMINI3_MODEL_NAME (capsule-cinema)+REA_VLM_MODEL may be a comma-separated fallback list.+REA_VLM_MEDIA = both | video | frames (default both: a short clip as data:video/mp4 plus keyframes)+"""+from __future__ import annotations++import base64+import hashlib+import json+import os+import re+import time+import urllib.error+import urllib.request+from dataclasses import dataclass+from pathlib import Path++from .classify import LABELS+from .util import LOG+++@dataclass+class VLMConfig:+ base_url: str+ api_key: str+ models: list[str]+ timeout: float = 180.0+ media: str = "both"++ @classmethod+ def from_env(cls) -> "VLMConfig | None":+ """First complete config wins; later configs on the same endpoint and key add their+ models as fallbacks (capsule-cinema keeps one model in VIDEO_ANALYSIS_* and a list in GEMINI3_*)."""+ cfg: VLMConfig | None = None+ for prefix, mkey in (("REA_VLM", "REA_VLM_MODEL"), ("VIDEO_ANALYSIS", "VIDEO_ANALYSIS_MODEL_NAME"), ("GEMINI3", "GEMINI3_MODEL_NAME")):+ base, key = os.getenv(f"{prefix}_BASE_URL", "").rstrip("/"), os.getenv(f"{prefix}_API_KEY", "")+ models = [m.strip() for m in os.getenv(mkey, "").split(",") if m.strip()]+ if not (base and key and models):+ continue+ if cfg is None:+ cfg = cls(base_url=base, api_key=key, models=models,+ timeout=float(os.getenv("REA_VLM_TIMEOUT", os.getenv("VIDEO_ANALYSIS_TIMEOUT_SECONDS", "180"))),+ media=os.getenv("REA_VLM_MEDIA", "both"))+ elif prefix != "REA_VLM" and base == cfg.base_url and key == cfg.api_key:+ cfg.models += [m for m in models if m not in cfg.models]+ return cfg++ def describe(self) -> str:+ host = re.sub(r"^https?://", "", self.base_url).split("/")[0]+ return f"{','.join(self.models)} @ {host}"+++SETUP_HINT = ("建议配置 VLM(任意 OpenAI 兼容的多模态模型,如 Gemini / GPT-4o / 豆包 / Qwen-VL):"+ "设置 REA_VLM_BASE_URL、REA_VLM_API_KEY、REA_VLM_MODEL(可写多个模型逗号分隔做备选),再加 --vlm 重跑")+++def vlm_note(info: dict, review: dict | None = None) -> str:+ """One line for reports / summaries: did the VLM (or an agent's review) actually contribute, and what to do if not."""+ base = _vlm_note(info)+ if review and review.get("shots"):+ seen = f"由 {review.get('by', 'agent')} 看图复核 {review['shots']}/{review.get('of', '?')} 个镜头,已并入结论"+ return seen if (info.get("status") or "off") == "off" else f"{base.split(';')[0]};{seen}"+ return base+++def _vlm_note(info: dict) -> str:+ status = info.get("status") or ("ok" if info.get("used") else "off")+ if status == "ok":+ return f"VLM 已生效({info.get('model', '')})"+ if status == "partial":+ return (f"VLM 部分生效({info.get('model', '')}:{info.get('ok_shots', 0)}/{info.get('asked_shots', 0)} 个镜头有结果,"+ f"整片分析{'有' if info.get('whole_ok') else '失败'});失败的镜头只靠确定性取证")+ limited = "实拍/AI/3D 的区分只靠像素统计,可信度有限"+ if status == "failed":+ err = (info.get("errors") or [""])[0]+ return f"VLM 已请求但全部调用失败({info.get('model', '')}:{err[:80]}),本次等同未开 VLM;{limited}。可稍后重试或换模型"+ if status == "not_configured":+ return f"VLM 已请求但没找到配置,本次未开 VLM;{limited}。{SETUP_HINT}"+ return f"未开 VLM;{limited}。能看图的 agent:运行 rea-video review 逐镜看图并 apply-review 并入;否则{SETUP_HINT}"+++def _data_uri(path: Path, mime: str) -> str:+ return f"data:{mime};base64," + base64.b64encode(path.read_bytes()).decode()+++def parse_json(text: str) -> dict:+ text = text.strip()+ text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text)+ m = re.search(r"\{[\s\S]*\}", text)+ if not m:+ raise ValueError("no JSON object in VLM response")+ return json.loads(m.group(0))+++class VLMClient:+ # after this many requests in a row fail on every model, stop calling the service for this run+ MAX_DEAD_REQUESTS = 2++ def __init__(self, cfg: VLMConfig, cache_dir: Path | None = None):+ self.cfg = cfg+ self.cache_dir = cache_dir+ self.dead_requests = 0+ self.models = list(cfg.models) # reordered: the last model that answered goes first+ if cache_dir:+ cache_dir.mkdir(parents=True, exist_ok=True)++ @property+ def gave_up(self) -> bool:+ return self.dead_requests >= self.MAX_DEAD_REQUESTS++ def _post(self, model: str, content: list[dict], max_tokens: int) -> str:+ body = json.dumps({"model": model, "messages": [{"role": "user", "content": content}],+ "max_tokens": max_tokens, "temperature": 0.2}).encode()+ req = urllib.request.Request(self.cfg.base_url + "/chat/completions", data=body, method="POST",+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.cfg.api_key}"})+ with urllib.request.urlopen(req, timeout=self.cfg.timeout) as resp:+ data = json.loads(resp.read().decode())+ return data["choices"][0]["message"]["content"]++ def ask_json(self, prompt: str, media: list[tuple[Path, str]], max_tokens: int = 4096) -> dict:+ h = hashlib.sha1(prompt.encode())+ for p, mime in media:+ h.update(mime.encode())+ h.update(hashlib.sha1(p.read_bytes()).digest())+ key = h.hexdigest()+ if self.cache_dir and (self.cache_dir / f"{key}.json").is_file():+ return json.loads((self.cache_dir / f"{key}.json").read_text(encoding="utf-8"))+ if self.gave_up:+ raise RuntimeError("VLM skipped: service failed on every model for earlier requests")+ content = [{"type": "image_url", "image_url": {"url": _data_uri(p, mime)}} for p, mime in media]+ content.append({"type": "text", "text": prompt})+ last: Exception | None = None+ for model in list(self.models):+ for attempt in range(2):+ try:+ t = time.time()+ text = self._post(model, content, max_tokens)+ out = parse_json(text)+ out["_model"] = model+ out["_seconds"] = round(time.time() - t, 1)+ if self.cache_dir:+ (self.cache_dir / f"{key}.json").write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")+ self.dead_requests = 0+ if self.models[0] != model:+ self.models.remove(model)+ self.models.insert(0, model)+ return out+ except (urllib.error.URLError, TimeoutError, ValueError, KeyError, json.JSONDecodeError) as exc:+ last = exc+ LOG.warning("VLM %s attempt %d failed: %s", model, attempt + 1, str(exc)[:200])+ time.sleep(1.5)+ if not isinstance(last, (ValueError, KeyError)): # transport/server errors, not a bad answer+ self.dead_requests += 1+ raise RuntimeError(f"all VLM models failed: {last}")+++SHOT_PROMPT = """你是视频制作逆向工程专家。判断这个镜头的「底层画面」是用什么方式制作的,并给出可复刻的描述。+只依据你在画面里看到的证据;不确定时如实给出概率分布。++底层画面类别(label_probs 的 key,概率和为 1):+- live_action:真实摄像机/手机实拍(真实人物与环境、真实光影与物理、传感器噪声、手持抖动、对焦呼吸、运动模糊自然)+- ai_video:AI 生成视频(文生/图生/参考生视频)。常见破绽:物体或手指形变、纹理"沸腾"闪烁、物理不合理、文字乱码、背景人物畸形、过于完美的光线与皮肤、动作缓慢漂浮、镜头结尾定格+- avatar:数字人口播(一张人像被音频驱动说话,嘴型驱动、头部轻微摆动、身体几乎不动)+- cg_3d:传统 3D 渲染(Blender/C4D/UE),几何干净、材质规则、光影一致、运动精确无形变+- code_render:代码/模板渲染的 2D 画面(MG 动效、文字排版、UI、图表、PPT 式卡片)+- screen_capture:屏幕录制或网页/应用截图(真实界面元素、光标、滚动)+- still_motion:一张静态图片做推拉摇移(Ken Burns),画面内部无独立运动+- static_hold:静帧定格(图片或卡片停留不动)++另外判断画面里有没有「引入的真实素材」:实拍片段、真实照片、商品实拍图、品牌 Logo、网页/App 截图或录屏。+它们通常是用户自己提供的素材,复刻时不能用模型生成替代,请在 embedded_assets 里逐个列出。++注意区分:卡通/3D 风格的 AI 视频(形变、闪烁、不精确)与真正的 3D 渲染(几何稳定、精确);+AI 生成的写实视频与实拍(看手、文字、背景细节、物理)。++确定性分析给出的参考信号(可能有误,以画面为准):+{hints}++只返回 JSON,不要任何其他文字:+{{+ "label_probs": {{"live_action": 0, "ai_video": 0, "avatar": 0, "cg_3d": 0, "code_render": 0, "screen_capture": 0, "still_motion": 0, "static_hold": 0}},+ "image_source": "ai_image|photo|graphic|screenshot|unknown",+ "evidence": ["具体可见证据,尽量指明位置/时间"],+ "generator_guess": "可能的生成模型或工具(如 Seedance/Kling/Veo/Hailuo/Blender/Remotion/剪映 模板),无法判断写 unknown",+ "description": "镜头内容:主体、动作、场景、景别、运镜、光线",+ "shot_size": "特写|近景|中景|全景|远景",+ "camera_move": "固定|推|拉|摇|移|跟|环绕|手持",+ "style": "画风/质感关键词",+ "overlay_text": ["后期叠加在画面上的文字(字幕/标题),不含场景里的实物文字"],+ "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": {{+ "image_prompt": "复刻首帧的中文图像提示词(主体、构图、光线、风格,具体可执行)",+ "video_prompt": "复刻该镜头的中文视频提示词:写清动作过程和结束状态、运镜;只写想要的内容,不写否定句",+ "video_prompt_en": "same video prompt in English"+ }}+}}"""+++WHOLE_PROMPT = """你是短视频拆解专家。完整观看并**仔细收听**这条视频,拆解它的结构、文案、声音与整体制作方式。+声音要拆到可以复刻:旁白是真人还是 TTS、音色;背景音乐的风格/情绪/节奏/是否 AI 生成或知名歌曲;+判断音乐来源时结合视频形式:AI 音乐 MV(整片一首歌、歌词唱的就是画面内容)大概率是 AI 生成的歌;普通视频的垫底配乐大概率是现成曲库;+能认出歌名就写出来;lyrics_match_content 表示歌词是否在唱这条视频的具体内容/角色/商品。+每一个音效出现的时间点、类型,以及它对应画面上的什么事件。+已检测到的镜头切分(秒):{shots}++只返回 JSON:+{{+ "summary": "一句话概括",+ "format": "口播|剧情|商品展示|知识讲解|MV|混剪|其他",+ "hook": "开头 3 秒如何抓人",+ "segments": [{{"start": 0.0, "end": 3.0, "beat": "这一段在叙事上的作用", "copy": "这一段的旁白/字幕文案", "audio": "人声/音乐/音效"}}],+ "narration": {{"type": "tts|human|none|mixed", "voice": "性别/年龄感/音色", "style": "语速、情绪、口癖", "language": "zh|en|...",+ "lines": [{{"start": 0.0, "end": 2.0, "text": "台词/旁白原文"}}]}},+ "music": {{"present": true, "segments": [{{"start": 0.0, "end": 10.0}}], "style": "风格", "genre": "流派", "mood": "情绪",+ "instruments": ["主要乐器"], "bpm_estimate": 0, "has_vocals": false,+ "source_guess": "ai_generated|stock_library|popular_song|original|unknown", "song_guess": "若是知名歌曲写歌名,否则空",+ "lyrics_excerpt": "若有人声演唱,摘几句歌词", "lyrics_match_content": false,+ "ending": "natural_end|fade_out|hard_cut",+ "beat_synced_cuts": false}},+ "sfx": [{{"t": 0.0, "type": "whoosh|pop|ding|click|typing|impact|laugh|applause|notification|cash|other", "description": "听到的声音",+ "sync_with": "cut|text_pop|action|transition|none"}}],+ "ambience": "环境声(街道、室内、无)",+ "mix": "人声/BGM/音效的音量关系,是否有人声出现时压低音乐(ducking)",+ "subtitles": {{"present": true, "style": "字体/描边/颜色/位置/逐字高亮等"}},+ "overall_production": "整体制作方式判断(实拍/AI生成/代码渲染/混合)与理由",+ "warnings": []+}}"""+++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]+ parts.append(f"temporal_family={facts.get('temporal_family')}, pulldown={facts.get('pulldown')}, graphic_score={facts.get('graphic_score')}")+ parts.append(f"确定性初判={det_top} ({det_prob:.0%})")+ return "; ".join(parts)+++def normalize_shot_result(raw: dict) -> dict:+ probs = raw.get("label_probs") or {}+ clean = {}+ for k in LABELS:+ try:+ clean[k] = max(0.0, float(probs.get(k, 0.0)))+ except (TypeError, ValueError):+ clean[k] = 0.0+ total = sum(clean.values()) or 1.0+ raw["label_probs"] = {k: v / total for k, v in clean.items()}+ return rawdiff --git a/scripts/install_skill.sh b/scripts/install_skill.shnew file mode 100755index 0000000..e2ca7e6--- /dev/null+++ b/scripts/install_skill.sh@@ -0,0 +1,12 @@+#!/usr/bin/env bash+# 把 rea-video skill 链接到常见 agent 的 skills 目录,并安装 CLI。+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+PY="${PYTHON_BIN:-python3}"+"$PY" -m pip install -e "$ROOT[ocr]"+for dir in "$HOME/.claude/skills" "$HOME/.codex/skills" "$HOME/.agents/skills"; do+ mkdir -p "$dir"+ ln -sfn "$ROOT/skills/rea-video" "$dir/rea-video"+ echo "linked $dir/rea-video"+done+echo "done. 试试:rea-video --help"diff --git a/scripts/validate_capabilities.py b/scripts/validate_capabilities.pynew file mode 100644index 0000000..0043779--- /dev/null+++ b/scripts/validate_capabilities.py@@ -0,0 +1,181 @@+#!/usr/bin/env python3+"""校验 rea-video 能力地图,并可生成能力矩阵。++用法:+ python3 scripts/validate_capabilities.py # 只校验+ python3 scripts/validate_capabilities.py --matrix # 校验并写出 capabilities/MATRIX.md++检查项:+ 1. 每个模型条目符合 capabilities/schema.json+ 2. 模型 id 全局唯一;primitives 引用都存在+ 3. 每个原语至少有一个可用(非 shutdown)模型,分析/渲染类除外的空缺会报 warning+ 4. routing.yaml 中 signals/route/prefer/verify 引用都存在+ 5. prefer 中的每个模型至少支持 route 链中的一个原语+ 6. verified.date 超过 90 天给 warning(提示需要复核)+"""+from __future__ import annotations++import datetime as dt+import json+import sys+from pathlib import Path++import yaml+try:+ from jsonschema import Draft202012Validator as SchemaValidator+except ImportError: # 旧版 jsonschema+ from jsonschema import Draft7Validator as SchemaValidator++ROOT = Path(__file__).resolve().parent.parent+CAP = ROOT / "capabilities"+STALE_DAYS = 90+++def _normalize(x):+ """YAML 会把 2026-10-29 解析成 date,这里统一转回字符串。"""+ if isinstance(x, (dt.date, dt.datetime)):+ return x.isoformat()+ if isinstance(x, dict):+ return {k: _normalize(v) for k, v in x.items()}+ if isinstance(x, list):+ return [_normalize(v) for v in x]+ return x+++def load_yaml(p: Path):+ with p.open(encoding="utf-8") as f:+ return _normalize(yaml.safe_load(f))+++def main() -> int:+ errors: list[str] = []+ warnings: list[str] = []++ schema = json.loads((CAP / "schema.json").read_text(encoding="utf-8"))+ validator = SchemaValidator(schema)++ prim_doc = load_yaml(CAP / "primitives.yaml")+ metrics = set(prim_doc["metrics"].keys())+ primitives = {p["id"]: p for p in prim_doc["primitives"]}+ if len(primitives) != len(prim_doc["primitives"]):+ errors.append("primitives.yaml 中存在重复的原语 id")+ for p in prim_doc["primitives"]:+ for m in p.get("metrics", []):+ if m not in metrics:+ errors.append(f"原语 {p['id']} 引用了未定义的指标 {m}")++ models: dict[str, dict] = {}+ model_file: dict[str, str] = {}+ for f in sorted((CAP / "models").glob("*.yaml")):+ doc = load_yaml(f) or {}+ for m in doc.get("models", []):+ mid = m.get("id", "<missing id>")+ for e in validator.iter_errors(m):+ loc = "/".join(str(x) for x in e.absolute_path)+ errors.append(f"{f.name}:{mid}: schema 错误 {loc}: {e.message}")+ if mid in models:+ errors.append(f"模型 id 重复: {mid}({model_file[mid]} 与 {f.name})")+ models[mid] = m+ model_file[mid] = f.name+ for pid in m.get("primitives", []):+ if pid not in primitives:+ errors.append(f"{f.name}:{mid}: 未知原语 {pid}")+ d = m.get("verified", {}).get("date")+ if d:+ age = (dt.date.today() - dt.date.fromisoformat(d)).days+ if age > STALE_DAYS:+ warnings.append(f"{mid}: 验证日期 {d} 已超过 {STALE_DAYS} 天,需要复核")++ live = {k: v for k, v in models.items() if v.get("status") != "shutdown"}+ by_prim: dict[str, list[str]] = {p: [] for p in primitives}+ for mid, m in live.items():+ for pid in m.get("primitives", []):+ if pid in by_prim:+ by_prim[pid].append(mid)+ for pid, ms in by_prim.items():+ if not ms:+ warnings.append(f"原语 {pid} 目前没有可用模型")++ routing = load_yaml(CAP / "routing.yaml")+ signals = set(routing.get("signals", {}).keys())+ for sname, s in routing.get("signals", {}).items():+ for pid in s.get("detected_by", []):+ if pid not in primitives:+ errors.append(f"signal {sname}: 未知原语 {pid}")++ def check_rule(r: dict, kind: str) -> None:+ rid = r.get("id", "<no id>")+ for s in (r.get("when") if isinstance(r.get("when"), list) else []):+ if s not in signals:+ errors.append(f"{kind} {rid}: 未知 signal {s}")+ route = r.get("route", [])+ for pid in route:+ if pid not in primitives:+ errors.append(f"{kind} {rid}: 未知原语 {pid}")+ for mid in r.get("prefer", []):+ if mid not in models:+ errors.append(f"{kind} {rid}: 未知模型 {mid}")+ continue+ if models[mid].get("status") == "shutdown":+ errors.append(f"{kind} {rid}: 引用了已关停模型 {mid}")+ if not set(models[mid]["primitives"]) & set(route):+ errors.append(f"{kind} {rid}: 模型 {mid} 不支持 route 中任何原语 {route}")+ for met in r.get("verify", []):+ if met not in metrics:+ errors.append(f"{kind} {rid}: 未知指标 {met}")+ for pid in route:+ if pid in by_prim and not by_prim[pid]:+ errors.append(f"{kind} {rid}: 原语 {pid} 没有任何可用模型")++ for key in ("rules", "audio_rules", "post_rules"):+ ids = [r.get("id") for r in routing.get(key, [])]+ if len(ids) != len(set(ids)):+ errors.append(f"routing.{key} 中存在重复 id")+ for r in routing.get(key, []):+ check_rule(r, key)++ # ---------- 输出 ----------+ print(f"原语 {len(primitives)} 个,指标 {len(metrics)} 个,模型 {len(models)} 个(可用 {len(live)}),"+ f"画面规则 {len(routing.get('rules', []))} 条,音频规则 {len(routing.get('audio_rules', []))} 条")+ for w in warnings:+ print(f"WARN {w}")+ for e in errors:+ print(f"ERROR {e}")++ if "--matrix" in sys.argv and not errors:+ write_matrix(primitives, models, by_prim)+ print("已写出 capabilities/MATRIX.md")++ if errors:+ print(f"\n校验失败:{len(errors)} 个错误")+ return 1+ print("\n校验通过")+ return 0+++def write_matrix(primitives: dict, models: dict, by_prim: dict) -> None:+ conf = {"high": "●", "medium": "◐", "low": "○"}+ lines = [+ "# 能力矩阵(自动生成,请勿手改)",+ "",+ "由 `python3 scripts/validate_capabilities.py --matrix` 根据 `capabilities/` 生成。",+ "置信度:● high ◐ medium ○ low。已关停的模型不列出。",+ "",+ "| 原语 | 名称 | 可用模型 |",+ "|---|---|---|",+ ]+ for pid, p in primitives.items():+ ms = sorted(by_prim[pid])+ cell = "、".join(f"{conf[models[m]['confidence']]} `{m}`" for m in ms) or "—(空缺)"+ lines.append(f"| `{pid}` | {p['name']} | {cell} |")+ lines += ["", "## 模型一览", "", "| 模型 | 厂商 | 类别 | 状态 | 时长上限(s) | 原生音频 | 商用 | 验证依据 |", "|---|---|---|---|---|---|---|---|"]+ for mid, m in sorted(models.items(), key=lambda kv: (kv[1]["category"], kv[0])):+ dur = (m.get("limits", {}).get("duration_s") or {}).get("max", "")+ aud = {True: "是", False: "否"}.get((m.get("audio") or {}).get("native"), "")+ com = {True: "是", False: "否", "conditional": "有条件"}[m["license"]["commercial"]]+ lines.append(f"| {m['name']} | {m['vendor']} | {m['category']} | {m['status']} | {dur} | {aud} | {com} | {m['verified']['basis']} {m['verified']['date']} |")+ (CAP / "MATRIX.md").write_text("\n".join(lines) + "\n", encoding="utf-8")+++if __name__ == "__main__":+ sys.exit(main())diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.mdnew file mode 100644index 0000000..024f79f--- /dev/null+++ b/skills/rea-video/SKILL.md@@ -0,0 +1,153 @@+---+name: rea-video+description: 逆向拆解一条视频是怎么做出来的——逐镜头判断实拍 / AI 生成 / 3D 渲染 / 代码模板渲染 / 录屏截图 / 静态图推拉 / 静帧,标出后期叠加层和用户真实素材,拆解人声、背景音乐、音效与剪辑节奏,并给出可执行的复刻方案(可对接 capsule-cinema)。当用户给出参考视频、问"这条视频怎么做的 / 是不是 AI / 用了什么素材 / 怎么复刻"时使用。+---++# rea-video:视频制作方式逆向拆解++你是视频制作的逆向工程师。用户给你一条视频,你要回答清楚:++1. **每个镜头的底层画面是怎么来的?**从 8 类里选:实拍 / AI 视频 / 数字人 / 3D 渲染 / 代码模板渲染 / 录屏截图 / 静态图推拉 / 静帧。+2. **上面叠了什么?**字幕、标题、文字标注、贴片、版式模板。+3. **哪些是用户真实素材?**实拍、照片、截图、录屏、商品图、Logo。复刻时这些不能用模型生成替代,必须标出来。+4. **声音怎么做的?**人声(TTS 还是真人)、BGM(风格 / BPM / 调性 / 段落)、音效(时间点、类型、对应哪个画面事件),以及切镜是否卡在节拍上。**重点是来源:AI 生成的还是现成的。**先看视频形式——AI 音乐 MV(整片是一首唱出来的歌)大概率是 AI 歌;普通视频配乐大概率是现成曲库,但 AI 工作流的视频 BGM 也常是 Suno 生成,必须标"待确认"并给确认方法。+5. **怎么复刻?**每镜给出路线和工具,AI 类镜头可以交给 capsule-cinema 生成。++核心原则:**每个结论都要有证据,确定不了就如实写"待确认"并说明还缺什么。**宁可写"实拍还是 AI 待确认(倾向 AI 70%)",也不要编一个确定的答案。++## 0. 环境(一次性)++```bash+cd <rea-video 仓库>+pip install -e ".[ocr]" # 需要 ffmpeg;Python ≥ 3.10+rea-video --help+```++**VLM(建议配置,不强制)**:VLM 是能看图/看视频的多模态大模型(Gemini、GPT-4o、豆包、Qwen-VL 等)。不开 VLM,工具只靠像素统计、帧率、OCR、元数据判断,照样能跑完、出报告,但**实拍 / AI / 3D 的区分明显变弱**,音效清单也只有信号层的低置信候选。开了 VLM,工具会把每个镜头的短片段和关键帧发给它,再和确定性结果融合。++配置走 OpenAI 兼容接口,按以下顺序读取:++1. `REA_VLM_BASE_URL` / `REA_VLM_API_KEY` / `REA_VLM_MODEL`(`REA_VLM_MODEL` 可写多个模型、逗号分隔,前一个失败自动换下一个)+2. 如果没有,回落到 capsule-cinema 的 `VIDEO_ANALYSIS_*` 或 `GEMINI3_*`++用 `--env-file <某个 .env>` 读取配置(例如复用 capsule-cinema 的)。**不要把密钥写进对话、仓库或报告,也不要打开 .env 看内容。**++用户没配 VLM 时:照常不加 `--vlm` 跑,不要因此中止任务。++- **你自己能看图(多模态 agent)**:你就是这次的"VLM",不需要建议用户另配。按第 1 节的「看图复核并入」做:`rea-video review` → 逐镜看图填答案 → `rea-video apply-review`,你的判断会并入工具结论和报告。结论里写"未开 VLM,由 agent 看图复核"。+- **你看不了图**:遵守下面「看不了图时的规则」,并在回复末尾用一句话建议配置 VLM(说明能提升实拍/AI/3D 的区分和音效识别)。+- 实测(2026-10-30,eval/RESULTS.md):agent 看图复核并入比单开 Gemini VLM 更准;Gemini 容易把卡通 3D 风格的 AI 视频判成 3D 渲染、把画进画面的游戏界面判成录屏。所以能看图时**一定要做看图复核**,开了 VLM 也要做,并且独立判断,不要照抄 VLM。+- 外部 VLM 仍有你替代不了的部分:它能直接看视频片段的运动、听音轨。你只能看静帧、听不了声音时,音效和人声来源照样标"待确认"。++**VLM 是否真的生效,以 `rea-video summary` 的 `VLM:` 一行为准**(也在 `breakdown.json` 的 `analysis.vlm.status`):`ok` 已生效、`partial` 部分镜头有结果、`failed` 请求了但全部调用失败(例如服务端 503)、`not_configured` 请求了但没找到配置、`off` 没请求。`failed` / `not_configured` 等同没开 VLM,报告里要如实写,不能写"已开 VLM"。++## 1. 标准流程++```bash+# ⓪ 先看记住了什么:用户偏好(默认引擎、是否开 VLM、给你的偏好说明)和常见纠正类型+rea-video memory+# ① 拆解(产出 out/<名>/breakdown.json、report.html、report.md、storyboard.jpg、audio.png、shots/、stems/)+rea-video --env-file ~/code/github/capsule-cinema/.env decompose ref.mp4 -o out/ref --vlm # 没有 VLM 配置就去掉 --env-file 和 --vlm+# ② 看紧凑摘要:低置信镜头会被标出;先看 VLM: 那一行确认 VLM 是否生效+rea-video summary out/ref/breakdown.json+```++### 看图复核并入(能看图的 agent 必做,开了 VLM 也建议做低置信镜头)++```bash+rea-video review out/ref # 写出 review_tasks.json(每镜要看的图、工具判断、优先级)和 review_answers.json(答案模板)+# 读 review_tasks.json 的 instructions,逐镜看 images 里的图(priority=high 必看),把 label_probs / evidence / description / embedded_assets 填进 review_answers.json+rea-video apply-review out/ref --by <你的名字> # 并入:重写 breakdown.json、report.md、report.html,打印改判了哪些镜头+rea-video summary out/ref/breakdown.json # 用并入后的结果写回复+```++没看过的镜头保持 label_probs 全 0,会被跳过。你的答案会和确定性结果融合(不是直接覆盖),所以帧率、AIGC 标识这类强证据仍然起作用;如果并入后的结论和你的看法不同,在回复里写明理由。++融合规则(实测得来,见 `eval/RESULTS.md`):+- 只有一个看图来源(只有 VLM 或只有你)时,看图结果只能在工具前两名候选里选。工具对"AI / 实拍 / 数字人"有把握时不改;转码的 24fps 素材不会仅凭"看起来真"改成实拍。看图结果在 3D / 代码动效 / 录屏之间的区分最有用。+- VLM 和你都答了:工具首选只要有你们其中一方支持,就按工具首选;你们两个一致反对工具时,按正常融合。+- review_tasks.json 里写着"用户过去 n 次把工具判的 X 改成 Y"的镜头,是用户反复纠正过的类型,要重点看。++然后**一定要自己复核**,不要直接转述工具输出:++1. 先看 `storyboard.jpg` 和 `audio.png`,对整片建立整体印象。+2. 对标了"低置信,需要复核"的镜头,或"次选"概率很接近的镜头:+ - 打开 `shots/shot_XXX.jpg`(首、中、尾联系表)。+ - 必要时抽帧细看:`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` 加进评测集。++### 看不了图时的规则(重要)++先确认你自己能不能看图(能不能读 `storyboard.jpg`、`shots/*.jpg` 并描述画面内容)。**看不了图、又没开 VLM 时:**++- **不要推翻工具对制作方式的判断**(实拍 / AI / 3D / 代码 / 录屏)。像素统计(用色数、平坦块、噪声)正是工具已经用过的证据,你再用一遍只会得出同样或更差的结论。实测:看不了图的 agent 把 AI 生成的铅笔素描判成"白底版式卡"、把玻璃质感 3D 元素判成"代码界面"。+- 你能做、也应该做的:核对时间轴和切点、读 OCR 文字轨甄别误读、用 `stems/` 的电平判断有没有人声、读元数据(AIGC 标识、平台转码标记)、把工具的低置信镜头列进"不确定点"。+- 一句话结论里写明"未开 VLM、未看画面",并把工具标了"实拍还是 AI 待确认"的镜头原样保留为待确认。++### 原片 / 参考片:判 AI 前先写反方证据++只有一个连续镜头、没有 AIGC 标识、也没有 24→30 重复帧的写实或手作质感视频(定格动画、俯拍生活片、手作微缩场景),工具常会判成 AI。看图后如果找不到明确的 AI 破绽(形变、纹理闪烁、物理错误、文字乱码),**不要给高置信度**:写成"AI 还是实拍 / 定格动画待确认(倾向 X)",列出正反两方的证据,置信度不超过 0.7。++### 平台转码视频(微信 / 抖音 / TikTok 下载的文件)++元数据里有 `Tencent CAPD MTS`、`Wxmm_`、`vid:v…` 时,工具会标 `video_context.transcoded`。二次压缩会抹掉传感器噪声、带来假的插帧节奏,所以:++- 噪声类证据失效,"没有噪声"不再说明是 AI;工具会把这类镜头标成"实拍还是 AI 待确认"。+- 仍然可靠的证据:24→30 的重复帧(生成模型多输出 24fps;整片原生 30fps、没有重复帧更像手机直出)、AIGC 隐式标识、画面内容(真手、真实环境、物理是否自然——这一条必须看图或开 VLM)。+- 证据冲突时的优先级:**规律的 24→30 重复帧 + AIGC 隐式标识**同时存在时,比"看图没发现 AI 破绽"更有分量,不要据此把镜头改判成实拍;最多写"倾向 AI,实拍待确认"。反过来,整片原生 30fps、无重复帧、无 AIGC 标识,再加上看图画面正常,才判实拍。++### 记住用户的纠正和偏好++- 用户指出某个镜头判错("这是定格动画不是 AI"、"这段是我自己拍的素材"):运行+ `rea-video correct out/ref --shots 3,5 --label still_motion --note "<用户原话>"`(也可用 `--start/--end` 指定时间段,`--shots all` 表示整条;真实素材用 `--real yes|no`)。+ 这会立刻改结论和报告,并记入 `~/.rea-video/corrections.jsonl`;以后拆同一个文件会自动套用,同类镜头会在复核任务里提示。+- 用户说出长期偏好:能对应参数的用 `rea-video prefs engine kling2.1`、`prefs vlm on`、`prefs env_file <路径>`、`prefs reviewer <名字>`;其余的用 `rea-video prefs --note "报告尽量短,重点写复刻方案"` 记下,下次 `rea-video memory` 会显示,按它调整回复。+- 只记用户明确说的,不要把你自己的猜测写成纠正。纠正不会自动改分类权重;积累到几条以后,用 `rea-video memory --export-labels eval/user_labels.yaml` 导出成评测样本,再按开发约定评测、改规则。++## 2. 交付给用户++按 `references/output-template.md` 的结构回复:++- 先给一句话结论,再给分镜表(时间 / 制作方式 / 置信度 / 素材来源 / 叠加层 / 复刻路线)。+- 然后写声音拆解、真实素材清单、复刻方案,最后写不确定点。+- 报告文件路径(`report.html`)写给用户。不要把 breakdown.json 整段贴进对话。++## 3. 复刻(需要时)++见 `references/capsule-cinema.md`,要点:++- **AI 类镜头**:用原镜头首尾帧加 VLM 提示词,通过 capsule-cinema 生成(会计费,先 `--dry-run`,并征得用户同意)。+- **静态图推拉、静帧**:本地按测得的运动参数重建。+- **代码渲染**:给出文字轨和版式,用 Remotion 重建。+- **真实素材**:列清单让用户提供。+- **声音**:TTS、BGM(按 BPM / 调性 / 情绪)、音效(按时间点)三条轨分别准备。++## 4. 判断要点速查(详见 references/taxonomy.md)++| 现象 | 指向 |+|---|---|+| 相邻帧逐像素重复、首尾无变化 | 静帧;如果是平涂渲染卡片,归为代码渲染 |+| 整帧按一个刚体变换缩放/平移,补偿后无残差,且**没有** 24fps 源的帧率痕迹 | 静态图推拉 |+| 平涂色块多、用色少、横竖直边多 | 渲染(代码或 3D);背景像素逐帧完全不变、只有局部在动 → 2D 代码动效 |+| 约 20% 帧重复、周期 4–6(24→30),或清晰度按周期起伏(插帧) | 源是 24fps:AI 生成 / 3D / 电影素材,不是手机原生拍摄 |+| 原生 ≥48fps 且无重复、无插帧周期 | 多为手机/相机实拍 |+| 传感器噪声和时域噪声明显、手持抖动 | 实拍 |+| 平台转码文件:整片原生 30fps、实拍类镜头没有重复帧 | 倾向手机实拍(转码后噪声证据失效,以帧率为准) |+| 几乎无彩色、只用个位数颜色的平面画面 | 界面/文档动效(代码渲染),不是 3D |+| 整片铺满音乐、人声在唱(持续音高多) | 音乐 MV → 歌大概率 AI 生成 |+| 旁白说话 + 垫底 BGM | 普通配乐 → 倾向现成曲库(待确认,AI 工作流常用 Suno) |+| 切镜处底噪跳变 | 声音跟着片段走:AI 视频原生出声或实拍同期声 |+| 文件带 GB 45438 AIGC 隐式标识 Label=1 | 声明为 AI 生成(只说明整片声明过,具体镜头仍要逐个判断) |+| 浅色面板内有大量小字号文字 | 嵌入的界面截图 → 真实素材 |+| 人声间隙里仍有响亮且有音调的声音 | 有 BGM 垫底 |++## 5. 不要做的事++- 不要只凭画风判断。卡通 3D 风格既可能是 AI 视频,也可能是 Blender 渲染,要看形变、闪烁和几何稳定性。+- 不要把代码渲染画面里的文字算成"叠加层",那些文字就是画面本身。+- 不要把用户的真实素材写成"可用 AI 生成"。+- 不要把元数据缺失当成"不是 AI"的证据,平台转码常会清除元数据。+- 不要在用户确认之前调用付费生成。diff --git a/skills/rea-video/references/audio.md b/skills/rea-video/references/audio.mdnew file mode 100644index 0000000..3957a50--- /dev/null+++ b/skills/rea-video/references/audio.md@@ -0,0 +1,97 @@+# 声音拆解++工具产出:`breakdown.json` 的 `audio`(测量值)和 `audio_plan`(与 VLM 合并后的结果和复刻方案),以及 `audio.png` 时间轴。++## 能信多少++| 项 | 方法 | 可靠度(capsule-cinema 样本) |+|---|---|---|+| 有无人声 | 人声频段的音节调制(3–8Hz),加上句间停顿 | 高 |+| 有无 BGM | 人声间隙里仍有响亮、有音调的声音(谐波占比 >0.62);没有人声时看谐波持续性;或者有明显节拍周期 | 高 |+| BPM | 打击成分起音包络的自相关,同时给出半速/倍速候选 | 高(咸鸭蛋 110.0 vs 真值 110.15) |+| 调性 | 色度 + Krumhansl 调性轮廓 | 中高(两条真值都对:D major) |+| 段落变化 | 色度和响度的新颖度峰值 | 中 |+| 音效 | 人声段落之外非常突出的瞬态,且不在节拍上;有 BGM 时要求更突出 | **低**:在人声 + BGM 的混音里,信号层面实测精度只有约 0.2,轻音效基本测不出。音效清单以 VLM 为准 |+| TTS 还是真人 | 交给 VLM | — |+| 男声 / 女声 | 基频中位数(<150Hz 偏男声,>200Hz 偏女声) | 中,只作参考 |+| 卡点剪辑 | 切点落在节拍上的比例 vs 随机概率 | 中高 |++## 剥离音轨++`decompose` 默认把声音剥成三条轨,放在 `stems/` 下(`rea-video stems <视频>` 可以只做这一步):++| 文件 | 内容 |+|---|---|+| `original.wav` | 原声(视频里的完整混音) |+| `vocals.wav` | 人声干声:旁白、口播、歌声。注意:键盘声、"叮"之类的瞬态音效也会落在这里 |+| `music.wav` | 配乐 + 环境声 |++模型是 UVR MDX-Net Inst HQ 3(ONNX,CPU 即可,首次运行从 GitHub 下载约 67 MB,缓存在 `~/.cache/rea-video/models`,可用 `REA_VIDEO_MODELS` 改位置)。实测 TTS + Suno BGM 混音分离 SDR 约 19.7 dB;纯 BGM 漏进人声轨 −42 dB。约 0.6 倍实时(4 核)。++复核时**直接听 vocals.wav 和 music.wav**,比听混音容易判断:人声是唱还是说、是不是 TTS,配乐有没有人声、结尾是不是被截断。++## 来源判断:AI 生成还是现成的?++**一句话结论**在 `sound_sources.summary_zh`,格式是"视频类型 → 人声 / 音乐 / 音效来源":++| 视频类型 | 人声 | 音乐 | 音效 |+|---|---|---|---|+| 音乐 MV / 歌曲类 | 歌曲自带的演唱 | **AI 生成**(Suno 等)为主 | 音效库 |+| AI 视频原生出声 | 视频模型生成 | 后期配乐 | 视频模型生成 |+| 实拍 | 同期声 / 真人配音 | 现成配乐 | 同期声 |+| 旁白/口播 + 配乐 | TTS 或真人配音 | **现成曲库**为主(AI 工作流也常用 Suno 垫乐) | 音效库 |+| 纯配乐 | — | 现成曲库 | 音效库 |++工具产出:`breakdown.json` 的 `sound_sources`(music / voice / sfx 各自的 `source`、`leaning`、`probs`、`evidence`、`how_to_confirm`)。++### 第一步:先看视频形式(决定先验)++| 形式 | 怎么认 | 音乐来源先验 |+|---|---|---|+| **AI 音乐 MV**(整片就是一首带人声的歌) | VLM 说 format=MV;或确定性层:音乐铺满全片(>85%)**且人声是唱的**(`voice.style` = singing / rap_or_rhythmic,在分离出的干声上测) | AI 生成 60%(未开 VLM 时降权为 45%) |+| **普通视频配乐**(旁白/口播 + 垫底 BGM,或无人声的纯配乐) | 人声是说话(`voice.style` = speech),或没有人声 | 现成曲库 60% |++"唱"和"说"在**人声干声**上判断,两个信号:++- 持续音高(`sustained_note_ratio`):唱歌会在一个音高上停留 ≥160ms,>0.3 算唱。实测 TTS 旁白 0.14–0.15,说唱 0.24(说唱本来就不拖长音)。+- 副歌重复(`chorus_repeat_share`):4 秒的人声旋律片段在 6 秒以后又出现。>0.1 算歌(包括说唱)。实测 AI 说唱 MV 0.26,TTS 旁白 0.00。短视频只截了一段、没有重复的副歌时,这个信号会失效。++### 第二步:用证据修正++| 证据 | 指向 | 权重 |+|---|---|---|+| 歌词唱的就是本片的角色/商品/剧情(VLM `lyrics_match_content`) | AI 生成(定制歌) | 强 |+| VLM 认出歌名(`song_guess`) | 知名歌曲 | 强 |+| 平台音乐标签是具体歌名(`--meta`) | 现成曲目 | 强 |+| 平台标签是「@作者创作的原声」 | 不是平台曲库;MV 类多为 AI 歌 | 中 |+| 片尾音乐满音量被硬切 | 截取的现成曲目 | 弱 |+| 音乐和视频一起收尾 | 按片长定制/剪辑(两种都可能) | 很弱 |+| 文件带 AIGC 隐式标识 | 整片声明含 AI 内容 | 很弱 |++最高概率 <45% 时输出"待确认",同时给出倾向(`leaning`)。++### 已知陷阱(一定要在回复里提醒)++**AI 工作流做出来的普通视频,BGM 也常是 Suno 生成的**(capsule-cinema 自己的 monkey_wine、咸鸭蛋、鸟窝都是)。"普通配乐 = 曲库"的先验在这类视频上会错,而纯听感/信号特征分不开 Suno 器乐和曲库器乐。所以普通配乐的结论必须写成"倾向曲库,待确认",并给出确认方法:++1. 抖音/小红书原页面的音乐标签(`--meta` 传进来最好)。+2. 汽水音乐 / QQ 音乐「听歌识曲」或 ACRCloud:识别得到就是现成歌曲;识别不到不代表是 AI(曲库冷门曲也常识别不到)。+3. 听感:AI 歌咬字含糊、高频发虚带金属感、歌词紧扣画面;AI 器乐常见结构一成不变、结尾突然收住或循环拼接。++### 人声和音效的来源++- **人声**:TTS / AI 视频自带人声 / 真人录音。镜头切换处底噪跳变(`per_clip_audio.resets_at_cuts`)说明每段声音跟着画面片段走,是 AI 视频模型原生出声(如 Veo、Seedance 带音频)或实拍同期声。+- **音效**:多数来自现成音效库(mixkit、爱给等);AI 视频模型原生出声时音效也跟着片段走。确定性层只能给倾向,清单以 VLM 为准。++## 复核方法++1. 看 `audio.png`:人声条、音乐条和切镜线是否对得上直觉。+2. 音效有疑问时,抽那一段画面看看有没有对应事件(文字弹出、转场、动作):`rea-video tiles`。+3. VLM 给出 `source_guess=popular_song`,或平台标签是具体歌名时,在复刻方案里写明"需要授权或替换"。+4. 音乐来源按上面的"来源判断"写,普通配乐不要写成确定的"曲库"。++## 复刻++- **人声**:capsule-cinema 的 DoubaoTTSTool / UniversalTTSTool 或 MiniMax 克隆;要卡原时间窗时用时长可控 TTS。+- **BGM**:按 BPM、调性、情绪用 Suno(UniversalMusicGenerationTool)或曲库;在段落变化点对齐镜头。+- **音效**:按时间点摆放;有音高的音效对齐 BGM 调性(capsule-cinema plush 配方的 sfx.py / cues.py 就是这样做的)。diff --git a/skills/rea-video/references/capsule-cinema.md b/skills/rea-video/references/capsule-cinema.mdnew file mode 100644index 0000000..d63a893--- /dev/null+++ b/skills/rea-video/references/capsule-cinema.md@@ -0,0 +1,19 @@+# 对接 capsule-cinema 复刻++capsule-cinema 的脚本必须用它自己的 Python 环境运行(`$CC/.venv/bin/python` 或 python3.12)。++```bash+CC=~/code/github/capsule-cinema; PY=$CC/.venv/bin/python+rea-video remake-plan out/ref/breakdown.json --capsule-root $CC --engine seedance2.0 # 也可以 --mode image_to_video / --labels ai_video+$PY integrations/capsule_cinema/run_remake.py --jobs out/ref/remake/jobs.json --dry-run # 先给用户看任务和费用+$PY integrations/capsule_cinema/run_remake.py --jobs out/ref/remake/jobs.json # 用户确认后再跑+rea-video assemble out/ref/breakdown.json out/ref/remake/results.json # 拼回原时间线 + compare.mp4+$PY integrations/capsule_cinema/to_capsule.py --breakdown out/ref/breakdown.json --capsule-root $CC --capsule-name xxx [--write-capsule]+```++- jobs.json 里每个任务的 `executor` 取值:+ - `capsule_cinema`:调模型生成+ - `local_ffmpeg`:静态图本地重建+ - `keep_original`:保留原片,比如代码渲染、录屏、真实素材+- `user_assets`:这个镜头需要用户提供的真实素材。生成结果只是近似,要提醒用户。+- `to_capsule.py`:通过 capsule-cinema 自带的 `tool_factory` 注入拆解结果,不改 capsule-cinema 代码,生成的配方草稿默认是 `review_required`。diff --git a/skills/rea-video/references/evaluation.md b/skills/rea-video/references/evaluation.mdnew file mode 100644index 0000000..21cf1e9--- /dev/null+++ b/skills/rea-video/references/evaluation.md@@ -0,0 +1,11 @@+# 扩充评测集++1. 在 `eval/labels.yaml`(或新建一个 yaml)里加条目:+ - `label`:可以是列表,表示可接受的多个标签+ - `segments`:分段真值+ - `real_material`:是否用了真实素材+ - `cuts` / `cut_tolerance`:切点真值+ - `audio`:`{voice, music, sfx, bpm, key}`+2. 真值要有出处,写在 `source` 字段:生产记录(timeline.json、manifest、cues.py)> 平台 AIGC 标识 > 人工目测(目测的要写"存疑")。+3. 跑 `rea-video eval eval/xxx.yaml -o out/eval_xxx`。改规则后不需要重新解码:评测会用缓存特征重新分类(`--only id` 只对指定视频重新解码)。+4. 调规则要防止过拟合:至少保留一组**改规则之后才第一次跑**的留出集,结果写进 `eval/RESULTS.md`。diff --git a/skills/rea-video/references/materials.md b/skills/rea-video/references/materials.mdnew file mode 100644index 0000000..c2d3f23--- /dev/null+++ b/skills/rea-video/references/materials.md@@ -0,0 +1,26 @@+# 用户真实素材++**定义**:不是制作方生成或渲染的,而是从现实中引入的素材,包括实拍视频、真实照片、商品实拍图、Logo、网页/App 截图、录屏。复刻时这些必须由用户提供,**不能写成"用 AI 生成"**。++## 工具怎么标++- **整帧**:+ - 实拍 → 实拍视频素材+ - 录屏/截图 → 录屏素材或界面截图(静止的算截图)+ - 静帧/推拉且来源是照片或截图 → 真实照片或截图+ - 静帧来源不明(没开 VLM)→ "图片素材(真实/AI 待确认)",不计为真实素材+- **嵌入**(只在渲染画面里检测,即代码渲染、录屏、3D、渲染卡片):+ - 照片纹理区域:灰度熵高、无平涂,且不在字幕带 → 照片/图片素材,**标为"真实还是 AI 待确认"**(模板里贴的也可能是 AI 图)。要么由 VLM 确认,要么你自己看图判断+ - 浅色面板 + 单帧 ≥6 处小字 → 界面截图(直接算真实素材)+ - 区域内有运动而周围静止 → 嵌入视频片段或录屏+- **VLM**:`embedded_assets` 里 `is_real_material=true` 的条目,比如商品图、Logo。++## 已知漏检++- 暗色、半透明、作为氛围背景的照片(例如 mediank 的 NASA 背景图):纹理对比太低,确定性检测不出来。看到深色模板时,要自己看一眼背景。+- 暗色主题网页截图:不是浅色面板,检测不到,要看画面里有没有浏览器或界面框。+- 实拍或 AI 画面里叠加的小 Logo、商品图:确定性层不在照片底图上做嵌入检测(容易误报),依赖 VLM。++## 交付时的写法++逐条列出:镜头号、时间、素材类型、画面位置、内容描述,以及"复刻时需要你提供:……"。diff --git a/skills/rea-video/references/output-template.md b/skills/rea-video/references/output-template.mdnew file mode 100644index 0000000..d839571--- /dev/null+++ b/skills/rea-video/references/output-template.md@@ -0,0 +1,21 @@+# 回复模板(中文)++**一句话结论**:混合制作——底层画面 AI 生成视频 62%、代码模板 30%、实拍 8%;全片字幕由代码叠加;引入了 2 段真实截图;女声 TTS + 110 BPM 流行 BGM,切镜卡在节拍上。++**分镜表**++| # | 时间 | 制作方式(置信度) | 素材来源 | 叠加层 | 关键证据 | 复刻路线 |+|---|---|---|---|---|---|---|+| 1 | 0:00–0:02.5 | AI 视频(86%) | AI 生成 | 字幕、标题 | 24→30 重复帧;手指形变 | capsule-cinema 首尾帧 |++**声音**:人声(TTS 还是真人、音色)/ BGM(风格、BPM、调性、来源、段落)/ 音效(时间点 → 对应画面事件)/ 混音(是否压低音乐)。++**需要你提供的真实素材**:镜头 #4 中部的 GitHub 页面截图……++**复刻方案**:按镜头分组写路线、工具和预计成本;涉及付费的操作先确认。++**不确定的地方**:#7 实拍还是 AI 待确认(倾向 AI 64%):没有手部和文字可供判断,建议……++**报告**:out/ref/report.html++**VLM**:照抄 `rea-video summary` 的 `VLM:` 一行(已生效 / 部分生效 / 全部调用失败 / 未配置 / 未开)。没生效、而且你自己也看不了图时,加一句建议:"配置任意多模态模型(REA_VLM_BASE_URL / REA_VLM_API_KEY / REA_VLM_MODEL)后加 --vlm 重跑,实拍/AI/3D 的判断会更准。"你能看图时写"由 agent 看图复核"即可。diff --git a/skills/rea-video/references/taxonomy.md b/skills/rea-video/references/taxonomy.mdnew file mode 100644index 0000000..b71b52a--- /dev/null+++ b/skills/rea-video/references/taxonomy.md@@ -0,0 +1,47 @@+# 制作方式分类与易混对照++## 8 类底层画面++| 标签 | 中文 | 典型证据 | 复刻路线 |+|---|---|---|---|+| live_action | 实拍 | 传感器噪声 σ>1、时域噪声 >0.8、逐像素不变比例 <0.55、手持抖动、原生 60fps、拍摄设备元数据 | 实拍素材(用户提供)或 AI 图生视频近似 |+| ai_video | AI 生成视频 | 无传感器噪声的照片纹理、24→30 重复帧或插帧周期、平滑漂浮的运镜;VLM 看到手指、文字、物体形变或纹理闪烁 | capsule-cinema 首尾帧生成 |+| avatar | 数字人口播 | 固定机位正脸,只有嘴和头在动,音频驱动 | TTS/克隆 + 数字人 |+| cg_3d | 3D 渲染 | 平涂/干净材质但背景不是逐像素冻结,几何稳定、无形变 | Blender/C4D,或 AI 首尾帧近似 |+| code_render | 代码/模板渲染 | 平坦块 >20%、用色 <70、横竖直边多;背景逐像素冻结、只有局部元素在动 | Remotion/HTML 重建 |+| screen_capture | 录屏/截图 | 大面积浅色界面、密集小字号文字、低饱和、整页滚动 | 真实界面录制(用户提供) |+| still_motion | 静态图推拉 | 刚体变换内点率 >95%、残差 <0.3px、补偿后无残余、无 24fps 帧率痕迹 | 一张图 + 本地 ffmpeg 按测得参数重建 |+| static_hold | 静帧 | 85% 以上帧逐像素重复 | 一张图 |++## 易混对照(复核时逐条看)++**实拍 vs AI 视频**+- 实拍:噪声颗粒随帧变化;手部、文字、远处人物正常;物理正确(布料、液体、碰撞)。+- AI:皮肤和光线过于完美;背景人物或文字乱码;物体边缘"沸腾";动作缓慢漂浮;镜头末尾容易定格。+- 帧率:24fps 源(AI/电影)vs 60fps 原生(手机)。注意 AI 插帧到 60fps 会留下清晰度周期,`sharp_period_ac>0.45`。+- 确定性层对这一对最弱,**必须结合 VLM 和你自己看帧**。++**卡通 3D 风格的 AI 视频 vs 真 3D 渲染**+- 真 3D:几何、材质逐帧稳定,毛发和布料按物理运动,可以精确循环,平坦块多、用色少。+- AI:同一物体在镜头内轻微变形,纹理闪烁,噪声更像照片(用色 >100)。+- 抖音上大量"3D 卡通"账号是 AI 生成的,但没有标识时只能写倾向。++**代码渲染 vs 录屏截图**+- 代码渲染:字号大、品牌配色、矢量清晰、元素有动画入场。+- 截图:浅色底、密集小字、界面控件(按钮、图标、导航),往往被整体缩放或滚动。+- 模板里嵌入了截图:底层算代码渲染,截图在"真实素材"里单独列出。++**静态图推拉 vs AI 视频的缓慢推镜**+- 推拉:剪辑软件按时间线帧率渲染,每帧都不同,没有 24→30 的重复规律。+- AI 推镜:带 24fps 源的重复帧规律,主体常有细微动作(呼吸、眨眼)。++**静帧:AI 图 vs 真实照片 vs 渲染卡片**+- 渲染卡片(平涂、少色)→ 归为代码渲染。+- AI 图和真实照片在确定性层无法区分,交给 VLM;判断不了就写"图片素材(真实/AI 待确认)"。++## 切镜++- 硬切:直方图距离与像素差的尖峰,且变化面积超过 25%。元素弹出不算切镜。+- 交叉溶解:中间帧是两端帧的线性混合(α 在 0.2–0.8,残差 <0.2),并用光流排除推拉运动。+- 淡入淡出:亮度降到极暗或极亮再回来。+- MG 节拍:长镜头内"定格 → 动画 → 定格",两个定格内容差异超过 12%,记为镜头内节拍,不算切镜。diff --git a/tests/conftest.py b/tests/conftest.pynew file mode 100644index 0000000..c087e65--- /dev/null+++ b/tests/conftest.py@@ -0,0 +1,75 @@+import subprocess+import sys+from pathlib import Path++import cv2+import numpy as np+import pytest++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+++def _photo_like(w: int, h: int, seed: int) -> np.ndarray:+ """Photographic-looking still: smooth multi-scale texture + sensor-like noise."""+ rng = np.random.default_rng(seed)+ img = np.zeros((h, w, 3), np.float32)+ for scale, amp in ((8, 90), (32, 40), (128, 20)):+ small = rng.random((max(2, h // scale), max(2, w // scale), 3)).astype(np.float32)+ img += cv2.resize(small, (w, h), interpolation=cv2.INTER_CUBIC) * amp+ img = cv2.GaussianBlur(img, (0, 0), 1.2) + rng.normal(0, 3.0, img.shape)+ return np.clip(img, 0, 255).astype(np.uint8)+++def _write(frames, path: Path, fps: int = 30) -> Path:+ h, w = frames[0].shape[:2]+ p = subprocess.Popen(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{w}x{h}", "-r", str(fps),+ "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "16", str(path)], stdin=subprocess.PIPE)+ for f in frames:+ p.stdin.write(f.tobytes())+ p.stdin.close()+ p.wait()+ return path++[email protected](scope="session")+def media(tmp_path_factory):+ d = tmp_path_factory.mktemp("media")+ w, h, fps = 360, 640, 30+ out = {}+ # 1) static photo hold, 2 s+ still = _photo_like(w, h, 1)+ out["static"] = _write([still] * (2 * fps), d / "static.mp4")+ # 2) Ken Burns: zoom in 4%/s on another photo, 3 s+ base = _photo_like(int(w * 1.3), int(h * 1.3), 2)+ frames = []+ for i in range(3 * fps):+ s = 1.0 + 0.04 * i / fps+ M = cv2.getRotationMatrix2D((base.shape[1] / 2, base.shape[0] / 2), 0, s)+ warped = cv2.warpAffine(base, M, (base.shape[1], base.shape[0]), flags=cv2.INTER_CUBIC)+ y0, x0 = (base.shape[0] - h) // 2, (base.shape[1] - w) // 2+ frames.append(np.ascontiguousarray(warped[y0:y0 + h, x0:x0 + w]))+ out["kenburns"] = _write(frames, d / "kenburns.mp4")+ # 3) code-render style: flat background, a card sliding in, text-like bars, 3 s+ frames = []+ for i in range(3 * fps):+ f = np.full((h, w, 3), (59, 41, 30), np.uint8)+ x = int(min(40, -200 + i * 12))+ cv2.rectangle(f, (x, 200), (x + 280, 360), (245, 245, 245), -1)+ for k in range(4):+ cv2.rectangle(f, (x + 20, 220 + k * 30), (x + 20 + 200 - k * 30, 236 + k * 30), (60, 60, 60), -1)+ cv2.putText(f, "REA VIDEO", (40, 120), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (80, 200, 250), 3, cv2.LINE_8)+ frames.append(f)+ out["code"] = _write(frames, d / "code.mp4")+ # 4) concatenation with known cuts at 2.0 and 5.0 s+ cat = d / "concat.txt"+ cat.write_text("".join(f"file '{out[k]}'\n" for k in ("static", "kenburns", "code")))+ out["edit"] = d / "edit.mp4"+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", str(cat), "-c", "copy", str(out["edit"])], check=True)+ return out++[email protected](autouse=True)+def _isolated_memory(tmp_path, monkeypatch):+ """Never read or write the real ~/.rea-video during tests."""+ monkeypatch.setenv("REA_VIDEO_HOME", str(tmp_path / "rea_home"))diff --git a/tests/test_audio.py b/tests/test_audio.pynew file mode 100644index 0000000..ddb0757--- /dev/null+++ b/tests/test_audio.py@@ -0,0 +1,68 @@+import subprocess+import wave++import numpy as np+import pytest++from rea_video.audio import analyze_audio++SR = 22050+++def _write_av(tmp_path, y: np.ndarray, name: str):+ wav = tmp_path / f"{name}.wav"+ with wave.open(str(wav), "wb") as w:+ w.setnchannels(1)+ w.setsampwidth(2)+ w.setframerate(SR)+ w.writeframes((np.clip(y, -1, 1) * 32767).astype(np.int16).tobytes())+ mp4 = tmp_path / f"{name}.mp4"+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", f"color=c=gray:s=160x90:d={len(y) / SR:.2f}",+ "-i", str(wav), "-shortest", "-c:v", "libx264", "-c:a", "aac", str(mp4)], check=True)+ return mp4+++def _music(dur=12.0, bpm=120.0):+ t = np.arange(int(dur * SR)) / SR+ y = 0.08 * sum(np.sin(2 * np.pi * f * t) for f in (261.63, 329.63, 392.0, 523.25)) # C major chord bed+ rng = np.random.default_rng(0)+ for k in np.arange(0, dur, 60 / bpm): # kick + hat on every beat+ i = int(k * SR)+ n = int(0.08 * SR)+ env = np.exp(-np.arange(n) / (0.015 * SR))+ y[i:i + n] += 0.5 * env * np.sin(2 * np.pi * 70 * np.arange(n) / SR)+ y[i:i + n // 3] += 0.15 * rng.normal(size=n // 3) * env[: n // 3]+ return y++[email protected](scope="module")+def music_mp4(tmp_path_factory):+ return _write_av(tmp_path_factory.mktemp("a"), _music(), "music")+++def test_music_tempo_key(music_mp4):+ a = analyze_audio(str(music_mp4))+ m = a["music"]+ assert m["present"] and not a["voice"]["present"]+ cands = [m["tempo_bpm"]] + m["tempo_alternatives"]+ assert any(abs(c - 120) < 4 for c in cands), cands+ assert m["key"]["tonic"] == "C" and m["key"]["mode"] == "major"+++def test_cut_on_beat(music_mp4):+ cuts = [2.0, 4.0, 6.0, 8.0, 10.0] # on the 120 BPM grid+ a = analyze_audio(str(music_mp4), cut_times=cuts)+ assert a["cuts_on_beat_ratio"] >= 0.8 and a["beat_synced_edit"]+++def test_isolated_sfx_in_silence(tmp_path):+ y = np.zeros(int(6 * SR))+ for t0 in (1.0, 2.5, 4.0): # three "dings" in an otherwise quiet track+ n = int(0.3 * SR)+ tt = np.arange(n) / SR+ y[int(t0 * SR):int(t0 * SR) + n] += 0.6 * np.exp(-tt / 0.08) * np.sin(2 * np.pi * 1800 * tt)+ y += 0.002 * np.random.default_rng(1).normal(size=len(y))+ a = analyze_audio(str(_write_av(tmp_path, y, "sfx")))+ ts = [e["t"] for e in a["sfx"]["events"]]+ assert all(any(abs(t - t0) < 0.08 for t in ts) for t0 in (1.0, 2.5, 4.0)), ts+ assert not a["music"]["present"]diff --git a/tests/test_memory.py b/tests/test_memory.pynew file mode 100644index 0000000..0771fcf--- /dev/null+++ b/tests/test_memory.py@@ -0,0 +1,94 @@+"""User memory: corrections fix the breakdown, persist, re-apply, and surface as hints; prefs set defaults."""+import json++import yaml++from rea_video.cli import main+from rea_video.memory import load_corrections, patterns+from rea_video.pipeline import _vlm_gate, decompose+++def test_correction_fixes_breakdown_and_is_remembered(media, tmp_path, capsys):+ out = tmp_path / "o"+ b = decompose(media["code"], out, use_vlm=False, ocr=False, workers=1, stems=False)+ first = b["shots"][0]["base"]["label"]+ assert first != "ai_video"+ assert main(["correct", str(out), "--shots", "1", "--label", "ai_video", "--real", "no", "--note", "这是 AI 生成的"]) == 0+ assert "已纠正 1 个镜头" in capsys.readouterr().out+ b2 = json.loads((out / "breakdown.json").read_text(encoding="utf-8"))+ s0 = b2["shots"][0]+ assert s0["base"]["label"] == "ai_video" and s0["base"]["decided_by"] == "user" and s0["base"]["confidence"] == 1.0+ assert s0["base"]["evidence"][0].startswith("[用户纠正]") and not s0["material"]["has_real_material"]+ assert "AI 生成视频" in b2["summary"]["verdict"]+ (c,) = load_corrections()+ assert c["before"] == first and c["label"] == "ai_video" and c["tool"] == first and c["note"] == "这是 AI 生成的"++ # the same file decomposed again gets the correction back+ b3 = decompose(media["code"], tmp_path / "o2", use_vlm=False, ocr=False, workers=1, stems=False)+ assert b3["shots"][0]["base"]["label"] == "ai_video"+ # ...but evaluation runs never see user corrections+ b4 = decompose(media["code"], tmp_path / "o3", use_vlm=False, ocr=False, workers=1, stems=False, memory=False)+ assert b4["shots"][0]["base"]["label"] == first++ # re-correcting the same file + shot counts once (latest wins)+ main(["correct", str(tmp_path / "o3"), "--shots", "1", "--label", "ai_video"])+ assert patterns()[0]["count"] == 1++ capsys.readouterr()+ assert main(["memory"]) == 0+ printed = capsys.readouterr().out+ assert "纠正:" in printed and "→ 用户「AI 生成视频」" in printed+ labels = tmp_path / "user_labels.yaml"+ assert main(["memory", "--export-labels", str(labels)]) == 0+ spec = yaml.safe_load(labels.read_text(encoding="utf-8"))+ assert spec["videos"][0]["segments"][0][2] == "ai_video"+++def test_prefs_set_defaults_and_validate(capsys):+ assert main(["prefs", "engine", "kling2.1"]) == 0+ assert main(["prefs", "vlm", "maybe"]) == 2+ assert main(["prefs", "colour", "red"]) == 2+ assert main(["prefs", "--note", "报告尽量短"]) == 0+ capsys.readouterr()+ assert main(["prefs"]) == 0+ printed = capsys.readouterr().out+ assert "engine = kling2.1" in printed and "说明 1: 报告尽量短" in printed+ assert main(["prefs", "engine", "--unset"]) == 0+ capsys.readouterr()+ main(["memory"])+ assert "报告尽量短" in capsys.readouterr().out+++def test_single_image_reader_cannot_flip_ai_vs_live_axis():+ from rea_video.classify import LABELS++ def p(**kw):+ rest = (1 - sum(kw.values())) / (len(LABELS) - len(kw))+ return {k: kw.get(k, rest) for k in LABELS}++ def rec(det, facts=None):+ return {"deterministic": {"probs": det, "facts": facts or {}}, "vlm": {"label_probs": {}}}++ vlm_avatar = p(avatar=0.9)+ assert _vlm_gate(rec(p(ai_video=0.9, avatar=0.03)), vlm_avatar, {}) is None # tools sure + not in top-2+ assert _vlm_gate(rec(p(ai_video=0.74, cg_3d=0.1)), p(cg_3d=0.95), {}) is None # tools sure on AI axis+ assert _vlm_gate(rec(p(cg_3d=0.56, code_render=0.36)), p(code_render=0.8), {}) # 3D vs code: VLM helps+ assert _vlm_gate(rec(p(ai_video=0.46, live_action=0.38), {"transcode_degraded": True}),+ p(live_action=0.85), {"native30": False}) is None # 24fps transcode never -> live+ assert _vlm_gate(rec(p(ai_video=0.46, live_action=0.38), {"transcode_degraded": True}),+ p(live_action=0.85), {"native30": True})+ agent_only = {"deterministic": {"probs": p(ai_video=0.9, avatar=0.03), "facts": {}}, "review": {"label_probs": vlm_avatar}}+ assert _vlm_gate(agent_only, vlm_avatar, {}) is None # same rule for a lone agent+ both = dict(agent_only, vlm={"label_probs": vlm_avatar})+ assert _vlm_gate(both, vlm_avatar, {}) is vlm_avatar # two readers: _majority decides+++def test_repeated_pattern_becomes_review_hint(media, tmp_path):+ from rea_video.memory import hint_for++ cs = [{"video_key": f"v{i}", "shot": "shot_001", "before": "cg_3d", "tool": "cg_3d", "label": "ai_video",+ "vlm": "cg_3d", "review": None, "context": {"transcoded": True}} for i in range(2)]+ (p,) = patterns(cs)+ assert p["count"] == 2 and p["vlm_wrong"] == 2 and p["transcoded"] == 2+ assert "用户过去 2 次" in hint_for("cg_3d", [p]) and hint_for("ai_video", [p]) is None+ assert hint_for("cg_3d", patterns(cs[:1])) is None # one correction is not a pattern yetdiff --git a/tests/test_pipeline.py b/tests/test_pipeline.pynew file mode 100644index 0000000..b53989d--- /dev/null+++ b/tests/test_pipeline.py@@ -0,0 +1,104 @@+import json+import subprocess+import sys+from pathlib import Path++import pytest++from rea_video.classify import LABELS, deterministic, fuse, top+from rea_video.integrations.capsule_cinema import build_remake_jobs, export_capsule_analysis+from rea_video.media import video_info+from rea_video.pipeline import decompose, finalize+from rea_video.remake import assemble+from rea_video.shots import build_track, detect_shots++ROOT = Path(__file__).resolve().parents[1]+++def test_capabilities_valid():+ r = subprocess.run([sys.executable, str(ROOT / "scripts/validate_capabilities.py")], capture_output=True, text=True)+ assert r.returncode == 0, r.stdout + r.stderr+++def test_shot_boundaries(media):+ info = video_info(media["edit"])+ shots = detect_shots(build_track(str(media["edit"]), info))+ starts = [round(s.start, 2) for s in shots[1:]]+ assert len(shots) == 3, starts+ assert abs(starts[0] - 2.0) < 0.07 and abs(starts[1] - 5.0) < 0.07++[email protected](scope="module")+def breakdown(media, tmp_path_factory):+ out = tmp_path_factory.mktemp("out") / "edit"+ return decompose(media["edit"], out, use_vlm=False, ocr=False, stems=False), out+++def test_labels(breakdown):+ b, _ = breakdown+ labels = [s["base"]["label"] for s in b["shots"]]+ assert labels == ["static_hold", "still_motion", "code_render"], labels+++def test_kenburns_measured(breakdown):+ b, _ = breakdown+ km = b["shots"][1]["features"]+ assert 0.025 < km["zoom_per_s"] < 0.06, km["zoom_per_s"]+ assert km["camera"] == "planar_zoom_pan"+++def test_outputs_and_schema(breakdown):+ b, out = breakdown+ for name in ("breakdown.json", "report.md", "report.html", "storyboard.jpg"):+ assert (out / name).is_file(), name+ assert b["schema"] == "rea_video.breakdown.v1"+ assert abs(sum(m["ratio"] for m in b["summary"]["production_mix"]) - 1.0) < 0.01+ for s in b["shots"]:+ assert set(s["base"]["probs"]) == set(LABELS)+ assert s["replication"]["rule"].startswith("R")+++def test_finalize_idempotent(breakdown):+ b, out = breakdown+ again = finalize(json.loads((out / "breakdown.json").read_text()), out)+ assert [s["base"]["label"] for s in again["shots"]] == [s["base"]["label"] for s in b["shots"]]+++def test_fuse_respects_frozen():+ det = {k: 0.0 for k in LABELS} | {"static_hold": 0.9, "code_render": 0.1}+ vlm = {k: 0.0 for k in LABELS} | {"ai_video": 0.9, "static_hold": 0.1}+ lab, _ = top(fuse(det, vlm, "frozen"))+ assert lab == "static_hold"+++def test_vlm_can_override_camera_like():+ f = {"noise_sigma": 0.5, "temporal_noise": 0.8, "flat_ratio": 0.05, "palette95": 200, "axis_edge_ratio": 0.2,+ "dup_ratio": 0.0, "zero_pixel_ratio": 0.5, "camera": "smooth_move", "kenburns_score": 0.0, "moving_pair_ratio": 0.9}+ det, _, facts = deterministic(f)+ vlm = {k: 0.0 for k in LABELS} | {"live_action": 0.95, "ai_video": 0.05}+ assert top(fuse(det, vlm, facts["temporal_family"]))[0] == "live_action"+++def test_capsule_export(breakdown, tmp_path):+ b, _ = breakdown+ p = export_capsule_analysis(b, tmp_path / "capsule_analysis.json")+ data = json.loads(p.read_text())+ for key in ("summary", "source_profile", "segments", "capsule_recipe", "execution_strategy", "content_scope"):+ assert key in data+ cs = data["content_scope"]+ assert cs["schema_version"] == "capsule.content_scope.v1" and cs["series_fixed"] and cs["episode_variable"]+ assert data["execution_strategy"]["mode"] == "review_required"+++def test_remake_jobs_and_assemble(breakdown, tmp_path):+ b, out = breakdown+ jobs_path = build_remake_jobs(b, out, capsule_root=tmp_path / "capsule", engine="seedance2.0")+ jobs = json.loads(jobs_path.read_text())["jobs"]+ execs = [j["executor"] for j in jobs]+ assert execs == ["local_ffmpeg", "local_ffmpeg", "keep_original"], execs+ results = jobs_path.with_name("results.json")+ results.write_text(json.dumps({"results": {}}))+ res = json.loads(assemble(out / "breakdown.json", results))+ assert Path(res["remake"]).is_file() and Path(res["compare"]).is_file()+ info = video_info(res["remake"])+ assert abs(info.duration - b["source"]["duration"]) < 0.2diff --git a/tests/test_review.py b/tests/test_review.pynew file mode 100644index 0000000..a9aaee2--- /dev/null+++ b/tests/test_review.py@@ -0,0 +1,75 @@+"""Agent-as-VLM: review tasks -> answers -> fused breakdown."""+import json++from rea_video.cli import main+from rea_video.pipeline import decompose+from rea_video.vlm import VLMConfig+++def test_review_roundtrip_overrides_and_reports(media, tmp_path, capsys):+ out = tmp_path / "o"+ b = decompose(media["code"], out, use_vlm=False, ocr=False, workers=1, stems=False)+ assert b["shots"][0]["base"]["label"] != "live_action"+ assert main(["review", str(out)]) == 0+ tasks = json.loads((out / "review_tasks.json").read_text(encoding="utf-8"))+ assert tasks["shots"] and "label_probs" in tasks["instructions"]+ assert (out / tasks["shots"][0]["images"]["sheet"]).is_file()+ ans = json.loads((out / "review_answers.json").read_text(encoding="utf-8"))+ first = ans["shots"][0]+ ranked = sorted(b["shots"][0]["deterministic"]["probs"].items(), key=lambda kv: -kv[1])+ second = ranked[1][0] # a lone reader may pick the tools' runner-up (but not a label they rule out)+ first["label_probs"].update({second: 0.9, ranked[0][0]: 0.1})+ first["evidence"] = ["真实的手和厨房"]+ first["description"] = "手持拍摄厨房台面"+ ans["shots"].append({"id": "shot_999", "label_probs": {"ai_video": 1}})+ (out / "review_answers.json").write_text(json.dumps(ans, ensure_ascii=False), encoding="utf-8")+ capsys.readouterr()+ assert main(["apply-review", str(out), "--by", "tester"]) == 0+ printed = capsys.readouterr().out+ assert "shot_999" in printed and "改判" in printed+ b2 = json.loads((out / "breakdown.json").read_text(encoding="utf-8"))+ s0 = b2["shots"][0]+ assert s0["base"]["label"] == second and s0["base"]["decided_by"] == "fused_agent"+ assert any(e.startswith("[tester 看图]") for e in s0["base"]["evidence"])+ assert "tester 看图复核 1/" in b2["summary"]["vlm"]+ md = (out / "report.md").read_text(encoding="utf-8")+ assert "agent 看图融合" in md and "手持拍摄厨房台面" in md+ # unanswered shots (all-zero probs) are skipped, not applied+ assert all("review" not in r for r in b2["shots"][1:])+ # a lone reader cannot push a code-render shot to live action: it is outside the tools' top two+ if "live_action" not in (ranked[0][0], second):+ ans["shots"][0]["label_probs"] = {"live_action": 1}+ (out / "review_answers.json").write_text(json.dumps(ans, ensure_ascii=False), encoding="utf-8")+ main(["apply-review", str(out), "--by", "tester"])+ assert json.loads((out / "breakdown.json").read_text(encoding="utf-8"))["shots"][0]["base"]["label"] != "live_action"+++def test_vlm_config_merges_fallback_models_on_same_endpoint(monkeypatch):+ for k in ("REA_VLM_BASE_URL", "REA_VLM_API_KEY", "REA_VLM_MODEL"):+ monkeypatch.delenv(k, raising=False)+ monkeypatch.setenv("VIDEO_ANALYSIS_BASE_URL", "https://x.test/v1")+ monkeypatch.setenv("VIDEO_ANALYSIS_API_KEY", "k")+ monkeypatch.setenv("VIDEO_ANALYSIS_MODEL_NAME", "m1")+ monkeypatch.setenv("GEMINI3_BASE_URL", "https://x.test/v1/")+ monkeypatch.setenv("GEMINI3_API_KEY", "k")+ monkeypatch.setenv("GEMINI3_MODEL_NAME", "m1,m2,m3")+ assert VLMConfig.from_env().models == ["m1", "m2", "m3"]+ monkeypatch.setenv("GEMINI3_API_KEY", "other")+ assert VLMConfig.from_env().models == ["m1"]+++def test_two_of_three_beat_one_confident_model():+ from rea_video.classify import LABELS, fuse++ def p(**kw):+ rest = (1 - sum(kw.values())) / (len(LABELS) - len(kw))+ return {k: kw.get(k, rest) for k in LABELS}++ det = p(ai_video=0.46, live_action=0.38)+ vlm_and_agent_avg = p(live_action=0.48, ai_video=0.39) # VLM says live 0.85, agent says AI 0.72+ assert max(fuse(det, vlm_and_agent_avg, "dynamic").items(), key=lambda kv: kv[1])[0] == "live_action"+ out = fuse(det, vlm_and_agent_avg, "dynamic", majority="ai_video")+ assert max(out, key=out.get) == "ai_video"+ # hard constraints still win: a frozen shot is never a generated video+ frozen = fuse(p(static_hold=0.6), p(ai_video=0.9), "frozen", majority="ai_video")+ assert max(frozen, key=frozen.get) == "static_hold" or frozen["ai_video"] < 0.5diff --git a/tests/test_sound_source.py b/tests/test_sound_source.pynew file mode 100644index 0000000..f152561--- /dev/null+++ b/tests/test_sound_source.py@@ -0,0 +1,56 @@+from rea_video.sound_source import classify_sound_sources+++def _b(music=True, voice=True, whole=None, meta=None, clip=None, labels=("ai_video",) * 4, ending_curve=None, sfx=None):+ shots = [{"base": {"label": l}, "duration": 5.0} for l in labels]+ ec = ending_curve or [0.0] * 40+ return {+ "source": {"duration": 20.0, "path": "x.mp4"}, "shots": shots, "provenance": {},+ "audio": {"has_audio": True, "energy_curve": ec,+ "music": {"present": music, "ratio": 0.95 if music else 0, "start": 0.0, "end": 20.0},+ "voice": {"present": voice, "ratio": 0.6 if voice else 0}},+ "whole_video_vlm": whole or {}, "platform_meta": meta or {}, "per_clip_audio": clip or {},+ "audio_plan": {"sfx_merged": sfx or []},+ }+++def test_mv_with_lyrics_about_content_is_ai():+ w = {"format": "MV", "music": {"present": True, "has_vocals": True, "lyrics_match_content": True}, "narration": {"type": "none"}}+ r = classify_sound_sources(_b(whole=w))+ assert r["format_context"]["music_mv"] and r["music"]["source"] == "ai_generated"+++def test_ordinary_bgm_hard_cut_is_library():+ w = {"format": "知识讲解", "music": {"present": True, "has_vocals": False}, "narration": {"type": "tts"}}+ r = classify_sound_sources(_b(whole=w, ending_curve=[0.0] * 40))+ assert r["music"]["leaning"] == "existing_library" and r["music"]["ending"] == "hard_cut"+++def test_platform_music_title_wins():+ meta = {"music": {"title": "某热门歌", "author": "某歌手", "is_original": False, "popular": True}}+ r = classify_sound_sources(_b(meta=meta))+ assert r["music"]["leaning"] == "popular_song"+++def test_native_clip_audio_means_ai_sfx_and_voice():+ clip = {"ratio": 2.4, "resets_at_cuts": True, "at_cuts_db": 20.0, "within_shots_db": 8.0}+ r = classify_sound_sources(_b(music=False, clip=clip))+ assert r["sfx"]["leaning"] == "ai_native"+ assert r["voice"]["leaning"] == "ai_video_native"+++def test_editor_sfx_synced_to_cuts():+ sfx = [{"t": 1.0, "sync_with": "cut"}, {"t": 2.0, "sync_with": "text_pop"}, {"t": 3.0, "sync_with": "none"}]+ r = classify_sound_sources(_b(sfx=sfx, labels=("code_render",) * 4))+ assert r["sfx"]["leaning"] == "library_editor"+++def test_sung_vocals_without_vlm_lean_ai_but_tts_narration_does_not():+ b = _b()+ b["audio"]["voice"].update({"style": "singing", "sung": True, "sustained_note_ratio": 0.44})+ r = classify_sound_sources(b)+ assert r["format_context"]["music_mv_maybe"] and r["music"]["leaning"] == "ai_generated"+ b = _b()+ b["audio"]["voice"].update({"style": "speech", "sung": False, "sustained_note_ratio": 0.15})+ r = classify_sound_sources(b)+ assert not r["format_context"]["music_mv_maybe"] and r["music"]["leaning"] == "existing_library"diff --git a/tests/test_stems.py b/tests/test_stems.pynew file mode 100644index 0000000..2cc9413--- /dev/null+++ b/tests/test_stems.py@@ -0,0 +1,41 @@+import numpy as np++from rea_video import stems as S+++def test_stft_roundtrip_matches_input():+ rng = np.random.default_rng(0)+ x = (rng.standard_normal((2, S.CHUNK)) * 0.1).astype(np.float32)+ y = S._istft(S._stft(x))+ mid = slice(S.TRIM, -S.TRIM)+ err = np.abs(y[:, mid] - x[:, mid]).std() / x.std()+ assert y.shape == x.shape and err < 0.02 # only the top bins above DIM_F are dropped+++def test_extract_stems_without_audio(tmp_path):+ assert S.extract_stems(tmp_path / "missing.mp4", tmp_path)["ok"] is False+++def test_ensure_model_rejects_partial_download_and_leaves_no_temp(tmp_path, monkeypatch):+ import pytest++ monkeypatch.setenv("REA_VIDEO_MODELS", str(tmp_path))+ monkeypatch.setattr(S.urllib.request, "urlretrieve", lambda url, dst: open(dst, "wb").write(b"x" * 10))+ with pytest.raises(OSError):+ S.ensure_model()+ assert list(tmp_path.iterdir()) == []+++def test_ensure_model_uses_unique_temp_names(tmp_path, monkeypatch):+ monkeypatch.setenv("REA_VIDEO_MODELS", str(tmp_path))+ seen = []++ def fake(url, dst):+ seen.append(dst.name)+ with open(dst, "wb") as f:+ f.truncate(S.MODEL_BYTES)++ monkeypatch.setattr(S.urllib.request, "urlretrieve", fake)+ S.ensure_model(force=True)+ S.ensure_model(force=True)+ assert len(set(seen)) == 2 and (tmp_path / S.MODEL_NAME).stat().st_size == S.MODEL_BYTESdiff --git a/tests/test_transcode.py b/tests/test_transcode.pynew file mode 100644index 0000000..59f27f1--- /dev/null+++ b/tests/test_transcode.py@@ -0,0 +1,47 @@+from rea_video.classify import deterministic, video_context++PHOTO = {"noise_sigma": 0.5, "temporal_noise": 1.2, "flat_ratio": 0.02, "palette95": 220, "axis_edge_ratio": 0.2,+ "dup_ratio": 0.0, "moving_pair_ratio": 1.0, "zero_pixel_ratio": 0.1, "camera": "smooth_move", "saturation": 0.3}+PROV_WECHAT = {"hints": {"platform": ["WeChat transcode"], "generator": [], "camera": []}}+++def _shots(dup):+ return [{"duration": 3.0, "features": dict(PHOTO, dup_ratio=dup)} for _ in range(3)]+++def test_video_context_native30_only_without_pulldown():+ assert video_context(_shots(0.0), PROV_WECHAT, 30.0)["native30"] is True+ assert video_context(_shots(0.2), PROV_WECHAT, 30.0)["native30"] is False+ assert video_context(_shots(0.0), PROV_WECHAT, 24.0)["native30"] is False+++def test_transcoded_phone_footage_is_not_called_ai():+ ctx = video_context(_shots(0.0), PROV_WECHAT, 30.0)+ probs, ev, facts = deterministic(PHOTO, provenance=PROV_WECHAT, fps=30.0, ctx=ctx)+ assert probs["live_action"] > probs["ai_video"]+ assert facts["transcode_degraded"]+++def test_transcoded_ai_with_pulldown_stays_ai():+ f = dict(PHOTO, dup_ratio=0.2, dup_period=5, dup_regularity=0.6)+ ctx = video_context(_shots(0.2), PROV_WECHAT, 30.0)+ probs, _, _ = deterministic(f, provenance=PROV_WECHAT, fps=30.0, ctx=ctx)+ assert probs["ai_video"] > probs["live_action"]+++def test_gray_ui_is_not_3d():+ ui = {"noise_sigma": 0.1, "temporal_noise": 0.2, "flat_ratio": 0.65, "palette95": 3, "axis_edge_ratio": 0.27,+ "dup_ratio": 0.2, "moving_pair_ratio": 1.0, "zero_pixel_ratio": 0.9, "saturation": 0.006}+ probs, _, facts = deterministic(ui)+ assert facts["ui_gray"] > 0.5 and probs["code_render"] > probs["cg_3d"]+++def test_transcoded_ai_or_live_without_decisive_evidence_is_flagged():+ from rea_video.pipeline import _ai_or_live_doubt++ t = {"transcode_degraded": True, "pulldown": "24→30"}+ assert _ai_or_live_doubt("ai_video", t, {}, {}) and _ai_or_live_doubt("live_action", t, {}, {"native30": False})+ assert _ai_or_live_doubt("ai_video", t, {"aigc": {"label": "1"}}, {}) is None # AIGC label settles it+ assert _ai_or_live_doubt("live_action", {"transcode_degraded": True}, {}, {"native30": True}) is None # phone camera+ assert _ai_or_live_doubt("ai_video", {"pulldown": "24→30"}, {}, {}) is None # not transcoded: noise evidence works+ assert _ai_or_live_doubt("cg_3d", t, {}, {}) is Nonediff --git a/tests/test_vlm_mock.py b/tests/test_vlm_mock.pynew file mode 100644index 0000000..c5e92c9--- /dev/null+++ b/tests/test_vlm_mock.py@@ -0,0 +1,138 @@+"""End-to-end VLM path against a local fake OpenAI-compatible server."""+import json+import threading+from http.server import BaseHTTPRequestHandler, HTTPServer++import pytest++from rea_video.pipeline import decompose++CANNED = {+ "label_probs": {"live_action": 0.05, "ai_video": 0.05, "avatar": 0, "cg_3d": 0, "code_render": 0.8, "screen_capture": 0.1,+ "still_motion": 0, "static_hold": 0},+ "image_source": "graphic", "evidence": ["扁平底色上的卡片滑入,文字边缘锐利"], "generator_guess": "Remotion",+ "description": "深色背景上白色卡片从左侧滑入", "shot_size": "全景", "camera_move": "固定", "style": "扁平 UI",+ "overlay_text": ["REA VIDEO"],+ "replication": {"image_prompt": "深色背景,白色圆角卡片", "video_prompt": "白色卡片从左侧滑入后停在画面中央", "video_prompt_en": "a white card slides in"},+}+++class Handler(BaseHTTPRequestHandler):+ seen = []++ def do_POST(self): # noqa: N802+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ Handler.seen.append(body)+ text = body["messages"][0]["content"][-1]["text"]+ payload = CANNED if "label_probs" in text else {"summary": "测试视频", "format": "知识讲解", "segments": []}+ resp = {"choices": [{"message": {"content": "```json\n" + json.dumps(payload, ensure_ascii=False) + "\n```"}}]}+ data = json.dumps(resp).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def log_message(self, *a):+ pass+++def fake_server(monkeypatch):+ srv = HTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ monkeypatch.setenv("REA_VLM_BASE_URL", f"http://127.0.0.1:{srv.server_port}/v1")+ monkeypatch.setenv("REA_VLM_API_KEY", "test")+ monkeypatch.setenv("REA_VLM_MODEL", "fake-model")+ yield Handler+ srv.shutdown()+++def test_vlm_fusion_end_to_end(media, tmp_path, fake_server):+ b = decompose(media["code"], tmp_path / "o", use_vlm=True, ocr=False, workers=1, stems=False)+ assert b["analysis"]["vlm"]["used"] and not b["analysis"]["vlm"]["errors"]+ s = b["shots"][0]+ assert s["base"]["decided_by"] == "fused" and s["base"]["label"] == "code_render"+ assert s["replication"]["executor"] == "code_render_spec"+ assert b["whole_video_vlm"]["summary"] == "测试视频"+ # the shot request carried a video clip and keyframes as data URIs+ parts = fake_server.seen[0]["messages"][0]["content"]+ kinds = [p["image_url"]["url"].split(";")[0] for p in parts if p["type"] == "image_url"]+ assert kinds[0] == "data:video/mp4" and "data:image/jpeg" in kinds+ # cache hit on second run: no new requests+ n = len(fake_server.seen)+ decompose(media["code"], tmp_path / "o", use_vlm=True, ocr=False, workers=1, stems=False)+ assert len(fake_server.seen) == n+++class Down(BaseHTTPRequestHandler):+ def do_POST(self): # noqa: N802+ self.rfile.read(int(self.headers["Content-Length"]))+ data = b'{"error":{"message":"model temporarily unavailable"}}'+ self.send_response(503)+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def log_message(self, *a):+ pass+++def test_vlm_all_calls_failing_is_reported_as_not_used(media, tmp_path, monkeypatch):+ srv = HTTPServer(("127.0.0.1", 0), Down)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ monkeypatch.setenv("REA_VLM_BASE_URL", f"http://127.0.0.1:{srv.server_port}/v1")+ monkeypatch.setenv("REA_VLM_API_KEY", "test")+ monkeypatch.setenv("REA_VLM_MODEL", "fake-model")+ monkeypatch.setattr("rea_video.vlm.time.sleep", lambda s: None)+ try:+ b = decompose(media["code"], tmp_path / "o", use_vlm=True, ocr=False, workers=1, stems=False)+ finally:+ srv.shutdown()+ v = b["analysis"]["vlm"]+ assert v["requested"] and not v["used"] and v["status"] == "failed" and v["errors"]+ assert "全部调用失败" in b["summary"]["vlm"]+ assert all(s["base"]["decided_by"] == "deterministic" for s in b["shots"])+ assert "全部调用失败" in (tmp_path / "o" / "report.md").read_text(encoding="utf-8")+++def test_vlm_off_suggests_setup_but_still_runs(media, tmp_path):+ b = decompose(media["code"], tmp_path / "o", use_vlm=False, ocr=False, workers=1, stems=False)+ assert b["analysis"]["vlm"]["status"] == "off" and "REA_VLM_BASE_URL" in b["summary"]["vlm"]+ assert b["summary"]["production_mix"]+++class FirstModelDown(Handler):+ calls = []++ def do_POST(self): # noqa: N802+ n = int(self.headers["Content-Length"])+ body = json.loads(self.rfile.read(n))+ FirstModelDown.calls.append(body["model"])+ if body["model"] == "down-model":+ self.send_response(503)+ self.send_header("Content-Length", "0")+ self.end_headers()+ return+ payload = CANNED if "label_probs" in body["messages"][0]["content"][-1]["text"] else {"summary": "x", "segments": []}+ data = json.dumps({"choices": [{"message": {"content": json.dumps(payload, ensure_ascii=False)}}]}).encode()+ self.send_response(200)+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)+++def test_vlm_falls_back_and_sticks_to_working_model(media, tmp_path, monkeypatch):+ srv = HTTPServer(("127.0.0.1", 0), FirstModelDown)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ monkeypatch.setenv("REA_VLM_BASE_URL", f"http://127.0.0.1:{srv.server_port}/v1")+ monkeypatch.setenv("REA_VLM_API_KEY", "test")+ monkeypatch.setenv("REA_VLM_MODEL", "down-model,good-model")+ monkeypatch.setattr("rea_video.vlm.time.sleep", lambda s: None)+ try:+ b = decompose(media["code"], tmp_path / "o", use_vlm=True, ocr=False, workers=1, stems=False)+ finally:+ srv.shutdown()+ assert b["analysis"]["vlm"]["status"] == "ok"+ # the dead model is tried on the first request only+ assert FirstModelDown.calls.count("down-model") == 2 and FirstModelDown.calls[-1] == "good-model"