Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.
Edit video đợt 2: REST, tab UI, MCP, sửa bằng lời, sửa phụ đề chồng chữ
Lumtek2cf76ad26151
diff --git a/README.md b/README.mdindex 1888492..2cd2241 100644--- a/README.md+++ b/README.md@@ -33,6 +33,7 @@| 🤖 **Built for AI agents** | MCP server, CLI and REST. Claude, Codex or any agent can create a video, submit a scene, preview, render, schedule, and drop the MP4 into a Google Drive folder. || ⏱️ **3 seconds to 10 minutes** | Type `90` or `1:30`. Long videos are split into scenes, and every frame is a pure function of time, so renders are deterministic. || 🔤 **Typography that holds up** | 25 font families with full Vietnamese diacritics. Missing glyphs, overflowing text and tiny type are flagged before rendering. |+| ✂️ **Edit your own footage** (new) | Drop in a talking-head clip you filmed and pick an edit style: LumReels transcribes it (Whisper large-v3, Vietnamese), lets Claude cut the pauses, false starts and retakes, then adds word-timed captions, punch-in zooms, a 9:16 reframe that follows your face, your music ducked under your voice and sound effects, mixed to −14 LUFS. Revise in plain words ("cut the first 3 seconds", "fewer zooms") without re-analysing. One-time setup: `node edit/setup.mjs` (Python 3.10–3.12, ~6 GB with the speech model). UI tab, `node cli.mjs edit`, REST `/api/edits`, MCP `edit_video`. |## Style librarydiff --git a/README.vi.md b/README.vi.mdindex 3337394..7d3ec65 100644--- a/README.vi.md+++ b/README.vi.md@@ -33,6 +33,7 @@| 🤖 **Cho AI agent gọi thẳng** | MCP server, CLI và REST. Claude, Codex hay agent bất kỳ: tạo video, gửi cảnh, xem thử, render, hẹn giờ, chép MP4 ra Google Drive. || ⏱️ **3 giây tới 10 phút** | Gõ `90` hoặc `1:30`. Video dài tự chia cảnh, mỗi khung là hàm thuần theo thời gian nên render ổn định. || 🇻🇳 **Tiếng Việt chuẩn** | 25 họ font có dấu tiếng Việt, tự kiểm font thiếu dấu, chữ tràn khung, chữ quá nhỏ trước khi render. |+| ✂️ **Edit video bạn tự quay** (mới) | Thả clip nói trước máy, chọn kiểu edit: LumReels chép lời (Whisper large-v3 tiếng Việt), Claude cắt chỗ ngập ngừng, nói dở, nói lại, rồi thêm phụ đề theo từng chữ, zoom nhấn, reframe 9:16 theo mặt, nhạc của bạn tự hạ khi nói, tiếng động, chuẩn −14 LUFS. Sửa bằng lời ("bỏ 3 giây đầu", "zoom ít lại") mà không phân tích lại. Cài một lần: `node edit/setup.mjs` (Python 3.10–3.12, ~6 GB gồm model giọng). Tab trên giao diện, `node cli.mjs edit`, REST `/api/edits`, MCP `edit_video`. |## Thư viện mẫudiff --git a/cli.mjs b/cli.mjsindex f4a3e1f..1f80a79 100644--- a/cli.mjs+++ b/cli.mjs@@ -8,7 +8,8 @@// node cli.mjs list [--json]// node cli.mjs show <jobId>// node cli.mjs templates [--json]-// node cli.mjs edit <video> --style <id> [--music file] [--content "dặn thêm"] [--draft] [--llm off] [--json]+// node cli.mjs edit <video> --style <id> [--music file] [--content "dặn thêm"] [--names "Lumfin, …"] [--draft] [--llm off] [--json]+// node cli.mjs edit-revise <editId> "<lời sửa>" · edit-show <editId> · edit-run <editId>import fs from 'node:fs';import path from 'node:path';import { createJob, runJob, renderJob, runDue, listJobs, readJob, readLog, jobPaths, loadCatalog, hasGuidance, exportOutput } from './generator/jobs.mjs';@@ -46,10 +47,13 @@ function usage() {list [--json] danh sách jobshow <jobId> trạng thái + log + đường dẫntemplates [--json] mẫu nào đã có guidance- edit <video> --style <id> [--music file] [--content "dặn thêm"] [--draft] [--llm off] [--json]+ edit <video> --style <id> [--music file] [--content "dặn thêm"] [--names "tên riêng, …"] [--draft] [--llm off] [--json]dựng lại video tự quay theo thẻ kiểu edit (edit-styles/<id>.md) → edits/<id>/out.mp4cắt ngập ngừng/nói lại (LLM), phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ, sfx, −14 LUFS.- --draft: phụ đề PIL vẽ thẳng (nhanh), mặc định phụ đề HyperFrames. Cài trước: node edit/setup.mjs`);+ --draft: phụ đề PIL vẽ thẳng (nhanh), mặc định phụ đề HyperFrames. Cài trước: node edit/setup.mjs+ edit-revise <editId> "<lời>" sửa bằng lời ("bỏ 3 giây đầu", "zoom ít lại") rồi render lại, không phân tích lại+ edit-show <editId> [--json] trạng thái, tiến độ, chữ LLM đã sửa, log+ edit-run <editId> chạy 1 edit đã tạo (MCP/REST dùng)`);}const readContent = (c) => (fs.existsSync(c) && fs.statSync(c).isFile() ? fs.readFileSync(c, 'utf8') : c);@@ -82,16 +86,37 @@ try {else if (done.error) console.log('Lỗi: ' + done.error);}process.exit(done.status === 'error' ? 1 : 0);- } else if (cmd === 'edit') {- if (!pos[0]) { usage(); process.exit(2); }- const { editVideo } = await import('./edit/pipeline.mjs');- const r = await editVideo(pos[0], { style: typeof opt.style === 'string' ? opt.style : 'sach-gon', music: typeof opt.music === 'string' ? opt.music : undefined,- content: typeof opt.content === 'string' ? readContent(opt.content) : undefined, draft: !!opt.draft, llm: opt.llm === 'off' ? 'off' : 'on',- log: opt.json ? () => {} : console.log });- if (opt.json) out(r);- else console.log(r.ok ? `MP4: ${r.out}-EDL: ${r.edl}-Xem trước: ${path.join(r.dir, 'preview.jpg')}` : 'Lỗi: ' + r.error);+ } else if (cmd === 'edit' || cmd === 'edit-run' || cmd === 'edit-revise' || cmd === 'edit-show') {+ const E = await import('./edit/jobs.mjs');+ const log = opt.json ? () => {} : console.log;+ let r;+ if (cmd === 'edit-show') {+ const v = pos[0] && E.editView(pos[0]);+ if (!v) { console.error('không thấy edit ' + (pos[0] || '')); process.exit(1); }+ if (opt.json) out(v);+ else {+ console.log(`${v.id} · ${v.status}${v.step ? ` · ${v.step} ${v.pct}%` : ''}`);+ console.log(`MP4: ${v.files.out || '-'}`);+ if (v.fixes.length) console.log('Chữ LLM sửa: ' + v.fixes.map((f) => `${f.heard} → ${f.text || '(ẩn)'}`).join(', '));+ console.log((v.log || []).slice(-8).join('\n'));+ }+ process.exit(0);+ }+ if (cmd === 'edit') {+ if (!pos[0]) { usage(); process.exit(2); }+ const job = E.createEdit({ video: pos[0], style: typeof opt.style === 'string' ? opt.style : 'sach-gon', music: typeof opt.music === 'string' ? opt.music : undefined,+ content: typeof opt.content === 'string' ? readContent(opt.content) : undefined, names: typeof opt.names === 'string' ? opt.names : undefined,+ draft: !!opt.draft, llm: opt.llm === 'off' ? 'off' : 'on' });+ r = await E.runEditJob(job.id, { log });+ } else if (cmd === 'edit-run') {+ if (!pos[0]) { usage(); process.exit(2); }+ r = await E.runEditJob(pos[0], { log });+ } else {+ if (!pos[0] || !pos[1]) { usage(); process.exit(2); }+ r = await E.reviseEditJob(pos[0], pos.slice(1).join(' '), { log });+ }+ if (opt.json) out(E.editView(r.id));+ else console.log(r.ok ? [`edit: ${r.id}`, `MP4: ${r.out}`, `EDL: ${r.edl}`, `Xem trước: ${path.join(r.dir, 'preview.jpg')}`].join('\n') : 'Lỗi: ' + r.error);process.exit(r.ok ? 0 : 1);} else if (cmd === 'render') {if (!pos[0]) { usage(); process.exit(2); }diff --git a/docs/CHI-TIET.md b/docs/CHI-TIET.mdindex e1e91e3..0a51201 100644--- a/docs/CHI-TIET.md+++ b/docs/CHI-TIET.md@@ -48,8 +48,8 @@ Trạng thái: `scheduled → queued → generating → (waiting_agent) → prevNút **Viết lại kịch bản** cạnh ô Nội dung (và `POST /api/rewrite {templateId, content, durationS}` → `{script, notes, engine, usage}`, CLI `node cli.mjs rewrite`, MCP `rewrite_script`): AI đọc §1–§3 và §10 guidance của mẫu, viết lại nội dung thành các ô nội dung đúng giới hạn ký tự, chia cảnh theo thời lượng; giữ ý, số liệu, thương hiệu, CTA; không bịa số liệu thật. Nội dung ≤ 4000 ký tự, tối đa 90 giây/lượt, server chỉ chạy 1 lượt một lúc (cách nhau ≥ 3 giây). Lõi: `generator/rewrite.mjs`.Engine: `api` (có `ANTHROPIC_API_KEY`, model `REWRITE_MODEL`) → `claude` (Claude Code headless `claude -p --tools ""`, không tool, không MCP, chạy trong thư mục tạm trống) → chưa có cả hai thì báo "Chưa cấu hình AI". Ở `auto`, khoá API bị từ chối (401/403) mà máy có Claude Code thì tự chuyển sang `claude` và ghi rõ trong kết quả (`fallbackFrom`).-## Edit video (dựng lại video tự quay) — đợt 1: lõi + CLI-Người dùng đưa video tự quay (nói trước máy), chọn **thẻ kiểu edit**; LumReels tự cắt chỗ ngập ngừng/nói lại, thêm phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ khi nói, tiếng động, chỉnh −14 LUFS. Chưa có UI/REST/MCP (đợt 2).+## Edit video (dựng lại video tự quay)+Người dùng đưa video tự quay (nói trước máy), chọn **thẻ kiểu edit**; LumReels tự cắt chỗ ngập ngừng/nói lại, thêm phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ khi nói, tiếng động, chỉnh −14 LUFS. Có tab **Edit video của bạn** trên giao diện, CLI, REST và MCP; sửa bằng lời rồi render lại mà không phân tích lại.- Cài (một lần, chạy lại được): `node edit/setup.mjs [--cpu]` → venv riêng `edit/.venv` (không đụng Python hệ thống; cần Python 3.10–3.12 + ffmpeg), gói Python (~670 MB), cuBLAS + cuDNN nếu có GPU NVIDIA (~2 GB), model mặt/người MediaPipe (21 MB, kiểm SHA-256), font Be Vietnam Pro TTF (ghép từ `engine/fonts`), whisper **large-v3** (~3 GB, vào `~/.cache/huggingface`). Dòng cuối: `READY` / `NEED_PYTHON` / `NEED_FFMPEG` / `NEED_NETWORK` / `NEED_NPM`.- Chạy: `node cli.mjs edit <video> --style sach-gon|phu-de-nay-mau [--music nhac.mp3] [--content "dặn thêm"] [--draft] [--llm off] [--json]` → `edits/<id>/`.@@ -76,7 +76,15 @@ video ─ edit/ingest.mjs : ffprobe đủ (xoay, VFR, HDR, start_time) + SHA-2- **EDL** (`edit/edl.schema.json`, nguồn sự thật là zod trong `edit/edl.mjs`; `node edit/edl.mjs <edl.json>` để kiểm): `version`, `source` (sha256, xoay, VFR, HDR…), `proxy`, `output`, `keep[]` (đoạn giữ, giây nguồn), `removed[]` (lý do + chữ bị bỏ), `reframe`, `zooms[]`, `captions{style, renderer, maxWords, position, words[], highlights[]}`, `sfx[]`, `music`, `audio{crossfadeMs: 20, keepSourceAudio}`. Mọi mốc là **giây của nguồn**.- Mã AskEditor (MIT) chép vào `edit/askeditor/` (chỉ lõi + clean-cut/captions/qc-check); chỗ sửa ghi trong `edit/askeditor/VENDORED.md`. Python luôn chạy với `-X utf8` (Windows cp1252 làm vỡ chữ Việt). Biến: `LUMEDIT_WHISPER` (mặc định `large-v3`), `FX_DEVICE` (`auto|cuda|cpu`), `EDIT_MODEL` (model Claude, mặc định Sonnet), `LUMEDIT_PYTHON` (Python dùng để tạo venv).- Clip thử tổng hợp (khi chưa có clip người thật): `node edit/test/make-synth.mjs edits/_synth/synth.mp4 [--wide]` (nối hình + giọng sạch của vài job, chèn 1 khoảng lặng 1,6 s và 1 câu nói dở rồi nói lại; ghi kèm `.truth.json`).-- Giới hạn đợt 1: 1 người nói, tiếng Việt; footage có nhạc nền to làm bước nghe lại loại nhiều chữ; reframe từ 1080p ngang phóng cửa sổ 608×1080 lên 1080×1920 (mờ hơn); chưa có sửa EDL bằng lời, UI, MCP.+- **Giao diện**: tab "Edit video của bạn" cạnh "Dựng từ mẫu": kéo thả video (≤ 2 GB), chọn kiểu, nhạc (tổng hợp có sẵn hoặc tải file), ô "tên riêng" (AI dùng để sửa chữ máy nghe sai, ngoài các tên này chỉ sửa chữ vô nghĩa rõ ràng), ô dặn thêm, bản nháp; thanh tiến độ theo 9 bước, video ra, **danh sách chữ AI đã sửa** để người xem lại, ô sửa bằng lời + nút Render lại, các lần sửa, nhật ký. Chưa cài `edit/setup.mjs` thì tab hiện lệnh cài.+- **REST** (`edit/http.mjs`, cùng chống DNS rebinding qua Host như các route khác, thêm chặn `Origin` lạ cho lệnh ghi):+ `GET /api/edit-options` (đã cài chưa, kiểu edit, nhạc) · `GET /api/edits` · `POST /api/edits` multipart (`video` ≤ 2 GB, `music`?, `style`, `musicStyle`?, `content`?, `names`?, `draft`?; ghi thẳng ra `edits/<id>/source.*`, không giữ trong RAM) hoặc JSON `{path, style, music?, content?, names?, draft?}` khi gọi từ máy · `GET /api/edits/:id` (trạng thái, bước, %, log, `fixes`, `revisions`, `checks`) · `POST /api/edits/:id/revise {instruction}` · file `/edits/:id/(out.mp4|preview.jpg|preview-final.jpg|edl.json|versions/out-<n>.mp4)`.+- **Hàng chờ**: mỗi lúc 1 edit chạy trên cả máy (khoá `edits/.edit.lock` có pid, dùng chung cho server, CLI, MCP; tiến trình chết thì khoá tự hết). Hồ sơ `edits/<id>/job.json`: `queued → running → done | error`, `step/pct`. Server khởi động: edit chạy dở bị đánh dấu lỗi để bấm lại.+- **Sửa bằng lời** (`reviseEdit`): LLM đọc lời chép kèm mốc giây BẢN HIỆN TẠI + đề xuất hiện tại → trả đề xuất mới, `cut_output` (giây bản hiện tại, code đổi sang giây nguồn theo keep và nới mép cho trọn chữ) và núm kiểu (`zoomScale`, `zoomMinGap`, `captionsMaxWords`, `musicGainDb`, `pause`, `sfxOff`). Code dựng lại EDL, render từ bước "xem trước". Bản cũ giữ ở `versions/out-<n>.mp4` + `edl-<n>.json`; trạng thái sửa trong `state.json`. LLM sai 2 vòng → báo lỗi, bản cũ giữ nguyên.+- **CLI**: `node cli.mjs edit <video> … [--names "Lumfin, …"]`, `edit-revise <id> "<lời>"`, `edit-show <id> [--json]`, `edit-run <id>`. **MCP**: `edit_video {path, style, music?, notes?, names?, draft?}` (chạy nền, trả editId), `revise_edit {editId, instruction}`, `get_edit {editId?}`.+- **Phụ đề không chồng nhau**: luật thời gian nhóm chữ (giống nhau ở `captions-hf.mjs` và `lumedit.py`): nối khe < 0,4 s, tối thiểu 0,25 s nhưng không bao giờ quá điểm bắt đầu của nhóm sau, nhóm bị ép < 0,1 s gộp vào nhóm sau; kiểm `cardOverlaps` — có chồng là dừng. (Lỗi cũ: chữ nói nhanh 0,22 s bị kéo lên 0,25 s nên "TRÀ" đè "SỮA".)+- **Tốc độ phụ đề HyperFrames** (đo trên 23,8 s, 80 nhóm): 1080p 61 s; `-w 10` 59 s; dựng ở 720p rồi phóng 51 s / 47 s (chữ mờ hơn, chưa dùng). Hướng tăng tốc thật (để sau): chỉ chụp khung có chuyển động (0,2 s đầu mỗi nhóm + khung đổi màu), giữ các khung tĩnh bằng ffmpeg.+- Giới hạn: 1 người nói, tiếng Việt; footage có nhạc nền to làm bước nghe lại loại nhiều chữ; reframe từ 1080p ngang phóng cửa sổ 608×1080 lên 1080×1920 (mờ hơn).## Cổng cho agent**MCP** (stdio): `node mcp/server.mjs` — tool `list_templates`, `get_template`, `rewrite_script`, `create_video` (`durationS` 3–600 hoặc `"1:30"`), `submit_scene`, `preview_job` (trả ảnh), `render_job`, `get_job`, `list_jobs`. Thử: `node scripts/mcp-smoke.mjs`.diff --git a/edit-styles/phu-de-nay-mau.md b/edit-styles/phu-de-nay-mau.mdindex 209f863..5d89217 100644--- a/edit-styles/phu-de-nay-mau.md+++ b/edit-styles/phu-de-nay-mau.md@@ -3,6 +3,7 @@"id": "phu-de-nay-mau","name": "Phụ đề nảy màu, zoom dồn dập","version": 1,+ "order": 2,"pause": 0.25,"cutFillers": true,"captions": { "style": "phu-de-nay-mau", "maxWords": 1, "position": "middle", "font": "Anton", "highlightsPerMinute": 12 },diff --git a/edit-styles/sach-gon.md b/edit-styles/sach-gon.mdindex 0caafa8..00f935e 100644--- a/edit-styles/sach-gon.md+++ b/edit-styles/sach-gon.md@@ -3,6 +3,7 @@"id": "sach-gon","name": "Sạch và gọn","version": 1,+ "order": 1,"pause": 0.35,"cutFillers": true,"captions": { "style": "sach-gon", "maxWords": 3, "position": "lower", "font": "Be Vietnam Pro", "highlightsPerMinute": 6 },diff --git a/edit/captions-hf.mjs b/edit/captions-hf.mjsindex 42e0b7c..46a2461 100644--- a/edit/captions-hf.mjs+++ b/edit/captions-hf.mjs@@ -20,15 +20,46 @@ export function captionCards(edl) {if (cur.length >= cap.maxWords || ends || gap > 0.45 || !nx) { groups.push(cur); cur = []; }});const cards = groups.map((g) => ({ words: g, start: toOutputNearest(keep, g[0].start), end: toOutputNearest(keep, g[g.length - 1].end) }));+ cards.sort((a, b) => a.start - b.start);+ return finishCards(cards, keep);+}++export const MIN_CARD = 0.25; // một nhóm chữ hiện ít nhất chừng này (nếu chưa tới nhóm sau)+export const MERGE_BELOW = 0.1; // nhóm bị ép ngắn hơn chừng này (chữ nói rất nhanh) thì gộp vào nhóm sau++/**+ * Luật thời gian của nhóm phụ đề (giống caption_cards trong lumedit.py):+ * nối khe < 0,4 s; kéo dài tối thiểu MIN_CARD; KHÔNG BAO GIỜ chồng lên nhóm sau (cắt end về start của nhóm sau);+ * nhóm còn < MERGE_BELOW thì gộp chữ vào nhóm sau. Lỗi cũ: kéo dài tối thiểu 0,25 s chạy SAU bước nối khe nên+ * "TRÀ" (0,22 s) đè lên "SỮA" — 2 nhóm cùng hiện ở cùng chỗ.+ */+export function finishCards(cards, keep) {for (let k = 0; k + 1 < cards.length; k++) {const gap = cards[k + 1].start - cards[k].end;if (gap >= 0 && gap < 0.4) cards[k].end = cards[k + 1].start;}- for (const c of cards) {- c.end = Math.max(c.end, c.start + 0.25);- c.wordOut = c.words.map((w) => toOutputNearest(keep, w.start));+ for (const c of cards) c.end = Math.max(c.end, c.start + MIN_CARD);+ for (let k = 0; k + 1 < cards.length; k++) cards[k].end = Math.min(cards[k].end, cards[k + 1].start);+ const out = [];+ for (let k = 0; k < cards.length; k++) {+ const c = cards[k]; const nx = cards[k + 1];+ if (nx && c.end - c.start < MERGE_BELOW) { nx.words = c.words.concat(nx.words); nx.start = c.start; continue; }+ out.push(c);+ }+ for (const c of out) c.wordOut = c.words.map((w) => Math.max(c.start, toOutputNearest(keep, w.start)));+ const bad = cardOverlaps(out);+ if (bad.length) throw new Error('phụ đề chồng nhau: ' + bad.join('; '));+ return out;+}++/** Luật kiểm: không bao giờ 2 nhóm phụ đề hiện cùng lúc (mọi nhóm cùng 1 vị trí). Trả danh sách lỗi. */+export function cardOverlaps(cards) {+ const errs = [];+ for (let k = 0; k + 1 < cards.length; k++) {+ if (cards[k].end > cards[k + 1].start + 1e-6) errs.push(`"${cards[k].words.map((w) => w.w).join(' ')}" (${cards[k].start.toFixed(2)}–${cards[k].end.toFixed(2)} s) đè "${cards[k + 1].words.map((w) => w.w).join(' ')}" (từ ${cards[k + 1].start.toFixed(2)} s)`);+ if (cards[k].end <= cards[k].start) errs.push(`nhóm ${k} dài 0 s`);}- return cards;+ return errs;}const LOOKS = {@@ -106,12 +137,12 @@ export function writeCaptionScene(edl, sceneDir) {}/** Render lớp chữ trong suốt → WebM VP9 alpha. */-export async function renderCaptionLayer(sceneDir, outWebm, { log = console.log } = {}) {+export async function renderCaptionLayer(sceneDir, outWebm, { log = console.log, onPct } = {}) {let last = -1;const r = await runHF(['render', sceneDir, '-o', outWebm, '--format', 'webm', '-f', String(OUT.fps), '-q', 'looks', '--quiet'], {onLine: (l) => {const m = /^@hf-progress (.*)$/.exec(l);- if (m) { try { const p = JSON.parse(m[1]); const b = Math.floor(p.pct / 20) * 20; if (b !== last) { last = b; log(`phụ đề HyperFrames ${p.pct}% ${p.code}`); } } catch { /* bỏ qua */ } }+ if (m) { try { const p = JSON.parse(m[1]); onPct?.(p.pct); const b = Math.floor(p.pct / 20) * 20; if (b !== last) { last = b; log(`phụ đề HyperFrames ${p.pct}% ${p.code}`); } } catch { /* bỏ qua */ } }},});if (r.code !== 0 || !fs.existsSync(outWebm)) throw new Error('HyperFrames render phụ đề lỗi: ' + r.out.trim().split(/\r?\n/).slice(-5).join(' | '));diff --git a/edit/http.mjs b/edit/http.mjsnew file mode 100644index 0000000..950f921--- /dev/null+++ b/edit/http.mjs@@ -0,0 +1,192 @@+// REST cho Edit video (server/server.mjs gọi handleEditRoute). Chống DNS rebinding đã làm ở server (Host),+// ở đây chặn thêm Origin lạ cho mọi lệnh ghi (trang web khác không gửi form upload/đường dẫn vào được).+// GET /api/edit-options → {ready, setup, styles[], music[]}+// GET /api/edits → danh sách+// POST /api/edits → multipart (video ≤ 2 GB, music?, style, musicStyle?, content?, names?, draft?)+// hoặc JSON {path, style, music?(đường dẫn|tên nhạc tổng hợp), content?, names?, draft?}+// GET /api/edits/:id → trạng thái, tiến độ, log, chữ LLM đã sửa, các lần sửa+// POST /api/edits/:id/revise → {instruction}: LLM sửa EDL theo lời, render lại, không phân tích lại+// GET /edits/:id/(out.mp4|out-r<n>.mp4|preview.jpg|preview-final.jpg|edl.json)+import fs from 'node:fs';+import path from 'node:path';+import { MUSIC_LIST, MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';+import {+ ID_RE, editDir, newEditId, createEdit, runEditJob, reviseEditJob, editView, listEdits, editStyles, editReady, readEditJob, markStaleEdits,+} from './jobs.mjs';++export const MAX_UPLOAD = 2 * 1024 ** 3; // 2 GB+const VIDEO_EXT = new Set(['.mp4', '.mov', '.m4v', '.mkv', '.webm', '.avi', '.3gp']);+const AUDIO_EXT = new Set(['.mp3', '.wav', '.m4a', '.aac', '.ogg', '.flac', '.opus']);++export function initEdits() { markStaleEdits(); }++/** Nhạc tổng hợp có sẵn → file wav 60 s trong thư mục edit (lặp khi video dài hơn). */+function synthMusicFile(id, styleName) {+ if (!MUSIC_STYLES.includes(styleName)) throw new Error('không có nhạc tổng hợp "' + styleName + '"');+ const f = path.join(editDir(id), `music-${styleName}.wav`);+ if (!fs.existsSync(f)) writeMusic(styleName, f, 60, 1);+ return f;+}++/**+ * Đọc multipart/form-data theo luồng (không giữ file trong RAM). Trường text ≤ 64 KB; file ghi thẳng ra đĩa qua+ * fileTarget(field, filename) → đường dẫn | null (null = bỏ qua). Tổng ≤ maxBytes.+ */+export function parseMultipart(req, { maxBytes, fileTarget }) {+ return new Promise((resolve, reject) => {+ const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(req.headers['content-type'] || '');+ if (!m) return reject(Object.assign(new Error('thiếu boundary multipart'), { code: 400 }));+ const delim = Buffer.from('\r\n--' + (m[1] || m[2]).trim());+ const fields = {}; const files = {};+ let buf = Buffer.from('\r\n'); // để dấu phân cách đầu tiên giống mọi dấu sau+ let state = 'pre'; let total = 0; let cur = null; let failed = false;+ const fail = (e) => { if (failed) return; failed = true; cur?.stream?.destroy(); req.unpipe?.(); req.resume(); reject(e); };+ const write = (data) => {+ if (!cur || !data.length) return;+ if (cur.stream) { cur.size += data.length; if (!cur.stream.write(data)) { req.pause(); cur.stream.once('drain', () => req.resume()); } }+ else if (cur.text !== null) { cur.text += data.toString('utf8'); if (cur.text.length > 64 * 1024) fail(Object.assign(new Error(`trường ${cur.name} quá dài`), { code: 413 })); }+ };+ const closePart = () => {+ if (!cur) return;+ if (cur.stream) { cur.stream.end(); files[cur.name] = { path: cur.path, filename: cur.filename, size: cur.size, done: new Promise((r) => cur.stream.on('close', r)) }; }+ else if (cur.text !== null) fields[cur.name] = cur.text;+ cur = null;+ };+ const pump = () => {+ for (;;) {+ if (state === 'pre' || state === 'body') {+ const i = buf.indexOf(delim);+ if (i < 0) {+ const keep = delim.length + 4;+ if (state === 'body' && buf.length > keep) { write(buf.subarray(0, buf.length - keep)); buf = buf.subarray(buf.length - keep); }+ return;+ }+ if (state === 'body') write(buf.subarray(0, i));+ closePart();+ if (buf.length < i + delim.length + 2) { buf = buf.subarray(i); state = 'pre'; return; }+ const tail = buf.subarray(i + delim.length, i + delim.length + 2).toString();+ if (tail === '--') { state = 'end'; buf = Buffer.alloc(0); return; }+ buf = buf.subarray(i + delim.length + 2); state = 'head';+ } else if (state === 'head') {+ const j = buf.indexOf('\r\n\r\n');+ if (j < 0) { if (buf.length > 16 * 1024) fail(Object.assign(new Error('đầu phần multipart quá dài'), { code: 400 })); return; }+ const head = buf.subarray(0, j).toString('utf8'); buf = buf.subarray(j + 4);+ const name = /name="([^"]*)"/i.exec(head)?.[1] || '';+ const filename = /filename="([^"]*)"/i.exec(head)?.[1];+ cur = { name, filename, text: null, stream: null, size: 0 };+ if (filename !== undefined) {+ const target = filename ? fileTarget(name, filename) : null;+ if (target) { cur.path = target; cur.stream = fs.createWriteStream(target); cur.stream.on('error', fail); }+ } else cur.text = '';+ state = 'body';+ } else return;+ }+ };+ req.on('data', (chunk) => {+ if (failed) return;+ total += chunk.length;+ if (total > maxBytes) return fail(Object.assign(new Error(`file quá lớn (tối đa ${Math.round(maxBytes / 1024 ** 3)} GB)`), { code: 413 }));+ buf = buf.length ? Buffer.concat([buf, chunk]) : chunk;+ try { pump(); } catch (e) { fail(e); }+ });+ req.on('end', async () => {+ if (failed) return;+ if (state !== 'end') return fail(Object.assign(new Error('multipart bị cắt ngang'), { code: 400 }));+ await Promise.all(Object.values(files).map((f) => f.done));+ resolve({ fields, files });+ });+ req.on('error', fail);+ });+}++const originOk = (req, allowedHosts) => {+ const o = req.headers.origin;+ if (!o) return true; // curl/agent cục bộ không gửi Origin+ try { return allowedHosts.has(new URL(o).host.toLowerCase()); } catch { return false; }+};++/** Trả true nếu đã xử lý route. */+export async function handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts }) {+ const isWrite = req.method === 'POST';+ if (!p.startsWith('/api/edit') && !p.startsWith('/edits/')) return false;+ if (isWrite && !originOk(req, allowedHosts)) { send(res, 403, { error: 'origin không hợp lệ' }); return true; }++ if (p === '/api/edit-options' && req.method === 'GET') {+ send(res, 200, { ...editReady(), styles: editStyles(), music: MUSIC_LIST.map((m) => ({ id: m.name, desc: m.desc })), maxUploadBytes: MAX_UPLOAD });+ return true;+ }+ if (p === '/api/edits' && req.method === 'GET') { send(res, 200, listEdits()); return true; }+ if (p === '/api/edits' && req.method === 'POST') {+ if (!editReady().ready) { send(res, 503, { error: editReady().note }); return true; }+ const ct = String(req.headers['content-type'] || '');+ let input;+ if (/^multipart\/form-data/i.test(ct)) {+ const id = newEditId();+ fs.mkdirSync(editDir(id), { recursive: true });+ let parsed;+ try {+ parsed = await parseMultipart(req, {+ maxBytes: MAX_UPLOAD + 200 * 1024 ** 2,+ fileTarget: (field, filename) => {+ const ext = path.extname(filename).toLowerCase();+ if (field === 'video') { if (!VIDEO_EXT.has(ext)) throw Object.assign(new Error(`định dạng video ${ext || '?'} chưa hỗ trợ`), { code: 415 }); return path.join(editDir(id), 'source' + ext); }+ if (field === 'music') { if (!AUDIO_EXT.has(ext)) throw Object.assign(new Error(`định dạng nhạc ${ext || '?'} chưa hỗ trợ`), { code: 415 }); return path.join(editDir(id), 'music' + ext); }+ return null;+ },+ });+ } catch (e) {+ fs.rmSync(editDir(id), { recursive: true, force: true });+ send(res, e.code && Number.isInteger(e.code) ? e.code : 400, { error: e.message });+ return true;+ }+ const { fields, files } = parsed;+ if (!files.video?.size) { fs.rmSync(editDir(id), { recursive: true, force: true }); send(res, 400, { error: 'thiếu file video' }); return true; }+ let music = files.music?.size ? files.music.path : null;+ if (!music && fields.musicStyle && fields.musicStyle !== 'none') music = synthMusicFile(id, fields.musicStyle);+ input = { id, video: files.video.path, sourceName: files.video.filename, style: fields.style, music, musicName: files.music?.filename || (fields.musicStyle && fields.musicStyle !== 'none' ? `nhạc tổng hợp ${fields.musicStyle}` : null),+ content: fields.content, names: fields.names, draft: fields.draft === '1' || fields.draft === 'true' };+ } else {+ const body = await readBody(req, 32 * 1024);+ if (!body.path) { send(res, 400, { error: 'cần multipart (video) hoặc JSON {path}' }); return true; }+ const id = newEditId();+ let music = null; let musicName = null;+ if (body.music && MUSIC_STYLES.includes(body.music)) { fs.mkdirSync(editDir(id), { recursive: true }); music = synthMusicFile(id, body.music); musicName = `nhạc tổng hợp ${body.music}`; }+ else if (body.music && body.music !== 'none') music = body.music;+ input = { id, video: body.path, style: body.style, music, musicName, content: body.content ?? body.notes, names: body.names, draft: !!body.draft, llm: body.llm };+ }+ let job;+ try { job = createEdit(input); } catch (e) { send(res, 422, { error: e.message }); return true; }+ runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));+ send(res, 202, editView(job.id));+ return true;+ }+ let m = /^\/api\/edits\/([\w-]+)$/.exec(p);+ if (m && req.method === 'GET') {+ const v = ID_RE.test(m[1]) && editView(m[1]);+ send(res, v ? 200 : 404, v || { error: 'không thấy edit' });+ return true;+ }+ m = /^\/api\/edits\/([\w-]+)\/revise$/.exec(p);+ if (m && req.method === 'POST') {+ const job = ID_RE.test(m[1]) && readEditJob(m[1]);+ if (!job) { send(res, 404, { error: 'không thấy edit' }); return true; }+ if (['queued', 'running'].includes(job.status)) { send(res, 409, { error: 'edit này đang chạy, chờ xong rồi sửa' }); return true; }+ if (!fs.existsSync(path.join(editDir(job.id), 'state.json'))) { send(res, 409, { error: 'edit này chưa dựng xong lần đầu' }); return true; }+ const body = await readBody(req, 16 * 1024);+ const text = String(body.instruction || '').trim();+ if (!text) { send(res, 400, { error: 'thiếu lời sửa (instruction)' }); return true; }+ if (text.length > 1000) { send(res, 413, { error: 'lời sửa quá dài (tối đa 1000 ký tự)' }); return true; }+ try {+ reviseEditJob(job.id, text).catch((e) => console.error('[edit revise]', job.id, e.message));+ } catch (e) { send(res, 422, { error: e.message }); return true; }+ await new Promise((r) => setTimeout(r, 50));+ send(res, 202, editView(job.id));+ return true;+ }+ if (p.startsWith('/api/')) return false;+ // ---- file ----+ m = /^\/edits\/([\w-]+)\/(out(?:-r\d{1,4})?\.mp4|preview\.jpg|preview-final\.jpg|edl\.json)$/.exec(p);+ if (m && (req.method === 'GET' || req.method === 'HEAD') && ID_RE.test(m[1])) { serveFile(req, res, editDir(m[1]), m[2]); return true; }+ send(res, 404, { error: 'không thấy file' });+ return true;+}diff --git a/edit/jobs.mjs b/edit/jobs.mjsnew file mode 100644index 0000000..72b23e2--- /dev/null+++ b/edit/jobs.mjs@@ -0,0 +1,168 @@+// Việc Edit video dùng chung cho REST (server), MCP và CLI: hồ sơ edits/<id>/job.json, tiến độ, hàng chờ.+// Mỗi lúc chỉ 1 edit chạy trên cả máy (khoá file edits/.edit.lock, có pid; tiến trình chết thì khoá tự hết hạn),+// vì render + whisper + HyperFrames đều ăn GPU/CPU.+import fs from 'node:fs';+import path from 'node:path';+import { EDITS, editDir, newEditId, editVideo, reviseEdit, STEPS } from './pipeline.mjs';+import { listStyles, loadStyle, parseNames } from './planner.mjs';+import { venvReady } from './env.mjs';++export { STEPS, EDITS, newEditId, editDir };+export const ID_RE = /^[\w-]{1,80}$/;+const LOCK = path.join(EDITS, '.edit.lock');+const readJson = (f, d = null) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return d; } };+const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };+const jobFile = (id) => path.join(editDir(id), 'job.json');+/** Tên file MP4 mới nhất (out.mp4 hoặc out-r<n>.mp4 sau mỗi lần sửa), null nếu chưa có. */+export function currentOut(id) {+ const st = readJson(path.join(editDir(id), 'state.json'), {});+ for (const f of [st.out, 'out.mp4']) if (f && /^out(-r\d{1,4})?\.mp4$/.test(f) && fs.existsSync(path.join(editDir(id), f))) return f;+ return null;+}++export function readEditJob(id) {+ if (!ID_RE.test(String(id))) return null;+ return readJson(jobFile(id));+}+function writeJob(id, patch) {+ const cur = readJson(jobFile(id), {});+ const next = { ...cur, ...patch, id, updatedAt: new Date().toISOString() };+ fs.mkdirSync(editDir(id), { recursive: true });+ const tmp = jobFile(id) + '.tmp';+ fs.writeFileSync(tmp, JSON.stringify(next, null, 1));+ fs.renameSync(tmp, jobFile(id));+ return next;+}++/** Kiểu edit có sẵn (cho UI/MCP). */+export function editStyles() {+ return listStyles().map((id) => { const s = loadStyle(id); return { id, order: s.order ?? 99, name: s.name, summary: s.guide.split('\n').find((l) => l.trim() && !l.startsWith('#')) || '' }; })+ .sort((a, b) => a.order - b.order);+}++/** Môi trường Python đã cài chưa (UI hiện hướng dẫn cài nếu chưa). */+export function editReady() {+ return { ready: venvReady(), setup: 'node edit/setup.mjs', note: venvReady() ? '' : 'Chưa cài môi trường Edit video (Python 3.10–3.12, ~6 GB gồm whisper large-v3). Chạy trong thư mục LumReels: node edit/setup.mjs' };+}++/**+ * Tạo hồ sơ edit (chưa chạy). input: {id?, video, style, music?, musicName?, content?, names?, draft?, llm?, sourceName?}+ */+export function createEdit(input) {+ const id = input.id || newEditId();+ if (!ID_RE.test(id)) throw new Error('id không hợp lệ');+ const video = path.resolve(String(input.video || ''));+ if (!input.video || !fs.existsSync(video) || !fs.statSync(video).isFile()) throw new Error(`không thấy video ${input.video || ''}`);+ const style = String(input.style || 'sach-gon');+ if (!listStyles().includes(style)) throw new Error(`không có kiểu edit "${style}" (có: ${listStyles().join(', ')})`);+ const music = input.music ? path.resolve(String(input.music)) : null;+ if (music && !fs.existsSync(music)) throw new Error(`không thấy file nhạc ${input.music}`);+ const content = String(input.content || '').slice(0, 2000);+ return writeJob(id, {+ status: 'queued', action: 'edit', step: null, stepIndex: -1, stepTotal: STEPS.length, pct: 0, note: '',+ source: video, sourceName: input.sourceName || path.basename(video), style, music, musicName: input.musicName || (music ? path.basename(music) : null),+ content, names: parseNames(input.names), draft: !!input.draft, llm: input.llm === 'off' ? 'off' : 'on',+ createdAt: new Date().toISOString(), error: null, out: null,+ });+}++// ---- khoá toàn máy ------------------------------------------------------------------------------------------------+async function withLock(id, fn) {+ fs.mkdirSync(EDITS, { recursive: true });+ for (;;) {+ try {+ fs.writeFileSync(LOCK, JSON.stringify({ pid: process.pid, id, at: Date.now() }), { flag: 'wx' });+ break;+ } catch {+ const cur = readJson(LOCK);+ if (!cur || !pidAlive(cur.pid)) { try { fs.unlinkSync(LOCK); } catch { /* tiến trình khác vừa xoá */ } continue; }+ await new Promise((r) => setTimeout(r, 2000));+ }+ }+ try { return await fn(); } finally { try { const cur = readJson(LOCK); if (cur?.pid === process.pid && cur?.id === id) fs.unlinkSync(LOCK); } catch { /* bỏ qua */ } }+}+/** Edit đang chiếm khoá (nếu có). */+export function editLockHolder() { const cur = readJson(LOCK); return cur && pidAlive(cur.pid) ? cur : null; }++const onProgress = (id) => (p) => writeJob(id, { step: p.step, stepIndex: p.index, stepTotal: p.total, pct: p.pct, note: p.note || '' });++/** Chạy dựng lần đầu (chờ khoá). log: hàm in dòng (mặc định im lặng). */+export async function runEditJob(id, { log = () => {} } = {}) {+ const job = readEditJob(id);+ if (!job) throw new Error('không thấy edit ' + id);+ writeJob(id, { status: 'queued', action: 'edit', error: null, pid: process.pid });+ return withLock(id, async () => {+ writeJob(id, { status: 'running', startedAt: new Date().toISOString(), pid: process.pid });+ const r = await editVideo(job.source, {+ id, style: job.style, music: job.music, content: job.content, names: job.names, draft: job.draft, llm: job.llm, log, progress: onProgress(id),+ });+ writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, error: null } : { status: 'error', error: r.error });+ return r;+ });+}++/** Sửa bằng lời rồi render lại (chờ khoá). Lỗi thì bản cũ vẫn giữ (status quay về done, ghi reviseError). */+export async function reviseEditJob(id, instruction, { log = () => {} } = {}) {+ const job = readEditJob(id);+ if (!job) throw new Error('không thấy edit ' + id);+ if (!fs.existsSync(path.join(editDir(id), 'state.json'))) throw new Error('edit này chưa dựng xong lần đầu');+ const text = String(instruction || '').trim();+ if (!text) throw new Error('thiếu lời sửa');+ writeJob(id, { status: 'queued', action: 'revise', instruction: text, reviseError: null, pid: process.pid });+ return withLock(id, async () => {+ writeJob(id, { status: 'running', startedAt: new Date().toISOString(), stepIndex: 2, pid: process.pid });+ const r = await reviseEdit(id, text, { log, progress: onProgress(id) });+ const hasOut = !!currentOut(id);+ writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, reviseError: null }+ : { status: hasOut ? 'done' : 'error', reviseError: r.error, error: hasOut ? null : r.error });+ return r;+ });+}++/** Hồ sơ đầy đủ cho UI/MCP: trạng thái, tiến độ, link file, chữ LLM đã sửa, các lần sửa, log cuối. */+export function editView(id, { withLog = true, urlBase = `/edits/${id}` } = {}) {+ const job = readEditJob(id);+ if (!job) return null;+ const dir = editDir(id);+ const has = (f) => fs.existsSync(path.join(dir, f));+ const result = readJson(path.join(dir, 'result.json'), {});+ const state = readJson(path.join(dir, 'state.json'), {});+ const stamp = (f) => { try { return Math.round(fs.statSync(path.join(dir, f)).mtimeMs); } catch { return 0; } };+ const outName = currentOut(id);+ const v = {+ ...job,+ styleName: (() => { try { return loadStyle(job.style).name; } catch { return job.style; } })(),+ steps: STEPS,+ fixes: result.checks?.fixes || [],+ revisions: state.revisions || [],+ checks: result.checks || null,+ timings: result.timings || null,+ warnings: result.warnings || [],+ links: {+ out: outName ? `${urlBase}/${outName}?v=${stamp(outName)}` : null,+ preview: has('preview.jpg') ? `${urlBase}/preview.jpg?v=${stamp('preview.jpg')}` : null,+ previewFinal: has('preview-final.jpg') ? `${urlBase}/preview-final.jpg?v=${stamp('preview-final.jpg')}` : null,+ edl: has('edl.json') ? `${urlBase}/edl.json` : null,+ },+ files: { dir, out: outName ? path.join(dir, outName) : null, edl: has('edl.json') ? path.join(dir, 'edl.json') : null },+ };+ if (withLog) {+ try { v.log = fs.readFileSync(path.join(dir, 'log.txt'), 'utf8').trim().split(/\r?\n/).slice(-40); } catch { v.log = []; }+ }+ return v;+}++export function listEdits(limit = 50) {+ if (!fs.existsSync(EDITS)) return [];+ return fs.readdirSync(EDITS).filter((d) => ID_RE.test(d) && fs.existsSync(jobFile(d)))+ .sort().reverse().slice(0, limit).map((id) => editView(id, { withLog: false }));+}++/** Server khởi động: edit "running"/"queued" mà tiến trình đã chết → báo lỗi (để người dùng bấm lại). */+export function markStaleEdits() {+ for (const v of listEdits(200)) {+ if (['running', 'queued'].includes(v.status) && !(v.pid && pidAlive(v.pid))) {+ writeJob(v.id, { status: currentOut(v.id) && v.action === 'revise' ? 'done' : 'error', error: v.action === 'revise' ? null : 'bị ngắt giữa chừng (server/tiến trình đã tắt) — bấm Dựng lại', reviseError: v.action === 'revise' ? 'bị ngắt giữa chừng' : v.reviseError });+ }+ }+}diff --git a/edit/pipeline.mjs b/edit/pipeline.mjsindex 8c99c69..389213d 100644--- a/edit/pipeline.mjs+++ b/edit/pipeline.mjs@@ -4,7 +4,10 @@// 5 render nền 1 lượt (cắt + reframe 9:16 + zoom; tiếng gốc nối 20 ms) + kiểm lẹm chữ (nghe lại)// 6 phụ đề: HyperFrames lớp trong suốt (bản chính) hoặc PIL vẽ thẳng (--draft)// 7 tiếng: giọng gốc + nhạc tự hạ + sfx → −14 LUFS 8 ghép → out.mp4 9 kiểm (qc-check + kích thước + lưới khung)-// Đầu ra: edits/<id>/ (edl.json, preview.jpg, out.mp4, preview-final.jpg, qc.json, result.json, log.txt)+// Sửa bằng lời (reviseEdit): LLM sửa đề xuất/cắt theo giây bản ra/núm kiểu → dựng lại EDL → bước 4–9. KHÔNG phân tích lại.+// Đầu ra: edits/<id>/ (edl.json, preview.jpg, out.mp4, preview-final.jpg, qc.json, result.json, state.json, log.txt,+// mỗi lần sửa n ra out-r<n>.mp4 MỚI (Windows khoá file đang phát nên không ghi đè), bản trước giữ nguyên,+// versions/edl-<n>.json = EDL trước lần sửa n; state.json.out = tên file bản mới nhất)import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';@@ -13,43 +16,65 @@ import { SFX_NAMES } from '../engine/audio/sfx.mjs';import { measureLoudness } from '../engine/audio/mix.mjs';import { ROOT, runLumedit } from './env.mjs';import { ingest } from './ingest.mjs';-import { loadStyle, wordList, propose, compileEdl } from './planner.mjs';+import {+ loadStyle, wordList, propose, compileEdl, parseNames, proposeRevision, applyOverrides, applyExtraCuts, outputCutToSource,+} from './planner.mjs';import { validateEdl, toOutputNearest, outputDuration, OUT } from './edl.mjs';import { writeCaptionScene, renderCaptionLayer } from './captions-hf.mjs';import { buildEditMix } from './audio.mjs';export const EDITS = path.join(ROOT, 'edits');+/** Các bước (để UI vẽ thanh tiến độ). Sửa bằng lời bắt đầu từ "LLM lập EDL". */+export const STEPS = ['nạp', 'phân tích', 'LLM lập EDL', 'xem trước', 'render nền', 'phụ đề', 'tiếng', 'ghép', 'kiểm'];-function newId() {+export function newEditId() {const d = new Date(); const p = (n) => String(n).padStart(2, '0');return `${String(d.getFullYear()).slice(2)}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${crypto.randomBytes(2).toString('hex')}`;}+export const editDir = (id) => path.join(EDITS, id);+const readJson = (f, d = null) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return d; } };-/**- * opts: {style, music?, content?, draft?, llm?: 'on'|'off', id?, log?}- * Trả {ok, id, dir, out, timings, checks, error?}- */-export async function editVideo(video, opts = {}) {- const id = opts.id || newId();- const dir = path.join(EDITS, id);+/** Bộ khung chung cho 1 lượt chạy: log, đo giờ từng bước, báo tiến độ. */+function runner(dir, opts) {fs.mkdirSync(dir, { recursive: true });const logFile = path.join(dir, 'log.txt');const log = (s) => { const line = `[${new Date().toISOString().slice(11, 19)}] ${s}`; fs.appendFileSync(logFile, line + '\n'); (opts.log || console.log)(line); };const timings = {}; const checks = {}; const warnings = [];- const step = async (name, fn) => { const t = Date.now(); log(`— ${name}`); const r = await fn(); timings[name] = +((Date.now() - t) / 1000).toFixed(1); log(` xong ${name}: ${timings[name]} s`); return r; };+ const progress = (step, pct = 0, note = '') => { try { opts.progress?.({ step, index: STEPS.indexOf(step), total: STEPS.length, pct, note }); } catch { /* bỏ qua */ } };+ const step = async (name, fn) => {+ const t = Date.now(); log(`— ${name}`); progress(name, 0);+ const r = await fn((pct, note) => progress(name, pct, note));+ timings[name] = +((Date.now() - t) / 1000).toFixed(1); log(` xong ${name}: ${timings[name]} s`); progress(name, 100);+ return r;+ };+ return { log, timings, checks, warnings, step };+}++/**+ * Dựng mới. opts: {style, music?, content?, names?, draft?, llm?: 'on'|'off', id?, log?, progress?}+ * Trả {ok, id, dir, out, edl, timings, checks, warnings, error?}+ */+export async function editVideo(video, opts = {}) {+ const id = opts.id || newEditId();+ const dir = editDir(id);+ const R = runner(dir, opts);+ const { log, timings, checks, warnings, step } = R;const result = { ok: false, id, dir, video: path.resolve(video), style: opts.style, draft: !!opts.draft, timings, checks, warnings };- const save = () => fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify(result, null, 2));try {if (!fs.existsSync(video)) throw new Error(`không thấy video ${video}`);if (opts.music && !fs.existsSync(opts.music)) throw new Error(`không thấy file nhạc ${opts.music}`);const style = { ...loadStyle(opts.style || 'sach-gon'), sfxNames: SFX_NAMES };- log(`edit ${id}: ${path.basename(video)} · kiểu ${style.id}${opts.draft ? ' · bản nháp (phụ đề PIL)' : ''}${opts.music ? ' · nhạc ' + path.basename(opts.music) : ''}`);+ const names = parseNames(opts.names);+ log(`edit ${id}: ${path.basename(video)} · kiểu ${style.id}${opts.draft ? ' · bản nháp (phụ đề PIL)' : ''}${opts.music ? ' · nhạc ' + path.basename(opts.music) : ''}${names.length ? ' · tên riêng: ' + names.join(', ') : ''}`);const ing = await step('nạp', () => ingest(path.resolve(video), path.join(dir, 'proxy.mov'), { log }));+ fs.writeFileSync(path.join(dir, 'ingest.json'), JSON.stringify(ing, null, 1));const analysisFile = path.join(dir, 'analysis.json');- const an = await step('phân tích', async () => {- const r = await runLumedit(['analyze', ing.proxy.file, '--out', analysisFile], { onProgress: (p) => log(` ${p.step}${p.note ? ': ' + p.note : ''}`) });+ const an = await step('phân tích', async (pg) => {+ const r = await runLumedit(['analyze', ing.proxy.file, '--out', analysisFile], {+ onProgress: (p) => { log(` ${p.step}${p.note ? ': ' + p.note : ''}`); pg({ words: 10, quiet: 70, face: 80 }[p.step] ?? 50, p.step); },+ });if (!r.ok) throw new Error('phân tích lỗi: ' + r.error);return { ...r.result, data: JSON.parse(fs.readFileSync(analysisFile, 'utf8')) };});@@ -58,96 +83,172 @@ export async function editVideo(video, opts = {}) {const words = wordList(an.data);style.hesitations = new Set(an.data.hesitations || []);- const plan = await step('LLM lập EDL', () => propose({ words, style, content: opts.content, duration: ing.source.duration, llm: opts.llm || 'on', log }));+ const plan = await step('LLM lập EDL', () => propose({ words, style, content: opts.content, names, duration: ing.source.duration, llm: opts.llm || 'on', log }));fs.writeFileSync(path.join(dir, 'proposal.json'), JSON.stringify({ ...plan, words: words.map((w) => `${w.i}:${w.w}${w.unsure ? '?' : ''}`) }, null, 1));warnings.push(...plan.warnings);log(` đề xuất (vòng ${plan.rounds}): bỏ ${plan.proposal.drop.length} khoảng, ${plan.proposal.zooms.length} zoom, ${plan.proposal.highlights.length} chữ nhấn, ${plan.proposal.fixes.length} chữ sửa${plan.proposal.notes ? ' · ' + plan.proposal.notes : ''}`);- const byI = new Map(words.map((w) => [w.i, w.w]));- checks.fixes = plan.proposal.fixes.map((f) => `${byI.get(f.word)} → ${f.text || '(ẩn)'}`);- if (checks.fixes.length) log(` chữ LLM sửa (cần người xem lại): ${checks.fixes.join(', ')}`);- const edl = compileEdl({ id, ingestRes: ing, analysis: an.data, words, proposal: plan.proposal, style, music: opts.music, draft: opts.draft });- const v = validateEdl(edl, { sfxNames: SFX_NAMES });- if (!v.ok) throw new Error('EDL không hợp lệ (lỗi code dựng EDL): ' + v.errors.map((e) => `${e.code} ${e.path}: ${e.msg}`).join('; '));- const edlFile = path.join(dir, 'edl.json');- fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));- const outDur = outputDuration(edl.keep);- checks.edl = { keep: edl.keep.length, removed: edl.removed.length, removedSeconds: +(ing.source.duration - outDur).toFixed(2), zooms: edl.zooms.length, sfx: edl.sfx.length, captionWords: edl.captions.words.length };- log(` EDL: ${ing.source.duration.toFixed(2)} s → ${outDur.toFixed(2)} s, ${edl.keep.length} đoạn giữ, ${edl.zooms.length} zoom, ${edl.sfx.length} sfx`);- for (const r of edl.removed) log(` bỏ ${r.start.toFixed(2)}–${r.end.toFixed(2)} s (${r.reason})${r.words ? ': ' + r.words : ''}`);-- await step('xem trước', async () => {- const r = await runLumedit(['stills', edlFile, '--out', path.join(dir, 'preview.jpg'), '--count', '16', '--draft-captions']);- if (!r.ok) throw new Error('xem trước lỗi: ' + r.error);- });+ const state = {+ version: 1, style: style.id, music: opts.music ? path.resolve(opts.music) : null, content: opts.content || '', names,+ draft: !!opts.draft, llm: opts.llm || 'on', proposal: plan.proposal, overrides: {}, extraCuts: [], revisions: [],+ };+ fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(state, null, 1));+ const edl = buildEdl({ id, ing, analysis: an.data, words, style, state, checks, log });+ const r = await renderEdl({ dir, edl, draft: state.draft, R, outName: 'out.mp4' });+ fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify({ ...state, out: 'out.mp4' }, null, 1));+ Object.assign(result, r, { ok: true });+ } catch (e) {+ result.error = e.message;+ log('LỖI: ' + e.message);+ }+ fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify(result, null, 2));+ return result;+}- const base = path.join(dir, 'base.mp4');- const rb = await step('render nền', async () => {- const r = await runLumedit(['render', edlFile, '--out', base, ...(opts.draft ? ['--draft-captions'] : [])], {- onProgress: (p) => { if (p.step === 'render' && p.pct % 25 === 0) log(` render ${p.pct}% (${p.done}/${p.total})`); else if (p.step !== 'render') log(` ${p.step}${p.note ? ': ' + p.note : ''}`); },- });- if (!r.ok) throw new Error('render nền lỗi: ' + r.error);- return r.result;- });- timings['render nền (vẽ khung)'] = rb.seconds.render;- if (rb.seconds.overcut_check !== undefined) timings['kiểm lẹm chữ (nghe lại)'] = rb.seconds.overcut_check;- checks.overcut = rb.overcut;- log(` lẹm chữ: ${rb.overcut?.verdict}`);-- let overlay = null;- if (!opts.draft && edl.captions.words.length) {- overlay = await step('phụ đề HyperFrames', async () => {- const sc = writeCaptionScene(edl, path.join(dir, 'captions'));- checks.captions = { cards: sc.cards, box: sc.box, safeZone: 'trong 120–960 px, đáy ≤ 80% khung' };- return renderCaptionLayer(path.join(dir, 'captions'), path.join(dir, 'captions.webm'), { log });- });- }+/** state (đề xuất + núm kiểu + cắt thêm) → EDL đã kiểm, ghi edl.json. */+function buildEdl({ id, ing, analysis, words, style, state, checks, log }) {+ const st = applyOverrides(style, state.overrides);+ const byI = new Map(words.map((w) => [w.i, w.w]));+ checks.fixes = state.proposal.fixes.map((f) => ({ word: f.word, heard: byI.get(f.word), text: f.text }));+ if (checks.fixes.length) log(` chữ LLM sửa (cần người xem lại): ${checks.fixes.map((f) => `${f.heard} → ${f.text || '(ẩn)'}`).join(', ')}`);+ let edl = compileEdl({ id, ingestRes: ing, analysis, words, proposal: state.proposal, style: st, music: state.music, draft: state.draft });+ edl = applyExtraCuts(edl, state.extraCuts);+ const v = validateEdl(edl, { sfxNames: SFX_NAMES });+ if (!v.ok) throw new Error('EDL không hợp lệ: ' + v.errors.map((e) => `${e.code} ${e.path}: ${e.msg}`).join('; '));+ const outDur = outputDuration(edl.keep);+ checks.edl = { keep: edl.keep.length, removed: edl.removed.length, removedSeconds: +(ing.source.duration - outDur).toFixed(2), outSeconds: +outDur.toFixed(2), zooms: edl.zooms.length, sfx: edl.sfx.length, captionWords: edl.captions.words.length };+ log(` EDL: ${ing.source.duration.toFixed(2)} s → ${outDur.toFixed(2)} s, ${edl.keep.length} đoạn giữ, ${edl.zooms.length} zoom, ${edl.sfx.length} sfx`);+ for (const r of edl.removed) log(` bỏ ${r.start.toFixed(2)}–${r.end.toFixed(2)} s (${r.reason})${r.words ? ': ' + r.words : ''}`);+ return edl;+}- const mix = await step('tiếng', () => buildEditMix({- base, duration: rb.seconds_out, workDir: path.join(dir, 'audio'), lufs: edl.output.lufs, log,- sfx: edl.sfx.map((s) => ({ t: toOutputNearest(edl.keep, s.at), name: s.name, gainDb: s.gainDb })),- music: edl.music,- }));+/** Bước 4–9 từ 1 EDL. Ghi edl.json, <outName>… Trả {out, edl, ...}. */+async function renderEdl({ dir, edl, draft, R, outName = 'out.mp4' }) {+ const { log, timings, checks, warnings, step } = R;+ const edlFile = path.join(dir, 'edl.json');+ fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));- const out = path.join(dir, 'out.mp4');- await step('ghép', async () => {- const args = ['-hide_banner', '-y', '-i', base];- if (overlay) args.push('-c:v', 'libvpx-vp9', '-i', overlay);- args.push('-i', mix.wav);- const ai = overlay ? 2 : 1;- if (overlay) args.push('-filter_complex', '[0:v][1:v]overlay=0:0:format=auto:eof_action=pass,format=yuv420p[v]', '-map', '[v]', '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-r', String(OUT.fps));- else args.push('-map', '0:v:0', '-c:v', 'copy');- args.push('-map', `${ai}:a:0`, '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2', '-shortest', '-movflags', '+faststart', out);- const r = await run('ffmpeg', args, { timeoutMs: 60 * 60e3 });- if (r.code !== 0) throw new Error('ghép lỗi: ' + r.out.trim().split(/\r?\n/).slice(-3).join(' | '));- });+ await step('xem trước', async () => {+ const r = await runLumedit(['stills', edlFile, '--out', path.join(dir, 'preview.jpg'), '--count', '16', '--draft-captions']);+ if (!r.ok) throw new Error('xem trước lỗi: ' + r.error);+ });- await step('kiểm', async () => {- const pr = await run('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_type,codec_name,width,height,r_frame_rate:format=duration', '-of', 'json', out]);- const j = JSON.parse(pr.out);- const vs = j.streams.find((s) => s.codec_type === 'video'); const as = j.streams.find((s) => s.codec_type === 'audio');- checks.file = { width: vs.width, height: vs.height, fps: vs.r_frame_rate, video: vs.codec_name, audio: as?.codec_name || null, duration: +Number(j.format.duration).toFixed(2) };- checks.file.ok = vs.width === OUT.width && vs.height === OUT.height && vs.r_frame_rate === '30/1' && !!as;- const loud = await measureLoudness(out);- checks.loudness = { lufs: +loud.lufs.toFixed(1), truePeak: +loud.truePeak.toFixed(1), ok: Math.abs(loud.lufs - OUT.lufs) <= 1 && loud.truePeak <= -1 };- const n = 16; const d = checks.file.duration;- const sel = Array.from({ length: n }, (_, k) => `eq(n\\,${Math.floor(((k + 0.5) / n) * d * OUT.fps)})`).join('+');- await run('ffmpeg', ['-hide_banner', '-y', '-i', out, '-vf', `select='${sel}',scale=270:480,tile=4x4:padding=6:color=0x181818`, '-frames:v', '1', '-q:v', '3', path.join(dir, 'preview-final.jpg')]);- const q = await runLumedit(['qc', out, '--out', path.join(dir, 'qc.json')]);- if (q.ok) {- checks.qc = { verdict: q.result.verdict, fails: q.result.findings.filter((f) => f.level === 'fail').map((f) => `${f.check}: ${f.what}`), warns: q.result.findings.filter((f) => f.level === 'warn').map((f) => `${f.check}: ${f.what}`) };- } else warnings.push('qc-check lỗi: ' + q.error);- log(` file ${checks.file.width}×${checks.file.height} ${checks.file.fps} ${checks.file.duration} s · ${checks.loudness.lufs} LUFS / ${checks.loudness.truePeak} dBTP · qc ${checks.qc?.verdict || '?'}`);- for (const f of checks.qc?.fails || []) log(` qc FAIL ${f}`);+ const base = path.join(dir, 'base.mp4');+ const rb = await step('render nền', async (pg) => {+ const r = await runLumedit(['render', edlFile, '--out', base, ...(draft ? ['--draft-captions'] : [])], {+ onProgress: (p) => {+ if (p.step === 'render') { pg(Math.round(p.pct * 0.6), `${p.done}/${p.total} khung`); if (p.pct % 25 === 0) log(` render ${p.pct}% (${p.done}/${p.total})`); }+ else { pg(65, 'nghe lại bản cắt'); log(` ${p.step}${p.note ? ': ' + p.note : ''}`); }+ },});- // proxy + nền là file trung gian lớn; giữ lại để sửa EDL rồi render lại không phải phân tích lại- result.ok = true; result.out = out; result.edl = edlFile;- timings.total = +Object.entries(timings).filter(([k]) => !k.includes('(')).reduce((s, [, v]) => s + v, 0).toFixed(1);- log(`XONG ${out} (${timings.total} s)`);+ if (!r.ok) throw new Error('render nền lỗi: ' + r.error);+ return r.result;+ });+ timings['render nền (vẽ khung)'] = rb.seconds.render;+ if (rb.seconds.overcut_check !== undefined) timings['kiểm lẹm chữ (nghe lại)'] = rb.seconds.overcut_check;+ checks.overcut = rb.overcut;+ log(` lẹm chữ: ${rb.overcut?.verdict}`);++ let overlay = null;+ await step('phụ đề', async (pg) => {+ if (draft || !edl.captions.words.length) { pg(100, draft ? 'phụ đề nháp đã vẽ trong nền' : 'không có chữ'); return; }+ const sc = writeCaptionScene(edl, path.join(dir, 'captions'));+ checks.captions = { cards: sc.cards, overlaps: 0, box: sc.box, safeZone: 'trong 120–960 px, đáy ≤ 80% khung' };+ overlay = await renderCaptionLayer(path.join(dir, 'captions'), path.join(dir, 'captions.webm'), { log, onPct: (p) => pg(p, 'HyperFrames') });+ });++ const mix = await step('tiếng', () => buildEditMix({+ base, duration: rb.seconds_out, workDir: path.join(dir, 'audio'), lufs: edl.output.lufs, log,+ sfx: edl.sfx.map((s) => ({ t: toOutputNearest(edl.keep, s.at), name: s.name, gainDb: s.gainDb })),+ music: edl.music,+ }));++ const out = path.join(dir, outName);+ await step('ghép', async () => {+ const tmp = out.replace(/\.mp4$/, '.part.mp4');+ const args = ['-hide_banner', '-y', '-i', base];+ if (overlay) args.push('-c:v', 'libvpx-vp9', '-i', overlay);+ args.push('-i', mix.wav);+ const ai = overlay ? 2 : 1;+ if (overlay) args.push('-filter_complex', '[0:v][1:v]overlay=0:0:format=auto:eof_action=pass,format=yuv420p[v]', '-map', '[v]', '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-r', String(OUT.fps));+ else args.push('-map', '0:v:0', '-c:v', 'copy');+ args.push('-map', `${ai}:a:0`, '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2', '-shortest', '-movflags', '+faststart', tmp);+ const r = await run('ffmpeg', args, { timeoutMs: 60 * 60e3 });+ if (r.code !== 0) throw new Error('ghép lỗi: ' + r.out.trim().split(/\r?\n/).slice(-3).join(' | '));+ fs.renameSync(tmp, out);+ });++ await step('kiểm', async () => {+ const pr = await run('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_type,codec_name,width,height,r_frame_rate:format=duration', '-of', 'json', out]);+ const j = JSON.parse(pr.out);+ const vs = j.streams.find((s) => s.codec_type === 'video'); const as = j.streams.find((s) => s.codec_type === 'audio');+ checks.file = { width: vs.width, height: vs.height, fps: vs.r_frame_rate, video: vs.codec_name, audio: as?.codec_name || null, duration: +Number(j.format.duration).toFixed(2) };+ checks.file.ok = vs.width === OUT.width && vs.height === OUT.height && vs.r_frame_rate === '30/1' && !!as;+ const loud = await measureLoudness(out);+ checks.loudness = { lufs: +loud.lufs.toFixed(1), truePeak: +loud.truePeak.toFixed(1), ok: Math.abs(loud.lufs - OUT.lufs) <= 1 && loud.truePeak <= -1 };+ const n = 16; const d = checks.file.duration;+ const sel = Array.from({ length: n }, (_, k) => `eq(n\\,${Math.floor(((k + 0.5) / n) * d * OUT.fps)})`).join('+');+ await run('ffmpeg', ['-hide_banner', '-y', '-i', out, '-vf', `select='${sel}',scale=270:480,tile=4x4:padding=6:color=0x181818`, '-frames:v', '1', '-q:v', '3', path.join(dir, 'preview-final.jpg')]);+ const q = await runLumedit(['qc', out, '--out', path.join(dir, 'qc.json')]);+ if (q.ok) {+ checks.qc = { verdict: q.result.verdict, fails: q.result.findings.filter((f) => f.level === 'fail').map((f) => `${f.check}: ${f.what}`), warns: q.result.findings.filter((f) => f.level === 'warn').map((f) => `${f.check}: ${f.what}`) };+ } else warnings.push('qc-check lỗi: ' + q.error);+ log(` file ${checks.file.width}×${checks.file.height} ${checks.file.fps} ${checks.file.duration} s · ${checks.loudness.lufs} LUFS / ${checks.loudness.truePeak} dBTP · qc ${checks.qc?.verdict || '?'}`);+ for (const f of checks.qc?.fails || []) log(` qc FAIL ${f}`);+ });+ timings.total = +Object.entries(timings).filter(([k]) => !k.includes('(') && k !== 'total').reduce((s, [, v]) => s + v, 0).toFixed(1);+ log(`XONG ${out} (${timings.total} s)`);+ return { out, edl: edlFile };+}++/**+ * Sửa bằng lời: không phân tích lại. Ra out-r<n>.mp4 mới; EDL cũ → versions/edl-<n>.json.+ * opts: {log?, progress?}. Trả như editVideo (+ revision).+ */+export async function reviseEdit(id, instruction, opts = {}) {+ const dir = editDir(id);+ const R = runner(dir, opts);+ const { log, timings, checks, warnings, step } = R;+ const result = { ok: false, id, dir, revision: null, timings, checks, warnings };+ let backup = null;+ try {+ instruction = String(instruction || '').trim();+ if (!instruction) throw new Error('thiếu lời sửa');+ if (instruction.length > 1000) throw new Error('lời sửa quá dài (tối đa 1000 ký tự)');+ const state = readJson(path.join(dir, 'state.json'));+ const ing = readJson(path.join(dir, 'ingest.json'));+ const analysis = readJson(path.join(dir, 'analysis.json'));+ const curEdl = readJson(path.join(dir, 'edl.json'));+ if (!state || !ing || !analysis || !curEdl) throw new Error('bản dựng này chưa xong lần đầu (thiếu state/ingest/analysis/edl)');+ const style = { ...loadStyle(state.style), sfxNames: SFX_NAMES, hesitations: new Set(analysis.hesitations || []) };+ const words = wordList(analysis);+ const n = (state.revisions?.length || 0) + 1;+ log(`sửa lần ${n}: "${instruction}"`);+ const rev = await step('LLM lập EDL', () => proposeRevision({+ words, edl: curEdl, proposal: state.proposal, style: applyOverrides(style, state.overrides), overrides: state.overrides, instruction, names: state.names, log,+ }));+ const newCuts = rev.cutsOut.flatMap((c) => outputCutToSource(curEdl.keep, c.start, c.end, words));+ log(` LLM: ${rev.notes || '(không ghi chú)'}${newCuts.length ? ` · cắt thêm ${newCuts.map((c) => `${c.start.toFixed(2)}–${c.end.toFixed(2)} s nguồn`).join(', ')}` : ''}`);+ // giữ bản cũ+ const vdir = path.join(dir, 'versions');+ fs.mkdirSync(vdir, { recursive: true });+ backup = path.join(vdir, `edl-${n}.json`);+ fs.copyFileSync(path.join(dir, 'edl.json'), backup);+ const next = { ...state, proposal: rev.proposal, overrides: rev.overrides, extraCuts: [...(state.extraCuts || []), ...newCuts] };+ const edl = buildEdl({ id, ing, analysis, words, style, state: next, checks, log });+ const outName = `out-r${n}.mp4`;+ next.revisions = [...(state.revisions || []), { n, instruction, notes: rev.notes, at: new Date().toISOString(), previous: state.out || 'out.mp4', out: outName }];+ const r = await renderEdl({ dir, edl, draft: state.draft, R, outName });+ next.out = outName;+ fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(next, null, 1));+ Object.assign(result, r, { ok: true, revision: next.revisions[next.revisions.length - 1] });} catch (e) {result.error = e.message;log('LỖI: ' + e.message);+ // lỗi giữa chừng: trả edl.json về bản trước lần sửa (state.json chỉ ghi khi render xong nên vẫn là bản cũ)+ if (backup && fs.existsSync(backup)) fs.copyFileSync(backup, path.join(dir, 'edl.json'));}- save();+ const prevResult = readJson(path.join(dir, 'result.json'), {});+ fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ ...prevResult, ...(result.ok ? result : {}), lastRevise: { ok: result.ok, error: result.error || null, at: new Date().toISOString() } }, null, 2));return result;}diff --git a/edit/planner.mjs b/edit/planner.mjsindex f2fdc34..6e83a2d 100644--- a/edit/planner.mjs+++ b/edit/planner.mjs@@ -6,7 +6,7 @@ import path from 'node:path';import { spawnClaude, findClaude } from '../generator/claude.mjs';import { MODEL_IDS } from '../generator/config.mjs';import { ROOT } from './env.mjs';-import { EDL_VERSION, OUT, REMOVE_REASONS } from './edl.mjs';+import { EDL_VERSION, OUT, REMOVE_REASONS, toOutput, outputDuration } from './edl.mjs';export const STYLES_DIR = path.join(ROOT, 'edit-styles');const LLM_TIMEOUT_MS = 6 * 60 * 1000;@@ -62,7 +62,7 @@ function transcriptText(words) {return lines.join('\n');}-export function buildPrompt({ words, style, content, duration, errors, previous }) {+export function buildPrompt({ words, style, content, names, duration, errors, previous }) {const sfx = style.sfxNames.join(', ');return `Mày là biên tập viên video ngắn tiếng Việt. Video người dùng tự quay, nói trước máy, dài ${duration.toFixed(1)} giây.Nhiệm vụ: đọc lời chép (có số thứ tự từng chữ) và quyết theo THẺ KIỂU EDIT: bỏ đoạn nào, nhấn chữ nào, zoom và đặt tiếng động ở chữ nào, sửa chữ máy nghe sai.@@ -74,6 +74,9 @@ ${style.guide}# Lời dặn của người dùng${content?.trim() || '(không có)'}+# Tên riêng / thuật ngữ đúng (người dùng khai)+${namesText(names)}+# Lời chép (máy nghe, có thể sai chính tả; [i] là số thứ tự chữ; chữ có dấu "?" là chữ máy nghe lại lần 2 nhưng không chắc, thường nằm ở chỗ nói lại hoặc nói vấp)${transcriptText(words)}@@ -95,6 +98,14 @@ Luật:${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;}+export const parseNames = (names) => (Array.isArray(names) ? names : String(names || '').split(/[,;\n]/))+ .map((x) => String(x).trim()).filter(Boolean).slice(0, 40);+function namesText(names) {+ const list = parseNames(names);+ return list.length ? list.map((x) => '- ' + x).join('\n') + '\nChữ máy nghe gần giống các tên này thì sửa thành đúng tên. Ngoài các tên này, chỉ sửa chữ vô nghĩa rõ ràng.'+ : '(không có) — đừng tự đoán tên riêng.';+}+// ---- gọi Claude (không tool) -----------------------------------------------------------------------------------export function callClaude(prompt, { model = process.env.EDIT_MODEL || MODEL_IDS.sonnet, log = console.log } = {}) {if (!findClaude()) return Promise.reject(new Error('Không tìm thấy lệnh claude (cài Claude Code hoặc đặt CLAUDE_BIN)'));@@ -185,12 +196,12 @@ export function fallbackProposal(words, style) {}/** LLM lập đề xuất; sai thì gửi lỗi cho LLM sửa đúng 1 vòng; vẫn sai thì bỏ mục hỏng. */-export async function propose({ words, style, content, duration, llm = 'on', log = console.log }) {+export async function propose({ words, style, content, names, duration, llm = 'on', log = console.log }) {if (llm === 'off') return { proposal: fallbackProposal(words, style), rounds: 0, warnings: ['LLM tắt'], costUSD: 0 };const warnings = [];let text = ''; let cost = 0; let prev = null;for (let round = 1; round <= 2; round++) {- const prompt = buildPrompt({ words, style, content, duration, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '' });+ const prompt = buildPrompt({ words, style, content, names, duration, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '' });let checked;try {const r = await callClaude(prompt, { log });@@ -287,3 +298,152 @@ export function compileEdl({ id, ingestRes, analysis, words, proposal, style, munotes: proposal.notes || '',};}++// ---- sửa bằng lời (revise) ------------------------------------------------------------------------------------+// Người dùng nói "bỏ đoạn 12s", "zoom ít lại", "bỏ 3 giây đầu"… → LLM trả: đề xuất mới (cùng dạng propose),+// các khoảng cần cắt theo GIÂY CỦA VIDEO HIỆN TẠI, và vài núm chỉnh kiểu. Code đổi giây bản ra → giây nguồn (theo keep+// hiện tại), nới mép cắt cho trọn chữ, dựng lại EDL. KHÔNG phân tích lại video.++/** Khoảng giây bản ra [a,b) → các khoảng giây nguồn (trong keep); mép rơi giữa chữ thì nới ra trọn chữ. */+export function outputCutToSource(keep, a, b, words) {+ const res = [];+ let acc = 0;+ for (const k of keep) {+ const d = k.end - k.start;+ const lo = Math.max(a, acc); const hi = Math.min(b, acc + d);+ if (hi > lo) res.push({ start: k.start + (lo - acc), end: k.start + (hi - acc) });+ acc += d;+ }+ for (const c of res) {+ for (const w of words) {+ if (w.s < c.start && w.e > c.start) c.start = Math.max(0, w.s - 0.02);+ if (w.s < c.end && w.e > c.end) c.end = w.e + 0.02;+ }+ }+ return res;+}++/** Trừ các khoảng nguồn khỏi EDL (keep), lọc phụ đề/zoom/sfx rơi vào chỗ bỏ. */+export function applyExtraCuts(edl, cuts) {+ if (!cuts?.length) return edl;+ let keep = edl.keep.map((k) => ({ ...k }));+ for (const c of cuts) {+ const next = [];+ for (const k of keep) {+ if (c.end <= k.start || c.start >= k.end) { next.push(k); continue; }+ if (c.start > k.start) next.push({ start: k.start, end: +c.start.toFixed(3) });+ if (c.end < k.end) next.push({ start: +c.end.toFixed(3), end: k.end });+ }+ keep = next.filter((k) => k.end - k.start >= 1 / 30);+ }+ const inK = (t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6);+ const words = edl.captions.words.filter((w) => inK((w.start + w.end) / 2));+ const ids = new Set(words.map((w) => w.i));+ return {+ ...edl, keep,+ removed: [...edl.removed, ...cuts.map((c) => ({ start: +c.start.toFixed(3), end: +c.end.toFixed(3), reason: 'by-hand', words: '' }))].sort((x, y) => x.start - y.start),+ zooms: edl.zooms.filter((z) => inK(z.at)),+ sfx: edl.sfx.filter((x) => inK(x.at)),+ captions: { ...edl.captions, words, highlights: edl.captions.highlights.filter((i) => ids.has(i)) },+ };+}++/** Núm chỉnh kiểu mà lời sửa được phép đổi (kẹp vào khoảng an toàn). */+export function applyOverrides(style, ov = {}) {+ const { guide, hesitations, sfxNames, ...rest } = style;+ const st = { ...JSON.parse(JSON.stringify(rest)), guide, hesitations, sfxNames };+ const clamp = (v, a, b) => Math.min(b, Math.max(a, Number(v)));+ if (ov.zoomScale != null) st.zoom.scale = clamp(ov.zoomScale, 1, 1.6);+ if (ov.zoomMinGap != null) st.zoom.minGap = clamp(ov.zoomMinGap, 0.8, 60);+ if (ov.captionsMaxWords != null) st.captions.maxWords = Math.round(clamp(ov.captionsMaxWords, 1, 8));+ if (ov.musicGainDb != null) st.music.gainDb = clamp(ov.musicGainDb, -40, 0);+ if (ov.pause != null) st.pause = clamp(ov.pause, 0.15, 3);+ if (ov.sfxOff) { st.sfx.onZoom = null; st.sfx.max = 0; }+ return st;+}++function reviseText(words, keep) {+ // lời chép với mốc giây BẢN HIỆN TẠI cho chữ đang giữ; chữ đã bỏ đánh dấu ✗+ const lines = []; let line = [];+ const flush = () => { if (line.length) { lines.push(line.join(' ')); line = []; } };+ for (const w of words) {+ const to = toOutput(keep, (w.s + w.e) / 2);+ if (!line.length) line.push(to === null ? '(đã bỏ)' : `(${to.toFixed(1)}s)`);+ line.push(`[${w.i}]${w.w}${to === null ? '✗' : ''}`);+ if (/[.?!]$/.test(w.w) || line.length > 16) flush();+ }+ flush();+ return lines.join('\n');+}++export function buildRevisePrompt({ words, edl, proposal, style, overrides, instruction, names, errors, previous }) {+ const outDur = outputDuration(edl.keep);+ return `Mày là biên tập viên video ngắn tiếng Việt. Video đã dựng xong, dài ${outDur.toFixed(1)} giây (bản hiện tại). Người dùng muốn sửa:+"${instruction}"++Chỉ trả về MỘT khối JSON. Mốc giây người dùng nói là giây của BẢN HIỆN TẠI.++# Lời chép ([i] = số thứ tự chữ; đầu dòng là mốc giây bản hiện tại; chữ có ✗ là đã bỏ)+${reviseText(words, edl.keep)}++# Đề xuất hiện tại+${JSON.stringify({ drop: proposal.drop, highlights: proposal.highlights, zooms: proposal.zooms, sfx: proposal.sfx, fixes: proposal.fixes })}++# Núm chỉnh kiểu hiện tại (${style.name})+${JSON.stringify({ zoomScale: style.zoom.scale, zoomMinGap: style.zoom.minGap, captionsMaxWords: style.captions.maxWords, musicGainDb: style.music.gainDb, pause: style.pause, ...overrides })}++# Tên riêng đúng+${namesText(names)}++# Định dạng trả về+{+ "proposal": { "drop": [...], "highlights": [...], "zooms": [...], "sfx": [...], "fixes": [...] },+ "cut_output": [{"start": <giây bản hiện tại>, "end": <giây>}],+ "style": { "zoomScale"?: 1–1.6, "zoomMinGap"?: giây, "captionsMaxWords"?: 1–8, "musicGainDb"?: -40–0, "pause"?: giây, "sfxOff"?: true },+ "notes": "<1 câu: đã đổi gì>"+}+Luật:+- "proposal" là bản ĐẦY ĐỦ sau khi sửa (cùng luật như lúc dựng: drop theo chỉ số chữ, "filler" chỉ cho từ đệm, sửa chữ dùng fixes). Không đổi thì chép lại đề xuất hiện tại.+- Yêu cầu theo thời gian ("bỏ 3 giây đầu", "bỏ đoạn 12s–15s") → "cut_output" theo giây bản hiện tại. Yêu cầu theo lời ("bỏ câu chào") → drop theo chữ.+- "zoom ít lại" → bớt zooms và/hoặc tăng zoomMinGap; "zoom mạnh hơn" → tăng zoomScale. Chỉ đưa vào "style" núm nào thật sự đổi.+- Không làm gì ngoài lời người dùng.+${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;+}++/** LLM đọc lời sửa → {proposal, cutsOut, overrides, notes}. Sai → sửa 1 vòng; vẫn sai → báo lỗi (không đoán bừa). */+export async function proposeRevision({ words, edl, proposal, style, overrides = {}, instruction, names, log = console.log }) {+ let text = ''; let prev = null; let cost = 0;+ const outDur = outputDuration(edl.keep);+ for (let round = 1; round <= 2; round++) {+ const prompt = buildRevisePrompt({ words, edl, proposal, style, overrides, instruction, names, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '' });+ let errors = []; let out = null;+ try {+ const r = await callClaude(prompt, { log });+ text = r.text; cost += r.costUSD || 0;+ const j = parseProposal(text);+ const checked = checkProposal(j.proposal || proposal, words, style);+ errors = checked.errors;+ const cuts = Array.isArray(j.cut_output) ? j.cut_output : [];+ for (const c of cuts) {+ if (!(Number.isFinite(c?.start) && Number.isFinite(c?.end) && c.start >= 0 && c.end > c.start && c.start < outDur)) {+ errors.push(`cut_output ${JSON.stringify(c)} không hợp lệ (0–${outDur.toFixed(1)} s, start < end)`);+ }+ }+ const ov = {};+ for (const k of ['zoomScale', 'zoomMinGap', 'captionsMaxWords', 'musicGainDb', 'pause']) {+ if (j.style?.[k] == null) continue;+ if (!Number.isFinite(Number(j.style[k]))) errors.push(`style.${k} không phải số`); else ov[k] = Number(j.style[k]);+ }+ if (j.style?.sfxOff) ov.sfxOff = true;+ out = {+ proposal: { ...checked.clean, notes: String(j.notes || '') },+ cutsOut: cuts.map((c) => ({ start: c.start, end: Math.min(c.end, outDur) })),+ overrides: { ...overrides, ...ov }, notes: String(j.notes || ''), costUSD: cost, rounds: round,+ };+ } catch (e) { errors = [`không đọc được JSON: ${e.message}`]; }+ if (!errors.length) return out;+ log(`LLM sửa vòng ${round}: ${errors.slice(0, 3).join('; ')}`);+ prev = { errors };+ }+ throw new Error('LLM không hiểu được lời sửa sau 2 vòng: ' + prev.errors.slice(0, 3).join('; '));+}diff --git a/edit/py/lumedit.py b/edit/py/lumedit.pyindex 3d402d2..e0f19fb 100644--- a/edit/py/lumedit.py+++ b/edit/py/lumedit.py@@ -196,6 +196,9 @@ def _font(size: int):return ImageFont.truetype(str(path), size)+MIN_CARD, MERGE_BELOW = 0.25, 0.1++def caption_cards(edl: dict, tl) -> list[dict]:"""The caption words in cards of at most maxWords, broken at a sentence end or a pause, timedin output seconds. Shared by the draft and (through the same rule in Node) the main captions."""@@ -215,13 +218,31 @@ def caption_cards(edl: dict, tl) -> list[dict]:for c in cards:out.append({"words": c, "start": tl.to_output_nearest(c[0]["start"]),"end": tl.to_output_nearest(c[-1]["end"])})- for a, b in zip(out, out[1:]): # no flicker between cards close together+ out.sort(key=lambda c: c["start"])+ # Same rule as finishCards in edit/captions-hf.mjs: bridge short gaps, at least MIN_CARD on screen,+ # never past the next card's start (two cards are never on screen together), a card squeezed+ # under MERGE_BELOW joins the next one.+ for a, b in zip(out, out[1:]):if 0 <= b["start"] - a["end"] < 0.4:a["end"] = b["start"]for c in out:- c["end"] = max(c["end"], c["start"] + 0.25)- c["word_out"] = [tl.to_output_nearest(w["start"]) for w in c["words"]]- return out+ c["end"] = max(c["end"], c["start"] + MIN_CARD)+ for a, b in zip(out, out[1:]):+ a["end"] = min(a["end"], b["start"])+ merged = []+ for k, c in enumerate(out):+ nxt = out[k + 1] if k + 1 < len(out) else None+ if nxt is not None and c["end"] - c["start"] < MERGE_BELOW:+ nxt["words"] = c["words"] + nxt["words"]+ nxt["start"] = c["start"]+ continue+ merged.append(c)+ for c in merged:+ c["word_out"] = [max(c["start"], tl.to_output_nearest(w["start"])) for w in c["words"]]+ for a, b in zip(merged, merged[1:]):+ if a["end"] > b["start"] + 1e-6:+ raise ValueError(f"captions overlap at {b['start']:.2f} s")+ return mergedclass DraftCaptions:diff --git a/mcp/server.mjs b/mcp/server.mjsindex 159a6fa..f81e148 100644--- a/mcp/server.mjs+++ b/mcp/server.mjs@@ -18,6 +18,7 @@ import { rewriteScript } from '../generator/rewrite.mjs';import { reAudio, listVersions, saveAudioSpec } from '../generator/audio-job.mjs';import { MUSIC_STYLES } from '../engine/audio/music.mjs';import { audioOptions } from '../engine/audio/prefs.mjs';+import { createEdit, editView, editStyles, editReady, readEditJob, ID_RE as EDIT_ID_RE } from '../edit/jobs.mjs';const audioSchema = z.object({music: z.string().optional().describe(`auto | none | ${MUSIC_STYLES.join(' | ')}`),@@ -244,5 +245,82 @@ server.registerTool('list_jobs', {inputSchema: { limit: z.number().int().min(1).max(100).default(20) },}, async ({ limit }) => ({ content: [json(listJobs().slice(0, limit).map(jobSummary))] }));+// ---- Edit video của bạn (edit/) -----------------------------------------------------------------------------------+const editSummary = (id) => {+ const v = editView(id, { withLog: true });+ if (!v) return null;+ return {+ editId: v.id, status: v.status, action: v.action, step: v.step, pct: v.pct, stepIndex: v.stepIndex, steps: v.steps, error: v.error || null, reviseError: v.reviseError || null,+ style: v.style, source: v.source, music: v.music, names: v.names, draft: v.draft,+ files: v.files, fixes: v.fixes, revisions: v.revisions, checks: v.checks, timings: v.timings, log: (v.log || []).slice(-15),+ };+};+server.registerTool('edit_video', {+ title: 'Dựng lại video tự quay (Edit video)',+ description: [+ 'Dựng lại 1 video người dùng TỰ QUAY (nói trước máy, tiếng Việt) theo 1 kiểu edit: cắt ngập ngừng/nói lại (LLM), phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ khi nói, sfx, −14 LUFS → MP4 1080×1920.',+ 'Chạy ở tiến trình nền (vài phút: video 35 giây ≈ 3–4 phút trên RTX 3070 Ti). Trả editId ngay; gọi get_edit để xem tiến độ và đường dẫn MP4.',+ 'Cần cài 1 lần: node edit/setup.mjs. style: ' + (() => { try { return editStyles().map((x) => `${x.id} (${x.name})`).join(', '); } catch { return 'sach-gon, phu-de-nay-mau'; } })() + '.',+ ].join(' '),+ inputSchema: {+ path: z.string().min(1).describe('đường dẫn file video trên máy (mp4/mov/…)'),+ style: z.string().default('sach-gon'),+ music: z.string().optional().describe('đường dẫn file nhạc, hoặc tên nhạc tổng hợp: ' + MUSIC_STYLES.join(' | ') + ', hoặc none'),+ notes: z.string().max(2000).optional().describe('lời dặn thêm cho người dựng (vd "bỏ câu chào đầu")'),+ names: z.array(z.string()).max(40).optional().describe('tên riêng/thuật ngữ viết đúng, để LLM sửa chữ máy nghe sai (vd ["Lumfin"])'),+ draft: z.boolean().optional().describe('true: phụ đề nháp PIL (nhanh hơn ~1 phút)'),+ },+}, async ({ path: video, style, music, notes, names, draft }) => {+ try {+ const ready = editReady();+ if (!ready.ready) return fail(ready.note);+ let musicFile = null;+ if (music && music !== 'none') {+ if (MUSIC_STYLES.includes(music)) {+ const { writeMusic } = await import('../engine/audio/music.mjs');+ const f = path.join(ROOT, 'engine', 'audio', 'samples', `music-${music}-60s.wav`);+ if (!fs.existsSync(f)) { fs.mkdirSync(path.dirname(f), { recursive: true }); writeMusic(music, f, 60, 1); }+ musicFile = f;+ } else musicFile = music;+ }+ const job = createEdit({ video, style, music: musicFile, content: notes, names, draft });+ const p = spawn(process.execPath, [path.join(ROOT, 'cli.mjs'), 'edit-run', job.id], { cwd: ROOT, detached: true, stdio: 'ignore', windowsHide: true, env: process.env });+ p.unref();+ return { content: [json({ ...editSummary(job.id), note: 'Đang dựng ở tiến trình nền. Gọi get_edit sau 1–2 phút.' })] };+ } catch (e) { return fail(e.message); }+});++server.registerTool('revise_edit', {+ title: 'Sửa bản edit bằng lời',+ description: 'Sửa 1 bản Edit video đã dựng xong bằng lời ("bỏ 3 giây đầu", "bỏ đoạn 12s", "zoom ít lại", "nhạc nhỏ lại"): LLM sửa EDL rồi render lại, KHÔNG phân tích lại. Bản cũ giữ ở versions/out-<n>.mp4. Chạy nền; gọi get_edit để xem.',+ inputSchema: { editId: z.string().regex(EDIT_ID_RE), instruction: z.string().min(1).max(1000) },+}, async ({ editId, instruction }) => {+ try {+ const job = readEditJob(editId);+ if (!job) return fail('Không thấy edit ' + editId);+ if (['queued', 'running'].includes(job.status)) return fail('Edit này đang chạy, chờ xong rồi sửa (get_edit).');+ if (!fs.existsSync(path.join(ROOT, 'edits', editId, 'state.json'))) return fail('Edit này chưa dựng xong lần đầu.');+ const p = spawn(process.execPath, [path.join(ROOT, 'cli.mjs'), 'edit-revise', editId, instruction], { cwd: ROOT, detached: true, stdio: 'ignore', windowsHide: true, env: process.env });+ p.unref();+ await new Promise((r) => setTimeout(r, 1500));+ return { content: [json({ ...editSummary(editId), note: 'Đang sửa + render lại ở tiến trình nền. Gọi get_edit sau 1–2 phút.' })] };+ } catch (e) { return fail(e.message); }+});++server.registerTool('get_edit', {+ title: 'Trạng thái Edit video',+ description: 'Trạng thái, bước đang chạy, đường dẫn MP4/EDL, chữ LLM đã sửa (để người xem lại), các lần sửa, kết quả kiểm và log cuối của 1 bản Edit video. Không truyền editId → danh sách gần nhất + kiểu edit có sẵn.',+ inputSchema: { editId: z.string().regex(EDIT_ID_RE).optional() },+}, async ({ editId }) => {+ try {+ if (!editId) {+ const { listEdits } = await import('../edit/jobs.mjs');+ return { content: [json({ ready: editReady(), styles: editStyles(), edits: listEdits(20).map((v) => ({ editId: v.id, status: v.status, style: v.style, source: v.sourceName, out: v.files.out, updatedAt: v.updatedAt })) })] };+ }+ const v = editSummary(editId);+ return v ? { content: [json(v)] } : fail('Không thấy edit ' + editId);+ } catch (e) { return fail(e.message); }+});+await server.connect(new StdioServerTransport());console.error('[lumreels mcp] sẵn sàng (stdio)');diff --git a/scripts/mcp-smoke.mjs b/scripts/mcp-smoke.mjsindex a1a9fba..7d33aa3 100644--- a/scripts/mcp-smoke.mjs+++ b/scripts/mcp-smoke.mjs@@ -24,6 +24,10 @@ const call = async (name, args, opts) => {const tools = await client.listTools();console.log('tools:', tools.tools.map((t) => t.name).join(', '));+for (const t of ['edit_video', 'revise_edit', 'get_edit']) if (!tools.tools.some((x) => x.name === t)) { console.error('thiếu tool ' + t); process.exitCode = 1; }+await call('get_edit', {});+await call('edit_video', { path: path.join(ROOT, 'khong-co-file.mp4') }); // phải báo lỗi rõ ràng+await call('revise_edit', { editId: '../../etc', instruction: 'x' }); // phải bị chặnawait call('list_templates', { query: 'tài chính' });const gt = await call('get_template', { id: '009' });if (gt.isError || !gt.content[0].text.includes('Ví dụ chỉ để hiểu định dạng ô')) { console.error('get_template thiếu guidance'); process.exitCode = 1; }diff --git a/server/public/edit-panel.css b/server/public/edit-panel.cssnew file mode 100644index 0000000..25dc8d9--- /dev/null+++ b/server/public/edit-panel.css@@ -0,0 +1,83 @@+/* Tab "Edit video của bạn" — dùng chung token của style.css */+.tabs { display: flex; gap: 8px; padding: 4px 24px 0; flex-wrap: wrap; }+.tab { min-height: 44px; padding: 0 18px; border-radius: 999px; border: 1px solid var(--line); background: var(--panel); color: var(--ink-2); font: 700 18px/1 var(--cond); text-transform: uppercase; letter-spacing: .04em; cursor: pointer; transition: background .15s, color .15s; }+.tab:hover { color: var(--ink); }+.tab[aria-selected="true"] { background: var(--ink); color: var(--bg); border-color: var(--ink); }+.tab .new { font: 600 11px/1 var(--mono); color: var(--accent); margin-left: 6px; vertical-align: 2px; }+.tab[aria-selected="true"] .new { color: var(--accent); }++.edit-wrap { display: grid; grid-template-columns: 380px minmax(0, 1fr); gap: 24px; padding: 16px 24px 48px; }+.edit-wrap[hidden], .layout[hidden] { display: none; }+.ed-card { background: var(--panel); border: 1px solid var(--line); border-radius: 18px; padding: 20px; }+.ed-setup { grid-column: 1 / -1; border-left: 3px solid var(--warn); }+.ed-setup h3 { margin: 0 0 6px; font: 700 20px/1.2 var(--cond); text-transform: uppercase; letter-spacing: .03em; }+.ed-setup p { margin: 0; color: var(--ink-2); font-size: 15px; }++.drop { display: grid; place-items: center; text-align: center; gap: 6px; min-height: 150px; padding: 18px; border: 2px dashed var(--line); border-radius: 14px; background: var(--bg); cursor: pointer; transition: border-color .15s, background .15s; }+.drop:hover, .drop.over { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 6%, var(--bg)); }+.drop svg { width: 34px; height: 34px; fill: none; stroke: var(--accent); stroke-width: 1.8; }+.drop .big { font-weight: 700; font-size: 16px; }+.drop .small { font-size: 13px; color: var(--ink-3); }+.drop.has { border-style: solid; border-color: var(--ok); }+.drop.has .big { color: var(--ok); word-break: break-all; }++.styles { display: grid; gap: 8px; }+.sty { text-align: left; min-height: 56px; padding: 10px 12px; border-radius: 12px; border: 1px solid var(--line); background: var(--panel-2); cursor: pointer; transition: border-color .15s; }+.sty .n { font-weight: 700; display: block; }+.sty .d { font-size: 13px; color: var(--ink-2); display: block; line-height: 1.4; margin-top: 2px; }+.sty[aria-checked="true"] { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(255,107,44,.18); }+.ed-in { width: 100%; min-height: 44px; background: var(--bg); border: 1px solid var(--line); border-radius: 10px; padding: 0 12px; }+.ed-row { display: flex; gap: 8px; align-items: center; }+.ed-row select { flex: 1; }+.ed-file { font-size: 13px; color: var(--ink-2); margin-top: 6px; word-break: break-all; }+.ed-check { display: flex; gap: 8px; align-items: center; min-height: 44px; color: var(--ink-2); font-size: 15px; cursor: pointer; }+.ed-check input { width: 18px; height: 18px; accent-color: var(--accent); }+.edit-wrap textarea { min-height: 84px; }++.ed-main { display: grid; gap: 16px; align-content: start; }+.ed-empty { color: var(--ink-3); text-align: center; padding: 48px 24px; border: 1px dashed var(--line); border-radius: 18px; background: var(--panel); }+.ed-view { display: grid; grid-template-columns: minmax(220px, 300px) minmax(0, 1fr); gap: 20px; align-items: start; }+.ed-media { aspect-ratio: 9 / 16; background: #000; border-radius: 12px; overflow: hidden; display: grid; place-items: center; color: var(--ink-3); font-size: 14px; text-align: center; padding: 0; }+.ed-media video, .ed-media img { width: 100%; height: 100%; object-fit: contain; display: block; }+.ed-head { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-bottom: 8px; }+.ed-head .tt { font-weight: 700; word-break: break-all; }+.ed-head .jid { font: 500 13px var(--mono); color: var(--ink-3); }++.steps { list-style: none; margin: 10px 0; padding: 0; display: grid; gap: 4px; }+.steps li { display: grid; grid-template-columns: 22px 1fr auto; gap: 8px; align-items: center; font-size: 14px; color: var(--ink-3); min-height: 26px; }+.steps li::before { content: ''; width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--line); justify-self: center; }+.steps li.done { color: var(--ink-2); } .steps li.done::before { background: var(--ok); border-color: var(--ok); }+.steps li.now { color: var(--ink); font-weight: 600; } .steps li.now::before { background: var(--accent); border-color: var(--accent); animation: pulse 1s ease-in-out infinite; }+.steps li .pc { font: 500 12px var(--mono); color: var(--ink-3); }+.bar { height: 6px; border-radius: 3px; background: var(--panel-2); overflow: hidden; margin: 6px 0 2px; }+.bar > i { display: block; height: 100%; width: 0; background: var(--accent); border-radius: 3px; transition: width .3s ease-out; }++.fixes { margin-top: 12px; }+.fixes h4, .ed-revise h4, .ed-hist h4 { margin: 0 0 6px; font-size: 14px; color: var(--ink-2); font-weight: 600; }+.fixes ul { margin: 0; padding: 0; list-style: none; display: flex; flex-wrap: wrap; gap: 6px; }+.fixes li { font-size: 14px; padding: 4px 10px; border-radius: 999px; background: var(--panel-2); border: 1px solid var(--line); }+.fixes li s { color: var(--ink-3); }+.fixes li b { color: var(--warn); font-weight: 600; }+.ed-revise { margin-top: 14px; }+.ed-revise .ed-row { align-items: stretch; }+.ed-revise input { flex: 1; }+.ed-revise button { min-height: 44px; padding: 0 16px; border-radius: 10px; border: 0; background: var(--accent); color: var(--accent-ink); font-weight: 700; cursor: pointer; white-space: nowrap; }+.ed-revise button:disabled { background: var(--panel-2); color: var(--ink-3); cursor: not-allowed; }+.ed-presets { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px; }+.ed-presets button { min-height: 36px; padding: 0 12px; border-radius: 999px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink-2); font-size: 13px; cursor: pointer; }+.ed-presets button:hover { color: var(--ink); }+.ed-hist ol { margin: 0; padding-left: 20px; color: var(--ink-2); font-size: 14px; }+.ed-checks { font-size: 13px; color: var(--ink-3); margin-top: 8px; line-height: 1.5; }+.ed-checks .ok { color: var(--ok); } .ed-checks .bad { color: var(--bad); }+.ed-list { display: grid; gap: 8px; }+.ed-item { display: grid; grid-template-columns: 1fr auto; gap: 8px; align-items: center; text-align: left; min-height: 52px; padding: 8px 12px; border-radius: 12px; border: 1px solid var(--line); background: var(--panel); cursor: pointer; }+.ed-item.sel { border-color: var(--accent); }+.ed-item .t { font-weight: 600; font-size: 14px; word-break: break-all; }+.ed-item .s { font: 500 12px var(--mono); color: var(--ink-3); }++@media (max-width: 900px) {+ .tabs { padding: 4px 16px 0; }+ .edit-wrap { grid-template-columns: 1fr; padding: 12px 16px 120px; }+ .ed-view { grid-template-columns: 1fr; }+ .ed-media { max-width: 320px; width: 100%; justify-self: center; }+}diff --git a/server/public/edit-panel.js b/server/public/edit-panel.jsnew file mode 100644index 0000000..0095d43--- /dev/null+++ b/server/public/edit-panel.js@@ -0,0 +1,210 @@+// Tab "Edit video của bạn": tải video tự quay lên, chọn kiểu edit, dựng, xem tiến độ, sửa bằng lời.+// API: GET /api/edit-options, GET/POST /api/edits, GET /api/edits/:id, POST /api/edits/:id/revise (edit/http.mjs)+(() => {+ const $ = (s, r = document) => r.querySelector(s);+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+ const fmtMB = (b) => (b >= 1e9 ? (b / 1e9).toFixed(2) + ' GB' : Math.max(1, Math.round(b / 1e6)) + ' MB');+ const ST_LABEL = { queued: 'Đang chờ', running: 'Đang dựng', done: 'Xong', error: 'Lỗi' };++ const state = { opts: null, style: null, video: null, music: null, current: null, timer: null, uploading: false };++ // ---- tab ------------------------------------------------------------------------------------------------------+ const tabs = document.querySelectorAll('.tab');+ function show(which) {+ tabs.forEach((t) => t.setAttribute('aria-selected', String(t.dataset.tab === which)));+ $('main.layout').hidden = which !== 'tpl';+ $('#editTab').hidden = which !== 'edit';+ try { localStorage.setItem('lumreels.tab', which); } catch { /* bỏ qua */ }+ if (which === 'edit' && !state.opts) init();+ }+ tabs.forEach((t) => t.addEventListener('click', () => show(t.dataset.tab)));+ document.addEventListener('keydown', (e) => {+ if (!e.target.closest?.('.tabs') || !['ArrowLeft', 'ArrowRight'].includes(e.key)) return;+ const list = [...tabs]; const i = list.indexOf(document.activeElement);+ const n = list[(i + (e.key === 'ArrowRight' ? 1 : list.length - 1)) % list.length]; n.focus(); n.click();+ });++ // ---- form ------------------------------------------------------------------------------------------------------+ async function init() {+ try {+ state.opts = await fetch('/api/edit-options').then((r) => r.json());+ } catch { $('#edSetup').hidden = false; $('#edSetupText').textContent = 'Không gọi được server.'; return; }+ const o = state.opts;+ if (!o.ready) { $('#edSetup').hidden = false; $('#edSetupText').innerHTML = `${esc(o.note)}`; $('#edSetupCmd').textContent = o.setup; }+ state.style = o.styles[0]?.id || null;+ $('#edStyles').innerHTML = o.styles.map((s, i) => `<button type="button" class="sty" role="radio" aria-checked="${i === 0}" data-id="${esc(s.id)}"><span class="n">${esc(s.name)}</span><span class="d">${esc(s.summary)}</span></button>`).join('');+ $('#edMusic').innerHTML = '<option value="none">Không nhạc</option>'+ + o.music.map((m) => `<option value="${esc(m.id)}">Nhạc tổng hợp: ${esc(m.id)} — ${esc(m.desc)}</option>`).join('')+ + '<option value="file">Tải file nhạc của tôi…</option>';+ refreshGo();+ loadList();+ }+ $('#edStyles').addEventListener('click', (e) => {+ const b = e.target.closest('.sty'); if (!b) return;+ state.style = b.dataset.id;+ document.querySelectorAll('#edStyles .sty').forEach((x) => x.setAttribute('aria-checked', String(x === b)));+ });+ $('#edMusic').addEventListener('change', () => {+ const f = $('#edMusic').value === 'file';+ $('#edMusicFile').hidden = !f;+ if (f) $('#edMusicFile').click(); else { state.music = null; $('#edMusicName').textContent = ''; }+ });+ $('#edMusicFile').addEventListener('change', (e) => { state.music = e.target.files[0] || null; $('#edMusicName').textContent = state.music ? `${state.music.name} · ${fmtMB(state.music.size)}` : ''; });++ const drop = $('#edDrop');+ const pickVideo = (f) => {+ if (!f) return;+ if (!/^video\//.test(f.type) && !/\.(mp4|mov|m4v|mkv|webm|avi|3gp)$/i.test(f.name)) { setErr('File này không phải video (mp4, mov, mkv, webm…).'); return; }+ if (state.opts && f.size > state.opts.maxUploadBytes) { setErr(`Video ${fmtMB(f.size)} quá lớn (tối đa 2 GB).`); return; }+ state.video = f; setErr('');+ drop.classList.add('has');+ $('.big', drop).textContent = f.name;+ $('.small', drop).textContent = `${fmtMB(f.size)} · bấm để đổi file`;+ refreshGo();+ };+ drop.addEventListener('click', () => $('#edVideo').click());+ drop.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); $('#edVideo').click(); } });+ $('#edVideo').addEventListener('change', (e) => pickVideo(e.target.files[0]));+ ['dragenter', 'dragover'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('over'); }));+ ['dragleave', 'drop'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.remove('over'); }));+ drop.addEventListener('drop', (e) => pickVideo(e.dataTransfer.files[0]));++ const setErr = (t) => { $('#edErr').textContent = t; };+ function refreshGo() { $('#edGo').disabled = !(state.opts?.ready && state.video && state.style) || state.uploading; }++ $('#edGo').addEventListener('click', () => {+ if ($('#edMusic').value === 'file' && !state.music) { setErr('Chọn file nhạc, hoặc đổi sang "Không nhạc".'); return; }+ const fd = new FormData();+ fd.append('style', state.style);+ fd.append('content', $('#edNotes').value.trim());+ fd.append('names', $('#edNames').value.trim());+ fd.append('draft', $('#edDraft').checked ? '1' : '0');+ const mv = $('#edMusic').value;+ if (mv !== 'file') fd.append('musicStyle', mv);+ if (mv === 'file' && state.music) fd.append('music', state.music, state.music.name);+ fd.append('video', state.video, state.video.name); // file sau cùng: trường chữ tới server trước+ state.uploading = true; refreshGo(); setErr('');+ const goLabel = $('#edGo span');+ const xhr = new XMLHttpRequest();+ xhr.open('POST', '/api/edits');+ xhr.upload.onprogress = (e) => { if (e.lengthComputable) goLabel.textContent = `Đang tải lên ${Math.round((e.loaded / e.total) * 100)}%`; };+ xhr.onload = () => {+ state.uploading = false; goLabel.textContent = 'Dựng'; refreshGo();+ let j = {}; try { j = JSON.parse(xhr.responseText); } catch { /* bỏ qua */ }+ if (xhr.status !== 202) { setErr(j.error || `Lỗi ${xhr.status}`); return; }+ select(j.id, j); loadList();+ };+ xhr.onerror = () => { state.uploading = false; goLabel.textContent = 'Dựng'; refreshGo(); setErr('Tải lên bị ngắt. Kiểm tra server rồi thử lại.'); };+ xhr.send(fd);+ });++ // ---- bản đang xem ------------------------------------------------------------------------------------------------+ async function loadList() {+ let list = [];+ try { list = await fetch('/api/edits').then((r) => r.json()); } catch { return; }+ $('#edList').innerHTML = list.length ? list.map((v) => `<button type="button" class="ed-item${v.id === state.current ? ' sel' : ''}" data-id="${esc(v.id)}">+ <span><span class="t">${esc(v.sourceName || v.id)}</span><br><span class="s">${esc(v.styleName || v.style)} · ${esc(v.id)}</span></span>+ <span class="st ${v.status === 'done' ? 'done' : v.status === 'error' ? 'error' : 'run'}">${esc(ST_LABEL[v.status] || v.status)}</span></button>`).join('')+ : '<div class="hint">Chưa có bản nào.</div>';+ if (!state.current && list[0]) select(list[0].id, list[0]);+ }+ $('#edList').addEventListener('click', (e) => { const b = e.target.closest('.ed-item'); if (b) select(b.dataset.id); });++ function select(id, view) {+ state.current = id;+ document.querySelectorAll('.ed-item').forEach((b) => b.classList.toggle('sel', b.dataset.id === id));+ if (view) render(view);+ poll();+ }+ async function poll() {+ clearTimeout(state.timer);+ const id = state.current; if (!id) return;+ let v;+ try { v = await fetch(`/api/edits/${encodeURIComponent(id)}`).then((r) => r.json()); } catch { state.timer = setTimeout(poll, 3000); return; }+ if (id !== state.current) return;+ render(v);+ if (['queued', 'running'].includes(v.status)) state.timer = setTimeout(poll, 1500);+ else loadList();+ }++ let lastOut = null;+ function render(v) {+ $('#edEmpty').hidden = true; $('#edView').hidden = false;+ const busy = ['queued', 'running'].includes(v.status);+ $('#edTitle').textContent = v.sourceName || v.id;+ $('#edId').textContent = `${v.styleName || v.style} · ${v.id}`;+ const st = $('#edStatus');+ st.className = 'st ' + (v.status === 'done' ? 'done' : v.status === 'error' ? 'error' : 'run');+ st.textContent = busy ? (v.status === 'queued' ? 'Đang chờ lượt' : v.action === 'revise' ? 'Đang sửa' : 'Đang dựng') : (ST_LABEL[v.status] || v.status);+ // bước+ const steps = v.steps || [];+ const from = v.action === 'revise' ? 2 : 0;+ $('#edSteps').innerHTML = steps.map((s, i) => {+ let cls = '';+ if (i < from && v.action === 'revise') cls = 'done';+ else if (v.status === 'done') cls = 'done';+ else if (busy && i < v.stepIndex) cls = 'done';+ else if (busy && i === v.stepIndex) cls = 'now';+ return `<li class="${cls}"><span>${esc(s)}</span><span class="pc">${cls === 'now' ? `${v.pct || 0}%` : ''}</span></li>`;+ }).join('');+ const doneSteps = v.status === 'done' ? steps.length : Math.max(0, v.stepIndex) + (v.pct || 0) / 100;+ $('#edBar').style.width = `${Math.min(100, (doneSteps / Math.max(1, steps.length)) * 100)}%`;+ $('#edBarWrap').hidden = !busy;+ $('#edNote').textContent = busy ? (v.note || '') : '';+ // lỗi+ $('#edViewErr').textContent = v.status === 'error' ? (v.error || 'Lỗi') : v.reviseError ? `Sửa chưa được: ${v.reviseError}` : '';+ // video+ const media = $('#edMedia');+ if (v.links?.out && v.links.out !== lastOut) {+ lastOut = v.links.out;+ media.innerHTML = `<video controls playsinline preload="metadata" src="${esc(v.links.out)}"></video>`;+ } else if (!v.links?.out) {+ lastOut = null;+ media.innerHTML = v.links?.preview ? `<img src="${esc(v.links.preview)}" alt="Lưới khung xem trước">` : '<span>Video sẽ hiện ở đây khi dựng xong</span>';+ }+ $('#edLinks').innerHTML = [+ v.links?.out ? `<a href="${esc(v.links.out)}" download>Tải MP4</a>` : '',+ v.links?.previewFinal ? `<a href="${esc(v.links.previewFinal)}" target="_blank" rel="noopener">Lưới khung bản ra</a>` : '',+ v.links?.edl ? `<a href="${esc(v.links.edl)}" target="_blank" rel="noopener">EDL</a>` : '',+ ].join('');+ // chữ LLM sửa+ const fx = v.fixes || [];+ $('#edFixes').hidden = !fx.length;+ $('#edFixList').innerHTML = fx.map((f) => `<li><s>${esc(f.heard)}</s> → <b>${f.text ? esc(f.text) : '(ẩn khỏi phụ đề)'}</b></li>`).join('');+ // kiểm+ const c = v.checks || {};+ const bits = [];+ if (c.edl) bits.push(`${c.edl.outSeconds ?? ''} s · bỏ ${c.edl.removedSeconds} s · ${c.edl.zooms} zoom`);+ if (c.overcut) bits.push(c.overcut.lost?.length || c.overcut.chopped?.length ? `<span class="bad">lẹm chữ: ${esc(c.overcut.verdict)}</span>` : '<span class="ok">không lẹm chữ</span>');+ if (c.loudness) bits.push(`${c.loudness.lufs} LUFS`);+ if (c.qc?.fails?.length) bits.push(`qc: ${esc(c.qc.fails.join('; '))}`);+ $('#edChecks').innerHTML = bits.join(' · ');+ // sửa bằng lời+ $('#edReviseBtn').disabled = busy || v.status !== 'done';+ $('#edRevise').hidden = !(v.links?.out || v.status === 'done');+ const revs = v.revisions || [];+ $('#edHist').hidden = !revs.length;+ $('#edHistList').innerHTML = revs.map((r) => `<li>"${esc(r.instruction)}"${r.notes ? ` — ${esc(r.notes)}` : ''}</li>`).join('');+ $('#edLog').textContent = (v.log || []).join('\n');+ }++ async function revise(text) {+ if (!state.current || !text) return;+ $('#edReviseBtn').disabled = true;+ try {+ const r = await fetch(`/api/edits/${encodeURIComponent(state.current)}/revise`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ instruction: text }) });+ const j = await r.json();+ if (!r.ok) { $('#edViewErr').textContent = j.error || `Lỗi ${r.status}`; $('#edReviseBtn').disabled = false; return; }+ $('#edReviseText').value = '';+ render(j); poll();+ } catch { $('#edViewErr').textContent = 'Không gửi được lời sửa.'; $('#edReviseBtn').disabled = false; }+ }+ $('#edReviseForm').addEventListener('submit', (e) => { e.preventDefault(); revise($('#edReviseText').value.trim()); });+ $('#edPresets').addEventListener('click', (e) => { const b = e.target.closest('button'); if (b) $('#edReviseText').value = b.textContent; $('#edReviseText').focus(); });++ // mở lại tab đã chọn lần trước+ let saved = 'tpl';+ try { saved = localStorage.getItem('lumreels.tab') || 'tpl'; } catch { /* bỏ qua */ }+ if (location.hash === '#edit') saved = 'edit';+ show(saved);+})();diff --git a/server/public/index.html b/server/public/index.htmlindex 5dae790..f39e2e7 100644--- a/server/public/index.html+++ b/server/public/index.html@@ -6,6 +6,7 @@<title>LumReels — dựng video dọc từ mẫu</title><link rel="stylesheet" href="/fonts/fonts.css" /><link rel="stylesheet" href="/style.css" />+<link rel="stylesheet" href="/edit-panel.css" /></head><body><header class="top">@@ -17,7 +18,12 @@<button type="button" class="ub-close" aria-label="Ẩn thông báo">×</button></div>-<main class="layout">+<nav class="tabs" role="tablist" aria-label="Chế độ">+ <button type="button" class="tab" role="tab" data-tab="tpl" aria-selected="true" aria-controls="tplTab">Dựng từ mẫu</button>+ <button type="button" class="tab" role="tab" data-tab="edit" aria-selected="false" aria-controls="editTab">Edit video của bạn<span class="new">MỚI</span></button>+</nav>++<main class="layout" id="tplTab" role="tabpanel"><section class="pick" aria-labelledby="h-pick"><div class="sec-head"><h2 id="h-pick"><span class="step">1</span>Chọn mẫu</h2>@@ -111,6 +117,74 @@</section></main>+<section class="edit-wrap" id="editTab" role="tabpanel" aria-label="Edit video của bạn" hidden>+ <div class="ed-card ed-setup" id="edSetup" hidden>+ <h3>Chưa cài phần Edit video</h3>+ <p id="edSetupText"></p>+ <div class="cmd" id="edSetupCmd">node edit/setup.mjs</div>+ </div>+ <div class="ed-card">+ <h2><span class="step">1</span>Video của bạn</h2>+ <div class="drop" id="edDrop" role="button" tabindex="0" aria-label="Chọn hoặc kéo thả video">+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 16V4m0 0-4 4m4-4 4 4"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/></svg>+ <span class="big">Kéo thả video vào đây</span>+ <span class="small">hoặc bấm để chọn · mp4, mov, mkv… tối đa 2 GB · nói trước máy, tiếng Việt</span>+ </div>+ <input type="file" id="edVideo" accept="video/*,.mkv,.mov" hidden />+ <label class="field">Kiểu edit</label>+ <div class="styles" id="edStyles" role="radiogroup" aria-label="Kiểu edit"></div>+ <label class="field" for="edMusic">Nhạc nền <span class="opt">(tự hạ khi bạn nói)</span></label>+ <select id="edMusic"><option value="none">Không nhạc</option></select>+ <input type="file" id="edMusicFile" accept="audio/*" hidden />+ <div class="ed-file" id="edMusicName"></div>+ <label class="field" for="edNames">Tên riêng, thuật ngữ <span class="opt">(để AI viết phụ đề đúng)</span></label>+ <input class="ed-in" id="edNames" type="text" maxlength="400" placeholder="Ví dụ: Lumfin, Hà Nội, ETF" autocomplete="off" />+ <label class="field" for="edNotes">Dặn thêm <span class="opt">(không bắt buộc)</span></label>+ <textarea id="edNotes" rows="3" maxlength="2000" placeholder="Ví dụ: bỏ câu chào đầu, giữ đoạn cuối kêu gọi theo dõi"></textarea>+ <label class="ed-check"><input type="checkbox" id="edDraft" /> Bản nháp nhanh (phụ đề đơn giản, nhanh hơn ~1 phút)</label>+ <p class="err" id="edErr" role="alert"></p>+ <button id="edGo" class="go" disabled>+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4v16l13-8z"/></svg>+ <span>Dựng</span>+ </button>+ </div>+ <div class="ed-main">+ <div class="ed-empty" id="edEmpty">Chọn video bên trái rồi bấm Dựng. Bản dựng sẽ hiện ở đây: tiến độ từng bước, video ra, chữ AI đã sửa, và ô sửa bằng lời.</div>+ <div class="ed-card" id="edView" hidden>+ <div class="ed-view">+ <div class="ed-media" id="edMedia"></div>+ <div>+ <div class="ed-head"><span class="tt" id="edTitle"></span><span class="st" id="edStatus"></span></div>+ <div class="jid" id="edId"></div>+ <div class="bar" id="edBarWrap" hidden><i id="edBar"></i></div>+ <div class="hint" id="edNote" aria-live="polite"></div>+ <ol class="steps" id="edSteps" aria-label="Các bước"></ol>+ <div class="errmsg" id="edViewErr" role="alert"></div>+ <div class="links" id="edLinks"></div>+ <div class="ed-checks" id="edChecks"></div>+ <div class="fixes" id="edFixes" hidden>+ <h4>Chữ AI đã sửa trong phụ đề, xem lại giúp</h4>+ <ul id="edFixList"></ul>+ </div>+ <div class="ed-revise" id="edRevise" hidden>+ <h4>Sửa bằng lời</h4>+ <form id="edReviseForm" class="ed-row">+ <label class="sr" for="edReviseText">Lời sửa</label>+ <input class="ed-in" id="edReviseText" type="text" maxlength="1000" placeholder='Ví dụ: "bỏ 3 giây đầu", "zoom ít lại"' autocomplete="off" />+ <button type="submit" id="edReviseBtn">Render lại</button>+ </form>+ <div class="ed-presets" id="edPresets"><button type="button">bỏ 3 giây đầu</button><button type="button">zoom ít lại</button><button type="button">nhạc nhỏ lại</button><button type="button">phụ đề 2 chữ một lần</button></div>+ </div>+ <div class="ed-hist" id="edHist" hidden><h4>Các lần sửa</h4><ol id="edHistList"></ol></div>+ <details class="log"><summary>Nhật ký</summary><pre id="edLog"></pre></details>+ </div>+ </div>+ </div>+ <h2>Các bản đã dựng</h2>+ <div class="ed-list" id="edList"></div>+ </div>+</section>+<dialog id="viewer" aria-label="Video minh hoạ của mẫu"><div class="dlg-head"><strong id="vTitle"></strong><button class="x" id="vClose" aria-label="Đóng">×</button></div><video id="vVideo" controls playsinline preload="metadata"></video>@@ -119,5 +193,6 @@<script src="/audio-panel.js"></script><script src="/app.js"></script>+<script src="/edit-panel.js"></script></body></html>diff --git a/server/server.mjs b/server/server.mjsindex dc495fb..812130a 100644--- a/server/server.mjs+++ b/server/server.mjs@@ -15,6 +15,7 @@ import { reAudio, listVersions, audioBusy, saveAudioSpec } from '../generator/auimport { audioOptions, normalizeAudioPrefs, voiceEngine, sampleTextFor } from '../engine/audio/prefs.mjs';import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';import { synthVoice } from '../engine/audio/voice.mjs';+import { handleEditRoute, initEdits } from '../edit/http.mjs';const AUDIO_SAMPLES = path.join(ROOT, 'engine', 'audio', 'samples');/** File nghe thử (cache trong engine/audio/samples/, chỉ sinh khi chưa có). Trả đường dẫn tuyệt đối. */@@ -193,6 +194,8 @@ const server = http.createServer(async (req, res) => {// Chống DNS rebinding: chỉ nhận Host là 127.0.0.1/localhost đúng cổng.if (!ALLOWED_HOSTS.has(String(req.headers.host || '').toLowerCase())) return send(res, 421, { error: 'host không hợp lệ' });try {+ // ---- Edit video của bạn (edit/http.mjs) ----+ if (await handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;// ---- API ----if (p === '/api/templates' && req.method === 'GET') return send(res, 200, templateList());if (p === '/api/version' && req.method === 'GET') return send(res, 200, { version: PKG_VERSION, update: updateState });@@ -295,6 +298,7 @@ const server = http.createServer(async (req, res) => {});markStale();+initEdits(); // edit đang chạy dở khi server tắt → báo lỗi để bấm lại// Job queued còn sót (server tắt trước khi kịp chạy) → chạy lại.for (const j of listJobs()) if (j.status === 'queued' && resolveMode(j.mode) !== 'manual') enqueueJob(j.id, () => runJob(j.id));// Bộ hẹn giờ: 15 giây kiểm 1 lần, job tới giờ thì xếp hàng chạy.