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.
Âm thanh, ảnh mẫu, thời lượng tự gõ, viết lại kịch bản
Lumtekf62132e9293c
diff --git a/.gitignore b/.gitignoreindex 3c619c3..1bb8e1d 100644--- a/.gitignore+++ b/.gitignore@@ -38,3 +38,5 @@ site/publish.sh# python__pycache__/*.pyc+engine/audio/samples/voices/+jobs/*/audio/diff --git a/README.md b/README.mdindex 5d2df98..d830bfc 100644--- a/README.md+++ b/README.md@@ -22,6 +22,7 @@ npm start # UI + API ở http://127.0.0.1:4400 (chỉ bind 127.0.0.1)| `OUTPUT_DIR` | render xong chép MP4 vào đây, vd thư mục Google Drive for Desktop || `PORT`, `VIDEOAI_MODE` | cổng; chế độ mặc định của web (`auto`) || `CLAUDE_BIN` | đường dẫn `claude` nếu không có trong PATH |+| `REWRITE_MODEL` / `REWRITE_ENGINE` | model cho nút "Viết lại kịch bản" ở chế độ api (mặc định `claude-haiku-5-5`) / ép engine `api` hoặc `claude` (mặc định `auto`) || `LUMREELS_HF_SLOTS` | số HyperFrames chạy song song trên máy (mặc định 3) || `VIDEOAI_FONTCHECK=0` | tắt kiểm font lúc preview/render |@@ -29,7 +30,7 @@ Hướng dẫn nối agent (có hình): [docs/HUONG-DAN-KET-NOI-AGENT.md](docs/H## Luồng```-job {templateId, content, durationS=8, aspect=9:16, mode, runAt?}+job {templateId, content, durationS=8 (3 giây → 10 phút; "90" hoặc "1:30"), aspect=9:16, mode, runAt?}├─ runAt ở tương lai → scheduled; server (15 giây/lần) hoặc `node cli.mjs run-due` chạy khi tới giờ└─ generator/prompt.mjs : PROMPT.md = nội dung + templates/guidance/<id>.md + engine/AUTHORING.md + luật chung├─ auto : api (có khoá) → claude (có lệnh claude) → manual@@ -42,13 +43,20 @@ job {templateId, content, durationS=8, aspect=9:16, mode, runAt?}```Trạng thái: `scheduled → queued → generating → (waiting_agent) → previewing → rendering → done | error`.+**Video dài** (> 12 giây): PROMPT dặn AI chia thành nhiều cảnh 6–10 giây nối nhau theo §10 của guidance, giữ phần tử xuyên suốt, mỗi khung là hàm thuần của t, `render(t)` < 1 giây. Render tăng theo tỉ lệ (video 8 giây ≈ 20–60 giây render → 1:30 ≈ 4–11 phút; 10:00 ≈ 25–75 phút). Mỗi lượt HyperFrames được giới hạn 10 phút + 2 phút cho mỗi 8 giây video (trần 3 giờ); Claude Code viết cảnh được 25 phút, video > 1 phút thêm 5 phút mỗi phút (trần 90 phút).++## Viết lại kịch bản+Nú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`).+## Cổng cho agent-**MCP** (stdio): `node mcp/server.mjs` — tool `list_templates`, `get_template`, `create_video`, `submit_scene`, `preview_job` (trả ảnh), `render_job`, `get_job`, `list_jobs`. Thử: `node scripts/mcp-smoke.mjs`.+**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`.**CLI**```node cli.mjs templates-node cli.mjs make --template 009 --content nd.txt [--duration 8] [--mode manual|agent|claude|api|auto] [--at 2026-11-28T07:00] [--json]+node cli.mjs rewrite --template 009 --content nd.txt [--duration 30] [--engine auto|api|claude] [--json]+node cli.mjs make --template 009 --content nd.txt [--duration 8|90|1:30] [--mode manual|agent|claude|api|auto] [--at 2026-11-28T07:00] [--json]node cli.mjs render <jobId> [--quality draft|looks|delivery] [--audio voice.mp3]node cli.mjs run-due # cho Windows Task Schedulernode cli.mjs list | show <jobId>@@ -57,18 +65,18 @@ node engine/preview.mjs <sceneDir> [-o preview.jpg] [--frame 3.5] # lưới 16node engine/render.mjs <sceneDir> -o out.mp4 [--audio file]node engine/fontcheck.mjs <sceneDir> [--readonly] # FONT_FALLBACK / OUTSIDE / WEIGHT / DIGITS / SMALL / DONG```-**REST** (127.0.0.1:4400): `GET /api/templates`, `GET|POST /api/jobs`, `GET /api/jobs/:id`, `POST /api/jobs/:id/scene` `{html, brief}`, `POST /api/jobs/:id/preview`, `POST /api/jobs/:id/render`, `GET /api/config`. Chỉ nhận Host `127.0.0.1`/`localhost`.+**REST** (127.0.0.1:4400): `GET /api/templates`, `GET|POST /api/jobs`, `GET /api/jobs/:id`, `POST /api/rewrite`, `POST /api/jobs/:id/scene` `{html, brief}`, `POST /api/jobs/:id/preview`, `POST /api/jobs/:id/render`, `GET /api/config`. Chỉ nhận Host `127.0.0.1`/`localhost`.## Cây thư mục```engine/ AUTHORING.md (contract viết cảnh), preview.mjs, render.mjs, fontcheck.mjs, lib.mjs, setup.mjsruntime/scene.js (VideoScene + cầu nối seek HyperFrames + __fontReport), vendor/ & fonts/ (sinh)-generator/ jobs.mjs (lõi dùng chung), prompt.mjs, api.mjs, claude.mjs, config.mjs+generator/ jobs.mjs (lõi dùng chung), rewrite.mjs (viết lại kịch bản), prompt.mjs, api.mjs, claude.mjs, config.mjsmcp/ server.mjs (MCP stdio)server/ server.mjs, public/ (UI 1 trang, không framework)-scripts/ sync-catalog.mjs, mcp-smoke.mjs, font-audit.mjs, scan-guidance-fonts.mjs, docs-shots.mjs+scripts/ sync-catalog.mjs, make-thumbs.mjs, mcp-smoke.mjs, font-audit.mjs, scan-guidance-fonts.mjs, docs-shots.mjsdocs/ HUONG-DAN-KET-NOI-AGENT.md, img/-templates/ catalog.json (danh mục mẫu), GUIDANCE-SPEC.md, guidance/<id>.md+templates/ catalog.json (danh mục mẫu), GUIDANCE-SPEC.md, guidance/<id>.md, thumbs/<id>.webp (ảnh đại diện 360×640)ref/<id>/, private/ (video tham chiếu riêng của mày — không commit)site/ build.mjs + src/ (trang giới thiệu), dist/media (video demo, dùng làm ảnh/video mẫu trong UI nếu có)tools/ fetch_refs.py, batch-lumfin.mjs@@ -79,7 +87,7 @@ cli.mjs## Thư viện mẫu`templates/catalog.json` liệt kê 104 mẫu phong cách (id, tên, nhóm faceless/ads/multi-style, thể loại, kỹ thuật, độ khó, có lời đọc hay không). Mỗi mẫu có 1 file `templates/guidance/<id>.md` mô tả **phong cách bằng chữ**: bảng màu, font, chất liệu, bố cục theo % khung, dòng thời gian theo giây, cách dựng bằng code, âm thanh, câu Tự kiểm. AI dựng cảnh chỉ đọc chữ này, không cần xem video nào.-Repo **không kèm video tham chiếu**. Ví dụ trong guidance (tên quán, khẩu hiệu, giá…) là ví dụ trung tính chỉ để hiểu định dạng ô nội dung; mọi chữ trên video lấy từ nội dung của mày. Ảnh và video trong lưới mẫu của UI là video demo do chính LumReels dựng (`site/dist/media`, có sau khi chạy `node site/build.mjs`); mẫu chưa có demo thì UI hiện poster tự sinh.+Repo **không kèm video tham chiếu**. Ví dụ trong guidance (tên quán, khẩu hiệu, giá…) là ví dụ trung tính chỉ để hiểu định dạng ô nội dung; mọi chữ trên video lấy từ nội dung của mày. Ảnh trong lưới mẫu của UI lấy theo thứ tự: poster video demo (`site/dist/media/<id>.webp`, có sau khi chạy `node site/build.mjs`) → `templates/thumbs/<id>.webp` (khung keyframe do chính LumReels dựng, có sẵn trong repo nên máy vừa clone vẫn thấy ảnh) → khung video tham chiếu riêng trên máy → poster SVG tự sinh. Video xem thử chỉ có khi máy có demo hoặc video tham chiếu riêng.## Thêm mẫu mới1. Chọn video tham chiếu của chính mày: tự quay, tự dựng, hoặc video mày có quyền dùng. Ghi vào `templates/private/refs.json` (thư mục riêng, không commit): `[{"id": "106", "file": "D:/quay/mau.mp4"}]` (hoặc `"url"`).@@ -87,8 +95,20 @@ Repo **không kèm video tham chiếu**. Ví dụ trong guidance (tên quán, kh3. Viết `templates/guidance/106.md` đúng khuôn `templates/GUIDANCE-SPEC.md`: tả phong cách bằng số đo, ví dụ ô nội dung trung tính, chỉ dùng font trong AUTHORING §4 (`node scripts/scan-guidance-fonts.mjs`) và kỹ thuật chạy được với engine (AUTHORING §10).4. `node scripts/sync-catalog.mjs` → thêm mẫu vào `templates/catalog.json` (tên lấy từ `title` của guidance; tự viết thêm `blurb` 1 câu). Mẫu tự hiện trong UI.5. Dựng thử 1 job `agent`, so `preview.jpg` với `ref/106/sheet.jpg`, sửa guidance chỗ AI hiểu sai.+6. Render xong, tạo ảnh đại diện cho lưới mẫu: `node scripts/make-thumbs.mjs 106 <jobId>` → `templates/thumbs/106.webp` (khung giây 5,5; đổi bằng `--at 4`, ghi đè bằng `--force`). Commit file này cùng guidance. `sync-catalog.mjs` liệt kê mẫu nào còn thiếu ảnh.## Âm thanhCảnh kèm `scene/audio.json` (AUTHORING §9): engine tự tổng hợp nhạc nền + tiếng động (DSP thuần JS), đọc lời tiếng Việt (VieNeu, dự phòng edge-tts), trộn −14 LUFS rồi ghép vào MP4 lúc render. Đã render rồi: `node cli.mjs audio <jobId>`. Ghép file có sẵn: `render.mjs --audio file`.++Nhạc và tiếng động không cần cài gì thêm (chỉ ffmpeg). **Giọng đọc là tuỳ chọn**, cần Python 3.10+:+```+pip install vieneu # giọng Việt chạy trên máy (mặc định, ~1 GB mô hình tải lần đầu; máy yếu đọc 1 câu mất 1–10 phút)+pip install edge-tts # dự phòng khi chưa có VieNeu (cần mạng)+```+Thiếu VieNeu thì UI ghi "Cài giọng đọc: pip install vieneu" và tự dùng edge-tts. `LUMREELS_PYTHON` = đường dẫn python nếu không phải `python`.++Chọn âm thanh khi tạo job: `{ audio: { music: <style>|"auto"|"none", voice: <tên giọng>|"auto"|"none", sfx: true|false } }` (REST `POST /api/jobs`, MCP `create_video`, CLI `make --music chill --voice "Trúc Ly" --no-sfx`). `auto` = AI chọn theo §9 guidance.+Đổi tiếng video đã dựng (không dựng lại hình): UI "Âm thanh · đổi nhạc, giọng đọc" trong mỗi video, REST `POST /api/jobs/:id/audio {music, voice, sfx}`, MCP `set_audio`, CLI `node cli.mjs audio <jobId> --music epic --voice "Thiện Minh"`. `out.mp4` luôn là bản mới nhất, bản cũ ở `versions/out-<n>.mp4` (+ `audio-<n>.json`), hình không tiếng ở `out.silent.mp4`. Chọn giọng mà chưa có lời → AI viết lời ngắn (api → claude, như "Viết lại kịch bản").+Lựa chọn + nghe thử: `GET /api/audio/options`, `GET /api/audio/preview?style=chill`, `GET /api/audio/preview?voice=Hải Đăng&text=...` (cache trong `engine/audio/samples/`). Nghe toàn bộ tiếng động: `engine/audio/samples/sfx-all.wav` (sinh lại: `node engine/audio/samples.mjs`).## EngineHyperFrames (npm `hyperframes`, Apache-2.0) chạy bằng CLI cục bộ, tắt telemetry/kiểm cập nhật. Khoá render toàn máy của HyperFrames được tắt và thay bằng hàng chờ riêng (`LUMREELS_HF_SLOTS`). Runtime `scene.js` đăng ký `window.__timelines.main` cho HyperFrames và xuất `window.__scene.seek(t)` để có thể đổi bộ chụp nếu cần.diff --git a/cli.mjs b/cli.mjsindex 37c06ee..2f99e3f 100644--- a/cli.mjs+++ b/cli.mjs@@ -1,6 +1,7 @@#!/usr/bin/env node// CLI cho người và AI agent.// node cli.mjs make --template 009 --content <file|chuỗi> [--duration 8] [--mode manual|agent|claude|api|auto] [--at 2026-11-28T07:00] [--json]+// node cli.mjs rewrite --template 009 --content <file|chuỗi> [--duration 30] [--engine auto|api|claude] [--json]// node cli.mjs run-due (chạy các job hẹn giờ đã tới giờ — cho Windows Task Scheduler)// node cli.mjs render <jobId> [--quality draft|looks|delivery] [--audio file]// node cli.mjs audio <jobId> [--export] (trộn + ghép tiếng theo scene/audio.json, không render lại hình)@@ -10,38 +11,59 @@import fs from 'node:fs';import { createJob, runJob, renderJob, runDue, listJobs, readJob, readLog, jobPaths, loadCatalog, hasGuidance, exportOutput } from './generator/jobs.mjs';import { parseArgs, probe } from './engine/lib.mjs';+import { rewriteScript } from './generator/rewrite.mjs';const [cmd, ...rest] = process.argv.slice(2);const { pos, opt } = parseArgs(rest);const out = (o) => console.log(opt.json ? JSON.stringify(o, null, 2) : o);+/** --music <style|auto|none> --voice <tên|auto|none> --no-sfx → {music, voice, sfx}; trường không truyền = undefined (giữ như cũ). */+const audioOpts = () => ({ music: opt.music === true ? undefined : opt.music, voice: opt.voice === true ? undefined : opt.voice, sfx: opt['no-sfx'] ? false : opt.sfx ? true : undefined });function usage() {console.log(`LumReels CLImake --template <id> --content <file|chuỗi> [--duration 8] [--mode manual|claude|api|auto] [--at <giờ>] [--json]+ --music <style|auto|none> --voice <tên giọng|auto|none> --no-sfx : âm thanh (mặc định auto, auto, có sfx)+ --duration: 3 giây → 10 phút, số giây (90) hoặc phút:giây (1:30, 10:00). Mặc định 8.manual (mặc định): ghi jobs/<id>/PROMPT.md, job ở trạng thái waiting_agent. Agent viếtjobs/<id>/brief.json + scene/index.html rồi gọi: node cli.mjs render <id>claude: chạy Claude Code headless sinh cảnh, rồi tự render.api: gọi Anthropic API (ANTHROPIC_API_KEY trong .env). auto: api → claude → manual.--at 2026-11-28T07:00 : hẹn giờ (giờ máy). Job ở trạng thái scheduled; server đang bật tự chạy,hoặc Task Scheduler gọi: node cli.mjs run-due+ rewrite --template <id> --content <file|chuỗi> [--duration 8] [--engine auto|api|claude] [--json]+ viết lại nội dung thành kịch bản hợp mẫu + thời lượng (in ra, không tạo job)run-due chạy mọi job hẹn giờ đã tới giờrun <jobId> chạy trọn 1 job (sinh cảnh + render), bỏ qua giờ hẹnrender <jobId> [--quality draft|looks|delivery] [--audio file] preview.jpg + out.mp4(có scene/audio.json thì tự trộn nhạc + sfx + lời và ghép vào out.mp4)- audio <jobId> [--export] [--json] chỉ trộn tiếng theo scene/audio.json và ghép vào out.mp4 đã có,- KHÔNG render lại hình (bản không tiếng giữ ở out.silent.mp4). --export: chép ra OUTPUT_DIR+ audio <jobId> [--music <style|auto|none>] [--voice <tên|auto|none>] [--no-sfx] [--export] [--json]+ trộn tiếng mới theo scene/audio.json (+ tuỳ chọn) và ghép vào hình đã dựng, KHÔNG render lại hình.+ out.mp4 = bản mới nhất, bản cũ → versions/out-<n>.mp4, hình không tiếng: out.silent.mp4.+ Chọn giọng mà chưa có lời đọc → AI viết lời ngắn. --export: chép ra OUTPUT_DIR+ audio-options [--json] style nhạc + giọng đọc có trên máylist [--json] danh sách jobshow <jobId> trạng thái + log + đường dẫntemplates [--json] mẫu nào đã có guidance`);}+const readContent = (c) => (fs.existsSync(c) && fs.statSync(c).isFile() ? fs.readFileSync(c, 'utf8') : c);+try {- if (cmd === 'make') {+ if (cmd === 'rewrite') {+ if (!opt.template || !opt.content) { usage(); process.exit(2); }+ const r = await rewriteScript({ templateId: String(opt.template), content: readContent(String(opt.content)), durationS: opt.duration === true ? undefined : opt.duration, engine: typeof opt.engine === 'string' ? opt.engine : undefined });+ if (opt.json) out(r);+ else {+ console.log(r.script + (r.notes ? `\n\n--- ghi chú ---\n${r.notes}` : ''));+ console.error(`\n(engine ${r.engine}${r.fallbackFrom ? ', sau khi ' + r.fallbackFrom : ''}${r.usage ? `, ${r.usage.inputTokens} token vào / ${r.usage.outputTokens} ra${r.usage.costUSD != null ? ` ≈ $${r.usage.costUSD}` : ''}` : ''})`);+ }+ process.exit(0);+ } else if (cmd === 'make') {if (!opt.template || !opt.content) { usage(); process.exit(2); }- const c = String(opt.content);- const content = fs.existsSync(c) && fs.statSync(c).isFile() ? fs.readFileSync(c, 'utf8') : c;+ const content = readContent(String(opt.content));const mode = opt.mode || process.env.VIDEOAI_CLI_MODE || 'manual';- const job = createJob({ templateId: String(opt.template), content, durationS: Number(opt.duration) || 8, mode, runAt: opt.at, source: 'cli' });+ const job = createJob({ templateId: String(opt.template), content, durationS: opt.duration === true ? undefined : opt.duration, mode, runAt: opt.at, source: 'cli',+ audio: (({ music, voice, sfx }) => ({ music: music ?? 'auto', voice: voice ?? 'auto', sfx: sfx ?? true }))(audioOpts()) });const p = jobPaths(job.id);const done = await runJob(job.id);if (opt.json) out({ ...done, paths: p });@@ -65,20 +87,23 @@ try {}process.exit(done.status === 'done' ? 0 : 1);} else if (cmd === 'audio') {- // Chỉ trộn + ghép tiếng theo scene/audio.json vào video đã render, KHÔNG render lại hình.+ // Trộn tiếng mới + ghép vào hình đã dựng, KHÔNG render lại hình. Bản cũ (nếu có tiếng) → versions/out-<n>.mp4.if (!pos[0]) { usage(); process.exit(2); }- const p = jobPaths(pos[0]);- const silent = p.mp4.replace(/\.mp4$/i, '.silent.mp4');- if (!fs.existsSync(p.mp4) && !fs.existsSync(silent)) { console.error(`Chưa có ${p.mp4}: render trước (node cli.mjs render ${pos[0]})`); process.exit(1); }- // out.mp4 chưa có tiếng (vừa render xong) → nó là bản hình mới nhất: chép thành out.silent.mp4- const hasAudio = fs.existsSync(p.mp4) && (await probe(p.mp4))?.streams?.some((s) => !s.width);- if (fs.existsSync(p.mp4) && (!hasAudio || !fs.existsSync(silent))) fs.copyFileSync(p.mp4, silent);- const { addAudio } = await import('./engine/audio/mix.mjs');- const res = await addAudio(p.scene, silent, p.mp4, { log: (l) => console.log(l), seedKey: pos[0] });- if (opt.export) { const j = readJob(pos[0]); if (j) exportOutput(j, (l) => console.log(l)); }- if (opt.json) out({ ...res, silent });- else console.log(`MP4: ${p.mp4}\nKhông tiếng: ${silent}${res.warnings.length ? `\n${res.warnings.length} cảnh báo âm thanh (xem trên)` : ''}`);+ const { reAudio } = await import('./generator/audio-job.mjs');+ const res = await reAudio(pos[0], audioOpts(), { log: (l) => console.log(l), exportOut: !!opt.export });+ if (opt.json) out(res);+ else console.log(`MP4: ${jobPaths(pos[0]).mp4} (bản ${res.version})${res.warnings.length ? `+${res.warnings.length} cảnh báo âm thanh (xem trên)` : ''}`);process.exit(0);+ } else if (cmd === 'audio-options') {+ const { audioOptions } = await import('./engine/audio/prefs.mjs');+ const o = audioOptions();+ if (opt.json) out(o);+ else {+ console.log('Nhạc: ' + o.music.map((m) => m.id).join(', '));+ console.log('Giọng: ' + o.voices.map((v) => v.id).join(', '));+ if (o.hint) console.log(o.hint);+ }} else if (cmd === 'run') {// Chạy trọn 1 job (sinh cảnh theo chế độ + render). MCP dùng lệnh này ở tiến trình tách riêng.if (!pos[0]) { usage(); process.exit(2); }diff --git a/docs/HUONG-DAN-KET-NOI-AGENT.md b/docs/HUONG-DAN-KET-NOI-AGENT.mdindex a4d8c31..2e862c4 100644--- a/docs/HUONG-DAN-KET-NOI-AGENT.md+++ b/docs/HUONG-DAN-KET-NOI-AGENT.md@@ -126,12 +126,15 @@ Agent sẽ dùng các công cụ:|---|---|| `list_templates` | Tìm mẫu theo nhóm/từ khoá, có độ khó || `get_template` | Đọc hướng dẫn phong cách của mẫu + luật viết cảnh |-| `create_video` | Tạo job. `auto` = app tự dựng; `agent` = agent tự viết cảnh. Có `runAt` để hẹn giờ |+| `rewrite_script` | Viết lại nội dung thô thành kịch bản đúng ô nội dung của mẫu + thời lượng (giữ số liệu, tên kênh, CTA). Mất 20–90 giây |+| `create_video` | Tạo job. `auto` = app tự dựng; `agent` = agent tự viết cảnh. `durationS` 3 giây → 10 phút (`90` hoặc `"1:30"`, mặc định 8). Có `runAt` để hẹn giờ || `submit_scene` | Agent nộp cảnh HTML (app kiểm lỗi trước khi nhận) || `preview_job` | Trả ảnh 16 khung để agent tự nhìn, kèm ảnh mẫu gốc để so || `render_job` | Ra MP4, chép ra thư mục xuất || `get_job` / `list_jobs` | Xem trạng thái, lỗi, chi phí |+Video dài hơn 60 giây: AI chia thành nhiều cảnh 6–10 giây nối nhau, render lâu theo tỉ lệ (video 8 giây mất 20–60 giây render, nên 1:30 mất khoảng 4–11 phút) và tốn token hơn.+`auto` dùng Claude API (tốn tiền theo token, chi phí ghi trong job). `agent` dùng chính gói Claude/ChatGPT của mày để viết cảnh, app chỉ render.## 6. Tự lên Google Drive@@ -151,7 +154,13 @@ Mỗi video render xong được chép vào đó với tên `<ngày>-<mẫu>-<v### Cách 1: ngay trong app (app phải đang bật)Trên web: điền nội dung, ô **Hẹn giờ dựng** chọn giờ, bấm **Hẹn dựng video**.-+++Ô **Thời lượng** nhận số giây (`90`) hoặc phút:giây (`1:30`, `10:00`), từ 3 giây tới 10 phút; nút 8s/15s/30s/60s để chọn nhanh.++Nút **Viết lại kịch bản** (cạnh ô Nội dung): AI xếp nội dung mày gõ vào đúng ô của mẫu đang chọn và thời lượng đang nhập, giữ nguyên số liệu, tên kênh, CTA. Xem trước rồi bấm **Dùng bản này** (bấm **Hoàn tác** để lấy lại bản cũ).++Job hiện nhãn **Đã hẹn** kèm giờ. Tới giờ, app tự dựng (app kiểm 15 giây một lần).@@ -191,7 +200,8 @@ App đang bật cũng không sao. Hai bên tranh nhau một job thì chỉ một```powershellnode cli.mjs templates # mẫu nào dùng được-node cli.mjs make --template 009 --content noidung.txt --mode agent+node cli.mjs rewrite --template 009 --content noidung.txt --duration 30 # in kịch bản viết lại+node cli.mjs make --template 009 --content noidung.txt --mode agent --duration 1:30# → in đường dẫn PROMPT.md; agent viết jobs\<id>\scene\index.htmlnode cli.mjs render <jobId> # preview + MP4 (+ chép ra OUTPUT_DIR)node cli.mjs list@@ -204,7 +214,8 @@ Invoke-RestMethod -Method Post http://127.0.0.1:4400/api/jobs -ContentType "appl| Lệnh | Việc ||---|---|| `GET /api/templates` | danh sách mẫu |-| `POST /api/jobs` | tạo job `{templateId, content, durationS, mode, runAt}` |+| `POST /api/jobs` | tạo job `{templateId, content, durationS, mode, runAt}` (`durationS` 3–600 hoặc `"1:30"`) |+| `POST /api/rewrite` | viết lại kịch bản `{templateId, content, durationS}` → `{script, notes, engine, usage}` || `POST /api/jobs/<id>/scene` | nộp cảnh `{html, brief}` || `POST /api/jobs/<id>/preview` | dựng preview.jpg || `POST /api/jobs/<id>/render` | render MP4 |diff --git a/docs/img/ui-danh-sach-job.png b/docs/img/ui-danh-sach-job.pngindex 49c61da..c8a55a9 100644Binary files a/docs/img/ui-danh-sach-job.png and b/docs/img/ui-danh-sach-job.png differdiff --git a/docs/img/ui-dien-thoai.png b/docs/img/ui-dien-thoai.pngindex d852f63..4f2bbe4 100644Binary files a/docs/img/ui-dien-thoai.png and b/docs/img/ui-dien-thoai.png differdiff --git a/docs/img/ui-form-hen-gio.png b/docs/img/ui-form-hen-gio.pngindex 7518895..73a056a 100644Binary files a/docs/img/ui-form-hen-gio.png and b/docs/img/ui-form-hen-gio.png differdiff --git a/docs/img/ui-luoi-mau.png b/docs/img/ui-luoi-mau.pngindex bc8d191..afa2a08 100644Binary files a/docs/img/ui-luoi-mau.png and b/docs/img/ui-luoi-mau.png differdiff --git a/docs/img/ui-viet-lai.png b/docs/img/ui-viet-lai.pngnew file mode 100644index 0000000..97c5070Binary files /dev/null and b/docs/img/ui-viet-lai.png differdiff --git a/engine/audio/mix.mjs b/engine/audio/mix.mjsindex d9f3fda..6f090d1 100644--- a/engine/audio/mix.mjs+++ b/engine/audio/mix.mjs@@ -1,159 +1,165 @@-// Trộn âm thanh theo scene/audio.json rồi ghép vào MP4 (ffmpeg).-// nhạc (style) + sfx (adelay) + giọng đọc → nhạc tự hạ khi có giọng (sidechain) → loudnorm −14 LUFS 2 lượt-// → AAC 192k stereo 48 kHz, cắt đúng độ dài hình. Hình giữ nguyên (-c:v copy).-//-// Mức gain (dB) so với "mức chuẩn" của từng lớp: nhạc và giọng đã chuẩn hoá RMS −16 dBFS, sfx đỉnh −1 dBFS.-// 0 dB nhạc = ngang giọng đọc. Mặc định: nhạc −6 (không lời) / −12 (có lời), sfx −6, giọng 0.-import fs from 'node:fs';-import path from 'node:path';-import { run, probe } from '../lib.mjs';-import { SFX_NAMES, writeSfx } from './sfx.mjs';-import { MUSIC_STYLES, writeMusic } from './music.mjs';-import { synthVoice, DEFAULT_VOICE } from './voice.mjs';-import { hashStr } from './dsp.mjs';--export const TARGET_LUFS = -14;--/** Đọc + kiểm scene/audio.json. Trả null nếu không có file. Ném lỗi nếu sai luật. */-export function loadAudioSpec(sceneDir) {- const f = path.join(sceneDir, 'audio.json');- if (!fs.existsSync(f)) return null;- let spec;- try { spec = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { throw new Error(`audio.json không phải JSON hợp lệ: ${e.message}`); }- const errs = [];- if (spec.music) {- if (!MUSIC_STYLES.includes(spec.music.style)) errs.push(`music.style "${spec.music.style}" không có (có: ${MUSIC_STYLES.join(', ')})`);- }- (spec.sfx || []).forEach((s, i) => {- if (!SFX_NAMES.includes(s.name)) errs.push(`sfx[${i}].name "${s.name}" không có (có: ${SFX_NAMES.join(', ')})`);- if (!(typeof s.t === 'number' && s.t >= 0)) errs.push(`sfx[${i}].t phải là số giây ≥ 0`);- });- const lines = spec.voice?.lines || [];- lines.forEach((l, i) => {- if (!(typeof l.t === 'number' && l.t >= 0)) errs.push(`voice.lines[${i}].t phải là số giây ≥ 0`);- if (!String(l.text || '').trim()) errs.push(`voice.lines[${i}].text trống`);- });- if (errs.length) throw new Error('audio.json sai: ' + errs.join('; '));- return spec;-}--async function ff(args, what) {- const r = await run('ffmpeg', ['-y', '-hide_banner', '-nostats', ...args]);- if (r.code !== 0) throw new Error(`${what} lỗi: ${r.out.slice(-800)}`);- return r.out;-}-function parseLoudnorm(out) {- const m = out.match(/\{[^{}]*"input_i"[^{}]*\}/);- if (!m) throw new Error('không đọc được kết quả loudnorm');- return JSON.parse(m[0]);-}-/** Đo loudness tích hợp (LUFS) + true peak (dBTP) của 1 file. */-export async function measureLoudness(file) {- const r = await run('ffmpeg', ['-hide_banner', '-nostats', '-i', file, '-map', '0:a:0', '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:print_format=json`, '-f', 'null', '-']);- const j = parseLoudnorm(r.out);- return { lufs: Number(j.input_i), truePeak: Number(j.input_tp), lra: Number(j.input_lra) };-}--/**- * Dựng file trộn WAV dài đúng `duration` giây. workDir: nơi chứa sfx/nhạc/giọng sinh ra (cache).- * Trả { wav, warnings, voice: [{t,text,dur}] }.- */-export async function buildMix(sceneDir, { duration, workDir, log = console.log, seedKey } = {}) {- const spec = loadAudioSpec(sceneDir);- if (!spec) throw new Error('Không có scene/audio.json');- fs.mkdirSync(workDir, { recursive: true });- const warnings = [];- const warn = (w) => { warnings.push(w); log('CẢNH BÁO âm thanh: ' + w); };- const inputs = [], chains = [], mixLabels = [];- const addInput = (file) => { inputs.push('-i', file); return inputs.length / 2 - 1; };- const fmt = 'aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo';-- // giọng đọc- const lines = (spec.voice?.lines || []).slice().sort((a, b) => a.t - b.t);- let voice = [];- if (lines.length) {- voice = await synthVoice(lines, workDir, { engine: spec.voice.engine || 'vieneu', voice: spec.voice.speaker || DEFAULT_VOICE, log });- voice.forEach((v, i) => {- const end = v.t + v.dur, next = i + 1 < voice.length ? voice[i + 1].t : duration;- if (end > next + 0.05) warn(`lời "${v.text}" dài ${v.dur.toFixed(2)}s, từ ${v.t}s tới ${end.toFixed(2)}s, lấn sang ${i + 1 < voice.length ? `câu sau (${next}s)` : `hết video (${duration.toFixed(2)}s)`}. Rút gọn câu hoặc dời mốc.`);- });- }- const vGain = spec.voice?.gain ?? 0;- const vLabels = voice.map((v, i) => {- const k = addInput(v.file);- chains.push(`[${k}:a]${fmt},adelay=${Math.round(v.t * 1000)}:all=1,volume=${vGain}dB[v${i}]`);- return `[v${i}]`;- });-- // nhạc- if (spec.music) {- const seed = spec.music.seed ?? (hashStr(seedKey || sceneDir) % 997) + 1;- const mf = path.join(workDir, `music-${spec.music.style}-${seed}-${duration.toFixed(3)}.wav`);- if (!fs.existsSync(mf)) writeMusic(spec.music.style, mf, duration, seed);- const k = addInput(mf);- const g = spec.music.gain ?? (vLabels.length ? -12 : -6);- chains.push(`[${k}:a]${fmt},volume=${g}dB[mus]`);- if (vLabels.length) {- chains.push(`${vLabels.join('')}amix=inputs=${vLabels.length}:normalize=0:duration=longest,asplit=2[vbus][vkey]`);- chains.push(`[mus][vkey]sidechaincompress=threshold=0.05:ratio=3:attack=25:release=450:makeup=1[musd]`);- mixLabels.push('[musd]', '[vbus]');- } else mixLabels.push('[mus]');- } else mixLabels.push(...vLabels);-- // tiếng động- (spec.sfx || []).forEach((s, i) => {- if (s.t >= duration) { warn(`sfx "${s.name}" ở ${s.t}s nằm ngoài video (${duration.toFixed(2)}s), bỏ qua`); return; }- const seed = s.seed ?? i + 1;- const f = path.join(workDir, `sfx-${s.name}-${seed}.wav`);- if (!fs.existsSync(f)) writeSfx(s.name, f, seed);- const k = addInput(f);- chains.push(`[${k}:a]${fmt},adelay=${Math.round(s.t * 1000)}:all=1,volume=${s.gain ?? -6}dB[s${i}]`);- mixLabels.push(`[s${i}]`);- });- if (!mixLabels.length) throw new Error('audio.json không có nhạc, sfx hay lời nào');-- // tiền trộn (float, chưa chuẩn hoá) dài đúng duration- const pre = path.join(workDir, 'premix.wav');- const graph = [...chains, `${mixLabels.join('')}amix=inputs=${mixLabels.length}:normalize=0:duration=longest,apad,atrim=0:${duration.toFixed(4)}[out]`].join(';');- await ff([...inputs, '-filter_complex', graph, '-map', '[out]', '-ar', '48000', '-c:a', 'pcm_f32le', pre], 'trộn âm thanh');-- // loudnorm 2 lượt → −14 LUFS- const m = parseLoudnorm(await ff(['-i', pre, '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:print_format=json`, '-f', 'null', '-'], 'đo loudness'));- const wav = path.join(workDir, 'mix.wav');- await ff(['-i', pre, '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:measured_thresh=${m.input_thresh}:offset=${m.target_offset}:linear=true,atrim=0:${duration.toFixed(4)}`,- '-ar', '48000', '-ac', '2', '-c:a', 'pcm_s16le', wav], 'chuẩn hoá loudness');- return { wav, warnings, voice: voice.map(({ t, text, spoken, dur }) => ({ t, text, spoken, dur })) };-}--/** Ghép WAV vào MP4: giữ hình (-c:v copy), AAC 192k stereo 48 kHz, cắt đúng độ dài hình. */-export async function muxAudio(videoIn, wav, outFile, duration) {- const tmp = outFile.replace(/\.mp4$/i, '.mux.tmp.mp4');- await ff(['-i', videoIn, '-i', wav, '-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2',- '-t', duration.toFixed(4), '-movflags', '+faststart', tmp], 'ghép âm thanh vào MP4');- fs.renameSync(tmp, outFile);- return outFile;-}--export async function videoDuration(file) {- const info = await probe(file);- const v = info?.streams?.find((s) => s.codec_name === 'h264') || info?.streams?.[0];- const [fa, fb] = String(v?.r_frame_rate || '0/1').split('/').map(Number);- const fps = fa / (fb || 1);- const d = Number(v?.nb_frames) > 0 && fps > 0 ? Number(v.nb_frames) / fps : Number(info?.format?.duration);- if (!(d > 0)) throw new Error('không đọc được độ dài video: ' + file);- return d;-}--/**- * Trộn theo sceneDir/audio.json và ghép vào `silentMp4` → `outMp4`. workDir mặc định = <thư mục out>/audio.- * Trả { ok, file, lufs, truePeak, warnings, voice }.- */-export async function addAudio(sceneDir, silentMp4, outMp4, { workDir, log = console.log, seedKey } = {}) {- const duration = await videoDuration(silentMp4);- workDir = workDir || path.join(path.dirname(outMp4), 'audio');- const mix = await buildMix(sceneDir, { duration, workDir, log, seedKey: seedKey || path.basename(path.dirname(path.resolve(sceneDir))) });- await muxAudio(silentMp4, mix.wav, outMp4, duration);- const L = await measureLoudness(outMp4);- log(`âm thanh: ${L.lufs.toFixed(1)} LUFS, đỉnh ${L.truePeak.toFixed(1)} dBTP, ${duration.toFixed(2)}s${mix.voice.length ? `, ${mix.voice.length} lời` : ''}`);- return { ok: true, file: outMp4, ...L, warnings: mix.warnings, voice: mix.voice };-}+// Trộn âm thanh theo scene/audio.json rồi ghép vào MP4 (ffmpeg).+// nhạc (style) + sfx (adelay) + giọng đọc → nhạc tự hạ khi có giọng (sidechain) → loudnorm −14 LUFS 2 lượt+// → AAC 192k stereo 48 kHz, cắt đúng độ dài hình. Hình giữ nguyên (-c:v copy).+//+// Mức gain (dB) so với "mức chuẩn" của từng lớp: nhạc và giọng đã chuẩn hoá RMS −16 dBFS, sfx đỉnh −1 dBFS.+// 0 dB nhạc = ngang giọng đọc. Mặc định: nhạc −6 (không lời) / −12 (có lời), sfx −6, giọng 0.+import fs from 'node:fs';+import path from 'node:path';+import { run, probe } from '../lib.mjs';+import { SFX_NAMES, writeSfx } from './sfx.mjs';+import { MUSIC_STYLES, writeMusic } from './music.mjs';+import { synthVoice, DEFAULT_VOICE } from './voice.mjs';+import { hashStr } from './dsp.mjs';++export const TARGET_LUFS = -14;++/** Đọc + kiểm scene/audio.json. Trả null nếu không có file. Ném lỗi nếu sai luật. */+export function loadAudioSpec(sceneDir) {+ const f = path.join(sceneDir, 'audio.json');+ if (!fs.existsSync(f)) return null;+ let spec;+ try { spec = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { throw new Error(`audio.json không phải JSON hợp lệ: ${e.message}`); }+ return validateAudioSpec(spec);+}++/** Kiểm 1 spec audio (cùng dạng audio.json). Ném lỗi nếu sai luật, trả lại spec. */+export function validateAudioSpec(spec) {+ if (!spec || typeof spec !== 'object') throw new Error('audio.json phải là object');+ const errs = [];+ if (spec.music) {+ if (!MUSIC_STYLES.includes(spec.music.style)) errs.push(`music.style "${spec.music.style}" không có (có: ${MUSIC_STYLES.join(', ')})`);+ }+ (spec.sfx || []).forEach((s, i) => {+ if (!SFX_NAMES.includes(s.name)) errs.push(`sfx[${i}].name "${s.name}" không có (có: ${SFX_NAMES.join(', ')})`);+ if (!(typeof s.t === 'number' && s.t >= 0)) errs.push(`sfx[${i}].t phải là số giây ≥ 0`);+ });+ const lines = spec.voice?.lines || [];+ lines.forEach((l, i) => {+ if (!(typeof l.t === 'number' && l.t >= 0)) errs.push(`voice.lines[${i}].t phải là số giây ≥ 0`);+ if (!String(l.text || '').trim()) errs.push(`voice.lines[${i}].text trống`);+ });+ if (errs.length) throw new Error('audio.json sai: ' + errs.join('; '));+ return spec;+}++async function ff(args, what) {+ const r = await run('ffmpeg', ['-y', '-hide_banner', '-nostats', ...args]);+ if (r.code !== 0) throw new Error(`${what} lỗi: ${r.out.slice(-800)}`);+ return r.out;+}+function parseLoudnorm(out) {+ const m = out.match(/\{[^{}]*"input_i"[^{}]*\}/);+ if (!m) throw new Error('không đọc được kết quả loudnorm');+ return JSON.parse(m[0]);+}+/** Đo loudness tích hợp (LUFS) + true peak (dBTP) của 1 file. */+export async function measureLoudness(file) {+ const r = await run('ffmpeg', ['-hide_banner', '-nostats', '-i', file, '-map', '0:a:0', '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:print_format=json`, '-f', 'null', '-']);+ const j = parseLoudnorm(r.out);+ return { lufs: Number(j.input_i), truePeak: Number(j.input_tp), lra: Number(j.input_lra) };+}++/**+ * Dựng file trộn WAV dài đúng `duration` giây. workDir: nơi chứa sfx/nhạc/giọng sinh ra (cache).+ * Trả { wav, warnings, voice: [{t,text,dur}] }.+ */+export async function buildMix(sceneDir, { duration, workDir, log = console.log, seedKey, spec: given } = {}) {+ const spec = given ? validateAudioSpec(given) : loadAudioSpec(sceneDir);+ if (!spec) throw new Error('Không có scene/audio.json');+ fs.mkdirSync(workDir, { recursive: true });+ const warnings = [];+ const warn = (w) => { warnings.push(w); log('CẢNH BÁO âm thanh: ' + w); };+ const inputs = [], chains = [], mixLabels = [];+ const addInput = (file) => { inputs.push('-i', file); return inputs.length / 2 - 1; };+ const fmt = 'aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo';++ // giọng đọc+ const lines = (spec.voice?.lines || []).slice().sort((a, b) => a.t - b.t);+ let voice = [];+ if (lines.length) {+ voice = await synthVoice(lines, workDir, { engine: spec.voice.engine || 'vieneu', voice: spec.voice.speaker || DEFAULT_VOICE, log });+ voice.forEach((v, i) => {+ const end = v.t + v.dur, next = i + 1 < voice.length ? voice[i + 1].t : duration;+ if (end > next + 0.05) warn(`lời "${v.text}" dài ${v.dur.toFixed(2)}s, từ ${v.t}s tới ${end.toFixed(2)}s, lấn sang ${i + 1 < voice.length ? `câu sau (${next}s)` : `hết video (${duration.toFixed(2)}s)`}. Rút gọn câu hoặc dời mốc.`);+ });+ }+ const vGain = spec.voice?.gain ?? 0;+ const vLabels = voice.map((v, i) => {+ const k = addInput(v.file);+ chains.push(`[${k}:a]${fmt},adelay=${Math.round(v.t * 1000)}:all=1,volume=${vGain}dB[v${i}]`);+ return `[v${i}]`;+ });++ // nhạc+ if (spec.music) {+ const seed = spec.music.seed ?? (hashStr(seedKey || sceneDir) % 997) + 1;+ const mf = path.join(workDir, `music-${spec.music.style}-${seed}-${duration.toFixed(3)}.wav`);+ if (!fs.existsSync(mf)) writeMusic(spec.music.style, mf, duration, seed);+ const k = addInput(mf);+ const g = spec.music.gain ?? (vLabels.length ? -12 : -6);+ chains.push(`[${k}:a]${fmt},volume=${g}dB[mus]`);+ if (vLabels.length) {+ chains.push(`${vLabels.join('')}amix=inputs=${vLabels.length}:normalize=0:duration=longest,asplit=2[vbus][vkey]`);+ chains.push(`[mus][vkey]sidechaincompress=threshold=0.05:ratio=3:attack=25:release=450:makeup=1[musd]`);+ mixLabels.push('[musd]', '[vbus]');+ } else mixLabels.push('[mus]');+ } else mixLabels.push(...vLabels);++ // tiếng động+ (spec.sfx || []).forEach((s, i) => {+ if (s.t >= duration) { warn(`sfx "${s.name}" ở ${s.t}s nằm ngoài video (${duration.toFixed(2)}s), bỏ qua`); return; }+ const seed = s.seed ?? i + 1;+ const f = path.join(workDir, `sfx-${s.name}-${seed}.wav`);+ if (!fs.existsSync(f)) writeSfx(s.name, f, seed);+ const k = addInput(f);+ chains.push(`[${k}:a]${fmt},adelay=${Math.round(s.t * 1000)}:all=1,volume=${s.gain ?? -6}dB[s${i}]`);+ mixLabels.push(`[s${i}]`);+ });+ if (!mixLabels.length) throw new Error('audio.json không có nhạc, sfx hay lời nào');++ // tiền trộn (float, chưa chuẩn hoá) dài đúng duration+ const pre = path.join(workDir, 'premix.wav');+ const graph = [...chains, `${mixLabels.join('')}amix=inputs=${mixLabels.length}:normalize=0:duration=longest,apad,atrim=0:${duration.toFixed(4)}[out]`].join(';');+ await ff([...inputs, '-filter_complex', graph, '-map', '[out]', '-ar', '48000', '-c:a', 'pcm_f32le', pre], 'trộn âm thanh');++ // loudnorm 2 lượt → −14 LUFS+ const m = parseLoudnorm(await ff(['-i', pre, '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:print_format=json`, '-f', 'null', '-'], 'đo loudness'));+ const wav = path.join(workDir, 'mix.wav');+ await ff(['-i', pre, '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:measured_thresh=${m.input_thresh}:offset=${m.target_offset}:linear=true,atrim=0:${duration.toFixed(4)}`,+ '-ar', '48000', '-ac', '2', '-c:a', 'pcm_s16le', wav], 'chuẩn hoá loudness');+ return { wav, warnings, voice: voice.map(({ t, text, spoken, dur }) => ({ t, text, spoken, dur })) };+}++/** Ghép WAV vào MP4: giữ hình (-c:v copy), AAC 192k stereo 48 kHz, cắt đúng độ dài hình. */+export async function muxAudio(videoIn, wav, outFile, duration) {+ const tmp = outFile.replace(/\.mp4$/i, '.mux.tmp.mp4');+ await ff(['-i', videoIn, '-i', wav, '-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2',+ '-t', duration.toFixed(4), '-movflags', '+faststart', tmp], 'ghép âm thanh vào MP4');+ fs.renameSync(tmp, outFile);+ return outFile;+}++export async function videoDuration(file) {+ const info = await probe(file);+ const v = info?.streams?.find((s) => s.codec_name === 'h264') || info?.streams?.[0];+ const [fa, fb] = String(v?.r_frame_rate || '0/1').split('/').map(Number);+ const fps = fa / (fb || 1);+ const d = Number(v?.nb_frames) > 0 && fps > 0 ? Number(v.nb_frames) / fps : Number(info?.format?.duration);+ if (!(d > 0)) throw new Error('không đọc được độ dài video: ' + file);+ return d;+}++/**+ * Trộn theo sceneDir/audio.json (hoặc `spec` truyền vào) và ghép vào `silentMp4` → `outMp4`. workDir mặc định = <thư mục out>/audio.+ * Trả { ok, file, lufs, truePeak, warnings, voice }.+ */+export async function addAudio(sceneDir, silentMp4, outMp4, { workDir, log = console.log, seedKey, spec } = {}) {+ const duration = await videoDuration(silentMp4);+ workDir = workDir || path.join(path.dirname(outMp4), 'audio');+ const mix = await buildMix(sceneDir, { duration, workDir, log, spec, seedKey: seedKey || path.basename(path.dirname(path.resolve(sceneDir))) });+ await muxAudio(silentMp4, mix.wav, outMp4, duration);+ const L = await measureLoudness(outMp4);+ log(`âm thanh: ${L.lufs.toFixed(1)} LUFS, đỉnh ${L.truePeak.toFixed(1)} dBTP, ${duration.toFixed(2)}s${mix.voice.length ? `, ${mix.voice.length} lời` : ''}`);+ return { ok: true, file: outMp4, ...L, warnings: mix.warnings, voice: mix.voice };+}diff --git a/engine/audio/prefs.mjs b/engine/audio/prefs.mjsnew file mode 100644index 0000000..6965573--- /dev/null+++ b/engine/audio/prefs.mjs@@ -0,0 +1,99 @@+// Tuỳ chọn âm thanh của job (dùng chung CLI / REST / MCP / UI):+// audio: { music: <style>|"auto"|"none", voice: <tên giọng>|"auto"|"none", sfx: true|false }+// "auto" = để AI chọn theo §9 guidance và viết scene/audio.json. Lúc trộn, tuỳ chọn cố định ghi đè audio.json.+import { spawnSync } from 'node:child_process';+import { MUSIC_STYLES, MUSIC_LIST } from './music.mjs';++const PY = process.env.LUMREELS_PYTHON || 'python';++/** Giọng VieNeu v3 Turbo có sẵn (preset). */+export const VIENEU_VOICES = [+ ['Hải Đăng', 'nam', 'Bắc', 'tự nhiên (mặc định)'], ['Thiện Minh', 'nam', 'Bắc', 'kể chuyện, trầm'], ['Xuân Vĩnh', 'nam', 'Bắc', 'tự nhiên'],+ ['Quốc Tuấn', 'nam', 'Bắc', 'tự nhiên'], ['Phạm Tuyên', 'nam', 'Bắc', 'tự nhiên'], ['Adam bựa', 'nam', 'Bắc', 'lầy'],+ ['Minh Đức', 'nam', 'Bắc', 'tin tức'], ['Thanh Bình', 'nam', 'Bắc', 'kể chuyện'], ['Quang Sơn', 'nam', 'Trung', 'tự nhiên'],+ ['Thái Sơn', 'nam', 'Nam', 'kể chuyện'], ['Đức Trí', 'nam', 'Nam', 'đọc truyện'],+ ['Trúc Ly', 'nữ', 'Bắc', 'tự nhiên'], ['Ngọc Huyền', 'nữ', 'Bắc', 'tự nhiên'], ['Đoan Trang', 'nữ', 'Bắc', 'tự nhiên'],+ ['Mai Anh', 'nữ', 'Bắc', 'tin tức'], ['Ngọc Linh', 'nữ', 'Bắc', 'kể chuyện'], ['Quỳnh Anh', 'nữ', 'Bắc', 'đọc truyện'],+ ['Ngọc Trân', 'nữ', 'Trung', 'tự nhiên'], ['Thùy Dung', 'nữ', 'Nam', 'tin tức'], ['Mỹ Duyên', 'nữ', 'Nam', 'đọc truyện'],+].map(([name, gender, region, style]) => ({ id: name, name, gender, region, style, engine: 'vieneu' }));+export const EDGE_VOICES = [+ { id: 'edge:vi-VN-HoaiMyNeural', name: 'Hoài My (edge-tts)', gender: 'nữ', region: 'Bắc', style: 'cần mạng', engine: 'edge' },+ { id: 'edge:vi-VN-NamMinhNeural', name: 'Nam Minh (edge-tts)', gender: 'nam', region: 'Bắc', style: 'cần mạng', engine: 'edge' },+];+export const VOICE_SAMPLE_TEXT = 'Xin chào, đây là giọng đọc thử của Lumfin.';++const hasPyModule = (m) => spawnSync(PY, ['-c', `import importlib.util,sys;sys.exit(0 if importlib.util.find_spec('${m}') else 1)`], { windowsHide: true, timeout: 20000 }).status === 0;+let tools = null;+/** Máy có VieNeu / edge-tts không (kiểm 1 lần mỗi tiến trình). */+export function ttsAvailable(refresh = false) {+ if (!tools || refresh) tools = { vieneu: hasPyModule('vieneu'), edge: hasPyModule('edge_tts') };+ return tools;+}++/** { engine, speaker } cho 1 giá trị voice. VieNeu không có trên máy → rơi về edge-tts cùng giới. */+export function voiceEngine(voice) {+ if (String(voice).startsWith('edge:')) return { engine: 'edge', speaker: voice.slice(5) };+ if (!ttsAvailable().vieneu) {+ const v = VIENEU_VOICES.find((x) => x.id === voice);+ return { engine: 'edge', speaker: v?.gender === 'nữ' ? 'vi-VN-HoaiMyNeural' : 'vi-VN-NamMinhNeural' };+ }+ return { engine: 'vieneu', speaker: voice };+}++/** Chuẩn hoá + kiểm tuỳ chọn. Thiếu trường → auto / auto / true. */+export function normalizeAudioPrefs(a) {+ if (a === undefined || a === null || a === '') return { music: 'auto', voice: 'auto', sfx: true };+ if (typeof a !== 'object') throw new Error('audio phải là object { music, voice, sfx }');+ const music = String(a.music ?? 'auto').trim() || 'auto';+ if (!['auto', 'none', ...MUSIC_STYLES].includes(music)) throw new Error(`audio.music "${music}" không có (auto | none | ${MUSIC_STYLES.join(' | ')})`);+ const voice = String(a.voice ?? 'auto').trim() || 'auto';+ const known = ['auto', 'none', ...VIENEU_VOICES.map((v) => v.id), ...EDGE_VOICES.map((v) => v.id)];+ if (!known.includes(voice) && !/^edge:vi-VN-\w+Neural$/.test(voice)) throw new Error(`audio.voice "${voice}" không có (auto | none | tên giọng: ${VIENEU_VOICES.map((v) => v.id).join(', ')})`);+ const sfx = a.sfx === undefined ? true : !(a.sfx === false || a.sfx === 'false' || a.sfx === 0 || a.sfx === '0');+ return { music, voice, sfx };+}++/** Đoán style nhạc từ §9 "Âm thanh" của guidance (dùng khi AI không viết audio.json). */+export function styleFromGuidance(md = '') {+ const s = (String(md).match(/##\s*9\.[^\n]*\n([\s\S]*?)(\n##\s|$)/) || [, String(md)])[1].toLowerCase();+ if (/8-?bit|chiptune|pixel|game cũ/.test(s)) return 'retro-8bit';+ if (/trailer|dàn dây|trống trận|hùng tráng|điện ảnh|epic|orchestr/.test(s)) return 'epic';+ if (/căng|hồi hộp|drone|bí ẩn|rùng|kinh dị|thriller|suspense/.test(s)) return 'tense';+ if (/lo-?fi|piano|ấm|nhẹ nhàng|chill|thư giãn|acoustic/.test(s)) return 'chill';+ if (/vui nhộn|tung tăng|marimba|hoạt hình|ukulele|trẻ con|hài|playful|xylophone/.test(s)) return 'playful';+ return 'upbeat';+}++/**+ * Áp tuỳ chọn lên spec audio.json (spec có thể null = AI chưa viết). Trả spec mới hoặc null nếu không có gì để trộn.+ * prefs.fallbackStyle: style dùng khi music "auto" mà spec không có nhạc.+ */+export function applyAudioPrefs(spec, prefs) {+ if (!prefs) return spec;+ const p = normalizeAudioPrefs(prefs);+ const out = spec ? JSON.parse(JSON.stringify(spec)) : { music: null, sfx: [], voice: null };+ if (p.music === 'none') out.music = null;+ else if (p.music !== 'auto') out.music = { ...(out.music || {}), style: p.music };+ else if (!out.music && !spec && prefs.fallbackStyle) out.music = { style: prefs.fallbackStyle };+ if (!p.sfx) out.sfx = [];+ if (p.voice === 'none') out.voice = null;+ else if (p.voice !== 'auto' && out.voice?.lines?.length) {+ const ve = voiceEngine(p.voice);+ out.voice = { ...out.voice, speaker: ve.speaker, engine: ve.engine };+ }+ if (!out.music && !(out.sfx || []).length && !out.voice?.lines?.length) return null;+ return out;+}++/** Danh sách cho UI / API. */+export function audioOptions() {+ const t = ttsAvailable();+ return {+ music: [{ id: 'auto', name: 'Tự chọn theo mẫu' }, { id: 'none', name: 'Không nhạc' }, ...MUSIC_LIST.map((m) => ({ id: m.name, name: m.name, desc: m.desc }))],+ voices: [{ id: 'auto', name: 'Theo mẫu (chỉ đọc khi mẫu có lời)' }, { id: 'none', name: 'Không lời đọc' },+ ...(t.vieneu ? VIENEU_VOICES : []), ...(t.edge ? EDGE_VOICES : [])],+ vieneu: t.vieneu, edgeTts: t.edge,+ hint: t.vieneu ? null : `Cài giọng đọc: pip install vieneu${t.edge ? ' (đang dùng edge-tts, cần mạng)' : ' (hoặc pip install edge-tts)'}`,+ sampleText: VOICE_SAMPLE_TEXT,+ };+}diff --git a/engine/audio/voice.mjs b/engine/audio/voice.mjsindex 1830eba..547cf64 100644--- a/engine/audio/voice.mjs+++ b/engine/audio/voice.mjs@@ -1,90 +1,97 @@-// Giọng đọc tiếng Việt: VieNeu (chạy trên máy, mặc định) → edge-tts (dự phòng, cần mạng).-// Mỗi câu ra 1 WAV 48 kHz mono đã cắt lặng đầu/cuối và đưa RMS về −16 dBFS; có cache theo nội dung.-import fs from 'node:fs';-import path from 'node:path';-import crypto from 'node:crypto';-import { fileURLToPath } from 'node:url';-import { run } from '../lib.mjs';-import { readWav, writeWav, normalizeRms, SR } from './dsp.mjs';--const HERE = path.dirname(fileURLToPath(import.meta.url));-export const DEFAULT_VOICE = 'Hải Đăng';-const PY = process.env.LUMREELS_PYTHON || 'python';--// Cách đọc cho TTS; chữ trên màn hình giữ nguyên. "Lum phin" là cách duy nhất whisper nghe ra đúng "Lumfin" (đã thử 7 cách).-const SAY = [- [/\blumfin\.net\b/gi, 'Lum phin chấm nét'],- [/\blumfin\b/gi, 'Lum phin'],- [/\blumi\b/gi, 'Lu mi'],- [/&/g, ' và '],- [/(\d+(?:[.,]\d+)?)\s*%/g, '$1 phần trăm'],-];-export function toSpeech(text) {- let s = String(text);- for (const [re, rep] of SAY) s = s.replace(re, rep);- return s.replace(/[*_#]/g, '').replace(/\s+/g, ' ').trim();-}--/** Giọng edge-tts tương ứng khi phải dự phòng. */-const EDGE = { female: 'vi-VN-HoaiMyNeural', male: 'vi-VN-NamMinhNeural' };-// Giọng nữ có sẵn của VieNeu v3 Turbo (còn lại là nam): Trúc Ly, Mai Anh, Thùy Dung, Ngọc Huyền, Ngọc Trân,-// Ngọc Linh, Đoan Trang, Thục Đoan, Mỹ Duyên, Quỳnh Anh, Kim Thanh. Nam hay dùng: Hải Đăng (mặc định), Thiện Minh (kể chuyện).-const FEMALE = /trúc ly|mai anh|thùy dung|ngọc|đoan|mỹ duyên|quỳnh anh|kim thanh/i;--async function toWav48(src, dst) {- const r = await run('ffmpeg', ['-y', '-v', 'error', '-i', src, '-ac', '1', '-ar', String(SR), '-c:a', 'pcm_s16le', dst]);- if (r.code !== 0) throw new Error('ffmpeg đổi giọng sang WAV lỗi: ' + r.out.slice(-300));-}-/** Cắt lặng đầu/cuối (ngưỡng −40 dBFS, chừa 30 ms) và chuẩn hoá RMS. */-function trimNormalize(file) {- const { chans } = readWav(file), x = chans[0], th = 0.01, pad = Math.round(0.03 * SR);- let a = 0, b = x.length - 1;- while (a < x.length && Math.abs(x[a]) < th) a++;- while (b > a && Math.abs(x[b]) < th) b--;- const y = x.slice(Math.max(0, a - pad), Math.min(x.length, b + pad));- normalizeRms([y], -16, -1);- writeWav(file, [y]);- return y.length / SR;-}--/**- * lines: [{t, text, say?}] → [{t, text, file, dur}]. workDir chứa cache voice-<hash>.wav.- * engine: 'vieneu' | 'edge'. Lỗi VieNeu thì tự chuyển edge-tts.- */-export async function synthVoice(lines, workDir, { engine = 'vieneu', voice = DEFAULT_VOICE, log = console.log } = {}) {- fs.mkdirSync(workDir, { recursive: true });- const items = lines.map((l) => {- const spoken = toSpeech(l.say || l.text);- const h = crypto.createHash('sha1').update(`${engine}|${voice}|${spoken}`).digest('hex').slice(0, 12);- return { ...l, spoken, file: path.join(workDir, `voice-${h}.wav`) };- });- const todo = items.filter((it) => !fs.existsSync(it.file));- if (todo.length && engine === 'vieneu') {- const raw = todo.map((it) => ({ text: it.spoken, voice, out: it.file.replace(/\.wav$/, '.raw.wav') }));- const jf = path.join(workDir, 'tts-jobs.json');- fs.writeFileSync(jf, JSON.stringify(raw, null, 1));- log(`giọng: VieNeu "${voice}" đọc ${todo.length} câu (nạp mô hình lần đầu hơi lâu)…`);- const r = await run(PY, [path.join(HERE, 'tts_vieneu.py'), jf], { env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });- for (let i = 0; i < todo.length; i++) {- if (fs.existsSync(raw[i].out)) { await toWav48(raw[i].out, todo[i].file); fs.rmSync(raw[i].out, { force: true }); }- }- if (r.code !== 0) log('CẢNH BÁO: VieNeu lỗi, chuyển edge-tts. ' + r.out.slice(-400));- }- for (const it of items.filter((x) => !fs.existsSync(x.file))) {- const ev = FEMALE.test(voice) ? EDGE.female : EDGE.male, mp3 = it.file.replace(/\.wav$/, '.mp3');- log(`giọng: edge-tts ${ev}: "${it.spoken}"`);- const r = await run(PY, ['-m', 'edge_tts', '--voice', ev, '--text', it.spoken, '--write-media', mp3], { env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });- if (r.code !== 0 || !fs.existsSync(mp3)) throw new Error('Không tạo được giọng đọc (VieNeu và edge-tts đều lỗi): ' + r.out.slice(-300));- await toWav48(mp3, it.file); fs.rmSync(mp3, { force: true });- }- const out = [];- const meta = path.join(workDir, 'voice-meta.json');- const cache = fs.existsSync(meta) ? JSON.parse(fs.readFileSync(meta, 'utf8')) : {};- for (const it of items) {- const key = path.basename(it.file);- if (!cache[key]) cache[key] = { dur: trimNormalize(it.file), spoken: it.spoken };- out.push({ t: it.t, text: it.text, spoken: it.spoken, file: it.file, dur: cache[key].dur });- }- fs.writeFileSync(meta, JSON.stringify(cache, null, 1));- return out;-}+// Giọng đọc tiếng Việt: VieNeu (chạy trên máy, mặc định) → edge-tts (dự phòng, cần mạng).+// Mỗi câu ra 1 WAV 48 kHz mono đã cắt lặng đầu/cuối và đưa RMS về −16 dBFS; có cache theo nội dung.+import fs from 'node:fs';+import path from 'node:path';+import crypto from 'node:crypto';+import { fileURLToPath } from 'node:url';+import { run } from '../lib.mjs';+import { readWav, writeWav, normalizeRms, SR } from './dsp.mjs';++const HERE = path.dirname(fileURLToPath(import.meta.url));+export const DEFAULT_VOICE = 'Hải Đăng';+const PY = process.env.LUMREELS_PYTHON || 'python';++// Cách đọc cho TTS; chữ trên màn hình giữ nguyên. "Lum phin" là cách duy nhất whisper nghe ra đúng "Lumfin" (đã thử 7 cách).+const SAY = [+ [/\blumfin\.net\b/gi, 'Lum phin chấm nét'],+ [/\blumfin\b/gi, 'Lum phin'],+ [/\blumi\b/gi, 'Lu mi'],+ [/&/g, ' và '],+ [/(\d+(?:[.,]\d+)?)\s*%/g, '$1 phần trăm'],+];+export function toSpeech(text) {+ let s = String(text);+ for (const [re, rep] of SAY) s = s.replace(re, rep);+ return s.replace(/[*_#]/g, '').replace(/\s+/g, ' ').trim();+}++/** Giọng edge-tts tương ứng khi phải dự phòng. */+const EDGE = { female: 'vi-VN-HoaiMyNeural', male: 'vi-VN-NamMinhNeural' };+// Giọng nữ có sẵn của VieNeu v3 Turbo (còn lại là nam): Trúc Ly, Mai Anh, Thùy Dung, Ngọc Huyền, Ngọc Trân,+// Ngọc Linh, Đoan Trang, Thục Đoan, Mỹ Duyên, Quỳnh Anh, Kim Thanh. Nam hay dùng: Hải Đăng (mặc định), Thiện Minh (kể chuyện).+const FEMALE = /trúc ly|mai anh|thùy dung|ngọc|đoan|mỹ duyên|quỳnh anh|kim thanh/i;++async function toWav48(src, dst) {+ const r = await run('ffmpeg', ['-y', '-v', 'error', '-i', src, '-ac', '1', '-ar', String(SR), '-c:a', 'pcm_s16le', dst]);+ if (r.code !== 0) throw new Error('ffmpeg đổi giọng sang WAV lỗi: ' + r.out.slice(-300));+}+/** Cắt lặng đầu/cuối (ngưỡng −40 dBFS, chừa 30 ms) và chuẩn hoá RMS. */+function trimNormalize(file) {+ const { chans } = readWav(file), x = chans[0], th = 0.01, pad = Math.round(0.03 * SR);+ let a = 0, b = x.length - 1;+ while (a < x.length && Math.abs(x[a]) < th) a++;+ while (b > a && Math.abs(x[b]) < th) b--;+ const y = x.slice(Math.max(0, a - pad), Math.min(x.length, b + pad));+ normalizeRms([y], -16, -1);+ writeWav(file, [y]);+ return y.length / SR;+}++/**+ * lines: [{t, text, say?}] → [{t, text, file, dur}]. workDir chứa cache voice-<hash>.wav.+ * engine: 'vieneu' | 'edge'. Lỗi VieNeu thì tự chuyển edge-tts.+ */+// Mỗi lúc chỉ 1 lượt TTS (VieNeu nạp mô hình nặng): xếp hàng trong tiến trình.+let ttsChain = Promise.resolve();+export function synthVoice(...args) {+ const p = ttsChain.then(() => synthVoiceNow(...args));+ ttsChain = p.catch(() => {});+ return p;+}+async function synthVoiceNow(lines, workDir, { engine = 'vieneu', voice = DEFAULT_VOICE, log = console.log } = {}) {+ fs.mkdirSync(workDir, { recursive: true });+ const items = lines.map((l) => {+ const spoken = toSpeech(l.say || l.text);+ const h = crypto.createHash('sha1').update(`${engine}|${voice}|${spoken}`).digest('hex').slice(0, 12);+ return { ...l, spoken, file: path.join(workDir, `voice-${h}.wav`) };+ });+ const todo = items.filter((it) => !fs.existsSync(it.file));+ if (todo.length && engine === 'vieneu') {+ const raw = todo.map((it) => ({ text: it.spoken, voice, out: it.file.replace(/\.wav$/, '.raw.wav') }));+ const jf = path.join(workDir, 'tts-jobs.json');+ fs.writeFileSync(jf, JSON.stringify(raw, null, 1));+ log(`giọng: VieNeu "${voice}" đọc ${todo.length} câu (nạp mô hình lần đầu hơi lâu)…`);+ const r = await run(PY, [path.join(HERE, 'tts_vieneu.py'), jf], { env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });+ for (let i = 0; i < todo.length; i++) {+ if (fs.existsSync(raw[i].out)) { await toWav48(raw[i].out, todo[i].file); fs.rmSync(raw[i].out, { force: true }); }+ }+ if (r.code !== 0) log('CẢNH BÁO: VieNeu lỗi, chuyển edge-tts. ' + r.out.slice(-400));+ }+ for (const it of items.filter((x) => !fs.existsSync(x.file))) {+ const ev = /^vi-VN-\w+Neural$/.test(voice) ? voice : FEMALE.test(voice) ? EDGE.female : EDGE.male, mp3 = it.file.replace(/\.wav$/, '.mp3');+ log(`giọng: edge-tts ${ev}: "${it.spoken}"`);+ const r = await run(PY, ['-m', 'edge_tts', '--voice', ev, '--text', it.spoken, '--write-media', mp3], { env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });+ if (r.code !== 0 || !fs.existsSync(mp3)) throw new Error('Không tạo được giọng đọc (VieNeu và edge-tts đều lỗi): ' + r.out.slice(-300));+ await toWav48(mp3, it.file); fs.rmSync(mp3, { force: true });+ }+ const out = [];+ const meta = path.join(workDir, 'voice-meta.json');+ const cache = fs.existsSync(meta) ? JSON.parse(fs.readFileSync(meta, 'utf8')) : {};+ for (const it of items) {+ const key = path.basename(it.file);+ if (!cache[key]) cache[key] = { dur: trimNormalize(it.file), spoken: it.spoken };+ out.push({ t: it.t, text: it.text, spoken: it.spoken, file: it.file, dur: cache[key].dur });+ }+ fs.writeFileSync(meta, JSON.stringify(cache, null, 1));+ return out;+}diff --git a/engine/lib.mjs b/engine/lib.mjsindex 2f0bd17..68022bc 100644--- a/engine/lib.mjs+++ b/engine/lib.mjs@@ -43,7 +43,7 @@ export async function acquireSlot({ max = Number(process.env.LUMREELS_HF_SLOTS)try {const pid = Number(fs.readFileSync(f, 'utf8'));const age = Date.now() - fs.statSync(f).mtimeMs;- if (!pid || !pidAlive(pid) || age > 20 * 60 * 1000) fs.rmSync(f, { force: true }); // chỗ của tiến trình đã chết / kẹt > 20 phút+ if (!pid || !pidAlive(pid) || age > hfTimeoutMs(600) + 60 * 1000) fs.rmSync(f, { force: true }); // chỗ của tiến trình đã chết / kẹt quá trần render dài nhất} catch { /* file vừa bị nhả */ }}}@@ -141,8 +141,17 @@ export function lintFonts(html) {return { errors, warnings, used: [...used] };}-/** Chạy CLI HyperFrames: chờ chỗ trống (acquireSlot), có giới hạn thời gian (mặc định 10 phút) để không treo vô hạn. */-export async function runHF(args, { cwd, onLine, timeoutMs = 10 * 60 * 1000 } = {}) {+/** Giới hạn 1 lượt HyperFrames theo thời lượng cảnh: 10 phút + 2 phút cho mỗi 8 giây video, trần 3 giờ. */+export function hfTimeoutMs(durationS = 8) {+ return Math.min(180, 10 + 2 * Math.ceil(Math.max(0, Number(durationS) || 8) / 8)) * 60 * 1000;+}+/** data-duration của <sceneDir>/index.html (args[1] của snapshot/render); không đọc được → 8. */+function sceneDuration(sceneDir) {+ try { return Number(/data-duration=["']([\d.]+)["']/.exec(fs.readFileSync(path.join(sceneDir, 'index.html'), 'utf8'))?.[1]) || 8; } catch { return 8; }+}++/** Chạy CLI HyperFrames: chờ chỗ trống (acquireSlot), có giới hạn thời gian (theo thời lượng cảnh, hfTimeoutMs) để không treo vô hạn. */+export async function runHF(args, { cwd, onLine, timeoutMs = hfTimeoutMs(sceneDuration(args[1] || cwd || '.')) } = {}) {const release = await acquireSlot({ onWait: () => onLine?.('chờ chỗ chạy HyperFrames (đang có nhiều render cùng lúc)…') });try {return await new Promise((resolve) => {diff --git a/engine/render.mjs b/engine/render.mjsindex 7a2a688..381b6dc 100644--- a/engine/render.mjs+++ b/engine/render.mjs@@ -1,77 +1,79 @@-#!/usr/bin/env node-// node engine/render.mjs <sceneDir> -o out.mp4 [--audio nhac.mp3] [--quality draft|looks|delivery]-// MP4 H.264 1080x1920 30fps qua HyperFrames. --audio: ghép 1 file âm thanh (giọng đọc/nhạc) sau khi render hình.-// Có <sceneDir>/audio.json thì tự trộn nhạc + sfx + lời (engine/audio/) và ghép; bản không tiếng giữ ở out.silent.mp4.-import fs from 'node:fs';-import path from 'node:path';-import { fileURLToPath } from 'node:url';-import { syncLib, lintScene, runHF, run, parseArgs, probe } from './lib.mjs';-import { fontCheck } from './fontcheck.mjs';-import { loadAudioSpec, addAudio } from './audio/mix.mjs';--export async function render(sceneDir, outFile, { audio, quality = 'looks', log = console.log } = {}) {- sceneDir = path.resolve(sceneDir);- outFile = path.resolve(outFile || path.join(sceneDir, 'out.mp4'));- syncLib(sceneDir);- const lint = lintScene(sceneDir);- for (const w of lint.warnings) log('CẢNH BÁO: ' + w);- if (lint.errors.length) {- for (const e of lint.errors) log('LỖI: ' + e);- return { ok: false, errors: lint.errors };- }- const { width, height } = lint.meta;- if (width !== 1080 || height !== 1920) log(`CẢNH BÁO: kích thước ${width}x${height}, mặc định là 1080x1920`);- // scene/audio.json (nhạc + sfx + lời tự tổng hợp) → render hình ra out.silent.mp4 rồi trộn + ghép vào out.mp4.- // --audio file (ghép thẳng 1 file) được ưu tiên hơn audio.json.- let audioSpec = null;- if (!audio) {- try { audioSpec = loadAudioSpec(sceneDir); } catch (e) { log('LỖI: ' + e.message); return { ok: false, errors: [e.message] }; }- }- const silent = audio ? outFile.replace(/\.mp4$/i, '.video.mp4') : audioSpec ? outFile.replace(/\.mp4$/i, '.silent.mp4') : outFile;- fs.mkdirSync(path.dirname(outFile), { recursive: true });- let lastPct = -1;- const fcP = process.env.VIDEOAI_FONTCHECK !== '0' ? fontCheck(sceneDir, { log }) : Promise.resolve(null);- const r = await runHF(['render', sceneDir, '-o', silent, '-f', '30', '-q', quality], {- cwd: sceneDir,- onLine: (l) => {- const m = l.match(/^@hf-progress (.*)$/);- if (m) {- try {- const p = JSON.parse(m[1]);- const bucket = Math.floor(p.pct / 10);- if (bucket !== lastPct) { lastPct = bucket; log(`render ${p.pct}% ${p.code}${p.total ? ` ${p.done}/${p.total}` : ''}`); }- } catch {}- } else if (/error|lỗi|fail/i.test(l) && !l.includes('[INFO]')) log(l);- },- });- const fc = await fcP;- if (r.code !== 0 || !fs.existsSync(silent)) {- log(r.out.slice(-3000));- return { ok: false, errors: ['HyperFrames render lỗi (mã ' + r.code + ')'] };- }- if (audio) {- // Chỗ gắn audio: giữ nguyên hình, AAC 192k, cắt theo độ dài hình.- const a = await run('ffmpeg', ['-y', '-v', 'error', '-i', silent, '-i', path.resolve(audio), '-map', '0:v:0', '-map', '1:a:0',- '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-shortest', '-movflags', '+faststart', outFile]);- if (a.code !== 0) return { ok: false, errors: ['ghép audio lỗi: ' + a.out.slice(-500)] };- fs.rmSync(silent, { force: true });- }- let audioRes = null;- if (audioSpec) {- try { audioRes = await addAudio(sceneDir, silent, outFile, { log }); }- catch (e) { log('CẢNH BÁO: trộn âm thanh lỗi, giữ video không tiếng: ' + e.message); fs.copyFileSync(silent, outFile); audioRes = { ok: false, error: e.message }; }- }- const info = await probe(outFile);- const v = info?.streams?.find((s) => s.codec_name === 'h264') || info?.streams?.[0];- log(`out: ${outFile} ${v?.codec_name} ${v?.width}x${v?.height} ${v?.r_frame_rate} ${(+info?.format?.duration).toFixed(2)}s`);- return { ok: true, file: outFile, probe: info, fonts: fc ? fc.issues : null, audio: audioRes };-}--if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {- const { pos, opt } = parseArgs(process.argv.slice(2));- if (!pos[0]) { console.error('Dùng: node engine/render.mjs <sceneDir> -o out.mp4 [--audio file] [--quality draft|looks|delivery]'); process.exit(2); }- const t0 = Date.now();- const res = await render(pos[0], opt.o || opt.out, { audio: opt.audio, quality: opt.quality || 'looks' });- console.log(`${res.ok ? 'OK' : 'FAIL'} sau ${((Date.now() - t0) / 1000).toFixed(1)}s`);- process.exit(res.ok ? 0 : 1);-}+#!/usr/bin/env node+// node engine/render.mjs <sceneDir> -o out.mp4 [--audio nhac.mp3] [--quality draft|looks|delivery]+// MP4 H.264 1080x1920 30fps qua HyperFrames. --audio: ghép 1 file âm thanh (giọng đọc/nhạc) sau khi render hình.+// Có <sceneDir>/audio.json thì tự trộn nhạc + sfx + lời (engine/audio/) và ghép; bản không tiếng giữ ở out.silent.mp4.+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { syncLib, lintScene, runHF, run, parseArgs, probe } from './lib.mjs';+import { fontCheck } from './fontcheck.mjs';+import { loadAudioSpec, addAudio } from './audio/mix.mjs';+import { applyAudioPrefs } from './audio/prefs.mjs';++export async function render(sceneDir, outFile, { audio, audioPrefs, quality = 'looks', log = console.log } = {}) {+ sceneDir = path.resolve(sceneDir);+ outFile = path.resolve(outFile || path.join(sceneDir, 'out.mp4'));+ syncLib(sceneDir);+ const lint = lintScene(sceneDir);+ for (const w of lint.warnings) log('CẢNH BÁO: ' + w);+ if (lint.errors.length) {+ for (const e of lint.errors) log('LỖI: ' + e);+ return { ok: false, errors: lint.errors };+ }+ const { width, height } = lint.meta;+ if (width !== 1080 || height !== 1920) log(`CẢNH BÁO: kích thước ${width}x${height}, mặc định là 1080x1920`);+ // scene/audio.json (nhạc + sfx + lời tự tổng hợp) → render hình ra out.silent.mp4 rồi trộn + ghép vào out.mp4.+ // --audio file (ghép thẳng 1 file) được ưu tiên hơn audio.json.+ let audioSpec = null;+ if (!audio) {+ // audioPrefs (tuỳ chọn của job: {music, voice, sfx, fallbackStyle}) ghi đè audio.json; không có audio.json mà có nhạc fallback thì vẫn có tiếng+ try { audioSpec = applyAudioPrefs(loadAudioSpec(sceneDir), audioPrefs); } catch (e) { log('LỖI: ' + e.message); return { ok: false, errors: [e.message] }; }+ }+ const silent = audio ? outFile.replace(/\.mp4$/i, '.video.mp4') : audioSpec ? outFile.replace(/\.mp4$/i, '.silent.mp4') : outFile;+ fs.mkdirSync(path.dirname(outFile), { recursive: true });+ let lastPct = -1;+ const fcP = process.env.VIDEOAI_FONTCHECK !== '0' ? fontCheck(sceneDir, { log }) : Promise.resolve(null);+ const r = await runHF(['render', sceneDir, '-o', silent, '-f', '30', '-q', quality], {+ cwd: sceneDir,+ onLine: (l) => {+ const m = l.match(/^@hf-progress (.*)$/);+ if (m) {+ try {+ const p = JSON.parse(m[1]);+ const bucket = Math.floor(p.pct / 10);+ if (bucket !== lastPct) { lastPct = bucket; log(`render ${p.pct}% ${p.code}${p.total ? ` ${p.done}/${p.total}` : ''}`); }+ } catch {}+ } else if (/error|lỗi|fail/i.test(l) && !l.includes('[INFO]')) log(l);+ },+ });+ const fc = await fcP;+ if (r.code !== 0 || !fs.existsSync(silent)) {+ log(r.out.slice(-3000));+ return { ok: false, errors: ['HyperFrames render lỗi (mã ' + r.code + ')'] };+ }+ if (audio) {+ // Chỗ gắn audio: giữ nguyên hình, AAC 192k, cắt theo độ dài hình.+ const a = await run('ffmpeg', ['-y', '-v', 'error', '-i', silent, '-i', path.resolve(audio), '-map', '0:v:0', '-map', '1:a:0',+ '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-shortest', '-movflags', '+faststart', outFile]);+ if (a.code !== 0) return { ok: false, errors: ['ghép audio lỗi: ' + a.out.slice(-500)] };+ fs.rmSync(silent, { force: true });+ }+ let audioRes = null;+ if (audioSpec) {+ try { audioRes = await addAudio(sceneDir, silent, outFile, { log, spec: audioSpec }); }+ catch (e) { log('CẢNH BÁO: trộn âm thanh lỗi, giữ video không tiếng: ' + e.message); fs.copyFileSync(silent, outFile); audioRes = { ok: false, error: e.message }; }+ }+ const info = await probe(outFile);+ const v = info?.streams?.find((s) => s.codec_name === 'h264') || info?.streams?.[0];+ log(`out: ${outFile} ${v?.codec_name} ${v?.width}x${v?.height} ${v?.r_frame_rate} ${(+info?.format?.duration).toFixed(2)}s`);+ return { ok: true, file: outFile, probe: info, fonts: fc ? fc.issues : null, audio: audioRes };+}++if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {+ const { pos, opt } = parseArgs(process.argv.slice(2));+ if (!pos[0]) { console.error('Dùng: node engine/render.mjs <sceneDir> -o out.mp4 [--audio file] [--quality draft|looks|delivery]'); process.exit(2); }+ const t0 = Date.now();+ const res = await render(pos[0], opt.o || opt.out, { audio: opt.audio, quality: opt.quality || 'looks' });+ console.log(`${res.ok ? 'OK' : 'FAIL'} sau ${((Date.now() - t0) / 1000).toFixed(1)}s`);+ process.exit(res.ok ? 0 : 1);+}diff --git a/generator/audio-job.mjs b/generator/audio-job.mjsnew file mode 100644index 0000000..0d997b4--- /dev/null+++ b/generator/audio-job.mjs@@ -0,0 +1,170 @@+// Đổi tiếng cho video ĐÃ DỰNG: trộn tiếng mới theo tuỳ chọn {music, voice, sfx} và ghép vào hình cũ (không dựng lại hình).+// Dùng chung cho CLI (`node cli.mjs audio`), REST (POST /api/jobs/:id/audio) và MCP (set_audio).+// out.mp4 luôn là bản mới nhất; bản trước chuyển sang versions/out-<n>.mp4 + versions/audio-<n>.json.+// out.silent.mp4 = hình gốc không tiếng (giữ nguyên).+// Chưa có lời đọc mà chọn giọng → AI viết 1–3 câu ngắn từ brief.json/nội dung (api → claude headless, như "Viết lại kịch bản").+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import Anthropic from '@anthropic-ai/sdk';+import { readJob, jobDir, guidancePath, logTo, exportOutput } from './jobs.mjs';+import { resolveRewriteEngine } from './rewrite.mjs';+import { probe } from '../engine/lib.mjs';+import { addAudio, loadAudioSpec, videoDuration } from '../engine/audio/mix.mjs';+import { normalizeAudioPrefs, applyAudioPrefs, styleFromGuidance, voiceEngine } from '../engine/audio/prefs.mjs';++const AI_TIMEOUT_MS = 90_000;+const busy = new Set();++function saveJob(id, patch) {+ const f = path.join(jobDir(id), 'job.json');+ const cur = JSON.parse(fs.readFileSync(f, 'utf8'));+ Object.assign(cur, patch, { updatedAt: new Date().toISOString() });+ fs.writeFileSync(f, JSON.stringify(cur, null, 2));+ return cur;+}+const hasAudioStream = async (f) => !!(await probe(f))?.streams?.some((s) => !s.width);++/** Danh sách bản: [{n, file, audio, createdAt, current?}] — bản hiện tại (out.mp4) đứng đầu. */+export function listVersions(id) {+ const dir = jobDir(id), vd = path.join(dir, 'versions'), job = readJob(id) || {};+ const meta = job.audioVersions || [];+ const out = [];+ if (fs.existsSync(path.join(dir, 'out.mp4'))) out.push({ n: meta.length ? Math.max(...meta.map((m) => m.n)) + 1 : 1, file: 'out.mp4', current: true, audio: job.audio || null, createdAt: job.audioAt || job.updatedAt });+ for (const m of [...meta].sort((a, b) => b.n - a.n)) if (fs.existsSync(path.join(vd, `out-${m.n}.mp4`))) out.push({ ...m, file: `versions/out-${m.n}.mp4` });+ return out;+}++/** Hỏi AI viết lời đọc ngắn khớp mốc. Trả [{t, text}]. */+export async function writeNarration(job, spec, duration, { log = () => {} } = {}) {+ const dir = jobDir(job.id);+ const brief = fs.existsSync(path.join(dir, 'brief.json')) ? fs.readFileSync(path.join(dir, 'brief.json'), 'utf8').slice(0, 6000) : '';+ const g = fs.existsSync(guidancePath(job.templateId)) ? fs.readFileSync(guidancePath(job.templateId), 'utf8') : '';+ const s9 = (g.match(/##\s*9\.[^\n]*\n([\s\S]*?)(\n##\s|$)/) || [])[1] || '';+ const marks = (spec?.sfx || []).map((s) => `${s.t}s ${s.name}`).join(', ');+ const prompt = `Viết LỜI ĐỌC tiếng Việt cho 1 video dọc ${duration.toFixed(1)} giây đã dựng xong (không đổi hình).+Trả ĐÚNG 1 khối JSON, không thêm gì: {"lines":[{"t":<giây bắt đầu>,"text":"<câu>"}]}++Luật:+- 1 đến ${duration > 12 ? 5 : 3} câu, mỗi câu ngắn. Tốc độ đọc ~4,5 âm tiết/giây: câu phải đọc xong trước "t" câu sau và trước giây ${(duration - 0.3).toFixed(1)}.+- Câu đầu bắt đầu trong 0,1–0,6s. Đặt "t" trùng mốc chuyển động chính (mốc tiếng động: ${marks || 'không có'}).+- Chỉ dùng ý, số, tên thương hiệu có trong nội dung/brief; không bịa số. Tiếng Việt đủ dấu, viết số bằng chữ số bình thường.+- Có tên thương hiệu/CTA thì câu cuối nói tên đó.+${s9 ? `- Gợi ý giọng/lời của mẫu: ${s9.trim().slice(0, 600)}` : ''}++Nội dung người dùng:+"""+${String(job.content || '').slice(0, 3000)}+"""+${brief ? `\nbrief.json (ô nội dung trên màn hình):\n${brief}` : ''}`;+ const engine = resolveRewriteEngine();+ if (!engine) throw new Error('Chưa có lời đọc và chưa cấu hình AI để viết lời (ANTHROPIC_API_KEY hoặc Claude Code). Thêm "voice.lines" vào scene/audio.json bằng tay.');+ log(`lời đọc: nhờ AI (${engine}) viết…`);+ let text;+ try { text = engine === 'api' ? await viaApi(prompt) : await viaClaude(prompt); }+ catch (e) {+ // khoá API sai (401/403) mà máy có Claude Code → thử claude, như "Viết lại kịch bản"+ const { findClaude } = await import('./claude.mjs');+ if (engine === 'api' && (e.status === 401 || e.status === 403) && findClaude()) { log(`lời đọc: API lỗi ${e.status}, chuyển Claude Code`); text = await viaClaude(prompt); }+ else throw new Error('AI viết lời đọc lỗi: ' + String(e.message).slice(0, 200));+ }+ const m = text.match(/\{[\s\S]*\}/);+ let lines;+ try { lines = JSON.parse(m?.[0] || '').lines; } catch { throw new Error('AI trả lời đọc sai dạng JSON, bấm lại thử'); }+ lines = (Array.isArray(lines) ? lines : []).filter((l) => typeof l?.t === 'number' && String(l.text || '').trim())+ .map((l) => ({ t: Math.max(0, Math.min(duration - 0.5, +l.t.toFixed(2))), text: String(l.text).trim().slice(0, 200) }));+ if (!lines.length) throw new Error('AI không trả câu lời đọc nào');+ return lines;+}+async function viaApi(prompt) {+ const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, maxRetries: 1, timeout: AI_TIMEOUT_MS });+ const msg = await client.messages.create({ model: process.env.REWRITE_MODEL || 'claude-haiku-5-5', max_tokens: 1000, messages: [{ role: 'user', content: prompt }] });+ return (msg.content || []).filter((b) => b.type === 'text').map((b) => b.text).join('\n');+}+async function viaClaude(prompt) {+ const { findClaude } = await import('./claude.mjs');+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'lumreels-voice-'));+ const args = ['-p', '--output-format', 'json', '--permission-mode', 'default', '--tools', '', '--setting-sources', 'project', '--strict-mcp-config', '--no-session-persistence', '--max-turns', '2'];+ return new Promise((resolve, reject) => {+ const p = spawn(findClaude(), args, { cwd, windowsHide: true, env: { ...process.env } });+ let out = '';+ const timer = setTimeout(() => { p.kill(); reject(new Error('Claude Code quá giờ khi viết lời đọc')); }, AI_TIMEOUT_MS);+ p.stdout.on('data', (d) => { out += d; });+ p.on('error', (e) => { clearTimeout(timer); reject(e); });+ p.on('close', (code) => {+ clearTimeout(timer); fs.rm(cwd, { recursive: true, force: true }, () => {});+ try { const r = JSON.parse(out.trim().split(/\r?\n/).pop()); if (code === 0 && !r.is_error) return resolve(String(r.result || '')); } catch { /* rơi xuống lỗi */ }+ reject(new Error(`claude thoát mã ${code} khi viết lời đọc`));+ });+ p.stdin.end(prompt);+ });+}++/**+ * Trộn tiếng mới cho job đã dựng. prefs = {music, voice, sfx} (thiếu → giữ như job/audio.json hiện có).+ * Trả { ok, file, version, lufs, truePeak, warnings, voice, spec }.+ */+export async function reAudio(id, prefs, { log, exportOut = false } = {}) {+ const job = readJob(id);+ if (!job) throw new Error('Không thấy job ' + id);+ if (busy.has(id)) throw new Error('Job này đang trộn tiếng, chờ xong đã');+ busy.add(id);+ const L = log || logTo(job);+ saveJob(id, { audioStatus: 'mixing', audioError: null });+ try {+ const dir = jobDir(id), scene = path.join(dir, 'scene'), mp4 = path.join(dir, 'out.mp4'), silent = path.join(dir, 'out.silent.mp4');+ if (!fs.existsSync(mp4) && !fs.existsSync(silent)) throw new Error('Job chưa dựng hình (chưa có out.mp4)');+ // out.mp4 chưa có tiếng = bản hình mới nhất → làm out.silent.mp4+ const mp4HasAudio = fs.existsSync(mp4) && await hasAudioStream(mp4);+ if (fs.existsSync(mp4) && (!mp4HasAudio || !fs.existsSync(silent))) fs.copyFileSync(mp4, silent);++ const base = typeof job.audio === 'object' && job.audio ? job.audio : {};+ const p = normalizeAudioPrefs({ ...base, ...Object.fromEntries(Object.entries(prefs || {}).filter(([, v]) => v !== undefined)) });+ const fallbackStyle = styleFromGuidance(fs.existsSync(guidancePath(job.templateId)) ? fs.readFileSync(guidancePath(job.templateId), 'utf8') : '');+ const cur = loadAudioSpec(scene);+ let spec = applyAudioPrefs(cur, { ...p, fallbackStyle });+ const duration = await videoDuration(silent);+ if (p.voice !== 'none' && p.voice !== 'auto' && !spec?.voice?.lines?.length) {+ const lines = await writeNarration(job, spec || cur, duration, { log: L });+ const ve = voiceEngine(p.voice);+ spec = { ...(spec || { music: null, sfx: [] }), voice: { speaker: ve.speaker, engine: ve.engine, lines } };+ L(`lời đọc AI viết: ${lines.map((l) => `${l.t}s "${l.text}"`).join(' | ')}`);+ }+ if (!spec) throw new Error('Không có gì để trộn (nhạc "none", tắt tiếng động, không lời đọc)');++ // lưu bản cũ (nếu out.mp4 đang có tiếng)+ const versions = [...(job.audioVersions || [])];+ if (mp4HasAudio) {+ const vd = path.join(dir, 'versions'); fs.mkdirSync(vd, { recursive: true });+ const n = versions.length ? Math.max(...versions.map((v) => v.n)) + 1 : 1;+ fs.copyFileSync(mp4, path.join(vd, `out-${n}.mp4`));+ if (cur) fs.writeFileSync(path.join(vd, `audio-${n}.json`), JSON.stringify(cur, null, 2));+ versions.push({ n, audio: job.audio || null, createdAt: job.audioAt || job.updatedAt });+ L(`giữ bản cũ: versions/out-${n}.mp4`);+ }+ fs.writeFileSync(path.join(scene, 'audio.json'), JSON.stringify(spec, null, 2));+ const res = await addAudio(scene, silent, mp4, { log: L, seedKey: id });+ saveJob(id, { audio: p, audioVersions: versions, audioAt: new Date().toISOString(), audioStatus: 'done' });+ if (exportOut) exportOutput(readJob(id), L);+ return { ...res, version: versions.length + 1, spec };+ } catch (e) {+ saveJob(id, { audioStatus: 'error', audioError: e.message });+ L('trộn tiếng lỗi: ' + e.message);+ throw e;+ } finally {+ busy.delete(id);+ }+}+export const audioBusy = (id) => busy.has(id);++/** Agent nộp scene/audio.json (MCP submit_scene / REST). Kiểm luật trước khi ghi; sai → ném lỗi, giữ bản cũ. */+export async function saveAudioSpec(id, spec) {+ const { validateAudioSpec } = await import('../engine/audio/mix.mjs');+ const obj = typeof spec === 'string' ? JSON.parse(spec) : spec;+ validateAudioSpec(obj);+ const f = path.join(jobDir(id), 'scene', 'audio.json');+ fs.mkdirSync(path.dirname(f), { recursive: true });+ fs.writeFileSync(f, JSON.stringify(obj, null, 2));+ return f;+}diff --git a/generator/claude.mjs b/generator/claude.mjsindex 7c37318..6cd9a3f 100644--- a/generator/claude.mjs+++ b/generator/claude.mjs@@ -43,7 +43,7 @@ export function runClaude(cwd, prompt, log = console.log, { timeoutMs = 25 * 60if (!bin) return Promise.resolve({ ok: false, error: 'Không tìm thấy lệnh claude (đặt CLAUDE_BIN hoặc thêm vào PATH)' });return new Promise((resolve) => {log(`claude: ${bin} (cwd ${cwd})`);- const p = spawn(bin, claudeArgs(), { cwd, windowsHide: true, env: { ...process.env } });+ const p = spawn(bin, claudeArgs(), { cwd, windowsHide: true, env: (({ ANTHROPIC_API_KEY, ...e }) => e)(process.env) });const raw = fs.createWriteStream(path.join(cwd, 'claude.stream.jsonl'));let buf = '';let result = null;diff --git a/generator/jobs.mjs b/generator/jobs.mjsindex 17dd975..0be0cab 100644--- a/generator/jobs.mjs+++ b/generator/jobs.mjs@@ -11,6 +11,7 @@ import { runApi } from './api.mjs';import { preview } from '../engine/preview.mjs';import { render } from '../engine/render.mjs';import { lintScene, syncLib } from '../engine/lib.mjs';+import { normalizeAudioPrefs, styleFromGuidance } from '../engine/audio/prefs.mjs';export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));export const JOBS = path.join(ROOT, 'jobs');@@ -85,6 +86,32 @@ export function parseRunAt(v) {return d.toISOString();}+// Thời lượng: 3 giây → 10 phút. Nhận số giây (8, 90) hoặc chuỗi "90", "90s", "1:30", "10:00".+export const MIN_DURATION_S = 3;+export const MAX_DURATION_S = 600;+/** Đổi thời lượng người dùng gõ thành số giây nguyên. Trống → mặc định (8). Sai dạng / ngoài 3s–10 phút → lỗi. */+export function parseDuration(v, fallback = 8) {+ if (v === undefined || v === null || v === '') return fallback;+ let s;+ if (typeof v === 'number') s = v;+ else {+ const t = String(v).trim().toLowerCase().replace(/\s+/g, '');+ let m;+ if ((m = /^(\d{1,4})(?:s|giây|giay)?$/.exec(t))) s = Number(m[1]);+ else if ((m = /^(\d{1,2}):([0-5]\d)$/.exec(t))) s = Number(m[1]) * 60 + Number(m[2]);+ else if ((m = /^(\d{1,2})(?:m|p|phút|phut)$/.exec(t))) s = Number(m[1]) * 60;+ else throw new Error(`Thời lượng không hiểu được: "${v}" (gõ số giây như 90, hoặc phút:giây như 1:30)`);+ }+ if (!Number.isFinite(s)) throw new Error(`Thời lượng không hợp lệ: ${v}`);+ s = Math.round(s);+ if (s < MIN_DURATION_S || s > MAX_DURATION_S) throw new Error(`Thời lượng ${s}s ngoài giới hạn ${MIN_DURATION_S} giây – 10 phút`);+ return s;+}+/** 90 → "1:30"; 8 → "8s". */+export function fmtDuration(s) {+ return s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;+}+/** Tạo job. input = {templateId, content, durationS=8, aspect='9:16', mode, runAt?, source?} */export function createJob(input) {const templateId = String(input.templateId || '').padStart(3, '0');@@ -94,12 +121,13 @@ export function createJob(input) {const content = String(input.content || '').trim();if (!content) throw new Error('Thiếu nội dung');if (content.length > 4000) throw new Error('Nội dung quá dài (tối đa 4000 ký tự)');- const durationS = Math.min(60, Math.max(3, Number(input.durationS) || 8));+ const durationS = parseDuration(input.durationS);const aspect = input.aspect || '9:16';if (aspect !== '9:16') throw new Error('Hiện chỉ hỗ trợ 9:16 (1080x1920)');let mode = input.mode === 'agent' ? 'manual' : (input.mode || 'manual');if (!MODES.includes(mode)) throw new Error(`Chế độ không hợp lệ: ${mode} (auto|api|claude|manual|agent)`);const runAt = parseRunAt(input.runAt);+ const audio = normalizeAudioPrefs(input.audio); // {music, voice, sfx} — xem engine/audio/prefs.mjsconst stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(2, 14);const id = `${stamp}-${templateId}-${crypto.randomBytes(2).toString('hex')}`;const dir = path.join(JOBS, id);@@ -108,7 +136,7 @@ export function createJob(input) {const hasRef = fs.existsSync(sheet);if (hasRef) fs.copyFileSync(sheet, path.join(dir, 'ref-sheet.jpg'));const job = {- id, templateId, templateTitle: tpl.name, content, durationS, aspect, mode, hasRef,+ id, templateId, templateTitle: tpl.name, content, durationS, aspect, mode, hasRef, audio,status: runAt && new Date(runAt) > new Date() ? 'scheduled' : 'queued',runAt, source: input.source || 'api', createdAt: new Date().toISOString(),};@@ -126,6 +154,11 @@ export function resolveMode(mode) {return 'manual';}+/** Thời gian tối đa cho Claude Code viết cảnh: 25 phút, video dài thêm 5 phút mỗi phút video (trần 90 phút). */+function claudeTimeoutMs(durationS = 8) {+ return Math.min(90, 25 + Math.ceil(Math.max(0, durationS - 60) / 60) * 5) * 60 * 1000;+}+/** Giành quyền chạy 1 job (chống 2 tiến trình cùng chạy: server + `cli run-due`). */function claim(id) {const f = path.join(jobDir(id), '.claim');@@ -168,7 +201,7 @@ export async function runJob(id, { force = false } = {}) {const prompt = fs.readFileSync(path.join(jobDir(id), 'PROMPT.md'), 'utf8');const r = engine === 'api'? await runApi(job, jobDir(id), prompt, log, (usage) => update(id, { usage }))- : await runClaude(jobDir(id), prompt, log);+ : await runClaude(jobDir(id), prompt, log, { timeoutMs: claudeTimeoutMs(job.durationS) });if (!r.ok) return setStatus(job, 'error', { error: r.error });return await renderJob(id, { claimed: true });} finally {@@ -241,8 +274,10 @@ export async function renderJob(id, { quality = 'looks', audio, claimed = falseconst pv = await preview(path.join(dir, 'scene'), path.join(dir, 'preview.jpg'), log);if (!pv.ok) return setStatus(job, 'error', { error: pv.errors.join('; ') });job = setStatus(job, 'rendering');- const audioFile = audio || (job.audio ? path.join(dir, job.audio) : undefined);- const rr = await render(path.join(dir, 'scene'), path.join(dir, 'out.mp4'), { quality, audio: audioFile, log });+ // job.audio: chuỗi = file âm thanh ghép thẳng (cũ); object = tuỳ chọn {music, voice, sfx} áp lên scene/audio.json+ const audioFile = audio || (typeof job.audio === 'string' ? path.join(dir, job.audio) : undefined);+ const audioPrefs = job.audio && typeof job.audio === 'object' ? { ...job.audio, fallbackStyle: styleFromGuidance(fs.readFileSync(guidancePath(job.templateId), 'utf8')) } : undefined;+ const rr = await render(path.join(dir, 'scene'), path.join(dir, 'out.mp4'), { quality, audio: audioFile, audioPrefs, log });if (!rr.ok) return setStatus(job, 'error', { error: rr.errors.join('; ') });const v = rr.probe?.streams?.find((s) => s.width) || {};const output = { mp4: 'out.mp4', preview: 'preview.jpg', width: v.width, height: v.height, fps: v.r_frame_rate, duration: Number(rr.probe?.format?.duration) };diff --git a/generator/prompt.mjs b/generator/prompt.mjsindex bc3b0d8..0febbf8 100644--- a/generator/prompt.mjs+++ b/generator/prompt.mjs@@ -3,8 +3,22 @@ import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+const fmt = (s) => (s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`);const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));+/** Tuỳ chọn âm thanh người dùng đã chọn (job.audio = {music, voice, sfx}) → luật thêm cho audio.json. */+function audioRule(a) {+ if (!a || typeof a !== 'object') return '';+ const r = [];+ if (a.music === 'none') r.push('KHÔNG nhạc nền: `"music": null`');+ else if (a.music && a.music !== 'auto') r.push(`nhạc nền dùng đúng \`"style": "${a.music}"\``);+ if (a.sfx === false) r.push('KHÔNG tiếng động: `"sfx": []`');+ if (a.voice === 'none') r.push('KHÔNG lời đọc: `"voice": null` (kể cả mẫu có narration)');+ else if (a.voice && a.voice !== 'auto') r.push(`CÓ lời đọc (kể cả mẫu không có narration), \`"speaker": "${a.voice}"\`: 1–3 câu ngắn bám nội dung trên màn hình, câu cuối nói tên thương hiệu/CTA nếu có`);+ return r.length ? ` - Người dùng đã chọn âm thanh: ${r.join('; ')}.+` : '';+}+export function buildPrompt(job) {const guidance = fs.readFileSync(path.join(ROOT, 'templates', 'guidance', `${job.templateId}.md`), 'utf8');const authoring = fs.readFileSync(path.join(ROOT, 'engine', 'AUTHORING.md'), 'utf8');@@ -12,6 +26,16 @@ export function buildPrompt(job) {const scaleNote = D === 8? 'Thời lượng 8 giây: bám đúng bảng §6 Dòng thời gian của guidance.': `Thời lượng ${D} giây (guidance viết cho 8 giây): nếu ${D} < 8 thì co các mốc §6 theo tỉ lệ ${D}/8; nếu ${D} > 8 thì làm theo §10 "Khi nội dung dài hơn 8 giây".`;+ const scenes = Math.max(2, Math.round(D / 8));+ const longNote = D > 12 ? `++## Video dài ${D} giây (${fmt(D)}): nhiều cảnh nối nhau+Guidance viết cho 1 màn 8 giây. Với ${D} giây, làm theo §10 "Khi nội dung dài hơn 8 giây" của guidance:+- Chia nội dung thành khoảng ${scenes} cảnh nối nhau, mỗi cảnh 6–10 giây (không cảnh nào < 5s hay > 12s). Ghi danh sách cảnh vào \`brief.json\` trường \`scenes\`: \`[{ "from": 0, "to": 8, "y": "ý chính", "slots": {…} }, …]\`; mỗi cảnh có ô nội dung riêng theo §3.+- Giữ phần tử xuyên suốt §10 nêu (khung nền, nhãn kênh, băng chạy…) trôi liên tục qua mọi cảnh; chỉ phần nội dung đổi. Chuyển cảnh theo cách §10 mô tả (nếu §10 không nói thì quét/xoá ≤ 0,5s, cùng chất mẫu). CTA/thẻ kết chỉ ở cảnh cuối.+- Mỗi khung là HÀM THUẦN của t: tính cảnh hiện tại bằng \`i = cảnh chứa t\`, \`p = (t − from_i)/(to_i − from_i)\`; dựng lại trạng thái từ đầu theo t, KHÔNG cộng dồn biến qua các khung, không phụ thuộc khung trước (engine seek nhảy cóc).+- Hiệu năng: mỗi lần \`render(t)\` phải xong < 1 giây kể cả ở giây cuối. Không tạo phần tử DOM/mesh mới trong render(t) (dựng sẵn 1 lần, chỉ đổi thuộc tính), không vòng lặp tỉ lệ với t, ẩn (display:none / visible=false) phần tử của cảnh không hiện.+- Âm thanh: sfx khoảng 1 cái mỗi 1–1,5 giây theo đúng mốc chuyển động; nhạc nền phủ đủ ${D} giây.` : '';return `# Việc: dựng 1 cảnh video từ mẫu ${job.templateId} "${job.templateTitle}"Mày là AI dựng cảnh. Thư mục làm việc hiện tại là thư mục job \`${job.id}\`.@@ -39,9 +63,9 @@ ${job.content}- **Đổi chủ thể**: người dùng có thể đổi nhân vật/đồ vật của mẫu (cây → heo đất, mèo → chó…). Giữ nguyên chất liệu, bảng màu nền, bố cục, nhịp và SỐ trạng thái của chủ thể như mẫu. Màu riêng của chủ thể được đổi cho hợp, nhưng độ tương phản giữa các trạng thái (vd khoẻ/héo, đầy/rỗng) phải rõ như mẫu.- **Đúng kỹ thuật**: frontmatter \`technique\` của guidance có \`three\` hoặc \`webgl-shader\` thì PHẢI dựng phần đó bằng Three.js / shader WebGL thật (./lib/vendor/three.module.js), không hạ xuống 2D phẳng. Chỉ được đổi nếu ghi rõ lý do trong brief.json (trường \`technique_note\`).- Font: chỉ dùng font trong AUTHORING §4, theo bảng ánh xạ ở đó.-- **Âm thanh (bắt buộc)**: ghi kèm \`scene/audio.json\` theo AUTHORING §9 — thiếu file này video ra không tiếng. Chọn \`music.style\` hợp §9 "Âm thanh" của guidance; 6–15 sfx (cho 8 giây) đặt \`t\` đúng các mốc chuyển động mày vừa viết trong \`render(t)\`; \`voice\` chỉ khi frontmatter guidance có \`narration: true\`, mỗi câu ngắn, đọc xong trước mốc câu sau. Hệ thống tự trộn và ghép lúc render.--Chỉ được: đọc file, ghi/sửa file trong thư mục job này, chạy đúng 2 lệnh preview/render ở trên. Không cài gì, không gọi mạng.+- **Âm thanh (bắt buộc)**: ghi kèm \`scene/audio.json\` theo AUTHORING §9 — thiếu file này video ra không tiếng. Chọn \`music.style\` hợp §9 "Âm thanh" của guidance; 6–15 sfx cho 8 giây (video dài hơn thì tăng theo tỉ lệ) đặt \`t\` đúng các mốc chuyển động mày vừa viết trong \`render(t)\`; \`voice\` chỉ khi frontmatter guidance có \`narration: true\`, mỗi câu ngắn, đọc xong trước mốc câu sau. Hệ thống tự trộn và ghép lúc render.+${audioRule(job.audio)}+Chỉ được: đọc file, ghi/sửa file trong thư mục job này, chạy đúng 2 lệnh preview/render ở trên. Không cài gì, không gọi mạng.${longNote}---# GUIDANCE mẫu ${job.templateId}diff --git a/generator/rewrite.mjs b/generator/rewrite.mjsnew file mode 100644index 0000000..4d48995--- /dev/null+++ b/generator/rewrite.mjs@@ -0,0 +1,171 @@+// Viết lại nội dung người dùng thành kịch bản hợp với 1 mẫu + thời lượng.+// Dùng chung cho REST (POST /api/rewrite), CLI (node cli.mjs rewrite) và MCP (rewrite_script).+// Engine: api (Anthropic API, REWRITE_MODEL) → claude (Claude Code headless, không tool) → lỗi "chưa cấu hình AI".+// Không bao giờ ghi khoá API ra log/file.+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import Anthropic from '@anthropic-ai/sdk';+import { config, costOf } from './config.mjs';+import { findClaude } from './claude.mjs';+import { loadCatalog, guidancePath, hasGuidance, parseDuration, fmtDuration } from './jobs.mjs';++export const REWRITE_MAX_CHARS = 4000;+export const REWRITE_TIMEOUT_MS = 90_000;+export const REWRITE_ENGINES = ['auto', 'api', 'claude'];++/** Lấy frontmatter title + các mục §1, §2, §3, §10 của guidance (bỏ phần còn lại để prompt gọn). */+export function guidanceForRewrite(id) {+ const md = fs.readFileSync(guidancePath(id), 'utf8');+ const title = (/^title:\s*(.+)$/m.exec(md) || [])[1]?.trim() || '';+ const narration = /^narration:\s*true/m.test(md);+ const parts = md.split(/^(?=## )/m);+ const keep = parts.filter((p) => /^## (1|2|3|10)\.\s/.test(p)).map((p) => p.trim());+ return { title, narration, text: keep.join('\n\n') };+}++export function buildRewritePrompt({ templateId, content, durationS }) {+ const g = guidanceForRewrite(templateId);+ const D = durationS;+ const scenes = D > 12 ? Math.max(2, Math.round(D / 8)) : 1;+ const shape = scenes > 1+ ? `Video dài ${fmtDuration(D)} (${D} giây): chia kịch bản thành khoảng ${scenes} cảnh nối nhau, mỗi cảnh 6–10 giây, theo §10 của guidance. Mỗi cảnh ghi 1 dòng "Cảnh k (từ–đến giây):" rồi giá trị từng ô nội dung §3 cho cảnh đó. Phần tử xuyên suốt (tên kênh, nhãn…) ghi 1 lần ở đầu. CTA chỉ ở cảnh cuối.`+ : `Video ${D} giây = 1 màn. Ghi giá trị từng ô nội dung §3, mỗi ô 1 dòng "tên_ô: giá trị".`;+ return `Mày là biên kịch video dọc ngắn. Viết lại NỘI DUNG NGƯỜI DÙNG dưới đây thành kịch bản dùng được ngay cho mẫu ${templateId} "${g.title}".++## Luật (bắt buộc)+- Giữ đúng ý chính, MỌI con số, tên thương hiệu/kênh và CTA người dùng đưa. Không đổi số, không thêm số liệu thật (giá, lãi suất, thống kê) mà người dùng không đưa. Cần phép tính thì tính từ số người dùng đưa và ghi rõ "giả định" nếu phải tự đặt.+- Tên thương hiệu, sản phẩm, kênh người dùng nêu phải còn nguyên ở ít nhất 1 ô (ô quá ngắn thì đặt vào ô khác hợp hơn, không bỏ hẳn).+- Viết tiếng Việt đủ dấu, câu ngắn, hợp giọng mẫu.+- Bám §3 "Ô nội dung": đúng tên ô, đúng giới hạn ký tự/in hoa của từng ô; ô bắt buộc phải có. Nội dung thiếu ô bắt buộc thì tự đặt hợp lý theo chính nội dung đó và nói trong phần ghi chú.+- KHÔNG chép chữ ở cột "Ví dụ" của §3 hay ví dụ nào trong guidance: chúng chỉ để hiểu định dạng.+- Nội dung không hợp mẫu (xem §2 "Không hợp") thì vẫn viết bản gần nhất có thể và nói rõ trong ghi chú.+- ${shape}${g.narration ? '\n- Mẫu có lời đọc: thêm dòng "loi_doc:" cho từng cảnh, câu ngắn, đọc xong trong thời lượng cảnh.' : ''}++## Trả lời ĐÚNG dạng này, không thêm gì khác+<kich_ban>+(kịch bản: các dòng "tên_ô: giá trị" theo §3${scenes > 1 ? ', nhóm theo cảnh' : ''})+</kich_ban>+<ghi_chu>+(1–4 gạch đầu dòng ngắn, không xưng "tôi": chỗ đã rút gọn, ô tự đặt, giả định, chỗ nội dung không hợp mẫu)+</ghi_chu>++## Nội dung người dùng (nguyên văn)+"""+${content}+"""++## Guidance mẫu ${templateId} (§1–§3, §10)+${g.text}+`;+}++/** Tách <kich_ban> và <ghi_chu> từ câu trả lời. */+export function parseRewrite(text) {+ const tag = (n) => (new RegExp(`<${n}>\\s*([\\s\\S]*?)\\s*</${n}>`, 'i').exec(text) || [])[1];+ const script = tag('kich_ban') ?? (/<kich_ban>\s*([\s\S]*)$/i.exec(text) || [])[1]?.trim();+ return { script: script?.trim() || '', notes: tag('ghi_chu')?.trim() || '' };+}++function validate(input) {+ const templateId = String(input.templateId || '').padStart(3, '0');+ if (!/^\d{3}$/.test(templateId) || !loadCatalog().some((t) => t.id === templateId)) throw new Error(`Không có mẫu ${templateId}`);+ if (!hasGuidance(templateId)) throw new Error(`Mẫu ${templateId} chưa có guidance`);+ const content = String(input.content || '').trim();+ if (content.length < 10) throw new Error('Nội dung quá ngắn để viết lại (tối thiểu 10 ký tự)');+ if (content.length > REWRITE_MAX_CHARS) throw new Error(`Nội dung quá dài (tối đa ${REWRITE_MAX_CHARS} ký tự)`);+ return { templateId, content, durationS: parseDuration(input.durationS) };+}++/** auto → api (có ANTHROPIC_API_KEY) → claude (có lệnh claude) → null (chưa cấu hình). */+export function resolveRewriteEngine(engine = process.env.REWRITE_ENGINE || 'auto') {+ if (!REWRITE_ENGINES.includes(engine)) throw new Error(`engine không hợp lệ: ${engine} (auto|api|claude)`);+ if (engine === 'api') return config.hasApiKey() ? 'api' : null;+ if (engine === 'claude') return findClaude() ? 'claude' : null;+ if (config.hasApiKey()) return 'api';+ if (findClaude()) return 'claude';+ return null;+}++const NO_AI = 'Chưa cấu hình AI: đặt ANTHROPIC_API_KEY trong .env hoặc cài Claude Code (lệnh claude / CLAUDE_BIN). Xem README mục "Viết lại kịch bản".';++async function viaApi(prompt) {+ const model = process.env.REWRITE_MODEL || 'claude-haiku-5-5';+ const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, maxRetries: 1, timeout: REWRITE_TIMEOUT_MS });+ const msg = await client.messages.create({ model, max_tokens: 4000, messages: [{ role: 'user', content: prompt }] });+ if (msg.stop_reason === 'refusal') throw new Error(`${model} từ chối viết lại`);+ const text = (msg.content || []).filter((b) => b.type === 'text').map((b) => b.text).join('\n');+ const u = msg.usage || {};+ return { text, usage: { model, inputTokens: u.input_tokens || 0, outputTokens: u.output_tokens || 0, costUSD: +costOf(model, u).toFixed(5) } };+}++/** Claude Code headless: không tool nào (--tools ""), không MCP, không lưu phiên, prompt qua stdin, chỉ lấy text. */+function viaClaude(prompt) {+ const bin = findClaude();+ const args = [+ '-p', '--output-format', 'json',+ '--permission-mode', 'default',+ '--tools', '',+ '--setting-sources', 'project',+ '--strict-mcp-config',+ '--no-session-persistence',+ '--max-turns', '2',+ ];+ if (process.env.REWRITE_CLAUDE_MODEL) args.push('--model', process.env.REWRITE_CLAUDE_MODEL);+ // Thư mục trống riêng: không đọc CLAUDE.md / cấu hình dự án nào.+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'lumreels-rewrite-'));+ return new Promise((resolve, reject) => {+ const p = spawn(bin, args, { cwd, windowsHide: true, env: (({ ANTHROPIC_API_KEY, ...e }) => e)(process.env) });+ let out = ''; let err = '';+ const timer = setTimeout(() => { p.kill(); reject(new Error(`Claude Code quá ${REWRITE_TIMEOUT_MS / 1000}s, đã dừng`)); }, REWRITE_TIMEOUT_MS);+ p.stdout.on('data', (d) => { out += d; });+ p.stderr.on('data', (d) => { err += d; });+ p.on('error', (e) => { clearTimeout(timer); reject(new Error('spawn claude lỗi: ' + e.message)); });+ p.on('close', (code) => {+ clearTimeout(timer);+ fs.rm(cwd, { recursive: true, force: true }, () => {});+ let r = null;+ try { r = JSON.parse(out.trim().split(/\r?\n/).pop()); } catch { /* không phải JSON */ }+ if (code !== 0 || !r || r.is_error) {+ const why = (r?.result || err || out || '').toString().trim().slice(-600);+ return reject(new Error(`claude thoát mã ${code}: ${why || 'không có thông báo'}`));+ }+ const u = r.usage || {};+ resolve({ text: String(r.result || ''), usage: {+ model: 'claude-code', inputTokens: (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0),+ outputTokens: u.output_tokens || 0, costUSD: typeof r.total_cost_usd === 'number' ? +r.total_cost_usd.toFixed(5) : null,+ } });+ });+ p.stdin.end(prompt);+ });+}++/**+ * Viết lại kịch bản. input = {templateId, content, durationS?, engine?: auto|api|claude}+ * Trả {script, notes, engine, usage, templateId, durationS}. Lỗi → throw Error (thông báo tiếng Việt).+ * auto: api lỗi xác thực (401/403) mà máy có Claude Code → thử claude, ghi lại trong fallbackFrom.+ */+export async function rewriteScript(input) {+ const v = validate(input);+ const want = input.engine || process.env.REWRITE_ENGINE || 'auto';+ const engine = resolveRewriteEngine(want);+ if (!engine) throw new Error(NO_AI);+ const prompt = buildRewritePrompt(v);+ let used = engine; let fallbackFrom = null; let r;+ try {+ r = engine === 'api' ? await viaApi(prompt) : await viaClaude(prompt);+ } catch (e) {+ const auth = e instanceof Anthropic.APIError && (e.status === 401 || e.status === 403);+ if (engine === 'api' && want === 'auto' && auth && findClaude()) {+ fallbackFrom = `api lỗi ${e.status} (khoá ANTHROPIC_API_KEY không hợp lệ)`;+ used = 'claude';+ r = await viaClaude(prompt);+ } else if (e instanceof Anthropic.APIError) {+ throw new Error(`API ${e.status ?? ''} ${e.name}: ${String(e.message).slice(0, 300)}`);+ } else throw e;+ }+ const { script, notes } = parseRewrite(r.text);+ if (!script) throw new Error('AI không trả kịch bản đúng dạng <kich_ban>…</kich_ban>. Bấm lại thử.');+ return { script, notes, engine: used, ...(fallbackFrom ? { fallbackFrom } : {}), usage: r.usage, templateId: v.templateId, durationS: v.durationS };+}diff --git a/mcp/server.mjs b/mcp/server.mjsindex f279d74..1da5308 100644--- a/mcp/server.mjs+++ b/mcp/server.mjs@@ -11,9 +11,19 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';import { z } from 'zod';import {- ROOT, loadCatalog, templateName, hasGuidance, guidancePath, createJob, runJob, renderJob, previewJob, submitScene,+ ROOT, MAX_DURATION_S, loadCatalog, templateName, hasGuidance, guidancePath, createJob, runJob, renderJob, previewJob, submitScene,readJob, listJobs, readLog, jobPaths, jobDir, resolveMode, jobActive,} from '../generator/jobs.mjs';+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';++const audioSchema = z.object({+ music: z.string().optional().describe(`auto | none | ${MUSIC_STYLES.join(' | ')}`),+ voice: z.string().optional().describe('auto | none | tên giọng (xem set_audio / audio-options), vd "Hải Đăng", "Trúc Ly", "edge:vi-VN-HoaiMyNeural"'),+ sfx: z.boolean().optional(),+});const AUTHORING = path.join(ROOT, 'engine', 'AUTHORING.md');const text = (t) => ({ type: 'text', text: t });@@ -26,7 +36,7 @@ function jobSummary(j) {return {jobId: j.id, status: j.status, templateId: j.templateId, templateTitle: templateName(j.templateId) || j.templateTitle, mode: j.mode, engine: j.engine,runAt: j.runAt || null, error: j.error || null, content: j.content.slice(0, 200), createdAt: j.createdAt, updatedAt: j.updatedAt,- output: j.output || null, usage: j.usage ? { costUSD: j.usage.costUSD, inputTokens: j.usage.inputTokens, outputTokens: j.usage.outputTokens } : null,+ output: j.output || null, audio: j.audio || null, audioStatus: j.audioStatus || null, audioError: j.audioError || null, usage: j.usage ? { costUSD: j.usage.costUSD, inputTokens: j.usage.inputTokens, outputTokens: j.usage.outputTokens } : null,files: { mp4: fs.existsSync(p.mp4) ? p.mp4 : null, preview: fs.existsSync(p.preview) ? p.preview : null, scene: p.sceneHtml },};}@@ -84,13 +94,15 @@ server.registerTool('create_video', {templateId: z.string().regex(/^\d{1,3}$/),content: z.string().min(5).max(4000),mode: z.enum(['auto', 'agent']).default('auto'),- durationS: z.number().min(3).max(60).optional(),+ durationS: z.union([z.number().min(3).max(MAX_DURATION_S), z.string().regex(/^\s*\d{1,4}\s*s?\s*$|^\s*\d{1,2}:[0-5]\d\s*$/)]).optional()+ .describe('Thời lượng: 3 giây → 10 phút; số giây (90) hoặc "phút:giây" ("1:30"). Mặc định 8. > 60s: chia nhiều cảnh, render lâu (8s video ≈ 20–60s render) và tốn token hơn.'),runAt: z.string().optional(),+ audio: audioSchema.optional().describe('Âm thanh. Mặc định {music:"auto", voice:"auto", sfx:true}: AI chọn nhạc/tiếng động theo mẫu, chỉ đọc lời khi mẫu có narration.'),},-}, async ({ templateId, content, mode, durationS, runAt }) => {+}, async ({ templateId, content, mode, durationS, runAt, audio }) => {let job;try {- job = createJob({ templateId, content, durationS, mode: mode === 'agent' ? 'manual' : 'auto', runAt, source: 'mcp' });+ job = createJob({ templateId, content, durationS, mode: mode === 'agent' ? 'manual' : 'auto', runAt, source: 'mcp', audio });} catch (e) { return fail(e.message); }const p = jobPaths(job.id);if (job.status === 'scheduled') {@@ -114,12 +126,28 @@ server.registerTool('create_video', {return { content: [json({ jobId: job.id, status: 'queued', engine: resolveMode('auto'), note: 'Đang tự sinh cảnh + render (1–5 phút) ở tiến trình nền. Gọi get_job để xem trạng thái.' })] };});+server.registerTool('rewrite_script', {+ title: 'Viết lại kịch bản',+ description: 'Viết lại nội dung thô thành kịch bản hợp mẫu (theo §1–§3 và §10 của guidance: ô nội dung, giới hạn ký tự) và thời lượng. Giữ đúng ý, số liệu, thương hiệu, CTA; không bịa số liệu thật. Trả {script, notes, engine, usage}; dùng script làm content cho create_video. Mất 20–90 giây. Engine: Claude API (REWRITE_MODEL) → Claude Code headless.',+ inputSchema: {+ templateId: z.string().regex(/^\d{1,3}$/),+ content: z.string().min(10).max(4000),+ durationS: z.union([z.number().min(3).max(MAX_DURATION_S), z.string().max(8)]).optional(),+ },+}, async ({ templateId, content, durationS }) => {+ try {+ return { content: [json(await rewriteScript({ templateId, content, durationS }))] };+ } catch (e) { return fail(e.message); }+});+server.registerTool('submit_scene', {title: 'Nộp cảnh HTML',- description: 'Ghi jobs/<jobId>/scene/index.html (chỉ trong thư mục job). Kiểm tĩnh như engine (không gọi mạng, không Math.random/Date.now, đủ VideoScene.define…). Lỗi → giữ bản cũ và trả danh sách lỗi.',- inputSchema: { jobId: z.string().regex(/^[\w-]{1,80}$/), html: z.string().min(50).max(2_000_000), brief: z.union([z.string(), z.record(z.string(), z.any())]).optional() },-}, async ({ jobId, html, brief }) => {+ description: 'Ghi jobs/<jobId>/scene/index.html (chỉ trong thư mục job) và scene/audio.json (nhạc + tiếng động + lời, AUTHORING §9; thiếu thì video không tiếng). Kiểm tĩnh như engine (không gọi mạng, không Math.random/Date.now, đủ VideoScene.define…). Lỗi → giữ bản cũ và trả danh sách lỗi.',+ inputSchema: { jobId: z.string().regex(/^[\w-]{1,80}$/), html: z.string().min(50).max(2_000_000), brief: z.union([z.string(), z.record(z.string(), z.any())]).optional(),+ audio: z.union([z.string(), z.record(z.string(), z.any())]).optional().describe('Nội dung scene/audio.json (AUTHORING §9)') },+}, async ({ jobId, html, brief, audio }) => {try {+ if (audio !== undefined) await saveAudioSpec(jobId, audio);const r = submitScene(jobId, html, brief);return r.ok ? { content: [json({ ok: true, warnings: r.warnings, meta: r.meta, next: 'Gọi preview_job để xem lưới 16 khung.' })] }: { isError: true, content: [json({ ok: false, errors: r.errors, warnings: r.warnings })] };@@ -157,7 +185,7 @@ server.registerTool('preview_job', {server.registerTool('render_job', {title: 'Render MP4',- description: 'Preview + render MP4 1080×1920 30fps (khoảng 30–60 giây), rồi chép ra OUTPUT_DIR nếu có. Chờ tối đa ~110 giây; lâu hơn thì trả trạng thái và mày gọi get_job.',+ description: 'Preview + render MP4 1080×1920 30fps (video 8 giây mất khoảng 20–60 giây; video dài tăng theo tỉ lệ), rồi chép ra OUTPUT_DIR nếu có. Chờ tối đa ~110 giây; lâu hơn thì trả trạng thái và mày gọi get_job.',inputSchema: { jobId: z.string().regex(/^[\w-]{1,80}$/) },}, async ({ jobId }) => {try {@@ -175,6 +203,28 @@ server.registerTool('render_job', {} catch (e) { return fail(e.message); }});+server.registerTool('set_audio', {+ title: 'Đổi tiếng video đã dựng',+ description: [+ 'Trộn tiếng mới (nhạc / giọng đọc / tiếng động) và ghép vào hình ĐÃ DỰNG, không dựng lại hình. out.mp4 thành bản mới nhất, bản cũ giữ ở versions/out-<n>.mp4.',+ 'Trường bỏ trống = giữ như hiện tại. Chọn giọng mà video chưa có lời đọc → AI viết 1–3 câu ngắn. Gọi không tham số (chỉ jobId) để xem lựa chọn + các bản đang có.',+ 'VieNeu (giọng trên máy) đọc mất 1–10 phút tuỳ máy; chờ tối đa ~100 giây, lâu hơn thì gọi get_job.',+ ].join(' '),+ inputSchema: { jobId: z.string().regex(/^[\w-]{1,80}$/), music: audioSchema.shape.music, voice: audioSchema.shape.voice, sfx: audioSchema.shape.sfx },+}, async ({ jobId, music, voice, sfx }) => {+ try {+ if (!readJob(jobId)) return fail('Không thấy job ' + jobId);+ if (music === undefined && voice === undefined && sfx === undefined) {+ const o = audioOptions();+ return { content: [json({ current: readJob(jobId).audio || null, versions: listVersions(jobId), music: o.music.map((m) => m.id), voices: o.voices.map((v) => v.id), hint: o.hint })] };+ }+ const run = reAudio(jobId, { music, voice, sfx });+ const r = await Promise.race([run, new Promise((res) => setTimeout(() => res(null), 100_000))]);+ if (!r) { run.catch(() => {}); return { content: [json({ pending: true, note: 'Đang trộn tiếng (VieNeu đọc lâu). Gọi get_job sau 1–2 phút; xong khi audioStatus = "done".' })] }; }+ return { content: [json({ ok: true, file: r.file, version: r.version, lufs: +r.lufs.toFixed(1), warnings: r.warnings, voice: r.voice, versions: listVersions(jobId) })] };+ } catch (e) { return fail(e.message); }+});+server.registerTool('get_job', {title: 'Trạng thái job',description: 'Trạng thái, lỗi, đường dẫn MP4/preview, chi phí API và 30 dòng log cuối của 1 job.',diff --git a/scripts/docs-shots.mjs b/scripts/docs-shots.mjsindex b9ccea4..bbc56b7 100644--- a/scripts/docs-shots.mjs+++ b/scripts/docs-shots.mjs@@ -35,9 +35,21 @@ await page.evaluate(() => {el.dispatchEvent(new Event('input', { bubbles: true }));document.querySelector('#mode').dispatchEvent(new Event('change', { bubbles: true }));});+// thời lượng tự gõ: "1:30" → 90 giây, hiện cảnh báo video dài+await page.click('#duration', { clickCount: 3 });+await page.type('#duration', '1:30');const form = await page.$('.compose .sticky');await form.screenshot({ path: path.join(IMG, 'ui-form-hen-gio.png') });+// 2b. Viết lại kịch bản (gọi AI thật, 20–90 giây): chỉ chạy khi DOCS_REWRITE=1+if (process.env.DOCS_REWRITE === '1') {+ await page.evaluate(() => { document.querySelector('#runAt').value = ''; document.querySelector('#runAt').dispatchEvent(new Event('input', { bubbles: true })); });+ await page.click('.pre[data-dur="15"]');+ await page.click('#rewrite');+ await page.waitForFunction(() => { const b = document.querySelector('#rwBox'); return !b.hidden && !b.classList.contains('load'); }, { timeout: 110000 });+ await form.screenshot({ path: path.join(IMG, 'ui-viet-lai.png') });+}+// 3. Danh sách jobawait page.evaluate(() => window.scrollTo(0, 0));await page.waitForSelector('.job');diff --git a/scripts/make-thumbs.mjs b/scripts/make-thumbs.mjsnew file mode 100644index 0000000..079e1a9--- /dev/null+++ b/scripts/make-thumbs.mjs@@ -0,0 +1,44 @@+#!/usr/bin/env node+// Cắt 1 khung keyframe làm ảnh đại diện mẫu trong lưới UI: templates/thumbs/<id>.webp (360×640, có trong repo).+// node scripts/make-thumbs.mjs <templateId> <jobId | file.mp4> [--at 5.5] [--force] [-o file.webp]+// vd: node scripts/make-thumbs.mjs 106 261128071500-106-ab12 (lấy jobs/<jobId>/out.mp4)+// Mặc định cắt ở giây 5,5 (thường là lúc cảnh đã đủ phần tử); video ngắn hơn thì lấy gần cuối.+// Cần ffmpeg/ffprobe trong PATH. Đã có ảnh thì không ghi đè, trừ khi --force.+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { parseArgs, probe, run } from '../engine/lib.mjs';++const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));+const OUT_DIR = path.join(ROOT, 'templates', 'thumbs');+const { pos, opt } = parseArgs(process.argv.slice(2));+const [idArg, src] = pos;+if (!idArg || !src) {+ console.log('Dùng: node scripts/make-thumbs.mjs <templateId> <jobId | file.mp4> [--at 5.5] [--force]');+ process.exit(2);+}+const id = String(idArg).padStart(3, '0');+if (!/^\d{3}$/.test(id)) { console.error('templateId phải là 1–3 chữ số'); process.exit(2); }+const catalog = JSON.parse(fs.readFileSync(path.join(ROOT, 'templates', 'catalog.json'), 'utf8'));+if (!catalog.some((t) => t.id === id)) console.warn(`Cảnh báo: mẫu ${id} chưa có trong catalog.json (chạy node scripts/sync-catalog.mjs)`);++let mp4 = src;+if (!/\.mp4$/i.test(src)) {+ if (!/^[\w-]{1,80}$/.test(src)) { console.error('jobId không hợp lệ'); process.exit(2); }+ mp4 = path.join(ROOT, 'jobs', src, 'out.mp4');+}+if (!fs.existsSync(mp4)) { console.error(`Không thấy ${mp4} (render job trước: node cli.mjs render <jobId>)`); process.exit(1); }++const out = typeof opt.o === 'string' ? path.resolve(opt.o) : path.join(OUT_DIR, `${id}.webp`);+if (fs.existsSync(out) && !opt.force) { console.error(`${out} đã có. Thêm --force để ghi đè.`); process.exit(1); }++const dur = Number((await probe(mp4))?.format?.duration) || 0;+let at = opt.at === undefined || opt.at === true ? 5.5 : Number(String(opt.at).replace(',', '.'));+if (!Number.isFinite(at) || at < 0) { console.error('--at phải là số giây'); process.exit(2); }+if (dur && at > dur - 0.1) at = Math.max(0, dur - 0.5);++fs.mkdirSync(path.dirname(out), { recursive: true });+const r = await run('ffmpeg', ['-v', 'error', '-y', '-ss', String(at), '-i', mp4, '-frames:v', '1',+ '-vf', 'scale=360:640:force_original_aspect_ratio=increase:flags=lanczos,crop=360:640', '-c:v', 'libwebp', '-quality', '80', out]);+if (r.code !== 0 || !fs.existsSync(out)) { console.error('ffmpeg lỗi:\n' + r.out); process.exit(1); }+console.log(`${path.relative(ROOT, out)} (${Math.round(fs.statSync(out).size / 1024)} KB, khung ${at}s của ${path.relative(ROOT, mp4)})`);diff --git a/scripts/sync-catalog.mjs b/scripts/sync-catalog.mjsindex cf9a848..85ba05f 100644--- a/scripts/sync-catalog.mjs+++ b/scripts/sync-catalog.mjs@@ -35,3 +35,6 @@ const items = fs.readdirSync(G).filter((f) => /^\d{3}\.md$/.test(f)).sort().map(});fs.writeFileSync(OUT, JSON.stringify(items, null, 1) + '\n');console.log(`catalog.json: ${items.length} mẫu`);+// Mẫu chưa có ảnh đại diện trong repo (templates/thumbs/<id>.webp) → lưới UI chỉ hiện poster SVG trên máy vừa clone.+const noThumb = items.filter((t) => !fs.existsSync(path.join(ROOT, 'templates', 'thumbs', `${t.id}.webp`))).map((t) => t.id);+if (noThumb.length) console.log(`chưa có ảnh đại diện: ${noThumb.join(', ')} → dựng thử 1 job rồi: node scripts/make-thumbs.mjs <id> <jobId>`);diff --git a/server/public/app.js b/server/public/app.jsindex 9913895..230acba 100644--- a/server/public/app.js+++ b/server/public/app.js@@ -13,6 +13,26 @@// datetime-local trả giờ máy không múi giờ → đổi sang ISO có múi giờ để server hiểu đúng.const runAtValue = () => { const v = $('#runAt').value; return v ? new Date(v).toISOString() : undefined; };+ // Thời lượng: số giây (90, 90s) hoặc phút:giây (1:30). Cùng luật với generator/jobs.mjs parseDuration.+ const DUR_MIN = 3, DUR_MAX = 600;+ function parseDur(v) {+ const t = String(v ?? '').trim().toLowerCase().replace(/\s+/g, '');+ if (!t) return { error: 'Nhập thời lượng, vd 8 hoặc 1:30' };+ let m, s;+ if ((m = /^(\d{1,4})(?:s|giây|giay)?$/.exec(t))) s = Number(m[1]);+ else if ((m = /^(\d{1,2}):([0-5]\d)$/.exec(t))) s = Number(m[1]) * 60 + Number(m[2]);+ else if ((m = /^(\d{1,2})(?:m|p|phút|phut)$/.exec(t))) s = Number(m[1]) * 60;+ else return { error: 'Gõ số giây (90) hoặc phút:giây (1:30)' };+ if (s < DUR_MIN) return { error: 'Ngắn nhất 3 giây' };+ if (s > DUR_MAX) return { error: 'Dài nhất 10 phút (10:00)' };+ return { s };+ }+ const fmtDur = (s) => (s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`);+ // Khoảng thời gian ước tính: "40–120 giây", "4–11 phút", "2–5 giờ"… (đơn vị theo đầu trên)+ const fmtRange = (a, b) => (b < 120 ? `${Math.round(a)}–${Math.round(b)} giây`+ : b < 7200 ? `${Math.max(1, Math.round(a / 60))}–${Math.round(b / 60)} phút` : `${(a / 3600).toFixed(1).replace('.', ',')}–${(b / 3600).toFixed(1).replace('.', ',')} giờ`);+ const durS = () => parseDur($('#duration').value).s;+let templates = [];let selected = null;let cat = '';@@ -81,11 +101,87 @@function updateGo() {const n = $('#content').value.length;$('#chars').textContent = n;- const ok = !!selected && $('#content').value.trim().length >= 10;+ const enough = $('#content').value.trim().length >= 10;+ const dur = !!durS();+ const ok = !!selected && enough && dur;$('#go').disabled = !ok;- $('#go').title = !selected ? 'Chọn 1 mẫu trước' : ok ? '' : 'Nội dung tối thiểu 10 ký tự';+ $('#go').title = !selected ? 'Chọn 1 mẫu trước' : !enough ? 'Nội dung tối thiểu 10 ký tự' : !dur ? 'Thời lượng chưa đúng' : '';+ const rw = $('#rewrite');+ rw.disabled = !ok || rwBusy;+ rw.title = rwBusy ? 'Đang viết lại…' : !selected ? 'Chọn 1 mẫu trước' : !enough ? 'Gõ nội dung trước (tối thiểu 10 ký tự)' : !dur ? 'Thời lượng chưa đúng' : '';+ }++ // ---------- thời lượng ----------+ function updateDur() {+ const r = parseDur($('#duration').value);+ $('#duration').setAttribute('aria-invalid', r.error ? 'true' : 'false');+ document.querySelectorAll('.pre').forEach((b) => b.classList.toggle('on', Number(b.dataset.dur) === r.s));+ const hint = $('#durHint');+ hint.classList.toggle('bad', !!r.error);+ hint.textContent = r.error ? r.error + '.' : r.s >= 60 ? `= ${r.s} giây (${fmtDur(r.s)}).` : `= ${r.s} giây. Gõ số giây (90) hoặc phút:giây (1:30).`;+ const warn = $('#durWarn');+ if (r.s > 60) {+ warn.hidden = false;+ warn.textContent = `Video dài ${fmtDur(r.s)}: render ước tính ${fmtRange(r.s / 8 * 20, r.s / 8 * 60)} (đo thực tế: video 8 giây mất 20–60 giây render), chưa tính lúc AI viết cảnh. `+ + `AI phải viết khoảng ${Math.round(r.s / 8)} cảnh nối nhau nên tốn token và chi phí hơn hẳn video 8 giây.`;+ } else warn.hidden = true;+ updateGo();}+ // ---------- viết lại kịch bản ----------+ let rwBusy = false;+ let rwResult = null; // bản AI vừa viết, chưa dùng+ let rwUndo = null; // nội dung trước khi bấm "Dùng bản này"+ function rwShow(cls, html) { const b = $('#rwBox'); b.className = 'rw ' + cls; b.innerHTML = html; b.hidden = !html; }+ async function rewrite() {+ if (rwBusy || !selected) return;+ const dur = durS();+ rwBusy = true; rwResult = null;+ const btn = $('#rewrite');+ btn.classList.add('busy'); btn.querySelector('span').textContent = 'Đang viết lại';+ updateGo();+ rwShow('load', `Đang viết lại cho mẫu ${esc(selected.id)} · ${fmtDur(dur)}… (thường 20–60 giây)`);+ const ctl = new AbortController();+ const timer = setTimeout(() => ctl.abort(), 100_000);+ try {+ const r = await fetch('/api/rewrite', {+ method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: ctl.signal,+ body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: dur }),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error || `Lỗi ${r.status}`);+ rwResult = j;+ const eng = j.engine === 'api' ? 'Claude API' : 'Claude Code';+ const cost = j.usage?.costUSD != null ? ` · ≈ $${Number(j.usage.costUSD).toFixed(3)}` : '';+ rwShow('', `<div class="rw-h"><span>Bản viết lại · mẫu ${esc(j.templateId)} · ${fmtDur(j.durationS)}</span><span class="eng">${eng}${cost}</span></div>+ <pre id="rwScript">${esc(j.script)}</pre>+ ${j.notes ? `<div class="rw-n">${esc(j.notes)}</div>` : ''}+ ${j.fallbackFrom ? `<div class="rw-n">Đã chuyển sang Claude Code vì ${esc(j.fallbackFrom)}.</div>` : ''}+ <div class="rw-a"><button type="button" class="use" data-rw="use">Dùng bản này</button><button type="button" data-rw="drop">Bỏ</button></div>`);+ } catch (e) {+ rwShow('err-box', esc(e.name === 'AbortError' ? 'Quá 100 giây chưa xong, đã dừng chờ. Bấm lại thử.' : e.message));+ } finally {+ clearTimeout(timer);+ rwBusy = false;+ btn.classList.remove('busy'); btn.querySelector('span').textContent = 'Viết lại kịch bản';+ updateGo();+ }+ }+ $('#rwBox').addEventListener('click', (e) => {+ const a = e.target.closest('[data-rw]')?.dataset.rw;+ if (!a) return;+ if (a === 'use' && rwResult) {+ rwUndo = $('#content').value;+ $('#content').value = rwResult.script.slice(0, 4000);+ rwResult = null;+ rwShow('', '<div class="rw-h"><span>Đã thay nội dung bằng bản viết lại.</span></div><div class="rw-a"><button type="button" data-rw="undo">Hoàn tác</button><button type="button" data-rw="close">Đóng</button></div>');+ } else if (a === 'undo' && rwUndo !== null) {+ $('#content').value = rwUndo; rwUndo = null;+ rwShow('', '');+ } else { rwResult = null; rwShow('', ''); }+ updateGo();+ });+async function submit() {$('#formErr').textContent = '';const btn = $('#go');@@ -93,7 +189,7 @@try {const r = await fetch('/api/jobs', {method: 'POST', headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: Number($('#duration').value), mode: $('#mode').value, runAt: runAtValue() }),+ body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: durS(), mode: $('#mode').value, runAt: runAtValue(), audio: window.LumAudio?.value() }),});const j = await r.json();if (!r.ok) throw new Error(j.error || 'Tạo job lỗi');@@ -166,7 +262,7 @@<div><div class="head"><span class="st ${j.status} ${running ? 'run' : ''}">${STATUS[j.status] || j.status}</span><span class="tt">Mẫu ${j.templateId} · ${esc(j.templateTitle || '')}</span></div>- <div class="jid">${j.id} · ${j.durationS}s · ${MODE_LABEL[j.engine || j.mode] || j.mode} ${out ? '· ' + out : ''}</div>+ <div class="jid">${j.id} · ${fmtDur(j.durationS)} · ${MODE_LABEL[j.engine || j.mode] || j.mode} ${out ? '· ' + out : ''}</div>${j.status === 'scheduled' ? `<div class="cost">Hẹn dựng lúc ${fmtTime(j.runAt)}</div>` : ''}${j.usage ? `<div class="cost">API: ${(j.usage.inputTokens / 1000).toFixed(1)}k vào · ${(j.usage.outputTokens / 1000).toFixed(1)}k ra · ≈ $${j.usage.costUSD.toFixed(3)}</div>` : ''}${j.output?.exported ? `<div class="cost">Đã chép ra: ${esc(j.output.exported)}</div>` : ''}@@ -209,6 +305,9 @@renderGrid();}));$('#content').addEventListener('input', updateGo);+ $('#rewrite').addEventListener('click', rewrite);+ $('#duration').addEventListener('input', updateDur);+ document.querySelectorAll('.pre').forEach((b) => b.addEventListener('click', () => { $('#duration').value = b.dataset.dur; updateDur(); }));$('#go').addEventListener('click', submit);$('#vClose').addEventListener('click', closeViewer);$('#viewer').addEventListener('cancel', (e) => { e.preventDefault(); closeViewer(); });@@ -242,6 +341,7 @@if (!c.apiAvailable) $('#mode').querySelector('[value=api]').disabled = true;modeHint();}).catch(() => {});+ updateDur();loadTemplates();loadJobs();})();diff --git a/server/public/audio-panel.css b/server/public/audio-panel.cssnew file mode 100644index 0000000..6a497fb--- /dev/null+++ b/server/public/audio-panel.css@@ -0,0 +1,34 @@+/* Khối "Âm thanh" (audio-panel.js). Dùng token màu của style.css. */+.ap { margin-top: 16px; padding: 16px; border: 1px solid var(--line); border-radius: var(--r); background: var(--panel); }+.ap-title { font: 700 18px/1.2 var(--cond); text-transform: uppercase; letter-spacing: .03em; margin-bottom: 4px; }+.ap-row { display: flex; gap: 8px; align-items: center; }+.ap-row select { flex: 1; min-width: 0; min-height: 44px; background: var(--panel-2); border: 1px solid var(--line); border-radius: 10px; padding: 0 10px; }+.ap-play { flex: none; width: 44px; height: 44px; display: grid; place-items: center; border-radius: 50%; border: 1px solid var(--line); background: var(--panel-2); color: var(--accent); cursor: pointer; transition: background .15s, transform .1s; }+.ap-play:hover { background: var(--line); }+.ap-play:active { transform: scale(.94); }+.ap-play svg { width: 18px; height: 18px; fill: currentColor; }+.ap-play[data-state="play"] { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }+.ap-spin { width: 16px; height: 16px; border-radius: 50%; border: 2px solid var(--ink-3); border-top-color: var(--accent); animation: ap-rot .8s linear infinite; }+@keyframes ap-rot { to { transform: rotate(360deg); } }+@media (prefers-reduced-motion: reduce) { .ap-spin { animation-duration: 2.4s; } }++.ap-switch { display: flex; align-items: center; gap: 10px; min-height: 44px; margin-top: 8px; cursor: pointer; color: var(--ink-2); }+.ap-switch input { position: absolute; opacity: 0; width: 1px; height: 1px; }+.ap-knob { position: relative; flex: none; width: 44px; height: 26px; border-radius: 999px; background: var(--panel-2); border: 1px solid var(--line); transition: background .15s; }+.ap-knob::after { content: ""; position: absolute; top: 3px; left: 3px; width: 18px; height: 18px; border-radius: 50%; background: var(--ink-3); transition: transform .15s, background .15s; }+.ap-switch input:checked + .ap-knob { background: var(--accent); border-color: var(--accent); }+.ap-switch input:checked + .ap-knob::after { transform: translateX(18px); background: var(--accent-ink); }+.ap-switch input:focus-visible + .ap-knob { outline: 2px solid var(--accent); outline-offset: 2px; }+.ap-hint { color: var(--warn); }+.ap-note:empty { display: none; }++.ap-job { margin-top: 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); }+.ap-job > summary { min-height: 44px; display: flex; align-items: center; padding: 0 14px; cursor: pointer; color: var(--ink-2); font-weight: 600; }+.ap-job .ap-body { padding: 0 14px 14px; }+.ap-go { margin-top: 12px; min-height: 44px; width: 100%; border: 0; border-radius: 10px; background: var(--accent); color: var(--accent-ink); font-weight: 700; cursor: pointer; }+.ap-go:disabled { opacity: .6; cursor: progress; }+.ap-sub { margin-top: 12px; color: var(--ink-3); font-size: 14px; }+.ap-ver { display: flex; gap: 8px; align-items: center; padding: 6px 0; border-top: 1px solid var(--line); font-size: 14px; color: var(--ink-2); }+.ap-ver span { flex: 1; min-width: 0; }+.ap-ver.cur span { color: var(--ink); font-weight: 600; }+.ap-ver .mini { min-height: 36px; padding: 0 12px; display: inline-flex; align-items: center; border-radius: 8px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink); text-decoration: none; cursor: pointer; }diff --git a/server/public/audio-panel.js b/server/public/audio-panel.jsnew file mode 100644index 0000000..7bc3d24--- /dev/null+++ b/server/public/audio-panel.js@@ -0,0 +1,168 @@+// Khối "Âm thanh": (1) trong form dựng — chọn nhạc nền, giọng đọc, tiếng động (có nút nghe thử);+// (2) trong mỗi video đã dựng — đổi nhạc/giọng/tiếng động rồi trộn bản tiếng mới (không dựng lại hình), xem/tải các bản.+// Tự chứa: tự nạp CSS, tự gắn vào #audioPanel và các thẻ .job trong #jobs. app.js chỉ đọc window.LumAudio.value().+(() => {+ const $ = (s, el = document) => el.querySelector(s);+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+ const css = document.createElement('link');+ css.rel = 'stylesheet'; css.href = '/audio-panel.css';+ document.head.appendChild(css);++ let opts = null;+ const optsP = fetch('/api/audio/options').then((r) => r.json()).then((o) => (opts = o)).catch(() => null);++ // ---------- nghe thử (1 trình phát chung) ----------+ const player = new Audio();+ let playingBtn = null;+ const ICON_PLAY = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4v16l13-8z"/></svg>';+ const ICON_STOP = '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>';+ function setBtn(btn, state) {+ if (!btn) return;+ btn.dataset.state = state;+ btn.innerHTML = state === 'play' ? ICON_STOP : state === 'load' ? '<span class="ap-spin" aria-hidden="true"></span>' : ICON_PLAY;+ btn.setAttribute('aria-label', state === 'play' ? 'Dừng nghe thử' : state === 'load' ? 'Đang tạo bản nghe thử' : btn.dataset.label);+ }+ player.addEventListener('ended', () => { setBtn(playingBtn, 'idle'); playingBtn = null; });+ async function preview(btn, url, note) {+ if (playingBtn === btn) { player.pause(); setBtn(btn, 'idle'); playingBtn = null; return; }+ if (playingBtn) { player.pause(); setBtn(playingBtn, 'idle'); }+ playingBtn = btn; setBtn(btn, 'load');+ if (note) note.textContent = url.includes('voice=') ? 'Đang tạo giọng mẫu… (VieNeu lần đầu có thể mất vài phút)' : '';+ try {+ const r = await fetch(url);+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'không tạo được bản nghe thử');+ const blob = await r.blob();+ if (playingBtn !== btn) return;+ player.src = URL.createObjectURL(blob);+ await player.play();+ setBtn(btn, 'play');+ if (note) note.textContent = '';+ } catch (e) {+ setBtn(btn, 'idle'); playingBtn = null;+ if (note) note.textContent = 'Nghe thử lỗi: ' + e.message;+ }+ }++ // ---------- 3 điều khiển dùng chung ----------+ let uid = 0;+ function controlsHtml(cur = {}, { keepLabel = false } = {}) {+ const id = 'ap' + (++uid);+ const keep = keepLabel ? '<option value="">Giữ như hiện tại</option>' : '';+ const music = (opts?.music || [{ id: 'auto', name: 'Tự chọn theo mẫu' }]).map((m) =>+ `<option value="${esc(m.id)}" ${cur.music === m.id ? 'selected' : ''}>${esc(m.id === 'auto' || m.id === 'none' ? m.name : m.id + ' — ' + (m.desc || ''))}</option>`).join('');+ const voices = (opts?.voices || [{ id: 'auto', name: 'Theo mẫu' }]).map((v) =>+ `<option value="${esc(v.id)}" ${cur.voice === v.id ? 'selected' : ''}>${esc(v.engine ? `${v.name} · ${v.gender}, ${v.region} · ${v.style}` : v.name)}</option>`).join('');+ return `+ <label class="field" for="${id}m">Nhạc nền</label>+ <div class="ap-row"><select id="${id}m" data-ap="music">${keep}${music}</select>+ <button type="button" class="ap-play" data-prev="music" data-label="Nghe thử nhạc nền" aria-label="Nghe thử nhạc nền">${ICON_PLAY}</button></div>+ <label class="field" for="${id}v">Giọng đọc</label>+ <div class="ap-row"><select id="${id}v" data-ap="voice">${keep}${voices}</select>+ <button type="button" class="ap-play" data-prev="voice" data-label="Nghe thử giọng đọc" aria-label="Nghe thử giọng đọc">${ICON_PLAY}</button></div>+ <label class="ap-switch"><input type="checkbox" data-ap="sfx" ${cur.sfx === false ? '' : 'checked'} /><span class="ap-knob" aria-hidden="true"></span> Tiếng động gắn theo chuyển động</label>+ ${opts?.hint ? `<div class="hint ap-hint">${esc(opts.hint)}</div>` : ''}+ <div class="hint ap-note" aria-live="polite"></div>`;+ }+ function readControls(box) {+ const m = $('[data-ap="music"]', box).value, v = $('[data-ap="voice"]', box).value;+ return { music: m || undefined, voice: v || undefined, sfx: $('[data-ap="sfx"]', box).checked };+ }+ function wirePreview(box) {+ box.addEventListener('click', (e) => {+ const b = e.target.closest('.ap-play'); if (!b) return;+ const note = $('.ap-note', box);+ if (b.dataset.prev === 'music') {+ const s = $('[data-ap="music"]', box).value;+ if (!s || s === 'auto' || s === 'none') { note.textContent = 'Chọn 1 kiểu nhạc cụ thể để nghe thử.'; return; }+ preview(b, '/api/audio/preview?style=' + encodeURIComponent(s), note);+ } else {+ const v = $('[data-ap="voice"]', box).value;+ if (!v || v === 'auto' || v === 'none') { note.textContent = 'Chọn 1 giọng cụ thể để nghe thử.'; return; }+ preview(b, '/api/audio/preview?voice=' + encodeURIComponent(v), note);+ }+ });+ }++ // ---------- (1) form dựng ----------+ const mount = document.getElementById('audioPanel');+ if (mount) {+ mount.classList.add('ap');+ mount.innerHTML = '<div class="ap-title">Âm thanh</div><div class="hint">Đang tải lựa chọn…</div>';+ optsP.then(() => { mount.innerHTML = '<div class="ap-title">Âm thanh</div>' + controlsHtml({ music: 'auto', voice: 'auto', sfx: true }); });+ wirePreview(mount);+ }+ window.LumAudio = {+ /** Giá trị cho POST /api/jobs: { music, voice, sfx }. */+ value: () => (mount && $('[data-ap="music"]', mount) ? readControls(mount) : undefined),+ };++ // ---------- (2) mỗi video đã dựng ----------+ const VOICE_NAME = (id) => (id === 'auto' ? 'giọng theo mẫu' : id === 'none' ? 'không lời' : (opts?.voices || []).find((v) => v.id === id)?.name || id);+ function versionsHtml(j) {+ const vs = j.versions || [];+ if (vs.length < 2) return '';+ return `<div class="ap-vers"><div class="ap-sub">Các bản (${vs.length})</div>${vs.map((v) => `+ <div class="ap-ver ${v.current ? 'cur' : ''}"><span>Bản ${v.n}${v.current ? ' · mới nhất' : ''}${v.audio ? ` · ${esc(v.audio.music)} · ${esc(VOICE_NAME(v.audio.voice))}${v.audio.sfx === false ? ' · không sfx' : ''}` : ''}</span>+ <button type="button" class="mini" data-ver="${esc(v.url)}">Xem</button><a class="mini" href="${esc(v.url)}" download>Tải</a></div>`).join('')}</div>`;+ }+ async function fillJob(details, id) {+ await optsP;+ const j = await (await fetch('/api/jobs/' + id)).json();+ const body = $('.ap-body', details);+ body.innerHTML = controlsHtml(j.audio && typeof j.audio === 'object' ? j.audio : {}, { keepLabel: false })+ + `<button type="button" class="ap-go" data-mix>Trộn tiếng mới</button>+ <div class="hint">Không dựng lại hình. Bản cũ được giữ lại; chọn giọng mà video chưa có lời thì AI viết lời ngắn.</div>`+ + (j.audioStatus === 'error' && j.audioError ? `<div class="errmsg">Lần trộn trước lỗi: ${esc(j.audioError)}</div>` : '')+ + `<div class="ap-verbox">${versionsHtml(j)}</div>`;+ body.dataset.ready = '1';+ if (j.audioBusy || j.audioStatus === 'mixing') watch(details, id);+ }+ function watch(details, id) {+ const btn = $('[data-mix]', details), note = $('.ap-note', details);+ if (btn) { btn.disabled = true; btn.textContent = 'Đang trộn tiếng…'; }+ if (note) note.textContent = 'Đang trộn (giọng VieNeu có thể mất vài phút)…';+ const tick = async () => {+ const j = await (await fetch('/api/jobs/' + id)).json().catch(() => null);+ if (j && (j.audioBusy || j.audioStatus === 'mixing')) return setTimeout(tick, 3000);+ if (btn) { btn.disabled = false; btn.textContent = 'Trộn tiếng mới'; }+ if (!j) return;+ if (j.audioStatus === 'error') { if (note) note.textContent = 'Lỗi: ' + (j.audioError || 'không rõ'); return; }+ if (note) note.textContent = 'Xong — đang phát bản mới nhất.';+ const card = document.getElementById('job-' + id), vid = card && $('.media video', card);+ if (vid) { vid.src = `/jobs/${id}/out.mp4?v=${Date.now()}`; vid.load(); }+ const vb = $('.ap-verbox', details); if (vb) vb.innerHTML = versionsHtml(j);+ };+ setTimeout(tick, 2000);+ }+ function enhance(card) {+ if (card.querySelector('.ap-job')) return;+ const id = card.id.replace(/^job-/, '');+ const hasVideo = card.querySelector('.media video');+ if (!hasVideo) return;+ const d = document.createElement('details');+ d.className = 'ap-job';+ d.innerHTML = '<summary>Âm thanh · đổi nhạc, giọng đọc</summary><div class="ap-body"><div class="hint">Đang tải…</div></div>';+ d.addEventListener('toggle', () => { if (d.open && !$('.ap-body', d).dataset.ready) fillJob(d, id); });+ wirePreview(d);+ d.addEventListener('click', async (e) => {+ const ver = e.target.closest('[data-ver]');+ if (ver) { const vid = $('.media video', card); if (vid) { vid.src = ver.dataset.ver + '?v=' + Date.now(); vid.play().catch(() => {}); } return; }+ if (!e.target.closest('[data-mix]')) return;+ const note = $('.ap-note', d);+ try {+ const r = await fetch(`/api/jobs/${id}/audio`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(readControls(d)) });+ const j = await r.json();+ if (!r.ok) throw new Error(j.error || 'lỗi');+ watch(d, id);+ } catch (err) { note.textContent = 'Không trộn được: ' + err.message; }+ });+ const host = card.querySelector('.links') || card.lastElementChild;+ host.insertAdjacentElement('afterend', d);+ }+ const jobs = document.getElementById('jobs');+ if (jobs) {+ const scan = () => jobs.querySelectorAll('article.job').forEach(enhance);+ new MutationObserver(scan).observe(jobs, { childList: true });+ scan();+ }+})();diff --git a/server/public/index.html b/server/public/index.htmlindex 9722c54..4257e3d 100644--- a/server/public/index.html+++ b/server/public/index.html@@ -40,15 +40,34 @@<div class="sticky"><h2 id="h-compose"><span class="step">2</span>Nội dung</h2><div id="picked" class="picked empty">Chưa chọn mẫu. Bấm 1 mẫu sáng màu bên trái.</div>- <label class="field" for="content">Nội dung video</label>+ <div class="field-head">+ <label class="field" for="content">Nội dung video</label>+ <button type="button" id="rewrite" class="ghost" disabled aria-describedby="rwHint">+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 20h4L19 9l-4-4L4 16z"/><path d="m13.5 6.5 4 4"/></svg>+ <span>Viết lại kịch bản</span>+ </button>+ </div><textarea id="content" rows="7" maxlength="4000" placeholder="Ví dụ: Mỗi tháng bỏ 3 triệu vào quỹ chỉ số, lãi giả định 10%/năm, sau 20 năm có bao nhiêu? Kênh: Lumfin. CTA: Theo dõi để biết thêm mẹo tiền"></textarea><div class="hint"><span id="chars">0</span>/4000 ký tự · ghi luôn tên kênh và CTA nếu có</div>- <div class="row">- <div>- <label class="field" for="duration">Thời lượng</label>- <select id="duration"><option value="8" selected>8 giây</option><option value="6">6 giây</option><option value="12">12 giây</option><option value="16">16 giây</option></select>+ <div class="hint" id="rwHint">Viết lại kịch bản: AI xếp nội dung vào đúng ô của mẫu đang chọn và thời lượng bên dưới, giữ nguyên số liệu, tên kênh, CTA.</div>+ <div id="rwBox" class="rw" hidden aria-live="polite"></div>++ <label class="field" for="duration">Thời lượng <span class="opt">(3 giây – 10 phút)</span></label>+ <div class="dur">+ <input id="duration" type="text" inputmode="numeric" autocomplete="off" spellcheck="false" value="8"+ placeholder="8" aria-describedby="durHint" />+ <div class="presets" role="group" aria-label="Chọn nhanh thời lượng">+ <button type="button" class="pre on" data-dur="8">8s</button>+ <button type="button" class="pre" data-dur="15">15s</button>+ <button type="button" class="pre" data-dur="30">30s</button>+ <button type="button" class="pre" data-dur="60">60s</button></div>- <div>+ </div>+ <div class="hint" id="durHint">Gõ số giây (90) hoặc phút:giây (1:30).</div>+ <div class="warn" id="durWarn" hidden></div>+ <div id="audioPanel" aria-label="Âm thanh"></div>+ <div class="row">+ <div class="span2"><label class="field" for="mode">Ai dựng cảnh</label><select id="mode"><option value="auto">Tự động</option>@@ -84,6 +103,7 @@<p class="dlg-desc" id="vDesc"></p></dialog>+<script src="/audio-panel.js"></script><script src="/app.js"></script></body></html>diff --git a/server/public/style.css b/server/public/style.cssindex 77330f2..092cc3a 100644--- a/server/public/style.css+++ b/server/public/style.css@@ -70,6 +70,35 @@ select { min-height: 44px; }.st.scheduled { color: #7FB7FF; }.cost { font: 500 13px var(--mono); color: var(--ink-2); }.row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }+.span2 { grid-column: 1 / -1; }+.field-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 8px; }+.field-head .field { margin-bottom: 6px; }+.ghost { min-height: 40px; display: inline-flex; align-items: center; gap: 6px; padding: 0 12px; margin-bottom: 4px; border-radius: 10px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink); font-size: 14px; font-weight: 600; cursor: pointer; transition: border-color .15s, color .15s; white-space: nowrap; }+.ghost svg { width: 16px; height: 16px; fill: none; stroke: var(--accent); stroke-width: 2; stroke-linejoin: round; }+.ghost:hover:not(:disabled) { border-color: var(--accent); }+.ghost:disabled { color: var(--ink-3); cursor: not-allowed; }+.ghost:disabled svg { stroke: var(--ink-3); }+.ghost.busy svg { animation: pulse 1s ease-in-out infinite; }+.rw { margin-top: 10px; background: var(--bg); border: 1px solid var(--line); border-left: 3px solid var(--accent); border-radius: 10px; padding: 12px; }+.rw .rw-h { font-size: 13px; font-weight: 600; color: var(--ink-2); display: flex; justify-content: space-between; gap: 8px; flex-wrap: wrap; }+.rw .rw-h .eng { font: 500 12px var(--mono); color: var(--ink-3); }+.rw pre { font: 400 14px/1.5 var(--sans); white-space: pre-wrap; margin: 8px 0; max-height: 260px; overflow: auto; color: var(--ink); }+.rw .rw-n { font-size: 13px; color: var(--ink-2); white-space: pre-wrap; border-top: 1px dashed var(--line); padding-top: 8px; margin-top: 4px; }+.rw .rw-a { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }+.rw .rw-a button { min-height: 40px; padding: 0 14px; border-radius: 8px; border: 1px solid var(--line); background: var(--panel-2); cursor: pointer; font-size: 14px; }+.rw .rw-a .use { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); font-weight: 700; }+.rw.err-box { border-left-color: var(--bad); color: var(--bad); font-size: 14px; }+.rw.load { color: var(--ink-2); font-size: 14px; }+.rw.load::after { content: ''; display: block; height: 3px; margin-top: 10px; border-radius: 2px; background: linear-gradient(90deg, transparent, var(--accent), transparent); background-size: 50% 100%; background-repeat: no-repeat; animation: sweep 1.2s linear infinite; }+@keyframes sweep { from { background-position: -50% 0; } to { background-position: 150% 0; } }+.dur { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }+.dur input { width: 96px; min-height: 44px; background: var(--bg); border: 1px solid var(--line); border-radius: 10px; padding: 0 12px; font: 600 16px var(--mono); }+.dur input[aria-invalid="true"] { border-color: var(--bad); }+.presets { display: flex; gap: 6px; flex-wrap: wrap; }+.pre { min-height: 44px; min-width: 52px; padding: 0 10px; border-radius: 999px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink-2); font: 500 14px var(--mono); cursor: pointer; }+.pre.on { background: var(--ink); color: var(--bg); border-color: var(--ink); font-weight: 700; }+.hint.bad { color: var(--bad); }+.warn { margin-top: 8px; font-size: 13px; line-height: 1.45; color: var(--warn); background: rgba(242,201,76,.08); border: 1px solid rgba(242,201,76,.3); border-radius: 8px; padding: 8px 10px; }.err { color: var(--bad); font-size: 14px; min-height: 20px; margin: 12px 0 0; }.go { margin-top: 8px; width: 100%; min-height: 60px; border: 0; border-radius: 14px; background: var(--accent); color: var(--accent-ink); font: 800 26px/1 var(--cond); text-transform: uppercase; letter-spacing: .04em; display: flex; align-items: center; justify-content: center; gap: 12px; cursor: pointer; transition: transform .1s, filter .15s; box-shadow: 0 10px 30px -12px rgba(255,107,44,.7); }.go svg { width: 22px; height: 22px; fill: currentColor; }diff --git a/server/server.mjs b/server/server.mjsindex e423aca..7ac5341 100644--- a/server/server.mjs+++ b/server/server.mjs@@ -8,7 +8,33 @@ import {dueJobs, resolveMode, submitScene, previewJob,} from '../generator/jobs.mjs';import { findClaude } from '../generator/claude.mjs';+import { rewriteScript, resolveRewriteEngine, REWRITE_MAX_CHARS } from '../generator/rewrite.mjs';import { config } from '../generator/config.mjs';+import { reAudio, listVersions, audioBusy, saveAudioSpec } from '../generator/audio-job.mjs';+import { audioOptions, normalizeAudioPrefs, voiceEngine, VOICE_SAMPLE_TEXT } from '../engine/audio/prefs.mjs';+import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';+import { synthVoice } from '../engine/audio/voice.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. */+async function audioPreviewFile(q) {+ const style = q.get('style'), voice = q.get('voice');+ if (style) {+ if (!MUSIC_STYLES.includes(style)) throw new Error('style nhạc không có: ' + style);+ const f = path.join(AUDIO_SAMPLES, `music-${style}.wav`);+ if (!fs.existsSync(f)) { fs.mkdirSync(AUDIO_SAMPLES, { recursive: true }); writeMusic(style, f, 8, 1); }+ return f;+ }+ if (voice) {+ const text = String(q.get('text') || VOICE_SAMPLE_TEXT).trim().slice(0, 160);+ const { voice: v } = normalizeAudioPrefs({ voice });+ if (v === 'auto' || v === 'none') throw new Error('chọn 1 giọng cụ thể để nghe thử');+ const ve = voiceEngine(v);+ const [r] = await synthVoice([{ t: 0, text }], path.join(AUDIO_SAMPLES, 'voices'), { engine: ve.engine, voice: ve.speaker, log: (l) => console.log('[audio] ' + l) });+ return r.file;+ }+ throw new Error('cần ?style=<nhạc> hoặc ?voice=<giọng>&text=...');+}const HOST = '127.0.0.1';const PORT = Number(process.env.PORT) || 4400;@@ -19,7 +45,7 @@ const ALLOWED_HOSTS = new Set([`127.0.0.1:${PORT}`, `localhost:${PORT}`]);const MIME = {'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8','.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',- '.png': 'image/png', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.m4a': 'audio/mp4', '.woff2': 'font/woff2', '.md': 'text/markdown; charset=utf-8',+ '.png': 'image/png', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.m4a': 'audio/mp4', '.wav': 'audio/wav', '.woff2': 'font/woff2', '.md': 'text/markdown; charset=utf-8',};// ---- hàng đợi: mỗi lúc chỉ 1 job chạy (render nặng) ----@@ -86,10 +112,13 @@ function readBody(req, limit = 64 * 1024) {}// Ảnh/video minh hoạ mỗi mẫu, theo thứ tự ưu tiên:-// 1. video demo do chính LumReels dựng (site/dist/media/<id>.mp4 + .webp, sinh bởi site/build.mjs)-// 2. video tham chiếu riêng trên máy (templates/ref/<id>/, tools/fetch_refs.py — không có trong repo)-// 3. poster SVG tự dựng (/poster/<id>.svg) từ tên + nhóm của mẫu+// ảnh: 1. site/dist/media/<id>.webp (poster video demo, sinh bởi site/build.mjs — không có trong repo)+// 2. templates/thumbs/<id>.webp (khung keyframe 360×640 có sẵn trong repo; tạo bằng scripts/make-thumbs.mjs)+// 3. khung video tham chiếu riêng trên máy (templates/ref/<id>/frames, tools/fetch_refs.py — không có trong repo)+// 4. poster SVG tự dựng (/poster/<id>.svg) từ tên + nhóm của mẫu+// video: demo (site/dist/media/<id>.mp4) → video tham chiếu riêng → không cóconst DEMO = path.join(ROOT, 'site', 'dist', 'media');+const THUMBS = path.join(TEMPLATES, 'thumbs');// LUMREELS_NO_REF=1: bỏ qua templates/ref (giả lập máy vừa clone repo; dùng khi chụp ảnh docs).const USE_REF = process.env.LUMREELS_NO_REF !== '1';function templateList() {@@ -98,12 +127,13 @@ function templateList() {const refThumb = USE_REF && ['f_08.jpg', 'f_09.jpg', 'f_07.jpg'].find((f) => fs.existsSync(path.join(ref, 'frames', f)));const demo = fs.existsSync(path.join(DEMO, `${t.id}.mp4`));const demoPoster = fs.existsSync(path.join(DEMO, `${t.id}.webp`));+ const keyThumb = fs.existsSync(path.join(THUMBS, `${t.id}.webp`));const refVideo = USE_REF && fs.existsSync(path.join(ref, 'video.mp4'));return {id: t.id, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre, technique: t.technique,difficulty: t.difficulty, narration: t.narration,hasGuidance: hasGuidance(t.id),- thumb: demoPoster ? `/demo/${t.id}.webp` : refThumb ? `/ref/${t.id}/frames/${refThumb}` : `/poster/${t.id}.svg`,+ thumb: demoPoster ? `/demo/${t.id}.webp` : keyThumb ? `/thumbs/${t.id}.webp` : refThumb ? `/ref/${t.id}/frames/${refThumb}` : `/poster/${t.id}.svg`,video: demo ? `/demo/${t.id}.mp4` : refVideo ? `/ref/${t.id}/video.mp4` : null,videoKind: demo ? 'demo' : refVideo ? 'ref' : null,};@@ -139,6 +169,8 @@ function jobView(job, withLog = false) {...job,templateTitle: templateName(job.templateId) || job.templateTitle,queued: queue.length,+ versions: listVersions(job.id).map((v) => ({ ...v, url: `/jobs/${job.id}/${v.file}` })),+ audioBusy: audioBusy(job.id),links: {mp4: has('out.mp4') && job.status === 'done' ? `/jobs/${job.id}/out.mp4` : null,preview: has('preview.jpg') ? `/jobs/${job.id}/preview.jpg` : null,@@ -151,6 +183,9 @@ function jobView(job, withLog = false) {return v;}+let rewriteBusy = false;+let rewriteLast = 0;+const server = http.createServer(async (req, res) => {const url = new URL(req.url, `http://${HOST}`);const p = decodeURIComponent(url.pathname);@@ -160,12 +195,29 @@ const server = http.createServer(async (req, res) => {// ---- API ----if (p === '/api/templates' && req.method === 'GET') return send(res, 200, templateList());if (p === '/api/config' && req.method === 'GET') {- return send(res, 200, { defaultMode: DEFAULT_MODE, autoResolves: resolveMode('auto'), claudeAvailable: !!findClaude(), apiAvailable: config.hasApiKey(), outputDir: !!config.outputDir() });+ return send(res, 200, { defaultMode: DEFAULT_MODE, autoResolves: resolveMode('auto'), claudeAvailable: !!findClaude(), apiAvailable: config.hasApiKey(), outputDir: !!config.outputDir(), rewriteEngine: resolveRewriteEngine() });+ }+ if (p === '/api/rewrite' && req.method === 'POST') {+ // Chống bấm liên tục: mỗi lúc 1 lượt, cách nhau ≥ 3 giây.+ if (rewriteBusy) return send(res, 429, { error: 'Đang viết lại 1 bản, chờ xong rồi bấm tiếp' });+ if (Date.now() - rewriteLast < 3000) return send(res, 429, { error: 'Bấm chậm lại chút (cách nhau 3 giây)' });+ const body = await readBody(req);+ if (String(body.content || '').length > REWRITE_MAX_CHARS) return send(res, 413, { error: `Nội dung quá dài (tối đa ${REWRITE_MAX_CHARS} ký tự)` });+ rewriteBusy = true;+ try {+ const r = await rewriteScript({ templateId: body.templateId, content: body.content, durationS: body.durationS });+ console.log(`[rewrite] mẫu ${r.templateId}, ${r.durationS}s, ${r.engine}${r.fallbackFrom ? ' (sau khi ' + r.fallbackFrom + ')' : ''}`);+ return send(res, 200, r);+ } catch (e) {+ return send(res, /chưa cấu hình AI/i.test(e.message) ? 503 : 422, { error: e.message });+ } finally {+ rewriteBusy = false; rewriteLast = Date.now();+ }}if (p === '/api/jobs' && req.method === 'GET') return send(res, 200, listJobs().map((j) => jobView(j)));if (p === '/api/jobs' && req.method === 'POST') {const body = await readBody(req);- const job = createJob({ templateId: body.templateId, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, runAt: body.runAt, source: body.source || 'web' });+ const job = createJob({ templateId: body.templateId, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, runAt: body.runAt, source: body.source || 'web', audio: body.audio });if (job.status === 'scheduled') { /* bộ hẹn giờ sẽ chạy khi tới giờ */ }else if (resolveMode(job.mode) === 'manual') await runJob(job.id); // chỉ chuyển sang waiting_agentelse enqueueJob(job.id, () => runJob(job.id));@@ -174,6 +226,7 @@ const server = http.createServer(async (req, res) => {let ms = /^\/api\/jobs\/([\w-]+)\/scene$/.exec(p);if (ms && req.method === 'POST') {const body = await readBody(req, 2_500_000);+ if (body.audio !== undefined && body.audio !== null) await saveAudioSpec(ms[1], body.audio); // scene/audio.json (AUTHORING §9)const r = submitScene(ms[1], body.html, body.brief);return send(res, r.ok ? 200 : 422, r);}@@ -194,6 +247,26 @@ const server = http.createServer(async (req, res) => {enqueueJob(job.id, () => renderJob(job.id));return send(res, 202, jobView(job, true));}+ // ---- âm thanh ----+ if (p === '/api/audio/options' && req.method === 'GET') return send(res, 200, audioOptions());+ if (p === '/api/audio/preview' && req.method === 'GET') {+ const f = await audioPreviewFile(url.searchParams);+ return serveFile(req, res, path.dirname(f), path.basename(f));+ }+ m = /^\/api\/jobs\/([\w-]+)\/audio$/.exec(p);+ if (m && req.method === 'POST') {+ const job = readJob(m[1]);+ if (!job) return send(res, 404, { error: 'không thấy job' });+ if (job.status !== 'done' && !fs.existsSync(path.join(JOBS, job.id, 'out.mp4'))) return send(res, 409, { error: 'video chưa dựng xong' });+ if (audioBusy(job.id)) return send(res, 409, { error: 'đang trộn tiếng cho video này' });+ const body = await readBody(req);+ const prefs = { music: body.music, voice: body.voice, sfx: body.sfx };+ normalizeAudioPrefs({ ...prefs }); // kiểm sớm, sai thì 400+ reAudio(job.id, prefs).catch((e) => console.error('[audio]', job.id, e.message)); // chạy nền; UI hỏi lại GET /api/jobs/:id+ return send(res, 202, { ...jobView(readJob(job.id), true), audioBusy: true });+ }+ m = /^\/api\/jobs\/([\w-]+)\/versions$/.exec(p);+ if (m && req.method === 'GET') return send(res, 200, listVersions(m[1]).map((v) => ({ ...v, url: `/jobs/${m[1]}/${v.file}` })));if (p.startsWith('/api/')) return send(res, 404, { error: 'không có API này' });// ---- file ----@@ -201,11 +274,15 @@ const server = http.createServer(async (req, res) => {if (p.startsWith('/ref/') && USE_REF) return serveFile(req, res, path.join(TEMPLATES, 'ref'), p.slice(5));m = /^\/demo\/(\d{3}\.(?:mp4|webp))$/.exec(p);if (m) return serveFile(req, res, DEMO, m[1]);+ m = /^\/thumbs\/(\d{3}\.webp)$/.exec(p);+ if (m) return serveFile(req, res, THUMBS, m[1]);m = /^\/poster\/(\d{3})\.svg$/.exec(p);if (m) {const t = loadCatalog().find((x) => x.id === m[1]);return t ? send(res, 200, posterSvg(t), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });}+ m = /^\/jobs\/([\w-]+)\/(versions\/out-\d{1,4}\.mp4)$/.exec(p);+ if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);m = /^\/jobs\/([\w-]+)\/(out\.mp4|preview\.jpg|PROMPT\.md|brief\.json)$/.exec(p);if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);if (p.startsWith('/fonts/')) return serveFile(req, res, path.join(ROOT, 'engine', 'fonts'), p.slice(7));diff --git a/templates/thumbs/001.webp b/templates/thumbs/001.webpnew file mode 100644index 0000000..6d3389cBinary files /dev/null and b/templates/thumbs/001.webp differdiff --git a/templates/thumbs/002.webp b/templates/thumbs/002.webpnew file mode 100644index 0000000..b3335fbBinary files /dev/null and b/templates/thumbs/002.webp differdiff --git a/templates/thumbs/003.webp b/templates/thumbs/003.webpnew file mode 100644index 0000000..d68ed8cBinary files /dev/null and b/templates/thumbs/003.webp differdiff --git a/templates/thumbs/004.webp b/templates/thumbs/004.webpnew file mode 100644index 0000000..be7d1fcBinary files /dev/null and b/templates/thumbs/004.webp differdiff --git a/templates/thumbs/005.webp b/templates/thumbs/005.webpnew file mode 100644index 0000000..59add76Binary files /dev/null and b/templates/thumbs/005.webp differdiff --git a/templates/thumbs/006.webp b/templates/thumbs/006.webpnew file mode 100644index 0000000..406f8adBinary files /dev/null and b/templates/thumbs/006.webp differdiff --git a/templates/thumbs/007.webp b/templates/thumbs/007.webpnew file mode 100644index 0000000..3f0aa17Binary files /dev/null and b/templates/thumbs/007.webp differdiff --git a/templates/thumbs/008.webp b/templates/thumbs/008.webpnew file mode 100644index 0000000..bdd7f17Binary files /dev/null and b/templates/thumbs/008.webp differdiff --git a/templates/thumbs/009.webp b/templates/thumbs/009.webpnew file mode 100644index 0000000..9045c42Binary files /dev/null and b/templates/thumbs/009.webp differdiff --git a/templates/thumbs/010.webp b/templates/thumbs/010.webpnew file mode 100644index 0000000..3e0376cBinary files /dev/null and b/templates/thumbs/010.webp differdiff --git a/templates/thumbs/011.webp b/templates/thumbs/011.webpnew file mode 100644index 0000000..2b8da30Binary files /dev/null and b/templates/thumbs/011.webp differdiff --git a/templates/thumbs/012.webp b/templates/thumbs/012.webpnew file mode 100644index 0000000..c1a9b70Binary files /dev/null and b/templates/thumbs/012.webp differdiff --git a/templates/thumbs/014.webp b/templates/thumbs/014.webpnew file mode 100644index 0000000..4a879f4Binary files /dev/null and b/templates/thumbs/014.webp differdiff --git a/templates/thumbs/015.webp b/templates/thumbs/015.webpnew file mode 100644index 0000000..a2018b4Binary files /dev/null and b/templates/thumbs/015.webp differdiff --git a/templates/thumbs/016.webp b/templates/thumbs/016.webpnew file mode 100644index 0000000..956cc62Binary files /dev/null and b/templates/thumbs/016.webp differdiff --git a/templates/thumbs/017.webp b/templates/thumbs/017.webpnew file mode 100644index 0000000..73897adBinary files /dev/null and b/templates/thumbs/017.webp differdiff --git a/templates/thumbs/018.webp b/templates/thumbs/018.webpnew file mode 100644index 0000000..e1b5c1bBinary files /dev/null and b/templates/thumbs/018.webp differdiff --git a/templates/thumbs/019.webp b/templates/thumbs/019.webpnew file mode 100644index 0000000..ec84f29Binary files /dev/null and b/templates/thumbs/019.webp differdiff --git a/templates/thumbs/020.webp b/templates/thumbs/020.webpnew file mode 100644index 0000000..f858249Binary files /dev/null and b/templates/thumbs/020.webp differdiff --git a/templates/thumbs/021.webp b/templates/thumbs/021.webpnew file mode 100644index 0000000..5a8dd2aBinary files /dev/null and b/templates/thumbs/021.webp differdiff --git a/templates/thumbs/022.webp b/templates/thumbs/022.webpnew file mode 100644index 0000000..713556aBinary files /dev/null and b/templates/thumbs/022.webp differdiff --git a/templates/thumbs/023.webp b/templates/thumbs/023.webpnew file mode 100644index 0000000..f25efa1Binary files /dev/null and b/templates/thumbs/023.webp differdiff --git a/templates/thumbs/024.webp b/templates/thumbs/024.webpnew file mode 100644index 0000000..9d2edcfBinary files /dev/null and b/templates/thumbs/024.webp differdiff --git a/templates/thumbs/025.webp b/templates/thumbs/025.webpnew file mode 100644index 0000000..ac07444Binary files /dev/null and b/templates/thumbs/025.webp differdiff --git a/templates/thumbs/026.webp b/templates/thumbs/026.webpnew file mode 100644index 0000000..a16bcf8Binary files /dev/null and b/templates/thumbs/026.webp differdiff --git a/templates/thumbs/027.webp b/templates/thumbs/027.webpnew file mode 100644index 0000000..0ed359aBinary files /dev/null and b/templates/thumbs/027.webp differdiff --git a/templates/thumbs/028.webp b/templates/thumbs/028.webpnew file mode 100644index 0000000..a11cf76Binary files /dev/null and b/templates/thumbs/028.webp differdiff --git a/templates/thumbs/029.webp b/templates/thumbs/029.webpnew file mode 100644index 0000000..68a9e05Binary files /dev/null and b/templates/thumbs/029.webp differdiff --git a/templates/thumbs/030.webp b/templates/thumbs/030.webpnew file mode 100644index 0000000..ecb98b9Binary files /dev/null and b/templates/thumbs/030.webp differdiff --git a/templates/thumbs/031.webp b/templates/thumbs/031.webpnew file mode 100644index 0000000..3b8fed6Binary files /dev/null and b/templates/thumbs/031.webp differdiff --git a/templates/thumbs/032.webp b/templates/thumbs/032.webpnew file mode 100644index 0000000..548069aBinary files /dev/null and b/templates/thumbs/032.webp differdiff --git a/templates/thumbs/033.webp b/templates/thumbs/033.webpnew file mode 100644index 0000000..721eb7aBinary files /dev/null and b/templates/thumbs/033.webp differdiff --git a/templates/thumbs/034.webp b/templates/thumbs/034.webpnew file mode 100644index 0000000..b6e1c1dBinary files /dev/null and b/templates/thumbs/034.webp differdiff --git a/templates/thumbs/035.webp b/templates/thumbs/035.webpnew file mode 100644index 0000000..a7145f2Binary files /dev/null and b/templates/thumbs/035.webp differdiff --git a/templates/thumbs/036.webp b/templates/thumbs/036.webpnew file mode 100644index 0000000..315b3fcBinary files /dev/null and b/templates/thumbs/036.webp differdiff --git a/templates/thumbs/037.webp b/templates/thumbs/037.webpnew file mode 100644index 0000000..8d48539Binary files /dev/null and b/templates/thumbs/037.webp differdiff --git a/templates/thumbs/038.webp b/templates/thumbs/038.webpnew file mode 100644index 0000000..b647059Binary files /dev/null and b/templates/thumbs/038.webp differdiff --git a/templates/thumbs/039.webp b/templates/thumbs/039.webpnew file mode 100644index 0000000..a3978bcBinary files /dev/null and b/templates/thumbs/039.webp differdiff --git a/templates/thumbs/040.webp b/templates/thumbs/040.webpnew file mode 100644index 0000000..5f59968Binary files /dev/null and b/templates/thumbs/040.webp differdiff --git a/templates/thumbs/041.webp b/templates/thumbs/041.webpnew file mode 100644index 0000000..613e716Binary files /dev/null and b/templates/thumbs/041.webp differdiff --git a/templates/thumbs/042.webp b/templates/thumbs/042.webpnew file mode 100644index 0000000..62919e5Binary files /dev/null and b/templates/thumbs/042.webp differdiff --git a/templates/thumbs/043.webp b/templates/thumbs/043.webpnew file mode 100644index 0000000..ebc231dBinary files /dev/null and b/templates/thumbs/043.webp differdiff --git a/templates/thumbs/044.webp b/templates/thumbs/044.webpnew file mode 100644index 0000000..6ef0602Binary files /dev/null and b/templates/thumbs/044.webp differdiff --git a/templates/thumbs/045.webp b/templates/thumbs/045.webpnew file mode 100644index 0000000..692a392Binary files /dev/null and b/templates/thumbs/045.webp differdiff --git a/templates/thumbs/046.webp b/templates/thumbs/046.webpnew file mode 100644index 0000000..13bcf87Binary files /dev/null and b/templates/thumbs/046.webp differdiff --git a/templates/thumbs/047.webp b/templates/thumbs/047.webpnew file mode 100644index 0000000..e90f4a9Binary files /dev/null and b/templates/thumbs/047.webp differdiff --git a/templates/thumbs/048.webp b/templates/thumbs/048.webpnew file mode 100644index 0000000..07dbaa8Binary files /dev/null and b/templates/thumbs/048.webp differdiff --git a/templates/thumbs/049.webp b/templates/thumbs/049.webpnew file mode 100644index 0000000..28836b8Binary files /dev/null and b/templates/thumbs/049.webp differdiff --git a/templates/thumbs/050.webp b/templates/thumbs/050.webpnew file mode 100644index 0000000..1418667Binary files /dev/null and b/templates/thumbs/050.webp differdiff --git a/templates/thumbs/051.webp b/templates/thumbs/051.webpnew file mode 100644index 0000000..bf78d60Binary files /dev/null and b/templates/thumbs/051.webp differdiff --git a/templates/thumbs/052.webp b/templates/thumbs/052.webpnew file mode 100644index 0000000..8e37f5fBinary files /dev/null and b/templates/thumbs/052.webp differdiff --git a/templates/thumbs/053.webp b/templates/thumbs/053.webpnew file mode 100644index 0000000..f7352c5Binary files /dev/null and b/templates/thumbs/053.webp differdiff --git a/templates/thumbs/054.webp b/templates/thumbs/054.webpnew file mode 100644index 0000000..fc7a9a1Binary files /dev/null and b/templates/thumbs/054.webp differdiff --git a/templates/thumbs/055.webp b/templates/thumbs/055.webpnew file mode 100644index 0000000..7dcc749Binary files /dev/null and b/templates/thumbs/055.webp differdiff --git a/templates/thumbs/056.webp b/templates/thumbs/056.webpnew file mode 100644index 0000000..6903fa7Binary files /dev/null and b/templates/thumbs/056.webp differdiff --git a/templates/thumbs/057.webp b/templates/thumbs/057.webpnew file mode 100644index 0000000..3de4968Binary files /dev/null and b/templates/thumbs/057.webp differdiff --git a/templates/thumbs/058.webp b/templates/thumbs/058.webpnew file mode 100644index 0000000..b043983Binary files /dev/null and b/templates/thumbs/058.webp differdiff --git a/templates/thumbs/059.webp b/templates/thumbs/059.webpnew file mode 100644index 0000000..7ceaa05Binary files /dev/null and b/templates/thumbs/059.webp differdiff --git a/templates/thumbs/060.webp b/templates/thumbs/060.webpnew file mode 100644index 0000000..b2e3887Binary files /dev/null and b/templates/thumbs/060.webp differdiff --git a/templates/thumbs/061.webp b/templates/thumbs/061.webpnew file mode 100644index 0000000..c2d08a7Binary files /dev/null and b/templates/thumbs/061.webp differdiff --git a/templates/thumbs/062.webp b/templates/thumbs/062.webpnew file mode 100644index 0000000..2a51686Binary files /dev/null and b/templates/thumbs/062.webp differdiff --git a/templates/thumbs/063.webp b/templates/thumbs/063.webpnew file mode 100644index 0000000..4981be0Binary files /dev/null and b/templates/thumbs/063.webp differdiff --git a/templates/thumbs/064.webp b/templates/thumbs/064.webpnew file mode 100644index 0000000..b8b7e7cBinary files /dev/null and b/templates/thumbs/064.webp differdiff --git a/templates/thumbs/065.webp b/templates/thumbs/065.webpnew file mode 100644index 0000000..63bbec6Binary files /dev/null and b/templates/thumbs/065.webp differdiff --git a/templates/thumbs/066.webp b/templates/thumbs/066.webpnew file mode 100644index 0000000..2e8a2bfBinary files /dev/null and b/templates/thumbs/066.webp differdiff --git a/templates/thumbs/067.webp b/templates/thumbs/067.webpnew file mode 100644index 0000000..76ed2beBinary files /dev/null and b/templates/thumbs/067.webp differdiff --git a/templates/thumbs/068.webp b/templates/thumbs/068.webpnew file mode 100644index 0000000..8de47d7Binary files /dev/null and b/templates/thumbs/068.webp differdiff --git a/templates/thumbs/069.webp b/templates/thumbs/069.webpnew file mode 100644index 0000000..1c84142Binary files /dev/null and b/templates/thumbs/069.webp differdiff --git a/templates/thumbs/070.webp b/templates/thumbs/070.webpnew file mode 100644index 0000000..c1a676eBinary files /dev/null and b/templates/thumbs/070.webp differdiff --git a/templates/thumbs/071.webp b/templates/thumbs/071.webpnew file mode 100644index 0000000..d5417a2Binary files /dev/null and b/templates/thumbs/071.webp differdiff --git a/templates/thumbs/072.webp b/templates/thumbs/072.webpnew file mode 100644index 0000000..5aa1f9dBinary files /dev/null and b/templates/thumbs/072.webp differdiff --git a/templates/thumbs/073.webp b/templates/thumbs/073.webpnew file mode 100644index 0000000..149d110Binary files /dev/null and b/templates/thumbs/073.webp differdiff --git a/templates/thumbs/074.webp b/templates/thumbs/074.webpnew file mode 100644index 0000000..623d92eBinary files /dev/null and b/templates/thumbs/074.webp differdiff --git a/templates/thumbs/075.webp b/templates/thumbs/075.webpnew file mode 100644index 0000000..f933a3bBinary files /dev/null and b/templates/thumbs/075.webp differdiff --git a/templates/thumbs/076.webp b/templates/thumbs/076.webpnew file mode 100644index 0000000..c6a7701Binary files /dev/null and b/templates/thumbs/076.webp differdiff --git a/templates/thumbs/077.webp b/templates/thumbs/077.webpnew file mode 100644index 0000000..61e85bdBinary files /dev/null and b/templates/thumbs/077.webp differdiff --git a/templates/thumbs/078.webp b/templates/thumbs/078.webpnew file mode 100644index 0000000..382d539Binary files /dev/null and b/templates/thumbs/078.webp differdiff --git a/templates/thumbs/079.webp b/templates/thumbs/079.webpnew file mode 100644index 0000000..959a70cBinary files /dev/null and b/templates/thumbs/079.webp differdiff --git a/templates/thumbs/080.webp b/templates/thumbs/080.webpnew file mode 100644index 0000000..a6a448bBinary files /dev/null and b/templates/thumbs/080.webp differdiff --git a/templates/thumbs/081.webp b/templates/thumbs/081.webpnew file mode 100644index 0000000..96822beBinary files /dev/null and b/templates/thumbs/081.webp differdiff --git a/templates/thumbs/082.webp b/templates/thumbs/082.webpnew file mode 100644index 0000000..e8748b6Binary files /dev/null and b/templates/thumbs/082.webp differdiff --git a/templates/thumbs/083.webp b/templates/thumbs/083.webpnew file mode 100644index 0000000..09e3aa2Binary files /dev/null and b/templates/thumbs/083.webp differdiff --git a/templates/thumbs/084.webp b/templates/thumbs/084.webpnew file mode 100644index 0000000..3f3633bBinary files /dev/null and b/templates/thumbs/084.webp differdiff --git a/templates/thumbs/085.webp b/templates/thumbs/085.webpnew file mode 100644index 0000000..07c501eBinary files /dev/null and b/templates/thumbs/085.webp differdiff --git a/templates/thumbs/086.webp b/templates/thumbs/086.webpnew file mode 100644index 0000000..749940eBinary files /dev/null and b/templates/thumbs/086.webp differdiff --git a/templates/thumbs/087.webp b/templates/thumbs/087.webpnew file mode 100644index 0000000..9d0a941Binary files /dev/null and b/templates/thumbs/087.webp differdiff --git a/templates/thumbs/088.webp b/templates/thumbs/088.webpnew file mode 100644index 0000000..54a3cbbBinary files /dev/null and b/templates/thumbs/088.webp differdiff --git a/templates/thumbs/089.webp b/templates/thumbs/089.webpnew file mode 100644index 0000000..b35d328Binary files /dev/null and b/templates/thumbs/089.webp differdiff --git a/templates/thumbs/090.webp b/templates/thumbs/090.webpnew file mode 100644index 0000000..bc10ee8Binary files /dev/null and b/templates/thumbs/090.webp differdiff --git a/templates/thumbs/091.webp b/templates/thumbs/091.webpnew file mode 100644index 0000000..bde64e1Binary files /dev/null and b/templates/thumbs/091.webp differdiff --git a/templates/thumbs/092.webp b/templates/thumbs/092.webpnew file mode 100644index 0000000..bd8048bBinary files /dev/null and b/templates/thumbs/092.webp differdiff --git a/templates/thumbs/093.webp b/templates/thumbs/093.webpnew file mode 100644index 0000000..855b34cBinary files /dev/null and b/templates/thumbs/093.webp differdiff --git a/templates/thumbs/094.webp b/templates/thumbs/094.webpnew file mode 100644index 0000000..87dce27Binary files /dev/null and b/templates/thumbs/094.webp differdiff --git a/templates/thumbs/095.webp b/templates/thumbs/095.webpnew file mode 100644index 0000000..5043887Binary files /dev/null and b/templates/thumbs/095.webp differdiff --git a/templates/thumbs/096.webp b/templates/thumbs/096.webpnew file mode 100644index 0000000..48ac7baBinary files /dev/null and b/templates/thumbs/096.webp differdiff --git a/templates/thumbs/097.webp b/templates/thumbs/097.webpnew file mode 100644index 0000000..9291e09Binary files /dev/null and b/templates/thumbs/097.webp differdiff --git a/templates/thumbs/098.webp b/templates/thumbs/098.webpnew file mode 100644index 0000000..ceeedbcBinary files /dev/null and b/templates/thumbs/098.webp differdiff --git a/templates/thumbs/099.webp b/templates/thumbs/099.webpnew file mode 100644index 0000000..c847b60Binary files /dev/null and b/templates/thumbs/099.webp differdiff --git a/templates/thumbs/100.webp b/templates/thumbs/100.webpnew file mode 100644index 0000000..b89f818Binary files /dev/null and b/templates/thumbs/100.webp differdiff --git a/templates/thumbs/101.webp b/templates/thumbs/101.webpnew file mode 100644index 0000000..c890491Binary files /dev/null and b/templates/thumbs/101.webp differdiff --git a/templates/thumbs/102.webp b/templates/thumbs/102.webpnew file mode 100644index 0000000..fd572e6Binary files /dev/null and b/templates/thumbs/102.webp differdiff --git a/templates/thumbs/103.webp b/templates/thumbs/103.webpnew file mode 100644index 0000000..bf9de15Binary files /dev/null and b/templates/thumbs/103.webp differdiff --git a/templates/thumbs/104.webp b/templates/thumbs/104.webpnew file mode 100644index 0000000..5aca923Binary files /dev/null and b/templates/thumbs/104.webp differdiff --git a/templates/thumbs/105.webp b/templates/thumbs/105.webpnew file mode 100644index 0000000..63d10d7Binary files /dev/null and b/templates/thumbs/105.webp differ