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.
#!/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);