Skip to content

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

12.8 KB
Raw Blame
#!/usr/bin/env node
// Kiểm tỉ lệ khung (9:16 · 16:9 · 4:3 · 3:4) cho cả 2 luồng, không gọi AI, không render:
//   node edit/test/ratio-check.mjs          → phần chạy tại chỗ (job tạm tự xoá, EDL dựng trong RAM)
//   node edit/test/ratio-check.mjs 4400     → thêm vài lệnh HTTP bị từ chối (tỉ lệ sai → 400, không tạo job)
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import http from 'node:http';
import { fileURLToPath } from 'node:url';
import { RATIOS, normRatio, dimsOf, safeArea, ratioOfDims, nearestRatio } from '../../engine/ratio.mjs';
import { createJob, validateBatch, jobDir, readJob } from '../../generator/jobs.mjs';
import { ratioRule } from '../../generator/prompt.mjs';
import { lintScene } from '../../engine/lib.mjs';
import { validateEdl, withFrame, OUT, SAFE, frameCy, frameOf } from '../edl.mjs';
import { layoutGraphics, baseSize } from '../graphics.mjs';
import { writeCaptionScene, captionTop } from '../captions-hf.mjs';
import { ManualSchema, applyPatch, manualView } from '../manual.mjs';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
let pass = 0; let fail = 0;
const ok = (c, name, extra = '') => { if (c) { pass++; console.log('PASS', name); } else { fail++; console.log('FAIL', name, extra); } };
const throws = (fn) => { try { fn(); return false; } catch { return true; } };

// ---- 1. bảng tỉ lệ ----
ok(JSON.stringify(Object.keys(RATIOS)) === '["9:16","16:9","4:3","3:4"]', 'đủ 4 tỉ lệ');
ok(dimsOf('9:16').width === 1080 && dimsOf('9:16').height === 1920 && dimsOf('16:9').width === 1920 && dimsOf('4:3').width === 1440 && dimsOf('3:4').height === 1440, 'kích thước đúng spec');
ok(Object.values(RATIOS).every((d) => Math.min(d.width, d.height) === 1080), 'cạnh ngắn luôn 1080 (luật cỡ chữ giữ nguyên)');
ok(normRatio(undefined) === '9:16' && normRatio('16x9') === '16:9' && normRatio('1440x1080') === '4:3' && normRatio(' 3/4 ') === '3:4', 'normRatio nhận nhiều cách viết');
ok(throws(() => normRatio('1:1')) && throws(() => normRatio('21:9')) && throws(() => normRatio('../x')), 'normRatio từ chối tỉ lệ lạ');
ok(ratioOfDims(1920, 1080) === '16:9' && ratioOfDims(1000, 1000) === null && nearestRatio(3840, 2160) === '16:9' && nearestRatio(720, 1280) === '9:16', 'ratioOfDims / nearestRatio');
for (const r of Object.keys(RATIOS)) { const s = safeArea(r); ok(s.x0 > 0 && s.x1 < 1 && s.y0 > 0 && s.y1 < 1 && s.x0 < s.x1 && s.y0 < s.y1, `vùng an toàn ${r} hợp lệ`); }

// ---- 2. dựng từ mẫu: job.json, prompt, lint ----
const made = [];
try {
  for (const r of Object.keys(RATIOS)) {
    const j = createJob({ templateId: '009', content: 'Kiểm tỉ lệ khung tự động, không chạy AI', durationS: 8, aspect: r, mode: 'manual', source: 'test' });
    made.push(j.id);
    const d = dimsOf(r);
    ok(j.aspect === r && j.width === d.width && j.height === d.height, `job ${r}: job.json có aspect + ${d.width}×${d.height}`);
    const p = fs.readFileSync(path.join(jobDir(j.id), 'PROMPT.md'), 'utf8');
    ok(p.includes(`(${d.width}×${d.height}`), `job ${r}: PROMPT ghi khung ${d.width}×${d.height}`);
    ok(r === '9:16' ? !p.includes('## Khung ') : p.includes(`## Khung ${r}`) && p.includes('Vùng an toàn') && p.includes('Cỡ chữ theo cạnh ngắn'), `job ${r}: ${r === '9:16' ? 'không thêm' : 'có'} khối luật khung chung`);
  }
  const j2 = createJob({ templateId: '009', content: 'Kiểm job cũ', durationS: 8, ratio: '16:9', mode: 'manual', source: 'test' });
  made.push(j2.id);
  ok(readJob(j2.id).aspect === '16:9', 'createJob nhận cả trường ratio (MCP/CLI)');
  ok(throws(() => createJob({ templateId: '009', content: 'x'.repeat(20), aspect: '1:1', mode: 'manual' })), 'createJob từ chối 1:1');
  ok(throws(() => validateBatch({ templateIds: ['009', '045'], content: 'x'.repeat(20), aspect: '5:4' })), 'lô nhiều mẫu: tỉ lệ sai → từ chối cả lô');
  ok(ratioRule('16:9').includes('xếp thành cột') && ratioRule('3:4').includes('×0.75') && ratioRule('9:16') === '', 'luật bố cục: ngang xếp cột, 3:4 nén dọc, 9:16 không thêm');
} finally { for (const id of made) fs.rmSync(path.join(ROOT, 'jobs', id), { recursive: true, force: true }); }

const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ratio-check-'));
try {
  const scene = (w, h, dw = w, dh = h) => `<!doctype html><html><head><meta charset="utf-8"><script src="./lib/vendor/gsap.min.js"></script><script src="./lib/runtime/scene.js"></script></head>
<body><div id="root" data-composition-id="main" data-start="0" data-duration="8" data-fps="30" data-width="${w}" data-height="${h}"></div>
<script>VideoScene.define({ duration: 8, fps: 30, width: ${dw}, height: ${dh}, render(t) {} });</script></body></html>`;
  fs.writeFileSync(path.join(tmp, 'index.html'), scene(1080, 1920));
  ok(lintScene(tmp, { expect: dimsOf('16:9') }).errors.some((e) => /Khung 1080×1920 sai/.test(e)), 'lint: job 16:9 mà cảnh 1080×1920 → lỗi');
  fs.writeFileSync(path.join(tmp, 'index.html'), scene(1920, 1080));
  ok(!lintScene(tmp, { expect: dimsOf('16:9') }).errors.some((e) => /Khung|không khớp/.test(e)), 'lint: cảnh 1920×1080 đúng job 16:9');
  fs.writeFileSync(path.join(tmp, 'index.html'), scene(1920, 1080, 1080, 1920));
  ok(lintScene(tmp, { expect: dimsOf('16:9') }).errors.some((e) => /VideoScene\.define width\/height/.test(e)), 'lint: define lệch #root → lỗi');
} finally { fs.rmSync(tmp, { recursive: true, force: true }); }

// ---- 3. edit: EDL, khung theo lượt chạy, phụ đề, đồ hoạ ----
const editDir = fs.readdirSync(path.join(ROOT, 'edits')).filter((d) => fs.existsSync(path.join(ROOT, 'edits', d, 'edl.json'))).sort().reverse()
  .find((d) => { try { const e = JSON.parse(fs.readFileSync(path.join(ROOT, 'edits', d, 'edl.json'), 'utf8')); return (e.output.ratio || '9:16') === '9:16' && (e.graphics || []).length; } catch { return false; } });
if (!editDir) console.log('(không có edit 9:16 có đồ hoạ để thử EDL: bỏ phần 3)');
else {
  const edl0 = JSON.parse(fs.readFileSync(path.join(ROOT, 'edits', editDir, 'edl.json'), 'utf8'));
  const old = JSON.parse(JSON.stringify(edl0)); delete old.output.ratio;
  ok(validateEdl(old, { checkFiles: false }).errors.every((e) => e.code !== 'schema'), 'EDL cũ (không có ratio) vẫn hợp lệ, hiểu là 9:16');
  ok(frameOf(old).ratio === '9:16', 'frameOf(EDL cũ) = 9:16');
  const bad = JSON.parse(JSON.stringify(edl0)); bad.output.ratio = '16:9';
  ok(validateEdl(bad, { checkFiles: false }).errors.some((e) => e.code === 'output'), 'EDL ratio 16:9 mà khung 1080×1920 → lỗi output');
  const wide = JSON.parse(JSON.stringify(edl0)); wide.output = { ...wide.output, ratio: '16:9', width: 1920, height: 1080 };
  wide.graphics[0].box = { ...wide.graphics[0].box, y: 1300 }; // chỗ hợp lệ trên khung dọc 1920, ngoài khung ngang 1080
  ok(validateEdl(wide, { checkFiles: false }).errors.some((e) => e.code === 'graphic' && /tràn vùng an toàn/.test(e.msg)), 'kiểm vùng an toàn theo khung của EDL (y 1300 tràn khung 16:9)');
  // khung theo lượt chạy, 2 lượt xen nhau không lẫn
  const seen = await Promise.all(['16:9', '3:4', '9:16', '4:3'].map((r) => withFrame(r, async () => { await new Promise((z) => setTimeout(z, 20 * Math.random())); return `${OUT.ratio}=${OUT.width}x${OUT.height}`; })));
  ok(seen.join(',') === '16:9=1920x1080,3:4=1080x1440,9:16=1080x1920,4:3=1440x1080', 'withFrame: 4 lượt async xen nhau giữ đúng khung riêng', seen.join(','));
  ok(OUT.width === 1080 && OUT.height === 1920 && Math.abs(SAFE.x0 - 120 / 1080) < 1e-9, 'ngoài withFrame: 9:16 như cũ');
  ok(withFrame('9:16', () => frameCy(0.70)) === 0.70 && withFrame('16:9', () => frameCy(0.70)) === 0.80 && withFrame('16:9', () => frameCy(0.5)) === 0.5, 'frameCy: 9:16 giữ, 16:9 phụ đề dưới xuống 0,80');
  // phụ đề: cảnh HyperFrames đúng cỡ khung
  const sd = fs.mkdtempSync(path.join(os.tmpdir(), 'ratio-cap-'));
  try {
    for (const r of ['16:9', '3:4']) {
      const d = dimsOf(r); const e = { ...JSON.parse(JSON.stringify(edl0)), output: { ...edl0.output, ratio: r, ...d }, graphics: [] };
      const sc = withFrame(e, () => writeCaptionScene(e, sd, { captions: true }));
      const html = fs.readFileSync(path.join(sd, 'index.html'), 'utf8');
      ok(html.includes(`data-width="${d.width}" data-height="${d.height}"`) && sc.box.x1 <= d.width && sc.box.cy < d.height && sc.box.yMax <= d.height, `phụ đề ${r}: cảnh ${d.width}×${d.height}, khối chữ trong khung (cy ${sc.box.cy}, đáy ${sc.box.yMax})`);
    }
  } finally { fs.rmSync(sd, { recursive: true, force: true }); }
  // đồ hoạ: khung ngang, mặt giữa khung → đặt cột cạnh mặt, không đè mặt, trong vùng an toàn
  await withFrame('16:9', async () => {
    const g = JSON.parse(JSON.stringify(edl0.graphics.find((x) => !x.data?.pin) || edl0.graphics[0]));
    g.box = null; g.face = null; g.squeeze = null;
    const keep = Object.assign(edl0.keep.map((k) => ({ ...k })), {});
    const face = [760, 160, 1160, 760];
    const faces = { step: 0.25, boxes: Array.from({ length: 4000 }, (_, i) => [i * 0.25, face]) };
    const list = [g];
    const w = layoutGraphics(list, keep, faces, captionTop(edl0.captions.style));
    const b = list[0]?.box;
    const hit = b && b.x < face[2] && b.x + b.w > face[0] && b.y < face[3] && b.y + b.h > face[1];
    const sa = safeArea('16:9');
    ok(b && !hit && b.x >= sa.x0 * 1920 - 1 && b.x + b.w <= sa.x1 * 1920 + 1 && b.y >= sa.y0 * 1080 - 1, `đồ hoạ ${g.type} 16:9: cột cạnh mặt, không đè, trong vùng an toàn`, JSON.stringify({ b, w, size: baseSize(g) }));
    ok(!list[0]?.squeeze, 'khung ngang không thu hình (squeeze)');
  });
  // Studio: bản vá ratio
  ok(ManualSchema.safeParse({ ratio: '4:3' }).success && !ManualSchema.safeParse({ ratio: '2:1' }).success, 'bản vá Studio nhận ratio 4:3, từ chối 2:1');
  const st = JSON.parse(fs.readFileSync(path.join(ROOT, 'edits', editDir, 'state.json'), 'utf8'));
  const ap = withFrame('3:4', () => applyPatch(edl0, st, { ratio: '3:4' }, { dir: path.join(ROOT, 'edits', editDir) }));
  ok(ap.relayout && ap.edl.output.ratio === '3:4' && ap.edl.output.width === 1080 && ap.edl.output.height === 1440 && ap.manual.ratio === '3:4' && ap.redo.base, 'applyPatch ratio: khung mới, cần đặt lại + render nền');
  ok(edl0.output.width === 1080 && edl0.output.height === 1920, 'applyPatch không sửa EDL gốc');
  ok(throws(() => withFrame('9:16', () => applyPatch(edl0, st, { ratio: '9:16' }, { dir: path.join(ROOT, 'edits', editDir) }))), 'đổi sang đúng tỉ lệ đang có → "không có gì khác"');
  const v = withFrame(edl0, () => manualView(edl0, st));
  ok(v.output?.ratio === '9:16' && v.output.width === 1080 && v.captions.looks.every((l) => Number.isFinite(l.css.cy0)), 'manualView có output.ratio + cy0 cho Studio');
}

// ---- 4. HTTP: tỉ lệ sai bị từ chối, không tạo gì ----
const port = Number(process.argv[2]);
function req(method, p, body) {
  return new Promise((resolve) => {
    const data = body ? JSON.stringify(body) : null;
    const r = http.request({ host: '127.0.0.1', port, path: p, method, headers: { Host: `127.0.0.1:${port}`, ...(data ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } : {}) } }, (res) => {
      let b = ''; res.setEncoding('utf8'); res.on('data', (c) => { b += c; }); res.on('end', () => resolve({ code: res.statusCode, body: b }));
    });
    r.on('error', (e) => resolve({ code: 0, body: e.message }));
    if (data) r.write(data); r.end();
  });
}
if (port) {
  const before = fs.readdirSync(path.join(ROOT, 'jobs')).length;
  const a = await req('POST', '/api/jobs', { templateId: '009', content: 'Kiểm tỉ lệ sai qua HTTP', aspect: '1:1', mode: 'manual' });
  ok(a.code === 400 && /Tỉ lệ khung không hỗ trợ/.test(a.body), 'POST /api/jobs tỉ lệ 1:1 → 400', a.body.slice(0, 120));
  const b = await req('POST', '/api/jobs/batch', { templateIds: ['009', '045'], content: 'Kiểm tỉ lệ sai qua HTTP', aspect: '21:9', mode: 'manual' });
  ok(b.code === 400, 'POST /api/jobs/batch tỉ lệ 21:9 → 400');
  ok(fs.readdirSync(path.join(ROOT, 'jobs')).length === before, 'không tạo job nào');
  const eds = fs.readdirSync(path.join(ROOT, 'edits')).length;
  const c = await req('POST', '/api/edits', { path: path.join(ROOT, 'test', 'VGA ngáo giá.mp4'), style: 'sach-gon', ratio: '2:3' });
  ok([400, 503].includes(c.code), 'POST /api/edits tỉ lệ 2:3 → 400', `${c.code} ${c.body.slice(0, 100)}`);
  ok(fs.readdirSync(path.join(ROOT, 'edits')).length === eds, 'không tạo edit nào');
  const d = await req('POST', '/api/edits/khong-co/manual', { ratio: '16:9' });
  ok(d.code === 404 || d.code === 415, 'bản vá ratio cho edit không có → 404');
}

console.log(`\n${pass} PASS, ${fail} FAIL`);
process.exit(fail ? 1 : 0);