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.
Chọn tỉ lệ khung 9:16 / 16:9 / 4:3 / 3:4 cho Dựng từ mẫu
Lumtek9299ce42eb03
diff --git a/cli.mjs b/cli.mjsindex 312c2d0..f0c5ca4 100644--- a/cli.mjs+++ b/cli.mjs@@ -1,6 +1,6 @@#!/usr/bin/env node// CLI cho người và AI agent.-// node cli.mjs make --template 009[,045,062] --content <file|chuỗi> [--duration 8] [--mode manual|agent|claude|api|auto] [--at 2026-11-28T07:00] [--json]+// node cli.mjs make --template 009[,045,062] --content <file|chuỗi> [--duration 8] [--ratio 9:16|16:9|4:3|3:4] [--mode manual|agent|claude|api|auto] [--at 2026-11-28T07:00] [--json]// node cli.mjs rewrite --template 009 --content <file|chuỗi> [--duration 30] [--engine auto|api|claude] [--json]// node cli.mjs run-due (chạy các job hẹn giờ đã tới giờ — cho Windows Task Scheduler)// node cli.mjs render <jobId> [--quality draft|looks|delivery] [--audio file]@@ -28,12 +28,13 @@ const audioOpts = () => ({ music: opt.music === true ? undefined : opt.music, vofunction usage() {console.log(`LumReels CLI- make --template <id>[,<id>…] --content <file|chuỗi> [--duration 8] [--mode manual|claude|api|auto] [--model auto|opus|sonnet|haiku] [--at <giờ>] [--json]+ make --template <id>[,<id>…] --content <file|chuỗi> [--duration 8] [--ratio 9:16] [--mode manual|claude|api|auto] [--model auto|opus|sonnet|haiku] [--at <giờ>] [--json]--template 009,045,062 : nhiều mẫu (tối đa ${MAX_BATCH}) → 1 job mỗi mẫu, cùng nội dung + tuỳ chọn, chạy lần lượt.Kiểm hết trước: 1 id sai / chưa có guidance thì không tạo job nào.--music <style|auto|none> --voice <tên giọng|vc-…|auto|none> --no-sfx : âm thanh (mặc định auto, auto, có sfx)vc-xxxxxxxx = giọng nhân bản của bạn (xem: node cli.mjs voices), chỉ đọc tiếng Việt--duration: 3 giây → 10 phút, số giây (90) hoặc phút:giây (1:30, 10:00). Mặc định 8.+ --ratio: tỉ lệ khung 9:16 (1080×1920, mặc định) · 16:9 (1920×1080) · 4:3 (1440×1080) · 3:4 (1080×1440)manual (mặc định): ghi jobs/<id>/PROMPT.md, job ở trạng thái waiting_agent. Agent viếtjobs/<id>/brief.json + scene/index.html rồi gọi: node cli.mjs render <id>claude: chạy Claude Code headless sinh cảnh, rồi tự render.@@ -62,9 +63,10 @@ function usage() {--items <ref,ref…> | --all-templates | --all-styles | --mine -o <file.lumpack>ref: 009 · sach-gon · tac-gia.ten-goi/slug (ghi rõ template:… / style:… nếu trùng)Gói lạ chạy ở chế độ khoá: AI chỉ đọc/ghi trong thư mục job. Mẫu gói dùng: make --template tac-gia.ten-goi/slug- edit <video> --style <id> [--music file] [--content "dặn thêm"] [--names "tên riêng, …"] [--target 45] [--draft] [--llm off] [--json]+ edit <video> --style <id> [--ratio 9:16|16:9|4:3|3:4] [--music file] [--content "dặn thêm"] [--names "tên riêng, …"] [--target 45] [--draft] [--llm off] [--json]dựng lại video tự quay theo thẻ kiểu edit (edit-styles/<id>.md) → edits/<id>/out.mp4- cắt ngập ngừng/nói lại (LLM), phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ, sfx, −14 LUFS.+ cắt ngập ngừng/nói lại (LLM), phụ đề tiếng Việt, zoom, reframe theo mặt về khung --ratio (mặc định 9:16;+ clip ngang + 16:9 thì giữ nguyên khung), nhạc tự hạ, sfx, −14 LUFS.--draft: phụ đề PIL vẽ thẳng (nhanh), mặc định phụ đề HyperFrames. Cài trước: node edit/setup.mjs--target 45: clip dài (5–20 phút) → LLM chọn đoạn hay nhất (hook … kết) thành short ≈ 45 sedit-revise <editId> "<lời>" | --file <f> sửa bằng lời ("bỏ 3 giây đầu", "zoom ít lại") rồi render lại, không phân tích lại@@ -217,7 +219,7 @@ try {const content = readContent(String(opt.content));const mode = opt.mode || process.env.VIDEOAI_CLI_MODE || 'manual';const ids = parseTemplateIds(String(opt.template));- const input = { content, durationS: opt.duration === true ? undefined : opt.duration, mode, model: typeof opt.model === 'string' ? opt.model : undefined, runAt: opt.at, source: 'cli',+ const input = { content, durationS: opt.duration === true ? undefined : opt.duration, aspect: typeof opt.ratio === 'string' ? opt.ratio : undefined, mode, model: typeof opt.model === 'string' ? opt.model : undefined, runAt: opt.at, source: 'cli',audio: (({ music, voice, sfx }) => ({ music: music ?? 'auto', voice: voice ?? 'auto', sfx: sfx ?? true }))(audioOpts()) };// 1 mẫu: như cũ. Nhiều mẫu: kiểm cả lô rồi tạo hết, sau đó chạy lần lượt từng job.const jobs = ids.length > 1 ? createJobs({ ...input, templateIds: ids }) : [createJob({ ...input, templateId: ids[0] || String(opt.template) })];@@ -262,7 +264,7 @@ try {}if (cmd === 'edit') {if (!pos[0]) { usage(); process.exit(2); }- const job = await E.createEdit({ video: pos[0], style: typeof opt.style === 'string' ? opt.style : 'sach-gon', music: typeof opt.music === 'string' ? opt.music : undefined,+ const job = await E.createEdit({ video: pos[0], style: typeof opt.style === 'string' ? opt.style : 'sach-gon', ratio: typeof opt.ratio === 'string' ? opt.ratio : undefined, music: typeof opt.music === 'string' ? opt.music : undefined,content: typeof opt.content === 'string' ? readContent(opt.content) : undefined, names: typeof opt.names === 'string' ? opt.names : undefined,draft: !!opt.draft, llm: opt.llm === 'off' ? 'off' : 'on', target: opt.target === undefined || opt.target === true ? undefined : opt.target });r = await E.runEditJob(job.id, { log });diff --git a/engine/fontcheck.mjs b/engine/fontcheck.mjsindex 8232f40..de7bfa3 100644--- a/engine/fontcheck.mjs+++ b/engine/fontcheck.mjs@@ -59,7 +59,14 @@ export async function fontCheck(sceneDir, { log = () => {}, times, readOnly = faconst errors = [];try {const page = await browser.newPage();- await page.setViewport({ width: 1080, height: 1920 });+ // cỡ khung theo #root của cảnh (9:16 1080×1920, 16:9 1920×1080, 4:3 1440×1080, 3:4 1080×1440)+ let vw = 1080; let vh = 1920;+ try {+ const tag = (fs.readFileSync(path.join(sceneDir, 'index.html'), 'utf8').match(/<div[^>]*id=["']root["'][^>]*>/i) || [''])[0];+ const w = Number((tag.match(/data-width=["'](\d+)/) || [])[1]); const h = Number((tag.match(/data-height=["'](\d+)/) || [])[1]);+ if (w >= 200 && h >= 200 && w <= 4096 && h <= 4096) { vw = w; vh = h; }+ } catch { /* giữ 9:16 */ }+ await page.setViewport({ width: vw, height: vh });page.on('pageerror', (e) => errors.push(String(e.message || e).slice(0, 200)));// Shader GLSL không biên dịch: Three.js chỉ in console.error, cảnh vẫn chạy nhưng mất hiệu ứng (AUTHORING §10.10).let shaderErrs = 0;diff --git a/engine/lib.mjs b/engine/lib.mjsindex fd35928..f0db85f 100644--- a/engine/lib.mjs+++ b/engine/lib.mjs@@ -84,7 +84,8 @@ function badFetches(html) {}/** Kiểm nhanh index.html theo AUTHORING.md. Trả {errors, warnings, meta}. restricted: thêm luật L4 của mẫu chạy khoá. */-export function lintScene(sceneDir, { restricted = false } = {}) {+/** expect: {width, height} của job (tỉ lệ khung đã chọn) → #root phải đúng cỡ đó. */+export function lintScene(sceneDir, { restricted = false, expect = null } = {}) {const errors = [];const warnings = [];const file = path.join(sceneDir, 'index.html');@@ -109,6 +110,13 @@ export function lintScene(sceneDir, { restricted = false } = {}) {if (!(meta.duration > 0)) errors.push('#root thiếu data-duration (giây).');if (!meta.width || !meta.height) errors.push('#root thiếu data-width / data-height.');if (!rootTag[0].includes('data-composition-id')) errors.push('#root thiếu data-composition-id="main".');+ if (expect && meta.width && meta.height && (meta.width !== expect.width || meta.height !== expect.height)) {+ errors.push(`Khung ${meta.width}×${meta.height} sai: job này chọn khung ${expect.width}×${expect.height}. Sửa data-width/data-height của #root, kích thước html/body/#root và width/height trong VideoScene.define.`);+ }+ const def = html.match(/VideoScene\.define\s*\(\s*\{[^]*?\bwidth\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)/);+ if (def && meta.width && meta.height && (Number(def[1]) !== meta.width || Number(def[2]) !== meta.height)) {+ errors.push(`VideoScene.define width/height (${def[1]}×${def[2]}) không khớp #root (${meta.width}×${meta.height}).`);+ }}if (restricted) {for (const [re, name] of RESTRICTED_PATTERNS) if (re.test(html)) errors.push(`Cảnh chạy khoá không được dùng ${name} (chỉ dùng ./lib, không gọi mạng, không mở trang khác).`);@@ -159,7 +167,7 @@ export function lintFonts(html) {warnings.push('Có ký hiệu "₫": nhiều font vẽ sai hoặc lệch dòng → viết "đ" (vd 3.000.000đ) hoặc "VNĐ" (AUTHORING §5).');}for (const m of html.matchAll(/font-size\s*:\s*(\d+(?:\.\d+)?)px/g)) {- if (Number(m[1]) < 28) { warnings.push(`Có font-size ${m[1]}px < 28px: chữ quá nhỏ trên khung 1080 (tối thiểu 28px, chữ chính ≥ 40px).`); break; }+ if (Number(m[1]) < 28) { warnings.push(`Có font-size ${m[1]}px < 28px: chữ quá nhỏ trên cạnh ngắn 1080 (tối thiểu 28px, chữ chính ≥ 40px).`); break; }}if (/-webkit-text-stroke/.test(html) && !/paint-order\s*:\s*stroke/.test(html)) {warnings.push('Có -webkit-text-stroke mà không có paint-order: stroke fill → viền ăn vào trong nét chữ. Thêm paint-order: stroke fill (AUTHORING §5).');diff --git a/engine/preview.mjs b/engine/preview.mjsindex b103b2b..44d522a 100644--- a/engine/preview.mjs+++ b/engine/preview.mjs@@ -1,7 +1,9 @@#!/usr/bin/env node// node engine/preview.mjs <sceneDir> [-o preview.jpg] → lưới 4x4 = 16 khung cách đều duration/16-// (8s → 0,0s 0,5s … 7,5s), cùng dạng templates/ref/<id>/sheet.jpg (1440x2560)-// node engine/preview.mjs <sceneDir> --frame 3.5 [-o khung.jpg] → 1 khung cỡ đầy đủ 1080x1920 để soát chữ+// (8s → 0,0s 0,5s … 7,5s); mỗi ô = 1/3 khung (9:16 → lưới 1440x2560,+// cùng dạng templates/ref/<id>/sheet.jpg; 16:9 → 2560x1440 …)+// node engine/preview.mjs <sceneDir> --frame 3.5 [-o khung.jpg] → 1 khung cỡ đầy đủ (theo #root) để soát chữ+// Cảnh nằm trong thư mục job (jobs/<id>/scene) → đọc ../job.json: #root phải đúng khung job đã chọn (tỉ lệ).// Luôn chạy kèm kiểm font (fontcheck.mjs): dòng FONT_FALLBACK / FONT_OUTSIDE / FONT_WEIGHT / FONT_DIGITS là cảnh báo.// Tắt kiểm font: VIDEOAI_FONTCHECK=0// Khoá (engine/sandbox.mjs): có LUMREELS_JAIL thì thư mục cảnh + file ra phải nằm trong jail (sai → thoát mã 2);@@ -12,17 +14,18 @@ import { fileURLToPath } from 'node:url';import { syncLib, lintScene, runHF, run, parseArgs } from './lib.mjs';import { fontCheck } from './fontcheck.mjs';import { assertJail, withCsp, offlineEnv, lockEngine, JailError } from './sandbox.mjs';+import { dimsOf } from './ratio.mjs';const fontCheckOn = () => process.env.VIDEOAI_FONTCHECK !== '0';-export async function preview(sceneDir, outFile, log = console.log, { frame, restricted = !!process.env.LUMREELS_JAIL } = {}) {+export async function preview(sceneDir, outFile, log = console.log, { frame, restricted = !!process.env.LUMREELS_JAIL, expect = null } = {}) {sceneDir = path.resolve(sceneDir);const single = frame !== undefined && frame !== null && frame !== true;outFile = path.resolve(outFile || path.join(sceneDir, single ? `frame-${frame}s.jpg` : 'preview.jpg'));assertJail([sceneDir, outFile]);if (!fs.existsSync(path.join(sceneDir, 'index.html'))) return { ok: false, errors: [`Không thấy ${path.join(sceneDir, 'index.html')}`] };syncLib(sceneDir);- const lint = lintScene(sceneDir, { restricted });+ const lint = lintScene(sceneDir, { restricted, expect });const lock = lockEngine(restricted);for (const w of lint.warnings) log('CẢNH BÁO: ' + w);if (lint.errors.length) {@@ -47,12 +50,13 @@ export async function preview(sceneDir, outFile, log = console.log, { frame, resif (single) {const f = await run('ffmpeg', ['-y', '-v', 'error', '-i', path.join(shotDir, pngs[0]), '-frames:v', '1', '-q:v', '2', outFile]);if (f.code !== 0 || !fs.existsSync(outFile)) return { ok: false, errors: ['ffmpeg lỗi: ' + f.out.slice(-500)] };- log(`khung ${times[0]}s: ${outFile} (1080x1920)`);+ log(`khung ${times[0]}s: ${outFile} (${lint.meta.width}x${lint.meta.height})`);return { ok: true, file: outFile };}const inputs = pngs.slice(0, 16).flatMap((f) => ['-i', path.join(shotDir, f)]);let fcg = '';- for (let i = 0; i < 16; i++) fcg += `[${i}:v]scale=360:640[s${i}];`;+ const tw = Math.round(lint.meta.width / 3 / 2) * 2; const th = Math.round(lint.meta.height / 3 / 2) * 2; // ô = 1/3 khung (9:16 → 360×640)+ for (let i = 0; i < 16; i++) fcg += `[${i}:v]scale=${tw}:${th}[s${i}];`;for (let row = 0; row < 4; row++) fcg += `${[0, 1, 2, 3].map((c) => `[s${row * 4 + c}]`).join('')}hstack=inputs=4[r${row}];`;fcg += '[r0][r1][r2][r3]vstack=inputs=4[out]';const f = await run('ffmpeg', ['-y', '-v', 'error', ...inputs, '-filter_complex', fcg, '-map', '[out]', '-frames:v', '1', '-q:v', '3', outFile]);@@ -66,7 +70,10 @@ if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {if (!pos[0]) { console.error('Dùng: node engine/preview.mjs <sceneDir> [-o preview.jpg] [--frame <giây>]'); process.exit(2); }const t0 = Date.now();let res;- try { res = await preview(pos[0], opt.o || opt.out, console.log, { frame: opt.frame }); } catch (e) {+ // cảnh của 1 job: khung phải đúng tỉ lệ job đã chọn (jobs/<id>/job.json, trường aspect)+ let expect = null;+ try { const j = JSON.parse(fs.readFileSync(path.join(path.resolve(pos[0]), '..', 'job.json'), 'utf8')); if (j && j.aspect) expect = dimsOf(j.aspect); } catch { /* không phải thư mục job */ }+ try { res = await preview(pos[0], opt.o || opt.out, console.log, { frame: opt.frame, expect }); } catch (e) {if (e instanceof JailError) { console.error('LỖI: ' + e.message); process.exit(2); }throw e;}diff --git a/engine/ratio.mjs b/engine/ratio.mjsnew file mode 100644index 0000000..f3d580d--- /dev/null+++ b/engine/ratio.mjs@@ -0,0 +1,49 @@+// Tỉ lệ khung dùng chung cho cả 2 luồng (dựng từ mẫu + edit video). Cạnh ngắn luôn 1080 px nên luật cỡ chữ+// "tối thiểu 28px / chữ chính ≥ 40px trên khung 1080" giữ nguyên cho mọi tỉ lệ.+// 9:16 = 1080×1920 (Reels/Shorts/TikTok, mặc định) · 16:9 = 1920×1080 (YouTube) · 4:3 = 1440×1080 · 3:4 = 1080×1440 (feed)+export const RATIOS = {+ '9:16': { width: 1080, height: 1920 },+ '16:9': { width: 1920, height: 1080 },+ '4:3': { width: 1440, height: 1080 },+ '3:4': { width: 1080, height: 1440 },+};+export const RATIO_IDS = Object.keys(RATIOS);+export const DEFAULT_RATIO = '9:16';++/** "16:9" | "16x9" | "16/9" | "1920x1080" | null → mã tỉ lệ chuẩn; trống → 9:16; lạ → throw. */+export function normRatio(v) {+ if (v === undefined || v === null || v === '') return DEFAULT_RATIO;+ const s = String(v).trim().toLowerCase().replace(/\s+/g, '').replace(/[x×/]/, ':');+ if (RATIOS[s]) return s;+ const m = /^(\d{3,4}):(\d{3,4})$/.exec(s);+ if (m) { const r = ratioOfDims(Number(m[1]), Number(m[2])); if (r) return r; }+ throw new Error(`Tỉ lệ khung không hỗ trợ: "${v}" (chọn ${RATIO_IDS.join(', ')})`);+}+export const isRatio = (v) => Object.prototype.hasOwnProperty.call(RATIOS, v);+/** {width, height} của tỉ lệ. */+export function dimsOf(r) { return { ...RATIOS[isRatio(r) ? r : DEFAULT_RATIO] }; }+/** Kích thước đúng 1 tỉ lệ → mã; không khớp → null. */+export function ratioOfDims(w, h) {+ for (const [id, d] of Object.entries(RATIOS)) if (d.width === Number(w) && d.height === Number(h)) return id;+ return null;+}+/** Tỉ lệ gần nhất với khung w×h bất kỳ (clip nguồn). */+export function nearestRatio(w, h) {+ const a = w / h;+ let best = DEFAULT_RATIO; let bd = Infinity;+ for (const [id, d] of Object.entries(RATIOS)) { const x = Math.abs(Math.log(a / (d.width / d.height))); if (x < bd) { bd = x; best = id; } }+ return best;+}+export const isLandscape = (r) => { const d = dimsOf(r); return d.width > d.height; };+/**+ * Vùng an toàn (phần của khung) để đặt chữ/đồ hoạ. 9:16 giữ như cũ (né nút của Reels/Shorts/TikTok: 120..960 px+ * ngang, 10%..80% dọc). Khung khác không có lớp nút đè lên → lề đều ~6% ngang, 7% trên, dưới chừa chỗ phụ đề.+ */+export function safeArea(r) {+ switch (isRatio(r) ? r : DEFAULT_RATIO) {+ case '16:9': return { x0: 0.06, x1: 0.94, y0: 0.07, y1: 0.9 };+ case '4:3': return { x0: 0.06, x1: 0.94, y0: 0.07, y1: 0.9 };+ case '3:4': return { x0: 0.07, x1: 0.93, y0: 0.07, y1: 0.86 };+ default: return { x0: 120 / 1080, x1: 960 / 1080, y0: 0.10, y1: 0.80 };+ }+}diff --git a/engine/render.mjs b/engine/render.mjsindex 85e0663..20e4edf 100644--- a/engine/render.mjs+++ b/engine/render.mjs@@ -1,6 +1,6 @@#!/usr/bin/env node// node engine/render.mjs <sceneDir> -o out.mp4 [--audio nhac.mp3] [--quality draft|looks|delivery]-// MP4 H.264 1080x1920 30fps qua HyperFrames. --audio: ghép 1 file âm thanh (giọng đọc/nhạc) sau khi render hình.+// MP4 H.264 30fps qua HyperFrames, cỡ theo #root của cảnh (1080x1920 hoặc khung khác: engine/ratio.mjs). --audio: ghép 1 file âm thanh (giọng đọc/nhạc) sau khi render hình.// Có <sceneDir>/audio.json thì tự trộn nhạc + sfx + lời (engine/audio/) và ghép; bản không tiếng giữ ở out.silent.mp4.// Khoá như preview.mjs: LUMREELS_JAIL (thoát mã 2 nếu cảnh / file ra / --audio ngoài jail), CSP, Chromium không mạng.import fs from 'node:fs';@@ -12,13 +12,13 @@ import { loadAudioSpec, addAudio } from './audio/mix.mjs';import { applyAudioPrefs } from './audio/prefs.mjs';import { assertJail, withCsp, offlineEnv, lockEngine, JailError } from './sandbox.mjs';-export async function render(sceneDir, outFile, { audio, audioPrefs, quality = 'looks', log = console.log, restricted = !!process.env.LUMREELS_JAIL } = {}) {+export async function render(sceneDir, outFile, { audio, audioPrefs, quality = 'looks', log = console.log, restricted = !!process.env.LUMREELS_JAIL, expect = null } = {}) {sceneDir = path.resolve(sceneDir);outFile = path.resolve(outFile || path.join(sceneDir, 'out.mp4'));assertJail([sceneDir, outFile, audio && path.resolve(audio)]);if (!fs.existsSync(path.join(sceneDir, 'index.html'))) return { ok: false, errors: [`Không thấy ${path.join(sceneDir, 'index.html')}`] };syncLib(sceneDir);- const lint = lintScene(sceneDir, { restricted });+ const lint = lintScene(sceneDir, { restricted, expect });const lock = lockEngine(restricted);for (const w of lint.warnings) log('CẢNH BÁO: ' + w);if (lint.errors.length) {@@ -26,7 +26,7 @@ export async function render(sceneDir, outFile, { audio, audioPrefs, quality = 'return { ok: false, errors: lint.errors };}const { width, height } = lint.meta;- if (width !== 1080 || height !== 1920) log(`CẢNH BÁO: kích thước ${width}x${height}, mặc định là 1080x1920`);+ if (!expect && (width !== 1080 || height !== 1920)) log(`kích thước ${width}x${height} (không phải 9:16 mặc định)`);// scene/audio.json (nhạc + sfx + lời tự tổng hợp) → render hình ra out.silent.mp4 rồi trộn + ghép vào out.mp4.// --audio file (ghép thẳng 1 file) được ưu tiên hơn audio.json.let audioSpec = null;diff --git a/engine/runtime/scene.js b/engine/runtime/scene.jsindex 18fa7fd..4149470 100644--- a/engine/runtime/scene.js+++ b/engine/runtime/scene.js@@ -148,12 +148,12 @@if (!text) return;var fam = firstFamily(cs.fontFamily);var base = cs.fontStyle + ' ' + cs.fontWeight + ' 100px ';- // Cỡ chữ thật trên khung 1080 (tính cả scale của transform): < 28px khó đọc trên điện thoại.+ // Cỡ chữ thật trên khung (cạnh ngắn luôn 1080, tính cả scale của transform): < 28px khó đọc trên điện thoại.var fs = parseFloat(cs.fontSize) || 0;var r = el.getBoundingClientRect();var k = el.offsetHeight ? r.height / el.offsetHeight : 1;var eff = fs * (k > 0 && isFinite(k) ? k : 1);- if (eff > 0 && eff < 28 && r.width > 0 && r.bottom > 0 && r.top < 1920) {+ if (eff > 0 && eff < 28 && r.width > 0 && r.bottom > 0 && r.top < (window.innerHeight || 1920)) {issues.push({ kind: 'FONT_SMALL', text: text.slice(0, 40), font: fam, weight: cs.fontWeight, why: 'cỡ chữ ~' + Math.round(eff) + 'px < 28px, khó đọc trên điện thoại' });}if (text.indexOf('₫') >= 0) {diff --git a/generator/jobs.mjs b/generator/jobs.mjsindex 64cc99d..c3aa7e1 100644--- a/generator/jobs.mjs+++ b/generator/jobs.mjs@@ -14,6 +14,7 @@ import { lintScene, syncLib } from '../engine/lib.mjs';import { normalizeAudioPrefs, styleFromGuidance } from '../engine/audio/prefs.mjs';import { isRestrictedSource } from '../engine/sandbox.mjs';import { resolveTemplate, readGuidance } from '../packs/registry.mjs';+import { normRatio, dimsOf } from '../engine/ratio.mjs';export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));export const JOBS = path.join(ROOT, 'jobs');@@ -118,7 +119,7 @@ export function fmtDuration(s) {return s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;}-/** Tạo job. input = {templateId, content, durationS=8, aspect='9:16', mode, runAt?, source?} */+/** Tạo job. input = {templateId, content, durationS=8, aspect='9:16' (| ratio: 9:16 · 16:9 · 4:3 · 3:4), mode, runAt?, source?} */export function createJob(input) {const raw = String(input.templateId || '').trim();const t = resolveTemplate(raw);@@ -130,8 +131,8 @@ export function createJob(input) {if (!content) throw new Error('Thiếu nội dung');if (content.length > 4000) throw new Error('Nội dung quá dài (tối đa 4000 ký tự)');const durationS = parseDuration(input.durationS);- const aspect = input.aspect || '9:16';- if (aspect !== '9:16') throw new Error('Hiện chỉ hỗ trợ 9:16 (1080x1920)');+ const aspect = normRatio(input.aspect ?? input.ratio);+ const { width, height } = dimsOf(aspect);let mode = input.mode === 'agent' ? 'manual' : (input.mode || 'manual');if (!MODES.includes(mode)) throw new Error(`Chế độ không hợp lệ: ${mode} (auto|api|claude|manual|agent)`);const runAt = parseRunAt(input.runAt);@@ -148,13 +149,13 @@ export function createJob(input) {if (hasRef) fs.copyFileSync(sheet, path.join(dir, 'ref-sheet.jpg'));const job = {id, templateId, templateTitle: tpl.name, templateSource: t.source, ...(t.packId ? { packId: t.packId } : {}), restricted: isRestrictedSource(t.source),- content, durationS, aspect, mode, hasRef, audio, model,+ content, durationS, aspect, width, height, mode, hasRef, audio, model,status: runAt && new Date(runAt) > new Date() ? 'scheduled' : 'queued',runAt, source: input.source || 'api', createdAt: new Date().toISOString(),};fs.writeFileSync(path.join(dir, 'PROMPT.md'), buildPrompt(job));writeJob(job);- logTo(job)(`tạo job: mẫu ${templateId} "${tpl.name}", ${durationS}s, chế độ ${mode}, model ${model.alias} (${model.why})${runAt ? ', hẹn ' + runAt : ''} (từ ${job.source})`);+ logTo(job)(`tạo job: mẫu ${templateId} "${tpl.name}", ${durationS}s, khung ${aspect} (${width}×${height}), chế độ ${mode}, model ${model.alias} (${model.why})${runAt ? ', hẹn ' + runAt : ''} (từ ${job.source})`);return job;}@@ -195,7 +196,7 @@ export function validateBatch(input) {if (!content) throw new Error('Thiếu nội dung');if (content.length > 4000) throw new Error('Nội dung quá dài (tối đa 4000 ký tự)');parseDuration(input.durationS);- if ((input.aspect || '9:16') !== '9:16') throw new Error('Hiện chỉ hỗ trợ 9:16 (1080x1920)');+ normRatio(input.aspect ?? input.ratio);const mode = input.mode === 'agent' ? 'manual' : (input.mode || 'manual');if (!MODES.includes(mode)) throw new Error(`Chế độ không hợp lệ: ${mode} (auto|api|claude|manual|agent)`);parseRunAt(input.runAt);@@ -210,6 +211,9 @@ export function createJobs(input) {return ids.map((templateId) => createJob({ ...common, templateId }));}+/** Kích thước khung của job (job cũ không có aspect → 9:16). */+export function jobDims(job) { return dimsOf(job?.aspect || '9:16'); }+/** Job có chạy khoá không (L1–L4): mẫu không phải gốc luôn khoá; mẫu gốc theo cờ LUMREELS_RESTRICT (tính lúc chạy). */export function jobRestricted(job) {return isRestrictedSource(job?.templateSource || 'builtin');@@ -309,7 +313,7 @@ export function submitScene(id, html, brief) {const prev = fs.existsSync(file) ? fs.readFileSync(file) : null;fs.writeFileSync(file, html);syncLib(sceneDir);- const lint = lintScene(sceneDir, { restricted: jobRestricted(job) });+ const lint = lintScene(sceneDir, { restricted: jobRestricted(job), expect: jobDims(job) });if (lint.errors.length) {if (prev) fs.writeFileSync(file, prev); else fs.rmSync(file);return { ok: false, errors: lint.errors, warnings: lint.warnings };@@ -328,7 +332,7 @@ export async function previewJob(id) {if (!job) throw new Error('Không thấy job ' + id);const dir = jobDir(id);if (!fs.existsSync(path.join(dir, 'scene', 'index.html'))) return { ok: false, errors: ['chưa có scene/index.html'] };- return preview(path.join(dir, 'scene'), path.join(dir, 'preview.jpg'), logTo(job), { restricted: jobRestricted(job) });+ return preview(path.join(dir, 'scene'), path.join(dir, 'preview.jpg'), logTo(job), { restricted: jobRestricted(job), expect: jobDims(job) });}/** Preview + render một job đã có scene/index.html. */@@ -342,7 +346,7 @@ export async function renderJob(id, { quality = 'looks', audio, claimed = falseif (!fs.existsSync(path.join(dir, 'scene', 'index.html'))) return setStatus(job, 'error', { error: 'chưa có scene/index.html' });const restricted = jobRestricted(job);job = setStatus(job, 'previewing');- const pv = await preview(path.join(dir, 'scene'), path.join(dir, 'preview.jpg'), log, { restricted });+ const pv = await preview(path.join(dir, 'scene'), path.join(dir, 'preview.jpg'), log, { restricted, expect: jobDims(job) });if (!pv.ok) return setStatus(job, 'error', { error: pv.errors.join('; ') });job = setStatus(job, 'rendering');// job.audio: chuỗi = file âm thanh ghép thẳng (cũ); object = tuỳ chọn {music, voice, sfx} áp lên scene/audio.json@@ -350,7 +354,7 @@ export async function renderJob(id, { quality = 'looks', audio, claimed = false// gói đã gỡ: không đọc được guidance nữa → bỏ fallbackStyle (cảnh + PROMPT.md đã có sẵn trong job)const g = readGuidance(job.templateId);const audioPrefs = job.audio && typeof job.audio === 'object' ? { ...job.audio, ...(g ? { fallbackStyle: styleFromGuidance(g) } : {}) } : undefined;- const rr = await render(path.join(dir, 'scene'), path.join(dir, 'out.mp4'), { quality, audio: audioFile, audioPrefs, log, restricted });+ const rr = await render(path.join(dir, 'scene'), path.join(dir, 'out.mp4'), { quality, audio: audioFile, audioPrefs, log, restricted, expect: jobDims(job) });if (!rr.ok) return setStatus(job, 'error', { error: rr.errors.join('; ') });const v = rr.probe?.streams?.find((s) => s.width) || {};const output = { mp4: 'out.mp4', preview: 'preview.jpg', width: v.width, height: v.height, fps: v.r_frame_rate, duration: Number(rr.probe?.format?.duration) };diff --git a/generator/prompt.mjs b/generator/prompt.mjsindex 24745e4..2238020 100644--- a/generator/prompt.mjs+++ b/generator/prompt.mjs@@ -6,6 +6,36 @@ import { detectLang, voiceLang, DEFAULT_VOICE_EN } from '../engine/audio/voice.mimport { isCloneVoice } from '../engine/audio/voice-store.mjs';import crypto from 'node:crypto';import { readGuidance, wrapUntrusted } from '../packs/registry.mjs';+import { normRatio, dimsOf, safeArea } from '../engine/ratio.mjs';++/**+ * Luật khung khi job KHÔNG phải 9:16: guidance (143 mẫu) và AUTHORING viết cho khung dọc 1080×1920 — không sửa từng file,+ * thay vào đó 1 khối luật chung: thay cỡ khung, đổi toạ độ, cỡ chữ theo cạnh ngắn, vùng an toàn, cách xếp lại bố cục.+ */+export function ratioRule(aspect) {+ const r = normRatio(aspect);+ if (r === '9:16') return '';+ const { width: W, height: H } = dimsOf(r);+ const sa = safeArea(r);+ const L = Math.round(sa.x0 * W); const T = Math.round(sa.y0 * H); const B = Math.round((1 - sa.y1) * H);+ const land = W > H;+ const layout = land ? `- **Xếp lại bố cục cho khung ngang** (guidance xếp mọi thứ chồng theo chiều dọc; khung này thấp ${H}px và rộng ${W}px):+ - Khối chồng dọc (tiêu đề trên → hình/chủ thể giữa → số/chữ dưới) → **xếp thành cột**: chủ thể/hình minh hoạ một bên (~45–55% bề ngang), chữ + số bên kia, canh giữa theo chiều dọc. Hoặc: tiêu đề chạy ngang trên cùng, bên dưới chia 2 cột.+ - Danh sách / thẻ / bước xếp dọc nhiều dòng → lưới 2–3 cột hoặc 1 hàng ngang; tối đa 3–4 dòng mỗi cột.+ - Biểu đồ cột/đường/thanh tiến độ: trải theo bề ngang, cao ≤ 55% khung; nhãn trục không dưới 28px.+ - Chủ thể tròn/vuông (đồng hồ, vòng, heo đất, mô hình 3D): giữ đúng tỉ lệ, KHÔNG kéo giãn theo bề ngang; cạnh lớn nhất ≤ 70% chiều cao khung. Three.js: \`camera.aspect = ${W}/${H}\`, renderer.setSize(${W}, ${H}); camera đặt sao cho chủ thể vẫn nằm trọn trong khung thấp.+ - Chuyển động trượt dọc dài (cuộn, rơi) → rút quãng đường theo chiều cao mới; có thể đổi thành trượt ngang nếu hợp chất mẫu.` : `- **Khung thấp hơn 9:16** (${H}px thay vì 1920): giữ bố cục dọc của guidance nhưng nén khoảng trống — mọi mốc y ×${(H / 1920).toFixed(2)}; khối cao (biểu đồ, danh sách) thu khoảng đệm trước, chưa đủ thì thu khối ≤ 15%; KHÔNG thu chữ dưới mức tối thiểu, bớt dòng phụ nếu chật.`;+ return `+## Khung ${r} = ${W}×${H} (guidance + AUTHORING viết cho khung dọc 1080×1920 — áp luật dưới, luật này thắng)+- **Cỡ khung**: mọi chỗ ghi 1080×1920 (khung mẫu HTML, \`<meta viewport>\`, html/body/#root, \`data-width\`/\`data-height\`, \`VideoScene.define({ width, height })\`, thuộc tính width/height của canvas, renderer WebGL) → **${W}×${H}**. Engine từ chối cảnh nếu #root sai cỡ.+- **Toạ độ px** trong guidance tính trên khung 1080 rộng × 1920 cao: vị trí ngang ×${(W / 1080).toFixed(3)}, vị trí dọc ×${(H / 1920).toFixed(3)}; với phần tử không được méo (chữ, hình tròn, ảnh, chủ thể) thì chỉ dời tâm, giữ nguyên cỡ.+- **Cỡ chữ theo cạnh ngắn**: cạnh ngắn vẫn là ${Math.min(W, H)}px nên cỡ chữ px của guidance giữ nguyên; chỉ thu khi khối chữ không vừa chỗ, không dưới 28px (chữ chính ≥ 40px, số/tiêu đề chính ≥ 72px). Dòng chữ dài thì xuống dòng hoặc rút gọn cho vừa vùng an toàn.+- **Vùng an toàn**: chữ và phần tử chính nằm trong lề trái/phải ≥ ${L}px, trên ≥ ${T}px, dưới ≥ ${B}px. Nền, hoạ tiết full-bleed phải phủ hết ${W}×${H} (tính lại số ô lưới/hạt/sọc theo cả W lẫn H, không để mép trống).+${layout}+- \`ref-sheet.jpg\` (nếu có) là khung dọc: chỉ lấy chất liệu, màu, kiểu chữ, nhịp; KHÔNG chép bố cục dọc của nó.+- **Tự kiểm thêm** (preview.jpg là lưới 4×4 khung ${W}×${H}): không chữ nào bị cắt mép hay tràn khung, không phần tử đè nhau, không vùng trống lớn (> 40% khung) kéo dài, chủ thể không bị méo.+`;+}const fmt = (s) => (s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`);const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));@@ -89,6 +119,7 @@ export function buildPrompt(job) {const guidance = full ? guidanceRaw : slimGuidance(guidanceRaw, job.durationS);const authoring = full ? authoringRaw : slimAuthoring(authoringRaw, guidanceRaw);const D = job.durationS;+ const { width: FW, height: FH } = dimsOf(normRatio(job.aspect));const scaleNote = D === 8? 'Thời lượng 8 giây: bám đúng bảng §6 Dòng thời gian của guidance.': `Thời lượng ${D} giây (guidance viết cho 8 giây): nếu ${D} < 8 thì co các mốc §6 theo tỉ lệ ${D}/8; nếu ${D} > 8 thì làm theo §10 "Khi nội dung dài hơn 8 giây".`;@@ -110,7 +141,7 @@ ${wrapUntrusted(guidance, crypto.randomBytes(8).toString('hex'), `GUIDANCE mẫureturn `# Việc: dựng 1 cảnh video từ mẫu ${job.templateId} "${job.templateTitle}"Mày là AI dựng cảnh. Thư mục làm việc hiện tại là thư mục job \`${job.id}\`.-Đầu ra: \`brief.json\`, \`scene/index.html\` (1080×1920, ${D}s, 30fps) và \`scene/audio.json\` (nhạc + tiếng động), cùng phong cách mẫu, nội dung của người dùng.+Đầu ra: \`brief.json\`, \`scene/index.html\` (${FW}×${FH}${FW !== 1080 || FH !== 1920 ? ` — khung ${job.aspect}, xem mục "Khung" bên dưới` : ''}, ${D}s, 30fps) và \`scene/audio.json\` (nhạc + tiếng động), cùng phong cách mẫu, nội dung của người dùng.## Nội dung người dùng (nguyên văn)"""@@ -142,7 +173,7 @@ ${guidanceBlock}- **Đúng kỹ thuật**: frontmatter \`technique\` của guidance có \`three\` hoặc \`webgl-shader\` thì PHẢI dựng phần đó bằng Three.js / shader WebGL thật (./lib/vendor/three.module.js), không hạ xuống 2D phẳng. Chỉ được đổi nếu ghi rõ lý do trong brief.json (trường \`technique_note\`).- Font: chỉ dùng font trong AUTHORING §4, theo bảng ánh xạ ở đó.- **Âm thanh (bắt buộc)**: ghi kèm \`scene/audio.json\` theo AUTHORING §9 — thiếu file này video ra không tiếng. Chọn \`music.style\` hợp §9 "Âm thanh" của guidance; 6–15 sfx cho 8 giây (video dài hơn thì tăng theo tỉ lệ) đặt \`t\` đúng các mốc chuyển động mày vừa viết trong \`render(t)\`; \`voice\` chỉ khi frontmatter guidance có \`narration: true\`, mỗi câu ngắn, đọc xong trước mốc câu sau. Hệ thống tự trộn và ghép lúc render.-${audioRule(job.audio, job.content)}+${audioRule(job.audio, job.content)}${ratioRule(job.aspect)}Chỉ được: đọc/ghi/sửa file TRONG thư mục job này (đường dẫn tương đối \`./…\`), chạy đúng lệnh preview ở bước 4 (đối số chỉ trỏ vào \`scene\` và file trong thư mục job). Không đọc file ngoài thư mục job, không cài gì, không gọi mạng.${longNote}${untrusted ? '' : `---diff --git a/mcp/server.mjs b/mcp/server.mjsindex 23acd31..c2c5b27 100644--- a/mcp/server.mjs+++ b/mcp/server.mjs@@ -137,13 +137,14 @@ server.registerTool('create_video', {model: z.enum(['auto', 'opus', 'sonnet', 'haiku']).optional().describe('Model viết cảnh (chế độ auto). auto = Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D.'),durationS: z.union([z.number().min(3).max(MAX_DURATION_S), z.string().regex(/^\s*\d{1,4}\s*s?\s*$|^\s*\d{1,2}:[0-5]\d\s*$/)]).optional().describe('Thời lượng: 3 giây → 10 phút; số giây (90) hoặc "phút:giây" ("1:30"). Mặc định 8. > 60s: chia nhiều cảnh, render lâu (8s video ≈ 20–60s render) và tốn token hơn.'),+ ratio: z.enum(['9:16', '16:9', '4:3', '3:4']).optional().describe('Tỉ lệ khung: 9:16 = 1080×1920 (mặc định, Reels/Shorts/TikTok), 16:9 = 1920×1080 (YouTube), 4:3 = 1440×1080, 3:4 = 1080×1440 (feed). Mẫu viết cho khung dọc; khung khác AI tự xếp lại bố cục.'),runAt: z.string().optional(),audio: audioSchema.optional().describe('Âm thanh. Mặc định {music:"auto", voice:"auto", sfx:true}: AI chọn nhạc/tiếng động theo mẫu, chỉ đọc lời khi mẫu có narration.'),},-}, async ({ templateId, templateIds, content, mode, model, durationS, runAt, audio }) => {+}, async ({ templateId, templateIds, content, mode, model, durationS, ratio, runAt, audio }) => {if (templateId && templateIds) return fail('Chỉ truyền 1 trong 2: templateId hoặc templateIds');if (!templateId && !templateIds) return fail('Thiếu templateId (1 mẫu) hoặc templateIds (nhiều mẫu)');- const common = { content, durationS, mode: mode === 'agent' ? 'manual' : 'auto', model, runAt, source: 'mcp', audio };+ const common = { content, durationS, aspect: ratio, mode: mode === 'agent' ? 'manual' : 'auto', model, runAt, source: 'mcp', audio };if (templateIds && templateIds.length > 1) {let jobs;try { jobs = createJobs({ ...common, templateIds }); } catch (e) { return fail(e.message); }@@ -217,7 +218,7 @@ server.registerTool('preview_job', {server.registerTool('render_job', {title: 'Render MP4',- description: 'Preview + render MP4 1080×1920 30fps (video 8 giây mất khoảng 20–60 giây; video dài tăng theo tỉ lệ), rồi chép ra OUTPUT_DIR nếu có. Chờ tối đa ~110 giây; lâu hơn thì trả trạng thái và mày gọi get_job.',+ description: 'Preview + render MP4 30fps theo khung của job (1080×1920 mặc định; 16:9/4:3/3:4 nếu tạo với ratio) (video 8 giây mất khoảng 20–60 giây; video dài tăng theo tỉ lệ), rồi chép ra OUTPUT_DIR nếu có. Chờ tối đa ~110 giây; lâu hơn thì trả trạng thái và mày gọi get_job.',inputSchema: { jobId: z.string().regex(/^[\w-]{1,80}$/) },}, async ({ jobId }) => {try {@@ -333,7 +334,7 @@ const editSummary = (id) => {server.registerTool('edit_video', {title: 'Dựng lại video tự quay (Edit video)',description: [- 'Dựng lại 1 video người dùng TỰ QUAY (nói trước máy, tiếng Việt) theo 1 kiểu edit: cắt ngập ngừng/nói lại (LLM), phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ khi nói, sfx, −14 LUFS → MP4 1080×1920.',+ 'Dựng lại 1 video người dùng TỰ QUAY (nói trước máy, tiếng Việt) theo 1 kiểu edit: cắt ngập ngừng/nói lại (LLM), phụ đề tiếng Việt, zoom, reframe theo mặt về khung ratio (9:16 mặc định, hoặc 16:9 / 4:3 / 3:4), nhạc tự hạ khi nói, sfx, −14 LUFS → MP4 (1080×1920 khi 9:16).','Chạy ở tiến trình nền (vài phút: video 35 giây ≈ 3–4 phút trên RTX 3070 Ti). Trả editId ngay; gọi get_edit để xem tiến độ và đường dẫn MP4.','Cần cài 1 lần: node edit/setup.mjs. style: ' + (() => { try { return editStyles().map((x) => `${x.id} (${x.name})`).join(', '); } catch { return 'sach-gon, phu-de-nay-mau'; } })() + '.',].join(' '),@@ -345,8 +346,9 @@ server.registerTool('edit_video', {names: z.array(z.string()).max(40).optional().describe('tên riêng/thuật ngữ viết đúng, để LLM sửa chữ máy nghe sai (vd ["Lumfin"])'),draft: z.boolean().optional().describe('true: phụ đề nháp PIL (nhanh hơn ~1 phút)'),target: z.number().int().min(15).max(180).optional().describe('clip dài (5–20 phút): số giây short muốn ra (vd 45); LLM chọn các đoạn hay nhất có hook và kết, rồi mới cắt ngập ngừng'),+ ratio: z.enum(['9:16', '16:9', '4:3', '3:4']).optional().describe('tỉ lệ khung bản ra: 9:16 = 1080×1920 (mặc định), 16:9 = 1920×1080, 4:3 = 1440×1080, 3:4 = 1080×1440. Reframe theo mặt; clip đã đúng khung thì không cắt.'),},-}, async ({ path: video, style, music, notes, names, draft, target }) => {+}, async ({ path: video, style, music, notes, names, draft, target, ratio }) => {try {const ready = editReady();if (!ready.ready) return fail(ready.note);@@ -359,7 +361,7 @@ server.registerTool('edit_video', {musicFile = f;} else musicFile = music;}- const job = await createEdit({ video, style, music: musicFile, content: notes, names, draft, target });+ const job = await createEdit({ video, style, ratio, music: musicFile, content: notes, names, draft, target });const p = spawn(process.execPath, [path.join(ROOT, 'cli.mjs'), 'edit-run', job.id], { cwd: ROOT, detached: true, stdio: 'ignore', windowsHide: true, env: process.env });p.unref();return { content: [json({ ...editSummary(job.id), note: 'Đang dựng ở tiến trình nền. Gọi get_edit sau 1–2 phút.' })] };diff --git a/server/public/app.js b/server/public/app.jsindex 7813ac6..3810d00 100644--- a/server/public/app.js+++ b/server/public/app.js@@ -49,6 +49,31 @@: b < 7200 ? `${Math.max(1, Math.round(a / 60))}–${Math.round(b / 60)} ${t('unit.min')}` : `${dec(a / 3600)}–${dec(b / 3600)} ${t('unit.hour')}`);const durS = () => parseDur($('#duration').value).s;+ // Tỉ lệ khung: 9:16 (mặc định) · 16:9 · 4:3 · 3:4 — cùng bảng với engine/ratio.mjs+ const RATIO_DIMS = { '9:16': [1080, 1920], '16:9': [1920, 1080], '4:3': [1440, 1080], '3:4': [1080, 1440] };+ let ratio = '9:16';+ try { const r = localStorage.getItem('lumreels.ratio'); if (RATIO_DIMS[r]) ratio = r; } catch { /* bỏ qua */ }+ function setRatio(r, focus) {+ if (!RATIO_DIMS[r]) return;+ ratio = r;+ try { localStorage.setItem('lumreels.ratio', r); } catch { /* bỏ qua */ }+ document.querySelectorAll('.ratio[data-ratio]').forEach((b) => { const on = b.dataset.ratio === r; b.classList.toggle('on', on); b.setAttribute('aria-checked', String(on)); b.tabIndex = on ? 0 : -1; if (on && focus) b.focus(); });+ paintRatio();+ }+ function paintRatio() {+ const [w, h] = RATIO_DIMS[ratio];+ $('#ratioSize').textContent = `${w}×${h}`;+ $('#ratioHint').textContent = t('ratio.hint.' + ratio.replace(':', 'x'));+ }+ document.querySelectorAll('.ratio[data-ratio]').forEach((b) => b.addEventListener('click', () => setRatio(b.dataset.ratio)));+ document.querySelector('.ratios').addEventListener('keydown', (e) => {+ const keys = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };+ if (!(e.key in keys)) return;+ e.preventDefault();+ const ids = Object.keys(RATIO_DIMS); const i = ids.indexOf(ratio);+ setRatio(ids[(i + keys[e.key] + ids.length) % ids.length], true);+ });+let templates = [];let templatesState = 'loading'; // loading | ok | error// Mẫu đang chọn (theo thứ tự bấm). Chế độ thường: tối đa 1. "Chọn nhiều mẫu": tối đa MAX_PICK, mỗi mẫu 1 job.@@ -342,7 +367,7 @@if (!picks.length) return;btn.disabled = true; btn.classList.add('busy'); btn.querySelector('span').textContent = t('go.sending');const batch = picks.length > 1;- const common = { content: $('#content').value, durationS: durS(), mode: $('#mode').value, model: $('#model').value, runAt: runAtValue(), audio: window.LumAudio?.value() };+ const common = { content: $('#content').value, durationS: durS(), aspect: ratio, mode: $('#mode').value, model: $('#model').value, runAt: runAtValue(), audio: window.LumAudio?.value() };try {const r = await fetch(batch ? '/api/jobs/batch' : '/api/jobs', {method: 'POST', headers: { 'Content-Type': 'application/json' },@@ -421,12 +446,13 @@: `<span>${esc(t(running ? 'job.building' : j.status === 'waiting_agent' ? 'job.waitScene' : 'job.noImage'))}</span>`;const last = (j.log || []).slice(-1)[0] || '';const out = j.output ? `${j.output.width}×${j.output.height} · ${j.output.fps} · ${Number(j.output.duration).toFixed(1)}s` : '';- return `<article class="job" id="job-${j.id}">- <div class="media">${media}</div>+ const ar = RATIO_DIMS[j.aspect] ? j.aspect : '9:16';+ return `<article class="job${ar !== '9:16' ? ' wide-' + ar.replace(':', 'x') : ''}" id="job-${j.id}">+ <div class="media" style="aspect-ratio:${ar.replace(':', ' / ')}">${media}</div><div><div class="head"><span class="st ${j.status} ${running ? 'run' : ''}">${esc(status(j.status))}</span><span class="tt"></span></div>- <div class="jid">${j.id} · ${fmtDur(j.durationS)} · ${esc(modeLabel(j.engine || j.mode) || j.mode)}${j.model && j.model.alias && (j.engine || j.mode) !== 'manual' ? ' · ' + esc(j.model.alias) : ''} ${out ? '· ' + out : ''}</div>+ <div class="jid">${j.id} · ${fmtDur(j.durationS)} · ${ar} · ${esc(modeLabel(j.engine || j.mode) || j.mode)}${j.model && j.model.alias && (j.engine || j.mode) !== 'manual' ? ' · ' + esc(j.model.alias) : ''} ${out ? '· ' + out : ''}</div>${j.status === 'scheduled' ? `<div class="cost">${esc(t('job.at', { t: fmtTime(j.runAt) }))}</div>` : ''}${j.usage ? `<div class="cost">${esc(t('job.api', { i: (j.usage.inputTokens / 1000).toFixed(1), o: (j.usage.outputTokens / 1000).toFixed(1), c: j.usage.costUSD.toFixed(3) }))}</div>` : ''}${j.output?.exported ? `<div class="cost">${esc(t('job.exported', { p: j.output.exported }))}</div>` : ''}@@ -562,6 +588,7 @@modeHint();modelHint();renderUpdate();+ paintRatio();if (rwView) rwView();if (viewing) $('#vDesc').textContent = viewerDesc(viewing);note(''); // báo nhẹ tự ẩn: bỏ luôn cho khỏi lẫn ngôn ngữ@@ -581,6 +608,7 @@});updateDur();+ setRatio(ratio);loadTemplates();loadJobs();})();diff --git a/server/public/i18n.js b/server/public/i18n.jsindex 69c9a1e..fb66dfc 100644--- a/server/public/i18n.js+++ b/server/public/i18n.js@@ -6,7 +6,7 @@const S = (n) => (n === 1 ? '' : 's');const vi = {'meta.title': 'LumReels — dựng video dọc từ mẫu',- 'top.tag': 'Chọn mẫu, dán nội dung, AI dựng cảnh, ra MP4 dọc 1080×1920.',+ 'top.tag': 'Chọn mẫu, dán nội dung, AI dựng cảnh, ra MP4 dọc 1080×1920, hoặc khung 16:9, 4:3, 3:4.','lang.group': 'Ngôn ngữ giao diện','lang.vi': 'Tiếng Việt (VI)','lang.en': 'Tiếng Anh (EN)',@@ -764,6 +764,20 @@'gfx.counter': 'Số đếm', 'gfx.bar_chart': 'Biểu đồ cột', 'gfx.compare': 'So sánh', 'gfx.spec_table': 'Bảng','gfx.checklist': 'Checklist', 'gfx.price_tag': 'Tem giá', 'gfx.sticker': 'Sticker', 'gfx.line_chart': 'Biểu đồ đường', 'gfx.title_card': 'Thẻ tiêu đề',+ // ---- tỉ lệ khung ----+ 'ratio.label': 'Khung hình',+ 'ratio.hint.9x16': 'Dọc: Reels, Shorts, TikTok. Mẫu viết cho khung này.',+ 'ratio.hint.16x9': 'Ngang: YouTube, màn hình máy tính. AI tự xếp lại bố cục (chia cột), nên xem trước khi đăng.',+ 'ratio.hint.4x3': 'Ngang gần vuông: slide, màn hình cũ. AI tự xếp lại bố cục, nên xem trước khi đăng.',+ 'ratio.hint.3x4': 'Dọc thấp: bài feed Facebook/Instagram. Bố cục mẫu nén lại theo chiều cao.',+ 'cr.ratioSame': 'Clip đã đúng khung này: giữ nguyên, không cắt.',+ 'cr.ratioHint.9x16': 'Dọc cho Reels, Shorts, TikTok. Clip ngang sẽ được cắt theo mặt người nói.',+ 'cr.ratioHint.16x9': 'Ngang cho YouTube. Clip dọc sẽ được cắt theo mặt (hình phóng to, kém nét hơn).',+ 'cr.ratioHint.4x3': 'Ngang gần vuông. Khung cắt đi theo mặt người nói.',+ 'cr.ratioHint.3x4': 'Dọc thấp cho bài feed. Khung cắt đi theo mặt người nói.',+ 'st.ratioAria': 'Khung hình (tỉ lệ bản ra)',+ 'st.ratioPending': 'Xem trước khung {r}: hình cắt giữa, mặt và đồ hoạ đặt lại khi xuất bản',+ 'st.ratioChanged': 'Đổi khung {r}. Bấm Xuất bản mới để dựng lại theo khung này.',// ---- nhật ký (log-panel.js) ----'log.btn': 'Nhật ký', 'log.btnErr': 'Xem lỗi', 'log.appBtn': 'Nhật ký app','log.title': 'Nhật ký', 'log.titleServer': 'Nhật ký app', 'log.subServer': 'Log server gần nhất (chỉ trong máy này)',@@ -794,7 +808,7 @@const en = {'meta.title': 'LumReels — vertical videos from templates',- 'top.tag': 'Pick a template, paste your text, AI builds the scenes. Out comes a 1080×1920 vertical MP4.',+ 'top.tag': 'Pick a template, paste your text, AI builds the scenes. Out comes a 1080×1920 vertical MP4, or 16:9, 4:3, 3:4.','lang.group': 'Interface language','lang.vi': 'Vietnamese (VI)','lang.en': 'English (EN)',@@ -1552,6 +1566,20 @@'gfx.counter': 'Counter', 'gfx.bar_chart': 'Bar chart', 'gfx.compare': 'Compare', 'gfx.spec_table': 'Table','gfx.checklist': 'Checklist', 'gfx.price_tag': 'Price tag', 'gfx.sticker': 'Sticker', 'gfx.line_chart': 'Line chart', 'gfx.title_card': 'Title card',+ // ---- aspect ratio ----+ 'ratio.label': 'Frame',+ 'ratio.hint.9x16': 'Vertical: Reels, Shorts, TikTok. Templates are written for this frame.',+ 'ratio.hint.16x9': 'Landscape: YouTube, desktop screens. The AI rearranges the layout (into columns); check it before posting.',+ 'ratio.hint.4x3': 'Near-square landscape: slides, older screens. The AI rearranges the layout; check it before posting.',+ 'ratio.hint.3x4': 'Short vertical: Facebook/Instagram feed posts. The template layout is squeezed to the height.',+ 'cr.ratioSame': 'The clip already has this frame: kept as is, no crop.',+ 'cr.ratioHint.9x16': 'Vertical for Reels, Shorts, TikTok. A landscape clip is cropped around the speaker.',+ 'cr.ratioHint.16x9': 'Landscape for YouTube. A vertical clip is cropped around the face (zoomed in, less sharp).',+ 'cr.ratioHint.4x3': 'Near-square landscape. The crop follows the speaker.',+ 'cr.ratioHint.3x4': 'Short vertical for feed posts. The crop follows the speaker.',+ 'st.ratioAria': 'Frame (output aspect ratio)',+ 'st.ratioPending': 'Previewing {r}: centre crop, face and graphics are placed when you publish',+ 'st.ratioChanged': 'Frame set to {r}. Hit Publish new to rebuild in this frame.',// ---- log panel ----'log.btn': 'Log', 'log.btnErr': 'See error', 'log.appBtn': 'App log','log.title': 'Log', 'log.titleServer': 'App log', 'log.subServer': 'Latest server log (this computer only)',diff --git a/server/public/index.html b/server/public/index.htmlindex 9b1beb4..12c36e7 100644--- a/server/public/index.html+++ b/server/public/index.html@@ -14,7 +14,7 @@<body><header class="top"><div class="brand"><span class="mark" aria-hidden="true"></span>LumReels</div>- <p class="tag" data-i18n="top.tag">Chọn mẫu, dán nội dung, AI dựng cảnh, ra MP4 dọc 1080×1920.</p>+ <p class="tag" data-i18n="top.tag">Chọn mẫu, dán nội dung, AI dựng cảnh, ra MP4 dọc 1080×1920, hoặc khung 16:9, 4:3, 3:4.</p><button type="button" class="ghost packs-open" id="packsOpen" data-packs-open><span data-i18n="pack.mineBtn">Gói của tôi</span></button><div class="lang-sw" role="group" aria-label="Ngôn ngữ giao diện" data-i18n-aria="lang.group"><button type="button" data-lang="vi" aria-pressed="true" aria-label="Tiếng Việt" data-i18n-aria="lang.vi">VI</button>@@ -95,6 +95,14 @@</div><div class="hint" id="durHint">Gõ số giây (90) hoặc phút:giây (1:30).</div><div class="warn" id="durWarn" hidden></div>+ <span class="field" id="ratioLbl"><span data-i18n="ratio.label">Khung hình</span> <span class="opt" id="ratioSize">1080×1920</span></span>+ <div class="ratios" role="radiogroup" aria-labelledby="ratioLbl" aria-describedby="ratioHint">+ <button type="button" class="ratio on" role="radio" aria-checked="true" data-ratio="9:16"><i style="--w:9;--h:16" aria-hidden="true"></i><span>9:16</span></button>+ <button type="button" class="ratio" role="radio" aria-checked="false" data-ratio="16:9"><i style="--w:16;--h:9" aria-hidden="true"></i><span>16:9</span></button>+ <button type="button" class="ratio" role="radio" aria-checked="false" data-ratio="4:3"><i style="--w:4;--h:3" aria-hidden="true"></i><span>4:3</span></button>+ <button type="button" class="ratio" role="radio" aria-checked="false" data-ratio="3:4"><i style="--w:3;--h:4" aria-hidden="true"></i><span>3:4</span></button>+ </div>+ <div class="hint" id="ratioHint"></div><div id="audioPanel" aria-label="Âm thanh" data-i18n-aria="audio.aria"></div><div class="row"><div class="span2">@@ -184,6 +192,16 @@<label class="sr" for="edMusicFile" data-i18n="ed.musicFileLabel">File nhạc</label><input type="file" id="edMusicFile" accept="audio/*" hidden /><div class="ed-file" id="edMusicName"></div></div>+ <div class="cr-blk">+ <div class="cr-h"><span id="crRatioH" data-i18n="ratio.label">Khung hình</span><small class="mono" id="crRatioSize">1080×1920</small></div>+ <div class="ratios cr-ratios" id="crRatio" role="radiogroup" aria-labelledby="crRatioH" aria-describedby="crRatioHint">+ <button type="button" class="ratio on" role="radio" aria-checked="true" data-ratio="9:16"><i style="--w:9;--h:16" aria-hidden="true"></i><span>9:16</span></button>+ <button type="button" class="ratio" role="radio" aria-checked="false" data-ratio="16:9"><i style="--w:16;--h:9" aria-hidden="true"></i><span>16:9</span></button>+ <button type="button" class="ratio" role="radio" aria-checked="false" data-ratio="4:3"><i style="--w:4;--h:3" aria-hidden="true"></i><span>4:3</span></button>+ <button type="button" class="ratio" role="radio" aria-checked="false" data-ratio="3:4"><i style="--w:3;--h:4" aria-hidden="true"></i><span>3:4</span></button>+ </div>+ <p class="cr-rhint" id="crRatioHint"></p>+ </div><div class="cr-blk"><div class="cr-h"><label for="crLen" data-i18n="cr.len">Độ dài bản ra</label><button type="button" class="cr-link" id="crLenAuto" data-i18n="cr.lenAuto">Tự động</button></div><div class="cr-range"><input type="range" id="crLen" min="15" max="180" step="5" value="40" aria-describedby="crLenV" /><output id="crLenV" for="crLen" class="mono"></output></div>diff --git a/server/public/style.css b/server/public/style.cssindex fb9a04c..0898e0e 100644--- a/server/public/style.css+++ b/server/public/style.css@@ -222,3 +222,13 @@ dialog.logp:not([open]) { display: none; }.app-foot button { min-height: 40px; padding: 0 12px; border-radius: 8px; border: 1px solid transparent; background: none; color: var(--ink-3); cursor: pointer; font-size: 13px; }.app-foot button:hover { color: var(--ink); border-color: var(--line); }body.studio-on .app-foot { display: none; }++/* ---- tỉ lệ khung (Dựng từ mẫu + Edit video) ---- */+.ratios { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }+.ratio { min-height: 64px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 6px 4px; border-radius: 12px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink-2); font: 600 13px/1 var(--mono); cursor: pointer; transition: background .15s, color .15s, border-color .15s; }+.ratio i { display: block; width: calc(var(--w) / max(var(--w), var(--h)) * 26px); height: calc(var(--h) / max(var(--w), var(--h)) * 26px); border: 2px solid currentColor; border-radius: 3px; }+.ratio:hover { color: var(--ink); }+.ratio.on { background: var(--ink); color: var(--bg); border-color: var(--ink); }+.ratio:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.job.wide-16x9, .job.wide-4x3 { grid-template-columns: 240px minmax(0, 1fr); }+@media (max-width: 720px) { .job.wide-16x9, .job.wide-4x3 { grid-template-columns: minmax(0, 1fr); } }