Skip to content

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

Add packaging layer: subtitle timeline and styling, huazi, stickers, sfx alignment

june56516c6ba038
diff --git a/README.md b/README.md
index bd27d96..74e43e1 100644
--- a/README.md
+++ b/README.md
@@ -34,7 +34,7 @@ rea-video 判断:左边全部实拍,一个场景、两个机位就能拍完
不管哪类视频,都会另外拆出这几层:
-- 花字和字幕:文字的位置和出现时间,区分字幕、标题和物体上的字(包装、招牌);字体、描边、颜色、逐字高亮等样式。
+- 剪辑包装:逐句字幕时间轴(导出 SRT / ASS);花字、标题、章节牌、跟随标签,以及它们的颜色、描边、底框、关键词高亮和弹出 / 淡入等动画;表情包、GIF 动图、贴纸、画中画小窗出现在哪、多久、是否循环;哪些音效卡在文字或贴纸出现的那一下。
- 剪辑:切点和节奏,跳切、推近切、多机位切换、剪气口,插入素材的比例,是否卡节拍。
- 真实素材:录屏、截图、产品图这类复刻时要你自己准备的东西。
- 声音:真人还是 AI 配音,BGM 是 AI 生成还是曲库,BPM 和调性,每个音效的时间点。
diff --git a/README_en.md b/README_en.md
index 072ba8c..fe05118 100644
--- a/README_en.md
+++ b/README_en.md
@@ -36,7 +36,7 @@ rea-video's verdict: the left is all live footage, one set and two camera positi
For every video type it also breaks out:
-- Styled text and captions: where and when text appears, telling captions, titles and on-object text (packaging, signs) apart; font, outline, color, word-by-word highlight and other styling.
+- Editing packaging: a line-by-line caption timeline (exported as SRT / ASS); styled text (花字), titles, chapter cards and tracking labels with their color, outline, box, keyword highlight and pop / fade animations; stickers, GIFs, emoji and picture-in-picture windows with position, timing and whether they loop; which sound effects land on a text pop or sticker.
- Editing: cut points and pacing, jump cuts, punch-ins, multi-camera switching, cuts on pauses, share of inserted material, whether cuts land on the beat.
- Real assets: screen recordings, screenshots, product photos and other material you'll need to supply yourself.
- Audio: human or AI voice-over, AI-generated or library music, BPM and key, and when each sound effect hits.
diff --git a/docs/cli.md b/docs/cli.md
index 7d9e142..5ca3dde 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -75,7 +75,7 @@ $PY integrations/capsule_cinema/to_capsule.py --breakdown out/ref/breakdown.json
| 命令 | 作用 |
|---|---|
-| `decompose VIDEO [--vlm] [--no-ocr]` | 拆解,输出 breakdown.json、report.html/md、storyboard.jpg、每镜首尾帧 |
+| `decompose VIDEO [--vlm] [--no-ocr] [--no-packaging]` | 拆解,输出 breakdown.json、report.html/md、storyboard.jpg、每镜首尾帧,以及 `packaging/`(字幕 SRT、带样式的 ASS、包装时间轴、贴纸截图);`--no-packaging` 跳过包装层(省约每分钟 30–50 秒) |
| `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]` | 用户指出判错:改正结论和报告,并记入记忆(以后同一文件自动套用,同类镜头复核时提示) |
diff --git a/docs/what-it-detects.md b/docs/what-it-detects.md
index 3ef7140..aec5b35 100644
--- a/docs/what-it-detects.md
+++ b/docs/what-it-detects.md
@@ -19,7 +19,7 @@
同一个镜头上还会分开标出:
-- 后期叠加:字幕、花字、标题、贴片、版式模板。文字的位置和出现时间用 OCR 测;字体、描边、颜色、逐字高亮等样式靠看图描述。物体上的字(包装、招牌)会尽量和字幕分开。
+- 后期叠加:字幕、花字、标题、贴片、版式模板。物体上的字(包装、招牌)会尽量和字幕分开。具体见下面「剪辑包装层」。
- 真实素材:画面里嵌入的录屏、截图、照片、视频片段,复刻时要用原文件;AI 画面里的产品、Logo、人物,列为复刻时的参考图。
- 实拍上的 AI 加工(看图判断):换脸、对口型、风格化重绘、AI 换装、抠像换背景、加删物体、美颜。复刻方案会写成「先拍,拍完再做哪步 AI 加工、用哪个模型」。
@@ -37,8 +37,25 @@
光比、软硬、色温、调色从像素测量;光源是什么、有没有轮廓光、是不是户外、拍摄速度,靠看图补充。两边的结果在报告里并排列出。
+## 剪辑包装层
+
+整条视频按一条时间轴拆,不按镜头切开(一句字幕、一个贴纸常常跨切镜)。
+
+| 项 | 怎么测 | 产出 |
+|---|---|---|
+| 字幕时间轴 | 每秒 2 帧 OCR,同一位置的文字逐句跟踪,再用每秒 10 帧的灰度帧把起止对齐到约 0.1 秒;双行字幕合成一句 | `packaging/subtitles.srt` |
+| 文字样式 | 从像素量:字色、描边色和粗细、底框颜色、渐变、关键词另一种颜色(说到时变色也能看出)、字号、倾斜、粗细 | 报告里的样式列 |
+| 文字分类 | 字幕(同一位置连续换句)、花字(字大 / 彩色 / 倾斜 / 粗描边 / 多色 / 弹出,至少两条)、标题(顶部常驻)、文字标注(章节牌、跟着物体走的标签)、画面里的字 | 每条文字的类型 |
+| 入场 / 出场 | 直接出现、缩放弹出、淡入、滑入、逐字出现;句中有没有弹跳或变色 | 报告、ASS 里的动画 |
+| 贴纸 / 动图 / 画中画 | 在动的画面上不动、边界清楚的一块;切镜时周围全变它不变;镜头中途整块出现又消失(实拍上这条只标「疑似」);里面在动且有固定周期就是循环 GIF | 时间、位置、截图(`packaging/sticker_XX.jpg`)。实测召回约一半,漏的靠看图补 |
+| 音效卡点 | 每个音效对齐到最近的画面事件(字幕 / 花字 / 贴纸出现、切镜,±0.2 秒);没开 VLM 时,在花字和贴纸出现的时刻补找瞬态声作为低置信候选 | 音效表的「对应画面」列 |
+
+另外导出 `packaging/overlays.ass`(带颜色、描边、位置、弹出动画,可以直接 `ffmpeg -vf ass=` 压制,字体要换成原片字体)和 `packaging/timeline.json`。
+
+字体是什么、贴纸贴的是什么内容,像素量不出来,靠 VLM 或 agent 看图补。3D、动画、版式画面里物体本来就会突然出现,这类镜头上只认跨切镜或循环播放的贴纸,其余的列为「画面内容」,需要的话看图确认。评测结果见 [eval/RESULTS.md](../eval/RESULTS.md)。
+
## 声音
- 人声:真人还是 AI 配音,口播文案。
- 配乐:BPM、调性、段落,是 AI 生成还是曲库。
-- 音效:每个音效的时间点和对应画面。
+- 音效:每个音效的时间点、类型,以及它卡在哪个画面事件上(字幕 / 花字 / 贴纸出现、切镜)。
diff --git a/eval/RESULTS.md b/eval/RESULTS.md
index d21ed9e..597e5f2 100644
--- a/eval/RESULTS.md
+++ b/eval/RESULTS.md
@@ -283,3 +283,39 @@ rea-video --env-file $CAPSULE_CINEMA_ROOT/.env eval eval/labels.yaml -o out/eval
- 只用工具 labels 0.999 / holdout 0.996 / holdout2 0.998 / articles 0.886 / koubo 0.755,真实素材 0.976 / 0.996 / 0.981 / 1.0;koubo 取景 / 布光 / 形式 2/2;缓存答案重新融合各组合、koubo +VLM / +agent / 都开 0.885 / 0.967 / 0.985,均与改前一致。koubo 室内重新解码,新测量正常写入。
- 案例调色:MV 暗调低饱和、榨汁杯原片和复刻版自然、3D 科普片日系清新(明亮低对比),与画面一致。
- 局限:新类别、AI 加工、新布光、调色都没有真实标注视频,阈值来自合成图和经验值;数字人仍没有评测视频。下一步要收集:不同博主的实拍(室内外、RGB 灯、产品台)、数字人、2D 动画、定格、换脸 / 对口型视频各几条。
+
+## 2026-11-01:剪辑包装层——字幕时间轴与样式、花字、贴纸 / GIF、音效卡点
+
+动机:之前只在每个镜头抽 4 帧做 OCR,知道「这镜有字幕」,但拆不出逐句时间、字幕样式、花字、贴纸 / 表情包 / GIF,音效也没和画面事件对上。复杂剪辑的包装层复刻不出来。
+
+改动(`rea_video/packaging.py`,整片一条时间轴,不按镜头切):
+- 字幕时间轴:整片每秒 2 帧 OCR(最多 240 帧,画面里没有任何 8×8 块变化才沿用上一帧结果),多行字幕合成一块,同一位置同一段字跟踪成一句;再用每秒 10 帧的灰度帧把起止对齐(以相邻句的画面为对照,避免两句互相侵入)。导出 `packaging/subtitles.srt`。
+- 文字样式(从像素量):只在文字框里聚类;字芯 = 被包住、碰不到背景的颜色里横跨整行的那个;描边 = 字芯外 2 像素一圈的主色且比背景里常见;底框 = 文字左右紧贴处颜色一致且和更远处不同;关键词高亮 = 另一个有实心笔画的颜色(和抗锯齿过渡色区分);渐变、字高、粗细、倾斜。同一条字幕轨的字色 / 描边按多数统一。
+- 文字分类:字幕(同一位置连续换句)、花字(字大 / 彩色 / 倾斜 / 粗描边 / 多色 / 弹出,至少两条)、标题(顶部常驻、只有一段字)、文字标注(章节牌、跟着物体走的标签)、画面里的字(跟着画面动、无描边无底框)。
+- 入场 / 出场:一帧到位 = 直接出现;否则按出现前后的差异区域判缩放弹出 / 逐字 / 滑入 / 淡入;句中弹跳、变色单独标。
+- 贴纸 / GIF / 画中画,三条线索:① 在动的画面上,一块边界清楚、内部不动、四周都在动、不贴画面边的区域,保持 1.5 秒以上(口播上贴的表情包、头像、截图);② 切镜时画面几乎全变(没变的不超过 15%,排除同机位跳切)而这一块不变;③ 去掉镜头运动后,镜头中途某块整体突变并保持,后面又整块消失、原处纹理恢复。③ 在实拍 / AI 画面上常是画面本身(抬手、换装),所以除非里面在循环播放或完全静止,只标「疑似」、不进结论。3D / 动画 / 版式 / 录屏画面里只认跨切镜或循环的。贴边、过细的区域不算。有贴纸的镜头,制作方式特征只在贴纸外的区域测。
+- 音效:每个音效对齐到最近的画面事件(±0.2 秒);没开 VLM 时在花字 / 标签 / 贴纸出现时刻补找瞬态声,作为低置信候选。
+- VLM 整片提示词增加 `text_effects`、`stickers`;`rea-video review` 增加 `packaging`(确认 / 否定贴纸、改文字类型、补漏)。导出 `packaging/overlays.ass`(颜色、描边、底框、位置、弹出动画)。`--no-packaging` 可跳过。
+- 新增 `tests/test_packaging.py`(8 项:合成视频上的字幕时间轴和白字黑描边、弹出花字、循环 GIF 贴纸位置和时间、音效对齐、ASS 导出、贴纸区域剔除、复核覆盖、流水线输出),`pytest` 79 项通过。
+
+真值:从 capsule-cinema 的叠字代码导出(`eval/*_text.json`)——salted_egg / birdnest 的 overlay.py(字幕逐句时间、说到关键词变黄弹跳、常驻标题、章节牌、跟着物体走的标签、大号贴字),monkey_wine_v3 的 subtitles.json(双行字幕)。**这三条在开发时反复看过,不是独立测试集。**
+
+| 视频 | 字幕句数 | 召回 | 精确 | 起 / 止误差中位 | 起止都在 0.25s 内 | 文字相似度 | 字色 / 描边 | 关键词高亮 |
+|---|---|---|---|---|---|---|---|---|
+| salted_egg_plush | 40 | 0.975 | 1.000 | 0.063 / 0.056s | 74% | 0.989 | 100% / 100% | 84% |
+| birdnest_plush | 32 | 1.000 | 1.000 | 0.066 / 0.045s | 66% | 0.988 | 100% / 97% | 100% |
+| monkey_wine_v3 | 42 | 1.000 | 0.933 | 0.070 / 0.042s | 86% | 0.990 | 93%(无描边,0 误报) | — |
+
+其他文字:标题 3/3、章节牌 12/12 找到且归类正确;跟着物体走的标签 11 个找到 7 个(只出现 0.5 秒左右的常被 OCR 漏掉),其中 2 个被分成了花字;大号贴字(「流油咸鸭蛋!」「燕窝!」)2/2 判为花字。
+
+贴纸:
+- 三条真值视频都没有图片贴纸,最终 0 处。birdnest 里「蛋突然孵化」被像素层当成贴纸,靠「3D 画面里只认跨切镜或循环」排除。
+- 合成视频:循环 GIF(两帧表情、0.4 秒一循环、背景在平移)能找到,位置、起止、循环都对。
+- 真实视频(articles 10 条 + koubo 2 条,人工看图核对,没有逐帧真值):进结论的检出 9 处,6 处是真贴纸(口播室内的猫猫表情包、机器人「Got it!」、4 个名人头像圆贴纸),3 处误报(v10 界面里播放的视频、v12 带货实拍、口播夜景片尾);另有 1 处「疑似」(v07 换装,确实不是)。漏检明显:口播夜景里人在动时贴上的「豆包」图标、点赞截图卡片、圈注截图,口播室内的聊天截图都没找到——估计召回约一半。这些要靠 VLM(整片提示词已要求列出贴纸)或 agent 看图补。
+- 第一版只靠「镜头中途突变」时,这 12 条视频上报了 30 多处,几乎全是误报(抬手、换装、跳切背景、画面边缘),所以才改成上面三条线索。
+
+音效:在 salted_egg / birdnest 上,花字 / 标签 / 贴纸出现时刻补出的候选 17 个,对上 cue sheet 的 7 个(41%)。这两条的真值音效很密(每秒约 1.7 个),随机落点也有约 28% 能对上,所以提升有限,只作为低置信候选;开了 VLM 时不补。
+
+回归:只用工具 labels 0.999 / holdout 0.996 / holdout2 0.998,真实素材 0.976 / 0.996 / 0.981,声音各项与改前一致。
+
+耗时:包装层每分钟视频约 30–50 秒(主要是 OCR)。
diff --git a/eval/birdnest_plush_text.json b/eval/birdnest_plush_text.json
new file mode 100644
index 0000000..c05de45
--- /dev/null
+++ b/eval/birdnest_plush_text.json
@@ -0,0 +1,597 @@
+{
+ "source": "capsule-cinema /work/overlay.py",
+ "duration": 66.458,
+ "subtitles": [
+ {
+ "t0": 0.227,
+ "t1": 1.957,
+ "text": "在海边高高的悬崖上",
+ "highlight": [
+ "悬崖"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 1.957,
+ "t1": 3.899,
+ "text": "住着一群小小的金丝燕",
+ "highlight": [
+ "金丝燕"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 3.899,
+ "t1": 6.099,
+ "text": "它们做的巢就是名贵的燕窝",
+ "highlight": [
+ "燕窝"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 6.099,
+ "t1": 7.658,
+ "text": "卖起来论克算钱",
+ "highlight": [
+ "论克算钱"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 7.658,
+ "t1": 9.478,
+ "text": "原来 繁殖季一到",
+ "highlight": [
+ "繁殖季"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 9.478,
+ "t1": 11.818,
+ "text": "雄燕舌下的唾液腺会肿胀",
+ "highlight": [
+ "唾液腺"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 11.818,
+ "t1": 14.022,
+ "text": "会涌出多得吓人的唾液",
+ "highlight": [
+ "唾液"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 14.022,
+ "t1": 16.422,
+ "text": "第一步 雄燕飞进洞穴",
+ "highlight": [
+ "洞穴"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 16.422,
+ "t1": 19.136,
+ "text": "把唾液一小口一小口吐在岩壁上",
+ "highlight": [
+ "岩壁"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 19.136,
+ "t1": 20.796,
+ "text": "这种唾液又黏又韧",
+ "highlight": [
+ "又黏又韧"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 20.796,
+ "t1": 23.543,
+ "text": "一碰空气就凝成半透明的唾液丝",
+ "highlight": [
+ "唾液丝"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 23.543,
+ "t1": 25.918,
+ "text": "就像棉花糖机吐出来的糖丝",
+ "highlight": [
+ "棉花糖机",
+ "糖丝"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 25.918,
+ "t1": 28.068,
+ "text": "第二步 它来来回回地飞",
+ "highlight": [],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 28.068,
+ "t1": 29.826,
+ "text": "把丝一根根粘叠起来",
+ "highlight": [
+ "一根根",
+ "粘叠"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 29.826,
+ "t1": 31.566,
+ "text": "花上 30~45 天",
+ "highlight": [
+ "30~45 天"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 31.566,
+ "t1": 33.2,
+ "text": "才叠成半个小碗",
+ "highlight": [
+ "小碗"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 33.2,
+ "t1": 35.96,
+ "text": "第三步 雌燕在窝里下了两颗蛋",
+ "highlight": [
+ "两颗蛋"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 35.96,
+ "t1": 37.665,
+ "text": "孵出毛茸茸的雏燕",
+ "highlight": [
+ "雏燕"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 37.665,
+ "t1": 39.685,
+ "text": "再喂养 40~45 天",
+ "highlight": [
+ "40~45 天"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 39.685,
+ "t1": 41.633,
+ "text": "雏燕的翅膀就长硬了",
+ "highlight": [
+ "翅膀"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 41.633,
+ "t1": 43.863,
+ "text": "第四步 雏燕飞走以后",
+ "highlight": [
+ "飞走"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 43.863,
+ "t1": 45.867,
+ "text": "这一盏空巢才能摘下来",
+ "highlight": [
+ "空巢"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 45.867,
+ "t1": 47.697,
+ "text": "从动工筑巢到采摘",
+ "highlight": [
+ "采摘"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 47.697,
+ "t1": 49.835,
+ "text": "前后要等 80~90 天",
+ "highlight": [
+ "80~90 天"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 49.835,
+ "t1": 51.455,
+ "text": "摘下来的空巢晒干了",
+ "highlight": [
+ "空巢"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 51.455,
+ "t1": 53.301,
+ "text": "泛出莹润的金光",
+ "highlight": [
+ "金光"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 53.301,
+ "t1": 55.389,
+ "text": "这 就是燕窝",
+ "highlight": [
+ "燕窝"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 55.389,
+ "t1": 57.989,
+ "text": "不过 九成多的燕子窝都不能吃",
+ "highlight": [
+ "不能吃"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 57.989,
+ "t1": 59.379,
+ "text": "能筑食用燕窝的",
+ "highlight": [],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 59.379,
+ "t1": 61.37,
+ "text": "主要是雨燕科的金丝燕",
+ "highlight": [
+ "雨燕科",
+ "金丝燕"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 61.37,
+ "t1": 63.29,
+ "text": "而且要等雏燕都飞走了",
+ "highlight": [
+ "雏燕"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 63.29,
+ "t1": 67.458,
+ "text": "才能摘这一盏空巢",
+ "highlight": [
+ "空巢"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ }
+ ],
+ "titles": [
+ {
+ "t0": 0.0,
+ "t1": 66.458,
+ "text": "燕窝是怎么筑成的?",
+ "decorative": true,
+ "style": {
+ "multicolor": true,
+ "stroke": "dark",
+ "animation": "scale_in"
+ }
+ }
+ ],
+ "cards": [
+ {
+ "t0": 14.005,
+ "t1": 25.901,
+ "text": "第1步 · 岩壁吐丝",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 25.901,
+ "t1": 33.183,
+ "text": "第2步 · 叠丝成碗",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 33.183,
+ "t1": 41.616,
+ "text": "第3步 · 下蛋孵雏",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 41.616,
+ "t1": 53.284,
+ "text": "第4步 · 空巢可采",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 53.284,
+ "t1": 55.372,
+ "text": "成了!",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 55.372,
+ "t1": 66.458,
+ "text": "注意!",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ }
+ ],
+ "labels": [
+ {
+ "t0": 10.671,
+ "t1": 11.833,
+ "text": "唾液腺",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 22.869,
+ "t1": 23.542,
+ "text": "唾液丝",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 24.156,
+ "t1": 25.917,
+ "text": "棉花糖机",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 32.679,
+ "t1": 33.208,
+ "text": "小碗",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 37.153,
+ "t1": 37.667,
+ "text": "雏燕",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 44.586,
+ "t1": 45.875,
+ "text": "空巢",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ }
+ ],
+ "stickers": [
+ {
+ "t0": 54.055,
+ "t1": 55.375,
+ "text": "燕窝!",
+ "decorative": true,
+ "style": {
+ "size_px": 150,
+ "stroke": "dark",
+ "animation": "pop_in_wobble"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/eval/holdout.yaml b/eval/holdout.yaml
index 9166ed6..f10d497 100644
--- a/eval/holdout.yaml
+++ b/eval/holdout.yaml
@@ -9,6 +9,8 @@ videos:
real_material: false
path: ${CAPSULE}/output/birdnest_plush/final.mp4
label: cg_3d # plush_diorama_science / Blender
+ packaging_truth: eval/birdnest_plush_text.json # overlay.py 时间表(开发包装层时看过,不独立)
+ sfx_truth: eval/birdnest_plush_sfx.json
- id: h3_realcat
real_material: false
path: ${CAPSULE}/output/dual_role_social_account_doctor_20260930/h3/realcat_s1_seed9300101.mp4
diff --git a/eval/labels.yaml b/eval/labels.yaml
index 5c8079a..0881383 100644
--- a/eval/labels.yaml
+++ b/eval/labels.yaml
@@ -16,6 +16,7 @@ videos:
real_material: false
path: ${CAPSULE}/output/monkey_wine_v3/release/monkey_wine_v3.mp4
label: ai_video # MiniMax H3 首尾帧生成的"3D 手办"风格 AI 视频 + 代码字幕
+ packaging_truth: eval/monkey_wine_v3_text.json # overlays_v3/subtitles.json(双行字幕)
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)
@@ -65,6 +66,8 @@ videos:
real_material: false
path: ${CAPSULE}/output/salted_egg_plush/final.mp4
label: cg_3d # plush_diorama_science:Blender 本地渲染 + 代码字幕
+ packaging_truth: eval/salted_egg_plush_text.json # overlay.py 的字幕/标题/章节牌/标签/贴字时间表
+ sfx_truth: eval/salted_egg_plush_sfx.json
source: capsule-cinema plush_diorama_science 配方
- id: murphy_shape
diff --git a/eval/monkey_wine_v3_text.json b/eval/monkey_wine_v3_text.json
new file mode 100644
index 0000000..6da6ecc
--- /dev/null
+++ b/eval/monkey_wine_v3_text.json
@@ -0,0 +1,437 @@
+{
+ "source": "capsule-cinema monkey_wine_v3/work/overlays_v3/subtitles.json (edit.py)",
+ "duration": 87.832,
+ "subtitles": [
+ {
+ "t0": 0.43,
+ "t1": 3.11,
+ "text": "要是你在深山里/撞见一群野猴子",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 3.11,
+ "t1": 4.62,
+ "text": "只要悄悄跟着它们",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 4.62,
+ "t1": 7.03,
+ "text": "八成就能找到/传说中的猴儿酒",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 7.246,
+ "t1": 9.166,
+ "text": "原来,秋天果子一熟",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 9.166,
+ "t1": 11.096,
+ "text": "猴子们为了/熬过缺吃的冬天",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 11.096,
+ "t1": 12.546,
+ "text": "就开始拼命囤粮",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 12.816,
+ "t1": 15.126,
+ "text": "它们搬来/一大堆高糖分的野果",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 15.126,
+ "t1": 17.176,
+ "text": "一股脑塞进天然的树洞里",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 17.512,
+ "t1": 18.722,
+ "text": "果子越堆越多",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 18.722,
+ "t1": 20.862,
+ "text": "互相挤压,果皮破了",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 20.862,
+ "t1": 23.272,
+ "text": "果肉里的糖水/就大量渗了出来",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 23.572,
+ "t1": 25.042,
+ "text": "树洞里空间密闭",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 25.042,
+ "t1": 26.112,
+ "text": "温度又稳定",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 26.112,
+ "t1": 28.212,
+ "text": "简直就是/一个天然的发酵罐",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 28.84,
+ "t1": 32.42,
+ "text": "更巧的是,果子表皮上/本来就带着野生酵母菌",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 32.708,
+ "t1": 34.678,
+ "text": "一下雨,雨水渗进树洞",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 34.678,
+ "t1": 36.348,
+ "text": "把浓稠的果浆稀释开",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 36.348,
+ "t1": 38.388,
+ "text": "正好满足了/发酵需要的湿度",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 38.68,
+ "t1": 40.67,
+ "text": "这时洞里还剩一点氧气",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 40.67,
+ "t1": 42.51,
+ "text": "酵母菌开始大量繁殖",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 42.51,
+ "t1": 44.97,
+ "text": "还把蔗糖/拆成了葡萄糖和果糖",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 45.504,
+ "t1": 47.964,
+ "text": "时间一长,果肉把树洞慢慢堵死",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 47.964,
+ "t1": 50.334,
+ "text": "里面变成了/密不透风的缺氧环境",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 50.604,
+ "t1": 51.734,
+ "text": "氧气一耗尽",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 51.734,
+ "t1": 53.894,
+ "text": "酵母菌马上切换生存模式",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 53.894,
+ "t1": 55.234,
+ "text": "开始无氧呼吸",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 55.234,
+ "t1": 57.544,
+ "text": "把糖分解成/酒精和二氧化碳",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 57.846,
+ "t1": 58.996,
+ "text": "糖越来越少",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 58.996,
+ "t1": 60.426,
+ "text": "酒精度越来越高",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 60.692,
+ "t1": 62.522,
+ "text": "可酵母也有耐受上限",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 62.522,
+ "t1": 65.162,
+ "text": "酒精度一到12%~15%左右",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 65.162,
+ "t1": 67.502,
+ "text": "它们就会被/自己产的酒精杀死",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 67.502,
+ "t1": 68.882,
+ "text": "发酵自动停止",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 69.562,
+ "t1": 72.082,
+ "text": "剩下的酒精/和果子里的有机酸",
+ "lines": 2,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 72.082,
+ "t1": 74.162,
+ "text": "还会慢慢发生酯化反应",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 74.162,
+ "t1": 76.232,
+ "text": "生成带果香的酯类物质",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 76.232,
+ "t1": 77.762,
+ "text": "飘出浓浓的酒香",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 78.088,
+ "t1": 80.018,
+ "text": "这就是传说中的猴儿酒",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 80.29,
+ "t1": 81.97,
+ "text": "不过树洞里杂菌太多",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 81.97,
+ "t1": 83.73,
+ "text": "很容易产生有毒物质",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 83.73,
+ "t1": 85.08,
+ "text": "所以这种猴儿酒",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ },
+ {
+ "t0": 85.08,
+ "t1": 86.45,
+ "text": "千万别随便喝",
+ "lines": 1,
+ "style": {
+ "fill": "dark",
+ "stroke": null
+ }
+ }
+ ],
+ "titles": [
+ {
+ "t0": 0.0,
+ "t1": 87.832,
+ "text": "猴儿酒是怎么来的?",
+ "decorative": false
+ }
+ ],
+ "cards": [],
+ "labels": [],
+ "stickers": []
+}
\ No newline at end of file
diff --git a/eval/salted_egg_plush_text.json b/eval/salted_egg_plush_text.json
new file mode 100644
index 0000000..60bd00d
--- /dev/null
+++ b/eval/salted_egg_plush_text.json
@@ -0,0 +1,685 @@
+{
+ "source": "capsule-cinema /work/overlay.py",
+ "duration": 66.542,
+ "subtitles": [
+ {
+ "t0": 0.187,
+ "t1": 1.457,
+ "text": "清晨的小院里",
+ "highlight": [],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 1.457,
+ "t1": 3.667,
+ "text": "鸭宝磕开一枚腌好的咸鸭蛋",
+ "highlight": [
+ "咸鸭蛋"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 3.667,
+ "t1": 5.218,
+ "text": "红亮的油涌了出来",
+ "highlight": [
+ "油"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 5.218,
+ "t1": 6.998,
+ "text": "明明没往里加一滴油",
+ "highlight": [
+ "油"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 6.998,
+ "t1": 8.879,
+ "text": "花猫看得眼睛都直了",
+ "highlight": [
+ "眼睛都直了"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 8.879,
+ "t1": 9.609,
+ "text": "这油",
+ "highlight": [],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 9.609,
+ "t1": 11.447,
+ "text": "到底是打哪儿冒出来的?",
+ "highlight": [
+ "冒出来"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 11.447,
+ "t1": 12.207,
+ "text": "原来",
+ "highlight": [],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 12.207,
+ "t1": 13.667,
+ "text": "这场流油的大戏",
+ "highlight": [
+ "流油"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 13.667,
+ "t1": 15.824,
+ "text": "幕后导演是普普通通的盐",
+ "highlight": [
+ "盐"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 15.824,
+ "t1": 18.014,
+ "text": "第一步 腌蛋的盐水里",
+ "highlight": [
+ "盐水"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 18.014,
+ "t1": 19.584,
+ "text": "盐顺着蛋壳的气孔",
+ "highlight": [
+ "气孔"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 19.584,
+ "t1": 21.039,
+ "text": "一粒粒往里钻",
+ "highlight": [
+ "钻"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 21.039,
+ "t1": 23.039,
+ "text": "第二步 盐先灌满蛋清",
+ "highlight": [
+ "蛋清"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 23.039,
+ "t1": 24.319,
+ "text": "再穿过蛋黄膜",
+ "highlight": [
+ "蛋黄膜"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 24.319,
+ "t1": 26.116,
+ "text": "一路潜进蛋黄深处",
+ "highlight": [
+ "深处"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 26.116,
+ "t1": 27.786,
+ "text": "蛋黄里存着的水分",
+ "highlight": [
+ "水分"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 27.786,
+ "t1": 29.446,
+ "text": "被盐一把拉了出去",
+ "highlight": [
+ "拉"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 29.446,
+ "t1": 30.606,
+ "text": "失了水的蛋黄",
+ "highlight": [],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 30.606,
+ "t1": 31.576,
+ "text": "缩成一团",
+ "highlight": [
+ "缩成一团"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 31.576,
+ "t1": 33.736,
+ "text": "越缩越小 越缩越硬",
+ "highlight": [
+ "硬"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 33.736,
+ "t1": 34.556,
+ "text": "第三步",
+ "highlight": [],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 34.556,
+ "t1": 36.496,
+ "text": "高盐让蛋黄里的蛋白质",
+ "highlight": [
+ "高盐",
+ "蛋白质"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 36.496,
+ "t1": 38.057,
+ "text": "纷纷收紧抱团",
+ "highlight": [
+ "收紧"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 38.057,
+ "t1": 39.997,
+ "text": "原本被裹得严严实实的油",
+ "highlight": [
+ "油"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 39.997,
+ "t1": 41.595,
+ "text": "一下子全散开了",
+ "highlight": [
+ "散开"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 41.595,
+ "t1": 42.725,
+ "text": "就像拧毛巾",
+ "highlight": [
+ "拧毛巾"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 42.725,
+ "t1": 43.685,
+ "text": "手一收紧",
+ "highlight": [],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 43.685,
+ "t1": 45.247,
+ "text": "水就被挤了出来",
+ "highlight": [
+ "挤"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 45.247,
+ "t1": 47.337,
+ "text": "第四步 剩下的交给时间",
+ "highlight": [
+ "时间"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 47.337,
+ "t1": 49.595,
+ "text": "家庭腌制要 30~40 天",
+ "highlight": [
+ "30~40 天"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 49.595,
+ "t1": 51.275,
+ "text": "腌足日子再敲开",
+ "highlight": [
+ "敲开"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 51.275,
+ "t1": 52.765,
+ "text": "红油汪在蛋黄上",
+ "highlight": [
+ "红油"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 52.765,
+ "t1": 54.952,
+ "text": "颤颤的 亮亮的",
+ "highlight": [],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 54.952,
+ "t1": 57.198,
+ "text": "这 就是流油咸鸭蛋",
+ "highlight": [
+ "流油咸鸭蛋"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 57.198,
+ "t1": 59.578,
+ "text": "不过 这油不是谁偷偷加的",
+ "highlight": [
+ "偷偷"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 59.578,
+ "t1": 60.739,
+ "text": "神秘物质",
+ "highlight": [
+ "神秘物质"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 60.739,
+ "t1": 62.979,
+ "text": "这些油本来就是蛋黄里的脂肪",
+ "highlight": [
+ "脂肪"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 62.979,
+ "t1": 63.919,
+ "text": "一滴没多",
+ "highlight": [
+ "一滴没多"
+ ],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ },
+ {
+ "t0": 63.919,
+ "t1": 67.542,
+ "text": "一滴也没少",
+ "highlight": [],
+ "style": {
+ "fill": "white",
+ "stroke": "dark",
+ "highlight_color": "yellow",
+ "animation": "keyword_bounce"
+ }
+ }
+ ],
+ "titles": [
+ {
+ "t0": 0.0,
+ "t1": 66.542,
+ "text": "咸鸭蛋为什么会流油?",
+ "decorative": true,
+ "style": {
+ "multicolor": true,
+ "stroke": "dark",
+ "animation": "scale_in"
+ }
+ }
+ ],
+ "cards": [
+ {
+ "t0": 15.807,
+ "t1": 21.022,
+ "text": "第1步 · 盐钻气孔",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 21.022,
+ "t1": 33.719,
+ "text": "第2步 · 盐进蛋黄",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 33.719,
+ "t1": 45.23,
+ "text": "第3步 · 蛋白挤油",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 45.23,
+ "t1": 54.935,
+ "text": "第4步 · 静待出油",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 54.935,
+ "t1": 57.181,
+ "text": "成了!",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 57.181,
+ "t1": 66.542,
+ "text": "注意!",
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ }
+ ],
+ "labels": [
+ {
+ "t0": 19.817,
+ "t1": 21.042,
+ "text": "气孔",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 22.692,
+ "t1": 23.042,
+ "text": "蛋清",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 23.832,
+ "t1": 24.333,
+ "text": "蛋黄膜",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 25.442,
+ "t1": 26.125,
+ "text": "蛋黄",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ },
+ {
+ "t0": 51.558,
+ "t1": 54.958,
+ "text": "红油",
+ "follows_object": true,
+ "style": {
+ "box": true,
+ "animation": "pop_in"
+ }
+ }
+ ],
+ "stickers": [
+ {
+ "t0": 55.335,
+ "t1": 57.208,
+ "text": "流油咸鸭蛋!",
+ "decorative": true,
+ "style": {
+ "size_px": 150,
+ "stroke": "dark",
+ "animation": "pop_in_wobble"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/rea_video/audio.py b/rea_video/audio.py
index 4d55b22..4a1a99b 100644
--- a/rea_video/audio.py
+++ b/rea_video/audio.py
@@ -191,6 +191,46 @@ def vocal_style(x: np.ndarray, Sh: np.ndarray, freqs: np.ndarray, voice_segs: li
return out
+def sfx_type(S: np.ndarray, freqs: np.ndarray, frame_db: np.ndarray, c: int, hop_t: float = T_HOP) -> tuple[str, dict]:
+ """Coarse type of the transient starting at STFT frame c, from its spectrum and decay."""
+ w = slice(c, min(len(S), c + int(0.12 / hop_t)))
+ spec = S[w].mean(axis=0)
+ total = float(spec.sum()) + 1e-9
+ hf_ratio = float(spec[freqs > 4000].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) * hop_t < 1.5:
+ j += 1
+ d = (j - c) * hop_t
+ 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"
+ return kind, {"dur": round(d, 3), "centroid_hz": int(centroid), "hf_ratio": round(hf_ratio, 3)}
+
+
+def onset_envelope(path: str):
+ """(percussive onset curve, frame dB, magnitude STFT, freqs, seconds per frame) of a file's soundtrack."""
+ x = extract_audio(path, SR)
+ if x is None or len(x) < SR * 0.3:
+ return None
+ S = _stft(x)
+ freqs = np.fft.rfftfreq(N_FFT, 1 / SR)
+ _, Sp = hpss(S)
+ frame_db = 10 * np.log10((S ** 2).mean(axis=1) + 1e-12)
+ perc = np.maximum(0, np.diff(np.log1p(Sp.sum(axis=1)), prepend=0))
+ return perc, frame_db, S, freqs, T_HOP
+
+
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:
@@ -302,7 +342,6 @@ def analyze_audio(path: str, cut_times: list[float] | None = None, visual_marks:
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:
@@ -327,30 +366,9 @@ def analyze_audio(path: str, cut_times: list[float] | None = None, visual_marks:
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"})
+ kind, info = sfx_type(S, freqs, frame_db, c, T_HOP)
+ events.append({"t": round(c * T_HOP, 3), "type": kind, **info, "strength": round(strength, 1),
+ "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):
diff --git a/rea_video/classify.py b/rea_video/classify.py
index 5c88e17..def20da 100644
--- a/rea_video/classify.py
+++ b/rea_video/classify.py
@@ -460,7 +460,8 @@ def verdict_text(label: str, image_source: str | None, layers: list[dict]) -> st
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"])
+ name = {"subtitle": "字幕", "title": "标题", "label": "文字标注", "static_graphic": "图形贴片", "layout_template": "版式模板",
+ "huazi": "花字", "animated_sticker": "动态贴纸/GIF", "static_sticker": "静态贴纸", "pip": "画中画"}.get(l["kind"], l["kind"])
if name not in kinds:
kinds.append(name)
if kinds:
diff --git a/rea_video/cli.py b/rea_video/cli.py
index ded9f22..c572c67 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -36,7 +36,8 @@ def cmd_decompose(args) -> int:
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)
+ workers=args.workers, engine=args.engine or pref("engine", "seedance2.0"), platform_meta=meta, stems=stems,
+ packaging=not args.no_packaging)
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))
@@ -215,6 +216,15 @@ def cmd_summary(args) -> int:
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(配乐)")
+ pk = b.get("packaging")
+ if pk:
+ lines += [""] + [f"包装: {x}" for x in (pk.get("summary_zh") or ["没有检出后期叠加的文字或贴纸"])]
+ low = [st for st in pk.get("stickers", []) if not st.get("in_picture") and st.get("confidence") in ("low", "vlm")]
+ if low:
+ lines.append("包装: 需要看图确认的贴纸 " + "、".join(f"{st['id']} {st['t0']:.1f}-{st['t1']:.1f}s" for st in low)
+ + "(截图在 packaging/)")
+ if pk.get("files"):
+ lines.append("包装文件: " + " ".join(pk["files"].values()))
print("\n".join(lines))
return 0
@@ -288,7 +298,8 @@ def main(argv: list[str] | None = None) -> int:
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("--no-ocr", action="store_true", help="不做 OCR(字幕/花字时间轴也会跳过,只剩贴纸检测)")
+ d.add_argument("--no-packaging", action="store_true", help="跳过剪辑包装层(整片字幕时间轴、花字、贴纸/动图、音效卡点);省掉约每分钟 30–50 秒")
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}}')
diff --git a/rea_video/evaluate.py b/rea_video/evaluate.py
index 9fea58f..f6d9cbe 100644
--- a/rea_video/evaluate.py
+++ b/rea_video/evaluate.py
@@ -7,7 +7,7 @@ from pathlib import Path
import yaml
from .classify import LABELS
-from .pipeline import decompose, finalize
+from .pipeline import PACKAGING_VERSION, decompose, finalize
from .util import LOG, read_json, round_floats, write_json
@@ -72,6 +72,99 @@ def audio_check(gt: dict, b: dict) -> dict:
return out
+def packaging_check(truth_path: str | Path, pack: dict, sfx: list[dict] | None = None, sfx_truth: list | None = None) -> dict:
+ """Packaging layer vs a ground-truth overlay schedule (eval/*_text.json, exported from the maker's overlay code).
+ Subtitles: a predicted subtitle cue matches a truth line when the words agree (similarity >= 0.6) and the
+ times overlap; timing error is measured on matched pairs. Other text (title / chapter cards / object labels /
+ decorative stickers): found = any predicted non-subtitle cue with similar words overlapping in time; kind_ok =
+ it got the expected kind. Image stickers: the truth files list none, so every predicted one is a false alarm."""
+ from .packaging import _norm, _similar
+
+ gt = read_json(Path(_expand(str(truth_path))))
+ cues = pack.get("text_cues", [])
+ subs = [c for c in cues if c["kind"] == "subtitle"]
+
+ def overlap(a0, a1, b0, b1):
+ return max(0.0, min(a1, b1) - max(a0, b0))
+
+ matched_pred: set[int] = set()
+ d0, d1, sims, hits = [], [], [], 0
+ for g in gt["subtitles"]:
+ gtext = g["text"].replace("/", "")
+ best, best_s = None, 0.0
+ for i, c in enumerate(subs):
+ if overlap(g["t0"], g["t1"], c["t0"], c["t1"]) <= 0:
+ continue
+ sim = _similar(gtext, c["text"])
+ if sim > best_s:
+ best, best_s = i, sim
+ if best is not None and best_s >= 0.6:
+ hits += 1
+ matched_pred.add(best)
+ c = subs[best]
+ d0.append(abs(c["t0"] - g["t0"]))
+ d1.append(abs(c["t1"] - g["t1"]))
+ sims.append(best_s)
+ # a prediction that is a fragment of a truth line (OCR split a line) is not a false alarm
+ for i, c in enumerate(subs):
+ if i in matched_pred:
+ continue
+ if any(overlap(g["t0"], g["t1"], c["t0"], c["t1"]) > 0 and _norm(c["text"]) and _norm(c["text"]) in _norm(g["text"])
+ for g in gt["subtitles"]):
+ matched_pred.add(i)
+ n_gt = len(gt["subtitles"])
+ out: dict = {"subtitles": {"truth": n_gt, "pred": len(subs), "recall": round(hits / n_gt, 3) if n_gt else None,
+ "precision": round(len(matched_pred) / len(subs), 3) if subs else None,
+ "start_err_median_s": round(float(sorted(d0)[len(d0) // 2]), 3) if d0 else None,
+ "end_err_median_s": round(float(sorted(d1)[len(d1) // 2]), 3) if d1 else None,
+ "within_0.25s": round(sum(1 for a, b in zip(d0, d1) if a <= 0.25 and b <= 0.25) / len(d0), 3) if d0 else None,
+ "text_similarity": round(sum(sims) / len(sims), 3) if sims else None}}
+ st = {}
+ for c in subs:
+ for k in ("fill_name", "stroke_name"):
+ v = (c.get("style") or {}).get(k)
+ if v:
+ st.setdefault(k, []).append(v)
+ want = (gt["subtitles"][0].get("style") or {}) if gt["subtitles"] else {}
+ if want and st:
+ fills = st.get("fill_name", [])
+ name = {"white": "白", "dark": ("黑", "棕", "灰")}
+ wf = name.get(want.get("fill"), want.get("fill"))
+ out["subtitles"]["fill_ok"] = round(sum(1 for f in fills if f in (wf if isinstance(wf, tuple) else (wf,))) / max(1, len(subs)), 3)
+ strokes = st.get("stroke_name", [])
+ if want.get("stroke"):
+ out["subtitles"]["stroke_found"] = round(len(strokes) / max(1, len(subs)), 3)
+ else:
+ out["subtitles"]["stroke_false"] = round(len(strokes) / max(1, len(subs)), 3)
+ if any(g.get("highlight") for g in gt["subtitles"]):
+ with_kw = [g for g in gt["subtitles"] if g.get("highlight")]
+ found = 0
+ for g in with_kw:
+ c = next((c for c in subs if overlap(g["t0"], g["t1"], c["t0"], c["t1"]) > 0.5 * (g["t1"] - g["t0"])), None)
+ found += bool(c and (c.get("style") or {}).get("multicolor"))
+ out["subtitles"]["keyword_highlight_found"] = round(found / len(with_kw), 3)
+ expect = {"titles": "title", "cards": "label", "labels": "label", "stickers": "huazi"}
+ others = [c for c in cues if c["kind"] != "subtitle"]
+ for key, kind in expect.items():
+ items = gt.get(key) or []
+ if not items:
+ continue
+ found = kind_ok = 0
+ for g in items:
+ cand = [c for c in others if overlap(g["t0"], g["t1"], c["t0"], c["t1"]) > 0 and _similar(g["text"], c["text"]) >= 0.5]
+ if cand:
+ found += 1
+ kind_ok += any(c["kind"] == kind for c in cand)
+ out[key] = {"truth": len(items), "found": found, "kind_ok": kind_ok}
+ out["image_stickers_false"] = sum(1 for st in pack.get("stickers", []) if not st.get("in_picture"))
+ if sfx is not None and sfx_truth is not None:
+ tt = sorted(float(x[0]) for x in sfx_truth)
+ anch = [e for e in sfx if e.get("source") == "deterministic_anchored"]
+ ok = sum(1 for e in anch if any(abs(e["t"] - t) <= 0.1 for t in tt))
+ out["sfx_anchored"] = {"pred": len(anch), "correct": ok, "precision": round(ok / len(anch), 3) if anch else None}
+ return out
+
+
def boundary_f1(pred: list[float], gt: list[float], tol: float = 0.1) -> dict:
used = set()
tp = 0
@@ -125,6 +218,17 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
b["stems"] = extract_stems(path, vout)
if voc.is_file():
refine_with_stems(b["audio"], str(voc))
+ if entry.get("packaging_truth") and (b.get("packaging") or {}).get("version") != PACKAGING_VERSION:
+ from .media import video_info
+ from .packaging import analyze as analyze_packaging, anchored_sfx, visual_events
+
+ info = video_info(path)
+ pk = analyze_packaging(path, info, [s["start"] for s in b["shots"][1:]], vout, ocr=ocr)
+ if b["source"].get("has_audio"):
+ ev = [e for e in visual_events(pk["text_cues"], pk["stickers"], []) if e["type"] != "subtitle_in"]
+ pk["sfx_anchored"] = anchored_sfx(path, ev, (b["audio"].get("sfx") or {}).get("events", []))
+ pk["version"] = PACKAGING_VERSION
+ b["packaging"] = round_floats(pk)
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)
@@ -166,6 +270,9 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
row["aspects"] = aspect_check(entry["aspects"], b)
for k, v in row["aspects"].items():
aspect_hits.setdefault(k, []).append(v)
+ if entry.get("packaging_truth") and b.get("packaging"):
+ sfx_truth = read_json(Path(_expand(entry["sfx_truth"]))) if entry.get("sfx_truth") else None
+ row["packaging"] = packaging_check(entry["packaging_truth"], b["packaging"], (b.get("audio_plan") or {}).get("sfx_merged", []), sfx_truth)
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"):
@@ -185,6 +292,22 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
summary["audio"] = {k: f"{sum(v)}/{len(v)}" for k, v in audio_hits.items()}
if aspect_hits:
summary["aspects"] = {k: f"{sum(v)}/{len(v)}" for k, v in aspect_hits.items()}
+ packs = [r["packaging"] for r in rows if r.get("packaging")]
+ if packs:
+ subs = [p_["subtitles"] for p_ in packs]
+ tot = sum(x["truth"] for x in subs)
+ summary["packaging"] = {
+ "videos": len(packs), "subtitle_lines": tot,
+ "subtitle_recall": round(sum(x["recall"] * x["truth"] for x in subs) / tot, 3) if tot else None,
+ "subtitle_precision_mean": round(sum(x["precision"] or 0 for x in subs) / len(subs), 3),
+ "start_err_median_s": {r["id"]: r["packaging"]["subtitles"]["start_err_median_s"] for r in rows if r.get("packaging")},
+ "end_err_median_s": {r["id"]: r["packaging"]["subtitles"]["end_err_median_s"] for r in rows if r.get("packaging")},
+ "other_text_found": f"{sum(p_[k]['found'] for p_ in packs for k in ('titles', 'cards', 'labels', 'stickers') if k in p_)}/"
+ f"{sum(p_[k]['truth'] for p_ in packs for k in ('titles', 'cards', 'labels', 'stickers') if k in p_)}",
+ "other_text_kind_ok": f"{sum(p_[k]['kind_ok'] for p_ in packs for k in ('titles', 'cards', 'labels', 'stickers') if k in p_)}/"
+ f"{sum(p_[k]['truth'] for p_ in packs for k in ('titles', 'cards', 'labels', 'stickers') if k in p_)}",
+ "image_sticker_false_alarms": sum(p_["image_stickers_false"] for p_ in packs),
+ }
cuts = [r["cut_f1"]["f1"] for r in rows if "cut_f1" in r]
if cuts:
summary["cut_f1_mean"] = round(sum(cuts) / len(cuts), 3)
diff --git a/rea_video/features.py b/rea_video/features.py
index 8b86d6c..64f9813 100644
--- a/rea_video/features.py
+++ b/rea_video/features.py
@@ -146,7 +146,9 @@ def global_motion(prev: np.ndarray, nxt: np.ndarray) -> dict | None:
}
-def collect_samples(path: str, info: VideoInfo, shot: Shot, n_frames: int = 16, n_motion: int = 24) -> ShotSamples:
+def collect_samples(path: str, info: VideoInfo, shot: Shot, n_frames: int = 16, n_motion: int = 24,
+ crop: tuple[float, float, float, float] | None = None) -> ShotSamples:
+ """crop: measure only this part of the frame (0-1 x, y, w, h), e.g. to leave out a sticker / GIF layer."""
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)
@@ -155,7 +157,7 @@ def collect_samples(path: str, info: VideoInfo, shot: Shot, n_frames: int = 16,
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)):
+ for i, bgr in enumerate(iter_frames(path, info, ANALYSIS_W, start=shot.start, duration=shot.duration, crop=crop)):
if i >= total:
break
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
diff --git a/rea_video/media.py b/rea_video/media.py
index 4b3cf11..c095648 100644
--- a/rea_video/media.py
+++ b/rea_video/media.py
@@ -140,11 +140,25 @@ def iter_frames(
start: float | None = None,
duration: float | None = None,
gray: bool = False,
+ fps: float | None = None,
+ crop: tuple[float, float, float, float] | None = None,
) -> 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."""
+ By default frames are passed through untouched (no fps resampling) so duplicate-frame
+ statistics stay meaningful; fps= resamples to a fixed rate (frame i is at start + i / fps).
+ crop=(x, y, w, h) in 0-1 of the displayed frame keeps only that region (width applies to the crop)."""
w, h = scaled_size(info, width)
+ vf = []
+ if fps:
+ vf.append(f"fps={fps:g}")
+ if crop:
+ cx, cy, cw, ch = crop
+ vf.append(f"crop=trunc(iw*{cw:.4f}/2)*2:trunc(ih*{ch:.4f}/2)*2:trunc(iw*{cx:.4f}):trunc(ih*{cy:.4f})")
+ full_w, full_h = scaled_size(info, 1 << 16) # displayed size at native resolution
+ crop_w, crop_h = max(2.0, full_w * cw), max(2.0, full_h * ch)
+ w = max(2, int(min(width, crop_w)) // 2 * 2)
+ h = max(2, int(round(w * crop_h / crop_w)) // 2 * 2)
+ vf.append(f"scale={w}:{h}:flags=area")
cmd = ["ffmpeg", "-v", "error", "-nostdin"]
if start is not None and start > 0:
cmd += ["-ss", f"{start:.4f}"]
@@ -152,7 +166,7 @@ def iter_frames(
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, "-"]
+ cmd += ["-an", "-sn", "-vf", ",".join(vf), *([] if fps else 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
diff --git a/rea_video/packaging.py b/rea_video/packaging.py
new file mode 100644
index 0000000..1e11a49
--- /dev/null
+++ b/rea_video/packaging.py
@@ -0,0 +1,1457 @@
+"""Packaging layer (剪辑包装): what an editor puts on top of the picture, on one timeline.
+
+1. Text cues: OCR over the whole video (about 2 frames/s), lines grouped into blocks (multi-line subtitles),
+ blocks tracked over time into cues with start / end. A dense grey pass (about 10 frames/s) then refines
+ each cue's start / end and reads its entrance / exit animation (cut-in, pop / scale, fade, slide,
+ typewriter reveal). Each cue gets a style read from its pixels (fill / stroke / box colours, gradient,
+ two-colour keyword highlight, size, tilt) and a kind:
+ subtitle a lane of changing lines at a fixed place
+ huazi 花字: decorative text (large, coloured, tilted, thick stroke, multi-colour, pop-in)
+ title long-lived text at the top
+ label other overlay text (chapter cards, captions, tags; "follows" when it moves with an object)
+ scene words printed on things in the picture (moves with the picture, no stroke / box)
+2. Stickers: regions that appear and disappear mid-shot as a block, or survive a cut while the rest of the
+ frame changes. Inside: animated (GIF / 表情包, looping or not), static (sticker / picture) or a
+ picture-in-picture video.
+3. Sound effects lined up with what happens on screen (text pops, sticker entrances, cuts), and extra
+ SFX candidates found at those moments (a transient right on a visual event is much more likely an
+ added sound effect than one in the middle of speech).
+
+Everything here is deterministic and best effort: styles and animations are measured, not read, so a VLM
+or the agent's look at the frames still settles fine typography (font family) and odd cases."""
+from __future__ import annotations
+
+import re
+from difflib import SequenceMatcher
+from pathlib import Path
+
+import cv2
+import numpy as np
+
+from .media import VideoInfo, extract_frame, iter_frames
+from .overlay import get_ocr
+from .util import LOG
+
+OCR_FPS = 2.0
+OCR_MAX = 240 # OCR calls per video (~0.2 s each)
+DENSE_FPS = 10.0
+DENSE_MAX = 1800 # dense grey frames per video
+DENSE_W = 360
+SMALL_W = 160 # sticker search resolution
+CELL = 8 # sticker search cell size (px at SMALL_W)
+MIN_CONF = 0.6
+
+KIND_ZH = {"subtitle": "字幕", "huazi": "花字", "title": "标题", "label": "文字标注", "scene": "画面里的字"}
+ANIM_ZH = {"cut": "直接出现", "pop": "缩放弹出", "fade": "淡入", "slide": "滑入", "reveal": "逐字出现",
+ "cut_out": "直接消失", "pop_out": "缩小消失", "fade_out": "淡出", "slide_out": "滑出"}
+STICKER_ZH = {"animated_sticker": "动态贴纸/GIF", "static_sticker": "静态贴纸/图片", "pip": "画中画小窗"}
+
+
+# ----------------------------------------------------------------------------- colour helpers
+
+def color_name(bgr) -> str:
+ b, g, r = (int(v) for v in bgr)
+ hsv = cv2.cvtColor(np.uint8([[[b, g, r]]]), cv2.COLOR_BGR2HSV)[0, 0]
+ h, s, v = int(hsv[0]) * 2, int(hsv[1]), int(hsv[2])
+ if v < 55:
+ return "黑"
+ if s < 40:
+ return "白" if v > 200 else "灰"
+ if s < 90 and v < 150:
+ return "灰"
+ if h < 12 or h >= 340:
+ return "红" if v > 110 else "棕"
+ if h < 40:
+ return "橙" if v > 150 else "棕"
+ if h < 68:
+ return "黄"
+ if h < 165:
+ return "绿"
+ if h < 195:
+ return "青"
+ if h < 255:
+ return "蓝"
+ if h < 295:
+ return "紫"
+ return "粉"
+
+
+def _hex(bgr) -> str:
+ b, g, r = (int(round(float(v))) for v in bgr)
+ return f"#{r:02x}{g:02x}{b:02x}"
+
+
+def text_style(frame: np.ndarray, box: tuple[int, int, int, int]) -> dict | None:
+ """Colours and decoration of one OCR'd text line. box = (x0, y0, x1, y1) in frame pixels.
+ Glyph fill = colour blobs inside the box that do not reach the ring around it (letters are closed shapes;
+ the background between them connects to the outside). Stroke = the colour that surrounds those blobs, when
+ it differs from the background. Works on busy backgrounds where the fill colour also occurs in the scene."""
+ H, W = frame.shape[:2]
+ x0, y0, x1, y1 = box
+ lh = max(4, y1 - y0)
+ pad = max(3, int(0.35 * lh))
+ X0, Y0, X1, Y1 = max(0, x0 - pad), max(0, y0 - pad), min(W, x1 + pad), min(H, y1 + pad)
+ crop = frame[Y0:Y1, X0:X1]
+ if crop.size == 0 or crop.shape[0] < 6 or crop.shape[1] < 6:
+ return None
+ ch, cw = crop.shape[:2]
+ inner = np.zeros((ch, cw), bool)
+ inner[max(0, y0 - Y0):y1 - Y0, max(0, x0 - X0):x1 - X0] = True
+ ring = ~inner
+ if ring.sum() < 20 or inner.sum() < 30:
+ return None
+ lab3 = cv2.cvtColor(crop, cv2.COLOR_BGR2LAB).astype(np.float32)
+ lab = lab3.reshape(-1, 3)
+ # cluster mostly on the text box itself so the glyph colours are not outvoted by a light background
+ rng = np.random.default_rng(0)
+ inner_px, ring_px = lab[inner.ravel()], lab[ring.ravel()]
+ pts = np.concatenate([inner_px[rng.choice(len(inner_px), min(len(inner_px), 4000), replace=False)],
+ ring_px[rng.choice(len(ring_px), min(len(ring_px), 1000), replace=False)]])
+ k = 6
+ crit = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
+ _, _, centers = cv2.kmeans(pts, k, None, crit, 2, cv2.KMEANS_PP_CENTERS)
+ lbl = np.argmin(((lab[:, None, :] - centers[None]) ** 2).sum(-1), axis=1).reshape(ch, cw)
+ # enclosed pixels per colour: connected blobs that stay inside the box
+ enclosed = np.zeros(k)
+ enc_mask = np.zeros((ch, cw), np.int32) - 1
+ for c in range(k):
+ m = (lbl == c).astype(np.uint8)
+ n, cc, stats, _ = cv2.connectedComponentsWithStats(m, connectivity=4)
+ touch = np.unique(cc[ring & (m > 0)])
+ for j in range(1, n):
+ if j in touch or stats[j, cv2.CC_STAT_AREA] < 3:
+ continue
+ enclosed[c] += stats[j, cv2.CC_STAT_AREA]
+ enc_mask[cc == j] = c
+ if enclosed.sum() < 0.02 * inner.sum():
+ return None
+ fill = int(np.argmax(enclosed))
+ # thin glyphs with a thick outline: the outline can cover more pixels than the fill. The fill is the colour
+ # that the other one wraps around.
+ def spread(c: int) -> float:
+ """Share of the line's columns where this colour has solid strokes (a keyword covers a stretch, the fill
+ the whole line; an anti-aliased rim has no solid strokes)."""
+ m = (enc_mask == c).astype(np.uint8)
+ solid = cv2.distanceTransform(m, cv2.DIST_L2, 3) >= 1.5
+ cols = solid[:, max(0, x0 - X0):x1 - X0].any(axis=0)
+ return float(cols.mean()) if cols.size else 0.0
+
+ # background = the ring's main colours where they connect to the outside; the fill sits deeper inside the
+ # glyphs than its outline does
+ ring_share0 = np.bincount(lbl[ring], minlength=k) / max(1, ring.sum())
+ bg_mask = (enc_mask == -1) & np.isin(lbl, [c for c in range(k) if ring_share0[c] >= 0.2])
+
+ def bg_contact(c: int) -> float:
+ """Share of the colour's rim (2 px out, past anti-aliasing) lying on the background: an outline borders
+ it, the fill inside an outline does not."""
+ m = (enc_mask == c).astype(np.uint8)
+ rim = cv2.dilate(m, np.ones((5, 5), np.uint8)).astype(bool) & ~cv2.dilate(m, np.ones((3, 3), np.uint8)).astype(bool)
+ return float(bg_mask[rim].mean()) if rim.sum() else 1.0
+
+ top = [int(c) for c in np.argsort(-enclosed)[:4] if enclosed[c] >= 0.08 * enclosed.max()]
+ sp = {c: spread(c) for c in top}
+ wide = [c for c in top if sp[c] >= 0.5 * max(sp.values())] or top
+ fill = min(wide, key=lambda c: (round(bg_contact(c), 1), -sp[c])) if bg_mask.any() else max(wide, key=lambda c: sp[c])
+ bgr_of = lambda c: cv2.cvtColor(np.uint8([[centers[c]]]), cv2.COLOR_LAB2BGR)[0, 0] # noqa: E731
+ out: dict = {"fill": _hex(bgr_of(fill)), "fill_name": color_name(bgr_of(fill))}
+ fm = (enc_mask == fill)
+ # what surrounds the fill blobs, 2 px out (skips the anti-aliased rim)
+ d1 = cv2.dilate(fm.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool)
+ d2 = cv2.dilate(fm.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool)
+ halo = d2 & ~d1 & (enc_mask != fill)
+ neigh = np.bincount(lbl[halo], minlength=k) / max(1, halo.sum())
+ ring_share = np.bincount(lbl[ring], minlength=k) / max(1, ring.sum())
+
+ def contrast(a: int, b: int) -> float:
+ return abs(float(centers[a][0] - centers[b][0])) + 0.5 * float(np.linalg.norm(centers[a][1:] - centers[b][1:]))
+
+ cands = [c for c in range(k) if c != fill and contrast(c, fill) > 30]
+ s_c = max(cands, key=lambda c: neigh[c]) if cands else None
+ # a stroke is a colour hugging the glyphs that is not just "the background": it is much rarer in the ring
+ # than right around the glyphs
+ if s_c is not None and neigh[s_c] >= 0.4 and neigh[s_c] > 2.0 * ring_share[s_c]:
+ sm = (lbl == s_c) & cv2.dilate(fm.astype(np.uint8), np.ones((9, 9), np.uint8)).astype(bool) & ~fm
+ perim = max(1.0, float((d1 & ~fm).sum()))
+ out.update(stroke=_hex(bgr_of(s_c)), stroke_name=color_name(bgr_of(s_c)),
+ stroke_ratio=round(float(sm.sum()) / perim / lh, 3))
+ else:
+ s_c = None
+ # a second enclosed colour far from the fill, with solid strokes of its own (not an anti-aliased rim):
+ # keyword highlight / two-colour title
+ core = lambda m: float((cv2.distanceTransform(m.astype(np.uint8), cv2.DIST_L2, 3) >= 1.5).sum()) # noqa: E731
+ fill_core = core(fm) / max(1.0, float(fm.sum()))
+ for c in np.argsort(-enclosed):
+ c = int(c)
+ if c in (fill, s_c) or enclosed[c] < 0.12 * enclosed[fill]:
+ continue
+ cm = enc_mask == c
+ if core(cm) / max(1.0, float(cm.sum())) < 0.5 * fill_core:
+ continue
+ # a colour between the fill and the stroke / background in lightness with the same hue is an edge blend
+ others_l = [float(centers[x][0]) for x in range(k) if x != fill and (x == s_c or ring_share[x] > 0.2)]
+ between = any(min(float(centers[fill][0]), o_) <= float(centers[c][0]) <= max(float(centers[fill][0]), o_) for o_ in others_l)
+ if float(np.linalg.norm(centers[c][1:] - centers[fill][1:])) > 25 or (not between and abs(float(centers[c][0] - centers[fill][0])) > 60):
+ out.update(multicolor=True, highlight=_hex(bgr_of(c)), highlight_name=color_name(bgr_of(c)))
+ break
+ # gradient: lightness / hue of the fill pixels drift along y or x
+ fy, fx = np.nonzero(fm)
+ if len(fy) > 40:
+ fl = lab3[fy, fx]
+ for coord in (fy, fx):
+ if coord.std() > 1:
+ for chn in (0, 2):
+ if fl[:, chn].std() < 3:
+ continue
+ r = float(np.corrcoef(coord, fl[:, chn])[0, 1])
+ span = abs(float(np.polyfit(coord, fl[:, chn], 1)[0])) * float(np.ptp(coord))
+ if abs(r) > 0.55 and span > 28:
+ out["gradient"] = True
+ # box (底框 / pill): the strips just left and right of the text (inside a pill's side margins) are one
+ # uniform colour that differs from what lies further out
+ def strip(xa: int, xb: int, ya: int, yb: int):
+ xa, xb, ya, yb = max(0, xa), min(W, xb), max(0, ya), min(H, yb)
+ if xb - xa < 2 or yb - ya < 2:
+ return None
+ return cv2.cvtColor(frame[ya:yb, xa:xb], cv2.COLOR_BGR2LAB).reshape(-1, 3).astype(np.float32)
+
+ ya, yb = y0 + int(0.25 * lh), y1 - int(0.25 * lh)
+ near = [strip(x0 - int(0.28 * lh), x0 - int(0.06 * lh), ya, yb), strip(x1 + int(0.06 * lh), x1 + int(0.28 * lh), ya, yb)]
+ far = [strip(x0 - int(1.7 * lh), x0 - int(1.2 * lh), ya, yb), strip(x1 + int(1.2 * lh), x1 + int(1.7 * lh), ya, yb),
+ strip(x0, x1, y0 - int(1.3 * lh), y0 - int(0.9 * lh)), strip(x0, x1, y1 + int(0.9 * lh), y1 + int(1.3 * lh))]
+ # (a tight pill can end right at the last glyph on one side: one uniform side is enough)
+ def uniform_(px: np.ndarray) -> bool: # most pixels one colour (anti-aliased glyph edges may poke in)
+ return float((np.linalg.norm(px - np.median(px, axis=0), axis=1) < 10).mean()) >= 0.7
+
+ near = [n_ for n_ in near if n_ is not None and len(n_) >= 6 and uniform_(n_)]
+ near = [n_[np.linalg.norm(n_ - np.median(n_, axis=0), axis=1) < 10] for n_ in near]
+ far = [f_ for f_ in far if f_ is not None and len(f_) >= 6]
+ if near and far:
+ meds = [np.median(n_, axis=0) for n_ in near]
+ uniform = len(meds) == 1 or float(np.linalg.norm(meds[0] - meds[1])) < 12
+ box_lab = np.mean(meds, axis=0)
+ if uniform and min(float(np.linalg.norm(np.median(f_, axis=0) - box_lab)) for f_ in far) > (18 if len(meds) == 2 else 25):
+ bcol = cv2.cvtColor(np.uint8([[box_lab]]), cv2.COLOR_LAB2BGR)[0, 0]
+ if float(np.linalg.norm(box_lab - centers[fill])) > 25:
+ out.update(box=True, box_color=_hex(bcol), box_name=color_name(bcol))
+ for key in ("stroke", "highlight"): # the box seen through glyph holes / around the glyphs is not a text colour
+ if out.get(key):
+ kc = cv2.cvtColor(np.uint8([[[int(out[key][5:7], 16), int(out[key][3:5], 16), int(out[key][1:3], 16)]]]),
+ cv2.COLOR_BGR2LAB)[0, 0].astype(np.float32)
+ if float(np.linalg.norm(kc - box_lab)) < 22:
+ for kk in [x for x in list(out) if x.startswith(key) or (key == "highlight" and x == "multicolor")]:
+ out.pop(kk)
+ # weight: glyph stroke thickness relative to the line height
+ dt = cv2.distanceTransform(fm.astype(np.uint8), cv2.DIST_L2, 3)
+ if (dt > 0).sum() > 20:
+ out["weight"] = round(2 * float(np.percentile(dt[dt > 0], 90)) / lh, 3)
+ return out
+
+
+# ----------------------------------------------------------------------------- OCR pass
+
+def _norm(s: str) -> str:
+ return re.sub(r"[\s,。、,.!!??::;;·•'\"“”‘’/\-—_~()()\[\]【】]", "", s).lower()
+
+
+def _similar(a: str, b: str) -> float:
+ a, b = _norm(a), _norm(b)
+ if not a or not b:
+ return 0.0
+ return SequenceMatcher(None, a, b, autojunk=False).ratio()
+
+
+def _band(cy: float) -> str:
+ return "top" if cy < 0.22 else ("bottom" if cy > 0.70 else "middle")
+
+
+def ocr_pass(path: str | Path, info: VideoInfo, max_calls: int = OCR_MAX) -> tuple[list[dict], float]:
+ """OCR the whole video at a fixed rate. Returns (items, step_seconds). Frames that did not change since the
+ last OCR'd frame reuse its result."""
+ ocr = get_ocr()
+ if ocr is None or info.duration <= 0:
+ return [], 0.0
+ fps = min(OCR_FPS, max(0.5, max_calls / info.duration))
+ portrait = (info.height > info.width) != (info.rotation in (90, 270))
+ width = 720 if portrait else 1280
+ items: list[dict] = []
+ prev_small, prev = None, []
+ for i, f in enumerate(iter_frames(path, info, width, fps=fps)):
+ t = round(i / fps, 3)
+ H, W = f.shape[:2]
+ small = cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY), (192, max(16, int(192 * H / W) // 8 * 8)), interpolation=cv2.INTER_AREA)
+ # reuse the last result only if no 8x8 block changed (a new subtitle line is a small local change)
+ if prev_small is not None and small.shape == prev_small.shape and float(
+ cv2.absdiff(small, prev_small).reshape(small.shape[0] // 8, 8, small.shape[1] // 8, 8).mean(axis=(1, 3)).max()) < 2.0:
+ items += [dict(it, t=t) for it in prev]
+ continue
+ prev_small = small
+ try:
+ res, _ = ocr(f)
+ except Exception as exc: # pragma: no cover
+ LOG.debug("ocr failed at %.2f: %s", t, exc)
+ res = None
+ cur = []
+ for box, text, conf in res or []:
+ if float(conf) < MIN_CONF or not re.search(r"[\w一-鿿]", text):
+ continue
+ pts = np.array(box, dtype=np.float32)
+ 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])))
+ bx = (int(x0), int(y0), int(x1), int(y1))
+ cur.append({"t": t, "text": text, "conf": round(float(conf), 3),
+ "bbox": [round(x0 / W, 4), round(y0 / H, 4), round((x1 - x0) / W, 4), round((y1 - y0) / H, 4)],
+ "angle": round(ang, 1), "style": text_style(f, bx)})
+ prev = cur
+ items += cur
+ return items, 1.0 / fps
+
+
+def _blocks(items: list[dict]) -> list[dict]:
+ """Lines OCR'd at the same moment that stack into one block (a two-line subtitle)."""
+ lines = sorted(items, key=lambda d: d["bbox"][1])
+ blocks: list[dict] = []
+ for it in lines:
+ x, y, w, h = it["bbox"]
+ cx = x + w / 2
+ hit = None
+ for b in blocks:
+ last = b["lines"][-1]
+ lx, ly, lw, lh = last["bbox"]
+ gap = y - (ly + lh)
+ same_look = not (it.get("style") and last.get("style")) or it["style"].get("fill_name") == last["style"].get("fill_name")
+ if (-0.3 * lh < gap < 0.8 * max(h, lh) and abs(cx - (lx + lw / 2)) < 0.12 and 0.8 < h / max(1e-6, lh) < 1.25
+ and same_look):
+ hit = b
+ break
+ if hit is None:
+ blocks.append({"lines": [it]})
+ else:
+ hit["lines"].append(it)
+ out = []
+ for b in blocks:
+ ls = b["lines"]
+ x0 = min(l["bbox"][0] for l in ls)
+ y0 = min(l["bbox"][1] for l in ls)
+ x1 = max(l["bbox"][0] + l["bbox"][2] for l in ls)
+ y1 = max(l["bbox"][1] + l["bbox"][3] for l in ls)
+ out.append({"t": ls[0]["t"], "text": "/".join(l["text"] for l in ls), "conf": float(np.mean([l["conf"] for l in ls])),
+ "bbox": [x0, y0, x1 - x0, y1 - y0], "line_h": float(np.median([l["bbox"][3] for l in ls])),
+ "n_lines": len(ls), "angle": float(np.median([l["angle"] for l in ls])),
+ "styles": [l["style"] for l in ls if l.get("style")]})
+ return out
+
+
+def build_cues(items: list[dict], step: float) -> list[dict]:
+ """Track text blocks over time: same place + same words = one cue; same place, new words = the next cue."""
+ by_t: dict[float, list[dict]] = {}
+ for it in items:
+ by_t.setdefault(it["t"], []).append(it)
+ cues: list[dict] = []
+ open_: list[dict] = []
+ for t in sorted(by_t):
+ for c in [c for c in open_ if c["last"] < t - 2.5 * step]:
+ open_.remove(c)
+ for b in _blocks(by_t[t]):
+ x, y, w, h = b["bbox"]
+ cx, cy = x + w / 2, y + h / 2
+ best, best_d = None, 9.0
+ for c in open_:
+ if c["last"] >= t:
+ continue
+ d = abs(cy - c["cy"]) / max(0.02, c["line_h"]) + abs(cx - c["cx"]) * 4
+ if abs(cy - c["cy"]) < max(0.03, 0.8 * c["line_h"]) + 0.02 and abs(cx - c["cx"]) < 0.2 and d < best_d:
+ best, best_d = c, d
+ if best is not None:
+ sim = _similar(b["text"], best["text"])
+ grow = len(_norm(b["text"])) > len(_norm(best["text"])) and _norm(b["text"]).startswith(_norm(best["text"])[:max(1, len(_norm(best["text"])) - 1)])
+ if sim >= 0.6 or grow:
+ if grow and sim < 0.9:
+ best["reveal"] = True
+ best["obs"].append(b)
+ best["last"] = t
+ if grow:
+ best["text"], best["conf"] = b["text"], b["conf"]
+ continue
+ open_.remove(best) # same place, new words: the previous cue ended
+ c = {"text": b["text"], "conf": b["conf"], "first": t, "last": t, "cx": cx, "cy": cy, "line_h": b["line_h"], "obs": [b]}
+ cues.append(c)
+ open_.append(c)
+ # a one-sample cue right before another at the same place is that text mid-entrance (scaling / blurred / half
+ # typed) misread by OCR: fold it into the next one
+ cues.sort(key=lambda c: c["first"])
+ merged_into: set[int] = set()
+ for i, c in enumerate(cues):
+ if len(c["obs"]) != 1:
+ continue
+ for j in range(i + 1, len(cues)):
+ o = cues[j]
+ if o["first"] - c["last"] > 1.6 * step:
+ break
+ entering = c["line_h"] < 0.85 * o["line_h"] or _similar(c["text"], o["text"]) >= 0.4 # still scaling in / half read
+ if (abs(o["cy"] - c["cy"]) < max(0.03, 0.8 * o["line_h"]) and abs(o["cx"] - c["cx"]) < 0.15 and len(o["obs"]) >= 2
+ and entering):
+ o["obs"] = c["obs"] + o["obs"]
+ o["first"] = c["first"]
+ o["entrance_misread"] = True
+ merged_into.add(i)
+ break
+ cues = [c for i, c in enumerate(cues) if i not in merged_into]
+ # the same words at the same place with a short gap (OCR missed a sample, a transition dimmed it): one cue
+ cues.sort(key=lambda c: c["first"])
+ keep: list[dict] = []
+ for c in cues:
+ prev = next((o for o in reversed(keep) if abs(o["cy"] - c["cy"]) < max(0.03, 0.8 * o["line_h"])
+ and abs(o["cx"] - c["cx"]) < 0.15 and c["first"] - o["last"] <= 1.0 + 1e-6 and o["last"] < c["first"]), None)
+ if prev is not None and _similar(prev["text"], c["text"]) >= 0.8:
+ prev["obs"] += c["obs"]
+ prev["last"] = c["last"]
+ continue
+ keep.append(c)
+ cues = keep
+ out = []
+ for c in cues:
+ obs = c["obs"]
+ if not c.get("reveal"): # the reading seen most often (OCR varies frame to frame)
+ votes: dict[str, list[float]] = {}
+ for o in obs:
+ votes.setdefault(o["text"], []).append(o["conf"])
+ c["text"] = max(votes, key=lambda k: (len(votes[k]), max(votes[k])))
+ c["conf"] = max(votes[c["text"]])
+ boxes = np.array([o["bbox"] for o in obs])
+ centers = boxes[:, :2] + boxes[:, 2:] / 2
+ x0, y0 = boxes[:, 0].min(), boxes[:, 1].min()
+ x1, y1 = (boxes[:, 0] + boxes[:, 2]).max(), (boxes[:, 1] + boxes[:, 3]).max()
+ styles = [s for o in obs for s in o["styles"]]
+ out.append({
+ "t0": c["first"], "t1": round(c["last"] + step, 3), "text": c["text"], "conf": round(c["conf"], 3),
+ "bbox": [round(float(v), 4) for v in (x0, y0, x1 - x0, y1 - y0)],
+ "bbox_median": [round(float(v), 4) for v in np.median(boxes, axis=0)],
+ "line_h": round(float(np.median([o["line_h"] for o in obs])), 4),
+ "n_lines": int(max(o["n_lines"] for o in obs)), "angle": round(float(np.median([o["angle"] for o in obs])), 1),
+ "drift": round(float(np.ptp(centers, axis=0).max()), 4) if len(obs) > 1 else 0.0,
+ "samples": len(obs), "reveal": bool(c.get("reveal")),
+ "style_obs": styles, "first_style_multicolor": bool(obs[0]["styles"] and any(s.get("multicolor") for s in obs[0]["styles"])),
+ })
+ return out
+
+
+# ----------------------------------------------------------------------------- style summary + kind
+
+def merge_style(styles: list[dict]) -> dict:
+ if not styles:
+ return {}
+ def vote(key):
+ vals = [s.get(key) for s in styles if s.get(key)]
+ return max(set(vals), key=vals.count) if vals else None
+ n = len(styles)
+ out = {"fill_name": vote("fill_name"), "fill": vote("fill")}
+ stroked = [s for s in styles if s.get("stroke")]
+ if len(stroked) >= max(1, 0.5 * n):
+ out.update(stroke_name=max({s["stroke_name"] for s in stroked}, key=[s["stroke_name"] for s in stroked].count),
+ stroke=stroked[0]["stroke"], stroke_ratio=round(float(np.median([s["stroke_ratio"] for s in stroked])), 3))
+ boxed = [s for s in styles if s.get("box")]
+ if len(boxed) >= max(1, 0.5 * n):
+ out.update(box=True, box_name=vote("box_name"), box_color=boxed[0]["box_color"])
+ if sum(1 for s in styles if s.get("gradient")) >= max(1, 0.5 * n):
+ out["gradient"] = True
+ multi = [s for s in styles if s.get("multicolor")]
+ if multi and len(multi) >= 0.25 * n:
+ out.update(multicolor=True, highlight_name=max({s["highlight_name"] for s in multi}, key=[s["highlight_name"] for s in multi].count))
+ w = [s["weight"] for s in styles if s.get("weight")]
+ if w:
+ out["weight"] = round(float(np.median(w)), 3)
+ return out
+
+
+def style_text(st: dict, line_h: float | None = None, frame_h: int | None = None) -> str:
+ if not st:
+ return ""
+ parts = [f"{st.get('fill_name', '?')}字"]
+ if st.get("stroke"):
+ parts.append(f"{st['stroke_name']}描边")
+ if st.get("box"):
+ parts.append(f"{st.get('box_name', '')}底框")
+ if st.get("gradient"):
+ parts.append("渐变")
+ if st.get("multicolor"):
+ parts.append(f"关键词{st.get('highlight_name', '')}色高亮")
+ if st.get("weight", 0) > 0.2:
+ parts.append("粗体")
+ if line_h:
+ parts.append(f"字高 {line_h:.1%}" + (f"(约 {line_h * frame_h:.0f}px)" if frame_h else ""))
+ return "、".join(parts)
+
+
+def _decor_score(c: dict) -> tuple[int, list[str]]:
+ st, why = c.get("style") or {}, []
+ if c["line_h"] >= 0.045:
+ why.append("字号大")
+ if abs(c["angle"]) >= 4:
+ why.append("倾斜")
+ if st.get("fill_name") not in (None, "白", "黑", "灰"):
+ why.append(f"{st['fill_name']}色字")
+ if st.get("multicolor") or st.get("gradient"):
+ why.append("多色/渐变")
+ if st.get("stroke") and st.get("stroke_ratio", 0) >= 0.06:
+ why.append("粗描边")
+ if (c.get("anim_in") or {}).get("kind") == "pop":
+ why.append("弹出入场")
+ return len(why), why
+
+
+def classify_cues(cues: list[dict], duration: float) -> None:
+ """Assign each cue a kind (subtitle / huazi / title / label / scene)."""
+ # lanes: cues stacked at the same place one after another
+ lanes: list[list[dict]] = []
+ for c in sorted(cues, key=lambda c: c["t0"]):
+ cy = c["bbox"][1] + c["bbox"][3] / 2
+ for lane in lanes:
+ ref = lane[-1]
+ rcy = ref["bbox"][1] + ref["bbox"][3] / 2
+ # one after another at the same place, same size: not two texts on screen together
+ if (abs(cy - rcy) < max(0.03, 1.2 * ref["line_h"]) and abs(c["line_h"] - ref["line_h"]) < 0.35 * ref["line_h"]
+ and c["t0"] >= ref["t1"] - 0.6):
+ lane.append(c)
+ break
+ else:
+ lanes.append([c])
+ for lane in lanes:
+ changing = len({_norm(c["text"]) for c in lane})
+ med = float(np.median([c["t1"] - c["t0"] for c in lane]))
+ h = float(np.median([c["line_h"] for c in lane]))
+ tilted = float(np.median([abs(c["angle"]) for c in lane])) >= 4
+ # readable lines (kinetic typography flashing words for a fraction of a second is not a subtitle track)
+ is_sub = (changing >= 3 or (changing >= 2 and duration < 15)) and 0.7 <= med <= 7.0 and h < 0.07 and not tilted
+ for c in lane:
+ c["lane"] = lanes.index(lane)
+ c["_sub_lane"] = is_sub
+ c["_lane_texts"] = changing
+ for c in cues:
+ st = c.get("style") or {}
+ score, why = _decor_score(c)
+ cy = c["bbox"][1] + c["bbox"][3] / 2
+ dur = c["t1"] - c["t0"]
+ moving = c["drift"] > 0.04 and c["samples"] >= 2
+ if moving and not (st.get("stroke") or st.get("box")):
+ kind = "scene"
+ why = ["跟着画面移动、没有描边或底框"]
+ elif c.get("_sub_lane") and not (score >= 3 and c["line_h"] >= 0.05):
+ kind = "subtitle"
+ elif cy < 0.3 and (dur >= 0.5 * duration or dur >= 8) and not moving and c.get("_lane_texts", 1) == 1:
+ kind = "title"
+ elif moving or c.get("_lane_texts", 1) >= 2:
+ kind = "label" # a tag that follows an object, or a run of chapter cards / captions at one place
+ elif score >= 2:
+ kind = "huazi"
+ else:
+ kind = "label"
+ c["kind"], c["kind_zh"] = kind, KIND_ZH[kind]
+ c["decor"] = why
+ if moving and kind != "scene":
+ c["follows"] = True # tracked to an object in the picture (label with a leader / tag)
+ c["band"] = _band(cy)
+ c.pop("_sub_lane", None)
+ c.pop("_lane_texts", None)
+
+
+# ----------------------------------------------------------------------------- dense pass
+
+def _sig(roi: np.ndarray) -> np.ndarray:
+ e = cv2.Canny(roi, 60, 160).astype(np.float32)
+ return cv2.resize(e, (64, 12), interpolation=cv2.INTER_AREA).ravel()
+
+
+def _ncc(a: np.ndarray, b: np.ndarray) -> float:
+ a, b = a - a.mean(), b - b.mean()
+ d = float(np.linalg.norm(a) * np.linalg.norm(b))
+ return float(a @ b / d) if d > 1e-6 else 0.0
+
+
+def dense_pass(path: str | Path, info: VideoInfo, cues: list[dict]) -> tuple[np.ndarray, float]:
+ """Decode grey frames at ~10 fps once: keep a small copy of every frame (sticker search) and, for each text
+ cue, the edge signature of its box around its start / end (timing + animation)."""
+ fps = min(DENSE_FPS, max(2.0, DENSE_MAX / max(info.duration, 0.1)))
+ small = []
+ for c in cues:
+ c["_dense"] = []
+ win = 1.0
+ for i, g in enumerate(iter_frames(path, info, DENSE_W, gray=True, fps=fps)):
+ t = i / fps
+ H, W = g.shape
+ small.append(cv2.resize(g, (SMALL_W, max(8, int(round(SMALL_W * H / W)))), interpolation=cv2.INTER_AREA))
+ for c in cues:
+ if not (c["t0"] - win <= t <= c["t1"] + win):
+ continue
+ x, y, w, h = c["bbox"]
+ px, py = 0.03 + 0.15 * w, 0.6 * c["line_h"]
+ X0, Y0 = int(max(0, x - px) * W), int(max(0, y - py) * H)
+ X1, Y1 = int(min(1, x + w + px) * W), int(min(1, y + h + py) * H)
+ roi = g[Y0:Y1, X0:X1]
+ if roi.shape[0] < 4 or roi.shape[1] < 8:
+ continue
+ c["_dense"].append((t, roi.copy()))
+ return np.array(small) if small else np.zeros((0, 8, SMALL_W), np.uint8), 1.0 / fps
+
+
+def _extent(mask: np.ndarray) -> tuple[float, float, float, float]:
+ """(x-extent, y-extent, cx, cy) of the True pixels, as fractions of the mask size."""
+ ys, xs = np.nonzero(mask)
+ if len(xs) < 5:
+ return 0.0, 0.0, 0.5, 0.5
+ x0, x1 = np.percentile(xs, [3, 97])
+ y0, y1 = np.percentile(ys, [3, 97])
+ return (float(x1 - x0) / mask.shape[1], float(y1 - y0) / mask.shape[0],
+ float(xs.mean()) / mask.shape[1], float(ys.mean()) / mask.shape[0])
+
+
+def refine_cue(c: dict, step: float, dstep: float, prev_last: float | None, next_first: float | None) -> None:
+ """Snap start / end to the dense frames and read the entrance / exit animation.
+ prev_last / next_first: when the previous cue at the same place was last seen and the next one first seen
+ (OCR times). Their look in this box is the competitor: a frame belongs to this cue only if it matches this
+ cue better than the neighbour."""
+ dense = c.pop("_dense", [])
+ if len(dense) < 3:
+ return
+ times = np.array([t for t, _ in dense])
+ rois = [r for _, r in dense]
+ shape = rois[len(rois) // 2].shape
+ rois = [r if r.shape == shape else cv2.resize(r, (shape[1], shape[0])) for r in rois]
+ a, b = c["t0"], c["t1"] - step # first / last OCR sighting
+ mid = [i for i, t in enumerate(times) if a - 1e-6 <= t <= b + 1e-6] or [int(np.argmin(np.abs(times - (a + b) / 2)))]
+ if len(mid) > 4:
+ mid = mid[len(mid) // 4:len(mid) - len(mid) // 4] or mid
+ sigs = [_sig(r) for r in rois]
+ ref = np.mean([sigs[i] for i in mid], axis=0)
+ pres = np.array([_ncc(s_, ref) for s_ in sigs])
+ plateau = float(np.median(pres[mid]))
+ comp = np.zeros(len(times))
+ for t_ref, side in ((prev_last, -1), (next_first, 1)):
+ if t_ref is None:
+ continue
+ # only frames on the neighbour's side of its sighting (it was surely on screen there)
+ near = [i for i, t in enumerate(times) if 0 <= (t - t_ref) * side <= 0.2]
+ if near:
+ r2 = np.mean([sigs[i] for i in near], axis=0)
+ comp = np.maximum(comp, [_ncc(s_, r2) for s_ in sigs])
+ vis = (pres >= max(0.45, 0.6 * plateau)) & (pres > comp + 0.08)
+ lo = prev_last if prev_last is not None else -1.0
+ hi = next_first if next_first is not None else 1e9
+ i0 = int(np.argmin(np.abs(times - a)))
+ while i0 > 0 and vis[i0 - 1] and times[i0 - 1] > lo + 1e-6:
+ i0 -= 1
+ i1 = int(np.argmin(np.abs(times - b)))
+ while i1 < len(times) - 1 and vis[i1 + 1] and times[i1 + 1] < hi - 1e-6:
+ i1 += 1
+ if i1 < i0:
+ return
+ c["t0"], c["t1"] = round(float(times[i0]), 3), round(float(times[i1] + dstep), 3)
+ c["timing"] = "dense"
+ ref_i = mid[len(mid) // 2]
+
+ def extents(i: int, bg_i: int):
+ bg = rois[bg_i].astype(np.int16)
+ m = np.abs(rois[i].astype(np.int16) - bg) > 22
+ return _extent(m), float(m.mean())
+
+ def animation(edge: int, outside: int, inward: int) -> str | None:
+ """edge: first (last) visible frame; outside: the frame before (after) it; inward: +1 / -1."""
+ if outside < 0 or outside >= len(times):
+ return None
+ if comp[outside] > 0.5 and comp[outside] >= pres[outside]:
+ # the neighbour was showing right before: a swap at the same place. Only "instant or not" is readable.
+ return "cut" if pres[edge] >= 0.85 * plateau else None
+ if pres[edge] >= 0.85 * plateau and pres[outside] < 0.35:
+ return "cut"
+ (rx, ry, rcx, rcy), rd = extents(ref_i, outside)
+ if rx < 0.05 or rd < 1e-4:
+ return None
+ frames = [edge + inward * j for j in range(4) if 0 <= edge + inward * j < len(times)
+ and abs(times[edge + inward * j] - times[edge]) <= 0.35]
+ first = frames[0]
+ (ex, ey, cx, cy), d = extents(first, outside)
+ xr, yr, dens = ex / rx, ey / max(ry, 1e-3), d / rd
+ if c.get("reveal") and inward > 0:
+ return "reveal"
+ if xr < 0.8 and yr < 0.8 and abs(xr - yr) < 0.3:
+ return "pop"
+ if inward > 0 and xr < 0.65 and yr > 0.8:
+ return "reveal"
+ if abs(cx - rcx) > 0.12 or abs(cy - rcy) > 0.25:
+ return "slide"
+ if dens < 0.6:
+ return "fade"
+ return "cut"
+
+ k_in = animation(i0, i0 - 1, 1)
+ if k_in:
+ c["anim_in"] = {"kind": k_in, "kind_zh": ANIM_ZH[k_in]}
+ k_out = animation(i1, i1 + 1, -1)
+ if k_out:
+ k_out = {"cut": "cut_out", "pop": "pop_out", "fade": "fade_out", "slide": "slide_out", "reveal": "cut_out"}[k_out]
+ c["anim_out"] = {"kind": k_out, "kind_zh": ANIM_ZH[k_out]}
+ # mid-cue motion with the same words: a keyword bounce / colour change / wobble
+ inside = pres[i0 + 1:i1]
+ if len(inside) >= 6 and float(np.percentile(inside, 10)) < 0.6 * plateau:
+ c["mid_motion"] = True
+
+
+# ----------------------------------------------------------------------------- stickers
+
+def _cells(frames: np.ndarray) -> np.ndarray:
+ n, h, w = frames.shape
+ gh, gw = h // CELL, w // CELL
+ return frames[:, :gh * CELL, :gw * CELL].reshape(n, gh, CELL, gw, CELL).astype(np.float32).mean(axis=(2, 4))
+
+
+def find_stickers(small: np.ndarray, dstep: float, cuts: list[float], cues: list[dict], duration: float) -> list[dict]:
+ """Overlay pictures (stickers, GIFs, emoji, picture-in-picture) from the small grey frames.
+ Cue 1: mid-shot, a compact block changes at once while the rest of the frame is quiet, and the change
+ stays (something was put there). Paired with a later change that restores the block = it left.
+ Cue 2: a block that survives a cut while everything around it changes.
+ Kept strict on purpose: in animation / motion graphics things appear all the time; a missed sticker costs
+ less than a report full of invented ones."""
+ n = len(small)
+ if n < 8:
+ return []
+ C = _cells(small)
+ gh, gw = C.shape[1:]
+ D = np.abs(np.diff(small[:, :gh * CELL, :gw * CELL].astype(np.int16), axis=0))
+ Dc = D.reshape(n - 1, gh, CELL, gw, CELL).mean(axis=(2, 4)).astype(np.float32)
+ cut_idx = sorted({int(round(c / dstep)) for c in cuts if 0 < c < duration})
+ near_cut = np.zeros(n - 1, bool)
+ for k in cut_idx:
+ near_cut[max(0, k - 3):min(n - 1, k + 3)] = True
+ total = gh * gw
+ Dm = _compensated_change(small, gh, gw) # change after removing camera motion (pan / zoom)
+ gq = np.median(Dm.reshape(n - 1, -1), axis=1)
+
+ def shot_bounds(i):
+ return max([k for k in cut_idx if k <= i], default=0), min([k for k in cut_idx if k > i], default=n)
+
+ def region(i, box):
+ x, y, w, h = box
+ return C[min(max(i, 0), n - 1), y:y + h, x:x + w]
+
+ def ring_of(box, grow=2):
+ x, y, w, h = box
+ m = np.zeros((gh, gw), bool)
+ m[max(0, y - grow):y + h + grow, max(0, x - grow):x + w + grow] = True
+ m[y:y + h, x:x + w] = False
+ return m
+
+ onsets = []
+ for i in range(1, n - 1):
+ if near_cut[i] or gq[i] > 2.0:
+ continue
+ spike = Dm[i] > np.maximum(14.0, 4 * gq[i] + 6)
+ if spike.sum() < 2 or spike.mean() > 0.4:
+ continue
+ nlab, lab, stats, _ = cv2.connectedComponentsWithStats(spike.astype(np.uint8), connectivity=8)
+ for j in range(1, nlab):
+ x, y, w, h, area = stats[j]
+ box = (x, y, w, h)
+ if area < max(3, 0.006 * total) or area > 0.4 * total or area / float(w * h) < 0.4:
+ continue
+ if spike.sum() - area > 0.02 * total:
+ continue # other things change at the same moment
+ inside = float(Dm[i][lab == j].mean())
+ ring = ring_of(box)
+ if ring.any() and float(Dm[i][ring].mean()) > 0.25 * inside:
+ continue # soft edge: motion, not a pasted layer
+ before = Dm[max(0, i - 10):i - 1, y:y + h, x:x + w]
+ if before.size and float(before.mean()) * 4 > inside:
+ continue # the block was already busy
+ onsets.append({"i": i, "box": box})
+ merged: list[dict] = []
+ for o in onsets:
+ for m in merged:
+ if o["i"] - m["i1"] <= 3 and _iou(o["box"], m["box"]) > 0.3:
+ m["i1"], m["box"] = o["i"], _union(m["box"], o["box"])
+ break
+ else:
+ merged.append({"i0": o["i"], "i1": o["i"], "box": o["box"]})
+ found, used = [], set()
+ for a_i, m in enumerate(merged):
+ if a_i in used:
+ continue
+ sa, sb = shot_bounds(m["i0"])
+ before, after, later = m["i0"] - 2, m["i1"] + 3, m["i1"] + 8
+ if before < sa or later >= sb:
+ continue
+ ref = region(before, m["box"])
+ if float(np.abs(region(after, m["box"]) - ref).mean()) < 15 or float(np.abs(region(later, m["box"]) - ref).mean()) < 15:
+ continue # nothing stayed: a flash, a blink, a passing object
+ end_i, paired = sb - 1, False
+ for b_i in range(a_i + 1, len(merged)):
+ e = merged[b_i]
+ if e["i0"] >= sb:
+ break
+ if _iou(e["box"], m["box"]) > 0.45 and e["i0"] > m["i1"] + 3 and e["i1"] + 3 < sb:
+ # the same block changes at once again and the place looks like it did before the block came
+ # (compared as a texture histogram, so a background that panned on meanwhile still matches;
+ # an outfit swap or a new object does not)
+ h_before, h_during, h_after = (_hist(small[i_], m["box"]) for i_ in (before, e["i0"] - 2, e["i1"] + 3))
+ d_bd, d_ba = float(np.abs(h_during - h_before).sum()), float(np.abs(h_after - h_before).sum())
+ if d_bd > 0.3 and d_ba < 0.5 * d_bd:
+ end_i, paired = e["i0"], True
+ used.add(b_i)
+ break
+ st = _sticker(m["box"], m["i0"], end_i, paired, False, small, Dc, dstep, gh, gw)
+ # without the matching exit, only shapes that do not occur naturally: a looping GIF, a block that pops in
+ # and then holds still, or a hard-edged rectangle of video (picture-in-picture)
+ if paired or st["looping"] or st["kind"] == "pip" or st["activity"] < 1.5:
+ found.append(st)
+ for k in cut_idx:
+ if k < 4 or k + 4 >= n:
+ continue
+ pairs = [np.abs(C[b_] - C[a_]) for a_ in (k - 2, k - 1) for b_ in (k, k + 1)]
+ d = np.min(pairs, axis=0)
+ glob = float(np.median(np.max(pairs, axis=0)))
+ if glob < 30:
+ continue
+ tex = small[k][:gh * CELL, :gw * CELL].reshape(gh, CELL, gw, CELL).std(axis=(1, 3)) > 8
+ unchanged = d < max(5.0, 0.15 * glob)
+ if float(unchanged.mean()) > 0.15:
+ continue # a jump cut on the same set: the background carries over, so "unchanged" proves nothing
+ surv = unchanged & tex
+ stay = np.abs(C[min(n - 1, k + 3)] - C[k - 3]) < max(8.0, 0.2 * glob)
+ surv &= stay
+ nlab, lab, stats, _ = cv2.connectedComponentsWithStats(surv.astype(np.uint8), connectivity=8)
+ for j in range(1, nlab):
+ x, y, w, h, area = stats[j]
+ box = (x, y, w, h)
+ if area < max(3, 0.006 * total) or area > 0.3 * total or area / float(w * h) < 0.5:
+ continue
+ if w > 0.6 * gw or h > 0.6 * gh:
+ continue # a band across the frame (letterbox, empty background), not a sticker
+ patch = small[k][y * CELL:(y + h) * CELL, x * CELL:(x + w) * CELL]
+ if float((cv2.Canny(patch, 60, 160) > 0).mean()) < 0.04:
+ continue # nothing drawn there: an empty patch of background that happened not to change
+ ring = ring_of(box)
+ if ring.any() and float(surv[ring].mean()) > 0.2:
+ continue # the area around survived too: similar shots, not a layer on top
+ hit = [s_ for s_ in found if _iou(box, s_["_cells"]) > 0.4 and s_["_i0"] <= k <= s_["_i1"] + 2]
+ for s_ in hit:
+ s_["crosses_cut"] = True
+ if not hit:
+ sa, _ = shot_bounds(k - 1)
+ _, sb = shot_bounds(k)
+ found.append(_sticker(box, sa, sb - 1, False, True, small, Dc, dstep, gh, gw))
+ found += _static_blocks(small, Dc, dstep, cut_idx, found, gh, gw)
+ out = []
+ for s_ in found:
+ bx = s_["bbox"]
+ x_, y_, w_, h_ = s_["_cells"]
+ # slivers along the frame edge are motion / crop artefacts, not something pasted on
+ if min(w_, h_) < 2 or (x_ == 0 or y_ == 0 or x_ + w_ >= gw or y_ + h_ >= gh) and min(w_ / gw, h_ / gh) < 0.15:
+ continue
+ covered = 0.0
+ for c in cues:
+ if c["t0"] - 0.4 <= s_["t1"] and s_["t0"] <= c["t1"] + 0.4:
+ covered = max(covered, _overlap_frac(bx, c["bbox"]), _overlap_frac(c["bbox"], bx) * 0.8)
+ if covered >= 0.3:
+ continue # text and its own animation / box
+ if s_["t1"] - s_["t0"] >= 0.8 * duration and not s_["animated"]:
+ continue # a watermark / layout skin: reported as a static overlay elsewhere
+ out.append(s_)
+ out = _dedupe_stickers(out)
+ for k, s_ in enumerate(out, 1):
+ s_["id"] = f"sticker_{k:02d}"
+ for key in ("_cells", "_i0", "_i1"):
+ s_.pop(key, None)
+ return out
+
+
+def _static_blocks(small: np.ndarray, Dc: np.ndarray, dstep: float, cut_idx: list[int], found: list[dict], gh: int, gw: int) -> list[dict]:
+ """A pasted picture on moving footage (an app icon, a screenshot card over a talking head): a block with
+ content that holds still while everything around it moves, floating inside the frame."""
+ n = len(small)
+ win = max(6, int(round(1.0 / dstep)))
+ total = gh * gw
+ hits: list[dict] = []
+ for a in range(0, n - 1 - win, max(1, win // 2)):
+ if any(a < k <= a + win for k in cut_idx):
+ continue
+ act = Dc[a:a + win].mean(axis=0)
+ mid = small[a + win // 2][:gh * CELL, :gw * CELL]
+ tex = mid.reshape(gh, CELL, gw, CELL).std(axis=(1, 3)) > 6
+ still = (act < 1.2) & tex
+ nlab, lab, stats, _ = cv2.connectedComponentsWithStats(still.astype(np.uint8), connectivity=8)
+ for j in range(1, nlab):
+ x, y, w, h, area = stats[j]
+ if area < max(4, 0.01 * total) or area > 0.4 * total or area / float(w * h) < 0.6:
+ continue
+ if x == 0 or y == 0 or x + w >= gw or y + h >= gh:
+ continue # touches the frame edge: background / letterbox
+ ring = np.zeros((gh, gw), bool)
+ ring[max(0, y - 1):y + h + 1, max(0, x - 1):x + w + 1] = True
+ ring[y:y + h, x:x + w] = False
+ if float(act[ring].mean()) < 4.0 or float((act[ring] > 2.0).mean()) < 0.6:
+ continue # the surroundings are still too: a static scene, not a layer
+ patch = mid[y * CELL:(y + h) * CELL, x * CELL:(x + w) * CELL]
+ if float((cv2.Canny(patch, 60, 160) > 0).mean()) < 0.04:
+ continue
+ hits.append({"a": a, "b": a + win, "box": (x, y, w, h)})
+ out: list[dict] = []
+ for h_ in hits:
+ for o in out:
+ if _iou(h_["box"], o["box"]) > 0.4 and h_["a"] <= o["b"] + 1:
+ o["b"] = max(o["b"], h_["b"])
+ o["n"] += 1
+ break
+ else:
+ out.append(dict(h_, n=1))
+ res = []
+ for o in out:
+ if o["n"] < 2:
+ continue # held for at least ~1.5 s
+ if any(_iou(o["box"], f["_cells"]) > 0.4 and f["_i0"] <= o["b"] and o["a"] <= f["_i1"] for f in found):
+ continue
+ st = _sticker(o["box"], o["a"], o["b"], False, False, small, Dc, dstep, gh, gw)
+ st.update(kind="static_sticker", kind_zh=STICKER_ZH["static_sticker"], appears_mid_shot=True, confidence="medium",
+ evidence="周围画面在动、这一块不动且边界清楚")
+ res.append(st)
+ return res
+
+
+def _hist(frame: np.ndarray, box, bins: int = 16) -> np.ndarray:
+ x, y, w, h = box
+ patch = frame[y * CELL:(y + h) * CELL, x * CELL:(x + w) * CELL]
+ hst = np.bincount((patch // (256 // bins)).ravel(), minlength=bins).astype(np.float32)
+ return hst / max(1.0, hst.sum())
+
+
+def _compensated_change(small: np.ndarray, gh: int, gw: int) -> np.ndarray:
+ """Per-cell change between consecutive frames after warping the earlier frame by the camera's motion
+ (a similarity transform fitted to tracked corners). Falls back to the plain difference when tracking fails."""
+ n = len(small)
+ out = np.zeros((n - 1, gh, gw), np.float32)
+ for i in range(n - 1):
+ a, b = small[i], small[i + 1]
+ warped = a
+ pts = cv2.goodFeaturesToTrack(a, maxCorners=150, qualityLevel=0.01, minDistance=5, blockSize=5)
+ if pts is not None and len(pts) >= 12:
+ nxt, st, _ = cv2.calcOpticalFlowPyrLK(a, b, pts, None, winSize=(15, 15), maxLevel=2)
+ ok = st.ravel() == 1 if st is not None else np.zeros(len(pts), bool)
+ if ok.sum() >= 10:
+ M, inl = cv2.estimateAffinePartial2D(pts.reshape(-1, 2)[ok], nxt.reshape(-1, 2)[ok], method=cv2.RANSAC,
+ ransacReprojThreshold=1.0)
+ moved = M is not None and (abs(M[0, 2]) > 0.2 or abs(M[1, 2]) > 0.2 or abs(M[0, 0] - 1) > 0.002)
+ if moved and inl is not None and inl.mean() > 0.5:
+ warped = cv2.warpAffine(a, M, (a.shape[1], a.shape[0]), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
+ d = np.abs(b[:gh * CELL, :gw * CELL].astype(np.int16) - warped[:gh * CELL, :gw * CELL].astype(np.int16))
+ out[i] = d.reshape(gh, CELL, gw, CELL).mean(axis=(1, 3))
+ return out
+
+
+def _sticker(box, i0, i1, paired, crosses, small, Dc, dstep, gh, gw) -> dict:
+ x, y, w, h = box
+ n = len(small)
+ i1 = min(i1, n - 1)
+ seg = Dc[i0 + 1:max(i0 + 2, i1 - 1), y:y + h, x:x + w]
+ activity = float(seg.mean()) if seg.size else 0.0
+ animated = activity > 2.5
+ period = None
+ if animated and i1 - i0 > 12:
+ # the middle of the block only (its corners can show the moving background around a round sticker)
+ px, py = max(1, int(w * CELL * 0.2)), max(1, int(h * CELL * 0.2))
+ X = small[i0 + 2:i1 - 1, y * CELL + py:(y + h) * CELL - py, x * CELL + px:(x + w) * CELL - px].astype(np.float32)
+ m = len(X)
+ r = [float(np.abs(X[L:] - X[:-L]).mean()) for L in range(1, min(60, m - 2))]
+ # a loop: some lag brings the picture back much closer than the shorter lags before it
+ for L in range(3, len(r) // 2 + 1): # 2L must still be a measured lag
+ peak = max(r[:L - 1])
+ # a real animation (not sensor / generator shimmer) that comes back at L and again at 2L
+ if peak > 6.0 and r[L - 1] < 0.45 * peak and r[2 * L - 1] < 0.45 * peak:
+ period = round(L * dstep, 2)
+ break
+ # a rectangle of video content (straight edges, continuously changing, not looping): picture-in-picture
+ rect = False
+ if animated and period is None and w >= 4 and h >= 4:
+ # straight, hard borders on all four sides of the block
+ f = small[(i0 + i1) // 2].astype(np.float32)
+ gx, gy = np.abs(cv2.Sobel(f, cv2.CV_32F, 1, 0)), np.abs(cv2.Sobel(f, cv2.CV_32F, 0, 1))
+ X0, Y0, X1, Y1 = x * CELL, y * CELL, (x + w) * CELL - 1, (y + h) * CELL - 1
+
+ def edge_strength(vals: np.ndarray) -> float:
+ return float(np.median(vals)) if vals.size else 0.0
+
+ sides = []
+ for xx in (X0, X1):
+ sides.append(max(edge_strength(gx[Y0:Y1, max(0, xx - d)]) for d in (-1, 0, 1) if 0 <= xx - d < f.shape[1]))
+ for yy in (Y0, Y1):
+ sides.append(max(edge_strength(gy[max(0, yy - d), X0:X1]) for d in (-1, 0, 1) if 0 <= yy - d < f.shape[0]))
+ interior = float(np.median(np.hypot(gx, gy)[Y0 + 2:Y1 - 2, X0 + 2:X1 - 2])) if Y1 - Y0 > 6 and X1 - X0 > 6 else 0.0
+ rect = min(sides) > max(20.0, 2.5 * interior)
+ kind = "pip" if rect and w * h >= 0.04 * gh * gw else ("animated_sticker" if animated else "static_sticker")
+ # measured on real footage (eval/articles, koubo): an appear / disappear pair over moving live or AI picture is
+ # usually the picture itself (an arm, an outfit swap); only a looping GIF or a block that holds perfectly still
+ # inside is trusted without a look
+ conf = "medium" if (crosses or (paired and (period is not None or not animated))) else "low"
+ activity, x, y, w, h = float(activity), int(x), int(y), int(w), int(h)
+ t0, t1 = round((i0 + 1) * dstep, 2), round(i1 * dstep, 2)
+ return {"kind": kind, "kind_zh": STICKER_ZH[kind], "t0": t0, "t1": t1,
+ "bbox": [round(float(x) / gw, 3), round(float(y) / gh, 3), round(float(w) / gw, 3), round(float(h) / gh, 3)],
+ "animated": bool(animated), "loop_period_s": period, "looping": period is not None, "activity": round(activity, 1),
+ "appears_mid_shot": not crosses or paired, "disappears_mid_shot": paired, "crosses_cut": crosses,
+ "confidence": conf, "_cells": box, "_i0": i0, "_i1": i1}
+
+
+def _iou(a, b) -> float:
+ ax, ay, aw, ah = a
+ bx, by, bw, bh = b
+ ix = max(0, min(ax + aw, bx + bw) - max(ax, bx))
+ iy = max(0, min(ay + ah, by + bh) - max(ay, by))
+ inter = ix * iy
+ return inter / float(aw * ah + bw * bh - inter) if inter else 0.0
+
+
+def _union(a, b):
+ x0, y0 = min(a[0], b[0]), min(a[1], b[1])
+ x1, y1 = max(a[0] + a[2], b[0] + b[2]), max(a[1] + a[3], b[1] + b[3])
+ return (x0, y0, x1 - x0, y1 - y0)
+
+
+def _overlap_frac(a, b) -> float:
+ """Share of box a covered by box b (0-1 coordinates)."""
+ ix = max(0.0, min(a[0] + a[2], b[0] + b[2]) - max(a[0], b[0]))
+ iy = max(0.0, min(a[1] + a[3], b[1] + b[3]) - max(a[1], b[1]))
+ return ix * iy / max(1e-6, a[2] * a[3])
+
+
+def _dedupe_stickers(items: list[dict]) -> list[dict]:
+ items = sorted(items, key=lambda s: (s["t0"], -s["bbox"][2] * s["bbox"][3]))
+ keep: list[dict] = []
+ for s in items:
+ dup = False
+ for k in keep:
+ if _iou(s["bbox"], k["bbox"]) > 0.5 and s["t0"] <= k["t1"] and k["t0"] <= s["t1"]:
+ k["t0"], k["t1"] = min(k["t0"], s["t0"]), max(k["t1"], s["t1"])
+ k["crosses_cut"] = k["crosses_cut"] or s["crosses_cut"]
+ if s["confidence"] == "medium":
+ k["confidence"] = "medium"
+ dup = True
+ break
+ if not dup:
+ keep.append(s)
+ return keep
+
+
+# ----------------------------------------------------------------------------- SFX alignment
+
+def visual_events(cues: list[dict], stickers: list[dict], cuts: list[float]) -> list[dict]:
+ ev = []
+ for c in cues:
+ if c["kind"] == "scene":
+ continue
+ what = f"{c['kind_zh']}「{c['text'].replace('/', ' ')[:16]}」出现"
+ ev.append({"t": c["t0"], "type": f"{c['kind']}_in", "what": what, "ref": c["id"]})
+ if c.get("mid_motion"):
+ ev.append({"t": None, "type": "mid", "ref": c["id"]})
+ for s in stickers:
+ ev.append({"t": s["t0"], "type": "sticker_in", "what": f"{s['kind_zh']}出现", "ref": s["id"]})
+ if s.get("disappears_mid_shot"):
+ ev.append({"t": s["t1"], "type": "sticker_out", "what": f"{s['kind_zh']}消失", "ref": s["id"]})
+ for t in cuts:
+ ev.append({"t": t, "type": "cut", "what": "切镜", "ref": None})
+ return [e for e in ev if e["t"] is not None]
+
+
+SFX_TOL = 0.2
+
+
+def align_sfx(sfx: list[dict], events: list[dict]) -> dict:
+ """Which on-screen event each sound effect lands on, and which pops / stickers carry a sound."""
+ times = np.array([e["t"] for e in events]) if events else np.zeros(0)
+ counts: dict[str, int] = {}
+ for s in sfx:
+ t = float(s.get("t", -9))
+ if not len(times):
+ break
+ d = np.abs(times - t)
+ # prefer a text / sticker entrance over a cut when both are in reach
+ order = sorted(range(len(events)), key=lambda i: (d[i] > SFX_TOL, events[i]["type"] == "cut", d[i]))
+ i = order[0]
+ if d[i] <= SFX_TOL:
+ s["on"] = {"type": events[i]["type"], "what": events[i]["what"], "dt": round(float(events[i]["t"] - t), 3), "ref": events[i]["ref"]}
+ counts[events[i]["type"]] = counts.get(events[i]["type"], 0) + 1
+ st = np.array([float(s.get("t", -9)) for s in sfx]) if sfx else np.zeros(0)
+ voiced = {}
+ for e in events:
+ if e["type"] == "cut":
+ continue
+ has = bool(len(st) and np.min(np.abs(st - e["t"])) <= SFX_TOL)
+ k = e["type"]
+ a, b = voiced.get(k, (0, 0))
+ voiced[k] = (a + has, b + 1)
+ return {"sfx_on": counts, "events_with_sfx": {k: {"with_sfx": a, "total": b} for k, (a, b) in voiced.items()}}
+
+
+def anchored_sfx(path: str | Path, events: list[dict], known: list[dict]) -> list[dict]:
+ """Extra SFX candidates: a sharp transient right on a text pop / sticker entrance (not cuts: music hits
+ land there too). Editors put a pop / ding on these moments far more often than chance."""
+ from .audio import onset_envelope, sfx_type
+
+ env = onset_envelope(str(path))
+ if env is None:
+ return []
+ perc, frame_db, S, freqs, hop_t = env
+ if not len(perc):
+ return []
+ peak_db = float(np.percentile(frame_db, 99))
+ w2 = int(round(1.0 / hop_t))
+ known_t = np.array([float(k.get("t", -9)) for k in known]) if known else np.zeros(0)
+ out = []
+ for e in events:
+ if e["type"] == "cut":
+ continue
+ a, b = int((e["t"] - 0.08) / hop_t), int((e["t"] + 0.15) / hop_t)
+ if a < 1 or b >= len(perc):
+ continue
+ c = a + int(np.argmax(perc[a:b]))
+ loc = float(np.percentile(perc[max(0, c - w2):c + w2], 90)) + 1e-6
+ strength = float(perc[c]) / loc
+ if strength < 1.6 or frame_db[c] < peak_db - 30:
+ continue
+ t = round(c * hop_t, 3)
+ if len(known_t) and np.min(np.abs(known_t - t)) < 0.12:
+ continue
+ if any(abs(o["t"] - t) < 0.12 for o in out):
+ continue
+ kind, info = sfx_type(S, freqs, frame_db, c, hop_t)
+ out.append({"t": t, "type": kind, **info, "strength": round(strength, 1), "source": "deterministic_anchored",
+ "confidence": "medium", "anchor": e["what"]})
+ return out
+
+
+# ----------------------------------------------------------------------------- top level
+
+def analyze(path: str | Path, info: VideoInfo, cuts: list[float], out_dir: Path | None = None, ocr: bool = True) -> dict:
+ """Whole-video packaging pass: text cues (subtitles / 花字 / titles / labels) and stickers."""
+ items, step = ocr_pass(path, info) if ocr else ([], 0.0)
+ cues = build_cues(items, step) if items else []
+ for k, c in enumerate(sorted(cues, key=lambda c: (c["t0"], c["bbox"][1])), 1):
+ c["id"] = f"text_{k:03d}"
+ small, dstep = dense_pass(path, info, cues)
+ for c in cues:
+ c["_first"], c["_last"] = c["t0"], c["t1"] - step # OCR sightings, before refinement moves t0 / t1
+ # refine timing; a cue cannot extend into its neighbours at the same place
+ for c in cues:
+ cy = c["bbox"][1] + c["bbox"][3] / 2
+ same = [o for o in cues if o is not c and abs((o["bbox"][1] + o["bbox"][3] / 2) - cy) < max(0.03, c["line_h"])
+ and abs(o["bbox"][0] + o["bbox"][2] / 2 - c["bbox"][0] - c["bbox"][2] / 2) < 0.2]
+ prev_last = max([o["_last"] for o in same if o["_first"] < c["_first"]], default=None)
+ next_first = min([o["_first"] for o in same if o["_first"] > c["_first"]], default=None)
+ refine_cue(c, step, dstep, prev_last, next_first)
+ for c in cues:
+ c.pop("_dense", None)
+ c.pop("_last", None)
+ c.pop("_first", None)
+ c["style"] = merge_style(c.pop("style_obs"))
+ if c["style"].get("multicolor") and not c.pop("first_style_multicolor", False) and c["samples"] >= 2:
+ c["style"]["highlight_timing"] = "spoken" # colour arrives later: keyword lights up when it is said
+ c.pop("first_style_multicolor", None)
+ classify_cues(cues, info.duration)
+ # subtitles in one lane share a template: per-line fill / stroke readings that disagree with the lane are noise
+ # (a keyword bouncing in its highlight colour, a dark frame); keyword highlight stays per line
+ lanes: dict[int, list[dict]] = {}
+ for c in cues:
+ if c["kind"] == "subtitle":
+ lanes.setdefault(c["lane"], []).append(c)
+ for lane in lanes.values():
+ for key, keys in (("fill_name", ("fill_name", "fill")), ("stroke_name", ("stroke_name", "stroke", "stroke_ratio"))):
+ vals = [c["style"].get(key) for c in lane]
+ top_ = max(set(vals), key=vals.count)
+ if vals.count(top_) >= 0.6 * len(vals):
+ donor = next(c["style"] for c in lane if c["style"].get(key) == top_)
+ for c in lane:
+ for k2 in keys:
+ if donor.get(k2) is None:
+ c["style"].pop(k2, None)
+ else:
+ c["style"][k2] = donor[k2]
+ for c in cues:
+ c["style_zh"] = style_text(c["style"], c["line_h"], info.height if info.rotation not in (90, 270) else info.width)
+ stickers = find_stickers(small, dstep, cuts, cues, info.duration) if len(small) else []
+ if out_dir is not None and stickers:
+ d = Path(out_dir) / "packaging"
+ d.mkdir(parents=True, exist_ok=True)
+ for s in stickers:
+ try:
+ p = extract_frame(path, (s["t0"] + s["t1"]) / 2, d / f"{s['id']}_frame.jpg", width=720)
+ img = cv2.imread(str(p))
+ if img is not None:
+ H, W = img.shape[:2]
+ x, y, w, h = s["bbox"]
+ crop = img[int(y * H):int((y + h) * H), int(x * W):int((x + w) * W)]
+ if crop.size:
+ cv2.imwrite(str(d / f"{s['id']}.jpg"), crop)
+ s["image"] = f"packaging/{s['id']}.jpg"
+ p.unlink(missing_ok=True)
+ except Exception as exc: # pragma: no cover
+ LOG.debug("sticker crop failed: %s", exc)
+ kinds: dict[str, int] = {}
+ for c in cues:
+ kinds[c["kind"]] = kinds.get(c["kind"], 0) + 1
+ return {"text_cues": cues, "stickers": stickers, "ocr": {"step_s": round(step, 3), "frames": int(round(info.duration / step)) if step else 0,
+ "dense_step_s": round(dstep, 3)},
+ "counts": {"text": kinds, "stickers": len(stickers)}}
+
+
+# ----------------------------------------------------------------------------- exports
+
+def _ts(t: float, sep: str = ",") -> str:
+ t = max(0.0, t)
+ h, rem = divmod(t, 3600)
+ m, s = divmod(rem, 60)
+ return f"{int(h):02d}:{int(m):02d}:{int(s):02d}{sep}{int(round((s % 1) * 1000)) % 1000:03d}"
+
+
+def to_srt(cues: list[dict], kinds=("subtitle",)) -> str:
+ rows = [c for c in sorted(cues, key=lambda c: c["t0"]) if c["kind"] in kinds]
+ return "\n".join(f"{i}\n{_ts(c['t0'])} --> {_ts(c['t1'])}\n{c['text'].replace('/', chr(10))}\n" for i, c in enumerate(rows, 1))
+
+
+def _ass_color(hexrgb: str | None, default: str) -> str:
+ h = (hexrgb or default).lstrip("#")
+ r, g, b = h[0:2], h[2:4], h[4:6]
+ return f"&H00{b}{g}{r}".upper()
+
+
+def to_ass(cues: list[dict], width: int, height: int) -> str:
+ """Subtitles + 花字 + titles + labels with their measured colours, size and position (\\pos), plus a \\fad / \\t
+ pop for the measured entrance. Fonts are not measured: replace "Sans" with the real font."""
+ head = ["[Script Info]", "ScriptType: v4.00+", f"PlayResX: {width}", f"PlayResY: {height}", "",
+ "[V4+ Styles]",
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, "
+ "StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding"]
+ styles, events = {}, []
+ for c in sorted(cues, key=lambda c: c["t0"]):
+ if c["kind"] == "scene":
+ continue
+ st = c.get("style") or {}
+ size = max(12, int(round(c["line_h"] * height * 0.95)))
+ name = f"{c['kind']}_{len(styles) + 1}"
+ box = st.get("box")
+ outline = max(0, int(round(st.get("stroke_ratio", 0.0) * c["line_h"] * height))) if st.get("stroke") else 0
+ styles[name] = (f"Style: {name},Sans,{size},{_ass_color(st.get('fill'), '#ffffff')},&H0000FFFF,"
+ f"{_ass_color(st.get('box_color') if box else st.get('stroke'), '#000000')},{_ass_color(st.get('box_color'), '#000000')},"
+ f"{-1 if st.get('weight', 0) > 0.2 else 0},0,0,0,100,100,0,{-c['angle']:.0f},{3 if box else 1},{outline if not box else 8},0,5,0,0,0,1")
+ x, y, w, h = c["bbox"]
+ tags = f"\\pos({(x + w / 2) * width:.0f},{(y + h / 2) * height:.0f})"
+ ak = (c.get("anim_in") or {}).get("kind")
+ if ak == "pop":
+ tags += "\\fscx60\\fscy60\\t(0,180,\\fscx110\\fscy110)\\t(180,260,\\fscx100\\fscy100)"
+ elif ak == "fade" or (c.get("anim_out") or {}).get("kind") == "fade_out":
+ tags += "\\fad(200,200)"
+ text = c["text"].replace("/", "\\N")
+ events.append(f"Dialogue: {0 if c['kind'] == 'subtitle' else 1},{_ts(c['t0'], '.')[1:-1]},{_ts(c['t1'], '.')[1:-1]},{name},,0,0,0,,{{{tags}}}{text}")
+ return "\n".join(head + list(styles.values()) + ["", "[Events]",
+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"] + events) + "\n"
+
+
+def summary_lines(pack: dict, sfx_align: dict | None = None) -> list[str]:
+ cues = pack.get("text_cues", [])
+ L = []
+ subs = [c for c in cues if c["kind"] == "subtitle"]
+ if subs:
+ st = merge_style([c["style"] for c in subs if c.get("style")])
+ anim = {}
+ for c in subs:
+ k = (c.get("anim_in") or {}).get("kind_zh")
+ if k:
+ anim[k] = anim.get(k, 0) + 1
+ lines = max(c["n_lines"] for c in subs)
+ bands = {{"top": "顶部", "middle": "中部", "bottom": "底部"}.get(c["band"], c["band"]) for c in subs}
+ L.append(f"字幕 {len(subs)} 句({'/'.join(sorted(bands))},最多 {lines} 行):{style_text(st, float(np.median([c['line_h'] for c in subs])))}"
+ + (f";入场:{'、'.join(f'{k}×{v}' for k, v in sorted(anim.items(), key=lambda kv: -kv[1]))}" if anim else "")
+ + (";说到关键词时变色" if any((c.get('style') or {}).get('highlight_timing') == 'spoken' for c in subs) else "")
+ + (";句中有弹跳/变色动效" if sum(1 for c in subs if c.get("mid_motion")) >= max(2, 0.2 * len(subs)) else ""))
+ for kind in ("huazi", "title", "label"):
+ cs = [c for c in cues if c["kind"] == kind]
+ if cs:
+ names = "、".join(f"「{c['text'].replace('/', ' ')[:14]}」" for c in cs[:6]) + ("等" if len(cs) > 6 else "")
+ extra = ""
+ if kind == "huazi":
+ extra = "(" + "、".join(dict.fromkeys(w for c in cs for w in c.get("decor", []))) + ")"
+ if kind == "label" and any(c.get("follows") for c in cs):
+ extra = f"(其中 {sum(1 for c in cs if c.get('follows'))} 个跟着物体移动)"
+ L.append(f"{KIND_ZH[kind]} {len(cs)} 处{extra}:{names}")
+ st_all = [s for s in pack.get("stickers", []) if not s.get("in_picture")]
+ st = [s for s in st_all if s.get("confidence") != "low"]
+ maybe = len(st_all) - len(st)
+ if maybe:
+ L.append(f"另有 {maybe} 处疑似贴纸(画面里一块突然变了,可能只是画面内容),需要看图确认")
+ if st:
+ kinds: dict[str, int] = {}
+ for s in st:
+ kinds[s["kind_zh"]] = kinds.get(s["kind_zh"], 0) + 1
+ loops = sum(1 for s in st if s.get("looping"))
+ L.append("贴纸/动图 " + "、".join(f"{k} {v} 处" for k, v in kinds.items()) + (f"({loops} 处循环播放)" if loops else "")
+ + (";VLM 看到的没有截图,需要核对" if any(s.get("confidence") == "vlm" for s in st) else ""))
+ if sfx_align:
+ on = sfx_align.get("sfx_on", {})
+ if on:
+ zh = {"subtitle_in": "字幕出现", "huazi_in": "花字出现", "title_in": "标题出现", "label_in": "文字标注出现",
+ "sticker_in": "贴纸出现", "sticker_out": "贴纸消失", "cut": "切镜"}
+ L.append("音效卡点:" + "、".join(f"{zh.get(k, k)} {v} 处" for k, v in sorted(on.items(), key=lambda kv: -kv[1])))
+ return L
+
+
+# ----------------------------------------------------------------------------- pipeline hooks
+
+# bases whose own picture has things popping in and out (cards, UI, animated objects): a block that appears
+# mid-shot there is content unless it also crosses a cut or loops like a GIF
+CONTENT_BASES = ("code_render", "screen_capture", "cg_3d", "anim_2d", "stop_motion")
+LAYER_ZH = {"huazi": "花字", "animated_sticker": "动态贴纸/GIF", "static_sticker": "静态贴纸", "pip": "画中画"}
+
+
+def clean_region(stickers: list[dict], t0: float, t1: float, min_area: float = 0.45) -> tuple[float, float, float, float] | None:
+ """The largest band of the frame (left / right / above / below) free of the stickers that sit on this shot for
+ most of it, so the picture's own statistics are measured without the pasted layer. None if no sticker
+ covers the shot or the free band is too small to measure."""
+ dur = max(1e-6, t1 - t0)
+ boxes = [s["bbox"] for s in stickers
+ if s.get("confidence") != "low" and min(t1, s["t1"]) - max(t0, s["t0"]) >= 0.4 * dur]
+ if not boxes:
+ return None
+ x0 = min(b[0] for b in boxes)
+ y0 = min(b[1] for b in boxes)
+ x1 = max(b[0] + b[2] for b in boxes)
+ y1 = max(b[1] + b[3] for b in boxes)
+ cands = [(0.0, 0.0, x0, 1.0), (x1, 0.0, 1.0 - x1, 1.0), (0.0, 0.0, 1.0, y0), (0.0, y1, 1.0, 1.0 - y1)]
+ best = max(cands, key=lambda c: c[2] * c[3])
+ return tuple(round(v, 4) for v in best) if best[2] * best[3] >= min_area else None
+
+
+def shot_layers(pack: dict, rec: dict, label: str) -> list[dict]:
+ """花字 / sticker layers on one shot. Marks stickers on content bases that are probably part of the picture."""
+ t0, t1 = rec["start"], rec["end"]
+ out = []
+ for c in pack.get("text_cues", []):
+ if c["kind"] == "huazi" and min(t1, c["t1"]) - max(t0, c["t0"]) > 0.1:
+ out.append({"kind": "huazi", "source": "code_or_editor", "band": c.get("band"), "texts": [c["text"]], "ref": c["id"]})
+ for s in pack.get("stickers", []):
+ ov = min(t1, s["t1"]) - max(t0, s["t0"])
+ if ov <= 0.1:
+ continue
+ if s.get("confirmed") is False or (s.get("in_picture") and s.get("confirmed") is None and s.get("source") is None):
+ continue
+ if (label in CONTENT_BASES and s.get("confirmed") is None and s.get("bbox") and not (s.get("crosses_cut") or s.get("looping"))
+ and ov >= 0.5 * (s["t1"] - s["t0"])):
+ s["in_picture"] = True # a thing appearing inside an animated / rendered picture, not a pasted layer
+ s["in_picture_why"] = f"出现在{label}画面里、不跨切镜也不循环:更像画面内容本身"
+ continue
+ if not s.get("in_picture") and s.get("confidence") != "low":
+ band = _band(s["bbox"][1] + s["bbox"][3] / 2) if s.get("bbox") else None
+ out.append({"kind": s["kind"], "source": "editor", "band": band, "bbox": s.get("bbox"), "ref": s["id"]})
+ return out
+
+
+def merge_vlm(pack: dict, whole: dict | None) -> None:
+ """Stickers / text effects the whole-video VLM saw that the pixel pass did not."""
+ if not whole:
+ return
+ for s in whole.get("stickers") or []:
+ try:
+ a, b = float(s.get("t0", s.get("t", 0))), float(s.get("t1", s.get("t0", s.get("t", 0))) or 0)
+ except (TypeError, ValueError):
+ continue
+ b = max(b, a + 0.5)
+ if any(min(b, o["t1"]) - max(a, o["t0"]) > 0 for o in pack.get("stickers", []) if not o.get("in_picture")):
+ continue
+ pack.setdefault("stickers", []).append({"id": f"sticker_vlm_{len(pack['stickers']) + 1:02d}", "kind": "animated_sticker"
+ if "gif" in str(s.get("what", "")).lower() or "动" in str(s.get("what", "")) else "static_sticker",
+ "kind_zh": str(s.get("what") or "贴纸"), "t0": round(a, 2), "t1": round(b, 2),
+ "where": s.get("where", ""), "bbox": None, "confidence": "vlm", "source": "vlm"})
+ pack["vlm_text_effects"] = [e for e in (whole.get("text_effects") or []) if isinstance(e, dict)][:60]
+
+
+def apply_review(pack: dict) -> None:
+ """An agent's look at the stickers and text kinds (rea-video review / apply-review) overrides the pixel pass."""
+ rv = pack.get("review")
+ if not rv:
+ return
+ for c in pack.get("text_cues", []):
+ if c["id"] in rv.get("text", {}):
+ c["kind"] = rv["text"][c["id"]]
+ c["kind_zh"] = KIND_ZH[c["kind"]]
+ c["reviewed"] = True
+ for st in pack.get("stickers", []):
+ a = rv.get("stickers", {}).get(st["id"])
+ if not a:
+ continue
+ st["confirmed"] = a["is_overlay"]
+ if a["is_overlay"]:
+ st["confidence"] = "confirmed"
+ st.pop("in_picture", None)
+ if a.get("what"):
+ st["what"] = a["what"]
+ else:
+ st["in_picture"] = True
+ st["in_picture_why"] = f"{rv.get('by', 'agent')} 看图:画面本身的东西"
+ ids = {st["id"] for st in pack.get("stickers", [])}
+ for k, m in enumerate(rv.get("missed", []), 1):
+ sid = f"sticker_agent_{k:02d}"
+ if sid in ids:
+ continue
+ try:
+ t0 = float(m["t0"])
+ t1 = float(m.get("t1", t0 + 1.0))
+ except (TypeError, ValueError):
+ continue
+ what = str(m.get("what") or "贴纸")
+ pack.setdefault("stickers", []).append({"id": sid, "kind": "animated_sticker" if ("gif" in what.lower() or "动" in what) else "static_sticker",
+ "kind_zh": what, "t0": round(t0, 2), "t1": round(max(t1, t0 + 0.2), 2), "bbox": None,
+ "where": str(m.get("where", "")), "confidence": "confirmed", "source": "agent"})
+
+
+def finalize_pack(breakdown: dict, out: Path) -> dict | None:
+ """After shots are labelled and the audio plan exists: SFX alignment, exports, summary lines."""
+ pack = breakdown.get("packaging")
+ if not pack:
+ return None
+ out = Path(out)
+ labels = {r["id"]: r["base"]["label"] for r in breakdown["shots"]}
+ for c in pack.get("text_cues", []):
+ mid = (c["t0"] + c["t1"]) / 2
+ r = next((r for r in breakdown["shots"] if r["start"] <= mid < r["end"]), None)
+ c["shot"] = r["index"] if r else None
+ # on a rendered / recorded picture, words are the picture's content, not a separate overlay
+ c["part_of_picture"] = bool(r and labels[r["id"]] in ("code_render", "screen_capture") and c["kind"] not in ("subtitle",))
+ stickers = [s for s in pack.get("stickers", []) if not s.get("in_picture")]
+ cues = [c for c in pack.get("text_cues", []) if c["kind"] != "scene"]
+ cuts = [r["start"] for r in breakdown["shots"][1:]]
+ plan = breakdown.get("audio_plan") or {}
+ sfx = plan.get("sfx_merged", [])
+ has_vlm_sfx = any(e.get("source") == "vlm" for e in sfx)
+ if not has_vlm_sfx:
+ known = {round(float(e.get("t", -9)), 2) for e in sfx}
+ for e in pack.get("sfx_anchored", []):
+ if all(abs(e["t"] - k) >= 0.12 for k in known):
+ sfx.append(dict(e, confidence="low"))
+ sfx.sort(key=lambda e: float(e.get("t", 0)))
+ events = visual_events(cues, stickers, cuts)
+ pack["sfx_alignment"] = align_sfx(sfx, events)
+ pack["summary_zh"] = summary_lines({**pack, "stickers": stickers}, pack["sfx_alignment"])
+ d = out / "packaging"
+ d.mkdir(parents=True, exist_ok=True)
+ srt = to_srt(cues)
+ pack["files"] = {}
+ if srt.strip():
+ (d / "subtitles.srt").write_text(srt, encoding="utf-8")
+ pack["files"]["srt"] = "packaging/subtitles.srt"
+ src = breakdown["source"]
+ if cues:
+ (d / "overlays.ass").write_text(to_ass([c for c in cues if not c.get("part_of_picture")], src["width"], src["height"]), encoding="utf-8")
+ pack["files"]["ass"] = "packaging/overlays.ass"
+ timeline = {"text": [{k: c.get(k) for k in ("id", "kind", "kind_zh", "t0", "t1", "text", "bbox", "style", "style_zh", "anim_in",
+ "anim_out", "mid_motion", "follows", "part_of_picture")} for c in cues],
+ "stickers": stickers,
+ "sfx": [{k: e.get(k) for k in ("t", "type", "description", "source", "confidence", "on")} for e in sfx]}
+ from .util import write_json
+
+ write_json(d / "timeline.json", timeline)
+ pack["files"]["timeline"] = "packaging/timeline.json"
+ return pack
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index d07c1b2..3dee7b0 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -35,7 +35,7 @@ def _sha256_head(path: Path, limit: int = 64 << 20) -> str:
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:
+ platform_meta: dict | None = None, stems: bool = True, memory: bool = True, packaging: bool = True) -> dict:
require_tools()
t0 = time.time()
video = Path(video).expanduser().resolve()
@@ -60,6 +60,18 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
if stem_info.get("ok"):
refine_with_stems(audio, stem_info["vocals"])
+ # ---------------- packaging layer: subtitles / 花字 / stickers on one timeline ---------------
+ pack = None
+ if packaging:
+ from .packaging import analyze as analyze_packaging, anchored_sfx, visual_events
+
+ LOG.info("packaging layer: subtitle timeline, 花字, stickers%s", "" if ocr else " (no OCR: stickers only)")
+ pack = analyze_packaging(video, info, [s.start for s in shots[1:]], out, ocr=ocr)
+ if info.has_audio:
+ ev = [e for e in visual_events(pack["text_cues"], pack["stickers"], []) if e["type"] != "subtitle_in"]
+ pack["sfx_anchored"] = anchored_sfx(video, ev, (audio.get("sfx") or {}).get("events", []))
+ pack["version"] = PACKAGING_VERSION
+
shot_records: list[dict] = []
template_frames: list[np.ndarray] = []
samples_by_shot = {}
@@ -70,9 +82,15 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
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": []}
+ from .packaging import clean_region
+
for s in shots:
smp = samples_by_shot[s.index]
- feats = shot_features(smp, info.fps)
+ crop = clean_region(pack["stickers"], s.start, s.end) if pack else None
+ # a sticker / GIF sitting on the shot would skew the picture statistics: measure the rest of the frame
+ feats = shot_features(collect_samples(str(video), info, s, crop=crop) if crop else smp, info.fps)
+ if crop:
+ feats["measured_region"] = list(crop)
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"))
@@ -167,6 +185,8 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
"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 pack is not None:
+ breakdown["packaging"] = round_floats(pack)
if memory:
from .memory import reapply
@@ -179,6 +199,7 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
DOUBT_CAP = 0.7
+PACKAGING_VERSION = 2
PULLDOWN_24 = ("24→30", "24→60", "25→30?")
@@ -320,6 +341,17 @@ def finalize(breakdown: dict, out: Path, engine: str = "seedance2.0") -> dict:
prov = breakdown.get("provenance", {})
template = breakdown.get("global_layers", {})
planner = Planner()
+ pack = breakdown.get("packaging")
+ if pack:
+ from .packaging import merge_vlm, shot_layers
+
+ for st in pack.get("stickers", []):
+ st.pop("in_picture", None)
+ st.pop("in_picture_why", None)
+ merge_vlm(pack, breakdown.get("whole_video_vlm"))
+ from .packaging import apply_review as apply_pack_review
+
+ apply_pack_review(pack)
vctx = video_context(shot_records, prov, breakdown["source"].get("fps"))
breakdown["video_context"] = vctx
for rec in shot_records:
@@ -377,6 +409,18 @@ def finalize(breakdown: dict, out: Path, engine: str = "seedance2.0") -> dict:
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"]
+ if pack:
+ extra = shot_layers(pack, rec, label)
+ if label in ("code_render", "screen_capture"):
+ extra = [l for l in extra if l["kind"] != "huazi"]
+ huazi = {t for l in extra if l["kind"] == "huazi" for t in l["texts"]}
+ from .classify import _same_words
+
+ # the per-shot OCR track that read the same 花字 is that layer, not a second "label"
+ rec["layers"] = [l for l in rec["layers"] if not (l.get("texts") and l["kind"] in ("label", "title")
+ and any(_same_words(t, h) for t in l["texts"] for h in huazi))] + extra
+ if (rec.get("features") or {}).get("measured_region"):
+ rec["base"]["evidence"].append("画面统计只在贴纸/动图之外的区域测量(x{:.0%} y{:.0%} 宽{:.0%} 高{:.0%})".format(*rec["features"]["measured_region"]))
# 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"))
@@ -415,7 +459,8 @@ def finalize(breakdown: dict, out: Path, engine: str = "seedance2.0") -> dict:
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": "版式模板"}
+ kind_zh = {"subtitle": "字幕", "title": "标题", "label": "文字标注", "static_graphic": "图形贴片", "layout_template": "版式模板",
+ "huazi": "花字", "animated_sticker": "动态贴纸/GIF", "static_sticker": "静态贴纸", "pip": "画中画"}
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
@@ -489,6 +534,10 @@ def finalize(breakdown: dict, out: Path, engine: str = "seedance2.0") -> dict:
rec["replication"]["shoot"] = {"summary": aspects.shot_text(rec), **res}
breakdown["audio_plan"] = merge_audio_with_vlm(audio, breakdown.get("whole_video_vlm"))
+ if pack:
+ from .packaging import finalize_pack
+
+ finalize_pack(breakdown, out)
srcs = classify_sound_sources(breakdown)
breakdown["sound_sources"] = srcs
for t in breakdown["audio_plan"].get("plan", []):
@@ -522,6 +571,26 @@ def finalize(breakdown: dict, out: Path, engine: str = "seedance2.0") -> dict:
a_parts.append(f"音效 {n_sfx} 处")
if a_parts:
summary["verdict"] += ";声音:" + " + ".join(a_parts)
+ if pack:
+ cues = [c for c in pack.get("text_cues", []) if not c.get("part_of_picture")]
+ p_parts = []
+ n_sub = sum(1 for c in cues if c["kind"] == "subtitle")
+ if n_sub:
+ p_parts.append(f"字幕 {n_sub} 句")
+ for k, zh in (("huazi", "花字"), ("title", "标题"), ("label", "文字标注")):
+ n = sum(1 for c in cues if c["kind"] == k)
+ if n:
+ p_parts.append(f"{zh} {n} 处")
+ n_st = sum(1 for st in pack.get("stickers", []) if not st.get("in_picture") and st.get("confidence") != "low")
+ if n_st:
+ p_parts.append(f"贴纸/动图 {n_st} 处")
+ on = (pack.get("sfx_alignment") or {}).get("sfx_on", {})
+ n_on = sum(v for k, v in on.items() if k != "cut")
+ if n_on:
+ p_parts.append(f"{n_on} 个音效卡在文字/贴纸出现上")
+ if p_parts:
+ summary["verdict"] += ";剪辑包装:" + "、".join(p_parts)
+ summary["packaging"] = pack.get("summary_zh", [])
from .production import production_plan
breakdown["production_plan"] = production_plan(breakdown, out, engine=engine)
diff --git a/rea_video/report.py b/rea_video/report.py
index 2e6d449..fd7d394 100644
--- a/rea_video/report.py
+++ b/rea_video/report.py
@@ -11,7 +11,8 @@ from .visual import LABEL_COLOR
from .production import report_md as production_md
from .vlm import vlm_note
-KIND_ZH = {"subtitle": "字幕", "title": "标题", "label": "文字", "static_graphic": "图形贴片", "layout_template": "版式模板"}
+KIND_ZH = {"subtitle": "字幕", "title": "标题", "label": "文字", "static_graphic": "图形贴片", "layout_template": "版式模板",
+ "huazi": "花字", "animated_sticker": "动态贴纸/GIF", "static_sticker": "静态贴纸", "pip": "画中画"}
CAMERA_ZH = {"static": "固定", "static_with_subject_motion": "固定(主体在动)", "planar_zoom_pan": "整图推拉/平移",
"handheld_like": "手持晃动", "smooth_move": "平滑运镜", "unknown": "—"}
@@ -111,8 +112,9 @@ def markdown(b: dict) -> str:
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', '')} |")
+ on = (e.get("on") or {}).get("what") or e.get("sync_with", "切点" if e.get("sync_with_visual") else "")
+ L.append(f"| {float(e.get('t', 0)):.2f}s | {e.get('type', '')} | {e.get('description', '') or e.get('anchor', '')} | "
+ f"{on} | {e.get('source', '')} |")
else:
L.append("- **音效**:信号层面未检出显著音效(在人声和音乐下面的轻音效需要 VLM 判断,见 --vlm)")
if plan.get("plan"):
@@ -121,6 +123,7 @@ def markdown(b: dict) -> str:
L.append(f"- {t['track']}({t['rule']}):{t['what']} → {t['how']}")
if plan.get("mix"):
L.append(f"- 混音:{plan['mix']}")
+ L += packaging_md(b)
w = b.get("whole_video_vlm")
if w:
L += ["", "## 结构与文案(VLM)", "", f"- 概括:{w.get('summary', '')}", f"- 形式:{w.get('format', '')};钩子:{w.get('hook', '')}"]
@@ -195,6 +198,84 @@ def markdown(b: dict) -> str:
return "\n".join(L)
+ANIM_ZH = {"cut": "直接出现", "pop": "弹出", "fade": "淡入", "slide": "滑入", "reveal": "逐字", "cut_out": "直接消失",
+ "pop_out": "缩小消失", "fade_out": "淡出", "slide_out": "滑出"}
+
+
+def packaging_md(b: dict) -> list[str]:
+ """剪辑包装层: subtitles / 花字 / titles / labels / stickers and the sound effects that land on them."""
+ pack = b.get("packaging")
+ if not pack:
+ return []
+ cues = [c for c in pack.get("text_cues", []) if c["kind"] != "scene" and not c.get("part_of_picture")]
+ stickers = [st for st in pack.get("stickers", []) if not st.get("in_picture")]
+ L = ["", "## 剪辑包装层(字幕 / 花字 / 贴纸 / 音效卡点)", ""]
+ for line in pack.get("summary_zh") or []:
+ L.append(f"- {line}")
+ if not cues and not stickers:
+ L.append("- 没有检出后期叠加的文字或贴纸" + ("(未开 OCR,文字层没有分析)" if not (b.get("analysis") or {}).get("ocr", True) else ""))
+ files = pack.get("files") or {}
+ if files:
+ L.append("- 导出:" + "、".join(f"`{v}`" for v in files.values())
+ + "(SRT 是字幕时间轴;ASS 带颜色、描边、位置和入场动画,字体需要换成原片字体;timeline.json 是完整时间轴)")
+ if cues:
+ L += ["", "| 时间 | 类型 | 文字 | 样式 | 入场 / 出场 | 音效 |", "|---|---|---|---|---|---|"]
+ sfx_by_ref: dict[str, list[str]] = {}
+ for e in (b.get("audio_plan") or {}).get("sfx_merged", []):
+ ref = (e.get("on") or {}).get("ref")
+ if ref:
+ sfx_by_ref.setdefault(ref, []).append(str(e.get("type", "")))
+ for c in sorted(cues, key=lambda c: c["t0"])[:120]:
+ anim = " / ".join(x for x in (ANIM_ZH.get((c.get("anim_in") or {}).get("kind"), ""), ANIM_ZH.get((c.get("anim_out") or {}).get("kind"), "")) if x)
+ if c.get("mid_motion"):
+ anim += "(中途有弹跳/变色)"
+ kind = c["kind_zh"] + ("·跟随物体" if c.get("follows") else "")
+ L.append(f"| {c['t0']:.2f}–{c['t1']:.2f}s | {kind} | {c['text'].replace('/', ' ⏎ ').replace('|', '|')[:40]} | "
+ f"{c.get('style_zh', '')} | {anim or '—'} | {'、'.join(sfx_by_ref.get(c['id'], [])) or '—'} |")
+ if stickers:
+ L += ["", "**贴纸 / 动图 / 画中画**", "", "| 时间 | 类型 | 位置 | 动态 | 置信 | 截图 |", "|---|---|---|---|---|---|"]
+ for st in stickers:
+ where = "x{:.0%} y{:.0%} 宽{:.0%} 高{:.0%}".format(*st["bbox"]) if st.get("bbox") else (st.get("where") or "—")
+ dyn = ("循环,周期 %.2fs" % st["loop_period_s"]) if st.get("looping") else ("在动" if st.get("animated") else "静止")
+ why = []
+ if st.get("crosses_cut"):
+ why.append("跨切镜不变")
+ if st.get("disappears_mid_shot"):
+ why.append("镜头中途出现又消失")
+ conf = {"medium": "中", "low": "低", "vlm": "VLM 看到"}.get(st.get("confidence"), st.get("confidence", ""))
+ L.append(f"| {st['t0']:.2f}–{st['t1']:.2f}s | {st['kind_zh']} | {where} | {dyn} | {conf}{('(' + '、'.join(why) + ')') if why else ''} | "
+ + (f"![{st['id']}]({st['image']})" if st.get("image") else "—") + " |")
+ dropped = [st for st in pack.get("stickers", []) if st.get("in_picture")]
+ if dropped:
+ L.append(f"- 另有 {len(dropped)} 处画面里突然出现的东西没算作贴纸(3D/动画/版式画面里元素本来就会出现)")
+ if pack.get("vlm_text_effects"):
+ L += ["", "**VLM 看到的文字特效**", ""]
+ for e in pack["vlm_text_effects"][:20]:
+ L.append(f"- {e.get('t', '')}s {e.get('kind', '')}「{e.get('text', '')}」{e.get('style', '')} {e.get('animation', '')}")
+ L += ["", "复刻:字幕和花字用 `packaging/overlays.ass` 直接压制(ffmpeg -vf ass=overlays.ass),或按 timeline.json 在剪映 / Remotion 里重建;"
+ "贴纸和动图要找同款素材(表情包库 / GIF 库),截图在 packaging/ 下。"]
+ return L
+
+
+def _packaging_html(b: dict) -> str:
+ pack = b.get("packaging")
+ if not pack:
+ return ""
+ esc = html.escape
+ parts = ["<section class='shot'><h3 style='margin:4px 0'>剪辑包装层</h3>"]
+ parts += [f"<p>{esc(x)}</p>" for x in pack.get("summary_zh") or []]
+ stickers = [st for st in pack.get("stickers", []) if not st.get("in_picture") and st.get("image")]
+ if stickers:
+ parts.append("<div style='display:flex;gap:8px;flex-wrap:wrap'>" + "".join(
+ f"<figure style='margin:0'><img src='{esc(st['image'])}' style='max-height:90px;border-radius:6px'>"
+ f"<figcaption class='muted' style='font-size:12px'>{esc(st['kind_zh'])} {st['t0']:.1f}s</figcaption></figure>" for st in stickers) + "</div>")
+ files = pack.get("files") or {}
+ if files:
+ parts.append("<p class='muted'>" + " · ".join(f"<a href='{esc(v)}'>{esc(v)}</a>" for v in files.values()) + "</p>")
+ parts.append("</section>")
+ return "".join(parts)
+
+
def html_report(b: dict) -> str:
s = b["summary"]
esc = html.escape
@@ -245,6 +326,7 @@ img.sb{{max-width:100%;border-radius:8px}} .real{{background:#0d9488;color:#fff;
{_production_html(b.get("production_plan") or {})}
{aspects.report_html(b)}
{_sound_html(b)}
+{_packaging_html(b)}
{''.join(rows)}
</main></body></html>"""
diff --git a/rea_video/review.py b/rea_video/review.py
index 8152cb2..d22e40f 100644
--- a/rea_video/review.py
+++ b/rea_video/review.py
@@ -49,7 +49,13 @@ video_prompt(复刻该镜头的中文视频提示词:写清动作过程和
{ASPECT_GUIDE}
工具已经测了景别、主体光比、主光左右/上下、软硬、色温、背景虚化(见每镜 aspects),你主要补:机位角度、
拍摄方式(自拍/支架)、主光是什么光源、眼神光、轮廓光/背景灯、画面里可见的光源;和测量冲突时写明依据。
-最后在答案顶层的 aspects 里写整片:机位/场景、推测设备、整体布光、剪辑手法、视频形式。"""
+最后在答案顶层的 aspects 里写整片:机位/场景、推测设备、整体布光、剪辑手法、视频形式。
+
+剪辑包装(tasks.packaging,有才做):
+- stickers:工具找到的贴纸 / 动图 / 画中画,看 image(贴纸截图)和 frame_cmd 抽的帧,在答案 packaging.stickers 里填
+ is_overlay(true = 后期贴上去的;false = 画面本身的东西,例如 3D 里突然出现的物体)和 what(表情包 / GIF / emoji / 箭头 / 小窗里放的什么)。
+- text:工具分好类的花字 / 标题 / 文字标注,分错了就在 packaging.text 里填 kind(subtitle / huazi / title / label / scene)。
+- 工具漏掉的贴纸、动图,写进 packaging.missed:{{"t0": 秒, "t1": 秒, "what": "...", "where": "画面位置"}}。"""
def _priority(rec: dict, ctx: dict) -> tuple[str, list[str]]:
@@ -100,16 +106,33 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
"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",
})
+ pack = breakdown.get("packaging") or {}
+ pk_tasks, pk_answers = None, None
+ if pack:
+ sts = [st for st in pack.get("stickers", []) if st.get("bbox")]
+ txt = [c for c in pack.get("text_cues", []) if c["kind"] not in ("subtitle",)]
+ pk_tasks = {"stickers": [{"id": st["id"], "t0": st["t0"], "t1": st["t1"], "kind_zh": st["kind_zh"], "confidence": st.get("confidence"),
+ "in_picture": bool(st.get("in_picture")), "image": st.get("image"), "bbox": st["bbox"],
+ "frame_cmd": f"rea-video tiles {video} --start {st['t0']:.2f} --end {st['t1']:.2f} --every 0.25 "
+ f"-o {out_dir}/check_{st['id']}.jpg"} for st in sts],
+ "text": [{"id": c["id"], "t0": c["t0"], "t1": c["t1"], "text": c["text"], "kind": c["kind"], "style": c.get("style_zh", "")}
+ for c in txt[:80]]}
+ pk_answers = {"stickers": [{"id": st["id"], "is_overlay": None, "what": ""} for st in sts],
+ "text": [{"id": c["id"], "kind": ""} for c in txt[:80]], "missed": []}
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}
+ if pk_tasks:
+ tasks["packaging"] = pk_tasks
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": [], "ai_edits": [],
"replication": {"image_prompt": "", "video_prompt": "", "video_prompt_en": ""},
"aspects": aspects.review_template()} for s in shots],
"aspects": aspects.review_template(video=True)}
+ if pk_answers:
+ answers["packaging"] = pk_answers
return tasks, answers
@@ -164,6 +187,15 @@ def apply_answers(breakdown: dict, answers: dict, by: str | None = None) -> dict
rec["review"] = clean
applied.append(sid)
changes.append((sid, before))
+ pk = answers.get("packaging")
+ if isinstance(pk, dict) and breakdown.get("packaging"):
+ kinds = ("subtitle", "huazi", "title", "label", "scene")
+ clean_pk = {"stickers": {str(a["id"]): {"is_overlay": bool(a["is_overlay"]), "what": str(a.get("what", ""))[:80]}
+ for a in pk.get("stickers") or [] if isinstance(a, dict) and isinstance(a.get("is_overlay"), bool)},
+ "text": {str(a["id"]): a["kind"] for a in pk.get("text") or [] if isinstance(a, dict) and a.get("kind") in kinds},
+ "missed": [m for m in pk.get("missed") or [] if isinstance(m, dict) and "t0" in m], "by": by}
+ if clean_pk["stickers"] or clean_pk["text"] or clean_pk["missed"]:
+ breakdown["packaging"]["review"] = clean_pk
whole = aspects.clean_answers(answers.get("aspects"), video=True)
if whole:
breakdown["review_aspects"] = whole
diff --git a/rea_video/vlm.py b/rea_video/vlm.py
index fb7e714..281620e 100644
--- a/rea_video/vlm.py
+++ b/rea_video/vlm.py
@@ -218,6 +218,8 @@ WHOLE_PROMPT = """你是短视频拆解专家。完整观看并**仔细收听**
判断音乐来源时结合视频形式:AI 音乐 MV(整片一首歌、歌词唱的就是画面内容)大概率是 AI 生成的歌;普通视频的垫底配乐大概率是现成曲库;
能认出歌名就写出来;lyrics_match_content 表示歌词是否在唱这条视频的具体内容/角色/商品。
每一个音效出现的时间点、类型,以及它对应画面上的什么事件。
+剪辑包装要拆全:字幕之外的花字、标题、章节牌、标签(含跟着物体走的标注)逐个列出时间、样式和动画;
+后期贴上去的表情包、GIF 动图、emoji、贴纸、画中画小窗、箭头圈注逐个列出出现/消失时间和位置(画面本身的内容不算)。
已检测到的镜头切分(秒):{shots}
只返回 JSON:
@@ -239,6 +241,10 @@ WHOLE_PROMPT = """你是短视频拆解专家。完整观看并**仔细收听**
"ambience": "环境声(街道、室内、无)",
"mix": "人声/BGM/音效的音量关系,是否有人声出现时压低音乐(ducking)",
"subtitles": {{"present": true, "style": "字体/描边/颜色/位置/逐字高亮等"}},
+ "text_effects": [{{"t": 0.0, "text": "花字/标题/标签上的字", "kind": "花字|标题|章节牌|标签|弹幕", "style": "字体、颜色、描边、底框、大小",
+ "animation": "弹出/缩放/抖动/打字机/逐字高亮/滑入/无"}}],
+ "stickers": [{{"t0": 0.0, "t1": 1.0, "what": "表情包/GIF 动图/emoji/静态贴纸/画中画小窗/箭头圈注", "where": "画面位置",
+ "description": "贴的是什么", "animated": true}}],
"aspects": <<VIDEO_ASPECTS>>,
"overall_production": "整体制作方式判断(实拍/AI生成/代码渲染/混合)与理由",
"warnings": []
diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.md
index acde673..9e4d99f 100644
--- a/skills/rea-video/SKILL.md
+++ b/skills/rea-video/SKILL.md
@@ -1,6 +1,6 @@
---
name: rea-video
-description: 逆向拆解一条视频是怎么做出来的——逐镜头判断实拍 / AI 生成 / 3D 渲染 / 2D 动画 / 定格动画 / 代码模板渲染 / 录屏截图 / 静态图推拉 / 静帧,以及实拍是否经过 AI 加工(换脸、对口型、风格化),标出后期叠加层和用户真实素材,拆解人声、背景音乐、音效与剪辑节奏,并给出可执行的复刻方案(可对接 capsule-cinema)。当用户给出参考视频、问"这条视频怎么做的 / 是不是 AI / 用了什么素材 / 怎么复刻"时使用。
+description: 逆向拆解一条视频是怎么做出来的——逐镜头判断实拍 / AI 生成 / 3D 渲染 / 2D 动画 / 定格动画 / 代码模板渲染 / 录屏截图 / 静态图推拉 / 静帧,以及实拍是否经过 AI 加工(换脸、对口型、风格化),标出后期叠加层(逐句字幕时间轴、花字、标题、贴纸 / GIF / 表情包、画中画)和用户真实素材,拆解人声、背景音乐、音效(卡在哪个画面事件上)与剪辑节奏,并给出可执行的复刻方案(可对接 capsule-cinema)。当用户给出参考视频、问"这条视频怎么做的 / 是不是 AI / 用了什么素材 / 怎么复刻"时使用。
---
# rea-video:视频制作方式逆向拆解
@@ -8,7 +8,7 @@ description: 逆向拆解一条视频是怎么做出来的——逐镜头判断
你是视频制作的逆向工程师。用户给你一条视频,你要回答清楚:
1. **每个镜头的底层画面是怎么来的?**从 10 类里选:实拍 / AI 视频 / 数字人 / 3D 渲染 / 2D 动画 / 定格动画 / 代码模板渲染 / 录屏截图 / 静态图推拉 / 静帧。2D 动画和定格动画工具测不出,要你看图判断。实拍镜头再看有没有被 AI 加工过(换脸、对口型、风格化、换装、换背景),填在 `ai_edits` 里(对照 `references/taxonomy.md`)。
-2. **上面叠了什么?**字幕、标题、文字标注、贴片、版式模板。
+2. **上面叠了什么?(剪辑包装)**逐句字幕(时间轴、颜色、描边、关键词高亮、入场方式)、花字、标题、章节牌、跟着物体走的标签、表情包 / GIF / 贴纸 / 画中画、版式模板,以及哪些音效卡在文字弹出或贴纸出现上。
3. **哪些是用户真实素材?**分两类:画面里嵌入的真实像素(实拍、照片、截图、录屏、版式里播放的视频片段),复刻时必须拿到原文件;AI / 3D 画面里出现的商品、Logo、人物,是复刻时要准备的参考图(报告里的「复刻要准备的参考素材」),不是嵌入素材。
4. **声音怎么做的?**人声(TTS 还是真人)、BGM(风格 / BPM / 调性 / 段落)、音效(时间点、类型、对应哪个画面事件),以及切镜是否卡在节拍上。**重点是来源:AI 生成的还是现成的。**先看视频形式——AI 音乐 MV(整片是一首唱出来的歌)大概率是 AI 歌;普通视频配乐大概率是现成曲库,但 AI 工作流的视频 BGM 也常是 Suno 生成,必须标"待确认"并给确认方法。
5. **实拍的话,怎么拍、怎么打光、怎么调色、怎么剪?**景别、机位、自拍还是支架、正常速度还是慢动作/延时;主光方向/软硬/光比/色温、有无补光和轮廓光,布光方案(正面柔光、主光 + 补光、侧光、逆光、夜景环境光、低调、高调、彩色氛围光、产品静物、户外直射/阴天/逆光——户外要靠你在 `lighting.location` 里写明"户外");调色风格(自然、青橙、日系、胶片、黑白、暗调);跳切、推近切、插入素材的节奏。
@@ -83,7 +83,12 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复
看图时在 `review_answers.json` 每镜的 `aspects` 和顶层 `aspects` 里补像素测不出的:机位角度、自拍还是支架、主光是什么光源、眼神光、轮廓光/背景灯、画面里的光源、推测设备、视频形式。报告里测量、VLM、看图三个来源并列,不平均。
注意:平台转码会压暗部,软硬和补光的测量偏保守。AI / 3D 画面也会给光影描述,但标明「不是拍摄方案」,只用于写生成提示词。
5. 真实素材按 `references/materials.md` 复核:代码模板里嵌入的截图和照片,确定性检测能找出大部分,但**暗色、半透明的背景照片会漏**。
-6. 如果你的判断和工具不同,以你的复核为准,在回复里写明理由;有价值的话,把这条视频按 `references/evaluation.md` 加进评测集。
+6. 剪辑包装(`rea-video summary` 的「包装:」几行,`report.md`「剪辑包装层」一节,文件在 `packaging/`):
+ - 字幕时间轴和样式是测出来的,一般可信;字体是什么要你看图补(工具只给颜色、描边、底框、字高)。
+ - 贴纸:标了「需要看图确认」的,看 `packaging/sticker_XX.jpg` 和 `review_tasks.json` 里的 `frame_cmd`,在 `review_answers.json` 的 `packaging.stickers` 里填 `is_overlay` 和 `what`;工具漏掉的写进 `packaging.missed`。3D / 动画 / 版式画面里突然出现的物体工具不算贴纸,你看到是后期贴的再补。
+ - 花字和标签分错类时在 `packaging.text` 里改 `kind`。
+ - 音效「对应画面」一列是按时间就近对齐的,没开 VLM 时补出的候选(来源 `deterministic_anchored`)实测只有约四成是真音效,写成"可能"。
+7. 如果你的判断和工具不同,以你的复核为准,在回复里写明理由;有价值的话,把这条视频按 `references/evaluation.md` 加进评测集。
### 看不了图时的规则(重要)
@@ -123,7 +128,7 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复
- 实拍镜头 → **拍摄场次**:哪些镜头是同一场景、同一机位,一起拍;每个场景的布光;先大景别后特写。分镜表本身仍然逐镜写细。
- 代码渲染 → 几段代码合成;静图推拉 → 本地重建。
- 提示词缺失(未开 VLM)时,你看图补写:`rea-video review` 的答案里每镜填 `replication.image_prompt / video_prompt / video_prompt_en`,`apply-review` 后生成单元会自动带上。
-- 然后写声音拆解、真实素材清单,最后写不确定点。
+- 然后写剪辑包装(字幕样式和时间轴文件、花字 / 贴纸清单、音效卡点)、声音拆解、真实素材清单,最后写不确定点。
- 报告文件路径(`report.html`)写给用户。不要把 breakdown.json 整段贴进对话。
## 3. 复刻(需要时)
diff --git a/skills/rea-video/references/output-template.md b/skills/rea-video/references/output-template.md
index 4e6623a..ad73d08 100644
--- a/skills/rea-video/references/output-template.md
+++ b/skills/rea-video/references/output-template.md
@@ -10,6 +10,8 @@
**拍法、打光与剪辑**(有实拍镜头时写,对应 `rea-video summary` 末尾的取景 / 机位 / 打光 / 剪辑 / 形式几行):视频形式(口播/桌拍/vlog)、景别和机位角度、手持还是支架、机位/场景数;布光方案(主光方向和高度、光比、软硬、色温、有无补光/轮廓光、画面里的光源);剪辑手法(跳切剪气口、推近切、插入截图/录屏的比例);给一份复刻器材清单。测量值和你看图的结论冲突时写明依据。
+**剪辑包装**:字幕(几句、位置、颜色 / 描边 / 底框、关键词高亮、入场方式,SRT/ASS 文件路径);花字、标题、章节牌、跟随标签(时间、文字、样式、动画);贴纸 / GIF / 表情包 / 画中画(时间、位置、贴的是什么、是否循环);哪些音效卡在文字弹出或贴纸出现上。工具没测到、你看图补的写明。
+
**声音**:人声(TTS 还是真人、音色)/ BGM(风格、BPM、调性、来源、段落)/ 音效(时间点 → 对应画面事件)/ 混音(是否压低音乐)。
**需要你提供的真实素材**:镜头 #4 中部的 GitHub 页面截图……
diff --git a/tests/test_packaging.py b/tests/test_packaging.py
new file mode 100644
index 0000000..b3d2875
--- /dev/null
+++ b/tests/test_packaging.py
@@ -0,0 +1,179 @@
+"""Packaging layer: subtitle timeline + style, 花字, stickers / GIFs, SFX alignment, exports."""
+import cv2
+import numpy as np
+import pytest
+
+from conftest import _photo_like, _write
+from rea_video import packaging as P
+from rea_video.media import video_info
+
+W, H, FPS = 360, 640, 30
+
+
+def _outlined(img, text, org, scale, color, thick, outline=(0, 0, 0)):
+ # the outline is the text stamped around the glyph (OpenCV 5 ignores thickness for anti-aliased text)
+ r = max(2, int(round(3 * scale)))
+ for dx in (-r, 0, r):
+ for dy in (-r, 0, r):
+ if dx or dy:
+ cv2.putText(img, text, (org[0] + dx, org[1] + dy), cv2.FONT_HERSHEY_DUPLEX, scale, outline, thick, cv2.LINE_AA)
+ cv2.putText(img, text, org, cv2.FONT_HERSHEY_DUPLEX, scale, color, thick, cv2.LINE_AA)
+
+
+def _emoji(frame_no: int) -> np.ndarray:
+ """A 2-frame looping 'GIF': a yellow face whose mouth opens / closes every 0.2 s, with a white sticker rim."""
+ s = np.zeros((96, 96, 3), np.uint8)
+ cv2.circle(s, (48, 48), 46, (255, 255, 255), -1)
+ cv2.circle(s, (48, 48), 40, (40, 210, 250), -1)
+ cv2.circle(s, (34, 38), 6, (30, 30, 30), -1)
+ cv2.circle(s, (62, 38), 6, (30, 30, 30), -1)
+ if (frame_no // 6) % 2:
+ cv2.ellipse(s, (48, 64), (16, 12), 0, 0, 360, (30, 30, 160), -1)
+ else:
+ cv2.line(s, (32, 64), (64, 64), (30, 30, 30), 4)
+ return s
+
+
+def _paste(f, s, x, y):
+ mask = s.sum(axis=2) > 0
+ f[y:y + s.shape[0], x:x + s.shape[1]][mask] = s[mask]
+
+
[email protected](scope="module")
+def packed(tmp_path_factory):
+ d = tmp_path_factory.mktemp("pack")
+ rng = np.random.default_rng(3)
+ shot_a = np.clip(_photo_like(W + 120, H, 11).astype(np.int16) + 70, 0, 255).astype(np.uint8) # light enough for a black outline
+ shot_b = np.clip(_photo_like(W + 120, H, 12).astype(np.int16) + 70, 0, 255).astype(np.uint8)
+ frames = []
+ for i in range(6 * FPS):
+ t = i / FPS
+ src = shot_a if t < 3.0 else shot_b
+ off = int(40 * (t % 3.0) / 3.0) # slow pan: live-ish background, never still
+ f = np.ascontiguousarray(src[:, off:off + W]).copy()
+ f = np.clip(f.astype(np.int16) + rng.normal(0, 2, f.shape).astype(np.int16), 0, 255).astype(np.uint8)
+ # subtitles: two lines in a fixed bottom lane, white with a black outline
+ if 0.5 <= t < 2.0:
+ _outlined(f, "HELLO WORLD", (70, 560), 0.9, (255, 255, 255), 2)
+ elif 2.0 <= t < 3.5:
+ _outlined(f, "SECOND LINE", (70, 560), 0.9, (255, 255, 255), 2)
+ elif 3.5 <= t < 5.5:
+ _outlined(f, "THIRD ONE", (90, 560), 0.9, (255, 255, 255), 2)
+ # looping GIF sticker, appears and leaves mid-shot
+ if 1.0 <= t < 2.4:
+ _paste(f, _emoji(i), 230, 90)
+ # 花字: big yellow word that pops in (scales up over 0.2 s)
+ if 4.0 <= t < 5.2:
+ k = min(1.0, 0.4 + 0.6 * (t - 4.0) / 0.2)
+ _outlined(f, "WOW!", (int(120 - 30 * (k - 1)), 300), 2.2 * k, (0, 230, 255), 5)
+ frames.append(f)
+ path = _write(frames, d / "pack.mp4", fps=FPS)
+ info = video_info(path)
+ return P.analyze(path, info, cuts=[3.0], out_dir=d, ocr=True), d
+
+
+def _ocr_ok():
+ from rea_video.overlay import get_ocr
+ return get_ocr() is not None
+
+
[email protected](not _ocr_ok(), reason="rapidocr not installed")
+def test_subtitle_timeline(packed):
+ pack, _ = packed
+ subs = [c for c in pack["text_cues"] if c["kind"] == "subtitle"]
+ texts = [P._norm(c["text"]) for c in subs]
+ assert any("helloworld" in t for t in texts) and any("secondline" in t for t in texts)
+ hello = next(c for c in subs if "helloworld" in P._norm(c["text"]))
+ assert abs(hello["t0"] - 0.5) <= 0.25 and abs(hello["t1"] - 2.0) <= 0.25
+ st = hello["style"]
+ assert st.get("fill_name") == "白" and st.get("stroke_name") == "黑"
+ srt = P.to_srt(pack["text_cues"])
+ assert "HELLOWORLD" in srt.upper().replace(" ", "") and "-->" in srt
+
+
[email protected](not _ocr_ok(), reason="rapidocr not installed")
+def test_huazi_pop(packed):
+ pack, _ = packed
+ wow = [c for c in pack["text_cues"] if "wow" in P._norm(c["text"])]
+ assert wow, [c["text"] for c in pack["text_cues"]]
+ c = wow[0]
+ assert c["kind"] == "huazi", c
+ assert c["style"].get("fill_name") == "黄"
+ assert abs(c["t0"] - 4.0) <= 0.25
+
+
+# without OCR the subtitle band is not recognized as text and shows up as a second "sticker"
[email protected](not _ocr_ok(), reason="rapidocr not installed")
+def test_gif_sticker(packed):
+ pack, d = packed
+ st = [s for s in pack["stickers"] if s["t0"] < 2.0 and s["t1"] > 1.2]
+ assert st, pack["stickers"]
+ s = st[0]
+ assert s["kind"] == "animated_sticker" and s["looping"]
+ assert abs(s["t0"] - 1.0) <= 0.2 and abs(s["t1"] - 2.4) <= 0.3
+ x, y, w, h = s["bbox"]
+ assert abs((x + w / 2) - (230 + 48) / W) < 0.08 and abs((y + h / 2) - (90 + 48) / H) < 0.06
+ assert (d / s["image"]).exists()
+ # nothing else is called a sticker: the subtitles and the 花字 are text, the pan is the picture
+ assert len(pack["stickers"]) == 1, pack["stickers"]
+
+
+def test_sfx_alignment():
+ cues = [{"id": "text_001", "kind": "huazi", "kind_zh": "花字", "text": "WOW", "t0": 4.0, "t1": 5.0}]
+ stickers = [{"id": "sticker_01", "kind_zh": "动态贴纸/GIF", "t0": 1.0, "t1": 2.4, "disappears_mid_shot": True}]
+ ev = P.visual_events(cues, stickers, [3.0])
+ sfx = [{"t": 4.05, "type": "pop"}, {"t": 1.02, "type": "pop"}, {"t": 3.01, "type": "whoosh"}, {"t": 0.3, "type": "ding"}]
+ res = P.align_sfx(sfx, ev)
+ assert sfx[0]["on"]["type"] == "huazi_in" and sfx[1]["on"]["type"] == "sticker_in" and sfx[2]["on"]["type"] == "cut"
+ assert "on" not in sfx[3]
+ assert res["events_with_sfx"]["huazi_in"] == {"with_sfx": 1, "total": 1}
+ assert res["events_with_sfx"]["sticker_out"] == {"with_sfx": 0, "total": 1}
+
+
+def test_ass_export():
+ cues = [{"kind": "subtitle", "text": "a/b", "t0": 1.0, "t1": 2.5, "bbox": [0.2, 0.8, 0.6, 0.08], "line_h": 0.035, "angle": 0.0,
+ "style": {"fill": "#ffffff", "stroke": "#000000", "stroke_ratio": 0.05}, "anim_in": {"kind": "pop"}},
+ {"kind": "scene", "text": "x", "t0": 0, "t1": 1, "bbox": [0, 0, 0.1, 0.1], "line_h": 0.02, "angle": 0.0, "style": {}}]
+ ass = P.to_ass(cues, 1080, 1920)
+ assert "Dialogue: 0,0:00:01.00,0:00:02.50" in ass and "a\\Nb" in ass and "\\fscx60" in ass
+ assert ass.count("Dialogue:") == 1 # scene text is not exported
+
+
+def test_clean_region():
+ st = [{"bbox": [0.6, 0.1, 0.3, 0.15], "t0": 1.0, "t1": 3.0, "confidence": "medium"}]
+ x, y, w, h = P.clean_region(st, 1.0, 3.0)
+ assert w * h >= 0.45 and (x + w <= 0.6 + 1e-6 or y >= 0.25 - 1e-6) # the band avoids the sticker
+ assert P.clean_region(st, 5.0, 8.0) is None # not on this shot
+ assert P.clean_region([dict(st[0], confidence="low")], 1.0, 3.0) is None # unconfirmed: leave the shot alone
+
+
+def test_review_overrides_stickers_and_kinds():
+ pack = {"text_cues": [{"id": "text_001", "kind": "label", "kind_zh": "文字标注", "text": "WOW", "t0": 1, "t1": 2}],
+ "stickers": [{"id": "sticker_01", "kind": "static_sticker", "kind_zh": "静态贴纸/图片", "t0": 1, "t1": 2,
+ "bbox": [0.1, 0.1, 0.2, 0.2], "confidence": "low"},
+ {"id": "sticker_02", "kind": "animated_sticker", "kind_zh": "动态贴纸/GIF", "t0": 3, "t1": 4,
+ "bbox": [0.5, 0.5, 0.2, 0.2], "confidence": "low"}],
+ "review": {"by": "claude", "text": {"text_001": "huazi"},
+ "stickers": {"sticker_01": {"is_overlay": False, "what": ""}, "sticker_02": {"is_overlay": True, "what": "猫猫表情包"}},
+ "missed": [{"t0": 6, "t1": 7, "what": "GIF 动图", "where": "右下"}]}}
+ P.apply_review(pack)
+ assert pack["text_cues"][0]["kind"] == "huazi"
+ s1, s2, s3 = pack["stickers"]
+ assert s1["in_picture"] and s2["confidence"] == "confirmed" and s2["what"] == "猫猫表情包"
+ assert s3["source"] == "agent" and s3["kind"] == "animated_sticker"
+ rec = {"start": 0.0, "end": 8.0}
+ kinds = [l["kind"] for l in P.shot_layers(pack, rec, "cg_3d")]
+ # confirmed stickers stay even on a 3D picture; the rejected one is gone
+ assert kinds.count("animated_sticker") == 2 and "static_sticker" not in kinds and "huazi" in kinds
+
+
+def test_pipeline_writes_packaging(tmp_path, media):
+ from rea_video.pipeline import decompose
+
+ b = decompose(media["edit"], tmp_path / "edit", use_vlm=False, ocr=False, stems=False, memory=False)
+ pk = b["packaging"]
+ assert pk["version"] >= 1 and (tmp_path / "edit" / pk["files"]["timeline"]).is_file()
+ # the code-render card sliding in is the picture's own content, not a sticker
+ assert not [s for s in pk["stickers"] if not s.get("in_picture")]
+ md = (tmp_path / "edit" / "report.md").read_text(encoding="utf-8")
+ assert "剪辑包装层" in md