Reverse-engineer any video, shot by shot: filmed, AI-generated or coded, and how to remake it. Breakdowns in the open VIDEO.md format. 逆向一切视频,逐个镜头看是拍的、AI 生成的还是代码做的,再告诉你怎么复刻;拆解结果按 VIDEO.md 格式输出。
Python agent-skillsai-videoaigc-detectionclaude-codecodexffmpegprompt-engineeringremotionreverse-engineeringshort-videoshot-detectionsubtitlesvideo-analysisvideo-breakdownvideo-editingvideo-generationvideomdvlm
Find magic reveals and highlight moments
june131d1527557d
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.jsonnew file mode 100644index 0000000..a463e49--- /dev/null+++ b/.agents/plugins/marketplace.json@@ -0,0 +1,12 @@+{+ "name": "rea-video",+ "interface": { "displayName": "rea-video" },+ "plugins": [+ {+ "name": "rea-video",+ "source": { "source": "url", "url": "https://github.com/JuneYaooo/rea-video.git" },+ "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" },+ "category": "Productivity"+ }+ ]+}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 346e0fd..ed8e18f 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -2,9 +2,18 @@"name": "rea-video","version": "0.1.0","description": "逆向拆解视频:逐镜头判断实拍 / AI / 3D / 代码渲染 / 录屏,拆剪辑包装、声音和真实素材,给出复刻方案。",- "author": { "name": "June" },+ "author": {+ "name": "June"+ },"homepage": "https://github.com/JuneYaooo/rea-video","repository": "https://github.com/JuneYaooo/rea-video","license": "Apache-2.0",- "keywords": ["video", "forensics", "ai-video", "remake"]+ "keywords": [+ "video",+ "forensics",+ "ai-video",+ "remake",+ "magic",+ "highlights"+ ]}diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonnew file mode 100644index 0000000..f72a6c7--- /dev/null+++ b/.codex-plugin/plugin.json@@ -0,0 +1,24 @@+{+ "name": "rea-video",+ "version": "0.1.0",+ "description": "逆向拆解视频:逐镜头判断实拍 / AI / 3D / 代码渲染 / 录屏,拆剪辑包装、声音和真实素材,给出复刻方案;抓魔术揭秘等特殊时刻。",+ "author": { "name": "June" },+ "homepage": "https://github.com/JuneYaooo/rea-video",+ "repository": "https://github.com/JuneYaooo/rea-video",+ "license": "Apache-2.0",+ "keywords": ["video", "forensics", "ai-video", "remake", "magic", "highlights"],+ "skills": "./skills/",+ "interface": {+ "displayName": "rea-video",+ "shortDescription": "拆解一条视频是怎么做出来的,给出复刻方案",+ "longDescription": "逐镜头判断制作方式(实拍、AI 生成、3D、代码渲染、录屏等),拆字幕花字、声音和真实素材,给出复刻方案;魔术、剧情类视频还能抓出揭秘、反转、穿帮时刻,出逐帧图解和慢放。需要本机装好 rea-video CLI(bash scripts/install_skill.sh)。",+ "developerName": "June",+ "category": "Productivity",+ "capabilities": ["Interactive", "Read", "Write"],+ "websiteURL": "https://github.com/JuneYaooo/rea-video",+ "defaultPrompt": [+ "用 rea-video 拆解这条视频是怎么做的:~/Movies/ref.mp4",+ "这条魔术视频是怎么变的?找出揭秘时刻:~/Movies/magic.mp4"+ ]+ }+}diff --git a/README.md b/README.mdindex 9cf50d7..130f65f 100644--- a/README.md+++ b/README.md@@ -51,6 +51,13 @@ You can also hook up a video-capable model (Gemini or Doubao both work) by givin> Reports are written in whichever language you ask in (Chinese or English). The example reports below are in English.+## Updates++- **2026-11-19**: Magic videos: finds the reveal of each trick, frame by frame with a slow-motion clip. Highlights (twists, climaxes, goofs) when you ask for them.+- **2026-11-17**: Better timing of cuts and moves.+- **2026-11-15**: Remake plans are made for the model you choose. The report is split into a breakdown part and a remake part.+- **2026-11-11**: VIDEO.md breakdown package, rewritten report, sound effects separated on their own track.+## What it can break down| Video type | Examples | What you get |@@ -71,6 +78,8 @@ Besides how the visuals were made, every breakdown also covers:- Audio: human or AI voice, AI or library music and its BPM, where each sound effect lands- Material you'll need to supply yourself: screen recordings, screenshots, product photos+For magic videos it also finds the reveal of each trick: when and how the object changes, laid out frame by frame and zoomed in, plus a slow-motion clip. Ask for highlights and it pulls out twists, climaxes and goofs too.+## ExamplesThe sample videos in `docs/cases/videos/` are re-compressed to keep the repo small, which strips the TikTok / Douyin platform tags. So if you run them yourself, you'll get different results from the reports below, especially without a vision model. To reproduce them, use the original downloads from the platform.diff --git a/docs/cli.md b/docs/cli.mdindex f2b013f..db499c7 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -40,6 +40,7 @@ export REA_VLM_BASE_URL=https://.../v1 REA_VLM_API_KEY=... REA_VLM_MODEL=gemini-rea-video decompose ref.mp4 -o out/ref --vlm# 或复用 capsule-cinema 的配置:rea-video --env-file ~/code/github/capsule-cinema/.env decompose ref.mp4 -o out/ref --vlm# VLM 调用全部失败时不会中断,报告和 `rea-video summary` 的 "VLM:" 一行会写明"全部调用失败,等同未开"+# 只有 Gemini 的 key 时:export GEMINI_API_KEY=...(模型用 REA_GEMINI_MODEL 改),特殊时刻走 Gemini 自己的接口,连声音一起看片段open out/ref/report.html@@ -97,9 +98,10 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name| 命令 | 作用 ||---|---|-| `decompose VIDEO [--vlm] [--no-ocr] [--ocr-lang zh\|ja\|ko] [--lang zh\|en] [--no-packaging] [--max-vlm-shots N] [--no-asr] [--asr-lang auto\|bn] [--no-speakers]` | 拆解,输出 breakdown.json、report.html/md、拆片包(`VIDEO.md` + `video/`)、storyboard.jpg、每镜首尾帧,`packaging/`(字幕 SRT、带样式的 ASS、包装时间轴、贴纸截图),以及 `sfx/`(每处音效从原片剪出的一小段,报告音效表里可直接试听);`--lang en` 让结论、报告、`summary` 输出和 VLM 描述都用英文(默认中文;agent 按用户提问的语言选,`rea-video prefs lang en` 可设成默认;breakdown.json 里的 `*_zh` 字段名保留,内容跟报告语言走);`--no-packaging` 跳过包装层(省约每分钟 30–50 秒);`--ocr-lang ja` 用日文识别模型读字幕和花字(首次使用自动下载约 10 MB 到 `$REA_VIDEO_MODELS`,离线时可用 `$REA_OCR_REC_MODEL` 指向本地模型),`rea-video prefs ocr_lang ja` 可设成默认;`--ocr-lang ko` 同理用韩文识别模型(PP-OCRv5,约 14 MB),并关掉文字方向分类(它会把韩文行误判成倒置、读成乱码);`--max-vlm-shots N` 是最多发给 VLM 的调用数(默认 60),镜头更多时先看最拿不准的,其余只靠确定性取证,`VLM:` 一行会写明送了多少个;装了可选的 `rea-video[asr]` 时会在人声干声上做本地语音识别,带时间的台词写进 `speech.lines` 和报告的脚本表(机器听写,未校对),`--no-asr` 跳过;台词是孟加拉语时加 `--asr-lang bn`,换用孟加拉语识别模型(SenseVoice 不认孟加拉语,会听成英/日/韩文;首次使用自动下载约 90 MB 到 `$REA_VIDEO_MODELS`),`rea-video prefs asr_lang bn` 可设成默认 |+| `decompose VIDEO [--vlm] [--no-ocr] [--ocr-lang zh\|ja\|ko] [--lang zh\|en] [--no-packaging] [--max-vlm-shots N] [--no-asr] [--asr-lang auto\|bn] [--no-speakers] [--no-moments]` | 拆解,输出 breakdown.json、report.html/md、拆片包(`VIDEO.md` + `video/`)、storyboard.jpg、每镜首尾帧,`packaging/`(字幕 SRT、带样式的 ASS、包装时间轴、贴纸截图),以及 `sfx/`(每处音效从原片剪出的一小段,报告音效表里可直接试听);`--lang en` 让结论、报告、`summary` 输出和 VLM 描述都用英文(默认中文;agent 按用户提问的语言选,`rea-video prefs lang en` 可设成默认;breakdown.json 里的 `*_zh` 字段名保留,内容跟报告语言走);`--no-packaging` 跳过包装层(省约每分钟 30–50 秒);`--ocr-lang ja` 用日文识别模型读字幕和花字(首次使用自动下载约 10 MB 到 `$REA_VIDEO_MODELS`,离线时可用 `$REA_OCR_REC_MODEL` 指向本地模型),`rea-video prefs ocr_lang ja` 可设成默认;`--ocr-lang ko` 同理用韩文识别模型(PP-OCRv5,约 14 MB),并关掉文字方向分类(它会把韩文行误判成倒置、读成乱码);`--max-vlm-shots N` 是最多发给 VLM 的调用数(默认 60),镜头更多时先看最拿不准的,其余只靠确定性取证,`VLM:` 一行会写明送了多少个;装了可选的 `rea-video[asr]` 时会在人声干声上做本地语音识别,带时间的台词写进 `speech.lines` 和报告的脚本表(机器听写,未校对),`--no-asr` 跳过;台词是孟加拉语时加 `--asr-lang bn`,换用孟加拉语识别模型(SenseVoice 不认孟加拉语,会听成英/日/韩文;首次使用自动下载约 90 MB 到 `$REA_VIDEO_MODELS`),`rea-video prefs asr_lang bn` 可设成默认 || `survey VIDEO [-o OUT_DIR] [--vlm] [--no-detail] [--workers N]` | 先看后拆:第一轮把全片排成一张小格总览图(只为找切点,格子小省 token;张数按剪辑快慢定,一半等距、一半放在画面变化多的地方),问每两格之间是同一画面、画面变化多、硬切、转场还是看不清;转场和看不清的地方下一轮放大逐帧再看(总览上已经够密的转场、相邻两帧之间的看不清不再放大,由画面变化曲线定)(转场按变化最大的帧抽,同一轮的任务可以并发,最多三轮);切点定下来后每镜都上关键帧图(动作多的镜头出候选帧,短镜头几格),让 AI 挑出关键帧、标明是哪一种,并判断画面是怎么做出来的。每张图都填到模型不缩图的大小(约 1568 px / 1.15 MP),一张能放多少格就放多少。问答是 JEV 格式:`state` 放材料,问题带 `criteria`,答案只写选项和概率。结果写进 `survey/timeline.json`(切点、转场时长、每镜关键帧、镜头长度、画面变化曲线、每段底层画面判断),decompose 按它切镜,报告和拆片包的「节奏与关键帧」也来自它。没有 VLM 时由 agent 回答:命令输出要看的图和要写的答案文件,答完再跑同一条命令;`--vlm` 用配置的模型自动答;decompose 开了 VLM 时会自动先跑(`--no-survey` 跳过) || `review OUT_DIR` | 给能看图的 agent 生成逐镜看图任务(review_tasks.json)和答案模板(review_answers.json) |+| `moments OUT_DIR [--vlm] [--no-vlm] [--redo]` | 找特殊时刻:魔术的变化瞬间、剧情反转、高潮、穿帮。先给台词、画面上的字、整片小格总览和工具候选(有人惊呼、人声突然变大、快速动作后定住,只作提醒),定出有特殊时刻的段落和类型;再把每段排成大格逐帧图,挑出初始状态、手法 / 关键动作、变化瞬间和反应;变化落在两格之间时再逐帧看一次;最后把每个时刻讲成 3-6 步(关键一步、变化的逐帧区间、确定时的红圈位置、放大区域、看得到的 / 推测的 / 为什么没发现)。总览按画面变化抽帧(动得多的地方密,几乎一样的帧合并)。结果进报告「特殊时刻」一节和 `video/moments.md`,每个时刻导出:编号图解加逐帧过程(`M1.jpg`)、揭秘时刻慢放(`M1_slow_*.mp4`:只放变化那一段,每帧停 0.2 秒、带时间,关键一帧画圈停住)、揭秘短片(`M1_reveal_*.mp4`:原速 → 变化慢放放大 → 定格 → 反应)、带声音的原片段和关键帧原图(`moments/`)。没有 VLM 时由 agent 回答,答完再跑同一条命令;VLM 能收视频时会连声音一起附上片段;只有 `GEMINI_API_KEY` 时走 Gemini 自己的接口。decompose 开了 VLM 时会自动做(约多 3–5 次调用,`--no-moments` 跳过) || `apply-review OUT_DIR [ANSWERS] [--by NAME] [--lang zh\|en]` | 把 agent 看图的答案和确定性结果融合,重写 breakdown.json 和报告;`--lang` 可以在这一步换报告语言(结论、证据和报告文字重新生成,VLM 已写好的描述和提示词保持原语言) || `correct OUT_DIR --shots N --label L [--real yes/no] [--note]` | 用户指出判错:改正结论和报告,并记入记忆(以后同一文件自动套用,同类镜头复核时提示) || `prefs [KEY VALUE] [--note TEXT]` | 用户偏好:默认引擎、是否默认开 VLM、VLM 配置文件、复核者名字、报告语言(`lang zh\|en`)、给 agent 的自由文字说明 |@@ -109,7 +111,7 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name| `videomd OUT_DIR` | 从 breakdown.json 重新生成拆片包(`VIDEO.md` + `video/`,给模型和下游程序读,格式见 [videomd.md](videomd.md));decompose 和 apply-review 会自动生成 || `videomd OUT_DIR --check` | 校验目录是否符合拆片包规范,不合格时逐条列出问题 || `pdf OUT_DIR` | 把 report.html 打印成 report.pdf(用本机的 Chrome / Chromium / Edge,`REA_CHROME` 可指定路径;正文的折叠内容展开,时间轴、逐镜取证这类查阅数据保持折叠) |-| `tiles VIDEO --start --end --every` | 按时间抽帧拼图,近距离复核 |+| `tiles VIDEO --start --end --every [--grid]` | 按时间抽帧拼图,近距离复核;`--grid` 每格画 0.1 一条的网格(整幅画面坐标),给特殊时刻的红圈定位用 || `frames OUT_DIR [--every 0.25] [--points 4000] [--all]` | 代码渲染镜头按场景切分(画上去的东西整体换了位置或形状就算新场景),写出 `frames/`:每场景首 / 中 / 尾原尺寸帧、`scene_XX_layer.png`(画上去那一层的抠图,背景和文字已去掉)、`points/scene_XX.json`(这一层的采样点)、`scenes.json`(底色、背景光、前景颜色、块数、范围、重心随时间的轨迹);深底浅底都适用;decompose 遇到代码渲染镜头会自动跑 || `compare REF REMAKE [--scenes frames/scenes.json] [-o DIR]` | 逐帧比较复刻和原片画上去的那一层:落在哪、形状重合度、多少;两边各按自己的底色取前景,换了底色也能直接比;并给出要改什么(整体早晚几秒、偏左偏右、铺开范围、多少、前景颜色和底色差多少),整段、每个场景、最差的几帧各一份;`-o` 写出 `compare.json` 和最差时刻的左右对比图 `compare_worst.jpg` || `drive OUT_DIR [--shots 3-7] [--depth] [--no-clean] [--prefer 10] [--max 15]` | 舞蹈 / 动作镜头的驱动视频:擦掉后期字幕和贴纸,在动作停顿、靠近拍点处切段,写出 `drive/seg_XX.mp4`(无声)、`seg_XX_first.jpg`(角色图按它对齐景别和朝向)、`seg_XX_music.wav`、`segments.jpg` 和带各路线提示词的 `README.md`;默认用复刻方案里的「动作驱动」单元(看图复核时 `performance.move` 标出的镜头);`--depth` 同时出深度视频(需要 transformers + torch) |diff --git a/docs/videomd.md b/docs/videomd.mdindex 7d5fd69..4efe8af 100644--- a/docs/videomd.md+++ b/docs/videomd.md@@ -26,6 +26,7 @@| `video/cast.md` | 角色、场景、道具 || `video/sound.md` | 人声、BGM、音效、节拍和来源 || `video/rhythm.md` | 节奏与关键帧:每分钟几刀、镜头长度、画面变化曲线(每 0.5 秒一位数字)、切点和转场的时间与时长(每个时间带原片帧号 @N;survey 看过的,后面写着切到了什么)、每镜关键帧(时间 + 是哪一种:首帧、动作开始 / 到位、转折、元素出入、构图变化、表情峰值、转场中段……) |+| `video/moments.md` | 特殊时刻(魔术揭秘、反转、高潮、穿帮):一行一个,类型、变化瞬间的时间、初始状态 / 手法 / 变化 / 反应四个关键帧、发生了什么、片段和揭秘短片路径,下一行是讲解步骤(* 是关键一步)和看得到的 / 推测的 / 为什么没发现;还没找时写怎么找 || `video/look.md` | 实拍镜头的景别、机位、打光、剪辑和器材(有实拍镜头时) || `video/packaging.md` | 字幕、花字、贴纸、画中画的时间和样式 || `video/remake.md` | 复刻方案:生成单元、拍摄场次、代码合成、要准备的真实素材、表演与情绪 |diff --git a/docs/what-it-detects.md b/docs/what-it-detects.mdindex fe0f92f..b6b0f59 100644--- a/docs/what-it-detects.md+++ b/docs/what-it-detects.md@@ -60,3 +60,7 @@- 人声:真人还是 AI 配音,口播文案。- 配乐:BPM、调性、段落,是 AI 生成还是曲库。- 音效:每个音效的时间点、类型,以及它卡在哪个画面事件上(字幕 / 花字 / 贴纸出现、切镜)。++## 特殊时刻++魔术揭秘、剧情反转、高潮、穿帮这类值得单独剪出来的时刻。它们是什么得看懂内容,所以由看图的一方(VLM 或 agent)来找:先通读台词、画面上的字和整片总览定段落,再逐段放大定四个关键帧(初始状态、手法 / 关键动作、变化瞬间、反应)。声音和画面给的候选(有人惊呼、语气惊讶、笑声、人声突然变大、快速动作后定住)只用来提醒去看哪里。最后把每个时刻讲成 3-6 步:标出东西真正变化的那一帧(常常比镜头亮出来、有人惊呼早),确定的地方画红圈,分开写画面里看得到的、只是推测的(手法、道具从哪来)和观众为什么没发现。变化那一段要逐帧标出来(东西是怎么一点点过去的,不是突然冒出来)。每个时刻导出:一张编号图解加逐帧过程、一段只放变化的慢放(每帧停 0.2 秒、带时间)、一段揭秘短片(原速 → 变化慢放放大 → 定格 → 反应)、带声音的原片段和关键帧,见 [cli.md](cli.md) 的 `moments`。diff --git a/i18n/README_zh.md b/i18n/README_zh.mdindex 9c832ca..9cb60fd 100644--- a/i18n/README_zh.md+++ b/i18n/README_zh.md@@ -49,6 +49,13 @@ agent 会自己装好命令行工具、看懂拆解流程,然后一路跑完还可以配一个能看视频的模型(Gemini、豆包都行),把接口地址和密钥给 agent 就好。配上之后实拍、AI、3D 分得更准,每个镜头还会反推出提示词。不配也能用,agent 自己能看图的话,会补看没把握的镜头。+## 更新记录++- **2026-11-19**:魔术视频自动找出每个魔术的揭秘时刻,逐帧图解加慢放;用户要高光时,也能抓出剧情反转、高潮、穿帮。+- **2026-11-17**:优化了时间卡点。+- **2026-11-15**:复刻方案按你选的模型规划;报告分成「拆解」和「复刻」两部分。+- **2026-11-11**:拆解标准包 VIDEO.md;报告重写;音效单独分离。+## 能拆哪些视频| 视频类型 | 常见例子 | 拆出什么 |@@ -69,6 +76,8 @@ agent 会自己装好命令行工具、看懂拆解流程,然后一路跑完- 声音:真人还是 AI 配音,配乐是 AI 做的还是曲库的、多少 BPM,音效落在哪一下- 要你自己准备的素材:录屏、截图、产品图+魔术视频还会找出每个魔术的揭秘时刻:东西是什么时候、怎么变过去的,逐帧放大排出来,再剪一段慢放。你说要高光的话,剧情反转、高潮、穿帮这些时刻也能单独抓出来。+## 案例`docs/cases/videos/` 里的样片为了减小仓库体积重新压缩过,抹掉了抖音 / TikTok 的平台标记。自己拿它们跑,结果会和下面的报告不一样,不开看图模型时尤其明显。要复现请用平台下载的原文件。diff --git a/rea_video/cli.py b/rea_video/cli.pyindex 549588e..bc864a8 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -8,7 +8,7 @@ import reimport sysfrom pathlib import Path-from .util import ASR_LANGS, LOG, OCR_LANGS, load_env_files, read_json, setup_logging, read_image+from .util import ASR_LANGS, LOG, OCR_LANGS, load_env_files, read_json, setup_logging, read_image, write_jsonfrom .i18n import LANGS, T, set_langfrom .classify import LABELSfrom .vlm import vlm_note@@ -87,7 +87,7 @@ def cmd_decompose(args) -> int: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"), platform_meta=meta, stems=stems,packaging=not args.no_packaging, lang=lang, asr=not args.no_asr, max_shots_vlm=max(1, args.max_vlm_shots),- speakers=not args.no_speakers, survey=not args.no_survey)+ speakers=not args.no_speakers, survey=not args.no_survey, moments=not args.no_moments)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))@@ -124,6 +124,57 @@ def cmd_survey(args) -> int:return 0+def cmd_moments(args) -> int:+ """Special moments, coarse to fine: the stretches from the words and an overview, then the key frames of each."""+ import shutil++ from . import moments as mo+ from .memory import pref+ from .pipeline import finalize++ out = Path(args.out_dir)+ b = read_json(out / "breakdown.json")+ set_lang(b.get("lang", "zh"))+ if args.redo and (out / "moments").is_dir():+ shutil.rmtree(out / "moments")+ b.get("moments", {}).pop("items", None)+ m = b.setdefault("moments", {})+ if "hints" not in m: # a breakdown made with --no-moments: the hints from the words and the voice (no decode)+ voc = out / "stems" / "vocals.wav"+ m.update(genre=mo.genre(b), status="pending",+ hints=mo.hints((b.get("speech") or {}).get("lines") or [], voc if voc.is_file() else None, None, b["source"]["duration"]))+ asker = None+ if args.vlm or (pref("vlm") == "on" and not args.no_vlm):+ _check_vlm_config()+ from .vlm import VLMClient, VLMConfig, prompt_lang_note++ from . import gemini++ cfg = VLMConfig.from_env()+ if cfg is not None:+ asker = mo.vlm_asker(VLMClient(cfg, out / "vlm_cache"), prompt_lang_note())+ elif gemini.configured(): # only a Gemini key: Gemini's own API, which watches the clips with sound+ asker = mo.vlm_asker(gemini.GeminiClient(), prompt_lang_note())+ else:+ raise SystemExit("rea-video: --vlm 需要 VLM 配置(REA_VLM_BASE_URL / REA_VLM_API_KEY / REA_VLM_MODEL,或 GEMINI_API_KEY)")+ res = mo.run(b, out, asker=asker)+ if res["status"] == "waiting":+ res["next"] = T("看 images 里的图,按 tasks 里的说明把答案写进 waiting 里的文件(filled 改成 true),再运行同一条命令",+ "look at the images, answer as the task says into the waiting file (set filled to true), then run the same command again")+ write_json(out / "breakdown.json", b, compact=True)+ print(json.dumps(res, ensure_ascii=False, indent=1))+ return 0+ finalize(b, out)+ from .moments import summary_line++ print(summary_line(b) or T("没有找到特殊时刻", "No special moments found"))+ for it in b["moments"].get("items") or []:+ f = it.get("files") or {}+ print(f" {it['id']}: " + " ".join(f[k] for k in ("strip", "slow", "reveal", "clip") if f.get(k)))+ print(T("报告「特殊时刻」一节和 video/moments.md 已更新", "The report's “Special moments” section and video/moments.md are updated"))+ return 0++def cmd_review(args) -> int:"""Write review_tasks.json + review_answers.json so a multimodal agent can act as the VLM."""from .review import build_tasks@@ -345,9 +396,27 @@ def cmd_tiles(args) -> int:frames = []with tempfile.TemporaryDirectory() as tmpd:for i, t in enumerate(times):- p = extract_frame(args.video, float(t), Path(tmpd) / f"tile_{i:03d}.jpg", width=args.cell)- img = read_image(p)+ focus = getattr(args, "focus", None)+ if focus: # a region of the frame, enlarged to the cell width (x0,y0,x1,y1 in 0-1)+ x0, y0, x1, y1 = (float(v) for v in str(focus).replace(",", ",").split(","))+ p = extract_frame(args.video, float(t), Path(tmpd) / f"tile_{i:03d}.jpg")+ img = read_image(p)+ if img is not None:+ h, w = img.shape[:2]+ img = img[int(y0 * h):max(int(y0 * h) + 2, int(y1 * h)), int(x0 * w):max(int(x0 * w) + 2, int(x1 * w))]+ img = cv2.resize(img, (args.cell, max(2, int(args.cell * img.shape[0] / img.shape[1]))), interpolation=cv2.INTER_CUBIC)+ else:+ p = extract_frame(args.video, float(t), Path(tmpd) / f"tile_{i:03d}.jpg", width=args.cell)+ img = read_image(p)if img is not None:+ if getattr(args, "grid", False): # tenths of the whole frame, for placing a point (x, y in 0-1, top left 0,0)+ h, w = img.shape[:2]+ for k in range(1, 10):+ x, y = int(w * k / 10), int(h * k / 10)+ cv2.line(img, (x, 0), (x, h), (0, 255, 255), 1)+ cv2.line(img, (0, y), (w, y), (0, 255, 255), 1)+ cv2.putText(img, f".{k}", (x + 2, 12), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 255, 255), 1)+ cv2.putText(img, f".{k}", (2, y - 2), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 255, 255), 1)frames.append(img)rows = [frames[i:i + args.cols] for i in range(0, len(frames), args.cols)]paths = []@@ -537,6 +606,14 @@ def cmd_summary(args) -> int:+ T("(截图在 packaging/)", " (crops under packaging/)"))if pk.get("files"):lines.append(f"{T('包装文件', 'Packaging files')}: " + " ".join(pk["files"].values()))+ from .moments import summary_line++ ml = summary_line(b)+ if ml:+ lines += ["", ml, T("(关键帧和片段在 moments/,说明见 video/moments.md)", "(key frames and clips under moments/, see video/moments.md)")]+ elif (b.get("moments") or {}).get("status") == "pending" and b["moments"].get("genre") in ("magic", "drama"):+ lines += ["", T("特殊时刻: 还没找(`rea-video moments <目录>`)", "Special moments: not looked for yet (`rea-video moments <dir>`)")+ + (T(";这是魔术视频,建议找", "; a magic video: worth doing") if b["moments"].get("genre") == "magic" else "")]print("\n".join(lines))return 0@@ -727,6 +804,7 @@ def main(argv: list[str] | None = None) -> int:d.add_argument("--no-speakers", action="store_true", help="不区分说话人(装了 rea-video[asr] 才会做:在人声干声上分出谁在什么时候说话,多人时每人输出一条 stems/voice_S1.wav;首次使用下载约 35 MB 模型)")d.add_argument("--no-survey", action="store_true", help="开 VLM 时也不做总览 + 局部细看(只用切镜检测器的切点)")d.add_argument("--no-stems", action="store_true", help="不做人声/配乐分离(默认会输出 stems/original.wav、vocals.wav、music.wav)")+ d.add_argument("--no-moments", action="store_true", help="不找特殊时刻(魔术揭秘、反转、高潮、穿帮);开 VLM 时默认会找,约多 3–5 次调用")d.set_defaults(func=cmd_decompose)st = sub.add_parser("stems", help="只把声音剥离成 原声 / 人声 / 配乐 三条轨")@@ -794,6 +872,8 @@ def main(argv: list[str] | None = None) -> int:t.add_argument("--cols", type=int, default=6)t.add_argument("--cell", type=int, default=320)t.add_argument("--max", type=int, default=48)+ t.add_argument("--focus", help="只看画面的一块并放大到 --cell 宽:x0,y0,x1,y1(0-1,整幅画面坐标);和 --grid 一起用时网格是这一块里的坐标")+ t.add_argument("--grid", action="store_true", help="每格画 0.1 一条的网格(整幅画面坐标,左上角 0,0),定位用")t.add_argument("-o", "--out", default="out/tiles.jpg")t.set_defaults(func=cmd_tiles)@@ -858,6 +938,13 @@ def main(argv: list[str] | None = None) -> int:sv.add_argument("--workers", type=int, default=4, help="VLM 并发数")sv.set_defaults(func=cmd_survey)+ mm = sub.add_parser("moments", help="找特殊时刻(魔术揭秘、反转、高潮、穿帮):先通读台词和总览定段落,再逐段放大定关键帧,导出片段和关键帧")+ mm.add_argument("out_dir", help="decompose 的输出目录")+ mm.add_argument("--vlm", action="store_true", help="用配置的 VLM 自动回答(约 3–5 次调用)")+ mm.add_argument("--no-vlm", action="store_true", help="本次不用 VLM(覆盖 prefs 里的 vlm=on):输出任务,由能看图的 agent 回答")+ mm.add_argument("--redo", action="store_true", help="丢掉上次的答案重新找")+ mm.set_defaults(func=cmd_moments)+rv = sub.add_parser("review", help="能看图的 agent 当 VLM:生成逐镜看图任务和答案模板")rv.add_argument("out_dir", help="decompose 的输出目录")rv.add_argument("--force", action="store_true", help="覆盖已有的 review_answers.json")diff --git a/rea_video/gemini.py b/rea_video/gemini.pynew file mode 100644index 0000000..c06e6cf--- /dev/null+++ b/rea_video/gemini.py@@ -0,0 +1,139 @@+"""Google Gemini as the image / video reader, through its own API (not an OpenAI-compatible gateway).++For users whose only key is a Gemini key: GEMINI_API_KEY (or GOOGLE_API_KEY), model REA_GEMINI_MODEL. Gemini watches+video with its sound, so a clip goes in whole: inline when small, else through the Files API (deleted after the+answer; an upload that can't be deleted expires on Google's side within 48 hours). Short clips are sampled densely+(video_metadata.fps), long ones at Gemini's default. Used only when the user asks for a VLM (--vlm): the video leaves+the machine.+"""+from __future__ import annotations++import base64+import json+import os+import subprocess+import time+import urllib.error+import urllib.request+from pathlib import Path++from . import __version__+from .util import LOG++API = "https://generativelanguage.googleapis.com"+DEFAULT_MODEL = "gemini-3.7-flash"+INLINE_MAX = 18 * 1024 * 1024 # request bodies over ~20 MB must use the Files API+CLIP_FPS = ((30.0, 10.0), (120.0, 4.0)) # (clips up to s, frames a second); longer: Gemini's default (1)+++def api_key() -> str:+ return os.getenv("GEMINI_API_KEY", "") or os.getenv("GOOGLE_API_KEY", "")+++def configured() -> bool:+ return bool(api_key())+++def _duration(p: Path) -> float:+ r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(p)],+ capture_output=True, text=True)+ try:+ return float(r.stdout.strip())+ except ValueError:+ return 0.0+++class GeminiError(RuntimeError):+ pass+++class GeminiClient:+ """ask_json(prompt, media) like VLMClient; media = [(path, mime)], images and video/mp4 clips."""+ video_ok = True++ def __init__(self, model: str | None = None, key: str | None = None, timeout: float = 600.0):+ self.key = key or api_key()+ if not self.key:+ raise GeminiError("GEMINI_API_KEY is not set")+ self.model = model or os.getenv("REA_GEMINI_MODEL", "") or DEFAULT_MODEL+ self.timeout = timeout+ self.models = [self.model]++ def describe(self) -> str:+ return f"Gemini {self.model}"++ def _call(self, method: str, url: str, data: bytes | None = None, headers: dict | None = None, timeout: float = 120.0):+ req = urllib.request.Request(url, data=data, method=method,+ headers={"x-goog-api-key": self.key, "User-Agent": f"rea-video/{__version__}", **(headers or {})})+ try:+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return dict(r.headers), r.read()+ except urllib.error.HTTPError as exc:+ body = exc.read()[:300].decode("utf-8", "replace")+ raise GeminiError(f"HTTP {exc.code}: {body}") from None++ def _upload(self, p: Path, mime: str, max_wait: float = 900.0) -> dict:+ size = p.stat().st_size+ h, _ = self._call("POST", f"{API}/upload/v1beta/files", json.dumps({"file": {"display_name": "rea-video"}}).encode(),+ {"X-Goog-Upload-Protocol": "resumable", "X-Goog-Upload-Command": "start",+ "X-Goog-Upload-Header-Content-Length": str(size), "X-Goog-Upload-Header-Content-Type": mime,+ "Content-Type": "application/json"})+ url = {k.lower(): v for k, v in h.items()}.get("x-goog-upload-url")+ if not url:+ raise GeminiError("the Files API returned no upload URL")+ _, body = self._call("POST", url, p.read_bytes(), {"Content-Length": str(size), "X-Goog-Upload-Offset": "0",+ "X-Goog-Upload-Command": "upload, finalize"}, timeout=3600.0)+ info = json.loads(body)["file"]+ waited = 0.0+ while info.get("state") == "PROCESSING" and waited < max_wait:+ time.sleep(2.0)+ waited += 2.0+ info = json.loads(self._call("GET", f"{API}/v1beta/{info['name']}")[1])+ if info.get("state") != "ACTIVE":+ self._delete(info.get("name", ""))+ raise GeminiError(f"uploaded file state {info.get('state')}")+ return info++ def _delete(self, name: str) -> None:+ if not name:+ return+ try:+ self._call("DELETE", f"{API}/v1beta/{name}")+ except Exception as exc: # noqa: BLE001 cleanup never masks the answer; Google drops it within 48 h+ LOG.warning("could not delete %s from Gemini (%s); it expires within 48 hours", name, str(exc)[:80])++ def ask_json(self, prompt: str, media: list[tuple[Path, str]], max_tokens: int = 4096) -> dict:+ from .vlm import parse_json++ parts, uploaded = [], []+ inline = sum(Path(p).stat().st_size for p, _ in media) <= INLINE_MAX+ try:+ for p, mime in media:+ p = Path(p)+ part: dict+ if inline or not mime.startswith("video/"):+ part = {"inline_data": {"mime_type": mime, "data": base64.b64encode(p.read_bytes()).decode()}}+ else:+ info = self._upload(p, mime)+ uploaded.append(info["name"])+ part = {"file_data": {"mime_type": info.get("mimeType") or mime, "file_uri": info["uri"]}}+ if mime.startswith("video/"):+ d = _duration(p)+ fps = next((f for lim, f in CLIP_FPS if 0 < d <= lim), None)+ if fps:+ part["video_metadata"] = {"fps": fps}+ parts.append(part)+ parts.append({"text": prompt})+ body = {"contents": [{"role": "user", "parts": parts}],+ "generationConfig": {"maxOutputTokens": max_tokens, "temperature": 0.2, "responseMimeType": "application/json"}}+ _, raw = self._call("POST", f"{API}/v1beta/models/{self.model}:generateContent", json.dumps(body).encode(),+ {"Content-Type": "application/json"}, timeout=self.timeout)+ finally:+ for name in uploaded:+ self._delete(name)+ data = json.loads(raw)+ try:+ text = "".join(pt.get("text", "") for pt in data["candidates"][0]["content"]["parts"])+ except (KeyError, IndexError, TypeError) as exc:+ raise GeminiError(f"no answer: {str(data)[:200]}") from exc+ return parse_json(text)diff --git a/rea_video/moments.py b/rea_video/moments.pynew file mode 100644index 0000000..8e4262a--- /dev/null+++ b/rea_video/moments.py@@ -0,0 +1,1031 @@+"""Special moments: the few seconds a viewer remembers. A magic trick's reveal, a drama's twist or goof, a climax.++What a moment *is* is content, so a reader finds them (the VLM, or an agent that can look at images), coarse to fine:++1. find: the transcript, an overview sheet of the whole video and the tool's hints -> the stretches where something+ special happens, each with its kind and one line on what happens;+2. pin: each stretch as a dense sheet -> the setup, the method window (the move that does it), the change itself and+ the reaction; a change that falls between two tiles gets one more look at every frame in between;+3. explain: each moment from setup to change, close -> 3-6 numbered steps (the key one marked, a point to ring where+ sure), the region to zoom on, what the frames show, what is only a guess, why viewers miss it. These become a frame+ diagram with the change frame by frame, a slow cut of the change and a reveal clip, see reveal.py.++The hints come from sound and picture, measured on what the breakdown already decoded: someone reacting (an+interjection, a surprised / happy voice, laughter, a line louder or higher than that speaker's usual), a short burst+in the vocal stem, a fast move that stops dead (the pose held to show the result). Most candidates are not moments:+they point a reader where to look and are never reported themselves.++Cost: the hints are free (no decode); a reader takes one look at the overview (one sheet per ~4 minutes) and one per+two or three stretches, then one to explain them, so with a VLM about 3-5 calls per video, next to the breakdown's up to 60.+"""+from __future__ import annotations++import json+import re+from pathlib import Path++import numpy as np++from .i18n import LangDict, T+from .util import LOG, fmt_time, read_json, write_json++VERSION = 2+STEP = 0.25 # seconds per hint sample+TOP_HINTS = 24+MAX_MOMENTS = 10+PIN_TILES = (24, 48) # frames shown for one stretch: up to PIN_LONG s, then longer stretches+PIN_LONG = 8.0+PIN_SPAN = (2.0, 45.0) # shortest / longest stretch looked at closely (s)+FRAME_TILES = 16 # frames shown when a change falls between two tiles+FIND_EVERY = (0.5, 4.0) # overview spacing bounds (s)+FIND_TILES = 240+FIND_FINE = 0.25 # candidate spacing for the overview (s); picked from by how much the picture changes+FIND_TIME_SHARE = 0.35 # share of the overview spread evenly in time, so a still stretch keeps a few tiles+FIND_AREA_MAX = 320 * 180+EXPLAIN_TILES = 24+EXPLAIN_LONG = 10.0 # longest stretch shown to explain one moment (s)+MAX_STEPS = 6+WINDOW_MAX = 3.0 # longest frame-by-frame stretch (s)+TILE_AREA = {"find": 160 * 90, "pin": 256 * 144, "explain": 320 * 180}++KIND = LangDict({"reveal": "揭秘 / 变化时刻", "twist": "反转时刻", "climax": "高潮时刻", "goof": "穿帮时刻"},+ en={"reveal": "reveal / change", "twist": "twist", "climax": "climax", "goof": "goof"})+KIND_CRITERIA = {+ "reveal": "揭秘 / 变化:东西出现、消失、变成别的(魔术的变化瞬间、开箱、前后对比)",+ "twist": "反转:剧情或说法突然翻转,结果和观众以为的不一样",+ "climax": "高潮:情绪或节奏最高的地方(爆笑、尖叫、音乐炸开、比赛决胜、动作最猛)",+ "goof": "穿帮:不该被看到的被看到了(魔术露馅、道具 / 工作人员 / 收音设备入镜、前后镜头不连贯、台词口误)",+}+ROLE = LangDict({"setup": "初始状态", "method": "手法 / 关键动作", "reveal": "变化瞬间", "reaction": "反应"},+ en={"setup": "setup", "method": "method / key move", "reveal": "the change", "reaction": "reaction"})+ROLES = ("setup", "method", "reveal", "reaction")+ROLE_CRITERIA = {+ "setup": "初始状态:观众被告知 / 看到的“正常”样子(空碗、空手、选好的牌),关键动作开始前最后一个看得清的帧",+ "method": "手法 / 关键动作:变化真正发生的那个动作(遮挡、换手、甩手、扑向镜头、镜头被挡、剪辑点),写一格或一段 \"07-09\"",+ "reveal": "变化瞬间:东西第一次出现 / 消失 / 换掉、看得清的那一格(最重要;只是一团运动模糊的不算);常常比镜头亮出来、人惊呼早,要往前找;结果出现在两格之间就写 \"10-11\",会逐帧再看一次",+ "reaction": "反应:人的反应最强的那一格(惊呼、大笑、凑上去看);没有就不写",+}++REACT = re.compile(r"^[\s,。,.!!??]*(诶|欸|哎|哇|啊|噢|哦|呀|我[靠操去天]|卧槽|握草|天[哪呐啊]|妈呀|什么)|"+ r"卧槽|我靠|我操|我去|天哪|天呐|怎么(变|做|弄|回事|可能|来的|过去)|哪来的|不可能|牛逼|牛啊|太牛|绝了|厉害|神了|离谱|"+ r"\b(wow|whoa|what|no way|oh my|holy|how did)\b", re.I)+MAGIC = re.compile(r"魔术|变魔术|魔术师|扑克|纸牌|硬币|三仙归洞|近景魔术|障眼法|\bmagic(ian)?\b|card trick", re.I)+LOUD_DB, HIGH_ST = 4.0, 2.0++FIND_INSTRUCTIONS = """你是短视频剪辑师,在找这条视频里值得单独剪出来的「特殊时刻」:<FOCUS>+材料:state.lines 是语音识别的台词(时间 说话人 文本 [语气],未校对,同音错字常见),state.screen_text 是画面上读到的字幕 / 花字(时间 文字,有字幕时比台词可靠);图是整片按时间排开的小格总览,格子左上角是秒数;+格子太小看不清时用 state.zoom_cmd 抽一段大图看(把 {start} {end} {every} 换成秒数、{name} 换成一个文件名;段长时 every 写大一点;东西小就加 --focus 只放大那一块;输出可能分成 _1、_2…,以命令打印的 tiles 列表为准;写在 look/zoom/ 里没关系);+能直接看视频的(比如 Gemini):可以直接看 state.video(带声音),比小格准,时间用整片的秒数写;+state.hints 是工具从声音和画面里测到的候选(有人惊呼、人声突然变大、快速动作后突然定住),大约只有一成是真的,只用来提醒你去看哪里。+先通读台词弄清这条视频在演什么(谁要变什么、剧情走到哪),再对着总览找画面上发生变化的地方。++按 JEV 格式回答,只回 JSON:{"moments": ["开始秒-结束秒 类型 概率 一句话:发生了什么", ...]}+- 类型从 kinds 里选;例如 "62.0-70.0 reveal .9 空手变出核桃,出现在左边碗里"。+- 一段从变化前的准备(初始状态)到人的反应结束,通常 3-15 秒;一段只放一次变化:同一个魔术先后变了两次(先出牌、再变花)就写成两段,按时间排。+- 画面里播放的别的视频(回放、录屏里的节目)不算,除非这条视频就是在讲它。+- 总览格子太稀看不清就把段落放宽一点,下一步会逐帧细看。没有特殊时刻就回 {"moments": []}。最多 <MAX> 段,挑最精彩的。"""+PIN_INSTRUCTIONS = """你是短视频剪辑师,在定每个特殊时刻的关键帧。图里每一块是一段(标题写着段编号、类型和时间),格子左上角是格子编号(时间在 state 里)。+state.what 是上一步对这一段的描述,state.lines 是这一段的台词,state.screen_text 是这一段画面上的字。++按 JEV 格式回答,只回 JSON:{"<段编号>": {"keep": "yes .9", "kind": "reveal", "setup": "02", "method": "05-07", "reveal": "09", "reaction": "14",+"what": "一句话:发生了什么", "how": "手法推测 / 穿帮细节,写成推测并给把握"}, ...}+- keep:这段到底是不是特殊时刻(yes / no + 概率);no 的只写 keep。+- 关键帧从 roles 里选,写格子编号;变化发生在两格之间(前一格还没有、后一格已经有)就把 reveal 写成 "10-11"。+- 变化不在这段里(还没开始就结束了,或者在最后一格之后):reveal 写 "before" 或 "after",会挪一下再看。+- what / how 里提到画面写秒数,不写格子编号(报告里看不到格子);how 只写看得见的依据("9.4s 左手一直扣着碗"),魔术手法、穿帮都要标"推测"。+- 格子标签是 "编号 秒数";看不清可以用 state.zoom_cmd 抽更密的大图(把 {start} {end} {every} 换成秒数、{name} 换成文件名,输出文件以命令打印的 tiles 列表为准)。"""+FRAME_INSTRUCTIONS = """你是短视频剪辑师,这一轮逐帧细看:每一块(标题写着段编号和时间)只有变化前后那一小段,格子标签是 "编号 秒数"。+只回 JSON:{"<段编号>": {"reveal": "05"}, ...},reveal 是第一次看清结果的那一格(只是一团运动模糊的不算);+结果在第一格就已经有了写 "00"(记在第一格),最后一格还没有写 "after"(记在最后一格;下一步讲解时可以用 * 改到真正的那一帧)。看完发现上一轮的 what / how 不对,可以在同一段里再写 what / how 改掉(写秒数)。"""+EXPLAIN_INSTRUCTIONS = """你是做魔术揭秘 / 高光解说的剪辑师,要把每个特殊时刻讲给没看懂的观众:工具会按你的回答画一张编号的连续帧图解,剪一段「原速 → 慢放放大 → 定格」的揭秘短片。+图里每一块是一段(标题写着段编号和时间),从初始状态到变化之后,格子标签是 "编号 秒数";state 里每段有上一轮的 what / how 和关键帧 frames(秒)。++按 JEV 格式回答,只回 JSON:{"<段编号>": {"steps": ["4.0 两只空碗倒扣在地上", "5.0 右手扣住左边的碗 @.36,.72", "*5.1 指缝下面出现核桃 @.36,.73", "7.6 松手,镜头这头才看见"],+"frames": "4.83-5.37", "focus": ".15,.50,.55,.90", "what": "一句话(可不写)", "seen": "一句话", "guess": "推测:一句话", "why": "一句话"}, ...}+- steps:3-6 步,按时间排,每步 "秒数 一句话"(关键动作那几步尽量落在 frames 里,比如"指尖捏着核桃靠近碗""手盖住碗""碗里看清核桃");一句话只写画面里看得见的事,不超过 20 字。可以超出图里的时间范围(变化更早 / 更晚时)。+- 关键一步前面加 *:东西第一次看得清地出现 / 消失 / 换掉的那一帧(短片会定格在这一帧,一团运动模糊的不行,往后挪到第一帧清楚的)。变化常常比镜头亮出来、人惊呼早,要往前找(手盖住、挡住、换手、镜头晃开的时候);更早那帧只是模糊的一团,可以作为前一步写进去。格子看不清就用 state.zoom_cmd 抽密的大图逐帧看,秒数写到 0.1 以内。+- 先核对上一轮的 what / 关键帧:逐帧放大看过后发现不对(比如东西其实还在手上),以你这一轮看到的为准,what 和 steps 都按新的写。+- 东西小(几十个像素)时,zoom_cmd 加 --focus x0,y0,x1,y1 只放大那一块再逐帧看(--grid 和 --focus 一起用时,网格是这一块里的坐标,@x,y 要换算回整幅画面)。+- 能直接看视频的(比如 Gemini):先看 state.video 的这一段(带声音)找变化,再用逐帧图定到帧。+- frames:变化的连续过程 "开始秒-结束秒":从关键动作开始(手捏着东西靠近、盖住、挡住)到东西完全看清,通常 0.2-1.5 秒。必须逐帧找:用 state.zoom_cmd 把 every 写成 0.033(每一帧)看这一段,写到 0.01 秒。图解会把这段每一帧放大排成一行,短片慢放的也是这一段——观众要看到东西是怎么一点点过去的,不是突然冒出来。+- @x,y:这一步该看的东西在整幅画面里的位置(0-1,左上角 0,0;整幅画面包括上下的模板、横幅)。先用 state.grid_cmd 抽这一步那一帧的带网格大图(把 {t} 换成这一步的秒数、{t_end} 换成秒数 +0.01),在图上量,圈在那个东西本身上(不是几个东西中间的空隙);只在看得清、确定的时候写,宁缺毋错(画错圈比不画更糟)。圈只在这一步的那一帧附近出现;圈必须在 focus 框里面,框外的圈不画。+- 每一步默认按 focus 放大;要看整个画面的一步(比如另一个人的反应)在句末写 "@全"。+- focus:放大区域 "x0,y0,x1,y1"(0-1,整幅画面坐标),图解和短片都按它放大,框越小放越大;框住手和道具、去掉模板和横幅;整个画面都要看就不写。框的宽高比会被限制在 0.6-1.8(太扁太窄会往外扩),短片里放大的画面按原比例加黑边。+- what:一句话重写这一段发生了什么(必写,图解标题用它;里面提到的秒数要和关键一步一致,或者干脆不写秒数)。+- seen:画面里看得到的证据(写秒数)。guess:画面里看不到、靠推测的部分(手法、道具从哪来),以"推测:"开头;没有就不写。why:观众为什么没发现(注意力被引到哪了);不是魔术可以不写。"""+FOCUS = {"magic": "这是魔术视频:每段魔术的变化瞬间(东西出现、消失、换了),以及露馅 / 穿帮的地方。",+ "drama": "这是剧情视频:反转、情绪高潮,以及穿帮(道具、工作人员、前后不连贯)。",+ "": "精彩的高光时刻:变化 / 揭秘、反转、高潮,以及穿帮。"}+++# ------------------------------------------------------------------ hints (sound + picture) --------------------------++def reactions(lines: list[dict]) -> list[dict]:+ """Lines that sound like a reaction, with a 0-1 strength and why."""+ out = []+ for ln in lines or []:+ text = str(ln.get("text") or "")+ why, s = [], 0.0+ if REACT.search(text):+ s += 0.5+ why.append(T("台词「{x}」", "line “{x}”", x=text[:16]))+ emo = ln.get("emotion")+ if emo == "surprised":+ s += 0.4+ why.append(T("语气惊讶", "surprised voice"))+ elif emo == "happy":+ s += 0.15+ why.append(T("语气开心", "happy voice"))+ ev = ln.get("event")+ if ev in ("laughter", "applause", "cry"):+ s += 0.4+ why.append({"laughter": T("笑声", "laughter"), "applause": T("掌声", "applause"), "cry": T("哭声", "crying")}[ev])+ pr = ln.get("prosody") or {}+ if (pr.get("level_rel") or 0) >= LOUD_DB or (pr.get("pitch_rel_st") or 0) >= HIGH_ST:+ s += 0.25+ why.append(T("比平时大声 / 调高", "louder / higher than usual"))+ if s > 0:+ out.append({"t": float(ln["start"]), "score": min(1.0, s), "why": why})+ return out+++def vocal_bursts(vocals: Path | None, dur: float) -> list[dict]:+ """Short bursts in the vocal stem, 6 dB and more over its last ten seconds: a shout or a laugh the recognizer+ often drops."""+ if not vocals or not Path(vocals).is_file():+ return []+ from .media import extract_audio++ x = extract_audio(vocals, 16000)+ if x is None or not len(x):+ return []+ hop = int(16000 * STEP)+ k = len(x) // hop+ db = 20 * np.log10(np.sqrt((x[:k * hop].reshape(k, hop) ** 2).mean(1) + 1e-10))+ w = int(10 / STEP)+ out = []+ for i in range(k):+ ref = float(np.median(db[max(0, i - w):i + 1]))+ jump = db[i] - ref - 6+ if jump > 0 and db[i] > -45 and (i == 0 or db[i] >= db[i - 1]) and (i + 1 >= k or db[i] >= db[i + 1]):+ out.append({"t": i * STEP, "score": min(1.0, jump / 20), "why": [T("人声突然变大", "voice jumps up")]})+ return out+++def holds(track) -> list[dict]:+ """A fast move that stops dead: the picture's busiest part moves hard, then holds (a pose held to show a result)."""+ if track is None or not track.n:+ return []+ import cv2++ B = np.stack([cv2.resize(t, (12, 8), interpolation=cv2.INTER_AREA) for t in track.thumbs]).astype(np.float32)+ d = np.zeros(len(B))+ d[1:] = np.abs(B[1:] - B[:-1]).max(axis=(1, 2))+ ts = np.asarray(track.times, dtype=float) if track.times is not None and len(track.times) else np.arange(track.n) / track.fps+ idx = np.clip((ts / STEP).astype(int), 0, None)+ n = int(idx.max()) + 1+ cnt = np.bincount(idx, minlength=n)+ m = np.bincount(idx, weights=d, minlength=n) / np.maximum(cnt, 1)+ r = np.argsort(np.argsort(m)) / max(1, n - 1) # rank: a busy video and a calm one alike+ out = []+ for i in range(1, n - 4):+ s = float(r[max(0, i - 4):i + 1].max() * (1 - r[i + 1:i + 5].mean()))+ if s >= 0.7:+ out.append({"t": (i + 1) * STEP, "score": s - 0.5, "why": [T("快速动作后定住", "a fast move stops dead")]})+ return out+++def hints(lines: list[dict], vocals: Path | None, track, dur: float, top: int | None = None) -> list[dict]:+ """The tool's candidate times (where something may happen; for the reader to check), in time order; about one+ per 20 s of video, TOP_HINTS at least."""+ top = top or max(TOP_HINTS, int(dur / 20))+ pts: list[dict] = []+ for r in reactions(lines): # a reaction comes after its cause: point a little before it+ pts.append({"t": max(0.0, r["t"] - 1.0), "score": r["score"], "why": r["why"]})+ for v in vocal_bursts(vocals, dur):+ pts.append({"t": max(0.0, v["t"] - 1.0), "score": 0.5 * v["score"], "why": v["why"]})+ for h in holds(track):+ pts.append({"t": h["t"], "score": 0.5 * h["score"], "why": h["why"]})+ pts.sort(key=lambda p: p["t"])+ merged: list[dict] = []+ for p in pts: # within 1.5 s: one hint, the signals add up+ if merged and p["t"] - merged[-1]["t"] <= 1.5:+ m = merged[-1]+ m["score"] = min(1.0, m["score"] + p["score"])+ m["why"] += [w for w in p["why"] if w not in m["why"]]+ else:+ merged.append({**p, "why": list(p["why"])})+ best = sorted(merged, key=lambda p: -p["score"])[:top]+ return [{"t": round(float(p["t"]), 2), "score": round(float(p["score"]), 2), "why": p["why"][:3]} for p in sorted(best, key=lambda p: p["t"])]+++def genre(b: dict) -> str:+ """"magic" when the title, the words or the VLM say so; "drama" for a story; else ""."""+ src = b.get("source") or {}+ meta = b.get("platform_meta") or {}+ w = b.get("whole_video_vlm") or {}+ title = " ".join(str(x) for x in (src.get("filename"), meta.get("title"), meta.get("desc")) if x)+ said = " ".join(str(ln.get("text") or "") for ln in (b.get("speech") or {}).get("lines") or [])+ seen = " ".join(str(w.get(k) or "") for k in ("summary", "format"))+ if MAGIC.search(title) or MAGIC.search(seen) or len(MAGIC.findall(said)) >= 2:+ return "magic"+ if "剧情" in str(w.get("format") or "") or re.search(r"短剧|剧情|drama", title, re.I):+ return "drama"+ return ""+++# ------------------------------------------------------------------ answers ----------------------------------------++_P = re.compile(r"^(?:0?\.\d+|1(?:\.0+)?)$")+++def _secs(s: str) -> float | None:+ from .vlm import _sec++ return _sec(s)+++def parse_found(ans: dict, dur: float) -> list[dict]:+ """{"moments": ["62.0-70.0 reveal .9 what", {...}]} -> [{"t0", "t1", "kind", "p", "what"}]."""+ out = []+ for m in (ans or {}).get("moments") or []:+ if isinstance(m, dict):+ t0, t1 = _secs(m.get("t0", m.get("start"))), _secs(m.get("t1", m.get("end")))+ kind, p, what = str(m.get("kind") or ""), m.get("p", 0.8), str(m.get("what") or "")+ elif isinstance(m, str):+ parts = m.strip().split(None, 3)+ if not parts or "-" not in parts[0].lstrip("-"):+ continue+ a, _, z = parts[0].partition("-")+ t0, t1 = _secs(a), _secs(z)+ kind = parts[1] if len(parts) > 1 else ""+ rest = parts[2:]+ p = 0.8+ if rest and _P.match(rest[0]):+ p = float(rest[0])+ rest = rest[1:]+ what = " ".join(rest)+ else:+ continue+ if t0 is None or t1 is None or kind not in KIND_CRITERIA:+ continue+ t0, t1 = max(0.0, min(t0, t1)), min(dur, max(t0, t1))+ try:+ p = float(p)+ except (TypeError, ValueError):+ p = 0.8+ if t1 - t0 >= 0.3:+ out.append({"t0": round(t0, 2), "t1": round(t1, 2), "kind": kind, "p": round(p, 2), "what": what.strip()[:120]})+ return sorted(out, key=lambda m: m["t0"])[:MAX_MOMENTS]+++def _tile(v, n: int) -> tuple[int, int] | str | None:+ """"07" -> (7, 7); "07-09" -> (7, 9); "before" / "after"; anything else None."""+ if isinstance(v, (int, float)) and not isinstance(v, bool):+ v = str(int(v))+ if not isinstance(v, str):+ return None+ v = v.strip().split()[0] if v.strip() else ""+ if v in ("before", "after"):+ return v+ a, _, z = v.partition("-")+ try:+ i, j = int(a), int(z) if z else int(a)+ except ValueError:+ return None+ if not (0 <= i < n and 0 <= j < n):+ return None+ return (min(i, j), max(i, j))+++def _yes(v) -> tuple[bool, float]:+ if isinstance(v, bool):+ return v, 1.0+ s = str(v or "yes").strip().split()+ p = float(s[1]) if len(s) > 1 and _P.match(s[1]) else 0.9+ return s[0].lower() not in ("no", "false", "否"), p+++# ------------------------------------------------------------------ sheets -----------------------------------------++def _tile_w(info, look: str, area: float | None = None) -> int:+ import math++ aspect = info.width / info.height if info.width and info.height else 16 / 9+ return max(40, int(round(math.sqrt((area or TILE_AREA[look]) * aspect))))+++def _thumbs(video: str, step: float) -> np.ndarray | None:+ """16x16 RGB thumbnails every `step` s, one decode pass; None when ffmpeg fails."""+ import subprocess++ r = subprocess.run(["ffmpeg", "-v", "error", "-i", video, "-an", "-vf", f"fps=1/{step:.4f},scale=16:16:flags=area",+ "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True)+ if r.returncode != 0 or not r.stdout:+ return None+ a = np.frombuffer(r.stdout, dtype=np.uint8)+ n = a.size // (16 * 16 * 3)+ return a[: n * 768].reshape(n, 768).astype(np.float32) if n else None+++def overview_times(video: str, dur: float, n: int) -> list[float]:+ """n overview times picked by picture change: dense where things move, sparse where nothing does (near-duplicate+ frames merge), with FIND_TIME_SHARE spread by time; uniform when the thumbnails can't be read."""+ uniform = [round(float(t), 2) for t in np.linspace(0.0, max(dur - 0.05, 0.0), n)]+ step = max(FIND_FINE, dur / (n * 8))+ th = _thumbs(video, step)+ if th is None or len(th) < 3 or len(th) <= n:+ return uniform if th is None or len(th) < 3 else [round(i * step, 2) for i in range(len(th)) if i * step < dur]+ diff = np.r_[0.0, np.abs(np.diff(th, axis=0)).mean(axis=1)]+ total = float(diff.sum())+ if total <= 1e-6:+ return uniform+ c = np.cumsum(diff * (1 - FIND_TIME_SHARE) / total + FIND_TIME_SHARE / len(diff))+ idx = np.unique(np.searchsorted(c, np.linspace(c[0], c[-1], n)).clip(0, len(th) - 1))+ return [round(float(i * step), 2) for i in idx if i * step < dur]+++def _blocks_sheets(video: str, info, blocks: list[tuple[str, list[float], list[str]]], look: str, out: Path, stem: str,+ area: float | None = None) -> list[str]:+ """Titled rows of tiles packed onto as few sheets as the reader takes in unshrunk; -> sheet paths (relative)."""+ from .survey import _cols, _grab, _grid, _pack, _sheet++ tw = _tile_w(info, look, area)+ ims = []+ for title, times, labels in blocks:+ grid = _grid(_grab(video, info, times, width=tw), labels, [0.0] * len(times), [False] * len(times),+ cols=_cols(tw, len(times)), tile_w=tw)+ ims.append((title, grid))+ paths = []+ for p, rows in enumerate(_pack([im for _, im in ims]), start=1):+ rel = f"moments/look/{stem}_{p:02d}.jpg"+ _sheet([[ims[k] for k in r] for r in rows], out / rel)+ paths.append(rel)+ return paths+++def _lines_text(lines: list[dict], t0: float = 0.0, t1: float = 1e9) -> list[str]:+ from .prosody import EMOTION++ out = []+ for ln in lines or []:+ if t0 <= float(ln.get("start", 0)) <= t1:+ tag = EMOTION.get(ln.get("emotion") or "", "") or ""+ ev = ln.get("event") or ""+ extra = " [" + "/".join(x for x in (tag, ev) if x) + "]" if (tag or ev) else ""+ out.append(f"{float(ln['start']):.1f} {ln.get('speaker') or ''} {str(ln.get('text') or '')[:60]}{extra}".replace(" ", " "))+ return out+++def _screen_text(b: dict, t0: float = 0.0, t1: float = 1e9, cap: int = 300) -> list[str]:+ """Text read off the frames (subtitles, 花字, labels), once each: often says what happens ("凭空出现!")."""+ out, seen = [], set()+ for c in (b.get("packaging") or {}).get("text_cues") or []:+ t, x = c.get("t0"), str(c.get("text") or "").strip()+ if t is None or not x or x in seen or not (t0 <= float(t) <= t1) or c.get("kind") == "scene":+ continue+ seen.add(x)+ out.append(f"{float(t):.1f} {x[:40]}")+ if len(out) > cap: # spread over the whole video, not its first minutes+ out = [out[int(i)] for i in np.linspace(0, len(out) - 1, cap).round()]+ return out+++def _zoom_cmd(video: str, out: Path) -> str:+ return (f"rea-video tiles '{video}' --start {{start}} --end {{end}} --every {{every}} --cell 320 [--focus x0,y0,x1,y1 --cell 480] "+ f"-o '{out / 'moments' / 'look' / 'zoom' / '{name}.jpg'}'")+++def _grid_cmd(video: str, out: Path) -> str:+ return f"rea-video tiles '{video}' --start {{t}} --end {{t_end}} --every 1 --cols 1 --cell 960 --grid -o '{out / 'moments' / 'look' / 'zoom' / 'grid_{{t}}.jpg'}'"+++def find_task(b: dict, out: Path, info) -> dict:+ video, dur = b["source"]["path"], float(b["source"]["duration"])+ every = min(FIND_EVERY[1], max(FIND_EVERY[0], dur / FIND_TILES))+ n = min(FIND_TILES, max(12, int(dur / every)))+ times = overview_times(video, dur, n)+ area = min(FIND_AREA_MAX, TILE_AREA["find"] * FIND_TILES / max(1, len(times)) * 0.5) if len(times) < FIND_TILES else None+ area = max(area, TILE_AREA["find"]) if area else None+ from .survey import _cols++ tw = _tile_w(info, "find", area)+ per_row = _cols(tw, len(times))+ blocks = []+ for k in range(0, len(times), per_row):+ row = times[k:k + per_row]+ blocks.append((f"{fmt_time(row[0])} – {fmt_time(row[-1])}", row, [f"{t:.1f}" for t in row]))+ images = _blocks_sheets(video, info, blocks, "find", out, "find", area=area)+ g = (b.get("moments") or {}).get("genre", "")+ w = b.get("whole_video_vlm") or {}+ state = {"video": video, "zoom_cmd": _zoom_cmd(video, out), "duration": round(dur, 2), "genre": g or None, "lines": _lines_text((b.get("speech") or {}).get("lines")),+ "screen_text": _screen_text(b),+ "hints": [f"{h['t']:.1f} {'、'.join(h['why'])}" for h in (b.get("moments") or {}).get("hints") or []],+ **({"summary": w["summary"]} if w.get("summary") else {}),+ "overview": "格子按画面变化抽:动得多的地方密、静止的地方稀(几乎一样的帧合并了),左上角是秒数"}+ instr = FIND_INSTRUCTIONS.replace("<FOCUS>", FOCUS.get(g, FOCUS[""])).replace("<MAX>", str(MAX_MOMENTS))+ return {"id": "find", "images": images, "instructions": instr, "state": state,+ "questions": {"moments": {"type": "list", "kinds": KIND_CRITERIA}}, "answer_template": {"filled": True, "moments": []}}+++def _pin_times(t0: float, t1: float, fps: float, n: int) -> list[float]:+ step = max(1.0 / max(fps, 1.0), (t1 - t0) / max(1, n - 1))+ return [round(float(t), 3) for t in np.arange(t0, t1 + 1e-6, step)][:n]+++def pin_task(b: dict, out: Path, info, found: list[dict], rnd: int, spans: dict[str, tuple[float, float]] | None = None,+ dense: bool = False) -> dict:+ """One look at several stretches; spans overrides a stretch's range (a moved or a frame-by-frame look)."""+ video, dur = b["source"]["path"], float(b["source"]["duration"])+ fps = float(b["source"].get("fps") or 30)+ lines = (b.get("speech") or {}).get("lines")+ blocks, state = [], {}+ for m in found:+ t0, t1 = (spans or {}).get(m["id"], (m["t0"], m["t1"]))+ if not dense: # the reader's range as given; a very short one widened, a very long one kept to its middle+ mid, half = (t0 + t1) / 2, max(PIN_SPAN[0], min(PIN_SPAN[1], t1 - t0)) / 2+ t0, t1 = max(0.0, mid - half), min(dur, mid + half)+ times = _pin_times(t0, t1, fps, FRAME_TILES if dense else PIN_TILES[0] if t1 - t0 <= PIN_LONG else PIN_TILES[1])+ blocks.append((f"{m['id']} {m['kind']} {fmt_time(t0)} – {fmt_time(t1)}", times, [f"{j:02d} {t:.2f}" for j, t in enumerate(times)]))+ state[m["id"]] = {"kind": m["kind"], "what": m.get("what", ""), "times": times,+ "lines": _lines_text(lines, t0 - 1.0, t1 + 1.0), "screen_text": _screen_text(b, t0 - 1.0, t1 + 1.0, cap=20)}+ images = _blocks_sheets(video, info, blocks, "pin", out, f"pin_r{rnd}")+ if dense:+ return {"id": f"pin_r{rnd}", "images": images, "instructions": FRAME_INSTRUCTIONS, "state": state,+ "questions": {"per": "stretch", "reveal": ROLE_CRITERIA["reveal"]},+ "answer_template": {"filled": True, **{m["id"]: {"reveal": ""} for m in found}}}+ return {"id": f"pin_r{rnd}", "images": images, "instructions": PIN_INSTRUCTIONS,+ "state": {"video": video, "zoom_cmd": _zoom_cmd(video, out), **state},+ "questions": {"per": "stretch", "roles": ROLE_CRITERIA, "kinds": KIND_CRITERIA},+ "answer_template": {"filled": True, **{m["id"]: {} for m in found}}}+++def explain_task(b: dict, out: Path, info, items: list[dict]) -> dict:+ """Each moment from setup to just after the change, closer than the pin look, for the steps."""+ video, dur = b["source"]["path"], float(b["source"]["duration"])+ fps = float(b["source"].get("fps") or 30)+ lines = (b.get("speech") or {}).get("lines")+ blocks, state = [], {}+ for it in items:+ fr = it["frames"]+ t1 = min(dur, max(it["t"] + 0.8, fr.get("reaction", 0.0)))+ t0 = max(0.0, min(fr.values()) - 0.5, t1 - EXPLAIN_LONG)+ times = _pin_times(t0, t1, fps, EXPLAIN_TILES)+ blocks.append((f"{it['id']} {it['kind']} {fmt_time(t0)} – {fmt_time(t1)}", times, [f"{j:02d} {t:.2f}" for j, t in enumerate(times)]))+ state[it["id"]] = {"kind": it["kind"], "what": it.get("what", ""), "how": it.get("how", ""),+ "frames": {r: fr[r] for r in ROLES if r in fr}, "times": times,+ "lines": _lines_text(lines, t0 - 1.0, t1 + 1.0), "screen_text": _screen_text(b, t0 - 1.0, t1 + 1.0, cap=20)}+ images = _blocks_sheets(video, info, blocks, "explain", out, "explain")+ return {"id": "explain", "images": images, "instructions": EXPLAIN_INSTRUCTIONS,+ "state": {"video": video, "zoom_cmd": _zoom_cmd(video, out), "grid_cmd": _grid_cmd(video, out), **state},+ "questions": {"per": "moment", "fields": ["steps", "frames", "focus", "what", "seen", "guess", "why"]},+ "answer_template": {"filled": True, **{it["id"]: {"steps": [], "frames": "", "focus": "", "what": "", "seen": "", "guess": "", "why": ""}+ for it in items}}}+++_STEP = re.compile(r"^\s*(\*)?\s*(\d+(?::\d+)?(?:\.\d+)?)\s*s?\s+(.+?)\s*(?:@\s*([01]?\.\d+|[01])\s*[,,]\s*([01]?\.\d+|[01]))?\s*$")+++def _frac(v) -> float | None:+ try:+ x = float(v)+ except (TypeError, ValueError):+ return None+ return x if 0.0 <= x <= 1.0 else None+++def parse_steps(v, dur: float) -> list[dict]:+ """["*5.1 指缝下面出现核桃 @.36,.73", ...] or dicts -> [{t, text, key?, at?}] in time order; one key step at most."""+ out = []+ for s in v if isinstance(v, list) else []:+ if isinstance(s, dict):+ t = _secs(str(s.get("t", "")))+ text, key = str(s.get("text") or "").strip(), bool(s.get("key"))+ at = s.get("at") if isinstance(s.get("at"), (list, tuple)) and len(s.get("at")) == 2 else None+ at = (_frac(at[0]), _frac(at[1])) if at else None+ else:+ raw = str(s)+ whole = bool(re.search(r"\s*@\s*(全|full)\s*$", raw, re.I))+ m = _STEP.match(re.sub(r"\s*@\s*(全|full)\s*$", "", raw, flags=re.I))+ if not m:+ continue+ t, text, key = _secs(m.group(2)), m.group(3).strip(), bool(m.group(1))+ at = (_frac(m.group(4)), _frac(m.group(5))) if m.group(4) else None+ if t is None or not text or not (0.0 <= t <= dur):+ continue+ st = {"t": round(float(t), 2), "text": text[:40]}+ if (s.get("whole") if isinstance(s, dict) else whole):+ st["whole"] = True+ if key:+ st["key"] = True+ if at and None not in at:+ st["at"] = [round(at[0], 3), round(at[1], 3)]+ out.append(st)+ out.sort(key=lambda x: x["t"])+ keys = [s for s in out if s.get("key")]+ for s in keys[1:]:+ s.pop("key")+ if len(out) > MAX_STEPS:+ rest = [s for s in out if not s.get("key")][:MAX_STEPS - len(keys[:1])]+ out = sorted(rest + keys[:1], key=lambda x: x["t"])+ return out+++def _box(v) -> list[float] | None:+ xs = [_frac(x) for x in re.split(r"[\s,,]+", str(v).strip())] if v else []+ if len(xs) != 4 or None in xs or xs[2] - xs[0] < 0.05 or xs[3] - xs[1] < 0.05:+ return None+ return [round(x, 3) for x in xs]+++def _window(v, dur: float) -> list[float] | None:+ """"4.83-5.37" -> [4.83, 5.37]: the change frame by frame, at most WINDOW_MAX s."""+ m = re.match(r"^\s*([\d:.]+)\s*[-–~]\s*([\d:.]+)\s*s?\s*$", str(v or ""))+ if not m:+ return None+ a, z = _secs(m.group(1)), _secs(m.group(2))+ if a is None or z is None or not (0.0 <= a < z <= dur) or z - a > WINDOW_MAX:+ return None+ return [round(a, 3), round(z, 3)]+++def apply_explain(it: dict, a: dict, dur: float) -> None:+ """The reader's steps onto a moment; a key step moves the change to it (a closer look than the pin rounds)."""+ steps = parse_steps((a or {}).get("steps"), dur)+ if not steps:+ return+ ex = {"steps": steps}+ if _box(a.get("focus")):+ ex["focus"] = _box(a.get("focus"))+ win = _window(a.get("frames"), dur)+ if win:+ ex["frames"] = win+ for k in ("seen", "guess", "why"):+ if str(a.get(k) or "").strip():+ ex[k] = str(a[k]).strip()[:120]+ if str(a.get("what") or "").strip():+ it["what"] = str(a["what"]).strip()[:200]+ it["explain"] = ex+ key = next((s for s in steps if s.get("key")), None)+ if key:+ fr = it["frames"]+ it["t"] = fr["reveal"] = key["t"]+ before = [s["t"] for s in steps if s["t"] < key["t"]]+ if fr.get("method", 0) >= key["t"]:+ fr.pop("method")+ if len(before) >= 2:+ fr["method"] = before[-1]+ if fr.get("setup", 0) >= fr.get("method", key["t"]):+ fr["setup"] = before[0] if before else round(max(0.0, key["t"] - 2.0), 3)+ if fr.get("reaction", 1e9) <= key["t"]:+ fr.pop("reaction")+ if it.get("method_span") and it["method_span"][0] >= key["t"]:+ it.pop("method_span")+ ts = [s["t"] for s in steps]+ it["span"] = [round(max(0.0, min(it["span"][0], min(ts) - 1.0)), 2), round(min(dur, max(it["span"][1], max(ts) + 1.5)), 2)]+++# ------------------------------------------------------------------ the loop ---------------------------------------++def _paths(out: Path, tid: str) -> tuple[Path, Path]:+ d = out / "moments" / "look"+ return d / f"{tid}.task.json", d / f"{tid}.answer.json"+++def _answer(out: Path, tid: str) -> dict | None:+ _, ap = _paths(out, tid)+ if not ap.is_file():+ return None+ try:+ a = read_json(ap)+ except (ValueError, OSError):+ return None+ return a if isinstance(a, dict) and a.get("filled") else None+++def _put(out: Path, task: dict) -> None:+ tp, ap = _paths(out, task["id"])+ write_json(tp, task)+ if not ap.is_file():+ write_json(ap, {**task["answer_template"], "filled": False})+++VIDEO_NOTE = ("另外附了视频(带声音),按顺序是:{list}。变化以视频为准(看连续的动作、听声音),"+ "图里的格子用来对时间、写格子编号;视频里的时间从片段开头算,要换算成整片的秒数(加上片段开始秒数)。")+CLIP_PAD = 0.5+++def _wants_video(client) -> bool:+ """Gemini takes video; an OpenAI-compatible VLM does unless REA_VLM_MEDIA=frames."""+ if getattr(client, "video_ok", False):+ return True+ cfg = getattr(client, "cfg", None)+ return bool(cfg) and getattr(cfg, "media", "both") != "frames"+++def _task_clips(task: dict, clip_dir: Path) -> list[tuple[Path, str]]:+ """Clips with sound for a task: the whole video (low res) for the overview, each stretch for a closer look."""+ from .media import cut_clip, video_info++ st = task.get("state") or {}+ video = st.get("video")+ if not video or not Path(video).is_file():+ return []+ clip_dir.mkdir(parents=True, exist_ok=True)+ if task["id"] == "find":+ p = clip_dir / "whole_480p.mp4"+ if not p.is_file():+ cut_clip(video, 0.0, video_info(video).duration, p, width=480, audio=True, crf=30)+ return [(p, "整片 0 秒起")]+ out = []+ for mid, s in st.items():+ if isinstance(s, dict) and s.get("times"):+ a, z = max(0.0, s["times"][0] - CLIP_PAD), s["times"][-1] + CLIP_PAD+ p = clip_dir / f"{task['id']}_{mid}_{a:.2f}-{z:.2f}.mp4"+ if not p.is_file():+ cut_clip(video, a, z - a, p, width=640, audio=True, crf=24)+ out.append((p, f"{mid} 从 {a:.2f} 秒起"))+ return out+++def vlm_asker(client, lang_note: str = ""):+ def ask(task: dict, images: list[Path]) -> dict:+ q = {k: task[k] for k in ("state", "questions")}+ prompt = (f"{task['instructions']}\n\n{lang_note}\n请求:\n{json.dumps(q, ensure_ascii=False)}\n\n"+ f"只输出 JSON,形如 {json.dumps(task['answer_template'], ensure_ascii=False)}。")+ media = [(p, "image/jpeg") for p in images]+ clips = []+ if _wants_video(client) and images:+ try:+ clips = _task_clips(task, Path(images[0]).parent / "clips")+ except Exception as exc: # noqa: BLE001 the images alone still answer+ LOG.warning("special moments: no clip for %s (%s)", task["id"], str(exc)[:80])+ if clips:+ note = VIDEO_NOTE.format(list=";".join(f"视频 {k} = {lbl}" for k, (_, lbl) in enumerate(clips, start=1)))+ try:+ got = client.ask_json(prompt + "\n\n" + note, [(p, "video/mp4") for p, _ in clips] + media, max_tokens=3000)+ if isinstance(got, dict) and got:+ return got+ except Exception as exc: # noqa: BLE001 a reader that refuses video: ask again with the images+ LOG.warning("special moments: the reader refused the clips (%s); images only", str(exc)[:80])+ got = client.ask_json(prompt, media, max_tokens=3000)+ return got if isinstance(got, dict) else {}+ return ask+++def run(b: dict, out: Path, asker=None) -> dict:+ """Advance the look as far as the answers allow. With `asker` (a VLM) each task is answered at once; without it+ the waiting answer files are returned for an agent to fill, then this runs again.+ -> {"status": "done" | "waiting", ...}; when done, b["moments"]["items"] holds the moments."""+ from .media import video_info++ out = Path(out)+ video = b["source"]["path"]+ info = video_info(video)+ dur = float(b["source"]["duration"])+ mo = b.setdefault("moments", {})+ meta_p = out / "moments" / "look" / "look.json"+ meta = read_json(meta_p) if meta_p.is_file() else {}+ src = {"sha256_head": b["source"].get("sha256_head"), "version": VERSION}+ if meta.get("source") != src:+ for p in (out / "moments" / "look").glob("*") if (out / "moments" / "look").is_dir() else []:+ p.unlink()+ meta = {"source": src, "rounds": []}++ def step(task: dict) -> dict | None:+ if not _paths(out, task["id"])[0].is_file():+ _put(out, task)+ got = _answer(out, task["id"])+ if got is None and asker is not None:+ got = {"filled": True, "by": "vlm", **(asker(task, [out / im for im in task["images"]]) or {})}+ write_json(_paths(out, task["id"])[1], got)+ return got++ def waiting(task: dict) -> dict:+ tp, ap = _paths(out, task["id"])+ return {"status": "waiting", "stage": task["id"], "tasks": [str(tp)], "waiting": [str(ap)],+ "images": [str(out / im) for im in task["images"]]}++ # ---- find+ tp, _ = _paths(out, "find")+ task = read_json(tp) if tp.is_file() else find_task(b, out, info)+ ans = step(task)+ if ans is None:+ write_json(meta_p, meta)+ return waiting(task)+ found = parse_found(ans, dur)+ for k, m in enumerate(found, start=1):+ m["id"] = f"M{k}"+ by = ans.get("by") or "agent"+ if not found:+ mo.update(items=[], looked_by=by, status="done")+ write_json(meta_p, meta)+ return {"status": "done", "moments": 0}++ # ---- pin: a round for every stretch, then one closer look where the change fell between tiles or outside+ state: dict[str, dict] = {m["id"]: {"m": m} for m in found}+ spans: dict[str, tuple[float, float]] = {}+ todo = [m for m in found]+ rnd = 0+ dense = False+ while todo and rnd < 3:+ rnd += 1+ tid = f"pin_r{rnd}"+ tp, _ = _paths(out, tid)+ task = read_json(tp) if tp.is_file() else pin_task(b, out, info, todo, rnd, spans, dense=dense)+ ans = step(task)+ if ans is None:+ write_json(meta_p, meta)+ return waiting(task)+ nxt, nspans, ndense = [], {}, False+ for m in todo:+ st = task["state"].get(m["id"]) or {}+ times = st.get("times") or []+ a = ans.get(m["id"]) if isinstance(ans.get(m["id"]), dict) else {}+ s = state[m["id"]]+ if not dense:+ keep, p = _yes(a.get("keep"))+ s.update(keep=keep, p=p)+ if not keep:+ continue+ kind = str(a.get("kind") or "").split()[0] if str(a.get("kind") or "").strip() else ""+ if kind in KIND_CRITERIA:+ s["kind"] = m["kind"] = kind+ for k in ("what", "how"):+ if a.get(k):+ s[k] = str(a[k]).strip()[:200]+ if s.get("what"):+ m["what"] = s["what"] # the next look shows the reader's latest words+ for r in ROLES:+ v = _tile(a.get(r), len(times))+ if isinstance(v, tuple):+ s.setdefault("frames", {})[r] = round((times[v[0]] + times[v[1]]) / 2, 3) if r != "reveal" else times[v[1]]+ if r == "method" and v[1] > v[0]:+ s["method_span"] = [times[v[0]], times[v[1]]]+ if r == "reveal":+ if v in ("before", "after") and not s.get("moved"): # outside the stretch: move it once+ s["moved"] = True+ w = times[-1] - times[0] if times else 6.0+ c = (times[0] - w / 2) if v == "before" else (times[-1] + w / 2)+ nspans[m["id"]] = (max(0.0, c - w / 2), min(dur, c + w / 2))+ nxt.append(m)+ elif isinstance(v, tuple) and v[1] > v[0] and v[1] - v[0] <= 2:+ s["between"] = (times[v[0]], times[v[1]])+ else:+ v = _tile(a.get("reveal"), len(times))+ if isinstance(v, tuple):+ s.setdefault("frames", {})["reveal"] = times[v[1]] if v[1] > v[0] else times[v[0]]+ elif v in ("before", "after") and times: # every frame between two tiles: the change is at one end+ s.setdefault("frames", {})["reveal"] = times[0] if v == "before" else times[-1]+ for k in ("what", "how"): # a closer look may correct the last one+ if a.get(k):+ s[k] = str(a[k]).strip()[:200]+ s.pop("between", None)+ if not nxt and not dense:+ fine = [state[i]["m"] for i in state if state[i].get("between")]+ if fine:+ nxt, ndense = fine, True+ nspans = {m["id"]: state[m["id"]]["between"] for m in fine}+ todo, spans, dense = nxt, nspans, ndense++ items = []+ for s in state.values():+ if not s.get("keep", False) or "reveal" not in (s.get("frames") or {}):+ continue+ m, fr = s["m"], s["frames"]+ rv = fr["reveal"]+ if fr.get("method", 0) > rv: # a range read the wrong way round: the move comes before the change+ fr.pop("method")+ s.pop("method_span", None)+ if fr.get("setup", 0) > rv:+ fr.pop("setup")+ fr.setdefault("setup", round(max(m["t0"], rv - 2.0), 3))+ fr.setdefault("method", round(max(fr["setup"], rv - 0.5), 3))+ items.append({"kind": s.get("kind") or m["kind"], "t": rv, "frames": {r: fr[r] for r in ROLES if r in fr},+ **({"method_span": s["method_span"]} if s.get("method_span") else {}),+ "span": [round(max(0.0, min(m["t0"], min(fr.values()) - 1.0)), 2), round(min(dur, max(m["t1"], max(fr.values()) + 1.5)), 2)],+ "what": s.get("what") or m.get("what", ""), "how": s.get("how", ""), "p": s.get("p", m.get("p")), "by": by})+ items.sort(key=lambda x: x["t"])+ for k, it in enumerate(items, start=1):+ it["id"] = f"M{k}"++ # ---- explain: the steps, for the diagram and the reveal clip+ if items:+ tp, _ = _paths(out, "explain")+ task = read_json(tp) if tp.is_file() else explain_task(b, out, info, items)+ ans = step(task)+ if ans is None:+ write_json(meta_p, meta)+ return waiting(task)+ for it in items:+ a = ans.get(it["id"])+ if isinstance(a, dict):+ apply_explain(it, a, dur)+ mo.update(items=items, looked_by=by, status="done")+ write_json(meta_p, meta)+ return {"status": "done", "moments": len(items)}+++# ------------------------------------------------------------------ export -----------------------------------------++def export(b: dict, out: Path) -> None:+ """Per moment: a clip with sound, the key frames full size and one picture (moments/M1.jpg): the numbered step+ diagram when the moment was explained, else a strip of the key frames; plus the reveal clip (moments/M1_reveal.mp4)."""+ from .media import cut_clip, extract_frame+ from . import reveal++ items = (b.get("moments") or {}).get("items") or []+ if not items:+ return+ out = Path(out)+ video = b["source"]["path"]+ if not Path(video).is_file():+ return+ d = out / "moments"+ d.mkdir(parents=True, exist_ok=True)+ w = min(1080, int(b["source"].get("width") or 1080))+ for it in items:+ files = {}+ for r, t in it["frames"].items():+ p = d / f"{it['id']}_{r}_{t:.2f}s.jpg"+ if not p.is_file():+ extract_frame(video, t, p, width=w)+ files[r] = p.name+ a, z = it["span"]+ clip = d / f"{it['id']}_{a:.1f}-{z:.1f}s.mp4"+ if not clip.is_file():+ try:+ cut_clip(video, a, min(30.0, z - a), clip, width=720, audio=bool(b["source"].get("has_audio")), crf=23)+ except Exception: # noqa: BLE001 the frames still stand without the clip+ clip = None+ strip = d / f"{it['id']}.jpg"+ ex = it.get("explain") or {}+ rv = None+ strip.unlink(missing_ok=True)+ if ex.get("steps"):+ sw, sh = int(b["source"].get("width") or 0), int(b["source"].get("height") or 0)+ box = reveal.zoom_box(ex.get("focus"), [tuple(s["at"]) for s in ex["steps"] if s.get("at") and not s.get("whole")], sw, sh) if sw and sh else None+ if box: # a ring outside the zoom would be drawn off the picture: drop it+ bx = (box[0] / sw, box[1] / sh, (box[0] + box[2]) / sw, (box[1] + box[3]) / sh)+ for s in ex["steps"]:+ if s.get("at") and not s.get("whole") and not (bx[0] <= s["at"][0] <= bx[2] and bx[1] <= s["at"][1] <= bx[3]):+ s.pop("at")+ notes = [(k, T(lbl, en) + ex[k]) for k, lbl, en in (("seen", "看得到的:", "Seen: "), ("guess", "看不到的:", "Not on screen: "),+ ("why", "为什么没发现:", "Why it's missed: ")) if ex.get(k)]+ title = f"{it['id']} · {KIND.get(it['kind'], it['kind'])}" + (f" · {it['what'][:60]}" if it.get("what") else "")+ sub = T("{a}–{b},{z}红圈 = 该看的地方", "{a}–{b}, {z}red ring = where to look", a=fmt_time(ex["steps"][0]["t"])[:-2],+ b=fmt_time(ex["steps"][-1]["t"])[:-2], z=T("局部放大;", "zoomed; ") if box else "")+ kt = next((s["t"] for s in ex["steps"] if s.get("key")), None)+ fps = float(b["source"].get("fps") or 30)+ win = ex.get("frames") or ([max(0.0, kt - reveal.SEQ_DEFAULT[0]), kt + reveal.SEQ_DEFAULT[1]] if kt is not None else None)+ seq = reveal.seq_times(win[0], win[1], fps, kt) if win else []+ step_ms = round((seq[1] - seq[0]) * 1000) if len(seq) > 1 else 0+ seq_title = T("逐帧过程 {a:.2f}–{z:.2f}s(每格间隔约 {ms} 毫秒{k};前后灰色格是变化前后的样子)", "Frame by frame {a:.2f}–{z:.2f}s (about {ms} ms apart{k}; grey tiles: before and after)",+ a=win[0], z=win[1], ms=step_ms, k=T(",红框是关键一帧", ", key frame in red") if kt is not None else "") if seq else ""+ reveal.diagram(video, ex["steps"], box, title, sub, notes, strip, seq=seq, seq_title=seq_title, key=kt,+ seq_labels=(T("前 ", "before "), T("后 ", "after ")))+ kt = kt if kt is not None else it["t"]+ rp = d / (f"{it['id']}_reveal_{kt:.2f}s" + (f"_{win[0]:.2f}-{win[1]:.2f}" if ex.get("frames") else "") + ".mp4")+ try:+ rv = rp if rp.is_file() else reveal.reveal_clip(+ video, bool(b["source"].get("has_audio")), (sw, sh), float(b["source"]["duration"]), tuple(it["span"]), ex["steps"],+ box, ex.get("guess", ""), rp, {"speed": T("原速", "Speed"), "slow": T("慢放 1/{n}", "Slow 1/{n}"),+ "hold": T("定格 {t:.2f}s", "Hold {t:.2f}s"), "react": T("反应", "Reaction")},+ window=tuple(ex["frames"]) if ex.get("frames") else None)+ except Exception: # noqa: BLE001 the diagram and the plain clip still stand+ rv = None+ sl = None+ if ex.get("steps") and sw and sh:+ win_s = ex.get("frames") or ([max(0.0, kt - reveal.SEQ_DEFAULT[0]), kt + reveal.SEQ_DEFAULT[1]] if kt is not None else None)+ if win_s:+ sp = d / f"{it['id']}_slow_{win_s[0]:.2f}-{win_s[1]:.2f}.mp4"+ key_step = next((s for s in ex["steps"] if s.get("key")), None)+ try:+ sl = sp if sp.is_file() else reveal.slow_clip(+ video, (sw, sh), float(b["source"]["duration"]), fps, tuple(win_s), kt, box,+ tuple(key_step["at"]) if key_step and key_step.get("at") else None, sp,+ {"slow": T("逐帧慢放 {i}/{n}", "Frame by frame {i}/{n}"), "pre": T("慢放 · 之前", "Slow · before"),+ "post": T("慢放 · 之后", "Slow · after"),+ "key": key_step["text"] if key_step else ""})+ except Exception: # noqa: BLE001+ sl = None+ if not strip.is_file():+ _strip([(d / files[r], ROLE[r], it["frames"][r]) for r in ROLES if r in files], strip)+ it["files"] = {"frames": files, "strip": f"moments/{strip.name}", **({"clip": f"moments/{clip.name}"} if clip else {}),+ **({"reveal": f"moments/{rv.name}"} if rv else {}), **({"slow": f"moments/{sl.name}"} if sl else {})}+ keep = set(files.values()) | {Path(x).name for x in (clip, rv, sl) if x}+ for p in d.glob(f"{it['id']}_*"): # files of an earlier answer (other times) go+ if p.name not in keep:+ p.unlink()+++def _strip(cells: list[tuple[Path, str, float]], out: Path, h: int = 360) -> None:+ from PIL import Image, ImageDraw++ from .visual import _font++ ims = []+ font = _font(20)+ for p, label, t in cells:+ try:+ im = Image.open(p).convert("RGB")+ except OSError:+ continue+ im = im.resize((max(1, int(im.width * h / im.height)), h))+ dr = ImageDraw.Draw(im)+ text = f"{label} {t:.1f}s"+ dr.rectangle([0, 0, int(dr.textlength(text, font=font)) + 10, 28], fill=(0, 0, 0))+ dr.text((5, 3), text, fill=(255, 255, 255), font=font)+ ims.append(im)+ if not ims:+ return+ sheet = Image.new("RGB", (sum(i.width for i in ims) + 6 * (len(ims) - 1), h), (255, 255, 255))+ x = 0+ for im in ims:+ sheet.paste(im, (x, 0))+ x += im.width + 6+ sheet.save(out, quality=88)+++# ------------------------------------------------------------------ text -------------------------------------------++def report_md(b: dict) -> list[str]:+ """The report's own block: every moment with its strip, what happens, how, and the clip."""+ mo = b.get("moments") or {}+ items = mo.get("items") or []+ if not items:+ return []+ L = ["", T("## 特殊时刻", "## Special moments"), ""]+ for it in items:+ L += [T("### {id} · {k} · {t}", "### {id} · {k} · {t}", id=it["id"], k=KIND.get(it["kind"], it["kind"]), t=fmt_time(it["t"])[:-2]), ""]+ f = it.get("files") or {}+ if f.get("strip"):+ L += [f"![{it['id']}]({f['strip']})", ""]+ ex = it.get("explain") or {}+ if f.get("slow"):+ L.append(T("- **揭秘时刻慢放**:[{c}]({c})(前 1 秒和后 1 秒 1/3 速,变化那一段每帧停 0.2 秒,都带时间;关键一帧画圈并停住)",+ "- **The change, slowed**: [{c}]({c}) (a second before and after at 1/3 speed, the change itself held 0.2 s a frame, all timed; the key frame ringed and held)", c=f["slow"]))+ if f.get("reveal"):+ L += [T("- **揭秘短片**:[{c}]({c})(原速 → 变化过程慢放放大 → 定格 → 反应)", "- **Reveal clip**: [{c}]({c}) (at speed → the change slowed and zoomed → held → reaction)",+ c=f["reveal"]), ""]+ if it.get("what"):+ L.append(T("- **发生了什么**:{x}", "- **What happens**: {x}", x=it["what"]))+ for j, st in enumerate(ex.get("steps") or [], start=1):+ L.append(f" {j}. {st['t']:g}s {'**' + st['text'] + '**' if st.get('key') else st['text']}")+ for k, zh, en in (("seen", "看得到的", "Seen"), ("guess", "看不到的", "Not on screen"), ("why", "为什么没发现", "Why it's missed")):+ if ex.get(k):+ L.append(f"- **{T(zh, en)}**{T(':', ': ')}{ex[k]}")+ if it.get("how") and not ex.get("guess"):+ L.append(T("- **怎么做到的 / 细节**:{x}", "- **How / detail**: {x}", x=it["how"]))+ L.append(T("- **关键帧**:", "- **Key frames**: ") + T(",", ", ").join(f"{ROLE[r]} {it['frames'][r]:.1f}s" for r in ROLES if r in it["frames"])+ + (T("(手法窗口 {a:.1f}–{z:.1f}s)", " (method window {a:.1f}–{z:.1f}s)", a=it["method_span"][0], z=it["method_span"][1]) if it.get("method_span") else ""))+ if f.get("clip"):+ L.append(T("- **片段**:[{c}]({c})({a:.1f}–{z:.1f}s,带声音)", "- **Clip**: [{c}]({c}) ({a:.1f}–{z:.1f}s, with sound)",+ c=f["clip"], a=it["span"][0], z=it["span"][1]))+ L.append("")+ L.append(T("_特殊时刻由 {by} 看图找出;手法和穿帮是推测。_", "_Special moments found by {by} looking at the frames; methods and goofs are guesses._",+ by=_by(mo.get("looked_by"))))+ return L+++def _by(by: str | None) -> str:+ return {"vlm": "VLM", "agent": "agent"}.get(by or "", by or "agent")+++def videomd(b: dict) -> list[str]:+ """For the model pack: the moments, one line each, or how to find them."""+ mo = b.get("moments") or {}+ items = mo.get("items") or []+ if items:+ L = ["## " + T("特殊时刻", "Special moments"), ""]+ for it in items:+ fr = " ".join(f"{r} {it['frames'][r]:.2f}" for r in ROLES if r in it["frames"])+ fs = it.get("files") or {}+ L.append(f"- {it['id']} {it['kind']} {it['t']:.2f}s | {fr} | {it.get('what', '')}"+ + (f" | how~ {it['how']}" if it.get("how") else "") + (f" | {fs['clip']}" if fs.get("clip") else "")+ + (f" | {fs['reveal']}" if fs.get("reveal") else ""))+ ex = it.get("explain") or {}+ if ex.get("steps"):+ L.append(" - steps: " + (f"frames {ex['frames'][0]:.2f}-{ex['frames'][1]:.2f} | " if ex.get("frames") else "") + "; ".join(("*" if s.get("key") else "") + f"{s['t']:.1f} {s['text']}" for s in ex["steps"])+ + "".join(f" | {k}~ {ex[k]}" if k == "guess" else f" | {k}: {ex[k]}" for k in ("seen", "guess", "why") if ex.get(k)))+ return L+ if mo.get("status") == "done":+ return ["## " + T("特殊时刻", "Special moments"), "", T("- 看过了,没有找到特殊时刻", "- Looked: no special moments found")]+ L = ["## " + T("特殊时刻", "Special moments"), "",+ T("- 还没有看图找:运行 `rea-video moments <本目录>`,按输出看图作答(开了 VLM 时 decompose 会自动做)",+ "- Not looked for yet: run `rea-video moments <this dir>` and answer from the images (decompose does it itself with a VLM)")]+ if mo.get("genre") == "magic":+ L.append(T("- 这是魔术视频:建议找出每段魔术的变化瞬间", "- This is a magic video: find each trick's reveal"))+ hs = mo.get("hints") or []+ if hs:+ L.append(T("- 工具候选(只供参考,约一成是真的):", "- Tool hints (for reference, about one in ten is real): ")+ + "; ".join(f"{h['t']:.1f}s {'/'.join(h['why'])}" for h in hs[:10]))+ return L+++def summary_line(b: dict) -> str | None:+ items = (b.get("moments") or {}).get("items") or []+ if not items:+ return None+ return T("特殊时刻", "Special moments") + ": " + "; ".join(+ f"{it['id']} {fmt_time(it['t'])[:-2]} {KIND.get(it['kind'], it['kind'])}" + (f" {it['what'][:60]}" if it.get("what") else "") for it in items)diff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex bf607f9..0c0544d 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -126,7 +126,7 @@ def decode_fingerprint() -> 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 | None = None, max_shots_vlm: int = 60,platform_meta: dict | None = None, stems: bool = True, memory: bool = True, packaging: bool = True, asr: bool = True,- lang: str = "zh", speakers: bool = True, survey: bool = True) -> dict:+ lang: str = "zh", speakers: bool = True, survey: bool = True, moments: bool = True) -> dict:lang = set_lang(lang)require_tools()t0 = time.time()@@ -326,7 +326,7 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,LOG.warning("--vlm requested but no VLM config found (REA_VLM_* / VIDEO_ANALYSIS_* / GEMINI3_*); continuing without it")vlm_info = {"used": False, "requested": True, "status": "not_configured", "error": "no_config"}else:- client = vlm_client or VLMClient(cfg, out / "vlm_cache")+ client = vlm_client = vlm_client or VLMClient(cfg, out / "vlm_cache")vlm_info = {"used": False, "requested": True, "status": "failed", "model": cfg.describe(), "media": cfg.media, "errors": []}def run_unit(unit: list[dict]) -> None:@@ -465,6 +465,14 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,}if pack is not None:breakdown["packaging"] = round_floats(pack)+ if moments:+ mclient = vlm_client if vlm_info.get("used") else None+ if mclient is None and use_vlm: # asked for a VLM but only a Gemini key is set: Gemini's own API reads the moments+ from . import gemini++ if gemini.configured():+ mclient = gemini.GeminiClient()+ _moments(breakdown, out, track, stem_info, mclient)if memory:from .memory import reapply@@ -485,6 +493,24 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,return breakdown+def _moments(b: dict, out: Path, track, stem_info: dict, client) -> None:+ """Special moments: the tool's hints from sound and picture always (free); with a VLM, its look (a few calls)."""+ from . import moments as mo++ try:+ voc = Path(stem_info["vocals"]) if stem_info.get("ok") else None+ b["moments"] = {"genre": mo.genre(b), "status": "pending",+ "hints": mo.hints((b.get("speech") or {}).get("lines") or [], voc, track, b["source"]["duration"])}+ if client is not None:+ from .vlm import prompt_lang_note++ LOG.info("special moments: the VLM looks for them (%s)", b["moments"]["genre"] or "any video")+ got = mo.run(b, out, asker=mo.vlm_asker(client, prompt_lang_note()))+ LOG.info("special moments: %s", got)+ except Exception as exc: # noqa: BLE001 an extra: the breakdown goes on without it+ LOG.warning("special moments skipped: %s", str(exc)[:160])++DOUBT_CAP = 0.7PACKAGING_VERSION = 2@@ -1124,6 +1150,13 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:breakdown["production_plan"] = production_plan(breakdown, out, engine=engine)summary["production"] = breakdown["production_plan"]["summary"]breakdown["summary"] = summary+ if (breakdown.get("moments") or {}).get("items"):+ from .moments import export as export_moments++ try: # clips and frames of the special moments: seeks only, a failure must not lose the report+ export_moments(breakdown, out)+ except Exception as exc: # noqa: BLE001+ LOG.warning("special moments export failed: %s", str(exc)[:160])write_json(out / "breakdown.json", breakdown, compact=True)from .report import write_reportsdiff --git a/rea_video/prosody.py b/rea_video/prosody.pyindex 5aae2cd..28ec067 100644--- a/rea_video/prosody.py+++ b/rea_video/prosody.py@@ -30,6 +30,14 @@ def emotion_tag(raw) -> str:return s if s in EMOTION else ""+EVENTS = {"laughter": "laughter", "applause": "applause", "cry": "cry"}+++def event_tag(raw) -> str:+ """SenseVoice's sound-event token ("<|Laughter|>") to laughter / applause / cry; speech, BGM and unknown give ""."""+ return EVENTS.get(str(raw or "").strip("<|>").lower(), "")++def units(text: str) -> tuple[int, str]:"""Spoken units in a line: characters for CJK text, words otherwise."""n = len(_CJK.findall(text or ""))diff --git a/rea_video/report.py b/rea_video/report.pyindex 75773c0..35befb0 100644--- a/rea_video/report.py+++ b/rea_video/report.py@@ -1095,7 +1095,9 @@ def markdown(b: dict) -> str:# part one is the breakdown (what is there and how it was made, the same whatever model you use); part two is the# remake, planned for one model; the reference detail closes the reportpart1 = ["", T("# 第一部分 · 拆解:这条视频的结构", "# Part one · Breakdown: how this video is built"), ""]- L = (_head_md(b) + part1 + _highlights_md(b) + _layers_md(b) + _content_md(b, user=True) + _shotlist_md(b)+ from .moments import report_md as _moments_md++ L = (_head_md(b) + part1 + _highlights_md(b) + _moments_md(b) + _layers_md(b) + _content_md(b, user=True) + _shotlist_md(b)+ _cast_md(b) + _visual_md(b, user=True) + packaging_md(b) + _audio_md(b) + _questions_md(b)+ _plan_md(b) + _appendix_md(b))return re.sub(r"\n{3,}", "\n\n", "\n".join(L)).strip() + "\n"diff --git a/rea_video/reveal.py b/rea_video/reveal.pynew file mode 100644index 0000000..0033edb--- /dev/null+++ b/rea_video/reveal.py@@ -0,0 +1,402 @@+"""Draw a special moment out for a viewer who missed it: a numbered frame diagram and a reveal clip.++The diagram is the steps the reader wrote, one frame each, zoomed on the place to look, with a red ring where the+reader was sure; then the change itself frame by frame (every frame of the stretch the reader marked, zoomed, so the+object is seen travelling rather than popping up); under it what the frames show, what is only a guess, and why+viewers miss it. The clip plays the moment at speed, that stretch again slowed down and zoomed in with the steps as+captions, holds the key frame, then the reaction.+"""+from __future__ import annotations++import subprocess+import tempfile+from pathlib import Path++from PIL import Image, ImageDraw++from .visual import _font++RED = (235, 40, 40)+INK = (25, 25, 25)+GUESS = (160, 70, 20)+SLOW = (3, 10) # the slow look plays at 1/n speed, n chosen so it lasts about SLOW_LEN seconds+SLOW_LEN = 6.0+SLOW_BEFORE, SLOW_AFTER = 1.0, 0.6 # seconds of source around the key step in the slow look, without a marked stretch+SEQ_MAX, SEQ_COLS = 18, 6 # frames in the frame-by-frame row+SEQ_DEFAULT = (0.4, 0.1) # stretch around the key step when the reader marked none+SEQ_CONTEXT = (0.25, 0.5) # frames added before and after the stretch in the frame-by-frame row (s away)+HOLD = 2.5 # seconds the key frame is held+CLIP_W = 720+++ASPECT = (0.6, 1.8) # the zoom keeps the reader's box shape within these width / height ratios+++def zoom_box(focus: list[float] | None, pts: list[tuple[float, float]], w: int, h: int) -> tuple[int, int, int, int] | None:+ """The region to zoom on, in pixels (x, y, w, h): the reader's focus box (its own shape, within ASPECT), else+ around the marked points; None when there is neither or it is about the whole frame."""+ if focus:+ x0, y0, x1, y1 = focus+ elif pts:+ cx, cy = sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts)+ x0, y0, x1, y1 = cx - .25, cy - .25, cx + .25, cy + .25+ else:+ return None+ for x, y in pts if not focus else []: # without a box, every marked point stays inside, with a margin+ x0, y0, x1, y1 = min(x0, x - .08), min(y0, y - .08), max(x1, x + .08), max(y1, y + .08)+ side = 0.25 * min(w, h)+ bw, bh = max((x1 - x0) * w, side), max((y1 - y0) * h, side)+ if bw / bh > ASPECT[1]:+ bh = bw / ASPECT[1]+ elif bw / bh < ASPECT[0]:+ bw = bh * ASPECT[0]+ bw, bh = min(bw, w), min(bh, h)+ cx, cy = (x0 + x1) / 2 * w, (y0 + y1) / 2 * h+ x = int(min(max(0, cx - bw / 2), w - bw))+ y = int(min(max(0, cy - bh / 2), h - bh))+ bw, bh = int(bw) // 2 * 2, int(bh) // 2 * 2+ if bw * bh >= 0.85 * w * h:+ return None+ return x, y, bw, bh+++def _grab(video: str, t: float, tmp: Path, k: int) -> Image.Image | None:+ p = tmp / f"f{k}.png"+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", f"{max(t, 0):.3f}", "-i", video, "-frames:v", "1", str(p)], capture_output=True)+ return Image.open(p).convert("RGB") if p.is_file() else None+++def _ring(d: ImageDraw.ImageDraw, c: tuple[float, float], r: float, w: int) -> None:+ d.ellipse([c[0] - r, c[1] - r, c[0] + r, c[1] + r], outline=RED, width=w)+++def _wrap(d: ImageDraw.ImageDraw, text: str, font, width: int) -> list[str]:+ out, cur = [], ""+ for ch in text:+ if d.textlength(cur + ch, font=font) > width and cur:+ out.append(cur)+ cur = ""+ cur += ch+ return out + ([cur] if cur else [])+++def _panel(im: Image.Image, box, at, pw: int, zoom: bool) -> Image.Image:+ """One step's frame: zoomed on the box (or whole), ring where the reader marked."""+ w, h = im.size+ if zoom and box:+ x, y, bw, bh = box+ im = im.crop((x, y, x + bw, y + bh))+ to = lambda p: ((p[0] * w - x) / bw, (p[1] * h - y) / bh) # noqa: E731+ else:+ to = lambda p: p # noqa: E731+ ph = int(pw * im.height / im.width)+ im = im.resize((pw, ph), Image.LANCZOS)+ if at:+ cx, cy = to(at)+ _ring(ImageDraw.Draw(im), (cx * pw, cy * ph), pw * (0.09 if zoom and box else 0.06), max(3, pw // 100))+ return im+++def seq_times(f0: float, f1: float, fps: float, key: float | None = None, n: int = SEQ_MAX) -> list[float]:+ """Every frame from f0 to f1, or every k-th when there are more than n, always with the key frame."""+ dt = 1.0 / max(fps, 1.0)+ allf = [f0 + i * dt for i in range(int(round((f1 - f0) / dt)) + 1)]+ k = max(1, -(-len(allf) // n))+ ts = allf[::k]+ if key is not None and f0 <= key <= f1 and all(abs(t - key) > dt / 2 for t in ts):+ ts = sorted(ts + [key])+ if len(ts) > n:+ ts.remove(min((t for t in ts if t != key), key=lambda t: abs(t - key)))+ return [round(t, 3) for t in ts]+++def diagram(video: str, steps: list[dict], box, title: str, sub: str, notes: list[tuple[str, str]], out: Path,+ seq: list[float] | None = None, seq_title: str = "", key: float | None = None, pw: int = 480, cols: int = 3,+ seq_labels: tuple[str, str] = ("前 ", "后 ")) -> None:+ """Numbered frames of the steps, zoomed, ringed, captioned; then `seq` frame by frame (the key one in red);+ notes = [(kind, text)], kind seen / guess / why."""+ cols = min(cols, max(1, len(steps)))+ W = cols * pw + (cols + 1) * 12+ sw = (W - (SEQ_COLS + 1) * 8) // SEQ_COLS+ with tempfile.TemporaryDirectory() as td:+ ims, seq_ims = [], []+ for k, s in enumerate(steps):+ im = _grab(video, s["t"], Path(td), k)+ if im is None:+ continue+ ims.append((s, _panel(im, box, s.get("at"), pw, box is not None and not s.get("whole"))))+ ctx = [round(seq[0] - d, 3) for d in SEQ_CONTEXT[::-1] if seq and seq[0] - d >= 0] + list(seq or []) \+ + [round(seq[-1] + d, 3) for d in SEQ_CONTEXT if seq]+ for k, t in enumerate(ctx):+ im = _grab(video, t, Path(td), 100 + k)+ if im is not None:+ pim = _panel(im, box, None, sw, box is not None)+ if seq and not (seq[0] - 1e-3 <= t <= seq[-1] + 1e-3):+ pim = Image.blend(pim, Image.new("RGB", pim.size, (250, 248, 244)), 0.35)+ seq_ims.append((t, pim))+ if not ims:+ return+ zoomed = [im.height for s, im in ims if not s.get("whole")] or [im.height for _, im in ims]+ ph = max(zoomed)+ fit = []+ for s, im in ims: # a whole-frame panel (often a tall portrait) fits the zoomed panels' height, centred+ if im.height > ph:+ im = im.resize((max(1, int(im.width * ph / im.height)), ph), Image.LANCZOS)+ pad_im = Image.new("RGB", (pw, ph), (250, 248, 244))+ pad_im.paste(im, ((pw - im.width) // 2, 0))+ im = pad_im+ fit.append((s, im))+ ims = fit+ rows = (len(ims) + cols - 1) // cols+ pad, cap_h = 12, 64+ sh = max((im.height for _, im in seq_ims), default=0)+ srows = (len(seq_ims) + SEQ_COLS - 1) // SEQ_COLS+ seq_h = (44 + srows * (sh + 30)) if seq_ims else 0+ probe = ImageDraw.Draw(Image.new("RGB", (1, 1)))+ f_title = _font(30)+ title_lines = _wrap(probe, title, f_title, W - 2 * pad - 8)[:2]+ head_h = 20 + 40 * len(title_lines) + 34+ f_note = _font(22)+ note_lines = []+ for kind, text in notes:+ for ln in _wrap(probe, text, f_note, W - 2 * pad - 8):+ note_lines.append((kind, ln))+ foot_h = 24 + 34 * len(note_lines)+ sheet = Image.new("RGB", (W, head_h + rows * (ph + cap_h + pad) + seq_h + foot_h), (250, 248, 244))+ d = ImageDraw.Draw(sheet)+ for j, ln in enumerate(title_lines):+ d.text((pad + 4, 14 + 40 * j), ln, fill=INK, font=f_title)+ d.text((pad + 4, head_h - 34), sub, fill=(115, 115, 115), font=_font(18))+ f_cap, f_num, f_t = _font(22), _font(26), _font(20)+ for k, (s, im) in enumerate(ims):+ r, c = divmod(k, cols)+ x, y = pad + c * (pw + pad), head_h + r * (ph + cap_h + pad)+ sheet.paste(im, (x, y))+ d.ellipse([x + 8, y + 8, x + 50, y + 50], fill=RED)+ d.text((x + 29, y + 29), str(k + 1), fill="white", font=f_num, anchor="mm")+ lbl = (f"{s['t']:.1f}" if abs(s["t"] - round(s["t"], 1)) < 1e-6 else f"{s['t']:.2f}") + "s"+ d.rectangle([x + 54, y + 14, x + 66 + int(d.textlength(lbl, font=f_t)), y + 44], fill=(0, 0, 0))+ d.text((x + 60, y + 17), lbl, fill="white", font=f_t)+ for j, ln in enumerate(_wrap(d, s["text"], f_cap, pw - 8)[:2]):+ d.text((x + 4, y + ph + 6 + j * 28), ln, fill=RED if s.get("key") else INK, font=f_cap)+ if seq_ims:+ y0 = head_h + rows * (ph + cap_h + pad)+ d.text((pad + 4, y0 + 6), seq_title, fill=INK, font=_font(24))+ f_s = _font(16)+ for k, (t, im) in enumerate(seq_ims):+ r, c = divmod(k, SEQ_COLS)+ x, y = 8 + c * (sw + 8), y0 + 44 + r * (sh + 30)+ sheet.paste(im, (x, y))+ hit = key is not None and k == min(range(len(seq_ims)), key=lambda j: abs(seq_ims[j][0] - key))+ if hit:+ d.rectangle([x - 4, y - 4, x + sw + 3, y + sh + 3], outline=RED, width=5)+ side = "" if not seq or seq[0] - 1e-3 <= t <= seq[-1] + 1e-3 else (seq_labels[0] if t < seq[0] else seq_labels[1])+ if side: # context outside the change: dimmed+ d.rectangle([x, y, x + sw - 1, y + sh - 1], fill=None, outline=(170, 170, 170), width=2)+ d.text((x + sw // 2, y + sh + 14), f"{side}{t:.2f}s", fill=RED if hit else ((140, 140, 140) if side else INK), font=f_s, anchor="mm")+ y = sheet.height - foot_h + 12+ for kind, ln in note_lines:+ d.text((pad + 4, y), ln, fill=GUESS if kind == "guess" else INK, font=f_note)+ y += 34+ out.parent.mkdir(parents=True, exist_ok=True)+ sheet.convert("RGB").save(out, quality=90)+++def _card(path: Path, w: int, h: int, label: str = "", lines: list[str] | None = None, ring: tuple[float, float, float] | None = None) -> Path:+ """A transparent overlay: a red label top left, captions on a dark band, a ring (x, y, r in pixels)."""+ im = Image.new("RGBA", (w, h), (0, 0, 0, 0))+ d = ImageDraw.Draw(im)+ s = max(18, w // 22)+ if label:+ f = _font(int(s * .7))+ tw = int(d.textlength(label, font=f))+ d.rounded_rectangle([12, 12, 12 + tw + 24, 12 + int(s * .7) + 18], 8, fill=RED + (235,))+ d.text((24, 12 + (int(s * .7) + 18) // 2), label, fill="white", font=f, anchor="lm")+ if lines:+ f = _font(s)+ wrapped = [x for ln in lines for x in _wrap(d, ln, f, w - 40)][:3]+ top = int(s * .7) + 44+ d.rectangle([0, top, w, top + (s + 12) * len(wrapped) + 12], fill=(0, 0, 0, 170))+ for j, ln in enumerate(wrapped):+ d.text((w // 2, top + 8 + j * (s + 12) + s // 2 + 2), ln, fill="white", font=f, anchor="mm")+ if ring:+ _ring(d, ring[:2], ring[2], max(4, w // 120))+ im.save(path)+ return path+++def reveal_clip(video: str, has_audio: bool, size: tuple[int, int], dur: float, span: tuple[float, float],+ steps: list[dict], box, guess: str, out: Path, labels: dict[str, str],+ window: tuple[float, float] | None = None) -> Path | None:+ """At speed -> the change (`window`, else around the key step) slowed and zoomed with the steps as captions ->+ the key frame held -> the reaction. None without a key step."""+ key = next((s for s in steps if s.get("key")), None)+ if key is None:+ return None+ sw, sh = size+ W = min(CLIP_W, sw) // 2 * 2+ H = int(W * sh / sw) // 2 * 2+ kt = float(key["t"])+ norm = f"scale={W}:{H},setsar=1,fps=30,format=yuv420p"+ zoom = (f"crop={box[2]}:{box[3]}:{box[0]}:{box[1]},scale={W}:{H}:force_original_aspect_ratio=decrease,"+ f"pad={W}:{H}:(ow-iw)/2:(oh-ih)/2," if box else "")++ def ring_px(at):+ if not at:+ return None+ x, y = at[0] * sw, at[1] * sh+ if not box:+ return (x * W / sw, y * H / sh, W * 0.06)+ k = min(W / box[2], H / box[3])+ ox, oy = (W - box[2] * k) / 2, (H - box[3] * k) / 2+ return (ox + (x - box[0]) * k, oy + (y - box[1]) * k, box[2] * k * 0.09)++ def ff(args):+ subprocess.run(["ffmpeg", "-v", "error", "-y", *args], check=True, capture_output=True)++ a_out = ["-c:v", "libx264", "-preset", "veryfast", "-crf", "21", "-c:a", "aac", "-ar", "44100", "-ac", "2"]+ with tempfile.TemporaryDirectory() as td:+ T = Path(td)+ segs = []++ def speed(name, t0, t1, label):+ if t1 - t0 < 0.3:+ return+ card = _card(T / f"{name}.png", W, H, label)+ src = ["-ss", f"{t0:.3f}", "-t", f"{t1 - t0:.3f}", "-i", video, "-i", str(card)]+ if has_audio:+ ff([*src, "-filter_complex", f"[0:v]{norm}[v];[v][1:v]overlay[o]", "-map", "[o]", "-map", "0:a", *a_out, str(T / f"{name}.mp4")])+ else:+ ff([*src, "-f", "lavfi", "-t", f"{t1 - t0:.3f}", "-i", "anullsrc=r=44100:cl=stereo",+ "-filter_complex", f"[0:v]{norm}[v];[v][1:v]overlay[o]", "-map", "[o]", "-map", "2:a", "-shortest", *a_out, str(T / f"{name}.mp4")])+ segs.append(T / f"{name}.mp4")++ # 1. at speed: the whole moment, at most 12 s around the key step+ a = max(span[0], kt - 6.0)+ speed("a", a, min(span[1], a + 12.0, dur), labels["speed"])++ # 2. slow and zoomed: each step's caption from its time on, the ring with the step that marked it+ if window:+ s0, s1 = max(0.0, window[0] - 0.3), min(dur, max(window[1], kt) + 0.3)+ else:+ s0, s1 = max(0.0, kt - SLOW_BEFORE), min(dur, kt + SLOW_AFTER)+ slow = float(min(SLOW[1], max(SLOW[0], round(SLOW_LEN / max(s1 - s0, 0.1)))))+ slow_lbl = labels["slow"].format(n=int(slow))+ inside = [s for s in steps if s0 - 1.0 <= s["t"] <= s1]+ cards, cuts = [], []+ for j, s in enumerate(inside):+ st = max(0.0, (s["t"] - s0) * slow)+ en = (inside[j + 1]["t"] - s0) * slow if j + 1 < len(inside) else (s1 - s0) * slow+ if en > st:+ cards.append(_card(T / f"b{j}.png", W, H, slow_lbl, [s["text"]]))+ cuts.append((st, en))+ if ring_px(s.get("at")) and s0 <= s["t"] <= s1: # the ring only around the frame it was placed on+ cards.append(_card(T / f"r{j}.png", W, H, ring=ring_px(s.get("at"))))+ cuts.append((max(0.0, (s["t"] - 0.04 - s0) * slow), min((s1 - s0) * slow, (min(s["t"] + 0.2, inside[j + 1]["t"] if j + 1 < len(inside) else 1e9) - s0) * slow)))+ lead = _card(T / "b_lead.png", W, H, slow_lbl)+ L = (s1 - s0) * slow+ inputs = ["-ss", f"{s0:.3f}", "-t", f"{s1 - s0:.3f}", "-i", video, "-i", str(lead)]+ chain = f"[0:v]{zoom}minterpolate=fps=60:mi_mode=blend,setpts={slow}*PTS,{norm}[v0];[v0][1:v]overlay[v1]"+ for j, (c, (st, en)) in enumerate(zip(cards, cuts)):+ inputs += ["-i", str(c)]+ chain += f";[v{j + 1}][{j + 2}:v]overlay=enable='between(t,{st:.3f},{en:.3f})'[v{j + 2}]"+ n = len(cards) + 2+ ff([*inputs, "-f", "lavfi", "-t", f"{L:.3f}", "-i", "anullsrc=r=44100:cl=stereo", "-filter_complex", chain,+ "-map", f"[v{len(cards) + 1}]", "-map", f"{n}:a", "-t", f"{L:.3f}", *a_out, str(T / "b.mp4")])+ segs.append(T / "b.mp4")++ # 3. the key frame held, with the key step and the guess+ ff(["-ss", f"{kt:.3f}", "-i", video, "-frames:v", "1", str(T / "k.png")])+ card = _card(T / "c.png", W, H, labels["hold"].format(t=kt), [key["text"]], ring_px(key.get("at")))+ ff(["-loop", "1", "-t", f"{HOLD}", "-i", str(T / "k.png"), "-i", str(card), "-f", "lavfi", "-t", f"{HOLD}", "-i", "anullsrc=r=44100:cl=stereo",+ "-filter_complex", f"[0:v]{zoom}{norm}[v];[v][1:v]overlay[o]", "-map", "[o]", "-map", "2:a", "-t", f"{HOLD}", *a_out, str(T / "c.mp4")])+ segs.append(T / "c.mp4")++ # 4. the reaction at speed+ after = [s["t"] for s in steps if s["t"] > kt + 0.3]+ r0 = max(kt + 0.3, (after[-1] - 0.5) if after else kt + 0.6)+ speed("d", r0, min(dur, r0 + 2.0), labels["react"])++ ins, flt = [], ""+ for j, p in enumerate(segs):+ ins += ["-i", str(p)]+ flt += f"[{j}:v][{j}:a]"+ out.parent.mkdir(parents=True, exist_ok=True)+ ff([*ins, "-filter_complex", f"{flt}concat=n={len(segs)}:v=1:a=1[v][a]", "-map", "[v]", "-map", "[a]",+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "21", "-c:a", "aac", "-b:a", "96k", "-movflags", "+faststart", str(out)])+ return out+++SLOW_FRAME = 0.2 # seconds each frame of the change stays on screen in the slow cut (5 frames a second: each one seen)+CONTEXT_FRAME = 0.1 # seconds each frame around the change stays on screen (a third of normal speed at 30 fps)+SLOW_PRE, SLOW_POST = 1.0, 1.0 # source seconds shown before the change (the approach) and after it (the result shown)+HOLD_KEY = 1.5 # seconds the key frame is held in the slow cut+++def slow_clip(video: str, size: tuple[int, int], dur: float, fps: float, window: tuple[float, float], key: float | None,+ box, at, out: Path, labels: dict[str, str]) -> Path | None:+ """The change alone, every frame shown long enough to see: zoomed, each frame's time on it, the key frame ringed+ and held. Frames are repeated, not blended, so nothing smears."""+ sw, sh = size+ bw0, bh0 = (box[2], box[3]) if box else (sw, sh) # the canvas takes the zoom's shape, so a wide region fills it+ W = CLIP_W if bw0 >= bh0 else int(CLIP_W * bw0 / bh0) // 2 * 2+ H = int(W * bh0 / bw0) // 2 * 2+ a, z = max(0.0, window[0] - SLOW_PRE), min(dur, max(window[1], key if key is not None else 0.0) + SLOW_POST)+ if z - a < 0.1:+ return None+ each = SLOW_FRAME+ with tempfile.TemporaryDirectory() as td:+ T = Path(td)+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", f"{a:.3f}", "-t", f"{z - a:.3f}", "-i", video,+ "-fps_mode", "passthrough", str(T / "s_%06d.png")], check=True, capture_output=True)+ frames = sorted(T.glob("s_*.png"))+ if not frames:+ return None+ n = len(frames)+ times = [a + i * (z - a) / max(1, n) for i in range(n)]+ ki = min(range(n), key=lambda i: abs(times[i] - key)) if key is not None else None+ f_t, f_l = _font(max(22, min(W, H) // 18)), _font(max(18, min(W, H) // 26))+ lst = []+ for i, (p, t) in enumerate(zip(frames, times)):+ im = Image.open(p).convert("RGB")+ if box:+ x, y, bw, bh = box+ crop = im.crop((x, y, x + bw, y + bh))+ k = min(W / bw, H / bh)+ crop = crop.resize((max(1, int(bw * k)), max(1, int(bh * k))), Image.LANCZOS)+ frame = Image.new("RGB", (W, H), (0, 0, 0))+ ox, oy = (W - crop.width) // 2, (H - crop.height) // 2+ frame.paste(crop, (ox, oy))+ to = (lambda q: (ox + (q[0] * sw - x) * k, oy + (q[1] * sh - y) * k)) if at else None+ r = bw * k * 0.09+ else:+ frame = im.resize((W, H), Image.LANCZOS)+ to = (lambda q: (q[0] * W, q[1] * H)) if at else None+ r = W * 0.06+ d = ImageDraw.Draw(frame)+ in_window = window[0] - 1e-3 <= t <= window[1] + 1e-3+ zone = "in" if in_window else ("pre" if t < window[0] else "post")+ if i == ki and to:+ _ring(d, to(at), r, max(4, W // 120))+ tag = f"{t:.2f}s"+ tw = int(d.textlength(tag, font=f_t))+ d.rectangle([W - tw - 28, 12, W - 12, 12 + f_t.size + 14], fill=RED if i == ki else (0, 0, 0))+ d.text((W - tw - 20, 18), tag, fill="white", font=f_t)+ lbl = labels["slow"].format(i=i + 1, n=n) if in_window else labels[zone]+ lw = int(d.textlength(lbl, font=f_l))+ d.rounded_rectangle([12, 12, 12 + lw + 24, 12 + f_l.size + 18], 8, fill=RED)+ d.text((24, 21), lbl, fill="white", font=f_l)+ if i == ki and labels.get("key"):+ kw = int(d.textlength(labels["key"], font=f_t))+ d.rectangle([(W - kw) // 2 - 14, H - f_t.size - 40, (W + kw) // 2 + 14, H - 12], fill=(0, 0, 0))+ d.text(((W - kw) // 2, H - f_t.size - 30), labels["key"], fill="white", font=f_t)+ q = T / f"o_{i:06d}.png"+ frame.save(q)+ lst += [f"file '{q}'", f"duration {(each if in_window else CONTEXT_FRAME) + (HOLD_KEY if i == ki else 0):.3f}"]+ lst.append(f"file '{T / f'o_{n - 1:06d}.png'}'") # the concat demuxer drops the last duration otherwise+ (T / "list.txt").write_text("\n".join(lst) + "\n")+ out.parent.mkdir(parents=True, exist_ok=True)+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", str(T / "list.txt"),+ "-vf", "fps=30,format=yuv420p", "-c:v", "libx264", "-preset", "veryfast", "-crf", "18",+ "-movflags", "+faststart", str(out)], check=True, capture_output=True)+ return outdiff --git a/rea_video/speech.py b/rea_video/speech.pyindex d6804d6..692c636 100644--- a/rea_video/speech.py+++ b/rea_video/speech.py@@ -23,7 +23,7 @@ from pathlib import Pathimport numpy as npfrom .media import extract_audio-from .prosody import emotion_tag+from .prosody import emotion_tag, event_tagfrom .stems import models_dirfrom .util import ASR_LANGS, LOG, fetch, sha256_file@@ -192,8 +192,9 @@ def _sentences(start: float, end: float, text: str) -> list[dict]:return out-def _decode(rec, samples: np.ndarray, streaming: bool) -> tuple[str, str, str]:- """One spoken stretch -> (text, language heard, emotion heard); the last two empty when the recognizer does not say."""+def _decode(rec, samples: np.ndarray, streaming: bool) -> tuple[str, str, str, str]:+ """One spoken stretch -> (text, language heard, emotion heard, sound event heard: laughter / applause / cry); the last+ three empty when the recognizer does not say."""st = rec.create_stream()st.accept_waveform(SR, samples)if streaming:@@ -201,10 +202,10 @@ def _decode(rec, samples: np.ndarray, streaming: bool) -> tuple[str, str, str]:st.input_finished()while rec.is_ready(st):rec.decode_stream(st)- return (rec.get_result(st) or "").strip(), "", ""+ return (rec.get_result(st) or "").strip(), "", "", ""rec.decode_stream(st)return ((st.result.text or "").strip(), str(getattr(st.result, "lang", "") or "").strip("<|>"),- emotion_tag(getattr(st.result, "emotion", "")))+ emotion_tag(getattr(st.result, "emotion", "")), event_tag(getattr(st.result, "event", "")))def transcribe(audio: str | Path, language: str | None = None, threads: int = 2, turns: list[dict] | None = None) -> dict:@@ -235,7 +236,7 @@ def transcribe(audio: str | Path, language: str | None = None, threads: int = 2,engine = "sensevoice-small-int8 (sherpa-onnx)"lines, langs = [], []for start, samples in _by_speaker(_stretches(x, vad_model), turns):- text, heard, emotion = _decode(rec, samples, streaming=lang == "bn")+ text, heard, emotion, event = _decode(rec, samples, streaming=lang == "bn")if len(text.strip("。,、!?.,!? ")) < 1:continuegot = _sentences(start, start + len(samples) / SR, text)@@ -246,6 +247,8 @@ def transcribe(audio: str | Path, language: str | None = None, threads: int = 2,got = [dict(ln, speaker=who) for ln in got] if who else gotif emotion: # SenseVoice hears it per stretch; every sentence cut from the stretch shares itgot = [dict(ln, emotion=emotion) for ln in got]+ if event: # laughter / applause heard in the stretch: a reaction, for the special moments+ got = [dict(ln, event=event) for ln in got]if heard:got = [dict(ln, lang=heard) for ln in got]lines += gotdiff --git a/rea_video/videomd.py b/rea_video/videomd.pyindex 046875e..7031490 100644--- a/rea_video/videomd.py+++ b/rea_video/videomd.py@@ -188,9 +188,11 @@ def _shot_file(r: dict) -> str:def _topics(b: dict) -> list[tuple[str, str, str, list[str]]]:"""(file stem, title, when to read it, report section lines)."""+ from .moments import videomd as moments_mdfrom .report import _audio_md, _cast_md, _content_md, _remake_md, _visual_md, packaging_mdreturn [+ ("moments", T("特殊时刻", "Special moments"), T("魔术揭秘、反转、高潮、穿帮:时间、关键帧、片段", "reveals, twists, climaxes, goofs: times, key frames, clips"), moments_md(b)),("content", T("内容与结构", "Content and structure"), T("要讲什么、叙事线、结构时间轴、台词", "what it says, the narrative line, structure, the script"), _content_md(b)),("cast", T("角色、场景与道具", "Cast, scenes and props"), T("做角色参考图、写首帧提示词", "reference images for characters, first-frame prompts"), _cast_md(b)),("sound", T("声音", "Sound"), T("人声、BGM、音效、节拍和来源", "voice, music, sound effects, beats and sources"), _audio_md(b)),@@ -334,6 +336,12 @@ def _next_steps(b: dict) -> list[str]:"`rea-video code-remake <本目录>` 只出粒子 / 数据可视化这类画面的快速草稿","Code-rendered shots are best rebuilt in an HTML video framework (such as HyperFrames) from the rhythm and key frames in ""`video/rhythm.md`; `rea-video code-remake <this dir>` only makes a quick draft for particles / data-visualisation pictures"))+ mo = b.get("moments") or {}+ if mo.get("status") == "pending" and mo.get("genre") in ("magic", "drama"): # other videos: only when the user asks+ L.append(T("特殊时刻(魔术揭秘、反转、高潮、穿帮)还没找:`rea-video moments <本目录>`,按输出看图作答" ++ (";这是魔术视频,建议做" if mo.get("genre") == "magic" else ""),+ "Special moments (reveals, twists, climaxes, goofs) not looked for yet: `rea-video moments <this dir>`, answer from the images" ++ ("; a magic video: worth doing" if mo.get("genre") == "magic" else "")))if (b.get("production_plan") or {}).get("drive"):L.append(T("舞蹈 / 动作镜头不走首尾帧生成:`rea-video drive <本目录>` 出去掉字幕、按停顿切好的驱动视频,生成好的段用 `--join` 拼回;路线和提示词在 `video/remake.md` 的「动作驱动」","Dance / action shots are not generated from first / last frames: `rea-video drive <this dir>` writes caption-free drive clips cut at calm moments, "diff --git a/scripts/install_skill.sh b/scripts/install_skill.shindex 691df82..a788c5f 100755--- a/scripts/install_skill.sh+++ b/scripts/install_skill.sh@@ -82,7 +82,7 @@ fi# ---- 链接 skill:只链到已经装了的 agent(都没装就链到 ~/.claude/skills) ----targets=()-for home in "$HOME/.claude" "$HOME/.codex" "$HOME/.agents"; do+for home in "$HOME/.claude" "$HOME/.codex" "$HOME/.agents" "$HOME/.gemini"; do[ -d "$home" ] && targets+=("$home/skills")done[ ${#targets[@]} -eq 0 ] && targets=("$HOME/.claude/skills")diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.mdindex b8fa6a1..830089e 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 加工(换脸、对口型、风格化),标出后期叠加层(逐句字幕时间轴、花字、标题、贴纸 / GIF / 表情包、画中画)和用户真实素材,拆解人声、背景音乐、音效(卡在哪个画面事件上)与剪辑节奏,并给出可执行的复刻方案(可用 capsule-cinema、ChatCut 等复刻)。当用户给出参考视频、问"这条视频怎么做的 / 是不是 AI / 用了什么素材 / 怎么复刻 / 想二创或做一条同款"时使用。+description: 逆向拆解一条视频是怎么做出来的——逐镜头判断实拍 / 影视片段 / AI 生成 / 3D 渲染 / 2D 动画 / 定格动画 / 代码模板渲染 / 录屏截图 / 静态图推拉 / 静帧,以及实拍是否经过 AI 加工(换脸、对口型、风格化),标出后期叠加层(逐句字幕时间轴、花字、标题、贴纸 / GIF / 表情包、画中画)和用户真实素材,拆解人声、背景音乐、音效(卡在哪个画面事件上)与剪辑节奏,并给出可执行的复刻方案(可用 capsule-cinema、ChatCut 等复刻);也能抓魔术揭秘、反转、高潮、穿帮等特殊时刻,出逐帧图解和慢放。当用户给出参考视频、问"这条视频怎么做的 / 是不是 AI / 用了什么素材 / 怎么复刻 / 想二创或做一条同款 / 魔术怎么变的 / 抓高光"时使用。---# rea-video:视频制作方式逆向拆解@@ -85,6 +85,10 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复8. 第 3、5、6、7 步改了 `review_answers.json` 的,改完**再跑一次** `rea-video apply-review out/ref --by <你的名字>`,否则这些修改进不了报告。9. 如果你的判断和工具不同,以你的复核为准,在回复里写明理由;有价值的话,建议用户把这条视频加进评测集(仓库 `docs/dev/evaluation.md`)。+### 特殊时刻(魔术、剧情、用户要高光 / 精彩镜头时)++魔术揭秘、反转、高潮、穿帮这类时刻单独抓出来:开了 VLM 时 decompose 已经找过;没开时,魔术类(`summary` 会提示)和用户要高光时跑 `rea-video moments out/ref`,按输出看图作答再跑同一条命令,直到出结果。先通读台词和总览定段落,再逐段放大定关键帧(初始状态、手法、变化瞬间、反应),最后写 3-6 步讲解(变化常常比镜头亮出、人惊呼早;红圈只在确定时画);工具给的候选只是提醒,大多不是。结果在报告「特殊时刻」一节、`video/moments.md`,图解、揭秘短片和片段在 `moments/`。+用户指出判错或说出长期偏好时,按 `references/memory.md` 记下来(`rea-video correct` / `rea-video prefs`)。## 2. 交付给用户diff --git a/skills/rea-video/references/setup.md b/skills/rea-video/references/setup.mdindex e84f57e..a7030c2 100644--- a/skills/rea-video/references/setup.md+++ b/skills/rea-video/references/setup.md@@ -41,6 +41,7 @@ pip install "rea-video[ocr,asr] @ git+https://github.com/JuneYaooo/rea-video"1. `REA_VLM_BASE_URL` / `REA_VLM_API_KEY` / `REA_VLM_MODEL`(`REA_VLM_MODEL` 可写多个模型、逗号分隔,前一个失败自动换下一个)2. 如果没有,回落到 capsule-cinema 的 `VIDEO_ANALYSIS_*` 或 `GEMINI3_*`+3. 只有 Gemini 的 key(`GEMINI_API_KEY`,模型用 `REA_GEMINI_MODEL` 改):特殊时刻(`moments`)走 Gemini 自己的接口,连声音一起看视频片段;视频会上传到 Google,用完即删用 `--env-file <某个 .env>` 读取配置(例如复用 capsule-cinema 的)。**不要把密钥写进对话、仓库或报告,也不要打开 .env 看内容。**