Skip to content

艺术动画skill:35种艺术风格、9种解说语法,用代码让画动起来。

feat: 反 PPT 门禁装进交付,交付说明里的事实由脚本写(改动包C)

alchain5cf0153d02d1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 92002fc..31b9850 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,3 +26,4 @@
- 2026-10-08 · P2/P3:增加现有图片与当前宿主工具桥接、需求计划/回执/透明背景/尺寸与SHA验收;旧配置保留,新增能力不自动授权;补充贡献与兼容性说明、CI及增量发布检查。三家安装重装通过,Codex在线验收通过,Claude/Kimi在线验收因账户条件待补。
- 2026-10-09 · 换掉把模型往坏处带的默认值(只改文档与样例):SKILL.md 首屏加模型分档(开阔档/轨道档)、「五种做坏方式」、窄桥改成「动在事件上」的脉冲节奏并写明真实素材当主画面、示范不许原样进成片;各语法卡删掉「静止就加慢推」药方、补「起手必查」,t2 的光斑、毛玻璃、渐变字降为可选;风格 INDEX 拆成材料层/时代标本,写明 35 张样片同构图是速通机制;固定场景骨架限定为速通/穿越类;8 份样例 spec 改成画面事件开场、每条字 ≤14。
- 2026-10-10 · 把认可过的做法做成引擎能力(改动包B,改代码):新增 `CAM.track` 脉冲镜头(快推 0.28s/同倍率横移 0.30s/整帧砸入 0.17s/震镜/硬切)与 `MO.PULSE/slamK/slam/pulse`;新增 `lib/media.js`(`MD.cover` 满幅+焦点推近、`MD.print` 冲印件、`MD.label` 黑底撕边标签、`MD.frameAt` 帧序列),素材缺失一律报错;片段 spec 认 `cues[].frames` 录像帧与 y4 角色帧库(`engine/spec_assets.py`);t2 截图默认满幅+highlight 快推+两屏之间横移,玻璃卡改为 `data.frame:"glass"` 可选;y1 中心物由 `data.center_style`/`data.image` 指定,默认按名字生成中性样式、不再是橙色带轨道星球;y2 照片改冲印件、占画面八九成;y4 默认角色换成中性造型(`data.character`:neutral/bun/author/造型对象/帧库目录),作者形象需显式指定;去掉 y1/y2/y4/y5/t2 内置的匀速慢推、手持微漂、呼吸、漂浮;引擎和转场按当前画布算,`render.py --film --width 1080 --height 1920` 出竖屏整片;引擎视频帧改为等比铺满、缺帧拒绝渲染;新增样例 `examples/t2_fullbleed_pulse.json`(两张真实终端截图)。横屏示范片、原片与全风格样片逐像素不变。
+- 2026-10-10 · 反 PPT 门禁装进交付(改动包C):新增 `scripts/film_gate.py`(只读成片,门禁只有快速运动帧占比,< 0.035 红灯、< 0.06 黄灯,阈值来自作者表过态的 13 支片;其余指标只报告,静止类不当门禁;报告给最差 30 秒窗口、一句话原因和修法)与 `scripts/deliver.py`(一条命令交付:红灯不复制成片、非零退出;绿灯、黄灯复制成片并写 `交付说明.md`,时长、分辨率、门禁各项、qa 结果、`审片/*.md` 有无都由脚本写,事实段带指纹、`--verify` 可查);qa 把短于 0.35 秒的单调推拉、横移记作镜头事件不算跳变,`--spec` 改用 `spec_assets` 解析,认 `frames` 与角色帧库;SKILL.md 轨道档第 5、6 步改为 qa → deliver.py,验收段、五种做坏方式第 1 条、09 号同步;`tests/test_film_gate.py` 用两支合成片端到端测门禁、交付与镜头事件。
diff --git a/README.md b/README.md
index f7387db..cb3ff3d 100644
--- a/README.md
+++ b/README.md
@@ -83,7 +83,7 @@ npx skills add alchaincyf/huashu-art-motion
| 「画面里要有人」 | 人交给生图模型出帧,代码负责合成、换帧和材质 |
| 「配个乐、卡节奏」 | BPM 网格、动机换乐器、结尾音效序列,纯代码合成 |
-交付前有一道数字验收:`qa.py` 量稳定、效率、动感、流畅及文字框景线索,再派一个没参与制作的 agent 只看成片挑问题。
+交付前有一道数字验收:`qa.py` 量稳定、效率、动感、流畅及文字框景线索,再派一个没参与制作的 agent 只看成片挑问题;最后 `deliver.py` 一条命令交付——成片先过反 PPT 门禁(整片几乎没有镜头内快动作就红灯,不出片),过了才复制成片、写交付说明,说明里的事实由脚本写。
---
@@ -109,6 +109,8 @@ huashu-art-motion/
├── engine/ # 可整个复制走的动画工程:引擎、转场、库、场景、示范片、片段
├── analyze/breakdown.py # 把参考动画拆成「能写代码的地图」
├── qa.py # 一键验收
+ ├── film_gate.py # 成片门禁:量翻页式 PPT 感(只读 mp4)
+ ├── deliver.py # 一条命令交付:门禁→复制成片→写交付说明
├── audio/ # 纯代码合成配乐的模板
└── font_subset.py ... # 字体子集、绿幕抠图
```
diff --git a/SKILL.md b/SKILL.md
index 21605f8..275823e 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -7,14 +7,14 @@ description: "艺术与视频动画:拆解复刻动画;代码画35种艺术
## 先分档:你按哪一档读
-- **开阔档**:你是 Claude Opus 5.5 或更强的模型。全文都适用:路由表、窄桥、开阔地;库可以自己组合,渲染器可以自己写。
+- **开阔档**:你是 Claude Opus 5.5 或更强的模型。全文都适用:路由表、窄桥、开阔地;库可以自己组合,渲染器可以自己写;交付同样走 `scripts/deliver.py`,红灯不交付。
- **轨道档**:其它模型,或判断不出自己是谁。只走下面这一条路,只读这条路需要的 2–3 个文件,其余 reference 先不读:
1. **复制工程**:`cp -R <skill>/scripts/engine <项目>/代码工程`。
2. **选语法**:读 `references/09-视频动画语法.md` 第二节(选型表)和第五节里你选的那一种,再读 `references/动画语法/<语法>.md` 的「起手必查」。要艺术风格画面(梵高、像素……)就改读 `references/风格配方/INDEX.md` 和一张风格卡,写 `scenes/<id>.js`。
3. **填 spec 或照卡做**:从 `examples/<语法>.json` 抄结构,不抄内容。第一个 cue 是画面事件,不是标题;每条 text ≤14 字。
4. **渲染**:`uv run --with playwright python <项目>/代码工程/render.py --spec <spec>.json --out 片段.mp4`;加 `--stills 1,3,5 --out 静帧/` 抽 3 帧看。
5. **qa**:`uv run <skill>/scripts/qa.py --spec <spec>.json`,再拿抽帧逐条对下面「五种做坏方式」。
- 6. **交付**:写清用了哪个语法、qa 数字、五种做坏方式逐条自查的结果。没派独立审片就写「没派」。
+ 6. **交付**:`uv run <skill>/scripts/deliver.py 片段.mp4 --spec <spec>.json --root <项目> --out output/`。红灯不交付:脚本不复制成片,照它打印的修法改完重渲、重跑。绿灯、黄灯它复制成片并写 `output/交付说明.md`,时长、门禁、qa、有没有审片由脚本写;你只在「制作说明」段补用了哪个语法、黄灯项逐条理由、五种做坏方式自查,事实段不许改。派了独立审片的,先让审片人把结论写进 `<项目>/审片/*.md` 再跑。
## 你是谁
@@ -22,7 +22,7 @@ description: "艺术与视频动画:拆解复刻动画;代码画35种艺术
## 最常见的五种做坏方式(开工前、交付前各对一遍)
-1. **翻页式 PPT**:固定页眉、页码,要点逐条淡入,每镜匀速慢推。→ 去掉页框,一镜一个画面事件,镜头按窄桥第一条的脉冲节奏动。
+1. **翻页式 PPT**:固定页眉、页码,要点逐条淡入,每镜匀速慢推。→ 去掉页框,一镜一个画面事件,镜头按窄桥第一条的脉冲节奏动。deliver.py 会量出来:整片几乎没有镜头内快动作就红灯,不出片。
2. **照搬示范**:示范片、样例 spec、风格样片里的构图、角色、素材直接进了成片。→ 只学做法,构图和物按题材重新设计。
3. **没有具体的物**:抽象概念只写成字和图标。→ 镜头表每行写出一个具体的物和它的动作,写不出物的那一行先别做。
4. **死背景**:大面积纯色或星空底一直不变,只有中间一小块在动。→ 主体放大到占画面一半以上,背景跟着内容换。
@@ -61,7 +61,7 @@ description: "艺术与视频动画:拆解复刻动画;代码画35种艺术
- **复刻是学机制,不是逐像素。** 提取场景、运动与转场规律,再用于新题材。
- **三方向硬门**:新的角色诠释或风格方向,先出三个给用户挑,三个方向的构图要不同,不能只换调色。指定了风格也不豁免。
- **确定性**:所有随机用种子,同一时刻渲两次逐像素一致。
-- **独立审片**:成片交付前派一个没参与制作的 agent 只看成片挑问题。
+- **独立审片**:成片交付前派一个没参与制作的 agent 只看成片挑问题,结论写进 `<项目>/审片/*.md`(deliver.py 只认这里)。
- 角色涉及未成年人(如 17 岁)时,服装一律端庄长款;给生图模型写「短裙」会被审核整张拒绝。
## 开阔地:当起点,不当配额
@@ -85,7 +85,7 @@ uv run scripts/analyze/breakdown.py --video 参考.mp4 --out 拆解/
## 验收
-交付前必跑 `uv run scripts/qa.py --project <工程>`(参数化片段用 `--spec`;稳定/效率/动感/流畅及文字框景线索)+派独立 agent 只看成片审片。qa 只量技术项,量不出 PPT 感,所以抽帧还要对一遍「五种做坏方式」;静止帧对高不一定是卡,脉冲节奏的片子本来就有大段停住。浅底无字幕成片再用`uv run --with numpy python scripts/subzone_gate.py 成片.mp4`检查图形进入字幕区;纹理底不适用。两样都做完才算完成。经验先看 `07-正面经验.md`。
+交付前三样,按顺序:①`uv run scripts/qa.py --project <工程>`(参数化片段用 `--spec`;稳定/效率/动感/流畅及文字框景线索;短于 0.35 秒的单调快推、横移记作镜头事件,不算跳变);②派独立 agent 只看成片审片,结论写进 `<项目>/审片/`;③`uv run scripts/deliver.py 成片.mp4 --project <工程>(或 --spec)--out output/`。deliver.py 先过门禁 `film_gate.py`:快速运动帧占比 < 0.035 红灯,不复制成片、非零退出;< 0.06 黄灯。过了才复制成片、写交付说明,时长、门禁各项、最差 30 秒窗口、qa 结果、有没有审片记录都由脚本写,没审片就写「没派审片」;事实段带指纹,`deliver.py --verify` 查得出改动。门禁只拦「整片没有一次镜头内快动作」这一种 PPT,页框、米底小图、前紧后松拦不住,所以抽帧还要对一遍「五种做坏方式」;静止多不是病,脉冲节奏的片子本来就有大段停住,静止类数字别拿来判。浅底无字幕成片再用`uv run --with numpy python scripts/subzone_gate.py 成片.mp4`检查图形进入字幕区;纹理底不适用。经验先看 `07-正面经验.md`。
## 回流
diff --git "a/references/09-\350\247\206\351\242\221\345\212\250\347\224\273\350\257\255\346\263\225.md" "b/references/09-\350\247\206\351\242\221\345\212\250\347\224\273\350\257\255\346\263\225.md"
index 17c2959..1b8ab3c 100644
--- "a/references/09-\350\247\206\351\242\221\345\212\250\347\224\273\350\257\255\346\263\225.md"
+++ "b/references/09-\350\247\206\351\242\221\345\212\250\347\224\273\350\257\255\346\263\225.md"
@@ -115,8 +115,9 @@ uv run --with playwright python engine/render.py --spec clip.json --stills 0.5,2
- 时长严格等于 `duration`:帧数 = round(duration × fps),第 i 帧的时间是 i / fps。H.264 每秒一个关键帧(GOP = fps),管线的渲染器按秒 seek 不冻帧。
- 宽高和 fps 从 spec 读,默认 1920×1080@30;竖屏写 `width: 1080, height: 1920`(或命令行 `--width 1080 --height 1920` 覆盖 spec),每种语法都有竖屏排版。
- spec 里的素材路径相对 spec 文件(也可以写绝对路径);render.py 只服务 spec 里点名的文件。认这些字段:`cues[].image`、`cues[].frames`(录像帧序列:一个目录或路径数组)、`data.image`、`data.character`(y4 帧库目录)。路径怎么解析见 `engine/spec_assets.py`。
-- 量这一段:`uv run qa.py --spec <clip.json>`(在 `scripts/` 下;整段当一段量确定性、运动、静止帧对、孤立跳变、耗时,竖屏按画幅缩)。
-- 页面报错(语法文件出错、图片或视频帧不存在)→ 非零退出,不出片。`qa.py --spec` 目前只认 `cues[].image` 和 `data.image`,用了 `frames` 或角色帧库的 spec 先用 render.py 渲、抽帧核。spec 里有字库没有的汉字只告警(会回退系统字体,换台机器会变样),常用字都在子集里。
+- 量这一段:`uv run qa.py --spec <clip.json>`(在 `scripts/` 下;整段当一段量确定性、运动、静止帧对、孤立跳变、耗时,竖屏按画幅缩;短于 0.35 秒的单调快推、横移、砸入记作镜头事件,不算跳变)。
+- 交付:`uv run deliver.py 片段.mp4 --spec <clip.json> --out output/`。先过门禁 `film_gate.py`(快速运动帧占比 < 0.035 红灯,不复制、非零退出),过了才复制并写 `交付说明.md`,事实段由脚本写。门禁是在 1–2 分钟的成片上标定的,10 秒以内的片段数值噪声大;片段要拼进成片的,在成片上跑 deliver.py。
+- 页面报错(语法文件出错、图片或视频帧不存在)→ 非零退出,不出片。`qa.py --spec` 和 render.py 用同一套素材解析(`engine/spec_assets.py`),`frames` 和角色帧库都认。spec 里有字库没有的汉字只告警(会回退系统字体,换台机器会变样),常用字都在子集里。
### spec
@@ -349,7 +350,8 @@ uv run --with playwright python engine/render.py --spec engine/examples/t2_fullb
| 8 支示范片 vs 实验原片 | 每片 16 个时刻(含转场窗口)逐像素一致;qa 25 段全部无报错、确定性 ✓;运动、跳变、耗时和原工程一致(各片首段起点从 8/16s 变成 0,qa 采样窗口不同,所以首段数字略有出入) |
| 2026-10-05 终审修复后 | 8 份样例+16 原段+36 样片+8 支示范片共 87 段 qa 全部确定性 ✓、无页面报错;样例静帧只有预期的变化(t2 差 1 色阶=修确定性、y5 深蓝页关键词改橙、y1 标题真的淡出);独立终审 36 份 spec(横屏样例、竖屏、压力、边界、alpha)无 🔴 |
| 2026-10-10 脉冲镜头、真实素材件、竖屏整片进引擎后 | 16 段原片、36 段全风格样片、8 支示范片、长卷示范,各取 18 个时刻,横屏改前改后逐像素一致(示范片 y4 显式用 `char: 'author'`);9 份样例横竖屏都渲过、qa 确定性 ✓;竖屏测试片的 push / bands / iris / comicPanels 转场按 1080×1920 算对 |
-| 已知的跳变 | y1_s3(42 倍→1 倍拉出中段)、y2_s2/s3(快摇与推满照片)、t1_s3(穿进神经元)、y5 拍点重音——都是设计内的相机推拉或节拍闪,原片里就有 |
+| 已知的跳变 | y1_s3(42 倍→1 倍拉出中段)、y2_s2/s3(快摇与推满照片)、t1_s3(穿进神经元)、y5 拍点重音——都是设计内的相机推拉或节拍闪,原片里就有。2026-10-10 起 qa 把短于 0.35 秒的单调推拉、横移记作镜头事件:示范片里 t1_s3 的 1.51s、y5 k4_agent 的 2.2s、t3_s1 的 2.1s 改记镜头事件;其余都长于 0.35 秒(或是一拍二的单帧跳),照旧记跳变 |
+| 2026-10-10 门禁与一条命令交付 | qa 改动前后:8 支示范片和 9 份样例 spec 的运动、静止帧对、确定性、框景不变;跳变只少了被认成镜头事件的那些(按事件计:示范片 3 处,样例 t2_keynote_ui 1 处、y4_storytime 3 处、y5_kinetic_type 2 处,都是 0.07–0.34 秒的推拉、砸入或姿势快切),长于 0.35 秒的推拉和一拍二的单帧跳照旧报;合成片(同三张图、每镜 3 秒):每镜匀速慢推 7.5% 快动帧 0.000 红灯,每镜一次 0.3 秒快推 30% 为 0.095 绿灯;整片模式里一次 0.3 秒快推以前记 8 个跳变,现在记 1 个镜头事件,闪一帧白仍记跳变 |
---
diff --git a/release-manifest.json b/release-manifest.json
index dcf44ad..23a8cfc 100644
--- a/release-manifest.json
+++ b/release-manifest.json
@@ -3,11 +3,11 @@
"files": {
".github/workflows/tests.yml": "91b5797ea6f59b6e31e53de2a846194e33ab1dbe24b2efb8c0ed4367324f8fbe",
".gitignore": "64ed0cc55105bb4b33ebd1baadd1eb18c74b604f6bbce0fbaa4c62b5eb425197",
- "CHANGELOG.md": "c13558423daafaeb95d7a4fc23a8e2b9613f7a8d8d81ee41ea6dcc1af438283b",
+ "CHANGELOG.md": "d5740e09c19b8ad33b8f6731e465d08f97e6639709faef295824bf94c8515953",
"CONTRIBUTING.md": "742a1a6071f6be25e82f0524a520fd6d09961be3f87d7a85940cd816ce7309a1",
"LICENSE": "6d6a2a9caf2e6d2b76974050427053b2892d8aa4c33fd168ce63a537fcee9d96",
- "README.md": "b129107c5e219fbeb558beae103d6eb5dc2a7c18d09e1b3a1d4853a400b370bb",
- "SKILL.md": "7472042ca137ef984f28cde3208abf8caa589aaf142273788ccc8b5539d93c50",
+ "README.md": "1b6a26c29af8e07338b2b8ace6219a3d7268901497870e6538b3633a9266f172",
+ "SKILL.md": "2329fae9fb1e517e36c976bc441d3cfdf9398f8292d147c231c205e8d4d47ba4",
"assets/showcase/egypt.gif": "256b946e2543192153f276dc46e0af98837c934ddb9e2e2c0c9843f0557cd54b",
"assets/showcase/hero.png": "3b6b42bfb00f84925aebe2a10f85052dc6b4efb492e86f581f21f652b6686407",
"assets/showcase/mario-claude.gif": "f63f2f464c1d7b477578d07359d85712086a39b615669f1d3bb015290c54741f",
@@ -36,7 +36,7 @@
"references/06-口播驱动的艺术短片.md": "9275abd6451831515ed9aed24724062bf47dda5e5d2d804baa8313c137236bc8",
"references/07-正面经验.md": "fd5f63474f15e01119e10586a14a456f602cf4f6ee03b4359bcf77c084305f1b",
"references/08-风格作者规范.md": "30312801d2833b478bc80218a704d87971c08f50a7ee0e31f3c08eefe15f9b4e",
- "references/09-视频动画语法.md": "23498069c7bc2f791b0a8c4c0b4f408cad8d21f41675ec8032c23071edb88dd4",
+ "references/09-视频动画语法.md": "2bc4da94971a27098cd6d45601c2adabb11035261b5a1e4e3bda315cd2697ad1",
"references/10-角色.md": "0c69bc849688069ee59bfe619eb7c44c48dbeee0324ee2bcc87bbe98d41af74b",
"references/11-长卷穿越片.md": "42f2e441687116c8d2dd789b187ada572390e242976996727a209959163a6ad6",
"references/12-口播整片与经验回流.md": "b85f6e8b665c13a5d98ea461c10af340679a6949101ee31dd64eee7e88aed415",
@@ -97,6 +97,7 @@
"scripts/audio/synth_艺术史速通.py": "6476605af684b477d47b7f47c3c987059277de36b97bff5d77d167c27efdb40d",
"scripts/capabilities.py": "43b1dd58d9f42efc638270cf67190ce85dda4e25fd591925c2f31e5bd6b4f63b",
"scripts/check_release.py": "508388bdcfe87d97d486de7d76fec87b893469779af14cc75e4b72b4c17ecc60",
+ "scripts/deliver.py": "55c4bd6fd4059b3db4d47c30b9125056e35c09b07cbe4cc6f98caaf79e9248e0",
"scripts/engine/clip.html": "dab49e34a45f0dfd8e49fb25444a6d6cd51425a7f53513d0001b0e215f15c343",
"scripts/engine/clip.js": "81c11d0261bd1913a384c25d30458c5dd4eabfda24e786858490d239c6b21191",
"scripts/engine/clips/t1_3b1b.js": "6e819bb9be76db0d8a7220e8aa5fedd83879b24ce6084579d7ac2641d85deaa2",
@@ -408,14 +409,16 @@
"scripts/engine/spec_assets.py": "0f32fb56eae66532c0bc644519afb1d9d71d36efcf9fe4c19539752387ef7e66",
"scripts/engine/transitions.js": "c4bd441cf765db346933e5d18270f532d4c9782c9303b0bcda1ba59a2124b618",
"scripts/engine/时代作者规范.md": "4e7661571b60fa0ed776fb5631462aff3a30235c5e6343aa06f9cd23973391fc",
+ "scripts/film_gate.py": "b04ac7ed7452fcd9adf491753605e0ea5bac1cb256020d42b02e79fe03e61c7b",
"scripts/font_subset.py": "ed826dffb4b370741602aa79caefd69157fcf6d7f9abd90a9078d4f7208896e0",
"scripts/images.py": "a47a2663f251525bfbed5b46533e3d43415c9e10c8a2b8a9f754abf204529535",
"scripts/key_green.py": "11ac28bb2508d6b4a240eb37a55b342a0f556943fe29a17962bbc0f93f90d303",
"scripts/key_split.py": "889759cd6b5353b4d48d34faf3878682890e06ca79887c9ade9be401b7359f86",
"scripts/koubo.py": "7837507e6bf02b20f8aa63efdc881c8de0d5de775b4bf31a1040bd3824348494",
- "scripts/qa.py": "e6d229292103ffc0783e999d46984b3521cfe5b24803bc2db214bc3e03b6efed",
+ "scripts/qa.py": "a1457de52ee311659039207ef3304b6ade1531f538843a15bb509698e4b37da9",
"scripts/subzone_gate.py": "8641a3b1b38ac28c1562e454a0e370f36a73d1a0c79cddf36175c7444a9c1598",
"tests/test_capabilities.py": "04ce548d5a72a11a87a3bd85c46a98e13f1aabafb096e3c59a6fc7a20bfdf4ad",
+ "tests/test_film_gate.py": "e5af578706bfb98bc9604d2e19742324a7f654d02a9f5b6b9a18658ff9d4339d",
"tests/test_images.py": "5fe7533ec25a2644e3685e1677186eaf1554ebbbcc390fcd56a45afbad872040",
"tests/test_local_server.py": "b775a60c86c4a0914d67c4cfb7cb37256a447db700bfdba146a2db3704ea83ff",
"tests/test_release.py": "a190d8825e23f6204263f3d00d6728bf709586bc178c980d53244a82ef198b41"
diff --git a/scripts/deliver.py b/scripts/deliver.py
new file mode 100644
index 0000000..2fd62b4
--- /dev/null
+++ b/scripts/deliver.py
@@ -0,0 +1,221 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = ["numpy", "opencv-python-headless"]
+# ///
+"""deliver.py —— 一条命令交付:量门禁 → 红灯不出片;绿灯、黄灯复制成片并写交付说明,说明里的事实由脚本写。
+
+ uv run deliver.py <成片.mp4> --out output/ [--spec 片段.json | --project <代码工程>] [--qa <qa 输出目录>] [--root <项目目录>]
+ [--sub-band 0.15] [--vertical auto|yes|no]
+ uv run deliver.py --verify output/交付说明.md # 核对事实段有没有被改过
+
+做三件事:
+ 1. 跑同目录的 film_gate.py。红灯:不复制成片、不写说明,打印原因和怎么改,退出码 2。
+ 2. 绿灯、黄灯:把成片复制到 --out,写 --out/交付说明.md。事实段全部由脚本写:
+ 时长、分辨率、帧率、音轨、文件指纹;门禁各指标和灯;最差 30 秒窗口;
+ qa 跑没跑过、结果如何(读 qa 输出目录里的 qa.json,没有就写「没跑」);
+ 有没有独立审片记录(<项目目录>/审片/*.md 在不在,列出文件名;没有就写「没派审片」)。
+ 3. 事实段末尾带指纹。制作者只在「制作说明」段补主观描述(用了哪个语法、黄灯项为什么可以这样、五种做坏方式自查),
+ 不改事实段;改了 --verify 会报出来。
+
+约定:
+ - qa 输出目录:--qa 优先;否则和 qa.py 的默认一致——--spec → <spec 所在目录>/qa,--project → <代码工程的上一级>/qa。
+ - 项目目录:--root 优先;否则 --project 的上一级;否则 --spec 所在目录;否则成片所在目录。
+ - 审片人(没参与制作的 agent 或人)把结论写成 <项目目录>/审片/<任意名>.md。脚本只看文件在不在,不读内容,不替审片人下结论。
+"""
+from __future__ import annotations
+
+import argparse
+import datetime
+import hashlib
+import json
+import re
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import film_gate # noqa: E402
+
+DOC = "交付说明.md"
+START = "<!-- deliver.py 事实段:开始。这一段由脚本生成,不要改;改了 deliver.py --verify 会报出来 -->"
+END_RE = re.compile(r"<!-- deliver\.py 事实段:结束 sha256=([0-9a-f]{64}) -->")
+LIGHT_ZH = {"red": "红灯", "yellow": "黄灯", "green": "绿灯", "--": ""}
+
+
+def probe(path):
+ out = subprocess.check_output(["ffprobe", "-v", "error", "-show_entries",
+ "stream=codec_type,codec_name,width,height,avg_frame_rate:format=duration",
+ "-of", "json", str(path)])
+ j = json.loads(out)
+ v = next(s for s in j["streams"] if s.get("codec_type") == "video")
+ a = [s for s in j["streams"] if s.get("codec_type") == "audio"]
+ num, _, den = (v.get("avg_frame_rate") or "0/1").partition("/")
+ fps = float(num) / float(den or 1) if float(den or 1) else 0.0
+ return {"duration": float(j["format"].get("duration") or 0), "width": v["width"], "height": v["height"],
+ "fps": round(fps, 3), "vcodec": v.get("codec_name"), "audio": a[0].get("codec_name") if a else None}
+
+
+def sha256(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for b in iter(lambda: f.read(1 << 20), b""):
+ h.update(b)
+ return h.hexdigest()
+
+
+def stamp(p):
+ return datetime.datetime.fromtimestamp(p.stat().st_mtime).strftime("%Y-%m-%d %H:%M:%S")
+
+
+def qa_facts(qa_dir, spec):
+ """读 qa.py 的输出。返回事实行(列表)。"""
+ if qa_dir is None:
+ return ["- 没跑(没给 --spec / --project / --qa,不知道去哪找 qa 输出)"]
+ f = qa_dir / "qa.json"
+ if not f.is_file():
+ return [f"- 没跑({f} 不存在)"]
+ try:
+ r = json.loads(f.read_text())
+ except (ValueError, OSError) as e:
+ return [f"- qa.json 读不了:{f}({type(e).__name__}),按没跑算"]
+ segs = r.get("segments", [])
+ det = sum(1 for s in segs if s.get("deterministic"))
+ spikes = sum(len(s.get("spikes_at_lt", [])) for s in segs)
+ cams = sum(len(s.get("camera_events_lt", [])) for s in segs)
+ framing = sum(len(s.get("framing", [])) for s in segs)
+ errs = r.get("page_errors", [])
+ L = [f"- 跑过:`{f}`(写于 {stamp(f)})",
+ f"- 页面报错 {len(errs)} 条" + ("(qa 判失败)" if errs else ""),
+ f"- 确定性:{det}/{len(segs)} 段逐像素一致",
+ f"- 跳变 {spikes} 处" + (f";另有镜头事件 {cams} 个(短于 0.35 秒的单调推拉/横移,不算跳变)" if "camera_events_lt" in (segs[0] if segs else {}) else ""),
+ f"- 框景线索 {framing} 条(半截字、叠字、进字幕带、近空白;是「去看这一帧」,不是错误)"]
+ for s in segs:
+ L.append(f" - {s.get('id')}:运动 {s.get('motion_pct')}%,静止帧对 {s.get('still_pairs_pct')}%,"
+ f"跳变 {len(s.get('spikes_at_lt', []))},{s.get('ms_mean')}/{s.get('ms_max')} ms/帧")
+ if spec is not None and r.get("spec") and Path(r["spec"]).resolve() != spec.resolve():
+ L.append(f"- 注意:这份 qa.json 量的是另一份 spec({r['spec']}),不是 {spec}")
+ if spec is not None and spec.is_file() and spec.stat().st_mtime > f.stat().st_mtime:
+ L.append(f"- 注意:spec 在 qa 之后改过(spec 写于 {stamp(spec)}),这份 qa 结果可能已经过期")
+ return L
+
+
+def review_facts(root):
+ d = root / "审片"
+ files = sorted(p.name for p in d.glob("*.md")) if d.is_dir() else []
+ if not files:
+ return [f"- 没派审片(`{d}` 下没有 .md 文件)"]
+ return [f"- 有 {len(files)} 份审片记录(`{d}`):" + "、".join(files),
+ "- 脚本只确认文件存在,没有读内容;审片结论以文件本身为准"]
+
+
+def facts_block(src, dst, info, res, rows, qa_lines, rv_lines):
+ ex = res["explain"]
+ gl = res["gate_light"]
+ L = ["## 事实(deliver.py 写入)", "",
+ f"- 生成时间:{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
+ f"- 成片:`{dst.name}`(sha256 {sha256(dst)[:16]};源文件 `{src}`)",
+ f"- 时长 {info['duration']:.2f}s | {info['width']}×{info['height']} | {info['fps']:g}fps | 视频 {info['vcodec']} | "
+ f"音轨:{info['audio'] or '无'}",
+ "", "### 门禁(film_gate)", "",
+ f"- 结论:{LIGHT_ZH[gl]}。快速运动帧占比 {res['fast_ratio']}(< 0.035 红灯,< 0.06 黄灯)",
+ f"- 一句话:{ex['summary']}。" + (";".join(ex["why"]) + "。" if ex["why"] else "")]
+ if ex["worst_window"]:
+ w = ex["worst_window"]
+ L.append(f"- 最差 {w['end_s'] - w['start_s']:.0f} 秒窗口:{w['start_s']:.0f}–{w['end_s']:.0f}s,快动帧占比 {w['fast_ratio']}")
+ if ex["fix"]:
+ L.append(f"- 怎么改:{ex['fix']}")
+ L += ["", "| 灯 | 类型 | 指标 | 值 |", "|---|---|---|---|"]
+ for k, name, v, lv, gate, unit in rows:
+ vs = "—" if v is None else (f"{v:.3f}" if isinstance(v, float) else str(v))
+ L.append(f"| {LIGHT_ZH[lv] or '只给数'} | {'门禁' if gate else '报告'} | {name} | {vs}{unit} |")
+ L += ["", "### qa", ""] + qa_lines + ["", "### 独立审片", ""] + rv_lines
+ return "\n".join(L) + "\n"
+
+
+def write_doc(out, dst, facts, res):
+ h = hashlib.sha256(facts.encode()).hexdigest()
+ look = [t for _, t in res["explain"]["look"]]
+ if res["gate_light"] == "yellow":
+ look.insert(0, f"门禁黄灯:快速运动帧占比 {res['fast_ratio']}(黄线 0.06)")
+ tail = ["## 制作说明(制作者填写;只写在这一段,事实段不要动)", "",
+ "- 用了哪个语法 / 风格:",
+ "- 「五种做坏方式」逐条自查:",
+ "- 黄灯项逐条说明(时间码+为什么可以这样):" + ("" if look else "无黄灯项")]
+ tail += [f" - {t}:" for t in look]
+ doc = f"# 交付说明:{dst.name}\n\n{START}\n{facts}<!-- deliver.py 事实段:结束 sha256={h} -->\n\n" + "\n".join(tail) + "\n"
+ (out / DOC).write_text(doc)
+ return out / DOC
+
+
+def verify(path):
+ t = Path(path).read_text()
+ i = t.find(START)
+ m = END_RE.search(t)
+ if i < 0 or not m or m.start() < i:
+ print(f"❌ {path}:找不到事实段的开始/结束标记(被删了或不是 deliver.py 写的)"); return 3
+ facts = t[i + len(START) + 1: m.start()]
+ if hashlib.sha256(facts.encode()).hexdigest() != m.group(1):
+ print(f"❌ {path}:事实段被改过,和 deliver.py 写入时不一致。重跑 deliver.py 生成。"); return 3
+ print(f"✓ {path}:事实段和 deliver.py 写入时一致"); return 0
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("mp4", nargs="?")
+ ap.add_argument("--out", help="交付目录(如 output/)")
+ ap.add_argument("--spec", help="参数化片段 spec(用来找 qa 输出:<spec 所在目录>/qa)")
+ ap.add_argument("--project", help="代码工程目录(用来找 qa 输出:<代码工程的上一级>/qa)")
+ ap.add_argument("--qa", help="qa 输出目录(qa.py --out 写到别处时用)")
+ ap.add_argument("--root", help="项目目录(在它下面找 审片/*.md)")
+ ap.add_argument("--sub-band", type=float, default=None, help="同 film_gate.py:屏蔽底部字幕带的比例")
+ ap.add_argument("--vertical", default="auto", choices=["auto", "yes", "no"])
+ ap.add_argument("--verify", metavar="交付说明.md", help="只核对事实段有没有被改过")
+ a = ap.parse_args()
+ if a.verify:
+ sys.exit(verify(a.verify))
+ if not a.mp4 or not a.out:
+ ap.error("要给成片和 --out")
+ src = Path(a.mp4).resolve()
+ if not src.is_file():
+ print(f"成片不存在:{src}", file=sys.stderr); sys.exit(1)
+ if not shutil.which("ffmpeg") or not shutil.which("ffprobe"):
+ print("需要 ffmpeg/ffprobe", file=sys.stderr); sys.exit(1)
+ spec = Path(a.spec).resolve() if a.spec else None
+ proj = Path(a.project).resolve() if a.project else None
+ qa_dir = Path(a.qa).resolve() if a.qa else spec.parent / "qa" if spec else proj.parent / "qa" if proj else None
+ root = Path(a.root).resolve() if a.root else proj.parent if proj else spec.parent if spec else src.parent
+
+ try:
+ info = probe(src)
+ res, rows = film_gate.measure(str(src), sub_band=a.sub_band, vertical=a.vertical)
+ except (subprocess.CalledProcessError, StopIteration, KeyError, RuntimeError, ValueError) as e:
+ print(f"读不了这支片:{src}({e})", file=sys.stderr); sys.exit(1)
+ print("\n".join(film_gate.report_lines(res, rows)))
+ ex = res["explain"]
+ if res["verdict"] == "red":
+ print(f"\n❌ 红灯,不交付:{ex['summary']}。" + (";".join(ex["why"]) + "。" if ex["why"] else ""))
+ print("怎么改:" + ex["fix"])
+ print(f"没有复制成片,也没有写{DOC}。改完重渲,再跑一次 deliver.py。")
+ sys.exit(2)
+
+ out = Path(a.out).resolve()
+ out.mkdir(parents=True, exist_ok=True)
+ dst = out / src.name
+ if dst != src:
+ shutil.copy2(src, dst)
+ qa_lines, rv_lines = qa_facts(qa_dir, spec), review_facts(root)
+ facts = facts_block(src, dst, info, res, rows, qa_lines, rv_lines)
+ doc = write_doc(out, dst, facts, res)
+ gl = res["gate_light"]
+ print(f"\n{'✓ 绿灯' if gl == 'green' else '⚠ 黄灯'},已交付:{dst}")
+ print(f"交付说明:{doc}(事实段由脚本写;主观描述只补在「制作说明」段)")
+ print("qa:" + qa_lines[0][2:])
+ print("审片:" + rv_lines[0][2:])
+ if ex["look"]:
+ print("黄灯项要在交付说明里逐条写时间码和理由:" + ";".join(t for _, t in ex["look"]))
+ sys.exit(0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/film_gate.py b/scripts/film_gate.py
new file mode 100644
index 0000000..58dbec0
--- /dev/null
+++ b/scripts/film_gate.py
@@ -0,0 +1,640 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = ["numpy", "opencv-python-headless"]
+# ///
+"""film_gate.py —— 只读成片 mp4,量「翻页式 PPT 感」。交付前由 deliver.py 调用,也可以单独跑。
+
+用法:
+ uv run film_gate.py 成片.mp4 [--json] [--vertical auto|yes|no] [--sub-band 0.15]
+ [--template 示范片.mp4] [--no-template]
+
+退出码:红灯 2;黄灯、绿灯 0;读不了文件 1。
+只依赖 ffmpeg/ffprobe 和 opencv,不依赖 art-motion 引擎,任何来源的成片都能量。
+
+门禁只有一条:快速运动帧占比(镜头内部相邻帧平均灰度差 ≥9 的帧对占比,12fps、320 宽灰度、
+屏蔽底部字幕带;像切点的帧和交叉淡化窗口整段排除,转场再快也不算)。< 0.035 红灯,< 0.06 黄灯。
+标定(2026-10-09):作者本人表过态的 13 支片(9 支认可、4 支否定),它是唯一单独就能把两组干净分开、
+阈值两侧都有余量的指标——认可的最低 0.068,否定的最高 0.021;帧差阈值在 6–13 之间取值都能分开。
+样本只有 13 支,读作「这 13 支里没有反例」,不是已经证明。
+
+其余指标只报告(最多黄灯,不拦)。静止类指标(静止帧占比、最长连续静止、最长无事件间隔)会把
+「停住→猛动→停住」的好片判反,所以绝不能拿来当门禁;黄灯只是「去看这一段」。
+
+拦不住的:每页硬塞一次快推的 PPT、前紧后松(看最差 30 秒窗口)、页框与米底小图、讲不明白。
+「去看」的黄灯项和独立审片仍然要做。
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import shutil
+import subprocess
+import sys
+
+import cv2
+import numpy as np
+
+FPS = 12 # 分析帧率
+WIDTH = 320 # 分析宽度(竖屏也是 320 宽)
+SAMPLE_FPS = 2 # 面积类指标的抽样帧率
+# 全风格样片随 Release 发布,不在仓库里;放到 assets/ 下才比「照搬示范构图」,没有就跳过这一项
+DEFAULT_TEMPLATE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets", "全风格样片.mp4")
+
+# ---------------------------------------------------------------- 阈值表
+# gate=True 的指标才会亮红灯并让脚本非零退出;其余只报告(最多黄灯,'info' 不打灯)。
+# 方向 'high_bad':值越大越可疑;'low_bad':值越小越可疑;'info':只给数,不判好坏。
+# 标定:2026-10-09 用作者本人判过的 13 支片(9 正 4 负),见文件头。阈值不要随手改:改了要用新的表态片重标。
+# 门禁只放「单个指标就能把正负例干净分开、阈值两边都有余量」的指标;目前只有 fast_ratio。
+# 黄线是从同一批片子读出来的经验线,样本太少,不能当判决,只提示「去看这一段」。
+METRICS = {
+ # key: (中文名, 方向, 黄线, 红线, 是否门禁, 单位)
+ "fast_ratio": ("快速运动帧占比", "low_bad", 0.06, 0.035, True, ""),
+ "fast_ratio_worst_window": ("最差30秒窗口的快动帧占比", "low_bad", 0.02, None, False, ""),
+ "top10_share": ("运动集中度(前10%帧占运动量)", "info", None, None, False, ""),
+ "drift_ratio": ("慢漂帧占比", "high_bad", 0.65, None, False, ""),
+ "still_ratio": ("静止帧占比(静止本身不是坏事)", "info", None, None, False, ""),
+ "longest_still_s": ("最长连续静止", "high_bad", 6.0, None, False, "秒"),
+ "event_rate": ("视觉事件密度", "low_bad", 2.0, None, False, "次/10秒"),
+ "max_event_gap_s": ("最长无事件间隔", "high_bad", 15.0, None, False, "秒"),
+ "dead_bg": ("死背景(扣相机后镜内不变)", "high_bad", 0.80, None, False, ""),
+ "dead_flat": ("死且平的空底", "high_bad", 0.50, None, False, ""),
+ "flat_area": ("平底色/空底面积", "info", None, None, False, ""),
+ "flat_light": ("浅色空底面积(米底/白底)", "high_bad", 0.35, None, False, ""),
+ "page_frame_share": ("固定页框时长占比", "high_bad", 0.30, None, False, ""),
+ "slow_zoom_share": ("匀速慢缩放镜头时长占比", "high_bad", 0.70, None, False, ""),
+ "slow_cam_share": ("慢漂相机镜头时长占比", "info", None, None, False, ""),
+ "dissolve_share": ("交叉淡化占转场比例", "high_bad", 0.60, None, False, ""),
+ "local_fade_ratio": ("原地淡变占变化帧比例", "info", None, None, False, ""),
+ "subject_box": ("最大主体块占画面", "info", None, None, False, ""),
+ "template_sim_share": ("与示范构图相似的时长占比", "high_bad", 0.30, None, False, ""),
+}
+
+
+# ---------------------------------------------------------------- 读帧
+def probe(path):
+ out = subprocess.check_output([
+ "ffprobe", "-v", "error", "-select_streams", "v:0",
+ "-show_entries", "stream=width,height:format=duration", "-of", "json", path])
+ j = json.loads(out)
+ s = j["streams"][0]
+ return int(s["width"]), int(s["height"]), float(j["format"].get("duration", 0) or 0)
+
+
+def decode_gray(path, fps=FPS, width=WIDTH, limit=None):
+ W, H, dur = probe(path)
+ h = int(round(H * width / W / 2) * 2)
+ cmd = ["ffmpeg", "-v", "error"] + (["-t", str(limit)] if limit else []) + ["-i", path, "-vf",
+ f"fps={fps},scale={width}:{h}:flags=area", "-pix_fmt", "gray", "-f", "rawvideo", "-"]
+ raw = subprocess.check_output(cmd)
+ n = len(raw) // (width * h)
+ F = np.frombuffer(raw[: n * width * h], np.uint8).reshape(n, h, width)
+ return F, (W, H, dur)
+
+
+# ---------------------------------------------------------------- 全局相机运动
+def pair_transform(a, b):
+ """a->b 的相似变换(LK 跟踪 + RANSAC)。返回 (M 2x3, 内点数, 内点率) 或 (None,0,0)。"""
+ pts = cv2.goodFeaturesToTrack(a, maxCorners=300, qualityLevel=0.01, minDistance=6, blockSize=5)
+ if pts is None or len(pts) < 15:
+ return None, 0, 0.0
+ nxt, st, _ = cv2.calcOpticalFlowPyrLK(a, b, pts, None, winSize=(21, 21), maxLevel=3)
+ ok = st.ravel() == 1
+ if ok.sum() < 12:
+ return None, 0, 0.0
+ p0, p1 = pts[ok].reshape(-1, 2), nxt[ok].reshape(-1, 2)
+ M, inl = cv2.estimateAffinePartial2D(p0, p1, method=cv2.RANSAC, ransacReprojThreshold=1.0)
+ if M is None:
+ return None, 0, 0.0
+ ni = int(inl.sum())
+ return M, ni, ni / len(pts)
+
+
+def cam_speed(M, w, h, fps):
+ """变换在一组网格点上的平均位移,换算成「屏宽/秒」。"""
+ if M is None:
+ return 0.0
+ xs, ys = np.meshgrid(np.linspace(0, w, 7), np.linspace(0, h, 7))
+ P = np.stack([xs.ravel(), ys.ravel(), np.ones(xs.size)], 1)
+ Q = P @ M.T
+ return float(np.hypot(*(Q - P[:, :2]).T).mean() / w * fps)
+
+
+def to3(M):
+ return np.vstack([M, [0, 0, 1]]) if M is not None else np.eye(3)
+
+
+# ---------------------------------------------------------------- 主分析
+def analyze(path, sub_band=None, vertical="auto", template=None, verbose=False):
+ F, (W0, H0, dur) = decode_gray(path)
+ is_vert = (H0 > W0) if vertical == "auto" else (vertical == "yes")
+ if sub_band is None:
+ sub_band = 0.18 if is_vert else 0.15
+ n, h, w = F.shape
+ hc = int(round(h * (1 - sub_band)))
+ F = np.ascontiguousarray(F[:, :hc]) # 屏蔽底部字幕带
+ h = hc
+ if n < 4:
+ raise RuntimeError("帧太少,无法分析")
+ F16 = F.astype(np.int16)
+
+ # --- 逐帧对:帧差、相机变换、补偿后残差、亮度直方图
+ d = np.zeros(n - 1); loc = np.zeros(n - 1); spd = np.zeros(n - 1); zr = np.zeros(n - 1)
+ fade_px = np.zeros(n - 1)
+ Ms = []
+ for i in range(n - 1):
+ a, b = F[i], F[i + 1]
+ diff = np.abs(F16[i + 1] - F16[i])
+ d[i] = diff.mean()
+ moved, wa = False, None
+ if d[i] < 0.05: # 完全一样:省掉估计
+ Ms.append(None); loc[i] = d[i]; fade_px[i] = -1; continue
+ M, ni, ir = pair_transform(a, b)
+ if M is not None and ni >= 20 and ir >= 0.35:
+ s = float(np.hypot(M[0, 0], M[1, 0]))
+ moved = abs(np.log(s)) > 1e-4 or abs(M[0, 2]) > 0.05 or abs(M[1, 2]) > 0.05
+ if moved:
+ wa = cv2.warpAffine(a, M, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
+ loc[i] = np.abs(F16[i + 1] - wa.astype(np.int16)).mean()
+ else:
+ loc[i] = d[i]
+ spd[i] = cam_speed(M, w, h, FPS)
+ zr[i] = np.log(s)
+ Ms.append(M)
+ else:
+ loc[i] = d[i]; Ms.append(None)
+ # 原地淡变:补偿相机后仍在变的像素里,光流几乎为 0(位置不动、只变亮度)的比例
+ if d[i] > 0.3 and spd[i] < 0.05:
+ base = wa if (Ms[-1] is not None and moved) else a
+ ch = np.abs(F16[i + 1] - base.astype(np.int16)) > 10
+ if ch.mean() > 0.003:
+ fl = cv2.calcOpticalFlowFarneback(base, b, None, 0.5, 3, 15, 3, 5, 1.2, 0)
+ mag = np.hypot(fl[..., 0], fl[..., 1])
+ fade_px[i] = float((mag[ch] < 0.5).mean())
+ else:
+ fade_px[i] = -1
+ else:
+ fade_px[i] = -1
+ # --- 硬切
+ # cut_like:所有「整帧突变、且不能用相机运动解释」的帧(含多帧的瓦片/像素/甩切转场)——统计运动时全部排除
+ # cut:连续的 cut_like 只取第一帧,用来数切点、分镜头
+ cut_like = np.zeros(n - 1, bool)
+ for i in range(n - 1):
+ lo, hi = max(0, i - 6), min(n - 1, i + 7)
+ nb = np.concatenate([d[lo:i], d[i + 1:hi]])
+ med = np.median(nb) if len(nb) else 0
+ cut_like[i] = d[i] >= max(8.0, 3 * med + 2) and loc[i] >= 0.6 * d[i]
+ cut = cut_like & ~np.concatenate([[False], cut_like[:-1]])
+
+ # --- 交叉淡化:端点差异大、中间每帧变化都温和、中间帧是两端的线性混合
+ diss = [] # (a, b, center)
+ in_diss = np.zeros(n - 1, bool)
+ cand = []
+ for wdw in (2, 3, 5, 8, 12): # 半窗 0.17s–1s
+ for t in range(wdw, n - wdw):
+ a_, b_ = t - wdw, t + wdw
+ if cut_like[a_:b_].any():
+ continue
+ seg = d[a_:b_]
+ if seg.max() > 0.75 * seg.sum() or seg.sum() < 10:
+ continue
+ Dab = np.abs(F16[b_] - F16[a_])
+ if Dab.mean() < 10 or (Dab > 20).mean() < 0.20: # 整帧级淡化;标题局部淡变一般只占几个百分点
+ continue
+ cand.append((t, wdw))
+ cand_set = {}
+ for t, wdw in cand:
+ a_, b_ = t - wdw, t + wdw
+ A = F16[a_].astype(np.float32); B = F16[b_].astype(np.float32)
+ D = A - B; nd = float((D * D).sum()) + 1e-6
+ res, alphas = [], []
+ for k in range(a_ + 1, b_):
+ X = F16[k].astype(np.float32) - B
+ al = float((X * D).sum() / nd)
+ r = np.abs(X - al * D).mean() / (np.abs(D).mean() + 1e-6)
+ res.append(r); alphas.append(al)
+ res = np.array(res); alphas = np.array(alphas)
+ mono = np.all(np.diff(alphas) <= 0.08)
+ mid = (alphas > 0.15) & (alphas < 0.85) # 真正「两张叠在一起」的中间帧
+ if (mid.sum() >= 2 and res[mid].mean() < 0.22 and res.mean() < 0.25 and mono
+ and alphas[0] > 0.55 and alphas[-1] < 0.45):
+ ks = np.arange(a_ + 1, b_)
+ tc = int(ks[np.argmin(np.abs(alphas - 0.5))]) # 混合系数过 0.5 的那一帧
+ cand_set[(t, wdw)] = (a_, b_, res.mean(), float(np.abs(D).mean()), tc)
+ # 合并重叠:先取端点差最大的(整段淡化都在窗里),再看残差
+ for key in sorted(cand_set, key=lambda k: (-round(cand_set[k][3], 0), cand_set[k][2])):
+ a_, b_, _, _, tc = cand_set[key]
+ if in_diss[a_:b_].any():
+ continue
+ in_diss[a_:b_] = True
+ diss.append((a_, b_, tc))
+ diss.sort()
+
+ # --- 镜头
+ bounds = sorted(set([0] + [i + 1 for i in np.where(cut)[0]] + [c for _, _, c in diss] + [n]))
+ shots = []
+ for s, e in zip(bounds[:-1], bounds[1:]):
+ if e - s >= 3:
+ shots.append((s, e))
+ elif shots:
+ shots[-1] = (shots[-1][0], e)
+ if not shots:
+ shots = [(0, n)]
+ trans = cut_like | in_diss
+ n_cut, n_diss = int(cut.sum()), len(diss)
+
+ # --- 运动分布(排除转场帧)
+ mv = np.where(trans, np.nan, d)
+ good = ~np.isnan(mv)
+ mvv = mv[good]
+ # 帧差口径:12fps、320 宽灰度、屏蔽字幕带后的平均绝对差(0–255)。
+ # 快动阈值 9 由标定得出(6–11 之间都能分开正负例,9 余量最大);
+ # LK 相机速度会漏掉 0.3 秒级快推,标定里单用它分不开,所以不进「快动」定义。
+ STILL, DRIFT_HI, FAST = 0.30, 3.0, 9.0
+ still = mvv < STILL
+ fast = mvv >= FAST
+ drift = (~still) & (~fast) & (mvv < DRIFT_HI)
+ srt = np.sort(mvv)[::-1]
+ top10 = srt[: max(1, len(srt) // 10)].sum() / max(srt.sum(), 1e-6)
+
+ # 最长连续静止(全片帧序列,转场打断)
+ st_full = (d < STILL) & ~trans
+ longest = run = longest_at = 0
+ for i, v in enumerate(st_full):
+ run = run + 1 if v else 0
+ if run > longest:
+ longest, longest_at = run, i - run + 1
+
+ # 事件:硬切、淡化、快速运动段(连续的快帧算一次)
+ fast_full = np.zeros(n - 1, bool)
+ fast_full[good] = fast
+ ev_t = [i for i in np.where(cut)[0]] + [c for _, _, c in diss]
+ prev = False
+ for i, v in enumerate(fast_full):
+ if v and not prev:
+ ev_t.append(i)
+ prev = v
+ ev_t = sorted(ev_t)
+ secs = n / FPS
+ gaps = np.diff([0] + ev_t + [n - 1]) / FPS
+ # 合并 0.3s 内重复的事件
+ ev_m = []
+ for t in ev_t:
+ if not ev_m or t - ev_m[-1] > 0.3 * FPS:
+ ev_m.append(t)
+ event_rate = len(ev_m) / secs * 10
+
+ # --- 每镜:死背景、慢缩放曲线
+ dead_w, dead_flat_w, shot_w = [], [], []
+ slow_zoom_dur, zoom_totals, slow_cam_dur = 0.0, [], 0.0
+ for s, e in shots:
+ L = e - s
+ dur_s = L / FPS
+ # 累积变换:A_k 把镜头首帧坐标映到第 k 帧
+ A = [np.eye(3)]
+ zc = [0.0]
+ for k in range(s, e - 1):
+ A.append(to3(Ms[k]) @ A[-1])
+ zc.append(zc[-1] + (zr[k] if Ms[k] is not None else 0.0))
+ zc = np.array(zc)
+ # 慢缩放:总缩放 2%–25%,单调铺满大半个镜头,且没有快推
+ if dur_s >= 1.2:
+ rates = np.abs(zr[s:e - 1]) * FPS
+ tot = abs(zc[-1] - zc[0])
+ active = (rates > 0.004).mean()
+ sgn = np.sign(zr[s:e - 1]); sgn = sgn[sgn != 0]
+ mono = abs(sgn.mean()) if len(sgn) else 0
+ if 0.02 <= tot <= 0.25 and active >= 0.6 and mono >= 0.7 and np.percentile(rates, 95) < 0.25:
+ slow_zoom_dur += dur_s
+ zoom_totals.append(tot / dur_s)
+ sp_ = spd[s:e - 1]
+ if (sp_ > 0.004).mean() >= 0.6 and np.percentile(sp_, 95) < 0.2:
+ slow_cam_dur += dur_s
+ if dur_s < 0.6:
+ continue
+ idx = np.unique(np.linspace(s, e - 1, min(L, 24)).astype(int))
+ r = idx[len(idx) // 2]
+ Ar = A[r - s]
+ stack, valid = [], []
+ ones = np.full((h, w), 255, np.uint8)
+ for k in idx:
+ T = (Ar @ np.linalg.inv(A[k - s]))[:2]
+ stack.append(cv2.warpAffine(F[k], T, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT))
+ valid.append(cv2.warpAffine(ones, T, (w, h), flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT) > 0)
+ stack = np.array(stack, np.int16); valid = np.array(valid)
+ vcount = valid.sum(0)
+ ok = vcount >= 0.8 * len(idx)
+ big = np.where(valid, stack, -1000).max(0); small = np.where(valid, stack, 1000).min(0)
+ rng = big - small
+ dead = ok & (rng <= 12)
+ ref = F[r]
+ gx = cv2.Sobel(ref, cv2.CV_32F, 1, 0); gy = cv2.Sobel(ref, cv2.CV_32F, 0, 1)
+ flatpx = cv2.blur(np.hypot(gx, gy), (9, 9)) < FLAT_GRAD
+ denom = max(ok.sum(), 1)
+ dead_w.append(dead.sum() / denom); dead_flat_w.append((dead & flatpx).sum() / denom); shot_w.append(dur_s)
+ shot_w = np.array(shot_w)
+ dead_bg = float(np.average(dead_w, weights=shot_w)) if len(shot_w) else 0.0
+ dead_flat = float(np.average(dead_flat_w, weights=shot_w)) if len(shot_w) else 0.0
+ slow_zoom_share = slow_zoom_dur / secs
+ zoom_cv = float(np.std(zoom_totals) / (np.mean(zoom_totals) + 1e-9)) if len(zoom_totals) >= 3 else float("nan")
+
+ # --- 抽样帧上的面积类指标
+ step = max(1, FPS // SAMPLE_FPS)
+ sidx = np.arange(0, n, step)
+ if len(sidx) > 240:
+ sidx = np.unique(np.linspace(0, n - 1, 240).astype(int))
+ S = F[sidx]
+ flat_area, flat_light, subj = [], [], []
+ BS = 8
+ gh, gw = h // BS, w // BS
+ cell_tex = np.zeros((len(sidx), gh, gw), bool)
+ for j, fr in enumerate(S):
+ gx = cv2.Sobel(fr, cv2.CV_32F, 1, 0); gy = cv2.Sobel(fr, cv2.CV_32F, 0, 1)
+ g = np.hypot(gx, gy)[: gh * BS, : gw * BS].reshape(gh, BS, gw, BS).mean((1, 3))
+ lum = fr[: gh * BS, : gw * BS].reshape(gh, BS, gw, BS).mean((1, 3))
+ flat = (g < FLAT_GRAD).astype(np.uint8)
+ nl, lab, stats, _ = cv2.connectedComponentsWithStats(flat, connectivity=4)
+ big = np.zeros_like(flat, bool)
+ for c in range(1, nl):
+ if stats[c, cv2.CC_STAT_AREA] >= 0.03 * gh * gw:
+ big |= lab == c
+ flat_area.append(big.mean()); flat_light.append((big & (lum > 150)).mean())
+ cell_tex[j] = g >= PAGE_GRAD
+ tex = (g >= TEX_GRAD).astype(np.uint8)
+ if tex.sum() == 0:
+ subj.append(0.0); continue
+ cl = cv2.morphologyEx(tex, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
+ nl, lab, stats, _ = cv2.connectedComponentsWithStats(cl, connectivity=8)
+ k = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
+ comp = (lab == k).astype(np.uint8)
+ cs, _ = cv2.findContours(comp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
+ fill = np.zeros_like(comp); cv2.drawContours(fill, cs, -1, 1, -1)
+ subj.append(float(fill.mean()))
+ flat_area = np.array(flat_area)
+
+ # --- 固定页框:同一屏幕位置、有纹理(字/线/logo)、在画面其余部分已经大变的时刻仍原样出现
+ page_share = page_frame(S, sidx, cell_tex, BS, gh, gw, shots)
+
+ # --- 与示范构图相似
+ tsim_share, tsim_max = float("nan"), float("nan")
+ if template:
+ tsim_share, tsim_max = template_similarity(F, shots, template)
+
+ # --- 原地淡入淡出占比:变化帧里局部结构符号一致(只变亮度不位移)的平均比例
+ chg = (~trans) & (fade_px >= 0)
+ lf = float(np.mean(fade_px[chg] > 0.7)) if chg.sum() > 5 else 0.0
+
+ # 前紧后松:最差的 30 秒窗口(片长不足 60 秒时取片长一半)里的快动帧占比
+ win = int(min(30.0, secs / 2) * FPS)
+ fr_full = np.where(trans, np.nan, fast_full.astype(float))
+ worst, worst_t = float("nan"), None
+ if win >= FPS * 4:
+ for st0 in range(0, n - 1 - win + 1, FPS):
+ seg = fr_full[st0: st0 + win]
+ v = np.nanmean(seg) if np.isfinite(seg).any() else 0.0
+ if not (worst == worst) or v < worst:
+ worst, worst_t = float(v), st0 / FPS
+ by10 = [round(float(np.nanmean(fr_full[k: k + 10 * FPS])), 3) if np.isfinite(fr_full[k: k + 10 * FPS]).any() else 0.0
+ for k in range(0, n - 1, 10 * FPS)]
+ if os.environ.get("FILM_GATE_DUMP"):
+ np.savez_compressed(os.environ["FILM_GATE_DUMP"], d=d, spd=spd, loc=loc, zr=zr, cut=cut, in_diss=in_diss, fade_px=fade_px)
+
+ shot_len = np.array([(e - s) / FPS for s, e in shots])
+ res = {
+ "file": os.path.basename(path),
+ "orientation": "vertical" if is_vert else "horizontal",
+ "duration_s": round(secs, 2),
+ "sub_band": sub_band,
+ "shots": len(shots), "hard_cuts": n_cut, "dissolves": n_diss,
+ "asl_s": round(float(shot_len.mean()), 2),
+ "dissolve_share": round(n_diss / max(1, n_cut + n_diss), 3),
+ "fast_ratio": round(float(fast.mean()), 4),
+ "top10_share": round(float(top10), 3),
+ "drift_ratio": round(float(drift.mean()), 3),
+ "still_ratio": round(float(still.mean()), 3),
+ "longest_still_s": round(longest / FPS, 2),
+ "longest_still_start_s": round(longest_at / FPS, 2),
+ "event_rate": round(event_rate, 2),
+ "max_event_gap_s": round(float(gaps.max()), 2),
+ "dead_bg": round(dead_bg, 3),
+ "dead_flat": round(dead_flat, 3),
+ "flat_area": round(float(flat_area.mean()), 3),
+ "flat40_frames": round(float((flat_area > 0.4).mean()), 3),
+ "page_frame_share": round(page_share, 3),
+ "slow_zoom_share": round(float(slow_zoom_share), 3),
+ "slow_cam_share": round(float(slow_cam_dur / secs), 3),
+ "zoom_curve_cv": round(zoom_cv, 3) if zoom_cv == zoom_cv else None,
+ "subject_box": round(float(np.median(subj)), 3),
+ "flat_light": round(float(np.mean(flat_light)), 3),
+ "template_sim_share": round(tsim_share, 3) if tsim_share == tsim_share else None,
+ "template_sim_max": round(tsim_max, 3) if tsim_max == tsim_max else None,
+ "local_fade_ratio": round(lf, 3),
+ "mean_diff": round(float(np.nanmean(mv)), 2),
+ "fast_ratio_worst_window": round(worst, 4) if worst == worst else None,
+ "worst_window_start_s": worst_t,
+ "worst_window_len_s": round(win / FPS, 2),
+ "fast_ratio_by_10s": by10,
+ "cut_times_s": [round((i + 1) / FPS, 2) for i in np.where(cut)[0]],
+ "dissolve_times_s": [round(c / FPS, 2) for _, _, c in diss],
+ }
+ return res
+
+
+FLAT_GRAD = 6.0 # 8x8 块平均梯度低于它算「平」(320 宽灰度)
+TEX_GRAD = 14.0 # 高于它算「有纹理」
+PAGE_GRAD = 25.0 # 页框格子要求的纹理(字、细线、logo 的强边)
+
+
+def page_frame(S, sidx, cell_tex, BS, gh, gw, shots):
+ """固定页框时长占比。
+ 一个格子在某帧「复现」= 强纹理,且在 ≥3 个相隔 ≥3 秒、整体画面已明显不同的帧里同位原样出现。
+ 全片里复现率 ≥25% 的格子算「页框格」(标题栏、页眉、页码、logo、进度条);
+ 某帧里页框格(且当帧复现)合计 ≥ 画面 1.5%,这一帧算被页框框住。
+ 只复用同一段素材、同一张底纹的镜头,复现是零散的,过不了 25% 这一关。"""
+ N = len(S)
+ if N < 6:
+ return 0.0
+ desc = np.array([cv2.resize(fr[: gh * BS, : gw * BS], (gw * 4, gh * 4), interpolation=cv2.INTER_AREA)
+ for fr in S]).astype(np.float32)
+ desc = desc.reshape(N, gh, 4, gw, 4).transpose(0, 1, 3, 2, 4).reshape(N, gh, gw, 16)
+ small = np.array([cv2.resize(fr, (32, 18), interpolation=cv2.INTER_AREA) for fr in S]).astype(np.float32)
+ t = sidx / FPS
+ G = np.abs(small[:, None] - small[None]).mean((2, 3))
+ far = (np.abs(t[:, None] - t[None]) >= 3.0) & (G > 12)
+ persist = np.zeros((N, gh, gw), bool)
+ for y in range(gh):
+ for x in range(gw):
+ tex = cell_tex[:, y, x]
+ if tex.sum() < 3:
+ continue
+ v = desc[:, y, x]
+ Dm = np.abs(v[:, None] - v[None]).mean(2)
+ persist[:, y, x] = ((Dm < 6.0) & far & tex[:, None] & tex[None]).sum(1) >= 3
+ chrome = persist.mean(0) >= 0.25
+ framed = (persist & chrome).sum((1, 2)) / (gh * gw) >= 0.015
+ return float(framed.mean())
+
+
+def layout_desc(fr):
+ e = cv2.Canny(fr, 60, 160).astype(np.float32)
+ g = cv2.resize(e, (12, 8), interpolation=cv2.INTER_AREA).ravel()
+ t = cv2.resize(fr, (12, 8), interpolation=cv2.INTER_AREA).astype(np.float32).ravel()
+ g = (g - g.mean()) / (g.std() + 1e-6); t = (t - t.mean()) / (t.std() + 1e-6)
+ return np.concatenate([g, t]) / np.sqrt(2 * g.size)
+
+
+_TPL_CACHE = {}
+
+
+def template_similarity(F, shots, template):
+ if template not in _TPL_CACHE:
+ T, _ = decode_gray(template, fps=2, limit=12)
+ T = T[:24] # 前 12 秒
+ T = T[:, : int(T.shape[1] * 0.85)]
+ _TPL_CACHE[template] = np.array([layout_desc(x) for x in T])
+ TD = _TPL_CACHE[template]
+ sims, durs = [], []
+ for s, e in shots:
+ k = (s + e) // 2
+ v = layout_desc(F[k])
+ sims.append(float((TD @ v).max())); durs.append(e - s)
+ sims, durs = np.array(sims), np.array(durs, float)
+ return float(durs[sims >= 0.70].sum() / durs.sum()), float(sims.max())
+
+
+# ---------------------------------------------------------------- 打灯
+def grade(res):
+ rows, red = [], False
+ for k, (name, direc, y, r, gate, unit) in METRICS.items():
+ v = res.get(k)
+ if v is None or direc == "info":
+ rows.append((k, name, v, "--", gate, unit)); continue
+ bad = (lambda t: v >= t) if direc == "high_bad" else (lambda t: v <= t)
+ lv = "red" if (gate and r is not None and bad(r)) else "yellow" if (y is not None and bad(y)) else "green"
+ red |= lv == "red"
+ rows.append((k, name, v, lv, gate, unit))
+ return rows, red
+
+
+# ---------------------------------------------------------------- 读给人听
+FIX = ("按 SKILL.md 窄桥第一条「动在事件上」改:每个镜头在口播节点上做「停住 → 快推 / 横移 / 砸入 → 停住」——"
+ "快推 0.28 秒推近 18–32%、同倍率横移 0.30 秒、砸入 0.17 秒,用 CAM.track 写镜头动作表(MO.slam 砸入);"
+ "有截图、照片、录像就用 MD.cover 满幅铺开,念到哪一处就把焦点推近到哪一处。"
+ "匀速慢推、淡入淡出、转场都不算数(转场再快也被排除在外)。"
+ "别为了过门每页硬塞一次快推:门禁只拦「整片没有猛动作」这一种 PPT,页框、米底小图、前紧后松它拦不住。")
+
+# 只报告的黄灯项:一句「去看哪里」
+LOOK = {
+ "fast_ratio_worst_window": lambda r: f"{r['worst_window_start_s']:.0f}–{r['worst_window_start_s'] + r['worst_window_len_s']:.0f}s 这段几乎没有快动作(前紧后松)",
+ "drift_ratio": lambda r: f"{r['drift_ratio']:.0%} 的帧在缓慢漂移",
+ "longest_still_s": lambda r: f"从 {r['longest_still_start_s']:.1f}s 起连续 {r['longest_still_s']:.1f}s 一动不动",
+ "event_rate": lambda r: f"平均每 10 秒只有 {r['event_rate']:.1f} 个视觉事件",
+ "max_event_gap_s": lambda r: f"最长 {r['max_event_gap_s']:.1f}s 没有任何切换或快动作",
+ "dead_bg": lambda r: f"扣掉相机运动后,平均 {r['dead_bg']:.0%} 的画面在镜头里一直不变",
+ "dead_flat": lambda r: f"{r['dead_flat']:.0%} 的画面是一直不变的空底",
+ "flat_light": lambda r: f"米底/白底空着的面积平均占 {r['flat_light']:.0%}(白板等浅底风格可以如此,确认是风格不是空着)",
+ "page_frame_share": lambda r: f"{r['page_frame_share']:.0%} 的时长被固定的页眉、页码、标题栏、logo 框着",
+ "slow_zoom_share": lambda r: f"{r['slow_zoom_share']:.0%} 的时长是匀速慢推/慢拉镜头",
+ "dissolve_share": lambda r: f"转场里 {r['dissolve_share']:.0%} 是交叉淡化",
+ "template_sim_share": lambda r: f"{r['template_sim_share']:.0%} 的时长和示范片构图几乎一样",
+}
+
+
+def explain(res):
+ """一句话结论+为什么+怎么改+黄灯项去看哪里。只用 res 里量出来的数。"""
+ fr, lv = res["fast_ratio"], res["lights"]["fast_ratio"]
+ if lv == "red":
+ head = ("整片没有一次镜头内的快速动作,读起来像翻页" if fr < 0.005 else
+ f"整片只有 {fr:.1%} 的帧在镜头内快速运动(红线 3.5%),读起来像翻页")
+ elif lv == "yellow":
+ head = f"镜头内的快速动作偏少({fr:.1%},黄线 6%),离翻页感不远"
+ else:
+ head = f"镜头内有足够的快速动作({fr:.1%})"
+ why = []
+ if lv != "green":
+ if res["slow_zoom_share"] >= 0.3:
+ why.append(f"{res['slow_zoom_share']:.0%} 的时长在匀速慢推/慢拉")
+ if res["still_ratio"] >= 0.5:
+ why.append(f"{res['still_ratio']:.0%} 的帧完全停着")
+ elif res["drift_ratio"] >= 0.4:
+ why.append(f"{res['drift_ratio']:.0%} 的帧只是在缓慢漂移")
+ if res["hard_cuts"] + res["dissolves"]:
+ why.append(f"画面变化主要靠转场(硬切 {res['hard_cuts']}、淡化 {res['dissolves']}),转场不算镜头内动作")
+ look = [(k, LOOK[k](res)) for k, l in res["lights"].items() if l == "yellow" and k in LOOK]
+ ww = None
+ if res.get("worst_window_start_s") is not None:
+ a = res["worst_window_start_s"]
+ ww = {"start_s": a, "end_s": round(a + res["worst_window_len_s"], 2), "fast_ratio": res["fast_ratio_worst_window"]}
+ return {"summary": head, "why": why, "fix": FIX if lv != "green" else None, "look": look, "worst_window": ww}
+
+
+def measure(path, sub_band=None, vertical="auto", template=DEFAULT_TEMPLATE):
+ """量一支成片,返回带 lights / gate_light / verdict / explain 的结果。deliver.py 也调它。"""
+ tpl = template if template and os.path.exists(template) else None
+ cv2.setNumThreads(max(1, (os.cpu_count() or 2) // 2))
+ res = analyze(path, sub_band=sub_band, vertical=vertical, template=tpl)
+ rows, red = grade(res)
+ res["lights"] = {k: lv for k, _, _, lv, _, _ in rows}
+ res["gate_metrics"] = [k for k, _, _, _, gate, _ in rows if gate]
+ res["gate_light"] = res["lights"]["fast_ratio"]
+ res["verdict"] = "red" if red else "pass"
+ res["explain"] = explain(res)
+ return res, rows
+
+
+LIGHT = {"red": "[红]", "yellow": "[黄]", "green": "[绿]", "--": "[ ]"}
+
+
+def report_lines(res, rows):
+ """文字报告(终端和交付说明共用)。"""
+ L = [f"{res['file']} {res['orientation']} {res['duration_s']}s "
+ f"镜头 {res['shots']}(硬切 {res['hard_cuts']},淡化 {res['dissolves']}) 平均镜长 {res['asl_s']}s"]
+ for k, name, v, lv, gate, unit in rows:
+ vs = "—" if v is None else (f"{v:.3f}" if isinstance(v, float) else str(v))
+ L.append(f" {LIGHT[lv]} {'门禁' if gate else '报告'} {name}:{vs}{unit}")
+ ex = res["explain"]
+ if ex["worst_window"]:
+ w = ex["worst_window"]
+ L.append(f" 最差 {w['end_s'] - w['start_s']:.0f} 秒窗口:{w['start_s']:.0f}–{w['end_s']:.0f}s,快动帧占比 {w['fast_ratio']};"
+ f"每 10 秒快动帧占比:{res['fast_ratio_by_10s']}")
+ return L
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("mp4")
+ ap.add_argument("--json", action="store_true")
+ ap.add_argument("--vertical", default="auto", choices=["auto", "yes", "no"],
+ help="横竖屏;auto 按宽高判断。只影响字幕带默认值")
+ ap.add_argument("--sub-band", type=float, default=None,
+ help="屏蔽底部字幕带的比例;默认横屏 0.15、竖屏 0.18;0 表示不屏蔽")
+ ap.add_argument("--template", default=DEFAULT_TEMPLATE, help="示范片(取前 12 秒比构图)")
+ ap.add_argument("--no-template", action="store_true")
+ a = ap.parse_args()
+ if not shutil.which("ffmpeg") or not shutil.which("ffprobe"):
+ print("需要 ffmpeg/ffprobe", file=sys.stderr); sys.exit(1)
+ try:
+ res, rows = measure(a.mp4, sub_band=a.sub_band, vertical=a.vertical, template=None if a.no_template else a.template)
+ except (subprocess.CalledProcessError, KeyError, IndexError, RuntimeError, ValueError) as e:
+ print(f"读不了这支片:{a.mp4}({e})", file=sys.stderr); sys.exit(1)
+ red = res["verdict"] == "red"
+ if a.json:
+ print(json.dumps(res, ensure_ascii=False, indent=1))
+ else:
+ print("\n".join(report_lines(res, rows)))
+ ex = res["explain"]
+ tag = {"red": "红灯,不出片", "yellow": "黄灯,可以交付但要人看", "green": "门禁通过"}[res["gate_light"]]
+ print(f"结论:{tag}——{ex['summary']}。" + ("".join(f"{w};" for w in ex["why"]).rstrip(";") + "。" if ex["why"] else ""))
+ if ex["fix"]:
+ print("怎么改:" + ex["fix"])
+ if ex["look"]:
+ print("黄灯项(只报告,不拦;去看这一段,交付说明里逐条说清为什么可以这样):")
+ for _, t in ex["look"]:
+ print(" - " + t)
+ if not red:
+ print("提醒:门禁只拦「整片几乎没有快动作」这一种 PPT;独立审片仍然要做。")
+ sys.exit(2 if red else 0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/qa.py b/scripts/qa.py
index 927daaa..72a2cb3 100644
--- a/scripts/qa.py
+++ b/scripts/qa.py
@@ -6,6 +6,7 @@
uv run qa.py --project <代码工程目录> [--film gallery] [--ids 01_cave,09_postimp] [--fps 30] [--out <目录>]
uv run qa.py --spec <片段 clip.json> [--out <目录>] # 参数化片段(口播管线的动画段):整段当一段量,竖屏也行;不量转场
+ # 素材字段和 render.py 同一套(engine/spec_assets.py):image、frames、data.image、data.character
逐段(eras.js 的每个 id)做四件事:
1. 稳定:场景加载失败直接退出(引擎 __bootErrors);同一时刻冷渲+热渲两次逐像素比对(确定性)。
@@ -13,6 +14,10 @@
3. 动感:避开转场后 0.35s 镜头冲击,在本段静止区按 --fps 连续取帧,报运动面积(相邻帧变化 >12 的像素占比)均值,
和「静止帧对」比例(相邻帧几乎不变 <0.05% —— 迁移测试 A 发现只看首尾差会漏掉一卡一卡)。
4. 流畅:相邻帧差的峰值 / 中位数。>6 且峰值 >3% 记为「跳变」(整屏笔触按 8fps 重洗、某帧穿帮、闪烁都会冒出来)。
+ 脉冲镜头(快推 0.28s、横移 0.30s、砸入 0.17s)不算跳变,单独记为「镜头事件」:从跳变帧往两边扩到帧差回落,
+ 这一串至少 2 对帧、不长于 0.35s(+1 帧),且最后一帧离第一帧最远(推过去就停在那,不是闪一下又回来)。
+ 孤立的一两帧(穿帮、闪白、整屏重洗)、闪过去又回来的、连续拖得更长的,照旧记跳变。只看像素,不读相机动作表,
+ 所以手写的快推和 CAM.track 一样认;代价是 0.35s 内的单调大变化(比如一下子整屏换成另一张图又刚好接着推)也会被当成镜头事件。
另做「转场冒烟」:每个带转场的段在 p=.25/.5/.75 渲整帧(renderFrame),报错计入页面报错——段内取帧用 renderSolo,
转场代码一次都不会执行,转场崩了也能全绿(全风格样片移植时踩到)。
判据是经验阈值不是规则:运动 0.5–8% 之间多数段好看;静止帧对 >40% 读作卡;跳变 >0 先看帧再判断(有意的节拍闪不算错)。
@@ -29,8 +34,10 @@
产物:<out>/qa.json(全部数字)、<out>/qa.md(表)、<out>/<id>.jpg(4 帧拼图+运动热图)。
"""
-import argparse, base64, functools, http.server, io, json, socketserver, threading, urllib.parse
+import argparse, base64, functools, http.server, io, json, socketserver, sys, threading, urllib.parse
from pathlib import Path
+sys.path.insert(0, str(Path(__file__).resolve().parent / 'engine'))
+import spec_assets
import numpy as np
from PIL import Image, ImageDraw
from playwright.sync_api import sync_playwright
@@ -42,16 +49,10 @@ ap.add_argument('--sub-band', type=float, default=None, help='字幕带上沿(
a = ap.parse_args()
if not (a.project or a.spec): ap.error('--project 或 --spec 二选一')
spec, ALLOWED = None, set()
-if a.spec: # 和 render.py 同一套:本地图片只服务 spec 里点名的文件
+if a.spec: # 和 render.py 同一套:本地素材(image / frames / 角色帧库)只服务 spec 里点名的文件
sp = Path(a.spec).resolve(); spec = json.loads(sp.read_text())
- def ref(v):
- if not v or v.startswith(('data:', 'http:', 'https:')): return v
- f = (sp.parent / v).resolve()
- if not f.exists(): raise SystemExit(f'spec 里的图片不存在:{v}')
- ALLOWED.add(str(f)); return '/__file__/' + urllib.parse.quote(str(f))
- for q in spec.get('cues', []):
- if q.get('image'): q['image'] = ref(q['image'])
- if (spec.get('data') or {}).get('image'): spec['data']['image'] = ref(spec['data']['image'])
+ try: spec_assets.localize(spec, sp.parent, ALLOWED)
+ except FileNotFoundError as e: raise SystemExit(str(e))
root = Path(a.project).resolve() if a.project else Path(__file__).resolve().parent / 'engine'
out = Path(a.out) if a.out else (Path(a.spec).resolve().parent / 'qa' if a.spec else root.parent / 'qa'); out.mkdir(parents=True, exist_ok=True)
VW, VH = (spec.get('width', 1920), spec.get('height', 1080)) if spec else (1920, 1080)
@@ -206,7 +207,21 @@ def near_blank(f):
return float((np.abs(f - med).max(axis=2) > 24).mean()) < 0.003
def img(b64, w=480): return np.asarray(Image.open(io.BytesIO(base64.b64decode(b64))).convert('RGB').resize((w, round(w * VH / VW)))).astype(np.int16) # 按画幅缩,竖屏不压扁
-report = {'project': str(root), 'segments': []}
+def camera_events(frames, diffs, idx, fps, max_s=0.35):
+ """把跳变里的脉冲镜头挑出来(判据见文件头第 4 条)。idx:跳变所在的帧对下标。返回 (还算跳变的下标, 镜头事件 [(l, r)])。"""
+ keep, events = [], []
+ for i in idx:
+ if any(l <= i <= r for l, r in events): continue
+ thr = max(0.5, 0.1 * diffs[i]); l = r = i
+ while l > 0 and diffs[l - 1] > thr: l -= 1
+ while r < len(diffs) - 1 and diffs[r + 1] > thr: r += 1
+ n = r - l + 1
+ far = [float(np.abs(frames[k] - frames[l]).mean()) for k in range(l + 1, r + 2)] # 这一串里每一帧离第一帧多远
+ if 2 <= n <= max_s * fps + 1 and far[-1] >= 0.8 * max(far): events.append((l, r))
+ else: keep.append(i)
+ return [i for i in keep if not any(l <= i <= r for l, r in events)], events
+
+report = {'project': str(root), 'spec': str(Path(a.spec).resolve()) if a.spec else None, 'segments': []}
errors = []
with sync_playwright() as p:
br = p.chromium.launch(args=['--enable-gpu-rasterization', '--ignore-gpu-blocklist'])
@@ -242,16 +257,19 @@ with sync_playwright() as p:
med = float(np.median(diffs)) if len(diffs) else 0
if spec: # 片段多是「动一下、定住」:全段中位数≈0,连续的推镜/滑入会整串被记成跳变。片段只认孤立的跳:比前后各 3 对的中位数大 6 倍
loc = lambda i: float(np.median(np.r_[diffs[max(0, i - 3):i], diffs[i + 1:i + 4]])) if len(diffs) > 1 else 0
- spikes = [round(ts[i + 1], 3) for i, d in enumerate(diffs) if d > 3 and d > 6 * max(loc(i), 0.05)]
+ sidx = [i for i, d in enumerate(diffs) if d > 3 and d > 6 * max(loc(i), 0.05)]
else:
- spikes = [round(ts[i + 1], 3) for i, d in enumerate(diffs) if d > 3 and d > 6 * max(med, 0.05)]
+ sidx = [i for i, d in enumerate(diffs) if d > 3 and d > 6 * max(med, 0.05)]
+ sidx, cams = camera_events(frames, diffs, sidx, a.fps)
+ spikes = [round(ts[i + 1], 3) for i in sidx]
still = float((diffs < 0.05).mean() * 100)
heat = np.zeros(frames[0].shape[:2]); [heat.__iadd__((np.abs(frames[i + 1] - frames[i]).max(axis=2) > 12)) for i in range(len(frames) - 1)]
rec = {'id': s['id'], 'window_lt': [round(lt0, 3), round(lt1, 3)], 'frames': n,
'ms_mean': round(float(np.mean(ms)), 1), 'ms_max': round(float(np.max(ms)), 1), 'ms_cold': round(cold_ms, 1),
'deterministic': det == 0 and det_cold == 0, 'det_maxdiff': max(det, det_cold),
'motion_pct': round(float(diffs.mean()), 2), 'motion_max': round(float(diffs.max()), 2), 'still_pairs_pct': round(still, 1),
- 'spike_ratio': round(float(diffs.max() / max(med, 0.05)), 1), 'spikes_at_lt': spikes}
+ 'spike_ratio': round(float(diffs.max() / max(med, 0.05)), 1), 'spikes_at_lt': spikes,
+ 'camera_events_lt': [[round(ts[l], 3), round(ts[r + 1], 3)] for l, r in cams]}
frame_runs = merge_runs(persistent(ts, [frame_issues(tb, a.sub_band) for tb in tbs]) +
persistent(ts, [[('近空白', '')] if near_blank(f) else [] for f in frames]))
rec['framing'] = [{'kind': k, 'text': txt, 'lt': [round(t0, 2), round(t1, 2)], 't': [round(s['t0'] + t0, 2), round(s['t0'] + t1, 2)]} for k, txt, t0, t1 in frame_runs]
@@ -264,9 +282,9 @@ with sync_playwright() as p:
hm = np.clip(heat / max(1, heat.max()) * 255, 0, 255).astype(np.uint8)
base = Image.fromarray(pick[0].astype(np.uint8)).convert('L').convert('RGB'); red = np.zeros((H_, W_, 3), np.uint8); red[..., 0] = hm
S.paste(Image.blend(base, Image.fromarray(red), 0.6), (4 * W_, 20))
- dr.text((4, 4), f"{s['id']} 运动 {rec['motion_pct']}% 静止帧对 {rec['still_pairs_pct']}% 跳变 {len(spikes)} {rec['ms_mean']}/{rec['ms_max']}ms 确定性 {'✓' if rec['deterministic'] else '✗'}", fill='black')
+ dr.text((4, 4), f"{s['id']} 运动 {rec['motion_pct']}% 静止帧对 {rec['still_pairs_pct']}% 跳变 {len(spikes)} 镜头事件 {len(cams)} {rec['ms_mean']}/{rec['ms_max']}ms 确定性 {'✓' if rec['deterministic'] else '✗'}", fill='black')
S.save(out / f"{s['id']}.jpg", quality=85)
- print(f"{s['id']:<18} 运动 {rec['motion_pct']:>5}% 静止帧对 {rec['still_pairs_pct']:>5}% 跳变 {len(spikes)} {rec['ms_mean']:>6}/{rec['ms_max']:>6}ms 确定性 {'✓' if rec['deterministic'] else '✗ ' + str(rec['det_maxdiff'])} 框景 {len(rec['framing'])}")
+ print(f"{s['id']:<18} 运动 {rec['motion_pct']:>5}% 静止帧对 {rec['still_pairs_pct']:>5}% 跳变 {len(spikes)} 镜头事件 {len(cams)} {rec['ms_mean']:>6}/{rec['ms_max']:>6}ms 确定性 {'✓' if rec['deterministic'] else '✗ ' + str(rec['det_maxdiff'])} 框景 {len(rec['framing'])}")
for r in rec['framing']: print(f" {r['kind']} {r['t'][0]:.2f}–{r['t'][1]:.2f}s {r['text']}")
# 转场冒烟:只查能不能渲、耗时多少,不参与运动/流畅判据
report['transitions'] = []
@@ -286,9 +304,9 @@ srv.shutdown()
srv.server_close()
report['page_errors'] = errors
json.dump(report, open(out / 'qa.json', 'w'), ensure_ascii=False, indent=1)
-rows = ['| 段 | 运动% | 静止帧对% | 跳变 | 均/峰 ms | 冷启动 ms | 确定性 | 框景 |', '|---|---|---|---|---|---|---|---|']
+rows = ['| 段 | 运动% | 静止帧对% | 跳变 | 镜头事件 | 均/峰 ms | 冷启动 ms | 确定性 | 框景 |', '|---|---|---|---|---|---|---|---|---|']
for r in report['segments']:
- rows.append(f"| {r['id']} | {r['motion_pct']} | {r['still_pairs_pct']} | {len(r['spikes_at_lt'])} {r['spikes_at_lt'][:3]} | {r['ms_mean']}/{r['ms_max']} | {r['ms_cold']} | {'✓' if r['deterministic'] else '✗'} | {len(r['framing'])} |")
+ rows.append(f"| {r['id']} | {r['motion_pct']} | {r['still_pairs_pct']} | {len(r['spikes_at_lt'])} {r['spikes_at_lt'][:3]} | {len(r['camera_events_lt'])} | {r['ms_mean']}/{r['ms_max']} | {r['ms_cold']} | {'✓' if r['deterministic'] else '✗'} | {len(r['framing'])} |")
fr = [(r['id'], x) for r in report['segments'] for x in r['framing']]
if fr: rows += ['', '框景线索(全片秒,持续 ≥0.3s;去看这一帧再判断):'] + [f"- {x['kind']} {x['t'][0]:.2f}–{x['t'][1]:.2f}s({i}){x['text']}" for i, x in fr]
if report.get('transitions'): rows += ['', '转场冒烟(整帧,峰值 ms):' + ','.join(f"{r['type']}→{r['id']} {r['ms_max']}" for r in report['transitions'])]
diff --git a/tests/test_film_gate.py b/tests/test_film_gate.py
new file mode 100644
index 0000000..15d0caa
--- /dev/null
+++ b/tests/test_film_gate.py
@@ -0,0 +1,204 @@
+"""film_gate.py / deliver.py / qa.py 镜头事件的端到端测试。
+
+用引擎渲两支合成小片:同三张图(仓库 assets/ 里有纹理的总览图)、每镜 3 秒、硬切,
+ slow —— 每镜匀速慢推 7.5%(翻页式 PPT 的做法) → film_gate 应红灯
+ punch —— 每镜停住、一次 0.3 秒快推 30%、再停住 → film_gate 应绿灯
+测试只在本机装了 uv、ffmpeg 和 Playwright Chromium 时跑(CI 的媒体契约任务没有这些,自动跳过)。
+测试用的语法文件写在临时复制的引擎里,不进仓库。
+"""
+import json
+import os
+import shutil
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = ROOT / 'scripts'
+ENGINE = SCRIPTS / 'engine'
+IMAGES = [ROOT / 'assets' / 'showcase' / 'hero.png', ROOT / 'assets' / '全风格总览.jpg', ROOT / 'assets' / '动画语法' / 'y2_vox_总览.jpg']
+SHOT = 3.0
+
+# 测试专用语法:kind=shot 的 cue 一镜一张图,满幅(MD.cover),镜头由 data.mode 决定。
+PROBE = r'''
+CLIPS._gate_probe = { draw(c, t, ctx) {
+ const shots = ctx.of('shot'); let i = 0;
+ for (let k = 0; k < shots.length; k++) if (t >= shots[k].at) i = k;
+ const q = shots[i], end = i + 1 < shots.length ? shots[i + 1].at : ctx.dur, len = end - q.at, mode = ctx.data.mode;
+ let z = 1;
+ if (mode === 'slow') z = CAM.zlerp(1, 1.075, U.clamp((t - q.at) / len)); // 匀速慢推
+ if (mode === 'punch') z = CAM.track({}, [{ at: q.at + len * 0.4, kind: 'punch', k: 0.3, dur: 0.3 }], t).z; // 停住→快推→停住
+ c.fillStyle = '#000'; c.fillRect(0, 0, ctx.W, ctx.H);
+ MD.cover(c, ctx.still(q), { z });
+} };
+'''
+
+# 整片模式(qa --project --film gateprobe):三段「停住→0.3 秒快推→停住」,第四段中间闪一下白。画面是种子随机的色块。
+PROBE_FILM = r'''
+const tex = (c, seed) => { const r = U.rng(seed); c.fillStyle = '#1d2330'; c.fillRect(0, 0, 1920, 1080);
+ for (let i = 0; i < 600; i++) { c.fillStyle = `hsl(${r() * 360},60%,${30 + r() * 50}%)`; const s = 20 + r() * 120; c.fillRect(r() * 1920, r() * 1080, s, s * (0.3 + r())); } };
+window.ERAS = [1, 2, 3].map(k => ({ id: 'punch' + k, dur: 2.5,
+ draw: (c, lt) => CAM.with(c, CAM.track({}, [{ at: 1.2, kind: 'punch', k: 0.3, dur: 0.3 }], lt), cc => tex(cc, k)) }));
+window.ERAS.push({ id: 'flash', dur: 2.5, draw: (c, lt) => { tex(c, 9); if (lt >= 1.5 && lt < 1.55) { c.fillStyle = '#fff'; c.fillRect(0, 0, 1920, 1080); } } });
+'''
+
+
+def tools_ready():
+ return all(shutil.which(x) for x in ('uv', 'ffmpeg', 'ffprobe'))
+
+
+def run(*args, cwd=None):
+ return subprocess.run(['uv', 'run', '--quiet', *map(str, args)], cwd=cwd, capture_output=True, text=True, timeout=900)
+
+
+W = {} # 模块级夹具:引擎副本、spec、渲好的两支片
+
+
+def setUpModule():
+ if not tools_ready():
+ raise unittest.SkipTest('需要 uv、ffmpeg、ffprobe')
+ W['tmp'] = tempfile.TemporaryDirectory()
+ tmp = Path(W['tmp'].name)
+ eng = tmp / 'engine'
+ shutil.copytree(ENGINE, eng, ignore=shutil.ignore_patterns('demos', 'reference_films', 'examples', '__pycache__'))
+ (eng / 'clips' / '_gate_probe.js').write_text(PROBE)
+ (eng / 'eras_gateprobe.js').write_text(PROBE_FILM)
+ (tmp / 'img').mkdir()
+ for f in IMAGES:
+ shutil.copy(f, tmp / 'img' / f.name)
+ W['eng'] = eng
+ for mode in ('slow', 'punch'):
+ d = tmp / mode
+ d.mkdir()
+ spec = {'grammar': '_gate_probe', 'duration': SHOT * len(IMAGES), 'fps': 30, 'width': 960, 'height': 540,
+ 'data': {'mode': mode},
+ 'cues': [{'at': SHOT * k, 'kind': 'shot', 'image': f'../img/{f.name}'} for k, f in enumerate(IMAGES)]}
+ (d / 'spec.json').write_text(json.dumps(spec, ensure_ascii=False))
+ W[mode] = d
+ for mode in ('slow', 'punch'):
+ r = run('--with', 'playwright', 'python', eng / 'render.py', '--spec', W[mode] / 'spec.json', '--out', W[mode] / f'{mode}.mp4')
+ if r.returncode != 0 and 'Executable doesn' in (r.stdout + r.stderr):
+ raise unittest.SkipTest('Playwright Chromium 没装:uv run --with playwright playwright install chromium')
+ assert r.returncode == 0, r.stdout + r.stderr
+
+
+def tearDownModule():
+ if 'tmp' in W:
+ W['tmp'].cleanup()
+
+
+def gate(mp4):
+ r = run(SCRIPTS / 'film_gate.py', mp4, '--json', '--no-template')
+ return r.returncode, json.loads(r.stdout)
+
+
+class FilmGateTests(unittest.TestCase):
+ def test_slow_push_is_red(self):
+ code, res = gate(W['slow'] / 'slow.mp4')
+ self.assertEqual(code, 2)
+ self.assertEqual(res['gate_light'], 'red')
+ self.assertLess(res['fast_ratio'], 0.035)
+ self.assertIn('读起来像翻页', res['explain']['summary'])
+ self.assertIn('CAM.track', res['explain']['fix'])
+ self.assertIn('MD.cover', res['explain']['fix'])
+
+ def test_punch_is_green(self):
+ code, res = gate(W['punch'] / 'punch.mp4')
+ self.assertEqual(code, 0)
+ self.assertEqual(res['gate_light'], 'green')
+ self.assertGreaterEqual(res['fast_ratio'], 0.06)
+ self.assertIsNone(res['explain']['fix'])
+
+ def test_unreadable_file_exits_1(self):
+ bad = Path(W['tmp'].name) / 'bad.mp4'
+ bad.write_bytes(b'not a video')
+ self.assertEqual(run(SCRIPTS / 'film_gate.py', bad).returncode, 1)
+
+ def test_text_report_names_worst_window_and_fix(self):
+ r = run(SCRIPTS / 'film_gate.py', W['slow'] / 'slow.mp4', '--no-template')
+ self.assertEqual(r.returncode, 2)
+ self.assertIn('最差', r.stdout)
+ self.assertIn('怎么改', r.stdout)
+
+
+class DeliverTests(unittest.TestCase):
+ def deliver(self, mode, out, *extra):
+ return run(SCRIPTS / 'deliver.py', W[mode] / f'{mode}.mp4', '--out', out, *extra)
+
+ def test_red_does_not_copy(self):
+ out = Path(W['tmp'].name) / 'out_red'
+ r = self.deliver('slow', out, '--spec', W['slow'] / 'spec.json')
+ self.assertEqual(r.returncode, 2, r.stdout + r.stderr)
+ self.assertFalse((out / 'slow.mp4').exists())
+ self.assertFalse((out / '交付说明.md').exists())
+ self.assertIn('怎么改', r.stdout)
+
+ def test_green_copies_and_writes_facts(self):
+ out = Path(W['tmp'].name) / 'out_green'
+ r = self.deliver('punch', out, '--spec', W['punch'] / 'spec.json')
+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+ self.assertTrue((out / 'punch.mp4').is_file())
+ doc = (out / '交付说明.md').read_text()
+ self.assertIn('没派审片', doc)
+ self.assertIn('没跑', doc) # 没跑 qa
+ self.assertIn('960×540', doc)
+ self.assertIn(f'{SHOT * len(IMAGES):.2f}s', doc)
+ self.assertIn('快速运动帧占比', doc)
+ self.assertEqual(run(SCRIPTS / 'deliver.py', '--verify', out / '交付说明.md').returncode, 0)
+ # 改了事实段 → verify 报出来
+ (out / '交付说明.md').write_text(doc.replace('没派审片', '已通过独立审片'))
+ self.assertNotEqual(run(SCRIPTS / 'deliver.py', '--verify', out / '交付说明.md').returncode, 0)
+ # 只在制作说明段补主观描述 → verify 仍然通过
+ (out / '交付说明.md').write_text(doc + '\n补充:节奏按口播停顿。\n')
+ self.assertEqual(run(SCRIPTS / 'deliver.py', '--verify', out / '交付说明.md').returncode, 0)
+
+ def test_review_files_and_qa_are_listed(self):
+ proj = W['punch']
+ (proj / '审片').mkdir(exist_ok=True)
+ (proj / '审片' / '审片人A.md').write_text('结论写在这里')
+ qa = proj / 'qa'
+ qa.mkdir(exist_ok=True)
+ (qa / 'qa.json').write_text(json.dumps({'spec': str(proj / 'spec.json'), 'page_errors': [], 'segments': [
+ {'id': 'punch', 'deterministic': True, 'spikes_at_lt': [], 'camera_events_lt': [[1.6, 1.9]], 'framing': [],
+ 'motion_pct': 1.0, 'still_pairs_pct': 80.0, 'ms_mean': 10, 'ms_max': 20}]}))
+ try:
+ out = Path(W['tmp'].name) / 'out_review'
+ r = self.deliver('punch', out, '--spec', proj / 'spec.json')
+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+ doc = (out / '交付说明.md').read_text()
+ self.assertIn('审片人A.md', doc)
+ self.assertNotIn('没派审片', doc)
+ self.assertIn('跑过', doc)
+ self.assertIn('确定性:1/1', doc)
+ finally:
+ shutil.rmtree(proj / '审片')
+ shutil.rmtree(qa)
+
+
+class QaCameraEventTests(unittest.TestCase):
+ """整片模式下段内中位数≈0,一次 0.3 秒快推以前会被整串记成跳变;现在记成一个镜头事件。闪一下白仍是跳变。"""
+ @classmethod
+ def setUpClass(cls):
+ out = Path(W['tmp'].name) / 'qa_film'
+ r = run('--with', 'playwright', SCRIPTS / 'qa.py', '--project', W['eng'], '--film', 'gateprobe', '--out', out)
+ assert r.returncode == 0, r.stdout + r.stderr
+ cls.segs = {s['id']: s for s in json.loads((out / 'qa.json').read_text())['segments']}
+
+ def test_pulse_push_is_camera_event_not_spike(self):
+ for k in (1, 2, 3):
+ s = self.segs[f'punch{k}']
+ self.assertEqual(s['spikes_at_lt'], [], s)
+ self.assertEqual(len(s['camera_events_lt']), 1, s)
+ t0, t1 = s['camera_events_lt'][0]
+ self.assertLessEqual(t1 - t0, 0.35 + 2 / 30)
+ self.assertTrue(t0 <= 1.5 and t1 >= 1.2, s) # 落在快推那 0.3 秒上
+
+ def test_single_frame_flash_is_still_spike(self):
+ s = self.segs['flash']
+ self.assertGreaterEqual(len(s['spikes_at_lt']), 1, s)
+ self.assertEqual(s['camera_events_lt'], [], s)
+
+
+if __name__ == '__main__':
+ unittest.main()