Skip to content

Show it a video you love. Get a new video in the same style. An AI crew (Claude Code or Codex) plans, builds and reviews it with you.

Aim for goosebumps: design and judge the climax against the reference

許元豪9fb7a07ca990
diff --git a/.claude/skills/anime-cel/template/render.mjs b/.claude/skills/anime-cel/template/render.mjs
index 9f7418a..238f559 100644
--- a/.claude/skills/anime-cel/template/render.mjs
+++ b/.claude/skills/anime-cel/template/render.mjs
@@ -17,7 +17,7 @@
// --chrome=<path to Chrome/Chromium>.
import puppeteer from 'puppeteer-core';
import { spawn } from 'node:child_process';
-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';
+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { homedir } from 'node:os';
@@ -47,8 +47,12 @@ const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of Stri
const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];
if (args.encode) {
- const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;
- console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);
+ // no page here, so read PROJECT.audio from the config file (encoding used to drop the music when --audio was left out)
+ const cfg = existsSync('src/config.js') ? readFileSync('src/config.js', 'utf8') : '';
+ const audio = args.audio || cfg.match(/\baudio\s*:\s*['"`]([^'"`]+)['"`]/)?.[1];
+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length;
+ if (audio && !existsSync(audio)) { console.error(`audio file not found: ${audio}`); process.exit(1); }
+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ' — WARNING: no audio track (pass --audio or set PROJECT.audio)'}`);
await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,
...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),
'-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);
diff --git a/.claude/skills/crayon-storybook/template/render.mjs b/.claude/skills/crayon-storybook/template/render.mjs
index 7f91853..4e21538 100644
--- a/.claude/skills/crayon-storybook/template/render.mjs
+++ b/.claude/skills/crayon-storybook/template/render.mjs
@@ -17,7 +17,7 @@
// --chrome=<path to Chrome/Chromium>.
import puppeteer from 'puppeteer-core';
import { spawn } from 'node:child_process';
-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';
+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { homedir } from 'node:os';
@@ -47,8 +47,12 @@ const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of Stri
const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];
if (args.encode) {
- const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;
- console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);
+ // no page here, so read PROJECT.audio from the config file (encoding used to drop the music when --audio was left out)
+ const cfg = existsSync('src/config.js') ? readFileSync('src/config.js', 'utf8') : '';
+ const audio = args.audio || cfg.match(/\baudio\s*:\s*['"`]([^'"`]+)['"`]/)?.[1];
+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length;
+ if (audio && !existsSync(audio)) { console.error(`audio file not found: ${audio}`); process.exit(1); }
+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ' — WARNING: no audio track (pass --audio or set PROJECT.audio)'}`);
await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,
...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),
'-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);
diff --git a/.claude/skills/painted-animation/template/render.mjs b/.claude/skills/painted-animation/template/render.mjs
index 9f7418a..238f559 100644
--- a/.claude/skills/painted-animation/template/render.mjs
+++ b/.claude/skills/painted-animation/template/render.mjs
@@ -17,7 +17,7 @@
// --chrome=<path to Chrome/Chromium>.
import puppeteer from 'puppeteer-core';
import { spawn } from 'node:child_process';
-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';
+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { homedir } from 'node:os';
@@ -47,8 +47,12 @@ const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of Stri
const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];
if (args.encode) {
- const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;
- console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);
+ // no page here, so read PROJECT.audio from the config file (encoding used to drop the music when --audio was left out)
+ const cfg = existsSync('src/config.js') ? readFileSync('src/config.js', 'utf8') : '';
+ const audio = args.audio || cfg.match(/\baudio\s*:\s*['"`]([^'"`]+)['"`]/)?.[1];
+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length;
+ if (audio && !existsSync(audio)) { console.error(`audio file not found: ${audio}`); process.exit(1); }
+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ' — WARNING: no audio track (pass --audio or set PROJECT.audio)'}`);
await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,
...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),
'-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);
diff --git a/.claude/skills/paper-cutout/template/render.mjs b/.claude/skills/paper-cutout/template/render.mjs
index 9f7418a..238f559 100644
--- a/.claude/skills/paper-cutout/template/render.mjs
+++ b/.claude/skills/paper-cutout/template/render.mjs
@@ -17,7 +17,7 @@
// --chrome=<path to Chrome/Chromium>.
import puppeteer from 'puppeteer-core';
import { spawn } from 'node:child_process';
-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';
+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { homedir } from 'node:os';
@@ -47,8 +47,12 @@ const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of Stri
const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];
if (args.encode) {
- const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;
- console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);
+ // no page here, so read PROJECT.audio from the config file (encoding used to drop the music when --audio was left out)
+ const cfg = existsSync('src/config.js') ? readFileSync('src/config.js', 'utf8') : '';
+ const audio = args.audio || cfg.match(/\baudio\s*:\s*['"`]([^'"`]+)['"`]/)?.[1];
+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length;
+ if (audio && !existsSync(audio)) { console.error(`audio file not found: ${audio}`); process.exit(1); }
+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ' — WARNING: no audio track (pass --audio or set PROJECT.audio)'}`);
await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,
...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),
'-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);
diff --git a/.claude/skills/pixel-art/template/render.mjs b/.claude/skills/pixel-art/template/render.mjs
index 9f7418a..238f559 100644
--- a/.claude/skills/pixel-art/template/render.mjs
+++ b/.claude/skills/pixel-art/template/render.mjs
@@ -17,7 +17,7 @@
// --chrome=<path to Chrome/Chromium>.
import puppeteer from 'puppeteer-core';
import { spawn } from 'node:child_process';
-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';
+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { homedir } from 'node:os';
@@ -47,8 +47,12 @@ const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of Stri
const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];
if (args.encode) {
- const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;
- console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);
+ // no page here, so read PROJECT.audio from the config file (encoding used to drop the music when --audio was left out)
+ const cfg = existsSync('src/config.js') ? readFileSync('src/config.js', 'utf8') : '';
+ const audio = args.audio || cfg.match(/\baudio\s*:\s*['"`]([^'"`]+)['"`]/)?.[1];
+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length;
+ if (audio && !existsSync(audio)) { console.error(`audio file not found: ${audio}`); process.exit(1); }
+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ' — WARNING: no audio track (pass --audio or set PROJECT.audio)'}`);
await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,
...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),
'-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);
diff --git a/.claude/skills/video-clone/CONTRACT.md b/.claude/skills/video-clone/CONTRACT.md
index 81db635..7a32e06 100644
--- a/.claude/skills/video-clone/CONTRACT.md
+++ b/.claude/skills/video-clone/CONTRACT.md
@@ -13,10 +13,12 @@ projects/<id>/
sheet_1fps.jpg 每秒一格總覽
sheet_scenes.jpg 每個鏡頭中間格
STYLE.md ← agent:風格拆解(給人看)
+ peaks.json ← agent:參考片的高潮(起雞皮疙瘩的 1–2 刻),peak_<n>.jpg 是它的連續影格
route.json ← agent:風格判定與選用的 skill
plan.json ← agent:前製企劃(前端的主要畫面)
STORYBOARD.md ← agent:同一份企劃的文字版
assets/ ← agent:抓到或做出的素材;ASSETS.md = 授權紀錄
+ out/check/key_<n>_vs_ref.jpg ← agent:每個高潮的爆點那一格,成片品質,和參考片同一格並排(style_frames 最前面)
out/check/style_*.jpg ← agent:前製階段的「風格定調畫面」(2–4 張)
out/check/*.jpg 製作中的審查影格
out/video.mp4 ← 成品
@@ -70,7 +72,13 @@ projects/<id>/
"query": "paper texture", "source": "openverse", "url": "", "file": "assets/a1.jpg",
"license": "CC BY 4.0", "attribution": "作者 / 連結" }
],
- "style_frames": ["out/check/style_1.jpg"],
+ "peaks": [
+ { "id": "P1", "ref_peak": "P1", "shots": ["S8", "S9"], "build_from_s": 21.5, "hold_s": [23.6, 24.0], "hit_s": 24.0, "hold_after_s": 1.5,
+ "build": "張力怎麼往上堆", "hit": "爆發那一格(主體、大小、構圖、色彩、密度)", "after": "停住多久、怎麼收",
+ "sound": "爆點前安靜 0.4 s → 撞擊落在 hit_s 的重拍", "techniques": ["白閃引信", "布幕揭開", "群眾填滿畫面"],
+ "emotion": "觀眾在這一刻感受到什麼", "key_frame": "out/check/key_1.jpg", "key_frame_note": "自評:哪裡已經贏、哪裡還輸" }
+ ],
+ "style_frames": ["out/check/key_1_vs_ref.jpg", "out/check/style_1.jpg"],
"open_questions": ["要不要加卡拉 OK 字幕?需要 LRC"],
"changelog": ["v1:初版"]
}
@@ -79,6 +87,16 @@ projects/<id>/
規則:
- `shots` 的時間兩種都寫(拍與秒);沒有音樂時 `start_beat/end_beat` 可省略。
- 每個鏡頭都要有 `ref_shot`、`ref_what`、`camera`(逐鏡對照參考片;camera 用 engine 能直接吃的規格)。
+- `peaks` 裡的鏡頭在 shots 標 `"hero": true`;hero 鏡頭的 action 寫到格的層級(預備、爆發、停住)。
+
+## analysis/peaks.json
+
+```json
+[ { "id": "P1", "from": 24.0, "hit": 26.0, "to": 29.0, "strip": "analysis/peak_1.jpg",
+ "build": "…", "hold": "…", "hit_what": "…", "after": "…", "sound": "…",
+ "techniques": ["…"], "why_it_works": "一句話" } ]
+```
+線索來自 report.json 的 `audio.peak_candidates` 與 `flashes`,但一定要看 clip_strip.py 的連續影格確認。
- `analysis/STYLE.md` 第一行寫媒材(2d-painted · 2d-vector · 3d-stylized · 3d-photoreal · live-action)。
- 審查結果寫 `out/check/review.md`(每鏡 6 項 1–5 分)與 `out/check/compare_*.jpg`(compare.py 產生)。
- 每次依使用者意見修改企劃:`version` +1、`changelog` 加一行說明改了什麼。
@@ -97,7 +115,10 @@ out/check/shots/<Cn>.done.json 製作 agent:{ shots:[{ id, sheet, crops, not
out/check/shots/<shot>_sheet.jpg 每鏡 stills/strip;<shot>_crop_*.png 角色全解析度裁切
out/check/shots/<Cn>.review.json 鏡頭審查:{ shots:[{ id, pass, issues:[{time, where, issue, fix}] }], verified_fixes, needs_user }
out/check/shots/<Cn>.fixes.json 製作 agent 修正:[{ shot, issue, change, before, after, status: fixed|cannot|shared }]
-out/check/critique.json 最後評審:{ pass, scores, must_fix, needs_user, verified_fixes, nice_to_have, summary }
+out/check/critique.json 最後評審:{ pass, peaks:[{id, ours, ref, strip, verdict: ours_better|equal|ref_better, why}], scores, score_notes,
+ shots:[{id, score, why}], must_fix, needs_user, verified_fixes, nice_to_have, summary }
+ 任何高潮 ref_better 都不會通過(系統會自動補成必修)
+out/check/motion/motion.json motion_check.py:硬切點、長時間靜止、黑格、閃白、片尾硬切黑(每項附前後影格 strip)
out/check/fixes.json 導演修成片:[{ issue, shot, time, change, before, after, status }]
analysis/lyrics/subs.lrc|.json 使用者貼的歌詞,自動對時結果(每句時間與匹配度)
```
diff --git a/.claude/skills/video-clone/SKILL.md b/.claude/skills/video-clone/SKILL.md
index 9526734..81f8f42 100644
--- a/.claude/skills/video-clone/SKILL.md
+++ b/.claude/skills/video-clone/SKILL.md
@@ -10,6 +10,9 @@ description: 參考影片風格克隆器 — 使用者給一支參考影片(
使用者沒有素材時,先用 `scripts/fetch_assets.py` 從授權安全的來源(Openverse CC0/CC BY、Pixabay、Freesound)找;不夠可以自己上網搜尋。每個素材都把來源、作者、授權記進 assets/ASSETS.md,授權不明的標「授權未確認」並告訴使用者。
它自己不畫任何東西,負責的是:拆解參考片、選出正確的製作 skill、把關品質、跟使用者對焦。
+
+**目標是驚艷、讓人起雞皮疙瘩,不是「沒有錯」。** 驚艷來自高潮設計:找出參考片打動人的那 1–2 刻,設計我們的對應高潮
+(鋪陳 → 屏息 → 落在重拍的爆發 → 停住),把力氣集中在那幾鏡,並且一律用連續影格和參考片並排比,不看單張。
流程照這份文件走;每個階段做完都用一兩句話告訴使用者現在做到哪。
## 0. 收件
@@ -40,7 +43,11 @@ python .claude/skills/video-clone/scripts/analyze.py "<檔案或網址>" --out p
- 字幕 / 文字的用法
- 畫面裡若出現製作工具或開源專案連結,記下來(可能直接就是對應的 skill)
-把拆解結果精簡回報給使用者(一張表 + 3–5 個「這支好看的關鍵」)。
+**找高潮**:report.json 的 `audio.peak_candidates`(音樂蓄力後爆發)與 `flashes`(閃白格)是線索。每個候選用
+`scripts/clip_strip.py analysis/source.mp4 --range a:b --out analysis/peak_<n>.jpg` 抽 12fps 連續影格實際看,
+確認真正的爆點,寫 `analysis/peaks.json`(格式見 CONTRACT.md):怎麼鋪陳、有沒有屏息、爆點那一格發生什麼、停多久、聲音、用了哪些手法、為什麼打得到人。
+
+把拆解結果精簡回報給使用者(一張表 + 3–5 個「這支好看的關鍵」+ 高潮在哪裡、靠什麼)。
## 2. 選風格 → 選製作 skill
@@ -76,6 +83,10 @@ plan.json 每個 shot 填 `ref_shot`(參考片鏡頭編號)、`ref_what`(
參考幾乎每鏡都在動,我們也不能有死的靜止鏡頭)。純字卡的比例、明暗比例、平均鏡頭長度要跟參考片接近(誤差 ±30%)。
寫完自己檢查:把 plan 的鏡頭和 `shot_details` 逐列對一次,不一致的要改,或在 notes 寫理由。
+**高潮先設計**:plan.json 的 `peaks` 對應 analysis/peaks.json,寫清楚鋪陳、屏息、爆點(hit_s 對拍)、停住、聲音與手法(參考用的一個都不少);
+peaks 裡的鏡頭標 `hero: true`。核准前先把每個爆點那一格做到成片品質,和參考片同一格並排成 `out/check/key_<n>_vs_ref.jpg`,
+放在 style_frames 最前面給使用者看;比參考片弱就繼續改,不要交出去。
+
給使用者看分鏡並簡短說明;使用者說過「你自己決定」就直接開做。
## 5. 製作:一關一關過,不要堆到最後才審
@@ -89,7 +100,10 @@ plan.json 每個 shot 填 `ref_shot`(參考片鏡頭編號)、`ref_what`(
2D 向量角色一律用 `assets/vector_rig/`(骨架+一體輪廓;見它的 README),不准用圓形、長方形另外拼頭、身體、手臂。
4. **分段製作+即時審查**:多個製作 agent 平行做不同段;每段一做完,就由一個全新的審查員看那一段的每鏡 sheet、strip 與角色裁切,
不過就退回同一個製作 agent 修(最多 3 輪)。
-5. **組裝** → **最後評審**只看跨段的東西:接縫、連戲、節奏、字幕全片一致,並先核對之前每一個「已修正」。
+ hero 鏡頭可以用特製姿勢、誇張變形、衝擊格、smear、光芒、粒子、鏡頭震動;做完用 clip_strip.py `--vs` 和參考高潮逐格並排比。
+ **不准用閃白或轉場蓋掉做不到的動作或該被看見的那一刻。** 動作一律看 12fps 連續影格判斷(跳格、瞬移、該動不動、僵硬整塊旋轉)。
+5. **組裝**(跑 `motion_check.py` 抓黑格、片尾硬切黑、意外靜止;確認有音軌)→ **最後評審**:先做**高潮對決**(我們的高潮 vs 參考片高潮,連續影格並排),
+ 輸給參考片就不能交件;分數以參考片為尺(4 = 和參考片並排不顯得陽春),每項附證據、逐鏡打分;再看接縫、連戲、節奏、字幕,並核對之前每一個「已修正」。
人眼清單(每一關都用):四肢都接在身上、有脖子、沒有接縫或雙層描邊、跟角色設定圖一致、線寬一致、沒有穿模、主體夠大、字看得清楚、
沒有色帶或閃爍、動作有預備與跟隨。看不清楚就裁切放大再看。
@@ -113,7 +127,8 @@ plan.json 每個 shot 填 `ref_shot`(參考片鏡頭編號)、`ref_what`(
- **角色**:
- **使用者自己擁有的角色可以直接用**:使用者提供自家角色/吉祥物的設計圖(放在 inputs/),就照它製作並保持造型一致,不必換成原創。
- - **其他情況用原創角色**:請直接去抓取使用者所說的腳色、衣服、髮型、配件等特徵,一模一樣抄下來。
+ - **使用者點名要用的角色可以直接用**:自己上網找它的造型(衣服、髮型、配件、配色)照著做,不要拒絕或換成「神似原創」。
+ - 使用者沒指定角色時用原創角色。
- **歌詞**:只使用使用者提供的 LRC / 歌詞文字,不自行寫出歌詞;分鏡與回報中也不要引用歌詞內容。
- **參考片**:只學風格與手法,不複製它的畫面、角色、Logo 或素材。
- **媒材**:目前只做 2D(3D 賽道暫停,見第 2 步);不做的是生成真人實拍影像或真實人物的臉。
diff --git a/.claude/skills/video-clone/scripts/analyze.py b/.claude/skills/video-clone/scripts/analyze.py
index bfff10e..a3b334d 100644
--- a/.claude/skills/video-clone/scripts/analyze.py
+++ b/.claude/skills/video-clone/scripts/analyze.py
@@ -9,14 +9,20 @@ Writes into --out:
audio.wav mono audio, phase-safe and loudness-normalised (only if the input has sound)
sheet_1fps.jpg one frame per second, tiled — look at this first
sheet_scenes.jpg the middle frame of every detected shot
- report.json everything measured: size, crop, shots, pacing, tempo, beats, audio health, best 30 s windows
+ report.json everything measured: size, crop, shots, pacing, tempo, beats, audio health, best 30 s windows,
+ and peak_candidates (where the music builds and hits: the reference's likely goosebump moments)
+
+Results are cached per input (URL, or file content) in ~/.reelmimic/cache/analysis/: the same reference is analysed once.
Lessons baked in (each one broke a real run):
- phone screen recordings: the video is a strip in the middle of a UI → cropdetect, then analyse the proxy
- stereo recordings with inverted phase cancel to silence when summed to mono → measure L, R and L+R separately
- loudness: normalise the chosen channel so beat tracking sees the music, not the noise floor
"""
-import argparse, json, os, re, shutil, subprocess, sys, collections
+import argparse, hashlib, json, os, re, shutil, subprocess, sys, collections
+
+ANALYZE_VERSION = 2 # bump when report.json gains fields, so cached analyses are redone
+CACHE = os.path.join(os.path.expanduser("~"), ".reelmimic", "cache", "analysis")
FFMPEG_FALLBACK = os.environ.get("FFMPEG_DIR", "") # folder with ffmpeg/ffprobe when they are not on PATH
if not shutil.which("ffmpeg") and FFMPEG_FALLBACK and os.path.isdir(FFMPEG_FALLBACK):
@@ -243,19 +249,108 @@ def audio(path, info, out):
cands.sort(reverse=True)
# noise floor: the quietest 10th percentile of 0.5 s windows
hop = sr // 2; w = [db(y[i:i + hop]) for i in range(0, len(y) - hop, hop)]
+ peaks = peak_candidates(y, sr, beats)
return {"present": True, "silent": False, "levels_db": {"L": round(L, 1), "R": round(R, 1), "mono": round(M, 1)},
"phase_inverted": bool(phase_inverted), "noise_floor_db": round(float(np.percentile(w, 10)), 1) if w else None,
"bpm": round(bpm, 2), "beat_seconds": round(60 / bpm, 4), "first_beat": round(float(beats[0]), 3) if len(beats) else None,
"beats": [round(float(b), 3) for b in beats],
"best_30s_starts": [{"start": round(s, 2), "density": round(m, 3)} for m, s in cands[:5]],
+ "peak_candidates": peaks,
"quality_warning": ("mono only (phase-inverted stereo)" if phase_inverted else None)}
+def peak_candidates(y, sr, beats, n=3):
+ """Where the music builds and then hits: the moments a reference spends its biggest visual on. Three curves in
+ 0.25 s steps (loudness, onset strength, spectral fullness), each z-scored and summed, because mastered pop is
+ loudness-flat and only gets fuller and busier at a chorus. A candidate is the sharpest rise from the 2 s before to
+ the 1 s after, scored higher when a quieter stretch (the held breath) sits right before it; snapped to the nearest
+ beat. Numbers only point: the director confirms by looking at the frames."""
+ import numpy as np, librosa
+ hop = sr // 4
+ rms = librosa.feature.rms(y=y, frame_length=hop * 2, hop_length=hop)[0]
+ onset = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop)
+ bw = librosa.feature.spectral_bandwidth(y=y, sr=sr, hop_length=hop)[0]
+ m = min(len(rms), len(onset), len(bw))
+ if m < 24: return []
+ z = lambda v: (v - v.mean()) / (v.std() + 1e-9)
+ cur = z(20 * np.log10(rms[:m] + 1e-9)) + z(onset[:m]) + z(bw[:m])
+ sm = np.convolve(cur, np.ones(4) / 4, mode="same")
+ out = []
+ for i in range(8, m - 4):
+ before, after = sm[i - 8:i].mean(), sm[i:i + 4].mean()
+ rise = after - before
+ if rise < 0.8: continue
+ dip = float(sm[i - 8:i].min())
+ out.append((rise + 0.5 * max(0.0, before - dip) + 0.3 * after, i * 0.25, rise, after))
+ out.sort(reverse=True)
+ picked = []
+ for score, t, rise, after in out:
+ if len(beats): t = float(beats[np.argmin(np.abs(np.asarray(beats) - t))])
+ if any(abs(t - p["t"]) < 6 for p in picked): continue
+ picked.append({"t": round(t, 2), "rise": round(float(rise), 2), "level_after": round(float(after), 2),
+ "kind": "drop" if rise >= 2.5 else "lift"})
+ if len(picked) >= n: break
+ return sorted(picked, key=lambda p: p["t"])
+
+
+def flashes(path, dur):
+ """Frames much brighter than the frames around them (white flash / impact frames) and the busiest cut stretch:
+ references often mark their hit with a flash. 6 fps luminance, 64 px wide."""
+ import numpy as np
+ r = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", "fps=6,scale=64:36,format=gray", "-f", "rawvideo", "-"],
+ capture_output=True)
+ a = np.frombuffer(r.stdout, np.uint8)
+ if not len(a): return []
+ lum = a[: len(a) // (64 * 36) * 64 * 36].reshape(-1, 64 * 36).mean(1) / 255
+ out = []
+ for i in range(2, len(lum) - 2):
+ ctx = np.r_[lum[i - 2:i], lum[i + 1:i + 3]]
+ if lum[i] > 0.75 and lum[i] - ctx.min() > 0.3:
+ t = round(i / 6, 2)
+ if not out or t - out[-1] > 1: out.append(t)
+ return out
+
+
+def cache_key(src):
+ """URL → the URL; local file → its size plus the first and last 4 MB (the same file copied into another project hits)."""
+ h = hashlib.sha1(f"v{ANALYZE_VERSION}|".encode())
+ if os.path.isfile(src):
+ size = os.path.getsize(src); h.update(str(size).encode())
+ with open(src, "rb") as f:
+ h.update(f.read(4 << 20))
+ if size > 8 << 20: f.seek(-(4 << 20), 2); h.update(f.read())
+ else:
+ h.update(src.strip().encode())
+ return h.hexdigest()[:16]
+
+
+def summary(rep, out):
+ info, crop, au = rep["video"], rep["crop"], rep["audio"]
+ print(f"video {info['width']}x{info['height']} {info['fps']}fps {info['duration']:.1f}s" + (f" crop → {crop['w']}x{crop['h']} ({crop['note']})" if crop else ""))
+ print(f"shots {rep['pacing']}")
+ if rep.get("look_summary"): print(f"look {rep['look_summary']}")
+ if au.get("present") and not au.get("silent"):
+ print(f"audio {au['bpm']} bpm, first beat {au['first_beat']}s, noise floor {au['noise_floor_db']} dB, phase_inverted={au['phase_inverted']}")
+ print(f"best 30s windows: {[c['start'] for c in au['best_30s_starts']]}")
+ print(f"peak candidates (build → hit): {[(p['t'], p['kind']) for p in au.get('peak_candidates', [])]}")
+ if rep.get("flashes"): print(f"flash frames: {rep['flashes']}")
+ elif au.get("silent"): print("audio SILENT —", au["note"])
+ else: print("audio none")
+ print("wrote", os.path.join(out, "report.json"))
+
+
def main():
ap = argparse.ArgumentParser()
ap.add_argument("src"); ap.add_argument("--out", required=True)
+ ap.add_argument("--no-cache", action="store_true")
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
+ key = cache_key(a.src); cdir = os.path.join(CACHE, key)
+ if not a.no_cache and os.path.isfile(os.path.join(cdir, "report.json")):
+ shutil.copytree(cdir, a.out, dirs_exist_ok=True)
+ with open(os.path.join(a.out, "report.json"), encoding="utf-8") as f: rep = json.load(f)
+ print(f"cache same reference analysed before ({key}): reused")
+ summary(rep, a.out); return
src = fetch(a.src, a.out)
info = probe(src)
crop = None
@@ -272,6 +367,7 @@ def main():
"shortest_s": round(min(lens), 2) if lens else None, "longest_s": round(max(lens), 2) if lens else None},
"audio": aud.result(),
"shot_details": shot_details(vid, cuts, info["duration"]) if info["width"] else []}
+ if info["width"]: rep["flashes"] = flashes(vid, info["duration"])
sd = rep["shot_details"]
if sd:
dark = sum(1 for x in sd if x["look"]["dark_ratio"] > 0.5) / len(sd)
@@ -283,16 +379,11 @@ def main():
rep["pacing"]["mean_shot_beats"] = round(rep["pacing"]["mean_shot_s"] / rep["audio"]["beat_seconds"], 1)
with open(os.path.join(a.out, "report.json"), "w", encoding="utf-8") as f:
json.dump(rep, f, ensure_ascii=False, indent=1)
- au = rep["audio"]
- print(f"video {info['width']}x{info['height']} {info['fps']}fps {info['duration']:.1f}s" + (f" crop → {crop['w']}x{crop['h']} ({crop['note']})" if crop else ""))
- print(f"shots {rep['pacing']}")
- if rep.get("look_summary"): print(f"look {rep['look_summary']}")
- if au.get("present") and not au.get("silent"):
- print(f"audio {au['bpm']} bpm, first beat {au['first_beat']}s, noise floor {au['noise_floor_db']} dB, phase_inverted={au['phase_inverted']}")
- print(f"best 30s windows: {[c['start'] for c in au['best_30s_starts']]}")
- elif au.get("silent"): print("audio SILENT —", au["note"])
- else: print("audio none")
- print("wrote", os.path.join(a.out, "report.json"))
+ try: # cache the whole analysis folder (the agents later read source/proxy from it too)
+ shutil.copytree(a.out, cdir, dirs_exist_ok=True, ignore=shutil.ignore_patterns("STYLE.md", "route.json", "proposed_style_*", "song", "lyrics"))
+ except OSError as e:
+ print("cache not written:", e)
+ summary(rep, a.out)
if __name__ == "__main__":
diff --git a/.claude/skills/video-clone/scripts/clip_strip.py b/.claude/skills/video-clone/scripts/clip_strip.py
new file mode 100644
index 0000000..520b0f3
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/clip_strip.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""clip_strip.py — consecutive frames of a stretch of video as one image, optionally stacked against the reference.
+
+Stills can't show motion or a climax: a hit is the frames around it. Use this whenever you judge a moment.
+
+ python clip_strip.py out/video.mp4 --range 24.0:26.0 --out out/check/peak_1.jpg
+ python clip_strip.py out/video.mp4 --range 24.0:26.0 --vs analysis/source.mp4 --vs-range 25.0:27.0 --out out/check/peak_1_vs_ref.jpg
+
+--fps (default 12) frames per second of the stretch; --w (default 240) width of each frame; --cols (default 12).
+With --vs, the reference range is sampled into the same number of frames and each reference row sits directly above
+the matching row of ours (labelled REF / OURS with the time of every frame), so the build, the hit and the hold line up.
+"""
+import argparse, os, shutil, subprocess, sys, tempfile
+
+FFMPEG_FALLBACK = os.environ.get("FFMPEG_DIR", "")
+if not shutil.which("ffmpeg") and FFMPEG_FALLBACK and os.path.isdir(FFMPEG_FALLBACK):
+ os.environ["PATH"] += os.pathsep + FFMPEG_FALLBACK
+
+from PIL import Image, ImageDraw, ImageFont
+
+
+def font(size):
+ for f in ("arial.ttf", "DejaVuSans.ttf", "/System/Library/Fonts/Helvetica.ttc"):
+ try: return ImageFont.truetype(f, size)
+ except OSError: pass
+ return ImageFont.load_default()
+
+
+def grab(path, a, b, n, w):
+ """n frames evenly spread over [a, b), each w px wide."""
+ tmp = tempfile.mkdtemp(prefix="strip_")
+ fps = n / max(b - a, 1e-3)
+ subprocess.run(["ffmpeg", "-v", "error", "-ss", f"{a}", "-t", f"{b - a}", "-i", path,
+ "-vf", f"fps={fps},scale={w}:-2", "-frames:v", str(n), os.path.join(tmp, "f%04d.png")], check=True)
+ files = sorted(os.listdir(tmp))
+ ims = [Image.open(os.path.join(tmp, f)).convert("RGB") for f in files]
+ shutil.rmtree(tmp, ignore_errors=True)
+ return [(a + i / fps, im) for i, im in enumerate(ims)]
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("video"); ap.add_argument("--range", required=True); ap.add_argument("--out", required=True)
+ ap.add_argument("--vs"); ap.add_argument("--vs-range")
+ ap.add_argument("--fps", type=float, default=12); ap.add_argument("--w", type=int, default=240); ap.add_argument("--cols", type=int, default=12)
+ a = ap.parse_args()
+ s, e = map(float, a.range.split(":"))
+ n = max(2, round((e - s) * a.fps))
+ ours = grab(a.video, s, e, n, a.w)
+ ref = None
+ if a.vs:
+ rs, re_ = map(float, (a.vs_range or a.range).split(":"))
+ ref = grab(a.vs, rs, re_, len(ours), a.w)
+ fh = ours[0][1].height; lab = 18; f = font(13)
+ rows = [ours[i:i + a.cols] for i in range(0, len(ours), a.cols)]
+ refrows = [ref[i:i + a.cols] for i in range(0, len(ref), a.cols)] if ref else []
+ bands = []
+ for k, row in enumerate(rows):
+ if ref: bands.append(("REF", refrows[k] if k < len(refrows) else []))
+ bands.append(("OURS" if ref else "", row))
+ W = a.cols * a.w + 50; H = len(bands) * (fh + lab) + (len(rows) * 8 if ref else 0)
+ sheet = Image.new("RGB", (W, H), (24, 24, 28)); d = ImageDraw.Draw(sheet)
+ y = 0
+ for i, (name, row) in enumerate(bands):
+ d.text((4, y + lab + fh // 2 - 7), name, fill=(255, 200, 80) if name == "REF" else (120, 220, 255), font=f)
+ for j, (t, im) in enumerate(row):
+ x = 50 + j * a.w
+ sheet.paste(im, (x, y + lab)); d.text((x + 3, y + 2), f"{t:.2f}s", fill=(220, 220, 220), font=f)
+ y += fh + lab
+ if ref and name == "OURS": y += 8
+ os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
+ sheet.save(a.out, quality=90)
+ print(f"wrote {a.out} ({len(ours)} frames{' vs reference' if ref else ''})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.claude/skills/video-clone/scripts/motion_check.py b/.claude/skills/video-clone/scripts/motion_check.py
new file mode 100644
index 0000000..d583a57
--- /dev/null
+++ b/.claude/skills/video-clone/scripts/motion_check.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+"""motion_check.py — find the motion defects that stills can't show, in a rendered video.
+
+ python motion_check.py out/video.mp4 --out out/check/motion [--from 0 --to 30]
+
+Looks at every frame (downscaled) and flags:
+ freeze a stretch where nothing moves for longer than --freeze seconds (default 1.0) outside title cards.
+ black frames that are (almost) black inside the film, and a hard cut to black at the end (no fade).
+ flash (almost) white frames — fine when designed, but they must not hide the moment they cover.
+Writes <out>/motion.json and one strip per flag (<out>/<kind>_<time>.jpg, the frames around it) — open the strips.
+It also lists the hard cuts, to check against the plan's shot list.
+Pops (a pose, expression or prop swapped with no in-between) are NOT detected here: frame differences can't tell them
+from wipes and caption changes (tested on real runs). Find them by looking: clip_strip.py at 12 fps over every action.
+"""
+import argparse, json, os, shutil, subprocess
+
+FFMPEG_FALLBACK = os.environ.get("FFMPEG_DIR", "")
+if not shutil.which("ffmpeg") and FFMPEG_FALLBACK and os.path.isdir(FFMPEG_FALLBACK):
+ os.environ["PATH"] += os.pathsep + FFMPEG_FALLBACK
+
+import numpy as np
+
+W, H, G = 160, 96, 8 # analysis size; G×G grid of cells for "how much of the frame changed"
+
+
+def probe_fps(path):
+ r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=r_frame_rate", "-of", "csv=p=0", path],
+ capture_output=True, text=True)
+ n, d = (r.stdout.strip().splitlines() or ["24/1"])[0].strip(",").split("/")
+ return float(n) / float(d)
+
+
+def frames(path, a, b):
+ cmd = ["ffmpeg", "-v", "error"] + (["-ss", str(a)] if a else []) + ["-i", path] + (["-t", str(b - a)] if b else []) + \
+ ["-vf", f"scale={W}:{H},format=gray", "-f", "rawvideo", "-"]
+ raw = subprocess.run(cmd, capture_output=True).stdout
+ arr = np.frombuffer(raw, np.uint8)
+ return arr[: len(arr) // (W * H) * W * H].reshape(-1, H, W).astype(np.float32) / 255
+
+
+def strip(path, t, fps, out, n=10):
+ a = max(0.0, t - (n // 2) / fps)
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", f"{a:.3f}", "-i", path, "-frames:v", str(n),
+ "-vf", f"scale=320:-2,drawtext=text='%{{pts\\:hms\\:{a:.3f}}}':x=4:y=4:fontsize=14:fontcolor=white:box=1:[email protected],tile={n}x1",
+ "-update", "1", out], capture_output=True)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("video"); ap.add_argument("--out", required=True)
+ ap.add_argument("--from", dest="a", type=float, default=0); ap.add_argument("--to", dest="b", type=float, default=0)
+ ap.add_argument("--freeze", type=float, default=1.0)
+ a = ap.parse_args()
+ os.makedirs(a.out, exist_ok=True)
+ fps = probe_fps(a.video)
+ F = frames(a.video, a.a, a.b)
+ if len(F) < 3: raise SystemExit("no frames")
+ t = lambda i: round(a.a + i / fps, 3)
+ lum = F.mean((1, 2))
+ d = np.abs(np.diff(F, axis=0)) # d[i] = change from frame i to i+1
+ whole = d.mean((1, 2))
+ cells = d.reshape(len(d), G, H // G, G, W // G).mean((2, 4)) # (n, G, G)
+ # cuts: most of the frame changes a lot at once (line boil / grain change everything a little, not a lot)
+ big = (cells > 0.1).mean((1, 2))
+ cut_at = {i for i in range(len(d)) if big[i] > 0.5 and whole[i] > 0.1}
+ cuts = [t(i + 1) for i in sorted(cut_at)]
+ freezes, run = [], 0
+ for i in range(len(d) + 1):
+ still = i < len(d) and whole[i] < 0.0015
+ if still: run += 1
+ else:
+ if run / fps >= a.freeze: freezes.append({"from": t(i - run), "to": t(i), "s": round(run / fps, 2)})
+ run = 0
+ black, white = [], []
+ for i, v in enumerate(lum):
+ if v < 0.04 and (not black or t(i) - black[-1]["to"] > 1.5 / fps): black.append({"from": t(i), "to": t(i)})
+ elif v < 0.04: black[-1]["to"] = t(i)
+ if v > 0.92 and (not white or t(i) - white[-1] > 0.5): white.append(t(i))
+ tail = lum[-int(fps * 0.5):] if len(lum) > fps else lum
+ end_hard_black = bool(lum[-1] < 0.04 and len(tail) > 3 and tail[0] > 0.12 and np.min(np.diff(tail)) < -0.1)
+ rep = {"video": a.video, "fps": fps, "frames": len(F), "cuts": cuts, "freezes": freezes,
+ "black": [b for b in black if b["from"] > a.a + 0.2], "white_flash": white, "end_hard_cut_to_black": end_hard_black,
+ "note": "open each strip. Pops are not detected here: check every action with clip_strip.py at 12 fps."}
+ for z in freezes: strip(a.video, (z["from"] + z["to"]) / 2, fps, os.path.join(a.out, f"freeze_{z['from']:.2f}.jpg"))
+ for b in rep["black"]: strip(a.video, b["from"], fps, os.path.join(a.out, f"black_{b['from']:.2f}.jpg"))
+ with open(os.path.join(a.out, "motion.json"), "w", encoding="utf-8") as f: json.dump(rep, f, indent=1)
+ print(f"cuts {len(cuts)} freezes {len(freezes)} black {len(rep['black'])} white {len(white)} end_hard_black {end_hard_black}")
+ for z in freezes: print(f" freeze {z['from']:.2f}–{z['to']:.2f}s ({z['s']}s)")
+ print("wrote", os.path.join(a.out, "motion.json"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.claude/skills/whiteboard/template/render.mjs b/.claude/skills/whiteboard/template/render.mjs
index 9f7418a..238f559 100644
--- a/.claude/skills/whiteboard/template/render.mjs
+++ b/.claude/skills/whiteboard/template/render.mjs
@@ -17,7 +17,7 @@
// --chrome=<path to Chrome/Chromium>.
import puppeteer from 'puppeteer-core';
import { spawn } from 'node:child_process';
-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';
+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { homedir } from 'node:os';
@@ -47,8 +47,12 @@ const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of Stri
const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];
if (args.encode) {
- const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;
- console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);
+ // no page here, so read PROJECT.audio from the config file (encoding used to drop the music when --audio was left out)
+ const cfg = existsSync('src/config.js') ? readFileSync('src/config.js', 'utf8') : '';
+ const audio = args.audio || cfg.match(/\baudio\s*:\s*['"`]([^'"`]+)['"`]/)?.[1];
+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length;
+ if (audio && !existsSync(audio)) { console.error(`audio file not found: ${audio}`); process.exit(1); }
+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ' — WARNING: no audio track (pass --audio or set PROJECT.audio)'}`);
await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,
...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),
'-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);
diff --git a/app/server/index.ts b/app/server/index.ts
index 6576ad2..10d768b 100644
--- a/app/server/index.ts
+++ b/app/server/index.ts
@@ -126,5 +126,6 @@ app.get<'/files/:id/*', { id: string; 0: string }>('/files/:id/*', (req, res) =>
const dist = join(import.meta.dirname, '..', 'dist');
if (existsSync(dist)) { app.use(express.static(dist)); app.get(/^\/(?!api|files).*/, (req, res) => res.sendFile(join(dist, 'index.html'))); }
-J.recoverOrphans();
+const cut = J.recoverOrphans();
+if (cut.length && process.env.AUTO_RESUME !== '0') { console.log(`Resuming ${cut.length} interrupted job(s): ${cut.join(', ')}`); J.autoResume(cut); }
app.listen(PORT, '127.0.0.1', () => console.log(`ReelMimic → http://localhost:${PORT}`));
diff --git a/app/server/jobs.ts b/app/server/jobs.ts
index c2aad14..2ca7130 100644
--- a/app/server/jobs.ts
+++ b/app/server/jobs.ts
@@ -41,6 +41,11 @@ export const CONFIG: Config = {
chunkRounds: +(process.env.CHUNK_ROUNDS || 3), // shot line: review/fix rounds per chunk
finalRounds: +(process.env.FINAL_ROUNDS || 2), // final panel: automatic revise rounds
maxAgentsGlobal: +(process.env.MAX_AGENTS || 12), // all projects together (CLI rate limits, CPU/GPU for renders)
+ maxReviews: +(process.env.MAX_REVIEWS || 4), // shot reviews at once per project: each one opens Chrome to grab frames;
+ // 13 at once meant 80–200 Chrome processes and screenshot timeouts
+ // Build shots while the cast gate is still running? Faster, but on real runs character files changed under the
+ // builders and every segment needed an extra round (0nczg, 4f1jx, 1qo20, 7e45u). Off by default: quality first.
+ overlapCast: process.env.OVERLAP_CAST === '1',
};
// Review/fix round limits: CONFIG holds the defaults; a project can set its own (job.settings), read at every check so a
@@ -88,14 +93,26 @@ function log(id: string, ev: LogEntry) {
}
// On startup nothing is running, so a job still marked as working was cut off by a restart: say so instead of pretending.
-export function recoverOrphans() {
+export function recoverOrphans(): string[] {
+ const cut: string[] = [];
const WORK = ['analyzing', 'styling', 'planning', 'replanning', 'producing', 'revising', 'critiquing'];
for (const d of existsSync(PROJECTS) ? readdirSync(PROJECTS) : []) {
if (!existsSync(jpath(d))) continue;
const j = load(d);
if (!WORK.includes(j.stage)) continue;
+ cut.push(d);
update(d, (x) => { x.failed = x.stage; x.stage = 'error'; x.error = L(d, '伺服器重新啟動,這一輪被中斷了(它可能已經改了部分檔案)。按「重試這一步」從目前的檔案繼續。', 'The server restarted and this turn was cut off (it may have changed some files). Click “Retry this step” to continue from the current files.'); x.chat.push({ role: 'system', text: L(d, '這一輪因為伺服器重新啟動而中斷。', 'This turn was cut off by a server restart.'), ts: now() }); });
}
+ return cut;
+}
+// After a restart, pick the interrupted jobs up again on their own (one real run sat cut off for 11.5 hours overnight).
+// Staggered so they don't all launch agents at once. AUTO_RESUME=0 turns it off.
+export function autoResume(ids: string[], gapMs = 5000) {
+ ids.forEach((id, i) => setTimeout(() => {
+ if (load(id).stage !== 'error') return; // the user already did something with it
+ chat(id, 'system', L(id, '伺服器重新啟動後自動接續這一步。', 'Resuming this step automatically after the server restart.'));
+ retry(id).catch((e) => console.error('auto-resume', id, e));
+ }, (i + 1) * gapMs));
}
const readJSON = <T>(p: string): T | null => { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } };
const readText = (p: string): string | null => { try { return readFileSync(p, 'utf8'); } catch { return null; } };
@@ -308,9 +325,10 @@ function collectNeeds(id: string, items: NeedRequest[] | undefined, from: string
}
// ---------- pre-production ----------
+const STYLE_OUT = ['analysis/STYLE.md', 'analysis/route.json', 'analysis/peaks.json']; // peaks: the reference's goosebump moments
export async function start(id: string) {
if (!(await analyze(id))) return;
- if (!(await step(id, 'styling', 'style', {}, ['analysis/STYLE.md', 'analysis/route.json'], 'styled'))) return;
+ if (!(await step(id, 'styling', 'style', {}, STYLE_OUT, 'styled'))) return;
await preProduction(id);
}
@@ -404,7 +422,7 @@ export async function approve(id: string) {
const open = openInputs(id);
if (open.length) throw Object.assign(new Error('還有需要你提供或略過的素材:' + open.map((r) => r.label || r.id).join('、')), { code: 409 });
await alignIfReady(id).catch(() => null); // lyrics pasted before the music arrived: time them now, before anything is built
- update(id, (j) => { j.approvedAt = now(); j.approvedPlanVersion = readJSON<Plan>(join(dirOf(id), 'plan.json'))?.version; j.engineSnapshot = snapshotEngine(id); j.pipeline = {}; j.sessions = j.approvedAtPrev ? {} : Object.fromEntries(Object.entries(j.sessions || {}).filter(([k]) => k.startsWith('cast-'))); j.approvedAtPrev = true; j.needs = []; j.userNote = null; });
+ update(id, (j) => { j.approvedAt = now(); j.approvedPlanVersion = readJSON<Plan>(join(dirOf(id), 'plan.json'))?.version; j.engineSnapshot = snapshotEngine(id); j.pipeline = {}; j.sessions = j.approvedAtPrev ? {} : Object.fromEntries(Object.entries(j.sessions || {}).filter(([k]) => k.startsWith('cast-'))); j.approvedAtPrev = true; j.needs = []; j.userNote = null; j.critiqueRounds = 0; });
chat(id, 'system', L(id, `企劃已核准,開始生產:角色關 → 分段製作(每段做完立刻審)→ 組裝 → 最後評審`, 'Plan approved. Production: characters → parts built and reviewed as they finish → assembly → final review'));
if (await production(id, { fresh: true })) await finalPanel(id);
}
@@ -423,6 +441,7 @@ async function production(id: string, { fresh = false } = {}): Promise<boolean>
// 2) cast gate and 3) shot building run at the same time: shots only call the shared character definitions, so cast fixes
// flow into them automatically. Shot REVIEWS wait until the cast has passed, and re-grab fresh frames first.
const castP = castGate(id, prev);
+ if (!CONFIG.overlapCast && !(await castP)) return false; // characters are final before any shot is built
const prod = readJSON<Production>(join(d, 'build', 'production.json')) || {};
const chunks = prod.chunks || [];
const old = prev.chunks || {};
@@ -437,7 +456,7 @@ async function production(id: string, { fresh = false } = {}): Promise<boolean>
const reviews: Record<string, Promise<boolean>> = {}, results: Record<string, { entry: ShotEntry; needs: NeedRequest[]; verified: unknown[] }> = {};
const reviewShot = (sid: string, round: number) => (reviews[sid] = (async () => {
if (!(await castP)) return false;
- const r = await turn(id, 'shot_qa', { chunk: c, shots: [sid], round, out: `out/check/shots/${sid}.review.json` }, [`out/check/shots/${sid}.review.json`], { session: 'fresh', who: `shot-qa-${sid}` });
+ const r = await reviewSlot(id, () => turn(id, 'shot_qa', { chunk: c, shots: [sid], round, out: `out/check/shots/${sid}.review.json` }, [`out/check/shots/${sid}.review.json`], { session: 'fresh', who: `shot-qa-${sid}` }));
if (!r.ok) return false;
const rv = readJSON<ChunkReview>(shotFile(sid, 'review')) || {};
results[sid] = { entry: (rv.shots || []).find((x) => x.id === sid) || { id: sid, pass: !!rv.pass, issues: rv.issues || [] }, needs: rv.needs_user || [], verified: rv.verified_fixes || [] };
@@ -596,6 +615,15 @@ async function castSerial(id: string, prev: Pipeline, firstReview?: Review | nul
return true;
}
+// at most CONFIG.maxReviews shot reviews of one project at a time (each grabs frames in Chrome)
+const reviewQ = new Map<string, { n: number; wait: (() => void)[] }>();
+async function reviewSlot<T>(id: string, fn: () => Promise<T>): Promise<T> {
+ const q = reviewQ.get(id) || { n: 0, wait: [] }; reviewQ.set(id, q);
+ if (q.n >= CONFIG.maxReviews) await new Promise<void>((r) => q.wait.push(r));
+ q.n++;
+ try { return await fn(); } finally { q.n--; q.wait.shift()?.(); }
+}
+
const sharedLocks = new Map<string, Promise<unknown>>(); // per project: one director edits shared files at a time
function sharedLock<T>(key: string, fn: () => Promise<T>): Promise<T> { const prev = sharedLocks.get(key) || Promise.resolve(); const next = prev.then(fn, fn); sharedLocks.set(key, next.catch(() => {})); return next; }
@@ -609,12 +637,16 @@ async function finalPanel(id: string) {
if (!(await step(id, 'critiquing', 'critique', { round }, ['out/check/critique.json'], null, { session: 'fresh', who: 'critic' }))) return;
const c = readJSON<Critique>(join(d, 'out', 'check', 'critique.json')) || {};
const must = (c.must_fix || []).filter(Boolean);
- update(id, (j) => { j.critiqueRounds = round; j.lastCritique = { pass: !must.length, must: must.length, at: now() }; });
+ // a climax that loses to the reference never passes, even if the critic forgot to list a fix for it
+ for (const pk of (c.peaks || []).filter((x) => x?.verdict === 'ref_better'))
+ if (!must.some((m) => m.issue.includes(pk.id))) must.push({ shot: pk.id, time: pk.ours?.[0], issue: `高潮 ${pk.id} 輸給參考片:${pk.why || ''}`, fix: `照 ${pk.strip || '高潮對照圖'} 逐格補上參考片爆點的手法,直到不輸參考片` });
+ const total = (load(id).critiqueRounds || 0) + 1; // every critic pass since approval (retries and user revisions included)
+ update(id, (j) => { j.critiqueRounds = total; j.lastCritique = { pass: !must.length, must: must.length, at: now() }; });
const needs = collectNeeds(id, c.needs_user, 'critic');
- if (!must.length) { chat(id, 'system', needs ? L(id, '評審:導演能修的都過了,剩下需要你提供的項目', 'Final review: everything the director can fix is done. What is left needs your input') : L(id, `評審通過(第 ${round} 輪)`, `Final review passed (round ${round})`)); setStage(id, needs ? 'needs_input' : 'done'); return; }
+ if (!must.length) { chat(id, 'system', needs ? L(id, '評審:導演能修的都過了,剩下需要你提供的項目', 'Final review: everything the director can fix is done. What is left needs your input') : L(id, `評審通過(第 ${total} 輪)`, `Final review passed (round ${total})`)); setStage(id, needs ? 'needs_input' : 'done'); return; }
if (round > rounds(id).finalRounds) { chat(id, 'system', L(id, `評審仍有 ${must.length} 項必修,已達自動修改上限,請你決定`, `The final review still has ${must.length} must-fix item${must.length > 1 ? 's' : ''} and the automatic fix limit is reached. Please decide`)); setStage(id, 'done'); return; }
const msg = must.map((m, i) => `${i + 1}. [${m.shot || '全片'}${m.time != null ? ' ' + m.time + 's' : ''}] ${m.issue}${m.fix ? ' → 建議:' + m.fix : ''}`).join('\n');
- chat(id, 'system', L(id, `評審第 ${round} 輪:${must.length} 項必修,交回導演(每項要附修改前後對照)`, `Final review round ${round}: ${must.length} must-fix item${must.length > 1 ? 's' : ''}, sent back to the director (each fix needs before/after proof)`));
+ chat(id, 'system', L(id, `評審第 ${total} 輪:${must.length} 項必修,交回導演(每項要附修改前後對照)`, `Final review round ${total}: ${must.length} must-fix item${must.length > 1 ? 's' : ''}, sent back to the director (each fix needs before/after proof)`));
if (!(await step(id, 'revising', 'revise', { message: msg, round }, ['out/video.mp4', 'out/check/fixes.json']))) return;
}
}
@@ -623,7 +655,7 @@ export async function retry(id: string) {
const j = load(id), f = j.failed;
update(id, (x) => { x.retryPending = true; });
if (f === 'analyzing') return start(id);
- if (f === 'styling') { if (await step(id, 'styling', 'style', {}, ['analysis/STYLE.md', 'analysis/route.json'], 'styled')) await preProduction(id); return; }
+ if (f === 'styling') { if (await step(id, 'styling', 'style', {}, STYLE_OUT, 'styled')) await preProduction(id); return; }
if (f === 'planning') return preProduction(id);
if (f === 'replanning') return step(id, 'replanning', 'replan', { message: [...j.chat].reverse().find((c) => c.role === 'user')?.text || '請重新整理企劃' }, ['plan.json'], 'plan_review');
if (f === 'producing' || j.stage === 'needs_input') { if (await production(id)) await finalPanel(id); return; }
diff --git a/app/server/pipeline.test.ts b/app/server/pipeline.test.ts
index 12ccb04..9732ebe 100644
--- a/app/server/pipeline.test.ts
+++ b/app/server/pipeline.test.ts
@@ -19,7 +19,7 @@ interface Scenario {
shotPass: (shot: string, round: number) => boolean;
sharedFix?: (chunk: string, call: number) => boolean; // the builder reports a shared-file problem instead
castShared?: (char: string, call: number) => boolean;
- critique: (round: number) => { must?: number; needs?: number };
+ critique: (round: number) => { must?: number; needs?: number; lostPeak?: boolean };
buildDelayMs?: number; // let the per-shot watcher (every 4 s) pick shots up
}
let S: Scenario;
@@ -31,7 +31,7 @@ function outputs(prompt: string, dir: string): [string, Record<string, unknown>]
const m = (re: RegExp) => prompt.match(re);
const json = (o: unknown) => o;
let r: RegExpMatchArray | null;
- if (m(/## 步驟:風格拆解/)) return ['style', { 'analysis/STYLE.md': '# 2D', 'analysis/route.json': { engine: 'no-such-engine' } }];
+ if (m(/## 步驟:風格拆解/)) return ['style', { 'analysis/STYLE.md': '# 2D', 'analysis/route.json': { engine: 'no-such-engine' }, 'analysis/peaks.json': [{ id: 'P1', hit: 2 }] }];
if (m(/## 步驟:前製企劃/)) return ['plan', { 'plan.json': { title: 'T', version: 1, characters: S.chars.map((id) => ({ id, name: id, file: `build/${id}.js` })) }, 'STORYBOARD.md': '# SB' }];
if ((r = m(/## 步驟:做角色「[^」]+」[\s\S]*?只寫 (\S+?):/))) return [`pre_cast`, { [r[1]]: '// character' }];
if (m(/## 步驟:整合前製結果/)) return ['plan_frames', { 'plan.json': { title: 'T', version: 2, characters: S.chars.map((id) => ({ id, name: id, file: `build/${id}.js` })) } }];
@@ -69,7 +69,7 @@ function outputs(prompt: string, dir: string): [string, Record<string, unknown>]
if (m(/## 步驟:組裝成片/)) return ['assemble', { 'out/video.mp4': 'mp4' }];
if (m(/獨立評審/)) {
const round = bump(`critique-${dir}`), c = S.critique(round);
- return [`critique`, { 'out/check/critique.json': { must_fix: Array.from({ length: c.must || 0 }, (_, i) => ({ shot: 'S1', issue: `must ${i}` })), needs_user: Array.from({ length: c.needs || 0 }, () => ({ kind: 'text', issue: 'confirm the lyric' })) } }];
+ return [`critique`, { 'out/check/critique.json': { peaks: [{ id: 'P1', verdict: c.lostPeak ? 'ref_better' : 'equal', why: 'smaller hit' }], must_fix: Array.from({ length: c.must || 0 }, (_, i) => ({ shot: 'S1', issue: `must ${i}` })), needs_user: Array.from({ length: c.needs || 0 }, () => ({ kind: 'text', issue: 'confirm the lyric' })) } }];
}
if (m(/## 步驟:修改成片/)) return ['revise', { 'out/video.mp4': 'mp4', 'out/check/fixes.json': [{ status: 'fixed' }] }];
throw new Error('fake agent: unknown step\n' + prompt.slice(0, 300));
@@ -154,6 +154,24 @@ describe('production', () => {
assert.equal(J.load(id).critiqueRounds, 2);
});
+ test('a climax that loses to the reference is sent back even with no must-fix listed', async () => {
+ S = base({ critique: (r) => ({ lostPeak: r === 1 }) });
+ const id = newProject('plan_review');
+ await J.approve(id);
+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');
+ assert.deepEqual(calls.slice(-3), ['critique', 'revise', 'critique']);
+ assert.ok(J.load(id).chat.some((c) => /高潮 P1 輸給參考片/.test(c.text) || /1 項必修/.test(c.text)));
+ });
+
+ test('no shot is built before the characters pass', async () => {
+ S = base({ castPass: (_w, r) => r >= 2 });
+ const id = newProject('plan_review');
+ await J.approve(id);
+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');
+ const firstBuild = calls.findIndex((c) => c.startsWith('build:'));
+ assert.ok(firstBuild > calls.lastIndexOf('cast_qa:serial'), calls.join(' '));
+ });
+
test('shot reviews start while the builder is still working (per-shot watcher)', async () => {
S = base({ chunks: [{ id: 'C1', shots: ['S1', 'S2'] }], buildDelayMs: 4600 });
const id = newProject('plan_review');
@@ -296,3 +314,18 @@ describe('no characters', () => {
assert.equal(J.load(id).stage, 'done', J.load(id).error || '');
});
});
+
+describe('restart', () => {
+ test('an interrupted job resumes on its own', async () => {
+ S = base();
+ const id = newProject('plan_review');
+ writeFileSync(join(J.dirOf(id), 'job.json'), JSON.stringify({ ...J.load(id), stage: 'replanning' }));
+ const cut = J.recoverOrphans();
+ assert.ok(cut.includes(id));
+ assert.equal(J.load(id).stage, 'error');
+ J.autoResume([id], 1);
+ for (let i = 0; i < 100 && J.load(id).stage !== 'plan_review'; i++) await new Promise((r) => setTimeout(r, 50));
+ assert.equal(J.load(id).stage, 'plan_review');
+ assert.ok(calls.includes('replan'));
+ });
+});
diff --git a/app/server/prompts.ts b/app/server/prompts.ts
index 742d3a7..cbdaab2 100644
--- a/app/server/prompts.ts
+++ b/app/server/prompts.ts
@@ -5,10 +5,20 @@ import type { BaseVars, Prompts } from './types.ts';
const SKILL = '.claude/skills/video-clone';
-const RULES = `規則:使用者在 inputs/ 提供的自家角色可直接照著做;其他角色與畫面原創(不畫知名既有角色、他人吉祥物或品牌);
+const RULES = `規則:使用者在 inputs/ 提供的自家角色可直接照著做;**使用者在需求或對話裡點名要用的角色(例如某個吉祥物、卡通人物)可以直接用**:
+自己上網找它的造型(服裝、髮型、配件、配色)照著做,不要拒絕或換成「神似原創」;其他角色與畫面原創;不放他人品牌 Logo;
歌詞只能來自使用者提供的文字(inputs/lyrics.txt 或 .lrc;已對時的在 analysis/lyrics/subs.lrc),不要自己寫出、轉錄或引用歌詞;
外部素材可以自己上網找(圖片、音效、配樂、字型、參考資料):先用 ${SKILL}/scripts/fetch_assets.py 的授權安全來源;不夠再用網路搜尋,
-每一個都把來源網址、作者、授權寫進 assets/ASSETS.md,授權不明的標「授權未確認」並在回報裡告訴使用者。不下載商業歌曲、不抓他人品牌 Logo 或知名角色圖。`;
+每一個都把來源網址、作者、授權寫進 assets/ASSETS.md,授權不明的標「授權未確認」並在回報裡告訴使用者。不下載商業歌曲、不抓他人品牌 Logo。
+邊界:只改 repo 裡的檔案(不要改使用者的 shell 設定 ~/.bashrc、~/.bash_profile、環境變數或系統設定);
+只結束你自己開的程序(不要用 pkill/taskkill 加萬用字元比對去殺 Chrome、node 等,別的 agent 和專案也在用)。`;
+
+// The point of every video: a moment that gives goosebumps. Shared by the planner, builders, reviewers and the critic.
+const WOW = `**這支片的目標是驚艷,讓人起雞皮疙瘩**,不是「沒有錯」。驚艷來自高潮設計,不是平均用力:
+- 高潮 = 鋪陳(張力往上堆)→ 屏息(安靜、停住、收窄)→ 爆發(落在重拍:構圖、色彩、動作、聲音同時翻轉)→ 停住(讓情緒落地 ≥ 1 秒,不要馬上切走)。
+- 爆發那一下要「看得到」:主體大、清楚、畫面密度和參考片的爆點一樣滿;閃白、光圈、轉場只能當引信,**不准用閃白或轉場蓋掉該被看到的那一刻**(擁抱、揭露、表情)。
+- 力氣集中在 plan.peaks 的 hero 鏡頭:特製姿勢、誇張變形臉、衝擊格、smear、光芒/粒子、鏡頭震動、色彩翻轉、音效(蓄力、撞擊、爆點前的安靜)——參考片爆點用了什麼,我們至少一樣多。
+- 判斷爆點一律用連續影格,不看單張:python ${SKILL}/scripts/clip_strip.py <我們的影片> --range a:b --vs analysis/<source 或 proxy> --vs-range c:d --out …(參考在上、我們在下,逐格對齊)。`;
const ENGINE = (p: BaseVars) => `企劃核准後,製作引擎已凍結成快照 ${p.dir}/build/engine/<engine>/(SNAPSHOT.json):製作一律用快照裡的 SKILL.md 與 scripts。
工具本體(.claude/skills/)是唯讀的;需要改引擎就複製到 build/ 裡改,並把「坑、修正、建議合回 skill」寫進 out/lessons.md。`;
@@ -42,7 +52,9 @@ const EYE = `用人眼逐處檢查(一定要看全解析度的放大截圖,
- 穿插與遮擋:角色之間、角色和道具不互相穿透;前後關係正確。
- 畫面:主體夠大(有情緒、對話、表情戲的鏡頭,主角至少佔畫面高度 35%,看得清臉;只有刻意的遠景建立鏡頭例外)、沒有無用途的大片空白;
字不壓主體;字幕要把整張圖縮到手機寬度(約 390px 寬)也讀得出來:字高至少畫面高度 4.5%、有描邊或半透明底;沒有色帶、髒污、破圖、閃格、跳格;轉場每個接縫都有。
-- 動作:有預備動作與餘韻、不機械;同一鏡內造型不跳動(例如眼鏡突然變墨鏡)。`;
+- 動作:有預備動作與餘韻、不機械;同一鏡內造型不跳動(例如眼鏡突然變墨鏡)。**動作只能從連續影格判斷**:每個動作(拿、轉身、坐下、跳、表情變化、道具移動)
+ 都要看 12fps 的連續 strip,找:一格就換姿勢/表情(沒有中間格)、道具瞬移、該動的手不動、整個人僵硬平移或旋轉、超過 1 秒完全靜止的表演鏡頭。
+- 不要用閃白、轉場或鏡頭切走去蓋掉做不到的動作;做不到就在共用角色定義新增姿勢或換一個做得到的演法。`;
const QA_OUT = (file: string, extra = '') => `寫 ${file}(JSON):${extra}
"needs_user": [ { "kind": "lyrics|audio|image|text|other", "issue": "缺什麼、為什麼導演自己做不到" } ] ← 只有必須由使用者提供的東西才放這裡,這類不算缺陷、不要放進問題清單
@@ -65,6 +77,13 @@ ${p.brief}
1. analyze.py 已跑完:讀 analysis/report.json,打開 analysis/sheet_1fps.jpg 與 sheet_scenes.jpg 實際看。
2. 寫 analysis/STYLE.md:第一行寫媒材;把 shot_details 整理成鏡頭清單表;配色與色彩弧線、角色造型語言、剪接、轉場、敘事結構、字幕用法;
最後列「這支好看的 3–5 個關鍵」。
+2b. **找參考片的高潮(起雞皮疙瘩的那 1–2 刻)**:report.json 的 audio.peak_candidates(音樂蓄力後爆發的時間點)與 flashes(閃白格)只是線索;
+ 對每個候選用 clip_strip.py 抽前 2 秒到後 2 秒的 12fps 連續影格(不加 --vs)存成 analysis/peak_<n>.jpg,打開看,確認真正的爆點。
+ 寫 analysis/peaks.json:[ { "id": "P1", "from": 24.0, "hit": 26.0, "to": 29.0, "strip": "analysis/peak_1.jpg",
+ "build": "爆發前怎麼堆張力(畫面、運鏡、音樂)", "hold": "爆發前有沒有停住或安靜、多久", "hit_what": "爆發那一格發生什麼(構圖、色彩、主體大小、畫面密度)",
+ "after": "爆發後停多久、怎麼收", "sound": "音樂與音效在做什麼", "techniques": ["白閃引信", "布幕揭開", "群眾填滿畫面", "…"],
+ "why_it_works": "一句話:為什麼這一刻打得到人" } ]。沒有音樂的參考片也要找出最強的 1 刻(笑點爆發、揭露、反轉)。
+ STYLE.md 加一節「高潮」摘要 peaks.json。
3. 讀 ${SKILL}/styles/*.md(跳過 _TEMPLATE.md 與 _disabled/;目前只做 2D)。參考片是 3D 時選最接近的 2D 風格並在 why 明說。
依辨識特徵打分選風格與 engine,寫 analysis/route.json(含 medium)。都不符合時選最接近的 engine,new_style_proposed: true,
並把建議的風格檔寫在 analysis/proposed_style_<name>.md(skills 目錄唯讀)。使用者指定風格或工具時以使用者為準。`,
@@ -82,6 +101,13 @@ ${p.brief}
- 參考片有歌詞字幕 → { "id": "lyrics", "kind": "lyrics", "label": "歌詞文字", "why": "卡拉 OK 字幕;貼上純文字即可,系統會自動對時" }
- 使用者要用自家角色、Logo、產品照 → kind image,label 寫清楚。
plan.json 寫 required_inputs 陣列(沒有就空陣列)。使用者沒提供前,核准按鈕會被擋住,使用者可以提供或選擇略過。
+${WOW}
+3b. **先設計高潮,再排其他鏡頭**:讀 analysis/peaks.json,寫 plan.peaks(每個參考高潮對應一個,片長短可以只做 1 個):
+ { "id": "P1", "ref_peak": "P1", "shots": ["S8","S9"], "build_from_s": 21.5, "hold_s": [23.6, 24.0], "hit_s": 24.0, "hold_after_s": 1.5,
+ "build": "…", "hit": "爆發那一格的畫面(主體、大小、構圖、色彩、密度)", "after": "…", "sound": "蓄力/安靜/撞擊/音樂落點",
+ "techniques": ["參考用的手法,一個都不少", "+ 我們多加的"], "emotion": "觀眾在這一刻應該感受到什麼", "key_frame": "out/check/key_1.jpg" }
+ 爆點要落在音樂的重拍或段落起點(hit_s 對拍)。peaks 裡的鏡頭在 shots 標 "hero": true,它們的 action 要寫到格的層級(預備、爆發、停住)。
+ 其他鏡頭的任務是把觀眾帶到高潮:開場 3 秒內要有鉤子,結尾要收回高潮的情緒(呼應)。
4. 寫 plan.json(CONTRACT.md 格式)與 STORYBOARD.md:logline、look、borrowed_from_reference、角色/產品、每鏡時間、動作、轉場、reads、
素材與音效;逐鏡對照:ref_shot、ref_what、camera(engine 規格、pace 跟參考一致)。平均鏡頭長度、字卡比例、暗調比例與參考接近(±30%)。
5. 角色:plan.characters 每個角色寫清楚造型(輪廓、比例、配色、髮型、服裝、特徵)與 id。
@@ -89,7 +115,8 @@ ${p.brief}
把 rig 複製到 build/assets/(角色檔要能在那裡跑)。**不要自己寫角色定義檔**:接下來每個角色會有一個 agent 同時做。
6. 素材:plan.assets 每一項寫 purpose、kind、query(搜尋關鍵字)與 status:要從外部取得的標 to_fetch、程式畫的標 drawn_in_code、使用者提供的標 user。
**不要自己下載**:接下來有一個素材 agent 同時去抓。旁白片要先生成旁白草稿、用真實長度排每鏡時間(這一步你自己做)。
-7. 風格定調畫面:這一輪不用做;在 plan.style_frames 先寫好 3–4 個要畫的畫面(路徑 out/check/style_<n>.jpg,對應哪一鏡、要表現什麼),角色與素材好了之後你會接著畫。
+7. 風格定調畫面:這一輪不用做;在 plan.style_frames 先寫好要畫的畫面,**最前面是每個高潮的關鍵畫面對照圖 out/check/key_<n>_vs_ref.jpg**,
+ 後面 2–3 張 out/check/style_<n>.jpg(對應哪一鏡、要表現什麼)。角色與素材好了之後你會接著畫。
8. open_questions 只放真的需要使用者決定的事(最多 4 個),缺素材的事寫在 required_inputs、不要只寫在問題裡。`,
// ---------- pre-production helpers that run in parallel after the plan core ----------
@@ -118,8 +145,13 @@ ${ENGINE(p)}
角色 agent 與素材 agent 已經做完(結果:${JSON.stringify(p.results)})。
1. 把 assets/fetched.json 合併進 plan.json 的 assets(file、source、license、attribution、status);抓不到的改用替代方案並更新該項。
2. 看每個角色的 out/check/cast/pre_*.jpg;明顯不符合企劃或拼接感的地方直接改角色檔(角色 agent 沒做的角色,你自己做)。
-3. 照 plan.style_frames 在 build/ 渲染 3–4 張全解析度關鍵畫面到 out/check/style_*.jpg(用真正的角色與素材),和對應參考鏡頭並排看,到水準才交出。
-4. 更新 plan.json(style_frames、assets)與 STORYBOARD.md;鏡頭內容除非必要不要改。
+3. **高潮關鍵畫面(最重要)**:每個 plan.peaks 在 build/ 用真正的角色、素材、光影、特效,把爆發那一格做到**成片品質**存成 key_frame(全解析度),
+ 再做 out/check/key_<n>_vs_ref.jpg:左邊參考片 hit 那一格(ffmpeg 從 analysis 的 source/proxy 抽)、右邊我們的,同高並排。
+ 打開並排圖誠實比較:主體大小、畫面密度、光影、色彩衝擊、情緒。**我們的明顯比較弱就繼續改**(加密度、加光、放大主體、改構圖),不要交出比參考片弱的關鍵畫面。
+ 在 plan.peaks[].key_frame_note 寫一句自評(哪裡已經贏、哪裡還輸)。使用者核准企劃時會先看這幾張。
+4. 照 plan.style_frames 其餘項目渲染 2–3 張 out/check/style_*.jpg(用真正的角色與素材),和對應參考鏡頭並排看,到水準才交出。
+5. 更新 plan.json(style_frames:key_*_vs_ref.jpg 放最前面;assets)與 STORYBOARD.md;鏡頭內容除非必要不要改。
+${WOW}
${EYE}`,
replan: (p) => `${HEADER(p)}
@@ -128,7 +160,8 @@ ${EYE}`,
使用者的意見:
${p.message}
-修改 plan.json 與 STORYBOARD.md(version +1,changelog),必要時補抓素材、重畫受影響的定調畫面。不要開始生成。逐條回報怎麼處理;做不到的直說並給替代方案。`,
+修改 plan.json 與 STORYBOARD.md(version +1,changelog),必要時補抓素材、重畫受影響的定調畫面(改到高潮就重做 key_<n>_vs_ref.jpg)。不要開始生成。逐條回報怎麼處理;做不到的直說並給替代方案。
+改動如果犧牲了參考片的核心(例如雙人故事改成獨角戲、拿掉高潮),在回報裡明講這個取捨。`,
// ---------- production: setup → cast gate → shot line → assemble ----------
setup: (p) => `${HEADER(p)}
@@ -140,7 +173,11 @@ ${ENGINE(p)}
全片規格一開始就定好、寫進共用檔(最後評審最常退回的就是這些):
- 字幕層:字高 ≥ 畫面高度 5%、粗描邊(1080p 下 ≥ 8 px)加下陰影或半透明底條,壓在白色/淺色物件上也讀得出來;縮到 390 px 寬要能一眼讀出。
- 片尾:不要在最後幾格硬切全黑;要黑就用 ≥ 0.4 秒淡出,字幕跟著淡出。
+ - 質感收尾層(全片共用、蓋在最上面):照參考片的質感加紙紋/顆粒、暗角、調色(色彩弧線每段一組),爆點加光暈(bloom);
+ 參考片有紙紋或手繪抖動就**不准拿掉**(那是它的質感,不是雜訊)。
+ - hero 鏡頭(plan.peaks)的特製素材先準備好:特製姿勢、變形臉、衝擊格、粒子、光芒,寫進共用角色定義或共用特效檔,讓製作 agent 直接呼叫。
- 混音:旁白約 -16 LUFS;配樂在旁白下約低 10–14 dB,但在沒有旁白的空檔(字卡、停頓笑點)要聽得到(約 -24 ~ -28 dBFS RMS),不要用過強的 sidechain 把音樂壓到消失;做完量一次空檔的音量。
+ - 高潮音效:plan.peaks 的 sound(爆點前的安靜或抽空、蓄力上升音、落在 hit_s 的撞擊/音樂重拍)在共用混音裡先放好。
每個鏡頭各自一個檔案(painted-animation:src/scenes/<shot>.js;hyperframes:compositions/<shot>.html),總檔先把全部鏡頭的引用都掛好,
讓製作 agent 只需要改自己的鏡頭檔,不會互相衝突。
2. **角色**:用 engine 的角色系統做出每個角色(2D 向量風格一律用 ${SKILL}/assets/vector_rig/ 的骨架+一體輪廓角色,不准用分開的形狀拼角色;
@@ -193,7 +230,11 @@ ${ENGINE(p)}
- 同時有好幾個製作 agent 在渲染:預覽只渲染需要的幾格(stills/strip),不要反覆整段渲染,也不要開大量平行 worker。
- 只改自己的鏡頭檔;共用檔(角色、配色、總檔)唯讀,發現共用檔有問題寫進 out/check/shots/${p.chunk.id}.done.json 的 notes,不要改。
- 角色一律呼叫共用角色定義,造型、比例、配色和設定圖一致;不准在鏡頭裡自己畫手臂、手、身體。
-- 每一鏡做完就渲染檢查(不要全部做完才看):stills(開頭/中間/結尾)與重要動作的 strip,存成 out/check/shots/<shot>_sheet.jpg,
+- **hero 鏡頭**(plan.shots 裡 "hero": true,屬於 plan.peaks):照 plan.peaks 的 build/hit/after 做到格的層級;可以用特製姿勢、誇張變形、衝擊格、smear、
+ 光芒、粒子、鏡頭震動(需要新的角色姿勢或變形臉就在 notes 寫 "status": "shared" 請導演加進共用角色定義,不要在鏡頭裡疊畫手臂或身體)。
+ 做完用 clip_strip.py 把這段和參考高潮(analysis/peaks.json 的 from–to)並排成 out/check/shots/<shot>_peak_vs_ref.jpg,打開比:我們的爆點不如參考片震撼就繼續加,不要交。
+${WOW}
+- 每一鏡做完就渲染檢查(不要全部做完才看):stills(開頭/中間/結尾)與**每個動作 12fps 的連續 strip**,存成 out/check/shots/<shot>_sheet.jpg,
並把每個角色裁切成全解析度 out/check/shots/<shot>_crop_*.png,自己打開看。
${EYE}
- **每一鏡做完、自己檢查過,就立刻寫 out/check/shots/<shot>.done.json**:{ "id": "S1", "sheet": "…", "crops": ["…"], "notes": "…" },
@@ -210,6 +251,10 @@ ${EYE}
3. 第 2 輪以後:先讀 out/check/shots/${p.chunk.id}.fixes.json,逐項用修改後的截圖核對是否真的修好;沒修好的直接列回問題。
${EYE}
另外:動作與運鏡是否照企劃、和參考鏡頭的手法一致;和角色設定圖比對造型一致性。
+ **動作**:每個動作都要看 12fps 連續影格(製作 agent 的 strip 不夠就自己用預覽指令的 strip 模式或 hf_frames --range 截)。一格換姿勢、道具瞬移、
+ 該動不動、僵硬整塊旋轉、表演鏡頭超過 1 秒完全靜止,都是 blocker。
+ **hero 鏡頭**(plan.peaks):打開 <shot>_peak_vs_ref.jpg(沒有就自己用 clip_strip.py 做),參考在上、我們在下逐格比。
+ 爆點比參考片弱(主體小、畫面空、沒有停住、被閃白蓋掉、沒有預備或衝擊)是 blocker,寫清楚差在哪、要加什麼。
4. ${QA_OUT(p.out || `out/check/shots/${p.chunk.id}.review.json`, '{ "shots": [ { "id": "S1", "pass": true|false, "issues": [ { "time": 1.2, "where": "畫面位置", "issue": "…", "fix": "…" } ] } ], "verified_fixes": [ { "issue": "…", "fixed": true|false } ], "needs_user": [] }')}
嚴格:專業動畫導演會退回的就不過。`,
@@ -242,8 +287,10 @@ ${ENGINE(p)}
## 步驟:組裝成片(所有鏡頭段都已通過審查)
1. 讀 build/production.json 與各段 out/check/shots/*.fixes.json 裡 "status": "shared" 的項目,先修共用檔的問題。
2. 接起全部鏡頭:轉場、配樂、音效、字幕(歌詞字幕只能用 analysis/lyrics/subs.lrc 或 inputs 的 LRC;沒有就不上歌詞字幕)。
-3. 正式渲染 out/video.mp4;跑 python ${SKILL}/scripts/compare.py ${p.dir};檢查每個接縫(前後 0.5 秒 strip)。
-4. 回報:長度、解析度、每鏡一句話、還不完美或暫代的部分。`,
+3. 正式渲染 out/video.mp4;確認有音軌(ffprobe;沒有就把混音 mux 進去)。跑 python ${SKILL}/scripts/compare.py ${p.dir};檢查每個接縫(前後 0.5 秒 strip)。
+4. 跑 python ${SKILL}/scripts/motion_check.py out/video.mp4 --out out/check/motion:片中黑格、片尾硬切黑、意外的長時間靜止都要修掉再交。
+5. 每個 plan.peaks 用 clip_strip.py 做 out/check/peak_<n>_vs_ref.jpg(我們的 build_from_s–hit_s+hold_after_s 對參考 peaks.json 的 from–to),打開比;明顯輸參考片就先修。
+6. 回報:長度、解析度、每鏡一句話、還不完美或暫代的部分。`,
// ---------- final panel ----------
critique: (p) => `你是這支影片的**獨立評審**(資深美術總監),不是製作者;你沒參與製作,沒有任何理由護短。
@@ -251,23 +298,36 @@ ${ENGINE(p)}
使用者需求:${p.brief}
${RULES}
-你只能讀、量、看,並寫 out/check/critique.json 與 critique.md;不要修改其他檔案。每個鏡頭在製作時已經過鏡頭審查,你的重點是整支片:
-連戲(角色造型、顏色、道具跨鏡一致)、節奏、接縫與轉場、音畫同步、字幕、開場與結尾、整體是否到參考片水準。
-
-1. 參考片:analysis/report.json 與 sheet 圖。
-2. 成片:ffmpeg 每 0.5 秒抽一格做總覽到 out/check/critic/,全部打開;每個接縫抽前後 0.5 秒的 strip;可疑處抽全解析度放大。
-3. 跑 compare.py,看 compare_all.jpg。
-4. 第 2 輪以後:先讀 out/check/fixes.json,**逐項核對上一輪的必修是否真的修好**(看它附的 before/after,再自己在成片同一秒抽格確認);
- 說修好但沒修好的,原樣列回 must_fix 並註明「上一輪已列,仍未修好」。
+你只能讀、量、看,並寫 out/check/critique.json 與 critique.md;不要修改其他檔案。每個鏡頭在製作時已經過鏡頭審查(他們只抓瑕疵)。
+**你的工作是判斷這支片能不能讓人起雞皮疙瘩、有沒有到參考片的水準**,不是確認「沒有錯」。
+${WOW}
+
+1. 參考片:analysis/report.json、peaks.json、sheet 圖。
+2. **高潮對決(最先做、最重要)**:plan.peaks 每一個,用 clip_strip.py 做 out/check/critic/peak_<n>_vs_ref.jpg
+ (我們:build_from_s 到 hit_s+hold_after_s;參考:peaks.json 的 from–to),打開逐格比:鋪陳、屏息、爆點那一格、停住、畫面密度、主體大小、聲音落點
+ (用 ffmpeg 的 astats/ebur128 量我們爆點前後的音量變化,對照參考)。判定 ours_better / equal / ref_better 並寫具體理由。
+ **ref_better 就不能通過**:在 must_fix 寫出要加什麼才會贏(具體到手法、格數、大小)。
+3. 成片:ffmpeg 每 0.5 秒抽一格做總覽到 out/check/critic/,全部打開;每個接縫抽前後 0.5 秒的 strip;
+ 每個動作用 clip_strip.py 抽 12fps 連續影格看(跳格、瞬移、該動不動、僵硬);可疑處抽全解析度放大。
+ 跑 python ${SKILL}/scripts/motion_check.py out/video.mp4 --out out/check/critic/motion,打開它產生的每張 strip。
+4. 跑 compare.py,看 compare_all.jpg;逐鏡打分(CLAUDE.md 要求每鏡 ≥ 4)。
+5. 第 2 輪以後:先讀 out/check/fixes.json,**逐項核對上一輪的必修是否真的修好**(看它附的 before/after,再自己在成片同一秒抽格確認;動作類的修正一定要看 12fps 連續影格,不是單張);
+ 說修好但沒修好的,原樣列回 must_fix 並註明「上一輪已列,仍未修好」。上一輪 nice_to_have 裡觀眾看得出來、改起來不難的項目還在的話,這輪升級成 must_fix。
${EYE}
-5. 寫 out/check/critique.json:
- { "pass": false, "scores": { "開場":1-5, "畫面質感":1-5, "角色":1-5, "運鏡":1-5, "構圖":1-5, "瑕疵":1-5, "字幕標題":1-5, "節奏連戲":1-5 },
+6. 寫 out/check/critique.json:
+ { "pass": false,
+ "peaks": [ { "id": "P1", "ours": [21.5, 25.5], "ref": [24.0, 29.0], "strip": "out/check/critic/peak_1_vs_ref.jpg", "verdict": "ours_better|equal|ref_better", "why": "具體" } ],
+ "scores": { "高潮震撼":1-5, "開場鉤子":1-5, "畫面質感":1-5, "角色表演":1-5, "動作流暢":1-5, "運鏡":1-5, "構圖密度":1-5, "瑕疵":1-5, "字幕標題":1-5, "節奏連戲":1-5, "聲音":1-5 },
+ "score_notes": { "高潮震撼": "給這個分數的證據(秒數+看到什麼)", "…": "…" },
+ "shots": [ { "id": "S1", "score": 1-5, "why": "一句話" } ],
"must_fix": [ { "shot": "S6", "time": 12.3, "issue": "具體問題", "fix": "具體改法" } ],
"needs_user": [ { "kind": "lyrics|audio|image|text|other", "issue": "缺什麼(例如:沒有歌詞文字,無法上卡拉OK字幕)" } ],
"verified_fixes": [ { "issue": "…", "fixed": true|false } ],
"nice_to_have": [], "summary": "一句話" }
+ **分數以參考片為尺**:5 = 比參考片好;4 = 和參考片同水準(放在一起看不出哪支比較陽春);3 = 看得出比參考片陽春;2 = 明顯差一截;1 = 壞掉。
+ 每一項都要在 score_notes 寫證據;不准整排給同一個分數交差——4 分表示你願意把它和參考片並排給人看。
規則:must_fix 只放導演能修的;缺使用者素材一律放 needs_user、不要放 must_fix(也不要因此扣分);
- 任何一項 < 4 必須有對應 must_fix;沒有 must_fix 時 pass 才能是 true。
+ 任何一項 < 4、任何一鏡 < 4、任何高潮 ref_better,都必須有對應 must_fix;沒有 must_fix 時 pass 才能是 true。
最後用 3–5 行繁體中文回報結論。`,
revise: (p) => `${HEADER(p)}
@@ -279,7 +339,9 @@ ${p.message}
逐項修改(只動相關鏡頭;共用檔的改動要檢查所有用到的鏡頭),重新輸出 out/video.mp4,同步更新 plan.json(version +1、changelog)。
- 角色的動作一律改 pose 參數(手臂角度、手型、表情)或共用角色定義;**不准在鏡頭裡另外疊畫手臂、手、身體**(會產生肩膀接縫、描邊伸進衣服)。
需要角色做 rig 做不到的動作,就在共用角色定義新增姿勢或手型,再重截設定圖確認。
-- 改完用 hf_frames 截改動處前後 0.5 秒的全解析度畫面,照人眼清單自己看過再交。
+- 改完用 hf_frames 截改動處前後 0.5 秒的全解析度畫面,照人眼清單自己看過再交;動作類的修正附 12fps 連續影格(clip_strip.py),不是單張。
+- 修到高潮(plan.peaks)的,重做 clip_strip.py 對參考的並排圖,確認我們的爆點不輸參考片。
+- 改完重跑 motion_check.py out/video.mp4 --out out/check/motion,確認沒有新的黑格、硬切黑。
${EYE}
**每一項都要附證據**,寫 out/check/fixes.json:
[ { "issue": "…", "shot": "S6", "time": 12.3, "change": "改了什麼", "before": "out/check/fixes/<n>_before.png", "after": "…_after.png", "status": "fixed|cannot" } ]
diff --git a/app/server/types.ts b/app/server/types.ts
index 5a3c266..4ac5984 100644
--- a/app/server/types.ts
+++ b/app/server/types.ts
@@ -15,7 +15,8 @@ export interface Production {
export interface SharedItem { status: 'shared'; issue: string; shot?: string; character?: string; [k: string]: unknown }
export interface ShotEntry { id: string; pass?: boolean; issues?: Issue[] }
export interface ChunkReview { shots?: ShotEntry[]; verified_fixes?: unknown[]; needs_user?: NeedRequest[]; pass?: boolean; issues?: Issue[] }
-export interface Critique { must_fix?: { shot?: string; time?: number; issue: string; fix?: string }[]; needs_user?: NeedRequest[] }
+export interface PeakVerdict { id: string; ours?: number[]; ref?: number[]; strip?: string; verdict?: 'ours_better' | 'equal' | 'ref_better'; why?: string }
+export interface Critique { must_fix?: { shot?: string; time?: number; issue: string; fix?: string }[]; needs_user?: NeedRequest[]; peaks?: PeakVerdict[] }
type NoVars = Record<never, never>;
diff --git a/app/shared/types.ts b/app/shared/types.ts
index 37566b6..a5ba6c0 100644
--- a/app/shared/types.ts
+++ b/app/shared/types.ts
@@ -15,6 +15,8 @@ export type Rounds = Record<RoundKey, number>;
export interface Config extends Rounds {
builders: number;
maxAgentsGlobal: number;
+ maxReviews: number;
+ overlapCast: boolean;
}
export interface Reference { type: 'file' | 'url'; src: string }
diff --git a/app/web/src/Project.tsx b/app/web/src/Project.tsx
index fac12c9..f6289e6 100644
--- a/app/web/src/Project.tsx
+++ b/app/web/src/Project.tsx
@@ -74,7 +74,7 @@ export function Project({ id }: { id: string }) {
{preProd && (s.requiredInputs || []).length > 0 && <RequiredInputs id={id} s={s} editable top />}
{tabs.length > 1 && <div className="tabs" role="tablist">{tabs.map((t) => <button key={t.k} role="tab" aria-selected={cur === t.k} className={cur === t.k ? 'on' : ''} onClick={() => setTab(t.k)}><I n={t.ico} />{t.label}{t.badge && <span className={`tb ${t.badge[1]}`}>{t.badge[0]}</span>}</button>)}</div>}
<div key={cur} className="fade-in">
- {cur === 'result' && <Result s={s} file={file} />}
+ {cur === 'result' && <Result s={s} file={file} onZoom={onZoom} />}
{cur === 'pipe' && <Pipeline s={s} file={file} onZoom={onZoom} />}
{cur === 'pipe' && !job.pipeline?.phase && s.checks.length > 0 && <div className="card"><div className="card-h"><h2>審查影格</h2></div><div className="gallery">{s.checks.slice(0, 12).map((c) => <img key={c} className="shot-img" src={file(c)} onClick={() => onZoom(file(c))} />)}</div></div>}
{cur === 'plan' && <Plan s={s} file={file} job={job} onTag={setTag} onZoom={onZoom} />}
@@ -452,7 +452,7 @@ function Pipeline({ s, file, onZoom }: { s: SnapshotView; file: FileUrl; onZoom:
// ---------- result: review the video like an editor — pause anywhere, type the note right there, send them all at once ----------
const tc = (x: number) => { const m = Math.floor(x / 60), s = x - m * 60; return `${m}:${s < 10 ? '0' : ''}${s.toFixed(1)}`; };
type Note = { id: number; t: number; text: string; thumb: string | null };
-function Result({ s, file }: { s: SnapshotView; file: FileUrl }) {
+function Result({ s, file, onZoom }: { s: SnapshotView; file: FileUrl; onZoom: Zoom }) {
const id = s.job.id, key = `notes:${id}`, v = useRef<HTMLVideoElement>(null), input = useRef<HTMLTextAreaElement>(null);
const [t, setT] = useState(0), [d, setD] = useState(0), [text, setText] = useState(''), [pin, setPin] = useState<number | null>(null);
const [notes, setNotes] = useState<Note[]>(() => { try { return JSON.parse(localStorage.getItem(key) ?? 'null') || []; } catch { return []; } });
@@ -508,17 +508,23 @@ function Result({ s, file }: { s: SnapshotView; file: FileUrl }) {
<button className="btn primary" disabled={!canSend || sending || notes.some((n) => !n.text.trim())} onClick={send}>{sending ? <span className="spin-ring" /> : <I n="up" s={2.4} />}送出 {notes.length} 則修改</button>
</div>
</div>}
- {s.critique && <Critique c={s.critique} onSeek={seek} id={id} stage={s.job.stage} />}
+ {s.critique && <Critique c={s.critique} onSeek={seek} id={id} stage={s.job.stage} file={file} onZoom={onZoom} />}
</section>
);
}
-function Critique({ c, onSeek, id, stage }: { c: CritiqueData; onSeek?: (t: number) => void; id: string; stage: Stage }) {
+const VERDICT = { ours_better: ['贏過參考片', 'ok'], equal: ['和參考片同級', 'ok'], ref_better: ['輸給參考片', 'bad'] } as const;
+function Critique({ c, onSeek, id, stage, file, onZoom }: { c: CritiqueData; onSeek?: (t: number) => void; id: string; stage: Stage; file: FileUrl; onZoom: Zoom }) {
const sc = Object.entries(c.scores || {}), must = (c.must_fix || []).filter((m): m is MustFix => !!m), [busy, setBusy] = useState(false);
const fix = async () => { setBusy(true); try { await api.message(id, `照獨立評審列的 ${must.length} 項必修全部修改:\n` + must.map((m, i) => `${i + 1}. [${m.shot || '全片'}${m.time != null ? ' ' + m.time + 's' : ''}] ${m.issue}`).join('\n')); } finally { setBusy(false); } };
return (
<div className="critique">
<div className="row"><div className="avatar-ai critic"><I n="mag" /></div><b>獨立評審</b><span className="grow" /><span className={`cap ${c.pass ? 'ok' : 'bad'}`}>{c.pass ? <><I n="check" s={2.4} />通過</> : `${must.length} 項必修`}</span></div>
{c.summary && <p className="small muted" style={{ margin: '10px 0 0' }}>{c.summary}</p>}
+ {(c.peaks || []).length > 0 && <div style={{ marginTop: 12 }}><div className="sub-h" style={{ marginTop: 0 }}>高潮對決(上:參考片,下:我們)</div>
+ {c.peaks!.map((p) => { const [label, cls] = VERDICT[p.verdict || 'equal'] || VERDICT.equal; return <div key={p.id} style={{ marginBottom: 10 }}>
+ <div className="row"><span className="tagc">{p.id}{p.ours?.length ? ` · ${p.ours[0]}–${p.ours[1]}s` : ''}</span><span className={`cap ${cls}`}>{label}</span></div>
+ {p.why && <p className="small muted" style={{ margin: '6px 0' }}>{p.why}</p>}
+ {p.strip && <img className="shot-img" src={file(p.strip)} onClick={() => onZoom(file(p.strip!))} />}</div>; })}</div>}
{sc.length > 0 && <div className="scores">{sc.map(([k, v]) => <div key={k} className={`score ${v < 4 ? 'low' : ''}`}><div className="row"><span>{k}</span><b>{v}</b></div><div className="pips">{[1, 2, 3, 4, 5].map((n) => <i key={n} className={n <= v ? 'on' : ''} />)}</div></div>)}</div>}
{must.length > 0 && <ul className="issues" onClick={(e) => (e.target as Element).closest('li')?.classList.toggle('open')}>{must.map((m, i) => <li key={i} className={typeof m.time === 'number' ? 'seekable' : ''} onClick={() => typeof m.time === 'number' && onSeek?.(m.time)}><span className="tagc">{m.shot || '全片'}{typeof m.time === 'number' ? ` · ${m.time}s` : ''}</span><span>{m.issue}{m.fix && <span className="faint"> → {m.fix}</span>}</span></li>)}</ul>}
{!c.pass && must.length > 0 && ['done', 'error'].includes(stage) && <div className="row" style={{ marginTop: 12 }}><button className="btn sm primary" disabled={busy} onClick={fix}>{busy ? <span className="spin-ring" /> : <I n="wand" />}照評審的 {must.length} 項全部修</button><span className="small faint">或在上方影片時間軸自己標要改的地方</span></div>}
diff --git a/app/web/src/types.ts b/app/web/src/types.ts
index aeda823..80b890f 100644
--- a/app/web/src/types.ts
+++ b/app/web/src/types.ts
@@ -30,7 +30,8 @@ export type Report = {
};
export type Route = { engine?: string; style?: string; medium?: string; confidence?: number; why?: string[] };
export type MustFix = { shot?: string; time?: number | null; issue: string; fix?: string };
-export type Critique = { pass?: boolean; summary?: string; scores?: Record<string, number>; must_fix?: (MustFix | null)[] };
+export type PeakVerdict = { id: string; ours?: number[]; ref?: number[]; strip?: string; verdict?: 'ours_better' | 'equal' | 'ref_better'; why?: string };
+export type Critique = { pass?: boolean; summary?: string; scores?: Record<string, number>; must_fix?: (MustFix | null)[]; peaks?: PeakVerdict[] };
export type Production = { characters?: { id: string; name?: string }[] };
export type LyricLine = { start?: number; end?: number; text: string; match: number };
export type Lyrics = { lines?: LyricLine[] };