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.
WIP Edit video: engine cho 11 cách dựng (đang dở, tạm dừng)
Lumtekc1714c93ac1c
diff --git a/cli.mjs b/cli.mjsindex e8be310..5f56f9b 100644--- a/cli.mjs+++ b/cli.mjs@@ -57,7 +57,8 @@ function usage() {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ạiedit-show <editId> [--json] trạng thái, tiến độ, chữ LLM đã sửa, logedit-run <editId> chạy 1 edit đã tạo (MCP/REST dùng)- edit-rm <editId> xoá hẳn 1 edit (thư mục edits/<id>)`);+ edit-rm <editId> xoá hẳn 1 edit (thư mục edits/<id>)+ edit-styles [--json] các kiểu edit (edit-styles/<id>.md): id, tên, độ dài mặc định, có ảnh minh hoạ chưa`);}const readContent = (c) => (fs.existsSync(c) && fs.statSync(c).isFile() ? fs.readFileSync(c, 'utf8') : c);@@ -188,6 +189,11 @@ ${res.warnings.length} cảnh báo âm thanh (xem trên)` : ''}`);const j = readJob(pos[0] || '');if (!j) { console.error('Không thấy job'); process.exit(1); }out({ ...j, paths: jobPaths(j.id), log: readLog(j.id, 40) });+ } else if (cmd === 'edit-styles') {+ const { editStyles } = await import('./edit/jobs.mjs');+ const list = editStyles();+ if (opt.json) out(list);+ else for (const s of list) console.log(`${String(s.order).padStart(2)} ${s.id.padEnd(20)} ${s.thumb ? '▣' : '·'} ${s.target ? `${s.target} s` : ' -'} ${s.name} · ${s.summary}`);} else if (cmd === 'templates') {const list = loadCatalog().map((t) => ({ id: t.id, name: t.name, category: t.category, genre: t.genre, technique: t.technique, difficulty: t.difficulty, guidance: hasGuidance(t.id) }));if (opt.json) out(list);diff --git a/edit-styles/ban-tin-nhanh.md b/edit-styles/ban-tin-nhanh.mdindex 64d3fcc..8265596 100644--- a/edit-styles/ban-tin-nhanh.md+++ b/edit-styles/ban-tin-nhanh.md@@ -2,6 +2,9 @@{"id": "ban-tin-nhanh","name": "Bản tin nhanh",+ "nameEn": "Quick news",+ "summary": "Tin nóng: thanh tin chạy dưới khung, nhịp nhanh",+ "summaryEn": "Breaking news: ticker bar captions, fast pace","version": 1,"order": 9,"pause": 0.18,@@ -13,7 +16,7 @@},"zoom": { "kind": "punch", "scale": 1.08, "dur": 0.5, "minGap": 2.5, "perMinute": [12, 20] },"sfx": { "onZoom": null, "max": 14, "gainDb": -13 },- "music": { "gainDb": -22, "duckDb": 10, "fadeOut": 0.8, "default": "upbeat" },+ "music": { "gainDb": -22, "duckDb": 10, "fadeOut": 0.8, "default": "news" },"graphics": {"accent": "#E8202A", "perMinute": [4, 10], "zoom": 1.06, "types": ["sticker", "counter", "line_chart", "bar_chart", "title_card"],"sfxBig": "whoosh", "sfxSmall": "pop", "sfxStamp": "glitch", "sfxTick": "tick", "sfxGainDb": -10@@ -50,7 +53,7 @@ Cho tin tức, cập nhật ("giá vàng hôm nay", "luật mới từ 1/7", "ap- Mày thêm "notification" ở chữ đầu mỗi tin mới (tối đa 4 cái). Không gắn tiếng vào zoom.## Nhạc-- "upbeat" (pop sáng, 118 BPM) −22 dB, tự hạ khi nói.+- "news" (nền bản tin, nhịp đều + pad, 120 BPM) −22 dB, tự hạ khi nói.## Tự kiểm- Sticker TIN NÓNG nằm trong 2 giây đầu.diff --git a/edit-styles/cau-noi-hay.md b/edit-styles/cau-noi-hay.mdindex 00be99a..ad42005 100644--- a/edit-styles/cau-noi-hay.md+++ b/edit-styles/cau-noi-hay.md@@ -2,6 +2,9 @@{"id": "cau-noi-hay","name": "Trích câu nói hay",+ "nameEn": "Quote of the day",+ "summary": "Câu chốt to giữa khung kiểu trích dẫn, nền mờ tối",+ "summaryEn": "Key line as a big centred quote over a dimmed video","version": 1,"order": 14,"pause": 0.7,@@ -15,7 +18,7 @@},"zoom": { "kind": "push", "scale": 1.10, "dur": 6.0, "minGap": 10, "perMinute": [1, 3] },"sfx": { "onZoom": null, "max": 2, "gainDb": -15 },- "music": { "gainDb": -25, "duckDb": 11, "fadeOut": 3.0, "default": "epic" }+ "music": { "gainDb": -25, "duckDb": 11, "fadeOut": 3.0, "default": "piano" }}---# Trích câu nói hay@@ -44,7 +47,7 @@ Cho clip truyền cảm hứng, lời khuyên đời, câu nói đáng nhớ. C- Tối đa 2: "riser" ở chữ khoảng 1,5 giây trước câu chốt, "chime" ở chữ đầu câu chốt. Không dùng tiếng mạnh.## Nhạc-- "epic" (dàn dây) −25 dB, dâng dần về câu chốt, fade dài 3 giây ở cuối.+- "piano" (piano chậm, 70 BPM, không trống) −25 dB, fade dài 3 giây ở cuối.## Tự kiểm- notes có đúng 1 dòng `QUOTE:` chỉ một câu trọn nghĩa, 6–25 chữ.diff --git a/edit-styles/chot-don-livestream.md b/edit-styles/chot-don-livestream.mdindex 90327e7..6a861f5 100644--- a/edit-styles/chot-don-livestream.md+++ b/edit-styles/chot-don-livestream.md@@ -2,6 +2,9 @@{"id": "chot-don-livestream","name": "Cắt livestream bán hàng",+ "nameEn": "Livestream sales cut",+ "summary": "Clip bán hàng: giá, giảm giá, kêu gọi đặt",+ "summaryEn": "Sales clip: price, discount, call to order","version": 1,"order": 11,"pause": 0.25,diff --git a/edit-styles/huong-dan-buoc.md b/edit-styles/huong-dan-buoc.mdindex 1dd4b6c..90912ec 100644--- a/edit-styles/huong-dan-buoc.md+++ b/edit-styles/huong-dan-buoc.md@@ -2,6 +2,9 @@{"id": "huong-dan-buoc","name": "Hướng dẫn từng bước",+ "nameEn": "Step-by-step tutorial",+ "summary": "Hướng dẫn: Bước 1/2/3, chữ gõ từng ký tự, tick dần",+ "summaryEn": "Tutorial: Step 1/2/3, typewriter captions, ticks as you go","version": 1,"order": 8,"pause": 0.4,diff --git a/edit-styles/ke-chuyen.md b/edit-styles/ke-chuyen.mdindex 5d6150b..dc875ec 100644--- a/edit-styles/ke-chuyen.md+++ b/edit-styles/ke-chuyen.md@@ -2,6 +2,9 @@{"id": "ke-chuyen","name": "Kể chuyện",+ "nameEn": "Storytime",+ "summary": "Kể chuyện, karaoke từng chữ, giữ nhịp thở",+ "summaryEn": "Story or experience, word-by-word karaoke, room to breathe","version": 1,"order": 5,"pause": 0.6,diff --git a/edit-styles/meo-15s.md b/edit-styles/meo-15s.mdindex 79b3b27..5af67d8 100644--- a/edit-styles/meo-15s.md+++ b/edit-styles/meo-15s.md@@ -2,6 +2,9 @@{"id": "meo-15s","name": "Mẹo nhanh 15 giây",+ "nameEn": "15-second tip",+ "summary": "Một mẹo duy nhất, ≤ 20 giây, chữ móc to đầu clip",+ "summaryEn": "One tip only, ≤ 20 s, big hook text up front","version": 1,"order": 13,"pause": 0.15,diff --git a/edit-styles/phu-de-nay-mau.md b/edit-styles/phu-de-nay-mau.mdindex 5d89217..544a365 100644--- a/edit-styles/phu-de-nay-mau.md+++ b/edit-styles/phu-de-nay-mau.md@@ -2,6 +2,9 @@{"id": "phu-de-nay-mau","name": "Phụ đề nảy màu, zoom dồn dập",+ "nameEn": "Bold pop captions, rapid zooms",+ "summary": "Chữ hoa to nảy màu từng chữ, zoom dồn dập",+ "summaryEn": "Big uppercase karaoke captions, fast punch zooms","version": 1,"order": 2,"pause": 0.25,diff --git a/edit-styles/podcast-trich-doan.md b/edit-styles/podcast-trich-doan.mdindex 5296e7a..3d6801b 100644--- a/edit-styles/podcast-trich-doan.md+++ b/edit-styles/podcast-trich-doan.md@@ -2,6 +2,9 @@{"id": "podcast-trich-doan","name": "Trích đoạn podcast",+ "nameEn": "Podcast clip",+ "summary": "Cắt 1 ý hay từ buổi nói dài, tiêu đề ghim trên",+ "summaryEn": "One strong idea from a long talk, pinned title","version": 1,"order": 4,"pause": 0.45,diff --git a/edit-styles/quan-diem-gat.md b/edit-styles/quan-diem-gat.mdindex 33f356f..cf30ab4 100644--- a/edit-styles/quan-diem-gat.md+++ b/edit-styles/quan-diem-gat.md@@ -2,6 +2,9 @@{"id": "quan-diem-gat","name": "Quan điểm gắt",+ "nameEn": "Hot take",+ "summary": "Câu gắt nhất kéo lên đầu, chữ đập, zoom mạnh",+ "summaryEn": "Spiciest line pulled to the front, slam captions, hard zooms","version": 1,"order": 10,"pause": 0.22,diff --git a/edit-styles/review-san-pham.md b/edit-styles/review-san-pham.mdindex fe1b3bf..7b1aa8f 100644--- a/edit-styles/review-san-pham.md+++ b/edit-styles/review-san-pham.md@@ -2,6 +2,9 @@{"id": "review-san-pham","name": "Review sản phẩm",+ "nameEn": "Product review",+ "summary": "Đập hộp, đánh giá: tem giá, bảng thông số, kết luận",+ "summaryEn": "Unboxing and review: price tag, spec table, verdict","version": 1,"order": 7,"pause": 0.32,diff --git a/edit-styles/sach-gon.md b/edit-styles/sach-gon.mdindex 00f935e..23de3e5 100644--- a/edit-styles/sach-gon.md+++ b/edit-styles/sach-gon.md@@ -2,6 +2,9 @@{"id": "sach-gon","name": "Sạch và gọn",+ "nameEn": "Clean and tight",+ "summary": "Cắt ngập ngừng, phụ đề gọn dưới khung, zoom nhẹ",+ "summaryEn": "Trims hesitations, tidy captions low in frame, gentle zoom","version": 1,"order": 1,"pause": 0.35,diff --git a/edit-styles/thong-tin-do-hoa.md b/edit-styles/thong-tin-do-hoa.mdindex fae24f1..6e97a51 100644--- a/edit-styles/thong-tin-do-hoa.md+++ b/edit-styles/thong-tin-do-hoa.md@@ -2,6 +2,9 @@{"id": "thong-tin-do-hoa","name": "Thông tin, nhiều đồ hoạ bảng biểu",+ "nameEn": "Info graphics heavy",+ "summary": "Bảng giá, biểu đồ, thông số hiện đúng lúc nói",+ "summaryEn": "Price tags, charts and spec tables timed to speech","version": 1,"order": 3,"pause": 0.3,diff --git a/edit-styles/thumbs/cau-noi-hay.webp b/edit-styles/thumbs/cau-noi-hay.webpnew file mode 100644index 0000000..5f8aa6cBinary files /dev/null and b/edit-styles/thumbs/cau-noi-hay.webp differdiff --git a/edit-styles/thumbs/ke-chuyen.webp b/edit-styles/thumbs/ke-chuyen.webpnew file mode 100644index 0000000..4bb18e6Binary files /dev/null and b/edit-styles/thumbs/ke-chuyen.webp differdiff --git a/edit-styles/thumbs/meo-15s.webp b/edit-styles/thumbs/meo-15s.webpnew file mode 100644index 0000000..7bca664Binary files /dev/null and b/edit-styles/thumbs/meo-15s.webp differdiff --git a/edit-styles/thumbs/phu-de-nay-mau.webp b/edit-styles/thumbs/phu-de-nay-mau.webpnew file mode 100644index 0000000..8d9295cBinary files /dev/null and b/edit-styles/thumbs/phu-de-nay-mau.webp differdiff --git a/edit-styles/thumbs/podcast-trich-doan.webp b/edit-styles/thumbs/podcast-trich-doan.webpnew file mode 100644index 0000000..76e094aBinary files /dev/null and b/edit-styles/thumbs/podcast-trich-doan.webp differdiff --git a/edit-styles/thumbs/quan-diem-gat.webp b/edit-styles/thumbs/quan-diem-gat.webpnew file mode 100644index 0000000..95dd496Binary files /dev/null and b/edit-styles/thumbs/quan-diem-gat.webp differdiff --git a/edit-styles/thumbs/sach-gon.webp b/edit-styles/thumbs/sach-gon.webpnew file mode 100644index 0000000..a868193Binary files /dev/null and b/edit-styles/thumbs/sach-gon.webp differdiff --git a/edit-styles/thumbs/thong-tin-do-hoa.webp b/edit-styles/thumbs/thong-tin-do-hoa.webpnew file mode 100644index 0000000..d5f64faBinary files /dev/null and b/edit-styles/thumbs/thong-tin-do-hoa.webp differdiff --git a/edit-styles/thumbs/top-danh-sach.webp b/edit-styles/thumbs/top-danh-sach.webpnew file mode 100644index 0000000..16d5692Binary files /dev/null and b/edit-styles/thumbs/top-danh-sach.webp differdiff --git a/edit-styles/top-danh-sach.md b/edit-styles/top-danh-sach.mdindex 79f9aaa..6160874 100644--- a/edit-styles/top-danh-sach.md+++ b/edit-styles/top-danh-sach.md@@ -2,6 +2,9 @@{"id": "top-danh-sach","name": "Top N",+ "nameEn": "Top N list",+ "summary": "\"3 cách…\", \"5 lỗi…\": thẻ #1 #2 #3, tổng kết cuối",+ "summaryEn": "\"3 ways…\", \"5 mistakes…\": #1 #2 #3 cards, recap at the end","version": 1,"order": 6,"pause": 0.3,diff --git a/edit-styles/vlog-nhe.md b/edit-styles/vlog-nhe.mdindex 147746f..78168bc 100644--- a/edit-styles/vlog-nhe.md+++ b/edit-styles/vlog-nhe.md@@ -2,6 +2,9 @@{"id": "vlog-nhe","name": "Vlog nhẹ nhàng",+ "nameEn": "Chill vlog",+ "summary": "Đời thường, chữ nhỏ mờ vào, ít cắt khoảng lặng",+ "summaryEn": "Everyday life, small soft captions, pauses kept","version": 1,"order": 12,"pause": 1.5,diff --git a/edit/askeditor/fx/core/render.py b/edit/askeditor/fx/core/render.pyindex 762433b..38abd0b 100644--- a/edit/askeditor/fx/core/render.py+++ b/edit/askeditor/fx/core/render.py@@ -101,6 +101,16 @@ def render(clip: Clip, timeline: Timeline, framing: Framing, draw: Optional[Drawtry:for j in range(n_out):k = timeline.source_frame(j, fps, info.frames)+ if k < k_read:+ # LumReels: a timeline may jump back in the source (a hook pulled to the front, then the clip from+ # its start): the reader only runs forward, so open it again rather than hold the last frame.+ close = getattr(reader, "close", None)+ if close is not None:+ close()+ if info.picture is None: # seek straight to frame k (CFR proxy: frame k starts at k / fps)+ reader, current, k_read = iter(video.FrameReader(info, start=max(0.0, k / fps - 1e-3))), None, k - 1+ else:+ reader, current, k_read = frames(info), None, -1while k_read < k:nxt = next(reader, None)if nxt is None: # the clip ran a frame short of its stated length: hold the lastdiff --git a/edit/captions-hf.mjs b/edit/captions-hf.mjsindex 2164212..09afa12 100644--- a/edit/captions-hf.mjs+++ b/edit/captions-hf.mjs@@ -1,28 +1,45 @@// Phụ đề bản chính: một cảnh HyperFrames nền trong suốt (chỉ có chữ), render ra WebM VP9 có alpha,// rồi ffmpeg chồng lên video nền. Font tiếng Việt lấy từ engine/fonts (fonts.css của LumReels).// Mốc chữ đổi từ giây nguồn sang giây bản ra theo keep[] của EDL — cùng luật chia thẻ với phụ đề nháp (lumedit.py).+// Có câu móc (edl.hook) thì bản ra = [móc] + keep: timelineOf(edl) dời mọi mốc; móc lặp lại (repeat) thì chữ của+// câu móc hiện 2 lần (đầu clip và chỗ cũ). Mọi kiểu hiện chữ là hàm của t − c.start (render(t) thuần, gsap seek).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 { toOutputNearest, outputDuration, timelineOf, SAFE, OUT } from './edl.mjs';import { graphicsScene, GFX_RUNTIME } from './graphics.mjs';const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));-/** Cùng luật với caption_cards trong edit/py/lumedit.py. */-export function captionCards(edl) {- const cap = edl.captions; const keep = edl.keep;+/** Chia chữ thành nhóm (cùng luật với caption_cards trong edit/py/lumedit.py). */+function groupWords(words, maxWords) {const groups = []; let cur = [];- cap.words.forEach((w, n) => {+ words.forEach((w, n) => {cur.push(w);- const nx = cap.words[n + 1];+ const nx = words[n + 1];const ends = /[.?!,:;…]$/.test(w.w.trim());const gap = nx ? nx.start - w.end : 99;- if (cur.length >= cap.maxWords || ends || gap > 0.45 || !nx) { groups.push(cur); cur = []; }+ if (cur.length >= maxWords || ends || gap > 0.45 || !nx) { groups.push(cur); cur = []; }});- const cards = groups.map((g) => ({ words: g, start: toOutputNearest(keep, g[0].start), end: toOutputNearest(keep, g[g.length - 1].end) }));- cards.sort((a, b) => a.start - b.start);- return finishCards(cards, keep);+ return groups;+}++/** Cùng luật với caption_cards trong edit/py/lumedit.py. */+export function captionCards(edl) {+ const cap = edl.captions; const tl = timelineOf(edl); const H = edl.hook;+ // mỗi chữ mang giây bản ra (o) của chính nó: chữ câu móc lặp lại có 2 chỗ trên bản ra+ const mk = (ws, map) => groupWords(ws, cap.maxWords).map((g) => ({ words: g.map((w) => ({ ...w, o: map(w.start) })), start: map(g[0].start), end: map(g[g.length - 1].end) }));+ const cards = mk(cap.words, (t) => toOutputNearest(tl, t)).sort((a, b) => a.start - b.start);+ if (!H) return finishCards(cards, tl);+ // có câu móc: thẻ của câu móc (0 … hookDur) và thẻ phần sau làm riêng, để thẻ móc không kéo dài qua chỗ nối+ const hd = H.end - H.start;+ const inH = H.repeat ? cap.words.filter((w) => (w.start + w.end) / 2 >= H.start && (w.start + w.end) / 2 <= H.end) : [];+ const head = H.repeat ? mk(inH, (t) => Math.min(hd, Math.max(0, t - H.start))) : cards.filter((c) => c.start < hd - 1e-6);+ const rest = cards.filter((c) => c.start >= hd - 1e-6);+ for (const c of head) c.end = Math.min(c.end, hd);+ const a = head.length ? finishCards(head, tl) : [];+ for (const c of a) c.end = Math.min(c.end, hd);+ return a.concat(rest.length ? finishCards(rest, tl) : []);}export const MIN_CARD = 0.25; // một nhóm chữ hiện ít nhất chừng này (nếu chưa tới nhóm sau)@@ -47,7 +64,7 @@ export function finishCards(cards, keep) {if (nx && c.end - c.start < MERGE_BELOW) { nx.words = c.words.concat(nx.words); nx.start = c.start; continue; }out.push(c);}- for (const c of out) c.wordOut = c.words.map((w) => Math.max(c.start, toOutputNearest(keep, w.start)));+ for (const c of out) c.wordOut = c.words.map((w) => Math.max(c.start, w.o ?? toOutputNearest(keep, w.start)));const bad = cardOverlaps(out);if (bad.length) throw new Error('phụ đề chồng nhau: ' + bad.join('; '));return out;@@ -63,53 +80,225 @@ export function cardOverlaps(cards) {return errs;}-const LOOKS = {+// Khoá: font, weight, size (px), upper, color, hi (chữ nhấn/karaoke), karaoke, cy (tâm dòng, phần khung),+// enter (fade | pop | pop-soft | slide-left | typewriter | ticker | slam | fade-slow),+// stroke (px viền, mặc định 10 chữ hoa / 8), shadow (CSS text-shadow), box (thanh tin), quote (trích dẫn).+// Chép từ khối "look" của edit-styles/<id>.md.+export 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' },+ 'podcast-trich-doan': { font: "'Montserrat'", weight: 800, size: 96, upper: false, color: '#FFFFFF', hi: '#FF8A3D', karaoke: false, cy: 0.56, enter: 'fade' },+ 'ke-chuyen': { font: "'Nunito'", weight: 800, size: 80, upper: false, color: '#FFFFFF', hi: '#7CF0C8', karaoke: true, cy: 0.66, enter: 'pop-soft' },+ 'top-danh-sach': { font: "'Bungee'", weight: 400, size: 78, upper: true, color: '#FFFFFF', hi: '#FF2E93', karaoke: false, cy: 0.74, enter: 'slide-left' },+ 'review-san-pham': { font: "'Oswald'", weight: 700, size: 88, upper: true, color: '#FFFFFF', hi: '#A78BFA', karaoke: false, cy: 0.77, enter: 'pop-soft' },+ 'huong-dan-buoc': { font: "'Space Grotesk'", weight: 700, size: 70, upper: false, color: '#FFFFFF', hi: '#5EA2FF', karaoke: false, cy: 0.72, enter: 'typewriter' },+ 'ban-tin-nhanh': {+ font: "'Barlow Condensed'", weight: 700, size: 64, upper: true, color: '#FFFFFF', hi: '#00E5FF', karaoke: false, cy: 0.775, enter: 'ticker',+ box: { bg: '#0B1E3F', full: true, align: 'left', stroke: 0, tag: 'TIN NÓNG', tagBg: '#E8202A' },+ },+ 'quan-diem-gat': { font: "'Alfa Slab One'", weight: 400, size: 104, upper: true, color: '#FFFFFF', hi: '#FF1F1F', karaoke: true, cy: 0.50, enter: 'slam' },+ 'chot-don-livestream': { font: "'Baloo 2'", weight: 800, size: 96, upper: false, color: '#FFFFFF', hi: '#FFB020', karaoke: false, cy: 0.62, enter: 'pop' },+ 'vlog-nhe': { font: "'Patrick Hand'", weight: 400, size: 60, upper: false, color: '#FFFDF7', hi: '#F5C6A5', karaoke: false, cy: 0.77, enter: 'fade-slow', stroke: 3, shadow: '0 3px 10px rgba(0,0,0,.45)' },+ 'meo-15s': { font: "'Bangers'", weight: 400, size: 128, upper: true, color: '#FFFFFF', hi: '#00FF87', karaoke: false, cy: 0.64, enter: 'pop' },+ 'cau-noi-hay': {+ font: "'Lora'", weight: 600, size: 66, upper: false, color: '#F5F1E8', hi: '#D4AF37', karaoke: false, cy: 0.74, enter: 'fade-slow',+ quote: { font: "'Playfair Display'", weight: 700, italic: true, size: 88, cy: 0.48, color: '#F5F1E8', marks: '#D4AF37', dimTo: 0.35, blurPx: 8, dimIn: 0.8, wordStagger: 0.12 },+ },};+export const lookOf = (captionStyle) => LOOKS[captionStyle] || LOOKS['sach-gon'];++// thanh tin (ticker): ô tag bên trái, chữ căn trái sau tag, cả thanh cao 1,5 em ở cy+const TICKER = { tagX: 60, tagPad: 22, tagEm: 0.62, gap: 24, right: Math.round(SAFE.x1 * OUT.width) };+const tickerTagW = (look) => Math.round([...look.box.tag].length * 0.56 * look.size * TICKER.tagEm + 2 * TICKER.tagPad);/** 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'];+ const look = lookOf(captionStyle);+ if (look.enter === 'ticker') return Math.round(look.cy * OUT.height - 0.75 * look.size) - 8;return Math.round(look.cy * OUT.height - 0.6 * look.size * 1.18) - 8;}+/** Cỡ chữ cho khối chữ tự xuống dòng: thu nhỏ tới khi ước số dòng ≤ maxLines (ước theo bề rộng trung bình 1 ký tự). */+export function fitBlock(text, widthPx, max, { maxLines = 4, em = 0.5, min = 40 } = {}) {+ const n = [...text].length;+ let size = max;+ while (size > min && Math.ceil((n * em * size * 1.1) / widthPx) > maxLines) size -= 2;+ return size;+}++/** Chữ móc: "*3 GIÂY* LÀ XONG" → [{t, hi}] (chữ trong *…* là chữ nhấn). */+export function hookTextParts(text) {+ const parts = []; const re = /\*([^*]+)\*|([^*]+)/g; let m;+ while ((m = re.exec(String(text)))) { if (m[1]) parts.push({ t: m[1], hi: true }); else if (m[2]) parts.push({ t: m[2], hi: false }); }+ return parts;+}++/** Khoảng câu trích dẫn trên bản ra: {q0, q1, end, words:[{w, i, o}]} hoặc null. */+export function quoteSpan(edl, dur) {+ const q = edl.quote; if (!q) return null;+ const look = lookOf(edl.captions.style).quote || LOOKS['cau-noi-hay'].quote;+ const tl = timelineOf(edl);+ const q0 = toOutputNearest(tl, q.start); const q1 = toOutputNearest(tl, q.end);+ const hold = q1 >= dur - 2.0; // câu chốt ở cuối: giữ tối tới hết clip+ const end = hold ? dur : Math.min(dur, q1 + 0.8);+ let last = -Infinity;+ const words = edl.captions.words.filter((w) => (w.start + w.end) / 2 >= q.start - 1e-6 && (w.start + w.end) / 2 <= q.end + 1e-6).map((w) => {+ const o = Math.max(q0, toOutputNearest(tl, w.start), last + look.wordStagger); last = o;+ return { w: w.w, i: w.i, o };+ });+ return { q0, q1, end, hold, words };+}+/*** 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ạ.+ * opts.style: thẻ kiểu (chữ móc hook.text, thanh bước graphics.stepTracker).*/-export function writeCaptionScene(edl, sceneDir, { captions = true, accent } = {}) {- const look = LOOKS[edl.captions.style] || LOOKS['sach-gon'];- 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);+export function writeCaptionScene(edl, sceneDir, { captions = true, accent, style = null } = {}) {+ const look = lookOf(edl.captions.style);+ const tlk = timelineOf(edl);+ const dur = Math.max(1 / OUT.fps, Math.round(outputDuration(tlk) * OUT.fps) / OUT.fps);+ let cards = captions && edl.captions.words.length ? captionCards(edl) : [];+ const gfx = (edl.graphics || []).length ? graphicsScene(edl, { accent: accent || look.hi, stepTracker: !!style?.graphics?.stepTracker, dur }) : null;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);const cy = Math.round(look.cy * OUT.height); const yMax = Math.round(SAFE.y1 * OUT.height);++ // câu trích dẫn: phụ đề thường tắt trong lúc đó+ const qs = captions ? quoteSpan(edl, dur) : null;+ if (qs) {+ cards = cards.filter((c) => !(c.start >= qs.q0 - 1e-3 && c.start < qs.end));+ for (const c of cards) if (c.start < qs.q0 && c.end > qs.q0) c.end = qs.q0;+ }+ const ticker = look.enter === 'ticker' && look.box;+ const tagW = ticker ? tickerTagW(look) : 0;+ const tkLeft = TICKER.tagX + tagW + TICKER.gap; const tkW = TICKER.right - tkLeft;+ const stroke = look.box ? (look.box.stroke ?? 0) : (look.stroke ?? (look.upper ? 10 : 8));+ const shadow = look.shadow || (ticker ? 'none' : '0 6px 18px rgba(0,0,0,.55)');+const html = cards.map((c, ci) => {// dấu , . ; : cuối chữ không hiện trên phụ đề (giữ ? ! …)const text = c.words.map((wd) => { const t = wd.w.replace(/[,.;:]+$/u, '') || wd.w; return look.upper ? t.toUpperCase() : t; });- // cỡ chữ: thẻ 1 chữ dài thì thu nhỏ để vừa vùng an toàn (Anton ~0,48 em mỗi ký tự hoa)- const longest = Math.max(...text.map((t) => t.length));- const size = c.words.length === 1 ? Math.min(look.size, Math.floor(w / (longest * 0.5 + 0.5))) : look.size;- const spans = c.words.map((wd, k) => `<span class="w${hi.has(wd.i) ? ' hi' : ''}" id="c${ci}w${k}">${esc(text[k])}</span>`).join(' ');- return `<div class="card" id="c${ci}" style="font-size:${size}px">${spans}</div>`;+ let size;+ if (ticker) {+ // thanh tin: 1 dòng, thu cỡ theo bề ngang còn lại sau ô tag (Barlow Condensed ~0,46 em mỗi ký tự hoa)+ const n = text.join(' ').length;+ size = Math.max(34, Math.min(look.size, Math.floor(tkW / (n * 0.46 + 0.4))));+ } else {+ // thẻ 1 chữ dài thì thu nhỏ để vừa vùng an toàn (Anton ~0,48 em mỗi ký tự hoa)+ const longest = Math.max(...text.map((t) => t.length));+ size = c.words.length === 1 ? Math.min(look.size, Math.floor(w / (longest * 0.5 + 0.5))) : look.size;+ }+ const inner = (t) => (look.enter === 'typewriter' ? [...t].map((ch) => `<i class="ch">${esc(ch)}</i>`).join('') : esc(t));+ const spans = c.words.map((wd, k) => `<span class="w${hi.has(wd.i) ? ' hi' : ''}" id="c${ci}w${k}">${inner(text[k])}</span>`).join(' ');+ return `<div class="card${ticker ? ' tk' : ''}" id="c${ci}" style="font-size:${size}px">${spans}</div>`;}).join('\n ');++ // thanh tin: mỗi câu (chuỗi thẻ liền nhau tới dấu kết câu / khoảng lặng > 0,5 s) là 1 lượt thanh trượt vào+ const runs = [];+ if (ticker) {+ cards.forEach((c, ci) => {+ const prev = cards[ci - 1];+ const brk = !prev || /[.?!…]$/.test(prev.words[prev.words.length - 1].w.trim()) || c.start - prev.end > 0.5;+ if (brk) runs.push({ first: ci, start: c.start, end: c.end }); else runs[runs.length - 1].end = c.end;+ });+ }+ const firstOfRun = new Set(runs.map((r) => r.first));+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)});`);+ const t0 = c.start.toFixed(3);+ const lines = [`tl.set('#c${ci}', {autoAlpha: 1}, ${t0});`];+ switch (look.enter) {+ case 'pop': lines.push(`tl.fromTo('#c${ci}', {scale: 0.55}, {scale: 1, duration: 0.18, ease: 'back.out(3)'}, ${t0});`); break;+ case '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)'}, ${t0});`); break;+ case 'slide-left': lines.push(`tl.fromTo('#c${ci}', {x: 80, opacity: 0}, {x: 0, opacity: 1, duration: 0.16, ease: 'power3.out'}, ${t0});`); break;+ case 'slam': {+ lines.push(`tl.fromTo('#c${ci}', {scale: 1.6, opacity: 0.4}, {scale: 1, opacity: 1, duration: 0.12, ease: 'power4.in'}, ${t0});`);+ [6, -6, 6, 0].forEach((x, k) => lines.push(`tl.to('#c${ci}', {x: ${x}, duration: 0.025, ease: 'none'}, ${(c.start + 0.12 + k * 0.025).toFixed(3)});`));+ break;+ }+ case 'fade-slow': {+ lines.push(`tl.fromTo('#c${ci}', {opacity: 0}, {opacity: 1, duration: 0.3, ease: 'power1.out'}, ${t0});`);+ const nx = cards[ci + 1];+ if ((!nx || nx.start - c.end >= 0.3) && c.end - c.start > 0.55) lines.push(`tl.to('#c${ci}', {opacity: 0, duration: 0.25, ease: 'power1.in'}, ${(c.end - 0.25).toFixed(3)});`);+ break;+ }+ case 'typewriter': {+ // ký tự k hiện ở c.start + k × min(0,035, (end − start) × 0,6 / số ký tự)+ const n = c.words.reduce((s, wd) => s + [...(wd.w.replace(/[,.;:]+$/u, '') || wd.w)].length, 0);+ const stepS = Math.min(0.035, ((c.end - c.start) * 0.6) / Math.max(1, n));+ lines.push(`tl.set('#c${ci} .ch', {opacity: 0}, ${t0});`);+ lines.push(`gsap.utils.toArray('#c${ci} .ch').forEach(function (el, k) { tl.set(el, {opacity: 1}, ${t0} + k * ${stepS.toFixed(4)}); });`);+ break;+ }+ case 'ticker': {+ if (!firstOfRun.has(ci)) lines.push(`tl.fromTo('#c${ci}', {opacity: 0}, {opacity: 1, duration: 0.08, ease: 'none'}, ${t0});`);+ break;+ }+ default: lines.push(`tl.fromTo('#c${ci}', {y: 18, opacity: 0}, {y: 0, opacity: 1, duration: 0.12, ease: 'power2.out'}, ${t0});`);+ }if (look.karaoke && c.words.length > 1) {c.words.forEach((wd, k) => {- const t0 = c.wordOut[k]; const t1 = k + 1 < c.words.length ? c.wordOut[k + 1] : c.end;- lines.push(`tl.set('#c${ci}w${k}', {color: '${look.hi}'}, ${t0.toFixed(3)}); tl.set('#c${ci}w${k}', {color: '${hi.has(wd.i) ? look.hi : look.color}'}, ${t1.toFixed(3)});`);+ const a = c.wordOut[k]; const b = k + 1 < c.words.length ? c.wordOut[k + 1] : c.end;+ lines.push(`tl.set('#c${ci}w${k}', {color: '${look.hi}'}, ${a.toFixed(3)}); tl.set('#c${ci}w${k}', {color: '${hi.has(wd.i) ? look.hi : look.color}'}, ${b.toFixed(3)});`);});}lines.push(`tl.set('#c${ci}', {autoAlpha: 0}, ${c.end.toFixed(3)});`);return lines.join(' ');- }).join('\n ');+ });+ runs.forEach((r, k) => {+ timeline.push(`tl.set('#tbar', {autoAlpha: 1}, ${r.start.toFixed(3)}); tl.fromTo('#tbar', {x: -${OUT.width}}, {x: 0, duration: 0.2, ease: 'power3.out'}, ${r.start.toFixed(3)});`);+ const nx = runs[k + 1];+ if (!nx || nx.start > r.end + 0.02) timeline.push(`tl.set('#tbar', {autoAlpha: 0}, ${r.end.toFixed(3)});`);+ });++ // câu trích dẫn to giữa khung+ let quoteHtml = ''; let quoteCss = '';+ if (qs && qs.words.length) {+ const q = look.quote || LOOKS['cau-noi-hay'].quote;+ const text = qs.words.map((x) => x.w).join(' ');+ const qsize = fitBlock(`“${text}”`, w, q.size, { maxLines: 4, em: 0.5, min: 44 });+ quoteHtml = `<div id="quote" style="font-size:${qsize}px"><span class="qm" id="qmo">“</span>${qs.words.map((x, k) => `<span class="qw${hi.has(x.i) ? ' hi' : ''}" id="qw${k}">${esc(x.w)}</span>`).join(' ')}<span class="qm" id="qmc">”</span></div>`;+ quoteCss = `+ #quote { position:absolute; left:${x0}px; width:${w}px; top:${Math.round(q.cy * OUT.height)}px; transform:translateY(-50%); text-align:center; line-height:1.25;+ font-family:${q.font}, serif; font-weight:${q.weight}; font-style:${q.italic ? 'italic' : 'normal'}; color:${q.color};+ text-shadow:0 4px 24px rgba(0,0,0,.6); visibility:hidden; opacity:0; }+ #quote .qw { display:inline-block; opacity:0; }+ #quote .qw.hi { color:${q.marks}; }+ #quote .qm { color:${q.marks}; font-size:1.3em; line-height:0; opacity:0; padding:0 .06em; }`;+ timeline.push(`tl.set('#quote', {autoAlpha: 1}, ${qs.q0.toFixed(3)}); tl.to('#qmo', {opacity: 1, duration: 0.3}, ${qs.q0.toFixed(3)});`);+ qs.words.forEach((x, k) => timeline.push(`tl.fromTo('#qw${k}', {opacity: 0, y: 14}, {opacity: 1, y: 0, duration: 0.2, ease: 'power2.out'}, ${x.o.toFixed(3)});`));+ const lastO = qs.words[qs.words.length - 1].o;+ timeline.push(`tl.to('#qmc', {opacity: 1, duration: 0.3}, ${(lastO + 0.15).toFixed(3)});`);+ if (!qs.hold) timeline.push(`tl.to('#quote', {opacity: 0, duration: 0.3}, ${Math.max(lastO + 0.4, qs.end - 0.3).toFixed(3)}); tl.set('#quote', {autoAlpha: 0}, ${qs.end.toFixed(3)});`);+ }++ // chữ móc to 0 → until (kiểu meo-15s)+ let hookHtml = ''; let hookCss = '';+ if (captions && edl.hookText) {+ const ht = { font: "'Bangers'", size: 150, cy: 0.22, color: '#FFFFFF', hi: look.hi, ...(style?.hook?.text || {}) };+ const parts = hookTextParts(edl.hookText.text.toUpperCase());+ const plain = parts.map((p) => p.t).join('');+ const hsize = fitBlock(plain, w, ht.size, { maxLines: 2, em: 0.46, min: 70 });+ hookHtml = `<div id="hooktext" style="font-size:${hsize}px">${parts.map((p) => `<span${p.hi ? ' class="hi"' : ''}>${esc(p.t)}</span>`).join('')}</div>`;+ hookCss = `+ #hooktext { position:absolute; left:${x0}px; width:${w}px; top:${Math.round(ht.cy * OUT.height)}px; margin-top:-0.55em; text-align:center; line-height:1.05;+ font-family:${ht.font}, sans-serif; color:${ht.color}; -webkit-text-stroke:12px #000; paint-order:stroke fill;+ text-shadow:0 8px 24px rgba(0,0,0,.55); transform-origin:50% 50%; visibility:hidden; opacity:0; }+ #hooktext .hi { color:${ht.hi}; }`;+ const until = Math.min(edl.hookText.until, dur);+ timeline.push(`tl.set('#hooktext', {autoAlpha: 1}, 0); tl.fromTo('#hooktext', {scale: 0.4, rotation: -4}, {scale: 1, rotation: -2, duration: 0.3, ease: 'back.out(2.6)'}, 0); tl.to('#hooktext', {opacity: 0, scale: 1.08, duration: 0.18}, ${Math.max(0.35, until - 0.18).toFixed(3)}); tl.set('#hooktext', {autoAlpha: 0}, ${until.toFixed(3)});`);+ }++ const tickerHtml = ticker ? `<div id="tbar"><div class="tag">${esc(look.box.tag)}</div>\n ${html}\n </div>` : '';+ const tickerCss = ticker ? `+ #tbar { position:absolute; left:0; width:${OUT.width}px; top:${cy}px; height:${Math.round(1.5 * look.size)}px; margin-top:-${Math.round(0.75 * look.size)}px;+ background:${look.box.bg}; visibility:hidden; opacity:0; box-shadow:0 10px 30px rgba(0,0,0,.35); }+ #tbar .tag { position:absolute; left:${TICKER.tagX}px; top:0; height:100%; width:${tagW}px; box-sizing:border-box; padding:0 ${TICKER.tagPad}px; background:${look.box.tagBg};+ color:#fff; font-family:${look.font}, sans-serif; font-weight:800; font-size:${Math.round(look.size * TICKER.tagEm)}px; line-height:${Math.round(1.5 * look.size)}px; letter-spacing:.04em; white-space:nowrap; text-align:center; }+ #tbar .card.tk { left:${tkLeft}px; width:${tkW}px; top:0; margin-top:0; height:100%; line-height:${Math.round(1.5 * look.size)}px; text-align:left; white-space:nowrap; max-height:none; overflow:hidden; }` : '';+const doc = `<!doctype html><html lang="vi"><head>@@ -123,30 +312,34 @@ export function writeCaptionScene(edl, sceneDir, { captions = true, accent } = {.card { position:absolute; left:${x0}px; width:${w}px; top:${cy}px; transform-origin:50% 50%;margin-top:-0.6em; text-align:center; line-height:1.18; visibility:hidden; opacity:0;font-family:${look.font}, sans-serif; font-weight:${look.weight}; color:${look.color};- -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; }+ -webkit-text-stroke: ${stroke}px #000; paint-order: stroke fill;+ text-shadow: ${shadow}; max-height:${yMax - cy}px; }.card .w { display:inline-block; }- .card .hi { color:${look.hi}; }${gfx ? gfx.css : ''}+ .card .ch { font-style:normal; }+ .card .hi { color:${look.hi}; }${tickerCss}${quoteCss}${hookCss}${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}+ ${ticker ? tickerHtml : html}+ ${quoteHtml}+ ${hookHtml}</div>${gfx ? `<script src="./lib/runtime/scene.js"></script><script>const tl = gsap.timeline({ paused: true });tl.set({}, {}, ${dur.toFixed(3)});- ${timeline}+ ${timeline.join('\n ')}const G = ${JSON.stringify(gfx.data)};+ const S = ${JSON.stringify(gfx.steps || null)};${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); } });+ render(t) { tl.seek(t, false); gfxRender(t, G); stepsRender(t, S); } });</script>` : `<script>const tl = gsap.timeline({ paused: true });tl.set({}, {}, ${dur.toFixed(3)});- ${timeline}+ ${timeline.join('\n ')}window.__timelines = window.__timelines || {};window.__timelines.main = tl;</script>`}@@ -156,7 +349,7 @@ ${gfx ? `<script src="./lib/runtime/scene.js"></script>fs.mkdirSync(sceneDir, { recursive: true });fs.writeFileSync(path.join(sceneDir, 'index.html'), doc);syncLib(sceneDir);- return { duration: dur, cards: cards.length, graphics: (edl.graphics || []).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 }, quote: !!qs, hookText: !!hookHtml, ticker: !!ticker };}/** Render lớp chữ trong suốt → WebM VP9 alpha. */diff --git a/edit/edl.mjs b/edit/edl.mjsindex 803f490..390f636 100644--- a/edit/edl.mjs+++ b/edit/edl.mjs@@ -74,27 +74,50 @@ export const EdlSchema = 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)'),+ hook: z.object({+ start: sec, end: sec,+ repeat: z.boolean().describe('true: câu móc vẫn phát lại ở chỗ cũ; false: đã trừ khỏi keep'),+ flash: z.boolean().describe('chớp trắng 2 khung ở chỗ nối móc → clip'),+ sfx: z.object({ name: z.string(), at: sec.describe('giây nguồn (trong khoảng móc)'), gainDb: z.number().min(-30).max(6) }).strict().nullable(),+ }).strict().nullable().default(null)+ .describe('câu móc kéo lên đầu: bản ra = [hook] + keep[]; mọi mốc bản ra của keep dời thêm (end − start)'),+ hookText: z.object({ text: z.string().min(1).max(40), until: z.number().min(0.5).max(5) }).strict().nullable().default(null)+ .describe('chữ móc to ở 0 → until giây bản ra (chữ nhấn trong *…*)'),+ quote: z.object({+ start: sec, end: sec, dimTo: z.number().min(0.1).max(1), blurPx: z.number().min(0).max(30), dimIn: z.number().min(0.1).max(3),+ }).strict().nullable().default(null).describe('câu trích dẫn to giữa khung (giây nguồn); video tối + mờ trong lúc đó'),audio: z.object({ crossfadeMs: z.number().min(5).max(80), keepSourceAudio: z.literal(true) }).strict(),notes: z.string().optional(),}).strict();// ---- ánh xạ thời gian nguồn → bản ra --------------------------------------------------------------------export function outputDuration(keep) { return keep.reduce((s, k) => s + (k.end - k.start), 0); }+// Các hàm dưới nhận `keep` (mảng đoạn giữ). Có câu móc (edl.hook) thì truyền timelineOf(edl): cùng mảng keep, kèm+// thuộc tính .hook — bản ra = [hook] + keep, mọi mốc của keep dời thêm hookDur. Mốc nằm cả trong keep lẫn trong+// hook (repeat) thì lấy chỗ trong keep; mốc chỉ có trong hook (repeat: false) thì về 0 … hookDur.+export const hookDur = (keep) => (keep?.hook ? keep.hook.end - keep.hook.start : 0);+/** Mảng keep của EDL (bản sao) mang theo .hook để các hàm ánh xạ biết câu móc ở đầu bản ra. */+export function timelineOf(edl) {+ const k = edl.keep.map((x) => ({ start: x.start, end: x.end }));+ if (edl.hook) Object.defineProperty(k, 'hook', { value: { ...edl.hook }, enumerable: false });+ return k;+}+const inHook = (keep, t) => !!keep?.hook && t >= keep.hook.start - 1e-9 && t <= keep.hook.end + 1e-9;+export function outputDuration(keep) { return hookDur(keep) + keep.reduce((s, k) => s + (k.end - k.start), 0); }/** Giây nguồn → giây bản ra; null nếu rơi vào đoạn bỏ. */export function toOutput(keep, t) {- let acc = 0;+ let acc = hookDur(keep);for (const k of keep) {- if (t < k.start - 1e-9) return null;+ if (t < k.start - 1e-9) break;if (t <= k.end + 1e-9) return acc + (t - k.start);acc += k.end - k.start;}- return null;+ return inHook(keep, t) ? t - keep.hook.start : null;}/** Như toOutput nhưng mốc rơi vào đoạn bỏ thì dời về mép giữ gần nhất. */export function toOutputNearest(keep, t) {const got = toOutput(keep, t);if (got !== null) return got;- let best = 0; let bd = Infinity; let acc = 0;+ let best = 0; let bd = Infinity; let acc = hookDur(keep);for (const k of keep) {for (const [src, o] of [[k.start, acc], [k.end, acc + k.end - k.start]]) {if (Math.abs(src - t) < bd) { bd = Math.abs(src - t); best = o; }@@ -103,7 +126,7 @@ export function toOutputNearest(keep, t) {}return best;}-export const inKeep = (keep, t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6);+export const inKeep = (keep, t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6) || inHook(keep, t);/*** Kiểm EDL: schema + luật thời gian. Trả {ok, errors:[{code, path, msg}], edl}.@@ -119,29 +142,42 @@ export function validateEdl(input, { sfxNames, checkFiles = true } = {}) {}const e = parsed.data;const dur = e.source.duration;+ const tl = timelineOf(e);const frame = 1 / e.output.fps;e.keep.forEach((k, i) => {if (k.end - k.start < frame) add('keep-short', `keep.${i}`, `đoạn giữ ${k.start}–${k.end} ngắn hơn 1 khung`);if (k.end > dur + 0.05) add('keep-out', `keep.${i}`, `đoạn giữ vượt quá độ dài nguồn (${dur.toFixed(2)} s)`);if (i && k.start < e.keep[i - 1].end - 1e-6) add('keep-overlap', `keep.${i}`, `đoạn giữ chồng/ngược thứ tự với đoạn trước`);});- const outDur = outputDuration(e.keep);+ if (e.hook) {+ const h = e.hook; const hd = h.end - h.start;+ if (hd < 0.3 || hd > 6) add('hook-len', 'hook', `câu móc dài ${hd.toFixed(2)} s (cần 0,3–6 s)`);+ if (h.end > dur + 0.05) add('hook-out', 'hook', 'câu móc vượt quá độ dài nguồn');+ if (h.sfx && (h.sfx.at < h.start - 1e-6 || h.sfx.at > h.end + 1e-6)) add('hook-sfx', 'hook.sfx', 'tiếng của câu móc nằm ngoài câu móc');+ if (h.sfx && sfxNames && !sfxNames.includes(h.sfx.name)) add('sfx-name', 'hook.sfx', `không có tiếng "${h.sfx.name}"`);+ if (!h.repeat && e.keep.some((k) => k.start < h.end - 1e-3 && k.end > h.start + 1e-3)) add('hook-overlap', 'hook', 'câu móc không lặp lại (repeat: false) mà vẫn nằm trong keep');+ }+ if (e.quote) {+ if (e.quote.end <= e.quote.start) add('quote', 'quote', 'câu trích dẫn kết thúc trước khi bắt đầu');+ else if (!inKeep(tl, e.quote.start) || !inKeep(tl, e.quote.end)) add('quote-cut', 'quote', 'câu trích dẫn rơi vào đoạn bị bỏ');+ }+ const outDur = outputDuration(tl);if (outDur < 1) add('too-short', 'keep', `bản ra chỉ ${outDur.toFixed(2)} s`);e.zooms.forEach((zm, i) => {- if (!inKeep(e.keep, zm.at)) add('zoom-cut', `zooms.${i}`, `zoom ở ${zm.at} s rơi vào đoạn bị bỏ`);+ if (!inKeep(tl, zm.at)) add('zoom-cut', `zooms.${i}`, `zoom ở ${zm.at} s rơi vào đoạn bị bỏ`);if (i && zm.at < e.zooms[i - 1].at) add('zoom-order', `zooms.${i}`, 'zoom phải theo thứ tự thời gian');});const ids = new Set();e.captions.words.forEach((w, i) => {if (w.end < w.start) add('word-time', `captions.words.${i}`, `chữ "${w.w}" kết thúc trước khi bắt đầu`);- if (!inKeep(e.keep, (w.start + w.end) / 2)) add('word-cut', `captions.words.${i}`, `chữ "${w.w}" ở ${w.start} s nằm trong đoạn bị bỏ`);+ if (!inKeep(tl, (w.start + w.end) / 2)) add('word-cut', `captions.words.${i}`, `chữ "${w.w}" ở ${w.start} s nằm trong đoạn bị bỏ`);if (i && w.start < e.captions.words[i - 1].start - 1e-6) add('word-order', `captions.words.${i}`, 'chữ phải theo thứ tự thời gian');ids.add(w.i);});e.captions.highlights.forEach((h, i) => { if (!ids.has(h)) add('highlight', `captions.highlights.${i}`, `chữ nhấn ${h} không có trong phụ đề`); });e.sfx.forEach((s, i) => {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ỏ`);+ if (!inKeep(tl, 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) {diff --git a/edit/edl.schema.json b/edit/edl.schema.jsonindex 5007cb4..f7b8937 100644--- a/edit/edl.schema.json+++ b/edit/edl.schema.json@@ -618,6 +618,149 @@"additionalProperties": false}},+ "hook": {+ "default": null,+ "description": "câu móc kéo lên đầu: bản ra = [hook] + keep[]; mọi mốc bản ra của keep dời thêm (end − start)",+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "start": {+ "type": "number",+ "minimum": 0+ },+ "end": {+ "type": "number",+ "minimum": 0+ },+ "repeat": {+ "type": "boolean",+ "description": "true: câu móc vẫn phát lại ở chỗ cũ; false: đã trừ khỏi keep"+ },+ "flash": {+ "type": "boolean",+ "description": "chớp trắng 2 khung ở chỗ nối móc → clip"+ },+ "sfx": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "at": {+ "type": "number",+ "minimum": 0,+ "description": "giây nguồn (trong khoảng móc)"+ },+ "gainDb": {+ "type": "number",+ "minimum": -30,+ "maximum": 6+ }+ },+ "required": [+ "name",+ "at",+ "gainDb"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "start",+ "end",+ "repeat",+ "flash",+ "sfx"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "hookText": {+ "default": null,+ "description": "chữ móc to ở 0 → until giây bản ra (chữ nhấn trong *…*)",+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "text": {+ "type": "string",+ "minLength": 1,+ "maxLength": 40+ },+ "until": {+ "type": "number",+ "minimum": 0.5,+ "maximum": 5+ }+ },+ "required": [+ "text",+ "until"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "quote": {+ "default": null,+ "description": "câu trích dẫn to giữa khung (giây nguồn); video tối + mờ trong lúc đó",+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "start": {+ "type": "number",+ "minimum": 0+ },+ "end": {+ "type": "number",+ "minimum": 0+ },+ "dimTo": {+ "type": "number",+ "minimum": 0.1,+ "maximum": 1+ },+ "blurPx": {+ "type": "number",+ "minimum": 0,+ "maximum": 30+ },+ "dimIn": {+ "type": "number",+ "minimum": 0.1,+ "maximum": 3+ }+ },+ "required": [+ "start",+ "end",+ "dimTo",+ "blurPx",+ "dimIn"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },"audio": {"type": "object","properties": {diff --git a/edit/graphics.mjs b/edit/graphics.mjsindex 526d784..fe787d9 100644--- a/edit/graphics.mjs+++ b/edit/graphics.mjs@@ -6,7 +6,7 @@// 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, unitAfter, unitOf, sameUnit, quantityText } from './numbers.mjs';-import { toOutputNearest, inKeep, OUT, SAFE } from './edl.mjs';+import { toOutputNearest, inKeep, timelineOf, outputDuration, hookDur, 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']);@@ -161,9 +161,22 @@ export async function selectSegments({ words, target, style, content, names, dur}// ---- 1b. kế hoạch đồ hoạ --------------------------------------------------------------------------------------------+/** Loại đồ hoạ kiểu này được dùng (style.graphics.types; không ghi thì cả 9 loại). */+export const allowedTypes = (style) => (Array.isArray(style?.graphics?.types) && style.graphics.types.length ? style.graphics.types.filter((t) => GRAPHIC_TYPES.includes(t)) : GRAPHIC_TYPES);++/** Những gì engine tự vẽ thêm theo thẻ kiểu, để LLM không làm trùng. */+function engineNotes(style) {+ const n = [];+ if (style.graphics?.pinFirst) n.push('- title_card ĐẦU TIÊN được ghim ở mép trên suốt clip (thu nhỏ sau 3 giây): chỉ cần 1 title_card ở chữ đầu tiên được giữ, không thêm đồ hoạ lớn nào khác.');+ if (style.graphics?.stepTracker) n.push('- Code vẽ thanh tiến độ bước ở mép trên suốt clip, mỗi title_card có kicker "BƯỚC n" là 1 chấm (tick khi sang bước sau): ghi kicker đúng dạng "BƯỚC 1", "BƯỚC 2"…');+ if (style.hook?.text) n.push('- Code tự vẽ chữ móc to 0–2 giây đầu (hookText): KHÔNG dùng title_card làm chữ móc.');+ return n.length ? `\n# Engine tự làm\n${n.join('\n')}\n` : '';+}+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).+ const types = allowedTypes(style);+ return `Mày là designer đồ hoạ thông tin cho short dọc tiếng Việt.Đọ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.@@ -178,17 +191,19 @@ ${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>","unit":"<đơn vị chung của các ô số, tuỳ chọn>","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>"}+${engineNotes(style)}+# Các loại đồ hoạ được dùng cho kiểu này (at/until/word là chỉ số chữ [i]; KHÔNG dùng loại khác)+${[+ ['counter', "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', "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', "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', "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', "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', "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', "spec_table: bảng thông số, dòng nổi lên theo chữ. {\"type\":\"spec_table\",\"at\":i,\"until\":j,\"title\":\"<≤ 30>\",\"unit\":\"<đơn vị chung của các ô số, tuỳ chọn>\",\"rows\":[{\"label\":\"<≤ 14>\",\"value\":\"<≤ 14>\",\"word\":i}]} (1–6 dòng)"],+ ['checklist', "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', "title_card: thẻ chương khi chuyển ý lớn. {\"type\":\"title_card\",\"at\":i,\"until\":j,\"kicker\":\"<≤ 20, tuỳ chọn>\",\"title\":\"<≤ 28>\"}"],+ ].filter(([t]) => types.includes(t)).map(([, l]) => '- ' + l).join('\n')}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ề@@ -209,7 +224,7 @@ ${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previou* 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) {+export function checkGraphics(plan, words, usable, spoken, types = GRAPHIC_TYPES) {const errors = []; const clean = [];const list = Array.isArray(plan?.graphics) ? plan.graphics : null;if (!list) return { errors: ['thiếu mảng "graphics"'], clean };@@ -218,7 +233,8 @@ export function checkGraphics(plan, words, usable, spoken) {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 (!g || !GRAPHIC_TYPES.includes(g.type)) { errors.push(`${where}: loại không hợp lệ (có: ${types.join(', ')})`); return; }+ if (!types.includes(g.type)) { errors.push(`${where}: kiểu này không dùng ${g.type} (chỉ: ${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;@@ -526,7 +542,7 @@ export async function planGraphics({ words, dropped, style, content, names, calltry {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);+ checked = checkGraphics(parse(text), words, usable, spoken, allowedTypes(style));} 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('; ')}`);@@ -542,25 +558,48 @@ export async function planGraphics({ words, dropped, style, content, names, call* 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}.*/+/**+ * Lúc chữ bắt đầu, kẹp vào đoạn giữ chứa giữa chữ: mép đoạn giữ đặt theo khoảng lặng thật nên có khi muộn hơn+ * mốc whisper của chữ đầu đoạn vài chục ms; mốc đồ hoạ/zoom/sfx rơi ra ngoài keep thì bị lọc hoặc làm EDL hỏng.+ */+export function wordStart(keep, w) {+ const mid = (w.s + w.e) / 2;+ const k = keep.find((x) => mid >= x.start - 1e-6 && mid <= x.end + 1e-6);+ return k ? Math.min(Math.max(w.s, k.start), k.end) : w.s;+}+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 outEnd = outputDuration(keep);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 t = (i) => { const w = byI.get(i); return +wordStart(keep, w || wa).toFixed(3); };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 });+ const a0 = wordStart(keep, wa);+ data.at = +a0.toFixed(3);+ gs.push({ id: `g${n + 1}`, type: p.type, start: +Math.max(0, a0 - 0.05).toFixed(3), end: +(wu.e + HOLD).toFixed(3), estimate: !!p.estimate, data, box: null, face: null, squeeze: null });});+ // ghim tiêu đề (pinFirst): title_card đầu tiên hiện suốt clip ở mép trên → bỏ trần 14 s; đồ hoạ lớn khác sẽ chồng nó nên bỏ+ const pinIdx = style.graphics?.pinFirst ? gs.findIndex((g) => g.type === 'title_card') : -1;+ if (pinIdx >= 0) {+ for (let k = gs.length - 1; k >= 0; k--) {+ if (k !== pinIdx && BIG.has(gs[k].type)) { warnings.push(`đồ hoạ ${gs[k].type} ở ${gs[k].start.toFixed(2)} s: thẻ tiêu đề đang ghim suốt clip, bỏ`); gs.splice(k, 1); }+ }+ }// giây bản ra: ≥ 1,5 s; không vượt đồ hoạ cùng hạng tiếp theo; ≤ 14 sconst out = [];for (let k = 0; k < gs.length; k++) {const g = gs[k];const o0 = toOutputNearest(keep, g.start);+ if (pinIdx >= 0 && g.type === 'title_card') {+ g.end = +outputToSource(keep, outEnd).toFixed(3); g.data.pin = true;+ g.outStart = +o0.toFixed(3); g.outEnd = +outEnd.toFixed(3);+ out.push(g); continue;+ }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);@@ -585,7 +624,8 @@ export function compileGraphics({ plan, words, keep, style }) {/** Giây bản ra → giây nguồn (trong keep). */export function outputToSource(keep, o) {- let acc = 0;+ let acc = hookDur(keep);+ if (o < acc) return keep.hook.start + Math.max(0, o);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;}@@ -611,14 +651,24 @@ export const squeezeBox = (b, q) => (b && q ? [Math.round(OUT.width / 2 + (b[0]* Đồ 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) {+export const STEP_BAR = { y: 196, h: 44 }; // thanh tiến độ bước (stepTracker): dải chấm ở mép trên vùng an toàn+export function layoutGraphics(graphics, keep, faces, captionTop, { stepTracker = false } = {}) {const warnings = [];- const Y0 = Math.round(SAFE.y0 * OUT.height) + 8; const Y1 = Math.min(captionTop - 24, Math.round(SAFE.y1 * OUT.height));+ const Y0 = stepTracker ? STEP_BAR.y + STEP_BAR.h + 16 : 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);+ if (g.data?.pin) {+ // thẻ ghim: cố định sát mép trên vùng an toàn suốt clip (không né mặt theo từng lúc; podcast mặt thường ở giữa khung)+ const { w, h } = baseSize(g); const s = +Math.min(1, (X1 - X0) / w).toFixed(3);+ const box = { x: Math.round(OUT.width / 2 - (w * s) / 2), y: Math.round(SAFE.y0 * OUT.height), w: Math.round(w * s), h: Math.round(h * s), scale: s };+ g.box = box; g.face = null; g.squeeze = null;+ placed.push({ o0, o1, box, squeeze: null });+ out.push(g); continue;+ }let fb = null;for (const [t, b] of faces?.boxes || []) {if (!b || t < o0 - 0.15 || t > o1 + 0.15) continue;@@ -672,7 +722,7 @@ export function layoutGraphics(graphics, keep, faces, captionTop) {/** 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 keep = timelineOf(edl); 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) => {@@ -753,20 +803,30 @@ function graphicHtml(g, k) {}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>`;+ return `<div class="gw" id="g${k}" style="left:${b.x}px;top:${b.y}px;width:${b.w}px;height:${b.h}px${d.pin ? ';transform-origin:50% 0' : ''}"><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' } = {}) {+/** Thẻ title_card có kicker "BƯỚC n" (kiểu hướng dẫn) → mốc bản ra của từng bước, theo thứ tự. */+export function stepTimes(edl) {+ const keep = timelineOf(edl);+ return (edl.graphics || []).filter((g) => g.type === 'title_card' && /^(bước|buoc)\s*\d+/u.test(String(g.data?.kicker || '').normalize('NFC').toLowerCase().trim()))+ .map((g) => +toOutputNearest(keep, g.start).toFixed(3)).sort((a, b) => a - b);+}++export function graphicsScene(edl, { accent = '#FCE802', stepTracker = false, dur = null } = {}) {const gs = edl.graphics || [];- const keep = edl.keep;- const html = gs.map((g, k) => graphicHtml(g, k)).join('\n ');+ const keep = timelineOf(edl);+ const st = stepTracker ? stepTimes(edl) : [];+ const steps = st.length >= 2 ? { t: st, end: +(dur ?? outputDuration(keep)).toFixed(3) } : null;+ const stepHtml = steps ? `<div id="stepbar" style="top:${STEP_BAR.y}px;height:${STEP_BAR.h}px">${st.map((_, k) => `${k ? '<i class="sl"></i>' : ''}<div class="sd" id="sd${k}"><span>${k + 1}</span><svg viewBox="0 0 40 40"><path d="M11 21 l6 6 l12 -13"/></svg></div>`).join('')}</div>` : '';+ const html = gs.map((g, k) => graphicHtml(g, k)).join('\n ') + stepHtml;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 };+ return { type: g.type, t0: tt(g.start), t1: tt(g.end), at: tt(d.at ?? g.start), items, pts, pin: !!d.pin };});const css = `.gw { position:absolute; visibility:hidden; opacity:0; transform-origin:50% 50%; }@@ -822,7 +882,16 @@ export function graphicsScene(edl, { accent = '#FCE802' } = {}) {.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 };+ const stepCss = steps ? `+ #stepbar { position:absolute; left:0; width:${OUT.width}px; display:flex; align-items:center; justify-content:center; gap:0; opacity:0; }+ #stepbar .sd { position:relative; width:${STEP_BAR.h}px; height:${STEP_BAR.h}px; border-radius:50%; box-sizing:border-box; border:3px solid rgba(255,255,255,.55);+ background:rgba(10,12,17,.55); color:#fff; font:800 22px/38px 'Be Vietnam Pro', sans-serif; text-align:center; }+ #stepbar .sd.on { background:${accent}; border-color:${accent}; color:#111; box-shadow:0 0 18px ${accent}88; }+ #stepbar .sd svg { position:absolute; left:0; top:0; width:100%; height:100%; opacity:0; }+ #stepbar .sd path { fill:none; stroke:#111; stroke-width:5; stroke-linecap:round; stroke-linejoin:round; stroke-dasharray:30; stroke-dashoffset:30; }+ #stepbar .sl { display:block; width:34px; height:4px; border-radius:2px; background:rgba(255,255,255,.35); }+ #stepbar .sl.on { background:${accent}; }` : '';+ return { css: css + stepCss, html, data, steps };}/** Hàm vẽ chạy trong trang: G = graphicsScene().data. Thuần theo t. */@@ -843,6 +912,7 @@ function gfxRender(t, G) {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}));+ if (g.pin) s *= 1 - 0.2 * outCubic(prog(t, g.t0 + 3, 0.4)); // thẻ ghim: 3 s đầu cỡ thật, rồi thu về 0,8el.style.opacity = a;el.style.transform = 'scale(' + s.toFixed(4) + ') rotate(' + rot + 'deg)';var vs = el.querySelectorAll('.v');@@ -894,6 +964,24 @@ function gfxRender(t, G) {el.querySelector('.ttl').style.transform = 'translateX(' + (-(1 - kc) * 40).toFixed(1) + 'px)';}}+}+function stepsRender(t, S) {+ if (!S) return;+ var clamp = function (x) { return x < 0 ? 0 : x > 1 ? 1 : x; };+ var bar = document.getElementById('stepbar');+ bar.style.opacity = clamp(t / 0.3) * clamp((S.end - t) / 0.25);+ var n = S.t.length, links = bar.querySelectorAll('.sl');+ for (var k = 0; k < n; k++) {+ var el = document.getElementById('sd' + k);+ var on = t >= S.t[k], doneAt = k + 1 < n ? S.t[k + 1] : S.end - 0.6, done = t >= doneAt;+ el.className = 'sd' + (on ? ' on' : '');+ var u = clamp((t - S.t[k]) / 0.25), pop = on ? 1 + 0.25 * Math.sin(Math.PI * u) : 1;+ el.style.transform = 'scale(' + pop.toFixed(3) + ')';+ var svg = el.querySelector('svg'), num = el.querySelector('span'), kt = clamp((t - doneAt) / 0.25);+ svg.style.opacity = done ? 1 : 0; num.style.opacity = done ? 0 : 1;+ el.querySelector('path').style.strokeDashoffset = (30 * (1 - kt)).toFixed(1);+ if (k) links[k - 1].className = 'sl' + (on ? ' on' : '');+ }}`;/** Chữ nhấn số cho phụ đề: chữ có chữ số, và đơn vị/hệ số đứng ngay sau chữ số. */diff --git a/edit/http.mjs b/edit/http.mjsindex b3dde8b..79165e2 100644--- a/edit/http.mjs+++ b/edit/http.mjs@@ -10,12 +10,13 @@// 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>// GET /edits/:id/(out.mp4|out-r<n>.mp4|preview.jpg|preview-final.jpg|edl.json)+// GET /edit-styles/thumbs/<id>.webp → ảnh minh hoạ dọc của thẻ kiểu (lưới chọn kiểu)import fs from 'node:fs';import path from 'node:path';import { MUSIC_LIST, MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';import {ID_RE, EDITS, editDir, newEditId, createEdit, runEditJob, reviseEditJob, editView, listEdits, editStyles, editReady, readEditJob,- markStaleEdits, deleteEdit,+ markStaleEdits, deleteEdit, STYLE_THUMBS,} from './jobs.mjs';import { installStatus, startInstall } from './setup-run.mjs';@@ -142,6 +143,9 @@ let uploading = false; // một lúc chỉ nhận 1 upload/** Trả true nếu đã xử lý route. */export async function handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts }) {+ // ảnh minh hoạ của thẻ kiểu edit (lưới chọn kiểu)+ const th = /^\/edit-styles\/thumbs\/([a-z0-9-]{1,40}\.webp)$/.exec(p);+ if (th && (req.method === 'GET' || req.method === 'HEAD')) { serveFile(req, res, STYLE_THUMBS, th[1]); return true; }if (!p.startsWith('/api/edit') && !p.startsWith('/edits/')) return false;if (['POST', 'DELETE', 'PUT', 'PATCH'].includes(req.method) && !originOk(req, allowedHosts)) { sendAndClose(res, req, send, 403, { error: 'origin không hợp lệ' }); return true; }diff --git a/edit/jobs.mjs b/edit/jobs.mjsindex 958a810..a9fb446 100644--- a/edit/jobs.mjs+++ b/edit/jobs.mjs@@ -4,7 +4,7 @@import fs from 'node:fs';import path from 'node:path';import { EDITS, editDir, newEditId, editVideo, reviseEdit, STEPS } from './pipeline.mjs';-import { listStyles, loadStyle, parseNames } from './planner.mjs';+import { listStyles, loadStyle, parseNames, STYLES_DIR } from './planner.mjs';import { setupStatus } from './env.mjs';import { probeSource } from './ingest.mjs';@@ -49,10 +49,20 @@ export function readEditJob(id) {return reapIfDead(readJson(jobFile(id)));}-/** Kiểu edit có sẵn (cho UI/MCP). */+/** Ảnh minh hoạ dọc của từng kiểu (khung từ bản demo), server phục vụ ở /edit-styles/thumbs/<id>.webp. */+export const STYLE_THUMBS = path.join(STYLES_DIR, 'thumbs');++/** Kiểu edit có sẵn (cho UI/MCP): tên + tóm tắt VI/EN, ảnh minh hoạ (nếu có), màu nhấn, độ dài mặc định. */export function editStyles() {- return listStyles().map((id) => { const s = loadStyle(id); return { id, order: s.order ?? 99, name: s.name, summary: s.guide.split('\n').find((l) => l.trim() && !l.startsWith('#')) || '' }; })- .sort((a, b) => a.order - b.order);+ return listStyles().map((id) => {+ const s = loadStyle(id);+ const thumb = fs.existsSync(path.join(STYLE_THUMBS, `${id}.webp`)) ? `/edit-styles/thumbs/${id}.webp` : null;+ return {+ id, order: s.order ?? 99, name: s.name, nameEn: s.nameEn || s.name,+ summary: s.summary || s.guide.split('\n').find((l) => l.trim() && !l.startsWith('#')) || '', summaryEn: s.summaryEn || '',+ thumb, accent: s.graphics?.accent || s.look?.hi || null, target: s.target ?? null,+ };+ }).sort((a, b) => a.order - b.order);}/** Đã cài đủ chưa (python, gói, model whisper, model mặt/người, font). UI hiện hướng dẫn cài nếu chưa. */diff --git a/edit/pipeline.mjs b/edit/pipeline.mjsindex ec42ba7..7a4377d 100644--- a/edit/pipeline.mjs+++ b/edit/pipeline.mjs@@ -18,11 +18,11 @@ import { ROOT, runLumedit } from './env.mjs';import { ingest, makeProxy } from './ingest.mjs';import {loadStyle, wordList, propose, compileEdl, parseNames, proposeRevision, applyOverrides, applyExtraCuts, outputCutToSource,- callClaude, parseProposal, repairCuts,+ callClaude, parseProposal, repairCuts, maxSecRequest,} from './planner.mjs';import { selectSegments, planGraphics, layoutGraphics, fillUnits, figureList, checkFigures, dropLowFigures } from './graphics.mjs';import { fmtVi } from './numbers.mjs';-import { validateEdl, toOutputNearest, outputDuration, OUT } from './edl.mjs';+import { validateEdl, toOutputNearest, outputDuration, timelineOf, inKeep, OUT } from './edl.mjs';import { writeCaptionScene, renderCaptionLayer, captionTop } from './captions-hf.mjs';import { buildEditMix } from './audio.mjs';@@ -89,7 +89,9 @@ export async function editVideo(video, opts = {}) {const words = wordList(an.data);style.hesitations = new Set(an.data.hesitations || []);- const target = opts.target ? Math.round(Number(opts.target)) : null;+ // độ dài: --target của người dùng, không có thì theo thẻ kiểu (style.target; nguồn đã ngắn thì bỏ qua như cũ)+ const target = Number(opts.target) > 0 ? Math.round(Number(opts.target)) : Number(style.target) > 0 ? Math.round(style.target) : null;+ if (!(Number(opts.target) > 0) && target) log(` độ dài theo kiểu: ${target} s${style.maxSec ? ` (trần ${style.maxSec} s)` : ''}`);const llmOn = (opts.llm || 'on') !== 'off';let selection = null;const plan = await step('LLM lập EDL', async (pg) => {@@ -134,7 +136,22 @@ export async function editVideo(video, opts = {}) {figures: plan.figures || [], units: plan.units || [], cutRepairs: [],};fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(state, null, 1));- const edl = await buildEdl({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });+ let edl = await buildEdl({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });+ // kiểu có trần độ dài (maxSec, vd meo-15s 20 s): quá thì LLM sửa 1 vòng "bỏ thêm X giây"; vẫn quá thì chỉ cảnh báo+ const over = maxSecRequest(style, outputDuration(timelineOf(edl)));+ if (over && llmOn) {+ log(' ' + over);+ const p2 = await step('LLM lập EDL', () => propose({ words, style, content: opts.content, names, duration: ing.source.duration, llm: 'on', log, exclude: selection?.exclude,+ extra: `${over}\nĐề xuất trước: ${JSON.stringify(state.proposal)}` }));+ warnings.push(...p2.warnings);+ state.proposal = p2.proposal; state.maxSecRetry = { before: +outputDuration(timelineOf(edl)).toFixed(2) };+ edl = await buildEdl({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });+ state.maxSecRetry.after = +outputDuration(timelineOf(edl)).toFixed(2);+ fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(state, null, 1));+ checks.maxSec = { max: style.maxSec, ...state.maxSecRetry };+ }+ const still = maxSecRequest(style, outputDuration(timelineOf(edl)));+ if (still) warnings.push(`bản ra ${outputDuration(timelineOf(edl)).toFixed(1)} s vẫn quá trần ${style.maxSec} s của kiểu ${style.id} (không tự cắt, cần người xem lại)`);const repair = cutRepairer({ 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', repair });fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify({ ...state, out: 'out.mp4' }, null, 1));@@ -216,8 +233,10 @@ async function buildEdl({ id, dir, ing, analysis, words, style, state, checks, wedl = 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 tlk = timelineOf(edl);+ const lost = edl.graphics.filter((g) => !inKeep(tlk, g.data.at));+ for (const g of lost) gw.push(`đồ hoạ ${g.type} ở ${g.data.at} s rơi vào đoạn bị bỏ, không hiện`);+ edl.graphics = edl.graphics.filter((g) => inKeep(tlk, 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');@@ -225,21 +244,24 @@ async function buildEdl({ id, dir, ing, analysis, words, style, state, checks, wfs.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)));+ gw.push(...layoutGraphics(edl.graphics, tlk, faces, captionTop(edl.captions.style), { stepTracker: !!st.graphics?.stepTracker }));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 })),+ items: edl.graphics.map((g) => ({ type: g.type, at: +toOutputNearest(tlk, g.start).toFixed(2), until: +toOutputNearest(tlk, g.end).toFixed(2), estimate: g.estimate, box: g.box, faceAvoided: !!g.face, pinned: !!g.data.pin })),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(', ')}`);+ log(` đồ hoạ: ${edl.graphics.map((g) => `${g.type} ${toOutputNearest(tlk, g.start).toFixed(1)}–${toOutputNearest(tlk, 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);+ const outDur = outputDuration(timelineOf(edl));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`);+ if (edl.hook) checks.hook = { start: edl.hook.start, end: edl.hook.end, seconds: +(edl.hook.end - edl.hook.start).toFixed(2), repeat: edl.hook.repeat, text: edl.captions.words.filter((w) => w.start >= edl.hook.start - 0.05 && w.end <= edl.hook.end + 0.05).map((w) => w.w).join(' ') };+ if (edl.quote) checks.quote = { start: edl.quote.start, end: edl.quote.end, text: edl.captions.words.filter((w) => (w.start + w.end) / 2 >= edl.quote.start && (w.start + w.end) / 2 <= edl.quote.end).map((w) => w.w).join(' ') };+ if (edl.hookText) checks.hookText = edl.hookText.text;+ 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${edl.hook ? `, móc ${edl.hook.start.toFixed(2)}–${edl.hook.end.toFixed(2)} s nguồn lên đầu ("${checks.hook.text}")` : ''}${edl.quote ? `, trích dẫn "${checks.quote.text}"` : ''}${edl.hookText ? `, chữ móc "${edl.hookText.text}"` : ''}`);for (const r of edl.removed) log(` bỏ ${r.start.toFixed(2)}–${r.end.toFixed(2)} s (${r.reason})${r.words ? ': ' + r.words : ''}`);return edl;}@@ -301,6 +323,18 @@ async function renderBase({ edlFile, base, draft, R }) {return rb;}+/**+ * Tiếng động theo giây bản ra. Câu móc lặp lại (repeat): tiếng nằm trong khoảng móc phát cả ở đầu clip lẫn chỗ cũ;+ * tiếng riêng của câu móc (hook.sfx, vd "boom") chỉ phát ở đầu clip.+ */+export function outputSfx(edl) {+ const tl = timelineOf(edl); const H = edl.hook;+ const out = edl.sfx.map((s) => ({ t: toOutputNearest(tl, s.at), name: s.name, gainDb: s.gainDb }));+ if (H?.repeat) for (const s of edl.sfx) if (s.at >= H.start && s.at <= H.end) out.push({ t: s.at - H.start, name: s.name, gainDb: s.gainDb });+ if (H?.sfx) out.push({ t: Math.max(0, H.sfx.at - H.start), name: H.sfx.name, gainDb: H.sfx.gainDb });+ return out.sort((a, b) => a.t - b.t);+}+/** Bước 6–9: phụ đề, tiếng, ghép, kiểm. */async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName }) {const { log, timings, checks, warnings, step } = R;@@ -309,16 +343,16 @@ async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName })await step('phụ đề', async (pg) => {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' };+ let accent; let style = null;+ try { style = loadStyle(edl.style); accent = style.graphics?.accent; } catch { /* kiểu đã bị xoá: màu mặc định */ }+ const sc = writeCaptionScene(edl, path.join(dir, 'captions'), { captions: !draft, accent, style });+ checks.captions = { cards: sc.cards, graphics: sc.graphics, overlaps: 0, box: sc.box, safeZone: 'trong 120–960 px, đáy ≤ 80% khung', quote: sc.quote, hookText: sc.hookText, ticker: sc.ticker };overlay = await renderCaptionLayer(path.join(dir, 'captions'), path.join(dir, 'captions.webm'), { log, onPct: (p) => pg(p, 'HyperFrames') });});const mix = await step('tiếng', () => buildEditMix({base, duration: rb.seconds_out, workDir: path.join(dir, 'audio'), lufs: edl.output.lufs, log,- sfx: edl.sfx.map((s) => ({ t: toOutputNearest(edl.keep, s.at), name: s.name, gainDb: s.gainDb })),+ sfx: outputSfx(edl),music: edl.music,}));@@ -387,7 +421,7 @@ export async function reviseEdit(id, instruction, opts = {}) {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));+ const newCuts = rev.cutsOut.flatMap((c) => outputCutToSource(timelineOf(curEdl), c.start, c.end, words));log(` LLM: ${rev.notes || '(không ghi chú)'}${newCuts.length ? ` · cắt thêm ${newCuts.map((c) => `${c.start.toFixed(2)}–${c.end.toFixed(2)} s nguồn`).join(', ')}` : ''}`);// giữ bản cũconst vdir = path.join(dir, 'versions');diff --git a/edit/planner.mjs b/edit/planner.mjsindex 52c890d..fa2e9a0 100644--- a/edit/planner.mjs+++ b/edit/planner.mjs@@ -6,8 +6,8 @@ import path from 'node:path';import { spawnClaude, findClaude } from '../generator/claude.mjs';import { MODEL_IDS } from '../generator/config.mjs';import { ROOT } from './env.mjs';-import { EDL_VERSION, OUT, REMOVE_REASONS, toOutput, outputDuration } from './edl.mjs';-import { compileGraphics, numberHighlights } from './graphics.mjs';+import { EDL_VERSION, OUT, REMOVE_REASONS, toOutput, outputDuration, timelineOf, hookDur } from './edl.mjs';+import { compileGraphics, numberHighlights, wordStart } from './graphics.mjs';import { soundOf, cutAfter, cutBefore, TAIL_Q, LEAD_Q } from './sound.mjs';export const STYLES_DIR = path.join(ROOT, 'edit-styles');@@ -68,8 +68,27 @@ function transcriptText(words, exclude = null) {return lines.join('\n');}-export function buildPrompt({ words, style, content, names, duration, errors, previous, exclude }) {+/** Phần thêm vào prompt cắt cho kiểu có câu móc / chữ móc / câu trích dẫn (engine đã làm được các trường này). */+function extraFields(style) {+ const f = []; const rules = [];+ if (style.hook?.pullToFront) {+ f.push(` "hook": {"from": <i>, "to": <i>}`);+ rules.push(`- "hook": câu móc theo thẻ kiểu (chữ đầu..chữ cuối, gồm cả hai đầu), một câu trọn nghĩa, dài ≤ ${style.hook.maxSec} giây theo mốc giây, KHÔNG nằm trong "drop". Code kéo câu này lên đầu bản ra${style.hook.repeatInPlace ? ' rồi phát clip từ đầu (câu vẫn ở chỗ cũ)' : ' và bỏ nó khỏi chỗ cũ'}${style.hook.flash ? ', chèn chớp trắng' : ''}${style.hook.sfx ? ` + "${style.hook.sfx}" (đừng tự thêm "${style.hook.sfx}" vào "sfx")` : ''}. Chọn câu nằm SAU câu mở đầu của phần được giữ (câu đã đứng ngay đầu thì kéo lên là vô nghĩa, nghe 2 lần); chỉ khi không còn câu nào đủ gắt mới chọn câu đầu. Không cần ghi HOOK vào notes.`);+ }+ if (style.hook?.text) {+ f.push(` "hookText": "<chữ móc ≤ ${style.hook.text.maxChars} ký tự, 1–2 chữ nhấn đặt trong *…*>"`);+ rules.push(`- "hookText": chữ móc to hiện 0–${style.hook.text.until} giây đầu (code vẽ riêng, không phải phụ đề): lợi ích/kết quả của mẹo viết gọn từ chính lời người nói, vd "*3 GIÂY* LÀ XONG". Có chữ móc này thì KHÔNG cần title_card làm chữ móc.`);+ }+ if (style.look?.quote) {+ f.push(` "quote": {"from": <i>, "to": <i>}`);+ rules.push('- "quote": câu chốt hiện kiểu trích dẫn to giữa khung (code tắt phụ đề thường, làm tối + mờ video): một câu trọn nghĩa 6–25 chữ, không nằm trong "drop", không bỏ chữ nào bên trong. Không cần nhấn (highlights) cả câu, không cần ghi QUOTE vào notes.');+ }+ return { fields: f.length ? ',\n' + f.join(',\n') : '', rules: rules.join('\n') };+}++export function buildPrompt({ words, style, content, names, duration, errors, previous, exclude, extra }) {const sfx = style.sfxNames.join(', ');+ const ex = extraFields(style);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.Chỉ trả về MỘT khối JSON, không giải thích ngoài JSON.@@ -93,7 +112,7 @@ ${transcriptText(words, exclude)}"zooms": [<i>, ...],"sfx": [{"word": <i>, "name": "<một trong: ${sfx}>"}],"fixes": [{"word": <i>, "text": "<chữ đúng>"}],- "notes": "<1–2 câu: đã bỏ gì, vì sao>"+ "notes": "<1–2 câu: đã bỏ gì, vì sao>"${ex.fields}}Luật:- "drop" là các khoảng chữ liền nhau [from..to] (gồm cả hai đầu) cần bỏ CẢ TIẾNG LẪN HÌNH. Nói lại: bỏ lần nói trước (kể cả phần nói dở), giữ lần sau cùng. Không chồng nhau. "filler" chỉ dùng cho từ đệm đứng riêng (ờ, ừm, ơ…).@@ -101,7 +120,7 @@ Luật:- Không cần liệt kê khoảng lặng: code tự rút. Không bỏ quá nửa số chữ.- "highlights", "zooms", "sfx", "fixes" chỉ dùng chữ KHÔNG bị bỏ. Zoom theo mật độ của thẻ kiểu (${style.zoom.perMinute[0]}–${style.zoom.perMinute[1]} lần mỗi phút, cách nhau ≥ ${style.zoom.minGap} giây).- "fixes" (text "" = ẩn chữ đó khỏi phụ đề, vẫn giữ tiếng): CHỈ sửa chữ mà máy nghe sai rõ ràng: chữ vô nghĩa trong câu, hoặc tên riêng/thuật ngữ người dùng đã dặn. Chữ đang hợp nghĩa (dù mày nghĩ người nói muốn chữ khác) thì GIỮ NGUYÊN — sửa sai còn tệ hơn không sửa. Mỗi mục 1 chữ → 1 chữ đúng (có thể vài tiếng).-${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;+${ex.rules ? ex.rules + '\n' : ''}${extra ? `\n# YÊU CẦU THÊM\n${extra}\n` : ''}${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;}export const parseNames = (names) => (Array.isArray(names) ? names : String(names || '').split(/[,;\n]/))@@ -190,9 +209,47 @@ export function checkProposal(p, words, style, exclude = null) {if (typeof f?.text !== 'string' || t.length > 40) { errors.push(`fix ${JSON.stringify(f)}: chữ sửa không hợp lệ hoặc quá dài`); continue; }if (keptIdx(f.word, 'fix')) clean.fixes.push({ word: f.word, text: t });}+ // câu móc / câu trích dẫn: LLM trả trường riêng; bản guidance cũ ghi "HOOK: [i]–[j]" / "QUOTE: [i]–[j]" vào notes+ const spanOf = (field, tag) => {+ if (p[field] && typeof p[field] === 'object') return p[field];+ const m = new RegExp(String.raw`${tag}\s*:?\s*\[?(\d+)\]?\s*[–—-]+\s*\[?(\d+)\]?`, 'i').exec(clean.notes);+ return m ? { from: Number(m[1]), to: Number(m[2]) } : null;+ };+ const checkSpan = (sp, what, maxSec) => {+ if (!isIdx(sp?.from) || !isIdx(sp?.to) || sp.from > sp.to) { errors.push(`${what} ${JSON.stringify(sp)}: from/to không hợp lệ (0..${n - 1}, from ≤ to)`); return null; }+ for (let i = sp.from; i <= sp.to; i++) if (dropped.has(i) || ex.has(i)) { errors.push(`${what} ${sp.from}–${sp.to}: chữ ${i} ("${words[i].w}") nằm trong đoạn bị bỏ`); return null; }+ const sec = words[sp.to].e - words[sp.from].s;+ if (maxSec && sec > maxSec + 1e-6) { errors.push(`${what} ${sp.from}–${sp.to} dài ${sec.toFixed(1)} s, quá ${maxSec} s: chọn câu ngắn hơn`); return null; }+ return { from: sp.from, to: sp.to };+ };+ if (style.hook?.pullToFront) {+ const sp = spanOf('hook', 'HOOK');+ if (sp) clean.hook = checkSpan(sp, 'hook', style.hook.maxSec);+ else errors.push('thiếu "hook" (câu móc kéo lên đầu)');+ }+ if (style.look?.quote) {+ const sp = spanOf('quote', 'QUOTE');+ if (sp) clean.quote = checkSpan(sp, 'quote', null);+ else errors.push('thiếu "quote" (câu chốt hiện kiểu trích dẫn)');+ }+ if (style.hook?.text) {+ const t = typeof p.hookText === 'string' ? p.hookText.trim() : '';+ const plain = t.replace(/\*/g, '');+ if (!plain) errors.push('thiếu "hookText" (chữ móc 0–2 giây)');+ else if ([...plain].length > style.hook.text.maxChars) errors.push(`hookText "${plain}" dài quá ${style.hook.text.maxChars} ký tự`);+ else clean.hookText = t;+ }return { errors, clean };}+/** Kiểu có trần độ dài (maxSec): bản ra dài quá → lời yêu cầu LLM bỏ thêm; không quá → null. */+export function maxSecRequest(style, outSec) {+ if (!style.maxSec || outSec <= style.maxSec + 1e-6) return null;+ const need = Math.ceil((outSec - style.maxSec) * 10) / 10;+ const vi = (x) => x.toFixed(1).replace('.', ',');+ return `Bản ra theo đề xuất trước dài ${vi(outSec)} giây, quá trần ${style.maxSec} giây của kiểu này. Bỏ thêm ≥ ${vi(need)} giây lời (drop thêm câu giải thích, câu phụ; giữ câu móc, các bước làm, con số và câu kết quả). Trả lại đề xuất ĐẦY ĐỦ.`;+}+/** Đề 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, exclude = null) {const zooms = []; let last = -Infinity;@@ -205,12 +262,12 @@ export function fallbackProposal(words, style, exclude = null) {}/** 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, exclude = null }) {+export async function propose({ words, style, content, names, duration, llm = 'on', log = console.log, exclude = null, extra = '' }) {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) : '', exclude });+ const prompt = buildPrompt({ words, style, content, names, duration, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '', exclude, extra });let checked;try {const r = await callClaude(prompt, { log });@@ -232,6 +289,7 @@ const LEAD = 0.10; // giữ trước chữ đầu mỗi đoạnconst TAIL = 0.22; // giữ sau chữ cuối (whisper hay báo hết chữ sớm ~0,15 s; spike đo 0,10–0,21 s)const MIN_CUT = 0.12; // cắt ngắn hơn thế thì không đáng một cú nhảy hìnhconst EDGE_END = 0.35; // giữ sau chữ cuối cùng của video+const HOOK_AT_START = 1.0; // câu móc bắt đầu trong ngần này giây đầu bản ra thì coi như đã ở đầu, không kéo/*** Một khoảng bỏ (của LLM hoặc từ đệm) chỉ được bỏ khi ở mỗi mép chạm chữ giữ, giọng có ngắt thật (khoảng lặng hoặc@@ -310,6 +368,10 @@ export function compileEdl({ id, ingestRes, analysis, words, proposal, style, muif (!q) continue;cs = Math.max(a.e - 0.06, Math.min(Math.max(q.q0, a.s + 0.02) + TAIL_Q, q.q1));ce = Math.min(b.s + 0.06, Math.max(Math.min(q.q1, b.e - 0.02) - LEAD_Q, q.q0));+ // kiểu kể chuyện/vlog: khoảng ngừng dài còn lại ≈ pauseKeep (mỗi bên một nửa), vẫn nằm trong khoảng lặng thật+ if (style.pauseKeep) { cs = Math.min(q.q1, Math.max(cs, a.e + style.pauseKeep / 2)); ce = Math.max(q.q0, Math.min(ce, b.s - style.pauseKeep / 2)); }+ } else if (style.pauseKeep) {+ cs = a.e + Math.max(TAIL, style.pauseKeep / 2); ce = b.s - Math.max(LEAD, style.pauseKeep / 2);}if (ce - cs < MIN_CUT) continue;keep.push({ start: +segStart.toFixed(3), end: +cs.toFixed(3) });@@ -336,22 +398,54 @@ export function compileEdl({ id, ingestRes, analysis, words, proposal, style, muif (reasonOf.has(w.i) && !w.unsure && restored.some((x) => mid >= x.start && mid <= x.end)) reasonOf.delete(w.i);}}- const inKeepT = (t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6);+ const byIdx = new Map(words.map((w) => [w.i, w]));+ // câu móc kéo lên đầu: bản ra = [hook] + keep. Mép cắt như mọi đoạn giữ (vào khoảng lặng/chỗ trũng, không lẹm chữ).+ let hook = null;+ const hp = style.hook?.pullToFront ? proposal.hook : null;+ if (hp && byIdx.has(hp.from) && byIdx.has(hp.to)) {+ const wf = byIdx.get(hp.from); const wt = byIdx.get(hp.to);+ const prev = byIdx.get(hp.from - 1); const next = byIdx.get(hp.to + 1);+ let hs = cutBefore(snd, wf, prev ? prev.e : wf.s - 0.6, prev ? prev.s : 0) ?? wf.s - LEAD;+ let he = cutAfter(snd, wt, next ? next.s : wt.e + 0.6, next ? next.e : dur) ?? wt.e + TAIL;+ if (prev && prev.e <= wf.s) hs = Math.max(hs, prev.e + 0.01);+ if (next && next.s >= wt.e) he = Math.min(he, next.s - 0.01);+ hs = Math.max(0, Math.min(hs, wf.s - 0.02)); he = Math.min(dur, Math.max(he, wt.e + 0.05));+ // câu móc vốn đã ở đầu bản ra (vd đoạn chọn mở bằng chính câu đó): không kéo nữa, nếu không sẽ nghe 2 lần liền nhau;+ // tiếng của câu móc vẫn đặt ở chữ cuối câu+ const at0 = toOutput(keep, Math.max(hs, keep[0].start));+ if (at0 !== null && at0 <= HOOK_AT_START) {+ if (style.hook.sfx) proposal = { ...proposal, sfx: [...proposal.sfx, { word: hp.to, name: style.hook.sfx }] };+ cutWarnings.push(`câu móc "${words.slice(hp.from, hp.to + 1).map((x) => x.w).join(' ')}" đã ở đầu clip (${at0.toFixed(1)} s): không kéo lên`);+ } else if (he - hs > 6) cutWarnings.push(`câu móc ${hp.from}–${hp.to} dài ${(he - hs).toFixed(1)} s (> 6 s), không kéo lên đầu`);+ else {+ const repeat = style.hook.repeatInPlace !== false;+ hook = { start: +hs.toFixed(3), end: +he.toFixed(3), repeat, flash: !!style.hook.flash,+ sfx: style.hook.sfx ? { name: style.hook.sfx, at: +wt.s.toFixed(3), gainDb: style.sfx.gainDb } : null };+ if (!repeat) {+ // không lặp lại: trừ khoảng móc khỏi keep (chữ trong đó vẫn lên phụ đề, ở đầu bản ra)+ keep = keep.flatMap((k) => (hook.end <= k.start || hook.start >= k.end ? [k]+ : [{ start: k.start, end: hook.start }, { start: hook.end, end: k.end }].filter((x) => x.end - x.start >= 1 / 30)));+ }+ }+ }+ const inHookT = (t) => !!hook && t >= hook.start - 1e-6 && t <= hook.end + 1e-6;+ const inKeepT = (t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6) || inHookT(t);const keptAll = words.filter((w) => !reasonOf.has(w.i) && inKeepT((w.s + w.e) / 2));+ if (!keep.length) throw new Error('câu móc chiếm hết đoạn giữ');+ const tlKeep = hook ? [...keep, { start: hook.start, end: hook.end }] : keep; // mốc chữ: kẹp vào đoạn giữ (hoặc câu móc)// zoom: theo đề xuất, ép khoảng cách tối thiểu của thẻ kiểu- const byIdx = new Map(words.map((w) => [w.i, w]));const zooms = []; let lastZ = -Infinity;for (const i of [...new Set(proposal.zooms)].sort((x, y) => x - y)) {const w = byIdx.get(i);if (!w || reasonOf.has(i) || w.s - lastZ < style.zoom.minGap) continue;- zooms.push({ at: +w.s.toFixed(3), dur: style.zoom.dur, scale: style.zoom.scale, kind: style.zoom.kind, word: i });+ zooms.push({ at: +wordStart(tlKeep, w).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 });+ gfx = compileGraphics({ plan: graphics, words, keep: timelineOf({ keep, hook }), 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);@@ -366,7 +460,7 @@ export function compileEdl({ id, ingestRes, analysis, words, proposal, style, muconst 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 }); }+ for (const s of proposal.sfx) { const w = byIdx.get(s.word); if (w && !reasonOf.has(s.word)) sfx.push({ at: +wordStart(tlKeep, w).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);@@ -385,6 +479,11 @@ export function compileEdl({ id, ingestRes, analysis, words, proposal, style, mu},sfx: sfxOut,graphics: gfx.graphics,+ hook,+ hookText: style.hook?.text && proposal.hookText ? { text: proposal.hookText, until: style.hook.text.until } : null,+ quote: style.look?.quote && proposal.quote && byIdx.has(proposal.quote.from) && byIdx.has(proposal.quote.to)+ ? { start: +byIdx.get(proposal.quote.from).s.toFixed(3), end: +byIdx.get(proposal.quote.to).e.toFixed(3), dimTo: style.look.quote.dimTo, blurPx: style.look.quote.blurPx, dimIn: style.look.quote.dimIn }+ : null,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 || '',@@ -410,7 +509,7 @@ const PHRASE = 1.6; // nới mép đoạn dài: tìm chỗ người nói ngexport function repairCuts(edl, overcut, analysis) {const snd = soundOf(analysis);const keep = edl.keep; const out = [];- const ends = []; let acc = 0;+ const ends = []; let acc = edl.hook ? edl.hook.end - edl.hook.start : 0; // vết nối móc → clip không tínhfor (const k of keep) { acc += k.end - k.start; ends.push(acc); }for (const item of [...(overcut?.lost || []), ...(overcut?.chopped || [])]) {if (typeof item.join !== 'number') continue;@@ -456,7 +555,7 @@ export function repairCuts(edl, overcut, analysis) {/** Khoảng giây bản ra [a,b) → các khoảng giây nguồn (trong keep); mép rơi giữa chữ thì nới ra trọn chữ. */export function outputCutToSource(keep, a, b, words) {const res = [];- let acc = 0;+ let acc = hookDur(keep); // keep có .hook (timelineOf): giây bản ra của keep bắt đầu sau câu mócfor (const k of keep) {const d = k.end - k.start;const lo = Math.max(a, acc); const hi = Math.min(b, acc + d);@@ -526,17 +625,17 @@ function reviseText(words, keep) {}export function buildRevisePrompt({ words, edl, proposal, style, overrides, instruction, names, errors, previous }) {- const outDur = outputDuration(edl.keep);+ const outDur = outputDuration(timelineOf(edl));return `Mày là biên tập viên video ngắn tiếng Việt. Video đã dựng xong, dài ${outDur.toFixed(1)} giây (bản hiện tại). Người dùng muốn sửa:"${instruction}"Chỉ trả về MỘT khối JSON. Mốc giây người dùng nói là giây của BẢN HIỆN TẠI.# Lời chép ([i] = số thứ tự chữ; đầu dòng là mốc giây bản hiện tại; chữ có ✗ là đã bỏ)-${reviseText(words, edl.keep)}+${reviseText(words, timelineOf(edl))}# Đề xuất hiện tại-${JSON.stringify({ drop: proposal.drop, highlights: proposal.highlights, zooms: proposal.zooms, sfx: proposal.sfx, fixes: proposal.fixes })}+${JSON.stringify({ drop: proposal.drop, highlights: proposal.highlights, zooms: proposal.zooms, sfx: proposal.sfx, fixes: proposal.fixes, ...(proposal.hook ? { hook: proposal.hook } : {}), ...(proposal.quote ? { quote: proposal.quote } : {}), ...(proposal.hookText ? { hookText: proposal.hookText } : {}) })}# Núm chỉnh kiểu hiện tại (${style.name})${JSON.stringify({ zoomScale: style.zoom.scale, zoomMinGap: style.zoom.minGap, captionsMaxWords: style.captions.maxWords, musicGainDb: style.music.gainDb, pause: style.pause, ...overrides })}@@ -562,7 +661,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, exclude = null }) {let text = ''; let prev = null; let cost = 0;- const outDur = outputDuration(edl.keep);+ const outDur = outputDuration(timelineOf(edl));for (let round = 1; round <= 2; round++) {const prompt = buildRevisePrompt({ words, edl, proposal, style, overrides, instruction, names, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '' });let errors = []; let out = null;@@ -570,7 +669,9 @@ 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, exclude);+ // câu móc / trích dẫn / chữ móc: lời sửa không nhắc tới thì giữ như cũ+ const keepExtra = Object.fromEntries(['hook', 'quote', 'hookText'].filter((k) => proposal[k] != null).map((k) => [k, proposal[k]]));+ const checked = checkProposal({ ...keepExtra, ...(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.pyindex 57a36ac..a7d6bce 100644--- a/edit/py/lumedit.py+++ b/edit/py/lumedit.py@@ -109,7 +109,8 @@ def build(edl: dict, draft_captions: bool):if abs(info.rate - OUT_FPS) > 0.01:raise ValueError(f"the proxy runs at {info.rate} fps; it must be the 30 fps proxy")segs = tuple((float(k["start"]), min(float(k["end"]), info.duration)) for k in edl["keep"])- tl = Timeline(tuple((a, b) for a, b in segs if b - a > 1e-3))+ segs = tuple((a, b) for a, b in segs if b - a > 1e-3)+ tl = hook_timeline(Timeline, segs, edl.get("hook"), info.duration)mode = edl["reframe"]["mode"]face = clip.face if mode == "face" else Nonefr = framing_mod.plan(info.width, info.height, info.rate, info.frames, face, shape="9:16",@@ -121,19 +122,97 @@ def build(edl: dict, draft_captions: bool):glass = Glass(edl, tl) if edl.get("graphics") else Nonesqueeze = Squeeze(edl, tl) if any(g.get("squeeze") for g in edl.get("graphics", [])) else Nonecaps = DraftCaptions(edl, tl) if draft_captions and edl["captions"]["words"] else None+ quote = QuoteDim(edl, tl) if edl.get("quote") else None+ hook = edl.get("hook") or None+ flash_at = (float(hook["end"]) - float(hook["start"])) if hook and hook.get("flash") else Nonedef draw(frame, j, t):zooms.apply(frame, j, t)if squeeze is not None:squeeze.apply(frame, t)+ if quote is not None:+ quote.apply(frame, t)if glass is not None:glass.apply(frame, t)if caps is not None:caps.draw(frame, t)+ # chớp trắng 2 khung ở chỗ nối câu móc → clip+ if flash_at is not None and flash_at - 1e-3 <= t < flash_at + 2.0 / OUT_FPS - 1e-3:+ frame[:] = 255return clip, tl, fr, draw+# ---- the hook pulled to the front ---------------------------------------------------------------------------++def hook_timeline(Timeline, segs, hook, duration):+ """The output plays the hook (edl.hook, source seconds) first, then the kept stretches. Playing (to_source,+ sample_ranges, joins) works on any order of segments; only source → output needs care: a moment inside a kept+ stretch lands there (after the hook), a moment only in the hook (repeat: false) lands at 0 … hook length."""+ if not hook:+ return Timeline(segs)+ from dataclasses import dataclass++ @dataclass(frozen=True)+ class HookTimeline(Timeline):+ def _play(self, t):+ (h0, h1), rest = self.segments[0], self.segments[1:]+ acc = h1 - h0+ for a, b in rest:+ if t < a - 1e-9:+ break+ if t <= b + 1e-9:+ return acc + (t - a)+ acc += b - a+ if h0 - 1e-9 <= t <= h1 + 1e-9:+ return t - h0+ return None++ def to_output_nearest(self, t):+ got = self.to_output(t)+ if got is not None:+ return got+ best, best_d = 0.0, math.inf+ for a, b in self.segments[1:]:+ for src in (a, b):+ if abs(src - t) < best_d:+ best, best_d = self.to_output(src), abs(src - t)+ return best++ h = (float(hook["start"]), min(float(hook["end"]), duration))+ return HookTimeline((h,) + tuple(segs))+++class QuoteDim:+ """edl.quote: while the quote is on screen the video dims to `dimTo` and blurs `blurPx`, eased in over `dimIn` s;+ held to the end when the quote closes the clip, else eased back out in 0.4 s (the quote block itself is drawn in+ the HyperFrames layer)."""++ def __init__(self, edl: dict, tl):+ q = edl["quote"]+ self.t0 = tl.to_output_nearest(float(q["start"]))+ q1 = tl.to_output_nearest(float(q["end"]))+ self.t1 = tl.duration + 1.0 if q1 >= tl.duration - 2.0 else min(tl.duration, q1 + 0.8)+ self.dim, self.blur, self.din = float(q["dimTo"]), float(q["blurPx"]), max(0.1, float(q["dimIn"]))++ def apply(self, frame, t: float) -> None:+ if not (self.t0 <= t < self.t1):+ return+ e = min(_ease((t - self.t0) / self.din), _ease((self.t1 - t) / 0.4))+ if e <= 0.01:+ return+ import cv2+ import numpy as np++ img = frame+ sigma = self.blur * e+ if sigma > 0.3:+ small = cv2.resize(frame, (OUT_W // 4, OUT_H // 4), interpolation=cv2.INTER_AREA)+ img = cv2.resize(cv2.GaussianBlur(small, (0, 0), sigma / 4), (OUT_W, OUT_H), interpolation=cv2.INTER_LINEAR)+ k = 1.0 - (1.0 - self.dim) * e+ frame[:] = (img.astype(np.float32) * k).astype(np.uint8)++# ---- zooms ---------------------------------------------------------------------------------------------------def _ease(x: float) -> float:@@ -150,15 +229,24 @@ class Zooms:def __init__(self, edl: dict, tl, fr, clip):self.items = []fps = clip.info.rate+ hook = edl.get("hook") or None+ hd = float(hook["end"]) - float(hook["start"]) if hook else 0.0for z in edl["zooms"]:- t0 = tl.to_output_nearest(float(z["at"]))- k = tl.source_frame(int(round(t0 * fps)), fps, clip.info.frames)- cx, cy = OUT_W / 2, OUT_H * 0.40- head = clip.face.head(k) if clip.face.any() else None- if head is not None:- r = fr.to_output(head, k)- cx, cy = (r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2- self.items.append((t0, float(z["dur"]), float(z["scale"]), z["kind"], cx, cy))+ at = float(z["at"])+ t_out = [(tl.to_output_nearest(at), float(z["dur"]))]+ # câu móc lặp lại: cú zoom trong câu móc chạy cả ở đầu clip (không tràn qua chỗ nối)+ if hook and hook.get("repeat") and float(hook["start"]) <= at <= float(hook["end"]):+ t_h = at - float(hook["start"])+ t_out.append((t_h, min(float(z["dur"]), hd - t_h)))+ for t0, dur in t_out:+ k = tl.source_frame(int(round(t0 * fps)), fps, clip.info.frames)+ cx, cy = OUT_W / 2, OUT_H * 0.40+ head = clip.face.head(k) if clip.face.any() else None+ if head is not None:+ r = fr.to_output(head, k)+ cx, cy = (r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2+ self.items.append((t0, max(0.2, dur), float(z["scale"]), z["kind"], cx, cy))+ self.items.sort(key=lambda x: x[0])def scale_at(self, t: float):for t0, dur, s, kind, cx, cy in self.items:@@ -241,7 +329,8 @@ class Glass:self.items = []for g in edl.get("graphics", []):b = g.get("box")- if not b or g["type"] in ("price_tag", "sticker"):+ # thẻ ghim (pinFirst) thu về 0,8× sau 3 s: vùng kính cố định sẽ lệch khỏi thẻ, nên không làm kính+ if not b or g["type"] in ("price_tag", "sticker") or (g.get("data") or {}).get("pin"):continuex0, 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"])))diff --git a/edit/test/styles-check.mjs b/edit/test/styles-check.mjsnew file mode 100644index 0000000..a778cf7--- /dev/null+++ b/edit/test/styles-check.mjs@@ -0,0 +1,182 @@+#!/usr/bin/env node+// Kiểm nhanh phần engine của 11 cách dựng mới (không cần GPU/LLM):+// pauseKeep (khoảng ngừng dài còn lại ≈ pauseKeep), hook (câu móc kéo lên đầu, có/không lặp lại, dời mốc bản ra,+// phụ đề + tiếng của câu móc), maxSec (lời yêu cầu bỏ thêm), checkProposal (hook/quote/hookText, đọc HOOK: trong notes),+// lọc loại đồ hoạ, ghim tiêu đề, thanh bước, và cảnh phụ đề của 14 look (script chạy được, đúng phần tử từng kiểu).+// node edit/test/styles-check.mjs+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { compileEdl, checkProposal, maxSecRequest, buildPrompt, listStyles, loadStyle } from '../planner.mjs';+import { toOutput, outputDuration, timelineOf, validateEdl } from '../edl.mjs';+import { captionCards, writeCaptionScene, LOOKS, hookTextParts } from '../captions-hf.mjs';+import { checkGraphics, compileGraphics, stepTimes, buildGraphicsPrompt, layoutGraphics, graphicsErrors } from '../graphics.mjs';+import { outputSfx } from '../pipeline.mjs';++let fail = 0;+const ok = (cond, msg) => { console.log(`${cond ? 'PASS' : 'FAIL'} ${msg}`); if (!cond) fail++; };+const near = (a, b, tol = 0.02) => Math.abs(a - b) <= tol;++// lời giả: 3 câu, mỗi chữ 0,3 s + hở 0,1 s; lặng 3 s sau câu 1, lặng 1 s sau câu 2+const S1 = 'Hôm nay tao kể chuyện.'.split(' '); const S2 = 'Tiết kiệm là vô dụng.'.split(' '); const S3 = 'Vì lạm phát ăn hết.'.split(' ');+const words = []; let t = 0.5;+for (const [k, sent] of [S1, S2, S3].entries()) {+ for (const w of sent) { words.push({ i: words.length, w, s: +t.toFixed(3), e: +(t + 0.3).toFixed(3), unsure: false, p: 0.9 }); t += 0.4; }+ t += k === 0 ? 2.9 : 0.9;+}+const dur = +(t + 0.5).toFixed(3);+const w = (i) => words[i];+const quiet = []; for (let k = 0; k + 1 < words.length; k++) if (w(k + 1).s - w(k).e > 0.5) quiet.push([w(k).e + 0.02, w(k + 1).s - 0.02]);+const analysis = { hesitations: [], quiet };+const ing = { source: { file: 'x.mp4', sha256: 'a'.repeat(64), size: 1, duration: dur, startTime: 0, fps: 30, vfr: false, rotation: 0, width: 1080, height: 1920, codec: 'h264', hdr: false, hasAudio: true },+ proxy: { file: 'x.mov', width: 1080, height: 1920, fps: 30, audioRate: 48000 } };+const baseStyle = (extra = {}) => ({ id: 'test', name: 't', pause: 0.3, cutFillers: false,+ zoom: { kind: 'punch', scale: 1.2, dur: 0.6, minGap: 2, perMinute: [5, 10] }, sfx: { onZoom: null, max: 10, gainDb: -10 },+ captions: { style: 'sach-gon', maxWords: 3, position: 'lower' }, music: { gainDb: -20, duckDb: 10, fadeOut: 1 }, sfxNames: ['boom', 'pop'], hesitations: new Set(), ...extra });+const empty = { drop: [], highlights: [], zooms: [], sfx: [], fixes: [], notes: '' };+const mk = (style, proposal = empty) => compileEdl({ id: 't', ingestRes: ing, analysis, words, proposal, style, music: null, draft: false });+const v = (edl) => validateEdl(JSON.parse(JSON.stringify(edl, (k, x) => (k === '_warnings' ? undefined : x))), { sfxNames: ['boom', 'pop'], checkFiles: false });+const silenceBetween = (edl, a, b) => { const tl = timelineOf(edl); return toOutput(tl, w(b).s) - toOutput(tl, w(a).e); };++// ---- pauseKeep -----------------------------------------------------------------------------------------------------+const plain = mk(baseStyle({ pause: 1.5 }));+const kept = mk(baseStyle({ pause: 1.5, pauseKeep: 0.8 }));+const g0 = silenceBetween(plain, 4, 5); const g1 = silenceBetween(kept, 4, 5);+ok(g0 < 0.5, `không pauseKeep: lặng 3 s rút còn ${g0.toFixed(2)} s`);+ok(near(g1, 0.8, 0.05), `pauseKeep 0,8: lặng 3 s còn ${g1.toFixed(2)} s (≈ 0,8)`);+ok(near(silenceBetween(kept, 9, 10), silenceBetween(plain, 9, 10), 1e-6), 'pauseKeep không đụng khoảng lặng ngắn hơn pause (1 s < 1,5 s)');+ok(v(kept).ok, 'EDL có pauseKeep hợp lệ');++// ---- hook: lặp lại (quan-diem-gat) ----------------------------------------------------------------------------------+const hookStyle = (repeat) => baseStyle({ hook: { pullToFront: true, maxSec: 4, repeatInPlace: repeat, sfx: 'boom', flash: true } });+const pr = { ...empty, hook: { from: 5, to: 9 }, zooms: [7] };+const hr = mk(hookStyle(true), pr);+const hd = hr.hook.end - hr.hook.start;+ok(hr.hook && hr.hook.repeat && hr.hook.start <= w(5).s && hr.hook.end >= w(9).e && hd < 2.5, `câu móc ${hr.hook.start}–${hr.hook.end} s (${hd.toFixed(2)} s) bọc trọn "Tiết … dụng."`);+const tlr = timelineOf(hr);+ok(near(outputDuration(tlr), hd + outputDuration(hr.keep), 1e-9), 'độ dài bản ra = móc + keep');+ok(near(toOutput(tlr, w(0).s), hd + (w(0).s - hr.keep[0].start), 1e-6), 'chữ đầu clip dời thêm đúng độ dài móc');+ok(near(toOutput(tlr, w(5).s), hd + toOutput(hr.keep, w(5).s), 1e-6), 'repeat: chữ của câu móc ở chỗ cũ vẫn map vào keep (sau móc)');+const cr = captionCards(hr);+ok(near(cr[0].start, w(5).s - hr.hook.start, 1e-6) && cr[0].words[0].w === 'Tiết', 'phụ đề: thẻ đầu tiên là câu móc, ngay đầu clip');+ok(cr.filter((c) => c.words.some((x) => x.w === 'Tiết')).length === 2, 'repeat: chữ câu móc hiện 2 lần (đầu clip + chỗ cũ)');+ok(cr.filter((c) => c.start < hd).every((c) => c.end <= hd + 1e-6), 'phụ đề câu móc không tràn qua chỗ nối');+const sx = outputSfx({ ...hr, sfx: [{ at: w(7).s, name: 'pop', gainDb: -10 }] });+ok(sx.some((s) => s.name === 'boom' && near(s.t, w(9).s - hr.hook.start, 1e-6)), 'tiếng "boom" ở chữ cuối câu móc, đầu clip');+ok(sx.filter((s) => s.name === 'pop').length === 2, 'repeat: tiếng trong câu móc phát cả ở đầu clip lẫn chỗ cũ');+ok(sx.filter((s) => s.name === 'boom').length === 1, '"boom" chỉ phát 1 lần (không ở chỗ cũ)');+ok(v(hr).ok, 'EDL có hook (repeat) hợp lệ: ' + (v(hr).errors || []).map((e) => e.msg).join('; '));++// ---- hook: không lặp lại (meo-15s) ----------------------------------------------------------------------------------+const hn = mk(hookStyle(false), pr);+const tln = timelineOf(hn);+ok(!hn.keep.some((k) => k.start < hn.hook.end - 1e-3 && k.end > hn.hook.start + 1e-3), 'repeat: false → khoảng móc bị trừ khỏi keep');+ok(near(outputDuration(tln), outputDuration(timelineOf(mk(baseStyle(), empty))), 0.05), 'repeat: false → tổng độ dài như không có móc (chỉ dời chỗ)');+ok(near(toOutput(tln, w(5).s), w(5).s - hn.hook.start, 1e-6), 'repeat: false → chữ câu móc map về đầu bản ra');+const cn = captionCards(hn);+ok(cn[0].words[0].w === 'Tiết' && cn.filter((c) => c.words.some((x) => x.w === 'Tiết')).length === 1, 'repeat: false → chữ câu móc hiện 1 lần, ở đầu');+ok(v(hn).ok, 'EDL có hook (không lặp) hợp lệ: ' + (v(hn).errors || []).map((e) => e.msg).join('; '));+const badHook = JSON.parse(JSON.stringify(hr, (k, x) => (k === '_warnings' ? undefined : x))); badHook.hook.end = badHook.hook.start + 7;+ok(validateEdl(badHook, { checkFiles: false }).errors.some((e) => e.code === 'hook-len'), 'schema: câu móc > 6 s bị bắt');+const h0 = mk(hookStyle(true), { ...empty, hook: { from: 0, to: 4 } });+ok(h0.hook === null && h0.sfx.some((s) => s.name === 'boom' && near(s.at, w(4).s, 1e-6)), 'câu móc đã ở đầu clip: không kéo (không nghe 2 lần liền), "boom" vẫn ở chữ cuối câu');++// ---- checkProposal: hook / quote / hookText ---------------------------------------------------------------------------+const hs = hookStyle(true);+let cp = checkProposal({ ...empty, hook: { from: 5, to: 9 } }, words, hs);+ok(!cp.errors.length && cp.clean.hook.from === 5, 'hook hợp lệ');+cp = checkProposal({ ...empty, hook: { from: 0, to: 14 } }, words, hs);+ok(cp.errors.some((e) => e.includes('quá 4 s')), 'hook dài quá maxSec bị bắt');+cp = checkProposal({ ...empty, drop: [{ from: 6, to: 6, reason: 'retake' }], hook: { from: 5, to: 9 } }, words, hs);+ok(cp.errors.some((e) => e.includes('đoạn bị bỏ')), 'hook chứa chữ bị bỏ bị bắt');+cp = checkProposal({ ...empty, notes: 'Bỏ câu chào. HOOK: [5]–[9]' }, words, hs);+ok(!cp.errors.length && cp.clean.hook?.to === 9, 'đọc được "HOOK: [5]–[9]" trong notes');+cp = checkProposal(empty, words, hs);+ok(cp.errors.some((e) => e.includes('thiếu "hook"')), 'kiểu có hook mà thiếu → báo LLM sửa');+const qst = baseStyle({ look: { quote: { dimTo: 0.35, blurPx: 8, dimIn: 0.8, wordStagger: 0.12 } } });+cp = checkProposal({ ...empty, notes: 'QUOTE: [10]-[14]' }, words, qst);+ok(!cp.errors.length && cp.clean.quote.from === 10, 'đọc được "QUOTE: [10]-[14]" trong notes');+const mst = baseStyle({ hook: { pullToFront: true, maxSec: 2, repeatInPlace: false, text: { maxChars: 24, until: 2 } } });+cp = checkProposal({ ...empty, hook: { from: 5, to: 7 }, hookText: '*3 GIÂY* LÀ XONG' }, words, mst);+ok(!cp.errors.length && cp.clean.hookText === '*3 GIÂY* LÀ XONG', 'hookText ≤ 24 ký tự (không tính dấu *) hợp lệ');+cp = checkProposal({ ...empty, hook: { from: 5, to: 7 }, hookText: 'MẸO NÀY GIÚP MÀY TIẾT KIỆM CẢ ĐỐNG TIỀN' }, words, mst);+ok(cp.errors.some((e) => e.includes('hookText')), 'hookText dài quá bị bắt');+ok(JSON.stringify(hookTextParts('*3 GIÂY* LÀ XONG')) === JSON.stringify([{ t: '3 GIÂY', hi: true }, { t: ' LÀ XONG', hi: false }]), 'tách chữ nhấn của hookText');+const pt = buildPrompt({ words, style: { ...mst, guide: 'g', zoom: mst.zoom }, duration: dur });+ok(pt.includes('"hook": {"from"') && pt.includes('"hookText"'), 'prompt cắt có trường hook + hookText khi kiểu cần');+ok(!buildPrompt({ words, style: { ...baseStyle(), guide: 'g' }, duration: dur }).includes('"hook"'), 'kiểu thường: prompt không có trường hook');++// quote → EDL+const qe = mk({ ...qst, look: { quote: { dimTo: 0.35, blurPx: 8, dimIn: 0.8, wordStagger: 0.12 } } }, { ...empty, quote: { from: 10, to: 14 } });+ok(qe.quote && near(qe.quote.start, w(10).s, 1e-6) && qe.quote.dimTo === 0.35 && v(qe).ok, 'quote vào EDL (giây nguồn + dimTo/blurPx/dimIn), hợp lệ');++// ---- maxSec ---------------------------------------------------------------------------------------------------------+ok(maxSecRequest({ maxSec: 20 }, 18.4) === null, 'maxSec 20: bản ra 18,4 s → đạt, không hỏi lại');+const msr = maxSecRequest({ maxSec: 20 }, 24.0);+ok(!!msr && msr.includes('24,0') && msr.includes('≥ 4,0'), 'maxSec 20: bản ra 24,0 s → yêu cầu "bỏ ≥ 4,0 giây"');+ok(maxSecRequest({}, 99) === null, 'kiểu không có maxSec: không bao giờ hỏi lại');+ok(loadStyle('meo-15s').maxSec === 20 && loadStyle('meo-15s').target === 15, 'meo-15s: target 15, maxSec 20');++// ---- đồ hoạ: lọc loại, ghim, thanh bước -------------------------------------------------------------------------------+const gw = 'giá RTX 5060 khoảng 9 rưỡi triệu bước một mở app bước hai vào cài đặt bước ba tắt gia hạn xong'.split(' ').map((x, i) => ({ i, w: x, s: i * 0.5, e: i * 0.5 + 0.4 }));+const all = () => true;+let gc = checkGraphics({ graphics: [{ type: 'bar_chart', at: 0, until: 5, items: [{ label: 'a', value: 9.5, word: 4 }, { label: 'b', value: 5060, word: 2 }] }] }, gw, all, [9.5, 5060], ['sticker']);+ok(gc.errors.some((e) => e.includes('không dùng bar_chart')) && !gc.clean.length, 'types ["sticker"]: bar_chart bị bắt');+ok(!buildGraphicsPrompt({ words: gw, exclude: new Set(), style: { name: 'q', guide: 'g', graphics: { perMinute: [1, 3], types: ['sticker'] } } }).includes('bar_chart: 2'), 'prompt đồ hoạ chỉ liệt kê loại của kiểu');+ok(!buildGraphicsPrompt({ words: gw, exclude: new Set(), style: { name: 'q', guide: 'g', graphics: { perMinute: [1, 3] } } }).includes('review phần cứng'), 'prompt đồ hoạ không còn cụm "review phần cứng"');+const gk = [{ start: 0, end: 12 }];+const gst = { graphics: { pinFirst: true, zoom: null, sfxBig: 'whoosh', sfxGainDb: -16 } };+const pinned = compileGraphics({ plan: [{ type: 'title_card', at: 0, until: 3, estimate: false, data: { title: 'Ý chính' } }, { type: 'title_card', at: 8, until: 10, estimate: false, data: { title: 'Khác' } }], words: gw, keep: gk, style: gst });+ok(pinned.graphics.length === 1 && pinned.graphics[0].data.pin && near(pinned.graphics[0].end, 12, 1e-6), 'pinFirst: thẻ đầu hiện tới hết clip (bỏ trần 14 s), thẻ lớn khác bị bỏ');+const pw = layoutGraphics(pinned.graphics, gk, { step: 0.25, boxes: [] }, 1300);+ok(!pw.length && pinned.graphics[0].box.y === 192 && !graphicsErrors({ keep: gk, graphics: pinned.graphics }).length, 'thẻ ghim nằm ở mép trên vùng an toàn (y 192), hợp lệ');+const steps = compileGraphics({ plan: [7, 11, 15].map((a, k) => ({ type: 'title_card', at: a, until: a + 2, estimate: false, data: { kicker: `BƯỚC ${k + 1}`, title: 'x' } })), words: gw, keep: gk, style: { graphics: { zoom: null, sfxBig: null } } });+ok(JSON.stringify(stepTimes({ keep: gk, graphics: steps.graphics })) === JSON.stringify(steps.graphics.map((g) => +g.start.toFixed(3))), `thanh bước: ${steps.graphics.length} chấm theo thẻ "BƯỚC n"`);++// mép đoạn giữ muộn hơn mốc whisper của chữ đầu đoạn (cắt theo khoảng lặng): mốc đồ hoạ/zoom/sfx vẫn phải nằm trong keep+const lateKeep = [{ start: 0, end: 2 }, { start: 3.53, end: 8 }]; // chữ 7 ("bước") bắt đầu 3,5 s, đoạn giữ từ 3,53 s+const lg = compileGraphics({ plan: [{ type: 'title_card', at: 7, until: 9, estimate: false, data: { kicker: 'BƯỚC 1', title: 'x' } }], words: gw, keep: lateKeep, style: { graphics: { zoom: 1.05, sfxBig: 'click', sfxGainDb: -11 } } });+ok(lg.graphics.length === 1 && lg.graphics[0].data.at >= 3.53 && lg.zooms[0].at >= 3.53 && lg.sfx[0].at >= 3.53, `mốc đồ hoạ/zoom/sfx kẹp vào đoạn giữ (${lg.graphics[0]?.data.at} s ≥ 3,53 s), không rơi ra ngoài`);++// ---- cảnh phụ đề của 14 look: script chạy được, đúng phần tử ---------------------------------------------------------+ok(listStyles().length === 14 && listStyles().every((id) => LOOKS[id]), '14 thẻ kiểu, kiểu nào cũng có look');+for (const id of listStyles()) {+ const st = loadStyle(id);+ const lk = JSON.stringify(st.look || null); const mine = JSON.stringify(LOOKS[id]);+ if (st.look) ok(lk === mine, `${id}: LOOKS khớp khối "look" của thẻ kiểu`);+}+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lumreels-styles-'));+const runScene = (html) => {+ const js = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((m) => m[1]).join('\n');+ const calls = { set: 0, fromTo: 0, to: 0 };+ const tl = { set: () => { calls.set++; return tl; }, fromTo: () => { calls.fromTo++; return tl; }, to: () => { calls.to++; return tl; }, seek: () => tl };+ const el = { style: {}, querySelectorAll: () => [], querySelector: () => el, setAttribute() {}, dataset: {}, className: '' };+ const fn = new Function('gsap', 'document', 'window', 'VideoScene', js);+ let def = null;+ fn({ timeline: () => tl, utils: { toArray: () => [1, 2, 3] } }, { getElementById: () => el }, {}, { define: (d) => { def = d; } });+ if (def) { def.render(0.5); def.render(3.2); }+ return calls;+};+const sceneEdl = (styleId, extra = {}) => ({ ...mk(baseStyle({ captions: { style: styleId, maxWords: 3, position: 'lower' } }), empty), ...extra });+for (const id of listStyles()) {+ const st = loadStyle(id);+ const extra = {};+ if (id === 'cau-noi-hay') extra.quote = { start: w(10).s, end: w(14).e, dimTo: 0.35, blurPx: 8, dimIn: 0.8 };+ if (id === 'meo-15s') extra.hookText = { text: '*3 GIÂY* LÀ XONG', until: 2 };+ const e = sceneEdl(id, extra);+ const dir = path.join(tmp, id);+ let r; let html = '';+ try { r = writeCaptionScene(e, dir, { style: st }); html = fs.readFileSync(path.join(dir, 'index.html'), 'utf8'); } catch (err) { ok(false, `${id}: dựng cảnh lỗi ${err.message}`); continue; }+ let calls;+ try { calls = runScene(html); } catch (err) { ok(false, `${id}: script cảnh lỗi ${err.message}`); continue; }+ const want = { 'ban-tin-nhanh': ['id="tbar"', 'TIN NÓNG'], 'huong-dan-buoc': ['class="ch"'], 'cau-noi-hay': ['id="quote"', '“'], 'meo-15s': ['id="hooktext"', 'class="hi">3 GIÂY'], 'vlog-nhe': ['-webkit-text-stroke: 3px', '0 3px 10px rgba(0,0,0,.45)'], 'podcast-trich-doan': ["'Montserrat'"] }[id] || [];+ ok(r.cards > 0 && calls.set > 0 && want.every((x) => html.includes(x)), `${id}: cảnh phụ đề ${r.cards} thẻ, ${calls.set + calls.fromTo + calls.to} lệnh timeline${want.length ? ', có ' + want.join(' + ') : ''}`);+}+// trích dẫn: phụ đề thường tắt trong lúc câu chốt hiện+const qEdl = sceneEdl('cau-noi-hay', { quote: { start: w(10).s, end: w(14).e, dimTo: 0.35, blurPx: 8, dimIn: 0.8 } });+const qr = writeCaptionScene(qEdl, path.join(tmp, 'q2'), { style: loadStyle('cau-noi-hay') });+ok(qr.quote && qr.cards < captionCards(qEdl).length, `trích dẫn: tắt ${captionCards(qEdl).length - qr.cards} thẻ phụ đề thường trong lúc câu chốt hiện`);+fs.rmSync(tmp, { recursive: true, force: true });++console.log(fail ? `${fail} FAIL` : 'ALL PASS');+process.exit(fail ? 1 : 0);diff --git a/engine/audio/music.mjs b/engine/audio/music.mjsindex 2b82352..2602663 100644--- a/engine/audio/music.mjs+++ b/engine/audio/music.mjs@@ -88,7 +88,7 @@ function melody(ctx, { scale, base, step = 0.5, density = 0.5, play, maxLen = 1}}-// ---------- 6 kiểu ----------+// ---------- 8 kiểu ----------const C = (root, ...iv) => iv.map((x) => root + x);const STYLES = {chill: { desc: 'lofi ấm, chậm, có tiếng đĩa than (78 BPM)', bpm: 78, chordBeats: 2, swing: 0.12, lp: 5200,@@ -186,6 +186,32 @@ const STYLES = {}melody(x, { scale: PENTA_MAJ, base: 72, step: 0.5, density: 0.65, maxLen: 1, play: (m, b, d) => x.add(tone(m, d * 0.85, 'square', { a: 0.001, s: 0.8, r: 0.02 }), b, 0.09, 0.2) });} },+ piano: { desc: 'piano chậm, cảm hứng, không trống (70 BPM)', bpm: 70, chordBeats: 4, lp: 6000,+ chords: [C(48, 0, 4, 7, 11), C(45, 0, 3, 7, 10), C(41, 0, 4, 7, 11), C(43, 0, 5, 7, 10)], // Cmaj7 Am7 Fmaj7 G7sus+ play(x) {+ for (let b = 0; b < x.nBeats; b += x.chordBeats) {+ const ch = x.chordAt(b);+ x.add(tone(ch[0] - 12, x.chordBeats * x.beat, 'sine', { a: 0.01, d: 0.6, s: 0.5, r: 0.4, cut: 500 }), b, 0.32, 0, 0.3);+ const arp = [0, 2, 1, 3, 2, 1, 3, 2];+ arp.forEach((ix, k) => x.add(ep(ch[ix] + 12, x.beat * 1.6), b + k * 0.5, 0.11 + (k % 4 === 0 ? 0.04 : 0), (ix - 1.5) * 0.2, 0.55));+ }+ melody(x, { scale: PENTA_MAJ, base: 76, step: 1, density: 0.4, maxLen: 3, play: (m, b, d) => x.add(ep(m, d * 1.2), b, 0.15, 0.15, 0.6) });+ } },+ news: { desc: 'nền bản tin: nhịp đều, pad + tiếng tích (120 BPM)', bpm: 120, chordBeats: 4,+ chords: [C(57, 0, 3, 7), C(53, 0, 4, 7), C(48, 0, 4, 7), C(55, 0, 4, 7)], // Am F C G+ play(x) {+ for (let b = 0; b < x.nBeats; b += x.chordBeats) {+ const ch = x.chordAt(b);+ ch.forEach((m, i) => x.add(pad(m, x.chordBeats * x.beat, { cut: 1200, att: 0.12 }), b, 0.09, i - 1, 0.3));+ for (let k = 0; k < 4; k += 0.25) x.add(tone(ch[0] - 12, x.beat * 0.18, 'square', { a: 0.001, d: 0.05, s: 0.3, r: 0.02, cut: 700 }), b + k, k % 1 ? 0.07 : 0.13);+ if ((b / x.chordBeats) % 2 === 0) x.add(tone(ch[2] + 24, 0.5, 'sine', { a: 0.002, d: 0.3, s: 0.2, r: 0.2 }), b, 0.12, 0.3, 0.5); // "ping"+ }+ for (let b = 0; b < x.nBeats; b++) {+ x.add(kick(0.9), b, 0.42);+ if (b % 2 === 1) x.add(clap(x.r), b, 0.22, 0, 0.15);+ x.add(hat(x.r), b + 0.5, 0.12, 0.3); x.add(hat(x.r), b + 0.25, 0.05, -0.3); x.add(hat(x.r), b + 0.75, 0.05, -0.3);+ }+ } },};export const MUSIC_STYLES = Object.keys(STYLES);export const MUSIC_LIST = MUSIC_STYLES.map((s) => ({ name: s, desc: STYLES[s].desc }));diff --git a/server/public/edit-panel.css b/server/public/edit-panel.cssindex fea5838..157d403 100644--- a/server/public/edit-panel.css+++ b/server/public/edit-panel.css@@ -38,11 +38,24 @@.drop.has { border-style: solid; border-color: var(--ok); }.drop.has .big { color: var(--ok); word-break: break-all; }-.styles { display: grid; gap: 8px; }-.sty { text-align: left; min-height: 56px; padding: 10px 12px; border-radius: 12px; border: 1px solid var(--line); background: var(--panel-2); cursor: pointer; transition: border-color .15s; }-.sty .n { font-weight: 700; display: block; }-.sty .d { font-size: 13px; color: var(--ink-2); display: block; line-height: 1.4; margin-top: 2px; }-.sty[aria-checked="true"] { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(255,107,44,.18); }+/* lưới thẻ kiểu edit: ảnh dọc 9:16 + tên; 14 kiểu → khung cuộn riêng (cao ~2,5 hàng) để form không dài vô tận */+.sty-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }+.sty-count { font-size: 13px; color: var(--ink-3); }+.styles { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; max-height: 452px; overflow-y: auto; overscroll-behavior: contain;+ padding: 4px; margin: 0 -4px; scroll-snap-type: y proximity; scrollbar-width: thin; }+.sty { display: flex; flex-direction: column; gap: 6px; text-align: left; padding: 4px 4px 8px; border-radius: 12px; border: 1px solid var(--line); background: var(--panel-2);+ cursor: pointer; transition: border-color .15s, transform .12s; scroll-snap-align: start; min-width: 0; color: var(--ink); }+.sty:hover { border-color: var(--ink-3); }+.sty:active { transform: scale(.97); }+.sty .pic { display: block; aspect-ratio: 9 / 16; border-radius: 9px; overflow: hidden; background: #000; }+.sty .pic img { width: 100%; height: 100%; object-fit: cover; display: block; }+.sty .ph { display: grid; place-items: center; height: 100%; padding: 8px; text-align: center; font: 700 15px/1.15 var(--cond); text-transform: uppercase;+ color: var(--sty-acc); background: radial-gradient(120% 80% at 50% 100%, color-mix(in srgb, var(--sty-acc) 28%, #000), #0b0b0d 70%); }+.sty .n { font-weight: 700; font-size: 13px; line-height: 1.25; padding: 0 2px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }+.sty[aria-checked="true"] { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(255,107,44,.22); }+.sty[aria-checked="true"] .n { color: var(--accent); }+.sty-desc { margin: 8px 0 0; min-height: 2.8em; font-size: 14px; line-height: 1.4; color: var(--ink-2); }+@media (prefers-reduced-motion: reduce) { .sty { transition: none; } .sty:active { transform: none; } }.ed-in { width: 100%; min-height: 44px; background: var(--bg); border: 1px solid var(--line); border-radius: 10px; padding: 0 12px; }.ed-row { display: flex; gap: 8px; align-items: center; }.ed-row select { flex: 1; }diff --git a/server/public/edit-panel.js b/server/public/edit-panel.jsindex ecd7db0..62b1695 100644--- a/server/public/edit-panel.js+++ b/server/public/edit-panel.js@@ -34,38 +34,53 @@const o = state.opts;if (!o.ready) {$('#edSetup').hidden = false;- $('#edSetupText').textContent = 'Phần Edit video cần thêm Python, model chép lời và model nhận mặt. Bấm Cài ngay, LumReels tự cài hết (chỉ làm một lần).';+ $('#edSetupText').textContent = t('ed.setupText');$('#edSetupCmd').textContent = o.setup;// đang cài dở (vd. tải lại trang giữa chừng) → hiện lại tiến độfetch('/api/edit-setup').then((r) => r.json()).then((st) => { if (st.running) watchInstall(); }).catch(() => {});} else $('#edSetup').hidden = true;state.style = o.styles[0]?.id || null;- $('#edStyles').innerHTML = o.styles.map((s, i) => `<button type="button" class="sty" role="radio" aria-checked="${i === 0}" tabindex="${i === 0 ? 0 : -1}" data-id="${esc(s.id)}"><span class="n">${esc(s.name)}</span><span class="d">${esc(s.summary)}</span></button>`).join('');+ renderStyles();renderMusic();refreshGo();loadList();}+ // ---- lưới thẻ kiểu edit: ảnh minh hoạ dọc + tên (theo ngôn ngữ); tóm tắt kiểu đang chọn hiện dưới lưới ------------+ const styleName = (s) => (I.lang === 'en' && s.nameEn ? s.nameEn : s.name);+ const styleSummary = (s) => (I.lang === 'en' && s.summaryEn ? s.summaryEn : s.summary);+ const styleById = (id) => (state.opts?.styles || []).find((s) => s.id === id);+ function renderStyles() {+ const list = state.opts?.styles || [];+ $('#edStyles').innerHTML = list.map((s) => {+ const on = s.id === state.style;+ const pic = s.thumb+ ? `<img src="${esc(s.thumb)}" alt="" loading="lazy" decoding="async" width="360" height="640">`+ : `<span class="ph" style="--sty-acc:${esc(s.accent || '#FCE802')}">${esc(styleName(s))}</span>`;+ return `<button type="button" class="sty" role="radio" aria-checked="${on}" tabindex="${on ? 0 : -1}" data-id="${esc(s.id)}" aria-label="${esc(t('ed.styleAria', { name: styleName(s), summary: styleSummary(s) }))}"><span class="pic">${pic}</span><span class="n">${esc(styleName(s))}</span></button>`;+ }).join('');+ $('#edStyleCount').textContent = list.length > 6 ? t('ed.styleHint', { n: list.length }) : '';+ renderStyleDesc();+ }+ function renderStyleDesc() { const s = styleById(state.style); $('#edStyleDesc').textContent = s ? styleSummary(s) : ''; }+// ---- nút "Cài ngay": server chạy edit/setup.mjs, trang hỏi tiến độ mỗi 1,5 giây ------------------------------ const INSTALL_FAIL = {- NEED_PYTHON: 'Máy chưa có Python 3.10–3.12. Cài theo hướng dẫn dưới rồi bấm Cài lại.',- NEED_FFMPEG: 'Máy chưa có ffmpeg. Cài theo hướng dẫn dưới rồi bấm Cài lại.',- NEED_NETWORK: 'Tải bị lỗi, kiểm tra mạng rồi bấm Cài lại (phần đã tải xong không phải tải lại).',- NEED_NPM: 'Thiếu font của LumReels: chạy npm install ở thư mục LumReels rồi bấm Cài lại.',- };+ const INSTALL_FAIL = new Set(['NEED_PYTHON', 'NEED_FFMPEG', 'NEED_NETWORK', 'NEED_NPM']);let installTimer = null;+ let lastInstall = null;function paintInstall(st) {+ lastInstall = st;const prog = $('#edInstallProg'); const step = $('#edInstallStep'); const btn = $('#edInstall');prog.hidden = false;const mm = (s) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;step.className = 'ed-install-step';if (st.running) {- step.textContent = `${st.step || 'Đang cài'}… (${mm(st.elapsedS || 0)})`;- btn.disabled = true; btn.textContent = 'Đang cài…';+ step.textContent = t('ed.installStep', { step: st.step ? I.srv(st.step) : t('ed.installStepDefault'), t: mm(st.elapsedS || 0) });+ btn.disabled = true; btn.textContent = t('ed.installing');} else if (st.ok) {- step.classList.add('ok'); step.textContent = `Cài xong sau ${mm(st.elapsedS || 0)}. Edit video đã sẵn sàng.`;+ step.classList.add('ok'); step.textContent = t('ed.installDone', { t: mm(st.elapsedS || 0) });} else {- step.classList.add('bad'); step.textContent = INSTALL_FAIL[st.word] || 'Cài chưa xong. Xem chi tiết bên dưới rồi bấm Cài lại.';- btn.disabled = false; btn.textContent = 'Cài lại';+ step.classList.add('bad'); step.textContent = INSTALL_FAIL.has(st.word) ? t('ed.fail.' + st.word) : t('ed.installFail');+ btn.disabled = false; btn.textContent = t('ed.installRetry');}prog.classList.toggle('stop', !st.running);$('#edInstallHint').hidden = !st.hint; $('#edInstallHint').textContent = st.hint || '';@@ -93,7 +108,7 @@} catch (e) {$('#edInstall').disabled = false;$('#edInstallProg').hidden = false; $('#edInstallStep').className = 'ed-install-step bad';- $('#edInstallStep').textContent = 'Không bắt đầu cài được: ' + e.message;+ $('#edInstallStep').textContent = t('ed.installCantStart', { e: e.message });}});@@ -109,14 +124,16 @@function pickStyle(b, focus) {state.style = b.dataset.id;document.querySelectorAll('#edStyles .sty').forEach((x) => { x.setAttribute('aria-checked', String(x === b)); x.tabIndex = x === b ? 0 : -1; });- if (focus) b.focus();+ renderStyleDesc();+ if (focus) { b.focus(); b.scrollIntoView({ block: 'nearest' }); }}$('#edStyles').addEventListener('click', (e) => { const b = e.target.closest('.sty'); if (b) pickStyle(b); });$('#edStyles').addEventListener('keydown', (e) => {const list = [...document.querySelectorAll('#edStyles .sty')];const i = list.indexOf(document.activeElement);if (i < 0) return;- const step = { ArrowDown: 1, ArrowRight: 1, ArrowUp: -1, ArrowLeft: -1 }[e.key];+ const cols = Math.max(1, getComputedStyle($('#edStyles')).gridTemplateColumns.split(' ').length);+ const step = { ArrowDown: cols, ArrowRight: 1, ArrowUp: -cols, ArrowLeft: -1 }[e.key];if (step) { e.preventDefault(); pickStyle(list[(i + step + list.length) % list.length], true); }else if (e.key === 'Home' || e.key === 'End') { e.preventDefault(); pickStyle(e.key === 'Home' ? list[0] : list[list.length - 1], true); }});@@ -199,10 +216,11 @@renderList();if (!state.current && list[0]) select(list[0].id, list[0]);}+ const viewStyleName = (v) => { const s = styleById(v.style); return s ? styleName(s) : v.styleName || v.style; };function renderList() {const list = state.list || [];$('#edList').innerHTML = list.length ? list.map((v) => `<button type="button" class="ed-item${v.id === state.current ? ' sel' : ''}" data-id="${esc(v.id)}">- <span><span class="t">${esc(v.sourceName || v.id)}</span><br><span class="s">${esc(v.styleName || v.style)} · ${esc(v.id)}</span></span>+ <span><span class="t">${esc(v.sourceName || v.id)}</span><br><span class="s">${esc(viewStyleName(v))} · ${esc(v.id)}</span></span><span class="st ${v.status === 'done' ? 'done' : v.status === 'error' ? 'error' : 'run'}">${esc(stLabel(v.status))}</span></button>`).join(''): `<div class="hint">${esc(t('ed.listEmpty'))}</div>`;}@@ -231,7 +249,7 @@$('#edEmpty').hidden = true; $('#edView').hidden = false;const busy = ['queued', 'running'].includes(v.status);$('#edTitle').textContent = v.sourceName || v.id;- $('#edId').textContent = `${v.styleName || v.style} · ${v.id}`;+ $('#edId').textContent = `${viewStyleName(v)} · ${v.id}`;const st = $('#edStatus');st.className = 'st ' + (v.status === 'done' ? 'done' : v.status === 'error' ? 'error' : 'run');st.textContent = busy ? t(v.status === 'queued' ? 'ed.waitTurn' : v.action === 'revise' ? 'ed.revising' : 'ed.st.running') : stLabel(v.status);@@ -273,13 +291,13 @@// số không chắc (không in lên đồ hoạ)const figs = v.checks?.figures || [];$('#edFigures').hidden = !figs.length;- $('#edFigureList').innerHTML = figs.map((f) => `<li title="${esc(f.why)}"><b>${esc(f.text)}</b>${f.at != null ? ` · ${esc(f.at.toFixed(1))} s nguồn` : ''} · <s>${esc(f.said)}</s>${f.heard ? ` → nghe lại: “${esc(f.heard)}”` : ''}</li>`).join('');+ $('#edFigureList').innerHTML = figs.map((f) => `<li title="${esc(f.why)}"><b>${esc(f.text)}</b>${f.at != null ? ` · ${esc(t('ed.figAt', { s: f.at.toFixed(1) }))}` : ''} · <s>${esc(f.said)}</s>${f.heard ? ` → ${esc(t('ed.figHeard', { h: f.heard }))}` : ''}</li>`).join('');// kiểmconst c = v.checks || {};const bits = [];if (c.edl) bits.push(esc(t('ed.checksEdl', { out: c.edl.outSeconds ?? '', rm: c.edl.removedSeconds, z: c.edl.zooms })));if (c.overcut) bits.push(c.overcut.lost?.length || c.overcut.chopped?.length ? `<span class="bad">${esc(t('ed.overcut', { v: c.overcut.verdict }))}</span>` : `<span class="ok">${esc(t('ed.noOvercut'))}</span>`);- if (c.cutRepairs?.length) bits.push(`đã sửa ${c.cutRepairs.length} vết cắt lẹm chữ`);+ if (c.cutRepairs?.length) bits.push(esc(t('ed.cutRepairs', { n: c.cutRepairs.length })));if (c.loudness) bits.push(`${c.loudness.lufs} LUFS`);if (c.qc?.fails?.length) bits.push(`qc: ${esc(c.qc.fails.join('; '))}`);$('#edChecks').innerHTML = bits.join(' · ');@@ -318,10 +336,12 @@$('#edReviseForm').addEventListener('submit', (e) => { e.preventDefault(); revise($('#edReviseText').value.trim()); });$('#edPresets').addEventListener('click', (e) => { const b = e.target.closest('button'); if (b) $('#edReviseText').value = b.textContent; $('#edReviseText').focus(); });- // Đổi VI/EN: vẽ lại phần JS sinh (chữ tĩnh do i18n.js đổi). Tên kiểu edit, lỗi/ghi chú server giữ nguyên.+ // Đổi VI/EN: vẽ lại phần JS sinh (chữ tĩnh do i18n.js đổi). Lỗi/ghi chú server giữ nguyên.window.addEventListener('lumreels:lang', () => {if (state.noServer) $('#edSetupText').textContent = t('ed.noServer');- if (state.opts) renderMusic();+ else if (state.opts && !state.opts.ready) $('#edSetupText').textContent = t('ed.setupText');+ if (lastInstall) paintInstall(lastInstall);+ if (state.opts) { renderMusic(); const had = document.activeElement?.closest?.('#edStyles'); renderStyles(); if (had) $('#edStyles .sty[aria-checked="true"]')?.focus(); }renderDrop();if (!state.uploading) $('#edGo span').textContent = t('ed.go');if (state.list) renderList();diff --git a/server/public/i18n.js b/server/public/i18n.jsindex ecb9c5d..d5b4d73 100644--- a/server/public/i18n.js+++ b/server/public/i18n.js@@ -264,6 +264,28 @@'ed.noOvercut': 'không lẹm chữ','ed.sendFail': 'Không gửi được lời sửa.','ed.confirmDel': 'Xoá hẳn bản dựng này (video ra, EDL, file đã tải lên)? Không lấy lại được.',+ 'ed.styleHint': '{n} kiểu · cuộn để xem hết',+ 'ed.styleAria': (v) => `${v.name}: ${v.summary}`,+ 'ed.setupText': 'Phần Edit video cần thêm Python, model chép lời và model nhận mặt. Bấm Cài ngay, LumReels tự cài hết (chỉ làm một lần).',+ 'ed.install': 'Cài ngay',+ 'ed.installing': 'Đang cài…',+ 'ed.installStep': '{step}… ({t})',+ 'ed.installStepDefault': 'Đang cài',+ 'ed.installDone': 'Cài xong sau {t}. Edit video đã sẵn sàng.',+ 'ed.installRetry': 'Cài lại',+ 'ed.installFail': 'Cài chưa xong. Xem chi tiết bên dưới rồi bấm Cài lại.',+ 'ed.installCantStart': 'Không bắt đầu cài được: {e}',+ 'ed.installNote': 'Tải khoảng 6 GB, mất 5–20 phút tuỳ mạng. Cứ để trang mở.',+ 'ed.installDetails': 'Xem chi tiết',+ 'ed.installManual': 'Hoặc tự cài bằng lệnh',+ 'ed.fail.NEED_PYTHON': 'Máy chưa có Python 3.10–3.12. Cài theo hướng dẫn dưới rồi bấm Cài lại.',+ 'ed.fail.NEED_FFMPEG': 'Máy chưa có ffmpeg. Cài theo hướng dẫn dưới rồi bấm Cài lại.',+ 'ed.fail.NEED_NETWORK': 'Tải bị lỗi, kiểm tra mạng rồi bấm Cài lại (phần đã tải xong không phải tải lại).',+ 'ed.fail.NEED_NPM': 'Thiếu font của LumReels: chạy npm install ở thư mục LumReels rồi bấm Cài lại.',+ 'ed.figuresH': 'Số máy nghe không chắc, chưa đưa lên đồ hoạ, nghe lại giúp',+ 'ed.figAt': '{s} s nguồn',+ 'ed.figHeard': 'nghe lại: “{h}”',+ 'ed.cutRepairs': (v) => `đã sửa ${v.n} vết cắt lẹm chữ`,};const en = {@@ -526,6 +548,28 @@'ed.noOvercut': 'no clipped words','ed.sendFail': "Couldn't send your change.",'ed.confirmDel': 'Delete this edit for good (output video, EDL, uploaded files)? This cannot be undone.',+ 'ed.styleHint': '{n} styles · scroll to see them all',+ 'ed.styleAria': (v) => `${v.name}: ${v.summary}`,+ 'ed.setupText': 'Video editing needs Python, a speech-to-text model and a face model. Click Install now and LumReels sets everything up (one time only).',+ 'ed.install': 'Install now',+ 'ed.installing': 'Installing…',+ 'ed.installStep': '{step}… ({t})',+ 'ed.installStepDefault': 'Installing',+ 'ed.installDone': 'Installed in {t}. Video editing is ready.',+ 'ed.installRetry': 'Try again',+ 'ed.installFail': "Install didn't finish. See the details below, then click Try again.",+ 'ed.installCantStart': "Couldn't start the install: {e}",+ 'ed.installNote': 'About a 6 GB download, 5–20 minutes depending on your connection. Keep this page open.',+ 'ed.installDetails': 'Show details',+ 'ed.installManual': 'Or install it yourself with a command',+ 'ed.fail.NEED_PYTHON': "Python 3.10–3.12 isn't installed. Install it as described below, then click Try again.",+ 'ed.fail.NEED_FFMPEG': "ffmpeg isn't installed. Install it as described below, then click Try again.",+ 'ed.fail.NEED_NETWORK': "The download failed. Check your connection, then click Try again (finished parts won't download again).",+ 'ed.fail.NEED_NPM': 'LumReels fonts are missing: run npm install in the LumReels folder, then click Try again.',+ 'ed.figuresH': "Numbers the machine wasn't sure it heard, left off the graphics: please listen again",+ 'ed.figAt': '{s} s in source',+ 'ed.figHeard': 'heard again as: “{h}”',+ 'ed.cutRepairs': (v) => `fixed ${v.n} cut${S(v.n)} that clipped words`,};// Chuỗi tiếng Việt cố định do server trả cho giao diện (nhãn tuỳ chọn, bước dựng). Không gồm lỗi, tên mẫu, kiểu edit.@@ -544,6 +588,12 @@'tung tăng, marimba + pizzicato (112 BPM)': 'bouncy marimba + pizzicato (112 BPM)','điện ảnh: dàn dây + trống trận (90 BPM)': 'cinematic: strings + war drums (90 BPM)','game 8-bit: xung vuông + trống nhiễu (132 BPM)': '8-bit game: square waves + noise drums (132 BPM)',+ 'Bắt đầu': 'Starting', 'Kiểm tra ffmpeg': 'Checking ffmpeg', 'Tạo môi trường Python': 'Creating the Python environment',+ 'Cài gói Python (vài trăm MB)': 'Installing Python packages (a few hundred MB)', 'Cài phần chạy bằng GPU (~2 GB)': 'Installing GPU support (~2 GB)',+ 'Tải model nhận mặt, người': 'Downloading face and person models', 'Chuẩn bị font phụ đề': 'Preparing caption fonts',+ 'Tải model chép lời (~3 GB, lâu nhất)': 'Downloading the speech-to-text model (~3 GB, the longest step)', 'Kiểm tra lần cuối': 'Final check',+ 'piano chậm, cảm hứng, không trống (70 BPM)': 'slow inspiring piano, no drums (70 BPM)',+ 'nền bản tin: nhịp đều, pad + tiếng tích (120 BPM)': 'newsroom bed: steady pulse, pad + ticks (120 BPM)','nạp': 'load', 'phân tích': 'analyze', 'LLM lập EDL': 'LLM plans EDL', 'xem trước': 'preview', 'render nền': 'base render','phụ đề': 'captions', 'tiếng': 'audio', 'ghép': 'mux', 'kiểm': 'check',};diff --git a/server/public/index.html b/server/public/index.htmlindex bae7cb1..936638c 100644--- a/server/public/index.html+++ b/server/public/index.html@@ -130,16 +130,16 @@<h3 data-i18n="ed.setupH">Chưa cài phần Edit video</h3><p id="edSetupText"></p><div class="ed-setup-act">- <button type="button" class="ed-install" id="edInstall">Cài ngay</button>- <span class="ed-install-note">Tải khoảng 6 GB, mất 5–20 phút tuỳ mạng. Cứ để trang mở.</span>+ <button type="button" class="ed-install" id="edInstall" data-i18n="ed.install">Cài ngay</button>+ <span class="ed-install-note" data-i18n="ed.installNote">Tải khoảng 6 GB, mất 5–20 phút tuỳ mạng. Cứ để trang mở.</span></div><div class="ed-install-prog" id="edInstallProg" hidden><div class="ed-install-step" id="edInstallStep" role="status" aria-live="polite"></div><div class="ed-install-bar" aria-hidden="true"><span></span></div><div class="ed-install-hint" id="edInstallHint" hidden></div>- <details><summary>Xem chi tiết</summary><pre id="edInstallLog"></pre></details>+ <details><summary data-i18n="ed.installDetails">Xem chi tiết</summary><pre id="edInstallLog"></pre></details></div>- <details class="ed-setup-manual"><summary>Hoặc tự cài bằng lệnh</summary><div class="cmd" id="edSetupCmd">node edit/setup.mjs</div></details>+ <details class="ed-setup-manual"><summary data-i18n="ed.installManual">Hoặc tự cài bằng lệnh</summary><div class="cmd" id="edSetupCmd">node edit/setup.mjs</div></details></div><div class="ed-card"><h2><span class="step">1</span><span data-i18n="ed.h">Video của bạn</span></h2>@@ -149,8 +149,9 @@<span class="small">hoặc bấm để chọn · mp4, mov, mkv… tối đa 2 GB · nói trước máy, tiếng Việt</span></div><label class="sr" for="edVideo" data-i18n="ed.fileLabel">File video</label><input type="file" id="edVideo" accept="video/*,.mkv,.mov" hidden />- <span class="field" id="edStyleLbl" data-i18n="ed.style">Kiểu edit</span>- <div class="styles" id="edStyles" role="radiogroup" aria-labelledby="edStyleLbl"></div>+ <div class="sty-head"><span class="field" id="edStyleLbl" data-i18n="ed.style">Kiểu edit</span><span class="sty-count" id="edStyleCount"></span></div>+ <div class="styles" id="edStyles" role="radiogroup" aria-labelledby="edStyleLbl" aria-describedby="edStyleDesc"></div>+ <p class="sty-desc" id="edStyleDesc" aria-live="polite"></p><label class="field" for="edMusic"><span data-i18n="ed.music">Nhạc nền</span> <span class="opt" data-i18n="ed.musicOpt">(tự hạ khi bạn nói)</span></label><select id="edMusic"><option value="none" data-i18n="ed.noMusic">Không nhạc</option></select><label class="sr" for="edMusicFile" data-i18n="ed.musicFileLabel">File nhạc</label><input type="file" id="edMusicFile" accept="audio/*" hidden />@@ -185,7 +186,7 @@<ul id="edFixList"></ul></div><div class="fixes" id="edFigures" hidden>- <h4>Số máy nghe không chắc, chưa đưa lên đồ hoạ, nghe lại giúp</h4>+ <h4 data-i18n="ed.figuresH">Số máy nghe không chắc, chưa đưa lên đồ hoạ, nghe lại giúp</h4><ul id="edFigureList"></ul></div><div class="ed-revise" id="edRevise" hidden>