Skip to content

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

Fix review precedence, moments v3 edge cases, DIY remake fallback, and capability drift

june92b9df331408
diff --git a/.gitignore b/.gitignore
index ec8cdce..084649c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
.cache/
+.DS_Store
out/
__pycache__/
*.egg-info/
@@ -21,3 +22,4 @@ scripts/roundtrip_compare.py
tests/
CHANGELOG.md
CLAUDE.md
+IGNORE/
diff --git a/docs/capsule-cinema.md b/docs/capsule-cinema.md
index d53f3cb..d7cbc01 100644
--- a/docs/capsule-cinema.md
+++ b/docs/capsule-cinema.md
@@ -1,6 +1,6 @@
# capsule-cinema 对接
-`remake-run` 和 `capsule-draft` 会用 **capsule-cinema 自己的 Python 环境**运行包里的 `rea_video/integrations/run_remake.py`、`to_capsule.py`(它们会 import capsule-cinema 的 `lib/` 和 `scripts/`,并读取它的 `.env`)。解释器按 `--python` > `$CAPSULE_CINEMA_PYTHON` > `<capsule-root>/.venv/bin/python` 的顺序找。rea-video 本身只依赖 numpy/opencv/pillow/pyyaml。
+`remake`、`remake-run`、`assemble`(在已安装 capsule-cinema 时)会调用 `<capsule-root>/scripts/remake_reference.py`,`capsule-draft` 会用 **capsule-cinema 自己的 Python 环境**运行 `rea_video/integrations/to_capsule.py`(读取它的 `.env`)。未安装 capsule-cinema 时,`remake` 和 `assemble` 自动回退到本地 DIY 复刻(静图推拉重建、代码重画、`mine.json` 素材拼回)。解释器按 `--python` > `$CAPSULE_CINEMA_PYTHON` > `<capsule-root>/.venv/bin/python` 的顺序找。rea-video 本身只依赖 numpy/opencv/pillow/pyyaml。
```bash
CC=~/code/github/capsule-cinema # capsule-cinema 仓库
diff --git a/docs/replicate.md b/docs/replicate.md
index 66daefd..f82f96c 100644
--- a/docs/replicate.md
+++ b/docs/replicate.md
@@ -23,7 +23,7 @@
2. 有两种做法:
- 手动:把单元提示词和参考图贴到即梦、可灵等网页上生成,再把生成的视频发给 agent,让它拼回原时间线。
- 自动:装了 [capsule-cinema](https://github.com/JuneYaooo/capsule-cinema) 的话,说「用 capsule-cinema 复刻 AI 镜头」,agent 会调用视频模型生成,再自动拼回、出对比片。调模型要花钱,所以它会先免费试跑一遍,等你确认后再正式生成。
-3. 目前自动生成还是一个镜头调用一次模型。报告里已经写好了一次生成多个镜头的提示词,这种方式更省钱,但现在只能走手动这条路。
+3. 支持多镜头或参考视频的模型(如 Seedance 2.5、MiniMax H3、Kling 3.0)会把同一段连着的镜头放进同一个生成单元一次生成,再按原片切点拆回各镜头,减少主体漂移和调用次数。
## 舞蹈和动作镜头:用原片驱动
diff --git a/eval/RESULTS.md b/eval/RESULTS.md
index eb36663..aba8634 100644
--- a/eval/RESULTS.md
+++ b/eval/RESULTS.md
@@ -159,6 +159,7 @@
| `code_videos.yaml` | 94.8% |
| `code_videos_holdout.yaml` | 100% |
| `particles.yaml`(3 条) | 66.7%(集合从 1 条扩到 3 条;新增的 bokeh 样本没认出,原有样本仍然判对) |
+| `magic.yaml`(1 条,12fps 藏剪辑) | 100%(切点 F1 1.00,2/2;无剪断局部突变召回 2/2,共 5 个候选) |
和前面记录的只用工具的分数比,除了 holdout 那一个短镜头,没有一组下降:文章视频 88.6% → 97.2%,带货 46.4% → 63.2%,口播 75.5% → 93.3%,影视混剪 15% → 15.8%。带货和影视混剪只用工具仍然不够,要靠看图复核(第 5、6 节)。
diff --git a/eval/magic.yaml b/eval/magic.yaml
new file mode 100644
index 0000000..fa907b3
--- /dev/null
+++ b/eval/magic.yaml
@@ -0,0 +1,13 @@
+# 魔术 / 藏剪辑评测集:画面里东西凭空出现的短视频。视频不入库(eval/media/ 已 gitignore)。
+# 真值来源:人工逐帧目测(2026-11-20),「存疑」:素材是平台转出的 12fps 无声 GIF,手法本身没有原片确认。
+# cuts:硬切 / 跳剪。sudden:没有剪断、局部一帧内出现东西的位置,box 是 x0,y0,x1,y1(0-1)。
+videos:
+ - id: mukbang_hidden_edit
+ path: eval/media/mukbang_hidden_edit.mp4
+ label: [live_action, ai_video] # 人和场景像实拍,食物出现的方式未确认
+ source: 用户实测案例,X 上转发的吃播片段(4.6 秒 GIF),人工逐帧目测,存疑
+ cuts: [1.67, 3.50]
+ cut_tolerance: 0.1
+ sudden:
+ - {t: 0.29, box: [0.25, 0.50, 0.80, 0.85]} # 螺旋薯塔从只有面的碗里出现
+ - {t: 2.00, box: [0.25, 0.50, 0.80, 0.85]} # 蟹排出现,旁边的薯塔不动
diff --git a/rea_video/aspects/editing.py b/rea_video/aspects/editing.py
index 530725c..a8d4c3e 100644
--- a/rea_video/aspects/editing.py
+++ b/rea_video/aspects/editing.py
@@ -66,7 +66,7 @@ class Editing(Aspect):
f_dur = sum(r["duration"] for r in filmed)
out = {"cuts_per_min": round(max(0, len(shots) - 1) / (total / 60), 1), "avg_shot_s": round(total / max(1, len(shots)), 2),
"filmed_share": round(f_dur / total, 3), "insert_share": round(1 - f_dur / total, 3)}
- if not filmed:
+ if not filmed or f_dur <= 0:
out["lines"] = [T("剪辑:每分钟 {c} 刀,平均镜头 {a}s;没有实拍镜头", "Editing: {c} cuts per minute, {a}s average shot; no live-action shots",
c=out["cuts_per_min"], a=out["avg_shot_s"])]
out["result"] = {}
diff --git a/rea_video/audio.py b/rea_video/audio.py
index 646e1d1..be6c59a 100644
--- a/rea_video/audio.py
+++ b/rea_video/audio.py
@@ -401,12 +401,19 @@ def analyze_audio(path: str, cut_times: list[float] | None = None, visual_marks:
if x is None or len(x) < SR * 0.3:
return {"has_audio": False}
dur = len(x) / SR
+ rms_dbfs = float(20 * np.log10(np.sqrt(np.mean(x ** 2)) + 1e-9))
+ peak_dbfs = float(20 * np.log10(np.abs(x).max() + 1e-9))
+ if peak_dbfs <= -70.0:
+ return {"has_audio": True, "duration": round(dur, 3), "rms_dbfs": round(rms_dbfs, 1), "peak_dbfs": round(peak_dbfs, 1),
+ "silence_ratio": 1.0, "voice": {"present": False, "ratio": 0.0, "segments": []},
+ "music": {"present": False, "ratio": 0.0, "segments": []}, "sfx": {"count": 0, "events": []},
+ "speech_likely": False, "music_likely": False, "tempo_bpm": None, "beat_synced_edit": False, "energy_curve": []}
S = _stft(x)
freqs = np.fft.rfftfreq(N_FFT, 1 / SR)
Sh, Sp = hpss(S)
frame_db = 10 * np.log10((S ** 2).mean(axis=1) + 1e-12)
peak_db = float(np.percentile(frame_db, 99))
- silent = frame_db < peak_db - 45
+ silent = (frame_db < peak_db - 45) | (frame_db < -95)
# ---------------- voice ----------------------------------------------------------------
band = (freqs > 300) & (freqs < 3400)
diff --git a/rea_video/capabilities/MATRIX.md b/rea_video/capabilities/MATRIX.md
index 855ea47..631f1f0 100644
--- a/rea_video/capabilities/MATRIX.md
+++ b/rea_video/capabilities/MATRIX.md
@@ -25,16 +25,16 @@
| `image.tryon` | 虚拟试穿 | ◐ `fashn-tryon-max`、◐ `fashn-v1.6`、◐ `kling-kolors-tryon`、◐ `kling-virtual-tryon-3`、◐ `qwen-image-2.1` |
| `video.t2v` | 文生视频 | ◐ `flux-3-video`、○ `flux-3-video-max`、◐ `gemini-omni-flash`、◐ `grok-imagine-video-1.5`、○ `grok-imagine-video-1.5-lite`、◐ `hailuo-2.3`、○ `happyhorse-1.0`、◐ `heygen-video-1`、◐ `hunyuanvideo-1.5`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-4.0-flash`、◐ `kling-o3`、◐ `ltx-2.5`、○ `luma-ray3.2`、● `minimax-h3`、◐ `minimax-h3-max`、○ `p-video-2-pro`、◐ `pika-h3-flex`、◐ `pixverse-v6`、◐ `runway-gen-4.5`、◐ `seedance-2.0`、● `seedance-2.5`、○ `seedance-2.5-flash`、○ `skyreels-v4`、○ `utopai-x`、◐ `veo-3.1`、◐ `vidu-q3`、● `wan-2.2`、◐ `wan-3.0` |
| `video.i2v_first_frame` | 图生视频(首帧) | ◐ `flux-3-video`、○ `flux-3-video-max`、◐ `gemini-omni-flash`、◐ `grok-imagine-video-1.5`、○ `grok-imagine-video-1.5-lite`、◐ `hailuo-2.3`、○ `happyhorse-1.0`、◐ `heygen-video-1`、◐ `hunyuanvideo-1.5`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-4.0-flash`、◐ `kling-o3`、◐ `ltx-2.5`、○ `luma-ray3.2`、● `minimax-h3`、◐ `minimax-h3-max`、○ `p-video-2-pro`、◐ `pika-h3-flex`、◐ `pixverse-v6`、◐ `runway-gen-4.5`、◐ `seedance-2.0`、● `seedance-2.5`、○ `seedance-2.5-flash`、○ `skyreels-v4`、◐ `veo-3.1`、◐ `vidu-q3`、◐ `vidu-q4-preview`、● `wan-2.2`、◐ `wan-3.0`、◐ `wan-vace` |
-| `video.i2v_first_last` | 首尾帧生成 | ◐ `flux-3-video`、○ `flux-3-video-max`、◐ `gemini-omni-flash`、◐ `grok-imagine-video-1.5`、◐ `heygen-video-1`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-o3`、● `minimax-h3`、◐ `minimax-h3-max`、○ `p-video-2-pro`、◐ `pika-h3-flex`、◐ `pixverse-v6`、◐ `seedance-2.0`、● `seedance-2.5`、○ `seedance-2.5-flash`、◐ `veo-3.1`、◐ `wan-3.0` |
+| `video.i2v_first_last` | 首尾帧生成 | ◐ `flux-3-video`、○ `flux-3-video-max`、◐ `gemini-omni-flash`、◐ `grok-imagine-video-1.5`、◐ `heygen-video-1`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-o3`、● `minimax-h3`、◐ `minimax-h3-max`、○ `p-video-2-pro`、◐ `pika-h3-flex`、◐ `pixverse-v6`、◐ `seedance-2.0`、● `seedance-2.5`、○ `seedance-2.5-flash`、◐ `veo-3.1`、◐ `vidu-q3`、◐ `wan-3.0` |
| `video.keyframes` | 多关键帧控制 | ◐ `flux-3-video`、○ `flux-3-video-max`、◐ `grok-imagine-video-1.5`、◐ `kling-4.0`、◐ `runway-gen-4.5` |
| `video.multi_reference` | 多参考生视频(主体一致) | ◐ `gemini-omni-flash`、◐ `grok-imagine-video-1.5`、○ `happyhorse-1.0`、◐ `heygen-video-1`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-4.0-flash`、◐ `kling-o3`、● `minimax-h3`、◐ `minimax-h3-max`、◐ `pika-h3-flex`、◐ `pixverse-v6`、◐ `seedance-2.0`、● `seedance-2.5`、○ `seedance-2.5-flash`、◐ `veo-3.1`、◐ `vidu-q3`、◐ `vidu-q4-preview`、◐ `wan-3.0` |
| `video.reference_video` | 参考视频生成(动作/运镜/特效迁移) | ◐ `gemini-omni-flash`、◐ `heygen-video-1`、◐ `kling-4.0`、◐ `kling-4.0-flash`、◐ `kling-o3`、● `minimax-h3`、◐ `minimax-h3-max`、◐ `pika-h3-flex`、◐ `pixverse-v6`、◐ `seedance-2.0`、● `seedance-2.5`、○ `seedance-2.5-flash`、○ `skyreels-v4`、◐ `wan-3.0` |
| `video.reference_audio` | 参考音频生成 | ◐ `grok-imagine-video-1.5`、◐ `heygen-video-1`、◐ `kling-4.0-flash`、◐ `ltx-2.5`、● `minimax-h3`、◐ `minimax-h3-max`、◐ `pika-h3-flex`、◐ `seedance-2.0`、● `seedance-2.5`、○ `seedance-2.5-flash`、◐ `vidu-q4-preview`、◐ `wan-3.0` |
-| `video.multi_shot` | 单次多镜头 | ◐ `flux-3-video`、◐ `gemini-omni-flash`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-4.0-flash`、◐ `kling-o3`、◐ `ltx-2.5`、● `minimax-h3`、◐ `pika-h3-flex`、◐ `pixverse-v6`、◐ `seedance-2.0`、● `seedance-2.5`、◐ `veo-3.1`、◐ `vidu-q4-preview`、◐ `wan-3.0` |
+| `video.multi_shot` | 单次多镜头 | ◐ `flux-3-video`、◐ `gemini-omni-flash`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-4.0-flash`、◐ `kling-o3`、◐ `ltx-2.5`、● `minimax-h3`、◐ `pika-h3-flex`、◐ `pixverse-v6`、◐ `seedance-2.0`、● `seedance-2.5`、◐ `veo-3.1`、◐ `vidu-q3`、◐ `vidu-q4-preview`、◐ `wan-3.0` |
| `video.extend` | 续写延长 | ◐ `flux-3-video`、◐ `gemini-omni-flash`、● `seedance-2.5`、◐ `veo-3.1` |
| `video.edit_v2v` | 视频编辑(保留运动) | ◐ `flux-3-video`、◐ `gemini-omni-flash`、○ `happyhorse-1.0`、○ `higgsfield-genjutsu`、◐ `kling-4.0`、◐ `kling-o3`、◐ `ltx-2.5`、○ `luma-ray3.2`、◐ `pika-h3-flex`、○ `runway-aleph-2`、◐ `runway-gen-4.5`、◐ `seedance-2.0`、● `seedance-2.5`、○ `skyreels-v4`、◐ `viggle-animate`、◐ `wan-2.2-animate`、○ `wan-2.7-edit`、◐ `wan-vace` |
| `video.camera_control` | 运镜与镜头参数控制 | ◐ `gemini-omni-flash`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `pixverse-v6`、○ `runway-aleph-2`、◐ `runway-gen-4.5`、● `seedance-2.5` |
-| `video.native_audio` | 音画同出 | ◐ `flux-3-video`、○ `flux-3-video-max`、◐ `gemini-omni-flash`、◐ `grok-imagine-video-1.5`、○ `grok-imagine-video-1.5-lite`、◐ `heygen-video-1`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-4.0-flash`、◐ `ltx-2.5`、○ `luma-ray3.2`、● `minimax-h3`、◐ `minimax-h3-max`、○ `p-video-2-pro`、◐ `pika-h3-flex`、◐ `pixverse-v6`、◐ `runway-gen-4.5`、◐ `seedance-2.0`、● `seedance-2.5`、○ `seedance-2.5-flash`、○ `skyreels-v4`、○ `utopai-x`、◐ `veo-3.1`、◐ `vidu-q3`、◐ `vidu-q4-preview`、◐ `wan-3.0` |
+| `video.native_audio` | 音画同出 | ◐ `flux-3-video`、○ `flux-3-video-max`、◐ `gemini-omni-flash`、◐ `grok-imagine-video-1.5`、○ `grok-imagine-video-1.5-lite`、◐ `heygen-video-1`、◐ `kling-3.0`、◐ `kling-4.0`、◐ `kling-4.0-flash`、◐ `kling-o3`、◐ `ltx-2.5`、● `minimax-h3`、◐ `minimax-h3-max`、○ `p-video-2-pro`、◐ `pika-h3-flex`、◐ `pixverse-v6`、◐ `seedance-2.0`、● `seedance-2.5`、○ `seedance-2.5-flash`、○ `skyreels-v4`、○ `utopai-x`、◐ `veo-3.1`、◐ `vidu-q3`、◐ `vidu-q4-preview`、◐ `wan-3.0` |
| `video.control_video` | 控制视频驱动生成 | ◐ `wan-vace` |
| `motion.transfer` | 动作迁移 | ○ `dreamactor-m2.0`、○ `higgsfield-genjutsu`、◐ `kling-motion-control`、◐ `runway-gen-4.5`、◐ `viggle-animate`、◐ `viggle-v4`、◐ `wan-2.2-animate`、◐ `wan-animate-2` |
| `avatar.audio_driven` | 音频驱动数字人 | ○ `creatify-aurora`、○ `hedra-omnia`、◐ `heygen-avatar-v`、◐ `kling-avatar-v2`、◐ `longcat-video-avatar-1.5`、◐ `ltx-2.3-lipsync`、◐ `ltx-2.5`、◐ `mirage-avatar-x`、◐ `omnihuman-2.0`、◐ `sync-3`、◐ `synthesia-express-3`、○ `veed-fabric-1.0` |
@@ -146,7 +146,7 @@
| Gemini Omni Flash | Google | video | ga | 15 | 是 | 是 | vendor 2026-11-12 |
| Grok Imagine Video 1.5 | xAI | video | ga | 15 | 是 | 有条件 | vendor 2026-11-12 |
| Grok Imagine Video 1.5 Lite | xAI | video | ga | 15 | 是 | 有条件 | vendor 2026-11-12 |
-| Hailuo 2.3 / 2.3 Fast(海螺) | MiniMax | video | ga | 10 | 是 | 是 | third-party 2026-10-29 |
+| Hailuo 2.3 / 2.3 Fast(海螺) | MiniMax | video | ga | 10 | 否 | 是 | third-party 2026-10-29 |
| HappyHorse 1.0 | Alibaba | video | ga | | | 有条件 | third-party 2026-11-12 |
| HeyGen Video 1 | HeyGen | video | ga | 30 | 是 | 有条件 | vendor 2026-11-12 |
| Higgsfield Genjutsu(含 Lite) | Higgsfield | video | ga | | | 有条件 | vendor 2026-11-12 |
@@ -154,16 +154,16 @@
| Kling 3.0(含 Turbo) | Kuaishou | video | ga | 15 | 是 | 是 | third-party 2026-10-29 |
| Kling 4.0(可灵 4.0) | Kuaishou | video | ga | 30 | 是 | 是 | vendor 2026-11-12 |
| Kling 4.0 Flash(可灵 4.0 Flash) | Kuaishou | video | ga | 20 | 是 | 是 | vendor 2026-11-12 |
-| Kling O3(Omni) | Kuaishou | video | ga | 15 | 否 | 是 | third-party 2026-10-29 |
+| Kling O3(Omni) | Kuaishou | video | ga | 15 | 是 | 是 | vendor 2026-11-22 |
| LTX-2.5(开源) | Lightricks | video | ga | | 是 | 有条件 | third-party 2026-11-12 |
-| Luma Ray3.2 / Modify | Luma AI | video | ga | 10 | 是 | 是 | vendor 2026-11-12 |
+| Luma Ray3.2 / Modify | Luma AI | video | ga | 10 | 否 | 是 | vendor 2026-11-12 |
| MiniMax H3 / H3 Max | MiniMax | video | ga | 15 | 是 | 有条件 | vendor 2026-11-22 |
| MiniMax H3 Max | MiniMax | video | ga | 15 | 是 | 有条件 | vendor 2026-11-12 |
| P-Video-2-Pro | Pruna AI | video | ga | 15 | 是 | 有条件 | third-party 2026-11-12 |
| Pika H3 Flex | Pika | video | ga | 15 | 是 | 有条件 | vendor 2026-11-12 |
| PixVerse V6 | PixVerse(爱诗科技) | video | ga | 15 | 是 | 是 | third-party 2026-10-29 |
| Runway Aleph 2 | Runway | video | ga | | | 是 | vendor 2026-11-12 |
-| Runway Gen-4.5(含 Act-Two) | Runway | video | ga | 10 | 是 | 是 | third-party 2026-10-29 |
+| Runway Gen-4.5(含 Act-Two) | Runway | video | ga | 10 | 否 | 是 | third-party 2026-10-29 |
| Seedance 2.0(含 Mini / Fast) | ByteDance Seed | video | ga | 15 | 是 | 是 | third-party 2026-11-11 |
| Seedance 2.5 | ByteDance Seed | video | ga | 30 | 是 | 是 | vendor 2026-11-11 |
| Seedance 2.5 Flash | ByteDance Seed | video | preview | | 是 | 有条件 | third-party 2026-11-12 |
diff --git a/rea_video/capabilities/models/video.yaml b/rea_video/capabilities/models/video.yaml
index 955669e..b9dcd9e 100644
--- a/rea_video/capabilities/models/video.yaml
+++ b/rea_video/capabilities/models/video.yaml
@@ -198,11 +198,13 @@ models:
release: 2026-03
status: ga
access: [app, api, api-aggregator]
- primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.multi_reference, video.multi_shot, video.edit_v2v, video.reference_video]
+ primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.multi_reference, video.multi_shot, video.edit_v2v, video.reference_video, video.native_audio]
limits:
duration_s: {min: 3, max: 15}
resolutions: [720p, 1080p, 4K]
- audio: {native: false}
+ refs: {image: 7, video: 1}
+ ref_video_s: {min: 3, max: 10}
+ audio: {native: true}
strengths:
- 视频改视频:换角色或道具、重新风格化、重打光,保留原动作
- Element 参考一致性更强;Director Mode 可组合文本、首尾帧、参考图和角色视频
@@ -211,9 +213,10 @@ models:
license: {commercial: true, note: 以平台条款为准}
sources:
- https://help.artlist.io/hc/en-us/articles/37026869403933-Kling-3-Model-Family
- verified: {date: 2026-10-29, basis: third-party}
+ - https://kling.ai/quickstart/klingai-video-3-omni-model-user-guide
+ verified: {date: 2026-11-22, basis: vendor}
confidence: medium
- notes: 发布月份为估计值;音频能力资料未提及
+ notes: 发布月份为估计值;传了参考视频时不能同时开原生音频
- id: veo-3.1
name: Veo 3.1(含 Lite)
@@ -314,7 +317,8 @@ models:
limits:
duration_s: {min: 3, max: 15}
resolutions: [720p, 1080p, 4K]
- refs: {image: 6}
+ refs: {image: 6, video: 1}
+ ref_video_s: {max: 3}
audio: {native: true}
strengths:
- 文本、图像、音频、视频任意组合输入;草图可作为动作引导
@@ -344,7 +348,7 @@ models:
release: 2026-04
status: ga
access: [app, api, api-aggregator]
- primitives: [video.t2v, video.i2v_first_frame, video.multi_reference, video.native_audio]
+ primitives: [video.t2v, video.i2v_first_frame, video.i2v_first_last, video.multi_reference, video.multi_shot, video.native_audio]
limits:
duration_s: {max: 16}
audio: {native: true}
@@ -595,7 +599,7 @@ models:
limits:
duration_s: {max: 10}
resolutions: [768p, 1080p]
- audio: {native: true}
+ audio: {native: false}
strengths:
- 微表情、风格化、动作有提升
- 便宜(Fast 版 768p 6 秒约 0.19 美元起)
@@ -789,11 +793,11 @@ models:
release: 2025-12
status: ga
access: [app, api]
- primitives: [video.t2v, video.i2v_first_frame, video.keyframes, video.edit_v2v, video.camera_control, motion.transfer, video.native_audio]
+ primitives: [video.t2v, video.i2v_first_frame, video.keyframes, video.edit_v2v, video.camera_control, motion.transfer]
limits:
duration_s: {max: 10}
resolutions: [720p]
- audio: {native: true}
+ audio: {native: false}
strengths:
- 控制工具最全:关键帧、运动笔刷、相机路径
- Act-Two 能把驱动表演迁移到角色图上
@@ -857,11 +861,11 @@ models:
release: 2026-06
status: ga
access: [app, api]
- primitives: [video.t2v, video.i2v_first_frame, video.edit_v2v, video.native_audio]
+ primitives: [video.t2v, video.i2v_first_frame, video.edit_v2v]
limits:
duration_s: {max: 10}
resolutions: [1080p]
- audio: {native: true}
+ audio: {native: false}
strengths:
- Modify 能替换演员并保留原动作和时序
- Ray 有"推理式"自我修正,提示词遵循好
diff --git a/rea_video/capabilities/schema.json b/rea_video/capabilities/schema.json
index 4403927..6954fcd 100644
--- a/rea_video/capabilities/schema.json
+++ b/rea_video/capabilities/schema.json
@@ -60,6 +60,7 @@
},
"confidence": {"enum": ["high", "medium", "low"]},
"planning": {"type": "object", "additionalProperties": false, "description": "How remake plans use this model by default, when that is narrower than its limits", "properties": {"strategy": {"enum": ["remix", "keyframes", "frames", "text"]}, "images": {"type": "integer", "minimum": 1}}},
+ "prompting": {"type": "object", "description": "Optional inline prompt-writing rules for user-defined model entries"},
"probe_scores": {"type": "object"},
"notes": {"type": "string"}
},
diff --git a/rea_video/cli.py b/rea_video/cli.py
index d41bd26..1f56674 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -76,7 +76,13 @@ def cmd_decompose(args) -> int:
out = Path(args.out) if args.out else Path("out") / Path(args.video).stem
from .memory import pref
- meta = read_json(Path(args.meta)) if args.meta else None
+ meta = None
+ if args.meta:
+ s_meta = args.meta.strip()
+ try:
+ meta = json.loads(s_meta) if s_meta.startswith("{") else read_json(Path(s_meta))
+ except (ValueError, OSError) as exc:
+ raise SystemExit(U(f"rea-video: --meta 解析失败:{exc}", f"rea-video: invalid --meta: {exc}"))
use_vlm = args.vlm or (pref("vlm") == "on" and not args.no_vlm)
if use_vlm:
_check_vlm_config()
@@ -106,12 +112,17 @@ def cmd_survey(args) -> int:
asker = None
if args.vlm or (pref("vlm") == "on" and not args.no_vlm):
_check_vlm_config()
+ from . import gemini
from .vlm import VLMClient, VLMConfig, prompt_lang_note
cfg = VLMConfig.from_env()
- if cfg is None:
- raise SystemExit(U("rea-video: --vlm 需要 VLM 配置(REA_VLM_BASE_URL / REA_VLM_API_KEY / REA_VLM_MODEL)", "rea-video: --vlm needs VLM settings (REA_VLM_BASE_URL / REA_VLM_API_KEY / REA_VLM_MODEL)"))
- asker = vlm_asker(VLMClient(cfg, out / "vlm_cache"), prompt_lang_note())
+ if cfg is not None:
+ asker = vlm_asker(VLMClient(cfg, out / "vlm_cache"), prompt_lang_note())
+ elif gemini.configured():
+ asker = vlm_asker(gemini.GeminiClient(), prompt_lang_note())
+ else:
+ raise SystemExit(U("rea-video: --vlm 需要 VLM 配置(REA_VLM_BASE_URL / REA_VLM_API_KEY / REA_VLM_MODEL,或 GEMINI_API_KEY)",
+ "rea-video: --vlm needs VLM settings (REA_VLM_BASE_URL / REA_VLM_API_KEY / REA_VLM_MODEL, or GEMINI_API_KEY)"))
res = run(Path(args.video).expanduser().resolve(), out.expanduser().resolve(), track, detect_shots(track), info,
asker=asker, workers=args.workers, detail=not args.no_detail)
if res["status"] == "waiting":
@@ -138,11 +149,24 @@ def cmd_moments(args) -> int:
if args.redo and (out / "moments").is_dir():
shutil.rmtree(out / "moments")
b.get("moments", {}).pop("items", None)
+ if "moments" in b:
+ b["moments"]["status"] = "pending"
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)
+ track = None
+ if ("hints" not in m or "measured" not in m) and Path(b["source"]["path"]).is_file():
+ from .media import video_info
+ from .shots import build_track
+
+ track = build_track(b["source"]["path"], video_info(b["source"]["path"]))
+ if "hints" not in m:
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"]))
+ hints=mo.hints((b.get("speech") or {}).get("lines") or [], voc if voc.is_file() else None, track, b["source"]["duration"]))
+ if "measured" not in m and track is not None: # a breakdown from before the frame measurements
+ fps = float(b["source"].get("fps") or track.fps or 30.0)
+ skips = [(int(round(s["transition"]["start"] * fps)), int(round(s["transition"]["end"] * fps)))
+ for s in (b.get("shots") or [])[1:] if s.get("transition")]
+ m["measured"] = mo.measured(track, [s["start_frame"] for s in (b.get("shots") or [])[1:]], skip=skips)
asker = None
if args.vlm or (pref("vlm") == "on" and not args.no_vlm):
_check_vlm_config()
@@ -393,11 +417,27 @@ def cmd_capsule_draft(args) -> int:
return _run_integration("to_capsule.py", _capsule_python(args.python, root), argv)
+def _has_capsule_script(args) -> bool:
+ from .memory import capsule_root
+
+ root = capsule_root(getattr(args, "capsule_root", None))
+ return (root / "scripts" / "remake_reference.py").is_file()
+
+
def cmd_assemble(args) -> int:
- pkg = Path(args.breakdown).expanduser().resolve().parent
- argv = ["assemble", str(pkg), "--results", str(Path(args.results).expanduser().resolve())]
- argv += ["-o", str(Path(args.out).expanduser().resolve())] if args.out else []
- return _capsule_command(args, argv + ([] if args.overlays else ["--no-overlays"]))
+ if getattr(args, "capsule_root", None) or _has_capsule_script(args):
+ pkg = Path(args.breakdown).expanduser().resolve().parent
+ argv = ["assemble", str(pkg), "--results", str(Path(args.results).expanduser().resolve())]
+ argv += ["-o", str(Path(args.out).expanduser().resolve())] if args.out else []
+ return _capsule_command(args, argv + ([] if args.overlays else ["--no-overlays"]))
+ from .remake import assemble
+
+ bpath = Path(args.breakdown).expanduser().resolve()
+ out_dir = Path(args.out).expanduser().resolve() if args.out else (bpath.parent / "remake")
+ code_mp4 = bpath.parent / "code" / "remake.mp4"
+ print(assemble(bpath, Path(args.results).expanduser().resolve(), out_dir, overlays=args.overlays,
+ code_video=code_mp4 if code_mp4.is_file() else None))
+ return 0
def cmd_tiles(args) -> int:
@@ -428,18 +468,27 @@ def cmd_tiles(args) -> int:
times = list(np.arange(args.start, end, args.every))[: args.max]
import tempfile
- frames = []
+ focus_box = None
+ if getattr(args, "focus", None):
+ try:
+ vals = [float(v) for v in str(args.focus).replace(",", ",").split(",")]
+ except ValueError:
+ vals = []
+ if len(vals) != 4 or not (0.0 <= vals[0] < vals[2] <= 1.0 and 0.0 <= vals[1] < vals[3] <= 1.0):
+ raise SystemExit(U("rea-video: --focus 必须是 0–1 之间的 x0,y0,x1,y1(且 x0<x1, y0<y1)",
+ "rea-video: --focus must be x0,y0,x1,y1 in 0..1 with x0<x1 and y0<y1"))
+ focus_box = vals
+ frames, kept_times = [], []
with tempfile.TemporaryDirectory() as tmpd:
for i, t in enumerate(times):
- 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(","))
+ if focus_box: # a region of the frame, enlarged to the cell width (x0,y0,x1,y1 in 0-1)
+ x0, y0, x1, y1 = focus_box
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)
+ img = cv2.resize(img, (args.cell, max(2, int(args.cell * img.shape[0] / max(1, 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)
@@ -453,13 +502,14 @@ def cmd_tiles(args) -> int:
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)
+ kept_times.append(float(t))
rows = [frames[i:i + args.cols] for i in range(0, len(frames), args.cols)]
paths = []
for r, row in enumerate(rows):
out = Path(args.out) if len(rows) == 1 else Path(args.out).with_name(f"{Path(args.out).stem}_{r + 1}{Path(args.out).suffix}")
- shot_sheet(row, [float(t) for t in times[r * args.cols:(r + 1) * args.cols]], out, n=len(row), cell_w=args.cell)
+ shot_sheet(row, kept_times[r * args.cols:(r + 1) * args.cols], out, n=len(row), cell_w=args.cell)
paths.append(str(out))
- print(json.dumps({"tiles": paths, "times": [round(float(t), 3) for t in times]}, ensure_ascii=False))
+ print(json.dumps({"tiles": paths, "times": [round(float(t), 3) for t in kept_times]}, ensure_ascii=False))
return 0
@@ -500,27 +550,33 @@ def cmd_compare(args) -> int:
def cmd_remake(args) -> int:
- """The plan is rea-video's; Capsule Cinema takes it from there (stills, clips in, assembly, status, check)."""
+ """The plan is rea-video's; Capsule Cinema takes it from there when installed, else local DIY remake runs."""
out = Path(args.out_dir).expanduser().resolve()
if not (out / "breakdown.json").is_file():
raise SystemExit(U(f"rea-video: {out} 下没有 breakdown.json,先运行 decompose", f"rea-video: no breakdown.json in {out}, run decompose first"))
- if args.code:
- from .code_remake import code_remake
-
- b = read_json(out / "breakdown.json")
- if any(sh["base"]["label"] == "code_render" for sh in b["shots"]) and not (out / "code" / "remake.mp4").is_file():
- try:
- code_remake(out)
- except (ValueError, OSError, RuntimeError) as exc:
- print(f"rea-video: code-remake: {exc}", file=sys.stderr)
- args.breakdown = str(out / "breakdown.json")
- args.capsule_root = getattr(args, "capsule_root", None)
- root = _capsule_root(args)
- args.capsule_root = str(root)
- rc = cmd_remake_plan(args)
- if rc:
- return rc
- return _capsule_command(args, ["assemble", str(out)] + (["--no-overlays"] if args.no_overlays else []))
+ if getattr(args, "capsule_root", None) or _has_capsule_script(args):
+ if args.code:
+ from .code_remake import code_remake
+
+ b = read_json(out / "breakdown.json")
+ if any(sh["base"]["label"] == "code_render" for sh in b["shots"]) and not (out / "code" / "remake.mp4").is_file():
+ try:
+ code_remake(out)
+ except (ValueError, OSError, RuntimeError) as exc:
+ print(f"rea-video: code-remake: {exc}", file=sys.stderr)
+ args.breakdown = str(out / "breakdown.json")
+ args.capsule_root = getattr(args, "capsule_root", None)
+ root = _capsule_root(args)
+ args.capsule_root = str(root)
+ rc = cmd_remake_plan(args)
+ if rc:
+ return rc
+ return _capsule_command(args, ["assemble", str(out)] + (["--no-overlays"] if args.no_overlays else []))
+ from .remake import remake
+
+ res = remake(out, code=args.code, overlays=not args.no_overlays)
+ print(json.dumps(res, ensure_ascii=False, indent=2))
+ return 0
def cmd_code_remake(args) -> int:
@@ -605,7 +661,7 @@ def cmd_summary(args) -> int:
for r in b["shots"]:
base = r["base"]
- alt = sorted(base["probs"].items(), key=lambda kv: -kv[1])[1]
+ alt = next((kv for kv in sorted(base["probs"].items(), key=lambda kv: -kv[1]) if kv[0] != base["label"]), ("-", 0.0))
det = r["deterministic"]["probs"]
past = None if base["decided_by"] == "user" or r.get("review") else hint_for(max(det, key=det.get), pats) # looked at: settled
mat = (r.get("material") or {}).get("origin_zh", "")
@@ -701,7 +757,7 @@ def cmd_plan(args) -> int:
from .integrations.capsule_cinema import ref_clips
from .pipeline import finalize
from .plan import CAP, Planner, user_capabilities
- from .production import _norm
+ from .production import _norm, pick_model
out = Path(args.out_dir)
intent = load_intent(out)
@@ -715,8 +771,12 @@ def cmd_plan(args) -> int:
intent["model"] = pref("engine") or DEFAULT_MODEL
pl = Planner()
- live = {k: m for k, m in pl.models.items() if m.get("status") not in ("shutdown", "deprecated")}
+ live = {k: x for k, x in pl.models.items() if x.get("status") not in ("shutdown", "deprecated")}
m = next((x for x in live.values() if _norm(x["id"]) == _norm(intent["model"]) or _norm(x.get("name", "")) == _norm(intent["model"])), None)
+ if m and not (m.get("category") == "video" and {"video.t2v", "video.i2v_first_frame"} & set(m.get("primitives", []))):
+ print(U(f"rea-video: {m['id']} 不是视频生成模型(需要支持文生视频或首帧生视频)。可选生视频模型:rea-video models",
+ f"rea-video: {m['id']} is not a video generation model (needs text-to-video or first-frame image-to-video). Available models: rea-video models"), file=sys.stderr)
+ return 2
if not m:
target = user_capabilities() / 'models' / (re.sub(r'[^a-z0-9.-]+', '-', intent['model'].lower()) + '.yaml')
print(U(f"rea-video: 能力地图里没有 {intent['model']}。先查这个模型的官方文档(单次时长、能不能吃参考视频 / 参考图和各几个、"
diff --git a/rea_video/code_remake.py b/rea_video/code_remake.py
index cdc3fd6..2708445 100644
--- a/rea_video/code_remake.py
+++ b/rea_video/code_remake.py
@@ -33,6 +33,13 @@ def _dot(m: dict, W: int) -> float:
return round(float(np.clip(np.sqrt(area / np.pi) if area else 1.0, 0.7, 1.4)), 2)
+def _display_even(src: dict) -> tuple[int, int]:
+ w, h = int(src.get("width") or 960), int(src.get("height") or 540)
+ if src.get("rotation") in (90, 270):
+ w, h = h, w
+ return max(2, w - w % 2), max(2, h - h % 2)
+
+
def build_spec(out: Path) -> dict:
"""spec.json for the code-rendered scenes of a breakdown, before matching."""
b = read_json(out / "breakdown.json")
@@ -44,7 +51,7 @@ def build_spec(out: Path) -> dict:
scene_frames(out, breakdown=b)
scenes = read_json(fdir / "scenes.json").get("scenes", [])
shots = {s.get("index"): s for s in b.get("shots", [])}
- W, H = int(src.get("width") or 960), int(src.get("height") or 540)
+ W, H = _display_even(src)
spec: dict = {"size": [W, H], "fps": float(src.get("fps") or 25), "duration": float(src.get("duration") or 0),
"text": "overlays.ass" if any(not c.get("part_of_picture") for c in (b.get("packaging") or {}).get("text_cues", [])) else None,
"bloom": 0.5, "bloom_size": 0.012, "scenes": []}
@@ -127,8 +134,8 @@ def code_remake(out: Path, reset: bool = False, render: bool = True, score: bool
shutil.copyfile(redraw.__file__, cdir / "render.py")
cues = [c for c in (b.get("packaging") or {}).get("text_cues", []) if not c.get("part_of_picture")]
if cues and (reset or not (cdir / "overlays.ass").exists()):
- src = b.get("source") or {}
- (cdir / "overlays.ass").write_text(to_ass(cues, int(src.get("width") or 960), int(src.get("height") or 540)), encoding="utf-8")
+ aw, ah = _display_even(b.get("source") or {})
+ (cdir / "overlays.ass").write_text(to_ass(cues, aw, ah), encoding="utf-8")
fit_ass_sizes(cdir / "overlays.ass")
if reset or not spec_path.exists():
spec = build_spec(out)
diff --git a/rea_video/drive.py b/rea_video/drive.py
index a142817..702d97c 100644
--- a/rea_video/drive.py
+++ b/rea_video/drive.py
@@ -70,10 +70,11 @@ def overlays(b: dict, persistent: bool = False) -> list[dict]:
continue
if int(c.get("samples") or 0) < MIN_SAMPLES:
continue # a flicker read: printing on a dancer's clothes, caught for a frame or two as it turns past
+ from .pipeline import shot_overlay_text
+
mid = (c["t0"] + c["t1"]) / 2
r = next((r for r in b.get("shots", []) if r["start"] <= mid < r["end"]), None) or {}
- said = (r.get("vlm") or {}).get("overlay_text")
- said = said if isinstance(said, list) else (r.get("review") or {}).get("overlay_text")
+ said = shot_overlay_text(r)
if isinstance(said, list) and not any(_same_words(c.get("text") or "", str(o)) for o in said):
continue # a reader listed this shot's post-production words; this one is text in the scene (a phone screen, a sign)
out.append({"t0": float(c["t0"]), "t1": float(c["t1"]), "bbox": c["bbox"], "what": c.get("kind_zh") or c.get("kind") or "text",
diff --git a/rea_video/entities.py b/rea_video/entities.py
index 2fadacd..fbb78fe 100644
--- a/rea_video/entities.py
+++ b/rea_video/entities.py
@@ -7,6 +7,7 @@ the per-shot references and a "no cast available" note instead of an empty secti
"""
from __future__ import annotations
+from .classify import LABEL_ZH
from .i18n import LangDict, T, join, semi
KIND_ZH = LangDict({"person": "真人", "animal": "动物", "cartoon": "卡通形象", "avatar": "数字人", "product": "商品", "other": "其他"},
@@ -178,9 +179,9 @@ def open_questions(b: dict) -> list[str]:
elif base.get("uncertain"):
q.append(f"{tag}{T(':', ': ')}{base['uncertain']}")
elif base.get("confidence", 1) < 0.6:
- alt = sorted((base.get("probs") or {}).items(), key=lambda kv: -kv[1])[:2]
+ alt = [kv for kv in sorted((base.get("probs") or {}).items(), key=lambda kv: -kv[1]) if kv[0] != base.get("label")]
q.append(tag + T(":{l} 只有 {c:.0%} 置信", ": {l} at only {c:.0%} confidence", l=base.get("label_zh", ""), c=base["confidence"])
- + (T(",次选 {a}", ", runner-up {a}", a=alt[1][0]) if len(alt) > 1 else ""))
+ + (T(",次选 {a}", ", runner-up {a}", a=LABEL_ZH.get(alt[0][0], alt[0][0])) if alt else ""))
unsure = sorted({it.get("kind_zh", "") for it in (r.get("material") or {}).get("items", []) if it.get("real_material") is None})
if unsure:
q.append(tag + T(":{k} 是真实素材还是生成的,待确认", ": {k}: real material or generated, to confirm", k=join(unsure)))
diff --git a/rea_video/evaluate.py b/rea_video/evaluate.py
index 444f9bd..276da3a 100644
--- a/rea_video/evaluate.py
+++ b/rea_video/evaluate.py
@@ -191,6 +191,14 @@ def boundary_f1(pred: list[float], gt: list[float], tol: float = 0.1, ignore: li
return {"precision": round(prec, 3), "recall": round(rec, 3), "f1": round(f1, 3), "tp": tp, "fp": fp, "fn": len(gt) - tp}
+def sudden_recall(truth: list[dict], found: list[dict], tol: float = 0.12) -> dict:
+ """Local changes without a cut: a labelled one is found when a candidate is close in time and inside its box."""
+ def hit(g: dict, f: dict) -> bool:
+ x, y = (f["box"][0] + f["box"][2]) / 2, (f["box"][1] + f["box"][3]) / 2
+ return abs(f["t"] - g["t"]) <= tol and g["box"][0] <= x <= g["box"][2] and g["box"][1] <= y <= g["box"][3]
+ return {"truth": len(truth), "found": sum(any(hit(g, f) for f in found) for g in truth), "candidates": len(found)}
+
+
def resolution_bucket(src: dict) -> str:
"""Short side of the picture as shown, rounded to the usual tiers."""
w, h = src.get("width") or 0, src.get("height") or 0
@@ -341,6 +349,8 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
ignore=entry.get("cuts_uncertain"),
spans=[(s["transition"]["start"], s["transition"]["end"]) if s.get("transition") else None
for s in b["shots"][1:]])
+ if entry.get("sudden"):
+ row["sudden"] = sudden_recall(entry["sudden"], ((b.get("moments") or {}).get("measured") or {}).get("sudden") or [])
if entry.get("image_source"):
srcs = {s["base"].get("image_source") for s in b["shots"]}
row["image_source_ok"] = entry["image_source"] in srcs
@@ -386,6 +396,11 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Tr
summary["cuts"] = {"truth": tp + fn, "found": tp, "false": fp,
"recall": round(tp / (tp + fn), 3) if tp + fn else None,
"precision": round(tp / (tp + fp), 3) if tp + fp else None}
+ suddens = [r["sudden"] for r in rows if "sudden" in r]
+ if suddens:
+ s_tot, s_hit, s_cand = (sum(x[k] for x in suddens) for k in ("truth", "found", "candidates"))
+ summary["sudden"] = {"truth": s_tot, "found": s_hit, "candidates": s_cand,
+ "recall": round(s_hit / s_tot, 3) if s_tot else None}
result = {"summary": summary, "rows": rows,
"confusion_seconds": {g: {p: round(v, 1) for p, v in ps.items() if v} for g, ps in confusion.items() if any(ps.values())}}
write_json(out / "eval_result.json", result)
diff --git a/rea_video/faces.py b/rea_video/faces.py
index af2c442..40c819b 100644
--- a/rea_video/faces.py
+++ b/rea_video/faces.py
@@ -72,7 +72,7 @@ def _detector():
return _DET
-def detect(frame: np.ndarray) -> list[dict]:
+def detect(frame: np.ndarray, min_area: float = MIN_AREA) -> list[dict]:
"""Faces in one BGR frame, largest first: {box: [x, y, w, h] in 0..1, area, score, landmarks: 5x[x, y] in 0..1 | None}."""
det = _detector()
if not det:
@@ -91,19 +91,20 @@ def detect(frame: np.ndarray) -> list[dict]:
g = cv2.equalizeHist(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY))
for (x, y, fw, fh) in d.detectMultiScale(g, scaleFactor=1.15, minNeighbors=5, minSize=(32, 32)):
out.append({"box": [x / w, y / h, fw / w, fh / h], "area": fw * fh / (w * h), "score": 1.0, "landmarks": None})
- out = [f for f in out if f["area"] >= MIN_AREA]
+ out = [f for f in out if f["area"] >= min_area]
return sorted(out, key=lambda f: -f["area"])
def shot_faces(frames: list[np.ndarray], max_frames: int = 6) -> dict:
- """Face summary over a shot's sampled frames: presence ratio and the main face per sampled frame."""
+ """Face summary over a shot's sampled frames: presence ratio (MIN_AREA, for the classifier) and the main face per
+ sampled frame (including medium/full-shot faces on 16:9 landscape, for framing and format aspects)."""
if not frames:
return {"presence": 0.0, "frames": []}
step = max(1, len(frames) // max_frames)
picked = list(range(0, len(frames), step))[:max_frames]
per = []
for i in picked:
- fs = detect(frames[i])
+ fs = [f for f in detect(frames[i], min_area=0.004) if f["area"] >= MIN_AREA or (f["box"][3] >= 0.08 and f["score"] >= 0.8)]
per.append({"i": i, "face": fs[0] if fs else None, "count": len(fs)})
- hits = sum(1 for p in per if p["face"])
+ hits = sum(1 for p in per if p["face"] and p["face"]["area"] >= MIN_AREA)
return {"presence": hits / len(per), "frames": per}
diff --git a/rea_video/gemini.py b/rea_video/gemini.py
index c06e6cf..12d0f24 100644
--- a/rea_video/gemini.py
+++ b/rea_video/gemini.py
@@ -21,8 +21,8 @@ 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
+DEFAULT_MODEL = "gemini-3.5-flash"
+INLINE_MAX = 14 * 1024 * 1024 # base64 adds 33%: 14 MB raw -> ~18.7 MB body, under Gemini's 20 MB inline limit
CLIP_FPS = ((30.0, 10.0), (120.0, 4.0)) # (clips up to s, frames a second); longer: Gemini's default (1)
@@ -85,10 +85,14 @@ class GeminiClient:
"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])
+ try:
+ 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])
+ except Exception:
+ self._delete(info.get("name", ""))
+ raise
if info.get("state") != "ACTIVE":
self._delete(info.get("name", ""))
raise GeminiError(f"uploaded file state {info.get('state')}")
diff --git a/rea_video/generation.py b/rea_video/generation.py
index a6d7ef1..a710caa 100644
--- a/rea_video/generation.py
+++ b/rea_video/generation.py
@@ -209,19 +209,23 @@ def _clips(ranges: list[list[float]], each: float) -> list[list[list[float]]]:
# ---------------------------------------------------------------- one unit
def _shot_text(r: dict) -> str:
"""What happens in the shot, in the report's language when the reader wrote it in both."""
+ from .pipeline import shot_description
+
p = shot_prompts(r)
if lang() == "en" and p.get("video_prompt_en"):
return p["video_prompt_en"]
- return p.get("video_prompt") or (r.get("review") or r.get("vlm") or {}).get("description") or ""
+ return p.get("video_prompt") or shot_description(r)
def _brief(seg: list[dict], keyframe_tag: dict[int, str]) -> list[dict]:
+ from .pipeline import shot_description
+
out, acc = [], 0.0
for r in seg:
act = performance.of(r)
out.append({"shot": r["index"], "time": [round(r["start"], 3), round(r["end"], 3)], "at": round(acc, 3),
"duration": round(r["duration"], 3), "label": r["base"]["label"],
- "source": (r.get("review") or r.get("vlm") or {}).get("description") or "",
+ "source": shot_description(r),
"action": with_acting(_shot_text(r), act, en=lang() == "en"), "framing": framing_words(r)[0],
"composition": keyframe_tag.get(r["index"]), **({"acting": performance.summary(act)} if act else {})})
acc += r["duration"]
@@ -297,6 +301,9 @@ def build_unit(seg: list[dict], k: int, strategy: str, spec: dict, own: list[dic
label = max(votes.items(), key=lambda kv: kv[1])[0]
parts = int(-(-dur // spec["max"])) if len(seg) == 1 and dur > spec["max"] + 1e-6 else 1
refs = [dict(r) for r in own] if strategy != "frames" or not spec["exclusive"] else []
+ kept_tags = {r["tag"] for r in refs}
+ unit_swaps = [re.sub(r"(参考 @图片\d+)| \(see @图片\d+\)", "", t) if not any(k in t for k in kept_tags) else t
+ for t in swaps_txt]
keyframe_tag: dict[int, str] = {}
if strategy == "remix":
each = min(REF_CLIP_S, spec["ref_total"])
@@ -324,7 +331,7 @@ def build_unit(seg: list[dict], k: int, strategy: str, spec: dict, own: list[dic
"shots": [r["index"] for r in seg], "start": round(t0, 3), "end": round(t1, 3), "duration": dur, "ranges": ranges,
"mode": "multi_shot" if len(seg) > 1 else ("split" if parts > 1 else "single"), "calls": parts,
"generate_s": round(dur / parts, 3), "model": (model or {}).get("id"), "model_name": model_name((model or {}).get("name")),
- "refs": refs, "brief": brief, "draft": _draft(strategy, refs, brief, swaps_txt, style),
+ "refs": refs, "brief": brief, "draft": _draft(strategy, refs, brief, unit_swaps, style),
"inputs": _inputs(strategy, refs, seg, spec)}
unframed = [x["shot"] for x in brief if strategy == "keyframes" and not x.get("composition")]
missing = [x["shot"] for x in brief if not x["action"]]
@@ -474,12 +481,19 @@ def checks(plan: dict, intent: dict, prompts: dict[str, str], notes: dict | None
add("error", T("参考图找不到,请重新提供:{p}", "reference image missing, provide it again: {p}", p=Path(s["image"]).name))
if spec.get("multi_ref") and not spec.get("images_stated"):
add("warn", T("能力地图没写这个模型最多几张参考图,按 {n} 张排的;查到实际数后补进模型资料", "the capability map has no image limit for this model; planned for {n}, add the real one", n=UNKNOWN_IMAGES))
+ if spec.get("exclusive") and plan.get("strategy") == "frames" and any(s.get("image") for s in intent.get("swaps") or []):
+ add("warn", T("当前模型在首尾帧模式下不接收额外参考图:先把替换主体画进每段首帧(remake/redrawn/<单元>_first.png)再生成",
+ "in first/last-frame mode this model takes no extra reference images: redraw each unit's first frame (remake/redrawn/<unit>_first.png) with the swapped subject first"))
for u in units:
n_img, n_vid = len(unit_images(u)), len({r["tag"] for r in u["refs"] if r["tag"].startswith("@视频")})
if spec.get("images") is not None and n_img > max(spec["images"], 0) and (n_img or spec.get("multi_ref")):
add("error", T("{u} 要传 {n} 张图,超过这个模型的 {m} 张", "{u} sends {n} images, over this model's {m}", u=u["id"], n=n_img, m=spec["images"]), u["id"])
for part in sorted({r.get("part", 1) for r in u["refs"] if r["tag"].startswith("@视频")}):
- secs = sum(z - a for r in u["refs"] if r["tag"].startswith("@视频") and r.get("part", 1) == part for a, z in r["ranges"])
+ part_vids = [r for r in u["refs"] if r["tag"].startswith("@视频") and r.get("part", 1) == part]
+ if len(part_vids) > max(1, int(spec.get("ref_videos") or 1)):
+ add("error", T("{u} 单次要传 {n} 段参考视频,超过这个模型的 {m} 段", "{u} sends {n} reference clips in one call, over this model's {m}",
+ u=u["id"], n=len(part_vids), m=spec.get("ref_videos", 1)), u["id"])
+ secs = sum(z - a for r in part_vids for a, z in r["ranges"])
if secs > spec.get("ref_total", 1e9) + 1e-3:
add("error", T("{u} 参考视频共 {s:.1f} 秒,超过这个模型的 {m:.0f} 秒", "{u} has {s:.1f}s of reference video, over this model's {m:.0f}s",
u=u["id"], s=secs, m=spec["ref_total"]), u["id"])
diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.py
index b63527e..33ad5bd 100644
--- a/rea_video/integrations/capsule_cinema.py
+++ b/rea_video/integrations/capsule_cinema.py
@@ -67,8 +67,9 @@ def export_capsule_analysis(b: dict, out_path: Path, keep_source_text: bool = Fa
mix_txt = "、".join(f"{m['label_zh']} {m['ratio']:.0%}" for m in s["production_mix"])
segments = []
literals: list[str] = []
+ from ..pipeline import shot_description
+
for sh in shots:
- v = sh.get("vlm") or {}
f = sh["features"]
copy = _shot_copy(sh) if keep_source_text else ""
literals += [t for t in copy.split(" / ") if len(t) >= 2]
@@ -78,7 +79,7 @@ def export_capsule_analysis(b: dict, out_path: Path, keep_source_text: bool = Fa
segments.append({
"start_time": _mmss(sh["start"]), "end_time": _mmss(sh["end"]),
"beat": f"镜头 {sh['index']}({sh['duration']:.1f}s)",
- "visuals": f"[{sh['base']['label_zh']} {sh['base']['confidence']:.0%}] " + ((v.get("description") or sh["verdict"]) if keep_source_text else "按原片的景别和机位重新设计内容"),
+ "visuals": f"[{sh['base']['label_zh']} {sh['base']['confidence']:.0%}] " + ((shot_description(sh) or sh["verdict"]) if keep_source_text else "按原片的景别和机位重新设计内容"),
"material": (sh.get("material") or {}).get("origin_zh", ""),
"motion": motion, "copy": copy,
"audio": "",
@@ -327,7 +328,7 @@ def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[str
if images:
params["image_paths"] = [x["path"] for x in images]
if u["strategy"] == "frames":
- first, last = files.get((1, "first")), files.get((1, "last"))
+ first, last = files.get((part, "first")) or files.get((1, "first")), files.get((part, "last")) or files.get((1, "last"))
if last:
params.update(start_image_path=first, end_image_path=last)
else:
@@ -335,7 +336,12 @@ def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[str
jid = u["id"] if len(parts) == 1 else f"{u['id']}-{part}"
times = [r["t"] for r in u["refs"] if r.get("keyframe") and not redrawn_frame(bdir, f"shot{int(r['keyframe']):03d}")]
if u["strategy"] == "frames":
- times += [t for name, t in ((f"{u['id']}_first", u["start"] + 0.05), (f"{u['id']}_last", u["end"] - 0.08)) if not redrawn_frame(bdir, name)]
+ span = max(0.0, u["end"] - u["start"])
+ ps0 = u["start"] + span * (part - 1) / max(1, len(parts))
+ ps1 = u["start"] + span * part / max(1, len(parts))
+ pd = max(0.0, ps1 - ps0)
+ t_first, t_last = min(ps1, ps0 + min(0.05, pd / 4)), max(ps0, ps1 - min(0.08, pd / 4))
+ times += [t for name, t in ((f"{u['id']}_first", t_first), (f"{u['id']}_last", t_last)) if not redrawn_frame(bdir, name)]
words = list(dict.fromkeys(w for t in times for w in scene_text(b, t)))
warning = T("参考帧里还有画面内文字({w}),模型可能照着生成:换成干净图,或确认有授权", "the reference frames still show text in the picture ({w}), which the model may copy: use a clean image or confirm you have the rights",
w=join(words[:6])) if words else None
@@ -369,11 +375,18 @@ def ref_clips(b: dict, bdir: Path, unit: dict) -> dict[tuple[int, str], str]:
out[(r.get("part", 1), r["tag"])] = str(f.resolve())
if unit.get("strategy") == "frames":
s0, s1 = unit["start"], unit["end"]
- for key, t in (("first", s0 + 0.05), ("last", s1 - 0.08)):
- if key == "last" and not any(x["kind"] == "last_frame" and x["need"] != "no" for x in unit.get("inputs") or []):
- continue
- f = redrawn_frame(bdir, f"{unit['id']}_{key}") or d / f"{unit['id']}_{key}_{t:.2f}.jpg"
- if not f.is_file():
- clean_frame(b, t, f)
- out[(1, key)] = str(f.resolve())
+ n_parts = max(1, int(unit.get("calls") or 1))
+ want_last = any(x["kind"] == "last_frame" and x["need"] != "no" for x in unit.get("inputs") or [])
+ for part in range(1, n_parts + 1):
+ ps0 = s0 + (s1 - s0) * (part - 1) / n_parts
+ ps1 = s0 + (s1 - s0) * part / n_parts
+ pd = max(0.0, ps1 - ps0)
+ for key, t in (("first", min(ps1, ps0 + min(0.05, pd / 4))), ("last", max(ps0, ps1 - min(0.08, pd / 4)))):
+ if key == "last" and not want_last:
+ continue
+ red = redrawn_frame(bdir, f"{unit['id']}_{key}" if n_parts == 1 else f"{unit['id']}_p{part}_{key}") or (redrawn_frame(bdir, f"{unit['id']}_{key}") if part == 1 else None)
+ f = red or d / f"{unit['id']}_p{part}_{key}_{t:.2f}.jpg" if n_parts > 1 else (red or d / f"{unit['id']}_{key}_{t:.2f}.jpg")
+ if not f.is_file():
+ clean_frame(b, t, f)
+ out[(part, key)] = str(f.resolve())
return out
diff --git a/rea_video/media.py b/rea_video/media.py
index 3b6bfb7..7730104 100644
--- a/rea_video/media.py
+++ b/rea_video/media.py
@@ -104,9 +104,12 @@ def video_info(path: str | Path) -> VideoInfo:
raise MediaError(f"no video stream in {path}")
v = vstreams[0]
fmt = data.get("format", {})
- fps = _ratio(v.get("avg_frame_rate")) or _ratio(v.get("r_frame_rate")) or 30.0
duration = float(v.get("duration") or fmt.get("duration") or 0.0)
- nb = int(v.get("nb_frames") or 0) or int(round(duration * fps))
+ nb_raw = int(v.get("nb_frames") or 0)
+ avg = _ratio(v.get("avg_frame_rate"))
+ rfps = _ratio(v.get("r_frame_rate"))
+ fps = avg or (nb_raw / duration if nb_raw and duration > 0 else 0.0) or (rfps if 0 < rfps <= 120 else 30.0)
+ nb = nb_raw or int(round(duration * fps))
rotation = 0
for sd in v.get("side_data_list", []) or []:
if "rotation" in sd:
diff --git a/rea_video/memory.py b/rea_video/memory.py
index 5f5d11f..94554e4 100644
--- a/rea_video/memory.py
+++ b/rea_video/memory.py
@@ -74,6 +74,11 @@ def set_pref(key: str, value: str | None) -> dict:
raise ValueError(U(f"ocr_lang 只能是 {' / '.join(OCR_LANGS)}", f"ocr_lang must be one of: {' / '.join(OCR_LANGS)}"))
if value is not None and key == "asr_lang" and value not in ASR_LANGS:
raise ValueError(U(f"asr_lang 只能是 {' / '.join(ASR_LANGS)}", f"asr_lang must be one of: {' / '.join(ASR_LANGS)}"))
+ if value is not None and key == "lang":
+ from .i18n import LANGS
+
+ if value not in LANGS:
+ raise ValueError(U(f"lang 只能是 {' / '.join(LANGS)}", f"lang must be one of: {' / '.join(LANGS)}"))
if value is not None and key in ("env_file", "capsule_root"):
value = str(Path(value).expanduser().resolve())
prefs = load_prefs()
diff --git a/rea_video/moments.py b/rea_video/moments.py
index 024d245..a3ac4e9 100644
--- a/rea_video/moments.py
+++ b/rea_video/moments.py
@@ -29,7 +29,7 @@ import numpy as np
from .i18n import LangDict, T
from .util import LOG, fmt_time, read_json, write_json
-VERSION = 2
+VERSION = 3
STEP = 0.25 # seconds per hint sample
TOP_HINTS = 24
MAX_MOMENTS = 10
@@ -46,6 +46,13 @@ 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)
+# a part of the picture that was at rest and changes for good in one frame, with no cut (something appears / is swapped)
+SUDDEN_GRID, SUDDEN_PRE, SUDDEN_POST = (16, 25), 3, 3 # blocks across, down (portrait); frames looked at before / after
+SUDDEN_STILL, SUDDEN_JUMP, SUDDEN_KEEP = 9.0, 12.0, 0.8 # grey levels: at rest before; the jump; share of it that stays
+SUDDEN_AREA = (0.015, 0.30) # share of the picture
+SUDDEN_MAX_ASPECT = 4.0 # wider than this is a line of text popping in
+SUDDEN_TOP = 6
+SURE = ("seen", "likely", "unknown")
TILE_AREA = {"find": 160 * 90, "pin": 256 * 144, "explain": 320 * 180}
KIND = LangDict({"reveal": "揭秘 / 变化时刻", "twist": "反转时刻", "climax": "高潮时刻", "goof": "穿帮时刻"},
@@ -77,6 +84,7 @@ FIND_INSTRUCTIONS = """你是短视频剪辑师,在找这条视频里值得单
格子太小看不清时用 state.zoom_cmd 抽一段大图看(把 {start} {end} {every} 换成秒数、{name} 换成一个文件名;段长时 every 写大一点;东西小就加 --focus 只放大那一块;输出可能分成 _1、_2…,以命令打印的 tiles 列表为准;写在 look/zoom/ 里没关系);
能直接看视频的(比如 Gemini):可以直接看 state.video(带声音),比小格准,时间用整片的秒数写;
state.hints 是工具从声音和画面里测到的候选(有人惊呼、人声突然变大、快速动作后突然定住),大约只有一成是真的,只用来提醒你去看哪里。
+state.measured 是逐帧量出来的:cuts 是剪辑点;sudden 是「某块画面上一帧还没有、这一帧突然变了、前后没有剪断」的位置(东西凭空出现常在这里,但手快速划过也会被量到,要看图确认)。
先通读台词弄清这条视频在演什么(谁要变什么、剧情走到哪),再对着总览找画面上发生变化的地方。
按 JEV 格式回答,只回 JSON:{"moments": ["开始秒-结束秒 类型 概率 一句话:发生了什么", ...]}
@@ -101,7 +109,7 @@ 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": "一句话"}, ...}
+"frames": "4.83-5.37", "focus": ".15,.50,.55,.90", "what": "一句话(可不写)", "seen": "一句话", "before": "前一帧这个位置有什么", "guess": "推测:一句话", "sure": "seen|likely|unknown", "why": "一句话"}, ...}
- steps:3-6 步,按时间排,每步 "秒数 一句话"(关键动作那几步尽量落在 frames 里,比如"指尖捏着核桃靠近碗""手盖住碗""碗里看清核桃");一句话只写画面里看得见的事,不超过 20 字。可以超出图里的时间范围(变化更早 / 更晚时)。
- 关键一步前面加 *:东西第一次看得清地出现 / 消失 / 换掉的那一帧(短片会定格在这一帧,一团运动模糊的不行,往后挪到第一帧清楚的)。变化常常比镜头亮出来、人惊呼早,要往前找(手盖住、挡住、换手、镜头晃开的时候);更早那帧只是模糊的一团,可以作为前一步写进去。格子看不清就用 state.zoom_cmd 抽密的大图逐帧看,秒数写到 0.1 以内。
- 先核对上一轮的 what / 关键帧:逐帧放大看过后发现不对(比如东西其实还在手上),以你这一轮看到的为准,what 和 steps 都按新的写。
@@ -112,7 +120,10 @@ EXPLAIN_INSTRUCTIONS = """你是做魔术揭秘 / 高光解说的剪辑师,要
- 每一步默认按 focus 放大;要看整个画面的一步(比如另一个人的反应)在句末写 "@全"。
- focus:放大区域 "x0,y0,x1,y1"(0-1,整幅画面坐标),图解和短片都按它放大,框越小放越大;框住手和道具、去掉模板和横幅;整个画面都要看就不写。框的宽高比会被限制在 0.6-1.8(太扁太窄会往外扩),短片里放大的画面按原比例加黑边。
- what:一句话重写这一段发生了什么(必写,图解标题用它;里面提到的秒数要和关键一步一致,或者干脆不写秒数)。
-- seen:画面里看得到的证据(写秒数)。guess:画面里看不到、靠推测的部分(手法、道具从哪来),以"推测:"开头;没有就不写。why:观众为什么没发现(注意力被引到哪了);不是魔术可以不写。"""
+- seen:画面里看得到的证据(写秒数)。guess:画面里看不到、靠推测的部分(手法、道具从哪来),以"推测:"开头;没有就不写。why:观众为什么没发现(注意力被引到哪了);不是魔术可以不写。
+- before:必写。放大看关键一步的**前一帧**,同一个位置上有什么("0.17s 碗里只有面,看不到薯塔")。写 guess 之前先拿它核对:手法要求东西事先在那里,而前一帧看不到,这个手法就不成立,换一个或写不知道。
+- sure:手法有多确定,三选一:seen(手法本身在画面里看得到)、likely(有证据但没直接看到)、unknown(说不清怎么做到的)。说不清就写 unknown,不要编一个听起来合理的解释。
+- state 里每段的 measured 是这一段逐帧量出来的剪辑点和局部突变。说「这里剪了一刀」要对得上 cuts;关键一步落在 cuts 上而解释没提剪辑,也要说明。对不上的会在报告里标「待确认」。"""
FOCUS = {"magic": "这是魔术视频:每段魔术的变化瞬间(东西出现、消失、换了),以及露馅 / 穿帮的地方。",
"drama": "这是剧情视频:反转、情绪高潮,以及穿帮(道具、工作人员、前后不连贯)。",
"": "精彩的高光时刻:变化 / 揭秘、反转、高潮,以及穿帮。"}
@@ -219,6 +230,104 @@ def hints(lines: list[dict], vocals: Path | None, track, dur: float, top: int |
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 sudden_changes(track, bounds: list[int], top: int | None = None,
+ skip: list[tuple[int, int]] | None = None) -> list[dict]:
+ """Parts of the picture that were at rest and change for good in a single frame, inside one shot: where something
+ appears out of nothing or is swapped. A fast hand can look the same, so these are candidates for a reader."""
+ if track is None or not track.thumbs or track.n < SUDDEN_PRE + SUDDEN_POST + 2:
+ return []
+ import cv2
+
+ h, w = track.thumbs[0].shape[:2]
+ grid = SUDDEN_GRID if h >= w else SUDDEN_GRID[::-1]
+ B = np.stack([cv2.resize(t, grid, interpolation=cv2.INTER_AREA) for t in track.thumbs]).astype(np.float32)
+ ts = np.asarray(track.times, dtype=float) if track.times is not None and len(track.times) else np.arange(track.n) / track.fps
+ edges = sorted(int(x) for x in bounds if 0 < int(x) < track.n)
+ spans = [(int(a), int(z)) for a, z in (skip or [])]
+ found: list[dict] = []
+ for a, z in zip([0] + edges, edges + [track.n]):
+ for i in range(a + SUDDEN_PRE, z - SUDDEN_POST):
+ if any(sa - 1 <= i <= sz + 1 for sa, sz in spans):
+ continue
+ before = B[i - SUDDEN_PRE:i]
+ ref = np.median(before, axis=0)
+ mask = ((before.max(axis=0) - before.min(axis=0)) < SUDDEN_STILL) & (np.abs(B[i] - B[i - 1]) > SUDDEN_JUMP) \
+ & (np.abs(B[i:i + SUDDEN_POST + 1] - ref).min(axis=0) > SUDDEN_JUMP * SUDDEN_KEEP)
+ if not mask.any():
+ continue
+ mask = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((2, 2), np.uint8))
+ k, _, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)
+ for x, y, bw, bh, cells in stats[1:k]:
+ area = cells / mask.size
+ box = [x / grid[0], y / grid[1], (x + bw) / grid[0], (y + bh) / grid[1]]
+ pw, ph = (box[2] - box[0]) * w, (box[3] - box[1]) * h
+ if not SUDDEN_AREA[0] <= area <= SUDDEN_AREA[1] or pw / max(ph, 1e-6) > SUDDEN_MAX_ASPECT:
+ continue
+ if x == 0 or y == 0 or x + bw >= grid[0] or y + bh >= grid[1]:
+ continue # reaches the edge of the picture: an arm or a body coming in, not something appearing
+ found.append({"t": round(float(ts[i]), 3), "frame": i, "area": round(float(area), 4), "box": [round(float(v), 3) for v in box]})
+ keep = sorted(found, key=lambda f: -f["area"])[:top or max(SUDDEN_TOP, int(float(ts[-1]) / 10))]
+ return sorted(keep, key=lambda f: f["t"])
+
+
+def measured(track, bounds: list[int], skip: list[tuple[int, int]] | None = None) -> dict:
+ """What the frames say, for the reader to check an explanation against: the cuts and the sudden local changes."""
+ if track is None or track.n == 0:
+ return {"cuts": [], "sudden": [], "frame_s": 0.04}
+ ts = np.asarray(track.times, dtype=float) if track.times is not None and len(track.times) else np.arange(track.n) / track.fps
+ return {"cuts": [round(float(ts[int(b)]), 3) for b in bounds if 0 < int(b) < track.n], "sudden": sudden_changes(track, bounds, skip=skip),
+ "frame_s": round(float(np.median(np.diff(ts))), 4) if len(ts) > 1 else 0.04}
+
+
+def _measured_lines(m: dict | None, t0: float = 0.0, t1: float = 1e9) -> dict:
+ m = m or {}
+ return {"cuts": [f"{c:.2f} 剪辑点" for c in m.get("cuts") or [] if t0 <= c <= t1],
+ "sudden": [f"{x['t']:.2f} 局部突变,区域 {','.join(f'{v:.2f}' for v in x['box'])},占画面 {x['area']:.1%},前后没有剪断"
+ for x in m.get("sudden") or [] if t0 <= x["t"] <= t1]}
+
+
+def shown_guess(ex: dict) -> str:
+ """The guess as a viewer reads it: an unsettled one says so on the diagram and in the clip."""
+ g = ex.get("guess") or ""
+ return T("待确认|", "To confirm | ") + g if g and ex.get("doubts") else g
+
+
+_NEG_CUT = re.compile(
+ r"(?:没有?|无|未|并非|不是|不靠|零)\s*(?:剪辑|切镜|跳切|跳剪|转场|剪断|剪了?一刀|切了?一刀|拼接)|一镜到底"
+ r"|\b(?:no|without(?:\s+a)?|not\s+a)\s+(?:cut|jump[\s-]?cut|edit)\b", re.I,
+)
+CUT_WORDS = re.compile(
+ r"剪辑|跳切|跳剪|切镜|硬切|暗切|藏剪|剪断|转场|剪了?一刀|切了?一刀|剪掉|剪去|拼接"
+ r"|\bjump[\s-]?cut\b|\bhard\s+cut\b|\bhidden\s+cut\b|\bcut\s+(?:away|to|here|at|between|out)\b|\bedit(?:ed|ing)?\b", re.I,
+)
+
+
+def _claims_cut(text: str) -> bool:
+ return bool(CUT_WORDS.search(_NEG_CUT.sub(" ", text or "")))
+
+
+def check_explain(ex: dict, m: dict | None) -> list[str]:
+ """Why an explanation is not settled: nobody checked the frame before the change, the reader is not sure, or it
+ disagrees with the measured cuts. The answer stays, marked as to be confirmed."""
+ doubts = []
+ claim = " ".join(str(ex.get(k) or "") for k in ("guess", "why"))
+ if not ex.get("before"):
+ doubts.append(T("没有核对变化前一帧", "the frame before the change was not checked"))
+ if ex.get("sure") != "seen":
+ doubts.append({"likely": T("手法没有直接看到", "the method is not directly visible"),
+ "unknown": T("说不清怎么做到的", "how it is done is unclear")}.get(ex.get("sure"), T("没有说明把握", "no confidence given")))
+ key = next((s["t"] for s in ex.get("steps") or [] if s.get("key")), None)
+ if m and key is not None and m.get("cuts") is not None:
+ near = 1.5 * float(m.get("frame_s") or 0.04)
+ at_cut = any(abs(c - key) <= near for c in m["cuts"])
+ says_cut = _claims_cut(claim)
+ if says_cut and not any(abs(c - key) <= max(near, 0.25) for c in m["cuts"]):
+ doubts.append(T("解释说这里有剪辑,但逐帧没量到剪辑点", "the explanation says there is a cut here, but none was measured"))
+ elif at_cut and not says_cut:
+ doubts.append(T("这一帧量到了剪辑点,解释没有提", "a cut was measured at this frame and the explanation does not mention it"))
+ return doubts
+
+
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 {}
@@ -311,7 +420,8 @@ def _yes(v) -> tuple[bool, float]:
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
+ dw, dh = info.display_size if hasattr(info, "display_size") else (info.width, info.height)
+ aspect = dw / dh if dw and dh else 16 / 9
return max(40, int(round(math.sqrt((area or TILE_AREA[look]) * aspect))))
@@ -422,6 +532,7 @@ def find_task(b: dict, out: Path, info) -> dict:
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 []],
+ "measured": _measured_lines((b.get("moments") or {}).get("measured")),
**({"summary": w["summary"]} if w.get("summary") else {}),
"overview": "格子按画面变化抽:动得多的地方密、静止的地方稀(几乎一样的帧合并了),左上角是秒数"}
instr = FIND_INSTRUCTIONS.replace("<FOCUS>", FOCUS.get(g, FOCUS[""])).replace("<MAX>", str(MAX_MOMENTS))
@@ -475,12 +586,13 @@ def explain_task(b: dict, out: Path, info, items: list[dict]) -> dict:
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,
+ "measured": _measured_lines((b.get("moments") or {}).get("measured"), t0, t1),
"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": ""}
+ "questions": {"per": "moment", "fields": ["steps", "frames", "focus", "what", "seen", "before", "guess", "sure", "why"]},
+ "answer_template": {"filled": True, **{it["id"]: {"steps": [], "frames": "", "focus": "", "what": "", "seen": "", "before": "", "guess": "", "sure": "", "why": ""}
for it in items}}}
@@ -550,7 +662,7 @@ def _window(v, dur: float) -> list[float] | None:
return [round(a, 3), round(z, 3)]
-def apply_explain(it: dict, a: dict, dur: float) -> None:
+def apply_explain(it: dict, a: dict, dur: float, m: dict | None = None) -> 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:
@@ -561,9 +673,16 @@ def apply_explain(it: dict, a: dict, dur: float) -> None:
win = _window(a.get("frames"), dur)
if win:
ex["frames"] = win
- for k in ("seen", "guess", "why"):
+ for k in ("seen", "before", "guess", "why"):
if str(a.get(k) or "").strip():
ex[k] = str(a[k]).strip()[:120]
+ sure = str(a.get("sure") or "").strip().lower()
+ if sure in SURE:
+ ex["sure"] = sure
+ if it.get("kind") in (None, "reveal", "goof") or any(ex.get(k) for k in ("guess", "before", "sure")):
+ doubts = check_explain(ex, m)
+ if doubts:
+ ex["doubts"] = doubts
if str(a.get("what") or "").strip():
it["what"] = str(a["what"]).strip()[:200]
it["explain"] = ex
@@ -683,6 +802,7 @@ def run(b: dict, out: Path, asker=None) -> dict:
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
+ import shutil
out = Path(out)
video = b["source"]["path"]
@@ -694,7 +814,9 @@ def run(b: dict, out: Path, asker=None) -> dict:
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()
+ shutil.rmtree(p) if p.is_dir() else p.unlink()
+ mo.pop("items", None)
+ mo["status"] = "pending"
meta = {"source": src, "rounds": []}
def step(task: dict) -> dict | None:
@@ -707,6 +829,8 @@ def run(b: dict, out: Path, asker=None) -> dict:
return got
def waiting(task: dict) -> dict:
+ mo.pop("items", None)
+ mo["status"] = "pending"
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"]]}
@@ -825,7 +949,7 @@ def run(b: dict, out: Path, asker=None) -> dict:
for it in items:
a = ans.get(it["id"])
if isinstance(a, dict):
- apply_explain(it, a, dur)
+ apply_explain(it, a, dur, mo.get("measured"))
mo.update(items=items, looked_by=by, status="done")
write_json(meta_p, meta)
return {"status": "done", "moments": len(items)}
@@ -836,6 +960,9 @@ def run(b: dict, out: Path, asker=None) -> dict:
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)."""
+ import hashlib
+
+ from .i18n import lang
from .media import cut_clip, extract_frame
from . import reveal
@@ -848,7 +975,12 @@ def export(b: dict, out: Path) -> None:
return
d = out / "moments"
d.mkdir(parents=True, exist_ok=True)
- w = min(1080, int(b["source"].get("width") or 1080))
+ rot = b["source"].get("rotation") in (90, 270)
+ sw0, sh0 = int(b["source"].get("width") or 0), int(b["source"].get("height") or 0)
+ sw, sh = (sh0, sw0) if rot else (sw0, sh0)
+ w = min(1080, sw or 1080)
+ sig_p = d / ".export.json"
+ sigs = read_json(sig_p) if sig_p.is_file() else {}
for it in items:
files = {}
for r, t in it["frames"].items():
@@ -866,54 +998,61 @@ def export(b: dict, out: Path) -> None:
strip = d / f"{it['id']}.jpg"
ex = it.get("explain") or {}
rv = None
+ sl = 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
+ steps = [dict(s) for s in ex["steps"]]
+ if box: # a ring outside the zoom would be drawn off the picture: drop it on the copy only
bx = (box[0] / sw, box[1] / sh, (box[0] + box[2]) / sw, (box[1] + box[3]) / sh)
- for s in ex["steps"]:
+ for s in 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: "),
+ notes = [(k, T(lbl, en) + (shown_guess(ex) if k == "guess" else 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)
+ sub = T("{a}–{b},{z}红圈 = 该看的地方", "{a}–{b}, {z}red ring = where to look", a=fmt_time(steps[0]["t"])[:-2],
+ b=fmt_time(steps[-1]["t"])[:-2], z=T("局部放大;", "zoomed; ") if box else "")
+ kt = next((s["t"] for s in 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,
+ reveal.diagram(video, 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"]
+ sig = hashlib.sha1(json.dumps([lang(), sw, sh, box, steps, shown_guess(ex), win], ensure_ascii=False, sort_keys=True).encode()).hexdigest()[:12]
+ fresh = sigs.get(it["id"]) == sig
rp = d / (f"{it['id']}_reveal_{kt:.2f}s" + (f"_{win[0]:.2f}-{win[1]:.2f}" if ex.get("frames") else "") + ".mp4")
+ if not fresh:
+ rp.unlink(missing_ok=True)
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}"),
+ video, bool(b["source"].get("has_audio")), (sw, sh), float(b["source"]["duration"]), tuple(it["span"]), steps,
+ box, shown_guess(ex), 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 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"
+ if not fresh:
+ sp.unlink(missing_ok=True)
+ key_step = next((s for s in 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
+ sigs[it["id"]] = sig
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 {}),
@@ -922,6 +1061,7 @@ def export(b: dict, out: Path) -> None:
for p in d.glob(f"{it['id']}_*"): # files of an earlier answer (other times) go
if p.name not in keep:
p.unlink()
+ write_json(sig_p, sigs)
def _strip(cells: list[tuple[Path, str, float]], out: Path, h: int = 360) -> None:
@@ -977,9 +1117,12 @@ def report_md(b: dict) -> list[str]:
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")):
+ for k, zh, en in (("seen", "看得到的", "Seen"), ("before", "变化前一帧", "The frame before"), ("guess", "看不到的", "Not on screen"),
+ ("why", "为什么没发现", "Why it's missed")):
if ex.get(k):
- L.append(f"- **{T(zh, en)}**{T(':', ': ')}{ex[k]}")
+ L.append(f"- **{T(zh, en)}**{T(':', ': ')}{shown_guess(ex) if k == 'guess' else ex[k]}")
+ if ex.get("doubts"):
+ L.append(T("- **⚠ 手法待确认**:", "- **⚠ Method to confirm**: ") + T(";", "; ").join(ex["doubts"]))
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"])
@@ -1012,7 +1155,8 @@ def videomd(b: dict) -> list[str]:
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)))
+ + "".join(f" | {k}~ {ex[k]}" if k == "guess" else f" | {k}: {ex[k]}" for k in ("seen", "before", "guess", "why") if ex.get(k))
+ + (" | to_confirm: " + "; ".join(ex["doubts"]) if ex.get("doubts") else ""))
return L
if mo.get("status") == "done":
return ["## " + T("特殊时刻", "Special moments"), "", T("- 看过了,没有找到特殊时刻", "- Looked: no special moments found")]
diff --git a/rea_video/packaging.py b/rea_video/packaging.py
index 6fbc75d..70d8e71 100644
--- a/rea_video/packaging.py
+++ b/rea_video/packaging.py
@@ -1641,8 +1641,8 @@ def to_ass(cues: list[dict], width: int, height: int) -> str:
elif ak == "fade" or (c.get("anim_out") or {}).get("kind") == "fade_out":
tags += "\\fad(200,200)"
# OCR text is literal: "{...}" would be read as override tags and "\\" as an escape
- text = c["text"].replace("\\", "\").replace("{", "{").replace("}", "}")
- text = "\\N".join(text) if vertical else text.replace("/", "\\N")
+ text = c["text"].replace("\r\n", "\n").replace("\r", "\n").replace("\\", "\").replace("{", "{").replace("}", "}")
+ text = "\\N".join(text.replace("\n", "")) if vertical else text.replace("\n", "\\N").replace("/", "\\N")
events.append(f"Dialogue: {0 if c['kind'] == 'subtitle' else 1},{_ts(c['t0'], '.')[1:-1]},{_ts(c['t1'], '.')[1:-1]},{name},,0,0,0,,{{{tags}}}{text}")
return "\n".join(head + list(styles.values()) + ["", "[Events]",
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"] + events) + "\n"
@@ -1892,6 +1892,8 @@ def finalize_pack(breakdown: dict, out: Path) -> dict | None:
if not pack:
return None
out = Path(out)
+ from .pipeline import shot_overlay_text
+
labels = {r["id"]: r["base"]["label"] for r in breakdown["shots"]}
for c in pack.get("text_cues", []):
mid = (c["t0"] + c["t1"]) / 2
@@ -1900,8 +1902,7 @@ def finalize_pack(breakdown: dict, out: Path) -> dict | None:
# on a rendered / recorded picture, words are the picture's content, not a separate overlay
c["part_of_picture"] = bool(r and labels[r["id"]] in ("code_render", "screen_capture") and c["kind"] not in ("subtitle",))
# an image reader listed this shot's post-production words: the rest is text filmed in the scene
- said = r and ((r.get("vlm") or {}).get("overlay_text") if isinstance((r.get("vlm") or {}).get("overlay_text"), list)
- else (r.get("review") or {}).get("overlay_text"))
+ said = shot_overlay_text(r) if r else None
if isinstance(said, list) and not any(_same_words(c["text"], o) for o in said): # [] = no post words in this shot
c["part_of_picture"] = True
src = breakdown.get("source") or {}
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index dbe64b4..3dd2a9f 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -20,7 +20,7 @@ from .plan import Planner
from .probe import provenance
from .motion import element_crops, motion_events, palette, strip_frames
from .shots import build_track, detect_shots
-from .util import LOG, fmt_time, round_floats, write_json, read_image
+from .util import LOG, fmt_time, read_image, read_json, round_floats, write_json
from . import aspects
from .faces import shot_faces
from .visual import LABEL_SHORT, shot_sheet, storyboard
@@ -63,7 +63,7 @@ def vlm_units(records: list[dict], max_calls: int) -> list[list[dict]]:
# modules that only run in finalize(): a change there needs no new decode. Everything else measures the video.
_FINALIZE_ONLY = {"classify.py", "report.py", "plan.py", "production.py", "entities.py", "narrative.py", "review.py", "cli.py",
- "evaluate.py", "remake.py", "memory.py", "i18n.py", "visual.py", "sound_source.py", "__init__.py"}
+ "evaluate.py", "remake.py", "memory.py", "i18n.py", "visual.py", "__init__.py"}
_DECODE_FP: str | None = None
@@ -145,10 +145,15 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
timeline = load_timeline(out, video, info)
vlm_client = None # one client for the survey and the shot pass: a model found down stays skipped
- if timeline is None and use_vlm and survey:
+ if (timeline is None or "keyframes" not in timeline) and use_vlm and survey:
+ from . import gemini
+
cfg = VLMConfig.from_env()
if cfg is not None:
vlm_client = VLMClient(cfg, out / "vlm_cache")
+ elif gemini.configured():
+ vlm_client = gemini.GeminiClient()
+ if vlm_client is not None:
try:
got = run_survey(video, out, track, shots, info, asker=vlm_asker(vlm_client, prompt_lang_note()), workers=workers)
LOG.info("survey: %s", {k: got.get(k) for k in ("status", "rounds", "shots", "keyframes")})
@@ -316,25 +321,42 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
stills_job.result()
decode_pool.shutdown()
+ # compute whole-video transcode context before selecting VLM units and formatting hints
+ vctx0 = video_context(shot_records, prov, info.fps)
+ for rec in shot_records:
+ probs0, ev0, facts0 = deterministic(rec["features"], rec.get("overlay"), rec.get("text"), rec.get("faces", 0.0),
+ audio, prov, fps=info.fps, ctx=vctx0)
+ rec["deterministic"] = {"probs": round_floats(probs0), "evidence": ev0, "facts": facts0}
+
# ---------------- VLM pass ------------------------------------------------------
# "used" means at least one VLM answer actually came back; "status" says why not otherwise.
vlm_info = {"used": False, "requested": use_vlm, "status": "off"}
whole = None
if use_vlm:
+ from . import gemini
+
cfg = VLMConfig.from_env()
- if cfg is None:
- LOG.warning("--vlm requested but no VLM config found (REA_VLM_* / VIDEO_ANALYSIS_* / GEMINI3_*); continuing without it")
+ if cfg is None and gemini.configured():
+ vlm_client = vlm_client or gemini.GeminiClient()
+ cfg_media, cfg_desc = "both", vlm_client.describe()
+ elif cfg is not None:
+ vlm_client = vlm_client or VLMClient(cfg, out / "vlm_cache")
+ cfg_media, cfg_desc = cfg.media, cfg.describe()
+ else:
+ cfg_media, cfg_desc = None, ""
+ if vlm_client is None:
+ LOG.warning("--vlm requested but no VLM config found (REA_VLM_* / VIDEO_ANALYSIS_* / GEMINI3_* / GEMINI_API_KEY); continuing without it")
vlm_info = {"used": False, "requested": True, "status": "not_configured", "error": "no_config"}
else:
- 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": []}
+ client = vlm_client
+ vlm_info = {"used": False, "requested": True, "status": "failed", "model": cfg_desc, "media": cfg_media, "errors": []}
def run_unit(unit: list[dict]) -> None:
"""One VLM call per unit: a single shot, or the jump-cut pieces of one take seen as one clip."""
first, last = unit[0], unit[-1]
span = last["end"] - first["start"]
media = []
- if cfg.media in ("both", "frames"):
+ if cfg_media in ("both", "frames"):
mid = unit[len(unit) // 2]
media += [(out / first["assets"]["first_frame"], "image/jpeg"), (out / mid["assets"]["sheet"], "image/jpeg"),
(out / last["assets"]["last_frame"], "image/jpeg")]
@@ -344,18 +366,18 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
if len(unit) > 1:
prompt += TAKE_NOTE.format(n=len(unit), cuts=", ".join(f"{r['start'] - first['start']:.2f}" for r in unit[1:]))
spoken = speaks_in(audio, first["start"], first["start"] + min(span, 12.0))
- if cfg.media in ("both", "video"):
+ if cfg_media in ("both", "video"):
prompt += SOUND_NOTE if spoken else SILENT_NOTE
prompt += prompt_lang_note()
fallback = None
try:
- if cfg.media in ("both", "video"): # a clip that fails to encode costs this unit its video, not the run
+ if cfg_media in ("both", "video"): # a clip that fails to encode costs this unit its video, not the run
clip = cut_clip(video, first["start"], min(span, 12.0), out / "clips" / f"{first['id']}.mp4", width=480, audio=spoken)
media.insert(0, (clip, "video/mp4"))
raw = client.ask_json(prompt, media)
except Exception as exc: # keep going; deterministic result stands
raw = None
- if spoken and cfg.media in ("both", "video"): # an endpoint that refuses a clip with sound still gets the picture
+ if spoken and cfg_media in ("both", "video"): # an endpoint that refuses a clip with sound still gets the picture
try:
clip = cut_clip(video, first["start"], min(span, 12.0), out / "clips" / f"{first['id']}_mute.mp4", width=480)
raw = client.ask_json(prompt.replace(SOUND_NOTE, SILENT_NOTE.replace("这一段没检测到人声,", "")),
@@ -363,7 +385,7 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
fallback = "mute_clip"
except Exception as exc2: # noqa: BLE001
exc = exc2
- if raw is None and cfg.media == "both":
+ if raw is None and cfg_media == "both":
try:
raw = client.ask_json(prompt, [m for m in media if m[1] != "video/mp4"])
fallback = "frames_only"
@@ -380,9 +402,12 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
if len(unit) > 1:
rec["vlm"]["take"] = {"shots": [r["index"] for r in unit], "piece": i + 1}
+ import contextvars
+
units = vlm_units(shot_records, max_shots_vlm)
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
- list(pool.map(run_unit, units))
+ for fut in [pool.submit(contextvars.copy_context().run, run_unit, u) for u in units]:
+ fut.result()
if whole_vlm:
try:
low = cut_clip(video, 0, info.duration, out / "clips" / "whole_480p.mp4", width=480, audio=True, crf=30)
@@ -499,8 +524,12 @@ def _moments(b: dict, out: Path, track, stem_info: dict, client) -> None:
try:
voc = Path(stem_info["vocals"]) if stem_info.get("ok") else None
+ fps = float(b["source"].get("fps") or (track.fps if track else 30.0))
+ skips = [(int(round(s["transition"]["start"] * fps)), int(round(s["transition"]["end"] * fps)))
+ for s in (b.get("shots") or [])[1:] if s.get("transition")]
b["moments"] = {"genre": mo.genre(b), "status": "pending",
- "hints": mo.hints((b.get("speech") or {}).get("lines") or [], voc, track, b["source"]["duration"])}
+ "hints": mo.hints((b.get("speech") or {}).get("lines") or [], voc, track, b["source"]["duration"]),
+ "measured": mo.measured(track, [s["start_frame"] for s in (b.get("shots") or [])[1:]], skip=skips)}
if client is not None:
from .vlm import prompt_lang_note
@@ -524,7 +553,9 @@ def _ai_or_live_doubt(label: str, facts: dict, prov: dict, vctx: dict, seen_live
native-30fps camera signature (live). Without them, cap the confidence and say why.
24fps-source pulldown alone is not decisive: AI video, stop motion and cinema cameras all produce it.
seen_live: how strongly the image readers (VLM / agent) think the shot was filmed."""
- if label not in ("ai_video", "live_action") or prov.get("aigc"):
+ aigc = prov.get("aigc")
+ has_aigc = (aigc.get("label") in ("1", "2", "3")) if isinstance(aigc, dict) else bool(aigc)
+ if label not in ("ai_video", "live_action") or has_aigc:
return None
hints = facts.get("film_hints") or []
if hints and not seen:
@@ -591,6 +622,20 @@ def _user_real(material: dict, real: bool) -> None:
material["user_corrected"] = True
+def shot_description(rec: dict) -> str:
+ """Description of a shot's picture: an agent review overrides the VLM when non-empty."""
+ return ((rec.get("review") or {}).get("description") or (rec.get("vlm") or {}).get("description") or "").strip()
+
+
+def shot_overlay_text(rec: dict) -> list[str] | None:
+ """Post-production overlay words listed by an image reader: agent review overrides VLM when given."""
+ rv = (rec.get("review") or {}).get("overlay_text")
+ if isinstance(rv, list):
+ return rv
+ vl = (rec.get("vlm") or {}).get("overlay_text")
+ return vl if isinstance(vl, list) else None
+
+
def visual_opinion(rec: dict) -> dict | None:
"""What a model saw in the shot: the VLM answer, an agent's review (rea-video apply-review), or both averaged;
with neither, the survey's look at the whole video (how this stretch was made, from the overview)."""
@@ -601,7 +646,17 @@ def visual_opinion(rec: dict) -> dict | None:
return v or a
merged = dict(v)
merged["label_probs"] = {k: (v["label_probs"].get(k, 0.0) + a["label_probs"].get(k, 0.0)) / 2 for k in LABEL_ZH}
- merged["embedded_assets"] = (v.get("embedded_assets") or []) + (a.get("embedded_assets") or [])
+ if a.get("image_source") and a["image_source"] != "unknown":
+ merged["image_source"] = a["image_source"]
+ if a.get("generator_guess"):
+ merged["generator_guess"] = a["generator_guess"]
+ if a.get("description"):
+ merged["description"] = a["description"]
+ seen_assets = list(v.get("embedded_assets") or [])
+ for e in a.get("embedded_assets") or []:
+ if not any(x.get("kind") == e.get("kind") and x.get("description") == e.get("description") for x in seen_assets):
+ seen_assets.append(e)
+ merged["embedded_assets"] = seen_assets
return merged
@@ -639,7 +694,7 @@ def _label_at(shots: list[dict], t: float) -> str | None:
return (r.get("base") or {}).get("label") if r else None
-def _vlm_gate(rec: dict, vprobs: dict | None, vctx: dict) -> dict | None:
+def _vlm_gate(rec: dict, vprobs: dict | None, vctx: dict, prov: dict | None = None) -> dict | None:
"""When only one image reader answered (the VLM, or an agent review, not both), let it decide only where
image readers have proved reliable. Measured on eval/articles + holdout + holdout2: they fix 3D vs
code-render vs screen-capture confusions, but on the AI / live-action / avatar axis they are confidently
@@ -659,7 +714,7 @@ def _vlm_gate(rec: dict, vprobs: dict | None, vctx: dict) -> dict | None:
rendered_top = d not in AI_LIVE_AXIS or ranked[1][0] not in AI_LIVE_AXIS
person = (v in AI_LIVE_AXIS and rendered_top
and bool(facts.get("big_face") or facts.get("lowlight") or facts.get("face_area", 0) >= RULES["big_face"]["area"]))
- if v in UNMEASURED: # 2D animation / stop motion: the tools cannot score them, so they cannot back them either
+ if v in UNMEASURED and ((prov or {}).get("aigc") or {}).get("label") != "1": # 2D animation / stop motion: the tools cannot score them, unless an explicit AIGC=1 label rules out film footage
return vprobs
# the survey's closer look is the only reader, and it saw this shot among its neighbours (a sheet's usual look,
# shots that differ marked): where the tools hold no hard evidence (no repeated frames; not sure either, as an
@@ -745,10 +800,11 @@ def _agent_review_dispute(dt: str, vt: dict | None, rv: dict | None, reviewed: b
Mirrors the VLM disputed flag above."""
if decided == "user" or vt or not rv or sum(rv.values()) == 0 or reviewed:
return None
- if (group_of(_top_group_label(rv)) == "live_action") != (group_of(dt) == "live_action"):
+ rg = _top_group_label(rv)
+ if (rg in AI_LIVE_AXIS or dt in AI_LIVE_AXIS) and group_of(rg) != group_of(dt):
return T("工具判{d}、看图复核判{r},融合规则在 AI/实拍轴上跟了工具(评测校准):请对照截图核实复核证据是否真的看得见",
"Tools say {d}, the image review says {r}; on the AI / live-action axis the fusion follows the tools (eval-calibrated): check the frames to see whether the review's evidence is really visible",
- d=LABEL_ZH[dt], r=LABEL_ZH[_top_group_label(rv)])
+ d=LABEL_ZH[dt], r=LABEL_ZH[rg])
return None
@@ -806,7 +862,7 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:
for rec in shot_records:
fam = rec["deterministic"]["facts"].get("temporal_family", "dynamic")
seen = visual_opinion(rec) or {}
- vprobs = _vlm_gate(rec, seen.get("label_probs"), vctx)
+ vprobs = _vlm_gate(rec, seen.get("label_probs"), vctx, prov=prov)
probs = fuse(rec["deterministic"]["probs"], vprobs, fam, majority=_majority(rec))
# group-first decision only when an image reader voted: the tools' avatar score is a slice of their AI score,
# so adding the two would outvote live action on tool-only runs (eval/koubo night street 0.51 -> 0.33)
@@ -873,8 +929,7 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:
if doubt:
rec["base"]["confidence"] = round(min(conf, DOUBT_CAP), 3)
rec["base"]["uncertain"] = doubt
- said = (rec.get("vlm") or {}).get("overlay_text")
- said = said if isinstance(said, list) else (rec.get("review") or {}).get("overlay_text")
+ said = shot_overlay_text(rec)
rec["layers"], scene_text = drop_scene_text(rec["layers"], label, said)
if scene_text:
rec["base"]["scene_text"] = scene_text # read by OCR but printed on things in the scene, not overlays
@@ -990,6 +1045,13 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:
refs.setdefault(k, []).append(r["index"])
if refs:
verdict += semi() + T("复刻需准备参考:", "references to prepare for the remake: ") + join(T("{k}({n} 镜)", "{k} ({n} shots)", k=k, n=len(v)) for k, v in sorted(refs.items(), key=lambda kv: -len(kv[1])))
+ st_lv = ((breakdown.get("stems") or {}).get("level_db") or {})
+ mus = audio.get("music") or {}
+ if mus.get("present") and st_lv.get("music") is not None and st_lv["music"] <= MUSIC_STEM_SILENT_DB:
+ # the separated accompaniment is near silent: the "beat" was measured on voice and room sound in the mix
+ audio["music"] = {**mus, "present": False, "dropped_by_stems": st_lv["music"]}
+ audio["music_likely"] = False
+ audio["beat_synced_edit"] = False
if audio.get("beat_synced_edit"):
verdict += semi() + T("剪辑卡在音乐节拍上", "cuts land on the music beat")
summary = {
@@ -1042,12 +1104,6 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:
if rec["index"] in told:
rec["narrative"] = told[rec["index"]]
breakdown["narrative"] = narrative.beats(breakdown)
-
- st_lv = ((breakdown.get("stems") or {}).get("level_db") or {})
- mus = audio.get("music") or {}
- if mus.get("present") and st_lv.get("music") is not None and st_lv["music"] <= MUSIC_STEM_SILENT_DB:
- # the separated accompaniment is near silent: the "beat" was measured on voice and room sound in the mix
- audio["music"] = {**mus, "present": False, "dropped_by_stems": st_lv["music"]}
fx = Path(out) / "stems" / "effects.wav"
if fx.is_file(): # effects found on their own separated track replace the onsets picked off the mix
from .effects import detect as detect_effects
@@ -1167,13 +1223,25 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:
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)
+ code_idx = sorted(r["index"] for r in shot_records if r["base"]["label"] == "code_render")
+ src_path = (breakdown.get("source") or {}).get("path", "")
+ if code_idx and src_path and Path(src_path).is_file():
+ from .layers import scene_frames
+
+ sc_file = out / "frames" / "scenes.json"
+ have_idx = sorted({sc.get("shot") for sc in read_json(sc_file).get("scenes", [])}) if sc_file.is_file() else None
+ if have_idx != code_idx:
+ try:
+ sc = scene_frames(out, breakdown=breakdown)
+ breakdown["layer_scenes"] = {"file": "frames/scenes.json", "count": len(sc["scenes"])}
+ except Exception as exc: # noqa: BLE001
+ LOG.warning("scene frames skipped (%s: %s)", type(exc).__name__, exc)
from .report import write_reports
-
from .stems import cut_sfx
plan_a = breakdown.get("audio_plan") or {}
- cut_sfx(breakdown["source"].get("path", ""), plan_a.get("sfx_merged", []), out,
- groups=[g for g in plan_a.get("sfx_groups") or [] if not g.get("in_scene")] if plan_a.get("sfx_groups") else None)
+ cut_sfx(src_path, plan_a.get("sfx_merged", []), out,
+ groups=[g for g in plan_a["sfx_groups"] if not g.get("in_scene")] if "sfx_groups" in plan_a else None)
+ write_json(out / "breakdown.json", breakdown, compact=True)
write_reports(breakdown, out)
return breakdown
diff --git a/rea_video/probe.py b/rea_video/probe.py
index 19f80d8..b565d66 100644
--- a/rea_video/probe.py
+++ b/rea_video/probe.py
@@ -146,15 +146,19 @@ def provenance(info: VideoInfo) -> dict:
short = key.split(".", 1)[-1]
if short in CAMERA_KEYS:
hints["camera"].append(f"{short}={value}")
- if any(a in short for a in AIGC_KEYS) or re.search(r"\baigc\b", value, re.I):
- aigc = parse_aigc(value) or {"label": "", "meaning": T("无法解析", "could not be parsed"), "raw": value[:200]}
- strong = aigc.get("label") in ("1", "2", "3")
+ is_aigc_key = any(a in short for a in AIGC_KEYS)
+ parsed = parse_aigc(value) if (is_aigc_key or (short not in FREE_TEXT_KEYS and re.search(r"\baigc\b", value, re.I))) else None
+ if parsed or is_aigc_key:
+ cand = parsed or {"label": "", "meaning": T("无法解析", "could not be parsed"), "raw": value[:200]}
+ strong = cand.get("label") in ("1", "2", "3")
+ if aigc is None or strong or not aigc.get("label"):
+ aigc = cand
evidence.append({"kind": "aigc_label", "detail": T("AIGC 隐式标识 Label={l}({m}),生成服务方编码 {p}",
"Implicit AIGC label Label={l} ({m}), content producer code {p}",
- l=aigc.get('label'), m=aigc.get('meaning'), p=aigc.get('content_producer') or '—'),
+ l=cand.get('label'), m=cand.get('meaning'), p=cand.get('content_producer') or '—'),
"weight": "strong" if strong else "weak"})
- if aigc.get("label") == "1":
- hints["generator"].append(T("AIGC 标识({m})", "AIGC label ({m})", m=aigc.get('meaning')))
+ if cand.get("label") == "1":
+ hints["generator"].append(T("AIGC 标识({m})", "AIGC label ({m})", m=cand.get('meaning')))
# tags a tool writes about itself (encoder, handler, software ...) versus text a person typed (title,
# description, comment ...): a generator named in typed text is what the video is about, not how it was made
diff --git a/rea_video/production.py b/rea_video/production.py
index 281f9e1..05ac5f8 100644
--- a/rea_video/production.py
+++ b/rea_video/production.py
@@ -288,8 +288,10 @@ def _setups(shots: list[dict], sig: dict, thr: float, b: dict) -> list[dict]:
cam = (a.get("camera") or {}).get("result") or {}
support = SUPPORT_ZH.get(cam.get("support"), cam.get("support_zh") or "—")
groups.setdefault((size, support), []).append(r)
+ from .pipeline import shot_description
+
light = (((sc[0].get("aspects") or {}).get("lighting") or {}).get("result") or {})
- desc = (sc[0].get("vlm") or sc[0].get("review") or {}).get("description", "")
+ desc = shot_description(sc[0])
if named:
nm = named[si - 1]
desc = T(",", ", ").join(str(x) for x in (nm.get("where"), nm.get("look")) if x) or desc
diff --git a/rea_video/report.py b/rea_video/report.py
index 4e5e03f..9914983 100644
--- a/rea_video/report.py
+++ b/rea_video/report.py
@@ -949,12 +949,14 @@ def _clock(t: float) -> str:
def _shotlist_md(b: dict) -> list[str]:
+ from .pipeline import shot_description
+
told = narrative.shot_roles(b)
mixed = len({r["base"]["label"] for r in b["shots"]}) > 1 # one kind throughout is already said at the top
rows = []
for r in b["shots"]:
base = r["base"]
- desc = ((r.get("vlm") or r.get("review") or {}).get("description") or "").replace("\n", " ")
+ desc = shot_description(r).replace("\n", " ")
n = told.get(r["index"]) or {}
says = (n.get("role_zh") or "") + (_colon() if n.get("role_zh") and n.get("point") else "") + (n.get("point") or "")
a = r.get("assets") or {}
@@ -975,14 +977,16 @@ def _questions_md(b: dict) -> list[str]:
def _shot_detail_md(r: dict) -> list[str]:
+ from .pipeline import shot_description, shot_overlay_text
+
base = r["base"]
seen, measured = list(base.get("seen") or []), list(base.get("measured") or [])
L = [f"![{r['id']}]({r['assets']['sheet']})", ""]
# what you can check against the frames
L.append(T("**画面里看得到的**(可以对照截图核实)", "**Visible on screen** (check against the frames)"))
- v = r.get("vlm") or r.get("review") or {}
- if v.get("description"):
- L.append(T("- 画面:{d}", "- Picture: {d}", d=v["description"]))
+ desc = shot_description(r)
+ if desc:
+ L.append(T("- 画面:{d}", "- Picture: {d}", d=desc))
act = performance.of(r)
if act:
L.append(T("- 表演:{a}", "- Acting: {a}", a=performance.summary(act))
@@ -993,8 +997,7 @@ def _shot_detail_md(r: dict) -> list[str]:
if base.get("scene_text"):
L.append(T("- 画面里物体上的字(不是后期字幕):", "- Text on objects in the scene (not subtitles): ") + join(base["scene_text"][:6]))
intrinsic = base["label"] in ("code_render", "screen_capture")
- said = (r.get("vlm") or {}).get("overlay_text")
- said = said if isinstance(said, list) else (r.get("review") or {}).get("overlay_text")
+ said = shot_overlay_text(r)
from .classify import _same_words
for tr in r.get("text", {}).get("tracks", [])[:4]:
@@ -1058,7 +1061,19 @@ def _appendix_md(b: dict) -> list[str]:
return L
-def markdown(b: dict, credit: bool = True) -> str:
+def _expand_md_marks(lines: list[str], b: dict) -> list[str]:
+ out = []
+ for ln in lines:
+ if ln == _MIX_MARK:
+ continue
+ if ln == _STEMS_MARK:
+ out.extend(f"- {name}{_colon()}[stems/{f}](stems/{f})" for f, name in _stem_tracks(b))
+ else:
+ out.append(ln)
+ return out
+
+
+def markdown(b: dict, credit: bool = True, html_marks: bool = False) -> str:
# what it is and why it works, how it is told and cut, how to remake it, then the reference detail
# 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 report
@@ -1068,6 +1083,8 @@ def markdown(b: dict, credit: bool = True) -> str:
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))
+ if not html_marks:
+ L = _expand_md_marks(L, b)
if credit:
L += ["", "---", "", T("由 [REA-VIDEO]({u}) 生成 · {u}", "Made with [REA-VIDEO]({u}) · {u}", u=PROJECT_URL)]
text = re.sub(r"\[[\w.-]*agent 看图\]", "[AI 看图]", "\n".join(L)) # who reviewed it is in breakdown.json
@@ -1359,7 +1376,7 @@ details{padding:0;border:0} summary{color:var(--fg)} a{color:inherit}}
def html_report(b: dict) -> str:
- body = _md_to_html(markdown(b, credit=False).split("\n"), b)
+ body = _md_to_html(markdown(b, credit=False, html_marks=True).split("\n"), b)
tagline = T("视频逆向拆解报告", "Video breakdown report")
return (f"<!doctype html><html lang=\"{lang()}\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"
f"<meta name=\"generator\" content=\"REA-VIDEO\"><title>{T('拆解:', 'Breakdown: ')}{html.escape(b['source']['filename'])} · REA-VIDEO</title><style>{_CSS}</style></head><body>"
diff --git a/rea_video/reveal.py b/rea_video/reveal.py
index 0033edb..07ecba5 100644
--- a/rea_video/reveal.py
+++ b/rea_video/reveal.py
@@ -307,7 +307,8 @@ def reveal_clip(video: str, has_audio: bool, size: tuple[int, int], dur: float,
# 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")))
+ hold_lines = [key["text"], *([guess] if guess else [])]
+ card = _card(T / "c.png", W, H, labels["hold"].format(t=kt), hold_lines, 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")
diff --git a/rea_video/review.py b/rea_video/review.py
index d171eb1..489904c 100644
--- a/rea_video/review.py
+++ b/rea_video/review.py
@@ -207,9 +207,12 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
"shots": shots}
if pk_tasks:
tasks["packaging"] = pk_tasks
+ rec_by_id = {r["id"]: r for r in breakdown["shots"]}
answers = {"by": "", "shots": [{"id": s["id"], "time": f"{s['start']:.2f}-{s['end']:.2f}",
"label_probs": {}, "image_source": "unknown",
- "evidence": [], "description": "", "narrative": {"role": "", "point": ""}, "embedded_assets": [], "ai_edits": [], "same_clip_as": None,
+ "evidence": [], "description": "", "narrative": {"role": "", "point": ""}, "embedded_assets": [],
+ "ai_edits": list(((rec_by_id.get(s["id"], {}).get("vlm") or {}).get("ai_edits")) or []),
+ "same_clip_as": None,
"replication": {"image_prompt": "", "video_prompt": "", "video_prompt_en": ""},
**({"aspects": aspects.review_template()} if shoot[s["id"]] else {}),
**({"performance": dict(PERF_TEMPLATE)} if acting[s["id"]] else {})} for s in shots],
@@ -274,12 +277,15 @@ def _clean(ans: dict) -> tuple[dict | None, str | None]:
ev = [ev] if ev.strip() else []
elif not isinstance(ev, list):
ev = []
+ raw_same = str(ans.get("same_clip_as") or "").strip()
+ m_same = re.fullmatch(r"(?:shot_)?0*(\d+)", raw_same, re.I)
+ same_clip = int(m_same.group(1)) if m_same and int(m_same.group(1)) > 0 else None
return {"label_probs": soft, "raw_probs": {k: round(v / total, 3) for k, v in vals.items()}, "image_source": src,
"evidence": [str(x) for x in ev][:8], "description": str(ans.get("description", "")),
"embedded_assets": assets, "replication": rep, "aspects": aspects.clean_answers(ans.get("aspects")),
"split_suggestion": split, "narrative": narrative.clean(ans.get("narrative")),
"performance": performance.clean(ans.get("performance")),
- "same_clip_as": int(ans["same_clip_as"]) if str(ans.get("same_clip_as", "")).strip().isdigit() else None,
+ "same_clip_as": same_clip,
# the words added in post (subtitles, styled text, labels), like the VLM's overlay_text: OCR text in the
# shot that matches none of them is part of the picture (a filmed phone screen, a gift box)
"overlay_text": [str(x) for x in ans["overlay_text"] if str(x).strip()] if isinstance(ans.get("overlay_text"), list) else None,
diff --git a/rea_video/shots.py b/rea_video/shots.py
index 3a55194..3dd2263 100644
--- a/rea_video/shots.py
+++ b/rea_video/shots.py
@@ -18,6 +18,12 @@ THUMB_W = 96
# sides, frames on each side that must stay quiet, and how little the picture may drift back (see _returns)
JUMP_MIN_CHANGED, JUMP_RATIO, JUMP_QUIET, JUMP_MIN_RETURN = 0.17, 2.5, 2, 0.7
SHORT_SHOT_S = 0.12 # shortest shot kept between two clean hard cuts (4 frames at 30 fps)
+# jump cuts in low-frame-rate footage (GIFs, frame-dropped reposts): every frame already moves a lot, so a cut does not
+# stand out from its neighbours. What still tells them apart: parts of the picture that were at rest (a bowl, a shoulder)
+# all jump in the same frame, spread over the picture. Measured on labelled footage, this only pays off at low fps.
+LOCKED_MAX_FPS, LOCKED_GRID = 18.0, (10, 14)
+LOCKED_REST, LOCKED_JUMP = 3.0, 10.0 # grey levels: a block "at rest" around the frame, a block that jumps in it
+LOCKED_MIN_REST, LOCKED_BREAK, LOCKED_ROWS, LOCKED_COLS = 0.4, 0.2, 0.45, 0.4
@dataclass
@@ -150,6 +156,7 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo
# (a title popping in over a static layout changes only a region -> not a cut)
chg = track.changed
chg_base = _local_median(chg, radius)
+ rest_breaks = _rest_breaks(track, radius) if fps <= LOCKED_MAX_FPS else None
for i in range(1, n):
s = score[i]
strong = s > cut_threshold and s > base[i] * 2.5 + 0.06 and chg[i] > 0.25
@@ -159,7 +166,7 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo
# frames; a filmed screen whose content changes keeps sensor noise, 0.002-0.03, and is not a cut)
still_swap = (s > cut_threshold and track.hist_dist[i] > 0.25 and chg[i] > 0.18 and chg_base[i] < 0.01
and s > base[i] * 5 + 0.1 and i >= 3 and float(track.pix_diff[i - 3:i].max()) < 1e-3)
- jump = _jump_cut(track, i)
+ jump = _jump_cut(track, i) or (rest_breaks is not None and _locked_jump(track, rest_breaks, i))
if strong or relative or still_swap or jump:
# a muzzle flash / strobe, or the frame where a one- or two-frame flash or glitch ends: the picture
# is back to what it was, so nothing was cut
@@ -344,6 +351,40 @@ def _jump_cut(track: FrameTrack, i: int) -> bool:
return _returns(track.thumbs, i) >= JUMP_MIN_RETURN
+def _rest_breaks(track: FrameTrack, radius: int) -> np.ndarray:
+ """Per frame: (share of the blocks at rest around it that jump in it, share of blocks at rest, rows hit, columns hit)."""
+ n = track.n
+ if n == 0 or not track.thumbs:
+ return np.zeros((n, 4))
+ h, w = track.thumbs[0].shape[:2]
+ grid = LOCKED_GRID if h >= w else LOCKED_GRID[::-1]
+ B = np.stack([cv2.resize(t, grid, interpolation=cv2.INTER_AREA) for t in track.thumbs]).astype(np.float32)
+ D = np.zeros_like(B)
+ D[1:] = np.abs(B[1:] - B[:-1])
+ out = np.zeros((n, 4))
+ for i in range(1, n):
+ around = [j for j in range(max(1, i - radius), min(n, i + radius + 1)) if j != i]
+ if len(around) < 3:
+ continue
+ rest = np.median(D[around], axis=0) < LOCKED_REST
+ hit = (D[i] > LOCKED_JUMP) & rest
+ if hit.any():
+ out[i] = hit.sum() / rest.sum(), rest.mean(), hit.any(axis=1).mean(), hit.any(axis=0).mean()
+ return out
+
+
+def _locked_jump(track: FrameTrack, breaks: np.ndarray, i: int) -> bool:
+ """A cut inside one take at low fps: resting parts all over the picture jump in this one frame and nowhere near it."""
+ if i < 4 or i + 3 >= track.n or track.changed[i] < JUMP_MIN_CHANGED:
+ return False
+ share, rest, rows, cols = breaks[i]
+ if share < LOCKED_BREAK or rest < LOCKED_MIN_REST or rows < LOCKED_ROWS or cols < LOCKED_COLS:
+ return False
+ near_rows = np.concatenate([breaks[max(0, i - 2):i], breaks[i + 1:i + 3]], axis=0)
+ near = near_rows[near_rows[:, 1] >= LOCKED_MIN_REST, 0]
+ return float(near.max(initial=0.0)) <= 0.5 * share and _returns(track.thumbs, i) >= JUMP_MIN_RETURN
+
+
def _flash(luma: np.ndarray, start: int, end: int, fps: float) -> float:
"""A cut that opens on a bright flash decaying into the new shot (a common motion-graphics transition):
seconds until the brightness settles, or 0."""
diff --git a/rea_video/stems.py b/rea_video/stems.py
index 77a9f40..7ee82c7 100644
--- a/rea_video/stems.py
+++ b/rea_video/stems.py
@@ -66,13 +66,16 @@ def ensure_model(force: bool = False) -> Path:
def _session():
import onnxruntime as ort
+ so = ort.SessionOptions()
+ so.intra_op_num_threads = MODEL_THREADS
+ so.inter_op_num_threads = 1
try:
- return ort.InferenceSession(str(ensure_model()), providers=["CPUExecutionProvider"])
+ return ort.InferenceSession(str(ensure_model()), sess_options=so, providers=["CPUExecutionProvider"])
except Exception as e: # corrupted cache (e.g. an older interrupted download): fetch again once
if "protobuf" not in str(e).lower() and "load model" not in str(e).lower():
raise
LOG.warning("cached stem model is unreadable (%s); downloading again", str(e)[:120])
- return ort.InferenceSession(str(ensure_model(force=True)), providers=["CPUExecutionProvider"])
+ return ort.InferenceSession(str(ensure_model(force=True)), sess_options=so, providers=["CPUExecutionProvider"])
def load_stereo(path: str | Path) -> np.ndarray | None:
@@ -167,18 +170,21 @@ def _without_effect_hits(inst: np.ndarray, effects_wav: str | Path) -> np.ndarra
from .effects import detect
hits = detect(effects_wav)
- r = subprocess.run(["ffmpeg", "-v", "error", "-i", str(effects_wav), "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"], capture_output=True)
+ r = subprocess.run(["ffmpeg", "-v", "error", "-i", str(effects_wav), "-ac", "2", "-ar", str(SR), "-f", "f32le", "-"], capture_output=True)
if not hits or r.returncode != 0 or not r.stdout:
return inst
- fx = np.frombuffer(r.stdout, np.float32)
+ fx = np.frombuffer(r.stdout, np.float32).reshape(-1, 2).T
n = inst.shape[1]
- fx = np.pad(fx, (0, max(0, n - len(fx))))[:n]
+ if fx.shape[1] < n:
+ fx = np.pad(fx, ((0, 0), (0, n - fx.shape[1])))
+ fx = fx[:, :n]
gate = np.zeros(n, np.float32)
for e in hits:
gate[max(0, int((e["t"] - 0.03) * SR)):min(n, int((e["t"] + e["dur"] + 0.08) * SR))] = 1
w = np.hanning(441)
gate = np.convolve(gate, w / w.sum(), "same").astype(np.float32) # 10 ms edges, no clicks
- return inst - gate * fx
+ sub = np.clip(gate * fx, -np.abs(inst), np.abs(inst))
+ return np.where(np.abs(inst) > 1e-4, inst - sub, inst)
SFX_DIR = "sfx"
@@ -199,9 +205,11 @@ def cut_sfx(src: str | Path, sfx: list[dict], out_dir: str | Path, limit: int =
src = fx
if not sfx or not Path(src).is_file():
return 0
+ picks = [(k, sfx[g["rep"]]) for k, g in enumerate(groups, 1)] if groups is not None else list(enumerate(sfx[:limit], 1))
+ if not picks:
+ return 0
d.mkdir(parents=True, exist_ok=True)
n = 0
- picks = [(k, sfx[g["rep"]]) for k, g in enumerate(groups, 1)] if groups else list(enumerate(sfx[:limit], 1))
for i, e in picks[:limit]:
t = float(e.get("t", 0.0))
a = max(0.0, t - 0.12) # a little lead-in so the attack is heard
diff --git a/rea_video/survey.py b/rea_video/survey.py
index ea1d279..f6d18ad 100644
--- a/rea_video/survey.py
+++ b/rea_video/survey.py
@@ -242,9 +242,10 @@ def _grab(video: str, info: VideoInfo, times: list[float], width: int = 160, fil
order = sorted(range(len(times)), key=lambda k: times[k])
sorted_t = [times[k] for k in order]
t0, t1 = sorted_t[0], sorted_t[-1]
- step = 1.0 / max(info.fps, 1)
+ rate = min(max(info.fps, 1.0), 60.0)
+ step = 1.0 / rate
best: dict[int, tuple[float, np.ndarray]] = {}
- for i, f in enumerate(iter_frames(video, info, width, start=t0, duration=t1 - t0 + 2 * step)):
+ for i, f in enumerate(iter_frames(video, info, width, start=t0, duration=t1 - t0 + 2 * step, fps=rate)):
ft = t0 + i * step
lo, hi = bisect.bisect_left(sorted_t, ft - step), bisect.bisect_right(sorted_t, ft + step)
for j in range(lo, hi):
@@ -263,7 +264,9 @@ def _grab(video: str, info: VideoInfo, times: list[float], width: int = 160, fil
def tile_size(info: VideoInfo, look: str) -> tuple[int, int]:
"""Tile width and height for a look (TILE_AREA), in the video's shape."""
- aspect = info.width / info.height if info.width and info.height else 16 / 9
+ rot = getattr(info, "rotation", 0) in (90, 270)
+ dw, dh = (info.height, info.width) if rot else (info.width, info.height)
+ aspect = dw / dh if dw and dh else 16 / 9
w = max(40, int(round(math.sqrt(TILE_AREA[look] * aspect))))
return w, max(24, int(round(w / aspect)))
@@ -275,6 +278,8 @@ def _cols(tile_w: int, n: int) -> int:
def _grid(frames: list[np.ndarray], labels: list[str], bars: list[float], cuts: list[bool], cols: int,
tile_w: int) -> Image.Image:
"""Tiles in rows; under each tile a bar for the change in the gap after it; a red edge for detector cuts."""
+ if not frames:
+ return Image.new("RGB", (max(1, tile_w), 32), (24, 24, 24))
font = _font(15 if tile_w >= 200 else (13 if tile_w >= 110 else 11))
cells = []
for f, lab, bar, cut in zip(frames, labels, bars, cuts):
@@ -800,13 +805,16 @@ def run(video: str | Path, out: Path, track: FrameTrack, shots: list[Shot], info
if asker is None:
return
+ import contextvars
+
def one(t: dict) -> None:
_, ap = _task_paths(sdir, t["id"])
if reader(ap) is None:
got = asker(_public(t), [Path(out) / im for im in t["images"]])
write_json(ap, {"filled": True, "by": "vlm", **(got or {})})
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
- list(pool.map(one, tasks))
+ for fut in [pool.submit(contextvars.copy_context().run, one, t) for t in tasks]:
+ fut.result()
def waiting(tasks: list[dict], reader, stage: str, rnd: int) -> dict | None:
left = [t for t in tasks if reader(_task_paths(sdir, t["id"])[1]) is None]
diff --git a/rea_video/util.py b/rea_video/util.py
index 322c393..f048345 100644
--- a/rea_video/util.py
+++ b/rea_video/util.py
@@ -95,7 +95,7 @@ def _portable_breakdown(data: Any, root: Path) -> Any:
return data
src = dict(data["source"])
path = str(src.get("path") or "")
- if path and (Path(path).is_absolute() or Path(path).is_file()):
+ if path and Path(path).is_file():
_remember_source(src, str(Path(path).resolve()))
if path:
src["path"] = src.get("filename") or Path(path).name
diff --git a/rea_video/videomd.py b/rea_video/videomd.py
index 4f01712..0cfa13a 100644
--- a/rea_video/videomd.py
+++ b/rea_video/videomd.py
@@ -67,17 +67,19 @@ def _sized(meta: dict, body: str) -> str:
_RE_DETAILS = re.compile(r'^<details(?: class="ref")?><summary>(.*)</summary>$')
+_RE_INLINE_IMG = re.compile(r"!\[[^\]]*\]\(([^)\s]+)\)")
def _plain(lines: list[str]) -> str:
"""A report section without the HTML folds: a model reads the whole file it opened."""
out = []
for ln in lines:
- m = _RE_DETAILS.match(ln.strip())
+ s = ln.strip()
+ m = _RE_DETAILS.match(s)
if m:
out.append(f"**{html.unescape(m.group(1))}**")
- elif ln.strip() != "</details>" and not ln.startswith("!["): # images: paths live in front matter (`frames`) or the map
- out.append(ln)
+ elif s != "</details>" and not ln.startswith("![") and not (s.startswith("<!--") and s.endswith("-->")):
+ out.append(_RE_INLINE_IMG.sub(r"`\1`", ln))
return re.sub(r"\n{3,}", "\n\n", "\n".join(out)).strip()
@@ -108,6 +110,7 @@ def _transition_in(r: dict) -> dict:
def timeline_line(r: dict, roles: dict, units: dict) -> str:
+ from .pipeline import shot_description
from .report import CAMERA_ZH, _layers, _origin, _route
base = r["base"]
@@ -115,7 +118,7 @@ def timeline_line(r: dict, roles: dict, units: dict) -> str:
n = roles.get(r["index"]) or {}
if n.get("role_zh") or n.get("point"):
f["story"] = _one_line(join(x for x in (n.get("role_zh"), n.get("point")) if x), 48)
- desc = (r.get("vlm") or r.get("review") or {}).get("description")
+ desc = shot_description(r)
if desc:
f["seen"] = _one_line(desc, 60)
act = performance.of(r)
@@ -221,13 +224,13 @@ def _shot_file(r: dict, *, scene: int | None = None, stickers: list[dict] | None
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_md
- from .report import _audio_md, _cast_md, _content_md, _remake_md, _visual_md, packaging_md
+ from .report import _audio_md, _cast_md, _content_md, _expand_md_marks, _remake_md, _visual_md, packaging_md
return [
("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)),
+ ("sound", T("声音", "Sound"), T("人声、BGM、音效、节拍和来源", "voice, music, sound effects, beats and sources"), _expand_md_marks(_audio_md(b), b)),
("rhythm", T("节奏与关键帧", "Rhythm and key frames"), T("切点和转场的时间、镜头长度、画面变化曲线、每镜关键帧", "when cuts and transitions happen, shot lengths, the change curve, key frames of each shot"), rhythm_md(b)),
("look", T("拍法、打光与剪辑", "Camera, lighting and editing"), T("有实拍镜头时:景别、机位、布光、器材", "for filmed shots: framing, camera, lighting, kit"), _visual_md(b)),
("packaging", T("剪辑包装", "Packaging"), T("字幕、花字、贴纸、画中画的时间和样式", "subtitles, styled text, stickers, picture-in-picture: timing and style"), packaging_md(b)),
@@ -344,13 +347,15 @@ def _description(b: dict) -> str:
def _about(b: dict) -> str:
"""What the video shows or says, from the best source this run has: the whole-video read, the story beats, what
the shots show, the opening lines, the file's title. Empty only when none of them says anything."""
- whole = _one_line((b.get("whole_video_vlm") or {}).get("summary"), 600)
+ from .pipeline import shot_description
+
+ whole = _one_line((b.get("review_story") or {}).get("summary") or (b.get("whole_video_vlm") or {}).get("summary"), 600)
if whole:
return whole
- points = [p for st in narrative.beats(b) for p in st.get("points") or []][:3]
+ points = list(dict.fromkeys(p for st in narrative.beats(b) for p in st.get("points") or [] if p))[:3]
if points:
return _one_line(T(";", "; ").join(points), 600)
- seen = [d for d in ((r.get("vlm") or r.get("review") or {}).get("description") for r in b.get("shots", [])) if d][:2]
+ seen = [d for d in (shot_description(r) for r in b.get("shots", [])) if d][:2]
if seen:
return _one_line(T(";", "; ").join(seen), 400)
said = [str(ln.get("text") or "").strip() for ln in ((b.get("speech") or {}).get("lines") or [])[:3]]
@@ -454,9 +459,10 @@ def _next_steps(b: dict) -> list[str]:
def _overview(b: dict, files: list[tuple[str, str, str, int]]) -> str:
s = b["summary"]
w = b.get("whole_video_vlm") or {}
+ story_sum = (b.get("review_story") or {}).get("summary") or w.get("summary")
L = [f"# {b['source']['filename']}", "", T("**结论**(推断):{v}", "**Verdict** (inferred): {v}", v=s["verdict"])]
- if w.get("summary"):
- L.append(T("**讲什么**:{s}", "**What it says**: {s}", s=_one_line(w["summary"], 200)))
+ if story_sum:
+ L.append(T("**讲什么**:{s}", "**What it says**: {s}", s=_one_line(story_sum, 200)))
steps = narrative.beats(b)
if steps:
L.append(T("**叙事线**:", "**Narrative**: ") + " → ".join(
@@ -539,6 +545,7 @@ def write(b: dict, out: Path) -> Path:
("stems/", T("人声、配乐、音效分轨", "voice, music and effects stems"), T("听声音、复刻配音配乐", "listening, remaking the sound")),
("sfx/", T("每处音效的试听片段", "a clip of each sound effect"), T("找同款音效", "finding matching effects")),
("packaging/", T("字幕文件、包装时间轴、贴纸截图", "subtitle files, packaging timeline, sticker frames"), T("复刻字幕和包装", "remaking subtitles and packaging")),
+ ("moments/", T("特殊时刻的关键帧、揭秘图和慢放短片", "key frames, step diagrams and slow-motion clips of special moments"), T("看魔术揭秘和关键瞬间", "checking reveals and key moments")),
("frames/", T("画面场景:每场景原尺寸帧、画上去那一层的抠图和采样点、测量值", "picture scenes: full-size frames, the drawn layer cut out and sampled, measurements"),
T("复刻代码渲染画面", "remaking rendered pictures")),
("audio.png", T("声音波形和节拍图", "waveform and beat chart"), T("看节奏", "seeing the rhythm"))):
diff --git a/rea_video/vlm.py b/rea_video/vlm.py
index 7b397ad..167a87a 100644
--- a/rea_video/vlm.py
+++ b/rea_video/vlm.py
@@ -150,8 +150,18 @@ def _data_uri(path: Path, mime: str) -> str:
def parse_json(text: str) -> dict:
- text = text.strip()
+ text = re.sub(r"<think>[\s\S]*?</think>", "", text or "", flags=re.I).strip()
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text)
+ dec = json.JSONDecoder()
+ pos = text.find("{")
+ while pos != -1:
+ try:
+ out, _ = dec.raw_decode(text, pos)
+ if isinstance(out, dict):
+ return out
+ except ValueError:
+ pass
+ pos = text.find("{", pos + 1)
m = re.search(r"\{[\s\S]*\}", text)
if not m:
raise ValueError("no JSON object in VLM response")
@@ -237,7 +247,9 @@ class VLMClient:
content = build(part)
last: Exception | None = None
refused = False
- for model in list(self.models):
+ with self._lock:
+ models_snapshot = list(self.models)
+ for model in models_snapshot:
for attempt in range(2):
try:
t = time.time()
diff --git a/scripts/validate_capabilities.py b/scripts/validate_capabilities.py
index bda3ac5..238cc4e 100644
--- a/scripts/validate_capabilities.py
+++ b/scripts/validate_capabilities.py
@@ -161,6 +161,13 @@ def main() -> int:
errors.append(f"prompting.yaml:{mid}: 字段 {k} 类型不对")
elif k not in text_keys | list_keys:
errors.append(f"prompting.yaml:{mid}: 未知字段 {k}")
+ if mid in models:
+ m_aud = (models[mid].get("audio") or {}).get("native")
+ dlg = str(n.get("dialogue") or "")
+ if m_aud is True and ("没有音频" in dlg or "没有原生音频" in dlg):
+ errors.append(f"{mid}: models 标了 audio.native=true,但 prompting.yaml 写无原生音频")
+ if m_aud is False and "video.native_audio" in (models[mid].get("primitives") or []):
+ errors.append(f"{mid}: audio.native=false 但 primitives 含 video.native_audio")
for mid, m in live.items():
if m.get("category") == "video" and mid not in (notes.get("models") or {}):
warnings.append(f"{mid}: 还没有提示词写法(prompting.yaml)")
diff --git a/skills/rea-video/references/remake.md b/skills/rea-video/references/remake.md
index a9f0a31..d4c1928 100644
--- a/skills/rea-video/references/remake.md
+++ b/skills/rea-video/references/remake.md
@@ -12,7 +12,7 @@
## 用哪个模型
-- 模型、整条重做还是只做 AI 镜头、换什么,都写在 `remake/intent.yaml`(见 SKILL.md「复刻」),`rea-video plan out/ref` 按它出方案。用户没说用哪个模型就先问。
+- 模型、整条重做还是只做 AI 镜头、换什么,都写在 `remake/intent.yaml`(见 SKILL.md「复刻」),`rea-video plan out/ref` 按它出方案。用户没说用哪个模型时,先按默认模型(MiniMax H3,或 `prefs engine` 记住的模型)出方案并在回复里说明,不要先停下来追问;用户想换模型再跑 `rea-video plan out/ref --model <id>`。
- 报告里每个单元的提示词是草稿。按 `rea-video models <id>` 打印的写法写成最终版放进 `remake/prompts.json`:时间和镜头怎么分、参考素材怎么指代、台词和不想要的内容怎么写;首帧 / 首尾帧模式下只留运动和运镜。`rea-video plan` 会按这个模型的格式规则检查。
- 选帧、擦字、首尾帧怎么配:`rea-video models keyframes`。