Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

Edit video: kiểu thong-tin-do-hoa (đồ hoạ bảng biểu) + chọn đoạn hay --target

Lumtek1ce298ad1d5d
diff --git a/cli.mjs b/cli.mjs
index e9cf921..b63f023 100644
--- a/cli.mjs
+++ b/cli.mjs
@@ -8,7 +8,7 @@
// node cli.mjs list [--json]
// node cli.mjs show <jobId>
// node cli.mjs templates [--json]
-// node cli.mjs edit <video> --style <id> [--music file] [--content "dặn thêm"] [--names "Lumfin, …"] [--draft] [--llm off] [--json]
+// node cli.mjs edit <video> --style <id> [--music file] [--content "dặn thêm"] [--names "Lumfin, …"] [--target 45] [--draft] [--llm off] [--json]
// node cli.mjs edit-revise <editId> "<lời sửa>" [--file f] · edit-show <editId> · edit-run <editId> · edit-rm <editId>
import fs from 'node:fs';
import path from 'node:path';
@@ -47,10 +47,11 @@ function usage() {
list [--json] danh sách job
show <jobId> trạng thái + log + đường dẫn
templates [--json] mẫu nào đã có guidance
- edit <video> --style <id> [--music file] [--content "dặn thêm"] [--names "tên riêng, …"] [--draft] [--llm off] [--json]
+ edit <video> --style <id> [--music file] [--content "dặn thêm"] [--names "tên riêng, …"] [--target 45] [--draft] [--llm off] [--json]
dựng lại video tự quay theo thẻ kiểu edit (edit-styles/<id>.md) → edits/<id>/out.mp4
cắt ngập ngừng/nói lại (LLM), phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ, sfx, −14 LUFS.
--draft: phụ đề PIL vẽ thẳng (nhanh), mặc định phụ đề HyperFrames. Cài trước: node edit/setup.mjs
+ --target 45: clip dài (5–20 phút) → LLM chọn đoạn hay nhất (hook … kết) thành short ≈ 45 s
edit-revise <editId> "<lời>" | --file <f> sửa bằng lời ("bỏ 3 giây đầu", "zoom ít lại") rồi render lại, không phân tích lại
edit-show <editId> [--json] trạng thái, tiến độ, chữ LLM đã sửa, log
edit-run <editId> chạy 1 edit đã tạo (MCP/REST dùng)
@@ -113,7 +114,7 @@ try {
if (!pos[0]) { usage(); process.exit(2); }
const job = await E.createEdit({ video: pos[0], style: typeof opt.style === 'string' ? opt.style : 'sach-gon', music: typeof opt.music === 'string' ? opt.music : undefined,
content: typeof opt.content === 'string' ? readContent(opt.content) : undefined, names: typeof opt.names === 'string' ? opt.names : undefined,
- draft: !!opt.draft, llm: opt.llm === 'off' ? 'off' : 'on' });
+ draft: !!opt.draft, llm: opt.llm === 'off' ? 'off' : 'on', target: opt.target === undefined || opt.target === true ? undefined : opt.target });
r = await E.runEditJob(job.id, { log });
} else if (cmd === 'edit-run') {
if (!pos[0]) { usage(); process.exit(2); }
diff --git a/docs/CHI-TIET.md b/docs/CHI-TIET.md
index 8eacdf0..02ed5d6 100644
--- a/docs/CHI-TIET.md
+++ b/docs/CHI-TIET.md
@@ -52,8 +52,15 @@ Engine: `api` (có `ANTHROPIC_API_KEY`, model `REWRITE_MODEL`) → `claude` (Cla
Người dùng đưa video tự quay (nói trước máy), chọn **thẻ kiểu edit**; LumReels tự cắt chỗ ngập ngừng/nói lại, thêm phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ khi nói, tiếng động, chỉnh −14 LUFS. Có tab **Edit video của bạn** trên giao diện, CLI, REST và MCP; sửa bằng lời rồi render lại mà không phân tích lại.
- Cài (một lần, chạy lại được): `node edit/setup.mjs [--cpu]` → venv riêng `edit/.venv` (không đụng Python hệ thống; cần Python 3.10–3.12 + ffmpeg), gói Python (~670 MB), cuBLAS + cuDNN nếu có GPU NVIDIA (~2 GB), model mặt/người MediaPipe (21 MB, kiểm SHA-256), font Be Vietnam Pro TTF (ghép từ `engine/fonts`), whisper **large-v3** (~3 GB, vào `~/.cache/huggingface`). Dòng cuối: `READY` / `NEED_PYTHON` / `NEED_FFMPEG` / `NEED_NETWORK` / `NEED_NPM`.
-- Chạy: `node cli.mjs edit <video> --style sach-gon|phu-de-nay-mau [--music nhac.mp3] [--content "dặn thêm"] [--draft] [--llm off] [--json]` → `edits/<id>/`.
-- Thẻ kiểu: `edit-styles/<id>.md` = khối `---json` (preset có version: ngưỡng lặng, số chữ phụ đề, zoom, mật độ, sfx, nhạc) + hướng dẫn cho LLM. Có `sach-gon` (cắt ngập ngừng, phụ đề 2–3 chữ, zoom nhẹ) và `phu-de-nay-mau` (từng chữ nảy màu, zoom 1–2 giây/cú, sfx mỗi cú).
+- Chạy: `node cli.mjs edit <video> --style sach-gon|phu-de-nay-mau|thong-tin-do-hoa [--music nhac.mp3] [--content "dặn thêm"] [--target 45] [--draft] [--llm off] [--json]` → `edits/<id>/`.
+- Thẻ kiểu: `edit-styles/<id>.md` = khối `---json` (preset có version: ngưỡng lặng, số chữ phụ đề, zoom, mật độ, sfx, nhạc) + hướng dẫn cho LLM. Có `sach-gon` (cắt ngập ngừng, phụ đề 2–3 chữ, zoom nhẹ), `phu-de-nay-mau` (từng chữ nảy màu, zoom 1–2 giây/cú, sfx mỗi cú) và `thong-tin-do-hoa` (review phần cứng/giá: phụ đề 2–4 chữ ở 1/3 dưới, số tự tô màu, đồ hoạ bảng biểu, zoom đẩy nhẹ + whoosh/pop khi đồ hoạ vào, nhạc lofi nhẹ mặc định).
+- **Chọn đoạn hay** (`--target <giây>`, 15–180; REST/MCP `target`): clip nguồn dài (5–20 phút) → LLM đọc cả lời chép, chọn các đoạn (đoạn đầu `hook`, cuối `end`, theo thứ tự thời gian, trọn câu) sao cho tổng lời ≈ target (code tính, cho phép 0,8–1,3×; sai thì LLM sửa 1 vòng, vẫn quá dài thì code bỏ bớt đoạn giữa). Chữ ngoài các đoạn → `removed` lý do `trim`; sau đó cắt ngập ngừng như thường (LLM chỉ thấy phần đã chọn). Chưa đảo thứ tự đoạn (keep[] luôn tăng dần).
+- **Lớp đồ hoạ** (`graphics[]` trong EDL, `edit/graphics.mjs`; thẻ kiểu có khối `graphics` mới bật): `counter`, `bar_chart` (2–5 cột mọc theo lời), `compare` (A vs B, dòng hiện dần), `spec_table`, `checklist` (tick dần), `price_tag`/`sticker` (tem dập), `line_chart` (3–7 điểm, đường vẽ dần), `title_card`. Mỗi mục: `type`, `start/end` (giây nguồn, map qua vết cắt như phụ đề), `data` (mốc `at` của từng dòng/cột/điểm cũng là giây nguồn), `estimate`, `box` (px bản ra, đã né mặt), `face` (hợp khung mặt lúc hiện).
+ - LLM lập kế hoạch theo **chỉ số chữ** (đồ hoạ hiện ở chữ `at`, từng dòng ở chữ người nói nhắc tới). Code kiểm: loại/số mục/độ dài chữ; **mọi số trên đồ hoạ (value và số trong nhãn/ô) phải có trong lời** (`edit/numbers.mjs` đọc cả chữ số "12.990.000", "8GB", "6%" lẫn số đọc bằng chữ "mười hai triệu chín trăm", "1 triệu rưỡi", "9 rưỡi"; cho phép đổi đơn vị nghìn/triệu/tỷ), không thì phải `estimate: true` (đồ hoạ ghi "ước tính"); đồ hoạ lớn không chồng nhau, đồ hoạ nhỏ không chồng nhau. Sai → LLM sửa 1 vòng → vẫn sai thì bỏ mục hỏng.
+ - Code giữ mỗi đồ hoạ ≥ 1,5 s bản ra (thêm 0,7 s sau chữ cuối, tối đa 14 s, không lấn đồ hoạ cùng hạng sau; không đủ chỗ thì bỏ + cảnh báo), thêm zoom `push` 1,06× khi đồ hoạ lớn vào (zoom của LLM gần đó nhường), sfx whoosh/pop/stamp/tick.
+ - Né mặt: `lumedit faces <edl>` trả khung đầu (bản ra, sau reframe **và** zoom) mỗi 0,25 s; mỗi đồ hoạ lấy hợp khung trong lúc hiện (+28 px), chọn dải trống lớn nhất trên/dưới mặt trong vùng an toàn và trên phụ đề, thu nhỏ ≥ 0,5× (không vừa → bỏ + cảnh báo). `validateEdl` kiểm lại: trong keep, ≥ 1,5 s, ≤ 1 đồ hoạ lớn cùng lúc, không tràn vùng an toàn, không đè mặt, không đè nhau.
+ - Vẽ: cùng cảnh HyperFrames của phụ đề (`render(t)` thuần theo t qua `VideoScene.define`, phụ đề GSAP `tl.seek(t)`), kính tối bo góc 38 px + 1 màu nhấn (`graphics.accent`), Be Vietnam Pro + Manrope (số, `tabular-nums`), vào bật nảy 0,35 s, ra 0,22 s. Phần "mờ" của kính do `lumedit render` làm mờ video ngay dưới khung đồ hoạ (cùng mốc vào/ra). Bản nháp (`--draft`) vẫn render lớp đồ hoạ.
+ - Sửa bằng lời giữ nguyên kế hoạch đồ hoạ; đồ hoạ có chữ bị cắt thì bỏ.
```
video ─ edit/ingest.mjs : ffprobe đủ (xoay, VFR, HDR, start_time) + SHA-256 → proxy.mov CFR 30 fps, H.264 SDR BT.709,
diff --git a/edit-styles/thong-tin-do-hoa.md b/edit-styles/thong-tin-do-hoa.md
new file mode 100644
index 0000000..0e28257
--- /dev/null
+++ b/edit-styles/thong-tin-do-hoa.md
@@ -0,0 +1,52 @@
+---json
+{
+ "id": "thong-tin-do-hoa",
+ "name": "Thông tin, nhiều đồ hoạ bảng biểu",
+ "version": 1,
+ "order": 3,
+ "pause": 0.3,
+ "cutFillers": true,
+ "captions": { "style": "thong-tin-do-hoa", "maxWords": 4, "position": "lower", "font": "Be Vietnam Pro", "highlightsPerMinute": 8, "numbers": true },
+ "zoom": { "kind": "push", "scale": 1.06, "dur": 2.0, "minGap": 6, "perMinute": [2, 6] },
+ "sfx": { "onZoom": null, "max": 40, "gainDb": -12 },
+ "music": { "gainDb": -24, "duckDb": 10, "fadeOut": 1.5, "default": "chill" },
+ "graphics": {
+ "accent": "#FCE802", "perMinute": [6, 14], "zoom": 1.06,
+ "sfxBig": "whoosh", "sfxSmall": "pop", "sfxStamp": "stamp", "sfxTick": "tick", "sfxGainDb": -11
+ }
+}
+---
+# Thông tin, nhiều đồ hoạ bảng biểu
+
+Cho clip review phần cứng, giá cả, so sánh sản phẩm (người nói về card đồ hoạ, giá, hiệu năng, có máy/bàn phím trong khung). Short 30–60 giây kiểu "thông tin": mỗi con số người nói ra hiện thành đồ hoạ (số đếm, biểu đồ cột, bảng so sánh, bảng thông số, tem giá), người xem nghe một mạch và nhìn thấy số.
+
+## Cắt
+- Bỏ mọi chỗ nói lại (giữ lần sau cùng), câu nói dở, câu chào/giới thiệu kênh dài, câu nói về buổi quay.
+- Bỏ từ đệm "ờ, ừm, à…" đứng riêng. Không bỏ trợ từ cuối câu ("nhá, ạ, nha").
+- Không bao giờ bỏ chữ mang số liệu, tên sản phẩm, đơn vị, phủ định.
+
+## Phụ đề
+- 2–4 chữ một lần ở 1/3 dưới khung, chữ trắng viền đen, chữ số và đơn vị đi kèm ("20 triệu", "16GB") tự tô màu nhấn.
+- Chữ nhấn thêm: tên sản phẩm, từ then chốt ("tăng", "cắt", "hết hàng"). Không nhấn trợ từ.
+- Sửa đúng tên sản phẩm/thuật ngữ máy nghe sai theo danh sách tên riêng (vd "vờ ga" → "VGA", "5060T" → "5060 Ti").
+
+## Đồ hoạ
+- Khi người nói đọc MỘT con số đáng nhớ (giá, %, FPS, dung lượng): `counter` hoặc `price_tag` đúng lúc nói số đó.
+- Khi người nói so 2–5 sản phẩm theo một số (giá, FPS): `bar_chart`, mỗi cột mọc lên đúng lúc nhắc tới sản phẩm đó.
+- Khi so 2 sản phẩm theo nhiều tiêu chí: `compare` (A vs B), dòng hiện khi nói tới tiêu chí.
+- Khi liệt kê thông số (VRAM, xung, công suất, bus): `spec_table`, dòng nổi lên theo lời.
+- Khi kể giá thay đổi qua các mốc (trước/nay/sắp tới): `line_chart`.
+- Khi liệt kê lý do/lời khuyên: `checklist`, tick dần theo từng ý.
+- Khi chuyển sang ý lớn (lý do 1, lý do 2…): `title_card` ngắn.
+- Nhận định mạnh, ngắn ("NGÁO GIÁ", "HẾT HÀNG"): `sticker`.
+- Số phải đúng như người nói. Người nói "9 rưỡi" thì ghi 9,5 triệu; người nói khoảng "22–23" thì ghi đúng khoảng đó trong ô chữ. Không tự cộng/trừ/quy đổi.
+- Không dồn: ít nhất 1 giây trống giữa 2 đồ hoạ lớn, không phải câu nào cũng có đồ hoạ.
+
+## Zoom và tiếng
+- Zoom đẩy nhẹ (1,06×) khi đồ hoạ lớn vào (code tự thêm); ngoài ra rất ít zoom.
+- Đồ hoạ lớn vào kèm "whoosh", số/tem kèm "pop"/"stamp", checklist "tick" mỗi ý (code tự thêm).
+- Nhạc nền nhẹ (lofi) nằm dưới giọng, tự hạ khi nói.
+
+## Tự kiểm
+- Mỗi đồ hoạ có số nào thì người nói đã nói số đó (hoặc ghi "ước tính").
+- Đồ hoạ không đè mặt, không đè phụ đề, chữ không tràn khung.
diff --git a/edit/captions-hf.mjs b/edit/captions-hf.mjs
index 46a2461..2164212 100644
--- a/edit/captions-hf.mjs
+++ b/edit/captions-hf.mjs
@@ -5,6 +5,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { syncLib, runHF } from '../engine/lib.mjs';
import { toOutputNearest, outputDuration, SAFE, OUT } from './edl.mjs';
+import { graphicsScene, GFX_RUNTIME } from './graphics.mjs';
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
@@ -64,13 +65,24 @@ export function cardOverlaps(cards) {
const LOOKS = {
'sach-gon': { font: "'Be Vietnam Pro'", weight: 800, size: 76, upper: false, color: '#FFFFFF', hi: '#FCE802', karaoke: false, cy: 0.70, enter: 'fade' },
+ 'thong-tin-do-hoa': { font: "'Be Vietnam Pro'", weight: 800, size: 68, upper: false, color: '#FFFFFF', hi: '#FCE802', karaoke: false, cy: 0.745, enter: 'pop-soft' },
'phu-de-nay-mau': { font: "'Anton'", weight: 400, size: 150, upper: true, color: '#FFFFFF', hi: '#FCE802', karaoke: true, cy: 0.58, enter: 'pop' },
};
-/** Ghi cảnh vào sceneDir. Trả {duration, cards, box}. */
-export function writeCaptionScene(edl, sceneDir) {
+/** Mép trên (px) của dòng phụ đề kiểu này — đồ hoạ đặt phía trên mép này. */
+export function captionTop(captionStyle) {
+ const look = LOOKS[captionStyle] || LOOKS['sach-gon'];
+ return Math.round(look.cy * OUT.height - 0.6 * look.size * 1.18) - 8;
+}
+
+/**
+ * Ghi cảnh vào sceneDir. Trả {duration, cards, graphics, box}.
+ * opts.captions=false: chỉ lớp đồ hoạ (bản nháp: phụ đề đã vẽ PIL trong nền). opts.accent: màu nhấn của đồ hoạ.
+ */
+export function writeCaptionScene(edl, sceneDir, { captions = true, accent } = {}) {
const look = LOOKS[edl.captions.style] || LOOKS['sach-gon'];
- const cards = captionCards(edl);
+ const cards = captions && edl.captions.words.length ? captionCards(edl) : [];
+ const gfx = (edl.graphics || []).length ? graphicsScene(edl, { accent: accent || look.hi }) : null;
const dur = Math.max(1 / OUT.fps, Math.round(outputDuration(edl.keep) * OUT.fps) / OUT.fps);
const hi = new Set(edl.captions.highlights);
const x0 = Math.round(SAFE.x0 * OUT.width); const w = Math.round((SAFE.x1 - SAFE.x0) * OUT.width);
@@ -87,6 +99,7 @@ export function writeCaptionScene(edl, sceneDir) {
const timeline = cards.map((c, ci) => {
const lines = [`tl.set('#c${ci}', {autoAlpha: 1}, ${c.start.toFixed(3)});`];
if (look.enter === 'pop') lines.push(`tl.fromTo('#c${ci}', {scale: 0.55}, {scale: 1, duration: 0.18, ease: 'back.out(3)'}, ${c.start.toFixed(3)});`);
+ else if (look.enter === 'pop-soft') lines.push(`tl.fromTo('#c${ci}', {scale: 0.86, opacity: 0}, {scale: 1, opacity: 1, duration: 0.14, ease: 'back.out(2.2)'}, ${c.start.toFixed(3)});`);
else lines.push(`tl.fromTo('#c${ci}', {y: 18, opacity: 0}, {y: 0, opacity: 1, duration: 0.12, ease: 'power2.out'}, ${c.start.toFixed(3)});`);
if (look.karaoke && c.words.length > 1) {
c.words.forEach((wd, k) => {
@@ -113,27 +126,37 @@ export function writeCaptionScene(edl, sceneDir) {
-webkit-text-stroke: ${look.upper ? 10 : 8}px #000; paint-order: stroke fill;
text-shadow: 0 6px 18px rgba(0,0,0,.55); max-height:${yMax - cy}px; }
.card .w { display:inline-block; }
- .card .hi { color:${look.hi}; }
+ .card .hi { color:${look.hi}; }${gfx ? gfx.css : ''}
</style>
</head>
<body>
<div id="root" data-composition-id="main" data-start="0" data-duration="${dur.toFixed(3)}" data-fps="${OUT.fps}" data-width="${OUT.width}" data-height="${OUT.height}">
+ ${gfx ? gfx.html : ''}
${html}
</div>
+${gfx ? `<script src="./lib/runtime/scene.js"></script>
<script>
+ const tl = gsap.timeline({ paused: true });
+ tl.set({}, {}, ${dur.toFixed(3)});
+ ${timeline}
+ const G = ${JSON.stringify(gfx.data)};
+ ${GFX_RUNTIME}
+ VideoScene.define({ duration: ${dur.toFixed(3)}, fps: ${OUT.fps}, width: ${OUT.width}, height: ${OUT.height},
+ render(t) { tl.seek(t, false); gfxRender(t, G); } });
+</script>` : `<script>
const tl = gsap.timeline({ paused: true });
tl.set({}, {}, ${dur.toFixed(3)});
${timeline}
window.__timelines = window.__timelines || {};
window.__timelines.main = tl;
-</script>
+</script>`}
</body>
</html>
`;
fs.mkdirSync(sceneDir, { recursive: true });
fs.writeFileSync(path.join(sceneDir, 'index.html'), doc);
syncLib(sceneDir);
- return { duration: dur, cards: cards.length, box: { x0, x1: x0 + w, cy, yMax } };
+ return { duration: dur, cards: cards.length, graphics: (edl.graphics || []).length, box: { x0, x1: x0 + w, cy, yMax } };
}
/** Render lớp chữ trong suốt → WebM VP9 alpha. */
diff --git a/edit/edl.mjs b/edit/edl.mjs
index a565912..803f490 100644
--- a/edit/edl.mjs
+++ b/edit/edl.mjs
@@ -8,15 +8,31 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { z } from 'zod';
+import { graphicsErrors } from './graphics.mjs';
export const EDL_VERSION = 1;
export const OUT = { width: 1080, height: 1920, fps: 30, audioRate: 48000, lufs: -14 };
-export const REMOVE_REASONS = ['pause', 'filler', 'retake', 'false-start', 'aside', 'edge', 'by-hand'];
+export const REMOVE_REASONS = ['pause', 'filler', 'retake', 'false-start', 'aside', 'edge', 'by-hand', 'trim'];
export const SAFE = { x0: 120 / 1080, x1: 960 / 1080, y0: 0.10, y1: 0.80 }; // vùng an toàn Reels/Shorts/TikTok
const sec = z.number().finite().min(0);
const span = z.object({ start: sec, end: sec }).strict();
+// lớp đồ hoạ thông tin (edit/graphics.mjs). Mốc là giây nguồn; data.at và at của từng dòng/cột/điểm cũng là giây nguồn.
+const item = z.object({ at: sec }).passthrough();
+export const GraphicSchema = z.object({
+ id: z.string(),
+ type: z.enum(['counter', 'bar_chart', 'compare', 'spec_table', 'checklist', 'price_tag', 'sticker', 'line_chart', 'title_card']),
+ start: sec, end: sec,
+ estimate: z.boolean().describe('có số suy ra, không nói thẳng → đồ hoạ ghi "ước tính"'),
+ data: z.object({ at: sec, items: z.array(item).optional(), points: z.array(item).optional(), rows: z.array(item).optional() }).passthrough(),
+ box: z.object({ x: z.number(), y: z.number(), w: z.number().positive(), h: z.number().positive(), scale: z.number().min(0.3).max(1) }).strict().nullable()
+ .describe('vị trí trên khung bản ra (px), đã né mặt'),
+ face: z.array(z.number()).length(4).nullable().describe('hợp khung mặt bản ra lúc đồ hoạ hiện (+lề, đã tính push), để kiểm không đè'),
+ squeeze: z.object({ scale: z.number().min(0.5).max(1), anchorY: z.number().min(0).max(OUT.height) }).strict().nullable().default(null)
+ .describe('thu cả khung hình quanh (giữa, anchorY) trong lúc đồ hoạ hiện — cận mặt, không đủ chỗ phía trên'),
+}).strict();
+
export const EdlSchema = z.object({
version: z.literal(EDL_VERSION),
id: z.string().min(1),
@@ -57,6 +73,7 @@ export const EdlSchema = z.object({
music: z.object({
file: z.string(), gainDb: z.number().min(-40).max(0), duckDb: z.number().min(0).max(30), fadeOut: z.number().min(0).max(10),
}).strict().nullable(),
+ graphics: z.array(GraphicSchema).default([]).describe('đồ hoạ bảng biểu (kiểu thong-tin-do-hoa)'),
audio: z.object({ crossfadeMs: z.number().min(5).max(80), keepSourceAudio: z.literal(true) }).strict(),
notes: z.string().optional(),
}).strict();
@@ -126,6 +143,7 @@ export function validateEdl(input, { sfxNames, checkFiles = true } = {}) {
if (sfxNames && !sfxNames.includes(s.name)) add('sfx-name', `sfx.${i}`, `không có tiếng "${s.name}"`);
if (!inKeep(e.keep, s.at)) add('sfx-cut', `sfx.${i}`, `tiếng "${s.name}" ở ${s.at} s rơi vào đoạn bị bỏ`);
});
+ for (const g of graphicsErrors(e)) errors.push(g);
if (checkFiles) {
if (!fs.existsSync(e.proxy.file)) add('file', 'proxy.file', `không thấy proxy ${e.proxy.file}`);
if (e.music && !fs.existsSync(e.music.file)) add('file', 'music.file', `không thấy file nhạc ${e.music.file}`);
diff --git a/edit/edl.schema.json b/edit/edl.schema.json
index 525911d..5007cb4 100644
--- a/edit/edl.schema.json
+++ b/edit/edl.schema.json
@@ -204,7 +204,8 @@
"false-start",
"aside",
"edge",
- "by-hand"
+ "by-hand",
+ "trim"
]
},
"words": {
@@ -421,6 +422,202 @@
}
]
},
+ "graphics": {
+ "default": [],
+ "description": "đồ hoạ bảng biểu (kiểu thong-tin-do-hoa)",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "counter",
+ "bar_chart",
+ "compare",
+ "spec_table",
+ "checklist",
+ "price_tag",
+ "sticker",
+ "line_chart",
+ "title_card"
+ ]
+ },
+ "start": {
+ "type": "number",
+ "minimum": 0
+ },
+ "end": {
+ "type": "number",
+ "minimum": 0
+ },
+ "estimate": {
+ "type": "boolean",
+ "description": "có số suy ra, không nói thẳng → đồ hoạ ghi \"ước tính\""
+ },
+ "data": {
+ "type": "object",
+ "properties": {
+ "at": {
+ "type": "number",
+ "minimum": 0
+ },
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "at": {
+ "type": "number",
+ "minimum": 0
+ }
+ },
+ "required": [
+ "at"
+ ],
+ "additionalProperties": {}
+ }
+ },
+ "points": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "at": {
+ "type": "number",
+ "minimum": 0
+ }
+ },
+ "required": [
+ "at"
+ ],
+ "additionalProperties": {}
+ }
+ },
+ "rows": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "at": {
+ "type": "number",
+ "minimum": 0
+ }
+ },
+ "required": [
+ "at"
+ ],
+ "additionalProperties": {}
+ }
+ }
+ },
+ "required": [
+ "at"
+ ],
+ "additionalProperties": {}
+ },
+ "box": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "x": {
+ "type": "number"
+ },
+ "y": {
+ "type": "number"
+ },
+ "w": {
+ "type": "number",
+ "exclusiveMinimum": 0
+ },
+ "h": {
+ "type": "number",
+ "exclusiveMinimum": 0
+ },
+ "scale": {
+ "type": "number",
+ "minimum": 0.3,
+ "maximum": 1
+ }
+ },
+ "required": [
+ "x",
+ "y",
+ "w",
+ "h",
+ "scale"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "vị trí trên khung bản ra (px), đã né mặt"
+ },
+ "face": {
+ "anyOf": [
+ {
+ "minItems": 4,
+ "maxItems": 4,
+ "type": "array",
+ "items": {
+ "type": "number"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "hợp khung mặt bản ra lúc đồ hoạ hiện (+lề, đã tính push), để kiểm không đè"
+ },
+ "squeeze": {
+ "default": null,
+ "description": "thu cả khung hình quanh (giữa, anchorY) trong lúc đồ hoạ hiện — cận mặt, không đủ chỗ phía trên",
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "scale": {
+ "type": "number",
+ "minimum": 0.5,
+ "maximum": 1
+ },
+ "anchorY": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": 1920
+ }
+ },
+ "required": [
+ "scale",
+ "anchorY"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "type",
+ "start",
+ "end",
+ "estimate",
+ "data",
+ "box",
+ "face"
+ ],
+ "additionalProperties": false
+ }
+ },
"audio": {
"type": "object",
"properties": {
diff --git a/edit/graphics.mjs b/edit/graphics.mjs
new file mode 100644
index 0000000..8242116
--- /dev/null
+++ b/edit/graphics.mjs
@@ -0,0 +1,694 @@
+// Lớp đồ hoạ thông tin (graphics[] trong EDL): counter, bar_chart, compare, spec_table, checklist, price_tag, sticker,
+// line_chart, title_card. Ba phần:
+// 1. LLM chọn đoạn hay (--target) và lập kế hoạch đồ hoạ THEO CHỈ SỐ CHỮ; code kiểm (số phải có trong lời, đúng loại,
+// mốc nằm trong đoạn giữ, đồ hoạ lớn không chồng nhau) — sai thì LLM sửa 1 vòng, vẫn sai thì bỏ mục hỏng.
+// 2. Code đổi chỉ số chữ → giây nguồn (start/end + mốc hiện từng dòng), giữ ≥ 1,5 s, thêm zoom nhẹ + sfx khi vào,
+// rồi đặt vị trí né mặt (khung mặt bản ra, sau reframe + zoom, do `lumedit faces` đo).
+// 3. Vẽ trong cảnh HyperFrames của lớp phụ đề: HTML/SVG, render(t) thuần theo t.
+import { extractNumbers, numbersInText, spokenMatch, fmtVi } from './numbers.mjs';
+import { toOutputNearest, inKeep, OUT, SAFE } from './edl.mjs';
+
+export const GRAPHIC_TYPES = ['counter', 'bar_chart', 'compare', 'spec_table', 'checklist', 'price_tag', 'sticker', 'line_chart', 'title_card'];
+export const BIG = new Set(['bar_chart', 'compare', 'spec_table', 'checklist', 'line_chart', 'title_card']);
+export const MIN_GRAPHIC = 1.5; // giây bản ra
+export const HOLD = 0.7; // giữ thêm sau chữ cuối của đồ hoạ
+export const MAX_GRAPHIC = 14;
+export const ENTER = 0.35; export const LEAVE = 0.22; // khớp với vùng kính mờ vẽ trong lumedit.py
+const W_BIG = 840; const W_SMALL = 620;
+const key = (w) => String(w).toLowerCase().normalize('NFC').replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');
+
+// ---- cỡ chữ vừa ô (ước theo bề rộng ký tự trung bình của Be Vietnam Pro/Manrope đậm) ----------------------------------
+const CHAR = 0.6; const CHAR_UP = 0.7;
+/** Cỡ chữ lớn nhất ≤ max để text vừa widthPx trên `lines` dòng; null nếu phải nhỏ hơn min. */
+export function fitSize(text, widthPx, max, min = 22, { upper = false, lines = 1 } = {}) {
+ const n = Math.max(1, [...String(text)].length);
+ const s = Math.floor((widthPx * lines) / (n * (upper ? CHAR_UP : CHAR)));
+ if (s >= max) return max;
+ return s >= min ? s : null;
+}
+
+// ---- kích thước gốc (chưa thu nhỏ) của từng loại: code dàn trang và HTML dùng chung -----------------------------------
+const HDR = 92;
+export function baseSize(g) {
+ const d = g.data; const hdr = d.title || d.unit ? HDR : 0;
+ switch (g.type) {
+ case 'counter': return { w: W_SMALL, h: d.label ? 250 : 190 };
+ case 'price_tag': return { w: W_SMALL, h: 220 + (d.label ? 50 : 0) + (d.old != null ? 56 : 0) };
+ case 'sticker': return { w: Math.min(W_BIG, 100 + [...d.text].length * 42), h: 130 };
+ case 'title_card': return { w: W_BIG, h: d.kicker ? 270 : 210 };
+ case 'bar_chart': return { w: W_BIG, h: hdr + 60 + 380 };
+ case 'line_chart': return { w: W_BIG, h: hdr + 60 + 340 };
+ case 'compare': return { w: W_BIG, h: hdr + 112 + d.rows.length * 92 + 60 };
+ case 'spec_table': return { w: W_BIG, h: hdr + d.rows.length * 84 + 60 };
+ case 'checklist': return { w: W_BIG, h: hdr + d.items.length * 88 + 60 };
+ default: return { w: W_BIG, h: 300 };
+ }
+}
+
+// ---- 1a. chọn đoạn hay (--target) -------------------------------------------------------------------------------------
+/** Giây bản ra ước cho 1 dải chữ [a..b] khi khoảng lặng bị rút còn ≤ pause. */
+export function speechSeconds(words, a, b, pause = 0.3) {
+ let s = 0;
+ for (let i = a; i <= b; i++) {
+ s += Math.max(0.05, words[i].e - words[i].s);
+ if (i < b) s += Math.min(pause, Math.max(0, words[i + 1].s - words[i].e));
+ }
+ return s;
+}
+
+function linesWithIndex(words, { exclude = null, showSec = true } = {}) {
+ const lines = []; let line = []; let skipped = false;
+ const flush = () => { if (line.length) { lines.push(line.join(' ')); line = []; } };
+ for (let k = 0; k < words.length; k++) {
+ const w = words[k];
+ if (exclude?.has(w.i)) { if (!skipped) { flush(); lines.push('… (đoạn không dùng) …'); skipped = true; } continue; }
+ skipped = false;
+ if (!line.length && showSec) line.push(`(${w.s.toFixed(1)}s)`);
+ line.push(`[${w.i}]${w.w}`);
+ if (/[.?!]$/.test(w.w) || line.length > 18) flush();
+ }
+ flush();
+ return lines.join('\n');
+}
+
+export function buildSelectPrompt({ words, target, style, content, names, duration, errors, previous }) {
+ return `Mày là biên tập viên short dọc tiếng Việt (TikTok/Reels/Shorts). Video nguồn người dùng tự quay dài ${(duration / 60).toFixed(1)} phút.
+Nhiệm vụ: chọn các đoạn HAY NHẤT để ghép thành 1 short khoảng ${target} giây (sau khi rút khoảng lặng), giữ nguyên thứ tự thời gian.
+Chỉ trả về MỘT khối JSON.
+
+# Kiểu edit: ${style.name}
+${style.guide.split('\n## ')[0]}
+
+# Lời dặn của người dùng
+${content?.trim() || '(không có)'}
+
+# Tên riêng đúng
+${names?.length ? names.join(', ') : '(không có)'}
+
+# Lời chép ([i] = số thứ tự chữ, đầu dòng là giây nguồn)
+${linesWithIndex(words)}
+
+# Định dạng trả về
+{
+ "segments": [{"from": <i>, "to": <i>, "role": "hook|body|end", "why": "<ngắn>"}],
+ "notes": "<1 câu: short nói về gì>"
+}
+Luật:
+- Đoạn ĐẦU (role "hook") phải giữ người xem trong 2 giây đầu: câu hỏi gây tò mò, con số gây sốc, nhận định mạnh. Không mở bằng câu chào/giới thiệu kênh.
+- Đoạn CUỐI (role "end") là câu chốt/kết luận/lời khuyên, nghe trọn ý. Không kết giữa câu.
+- Ở giữa (role "body"): các ý chính, ưu tiên chỗ người nói đọc SỐ LIỆU (giá, %, FPS, thông số, so sánh) vì kiểu này có đồ hoạ bảng biểu.
+- Mỗi đoạn bắt đầu ở đầu câu và kết ở cuối câu (≥ 4 chữ). Các đoạn theo thứ tự tăng dần, không chồng nhau.
+- Tổng thời lượng nói ≈ ${target} giây (code tự tính; được phép ${Math.round(target * 0.8)}–${Math.round(target * 1.3)} giây). Bỏ phần chào, lan man, quảng cáo kênh.
+${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;
+}
+
+/** Kiểm lựa chọn đoạn. Trả {errors, clean:{segments}, seconds}. */
+export function checkSelection(sel, words, target, pause = 0.3) {
+ const errors = []; const n = words.length; const segs = [];
+ const raw = Array.isArray(sel?.segments) ? sel.segments : null;
+ if (!raw?.length) return { errors: ['thiếu "segments"'], clean: { segments: [] }, seconds: 0 };
+ let last = -1;
+ for (const s of [...raw].sort((a, b) => a.from - b.from)) {
+ if (!Number.isInteger(s.from) || !Number.isInteger(s.to) || s.from < 0 || s.to >= n || s.from > s.to) { errors.push(`đoạn ${JSON.stringify(s)}: from/to không hợp lệ (0..${n - 1})`); continue; }
+ if (s.from <= last) { errors.push(`đoạn ${s.from}–${s.to} chồng đoạn trước`); continue; }
+ if (s.to - s.from < 3) { errors.push(`đoạn ${s.from}–${s.to} quá ngắn (< 4 chữ)`); continue; }
+ segs.push({ from: s.from, to: s.to, role: ['hook', 'body', 'end'].includes(s.role) ? s.role : 'body', why: String(s.why || '') });
+ last = s.to;
+ }
+ if (segs.length && segs[0].role !== 'hook') errors.push('đoạn đầu phải là "hook"');
+ if (segs.length && segs[segs.length - 1].role !== 'end') errors.push('đoạn cuối phải là "end"');
+ const seconds = segs.reduce((a, s) => a + speechSeconds(words, s.from, s.to, pause), 0);
+ if (seconds < target * 0.8 || seconds > target * 1.3) errors.push(`tổng ${seconds.toFixed(1)} s, cần ${Math.round(target * 0.8)}–${Math.round(target * 1.3)} s (mục tiêu ${target} s)`);
+ return { errors, clean: { segments: segs }, seconds };
+}
+
+/** Lựa chọn còn hỏng sau 2 vòng: giữ đoạn hợp lệ, quá dài thì bỏ bớt đoạn body từ cuối lên. */
+function trimSelection(segs, words, target, pause) {
+ const out = [...segs];
+ const total = () => out.reduce((a, s) => a + speechSeconds(words, s.from, s.to, pause), 0);
+ while (total() > target * 1.3 && out.length > 2) {
+ const k = out.map((s, i) => [s, i]).filter(([s, i]) => s.role === 'body' && i > 0 && i < out.length - 1).pop();
+ if (!k) break;
+ out.splice(k[1], 1);
+ }
+ return out;
+}
+
+/** --target: LLM chọn đoạn → {exclude:Set(chỉ số chữ không dùng), segments, seconds, warnings}. */
+export async function selectSegments({ words, target, style, content, names, duration, callClaude, parse, log = console.log }) {
+ const pause = Math.min(style.pause ?? 0.3, 0.3);
+ let text = ''; let prev = null; const warnings = [];
+ for (let round = 1; round <= 2; round++) {
+ let checked;
+ try {
+ const r = await callClaude(buildSelectPrompt({ words, target, style, content, names, duration, errors: prev?.errors, previous: prev ? text.slice(0, 4000) : '' }), { log });
+ text = r.text;
+ checked = checkSelection(parse(text), words, target, pause);
+ } catch (e) { checked = { errors: [`không đọc được JSON: ${e.message}`], clean: { segments: [] }, seconds: 0 }; }
+ if (!checked.errors.length) { prev = checked; break; }
+ log(` chọn đoạn vòng ${round}: ${checked.errors.slice(0, 3).join('; ')}`);
+ prev = checked;
+ if (round === 2) warnings.push(...checked.errors.map((e) => 'chọn đoạn: ' + e));
+ }
+ let segs = prev.clean.segments;
+ if (!segs.length) throw new Error('LLM không chọn được đoạn nào cho --target');
+ segs = trimSelection(segs, words, target, pause);
+ const keepIdx = new Set();
+ for (const s of segs) for (let i = s.from; i <= s.to; i++) keepIdx.add(i);
+ const exclude = new Set(words.filter((w) => !keepIdx.has(w.i)).map((w) => w.i));
+ const seconds = segs.reduce((a, s) => a + speechSeconds(words, s.from, s.to, pause), 0);
+ return { exclude, segments: segs, seconds, warnings };
+}
+
+// ---- 1b. kế hoạch đồ hoạ --------------------------------------------------------------------------------------------
+export function buildGraphicsPrompt({ words, exclude, style, content, names, errors, previous }) {
+ const g = style.graphics;
+ return `Mày là designer đồ hoạ thông tin cho short dọc tiếng Việt (review phần cứng/công nghệ/tài chính).
+Đọc lời chép (chỉ phần được giữ) và lập kế hoạch đồ hoạ bảng biểu hiện đúng lúc người nói nói tới.
+Chỉ trả về MỘT khối JSON.
+
+# Kiểu edit: ${style.name}
+${style.guide}
+
+# Lời dặn của người dùng
+${content?.trim() || '(không có)'}
+
+# Tên riêng đúng (dùng đúng chính tả này trong nhãn)
+${names?.length ? names.join(', ') : '(không có)'}
+
+# Lời chép ([i] = số thứ tự chữ; đầu dòng là giây nguồn; máy nghe có thể sai chính tả tên riêng)
+${linesWithIndex(words, { exclude })}
+
+# Các loại đồ hoạ (at/until/word là chỉ số chữ [i])
+- counter: số đếm lên khi người nói đọc 1 con số. {"type":"counter","at":i,"until":j,"value":<số>,"prefix":"","suffix":"triệu đ|%|FPS|GB…","label":"<≤ 26 ký tự>"}
+- price_tag: tem giá dập xuống. {"type":"price_tag","at":i,"until":j,"value":<số>,"suffix":"triệu","label":"<tên máy ≤ 24>","old":<giá cũ, tuỳ chọn>}
+- sticker: tem chữ ngắn dập xuống (nhận định mạnh). {"type":"sticker","at":i,"until":j,"text":"<≤ 16 ký tự>"}
+- bar_chart: 2–5 cột so sánh, cột mọc lên lúc người nói nói tới mục đó. {"type":"bar_chart","at":i,"until":j,"title":"<≤ 30>","unit":"triệu","items":[{"label":"<≤ 12>","value":<số>,"word":i}]}
+- line_chart: 3–7 điểm giá lên xuống theo thời gian/mốc. {"type":"line_chart","at":i,"until":j,"title":"<≤ 30>","unit":"triệu","points":[{"label":"<≤ 8>","value":<số>,"word":i}]}
+- compare: bảng A vs B, dòng hiện dần. {"type":"compare","at":i,"until":j,"title":"<≤ 30, tuỳ chọn>","a":"<≤ 12>","b":"<≤ 12>","rows":[{"label":"<≤ 14>","a":"<≤ 12>","b":"<≤ 12>","word":i,"winner":"a|b|null"}]} (1–5 dòng)
+- spec_table: bảng thông số, dòng nổi lên theo chữ. {"type":"spec_table","at":i,"until":j,"title":"<≤ 30>","rows":[{"label":"<≤ 14>","value":"<≤ 14>","word":i}]} (1–6 dòng)
+- checklist: các ý tick dần. {"type":"checklist","at":i,"until":j,"title":"<≤ 30, tuỳ chọn>","items":[{"text":"<≤ 30>","word":i,"ok":true|false}]} (2–5 ý)
+- title_card: thẻ chương khi chuyển ý lớn. {"type":"title_card","at":i,"until":j,"kicker":"<≤ 20, tuỳ chọn>","title":"<≤ 28>"}
+Mọi loại nhận thêm "estimate": true nếu có số KHÔNG được nói thẳng mà mày suy ra (đồ hoạ sẽ ghi "ước tính"). Hạn chế dùng.
+
+# Định dạng trả về
+{ "graphics": [ ... ], "notes": "<1 câu>" }
+
+Luật:
+- SỐ: mọi con số trên đồ hoạ (value, số trong nhãn/ô) phải là số người nói THẬT SỰ nói ra trong lời chép. Không bịa, không làm tròn, không tự tính. Người nói "9 rưỡi" (triệu) → value 9.5, suffix "triệu". Khoảng "22-23" → dùng 1 số đã nói hoặc ghi chữ "22–23" trong ô bảng.
+- MỐC: "at" = chữ đầu tiên của ý đó (đồ hoạ hiện lúc này), "until" = chữ cuối của ý; mỗi dòng/cột/điểm có "word" = chữ người nói nói tới mục đó (at ≤ word ≤ until). Counter/price_tag: "at" là chữ của chính con số.
+- Đồ hoạ LỚN (bar_chart, line_chart, compare, spec_table, checklist, title_card) KHÔNG được chồng thời gian nhau. Đồ hoạ nhỏ (counter, price_tag, sticker) không chồng nhau, có thể hiện cùng 1 đồ hoạ lớn chỉ khi bổ sung cho nó.
+- Mỗi đồ hoạ hiện ít nhất 1,5 giây (code tự giữ thêm ~0,7 s sau "until"). Mật độ ${g.perMinute[0]}–${g.perMinute[1]} đồ hoạ mỗi phút; không phải câu nào cũng cần.
+- Chỉ dùng chữ trong phần được giữ. Nhãn ngắn, viết đúng tên riêng (vd "RTX 5070 Ti"), không viết hoa toàn bộ trừ sticker.
+${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;
+}
+
+/**
+ * Kiểm kế hoạch đồ hoạ. words: toàn bộ chữ (chỉ số = vị trí). usable(i): chữ i còn được giữ.
+ * spoken: các giá trị số trong lời (extractNumbers trên mọi chữ + số trong tên riêng người dùng khai).
+ * Trả {errors, clean:[mục hợp lệ]}.
+ */
+export function checkGraphics(plan, words, usable, spoken) {
+ const errors = []; const clean = [];
+ const list = Array.isArray(plan?.graphics) ? plan.graphics : null;
+ if (!list) return { errors: ['thiếu mảng "graphics"'], clean };
+ const n = words.length;
+ const idx = (i) => Number.isInteger(i) && i >= 0 && i < n;
+ list.forEach((g, gi) => {
+ const errs = []; const where = `graphics[${gi}] (${g?.type})`;
+ const bad = (m) => errs.push(`${where}: ${m}`);
+ if (!g || !GRAPHIC_TYPES.includes(g.type)) { errors.push(`${where}: loại không hợp lệ (có: ${GRAPHIC_TYPES.join(', ')})`); return; }
+ if (!idx(g.at) || !idx(g.until) || g.at > g.until) { errors.push(`${where}: at/until không hợp lệ (0..${n - 1}, at ≤ until)`); return; }
+ if (!usable(g.at) || !usable(g.until)) bad(`at ${g.at}/until ${g.until} rơi vào chữ bị bỏ`);
+ const estimate = g.estimate === true;
+ const numOk = (v, what) => { if (!estimate && !spokenMatch(v, spoken)) bad(`${what} ${v} không có trong lời người nói (không bịa số; nếu suy ra thì "estimate": true)`); };
+ const textOk = (s, what, max, { need = true } = {}) => {
+ const t = typeof s === 'string' || typeof s === 'number' ? String(s).trim() : '';
+ if (!t) { if (need) bad(`thiếu ${what}`); return ''; }
+ if ([...t].length > max) bad(`${what} "${t}" dài quá ${max} ký tự`);
+ for (const v of numbersInText(t)) numOk(v, `số trong ${what} "${t}"`);
+ return t;
+ };
+ const wordOk = (i, what) => {
+ if (!idx(i)) { bad(`${what}: "word" không hợp lệ`); return false; }
+ if (i < g.at || i > g.until) bad(`${what}: word ${i} nằm ngoài at..until (${g.at}..${g.until})`);
+ if (!usable(i)) bad(`${what}: word ${i} rơi vào chữ bị bỏ`);
+ return true;
+ };
+ const num = (v, what) => { const x = Number(v); if (v === null || v === '' || !Number.isFinite(x)) { bad(`${what} phải là số`); return null; } numOk(x, what); return x; };
+ const out = { type: g.type, at: g.at, until: g.until, estimate, data: {} };
+ const d = out.data;
+ switch (g.type) {
+ case 'counter': case 'price_tag': {
+ d.value = num(g.value, 'value');
+ d.prefix = textOk(g.prefix, 'prefix', 6, { need: false });
+ d.suffix = textOk(g.suffix, 'suffix', 10, { need: false });
+ d.label = textOk(g.label, 'label', g.type === 'counter' ? 26 : 24, { need: false });
+ if (g.type === 'price_tag' && g.old != null && g.old !== '') d.old = num(g.old, 'old');
+ break;
+ }
+ case 'sticker': d.text = textOk(g.text, 'text', 16); break;
+ case 'title_card': d.kicker = textOk(g.kicker, 'kicker', 20, { need: false }); d.title = textOk(g.title, 'title', 28); break;
+ case 'bar_chart': case 'line_chart': {
+ const arr = g.type === 'bar_chart' ? g.items : g.points;
+ const [lo, hi] = g.type === 'bar_chart' ? [2, 5] : [3, 7];
+ d.title = textOk(g.title, 'title', 30, { need: false }); d.unit = textOk(g.unit, 'unit', 10, { need: false });
+ if (!Array.isArray(arr) || arr.length < lo || arr.length > hi) { bad(`cần ${lo}–${hi} ${g.type === 'bar_chart' ? 'items' : 'points'}`); break; }
+ d[g.type === 'bar_chart' ? 'items' : 'points'] = arr.map((it, k) => {
+ wordOk(it?.word, `mục ${k}`);
+ return { label: textOk(it?.label, `label mục ${k}`, g.type === 'bar_chart' ? 12 : 8), value: num(it?.value, `value mục ${k}`), word: it?.word, hi: it?.highlight === true };
+ });
+ break;
+ }
+ case 'compare': {
+ d.title = textOk(g.title, 'title', 30, { need: false }); d.a = textOk(g.a, 'a', 12); d.b = textOk(g.b, 'b', 12);
+ if (!Array.isArray(g.rows) || g.rows.length < 1 || g.rows.length > 5) { bad('cần 1–5 rows'); break; }
+ d.rows = g.rows.map((r, k) => { wordOk(r?.word, `dòng ${k}`); return { label: textOk(r?.label, `label dòng ${k}`, 14), a: textOk(r?.a, `a dòng ${k}`, 12), b: textOk(r?.b, `b dòng ${k}`, 12), word: r?.word, winner: ['a', 'b'].includes(r?.winner) ? r.winner : null }; });
+ break;
+ }
+ case 'spec_table': {
+ d.title = textOk(g.title, 'title', 30, { need: false });
+ if (!Array.isArray(g.rows) || g.rows.length < 1 || g.rows.length > 6) { bad('cần 1–6 rows'); break; }
+ d.rows = g.rows.map((r, k) => { wordOk(r?.word, `dòng ${k}`); return { label: textOk(r?.label, `label dòng ${k}`, 14), value: textOk(r?.value, `value dòng ${k}`, 14), word: r?.word }; });
+ break;
+ }
+ case 'checklist': {
+ d.title = textOk(g.title, 'title', 30, { need: false });
+ if (!Array.isArray(g.items) || g.items.length < 2 || g.items.length > 5) { bad('cần 2–5 items'); break; }
+ d.items = g.items.map((r, k) => { wordOk(r?.word, `ý ${k}`); return { text: textOk(r?.text, `text ý ${k}`, 30), word: r?.word, ok: r?.ok !== false }; });
+ break;
+ }
+ default: break;
+ }
+ if (errs.length) { errors.push(...errs); return; }
+ clean.push(out);
+ });
+ // chồng thời gian (theo giây nguồn của chữ; code còn giữ thêm HOLD và kiểm lại theo giây bản ra)
+ const span = (g) => [words[g.at].s, words[g.until].e];
+ const keepClean = [];
+ for (const g of clean.sort((a, b) => a.at - b.at)) {
+ const [s] = span(g);
+ const clash = keepClean.find((o) => (BIG.has(o.type) === BIG.has(g.type)) && span(o)[1] > s - 0.05);
+ if (clash) { errors.push(`${g.type} ở chữ ${g.at} chồng thời gian với ${clash.type} (${clash.at}..${clash.until}); đồ hoạ ${BIG.has(g.type) ? 'lớn' : 'nhỏ'} không được hiện cùng lúc`); continue; }
+ keepClean.push(g);
+ }
+ return { errors, clean: keepClean };
+}
+
+/** Giá trị số người nói ra (mọi chữ, kể cả đoạn không dùng) + số trong tên riêng người dùng khai. */
+export function spokenNumbers(words, names = []) {
+ const vals = extractNumbers(words.map((w) => w.w)).map((x) => x.value);
+ for (const nm of names) vals.push(...numbersInText(nm));
+ return vals;
+}
+
+/** LLM lập kế hoạch đồ hoạ; sai → sửa 1 vòng; vẫn sai → bỏ mục hỏng. */
+export async function planGraphics({ words, dropped, style, content, names, callClaude, parse, log = console.log }) {
+ const usable = (i) => !dropped.has(i);
+ const spoken = spokenNumbers(words, names);
+ let text = ''; let prev = null; const warnings = [];
+ for (let round = 1; round <= 2; round++) {
+ let checked;
+ try {
+ const r = await callClaude(buildGraphicsPrompt({ words, exclude: dropped, style, content, names, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '' }), { log });
+ text = r.text;
+ checked = checkGraphics(parse(text), words, usable, spoken);
+ } catch (e) { checked = { errors: [`không đọc được JSON: ${e.message}`], clean: prev?.clean || [] }; }
+ if (!checked.errors.length) return { graphics: checked.clean, rounds: round, warnings, raw: text };
+ log(` đồ hoạ vòng ${round}: ${checked.errors.length} lỗi: ${checked.errors.slice(0, 3).join('; ')}`);
+ prev = checked;
+ }
+ warnings.push(...prev.errors.map((e) => 'đồ hoạ bỏ mục hỏng: ' + e));
+ return { graphics: prev.clean, rounds: 2, warnings, raw: text };
+}
+
+// ---- 2. kế hoạch (chỉ số chữ) → graphics[] của EDL (giây nguồn) ---------------------------------------------------------
+/**
+ * plan: các mục đã kiểm (state.graphics). keep: đoạn giữ của EDL. Mục nào rơi vào đoạn bỏ (sửa bằng lời cắt mất)
+ * thì bỏ. Kéo dài tới ≥ MIN_GRAPHIC giây bản ra nếu còn chỗ trước đồ hoạ cùng hạng sau; hết chỗ thì bỏ (cảnh báo).
+ * Trả {graphics, zooms, sfx, warnings}.
+ */
+export function compileGraphics({ plan, words, keep, style }) {
+ const warnings = []; const gs = [];
+ const byI = new Map(words.map((w) => [w.i, w]));
+ const outEnd = keep.reduce((a, k) => a + k.end - k.start, 0);
+ const items = [...(plan || [])].sort((a, b) => a.at - b.at);
+ items.forEach((p, n) => {
+ const wa = byI.get(p.at); const wu = byI.get(p.until);
+ if (!wa || !wu || !inKeep(keep, (wa.s + wa.e) / 2)) { warnings.push(`đồ hoạ ${p.type} ở chữ ${p.at}: chữ đã bị bỏ, không hiện`); return; }
+ const t = (i) => { const w = byI.get(i); return w ? +w.s.toFixed(3) : wa.s; };
+ const data = JSON.parse(JSON.stringify(p.data));
+ for (const arr of [data.items, data.points, data.rows]) if (Array.isArray(arr)) for (const it of arr) { it.at = t(it.word); delete it.word; }
+ data.at = +wa.s.toFixed(3);
+ gs.push({ id: `g${n + 1}`, type: p.type, start: +Math.max(0, wa.s - 0.05).toFixed(3), end: +(wu.e + HOLD).toFixed(3), estimate: !!p.estimate, data, box: null, face: null, squeeze: null });
+ });
+ // giây bản ra: ≥ 1,5 s; không vượt đồ hoạ cùng hạng tiếp theo; ≤ 14 s
+ const out = [];
+ for (let k = 0; k < gs.length; k++) {
+ const g = gs[k];
+ const o0 = toOutputNearest(keep, g.start);
+ const next = gs.slice(k + 1).find((x) => BIG.has(x.type) === BIG.has(g.type));
+ const limit = Math.min(outEnd, next ? toOutputNearest(keep, next.start) - 0.05 : outEnd);
+ let o1 = Math.min(toOutputNearest(keep, g.end), limit, o0 + MAX_GRAPHIC);
+ if (o1 - o0 < MIN_GRAPHIC) o1 = Math.min(limit, o0 + MIN_GRAPHIC);
+ if (o1 - o0 < MIN_GRAPHIC - 1e-6) { warnings.push(`đồ hoạ ${g.type} ở ${g.start.toFixed(2)} s: không đủ ${MIN_GRAPHIC} s trước đồ hoạ sau, bỏ`); continue; }
+ g.end = +outputToSource(keep, o1).toFixed(3);
+ g.outStart = +o0.toFixed(3); g.outEnd = +o1.toFixed(3);
+ out.push(g);
+ }
+ // zoom nhẹ khi vào đồ hoạ lớn, tiếng động khi vào
+ const gz = style.graphics;
+ const zooms = out.filter((g) => BIG.has(g.type) && gz.zoom).map((g) => ({ at: g.data.at, dur: +Math.min(8, Math.max(0.6, Math.min(2.4, g.outEnd - g.outStart))).toFixed(3), scale: gz.zoom, kind: 'push' }));
+ const sfx = [];
+ for (const g of out) {
+ const name = BIG.has(g.type) ? gz.sfxBig : ['price_tag', 'sticker'].includes(g.type) ? gz.sfxStamp : gz.sfxSmall;
+ if (name) sfx.push({ at: g.data.at, name, gainDb: gz.sfxGainDb });
+ if (g.type === 'checklist' && gz.sfxTick) for (const it of g.data.items) if (it.at > g.data.at + 0.2) sfx.push({ at: it.at, name: gz.sfxTick, gainDb: gz.sfxGainDb - 4 });
+ }
+ for (const g of out) { delete g.outStart; delete g.outEnd; }
+ return { graphics: out, zooms, sfx, warnings };
+}
+
+/** Giây bản ra → giây nguồn (trong keep). */
+export function outputToSource(keep, o) {
+ let acc = 0;
+ for (const k of keep) { const d = k.end - k.start; if (o <= acc + d + 1e-9) return k.start + Math.max(0, o - acc); acc += d; }
+ return keep[keep.length - 1].end;
+}
+
+// ---- 2b. dàn trang né mặt -------------------------------------------------------------------------------------------------
+const PAD = 20;
+const rectHit = (a, b) => a.x < b[2] && a.x + a.w > b[0] && a.y < b[3] && a.y + a.h > b[1];
+const boxHit = (a, b) => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
+
+export const GOOD_SCALE = 0.8; // dưới mức này chữ trên đồ hoạ khó đọc trên điện thoại → thu hình
+export const MIN_SCALE = 0.5;
+export const MIN_SQUEEZE = 0.62; // thu hình nhỏ nhất (tỉ lệ)
+/** Khung mặt sau khi thu hình k quanh điểm (540, ay). */
+export const squeezeBox = (b, q) => (b && q ? [Math.round(OUT.width / 2 + (b[0] - OUT.width / 2) * q.scale), Math.round(q.anchorY + (b[1] - q.anchorY) * q.scale),
+ Math.round(OUT.width / 2 + (b[2] - OUT.width / 2) * q.scale), Math.round(q.anchorY + (b[3] - q.anchorY) * q.scale)] : b);
+
+/**
+ * Đặt vị trí từng đồ hoạ: lấy hợp khung mặt (bản ra) trong suốt thời gian hiện, chọn dải trống lớn nhất phía trên
+ * hoặc dưới mặt (trong vùng an toàn, trên phụ đề), thu nhỏ cho vừa.
+ * Cận mặt (dải trống quá hẹp, đồ hoạ phải thu < 0,8×): THU HÌNH `squeeze` {scale, anchorY} trong lúc đồ hoạ hiện —
+ * lumedit thu cả khung hình quanh điểm (giữa, cằm) nên cằm đứng yên, đỉnh đầu hạ xuống, phần trống lấp bằng chính hình
+ * đó làm mờ tối — để đồ hoạ có chỗ ở cỡ đọc được mà mặt không xuống dưới phụ đề.
+ * Đồ hoạ nhỏ hiện cùng lúc dùng chung khung mặt đã thu của đồ hoạ đang hiện.
+ * faces: {step, boxes:[[t,[x0,y0,x1,y1]|null]]}. captionTop: px mép trên phụ đề. Ghi g.box, g.face, g.squeeze. Trả warnings.
+ */
+export function layoutGraphics(graphics, keep, faces, captionTop) {
+ const warnings = [];
+ const Y0 = Math.round(SAFE.y0 * OUT.height) + 8; const Y1 = Math.min(captionTop - 24, Math.round(SAFE.y1 * OUT.height));
+ const X0 = Math.round(SAFE.x0 * OUT.width); const X1 = Math.round(SAFE.x1 * OUT.width);
+ const placed = [];
+ const out = [];
+ for (const g of graphics) {
+ const o0 = toOutputNearest(keep, g.start); const o1 = toOutputNearest(keep, g.end);
+ let fb = null;
+ for (const [t, b] of faces?.boxes || []) {
+ if (!b || t < o0 - 0.15 || t > o1 + 0.15) continue;
+ fb = fb ? [Math.min(fb[0], b[0]), Math.min(fb[1], b[1]), Math.max(fb[2], b[2]), Math.max(fb[3], b[3])] : [...b];
+ }
+ const face0 = fb ? [Math.max(0, fb[0] - PAD), Math.max(0, fb[1] - PAD), Math.min(OUT.width, fb[2] + PAD), Math.min(OUT.height, fb[3] + PAD)] : null;
+ const over = placed.filter((p) => p.o0 < o1 - 1e-3 && p.o1 > o0 + 1e-3);
+ const inherited = over.find((p) => p.squeeze)?.squeeze || null; // đang có đồ hoạ thu hình: mặt đã ở chỗ mới
+ const { w, h } = baseSize(g);
+ const fit = (face) => {
+ let bands = [[Y0, Y1]];
+ const blockers = [];
+ if (face && face[2] > X0 && face[0] < X1) blockers.push([face[1], face[3]]);
+ for (const p of over) blockers.push([p.box.y - 16, p.box.y + p.box.h + 16]);
+ for (const [b0, b1] of blockers) bands = bands.flatMap(([a, b]) => (b1 <= a || b0 >= b ? [[a, b]] : [[a, Math.min(b, b0)], [Math.max(a, b1), b]].filter(([x, y]) => y - x > 40)));
+ let best = null;
+ for (const [a, b] of bands) {
+ const s = Math.min(1, (b - a) / h, (X1 - X0) / w);
+ if (!best || s > best.s + 1e-6) best = { a, b, s };
+ }
+ return best;
+ };
+ let squeeze = null; let face = squeezeBox(face0, inherited);
+ let best = fit(face);
+ if (face0 && !inherited && !over.length && (!best || best.s < GOOD_SCALE)) {
+ // thu hình quanh (giữa, cằm): đỉnh đầu hạ xuống ay − (ay − top)·k; cần đỉnh đầu ≥ Y0 + cỡ đồ hoạ
+ const ay = Math.min(face0[3], Y1);
+ for (const s of [1, 0.92, 0.85, GOOD_SCALE]) {
+ const k = (ay - Y0 - s * h - 12) / Math.max(1, ay - face0[1]);
+ if (k >= MIN_SQUEEZE && k < 1 && s * w <= X1 - X0) { squeeze = { scale: +Math.min(0.97, k).toFixed(3), anchorY: ay }; break; }
+ }
+ if (squeeze) { face = squeezeBox(face0, squeeze); best = fit(face); }
+ }
+ if (!best || best.s < MIN_SCALE) { warnings.push(`đồ hoạ ${g.type} ở ${o0.toFixed(1)} s: không đủ chỗ né mặt (${best ? 'chỉ thu được ' + best.s.toFixed(2) : 'không còn dải trống'}), bỏ`); continue; }
+ const s = +best.s.toFixed(3);
+ const bw = Math.round(w * s); const bh = Math.round(h * s);
+ // dải phía trên mặt: dính sát dưới (gần mặt); dải dưới mặt: dính sát trên; không có mặt: giữa dải
+ let y;
+ if (face && best.b <= face[1] + 1) y = Math.round(best.b - bh);
+ else if (face && best.a >= face[3] - 1) y = Math.round(best.a);
+ else y = Math.round((best.a + best.b - bh) / 2);
+ const box = { x: Math.round(OUT.width / 2 - bw / 2), y, w: bw, h: bh, scale: s };
+ g.box = box; g.face = face; g.squeeze = squeeze;
+ placed.push({ o0, o1, box, squeeze: squeeze || inherited });
+ out.push(g);
+ }
+ graphics.length = 0; graphics.push(...out);
+ return warnings;
+}
+
+/** Kiểm lớp đồ hoạ của EDL (gọi từ validateEdl). */
+export function graphicsErrors(edl) {
+ const errs = []; const add = (p, m) => errs.push({ code: 'graphic', path: p, msg: m });
+ const keep = edl.keep; const gs = edl.graphics || [];
+ const X0 = SAFE.x0 * OUT.width - 1; const X1 = SAFE.x1 * OUT.width + 1; const Y0 = SAFE.y0 * OUT.height - 1; const Y1 = SAFE.y1 * OUT.height + 1;
+ const T = gs.map((g) => [toOutputNearest(keep, g.start), toOutputNearest(keep, g.end)]);
+ gs.forEach((g, i) => {
+ const p = `graphics.${i}`;
+ if (!inKeep(keep, g.data.at ?? g.start)) add(p, `đồ hoạ ${g.type} ở ${g.start} s rơi vào đoạn bị bỏ`);
+ if (T[i][1] - T[i][0] < MIN_GRAPHIC - 1e-3) add(p, `đồ hoạ ${g.type} chỉ hiện ${(T[i][1] - T[i][0]).toFixed(2)} s (< ${MIN_GRAPHIC} s)`);
+ if (!g.box) { add(p, `đồ hoạ ${g.type} chưa có vị trí`); return; }
+ const b = g.box;
+ if (b.x < X0 || b.x + b.w > X1 || b.y < Y0 || b.y + b.h > Y1) add(p, `đồ hoạ ${g.type} tràn vùng an toàn (${b.x},${b.y} ${b.w}×${b.h})`);
+ if (g.face && rectHit(b, g.face)) add(p, `đồ hoạ ${g.type} đè mặt`);
+ for (let k = 0; k < i; k++) {
+ const o = gs[k];
+ if (!(T[k][0] < T[i][1] - 1e-3 && T[k][1] > T[i][0] + 1e-3)) continue;
+ if (BIG.has(o.type) && BIG.has(g.type)) add(p, `2 đồ hoạ lớn cùng lúc (${o.type} và ${g.type})`);
+ if (o.squeeze && g.squeeze) add(p, `2 đồ hoạ cùng thu hình (${o.type} và ${g.type})`);
+ if (o.box && boxHit(o.box, b)) add(p, `đồ hoạ ${g.type} đè ${o.type}`);
+ }
+ });
+ return errs;
+}
+
+// ---- 3. vẽ (HyperFrames, render(t) thuần) -------------------------------------------------------------------------------
+const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
+const decimalsOf = (v) => (Number.isInteger(v) ? 0 : Math.min(2, (String(v).split('.')[1] || '').length));
+
+/** HTML tĩnh của 1 đồ hoạ (cỡ gốc). Phần chuyển động do GFX_RUNTIME đặt theo t. */
+function graphicHtml(g, k) {
+ const d = g.data; const { w, h } = baseSize(g);
+ const est = g.estimate ? '<div class="est">ước tính</div>' : '';
+ const htxt = (d.title || '') + (d.unit ? ` · ${d.unit}` : '');
+ const head = d.title || d.unit ? `<div class="hdr" style="font-size:${fitSize(htxt, w - 220, 40, 24) || 24}px">${esc(d.title || '')}${d.unit ? `<span class="u">${d.title ? ' · ' : ''}${esc(d.unit)}</span>` : ''}</div>` : '';
+ const inner = w - 64;
+ let body = '';
+ switch (g.type) {
+ case 'counter': {
+ const big = fitSize(`${d.prefix}${fmtVi(d.value)}${d.suffix ? ' ' + d.suffix : ''}`, inner, 112, 48);
+ body = `${d.label ? `<div class="lbl">${esc(d.label)}</div>` : ''}<div class="num big" style="font-size:${big || 48}px"><span>${esc(d.prefix)}</span><span class="v" data-v="${d.value}" data-dec="${decimalsOf(d.value)}">${fmtVi(d.value)}</span>${d.suffix ? `<span class="suf">${/^[%°]/.test(d.suffix) ? "" : " "}${esc(d.suffix)}</span>` : ''}</div>`;
+ break;
+ }
+ case 'price_tag': {
+ const big = fitSize(`${d.prefix}${fmtVi(d.value)} ${d.suffix}`, inner - 40, 104, 44);
+ body = `<div class="tag">${d.label ? `<div class="lbl dark">${esc(d.label)}</div>` : ''}${d.old != null ? `<div class="old num">${fmtVi(d.old)} ${esc(d.suffix)}</div>` : ''}<div class="num big dark" style="font-size:${big || 44}px">${esc(d.prefix)}${fmtVi(d.value)}<span class="suf">${/^[%°]/.test(d.suffix) ? "" : " "}${esc(d.suffix)}</span></div><div class="hole"></div></div>`;
+ break;
+ }
+ case 'sticker': body = `<div class="stk" style="font-size:${fitSize(d.text.toUpperCase(), w - 70, 62, 36, { upper: true }) || 36}px">${esc(d.text.toUpperCase())}</div>`; break;
+ case 'title_card': body = `<div class="bar"></div>${d.kicker ? `<div class="kick">${esc(d.kicker)}</div>` : ''}<div class="ttl" style="font-size:${fitSize(d.title, inner - 30, 70, 40, { lines: 1 }) || 40}px">${esc(d.title)}</div>`; break;
+ case 'bar_chart': {
+ const n = d.items.length; const gap = 28; const cw = Math.floor((inner - gap * (n - 1)) / n);
+ const maxV = Math.max(...d.items.map((x) => Math.abs(x.value))) || 1;
+ const hiIdx = d.items.some((x) => x.hi) ? null : d.items.findIndex((x) => x.value === Math.max(...d.items.map((y) => y.value)));
+ body = `${head}<div class="bars">${d.items.map((it, j) => {
+ const vs = `${fmtVi(it.value)}`;
+ return `<div class="col" style="width:${cw}px"><div class="bv num" style="font-size:${fitSize(vs + (d.unit ? ' ' : ''), cw, 40, 22) || 22}px"><span class="v" data-v="${it.value}" data-dec="${decimalsOf(it.value)}">${vs}</span></div>`
+ + `<div class="bt"><div class="bf${it.hi || j === hiIdx ? ' acc' : ''}" data-h="${Math.round(256 * Math.abs(it.value) / maxV)}"></div></div>`
+ + `<div class="bl" style="font-size:${fitSize(it.label, cw, 28, 18, { lines: 2 }) || 18}px">${esc(it.label)}</div></div>`;
+ }).join('')}</div>`;
+ break;
+ }
+ case 'line_chart': {
+ const P = d.points; const cw = inner; const ch = 270; const vals = P.map((p) => p.value);
+ const lo = Math.min(...vals); const hi = Math.max(...vals); const pad = (hi - lo) * 0.18 || Math.abs(hi) * 0.1 || 1;
+ const y = (v) => Math.round(30 + (ch - 50) * (1 - (v - (lo - pad)) / ((hi + pad) - (lo - pad))));
+ const x = (j) => Math.round(72 + (cw - 144) * (P.length === 1 ? 0.5 : j / (P.length - 1)));
+ g._pts = P.map((p, j) => [x(j), y(p.value)]);
+ body = `${head}<svg class="lc" width="${cw}" height="${ch + 70}" viewBox="0 0 ${cw} ${ch + 70}">
+ ${[0, 1, 2, 3].map((q) => `<line x1="0" x2="${cw}" y1="${30 + q * (ch - 50) / 3}" y2="${30 + q * (ch - 50) / 3}" class="grid"/>`).join('')}
+ <path class="area" d=""/><path class="line" d=""/>
+ ${P.map((p, j) => `<g class="pt" data-j="${j}"><circle cx="${x(j)}" cy="${y(p.value)}" r="11"/><text class="pv num" x="${x(j)}" y="${y(p.value) - 24}" text-anchor="middle">${fmtVi(p.value)}</text><text class="px" x="${x(j)}" y="${ch + 52}" text-anchor="middle">${esc(p.label)}</text></g>`).join('')}
+ </svg>`;
+ break;
+ }
+ case 'compare': body = `${head}<div class="cmp-h"><div class="cn" style="font-size:${fitSize(d.a, 290, 38, 22) || 22}px">${esc(d.a)}</div><div class="vs">VS</div><div class="cn" style="font-size:${fitSize(d.b, 290, 38, 22) || 22}px">${esc(d.b)}</div></div>`
+ + d.rows.map((r) => `<div class="row cmp"><div class="ca num${r.winner === 'a' ? ' win' : ''}" style="font-size:${fitSize(r.a, 280, 36, 20) || 20}px">${esc(r.a)}</div><div class="cl" style="font-size:${fitSize(r.label, 200, 25, 16) || 16}px">${esc(r.label)}</div><div class="cb num${r.winner === 'b' ? ' win' : ''}" style="font-size:${fitSize(r.b, 280, 36, 20) || 20}px">${esc(r.b)}</div></div>`).join('');
+ break;
+ case 'spec_table': body = head + d.rows.map((r) => `<div class="row spec"><div class="sl" style="font-size:${fitSize(r.label, 360, 30, 18) || 18}px">${esc(r.label)}</div><div class="sv num" style="font-size:${fitSize(r.value, 380, 38, 20) || 20}px">${esc(r.value)}</div></div>`).join(''); break;
+ case 'checklist': body = head + d.items.map((r) => `<div class="row chk"><svg class="cb" width="52" height="52" viewBox="0 0 52 52"><rect x="3" y="3" width="46" height="46" rx="12"/><path class="${r.ok ? 'tick' : 'cross'}" d="${r.ok ? 'M14 27 L23 36 L39 17' : 'M16 16 L36 36 M36 16 L16 36'}"/></svg><div class="ct" style="font-size:${fitSize(r.text, inner - 90, 32, 20) || 20}px">${esc(r.text)}</div></div>`).join(''); break;
+ default: break;
+ }
+ const b = g.box;
+ const solid = ['price_tag', 'sticker'].includes(g.type);
+ return `<div class="gw" id="g${k}" style="left:${b.x}px;top:${b.y}px;width:${b.w}px;height:${b.h}px"><div class="g ${g.type}${solid ? ' solid' : ''}" style="width:${w}px;height:${h}px;transform:scale(${b.scale})">${est}${body}</div></div>`;
+}
+
+/** Phần chèn vào cảnh phụ đề: {css, html, data, runtime}. look.accent = màu nhấn duy nhất. */
+export function graphicsScene(edl, { accent = '#FCE802' } = {}) {
+ const gs = edl.graphics || [];
+ const keep = edl.keep;
+ const html = gs.map((g, k) => graphicHtml(g, k)).join('\n ');
+ const data = gs.map((g) => {
+ const tt = (s) => +toOutputNearest(keep, s).toFixed(3);
+ const d = g.data;
+ const items = (d.items || d.points || d.rows || []).map((it) => tt(it.at));
+ const pts = g._pts || null; delete g._pts;
+ return { type: g.type, t0: tt(g.start), t1: tt(g.end), at: tt(d.at ?? g.start), items, pts };
+ });
+ const css = `
+ .gw { position:absolute; visibility:hidden; opacity:0; transform-origin:50% 50%; }
+ .g { position:absolute; left:0; top:0; transform-origin:0 0; box-sizing:border-box; padding:30px 32px; border-radius:38px; color:#fff;
+ font-family:'Be Vietnam Pro', sans-serif; font-weight:700; overflow:hidden;
+ background:linear-gradient(160deg, rgba(34,38,48,.80), rgba(10,12,17,.74)); border:2px solid rgba(255,255,255,.14);
+ box-shadow:0 22px 60px rgba(0,0,0,.38), inset 0 1px 0 rgba(255,255,255,.16); }
+ .g.solid { background:none; border:none; box-shadow:none; padding:0; overflow:visible; }
+ .num { font-family:'Manrope', sans-serif; font-weight:800; font-variant-numeric:tabular-nums; letter-spacing:-0.01em; }
+ .est { position:absolute; right:26px; top:22px; font-size:22px; font-weight:600; padding:4px 14px; border-radius:99px; border:1.5px solid ${accent}; color:${accent}; }
+ .hdr { font-weight:800; line-height:1.15; height:${HDR - 30}px; white-space:nowrap; padding-right:150px; }
+ .lbl { font-size:32px; font-weight:600; opacity:.78; white-space:nowrap; margin-bottom:6px; }
+ .lbl.dark, .num.dark { color:#111; opacity:1; }
+ .big { line-height:1.08; white-space:nowrap; color:#fff; }
+ .big .suf, .suf { color:${accent}; font-size:.52em; font-weight:800; }
+ .counter .big .v { color:${accent}; }
+ .hdr .u { color:${accent}; font-weight:700; font-size:.8em; }
+ .bars { display:flex; gap:28px; align-items:flex-end; height:380px; }
+ .col { display:flex; flex-direction:column; align-items:center; height:380px; justify-content:flex-end; }
+ .bv { height:52px; line-height:52px; white-space:nowrap; }
+ .bt { width:100%; display:flex; align-items:flex-end; }
+ .bf { width:100%; height:0; border-radius:16px 16px 6px 6px; background:rgba(255,255,255,.34); }
+ .bf.acc { background:${accent}; box-shadow:0 0 30px ${accent}55; }
+ .bl { height:70px; box-sizing:border-box; padding-top:10px; text-align:center; line-height:1.15; font-weight:600; opacity:.9; }
+ .lc .grid { stroke:rgba(255,255,255,.10); stroke-width:2; }
+ .lc .line { fill:none; stroke:${accent}; stroke-width:7; stroke-linecap:round; stroke-linejoin:round; }
+ .lc .area { fill:${accent}; opacity:.14; stroke:none; }
+ .lc circle { fill:#11141b; stroke:${accent}; stroke-width:6; }
+ .lc .pv { fill:#fff; font-size:30px; } .lc .px { fill:rgba(255,255,255,.72); font-size:24px; font-family:'Be Vietnam Pro'; font-weight:600; }
+ .row { display:flex; align-items:center; box-sizing:border-box; }
+ .cmp-h { display:flex; align-items:center; height:96px; margin-bottom:14px; border-bottom:2px solid rgba(255,255,255,.12); }
+ .cmp-h .cn { width:300px; text-align:center; font-weight:800; white-space:nowrap; }
+ .cmp-h .vs { width:176px; text-align:center; font-weight:800; font-size:30px; color:#111; }
+ .cmp-h .vs { background:${accent}; border-radius:99px; height:54px; line-height:54px; width:96px; margin:0 40px; }
+ .row.cmp { height:92px; }
+ .cmp .ca, .cmp .cb { width:300px; text-align:center; white-space:nowrap; }
+ .cmp .cl { width:176px; text-align:center; opacity:.68; font-weight:600; line-height:1.15; }
+ .cmp .win { color:${accent}; }
+ .row.spec { height:84px; justify-content:space-between; border-bottom:2px solid rgba(255,255,255,.09); padding-left:20px; position:relative; }
+ .row.spec::before { content:''; position:absolute; left:0; top:24px; bottom:24px; width:6px; border-radius:4px; background:${accent}; }
+ .spec .sl { opacity:.72; font-weight:600; white-space:nowrap; } .spec .sv { white-space:nowrap; }
+ .row.chk { height:88px; gap:24px; }
+ .chk .cb rect { fill:rgba(255,255,255,.08); stroke:rgba(255,255,255,.35); stroke-width:3; }
+ .chk .cb path { fill:none; stroke-width:7; stroke-linecap:round; stroke-linejoin:round; }
+ .chk .cb .tick { stroke:${accent}; } .chk .cb .cross { stroke:rgba(255,255,255,.55); }
+ .chk .ct { font-weight:600; white-space:nowrap; }
+ .g.title_card { display:flex; flex-direction:column; justify-content:center; }
+ .title_card .bar { position:absolute; left:0; top:0; bottom:0; width:14px; background:${accent}; }
+ .title_card .kick { color:${accent}; font-size:30px; font-weight:800; letter-spacing:.06em; text-transform:uppercase; margin:0 0 10px 16px; }
+ .title_card .ttl { font-weight:800; line-height:1.12; margin-left:16px; white-space:nowrap; }
+ .tag { position:relative; background:${accent}; border-radius:30px 30px 30px 30px; padding:26px 36px 26px 76px; box-shadow:0 18px 44px rgba(0,0,0,.40); }
+ .tag .hole { position:absolute; left:26px; top:50%; width:26px; height:26px; margin-top:-13px; border-radius:50%; background:rgba(0,0,0,.55); }
+ .tag .old { color:#111; opacity:.6; font-size:36px; text-decoration:line-through; text-decoration-thickness:4px; }
+ .tag .suf { color:#111; }
+ .stk { display:inline-block; background:${accent}; color:#111; font-weight:800; padding:22px 36px; border-radius:22px; white-space:nowrap; line-height:1.1; box-shadow:0 16px 40px rgba(0,0,0,.42); border:5px solid #111; }`;
+ return { css, html, data };
+}
+
+/** Hàm vẽ chạy trong trang: G = graphicsScene().data. Thuần theo t. */
+export const GFX_RUNTIME = String.raw`
+function gfxRender(t, G) {
+ var clamp = function (x) { return x < 0 ? 0 : x > 1 ? 1 : x; };
+ var prog = function (t, a, d) { return clamp((t - a) / d); };
+ var outCubic = function (x) { return 1 - Math.pow(1 - x, 3); };
+ var outBack = function (x) { var c = 1.9, c3 = c + 1; return 1 + c3 * Math.pow(x - 1, 3) + c * Math.pow(x - 1, 2); };
+ var fmt = function (v, dec) { var s = Math.abs(v).toFixed(dec).split('.'); return (v < 0 ? '\u2212' : '') + s[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.') + (s[1] ? ',' + s[1] : ''); };
+ for (var k = 0; k < G.length; k++) {
+ var g = G[k], el = document.getElementById('g' + k);
+ if (!(t >= g.t0 && t < g.t1)) { el.style.visibility = 'hidden'; el.style.opacity = 0; continue; }
+ el.style.visibility = 'visible';
+ var u = t - g.t0, stamp = g.type === 'price_tag' || g.type === 'sticker';
+ var a = Math.min(prog(t, g.t0, 0.15), clamp((g.t1 - t) / ${LEAVE}));
+ var s, rot = 0;
+ if (stamp) { var q = prog(t, g.t0, 0.26); s = q < 1 ? 1.65 - 0.65 * outCubic(q) - Math.sin(q * Math.PI) * 0.04 : 1; rot = g.type === 'sticker' ? -5 : -3; }
+ else s = 0.86 + 0.14 * outBack(prog(t, g.t0, ${ENTER}));
+ s *= 1 - 0.04 * (1 - clamp((g.t1 - t) / ${LEAVE}));
+ el.style.opacity = a;
+ el.style.transform = 'scale(' + s.toFixed(4) + ') rotate(' + rot + 'deg)';
+ var vs = el.querySelectorAll('.v');
+ if (g.type === 'counter') {
+ var v = vs[0], k1 = outCubic(prog(t, g.at, 0.9));
+ v.textContent = fmt(Number(v.dataset.v) * k1, Number(v.dataset.dec));
+ }
+ if (g.type === 'bar_chart') {
+ var bf = el.querySelectorAll('.bf'), bl = el.querySelectorAll('.bl'), bv = el.querySelectorAll('.bv');
+ for (var j = 0; j < bf.length; j++) {
+ var kb = prog(t, g.items[j], 0.55), e = kb > 0 ? outBack(kb) : 0;
+ bf[j].style.height = Math.max(0, Number(bf[j].dataset.h) * e).toFixed(1) + 'px';
+ bv[j].style.opacity = prog(t, g.items[j] + 0.1, 0.2); bl[j].style.opacity = 0.35 + 0.65 * prog(t, g.items[j], 0.2);
+ vs[j].textContent = fmt(Number(vs[j].dataset.v) * outCubic(kb), Number(vs[j].dataset.dec));
+ }
+ }
+ if (g.type === 'compare' || g.type === 'spec_table' || g.type === 'checklist') {
+ var rows = el.querySelectorAll('.row');
+ for (var r = 0; r < rows.length; r++) {
+ var kr = outCubic(prog(t, g.items[r], 0.32));
+ rows[r].style.opacity = kr; rows[r].style.transform = 'translateY(' + ((1 - kr) * 26).toFixed(1) + 'px)';
+ if (g.type === 'checklist') {
+ var p = rows[r].querySelector('path'), kt = prog(t, g.items[r] + 0.12, 0.28);
+ p.style.strokeDasharray = 80; p.style.strokeDashoffset = (80 * (1 - outCubic(kt))).toFixed(1);
+ }
+ if (g.type === 'compare') { var w = rows[r].querySelectorAll('.win'); for (var x = 0; x < w.length; x++) w[x].style.transform = 'scale(' + (1 + 0.12 * Math.sin(Math.PI * prog(t, g.items[r] + 0.3, 0.3))).toFixed(3) + ')'; }
+ }
+ }
+ if (g.type === 'line_chart') {
+ var P = g.pts, d = '', ar = '', last = null, base = 270 - 20;
+ for (var i = 0; i < P.length; i++) {
+ var kp = prog(t, g.items[i], 0.45);
+ var pt = el.querySelector('.pt[data-j="' + i + '"]');
+ if (kp <= 0) { pt.style.opacity = 0; continue; }
+ var px = P[i][0], py = P[i][1];
+ if (last) { var e2 = outCubic(kp); px = last[0] + (P[i][0] - last[0]) * e2; py = last[1] + (P[i][1] - last[1]) * e2; }
+ d += (d ? ' L' : 'M') + px.toFixed(1) + ' ' + py.toFixed(1);
+ ar += (ar ? ' L' : 'M') + px.toFixed(1) + ' ' + (ar ? py.toFixed(1) : base + ' L' + px.toFixed(1) + ' ' + py.toFixed(1));
+ last = [px, py];
+ pt.style.opacity = prog(t, g.items[i] + 0.3, 0.15);
+ if (kp < 1) break;
+ }
+ el.querySelector('.line').setAttribute('d', d);
+ el.querySelector('.area').setAttribute('d', last ? ar + ' L' + last[0].toFixed(1) + ' ' + base + ' Z' : '');
+ }
+ if (g.type === 'title_card') {
+ var kc = outCubic(prog(t, g.t0, 0.45));
+ el.querySelector('.bar').style.transform = 'scaleY(' + kc.toFixed(3) + ')';
+ el.querySelector('.ttl').style.transform = 'translateX(' + (-(1 - kc) * 40).toFixed(1) + 'px)';
+ }
+ }
+}`;
+
+/** Chữ nhấn số cho phụ đề: chữ có chữ số, và đơn vị/hệ số đứng ngay sau chữ số. */
+const UNIT_AFTER = new Set(['nghìn', 'ngàn', 'triệu', 'tỷ', 'tỉ', 'k', 'đ', 'đồng', '%', 'phần', 'trăm', 'rưỡi', 'fps', 'gb', 'w', 'mhz', 'ghz']);
+export function numberHighlights(capWords) {
+ const out = [];
+ capWords.forEach((w, k) => {
+ if (/\d/.test(w.w)) out.push(w.i);
+ else if (k && /\d/.test(capWords[k - 1].w) && UNIT_AFTER.has(key(w.w))) out.push(w.i);
+ });
+ return out;
+}
diff --git a/edit/http.mjs b/edit/http.mjs
index 2f4ba05..6a3513f 100644
--- a/edit/http.mjs
+++ b/edit/http.mjs
@@ -2,8 +2,8 @@
// ở đây chặn thêm Origin lạ cho mọi lệnh ghi (trang web khác không gửi form upload/đường dẫn/xoá vào được).
// GET /api/edit-options → {ready, missing, setup, styles[], music[], maxUploadBytes}
// GET /api/edits → danh sách
-// POST /api/edits → multipart (video ≤ 2 GB, music?, style, musicStyle?, content?, names?, draft?)
-// hoặc JSON {path, style, music?(đường dẫn|tên nhạc tổng hợp), content?, names?, draft?}
+// POST /api/edits → multipart (video ≤ 2 GB, music?, style, musicStyle?, content?, names?, draft?, target?)
+// hoặc JSON {path, style, music?(đường dẫn|tên nhạc tổng hợp), content?, names?, draft?, target?}
// GET /api/edits/:id → trạng thái, tiến độ, log, chữ LLM đã sửa, các lần sửa
// POST /api/edits/:id/revise → {instruction}: LLM sửa EDL theo lời, render lại, không phân tích lại
// DELETE /api/edits/:id → xoá hẳn thư mục edits/<id>
@@ -183,7 +183,7 @@ export async function handleEditRoute(req, res, p, { send, readBody, serveFile,
const job = await createEdit({
id, video: files.video.path, sourceName: files.video.filename, style: fields.style, music,
musicName: files.music?.filename || (fields.musicStyle && fields.musicStyle !== 'none' ? `nhạc tổng hợp ${fields.musicStyle}` : null),
- content: fields.content, names: fields.names, draft: fields.draft === '1' || fields.draft === 'true',
+ content: fields.content, names: fields.names, draft: fields.draft === '1' || fields.draft === 'true', target: fields.target,
});
runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));
send(res, 202, editView(job.id));
@@ -204,7 +204,7 @@ export async function handleEditRoute(req, res, p, { send, readBody, serveFile,
let music = null; let musicName = null;
if (body.music && MUSIC_STYLES.includes(body.music)) { fs.mkdirSync(editDir(id), { recursive: true }); music = synthMusicFile(id, body.music); musicName = `nhạc tổng hợp ${body.music}`; }
else if (body.music && body.music !== 'none') music = body.music;
- const job = await createEdit({ id, video: body.path, style: body.style, music, musicName, content: body.content ?? body.notes, names: body.names, draft: !!body.draft, llm: body.llm });
+ const job = await createEdit({ id, video: body.path, style: body.style, music, musicName, content: body.content ?? body.notes, names: body.names, draft: !!body.draft, llm: body.llm, target: body.target });
runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));
send(res, 202, editView(job.id));
} catch (e) {
diff --git a/edit/jobs.mjs b/edit/jobs.mjs
index 9351a27..958a810 100644
--- a/edit/jobs.mjs
+++ b/edit/jobs.mjs
@@ -95,15 +95,25 @@ export async function createEdit(input) {
if (music && (!fs.existsSync(music) || !fs.statSync(music).isFile())) throw new Error(`không thấy file nhạc ${input.music}`);
const info = await checkMedia(video, music);
const content = String(input.content || '').slice(0, 2000);
+ const target = parseTarget(input.target);
+ if (target && target >= info.duration) throw Object.assign(new Error(`--target ${target} s không ngắn hơn video (${Math.round(info.duration)} s)`), { code: 400 });
return writeJob(id, {
status: 'queued', action: 'edit', step: null, stepIndex: -1, stepTotal: STEPS.length, pct: 0, note: '',
source: video, sourceName: input.sourceName || path.basename(video), sourceSeconds: +info.duration.toFixed(2),
style, music, musicName: input.musicName || (music ? path.basename(music) : null),
- content, names: parseNames(input.names), draft: !!input.draft, llm: input.llm === 'off' ? 'off' : 'on',
+ content, names: parseNames(input.names), draft: !!input.draft, llm: input.llm === 'off' ? 'off' : 'on', target,
createdAt: new Date().toISOString(), error: null, out: null, pid: process.pid,
});
}
+/** --target (giây của short muốn ra): rỗng → null; số nguyên 15–180, sai → throw 400. */
+export function parseTarget(v) {
+ if (v === undefined || v === null || v === '' || v === false) return null;
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < 15 || n > 180) throw Object.assign(new Error('target phải là số giây 15–180 (vd 45)'), { code: 400 });
+ return Math.round(n);
+}
+
// ---- khoá toàn máy ------------------------------------------------------------------------------------------------
function tryCreate(file, data) {
try { fs.writeFileSync(file, data, { flag: 'wx' }); return true; } catch (e) { if (e.code === 'EEXIST') return false; throw e; }
@@ -189,7 +199,7 @@ export async function runEditJob(id, { log = () => {} } = {}) {
let r;
try {
r = await editVideo(job.source, {
- id, style: job.style, music: job.music, content: job.content, names: job.names, draft: job.draft, llm: job.llm, log, progress: onProgress(id),
+ id, style: job.style, music: job.music, content: job.content, names: job.names, draft: job.draft, llm: job.llm, target: job.target, log, progress: onProgress(id),
});
} catch (e) { r = { ok: false, id, error: e.message }; }
const freed = cleanupEdit(id);
diff --git a/edit/numbers.mjs b/edit/numbers.mjs
new file mode 100644
index 0000000..a4421f8
--- /dev/null
+++ b/edit/numbers.mjs
@@ -0,0 +1,103 @@
+// Số trong lời nói tiếng Việt: rút mọi giá trị số người nói THẬT SỰ nói ra (chữ số "12.990.000", "8GB", "6%",
+// lẫn số đọc bằng chữ "mười hai triệu chín trăm", "một triệu rưỡi", "50 nghìn") để kiểm đồ hoạ không bịa số,
+// và định dạng số kiểu Việt (1.234.567 · 12,99).
+
+const DIGIT = { 'không': 0, 'một': 1, 'mốt': 1, 'hai': 2, 'ba': 3, 'bốn': 4, 'tư': 4, 'năm': 5, 'lăm': 5, 'nhăm': 5, 'sáu': 6, 'bảy': 7, 'bẩy': 7, 'tám': 8, 'chín': 9 };
+const MULT = { 'nghìn': 1e3, 'ngàn': 1e3, 'k': 1e3, 'triệu': 1e6, 'tr': 1e6, 'củ': 1e6, 'tỷ': 1e9, 'tỉ': 1e9 };
+const norm = (w) => String(w).toLowerCase().normalize('NFC').replace(/^[^\p{L}\p{N}%]+|[^\p{L}\p{N}%]+$/gu, '');
+
+/** "12.990.000" → 12990000 · "12,99" → 12.99 · "1.5" → 1.5 · "4060" → 4060. null nếu không phải số. */
+export function parseDigits(s) {
+ const m = /^(\d{1,3}(?:[.,]\d{3})+|\d+(?:[.,]\d+)?)/.exec(s);
+ if (!m) return null;
+ const raw = m[1];
+ // nhóm nghìn: 12.990.000 / 300.000 / 1.500 (đúng 3 chữ số sau mỗi dấu); còn lại dấu là phần thập phân
+ const v = /^\d{1,3}([.,]\d{3})+$/.test(raw) ? Number(raw.replace(/[.,]/g, '')) : Number(raw.replace(',', '.'));
+ return Number.isFinite(v) ? { value: v, rest: s.slice(raw.length) } : null;
+}
+
+/**
+ * Mọi giá trị số trong dãy chữ. Trả mảng {value, from, to} (chỉ số chữ trong mảng đầu vào).
+ * Gồm: từng số đứng riêng, số ghép với hệ số (nghìn/triệu/tỷ/rưỡi), số đọc bằng chữ, và 2 số liền nhau ghép chữ số
+ * ("40 60" → 4060, tên card hay bị máy nghe tách).
+ */
+export function extractNumbers(words) {
+ const toks = words.map(norm);
+ const out = [];
+ const push = (value, from, to) => { if (Number.isFinite(value)) out.push({ value: +value.toPrecision(12), from, to }); };
+ let k = 0;
+ while (k < toks.length) {
+ const t = toks[k];
+ const d = parseDigits(t);
+ const isWordNum = DIGIT[t] !== undefined || t === 'mười' || t === 'mươi' || t === 'trăm';
+ if (!d && !isWordNum) { k++; continue; }
+ // một cụm số: chữ số / chữ đọc số / hệ số liền nhau
+ // prev: 'digit' (vừa có chữ số đơn) | 'tens' | 'hundred' | 'mult' | 'linh'
+ let total = 0; let cur = 0; let last = 0; let lastMult = 0; let j = k; let any = false; let prev = '';
+ for (; j < toks.length; j++) {
+ const w = toks[j];
+ const dg = parseDigits(w);
+ if (dg) {
+ if (any && prev === 'digit') break; // "40 60", "2 năm": 2 số liền nhau, không phải 1 cụm
+ push(dg.value, j, j);
+ cur += dg.value; last = dg.value; any = true; lastMult = 0; prev = 'digit';
+ const unit = norm(dg.rest);
+ if (MULT[unit]) { total = total < MULT[unit] ? (total + (cur || 1)) * MULT[unit] : total + (cur || 1) * MULT[unit]; cur = 0; lastMult = MULT[unit]; prev = 'mult'; }
+ continue;
+ }
+ if (DIGIT[w] !== undefined) {
+ if (any && prev === 'digit') break;
+ if (w === 'năm' && !any) {
+ // "năm" còn là "năm (year)": đứng đầu thì chỉ là số khi theo sau là mươi/trăm/hệ số
+ const nx = toks[j + 1];
+ if (!(nx in MULT || nx === 'mươi' || nx === 'trăm')) break;
+ }
+ if ((w === 'tư' || w === 'không') && !any) break;
+ cur += DIGIT[w]; last = DIGIT[w]; any = true; lastMult = 0; prev = 'digit'; continue;
+ }
+ if (w === 'mười') { if (any && prev === 'digit') break; cur += 10; last = 10; any = true; lastMult = 0; prev = 'tens'; continue; }
+ if (w === 'mươi' && prev === 'digit') { cur = cur - last + last * 10; last *= 10; prev = 'tens'; continue; }
+ if (w === 'trăm' && prev === 'digit') { cur = cur - last + last * 100; last *= 100; lastMult = 100; prev = 'hundred'; continue; }
+ if ((w === 'linh' || w === 'lẻ') && prev === 'hundred') { prev = 'linh'; continue; }
+ if (MULT[w] && any && prev !== 'mult') {
+ total = total < MULT[w] ? (total + cur) * MULT[w] : total + cur * MULT[w];
+ cur = 0; last = 0; lastMult = MULT[w]; prev = 'mult'; continue;
+ }
+ if ((w === 'rưỡi' || w === 'rưởi') && lastMult) { total += lastMult / 2; lastMult = 0; prev = 'x'; continue; }
+ if ((w === 'rưỡi' || w === 'rưởi') && prev === 'digit') { cur += 0.5; prev = 'x'; continue; } // "9 rưỡi" (triệu ngầm hiểu)
+ break;
+ }
+ if (any) {
+ const v = total + cur;
+ push(v, k, Math.max(k, j - 1));
+ if (cur && total) push(cur, k, j - 1);
+ }
+ // 2 số chữ số liền nhau → ghép ("40" "60" → 4060)
+ const a = parseDigits(toks[k]); const b = parseDigits(toks[k + 1] || '');
+ if (a && b && /^\d+$/.test(toks[k]) && /^\d+$/.test(toks[k + 1])) push(Number(toks[k] + toks[k + 1]), k, k + 1);
+ k = Math.max(k + 1, j);
+ }
+ return out;
+}
+
+/** Số rút từ 1 chuỗi chữ (nhãn, ô bảng do LLM viết). */
+export const numbersInText = (s) => extractNumbers(String(s).split(/\s+/).filter(Boolean)).map((x) => x.value);
+
+/** v có "được nói ra" không: trùng 1 giá trị trong lời (cho phép đổi đơn vị nghìn/triệu/tỷ). */
+export function spokenMatch(v, spoken) {
+ if (!Number.isFinite(v)) return false;
+ const eq = (a, b) => Math.abs(a - b) <= 1e-6 * Math.max(1, Math.abs(b));
+ for (const s of spoken) {
+ if (eq(v, s)) return true;
+ for (const m of [1e3, 1e6, 1e9]) if (eq(v * m, s) || eq(v, s * m)) return true;
+ }
+ return false;
+}
+
+/** Định dạng kiểu Việt: 12990000 → "12.990.000", 12.99 → "12,99". */
+export function fmtVi(v, decimals = null) {
+ if (!Number.isFinite(v)) return String(v);
+ const dec = decimals ?? (Number.isInteger(v) ? 0 : Math.min(2, (String(v).split('.')[1] || '').length));
+ const [i, f] = Math.abs(v).toFixed(dec).split('.');
+ return (v < 0 ? '−' : '') + i.replace(/\B(?=(\d{3})+(?!\d))/g, '.') + (f ? ',' + f : '');
+}
diff --git a/edit/pipeline.mjs b/edit/pipeline.mjs
index 66eeb40..72dd02e 100644
--- a/edit/pipeline.mjs
+++ b/edit/pipeline.mjs
@@ -18,12 +18,15 @@ import { ROOT, runLumedit } from './env.mjs';
import { ingest, makeProxy } from './ingest.mjs';
import {
loadStyle, wordList, propose, compileEdl, parseNames, proposeRevision, applyOverrides, applyExtraCuts, outputCutToSource,
+ callClaude, parseProposal,
} from './planner.mjs';
+import { selectSegments, planGraphics, layoutGraphics } from './graphics.mjs';
import { validateEdl, toOutputNearest, outputDuration, OUT } from './edl.mjs';
-import { writeCaptionScene, renderCaptionLayer } from './captions-hf.mjs';
+import { writeCaptionScene, renderCaptionLayer, captionTop } from './captions-hf.mjs';
import { buildEditMix } from './audio.mjs';
export const EDITS = path.join(ROOT, 'edits');
+const wordKey = (w) => w.toLowerCase().normalize('NFC').replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');
/** Các bước (để UI vẽ thanh tiến độ). Sửa bằng lời bắt đầu từ "LLM lập EDL". */
export const STEPS = ['nạp', 'phân tích', 'LLM lập EDL', 'xem trước', 'render nền', 'phụ đề', 'tiếng', 'ghép', 'kiểm'];
@@ -51,7 +54,8 @@ function runner(dir, opts) {
}
/**
- * Dựng mới. opts: {style, music?, content?, names?, draft?, llm?: 'on'|'off', id?, log?, progress?}
+ * Dựng mới. opts: {style, music?, content?, names?, draft?, llm?: 'on'|'off', target?: giây, id?, log?, progress?}
+ * target: clip nguồn dài → LLM chọn các đoạn hay nhất (hook … kết) ghép thành short ≈ target giây, rồi mới cắt ngập ngừng.
* Trả {ok, id, dir, out, edl, timings, checks, warnings, error?}
*/
export async function editVideo(video, opts = {}) {
@@ -83,17 +87,48 @@ export async function editVideo(video, opts = {}) {
const words = wordList(an.data);
style.hesitations = new Set(an.data.hesitations || []);
- const plan = await step('LLM lập EDL', () => propose({ words, style, content: opts.content, names, duration: ing.source.duration, llm: opts.llm || 'on', log }));
+ const target = opts.target ? Math.round(Number(opts.target)) : null;
+ const llmOn = (opts.llm || 'on') !== 'off';
+ let selection = null;
+ const plan = await step('LLM lập EDL', async (pg) => {
+ if (target && !llmOn) warnings.push('--target cần LLM: bỏ qua (LLM tắt)');
+ else if (target && ing.source.duration < target * 1.15) log(` nguồn ${ing.source.duration.toFixed(0)} s đã gần ${target} s: không chọn đoạn`);
+ else if (target) {
+ pg(5, 'chọn đoạn hay');
+ selection = await selectSegments({ words, target, style, content: opts.content, names, duration: ing.source.duration, callClaude, parse: parseProposal, log });
+ warnings.push(...selection.warnings);
+ log(` chọn ${selection.segments.length} đoạn ≈ ${selection.seconds.toFixed(1)} s nói: ${selection.segments.map((x) => `${x.role} ${words[x.from].s.toFixed(1)}–${words[x.to].e.toFixed(1)} s`).join(', ')}`);
+ }
+ pg(35, 'cắt ngập ngừng');
+ const p = await propose({ words, style, content: opts.content, names, duration: ing.source.duration, llm: opts.llm || 'on', log, exclude: selection?.exclude });
+ if (style.graphics && llmOn) {
+ pg(70, 'kế hoạch đồ hoạ');
+ const dropped = new Set(selection?.exclude || []);
+ for (const d of p.proposal.drop) for (let i = d.from; i <= d.to; i++) dropped.add(i);
+ if (style.cutFillers) for (const w of words) if (style.hesitations.has(wordKey(w.w))) dropped.add(w.i);
+ const gp = await planGraphics({ words, dropped, style, content: opts.content, names, callClaude, parse: parseProposal, log });
+ p.graphics = gp.graphics; p.warnings.push(...gp.warnings);
+ log(` đồ hoạ (vòng ${gp.rounds}): ${gp.graphics.map((g) => `${g.type}@${words[g.at].s.toFixed(1)}s`).join(', ') || 'không có'}`);
+ }
+ return p;
+ });
fs.writeFileSync(path.join(dir, 'proposal.json'), JSON.stringify({ ...plan, words: words.map((w) => `${w.i}:${w.w}${w.unsure ? '?' : ''}`) }, null, 1));
warnings.push(...plan.warnings);
log(` đề xuất (vòng ${plan.rounds}): bỏ ${plan.proposal.drop.length} khoảng, ${plan.proposal.zooms.length} zoom, ${plan.proposal.highlights.length} chữ nhấn, ${plan.proposal.fixes.length} chữ sửa${plan.proposal.notes ? ' · ' + plan.proposal.notes : ''}`);
+ // kiểu có nhạc mặc định (vd thong-tin-do-hoa: lofi nhẹ) mà người dùng không chọn nhạc → nhạc tổng hợp, lặp theo độ dài
+ let music = opts.music ? path.resolve(opts.music) : null;
+ if (!music && style.music?.default) {
+ const { writeMusic, MUSIC_STYLES } = await import('../engine/audio/music.mjs');
+ if (MUSIC_STYLES.includes(style.music.default)) { music = writeMusic(style.music.default, path.join(dir, `music-${style.music.default}.wav`), 60, 1); log(` nhạc nền mặc định của kiểu: ${style.music.default}`); }
+ }
const state = {
- version: 1, style: style.id, music: opts.music ? path.resolve(opts.music) : null, content: opts.content || '', names,
+ version: 1, style: style.id, music, content: opts.content || '', names,
draft: !!opts.draft, llm: opts.llm || 'on', proposal: plan.proposal, overrides: {}, extraCuts: [], revisions: [],
+ target, segments: selection?.segments || null, exclude: selection ? [...selection.exclude] : [], graphics: plan.graphics || [],
};
fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(state, null, 1));
- const edl = buildEdl({ id, ing, analysis: an.data, words, style, state, checks, log });
+ const edl = await buildEdl({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });
const r = await renderEdl({ dir, edl, draft: state.draft, R, outName: 'out.mp4' });
fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify({ ...state, out: 'out.mp4' }, null, 1));
Object.assign(result, r, { ok: true });
@@ -105,17 +140,40 @@ export async function editVideo(video, opts = {}) {
return result;
}
-/** state (đề xuất + núm kiểu + cắt thêm) → EDL đã kiểm, ghi edl.json. */
-function buildEdl({ id, ing, analysis, words, style, state, checks, log }) {
+/** state (đề xuất + núm kiểu + cắt thêm + đồ hoạ) → EDL đã kiểm (đồ hoạ đã đặt né mặt). */
+async function buildEdl({ id, dir, ing, analysis, words, style, state, checks, warnings, log }) {
const st = applyOverrides(style, state.overrides);
const byI = new Map(words.map((w) => [w.i, w.w]));
checks.fixes = state.proposal.fixes.map((f) => ({ word: f.word, heard: byI.get(f.word), text: f.text }));
if (checks.fixes.length) log(` chữ LLM sửa (cần người xem lại): ${checks.fixes.map((f) => `${f.heard} → ${f.text || '(ẩn)'}`).join(', ')}`);
- let edl = compileEdl({ id, ingestRes: ing, analysis, words, proposal: state.proposal, style: st, music: state.music, draft: state.draft });
+ let edl = compileEdl({ id, ingestRes: ing, analysis, words, proposal: state.proposal, style: st, music: state.music, draft: state.draft,
+ exclude: state.exclude || [], graphics: state.graphics || [] });
+ const gw = edl._warnings || []; delete edl._warnings;
edl = applyExtraCuts(edl, state.extraCuts);
+ if (edl.graphics.length) {
+ // đồ hoạ: đo khung mặt bản ra (sau reframe + zoom) rồi đặt né mặt, phía trên phụ đề
+ const inK = (t) => edl.keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6);
+ edl.graphics = edl.graphics.filter((g) => inK(g.data.at));
+ const tmp = path.join(dir, 'edl.faces.json');
+ fs.writeFileSync(tmp, JSON.stringify(edl));
+ const facesFile = path.join(dir, 'faces-out.json');
+ const fr = await runLumedit(['faces', tmp, '--out', facesFile, '--step', '0.25']);
+ fs.rmSync(tmp, { force: true });
+ if (!fr.ok) throw new Error('đo khung mặt cho đồ hoạ lỗi: ' + fr.error);
+ const faces = JSON.parse(fs.readFileSync(facesFile, 'utf8'));
+ gw.push(...layoutGraphics(edl.graphics, edl.keep, faces, captionTop(edl.captions.style)));
+ checks.graphics = {
+ count: edl.graphics.length, faceFound: faces.found_share,
+ items: edl.graphics.map((g) => ({ type: g.type, at: +toOutputNearest(edl.keep, g.start).toFixed(2), until: +toOutputNearest(edl.keep, g.end).toFixed(2), estimate: g.estimate, box: g.box, faceAvoided: !!g.face })),
+ dropped: gw,
+ };
+ log(` đồ hoạ: ${edl.graphics.map((g) => `${g.type} ${toOutputNearest(edl.keep, g.start).toFixed(1)}–${toOutputNearest(edl.keep, g.end).toFixed(1)} s @y${g.box.y}×${g.box.scale}`).join(', ')}`);
+ }
+ for (const w of gw) { log(' ' + w); warnings?.push(w); }
const v = validateEdl(edl, { sfxNames: SFX_NAMES });
if (!v.ok) throw new Error('EDL không hợp lệ: ' + v.errors.map((e) => `${e.code} ${e.path}: ${e.msg}`).join('; '));
const outDur = outputDuration(edl.keep);
+ if (state.segments) checks.selection = { target: state.target, segments: state.segments.map((x) => ({ role: x.role, from: x.from, to: x.to, why: x.why })) };
checks.edl = { keep: edl.keep.length, removed: edl.removed.length, removedSeconds: +(ing.source.duration - outDur).toFixed(2), outSeconds: +outDur.toFixed(2), zooms: edl.zooms.length, sfx: edl.sfx.length, captionWords: edl.captions.words.length };
log(` EDL: ${ing.source.duration.toFixed(2)} s → ${outDur.toFixed(2)} s, ${edl.keep.length} đoạn giữ, ${edl.zooms.length} zoom, ${edl.sfx.length} sfx`);
for (const r of edl.removed) log(` bỏ ${r.start.toFixed(2)}–${r.end.toFixed(2)} s (${r.reason})${r.words ? ': ' + r.words : ''}`);
@@ -151,9 +209,12 @@ async function renderEdl({ dir, edl, draft, R, outName = 'out.mp4' }) {
let overlay = null;
await step('phụ đề', async (pg) => {
- if (draft || !edl.captions.words.length) { pg(100, draft ? 'phụ đề nháp đã vẽ trong nền' : 'không có chữ'); return; }
- const sc = writeCaptionScene(edl, path.join(dir, 'captions'));
- checks.captions = { cards: sc.cards, overlaps: 0, box: sc.box, safeZone: 'trong 120–960 px, đáy ≤ 80% khung' };
+ const hasGfx = (edl.graphics || []).length > 0;
+ if ((draft || !edl.captions.words.length) && !hasGfx) { pg(100, draft ? 'phụ đề nháp đã vẽ trong nền' : 'không có chữ'); return; }
+ let accent;
+ try { accent = loadStyle(edl.style).graphics?.accent; } catch { /* kiểu đã bị xoá: màu mặc định */ }
+ const sc = writeCaptionScene(edl, path.join(dir, 'captions'), { captions: !draft, accent });
+ checks.captions = { cards: sc.cards, graphics: sc.graphics, overlaps: 0, box: sc.box, safeZone: 'trong 120–960 px, đáy ≤ 80% khung' };
overlay = await renderCaptionLayer(path.join(dir, 'captions'), path.join(dir, 'captions.webm'), { log, onPct: (p) => pg(p, 'HyperFrames') });
});
@@ -226,6 +287,7 @@ export async function reviseEdit(id, instruction, opts = {}) {
log(`sửa lần ${n}: "${instruction}"`);
const rev = await step('LLM lập EDL', () => proposeRevision({
words, edl: curEdl, proposal: state.proposal, style: applyOverrides(style, state.overrides), overrides: state.overrides, instruction, names: state.names, log,
+ exclude: new Set(state.exclude || []),
}));
const newCuts = rev.cutsOut.flatMap((c) => outputCutToSource(curEdl.keep, c.start, c.end, words));
log(` LLM: ${rev.notes || '(không ghi chú)'}${newCuts.length ? ` · cắt thêm ${newCuts.map((c) => `${c.start.toFixed(2)}–${c.end.toFixed(2)} s nguồn`).join(', ')}` : ''}`);
@@ -243,7 +305,7 @@ export async function reviseEdit(id, instruction, opts = {}) {
await makeProxy(ing.source.file, ing.info, ing.proxy.file, { log });
log(` dựng lại proxy từ nguồn: ${((Date.now() - t) / 1000).toFixed(1)} s`);
}
- const edl = buildEdl({ id, ing, analysis, words, style, state: next, checks, log });
+ const edl = await buildEdl({ id, dir, ing, analysis, words, style, state: next, checks, warnings, log });
const outName = `out-r${n}.mp4`;
next.revisions = [...(state.revisions || []), { n, instruction, notes: rev.notes, at: new Date().toISOString(), previous: state.out || 'out.mp4', out: outName }];
const r = await renderEdl({ dir, edl, draft: state.draft, R, outName });
@@ -260,3 +322,6 @@ export async function reviseEdit(id, instruction, opts = {}) {
fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ ...prevResult, ...(result.ok ? result : {}), lastRevise: { ok: result.ok, error: result.error || null, at: new Date().toISOString() } }, null, 2));
return result;
}
+
+// cho script kiểm thử: dựng lại EDL + render từ state.json đã có (không gọi LLM, không phân tích lại)
+export const _internal = { buildEdl, renderEdl, runner };
diff --git a/edit/planner.mjs b/edit/planner.mjs
index 6e83a2d..a8e7549 100644
--- a/edit/planner.mjs
+++ b/edit/planner.mjs
@@ -7,6 +7,7 @@ import { spawnClaude, findClaude } from '../generator/claude.mjs';
import { MODEL_IDS } from '../generator/config.mjs';
import { ROOT } from './env.mjs';
import { EDL_VERSION, OUT, REMOVE_REASONS, toOutput, outputDuration } from './edl.mjs';
+import { compileGraphics, numberHighlights } from './graphics.mjs';
export const STYLES_DIR = path.join(ROOT, 'edit-styles');
const LLM_TIMEOUT_MS = 6 * 60 * 1000;
@@ -46,15 +47,17 @@ export function wordList(analysis) {
return merged.map((w, i) => ({ ...w, i }));
}
-function transcriptText(words) {
- const lines = []; let line = [];
+function transcriptText(words, exclude = null) {
+ const lines = []; let line = []; let skipped = false;
const flush = () => { if (line.length) { lines.push(line.join(' ')); line = []; } };
for (let k = 0; k < words.length; k++) {
const w = words[k];
+ if (exclude?.has(w.i)) { if (!skipped) { flush(); lines.push('… (đoạn không dùng cho short, đã bỏ) …'); skipped = true; } continue; }
+ skipped = false;
if (!line.length) line.push(`(${w.s.toFixed(2)}s)`);
line.push(`[${w.i}]${w.w}${w.unsure ? '?' : ''}`);
const nx = words[k + 1];
- const gap = nx ? nx.s - w.e : 0;
+ const gap = nx && !exclude?.has(nx.i) ? nx.s - w.e : 0;
if (gap >= 0.6) { flush(); lines.push(`… lặng ${gap.toFixed(1)} s …`); }
else if (/[.?!]$/.test(w.w) || line.length > 16) flush();
}
@@ -62,7 +65,7 @@ function transcriptText(words) {
return lines.join('\n');
}
-export function buildPrompt({ words, style, content, names, duration, errors, previous }) {
+export function buildPrompt({ words, style, content, names, duration, errors, previous, exclude }) {
const sfx = style.sfxNames.join(', ');
return `Mày là biên tập viên video ngắn tiếng Việt. Video người dùng tự quay, nói trước máy, dài ${duration.toFixed(1)} giây.
Nhiệm vụ: đọc lời chép (có số thứ tự từng chữ) và quyết theo THẺ KIỂU EDIT: bỏ đoạn nào, nhấn chữ nào, zoom và đặt tiếng động ở chữ nào, sửa chữ máy nghe sai.
@@ -78,7 +81,7 @@ ${content?.trim() || '(không có)'}
${namesText(names)}
# Lời chép (máy nghe, có thể sai chính tả; [i] là số thứ tự chữ; chữ có dấu "?" là chữ máy nghe lại lần 2 nhưng không chắc, thường nằm ở chỗ nói lại hoặc nói vấp)
-${transcriptText(words)}
+${transcriptText(words, exclude)}
# Định dạng trả về
{
@@ -140,8 +143,9 @@ export function parseProposal(text) {
// ---- kiểm đề xuất (ngữ nghĩa) -----------------------------------------------------------------------------------
/** Trả {errors[], clean}: clean là đề xuất đã bỏ mục hỏng (dùng khi LLM sửa 1 vòng vẫn sai). */
-export function checkProposal(p, words, style) {
+export function checkProposal(p, words, style, exclude = null) {
const errors = []; const n = words.length;
+ const ex = exclude || new Set();
const isIdx = (i) => Number.isInteger(i) && i >= 0 && i < n;
const clean = { drop: [], highlights: [], zooms: [], sfx: [], fixes: [], notes: typeof p?.notes === 'string' ? p.notes : '' };
if (!p || typeof p !== 'object') return { errors: ['không phải object JSON'], clean };
@@ -152,6 +156,7 @@ export function checkProposal(p, words, style) {
for (const d of drops) {
if (!isIdx(d.from) || !isIdx(d.to) || d.from > d.to) { errors.push(`drop ${JSON.stringify(d)}: from/to không hợp lệ (0..${n - 1}, from ≤ to)`); continue; }
if (d.from <= lastTo) { errors.push(`drop ${d.from}–${d.to} chồng lên khoảng trước`); continue; }
+ if (ex.has(d.from) || ex.has(d.to)) { errors.push(`drop ${d.from}–${d.to}: nằm ngoài đoạn đã chọn cho short (đã bỏ sẵn)`); continue; }
const reason = ['retake', 'false-start', 'filler', 'aside'].includes(d.reason) ? d.reason : 'retake';
if (reason !== d.reason) errors.push(`drop ${d.from}–${d.to}: reason "${d.reason}" không hợp lệ`);
if (reason === 'filler') {
@@ -162,12 +167,13 @@ export function checkProposal(p, words, style) {
for (let i = d.from; i <= d.to; i++) dropped.add(i);
lastTo = d.to;
}
- const sure = words.filter((w) => !w.unsure).length;
- if (dropped.size > Math.max(3, 0.5 * n)) errors.push(`bỏ ${dropped.size}/${n} chữ, quá nửa`);
- if (sure && words.filter((w) => !w.unsure && !dropped.has(w.i)).length === 0) errors.push('không còn chữ nào được giữ');
+ const live = n - ex.size;
+ const sure = words.filter((w) => !w.unsure && !ex.has(w.i)).length;
+ if (dropped.size > Math.max(3, 0.5 * live)) errors.push(`bỏ ${dropped.size}/${live} chữ, quá nửa`);
+ if (sure && words.filter((w) => !w.unsure && !dropped.has(w.i) && !ex.has(w.i)).length === 0) errors.push('không còn chữ nào được giữ');
const keptIdx = (i, what) => {
if (!isIdx(i)) { errors.push(`${what} ${i}: không có chữ này`); return false; }
- if (dropped.has(i)) { errors.push(`${what} ${i} ("${words[i].w}") nằm trong đoạn bị bỏ`); return false; }
+ if (dropped.has(i) || ex.has(i)) { errors.push(`${what} ${i} ("${words[i].w}") nằm trong đoạn bị bỏ`); return false; }
return true;
};
for (const i of p.highlights || []) if (keptIdx(i, 'highlight')) clean.highlights.push(i);
@@ -185,28 +191,28 @@ export function checkProposal(p, words, style) {
}
/** Đề xuất khi không dùng LLM (--llm off, hoặc LLM lỗi): không bỏ chữ nào, zoom đều theo mật độ thẻ kiểu. */
-export function fallbackProposal(words, style) {
+export function fallbackProposal(words, style, exclude = null) {
const zooms = []; let last = -Infinity;
const gap = Math.max(style.zoom.minGap, 60 / style.zoom.perMinute[0] / 1.5);
for (const w of words) {
- if (w.unsure || key(w.w).length < 3) continue;
+ if (w.unsure || key(w.w).length < 3 || exclude?.has(w.i)) continue;
if (w.s - last >= gap) { zooms.push(w.i); last = w.s; }
}
return { drop: [], highlights: [], zooms, sfx: [], fixes: [], notes: 'không dùng LLM: chỉ rút khoảng lặng, zoom đều' };
}
/** LLM lập đề xuất; sai thì gửi lỗi cho LLM sửa đúng 1 vòng; vẫn sai thì bỏ mục hỏng. */
-export async function propose({ words, style, content, names, duration, llm = 'on', log = console.log }) {
- if (llm === 'off') return { proposal: fallbackProposal(words, style), rounds: 0, warnings: ['LLM tắt'], costUSD: 0 };
+export async function propose({ words, style, content, names, duration, llm = 'on', log = console.log, exclude = null }) {
+ if (llm === 'off') return { proposal: fallbackProposal(words, style, exclude), rounds: 0, warnings: ['LLM tắt'], costUSD: 0 };
const warnings = [];
let text = ''; let cost = 0; let prev = null;
for (let round = 1; round <= 2; round++) {
- const prompt = buildPrompt({ words, style, content, names, duration, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '' });
+ const prompt = buildPrompt({ words, style, content, names, duration, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '', exclude });
let checked;
try {
const r = await callClaude(prompt, { log });
text = r.text; cost += r.costUSD || 0;
- checked = checkProposal(parseProposal(text), words, style);
+ checked = checkProposal(parseProposal(text), words, style, exclude);
} catch (e) {
checked = { errors: [`không đọc được JSON: ${e.message}`], clean: null };
}
@@ -215,7 +221,7 @@ export async function propose({ words, style, content, names, duration, llm = 'o
prev = checked;
}
warnings.push(...prev.errors.map((e) => 'bỏ mục hỏng: ' + e));
- return { proposal: prev.clean || fallbackProposal(words, style), rounds: 2, warnings, costUSD: cost, raw: text };
+ return { proposal: prev.clean || fallbackProposal(words, style, exclude), rounds: 2, warnings, costUSD: cost, raw: text };
}
// ---- code dựng EDL từ đề xuất ------------------------------------------------------------------------------------
@@ -224,10 +230,11 @@ const TAIL = 0.22; // giữ sau chữ cuối (whisper hay báo hết chữ
const MIN_CUT = 0.12; // cắt ngắn hơn thế thì không đáng một cú nhảy hình
const EDGE_END = 0.35; // giữ sau chữ cuối cùng của video
-export function compileEdl({ id, ingestRes, analysis, words, proposal, style, music, draft }) {
+export function compileEdl({ id, ingestRes, analysis, words, proposal, style, music, draft, exclude = [], graphics = null }) {
const dur = ingestRes.source.duration;
const hes = new Set(analysis.hesitations || []);
const reasonOf = new Map();
+ for (const i of exclude) reasonOf.set(i, 'trim');
for (const d of proposal.drop) for (let i = d.from; i <= d.to; i++) reasonOf.set(i, d.reason);
for (const w of words) {
if (style.cutFillers && hes.has(key(w.w)) && !reasonOf.has(w.i)) reasonOf.set(w.i, 'filler');
@@ -267,6 +274,14 @@ export function compileEdl({ id, ingestRes, analysis, words, proposal, style, mu
zooms.push({ at: +w.s.toFixed(3), dur: style.zoom.dur, scale: style.zoom.scale, kind: style.zoom.kind, word: i });
lastZ = w.s;
}
+ // đồ hoạ (kiểu có style.graphics): giây nguồn theo keep, zoom nhẹ + sfx khi vào; zoom của LLM gần đó nhường chỗ
+ let gfx = { graphics: [], zooms: [], sfx: [], warnings: [] };
+ if (style.graphics && graphics?.length) {
+ gfx = compileGraphics({ plan: graphics, words, keep, style });
+ const near = (t) => gfx.zooms.some((g) => t > g.at - style.zoom.minGap && t < g.at + g.dur + style.zoom.minGap / 2);
+ const merged = zooms.filter((z) => !near(z.at)).concat(gfx.zooms).sort((a, b) => a.at - b.at);
+ zooms.length = 0; zooms.push(...merged);
+ }
// zoom không được tràn sang cú sau
for (let k = 0; k + 1 < zooms.length; k++) zooms[k].dur = +Math.max(0.2, Math.min(zooms[k].dur, zooms[k + 1].at - zooms[k].at - 0.05)).toFixed(3);
@@ -274,10 +289,12 @@ export function compileEdl({ id, ingestRes, analysis, words, proposal, style, mu
const capWords = kept.filter((w) => !hes.has(key(w.w)) && fixes.get(w.i) !== '')
.map((w) => ({ i: w.i, w: fixes.get(w.i) || w.w, start: +w.s.toFixed(3), end: +Math.max(w.e, w.s + 0.05).toFixed(3) }));
const capIds = new Set(capWords.map((w) => w.i));
+ const numHi = style.captions.numbers ? numberHighlights(capWords) : [];
const sfx = [];
for (const s of proposal.sfx) { const w = byIdx.get(s.word); if (w && !reasonOf.has(s.word)) sfx.push({ at: +w.s.toFixed(3), name: s.name, gainDb: style.sfx.gainDb }); }
if (style.sfx.onZoom) for (const z of zooms) sfx.push({ at: z.at, name: style.sfx.onZoom, gainDb: style.sfx.gainDb });
+ sfx.push(...gfx.sfx);
sfx.sort((a, b) => a.at - b.at);
const sfxOut = sfx.filter((s, k) => k === 0 || s.at - sfx[k - 1].at > 0.15).slice(0, style.sfx.max);
@@ -290,12 +307,14 @@ export function compileEdl({ id, ingestRes, analysis, words, proposal, style, mu
zooms,
captions: {
style: style.captions.style, renderer: draft ? 'pil' : 'hyperframes', maxWords: style.captions.maxWords,
- position: style.captions.position, words: capWords, highlights: [...new Set(proposal.highlights)].filter((i) => capIds.has(i)),
+ position: style.captions.position, words: capWords, highlights: [...new Set([...proposal.highlights, ...numHi])].filter((i) => capIds.has(i)).sort((a, b) => a - b),
},
sfx: sfxOut,
+ graphics: gfx.graphics,
music: music ? { file: path.resolve(music), gainDb: style.music.gainDb, duckDb: style.music.duckDb, fadeOut: style.music.fadeOut } : null,
audio: { crossfadeMs: 20, keepSourceAudio: true },
notes: proposal.notes || '',
+ ...(gfx.warnings.length ? { _warnings: gfx.warnings } : {}),
};
}
@@ -411,7 +430,7 @@ ${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previou
}
/** LLM đọc lời sửa → {proposal, cutsOut, overrides, notes}. Sai → sửa 1 vòng; vẫn sai → báo lỗi (không đoán bừa). */
-export async function proposeRevision({ words, edl, proposal, style, overrides = {}, instruction, names, log = console.log }) {
+export async function proposeRevision({ words, edl, proposal, style, overrides = {}, instruction, names, log = console.log, exclude = null }) {
let text = ''; let prev = null; let cost = 0;
const outDur = outputDuration(edl.keep);
for (let round = 1; round <= 2; round++) {
@@ -421,7 +440,7 @@ export async function proposeRevision({ words, edl, proposal, style, overrides =
const r = await callClaude(prompt, { log });
text = r.text; cost += r.costUSD || 0;
const j = parseProposal(text);
- const checked = checkProposal(j.proposal || proposal, words, style);
+ const checked = checkProposal(j.proposal || proposal, words, style, exclude);
errors = checked.errors;
const cuts = Array.isArray(j.cut_output) ? j.cut_output : [];
for (const c of cuts) {
diff --git a/edit/py/lumedit.py b/edit/py/lumedit.py
index e0f19fb..9dda6b9 100644
--- a/edit/py/lumedit.py
+++ b/edit/py/lumedit.py
@@ -113,10 +113,16 @@ def build(edl: dict, draft_captions: bool):
if (fr.out_w, fr.out_h) != (OUT_W, OUT_H):
fr.out_w, fr.out_h = OUT_W, OUT_H
zooms = Zooms(edl, tl, fr, clip)
+ glass = Glass(edl, tl) if edl.get("graphics") else None
+ squeeze = Squeeze(edl, tl) if any(g.get("squeeze") for g in edl.get("graphics", [])) else None
caps = DraftCaptions(edl, tl) if draft_captions and edl["captions"]["words"] else None
def draw(frame, j, t):
zooms.apply(frame, j, t)
+ if squeeze is not None:
+ squeeze.apply(frame, t)
+ if glass is not None:
+ glass.apply(frame, t)
if caps is not None:
caps.draw(frame, t)
@@ -177,6 +183,90 @@ class Zooms:
frame[:] = cv2.warpAffine(frame, m, (OUT_W, OUT_H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
+# ---- squeeze the picture while a graphic needs the room above a close face ----------------------------------------
+
+class Squeeze:
+ """edit/graphics.mjs sets `squeeze` {scale, anchorY} on a graphic when the face fills the frame: during that
+ graphic the whole picture shrinks about (centre, anchorY) — the chin stays put, the top of the head comes down —
+ eased in 0.3 s and out 0.25 s; around it, the same picture blurred and darkened."""
+
+ IN, OUT_ = 0.3, 0.25
+
+ def __init__(self, edl: dict, tl):
+ self.items = [(tl.to_output_nearest(float(g["start"])), tl.to_output_nearest(float(g["end"])),
+ float(g["squeeze"]["scale"]), float(g["squeeze"]["anchorY"]))
+ for g in edl.get("graphics", []) if g.get("squeeze")]
+
+ def at(self, t: float):
+ for t0, t1, k, ay in self.items:
+ if t0 <= t < t1:
+ e = min(_ease((t - t0) / self.IN), _ease((t1 - t) / self.OUT_))
+ return 1.0 - (1.0 - k) * e, ay
+ return 1.0, 0.0
+
+ def apply(self, frame, t: float) -> None:
+ s, ay = self.at(t)
+ if s > 0.999:
+ return
+ import cv2
+ import numpy as np
+
+ small = cv2.resize(frame, (OUT_W // 10, OUT_H // 10), interpolation=cv2.INTER_AREA)
+ bg = cv2.resize(cv2.GaussianBlur(small, (0, 0), 4), (OUT_W, OUT_H), interpolation=cv2.INTER_LINEAR)
+ m = np.array([[s, 0.0, OUT_W / 2 * (1 - s)], [0.0, s, ay * (1 - s)]], np.float64)
+ fg = cv2.warpAffine(frame, m, (OUT_W, OUT_H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
+ x0, y0 = int(np.ceil(OUT_W / 2 * (1 - s))), int(np.ceil(ay * (1 - s)))
+ x1, y1 = int(np.floor(x0 + OUT_W * s)) - 1, int(np.floor(y0 + OUT_H * s)) - 1
+ out = (bg.astype(np.float32) * 0.5).astype(np.uint8)
+ out[y0:y1, x0:x1] = fg[y0:y1, x0:x1]
+ frame[:] = out
+
+
+# ---- frosted glass under the graphics (edit/graphics.mjs draws the card itself in the HyperFrames layer) ----------
+
+class Glass:
+ """Blurs the video under each graphic's card (rounded box), fading in/out with the card, so the semi-dark card of the
+ overlay reads as frosted glass. Price tags and stickers are solid and get no glass."""
+
+ ENTER, LEAVE, RADIUS = 0.15, 0.22, 38
+
+ def __init__(self, edl: dict, tl):
+ import numpy as np
+
+ self.items = []
+ for g in edl.get("graphics", []):
+ b = g.get("box")
+ if not b or g["type"] in ("price_tag", "sticker"):
+ continue
+ x0, y0 = max(0, int(round(b["x"]))), max(0, int(round(b["y"])))
+ x1, y1 = min(OUT_W, int(round(b["x"] + b["w"]))), min(OUT_H, int(round(b["y"] + b["h"])))
+ if x1 - x0 < 8 or y1 - y0 < 8:
+ continue
+ r = max(4, int(self.RADIUS * float(b.get("scale", 1))))
+ yy, xx = np.mgrid[0:y1 - y0, 0:x1 - x0]
+ w, h = x1 - x0, y1 - y0
+ dx = np.maximum(np.maximum(r - xx, xx - (w - 1 - r)), 0)
+ dy = np.maximum(np.maximum(r - yy, yy - (h - 1 - r)), 0)
+ mask = np.clip(r + 0.5 - np.sqrt(dx * dx + dy * dy), 0, 1).astype(np.float32)[..., None]
+ self.items.append((tl.to_output_nearest(float(g["start"])), tl.to_output_nearest(float(g["end"])), x0, y0, x1, y1, mask))
+
+ def apply(self, frame, t: float) -> None:
+ import cv2
+ import numpy as np
+
+ for t0, t1, x0, y0, x1, y1, mask in self.items:
+ if not (t0 <= t < t1):
+ continue
+ a = min(_ease((t - t0) / self.ENTER), _ease((t1 - t) / self.LEAVE))
+ if a <= 0.01:
+ continue
+ reg = frame[y0:y1, x0:x1]
+ small = cv2.resize(reg, ((x1 - x0) // 4 or 1, (y1 - y0) // 4 or 1), interpolation=cv2.INTER_AREA)
+ blur = cv2.resize(cv2.GaussianBlur(small, (0, 0), 6), (x1 - x0, y1 - y0), interpolation=cv2.INTER_LINEAR)
+ m = mask * a
+ frame[y0:y1, x0:x1] = (reg.astype(np.float32) * (1 - m) + blur.astype(np.float32) * m).astype(np.uint8)
+
+
# ---- draft captions (PIL) -------------------------------------------------------------------------------------
STYLE_DRAFT = {
@@ -384,6 +474,68 @@ def cmd_stills(edl_path: Path, out: Path, count: int, draft_captions: bool) -> d
return {"out": str(out), "times": [round(t, 2) for t in times]}
+# What a graphic must keep clear of: the detector's own box (BlazeFace's box already runs wide of the cheeks and
+# below the chin) grown upward for the hair. Measured on the founder's review clip (28/11/2026): `head()` (+60% up,
+# +20% sides) came out about twice the visible head and left no room for any graphic in a close talking-head shot.
+GRAPHIC_HEAD = {"left": 0.04, "top": 0.20, "right": 0.04, "bottom": 0.04}
+
+
+def _graphic_head(face, k: int, near: int):
+ """The face at source frame k from the detector's own boxes (the nearest within `near` frames; the detector runs
+ on every frame but misses some), so B-roll without a face leaves the whole frame to the graphics; None when no
+ face is there. Boxes of implausible size are ignored."""
+ import numpy as np
+
+ from fx.core.layout import Rect
+
+ lo, hi = max(0, k - near), min(face.n - 1, k + near)
+ best = None
+ for i in range(lo, hi + 1):
+ x = face.raw[i, 0]
+ if not np.isnan(x) and not (0.05 * face.height <= face.raw[i, 3] <= 0.7 * face.height):
+ continue
+ if np.isnan(x) or (best is not None and abs(i - k) >= abs(best - k)):
+ continue
+ best = i
+ if best is None:
+ return None
+ x, y, w, h, _ = face.raw[best]
+ g = GRAPHIC_HEAD
+ return Rect(x - g["left"] * w, y - g["top"] * h, x + w + g["right"] * w, y + h + g["bottom"] * h)
+
+
+def cmd_faces(edl_path: Path, out: Path, step: float) -> dict:
+ """Head box in OUTPUT pixels (after reframe and zoom) every `step` s of the output: what graphics must avoid."""
+ edl = load_edl(edl_path)
+ clip, tl, fr, _draw = build(edl, False)
+ zooms = Zooms(edl, tl, fr, clip)
+ fps = clip.info.rate
+ rows = []
+ n = int(tl.duration / step) + 1
+ face = clip.face if clip.face.any() else None
+ near = int(round(0.5 * fps))
+ for m in range(n):
+ t = min(tl.duration, m * step)
+ k = tl.source_frame(int(round(t * fps)), fps, clip.info.frames)
+ head = _graphic_head(face, k, near) if face is not None else None
+ if head is None:
+ rows.append([round(t, 3), None])
+ continue
+ r = fr.to_output(head, k)
+ x0, y0, x1, y1 = r.x0, r.y0, r.x1, r.y1
+ s, cx, cy = zooms.scale_at(t)
+ if s > 1.001:
+ w, h = OUT_W / s, OUT_H / s
+ ox = min(max(cx - w / 2, 0.0), OUT_W - w)
+ oy = min(max(cy - h * 0.42, 0.0), OUT_H - h)
+ x0, x1, y0, y1 = (x0 - ox) * s, (x1 - ox) * s, (y0 - oy) * s, (y1 - oy) * s
+ bx = [round(max(0, x0)), round(max(0, y0)), round(min(OUT_W, x1)), round(min(OUT_H, y1))]
+ rows.append([round(t, 3), bx if bx[2] - bx[0] > 8 and bx[3] - bx[1] > 8 else None])
+ data = {"step": step, "found_share": round(float(clip.face.found_share), 3) if clip.face.any() else 0.0, "boxes": rows}
+ out.write_text(json.dumps(data), encoding="utf-8")
+ return {"out": str(out), "samples": len(rows)}
+
+
# ---- qc ---------------------------------------------------------------------------------------------------------
def cmd_qc(video_path: Path, out: Path) -> dict:
@@ -405,6 +557,8 @@ def main(argv=None) -> int:
r.add_argument("--draft-captions", action="store_true"); r.add_argument("--no-check", action="store_true")
s = sub.add_parser("stills"); s.add_argument("edl"); s.add_argument("--out", required=True)
s.add_argument("--count", type=int, default=16); s.add_argument("--draft-captions", action="store_true")
+ f = sub.add_parser("faces"); f.add_argument("edl"); f.add_argument("--out", required=True)
+ f.add_argument("--step", type=float, default=0.25)
q = sub.add_parser("qc"); q.add_argument("video"); q.add_argument("--out", required=True)
args = ap.parse_args(argv)
try:
@@ -414,6 +568,8 @@ def main(argv=None) -> int:
res = cmd_render(Path(args.edl).resolve(), Path(args.out).resolve(), args.draft_captions, not args.no_check)
elif args.cmd == "stills":
res = cmd_stills(Path(args.edl).resolve(), Path(args.out).resolve(), args.count, args.draft_captions)
+ elif args.cmd == "faces":
+ res = cmd_faces(Path(args.edl).resolve(), Path(args.out).resolve(), args.step)
else:
res = cmd_qc(Path(args.video).resolve(), Path(args.out).resolve())
except (ValueError, KeyError, FileNotFoundError) as e:
diff --git a/edit/test/graphics-check.mjs b/edit/test/graphics-check.mjs
new file mode 100644
index 0000000..e74f240
--- /dev/null
+++ b/edit/test/graphics-check.mjs
@@ -0,0 +1,57 @@
+#!/usr/bin/env node
+// Kiểm nhanh lớp đồ hoạ (không cần GPU/LLM): đọc số tiếng Việt, luật "không bịa số", chồng thời gian,
+// dàn trang né mặt, và validateEdl bắt đồ hoạ đè mặt / quá ngắn / 2 đồ hoạ lớn cùng lúc.
+// node edit/test/graphics-check.mjs
+import { extractNumbers, fmtVi } from '../numbers.mjs';
+import { checkGraphics, spokenNumbers, compileGraphics, layoutGraphics, graphicsErrors } from '../graphics.mjs';
+
+let fail = 0;
+const ok = (cond, msg) => { console.log(`${cond ? 'PASS' : 'FAIL'} ${msg}`); if (!cond) fail++; };
+const nums = (s) => extractNumbers(s.split(' ')).map((x) => x.value);
+
+ok(nums('Mỗi ngày 50 nghìn').includes(50000), 'đọc "50 nghìn" = 50000');
+ok(nums('một tháng 1 triệu rưỡi').includes(1500000), 'đọc "1 triệu rưỡi" = 1500000');
+ok(nums('giá mười hai triệu chín trăm chín mươi nghìn').includes(12990000), 'đọc số bằng chữ = 12990000');
+ok(nums('săn sale giá khoảng 9 rưỡi').includes(9.5), 'đọc "9 rưỡi" = 9,5');
+ok(nums('thêm 300.000 đ').includes(300000) && nums('lãi 6%').includes(6) && nums('16GB').includes(16), 'chữ số có nhóm nghìn / % / đơn vị dính');
+ok(nums('card 40 60 ti').includes(4060), '"40 60" ghép thành 4060');
+ok(!nums('hai năm trước').includes(7), '"hai năm" không thành 7');
+ok(fmtVi(12990000) === '12.990.000' && fmtVi(9.5) === '9,5', 'định dạng số kiểu Việt');
+
+// lời giả: 0..n chữ, 0,4 s mỗi chữ
+const text = 'giá RTX 5060 bây giờ khoảng 9 rưỡi còn RTX 5070 thì 22 triệu và sắp tới có thể lên 30 triệu anh em ạ';
+const words = text.split(' ').map((w, i) => ({ i, w, s: i * 0.4, e: i * 0.4 + 0.3 }));
+const spoken = spokenNumbers(words, ['RTX 5060', 'RTX 5070']);
+const all = () => true;
+const bar = { type: 'bar_chart', at: 0, until: 17, title: 'Giá', unit: 'triệu', items: [{ label: 'RTX 5060', value: 9.5, word: 6 }, { label: 'RTX 5070', value: 22, word: 12 }] };
+let r = checkGraphics({ graphics: [bar] }, words, all, spoken);
+ok(!r.errors.length && r.clean.length === 1, 'bar_chart đúng số người nói → hợp lệ');
+r = checkGraphics({ graphics: [{ ...bar, items: [{ label: 'RTX 5060', value: 10, word: 6 }, { label: 'RTX 5070', value: 22, word: 12 }] }] }, words, all, spoken);
+ok(r.errors.some((e) => e.includes('không có trong lời')), 'số bịa (10) bị bắt');
+r = checkGraphics({ graphics: [{ ...bar, estimate: true, items: [{ label: 'RTX 5060', value: 10, word: 6 }, { label: 'RTX 5070', value: 22, word: 12 }] }] }, words, all, spoken);
+ok(!r.errors.length, 'số suy ra có estimate: true → được, ghi "ước tính"');
+r = checkGraphics({ graphics: [{ type: 'spec_table', at: 0, until: 10, rows: [{ label: 'Giá', value: '12 triệu', word: 2 }] }] }, words, all, spoken);
+ok(r.errors.length > 0, 'số bịa trong ô chữ bị bắt');
+r = checkGraphics({ graphics: [bar, { type: 'title_card', at: 10, until: 20, title: 'Giá sắp tới' }] }, words, all, spoken);
+ok(r.errors.some((e) => e.includes('chồng thời gian')) && r.clean.length === 1, '2 đồ hoạ lớn chồng nhau bị bắt');
+r = checkGraphics({ graphics: [{ ...bar, items: [{ label: 'RTX 5060', value: 9.5, word: 30 }, { label: 'RTX 5070', value: 22, word: 12 }] }] }, words, all, spoken);
+ok(r.errors.length > 0, 'mốc dòng ngoài at..until bị bắt');
+
+// compile + layout: mặt ở 30–48% khung, đồ hoạ phải nằm ngoài
+const keep = [{ start: 0, end: 10 }];
+const style = { graphics: { zoom: 1.06, sfxBig: 'whoosh', sfxSmall: 'pop', sfxStamp: 'stamp', sfxTick: 'tick', sfxGainDb: -11 } };
+const cg = compileGraphics({ plan: checkGraphics({ graphics: [bar, { type: 'counter', at: 20, until: 20, value: 30, suffix: 'triệu' }] }, words, all, spoken).clean, words, keep, style });
+ok(cg.graphics.length === 2 && cg.zooms.length === 1 && cg.sfx.length === 2, 'compile: 2 đồ hoạ, 1 zoom, 2 sfx');
+ok(cg.graphics.every((g) => g.end - g.start >= 1.5 - 1e-6), 'mỗi đồ hoạ ≥ 1,5 s');
+const face = [360, 560, 720, 920];
+const faces = { step: 0.25, boxes: Array.from({ length: 41 }, (_, k) => [k * 0.25, face]) };
+const warn = layoutGraphics(cg.graphics, keep, faces, 1360);
+const edl = { keep, graphics: cg.graphics };
+ok(!warn.length && !graphicsErrors(edl).length, 'dàn trang né mặt, không tràn, validateEdl không lỗi');
+ok(cg.graphics.every((g) => g.box.y + g.box.h <= g.face[1] || g.box.y >= g.face[3]), 'đồ hoạ ở ngoài dải mặt (mặt sau khi thu hình nếu có)');
+ok(cg.graphics.some((g) => g.squeeze) && cg.graphics.every((g) => g.box.scale >= 0.8), 'cận mặt: thu hình để đồ hoạ ≥ 0,8×');
+const bad = { keep, graphics: [{ ...cg.graphics[0], box: { x: 120, y: 600, w: 840, h: 300, scale: 1 }, face: [360, 500, 720, 900] }] };
+ok(graphicsErrors(bad).some((e) => e.msg.includes('đè mặt')), 'validateEdl bắt đồ hoạ đè mặt');
+
+console.log(fail ? `${fail} FAIL` : 'ALL PASS');
+process.exit(fail ? 1 : 0);
diff --git a/mcp/server.mjs b/mcp/server.mjs
index 18ab067..591aee5 100644
--- a/mcp/server.mjs
+++ b/mcp/server.mjs
@@ -269,8 +269,9 @@ server.registerTool('edit_video', {
notes: z.string().max(2000).optional().describe('lời dặn thêm cho người dựng (vd "bỏ câu chào đầu")'),
names: z.array(z.string()).max(40).optional().describe('tên riêng/thuật ngữ viết đúng, để LLM sửa chữ máy nghe sai (vd ["Lumfin"])'),
draft: z.boolean().optional().describe('true: phụ đề nháp PIL (nhanh hơn ~1 phút)'),
+ target: z.number().int().min(15).max(180).optional().describe('clip dài (5–20 phút): số giây short muốn ra (vd 45); LLM chọn các đoạn hay nhất có hook và kết, rồi mới cắt ngập ngừng'),
},
-}, async ({ path: video, style, music, notes, names, draft }) => {
+}, async ({ path: video, style, music, notes, names, draft, target }) => {
try {
const ready = editReady();
if (!ready.ready) return fail(ready.note);
@@ -283,7 +284,7 @@ server.registerTool('edit_video', {
musicFile = f;
} else musicFile = music;
}
- const job = await createEdit({ video, style, music: musicFile, content: notes, names, draft });
+ const job = await createEdit({ video, style, music: musicFile, content: notes, names, draft, target });
const p = spawn(process.execPath, [path.join(ROOT, 'cli.mjs'), 'edit-run', job.id], { cwd: ROOT, detached: true, stdio: 'ignore', windowsHide: true, env: process.env });
p.unref();
return { content: [json({ ...editSummary(job.id), note: 'Đang dựng ở tiến trình nền. Gọi get_edit sau 1–2 phút.' })] };