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 chỉnh tay (edit/manual.mjs) — phần không cần server: schema chặt, dòng phụ đề (gộp/tách/đè), áp bản vá lên EDL
// (lớp nào phải dựng lại), giữ chỉnh tay khi dựng lại EDL. Có cổng thì kiểm thêm REST trên server đang chạy:
// schema sai → 400, Origin lạ → 403, id lạ → 404, Content-Type sai → 415, JSON hỏng → 400, nhạc tải lên sai định dạng → 415.
// node edit/test/manual-check.mjs [port] [editId đã dựng xong]
import http from 'node:http';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { parseManual, buildLines, lineTokens, lineText, applyPatch, applyManual, currentLines, cutSig } from '../manual.mjs';
import { validateEdl } from '../edl.mjs';
import { captionCards } from '../captions-hf.mjs';
let fails = 0;
const check = (ok, what) => { console.log(`${ok ? 'PASS' : 'FAIL'} ${what}`); if (!ok) fails++; };
const throws = (f, code, re) => { try { f(); return false; } catch (e) { return (code == null || e.code === code) && (!re || re.test(e.message)); } };
// ---- schema ----
check(throws(() => parseManual({}), 400, /rỗng/), 'bản vá rỗng → 400');
check(throws(() => parseManual({ foo: 1 }), 400), 'khoá lạ ở gốc → 400');
check(throws(() => parseManual({ music: { gainDb: 5 } }), 400, /music\.gainDb/), 'nhạc +5 dB (trần 0) → 400 kèm đường dẫn trường');
check(throws(() => parseManual({ music: { source: '../../etc/passwd' } }), 400), 'nguồn nhạc là đường dẫn → 400');
check(throws(() => parseManual({ music: { source: 'upload:../x.mp3' } }), 400), 'upload có ../ → 400');
check(throws(() => parseManual({ captions: { lines: [{ start: 0, end: 1, text: 'a', x: 1 }] } }), 400), 'dòng có khoá lạ → 400');
check(throws(() => parseManual({ captions: { look: 'khong-co' } }), 400), 'look lạ → 400');
check(throws(() => parseManual({ zooms: { remove: [-1] } }), 400), 'zoom số âm → 400');
check(throws(() => parseManual({ voice: { gainDb: 40 } }), 400), 'giọng +40 dB → 400');
check(!throws(() => parseManual({ music: { gainDb: -28, duck: false } })), 'bản vá hợp lệ qua');
// ---- dòng phụ đề ----
check(JSON.stringify(lineTokens('*Giá* tăng *gấp đôi*')) === JSON.stringify([{ w: 'Giá', hi: true }, { w: 'tăng', hi: false }, { w: 'gấp', hi: true }, { w: 'đôi', hi: true }]), 'tách chữ nhấn *…*');
check(lineText([{ w: 'a', hi: true }, { w: 'b', hi: false }]) === '*a* b', 'ghép lại chữ nhấn');
const prev = [{ start: 0, end: 1, words: [{ w: 'xin', o: 0, hi: false }, { w: 'chào', o: 0.5, hi: false }] }];
const L = buildLines([{ start: 0, end: 1, text: 'xin *chào* mọi người' }], prev, 10);
check(L[0].words[1].o === 0.5 && L[0].words[1].hi && L[0].words[2].o > 0.5 && L[0].words[3].o < 1, 'giữ mốc chữ cũ, chữ mới chia đều trong dòng');
check(throws(() => buildLines([{ start: 0, end: 1, text: 'a' }, { start: 0.5, end: 2, text: 'b' }], [], 10), 400, /đè/), 'hai dòng đè nhau → 400');
check(throws(() => buildLines([{ start: 2, end: 2.05, text: 'a' }], [], 10), 400), 'dòng < 0,1 s → 400');
check(throws(() => buildLines([{ start: 12, end: 13, text: 'a' }], [], 10), 400, /sau cuối/), 'dòng sau cuối video → 400');
const sorted = buildLines([{ start: 3, end: 4, text: 'sau' }, { start: 1, end: 2, text: 'trước' }], [], 10);
check(sorted[0].words[0].w === 'trước', 'dòng gửi lộn thứ tự được xếp lại theo giờ');
// ---- áp lên EDL giả ----
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lumedit-man-'));
const music = path.join(tmp, 'm.wav'); fs.writeFileSync(music, 'x');
const words = ['Giá', 'VGA', 'tăng', 'gấp', 'đôi.', 'Mua', 'ngay', 'đi.'].map((w, i) => ({ i, w, start: 1 + i * 0.5, end: 1.4 + i * 0.5 }));
const edl = {
version: 1, id: 't', createdAt: new Date().toISOString(), style: 'sach-gon',
source: { file: 'x.mp4', sha256: '0'.repeat(64), size: 1, duration: 10, startTime: 0, fps: 30, vfr: false, rotation: 0, width: 1920, height: 1080, codec: 'h264', hdr: false, hasAudio: true },
proxy: { file: 'x.mov', width: 1920, height: 1080, fps: 30, audioRate: 48000 },
output: { width: 1080, height: 1920, fps: 30, audioRate: 48000, lufs: -14 },
keep: [{ start: 0.5, end: 6 }], removed: [], reframe: { mode: 'center' },
zooms: [{ at: 1.2, dur: 1, scale: 1.2, kind: 'punch' }, { at: 3.1, dur: 1, scale: 1.1, kind: 'push' }],
captions: { style: 'sach-gon', renderer: 'hyperframes', maxWords: 3, position: 'lower', words, highlights: [1] },
sfx: [{ at: 1.2, name: 'whoosh', gainDb: -6 }],
music: { file: music, gainDb: -22, duckDb: 10, fadeOut: 1.5 },
graphics: [], hook: null, hookText: null, quote: null, audio: { crossfadeMs: 20, keepSourceAudio: true },
};
check(validateEdl(edl, { checkFiles: false }).ok, 'EDL cũ (chưa có trường chỉnh tay) vẫn hợp lệ');
const state = { style: 'sach-gon', music, draft: false };
const lines0 = currentLines(edl);
check(lines0.length >= 2 && lines0[0].words.some((w) => w.hi), 'dòng hiện tại lấy từ nhóm chữ tự động, có chữ nhấn');
// sửa chữ 2 dòng + gộp
const edited = lines0.map((l) => ({ start: l.start, end: l.end, text: lineText(l.words) }));
edited[0].text = 'Giá *card đồ hoạ*';
edited[1].text = edited[1].text + ' nhé';
const a = applyPatch(edl, state, { captions: { lines: edited }, music: { gainDb: -28, duck: false }, zooms: { remove: [0] } }, { dir: tmp });
check(a.redo.layer && a.redo.mix && a.redo.base, 'sửa chữ + nhạc + xoá zoom → dựng lại lớp chữ, tiếng, nền');
check(a.edl.music.gainDb === -28 && a.edl.music.duckDb === 0, 'nhạc −28 dB, tắt ducking (duckDb 0)');
check(a.edl.zooms.length === 1 && a.edl.zooms[0].at === 3.1, 'xoá đúng zoom số 0');
check(validateEdl(a.edl, { checkFiles: false }).ok, 'EDL sau chỉnh tay hợp lệ');
const cards = captionCards(a.edl);
check(cards[0].words.map((w) => w.w).join(' ') === 'Giá card đồ hoạ' && cards[0].words[1].hl === true, 'lớp chữ dùng dòng chỉnh tay (chữ + nhấn)');
const b = applyPatch(edl, state, { music: { gainDb: -30 } }, { dir: tmp });
check(!b.redo.layer && !b.redo.base && b.redo.mix, 'chỉ đổi nhạc → chỉ trộn lại tiếng');
const c = applyPatch(edl, state, { captions: { highlights: false } }, { dir: tmp });
check(c.redo.layer && !c.redo.mix && c.edl.captions.hiOff, 'tắt chữ nhấn → chỉ lớp chữ');
check(throws(() => applyPatch(edl, state, { music: { gainDb: -22 } }, { dir: tmp }), 400, /không có gì khác/), 'bản vá giống hệt bản đang có → 400');
check(throws(() => applyPatch(edl, state, { zooms: { remove: [5] } }, { dir: tmp }), 400), 'xoá zoom không có → 400');
check(throws(() => applyPatch(edl, state, { music: { source: 'upload:music-up-1.mp3' } }, { dir: tmp }), 400, /chưa tải/), 'nhạc tải lên chưa có → 400');
check(throws(() => applyPatch(edl, { ...state, draft: true }, { captions: { highlights: false } }, { dir: tmp }), 409), 'bản nháp: sửa phụ đề → 409');
const none = applyPatch(edl, state, { music: { source: 'none' } }, { dir: tmp });
check(none.edl.music === null && none.music === null, 'bỏ nhạc');
const syn = applyPatch(edl, state, { music: { source: 'synth:chill' } }, { dir: tmp });
check(syn.edl.music && fs.existsSync(syn.edl.music.file) && syn.edl.music.start === 0, 'đổi sang nhạc tổng hợp chill (file sinh ra)');
// dựng lại EDL (sửa bằng lời): giữ chỉnh tay
const rebuilt = JSON.parse(JSON.stringify(edl));
const w1 = applyManual(rebuilt, a.manual);
check(rebuilt.captions.lines && rebuilt.music.duckDb === 0 && rebuilt.zooms.length === 1 && !w1.length, 'dựng lại cùng phần cắt: giữ dòng chỉnh tay, nhạc, zoom đã xoá');
const recut = JSON.parse(JSON.stringify(edl)); recut.keep = [{ start: 0.5, end: 4 }];
const w2 = applyManual(recut, a.manual);
check(!recut.captions.lines && w2.length === 1 && cutSig(recut) !== a.manual.lines.sig, 'phần cắt đổi: bỏ dòng chỉnh tay (mốc cũ sai), có cảnh báo');
fs.rmSync(tmp, { recursive: true, force: true });
// ---- REST (server đang chạy) ----
const PORT = Number(process.argv[2]);
const ID = process.argv[3];
if (PORT) {
const HOST = `127.0.0.1:${PORT}`;
const req = ({ method = 'POST', p, headers = {}, body }) => new Promise((resolve) => {
const r = http.request({ host: '127.0.0.1', port: PORT, method, path: p, headers: { Host: HOST, ...headers } }, (res) => {
let d = ''; res.on('data', (x) => { d += x; }); res.on('end', () => resolve({ code: res.statusCode, body: d }));
});
r.on('error', (e) => resolve({ code: -1, body: e.message }));
r.end(body);
});
const json = { 'Content-Type': 'application/json' };
let r = await req({ p: '/api/edits/khong-co-dau/manual', headers: json, body: '{"voice":{"gainDb":2}}' });
check(r.code === 404, `id lạ → 404 (${r.code})`);
r = await req({ method: 'GET', p: '/api/edits/khong-co-dau/manual' });
check(r.code === 404, `GET id lạ → 404 (${r.code})`);
r = await req({ p: '/api/edits/..%2F..%2Fetc/manual', headers: json, body: '{}' });
check(r.code === 404, `id có ../ → 404 (${r.code})`);
r = await req({ p: `/api/edits/${ID || 'x'}/manual`, headers: { ...json, Origin: 'https://evil.example' }, body: '{"voice":{"gainDb":2}}' });
check(r.code === 403, `Origin lạ → 403 (${r.code})`);
r = await req({ p: `/api/edits/${ID || 'x'}/music`, headers: { Origin: 'https://evil.example', 'Content-Type': 'multipart/form-data; boundary=x', 'Content-Length': '10' }, body: '0123456789' });
check(r.code === 403, `tải nhạc với Origin lạ → 403 (${r.code})`);
if (ID) {
r = await req({ p: `/api/edits/${ID}/manual`, headers: { 'Content-Type': 'text/plain' }, body: '{"voice":{"gainDb":2}}' });
check(r.code === 415, `Content-Type không phải JSON → 415 (${r.code})`);
r = await req({ p: `/api/edits/${ID}/manual`, headers: json, body: '{"voice":' });
check(r.code === 400, `JSON hỏng → 400 (${r.code})`);
r = await req({ p: `/api/edits/${ID}/manual`, headers: json, body: '{"music":{"gainDb":12}}' });
check(r.code === 400 && /music\.gainDb/.test(r.body), `schema sai (nhạc +12 dB) → 400 có tên trường (${r.code})`);
r = await req({ p: `/api/edits/${ID}/manual`, headers: json, body: '{"zooms":{"remove":[999]}}' });
check(r.code === 400, `xoá zoom không có → 400 đồng bộ, không 202 (${r.code})`);
r = await req({ p: `/api/edits/${ID}/manual`, headers: json, body: '[1,2]' });
check(r.code === 400, `bản vá là mảng → 400 (${r.code})`);
r = await req({ method: 'GET', p: `/api/edits/${ID}/manual` });
const v = r.code === 200 ? JSON.parse(r.body) : null;
check(!!v && Array.isArray(v.captions.lines) && typeof v.duration === 'number', `GET manual → 200 có dòng phụ đề (${r.code}, ${v?.captions.lines.length} dòng)`);
const B = 'mUsIcB0uNd';
const mp = Buffer.from(`--${B}\r\nContent-Disposition: form-data; name="music"; filename="x.exe"\r\n\r\nMZ\r\n--${B}--\r\n`);
r = await req({ p: `/api/edits/${ID}/music`, headers: { 'Content-Type': `multipart/form-data; boundary=${B}`, 'Content-Length': String(mp.length) }, body: mp });
check(r.code === 415, `tải nhạc đuôi .exe → 415 (${r.code})`);
const bad = Buffer.from(`--${B}\r\nContent-Disposition: form-data; name="music"; filename="x.mp3"\r\n\r\nkhong phai mp3\r\n--${B}--\r\n`);
r = await req({ p: `/api/edits/${ID}/music`, headers: { 'Content-Type': `multipart/form-data; boundary=${B}`, 'Content-Length': String(bad.length) }, body: bad });
check(r.code === 422, `tải "mp3" hỏng → 422 và xoá file (${r.code})`);
}
}
console.log(fails ? `\n${fails} FAIL` : '\nTẤT CẢ PASS');
process.exit(fails ? 1 : 0);