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.

Trả lại xuống dòng CRLF cho 5 file đã lỡ đổi sang LF (server.mjs, logs.mjs, app.js, i18n.js, index.html)

Lumtek699e9395d8ed
diff --git a/server/logs.mjs b/server/logs.mjs
index 6fb82f1..0b6cf73 100644
--- a/server/logs.mjs
+++ b/server/logs.mjs
@@ -1,223 +1,223 @@
-// Nhật ký cho người dùng: xem vì sao 1 job hỏng mà không mở terminal.
-// GET /api/logs/job/:id → job dựng từ mẫu (jobs/<id>/log.txt)
-// GET /api/logs/edit/:id → job edit (edits/<id>/log.txt)
-// GET /api/logs/server → log server gần nhất (ring buffer trong RAM + đuôi logs/server.log nếu file đó đã có)
-// thêm ?download=1 → text/plain kèm Content-Disposition (nút "Tải file .txt")
-// Chỉ đọc. id kiểm chặt (^[\w-]{1,80}$, không có "." nên không ".."), Origin lạ → 403 như các route ghi.
-// Mọi chữ trả ra đã qua redact(): khoá API (sk-…), KEY=/TOKEN=, header Authorization/Bearer, x-api-key, JWT,
-// token GitHub/Slack/AWS, ?key=/&token= trong URL; đường dẫn thư mục nhà rút về "~".
-// explain(): map lỗi hay gặp sang mã (UI tra i18n "log.why.<mã>"); không khớp mã nào → UI hiện nguyên văn (đã lọc).
-import fs from 'node:fs';
-import os from 'node:os';
-import path from 'node:path';
-
-export const LOG_TAIL = 300; // số dòng cuối của log job trả ra
-const RING_MAX = 1000; // số dòng log server giữ trong RAM
-const MAX_LINE = 2000; // cắt dòng quá dài (traceback, JSON lỗi)
-const ID_RE = /^[\w-]{1,80}$/;
-
-// ---- lọc bí mật ------------------------------------------------------------------------------------------------
-const HIDE = '[đã ẩn]';
-const homeForms = (() => {
- const h = os.homedir();
- if (!h || h.length < 3) return [];
- const fwd = h.replace(/\\/g, '/');
- const set = new Set([h, fwd, h.replace(/\\/g, '\\\\'), fwd.replace(/^([A-Za-z]):/, (m, d) => `/${d.toLowerCase()}`)]);
- return [...set].sort((a, b) => b.length - a.length);
-})();
-const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-const HOME_RE = homeForms.length ? new RegExp(homeForms.map(reEsc).join('|'), 'gi') : null;
-const RULES = [
- // KEY=..., TOKEN: ..., "api_key": "...", password=... (tên biến/thuộc tính chứa key/token/secret/password)
- [/((?:["']?)[A-Za-z0-9_.-]*(?:api[_-]?key|apikey|secret|token(?![sS])|passw(?:or)?d|auth[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_.-]*["']?\s*[:=]\s*)(["']?)[^\s"',;&]{3,}\2/gi, `$1$2${HIDE}$2`],
- // header Authorization / Proxy-Authorization / x-api-key / Cookie
- [/((?:proxy-)?authorization["']?\s*[:=]\s*["']?)(?:(?:bearer|basic|token)\s+)?[^\s"',;]+/gi, `$1${HIDE}`],
- [/((?:x-api-key|x-goog-api-key|api-key|cookie|set-cookie)["']?\s*[:=]\s*["']?)[^\s"',;]+/gi, `$1${HIDE}`],
- [/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, `$1 ${HIDE}`],
- // khoá dạng sk-… (Anthropic sk-ant-…, OpenAI sk-…/sk-proj-…), token GitHub/Slack/Google/AWS/HuggingFace, JWT
- [/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{8,}/g, `sk-${HIDE}`],
- [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, HIDE],
- [/\bxox[abposr]-[A-Za-z0-9-]{10,}/g, HIDE],
- [/\bAIza[0-9A-Za-z_-]{30,}/g, HIDE],
- [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, HIDE],
- [/\bhf_[A-Za-z0-9]{20,}/g, HIDE],
- [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, HIDE],
- // ?key=… &token=… trong URL
- [/([?&](?:key|api_key|apikey|token|access_token|auth|sig|signature)=)[^&\s"']+/gi, `$1${HIDE}`],
- // mật khẩu trong URL: scheme://user:pass@host
- [/(\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@]+:)[^\s@/]+@/gi, `$1${HIDE}@`],
-];
-/** Lọc bí mật + rút đường dẫn nhà về "~". Nhận chuỗi bất kỳ, trả chuỗi. */
-export function redact(text) {
- let s = String(text ?? '');
- for (const [re, to] of RULES) s = s.replace(re, to);
- if (HOME_RE) s = s.replace(HOME_RE, '~');
- return s;
-}
-const clip = (l) => (l.length > MAX_LINE ? l.slice(0, MAX_LINE) + ' …' : l);
-
-// ---- câu lỗi dễ hiểu ---------------------------------------------------------------------------------------------
-// Thứ tự = độ ưu tiên (cụ thể trước chung). UI: t('log.why.<code>') + t('log.fix.<code>').
-const WHY = [
- ['claude_login', /please run \/login|not logged in|run `?claude login|invalid api key · please run|chưa đăng nhập claude|login required/i],
- ['api_key', /API 401|Khoá Anthropic không (?:hợp lệ|có quyền)|\b401\b\s*(?:\{|unauthori|authentication)|authentication_error|invalid[ _-]?(?:x-)?api[ _-]?key|incorrect api key|unauthori[sz]ed|permission_error/i],
- ['quota', /insufficient_quota|credit balance is too low|quota|billing|rate[_ ]limit|API 429|\b429\b\s*(?:\{|too many)|usage limit|hết hạn mức|limit reached|resets? at/i],
- ['overloaded', /overloaded_error|API 529|\b529\b\s*\{|overloaded|\b503\b service unavailable/i],
- ['disk', /ENOSPC|no space left|not enough space|disk (?:is )?full|ổ đĩa còn|hết dung lượng|There is not enough space/i],
- ['cuda', /CUDA|cudnn|cublas|libcudnn|nvcuda|CUBLAS_STATUS|out of memory.*GPU|GPU.*out of memory|ctranslate2.*cuda/i],
- ['ffmpeg', /(?:spawn|ENOENT).*ff(?:mpeg|probe)|ff(?:mpeg|probe)['"]? (?:is not recognized|not found)|không thấy ff(?:mpeg|probe)|ffmpeg: command not found|cần ffmpeg/i],
- ['python', /(?:spawn|ENOENT).*python|python(?:3)?['"]? (?:is not recognized|not found)|No module named|ModuleNotFoundError|môi trường Python|chưa cài đủ phần Edit/i],
- ['claude_missing', /không thấy lệnh claude|claude['"]? (?:is not recognized|not found)|(?:spawn|ENOENT).*claude/i],
- ['timeout', /timed? ?out|ETIMEDOUT|quá giờ|quá thời gian|hết giờ|timeout|render bị dừng|dừng sau \d+ phút|SIGTERM/i],
- ['interrupted', /server khởi động lại|bị ngắt giữa chừng|tiến trình .* đã tắt/i],
- ['network', /ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|getaddrinfo|network error|fetch failed|socket hang up/i],
- ['no_scene', /chưa có scene\/index\.html|Không thấy .*index\.html/i],
- ['scene_invalid', /Thiếu <div id="root"|#root thiếu|snapshot chỉ ra|HyperFrames render lỗi|SHADER_ERROR|lint/i],
- ['no_speech', /không nghe được lời nào|video không có tiếng/i],
- ['bad_video', /không đọc được video|video quá ngắn|hỏng \(dưới 1 giây\)|moov atom not found|Invalid data found/i],
- ['edl_invalid', /EDL không hợp lệ/i],
-];
-/** Tìm mã lỗi dễ hiểu trong câu lỗi (ưu tiên) rồi trong các dòng log cuối. Trả mã hoặc null. */
-export function explain(error, lines = []) {
- const hay = [String(error || ''), ...lines.slice(-60).reverse()];
- for (const h of hay) {
- if (!h) continue;
- for (const [code, re] of WHY) if (re.test(h)) return code;
- }
- return null;
-}
-export const WHY_CODES = WHY.map(([c]) => c);
-
-// ---- đọc đuôi file log -------------------------------------------------------------------------------------------
-/** n dòng cuối của file (đọc tối đa 2 MB cuối, không nạp cả file lớn). */
-export function tailFile(file, n = LOG_TAIL) {
- let fd;
- try {
- const st = fs.statSync(file);
- if (!st.isFile()) return { lines: [], total: 0, truncated: false };
- const len = Math.min(st.size, 2 * 1024 * 1024);
- const buf = Buffer.alloc(len);
- fd = fs.openSync(file, 'r');
- fs.readSync(fd, buf, 0, len, st.size - len);
- let all = buf.toString('utf8').split(/\r?\n/);
- if (st.size > len) all = all.slice(1); // dòng đầu có thể bị cắt giữa chừng
- all = all.filter((l) => l.length);
- return { lines: all.slice(-n), total: all.length, truncated: all.length > n || st.size > len };
- } catch { return { lines: [], total: 0, truncated: false }; } finally { if (fd !== undefined) try { fs.closeSync(fd); } catch { /* bỏ qua */ } }
-}
-
-// ---- log server: ring buffer -------------------------------------------------------------------------------------
-const ring = [];
-let ringFile = null;
-let installed = false;
-/**
- * Bắt console.log/info/warn/error vào ring buffer (giữ RING_MAX dòng). Có sẵn file logs/server.log (hoặc
- * LUMREELS_LOG_FILE) thì ghi thêm vào đó — không tự tạo file. Gọi 1 lần lúc server khởi động.
- */
-export function installLogCapture(root) {
- if (installed) return;
- installed = true;
- const f = process.env.LUMREELS_LOG_FILE || path.join(root, 'logs', 'server.log');
- try { if (fs.statSync(f).isFile()) ringFile = f; } catch { /* không có file: chỉ RAM */ }
- for (const level of ['log', 'info', 'warn', 'error']) {
- const orig = console[level].bind(console);
- console[level] = (...args) => {
- orig(...args);
- try {
- const text = args.map((a) => (a instanceof Error ? (a.stack || a.message) : typeof a === 'string' ? a : (() => { try { return JSON.stringify(a); } catch { return String(a); } })())).join(' ');
- const stamp = new Date().toISOString().slice(0, 19).replace('T', ' ');
- for (const l of text.split(/\r?\n/)) {
- if (!l) continue;
- const line = `[${stamp}]${level === 'error' ? ' LỖI' : level === 'warn' ? ' CẢNH BÁO' : ''} ${clip(l)}`;
- ring.push(line);
- if (ringFile) try { fs.appendFileSync(ringFile, redact(line) + '\n'); } catch { ringFile = null; }
- }
- if (ring.length > RING_MAX) ring.splice(0, ring.length - RING_MAX);
- } catch { /* log không được thì thôi */ }
- };
- }
-}
-/** Log server gần nhất (đã lọc). Ring ít dòng (vừa khởi động lại) → nối đuôi file log nếu có. */
-export function serverLog(n = LOG_TAIL) {
- let lines = ring.slice(-n);
- let source = 'memory';
- if (lines.length < n && ringFile) {
- const ft = tailFile(ringFile, n);
- const have = new Set(lines);
- const older = ft.lines.filter((l) => !have.has(l));
- if (older.length) { lines = [...older.slice(-(n - lines.length)), ...lines]; source = 'memory+file'; }
- }
- return { kind: 'server', source, lines: lines.map((l) => clip(redact(l))), total: ring.length, truncated: ring.length > n, at: new Date().toISOString() };
-}
-
-// ---- nhật ký 1 job ------------------------------------------------------------------------------------------------
-const TPL_STEPS = ['generating', 'waiting_agent', 'previewing', 'rendering'];
-/** Bước hỏng của job dựng từ mẫu: trạng thái cuối cùng trước "error" trong log ("trạng thái → X"). */
-function tplFailedStep(lines) {
- let last = null;
- for (const l of lines) {
- const m = /trạng thái → (\w+)/.exec(l);
- if (!m) continue;
- if (m[1] === 'error') return last;
- if (TPL_STEPS.includes(m[1])) last = m[1];
- }
- return null;
-}
-/**
- * Nhật ký job: {kind, id, status, step, error, why, lines[], total, truncated}. Mọi chữ đã lọc.
- * kind 'job' (dựng từ mẫu, step = mã trạng thái: generating | previewing | rendering …) hoặc 'edit' (step = tên bước edit).
- */
-export function jobLog(kind, id, { jobsDir, editsDir, readJob, readEdit }) {
- if (!ID_RE.test(String(id))) return null;
- const base = kind === 'edit' ? editsDir : jobsDir;
- const dir = path.resolve(base, id);
- if (path.dirname(dir) !== path.resolve(base)) return null;
- const job = kind === 'edit' ? readEdit(id) : readJob(id);
- if (!job) return null;
- const t = tailFile(path.join(dir, 'log.txt'));
- const failed = job.status === 'error' || (kind === 'edit' && !!job.reviseError);
- const error = kind === 'edit' ? (job.status === 'error' ? job.error : job.reviseError) || null : job.status === 'error' ? job.error || null : null;
- let step = null;
- if (failed) step = kind === 'edit' ? job.step || null : tplFailedStep(t.lines);
- return {
- kind, id, status: job.status, failed, step, error: error ? clip(redact(error)) : null,
- why: failed ? explain(error, t.lines) : null,
- lines: t.lines.map((l) => clip(redact(l))), total: t.total, truncated: t.truncated,
- title: kind === 'edit' ? redact(job.sourceName || '') : redact(job.templateTitle || job.templateId || ''),
- at: new Date().toISOString(),
- };
-}
-
-/** Văn bản .txt để tải về / chép (đầu: trạng thái, bước, lỗi; rồi log thô). */
-export function logText(v) {
- const head = v.kind === 'server'
- ? [`LumReels — nhật ký server (${v.at})`, `nguồn: ${v.source}, ${v.lines.length} dòng`]
- : [`LumReels — nhật ký ${v.kind === 'edit' ? 'edit' : 'job'} ${v.id}${v.title ? ` (${v.title})` : ''}`, `trạng thái: ${v.status}${v.step ? ` · bước hỏng: ${v.step}` : ''}`,
- ...(v.error ? [`lỗi: ${v.error}`] : []), ...(v.why ? [`mã lỗi: ${v.why}`] : []), `xuất lúc: ${v.at}`];
- return `${head.join('\n')}\n${'-'.repeat(60)}\n${v.lines.join('\n')}\n`;
-}
-
-/** Route /api/logs/…; trả true nếu đã xử lý. ctx: {send, originOk(req), jobsDir, editsDir, readJob, readEdit}. */
-export function handleLogRoute(req, res, p, url, ctx) {
- if (!p.startsWith('/api/logs')) return false;
- if (req.method !== 'GET' && req.method !== 'HEAD') { ctx.send(res, 405, { error: 'chỉ đọc' }); return true; }
- // Origin lạ (trang web khác gọi fetch) → 403; không có Origin (cùng trang / curl cục bộ) thì cho.
- if (!ctx.originOk(req)) { ctx.send(res, 403, { error: 'origin không hợp lệ' }); return true; }
- let v = null;
- if (p === '/api/logs/server') v = serverLog();
- else {
- const m = /^\/api\/logs\/(job|edit)\/([^/]+)$/.exec(p);
- if (!m) { ctx.send(res, 404, { error: 'không có API này' }); return true; }
- if (!ID_RE.test(m[2])) { ctx.send(res, 400, { error: 'id không hợp lệ' }); return true; }
- v = jobLog(m[1], m[2], ctx);
- if (!v) { ctx.send(res, 404, { error: 'không thấy job' }); return true; }
- }
- if (url.searchParams.get('download') === '1') {
- const name = v.kind === 'server' ? 'lumreels-server-log.txt' : `lumreels-${v.kind}-${v.id}-log.txt`;
- res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Disposition': `attachment; filename="${name}"`, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
- res.end(req.method === 'HEAD' ? undefined : logText(v));
- return true;
- }
- ctx.send(res, 200, v);
- return true;
-}
+// Nhật ký cho người dùng: xem vì sao 1 job hỏng mà không mở terminal.
+// GET /api/logs/job/:id → job dựng từ mẫu (jobs/<id>/log.txt)
+// GET /api/logs/edit/:id → job edit (edits/<id>/log.txt)
+// GET /api/logs/server → log server gần nhất (ring buffer trong RAM + đuôi logs/server.log nếu file đó đã có)
+// thêm ?download=1 → text/plain kèm Content-Disposition (nút "Tải file .txt")
+// Chỉ đọc. id kiểm chặt (^[\w-]{1,80}$, không có "." nên không ".."), Origin lạ → 403 như các route ghi.
+// Mọi chữ trả ra đã qua redact(): khoá API (sk-…), KEY=/TOKEN=, header Authorization/Bearer, x-api-key, JWT,
+// token GitHub/Slack/AWS, ?key=/&token= trong URL; đường dẫn thư mục nhà rút về "~".
+// explain(): map lỗi hay gặp sang mã (UI tra i18n "log.why.<mã>"); không khớp mã nào → UI hiện nguyên văn (đã lọc).
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+export const LOG_TAIL = 300; // số dòng cuối của log job trả ra
+const RING_MAX = 1000; // số dòng log server giữ trong RAM
+const MAX_LINE = 2000; // cắt dòng quá dài (traceback, JSON lỗi)
+const ID_RE = /^[\w-]{1,80}$/;
+
+// ---- lọc bí mật ------------------------------------------------------------------------------------------------
+const HIDE = '[đã ẩn]';
+const homeForms = (() => {
+ const h = os.homedir();
+ if (!h || h.length < 3) return [];
+ const fwd = h.replace(/\\/g, '/');
+ const set = new Set([h, fwd, h.replace(/\\/g, '\\\\'), fwd.replace(/^([A-Za-z]):/, (m, d) => `/${d.toLowerCase()}`)]);
+ return [...set].sort((a, b) => b.length - a.length);
+})();
+const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+const HOME_RE = homeForms.length ? new RegExp(homeForms.map(reEsc).join('|'), 'gi') : null;
+const RULES = [
+ // KEY=..., TOKEN: ..., "api_key": "...", password=... (tên biến/thuộc tính chứa key/token/secret/password)
+ [/((?:["']?)[A-Za-z0-9_.-]*(?:api[_-]?key|apikey|secret|token(?![sS])|passw(?:or)?d|auth[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_.-]*["']?\s*[:=]\s*)(["']?)[^\s"',;&]{3,}\2/gi, `$1$2${HIDE}$2`],
+ // header Authorization / Proxy-Authorization / x-api-key / Cookie
+ [/((?:proxy-)?authorization["']?\s*[:=]\s*["']?)(?:(?:bearer|basic|token)\s+)?[^\s"',;]+/gi, `$1${HIDE}`],
+ [/((?:x-api-key|x-goog-api-key|api-key|cookie|set-cookie)["']?\s*[:=]\s*["']?)[^\s"',;]+/gi, `$1${HIDE}`],
+ [/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, `$1 ${HIDE}`],
+ // khoá dạng sk-… (Anthropic sk-ant-…, OpenAI sk-…/sk-proj-…), token GitHub/Slack/Google/AWS/HuggingFace, JWT
+ [/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{8,}/g, `sk-${HIDE}`],
+ [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, HIDE],
+ [/\bxox[abposr]-[A-Za-z0-9-]{10,}/g, HIDE],
+ [/\bAIza[0-9A-Za-z_-]{30,}/g, HIDE],
+ [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, HIDE],
+ [/\bhf_[A-Za-z0-9]{20,}/g, HIDE],
+ [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, HIDE],
+ // ?key=… &token=… trong URL
+ [/([?&](?:key|api_key|apikey|token|access_token|auth|sig|signature)=)[^&\s"']+/gi, `$1${HIDE}`],
+ // mật khẩu trong URL: scheme://user:pass@host
+ [/(\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@]+:)[^\s@/]+@/gi, `$1${HIDE}@`],
+];
+/** Lọc bí mật + rút đường dẫn nhà về "~". Nhận chuỗi bất kỳ, trả chuỗi. */
+export function redact(text) {
+ let s = String(text ?? '');
+ for (const [re, to] of RULES) s = s.replace(re, to);
+ if (HOME_RE) s = s.replace(HOME_RE, '~');
+ return s;
+}
+const clip = (l) => (l.length > MAX_LINE ? l.slice(0, MAX_LINE) + ' …' : l);
+
+// ---- câu lỗi dễ hiểu ---------------------------------------------------------------------------------------------
+// Thứ tự = độ ưu tiên (cụ thể trước chung). UI: t('log.why.<code>') + t('log.fix.<code>').
+const WHY = [
+ ['claude_login', /please run \/login|not logged in|run `?claude login|invalid api key · please run|chưa đăng nhập claude|login required/i],
+ ['api_key', /API 401|Khoá Anthropic không (?:hợp lệ|có quyền)|\b401\b\s*(?:\{|unauthori|authentication)|authentication_error|invalid[ _-]?(?:x-)?api[ _-]?key|incorrect api key|unauthori[sz]ed|permission_error/i],
+ ['quota', /insufficient_quota|credit balance is too low|quota|billing|rate[_ ]limit|API 429|\b429\b\s*(?:\{|too many)|usage limit|hết hạn mức|limit reached|resets? at/i],
+ ['overloaded', /overloaded_error|API 529|\b529\b\s*\{|overloaded|\b503\b service unavailable/i],
+ ['disk', /ENOSPC|no space left|not enough space|disk (?:is )?full|ổ đĩa còn|hết dung lượng|There is not enough space/i],
+ ['cuda', /CUDA|cudnn|cublas|libcudnn|nvcuda|CUBLAS_STATUS|out of memory.*GPU|GPU.*out of memory|ctranslate2.*cuda/i],
+ ['ffmpeg', /(?:spawn|ENOENT).*ff(?:mpeg|probe)|ff(?:mpeg|probe)['"]? (?:is not recognized|not found)|không thấy ff(?:mpeg|probe)|ffmpeg: command not found|cần ffmpeg/i],
+ ['python', /(?:spawn|ENOENT).*python|python(?:3)?['"]? (?:is not recognized|not found)|No module named|ModuleNotFoundError|môi trường Python|chưa cài đủ phần Edit/i],
+ ['claude_missing', /không thấy lệnh claude|claude['"]? (?:is not recognized|not found)|(?:spawn|ENOENT).*claude/i],
+ ['timeout', /timed? ?out|ETIMEDOUT|quá giờ|quá thời gian|hết giờ|timeout|render bị dừng|dừng sau \d+ phút|SIGTERM/i],
+ ['interrupted', /server khởi động lại|bị ngắt giữa chừng|tiến trình .* đã tắt/i],
+ ['network', /ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|getaddrinfo|network error|fetch failed|socket hang up/i],
+ ['no_scene', /chưa có scene\/index\.html|Không thấy .*index\.html/i],
+ ['scene_invalid', /Thiếu <div id="root"|#root thiếu|snapshot chỉ ra|HyperFrames render lỗi|SHADER_ERROR|lint/i],
+ ['no_speech', /không nghe được lời nào|video không có tiếng/i],
+ ['bad_video', /không đọc được video|video quá ngắn|hỏng \(dưới 1 giây\)|moov atom not found|Invalid data found/i],
+ ['edl_invalid', /EDL không hợp lệ/i],
+];
+/** Tìm mã lỗi dễ hiểu trong câu lỗi (ưu tiên) rồi trong các dòng log cuối. Trả mã hoặc null. */
+export function explain(error, lines = []) {
+ const hay = [String(error || ''), ...lines.slice(-60).reverse()];
+ for (const h of hay) {
+ if (!h) continue;
+ for (const [code, re] of WHY) if (re.test(h)) return code;
+ }
+ return null;
+}
+export const WHY_CODES = WHY.map(([c]) => c);
+
+// ---- đọc đuôi file log -------------------------------------------------------------------------------------------
+/** n dòng cuối của file (đọc tối đa 2 MB cuối, không nạp cả file lớn). */
+export function tailFile(file, n = LOG_TAIL) {
+ let fd;
+ try {
+ const st = fs.statSync(file);
+ if (!st.isFile()) return { lines: [], total: 0, truncated: false };
+ const len = Math.min(st.size, 2 * 1024 * 1024);
+ const buf = Buffer.alloc(len);
+ fd = fs.openSync(file, 'r');
+ fs.readSync(fd, buf, 0, len, st.size - len);
+ let all = buf.toString('utf8').split(/\r?\n/);
+ if (st.size > len) all = all.slice(1); // dòng đầu có thể bị cắt giữa chừng
+ all = all.filter((l) => l.length);
+ return { lines: all.slice(-n), total: all.length, truncated: all.length > n || st.size > len };
+ } catch { return { lines: [], total: 0, truncated: false }; } finally { if (fd !== undefined) try { fs.closeSync(fd); } catch { /* bỏ qua */ } }
+}
+
+// ---- log server: ring buffer -------------------------------------------------------------------------------------
+const ring = [];
+let ringFile = null;
+let installed = false;
+/**
+ * Bắt console.log/info/warn/error vào ring buffer (giữ RING_MAX dòng). Có sẵn file logs/server.log (hoặc
+ * LUMREELS_LOG_FILE) thì ghi thêm vào đó — không tự tạo file. Gọi 1 lần lúc server khởi động.
+ */
+export function installLogCapture(root) {
+ if (installed) return;
+ installed = true;
+ const f = process.env.LUMREELS_LOG_FILE || path.join(root, 'logs', 'server.log');
+ try { if (fs.statSync(f).isFile()) ringFile = f; } catch { /* không có file: chỉ RAM */ }
+ for (const level of ['log', 'info', 'warn', 'error']) {
+ const orig = console[level].bind(console);
+ console[level] = (...args) => {
+ orig(...args);
+ try {
+ const text = args.map((a) => (a instanceof Error ? (a.stack || a.message) : typeof a === 'string' ? a : (() => { try { return JSON.stringify(a); } catch { return String(a); } })())).join(' ');
+ const stamp = new Date().toISOString().slice(0, 19).replace('T', ' ');
+ for (const l of text.split(/\r?\n/)) {
+ if (!l) continue;
+ const line = `[${stamp}]${level === 'error' ? ' LỖI' : level === 'warn' ? ' CẢNH BÁO' : ''} ${clip(l)}`;
+ ring.push(line);
+ if (ringFile) try { fs.appendFileSync(ringFile, redact(line) + '\n'); } catch { ringFile = null; }
+ }
+ if (ring.length > RING_MAX) ring.splice(0, ring.length - RING_MAX);
+ } catch { /* log không được thì thôi */ }
+ };
+ }
+}
+/** Log server gần nhất (đã lọc). Ring ít dòng (vừa khởi động lại) → nối đuôi file log nếu có. */
+export function serverLog(n = LOG_TAIL) {
+ let lines = ring.slice(-n);
+ let source = 'memory';
+ if (lines.length < n && ringFile) {
+ const ft = tailFile(ringFile, n);
+ const have = new Set(lines);
+ const older = ft.lines.filter((l) => !have.has(l));
+ if (older.length) { lines = [...older.slice(-(n - lines.length)), ...lines]; source = 'memory+file'; }
+ }
+ return { kind: 'server', source, lines: lines.map((l) => clip(redact(l))), total: ring.length, truncated: ring.length > n, at: new Date().toISOString() };
+}
+
+// ---- nhật ký 1 job ------------------------------------------------------------------------------------------------
+const TPL_STEPS = ['generating', 'waiting_agent', 'previewing', 'rendering'];
+/** Bước hỏng của job dựng từ mẫu: trạng thái cuối cùng trước "error" trong log ("trạng thái → X"). */
+function tplFailedStep(lines) {
+ let last = null;
+ for (const l of lines) {
+ const m = /trạng thái → (\w+)/.exec(l);
+ if (!m) continue;
+ if (m[1] === 'error') return last;
+ if (TPL_STEPS.includes(m[1])) last = m[1];
+ }
+ return null;
+}
+/**
+ * Nhật ký job: {kind, id, status, step, error, why, lines[], total, truncated}. Mọi chữ đã lọc.
+ * kind 'job' (dựng từ mẫu, step = mã trạng thái: generating | previewing | rendering …) hoặc 'edit' (step = tên bước edit).
+ */
+export function jobLog(kind, id, { jobsDir, editsDir, readJob, readEdit }) {
+ if (!ID_RE.test(String(id))) return null;
+ const base = kind === 'edit' ? editsDir : jobsDir;
+ const dir = path.resolve(base, id);
+ if (path.dirname(dir) !== path.resolve(base)) return null;
+ const job = kind === 'edit' ? readEdit(id) : readJob(id);
+ if (!job) return null;
+ const t = tailFile(path.join(dir, 'log.txt'));
+ const failed = job.status === 'error' || (kind === 'edit' && !!job.reviseError);
+ const error = kind === 'edit' ? (job.status === 'error' ? job.error : job.reviseError) || null : job.status === 'error' ? job.error || null : null;
+ let step = null;
+ if (failed) step = kind === 'edit' ? job.step || null : tplFailedStep(t.lines);
+ return {
+ kind, id, status: job.status, failed, step, error: error ? clip(redact(error)) : null,
+ why: failed ? explain(error, t.lines) : null,
+ lines: t.lines.map((l) => clip(redact(l))), total: t.total, truncated: t.truncated,
+ title: kind === 'edit' ? redact(job.sourceName || '') : redact(job.templateTitle || job.templateId || ''),
+ at: new Date().toISOString(),
+ };
+}
+
+/** Văn bản .txt để tải về / chép (đầu: trạng thái, bước, lỗi; rồi log thô). */
+export function logText(v) {
+ const head = v.kind === 'server'
+ ? [`LumReels — nhật ký server (${v.at})`, `nguồn: ${v.source}, ${v.lines.length} dòng`]
+ : [`LumReels — nhật ký ${v.kind === 'edit' ? 'edit' : 'job'} ${v.id}${v.title ? ` (${v.title})` : ''}`, `trạng thái: ${v.status}${v.step ? ` · bước hỏng: ${v.step}` : ''}`,
+ ...(v.error ? [`lỗi: ${v.error}`] : []), ...(v.why ? [`mã lỗi: ${v.why}`] : []), `xuất lúc: ${v.at}`];
+ return `${head.join('\n')}\n${'-'.repeat(60)}\n${v.lines.join('\n')}\n`;
+}
+
+/** Route /api/logs/…; trả true nếu đã xử lý. ctx: {send, originOk(req), jobsDir, editsDir, readJob, readEdit}. */
+export function handleLogRoute(req, res, p, url, ctx) {
+ if (!p.startsWith('/api/logs')) return false;
+ if (req.method !== 'GET' && req.method !== 'HEAD') { ctx.send(res, 405, { error: 'chỉ đọc' }); return true; }
+ // Origin lạ (trang web khác gọi fetch) → 403; không có Origin (cùng trang / curl cục bộ) thì cho.
+ if (!ctx.originOk(req)) { ctx.send(res, 403, { error: 'origin không hợp lệ' }); return true; }
+ let v = null;
+ if (p === '/api/logs/server') v = serverLog();
+ else {
+ const m = /^\/api\/logs\/(job|edit)\/([^/]+)$/.exec(p);
+ if (!m) { ctx.send(res, 404, { error: 'không có API này' }); return true; }
+ if (!ID_RE.test(m[2])) { ctx.send(res, 400, { error: 'id không hợp lệ' }); return true; }
+ v = jobLog(m[1], m[2], ctx);
+ if (!v) { ctx.send(res, 404, { error: 'không thấy job' }); return true; }
+ }
+ if (url.searchParams.get('download') === '1') {
+ const name = v.kind === 'server' ? 'lumreels-server-log.txt' : `lumreels-${v.kind}-${v.id}-log.txt`;
+ res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Disposition': `attachment; filename="${name}"`, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
+ res.end(req.method === 'HEAD' ? undefined : logText(v));
+ return true;
+ }
+ ctx.send(res, 200, v);
+ return true;
+}
diff --git a/server/public/app.js b/server/public/app.js
index 6c00780..b356403 100644
--- a/server/public/app.js
+++ b/server/public/app.js
@@ -1,632 +1,632 @@
-// UI 1 trang: lưới mẫu, ô nội dung, danh sách job. Không framework. Chữ giao diện lấy từ i18n.js (window.I18N).
-(() => {
- const $ = (s, el = document) => el.querySelector(s);
- const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
- const I = window.I18N;
- const t = (k, v) => I.t(k, v);
- const status = (s) => (['scheduled', 'queued', 'generating', 'waiting_agent', 'previewing', 'rendering', 'done', 'error'].includes(s) ? t('st.' + s) : s);
- const RUNNING = ['queued', 'generating', 'previewing', 'rendering'];
- const CATS = ['faceless', 'ads', 'multi-style', 'viet-nam'];
- const catName = (c) => (CATS.includes(c) ? t('cat.' + c) : c);
- // Nhãn nguồn của mẫu (L13): gốc / của tôi (tự tạo) / cộng đồng (gói nhập). Chữ của gói chỉ vào textContent (L9).
- const SOURCES = ['builtin', 'local', 'pack'];
- const srcOf = (x) => (SOURCES.includes(x?.source) ? x.source : 'builtin');
- const srcLabel = (x) => t('src.' + srcOf(x));
- /** Tạo phần tử: props {class, text, attrs:{}, data:{}}; con là phần tử hoặc chuỗi (thành nút chữ). */
- function h(tag, props = {}, ...kids) {
- const el = document.createElement(tag);
- if (props.class) el.className = props.class;
- if (props.text != null) el.textContent = props.text;
- for (const [k, v] of Object.entries(props.attrs || {})) if (v != null && v !== false) el.setAttribute(k, v === true ? '' : String(v));
- for (const [k, v] of Object.entries(props.data || {})) el.dataset[k] = String(v);
- for (const c of kids.flat()) if (c != null && c !== false) el.append(c instanceof Node ? c : document.createTextNode(String(c)));
- return el;
- }
- const srcBadge = (x) => h('span', { class: 'src src-' + srcOf(x), text: srcLabel(x) });
- const modeLabel = (m) => ({ auto: t('modeLabel.auto'), api: 'Claude API', claude: 'Claude Code', manual: t('modeLabel.manual') }[m]);
- const fmtTime = (iso) => new Date(iso).toLocaleString(I.locale, { hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit', year: 'numeric' });
- // datetime-local trả giờ máy không múi giờ → đổi sang ISO có múi giờ để server hiểu đúng.
- const runAtValue = () => { const v = $('#runAt').value; return v ? new Date(v).toISOString() : undefined; };
-
- // Thời lượng: số giây (90, 90s) hoặc phút:giây (1:30). Cùng luật với generator/jobs.mjs parseDuration.
- const DUR_MIN = 3, DUR_MAX = 600;
- function parseDur(v) {
- const s0 = String(v ?? '').trim().toLowerCase().replace(/\s+/g, '');
- if (!s0) return { error: t('dur.errEmpty') };
- let m, s;
- if ((m = /^(\d{1,4})(?:s|giây|giay)?$/.exec(s0))) s = Number(m[1]);
- else if ((m = /^(\d{1,2}):([0-5]\d)$/.exec(s0))) s = Number(m[1]) * 60 + Number(m[2]);
- else if ((m = /^(\d{1,2})(?:m|p|phút|phut)$/.exec(s0))) s = Number(m[1]) * 60;
- else return { error: t('dur.errFmt') };
- if (s < DUR_MIN) return { error: t('dur.errMin') };
- if (s > DUR_MAX) return { error: t('dur.errMax') };
- return { s };
- }
- const fmtDur = (s) => (s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`);
- // Khoảng thời gian ước tính: "40–120 giây", "4–11 phút", "2–5 giờ"… (đơn vị theo đầu trên)
- const dec = (x) => x.toFixed(1).replace('.', t('num.dec'));
- const fmtRange = (a, b) => (b < 120 ? `${Math.round(a)}–${Math.round(b)} ${t('unit.sec')}`
- : 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.
- const MAX_PICK = 12;
- let picks = [];
- let multi = false;
- const one = () => (picks.length === 1 ? picks[0] : null);
- const pickIndex = (id) => picks.findIndex((x) => x.id === id);
- let cat = '';
- let srcFilter = ''; // '' | 'local' | 'pack' (chip "Của tôi" / "Cộng đồng")
- let pollTimer = null;
- const JOB_PAGE = 6;
- let showAll = false;
- let allJobsCount = 0;
-
- // ---------- bản mới ----------
- let update = null;
- function renderUpdate() {
- const box = $('#update-banner');
- const u = update;
- if (!box || !u) return;
- const tx = box.querySelector('.ub-text');
- tx.textContent = '';
- // u.changes[0] là tiêu đề commit (dữ liệu git), giữ nguyên
- tx.append(t('update.text', { n: u.behind, first: u.changes && u.changes[0] ? u.changes[0] : '' }));
- const c = document.createElement('code'); c.textContent = 'npm start';
- tx.append(c, t('update.after'));
- }
- async function checkVersion(retry = 3) {
- let d;
- try { d = await (await fetch('/api/version')).json(); } catch { return; }
- const u = d && d.update;
- if (!u) { if (retry > 0) setTimeout(() => checkVersion(retry - 1), 8000); return; }
- const box = $('#update-banner');
- if (!box || !u.ok || !u.behind) return;
- const key = 'lumreels-hide-update-' + (u.upstream || '') + '-' + u.behind;
- try { if (localStorage.getItem(key)) return; } catch { /* bỏ qua */ }
- update = u;
- renderUpdate();
- box.hidden = false;
- box.querySelector('.ub-close').onclick = () => { box.hidden = true; try { localStorage.setItem(key, '1'); } catch { /* bỏ qua */ } };
- }
- setTimeout(checkVersion, 1500);
-
- // ---------- mẫu ----------
- async function loadTemplates() {
- templatesState = 'loading'; renderGrid();
- try {
- templates = await (await fetch('/api/templates')).json();
- templatesState = 'ok';
- } catch {
- templatesState = 'error';
- }
- renderGrid();
- }
-
- // Mã hiện trên thẻ: mẫu gốc "045"; mẫu gói chỉ hiện slug (mã đầy đủ nằm trong aria-label / title).
- const shortId = (x) => (srcOf(x) === 'builtin' ? x.id : String(x.id).split('/').pop());
- const PLAY_SVG = 'M8 5v14l11-7z';
- function playIcon() {
- const ns = 'http://www.w3.org/2000/svg';
- const svg = document.createElementNS(ns, 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true');
- const path = document.createElementNS(ns, 'path'); path.setAttribute('d', PLAY_SVG); svg.append(path);
- return svg;
- }
- function tplCard(x) {
- const k = pickIndex(x.id);
- const card = h('div', {
- class: `tpl${x.hasGuidance ? '' : ' off'}${k >= 0 ? ' sel' : ''}`, data: { id: x.id },
- attrs: { role: 'button', tabindex: 0, 'aria-disabled': String(!x.hasGuidance), 'aria-pressed': String(k >= 0),
- 'aria-label': t('tpl.aria', { id: x.id, name: x.name, ready: x.hasGuidance, order: multi && k >= 0 ? k + 1 : 0 }) + ' · ' + srcLabel(x) },
- });
- if (multi && k >= 0) card.append(h('span', { class: 'order', text: k + 1, attrs: { 'aria-hidden': 'true' } }));
- // x.thumb do server ghép từ id/slug đã kiểm (/thumbs/045.webp, /pack-thumbs/<gói>/template-<slug>.webp, /poster/…)
- card.append(x.thumb ? h('img', { class: 'thumb', attrs: { src: x.thumb, alt: '', loading: 'lazy', decoding: 'async', width: 540, height: 960 } })
- : h('div', { class: 'thumb ph', text: t('tpl.noThumb') }));
- card.append(h('span', { class: 'badge' + (x.hasGuidance ? ' ready' : ''), text: t(x.hasGuidance ? 'tpl.ready' : 'tpl.noGuide') }));
- if (x.video) {
- const b = h('button', { class: 'play', data: { play: x.id }, attrs: { type: 'button', 'aria-label': t(x.videoKind === 'demo' ? 'tpl.playDemo' : 'tpl.playRef', { id: x.id }) } });
- b.append(playIcon());
- card.append(b);
- }
- card.append(h('div', { class: 'meta' },
- h('div', { class: 'id' }, srcBadge(x), h('span', { text: `${shortId(x)} · ${catName(x.category)}` })),
- h('div', { class: 't', text: x.name })));
- if (srcOf(x) !== 'builtin') card.title = x.id;
- return card;
- }
- function renderGrid() {
- const grid = $('#grid');
- if (templatesState !== 'ok') {
- grid.replaceChildren(h('div', { class: 'empty-grid', text: t(templatesState === 'error' ? 'grid.loadErr' : 'grid.loading') }));
- return;
- }
- const q = $('#q').value.trim().toLowerCase();
- const readyOnly = $('#readyOnly').checked;
- const list = templates.filter((x) => (!cat || x.category === cat) && (!srcFilter || srcOf(x) === srcFilter) && (!readyOnly || x.hasGuidance) &&
- (!q || `${x.name} ${x.genre} ${x.blurb}`.toLowerCase().includes(q) || String(x.id).includes(q)));
- const ready = templates.filter((x) => x.hasGuidance).length;
- $('#tplCount').textContent = t('pick.count', { ready, total: templates.length });
- if (!list.length) {
- const empty = h('div', { class: 'empty-grid', text: t(srcFilter && !q ? 'grid.emptySrc.' + srcFilter : 'grid.empty') });
- if (srcFilter && !q) empty.append(' ', h('button', { class: 'linkish', text: t('pack.importBtn'), data: { packImport: 1 }, attrs: { type: 'button' } }));
- grid.replaceChildren(empty);
- return;
- }
- const focusId = document.activeElement?.closest?.('#grid .tpl')?.dataset.id;
- grid.classList.toggle('multi', multi);
- grid.replaceChildren(...list.map(tplCard));
- if (focusId) [...grid.querySelectorAll('.tpl')].find((el) => el.dataset.id === focusId)?.focus({ preventScroll: true });
- }
-
- // Báo nhẹ (tự ẩn), vd chọn quá 12 mẫu.
- let noteTimer = null;
- function note(msg) {
- const el = $('#pickNote');
- el.textContent = msg;
- clearTimeout(noteTimer);
- if (msg) noteTimer = setTimeout(() => { el.textContent = ''; }, 4000);
- }
-
- function pick(id) {
- const x = templates.find((y) => y.id === id);
- if (!x || !x.hasGuidance) return;
- if (!multi) picks = [x];
- else {
- const k = pickIndex(id);
- if (k >= 0) picks.splice(k, 1);
- else if (picks.length >= MAX_PICK) { note(t('pick.max', { max: MAX_PICK })); return; }
- else picks.push(x);
- }
- note('');
- picksChanged();
- }
- function unpick(id) { const k = pickIndex(id); if (k >= 0) { picks.splice(k, 1); picksChanged(); } }
- function setMulti(on) {
- multi = on;
- $('#multiPick').checked = on;
- if (!on) picks = picks.slice(0, 1); // tắt: quay về chọn 1, giữ mẫu đầu tiên
- note('');
- picksChanged();
- }
-
- function picksChanged() {
- renderGrid();
- renderPicked();
- window.dispatchEvent(new Event('lumreels:picked'));
- updateWhen();
- updateGo();
- }
-
- function renderPicked() {
- const box = $('#picked');
- if (!picks.length) {
- box.className = 'picked empty';
- box.textContent = multi ? t('picked.noneMulti', { max: MAX_PICK }) : t('picked.none');
- return;
- }
- if (!multi) {
- const x = picks[0];
- box.className = 'picked';
- const info = h('div', {}, h('div', { class: 't' }, srcBadge(x), ` ${shortId(x)} · ${x.name}`), h('div', { class: 'd', text: x.blurb || x.genre || '' }));
- if (srcOf(x) !== 'builtin') info.append(h('div', { class: 'd lock', text: t('pack.lockedNote') }));
- box.replaceChildren(...(x.thumb ? [h('img', { attrs: { src: x.thumb, alt: '' } })] : []), info);
- return;
- }
- box.className = 'picked multi';
- const strip = h('ul', { class: 'strip', attrs: { 'aria-label': t('picked.strip') } }, picks.map((x, i) => h('li', { class: 'pk', attrs: { title: `${x.id} · ${x.name}` } },
- x.thumb ? h('img', { attrs: { src: x.thumb, alt: '' } }) : h('span', { class: 'ph' }),
- h('span', { class: 'n', text: i + 1, attrs: { 'aria-hidden': 'true' } }),
- h('button', { class: 'rm', text: '×', data: { unpick: x.id }, attrs: { type: 'button', 'aria-label': t('picked.remove', { id: x.id, name: x.name }) } }))));
- box.replaceChildren(
- h('div', { class: 'pm-head' }, h('span', { class: 't', text: t('picked.count', { n: picks.length }) }),
- h('button', { class: 'mini', text: t('picked.clear'), data: { clear: 1 }, attrs: { type: 'button' } })),
- strip);
- }
-
- let viewing = null;
- function viewerDesc(x) {
- return (x.videoKind === 'demo' ? t('viewer.demo') : x.videoKind === 'ref' ? t('viewer.ref') : '') + (x.blurb || '');
- }
- function openViewer(id) {
- const x = templates.find((y) => y.id === id);
- if (!x) return;
- viewing = x;
- $('#vTitle').textContent = `${x.id} · ${x.name}`;
- $('#vDesc').textContent = viewerDesc(x);
- const v = $('#vVideo');
- v.hidden = !x.video;
- if (x.video) { v.src = x.video; v.play().catch(() => {}); }
- $('#viewer').showModal();
- }
- function closeViewer() { const v = $('#vVideo'); v.pause(); v.removeAttribute('src'); v.load(); $('#viewer').close(); viewing = null; }
-
- // ---------- form ----------
- function updateGo() {
- const n = $('#content').value.length;
- $('#chars').textContent = n;
- const enough = $('#content').value.trim().length >= 10;
- const dur = !!durS();
- const ok = picks.length > 0 && enough && dur;
- $('#go').disabled = !ok;
- $('#go').title = !picks.length ? t('go.needTpl') : !enough ? t('go.needText') : !dur ? t('go.badDur') : '';
- const rw = $('#rewrite');
- const many = picks.length > 1;
- rw.disabled = !ok || many || rwBusy;
- rw.title = rwBusy ? t('rw.busy') : !picks.length ? t('rw.needOne') : many ? t('rw.onlyOne') : !enough ? t('rw.needText') : !dur ? t('go.badDur') : '';
- rw.querySelector('span').textContent = t(rwBusy ? 'rw.btnBusy' : 'rw.btn');
- const hint = $('#rwHint');
- hint.classList.toggle('bad', many);
- hint.textContent = many ? t('rw.hintMany', { n: picks.length }) : t('rw.hint');
- }
-
- // ---------- thời lượng ----------
- function updateDur() {
- const r = parseDur($('#duration').value);
- $('#duration').setAttribute('aria-invalid', r.error ? 'true' : 'false');
- document.querySelectorAll('.pre').forEach((b) => b.classList.toggle('on', Number(b.dataset.dur) === r.s));
- const hint = $('#durHint');
- hint.classList.toggle('bad', !!r.error);
- hint.textContent = r.error ? r.error + '.' : r.s >= 60 ? t('dur.eqLong', { s: r.s, f: fmtDur(r.s) }) : t('dur.eq', { s: r.s });
- const warn = $('#durWarn');
- if (r.s > 60) {
- warn.hidden = false;
- warn.textContent = t('dur.warn', { f: fmtDur(r.s), range: fmtRange(r.s / 8 * 20, r.s / 8 * 60), scenes: Math.round(r.s / 8) });
- } else warn.hidden = true;
- updateGo();
- }
-
- // ---------- viết lại kịch bản ----------
- let rwBusy = false;
- let rwResult = null; // bản AI vừa viết, chưa dùng
- let rwUndo = null; // nội dung trước khi bấm "Dùng bản này"
- let rwView = null; // hàm vẽ lại ô kết quả (đổi ngôn ngữ thì gọi lại)
- function rwShow(cls, html) { const b = $('#rwBox'); b.className = 'rw ' + cls; b.innerHTML = html; b.hidden = !html; }
- function rwSet(fn) { rwView = fn; if (fn) fn(); else rwShow('', ''); }
- async function rewrite() {
- const selected = one();
- if (rwBusy || !selected) return;
- const dur = durS();
- rwBusy = true; rwResult = null;
- const btn = $('#rewrite');
- btn.classList.add('busy');
- updateGo();
- rwSet(() => rwShow('load', esc(t('rw.loading', { id: selected.id, d: fmtDur(dur) }))));
- const ctl = new AbortController();
- const timer = setTimeout(() => ctl.abort(), 100_000);
- try {
- const r = await fetch('/api/rewrite', {
- method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: ctl.signal,
- body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: dur }),
- });
- const j = await r.json().catch(() => ({}));
- if (!r.ok) throw new Error(j.error || t('err.status', { s: r.status }));
- rwResult = j;
- const eng = j.engine === 'api' ? 'Claude API' : 'Claude Code';
- const cost = j.usage?.costUSD != null ? ` · ≈ $${Number(j.usage.costUSD).toFixed(3)}` : '';
- rwSet(() => rwShow('', `<div class="rw-h"><span>${esc(t('rw.title', { id: j.templateId, d: fmtDur(j.durationS) }))}</span><span class="eng">${eng}${cost}</span></div>
- <pre id="rwScript">${esc(j.script)}</pre>
- ${j.notes ? `<div class="rw-n">${esc(j.notes)}</div>` : ''}
- ${j.fallbackFrom ? `<div class="rw-n">${esc(t('rw.fallback', { why: j.fallbackFrom }))}</div>` : ''}
- <div class="rw-a"><button type="button" class="use" data-rw="use">${esc(t('rw.use'))}</button><button type="button" data-rw="drop">${esc(t('rw.drop'))}</button></div>`));
- } catch (e) {
- const msg = e.name === 'AbortError' ? null : e.message;
- rwSet(() => rwShow('err-box', esc(msg ?? t('rw.timeout'))));
- } finally {
- clearTimeout(timer);
- rwBusy = false;
- btn.classList.remove('busy');
- updateGo();
- }
- }
- $('#rwBox').addEventListener('click', (e) => {
- const a = e.target.closest('[data-rw]')?.dataset.rw;
- if (!a) return;
- if (a === 'use' && rwResult) {
- rwUndo = $('#content').value;
- $('#content').value = rwResult.script.slice(0, 4000);
- rwResult = null;
- rwSet(() => rwShow('', `<div class="rw-h"><span>${esc(t('rw.replaced'))}</span></div><div class="rw-a"><button type="button" data-rw="undo">${esc(t('rw.undo'))}</button><button type="button" data-rw="close">${esc(t('rw.close'))}</button></div>`));
- } else if (a === 'undo' && rwUndo !== null) {
- $('#content').value = rwUndo; rwUndo = null;
- rwSet(null);
- } else { rwResult = null; rwSet(null); }
- updateGo();
- });
-
- async function submit() {
- $('#formErr').textContent = '';
- const btn = $('#go');
- 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(), 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' },
- body: JSON.stringify(batch ? { templateIds: picks.map((x) => x.id), ...common } : { templateId: picks[0].id, ...common }),
- });
- const j = await r.json();
- if (!r.ok) throw new Error(j.error || t('form.jobErr'));
- const created = batch ? j.jobs : [j];
- if (created.length > JOB_PAGE) showAll = true; // cả lô đều hiện trong danh sách
- await loadJobs();
- document.getElementById('job-' + created[0].id)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
- } catch (e) {
- $('#formErr').textContent = e.message + t('form.retry');
- } finally {
- btn.classList.remove('busy'); updateWhen(); updateGo();
- }
- }
-
- // ---------- jobs ----------
- async function loadJobs() {
- let jobs = [];
- try { jobs = await (await fetch('/api/jobs')).json(); } catch { return; }
- // log chi tiết cho job đang chạy
- allJobsCount = jobs.length;
- const detailed = await Promise.all(jobs.slice(0, showAll ? 60 : JOB_PAGE).map(async (j) =>
- (RUNNING.includes(j.status) || j.status === 'error' || j.status === 'waiting_agent')
- ? (await fetch('/api/jobs/' + j.id)).json().catch(() => j) : j));
- renderJobs(detailed);
- clearTimeout(pollTimer);
- if (jobs.some((j) => RUNNING.includes(j.status))) pollTimer = setTimeout(loadJobs, 2000);
- else if (jobs.some((j) => j.status === 'scheduled')) pollTimer = setTimeout(loadJobs, 10000);
- }
-
- function renderJobs(jobs) {
- const box = $('#jobs');
- if (!jobs.length) {
- box.innerHTML = `<div class="no-jobs">${t('jobs.empty')}</div>`;
- return;
- }
- // giữ video đang phát, không vẽ lại job không đổi (chữ ký có ngôn ngữ: đổi VI/EN thì vẽ lại chữ)
- const prev = new Map([...box.querySelectorAll('.job')].map((el) => [el.id, el.dataset.sig]));
- const rows = jobs.map((j) => {
- const sig = `${j.status}|${j.updatedAt}|${I.lang}`;
- if (prev.get('job-' + j.id) === sig && j.status === 'done') return null;
- return { id: j.id, sig, html: jobHtml(j) };
- });
- const frag = [];
- jobs.forEach((j, i) => {
- const h = rows[i];
- if (!h) frag.push(document.getElementById('job-' + j.id));
- else {
- const d = document.createElement('div'); d.innerHTML = h.html.trim(); const el = d.firstChild; el.dataset.sig = h.sig;
- // tên mẫu có thể là chữ của gói (L9): chỉ textContent
- const tt = el.querySelector('.tt'); if (tt) tt.textContent = t('job.tpl', { id: j.templateId, name: j.templateTitle || '' }) + (j.templateSource && j.templateSource !== 'builtin' ? ' · ' + t('src.' + (j.templateSource === 'local' ? 'local' : 'pack')) : '');
- frag.push(el);
- }
- });
- if (allJobsCount > frag.length) {
- const more = document.createElement('button');
- more.className = 'more'; more.type = 'button'; more.dataset.sig = 'more';
- more.textContent = showAll ? t('jobs.less') : t('jobs.more', { n: allJobsCount - frag.length });
- more.addEventListener('click', () => { showAll = !showAll; loadJobs(); });
- frag.push(more);
- } else if (showAll && allJobsCount > JOB_PAGE) {
- const less = document.createElement('button'); less.className = 'more'; less.type = 'button'; less.textContent = t('jobs.less');
- less.addEventListener('click', () => { showAll = false; loadJobs(); }); frag.push(less);
- }
- box.replaceChildren(...frag);
- }
-
- function jobHtml(j) {
- const running = RUNNING.includes(j.status);
- const media = j.links?.mp4
- ? `<video src="${j.links.mp4}" controls playsinline preload="metadata"></video>`
- : j.links?.preview ? `<img src="${j.links.preview}?v=${encodeURIComponent(j.updatedAt)}" alt="${esc(t('job.previewAlt'))}">`
- : `<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` : '';
- 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)} · ${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>` : ''}
- <div class="content">${esc(j.content)}</div>
- ${running && last ? `<div class="jid">${esc(last)}</div>` : ''}
- ${j.status === 'error' ? `<div class="errmsg">${esc(j.error || t('job.errUnknown'))}${esc(t('job.errTail'))}</div>` : ''}
- ${j.status === 'waiting_agent' ? `<div class="cmd">${esc(t('job.agent', { prompt: j.paths?.prompt, scene: j.paths?.scene, id: j.id }))}</div>` : ''}
- <div class="links">
- ${j.links?.mp4 ? `<a href="${j.links.mp4}" download>${esc(t('job.mp4'))}</a>` : ''}
- ${j.links?.preview ? `<a href="${j.links.preview}" target="_blank" rel="noopener">${esc(t('job.preview'))}</a>` : ''}
- <a href="${j.links?.prompt}" target="_blank" rel="noopener">Prompt</a>
- ${j.links?.brief ? `<a href="${j.links.brief}" target="_blank" rel="noopener">Brief</a>` : ''}
- ${j.status === 'done' && j.links?.mp4 ? `<button type="button" class="to-studio" data-studio="${j.id}">${esc(t('job.studio'))}</button>` : ''}
- ${['waiting_agent', 'error', 'done'].includes(j.status) ? `<button data-render="${j.id}">${esc(t(j.status === 'done' ? 'job.rerender' : 'job.render'))}</button>` : ''}
- <button type="button" class="log-btn${j.status === 'error' ? ' bad' : ''}" data-log-kind="job" data-log-id="${j.id}">${esc(t(j.status === 'error' ? 'log.btnErr' : 'log.btn'))}</button>
- </div>
- ${running && j.log?.length ? `<details class="log"><summary>${esc(t('job.log', { n: j.log.length }))}</summary><pre>${esc(j.log.join('\n'))}</pre></details>` : ''}
- </div>
- </article>`;
- }
-
- async function rerender(id) {
- await fetch(`/api/jobs/${id}/render`, { method: 'POST' });
- loadJobs();
- }
-
- // ---------- sự kiện ----------
- $('#grid').addEventListener('click', (e) => {
- const play = e.target.closest('[data-play]');
- if (play) { e.stopPropagation(); openViewer(play.dataset.play); return; }
- const card = e.target.closest('.tpl');
- if (card) pick(card.dataset.id);
- });
- $('#grid').addEventListener('keydown', (e) => {
- if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('tpl')) { e.preventDefault(); pick(e.target.dataset.id); }
- });
- $('#multiPick').addEventListener('change', (e) => setMulti(e.target.checked));
- $('#picked').addEventListener('click', (e) => {
- const rm = e.target.closest('[data-unpick]');
- if (rm) { unpick(rm.dataset.unpick); ($('#picked [data-unpick]') || $('#multiPick')).focus(); return; }
- if (e.target.closest('[data-clear]')) { picks = []; picksChanged(); $('#multiPick').focus(); }
- });
- $('#q').addEventListener('input', renderGrid);
- $('#readyOnly').addEventListener('change', renderGrid);
- function setChip(c) {
- cat = c.dataset.cat || '';
- srcFilter = c.dataset.src || '';
- document.querySelectorAll('.filters .chip').forEach((x) => { x.classList.toggle('on', x === c); x.setAttribute('aria-checked', x === c); });
- renderGrid();
- }
- document.querySelectorAll('.filters .chip').forEach((c) => c.addEventListener('click', () => setChip(c)));
- // packs-panel.js: cài/gỡ gói xong → tải lại lưới; "Xem trong lưới" → bật chip nguồn
- window.addEventListener('lumreels:packs', (e) => {
- const show = e.detail?.show;
- if (show) { const c = document.querySelector(`.filters .chip[data-src="${show === 'local' ? 'local' : 'pack'}"]`); if (c) setChip(c); }
- const removed = e.detail?.removed;
- if (removed) { picks = picks.filter((x) => !String(x.id).startsWith(removed + '/')); picksChanged(); }
- loadTemplates();
- });
- $('#content').addEventListener('input', updateGo);
- $('#rewrite').addEventListener('click', rewrite);
- $('#duration').addEventListener('input', updateDur);
- document.querySelectorAll('.pre').forEach((b) => b.addEventListener('click', () => { $('#duration').value = b.dataset.dur; updateDur(); }));
- $('#go').addEventListener('click', submit);
- $('#vClose').addEventListener('click', closeViewer);
- $('#viewer').addEventListener('cancel', (e) => { e.preventDefault(); closeViewer(); });
- $('#jobs').addEventListener('click', (e) => { const b = e.target.closest('[data-render]'); if (b) { b.disabled = true; rerender(b.dataset.render); } });
-
- function updateWhen() {
- const v = $('#runAt').value;
- const btn = $('#go').querySelector('span');
- if (!btn.closest('.busy')) btn.textContent = t(v ? 'go.schedule' : 'go.build', { n: picks.length });
- $('#clearAt').hidden = !v;
- }
- $('#runAt').addEventListener('input', updateWhen);
- $('#clearAt').addEventListener('click', () => { $('#runAt').value = ''; updateWhen(); });
- updateWhen();
-
- let cfg = {};
- const modeHint = () => {
- const m = $('#mode').value;
- $('#modeHint').textContent = {
- auto: t('mode.hintAuto', { m: modeLabel(cfg.autoResolves) || '…' }),
- api: t('mode.hintApi'),
- claude: t('mode.hintClaude'),
- manual: t('mode.hintManual'),
- }[m] + (cfg.outputDir ? t('mode.hintExport') : '');
- };
- $('#mode').addEventListener('change', modeHint);
- // Model: tự chọn = Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D (rẻ hơn, đủ tốt cho DOM/SVG/Canvas)
- const MODEL_NAME = { opus: 'Opus', sonnet: 'Sonnet', haiku: 'Haiku' };
- const heavy = (x) => (x?.technique || []).some((y) => /three|webgl|shader/i.test(y));
- function modelHint() {
- if (picks.length > 1) return modelHintMany();
- const selected = one();
- const m = $('#model').value;
- const rec = selected ? (heavy(selected) ? 'opus' : 'sonnet') : null;
- const recTxt = rec ? t('model.rec', { heavy: heavy(selected), m: MODEL_NAME[rec] }) : t('model.pickFirst');
- const opt = $('#model').querySelector('[value=auto]');
- opt.textContent = rec ? t('model.autoRec', { m: MODEL_NAME[rec] }) : t('model.auto');
- const warn = m === 'haiku' && rec === 'opus' ? t('model.haikuWarn') : m !== 'auto' && rec && m !== rec ? t('model.override', { m: MODEL_NAME[m] }) : '';
- $('#modelHint').textContent = recTxt + warn + t('model.agentNote');
- }
- // Nhiều mẫu: "3 mẫu 2D → Sonnet, 1 mẫu 3D/shader → Opus" (mỗi job tự chọn theo mẫu của nó).
- function modelHintMany() {
- const m = $('#model').value;
- const nHeavy = picks.filter(heavy).length, nLight = picks.length - nHeavy;
- $('#model').querySelector('[value=auto]').textContent = t('model.autoMany');
- const parts = [];
- if (nLight) parts.push(t('model.manyLight', { n: nLight, m: MODEL_NAME.sonnet }));
- if (nHeavy) parts.push(t('model.manyHeavy', { n: nHeavy, m: MODEL_NAME.opus }));
- const txt = m === 'auto' ? t('model.manyAuto', { parts: parts.join(', ') })
- : t('model.manyFixed', { n: picks.length, m: MODEL_NAME[m], parts: parts.join(', ') }) + (m === 'haiku' && nHeavy ? t('model.haikuWarnMany') : '');
- $('#modelHint').textContent = txt + t('model.agentNote');
- }
- $('#model').addEventListener('change', modelHint);
- window.addEventListener('lumreels:picked', modelHint);
- modelHint();
- function loadConfig(first) {
- return fetch('/api/config').then((r) => r.json()).then((c) => {
- cfg = c;
- if (first) $('#mode').value = c.defaultMode;
- $('#mode').querySelector('[value=claude]').disabled = !c.claudeAvailable;
- $('#mode').querySelector('[value=api]').disabled = !c.apiAvailable;
- if ($('#mode').selectedOptions[0]?.disabled) $('#mode').value = 'auto';
- modeHint();
- }).catch(() => {});
- }
- loadConfig(true);
- // doctor-panel.js: khoá vừa lưu/xoá → bật/tắt lại ô "Claude API"; vừa tạo job "Video đầu tiên" → nạp lại danh sách
- window.addEventListener('lumreels:config', () => loadConfig(false));
- window.addEventListener('lumreels:jobs-reload', () => loadJobs());
- // "Sửa nội dung trước" của thẻ Video đầu tiên: điền sẵn form (mẫu, nội dung, thời lượng, khung)
- window.addEventListener('lumreels:prefill', (e) => {
- const d = e.detail || {};
- if (multi) setMulti(false);
- if (d.templateId && !picks.some((x) => x.id === d.templateId)) pick(d.templateId);
- if (typeof d.content === 'string') { $('#content').value = d.content; $('#content').dispatchEvent(new Event('input', { bubbles: true })); }
- if (d.durationS) { $('#duration').value = String(d.durationS); $('#duration').dispatchEvent(new Event('input', { bubbles: true })); }
- if (d.ratio) setRatio(d.ratio);
- $('#content').focus();
- $('#content').scrollIntoView({ behavior: 'smooth', block: 'center' });
- });
-
- // Đổi VI/EN: vẽ lại mọi chữ do JS sinh (chữ tĩnh trong HTML đã được i18n.js đổi).
- window.addEventListener('lumreels:lang', () => {
- renderGrid();
- renderPicked();
- updateDur(); // gọi luôn updateGo
- updateWhen();
- 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ữ
- loadJobs();
- });
-
- // learn-panel.js vừa lưu 1 mẫu "Của tôi" → nạp lại danh sách, lọc Của tôi, chọn luôn mẫu đó
- window.addEventListener('lumreels:templates', async (e) => {
- await loadTemplates();
- const ref = e.detail?.pick;
- if (!ref) return;
- const chip = document.querySelector('.chip[data-cat="mine"]');
- if (chip) chip.click();
- if (multi) setMulti(false);
- pick(ref);
- document.querySelector(`#grid .tpl[data-id="${CSS.escape(ref)}"]`)?.scrollIntoView({ block: 'nearest' });
- });
-
- updateDur();
- setRatio(ratio);
- loadTemplates();
- loadJobs();
-})();
+// UI 1 trang: lưới mẫu, ô nội dung, danh sách job. Không framework. Chữ giao diện lấy từ i18n.js (window.I18N).
+(() => {
+ const $ = (s, el = document) => el.querySelector(s);
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ const I = window.I18N;
+ const t = (k, v) => I.t(k, v);
+ const status = (s) => (['scheduled', 'queued', 'generating', 'waiting_agent', 'previewing', 'rendering', 'done', 'error'].includes(s) ? t('st.' + s) : s);
+ const RUNNING = ['queued', 'generating', 'previewing', 'rendering'];
+ const CATS = ['faceless', 'ads', 'multi-style', 'viet-nam'];
+ const catName = (c) => (CATS.includes(c) ? t('cat.' + c) : c);
+ // Nhãn nguồn của mẫu (L13): gốc / của tôi (tự tạo) / cộng đồng (gói nhập). Chữ của gói chỉ vào textContent (L9).
+ const SOURCES = ['builtin', 'local', 'pack'];
+ const srcOf = (x) => (SOURCES.includes(x?.source) ? x.source : 'builtin');
+ const srcLabel = (x) => t('src.' + srcOf(x));
+ /** Tạo phần tử: props {class, text, attrs:{}, data:{}}; con là phần tử hoặc chuỗi (thành nút chữ). */
+ function h(tag, props = {}, ...kids) {
+ const el = document.createElement(tag);
+ if (props.class) el.className = props.class;
+ if (props.text != null) el.textContent = props.text;
+ for (const [k, v] of Object.entries(props.attrs || {})) if (v != null && v !== false) el.setAttribute(k, v === true ? '' : String(v));
+ for (const [k, v] of Object.entries(props.data || {})) el.dataset[k] = String(v);
+ for (const c of kids.flat()) if (c != null && c !== false) el.append(c instanceof Node ? c : document.createTextNode(String(c)));
+ return el;
+ }
+ const srcBadge = (x) => h('span', { class: 'src src-' + srcOf(x), text: srcLabel(x) });
+ const modeLabel = (m) => ({ auto: t('modeLabel.auto'), api: 'Claude API', claude: 'Claude Code', manual: t('modeLabel.manual') }[m]);
+ const fmtTime = (iso) => new Date(iso).toLocaleString(I.locale, { hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit', year: 'numeric' });
+ // datetime-local trả giờ máy không múi giờ → đổi sang ISO có múi giờ để server hiểu đúng.
+ const runAtValue = () => { const v = $('#runAt').value; return v ? new Date(v).toISOString() : undefined; };
+
+ // Thời lượng: số giây (90, 90s) hoặc phút:giây (1:30). Cùng luật với generator/jobs.mjs parseDuration.
+ const DUR_MIN = 3, DUR_MAX = 600;
+ function parseDur(v) {
+ const s0 = String(v ?? '').trim().toLowerCase().replace(/\s+/g, '');
+ if (!s0) return { error: t('dur.errEmpty') };
+ let m, s;
+ if ((m = /^(\d{1,4})(?:s|giây|giay)?$/.exec(s0))) s = Number(m[1]);
+ else if ((m = /^(\d{1,2}):([0-5]\d)$/.exec(s0))) s = Number(m[1]) * 60 + Number(m[2]);
+ else if ((m = /^(\d{1,2})(?:m|p|phút|phut)$/.exec(s0))) s = Number(m[1]) * 60;
+ else return { error: t('dur.errFmt') };
+ if (s < DUR_MIN) return { error: t('dur.errMin') };
+ if (s > DUR_MAX) return { error: t('dur.errMax') };
+ return { s };
+ }
+ const fmtDur = (s) => (s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`);
+ // Khoảng thời gian ước tính: "40–120 giây", "4–11 phút", "2–5 giờ"… (đơn vị theo đầu trên)
+ const dec = (x) => x.toFixed(1).replace('.', t('num.dec'));
+ const fmtRange = (a, b) => (b < 120 ? `${Math.round(a)}–${Math.round(b)} ${t('unit.sec')}`
+ : 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.
+ const MAX_PICK = 12;
+ let picks = [];
+ let multi = false;
+ const one = () => (picks.length === 1 ? picks[0] : null);
+ const pickIndex = (id) => picks.findIndex((x) => x.id === id);
+ let cat = '';
+ let srcFilter = ''; // '' | 'local' | 'pack' (chip "Của tôi" / "Cộng đồng")
+ let pollTimer = null;
+ const JOB_PAGE = 6;
+ let showAll = false;
+ let allJobsCount = 0;
+
+ // ---------- bản mới ----------
+ let update = null;
+ function renderUpdate() {
+ const box = $('#update-banner');
+ const u = update;
+ if (!box || !u) return;
+ const tx = box.querySelector('.ub-text');
+ tx.textContent = '';
+ // u.changes[0] là tiêu đề commit (dữ liệu git), giữ nguyên
+ tx.append(t('update.text', { n: u.behind, first: u.changes && u.changes[0] ? u.changes[0] : '' }));
+ const c = document.createElement('code'); c.textContent = 'npm start';
+ tx.append(c, t('update.after'));
+ }
+ async function checkVersion(retry = 3) {
+ let d;
+ try { d = await (await fetch('/api/version')).json(); } catch { return; }
+ const u = d && d.update;
+ if (!u) { if (retry > 0) setTimeout(() => checkVersion(retry - 1), 8000); return; }
+ const box = $('#update-banner');
+ if (!box || !u.ok || !u.behind) return;
+ const key = 'lumreels-hide-update-' + (u.upstream || '') + '-' + u.behind;
+ try { if (localStorage.getItem(key)) return; } catch { /* bỏ qua */ }
+ update = u;
+ renderUpdate();
+ box.hidden = false;
+ box.querySelector('.ub-close').onclick = () => { box.hidden = true; try { localStorage.setItem(key, '1'); } catch { /* bỏ qua */ } };
+ }
+ setTimeout(checkVersion, 1500);
+
+ // ---------- mẫu ----------
+ async function loadTemplates() {
+ templatesState = 'loading'; renderGrid();
+ try {
+ templates = await (await fetch('/api/templates')).json();
+ templatesState = 'ok';
+ } catch {
+ templatesState = 'error';
+ }
+ renderGrid();
+ }
+
+ // Mã hiện trên thẻ: mẫu gốc "045"; mẫu gói chỉ hiện slug (mã đầy đủ nằm trong aria-label / title).
+ const shortId = (x) => (srcOf(x) === 'builtin' ? x.id : String(x.id).split('/').pop());
+ const PLAY_SVG = 'M8 5v14l11-7z';
+ function playIcon() {
+ const ns = 'http://www.w3.org/2000/svg';
+ const svg = document.createElementNS(ns, 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true');
+ const path = document.createElementNS(ns, 'path'); path.setAttribute('d', PLAY_SVG); svg.append(path);
+ return svg;
+ }
+ function tplCard(x) {
+ const k = pickIndex(x.id);
+ const card = h('div', {
+ class: `tpl${x.hasGuidance ? '' : ' off'}${k >= 0 ? ' sel' : ''}`, data: { id: x.id },
+ attrs: { role: 'button', tabindex: 0, 'aria-disabled': String(!x.hasGuidance), 'aria-pressed': String(k >= 0),
+ 'aria-label': t('tpl.aria', { id: x.id, name: x.name, ready: x.hasGuidance, order: multi && k >= 0 ? k + 1 : 0 }) + ' · ' + srcLabel(x) },
+ });
+ if (multi && k >= 0) card.append(h('span', { class: 'order', text: k + 1, attrs: { 'aria-hidden': 'true' } }));
+ // x.thumb do server ghép từ id/slug đã kiểm (/thumbs/045.webp, /pack-thumbs/<gói>/template-<slug>.webp, /poster/…)
+ card.append(x.thumb ? h('img', { class: 'thumb', attrs: { src: x.thumb, alt: '', loading: 'lazy', decoding: 'async', width: 540, height: 960 } })
+ : h('div', { class: 'thumb ph', text: t('tpl.noThumb') }));
+ card.append(h('span', { class: 'badge' + (x.hasGuidance ? ' ready' : ''), text: t(x.hasGuidance ? 'tpl.ready' : 'tpl.noGuide') }));
+ if (x.video) {
+ const b = h('button', { class: 'play', data: { play: x.id }, attrs: { type: 'button', 'aria-label': t(x.videoKind === 'demo' ? 'tpl.playDemo' : 'tpl.playRef', { id: x.id }) } });
+ b.append(playIcon());
+ card.append(b);
+ }
+ card.append(h('div', { class: 'meta' },
+ h('div', { class: 'id' }, srcBadge(x), h('span', { text: `${shortId(x)} · ${catName(x.category)}` })),
+ h('div', { class: 't', text: x.name })));
+ if (srcOf(x) !== 'builtin') card.title = x.id;
+ return card;
+ }
+ function renderGrid() {
+ const grid = $('#grid');
+ if (templatesState !== 'ok') {
+ grid.replaceChildren(h('div', { class: 'empty-grid', text: t(templatesState === 'error' ? 'grid.loadErr' : 'grid.loading') }));
+ return;
+ }
+ const q = $('#q').value.trim().toLowerCase();
+ const readyOnly = $('#readyOnly').checked;
+ const list = templates.filter((x) => (!cat || x.category === cat) && (!srcFilter || srcOf(x) === srcFilter) && (!readyOnly || x.hasGuidance) &&
+ (!q || `${x.name} ${x.genre} ${x.blurb}`.toLowerCase().includes(q) || String(x.id).includes(q)));
+ const ready = templates.filter((x) => x.hasGuidance).length;
+ $('#tplCount').textContent = t('pick.count', { ready, total: templates.length });
+ if (!list.length) {
+ const empty = h('div', { class: 'empty-grid', text: t(srcFilter && !q ? 'grid.emptySrc.' + srcFilter : 'grid.empty') });
+ if (srcFilter && !q) empty.append(' ', h('button', { class: 'linkish', text: t('pack.importBtn'), data: { packImport: 1 }, attrs: { type: 'button' } }));
+ grid.replaceChildren(empty);
+ return;
+ }
+ const focusId = document.activeElement?.closest?.('#grid .tpl')?.dataset.id;
+ grid.classList.toggle('multi', multi);
+ grid.replaceChildren(...list.map(tplCard));
+ if (focusId) [...grid.querySelectorAll('.tpl')].find((el) => el.dataset.id === focusId)?.focus({ preventScroll: true });
+ }
+
+ // Báo nhẹ (tự ẩn), vd chọn quá 12 mẫu.
+ let noteTimer = null;
+ function note(msg) {
+ const el = $('#pickNote');
+ el.textContent = msg;
+ clearTimeout(noteTimer);
+ if (msg) noteTimer = setTimeout(() => { el.textContent = ''; }, 4000);
+ }
+
+ function pick(id) {
+ const x = templates.find((y) => y.id === id);
+ if (!x || !x.hasGuidance) return;
+ if (!multi) picks = [x];
+ else {
+ const k = pickIndex(id);
+ if (k >= 0) picks.splice(k, 1);
+ else if (picks.length >= MAX_PICK) { note(t('pick.max', { max: MAX_PICK })); return; }
+ else picks.push(x);
+ }
+ note('');
+ picksChanged();
+ }
+ function unpick(id) { const k = pickIndex(id); if (k >= 0) { picks.splice(k, 1); picksChanged(); } }
+ function setMulti(on) {
+ multi = on;
+ $('#multiPick').checked = on;
+ if (!on) picks = picks.slice(0, 1); // tắt: quay về chọn 1, giữ mẫu đầu tiên
+ note('');
+ picksChanged();
+ }
+
+ function picksChanged() {
+ renderGrid();
+ renderPicked();
+ window.dispatchEvent(new Event('lumreels:picked'));
+ updateWhen();
+ updateGo();
+ }
+
+ function renderPicked() {
+ const box = $('#picked');
+ if (!picks.length) {
+ box.className = 'picked empty';
+ box.textContent = multi ? t('picked.noneMulti', { max: MAX_PICK }) : t('picked.none');
+ return;
+ }
+ if (!multi) {
+ const x = picks[0];
+ box.className = 'picked';
+ const info = h('div', {}, h('div', { class: 't' }, srcBadge(x), ` ${shortId(x)} · ${x.name}`), h('div', { class: 'd', text: x.blurb || x.genre || '' }));
+ if (srcOf(x) !== 'builtin') info.append(h('div', { class: 'd lock', text: t('pack.lockedNote') }));
+ box.replaceChildren(...(x.thumb ? [h('img', { attrs: { src: x.thumb, alt: '' } })] : []), info);
+ return;
+ }
+ box.className = 'picked multi';
+ const strip = h('ul', { class: 'strip', attrs: { 'aria-label': t('picked.strip') } }, picks.map((x, i) => h('li', { class: 'pk', attrs: { title: `${x.id} · ${x.name}` } },
+ x.thumb ? h('img', { attrs: { src: x.thumb, alt: '' } }) : h('span', { class: 'ph' }),
+ h('span', { class: 'n', text: i + 1, attrs: { 'aria-hidden': 'true' } }),
+ h('button', { class: 'rm', text: '×', data: { unpick: x.id }, attrs: { type: 'button', 'aria-label': t('picked.remove', { id: x.id, name: x.name }) } }))));
+ box.replaceChildren(
+ h('div', { class: 'pm-head' }, h('span', { class: 't', text: t('picked.count', { n: picks.length }) }),
+ h('button', { class: 'mini', text: t('picked.clear'), data: { clear: 1 }, attrs: { type: 'button' } })),
+ strip);
+ }
+
+ let viewing = null;
+ function viewerDesc(x) {
+ return (x.videoKind === 'demo' ? t('viewer.demo') : x.videoKind === 'ref' ? t('viewer.ref') : '') + (x.blurb || '');
+ }
+ function openViewer(id) {
+ const x = templates.find((y) => y.id === id);
+ if (!x) return;
+ viewing = x;
+ $('#vTitle').textContent = `${x.id} · ${x.name}`;
+ $('#vDesc').textContent = viewerDesc(x);
+ const v = $('#vVideo');
+ v.hidden = !x.video;
+ if (x.video) { v.src = x.video; v.play().catch(() => {}); }
+ $('#viewer').showModal();
+ }
+ function closeViewer() { const v = $('#vVideo'); v.pause(); v.removeAttribute('src'); v.load(); $('#viewer').close(); viewing = null; }
+
+ // ---------- form ----------
+ function updateGo() {
+ const n = $('#content').value.length;
+ $('#chars').textContent = n;
+ const enough = $('#content').value.trim().length >= 10;
+ const dur = !!durS();
+ const ok = picks.length > 0 && enough && dur;
+ $('#go').disabled = !ok;
+ $('#go').title = !picks.length ? t('go.needTpl') : !enough ? t('go.needText') : !dur ? t('go.badDur') : '';
+ const rw = $('#rewrite');
+ const many = picks.length > 1;
+ rw.disabled = !ok || many || rwBusy;
+ rw.title = rwBusy ? t('rw.busy') : !picks.length ? t('rw.needOne') : many ? t('rw.onlyOne') : !enough ? t('rw.needText') : !dur ? t('go.badDur') : '';
+ rw.querySelector('span').textContent = t(rwBusy ? 'rw.btnBusy' : 'rw.btn');
+ const hint = $('#rwHint');
+ hint.classList.toggle('bad', many);
+ hint.textContent = many ? t('rw.hintMany', { n: picks.length }) : t('rw.hint');
+ }
+
+ // ---------- thời lượng ----------
+ function updateDur() {
+ const r = parseDur($('#duration').value);
+ $('#duration').setAttribute('aria-invalid', r.error ? 'true' : 'false');
+ document.querySelectorAll('.pre').forEach((b) => b.classList.toggle('on', Number(b.dataset.dur) === r.s));
+ const hint = $('#durHint');
+ hint.classList.toggle('bad', !!r.error);
+ hint.textContent = r.error ? r.error + '.' : r.s >= 60 ? t('dur.eqLong', { s: r.s, f: fmtDur(r.s) }) : t('dur.eq', { s: r.s });
+ const warn = $('#durWarn');
+ if (r.s > 60) {
+ warn.hidden = false;
+ warn.textContent = t('dur.warn', { f: fmtDur(r.s), range: fmtRange(r.s / 8 * 20, r.s / 8 * 60), scenes: Math.round(r.s / 8) });
+ } else warn.hidden = true;
+ updateGo();
+ }
+
+ // ---------- viết lại kịch bản ----------
+ let rwBusy = false;
+ let rwResult = null; // bản AI vừa viết, chưa dùng
+ let rwUndo = null; // nội dung trước khi bấm "Dùng bản này"
+ let rwView = null; // hàm vẽ lại ô kết quả (đổi ngôn ngữ thì gọi lại)
+ function rwShow(cls, html) { const b = $('#rwBox'); b.className = 'rw ' + cls; b.innerHTML = html; b.hidden = !html; }
+ function rwSet(fn) { rwView = fn; if (fn) fn(); else rwShow('', ''); }
+ async function rewrite() {
+ const selected = one();
+ if (rwBusy || !selected) return;
+ const dur = durS();
+ rwBusy = true; rwResult = null;
+ const btn = $('#rewrite');
+ btn.classList.add('busy');
+ updateGo();
+ rwSet(() => rwShow('load', esc(t('rw.loading', { id: selected.id, d: fmtDur(dur) }))));
+ const ctl = new AbortController();
+ const timer = setTimeout(() => ctl.abort(), 100_000);
+ try {
+ const r = await fetch('/api/rewrite', {
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: ctl.signal,
+ body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: dur }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error || t('err.status', { s: r.status }));
+ rwResult = j;
+ const eng = j.engine === 'api' ? 'Claude API' : 'Claude Code';
+ const cost = j.usage?.costUSD != null ? ` · ≈ $${Number(j.usage.costUSD).toFixed(3)}` : '';
+ rwSet(() => rwShow('', `<div class="rw-h"><span>${esc(t('rw.title', { id: j.templateId, d: fmtDur(j.durationS) }))}</span><span class="eng">${eng}${cost}</span></div>
+ <pre id="rwScript">${esc(j.script)}</pre>
+ ${j.notes ? `<div class="rw-n">${esc(j.notes)}</div>` : ''}
+ ${j.fallbackFrom ? `<div class="rw-n">${esc(t('rw.fallback', { why: j.fallbackFrom }))}</div>` : ''}
+ <div class="rw-a"><button type="button" class="use" data-rw="use">${esc(t('rw.use'))}</button><button type="button" data-rw="drop">${esc(t('rw.drop'))}</button></div>`));
+ } catch (e) {
+ const msg = e.name === 'AbortError' ? null : e.message;
+ rwSet(() => rwShow('err-box', esc(msg ?? t('rw.timeout'))));
+ } finally {
+ clearTimeout(timer);
+ rwBusy = false;
+ btn.classList.remove('busy');
+ updateGo();
+ }
+ }
+ $('#rwBox').addEventListener('click', (e) => {
+ const a = e.target.closest('[data-rw]')?.dataset.rw;
+ if (!a) return;
+ if (a === 'use' && rwResult) {
+ rwUndo = $('#content').value;
+ $('#content').value = rwResult.script.slice(0, 4000);
+ rwResult = null;
+ rwSet(() => rwShow('', `<div class="rw-h"><span>${esc(t('rw.replaced'))}</span></div><div class="rw-a"><button type="button" data-rw="undo">${esc(t('rw.undo'))}</button><button type="button" data-rw="close">${esc(t('rw.close'))}</button></div>`));
+ } else if (a === 'undo' && rwUndo !== null) {
+ $('#content').value = rwUndo; rwUndo = null;
+ rwSet(null);
+ } else { rwResult = null; rwSet(null); }
+ updateGo();
+ });
+
+ async function submit() {
+ $('#formErr').textContent = '';
+ const btn = $('#go');
+ 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(), 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' },
+ body: JSON.stringify(batch ? { templateIds: picks.map((x) => x.id), ...common } : { templateId: picks[0].id, ...common }),
+ });
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error || t('form.jobErr'));
+ const created = batch ? j.jobs : [j];
+ if (created.length > JOB_PAGE) showAll = true; // cả lô đều hiện trong danh sách
+ await loadJobs();
+ document.getElementById('job-' + created[0].id)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ } catch (e) {
+ $('#formErr').textContent = e.message + t('form.retry');
+ } finally {
+ btn.classList.remove('busy'); updateWhen(); updateGo();
+ }
+ }
+
+ // ---------- jobs ----------
+ async function loadJobs() {
+ let jobs = [];
+ try { jobs = await (await fetch('/api/jobs')).json(); } catch { return; }
+ // log chi tiết cho job đang chạy
+ allJobsCount = jobs.length;
+ const detailed = await Promise.all(jobs.slice(0, showAll ? 60 : JOB_PAGE).map(async (j) =>
+ (RUNNING.includes(j.status) || j.status === 'error' || j.status === 'waiting_agent')
+ ? (await fetch('/api/jobs/' + j.id)).json().catch(() => j) : j));
+ renderJobs(detailed);
+ clearTimeout(pollTimer);
+ if (jobs.some((j) => RUNNING.includes(j.status))) pollTimer = setTimeout(loadJobs, 2000);
+ else if (jobs.some((j) => j.status === 'scheduled')) pollTimer = setTimeout(loadJobs, 10000);
+ }
+
+ function renderJobs(jobs) {
+ const box = $('#jobs');
+ if (!jobs.length) {
+ box.innerHTML = `<div class="no-jobs">${t('jobs.empty')}</div>`;
+ return;
+ }
+ // giữ video đang phát, không vẽ lại job không đổi (chữ ký có ngôn ngữ: đổi VI/EN thì vẽ lại chữ)
+ const prev = new Map([...box.querySelectorAll('.job')].map((el) => [el.id, el.dataset.sig]));
+ const rows = jobs.map((j) => {
+ const sig = `${j.status}|${j.updatedAt}|${I.lang}`;
+ if (prev.get('job-' + j.id) === sig && j.status === 'done') return null;
+ return { id: j.id, sig, html: jobHtml(j) };
+ });
+ const frag = [];
+ jobs.forEach((j, i) => {
+ const h = rows[i];
+ if (!h) frag.push(document.getElementById('job-' + j.id));
+ else {
+ const d = document.createElement('div'); d.innerHTML = h.html.trim(); const el = d.firstChild; el.dataset.sig = h.sig;
+ // tên mẫu có thể là chữ của gói (L9): chỉ textContent
+ const tt = el.querySelector('.tt'); if (tt) tt.textContent = t('job.tpl', { id: j.templateId, name: j.templateTitle || '' }) + (j.templateSource && j.templateSource !== 'builtin' ? ' · ' + t('src.' + (j.templateSource === 'local' ? 'local' : 'pack')) : '');
+ frag.push(el);
+ }
+ });
+ if (allJobsCount > frag.length) {
+ const more = document.createElement('button');
+ more.className = 'more'; more.type = 'button'; more.dataset.sig = 'more';
+ more.textContent = showAll ? t('jobs.less') : t('jobs.more', { n: allJobsCount - frag.length });
+ more.addEventListener('click', () => { showAll = !showAll; loadJobs(); });
+ frag.push(more);
+ } else if (showAll && allJobsCount > JOB_PAGE) {
+ const less = document.createElement('button'); less.className = 'more'; less.type = 'button'; less.textContent = t('jobs.less');
+ less.addEventListener('click', () => { showAll = false; loadJobs(); }); frag.push(less);
+ }
+ box.replaceChildren(...frag);
+ }
+
+ function jobHtml(j) {
+ const running = RUNNING.includes(j.status);
+ const media = j.links?.mp4
+ ? `<video src="${j.links.mp4}" controls playsinline preload="metadata"></video>`
+ : j.links?.preview ? `<img src="${j.links.preview}?v=${encodeURIComponent(j.updatedAt)}" alt="${esc(t('job.previewAlt'))}">`
+ : `<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` : '';
+ 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)} · ${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>` : ''}
+ <div class="content">${esc(j.content)}</div>
+ ${running && last ? `<div class="jid">${esc(last)}</div>` : ''}
+ ${j.status === 'error' ? `<div class="errmsg">${esc(j.error || t('job.errUnknown'))}${esc(t('job.errTail'))}</div>` : ''}
+ ${j.status === 'waiting_agent' ? `<div class="cmd">${esc(t('job.agent', { prompt: j.paths?.prompt, scene: j.paths?.scene, id: j.id }))}</div>` : ''}
+ <div class="links">
+ ${j.links?.mp4 ? `<a href="${j.links.mp4}" download>${esc(t('job.mp4'))}</a>` : ''}
+ ${j.links?.preview ? `<a href="${j.links.preview}" target="_blank" rel="noopener">${esc(t('job.preview'))}</a>` : ''}
+ <a href="${j.links?.prompt}" target="_blank" rel="noopener">Prompt</a>
+ ${j.links?.brief ? `<a href="${j.links.brief}" target="_blank" rel="noopener">Brief</a>` : ''}
+ ${j.status === 'done' && j.links?.mp4 ? `<button type="button" class="to-studio" data-studio="${j.id}">${esc(t('job.studio'))}</button>` : ''}
+ ${['waiting_agent', 'error', 'done'].includes(j.status) ? `<button data-render="${j.id}">${esc(t(j.status === 'done' ? 'job.rerender' : 'job.render'))}</button>` : ''}
+ <button type="button" class="log-btn${j.status === 'error' ? ' bad' : ''}" data-log-kind="job" data-log-id="${j.id}">${esc(t(j.status === 'error' ? 'log.btnErr' : 'log.btn'))}</button>
+ </div>
+ ${running && j.log?.length ? `<details class="log"><summary>${esc(t('job.log', { n: j.log.length }))}</summary><pre>${esc(j.log.join('\n'))}</pre></details>` : ''}
+ </div>
+ </article>`;
+ }
+
+ async function rerender(id) {
+ await fetch(`/api/jobs/${id}/render`, { method: 'POST' });
+ loadJobs();
+ }
+
+ // ---------- sự kiện ----------
+ $('#grid').addEventListener('click', (e) => {
+ const play = e.target.closest('[data-play]');
+ if (play) { e.stopPropagation(); openViewer(play.dataset.play); return; }
+ const card = e.target.closest('.tpl');
+ if (card) pick(card.dataset.id);
+ });
+ $('#grid').addEventListener('keydown', (e) => {
+ if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('tpl')) { e.preventDefault(); pick(e.target.dataset.id); }
+ });
+ $('#multiPick').addEventListener('change', (e) => setMulti(e.target.checked));
+ $('#picked').addEventListener('click', (e) => {
+ const rm = e.target.closest('[data-unpick]');
+ if (rm) { unpick(rm.dataset.unpick); ($('#picked [data-unpick]') || $('#multiPick')).focus(); return; }
+ if (e.target.closest('[data-clear]')) { picks = []; picksChanged(); $('#multiPick').focus(); }
+ });
+ $('#q').addEventListener('input', renderGrid);
+ $('#readyOnly').addEventListener('change', renderGrid);
+ function setChip(c) {
+ cat = c.dataset.cat || '';
+ srcFilter = c.dataset.src || '';
+ document.querySelectorAll('.filters .chip').forEach((x) => { x.classList.toggle('on', x === c); x.setAttribute('aria-checked', x === c); });
+ renderGrid();
+ }
+ document.querySelectorAll('.filters .chip').forEach((c) => c.addEventListener('click', () => setChip(c)));
+ // packs-panel.js: cài/gỡ gói xong → tải lại lưới; "Xem trong lưới" → bật chip nguồn
+ window.addEventListener('lumreels:packs', (e) => {
+ const show = e.detail?.show;
+ if (show) { const c = document.querySelector(`.filters .chip[data-src="${show === 'local' ? 'local' : 'pack'}"]`); if (c) setChip(c); }
+ const removed = e.detail?.removed;
+ if (removed) { picks = picks.filter((x) => !String(x.id).startsWith(removed + '/')); picksChanged(); }
+ loadTemplates();
+ });
+ $('#content').addEventListener('input', updateGo);
+ $('#rewrite').addEventListener('click', rewrite);
+ $('#duration').addEventListener('input', updateDur);
+ document.querySelectorAll('.pre').forEach((b) => b.addEventListener('click', () => { $('#duration').value = b.dataset.dur; updateDur(); }));
+ $('#go').addEventListener('click', submit);
+ $('#vClose').addEventListener('click', closeViewer);
+ $('#viewer').addEventListener('cancel', (e) => { e.preventDefault(); closeViewer(); });
+ $('#jobs').addEventListener('click', (e) => { const b = e.target.closest('[data-render]'); if (b) { b.disabled = true; rerender(b.dataset.render); } });
+
+ function updateWhen() {
+ const v = $('#runAt').value;
+ const btn = $('#go').querySelector('span');
+ if (!btn.closest('.busy')) btn.textContent = t(v ? 'go.schedule' : 'go.build', { n: picks.length });
+ $('#clearAt').hidden = !v;
+ }
+ $('#runAt').addEventListener('input', updateWhen);
+ $('#clearAt').addEventListener('click', () => { $('#runAt').value = ''; updateWhen(); });
+ updateWhen();
+
+ let cfg = {};
+ const modeHint = () => {
+ const m = $('#mode').value;
+ $('#modeHint').textContent = {
+ auto: t('mode.hintAuto', { m: modeLabel(cfg.autoResolves) || '…' }),
+ api: t('mode.hintApi'),
+ claude: t('mode.hintClaude'),
+ manual: t('mode.hintManual'),
+ }[m] + (cfg.outputDir ? t('mode.hintExport') : '');
+ };
+ $('#mode').addEventListener('change', modeHint);
+ // Model: tự chọn = Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D (rẻ hơn, đủ tốt cho DOM/SVG/Canvas)
+ const MODEL_NAME = { opus: 'Opus', sonnet: 'Sonnet', haiku: 'Haiku' };
+ const heavy = (x) => (x?.technique || []).some((y) => /three|webgl|shader/i.test(y));
+ function modelHint() {
+ if (picks.length > 1) return modelHintMany();
+ const selected = one();
+ const m = $('#model').value;
+ const rec = selected ? (heavy(selected) ? 'opus' : 'sonnet') : null;
+ const recTxt = rec ? t('model.rec', { heavy: heavy(selected), m: MODEL_NAME[rec] }) : t('model.pickFirst');
+ const opt = $('#model').querySelector('[value=auto]');
+ opt.textContent = rec ? t('model.autoRec', { m: MODEL_NAME[rec] }) : t('model.auto');
+ const warn = m === 'haiku' && rec === 'opus' ? t('model.haikuWarn') : m !== 'auto' && rec && m !== rec ? t('model.override', { m: MODEL_NAME[m] }) : '';
+ $('#modelHint').textContent = recTxt + warn + t('model.agentNote');
+ }
+ // Nhiều mẫu: "3 mẫu 2D → Sonnet, 1 mẫu 3D/shader → Opus" (mỗi job tự chọn theo mẫu của nó).
+ function modelHintMany() {
+ const m = $('#model').value;
+ const nHeavy = picks.filter(heavy).length, nLight = picks.length - nHeavy;
+ $('#model').querySelector('[value=auto]').textContent = t('model.autoMany');
+ const parts = [];
+ if (nLight) parts.push(t('model.manyLight', { n: nLight, m: MODEL_NAME.sonnet }));
+ if (nHeavy) parts.push(t('model.manyHeavy', { n: nHeavy, m: MODEL_NAME.opus }));
+ const txt = m === 'auto' ? t('model.manyAuto', { parts: parts.join(', ') })
+ : t('model.manyFixed', { n: picks.length, m: MODEL_NAME[m], parts: parts.join(', ') }) + (m === 'haiku' && nHeavy ? t('model.haikuWarnMany') : '');
+ $('#modelHint').textContent = txt + t('model.agentNote');
+ }
+ $('#model').addEventListener('change', modelHint);
+ window.addEventListener('lumreels:picked', modelHint);
+ modelHint();
+ function loadConfig(first) {
+ return fetch('/api/config').then((r) => r.json()).then((c) => {
+ cfg = c;
+ if (first) $('#mode').value = c.defaultMode;
+ $('#mode').querySelector('[value=claude]').disabled = !c.claudeAvailable;
+ $('#mode').querySelector('[value=api]').disabled = !c.apiAvailable;
+ if ($('#mode').selectedOptions[0]?.disabled) $('#mode').value = 'auto';
+ modeHint();
+ }).catch(() => {});
+ }
+ loadConfig(true);
+ // doctor-panel.js: khoá vừa lưu/xoá → bật/tắt lại ô "Claude API"; vừa tạo job "Video đầu tiên" → nạp lại danh sách
+ window.addEventListener('lumreels:config', () => loadConfig(false));
+ window.addEventListener('lumreels:jobs-reload', () => loadJobs());
+ // "Sửa nội dung trước" của thẻ Video đầu tiên: điền sẵn form (mẫu, nội dung, thời lượng, khung)
+ window.addEventListener('lumreels:prefill', (e) => {
+ const d = e.detail || {};
+ if (multi) setMulti(false);
+ if (d.templateId && !picks.some((x) => x.id === d.templateId)) pick(d.templateId);
+ if (typeof d.content === 'string') { $('#content').value = d.content; $('#content').dispatchEvent(new Event('input', { bubbles: true })); }
+ if (d.durationS) { $('#duration').value = String(d.durationS); $('#duration').dispatchEvent(new Event('input', { bubbles: true })); }
+ if (d.ratio) setRatio(d.ratio);
+ $('#content').focus();
+ $('#content').scrollIntoView({ behavior: 'smooth', block: 'center' });
+ });
+
+ // Đổi VI/EN: vẽ lại mọi chữ do JS sinh (chữ tĩnh trong HTML đã được i18n.js đổi).
+ window.addEventListener('lumreels:lang', () => {
+ renderGrid();
+ renderPicked();
+ updateDur(); // gọi luôn updateGo
+ updateWhen();
+ 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ữ
+ loadJobs();
+ });
+
+ // learn-panel.js vừa lưu 1 mẫu "Của tôi" → nạp lại danh sách, lọc Của tôi, chọn luôn mẫu đó
+ window.addEventListener('lumreels:templates', async (e) => {
+ await loadTemplates();
+ const ref = e.detail?.pick;
+ if (!ref) return;
+ const chip = document.querySelector('.chip[data-cat="mine"]');
+ if (chip) chip.click();
+ if (multi) setMulti(false);
+ pick(ref);
+ document.querySelector(`#grid .tpl[data-id="${CSS.escape(ref)}"]`)?.scrollIntoView({ block: 'nearest' });
+ });
+
+ updateDur();
+ setRatio(ratio);
+ loadTemplates();
+ loadJobs();
+})();
diff --git a/server/public/i18n.js b/server/public/i18n.js
index 2bbaaf3..7472f14 100644
--- a/server/public/i18n.js
+++ b/server/public/i18n.js
@@ -1,1702 +1,1702 @@
-// Ngôn ngữ giao diện VI / EN. Chỉ dịch chữ giao diện; tên mẫu, nội dung người dùng, lỗi server giữ nguyên.
-// HTML: data-i18n (textContent), data-i18n-placeholder, data-i18n-aria (aria-label).
-// JS: window.I18N.t(key, vars) · I18N.lang · I18N.set('vi'|'en') · I18N.srv(chuỗi server) · sự kiện window 'lumreels:lang'.
-// Giá trị trong bảng là chuỗi (thay {tên}) hoặc hàm (vars) => chuỗi (dùng cho số nhiều).
-(() => {
- 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, 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)',
-
- 'update.hide': 'Ẩn thông báo',
- 'update.text': (v) => `Có ${v.n} cập nhật mới cho LumReels${v.first ? ` (${v.first}${v.n > 1 ? ', …' : ''})` : ''}. Tắt app rồi chạy lại `,
- 'update.after': ' để cập nhật.',
-
- 'tabs.aria': 'Chế độ',
- 'tabs.tpl': 'Dựng từ mẫu',
- 'tabs.edit': 'Edit video của bạn',
- 'tabs.new': 'MỚI',
-
- 'pick.h': 'Chọn mẫu',
- 'pick.searchLabel': 'Tìm mẫu theo tên',
- 'pick.searchPh': 'Tìm theo tên, thể loại…',
- 'pick.chipsAria': 'Lọc theo nhóm',
- 'cat.all': 'Tất cả',
- 'cat.faceless': 'Faceless',
- 'cat.ads': 'Quảng cáo',
- 'cat.multi-style': 'Đa phong cách',
- 'cat.viet-nam': 'Việt Nam hoá',
- 'pick.readyOnly': 'Chỉ mẫu dùng được',
- 'pick.multi': 'Chọn nhiều mẫu',
- 'pick.multiHint': 'Bật lên thì bấm mẫu để chọn hoặc bỏ, tối đa 12 mẫu, mỗi mẫu ra 1 video cùng nội dung.',
- 'pick.count': '{ready}/{total} mẫu dùng được',
- 'pick.max': 'Tối đa {max} mẫu mỗi lần dựng. Bỏ bớt 1 mẫu rồi chọn tiếp.',
- 'grid.loading': 'Đang tải mẫu…',
- 'grid.loadErr': 'Không tải được danh sách mẫu. Kiểm tra server rồi tải lại trang.',
- 'grid.empty': 'Không có mẫu khớp. Thử bỏ lọc hoặc đổi từ khoá.',
- 'tpl.aria': (v) => `Mẫu ${v.id}: ${v.name}${v.ready ? '' : ' (chưa có guidance, chưa dùng được)'}${v.order ? `, đã chọn thứ ${v.order}` : ''}`,
- 'tpl.noThumb': 'chưa có ảnh',
- 'tpl.ready': 'Sẵn sàng',
- 'tpl.noGuide': 'Chưa có guidance',
- 'tpl.playDemo': 'Xem video demo mẫu {id}',
- 'tpl.playRef': 'Xem video tham chiếu mẫu {id}',
- // ---- gói mẫu (.lumpack) ----
- 'src.builtin': 'Gốc',
- 'src.local': 'Của tôi',
- 'src.pack': 'Cộng đồng',
- 'grid.emptySrc.local': 'Chưa có mẫu "Của tôi". Mẫu tự tạo hoặc nhập từ gói của bạn sẽ hiện ở đây.',
- 'grid.emptySrc.pack': 'Chưa cài gói cộng đồng nào.',
- 'pack.importBtn': 'Nhập gói',
- 'pack.mineBtn': 'Gói của tôi',
- 'pack.lockedNote': 'Mẫu ngoài chạy ở chế độ khoá: AI chỉ đọc/ghi trong thư mục của video này.',
- 'kind.template': 'Mẫu dựng',
- 'kind.edit-style': 'Cách dựng Edit',
- 'prov.original': 'Tự sáng tác',
- 'prov.own-video': 'Học từ video của chính tác giả',
- 'prov.style-study': 'Học phong cách từ video khác',
- 'pk.title': 'Nhập gói mẫu',
- 'pk.close': 'Đóng',
- 'pk.dropBig': 'Chọn file .lumpack',
- 'pk.dropSmall': 'hoặc kéo thả vào đây · tối đa 12 MB · xem trước rồi mới cài',
- 'pk.reading': 'Đang đọc và kiểm gói…',
- 'pk.restricted': 'Mẫu cộng đồng chạy ở chế độ khoá: AI chỉ đọc/ghi trong thư mục của video này.',
- 'pk.noName': '(không tên)',
- 'pk.author': 'Tác giả',
- 'pk.contact': 'Liên hệ',
- 'pk.license': 'Giấy phép',
- 'pk.provenance': 'Nguồn gốc',
- 'pk.id': 'Mã gói',
- 'pk.engine': 'Cần LumReels',
- 'pk.items': 'Số mục',
- 'pk.sha': 'Mã kiểm (sha256)',
- 'pk.warnHead': (v) => `${v.n} mục có chữ cần đọc kỹ (tô vàng bên dưới). Chữ này không bị chặn, nhưng nên đọc trước khi cài.`,
- 'pk.warnItem': 'cần đọc kỹ',
- 'pk.showText': 'Xem nguyên văn',
- 'pk.err.not-pack': 'File này không phải gói LumReels (.lumpack).',
- 'pk.err.tooBig': 'File lớn hơn 12 MB.',
- 'pk.err.engine': 'Gói này cần bản LumReels mới hơn. Cập nhật app rồi nhập lại.',
- 'pk.err.rejected': 'Gói bị từ chối: nội dung không an toàn hoặc sai định dạng.',
- 'pk.err.first': 'Lý do đầu tiên: {e}',
- 'pk.err.more': 'Xem tất cả lỗi ({n})',
- 'pk.err.expired': 'Bản xem trước đã hết hạn (10 phút). Chọn lại file.',
- 'pk.err.net': 'Không gửi được tới app. Kiểm tra app còn chạy rồi thử lại.',
- 'pk.st.installed': 'Gói này (bản {v}) đã cài rồi.',
- 'pk.st.conflict': 'Đã cài {id} bản {v}, nhưng nội dung khác bản này: không cài đè được.',
- 'pk.st.older': 'Máy đang có bản mới hơn ({v}).',
- 'pk.st.upgrade': 'Máy đang có bản {v}.',
- 'pk.replace': 'Thay bằng bản {v}',
- 'pk.cancel': 'Huỷ',
- 'pk.other': 'Chọn file khác',
- 'pk.install': 'Cài',
- 'pk.installing': 'Đang cài…',
- 'pk.done': (v) => `Đã cài "${v.name}": ${v.n} mục. Mẫu hiện trong lưới với nhãn Cộng đồng.`,
- 'pk.showGrid': 'Xem trong lưới',
- 'mp.title': 'Gói của tôi',
- 'mp.loading': 'Đang tải…',
- 'mp.loadErr': 'Không tải được danh sách gói.',
- 'mp.retry': 'Thử lại',
- 'mp.empty': 'Chưa cài gói nào. Bấm Nhập gói để thêm mẫu từ file .lumpack.',
- 'mp.items': '{n} mục',
- 'mp.view': 'Xem',
- 'mp.hide': 'Ẩn',
- 'mp.verified': 'Đã duyệt',
- 'mp.remove': 'Gỡ',
- 'mp.removeQ': 'Gỡ gói "{name}"? Video đã dựng bằng gói này vẫn giữ nguyên.',
- 'mp.removeYes': 'Gỡ gói',
- 'mp.removed': 'Đã gỡ "{name}".',
- 'mp.deleted': 'Đã xoá "{name}".',
- 'mp.delItem': 'Xoá',
- 'mp.delItemQ': 'Xoá "{name}" khỏi mẫu của tôi? Không lấy lại được.',
- 'mp.export': 'Xuất gói',
- 'ex.title': 'Xuất mẫu "Của tôi" ra file .lumpack',
- 'ex.none': 'Chưa có mẫu "Của tôi" để xuất. Mẫu tự tạo (nút Tạo mẫu, sắp có) sẽ hiện ở đây.',
- 'ex.pick': 'Chọn mục',
- 'ex.name': 'Tên gói',
- 'ex.id': 'Mã gói',
- 'ex.idHint': 'Dạng tac-gia.ten-goi: chữ thường không dấu, số, gạch nối. Tự điền theo tác giả + tên.',
- 'ex.author': 'Tác giả',
- 'ex.contact': 'Liên hệ (không bắt buộc)',
- 'ex.license': 'Giấy phép',
- 'ex.version': 'Phiên bản',
- 'ex.go': 'Tải file .lumpack',
- 'ex.busy': 'Đang xuất…',
- 'ex.ok': 'Đã xuất {file} ({kb}).',
- 'ex.err.items': 'Chọn ít nhất 1 mục để xuất.',
- 'ex.err.name': 'Điền tên gói.',
- 'ex.err.author': 'Điền tên tác giả.',
- 'ex.err.id': 'Mã gói phải dạng tac-gia.ten-goi, mỗi nửa 2–24 ký tự.',
- 'ex.err.ver': 'Phiên bản phải dạng 1.0.0.',
- 'ex.err.reserved': 'Tên tác giả này dành riêng cho LumReels. Đổi phần trước dấu chấm của mã gói.',
-
- 'picked.none': 'Chưa chọn mẫu. Bấm 1 mẫu sáng màu bên trái.',
- 'picked.noneMulti': 'Đang chọn nhiều: bấm các mẫu sáng màu bên trái (tối đa {max}), mỗi mẫu ra 1 video.',
- 'picked.count': 'Đã chọn {n} mẫu',
- 'picked.clear': 'Bỏ chọn hết',
- 'picked.strip': 'Các mẫu đã chọn',
- 'picked.remove': 'Bỏ mẫu {id}: {name}',
-
- 'viewer.aria': 'Video minh hoạ của mẫu',
- 'viewer.close': 'Đóng',
- 'viewer.demo': 'Video demo dựng bằng LumReels. ',
- 'viewer.ref': 'Video tham chiếu trên máy mày (không có trong repo). ',
-
- 'compose.h': 'Nội dung',
- 'compose.label': 'Nội dung video',
- 'compose.ph': 'Ví dụ: Mỗi tháng bỏ 3 triệu vào quỹ chỉ số, lãi giả định 10%/năm, sau 20 năm có bao nhiêu? Kênh: Lumfin. CTA: Theo dõi để biết thêm mẹo tiền',
- 'compose.charsTail': '/4000 ký tự · ghi luôn tên kênh và CTA nếu có',
- 'rw.btn': 'Viết lại kịch bản',
- 'rw.btnBusy': 'Đang viết lại',
- 'rw.hint': 'Viết lại kịch bản: AI xếp nội dung vào đúng ô của mẫu đang chọn và thời lượng bên dưới, giữ nguyên số liệu, tên kênh, CTA.',
- 'rw.hintMany': 'Viết lại kịch bản tắt vì đang chọn {n} mẫu: mỗi mẫu có ô nội dung khác nhau. Muốn AI viết lại thì chọn 1 mẫu; còn không, cả {n} video dùng chung nội dung đang gõ.',
- 'rw.busy': 'Đang viết lại…',
- 'rw.needOne': 'Chọn 1 mẫu trước',
- 'rw.onlyOne': 'Chỉ viết lại được khi chọn 1 mẫu',
- 'rw.needText': 'Gõ nội dung trước (tối thiểu 10 ký tự)',
- 'rw.loading': 'Đang viết lại cho mẫu {id} · {d}… (thường 20–60 giây)',
- 'rw.title': 'Bản viết lại · mẫu {id} · {d}',
- 'rw.fallback': 'Đã chuyển sang Claude Code vì {why}.',
- 'rw.use': 'Dùng bản này',
- 'rw.drop': 'Bỏ',
- 'rw.timeout': 'Quá 100 giây chưa xong, đã dừng chờ. Bấm lại thử.',
- 'rw.replaced': 'Đã thay nội dung bằng bản viết lại.',
- 'rw.undo': 'Hoàn tác',
- 'rw.close': 'Đóng',
- 'err.status': 'Lỗi {s}',
-
- 'dur.label': 'Thời lượng',
- 'dur.range': '(3 giây – 10 phút)',
- 'dur.presets': 'Chọn nhanh thời lượng',
- 'dur.hint': 'Gõ số giây (90) hoặc phút:giây (1:30).',
- 'dur.errEmpty': 'Nhập thời lượng, vd 8 hoặc 1:30',
- 'dur.errFmt': 'Gõ số giây (90) hoặc phút:giây (1:30)',
- 'dur.errMin': 'Ngắn nhất 3 giây',
- 'dur.errMax': 'Dài nhất 10 phút (10:00)',
- 'dur.eqLong': '= {s} giây ({f}).',
- 'dur.eq': '= {s} giây. Gõ số giây (90) hoặc phút:giây (1:30).',
- 'dur.warn': 'Video dài {f}: render ước tính {range} (đo thực tế: video 8 giây mất 20–60 giây render), chưa tính lúc AI viết cảnh. AI phải viết khoảng {scenes} cảnh nối nhau nên tốn token và chi phí hơn hẳn video 8 giây.',
- 'unit.sec': 'giây',
- 'unit.min': 'phút',
- 'unit.hour': 'giờ',
- 'num.dec': ',',
-
- 'audio.aria': 'Âm thanh',
- 'mode.label': 'Ai dựng cảnh',
- 'mode.auto': 'Tự động',
- 'mode.manual': 'Agent ngoài',
- 'modeLabel.auto': 'tự động',
- 'modeLabel.manual': 'agent ngoài',
- 'mode.hintAuto': 'Tự động: đang dùng {m}.',
- 'mode.hintApi': 'Gọi Claude API bằng khoá Anthropic (nhập ở Kiểm tra máy hoặc .env; tốn tiền theo token, ghi chi phí vào job).',
- 'mode.hintClaude': 'Chạy Claude Code trên máy này (dùng gói Claude của mày).',
- 'mode.hintManual': 'Chỉ tạo đề bài; agent bên ngoài (MCP/CLI) viết cảnh rồi gọi render.',
- 'mode.hintExport': ' Xong sẽ chép MP4 ra thư mục xuất.',
- 'model.label': 'Model viết cảnh',
- 'model.auto': 'Tự chọn theo mẫu',
- 'model.autoRec': 'Tự chọn theo mẫu ({m})',
- 'model.autoMany': 'Tự chọn theo từng mẫu',
- 'model.opus': 'Opus (đẹp nhất, tốn nhất)',
- 'model.sonnet': 'Sonnet (cân bằng)',
- 'model.haiku': 'Haiku (rẻ nhất)',
- 'model.rec': (v) => `Mẫu này ${v.heavy ? 'dựng 3D/shader' : 'là 2D'} → đề xuất ${v.m}.`,
- 'model.pickFirst': 'Chọn mẫu để xem đề xuất.',
- 'model.haikuWarn': ' Haiku hay làm phẳng cảnh 3D, nên dùng Opus.',
- 'model.override': ' (đang chọn {m} thay vì đề xuất)',
- 'model.agentNote': ' Agent ngoài thì model do agent đó quyết.',
- 'model.manyLight': '{n} mẫu 2D → {m}',
- 'model.manyHeavy': '{n} mẫu 3D/shader → {m}',
- 'model.manyAuto': 'Mỗi video tự chọn theo mẫu: {parts}.',
- 'model.manyFixed': 'Cả {n} video dùng {m} (đề xuất: {parts}).',
- 'model.haikuWarnMany': ' Haiku hay làm phẳng cảnh 3D, nên dùng Opus cho mẫu 3D.',
- 'runAt.label': 'Hẹn giờ dựng',
- 'runAt.opt': '(bỏ trống = dựng ngay)',
- 'runAt.clear': 'Bỏ hẹn',
- 'runAt.clearAria': 'Bỏ hẹn giờ',
- 'go.build': (v) => (v.n > 1 ? `Dựng ${v.n} video` : 'Dựng video'),
- 'go.schedule': (v) => (v.n > 1 ? `Hẹn dựng ${v.n} video` : 'Hẹn dựng video'),
- 'go.sending': 'Đang gửi',
- 'go.needTpl': 'Chọn mẫu trước',
- 'go.needText': 'Nội dung tối thiểu 10 ký tự',
- 'go.badDur': 'Thời lượng chưa đúng',
- 'form.jobErr': 'Tạo job lỗi',
- 'form.retry': '. Sửa rồi bấm lại.',
-
- 'jobs.h': 'Video đã dựng',
- 'jobs.empty': 'Chưa có video nào. Chọn mẫu, dán nội dung rồi bấm <b>Dựng video</b>.',
- 'jobs.less': 'Thu gọn',
- 'jobs.more': 'Xem thêm ({n} video cũ hơn)',
- 'st.scheduled': 'Đã hẹn',
- 'st.queued': 'Đang chờ',
- 'st.generating': 'AI đang viết cảnh',
- 'st.waiting_agent': 'Chờ agent viết cảnh',
- 'st.previewing': 'Đang dựng preview',
- 'st.rendering': 'Đang render',
- 'st.done': 'Xong',
- 'st.error': 'Lỗi',
- 'job.previewAlt': 'Preview 16 khung',
- 'job.building': 'Đang dựng…',
- 'job.waitScene': 'Chờ cảnh',
- 'job.noImage': 'Chưa có hình',
- 'job.tpl': 'Mẫu {id} · {name}',
- 'job.at': 'Hẹn dựng lúc {t}',
- 'job.api': 'API: {i}k vào · {o}k ra · ≈ ${c}',
- 'job.exported': 'Đã chép ra: {p}',
- 'job.errUnknown': 'Lỗi không rõ',
- 'job.errTail': '. Xem log, sửa cảnh rồi bấm Render lại.',
- 'job.agent': 'Agent đọc: {prompt}\nViết: {scene}\nRồi chạy: node cli.mjs render {id}',
- 'job.mp4': 'Tải MP4',
- 'job.preview': 'Preview 16 khung',
- 'job.rerender': 'Render lại',
- 'job.render': 'Render',
- 'job.log': 'Log ({n} dòng)',
-
- 'ap.title': 'Âm thanh',
- 'ap.loadingOpts': 'Đang tải lựa chọn…',
- 'ap.stop': 'Dừng nghe thử',
- 'ap.making': 'Đang tạo bản nghe thử',
- 'ap.voiceLoading': 'Đang tạo giọng mẫu… (lần đầu nạp mô hình có thể mất vài phút)',
- 'ap.prevFail': 'không tạo được bản nghe thử',
- 'ap.prevErr': 'Nghe thử lỗi: ',
- 'ap.keep': 'Giữ như hiện tại',
- 'ap.music': 'Nhạc nền',
- 'ap.musicPrev': 'Nghe thử nhạc nền',
- 'ap.voice': 'Giọng đọc',
- 'ap.voicePrev': 'Nghe thử giọng đọc',
- 'ap.sfx': 'Tiếng động gắn theo chuyển động',
- 'ap.pickMusic': 'Chọn 1 kiểu nhạc cụ thể để nghe thử.',
- 'ap.pickVoice': 'Chọn 1 giọng cụ thể để nghe thử.',
- 'ap.vAuto': 'giọng theo mẫu',
- 'ap.vNone': 'không lời',
- 'ap.versions': 'Các bản ({n})',
- 'ap.ver': 'Bản {n}',
- 'ap.latest': ' · mới nhất',
- 'ap.noSfx': ' · không sfx',
- 'ap.view': 'Xem',
- 'ap.dl': 'Tải',
- 'ap.mix': 'Trộn tiếng mới',
- 'ap.mixNote': 'Không dựng lại hình. Bản cũ được giữ lại; chọn giọng mà video chưa có lời thì AI viết lời ngắn.',
- 'ap.lastErr': 'Lần trộn trước lỗi: ',
- 'ap.mixing': 'Đang trộn tiếng…',
- 'ap.mixingNote': 'Đang trộn (giọng VieNeu có thể mất vài phút)…',
- 'ap.err': 'Lỗi: ',
- 'ap.unknown': 'không rõ',
- 'ap.done': 'Xong — đang phát bản mới nhất.',
- 'ap.summary': 'Âm thanh · đổi nhạc, giọng đọc',
- 'ap.loading': 'Đang tải…',
- 'ap.mixFail': 'Không trộn được: ',
- 'ap.errShort': 'lỗi',
- 'vc.title': 'Giọng của tôi',
- 'vc.optTag': 'giọng nhân bản',
- 'vc.add': '+ Thêm giọng',
- 'vc.loading': 'Đang tải giọng của bạn…',
- 'vc.loadErr': 'Không tải được danh sách giọng.',
- 'vc.retry': 'Thử lại',
- 'vc.empty': 'Chưa có giọng nào. Tải lên hoặc thu 10 giây – 3 phút giọng nói, app học giọng rồi đọc lời video bằng chính giọng đó.',
- 'vc.needVieneu': 'Cần VieNeu-TTS trên máy để nhân bản giọng: pip install vieneu',
- 'vc.ready': 'Sẵn sàng',
- 'vc.error': 'Lỗi',
- 'vc.step.queued': 'Đang chờ…',
- 'vc.step.transcribe': 'Đang chép lời đoạn mẫu…',
- 'vc.step.encode': 'Đang học giọng + đọc thử…',
- 'vc.play': 'Nghe thử giọng {name}',
- 'vc.stop': 'Dừng nghe',
- 'vc.rename': 'Đổi tên giọng {name}',
- 'vc.delete': 'Xoá giọng {name}',
- 'vc.newName': 'Tên mới',
- 'vc.save': 'Lưu',
- 'vc.cancel': 'Huỷ',
- 'vc.refSum': 'Đoạn mẫu app đã chọn',
- 'vc.refText': 'Lời của đoạn mẫu',
- 'vc.byWhisper': '(máy tự chép, sửa nếu sai)',
- 'vc.refTextPh': 'Gõ đúng những gì bạn nói trong đoạn mẫu',
- 'vc.refTextHint': 'Không bắt buộc với VieNeu v3 Turbo; giúp nhận ra đoạn mẫu nói gì.',
- 'vc.saveText': 'Lưu lời',
- 'vc.noWhisper': 'Máy chưa có whisper nên chưa chép được lời đoạn mẫu. Mở "Đoạn mẫu" để nghe và gõ lời (không bắt buộc).',
- 'vc.srcAria': 'Lấy giọng từ',
- 'vc.srcFile': 'Chọn file',
- 'vc.srcRec': 'Thu âm',
- 'vc.fileLabel': 'File âm thanh giọng nói',
- 'vc.fileHint': 'wav, mp3, m4a, ogg hoặc webm · 10 giây – 3 phút · tối đa {max} MB · chỉ 1 người nói, ít tạp âm.',
- 'vc.readTip': 'Gợi ý: đọc to đoạn này, tự nhiên như đang nói chuyện',
- 'vc.readText': 'Hôm nay mình muốn kể cho bạn nghe một chuyện nhỏ. Sáng nào mình cũng dậy sớm, pha một ly cà phê, mở cửa sổ và nghe phố xá bắt đầu nhộn nhịp. Có hôm trời mưa, có hôm nắng gắt, nhưng mình vẫn giữ thói quen đó. Một, hai, ba, bốn, năm: thói quen nhỏ, kết quả lớn.',
- 'vc.recStart': 'Bắt đầu thu',
- 'vc.recAgain': 'Thu lại',
- 'vc.recStop': 'Dừng',
- 'vc.recHint': 'Thu ở chỗ yên tĩnh, cách micro một gang tay, ít nhất 20 giây. Tự dừng sau 3 phút.',
- 'vc.recFile': 'thu-am',
- 'vc.nameLabel': 'Tên giọng',
- 'vc.namePh': 'Ví dụ: Giọng Nam',
- 'vc.consent': 'Đây là giọng của tôi, hoặc tôi được người đó cho phép dùng',
- 'vc.langNote': 'Giọng nhân bản đọc tiếng Việt. Chọn giọng này cho nội dung tiếng Anh thì lời đọc được viết bằng tiếng Việt.',
- 'vc.create': 'Tạo giọng',
- 'vc.sending': 'Đang gửi… {pct}%',
- 'vc.processing': 'Đã nhận giọng {name}. Đang học giọng, khoảng 1 phút.',
- 'vc.readyNote': 'Giọng {name} đã sẵn sàng và được chọn làm giọng đọc. Bấm nút phát để nghe thử.',
- 'vc.errNoFile': 'Chọn 1 file âm thanh.',
- 'vc.errNoRec': 'Thu âm trước đã.',
- 'vc.errExt': 'Định dạng chưa hỗ trợ. Dùng wav, mp3, m4a, ogg hoặc webm.',
- 'vc.errBig': 'File quá lớn (tối đa {max} MB).',
- 'vc.errShort': 'Ngắn quá ({s} giây). Cần ít nhất 10 giây.',
- 'vc.errLong': 'Dài quá 3 phút. Cắt bớt rồi thử lại.',
- 'vc.errName': 'Đặt tên cho giọng.',
- 'vc.errNameLong': 'Tên tối đa {max} ký tự.',
- 'vc.errConsent': 'Tick xác nhận để tiếp tục.',
- 'vc.errNoMic': 'Trình duyệt này không thu âm được. Chọn file thay thế.',
- 'vc.errMicDenied': 'Chưa được dùng micro. Cho phép micro trong trình duyệt rồi thử lại.',
- 'vc.errUpload': 'Gửi không được. Kiểm tra app còn chạy rồi thử lại.',
- 'vc.errDel': 'Không xoá được giọng.',
- 'vc.errSave': 'Không lưu được.',
- 'vc.confirmDel': 'Xoá giọng "{name}"? File giọng trên máy bị xoá hẳn, không khôi phục được.',
- 'vc.deleted': 'Đã xoá giọng {name}.',
- 'vc.renamed': 'Đã đổi tên thành {name}.',
- 'vc.textSaved': 'Đã lưu lời đoạn mẫu.',
-
- 'ed.aria': 'Edit video của bạn',
- 'ed.setupH': 'Chưa cài phần Edit video',
- 'ed.noServer': 'Không gọi được server.',
- 'ed.h': 'Video của bạn',
- 'ed.dropAria': 'Chọn hoặc kéo thả video',
- 'ed.dropBig': 'Kéo thả video vào đây',
- 'ed.dropSmall': 'hoặc bấm để chọn · mp4, mov, mkv… tối đa 2 GB · nói trước máy, tiếng Việt',
- 'ed.fileLabel': 'File video',
- 'ed.style': 'Kiểu edit',
- 'ed.music': 'Nhạc nền',
- 'ed.musicOpt': '(tự hạ khi bạn nói)',
- 'ed.noMusic': 'Không nhạc',
- 'ed.musicSynth': 'Nhạc tổng hợp: {id} — {desc}',
- 'ed.musicFile': 'Tải file nhạc của tôi…',
- 'ed.musicFileLabel': 'File nhạc',
- 'ed.names': 'Tên riêng, thuật ngữ',
- 'ed.namesOpt': '(để AI viết phụ đề đúng)',
- 'ed.namesPh': 'Ví dụ: Lumfin, Hà Nội, ETF',
- 'ed.notes': 'Dặn thêm',
- 'ed.notesOpt': '(không bắt buộc)',
- 'ed.notesPh': 'Ví dụ: bỏ câu chào đầu, giữ đoạn cuối kêu gọi theo dõi',
- 'ed.draft': 'Bản nháp nhanh (phụ đề đơn giản, nhanh hơn ~1 phút)',
- 'ed.go': 'Dựng',
- 'ed.empty': 'Chọn video bên trái rồi bấm Dựng.',
- 'ed.steps': 'Các bước',
- 'ed.fixesH': 'Chữ AI đã sửa trong phụ đề, xem lại giúp',
- 'ed.reviseH': 'Sửa bằng lời',
- 'ed.reviseLabel': 'Lời sửa',
- 'ed.revisePh': 'Ví dụ: "bỏ 3 giây đầu", "zoom ít lại"',
- 'ed.reviseBtn': 'Render lại',
- 'ed.p1': 'bỏ 3 giây đầu',
- 'ed.p2': 'zoom ít lại',
- 'ed.p3': 'nhạc nhỏ lại',
- 'ed.p4': 'phụ đề 2 chữ một lần',
- 'ed.histH': 'Các lần sửa',
- 'ed.log': 'Nhật ký',
- 'ed.delete': 'Xoá bản dựng này',
- 'ed.listH': 'Các bản đã dựng',
- 'ed.st.queued': 'Đang chờ',
- 'ed.st.running': 'Đang dựng',
- 'ed.st.done': 'Xong',
- 'ed.st.error': 'Lỗi',
- 'ed.waitTurn': 'Đang chờ lượt',
- 'ed.revising': 'Đang sửa',
- 'ed.notVideo': 'File này không phải video (mp4, mov, mkv, webm…).',
- 'ed.tooBig': 'Video {size} quá lớn (tối đa 2 GB).',
- 'ed.changeFile': '{size} · bấm để đổi file',
- 'ed.needMusic': 'Chọn file nhạc, hoặc đổi sang "Không nhạc".',
- 'ed.uploading': 'Đang tải lên {p}%',
- 'ed.uploadCut': 'Tải lên bị ngắt. Kiểm tra server rồi thử lại.',
- 'ed.listEmpty': 'Chưa có bản nào.',
- 'ed.err': 'Lỗi',
- 'ed.reviseErr': 'Sửa chưa được: {e}',
- 'ed.previewAlt': 'Lưới khung xem trước',
- 'ed.mediaEmpty': 'Video sẽ hiện ở đây khi dựng xong',
- 'ed.mp4': 'Tải MP4',
- 'ed.gridOut': 'Lưới khung bản ra',
- 'ed.hidden': '(ẩn khỏi phụ đề)',
- 'ed.checksEdl': '{out} s · bỏ {rm} s · {z} zoom',
- 'ed.overcut': 'lẹm chữ: {v}',
- '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.',
- 'man.h': 'Chỉnh tay',
- 'man.tabCap': 'Phụ đề',
- 'man.tabAud': 'Nhạc & tiếng',
- 'man.tabFx': 'Zoom & đồ hoạ',
- 'man.look': 'Kiểu chữ',
- 'man.hi': 'Chữ nhấn (chữ trong *sao* đổi màu)',
- 'man.capHint': 'Bấm mốc giờ để video nhảy tới dòng đó. Bọc *chữ* để nhấn.',
- 'man.draftNote': 'Bản nháp vẽ phụ đề thẳng vào nền nên chưa sửa tay được. Bỏ "nháp" rồi dựng lại.',
- 'man.music': 'Nhạc',
- 'man.musicKeep': 'Giữ nhạc đang dùng ({name})',
- 'man.synth': 'Nhạc tổng hợp: {id}',
- 'man.uploaded': 'Đã tải: {name}',
- 'man.uploading': 'Đang tải {name} ({size})…',
- 'man.uploadOk': 'Đã tải lên {name}. Bấm Áp dụng để trộn lại tiếng.',
- 'man.uploadErr': 'Tải nhạc chưa được: {e}',
- 'man.musicGain': 'Âm lượng nhạc',
- 'man.duck': 'Ducking: nhạc nhỏ lại khi có tiếng nói',
- 'man.fade': 'Fade out cuối',
- 'man.start': 'Nhạc bắt đầu từ giây',
- 'man.voice': 'Âm lượng giọng (so với nhạc)',
- 'man.loudHint': 'Cả bản luôn chuẩn về −14 LUFS: tăng giọng tức là nhạc và tiếng động nhỏ đi tương đối.',
- 'man.sfx': (v) => `Tiếng động${v.n ? ` · ${v.n}` : ' · không có'}`,
- 'man.zooms': 'Zoom',
- 'man.gfx': 'Đồ hoạ',
- 'man.zoomKind': (v) => `${v.kind === 'punch' ? 'Zoom giật' : 'Zoom đẩy'} ×${v.scale}`,
- 'man.noZoom': 'Bản này không có zoom.',
- 'man.noGfx': 'Bản này không có đồ hoạ.',
- 'man.noLines': 'Bản này không có phụ đề.',
- 'man.remove': 'Xoá',
- 'man.undo': 'Giữ lại',
- 'man.removeN': 'Xoá {what}',
- 'man.undoN': 'Giữ lại {what}',
- 'man.jump': 'Nhảy tới giây {s}',
- 'man.lineText': 'Chữ dòng {n}',
- 'man.lineStart': 'Giây bắt đầu dòng {n}',
- 'man.lineEnd': 'Giây kết thúc dòng {n}',
- 'man.split': 'Tách',
- 'man.merge': 'Gộp ↓',
- 'man.splitN': 'Tách dòng {n} làm đôi',
- 'man.mergeN': 'Gộp dòng {n} với dòng sau',
- 'man.delN': 'Xoá dòng {n}',
- 'man.cantSplit': 'Dòng chỉ có 1 chữ, không tách được.',
- 'man.errShort': 'Dòng phải dài ít nhất 0,1 giây (kết thúc sau bắt đầu).',
- 'man.errAfter': 'Bắt đầu sau cuối video ({d} s).',
- 'man.errOverlap': 'Đè lên dòng trước: dời giờ bắt đầu ra sau.',
- 'man.errEmpty': 'Dòng trống: gõ chữ hoặc xoá dòng.',
- 'man.fixFirst': (v) => `Sửa ${v.n} dòng báo đỏ trước khi áp dụng.`,
- 'man.dirty': (v) => `${v.n} thay đổi · dựng lại: ${v.what}`,
- 'man.clean': 'Chưa có thay đổi.',
- 'man.wCap': 'lớp chữ',
- 'man.wAud': 'tiếng',
- 'man.wBase': 'nền',
- 'man.reset': 'Bỏ thay đổi',
- 'man.apply': 'Áp dụng',
- 'man.applying': 'Đang dựng…',
- 'man.running': 'Đang dựng bản chỉnh tay',
- 'man.loadErr': 'Không tải được phần chỉnh tay: {e}',
- 'man.sendFail': 'Không gửi được phần chỉnh tay.',
- 'man.tag': 'Chỉnh tay',
- 'man.took': 'dựng {s} giây',
- 'man.watch': 'Xem',
- 'man.original': 'Bản đầu tiên',
- '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.more': 'Thêm',
- 'ed.review': (v) => `Cần xem lại (${v.n})`,
- 'ed.revFixes': 'Chữ AI sửa',
- 'ed.revFigs': 'Số chưa chắc',
- 'ed.specs': 'Thông số',
- 'ed.stepOf': '{i}/{n} · {step} · {p}%',
- 'ed.revisePhS': 'bỏ 3 giây đầu…',
- 'man.hiShort': 'Chữ nhấn',
- 'man.hiTip': 'Bọc *chữ* để đổi màu',
- 'man.gainS': 'Âm lượng',
- 'man.fadeS': 'Fade cuối',
- 'man.startS': 'Bắt đầu (s)',
- 'man.duckS': 'Tự hạ khi nói',
- 'man.voiceS': 'Giọng',
- 'man.dirtyS': (v) => `${v.n} thay đổi`,
- 'ed.cutRepairs': (v) => `đã sửa ${v.n} vết cắt lẹm chữ`,
-
- // ---- Tạo mẫu từ video (learn-panel.js) ----
- 'cat.mine': 'Của tôi',
- 'lp.open': 'Tạo mẫu từ video',
- 'lp.title': 'Tạo mẫu từ video',
- 'lp.lead': 'Đưa 1 video trên máy, AI học phong cách dựng (màu, bố cục, nhịp, chuyển động), dựng thử 1 bản với nội dung khác, rồi bạn xem và lưu thành mẫu của mình.',
- 'lp.back': 'Quay lại',
- 'lp.close': 'Đóng',
- 'lp.loadErr': 'Không tải được nháp. Thử lại sau.',
- 'lp.noDrafts': 'Chưa có nháp nào.',
- 'lp.new': 'Tạo từ video mới',
- 'lp.drop': 'Kéo thả video vào đây',
- 'lp.dropHint': 'hoặc bấm để chọn · mp4, mov, webm · 4 giây – 3 phút · tối đa 200 MB',
- 'lp.change': 'Đổi video',
- 'lp.refVideo': 'Video tham khảo',
- 'lp.from': 'Học đoạn 8 giây nào',
- 'lp.seg': '{a}–{b} s',
- 'lp.fromHint': 'Chọn đoạn có phong cách rõ nhất. Video đang phát lặp đúng đoạn này.',
- 'lp.name': 'Tên mẫu',
- 'lp.optional': '(không bắt buộc)',
- 'lp.namePh': 'Ví dụ: Thẻ bài giấy cũ',
- 'lp.cat': 'Nhóm',
- 'lp.catAuto': 'Để AI chọn',
- 'lp.note': 'Đây là video gì',
- 'lp.notePh': 'Ví dụ: video giới thiệu món ăn, chữ to, cắt nhanh',
- 'lp.rulesH': 'Học phong cách, không chép',
- 'lp.rule1': 'Chỉ học màu, bố cục, nhịp, kiểu chuyển động, kiểu chữ gần nhất trong font mở.',
- 'lp.rule2': 'Chữ, tên kênh, logo, nhân vật nhìn thấy trong video được gỡ khỏi mẫu bằng máy.',
- 'lp.rule3': 'Video tham khảo chỉ nằm trên máy này, bị xoá khi bạn Lưu hoặc Bỏ. Ảnh đại diện lấy từ bản dựng thử.',
- 'lp.consent': 'Video này của tôi, hoặc tôi chỉ dùng nó để học phong cách dựng. Tôi không sao chép nhân vật, logo, nhạc hay hình ảnh của người khác.',
- 'lp.needConsent': 'Tick ô xác nhận để bắt đầu',
- 'lp.skipTest': 'Bỏ dựng thử (nhanh và rẻ hơn, nhưng chưa biết mẫu có ra hình đúng không)',
- 'lp.est': 'Khoảng 7–13 phút, chi phí AI khoảng 1–2,5 USD theo giá API (có dựng thử 1 video 8 giây).',
- 'lp.estNoTest': 'Khoảng 2–3 phút, chi phí AI khoảng 0,2–0,4 USD theo giá API. Nháp sẽ ghi "chưa dựng thử".',
- 'lp.go': 'Bắt đầu',
- 'lp.uploading': 'Đang tải video lên',
- 'lp.uploadingPct': 'Đang tải lên {p}%',
- 'lp.started': 'Đã nhận video, đang đo.',
- 'lp.err.ext': 'Định dạng này chưa hỗ trợ. Dùng mp4, mov hoặc webm.',
- 'lp.err.big': 'Video quá nặng (tối đa 200 MB).',
- 'lp.err.short': 'Video quá ngắn, cần ít nhất {min} giây.',
- 'lp.err.long': 'Video quá dài, tối đa 3 phút. Cắt bớt rồi thử lại.',
- 'lp.err.upload': 'Không gửi được video. Kiểm tra server rồi thử lại.',
- 'lp.err.run': 'Tạo mẫu bị lỗi.',
- 'lp.st.uploaded': 'Đã nhận',
- 'lp.st.measuring': 'Đang đo',
- 'lp.st.writing': 'AI đang viết',
- 'lp.st.testing': 'Đang dựng thử',
- 'lp.st.comparing': 'Đang so',
- 'lp.st.revising': 'AI đang sửa',
- 'lp.st.ready': 'Sẵn sàng',
- 'lp.st.readyNoTest': 'Sẵn sàng (chưa dựng thử)',
- 'lp.st.error': 'Lỗi',
- 'lp.st.saved': 'Đã lưu',
- 'lp.st.discarded': 'Đã bỏ',
- 'lp.step.measuring': 'Đo video (màu, nhịp, chuyển động)',
- 'lp.step.writing': 'AI viết mẫu theo khuôn',
- 'lp.step.testing': 'Dựng thử 1 video 8 giây',
- 'lp.step.comparing': 'So bản dựng thử với video gốc',
- 'lp.step.revising': 'AI sửa mẫu 1 vòng',
- 'lp.stepNow': '{e} / ~{est}',
- 'lp.stepEst': '~{est}',
- 'lp.progress': 'Tiến độ tạo mẫu',
- 'lp.canClose': 'Có thể đóng hộp này, việc vẫn chạy. Mở lại bằng nút Tạo mẫu từ video.',
- 'lp.draftH': 'Nháp mẫu',
- 'lp.totals': 'Thời gian {t} · chi phí AI {c}',
- 'lp.fromFile': '{f} · đoạn {a}–{b} s',
- 'lp.noRef': 'Video tham khảo đã xoá',
- 'lp.testVideo': 'Bản dựng thử',
- 'lp.notTested': 'Chưa dựng thử',
- 'lp.sheets': 'Xem 16 khung cạnh nhau',
- 'lp.refSheet': 'Gốc',
- 'lp.refSheetAlt': 'Lưới 16 khung của video tham khảo',
- 'lp.testSheet': 'Bản dựng thử',
- 'lp.testSheetAlt': 'Lưới 16 khung của bản dựng thử',
- 'lp.cmpH': (v) => `So số đo: ${v.n}/${v.total} chỉ số lệch quá 25%`,
- 'lp.cmpMetric': 'Chỉ số',
- 'lp.cmpRef': 'Gốc',
- 'lp.cmpTest': 'Dựng thử',
- 'lp.cmpDev': 'Lệch',
- 'lp.off': 'lệch',
- 'lp.near': 'gần',
- 'lp.m.palette': 'Bảng màu chính',
- 'lp.m.brightness': 'Độ sáng',
- 'lp.m.saturation': 'Độ đậm màu',
- 'lp.m.events': 'Phần tử mới mỗi giây',
- 'lp.m.motion': 'Mức chuyển động',
- 'lp.m.cuts': 'Số lần cắt cảnh',
- 'lp.m.still': 'Tỉ lệ đứng im',
- 'lp.diffsH': 'Điểm còn lệch (AI nhìn 2 lưới)',
- 'lp.diffsFixed': 'Điểm lệch AI thấy và đã sửa vào mẫu',
- 'lp.selfH': 'Tự kiểm: {ok}/{n} câu đạt',
- 'lp.yes': 'có',
- 'lp.no': 'không',
- 'lp.guideH': 'Mẫu (guidance)',
- 'lp.guideHint': 'AI dựng cảnh đọc chữ này. Sửa tay được.',
- 'lp.saveText': 'Lưu chỗ sửa',
- 'lp.unsaved': 'Có chỗ sửa chưa lưu',
- 'lp.seenHit': 'còn chữ của video gốc: "{s}"',
- 'lp.textOk': 'Đã lưu chỗ sửa, qua bộ kiểm.',
- 'lp.textBad': 'Đã lưu chỗ sửa, còn lỗi cần sửa trước khi lưu mẫu.',
- 'lp.saveH': 'Lưu thành mẫu "Của tôi"',
- 'lp.saveName': 'Tên mẫu',
- 'lp.slug': 'Mã mẫu',
- 'lp.slugHint': 'Chữ thường không dấu, số, gạch nối. Dùng trong lệnh: make --template local.mine/<mã>',
- 'lp.save': 'Lưu thành mẫu',
- 'lp.retest': 'Dựng thử lại',
- 'lp.discard': 'Bỏ nháp',
- 'lp.discardAsk': 'Bỏ nháp này? Video tham khảo và bản nháp sẽ bị xoá.',
- 'lp.discarded': 'Đã bỏ nháp.',
- 'lp.saveNote': 'Lưu xong, video tham khảo và khung hình bị xoá khỏi máy. Mẫu chạy ở chế độ khoá: AI chỉ đọc/ghi trong thư mục của video đang dựng.',
- 'lp.errNoSave': 'Nháp lỗi ở bước dựng thử: sửa mẫu rồi bấm Dựng thử lại trước khi lưu.',
- 'lp.savedH': 'Đã lưu vào Của tôi',
- 'lp.savedP': 'Mẫu {ref} nằm trong lưới mẫu, lọc "Của tôi". Dựng với nội dung bất kỳ như mẫu gốc.',
- 'lp.useNow': 'Dùng mẫu này',
- // ---- màn tạo mới (studio/create.js) ----
- 'cr.title': 'Dự án mới',
- 'cr.backStep': 'Về bước trước',
- 'cr.stepsAria': 'Các bước',
- 'cr.s1': 'Clip', 'cr.s2': 'Cách dựng', 'cr.s3': 'Dựng',
- 'cr.sideAria': 'Thiết lập bản dựng',
- 'cr.yourClip': 'Clip của bạn',
- 'cr.changeClip': 'Đổi clip',
- 'cr.noClip': 'Chưa chọn clip. Kéo thả video vào ô bên phải.',
- 'cr.musicStyle': 'Theo cách dựng',
- 'cr.musicUpload': 'Tải nhạc',
- 'cr.len': 'Độ dài bản ra',
- 'cr.lenAuto': 'Tự động',
- 'cr.lenAutoOn': 'Đặt độ dài',
- 'cr.lenAutoV': 'Tự động',
- 'cr.lenV': '~{s} giây',
- 'cr.names': 'Tên riêng',
- 'cr.namesWhy': 'để phụ đề viết đúng',
- 'cr.namePh': 'Ví dụ: Lumfin (Enter để thêm)',
- 'cr.addName': 'Thêm',
- 'cr.removeName': 'Bỏ tên riêng {n}',
- 'cr.h1': 'Chọn clip',
- 'cr.sub1': 'Video nói trước máy, tiếng Việt. AI cắt khoảng lặng, làm phụ đề, zoom và đồ hoạ.',
- 'cr.h2': 'Chọn cách dựng',
- 'cr.sub2': 'Mỗi cách là một kiểu cắt, phụ đề và đồ hoạ. Đổi lại được sau khi dựng.',
- 'cr.h3': 'Đang dựng',
- 'cr.open': 'Mở Studio',
- 'cr.another': 'Dựng clip khác',
- 'cr.next': 'Tiếp: chọn cách dựng',
- 'cr.eta': 'Mất khoảng {m} phút',
- 'cr.delete': 'Xoá bản dựng {name}',
- // ---- Studio (studio/*.js) ----
- 'st.fromReel': 'Từ reel (giữ nguyên)',
- 'st.reelMusic': 'Nhạc của reel',
- 'st.reelLink': '↩ Reel: {title}',
- 'st.reelBack': 'Quay về video reel này ở tab Dựng từ mẫu',
- 'st.videoHint': 'Bấm track Video để chọn clip, kéo để chọn vùng; S tách clip tại đầu phát; Delete cắt bỏ đoạn đang chọn.',
- 'st.videoPick': 'Chưa chọn đoạn nào trên track Video.',
- 'st.cutThis': 'Cắt bỏ đoạn này',
- 'st.restoreCut': 'Trả lại đoạn đã cắt',
- 'st.splitClip': 'Tách clip tại đầu phát (S)',
- 'st.cutDone': 'Đã đánh dấu cắt {a}–{b}. Xuất bản mới để áp dụng.',
- 'st.noSplitHere': 'Không tách được ở đây (sát đầu/cuối hoặc trong chỗ đã cắt).',
- 'st.cutsPending': (v) => `${v.n} chỗ cắt chờ xuất bản (−${v.s} s). Xem trước đã nhảy qua.`,
- 'st.cutItem': 'Cắt {a}–{b}',
- 'st.showCaps': 'Hiện phụ đề',
- 'st.showCapsTip': 'Reel nhập vào đã có chữ trong cảnh nên phụ đề tắt sẵn; bật để vẽ thêm phụ đề từ lời đọc.',
- 'job.studio': 'Sửa tiếp trong Studio',
- 'job.studioBusy': 'Đang mở Studio…',
- 'job.studioErr': 'Không mở được Studio: {e}',
- 'st.back': 'Quay lại danh sách',
- 'st.versions': 'Phiên bản',
- 'st.r0': 'gốc',
- 'st.r0Tip': 'Bản dựng đầu tiên',
- 'st.undo': 'Hoàn tác (Ctrl+Z)',
- 'st.redo': 'Làm lại (Ctrl+Shift+Z)',
- 'st.needReview': 'Cần xem lại',
- 'st.publish': (v) => `Xuất bản mới (${v.n} thay đổi)`,
- 'st.publishing': 'Đang xuất bản',
- 'st.published': 'Đã xuất bản r{n}. Đang xem bản mới.',
- 'st.resetAsk': 'Bỏ hết thay đổi chưa xuất bản?',
- 'st.tools': 'Công cụ',
- 'st.railAi': 'Sửa lời',
- 'st.trVideo': 'Video', 'st.trCap': 'Phụ đề', 'st.trZoom': 'Zoom', 'st.trGfx': 'Đồ hoạ', 'st.trMusic': 'Nhạc',
- 'st.timeline': 'Dòng thời gian',
- 'st.splitS': 'Tách phụ đề tại đầu phát (S)',
- 'st.mergeNext': 'Gộp với dòng sau',
- 'st.delSel': 'Xoá khối đang chọn (Delete)',
- 'st.addZoom': 'Thêm zoom tại đầu phát',
- 'st.zoomIn': 'Phóng to timeline',
- 'st.zoomOut': 'Thu nhỏ timeline',
- 'st.fitAll': 'Vừa khung: xem toàn bộ video',
- 'st.tlZoom': 'Độ phóng timeline (Ctrl + lăn chuột)',
- 'st.noMusic': 'Không nhạc',
- 'st.lineText': 'Sửa chữ dòng phụ đề',
- 'st.play': 'Phát', 'st.pause': 'Dừng',
- 'st.prevFrame': 'Lùi 1 khung (←, Shift: 1 giây)',
- 'st.nextFrame': 'Tới 1 khung (→, Shift: 1 giây)',
- 'st.viewOut': 'Bản xuất',
- 'st.viewingOut': 'Đang xem MP4 đã xuất',
- 'st.closeSheet': 'Đóng bảng',
- 'st.readOnly': 'Đang xem bản cũ: chỉ xem. Chọn bản mới nhất để chỉnh.',
- 'st.capLines': 'Dòng chữ',
- 'st.capLook': 'Kiểu chữ',
- 'st.capReview': (v) => `Xem lại · ${v.n}`,
- 'st.flagged': 'Có chỗ cần xem lại',
- 'st.markHi': 'Nhấn chữ: bọc chữ đang chọn để đổi màu',
- 'st.del': 'Xoá',
- 'st.aiFixed': 'AI sửa “{heard}” thành “{text}”',
- 'st.figCheck': 'Số “{text}” — nghe được: “{said}”',
- 'st.lineErr.short': 'Dòng ngắn hơn 0,1 giây.',
- 'st.lineErr.after': 'Dòng bắt đầu sau cuối video.',
- 'st.lineErr.overlap': 'Dòng đè lên dòng trước.',
- 'st.lineErr.empty': 'Dòng không có chữ.',
- 'st.reviewH': 'Cần xem lại',
- 'st.reviewNone': 'Không có gì cần xem lại.',
- 'st.prevItem': 'Mục trước', 'st.nextItem': 'Mục sau',
- 'st.rFix': 'AI sửa', 'st.rFig': 'Số',
- 'st.rKeep': 'Giữ', 'st.rEdit': 'Sửa', 'st.rRevert': 'Trả lại',
- 'st.rNoRevert': 'Không trả lại được: dòng không còn chữ AI đã sửa',
- 'st.rNoGfx': 'Đồ hoạ có số này không còn trong bản (đã bị bỏ khi dựng).',
- 'st.rGfxCell': 'Ô {g}: “{cell}” → Trả lại thành “{to}” (số nghe được)',
- 'st.rStatus.keep': 'Đã giữ', 'st.rStatus.edit': 'Đã mở sửa', 'st.rStatus.revert': 'Đã trả lại chữ gốc',
- 'st.uploadMusic': 'Tải bài lên',
- 'st.gain': 'Âm lượng nhạc',
- 'st.zoomKind': 'Kiểu zoom',
- 'st.push': 'Đẩy chậm', 'st.punch': 'Giật nhanh', 'st.pushS': 'Đẩy', 'st.punchS': 'Giật',
- 'st.pushHint': 'Phóng chậm suốt khối, lùi về ở cuối.',
- 'st.punchHint': 'Phóng tức thì, giữ, rồi trả về.',
- 'st.zStrength': 'Độ mạnh',
- 'st.zLength': 'Độ dài',
- 'st.zoomPick': 'Chọn 1 khối zoom trên timeline, hoặc thêm zoom tại đầu phát.',
- 'st.zoomHere': 'Đầu phát đang ở trong 1 zoom: đã chọn zoom đó.',
- 'st.zoomNoRoom': 'Không đủ chỗ cho zoom mới ở đây.',
- 'st.gfxPick': 'Chọn 1 đồ hoạ trên timeline để sửa chữ, số và giờ hiện.',
- 'st.gStart': 'Giờ bắt đầu đồ hoạ', 'st.gEnd': 'Giờ kết thúc đồ hoạ',
- 'st.estimate': 'ước tính',
- 'st.delGfx': 'Xoá đồ hoạ',
- 'st.aiH': 'Sửa bằng lời (AI)',
- 'st.aiHint': 'Nói điều muốn đổi, AI dựng lại từ bản mới nhất (vài phút).',
- 'st.aiGo': 'Sửa bằng AI',
- 'st.aiPending': (v) => `Còn ${v.n} thay đổi chưa xuất bản: xuất bản hoặc bỏ thay đổi trước khi sửa bằng lời.`,
- 'st.noLineHere': 'Đầu phát không nằm trên dòng phụ đề nào.',
- 'st.noMerge': 'Chọn 1 dòng còn dòng sau để gộp.',
- 'st.selFirst': 'Chọn 1 khối trên timeline trước.',
- 'st.fixFirst': (v) => `Còn ${v.n} dòng phụ đề lỗi (đỏ): sửa xong mới xuất bản được.`,
- 'st.notFound': 'Không mở được bản này: {e}',
- 'st.buildErr': 'Bản này dựng lỗi: {e}',
- 'gf.kicker': 'Dòng nhỏ trên', 'gf.title': 'Tiêu đề', 'gf.unit': 'Đơn vị', 'gf.label': 'Nhãn', 'gf.prefix': 'Trước số',
- 'gf.value': 'Số', 'gf.suffix': 'Sau số', 'gf.old': 'Giá cũ', 'gf.text': 'Chữ', 'gf.a': 'Cột A', 'gf.b': 'Cột B',
- 'gf.row': 'Dòng {n}', 'gf.ok': 'Đánh dấu ✓',
- '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)',
- 'log.close': 'Đóng nhật ký', 'log.copy': 'Chép nhật ký', 'log.copied': 'Đã chép', 'log.copyManual': 'Đã chọn chữ, bấm Ctrl+C',
- 'log.download': 'Tải file .txt', 'log.reload': 'Tải lại', 'log.loading': 'Đang đọc nhật ký…', 'log.loadErr': 'Không đọc được nhật ký: {e}',
- 'log.step': 'Hỏng ở bước: {s}', 'log.rawError': 'Câu lỗi gốc', 'log.whyUnknown': 'Lỗi chưa có trong danh sách quen. Câu lỗi gốc ở dưới, chép nhật ký gửi người hỗ trợ.',
- 'log.okDone': 'Job này chạy xong, không có lỗi.', 'log.okRunning': 'Job chưa xong hoặc chưa lỗi. Bấm Tải lại để xem dòng mới.',
- 'log.serverNote': (v) => `${v.n} dòng log gần nhất của server. Khoá API, token và đường dẫn thư mục nhà đã được ẩn.`,
- 'log.rawHead': (v) => (v.total > v.n ? `Log thô: ${v.n} dòng cuối (trong ${v.total} dòng)` : `Log thô: ${v.n} dòng`), 'log.empty': 'Chưa có dòng log nào.',
- 'log.why.claude_login': 'Claude Code chưa đăng nhập.', 'log.fix.claude_login': 'Mở terminal, chạy lệnh claude rồi gõ /login, đăng nhập xong bấm Render lại.',
- 'log.why.api_key': 'Khoá Claude API sai hoặc đã bị thu hồi (lỗi 401).', 'log.fix.api_key': 'Mở "Kiểm tra máy" (nút trên cùng), dán khoá mới (lấy ở console.anthropic.com), bấm Lưu và kiểm tra rồi dựng lại. Hoặc chọn "Claude Code" ở ô Ai dựng cảnh.',
- 'log.why.quota': 'Hết hạn mức hoặc bị giới hạn tốc độ của AI.', 'log.fix.quota': 'Nạp thêm tiền / chờ hạn mức mở lại, hoặc đổi sang model rẻ hơn (Haiku) rồi dựng lại.',
- 'log.why.overloaded': 'Máy chủ AI đang quá tải.', 'log.fix.overloaded': 'Chờ vài phút rồi bấm Render lại.',
- 'log.why.disk': 'Ổ đĩa hết chỗ trống.', 'log.fix.disk': 'Xoá bớt video cũ (job, bản edit) hoặc dọn ổ đĩa, cần trống vài GB, rồi dựng lại.',
- 'log.why.cuda': 'Chép lời bằng GPU lỗi (thiếu CUDA/cuDNN hoặc GPU hết bộ nhớ).', 'log.fix.cuda': 'Cập nhật driver NVIDIA, đóng app đang dùng GPU, hoặc chạy lại node edit/setup.mjs. Không có GPU thì app tự chép lời bằng CPU (chậm hơn).',
- 'log.why.ffmpeg': 'Máy chưa có ffmpeg (hoặc không tìm thấy).', 'log.fix.ffmpeg': 'Cài ffmpeg (winget install ffmpeg trên Windows, brew install ffmpeg trên Mac) rồi khởi động lại app.',
- 'log.why.python': 'Thiếu Python hoặc gói Python cho phần Edit video.', 'log.fix.python': 'Cài Python 3.10–3.12, rồi bấm "Cài ngay" ở tab Edit video (hoặc chạy node edit/setup.mjs).',
- 'log.why.claude_missing': 'Không tìm thấy lệnh claude (Claude Code).', 'log.fix.claude_missing': 'Cài Claude Code (npm i -g @anthropic-ai/claude-code), hoặc chọn "Claude API" nếu đã có khoá API.',
- 'log.why.timeout': 'Quá thời gian cho phép (AI viết cảnh hoặc render chạy quá lâu).', 'log.fix.timeout': 'Rút ngắn thời lượng, chọn mẫu 2D nhẹ hơn, hoặc dựng lại lúc máy rảnh.',
- 'log.why.interrupted': 'App bị tắt khi job đang chạy.', 'log.fix.interrupted': 'Bấm Render lại / Dựng lại để chạy tiếp.',
- 'log.why.network': 'Mất mạng hoặc không kết nối được máy chủ.', 'log.fix.network': 'Kiểm tra mạng rồi thử lại.',
- 'log.why.no_scene': 'AI chưa viết xong cảnh (thiếu scene/index.html).', 'log.fix.no_scene': 'Bấm Render lại; nếu vẫn lỗi, xem log thô để biết AI dừng ở đâu.',
- 'log.why.scene_invalid': 'Cảnh AI viết có lỗi nên không render được.', 'log.fix.scene_invalid': 'Bấm Render lại để AI sửa, hoặc dựng lại với model mạnh hơn.',
- 'log.why.no_speech': 'Video không có tiếng nói nghe được.', 'log.fix.no_speech': 'Chọn clip có người nói rõ (tiếng Việt), không phải nhạc nền.',
- 'log.why.bad_video': 'File video hỏng hoặc định dạng không đọc được.', 'log.fix.bad_video': 'Xuất lại video sang MP4 (H.264) rồi tải lên lại.',
- 'log.why.edl_invalid': 'Bản dựng AI lập bị lệch (đoạn cắt, zoom, tiếng không khớp).', 'log.fix.edl_invalid': 'Bấm Dựng lại; lần sau AI sẽ lập lại từ đầu.',
- };
-
- 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, or 16:9, 4:3, 3:4.',
- 'lang.group': 'Interface language',
- 'lang.vi': 'Vietnamese (VI)',
- 'lang.en': 'English (EN)',
-
- 'update.hide': 'Dismiss',
- 'update.text': (v) => `${v.n} new update${S(v.n)} for LumReels${v.first ? ` (${v.first}${v.n > 1 ? ', …' : ''})` : ''}. Quit the app and run `,
- 'update.after': ' to update.',
-
- 'tabs.aria': 'Mode',
- 'tabs.tpl': 'From a template',
- 'tabs.edit': 'Edit your video',
- 'tabs.new': 'NEW',
-
- 'pick.h': 'Pick a template',
- 'pick.searchLabel': 'Search templates by name',
- 'pick.searchPh': 'Search by name or genre…',
- 'pick.chipsAria': 'Filter by group',
- 'cat.all': 'All',
- 'cat.faceless': 'Faceless',
- 'cat.ads': 'Ads',
- 'cat.multi-style': 'Multi-style',
- 'cat.viet-nam': 'Vietnam edition',
- 'pick.readyOnly': 'Ready only',
- 'pick.multi': 'Pick several',
- 'pick.multiHint': 'When on, tap templates to add or remove them, up to 12. Each one makes a video from the same text.',
- 'pick.count': '{ready}/{total} templates ready',
- 'pick.max': 'Up to {max} templates per run. Remove one to pick another.',
- 'grid.loading': 'Loading templates…',
- 'grid.loadErr': "Couldn't load templates. Check the server, then reload the page.",
- 'grid.empty': 'No matching templates. Clear the filters or try another word.',
- 'tpl.aria': (v) => `Template ${v.id}: ${v.name}${v.ready ? '' : ' (no guidance yet, not usable)'}${v.order ? `, picked #${v.order}` : ''}`,
- 'tpl.noThumb': 'no image',
- 'tpl.ready': 'Ready',
- 'tpl.noGuide': 'No guidance',
- 'tpl.playDemo': 'Play demo video for template {id}',
- 'tpl.playRef': 'Play reference video for template {id}',
- // ---- template packs (.lumpack) ----
- 'src.builtin': 'Built-in',
- 'src.local': 'Mine',
- 'src.pack': 'Community',
- 'grid.emptySrc.local': 'No templates of your own yet. Ones you create or import from your own pack show up here.',
- 'grid.emptySrc.pack': 'No community packs installed yet.',
- 'pack.importBtn': 'Import pack',
- 'pack.mineBtn': 'My packs',
- 'pack.lockedNote': 'Outside templates run locked: the AI can only read/write inside this video’s folder.',
- 'kind.template': 'Template',
- 'kind.edit-style': 'Edit style',
- 'prov.original': 'Original work',
- 'prov.own-video': 'Learned from the author’s own video',
- 'prov.style-study': 'Style study of another video',
- 'pk.title': 'Import a template pack',
- 'pk.close': 'Close',
- 'pk.dropBig': 'Choose a .lumpack file',
- 'pk.dropSmall': 'or drop it here · up to 12 MB · you preview it before installing',
- 'pk.reading': 'Reading and checking the pack…',
- 'pk.restricted': 'Community templates run locked: the AI can only read/write inside this video’s folder.',
- 'pk.noName': '(no name)',
- 'pk.author': 'Author',
- 'pk.contact': 'Contact',
- 'pk.license': 'License',
- 'pk.provenance': 'Origin',
- 'pk.id': 'Pack ID',
- 'pk.engine': 'Needs LumReels',
- 'pk.items': 'Items',
- 'pk.sha': 'Checksum (sha256)',
- 'pk.warnHead': (v) => `${v.n} item${S(v.n)} contain${v.n === 1 ? 's' : ''} words worth reading closely (highlighted below). They aren’t blocked, but read them before installing.`,
- 'pk.warnItem': 'read closely',
- 'pk.showText': 'Show full text',
- 'pk.err.not-pack': 'This file isn’t a LumReels pack (.lumpack).',
- 'pk.err.tooBig': 'The file is larger than 12 MB.',
- 'pk.err.engine': 'This pack needs a newer LumReels. Update the app, then import again.',
- 'pk.err.rejected': 'Pack rejected: unsafe content or wrong format.',
- 'pk.err.first': 'First reason: {e}',
- 'pk.err.more': 'Show all errors ({n})',
- 'pk.err.expired': 'The preview expired (10 minutes). Choose the file again.',
- 'pk.err.net': 'Couldn’t reach the app. Check it’s still running, then try again.',
- 'pk.st.installed': 'This pack (version {v}) is already installed.',
- 'pk.st.conflict': '{id} version {v} is installed with different content: can’t overwrite it.',
- 'pk.st.older': 'A newer version ({v}) is already installed.',
- 'pk.st.upgrade': 'Version {v} is installed.',
- 'pk.replace': 'Replace it with version {v}',
- 'pk.cancel': 'Cancel',
- 'pk.other': 'Choose another file',
- 'pk.install': 'Install',
- 'pk.installing': 'Installing…',
- 'pk.done': (v) => `Installed "${v.name}": ${v.n} item${S(v.n)}. They show in the grid with the Community label.`,
- 'pk.showGrid': 'Show in grid',
- 'mp.title': 'My packs',
- 'mp.loading': 'Loading…',
- 'mp.loadErr': 'Couldn’t load the pack list.',
- 'mp.retry': 'Try again',
- 'mp.empty': 'No packs installed. Click Import pack to add templates from a .lumpack file.',
- 'mp.items': (v) => `${v.n} item${S(v.n)}`,
- 'mp.view': 'View',
- 'mp.hide': 'Hide',
- 'mp.verified': 'Reviewed',
- 'mp.remove': 'Remove',
- 'mp.removeQ': 'Remove pack "{name}"? Videos already made with it stay as they are.',
- 'mp.removeYes': 'Remove pack',
- 'mp.removed': 'Removed "{name}".',
- 'mp.deleted': 'Deleted "{name}".',
- 'mp.delItem': 'Delete',
- 'mp.delItemQ': 'Delete "{name}" from your templates? This can’t be undone.',
- 'mp.export': 'Export pack',
- 'ex.title': 'Export your own templates to a .lumpack file',
- 'ex.none': 'Nothing of your own to export yet. Templates you create (Create template button, coming soon) show up here.',
- 'ex.pick': 'Choose items',
- 'ex.name': 'Pack name',
- 'ex.id': 'Pack ID',
- 'ex.idHint': 'Format author.pack-name: lowercase without accents, digits, hyphens. Filled in from author + name.',
- 'ex.author': 'Author',
- 'ex.contact': 'Contact (optional)',
- 'ex.license': 'License',
- 'ex.version': 'Version',
- 'ex.go': 'Download .lumpack',
- 'ex.busy': 'Exporting…',
- 'ex.ok': 'Exported {file} ({kb}).',
- 'ex.err.items': 'Pick at least 1 item to export.',
- 'ex.err.name': 'Enter a pack name.',
- 'ex.err.author': 'Enter the author name.',
- 'ex.err.id': 'Pack ID must look like author.pack-name, each half 2–24 characters.',
- 'ex.err.ver': 'Version must look like 1.0.0.',
- 'ex.err.reserved': 'That author name is reserved for LumReels. Change the part before the dot.',
-
- 'picked.none': 'No template yet. Tap a bright one on the left.',
- 'picked.noneMulti': 'Multi-pick on: tap bright templates on the left (up to {max}). Each makes one video.',
- 'picked.count': (v) => `${v.n} template${S(v.n)} picked`,
- 'picked.clear': 'Clear all',
- 'picked.strip': 'Picked templates',
- 'picked.remove': 'Remove template {id}: {name}',
-
- 'viewer.aria': 'Template preview video',
- 'viewer.close': 'Close',
- 'viewer.demo': 'Demo video made with LumReels. ',
- 'viewer.ref': 'Reference video on your machine (not in the repo). ',
-
- 'compose.h': 'Your text',
- 'compose.label': 'Video text',
- 'compose.ph': 'Example: Put $100 a month into an index fund at an assumed 10% a year. How much after 20 years? Channel: Lumfin. CTA: Follow for more money tips',
- 'compose.charsTail': '/4000 characters · include your channel name and CTA if you have them',
- 'rw.btn': 'Rewrite script',
- 'rw.btnBusy': 'Rewriting',
- 'rw.hint': 'Rewrite script: AI fits your text into the slots of the picked template and the length below, keeping numbers, channel name and CTA.',
- 'rw.hintMany': 'Rewrite is off because {n} templates are picked and each has different slots. Pick 1 template to use it; otherwise all {n} videos share the text you typed.',
- 'rw.busy': 'Rewriting…',
- 'rw.needOne': 'Pick 1 template first',
- 'rw.onlyOne': 'Rewrite works with 1 template only',
- 'rw.needText': 'Type your text first (at least 10 characters)',
- 'rw.loading': 'Rewriting for template {id} · {d}… (usually 20–60 seconds)',
- 'rw.title': 'Rewrite · template {id} · {d}',
- 'rw.fallback': 'Switched to Claude Code because: {why}.',
- 'rw.use': 'Use this',
- 'rw.drop': 'Discard',
- 'rw.timeout': 'Still not done after 100 seconds, so we stopped waiting. Try again.',
- 'rw.replaced': 'Your text was replaced with the rewrite.',
- 'rw.undo': 'Undo',
- 'rw.close': 'Close',
- 'err.status': 'Error {s}',
-
- 'dur.label': 'Length',
- 'dur.range': '(3 s – 10 min)',
- 'dur.presets': 'Quick lengths',
- 'dur.hint': 'Type seconds (90) or min:sec (1:30).',
- 'dur.errEmpty': 'Enter a length, e.g. 8 or 1:30',
- 'dur.errFmt': 'Type seconds (90) or min:sec (1:30)',
- 'dur.errMin': 'Minimum 3 seconds',
- 'dur.errMax': 'Maximum 10 minutes (10:00)',
- 'dur.eqLong': '= {s} seconds ({f}).',
- 'dur.eq': '= {s} seconds. Type seconds (90) or min:sec (1:30).',
- 'dur.warn': 'A {f} video takes about {range} to render (measured: an 8-second video takes 20–60 seconds), not counting the time AI spends writing scenes. AI has to write about {scenes} connected scenes, so it costs far more tokens than an 8-second video.',
- 'unit.sec': 'seconds',
- 'unit.min': 'min',
- 'unit.hour': 'hours',
- 'num.dec': '.',
-
- 'audio.aria': 'Audio',
- 'mode.label': 'Scene builder',
- 'mode.auto': 'Auto',
- 'mode.manual': 'External agent',
- 'modeLabel.auto': 'auto',
- 'modeLabel.manual': 'external agent',
- 'mode.hintAuto': 'Auto: using {m}.',
- 'mode.hintApi': 'Calls the Claude API with your Anthropic key (set in System check or .env; billed per token, cost is saved on the job).',
- 'mode.hintClaude': 'Runs Claude Code on this machine (uses your Claude plan).',
- 'mode.hintManual': 'Only writes the brief; an external agent (MCP/CLI) writes the scenes and calls render.',
- 'mode.hintExport': ' When done, the MP4 is copied to your export folder.',
- 'model.label': 'Scene model',
- 'model.auto': 'Auto (by template)',
- 'model.autoRec': 'Auto by template ({m})',
- 'model.autoMany': 'Auto per template',
- 'model.opus': 'Opus (best, priciest)',
- 'model.sonnet': 'Sonnet (balanced)',
- 'model.haiku': 'Haiku (cheapest)',
- 'model.rec': (v) => `This template ${v.heavy ? 'uses 3D/shaders' : 'is 2D'} → ${v.m} recommended.`,
- 'model.pickFirst': 'Pick a template to see a recommendation.',
- 'model.haikuWarn': ' Haiku tends to flatten 3D scenes; use Opus.',
- 'model.override': ' (using {m} instead of the recommendation)',
- 'model.agentNote': ' With an external agent, that agent picks the model.',
- 'model.manyLight': '{n} 2D → {m}',
- 'model.manyHeavy': '{n} 3D/shader → {m}',
- 'model.manyAuto': 'Each video picks by its template: {parts}.',
- 'model.manyFixed': 'All {n} videos use {m} (recommended: {parts}).',
- 'model.haikuWarnMany': ' Haiku tends to flatten 3D scenes; use Opus for 3D templates.',
- 'runAt.label': 'Schedule',
- 'runAt.opt': '(leave blank to build now)',
- 'runAt.clear': 'Clear',
- 'runAt.clearAria': 'Clear schedule',
- 'go.build': (v) => (v.n > 1 ? `Build ${v.n} videos` : 'Build video'),
- 'go.schedule': (v) => (v.n > 1 ? `Schedule ${v.n} videos` : 'Schedule video'),
- 'go.sending': 'Sending',
- 'go.needTpl': 'Pick a template first',
- 'go.needText': 'Text needs at least 10 characters',
- 'go.badDur': 'Length is not valid',
- 'form.jobErr': "Couldn't create the job",
- 'form.retry': '. Fix it and try again.',
-
- 'jobs.h': 'Your videos',
- 'jobs.empty': 'No videos yet. Pick a template, paste your text, then hit <b>Build video</b>.',
- 'jobs.less': 'Show less',
- 'jobs.more': (v) => `Show more (${v.n} older video${S(v.n)})`,
- 'st.scheduled': 'Scheduled',
- 'st.queued': 'Queued',
- 'st.generating': 'AI writing scenes',
- 'st.waiting_agent': 'Waiting for agent',
- 'st.previewing': 'Building preview',
- 'st.rendering': 'Rendering',
- 'st.done': 'Done',
- 'st.error': 'Error',
- 'job.previewAlt': '16-frame preview',
- 'job.building': 'Building…',
- 'job.waitScene': 'Waiting for scenes',
- 'job.noImage': 'No image yet',
- 'job.tpl': 'Template {id} · {name}',
- 'job.at': 'Scheduled for {t}',
- 'job.api': 'API: {i}k in · {o}k out · ≈ ${c}',
- 'job.exported': 'Copied to: {p}',
- 'job.errUnknown': 'Unknown error',
- 'job.errTail': '. Check the log, fix the scenes, then hit Re-render.',
- 'job.agent': 'Agent reads: {prompt}\nWrites: {scene}\nThen run: node cli.mjs render {id}',
- 'job.mp4': 'Download MP4',
- 'job.preview': '16-frame preview',
- 'job.rerender': 'Re-render',
- 'job.render': 'Render',
- 'job.log': (v) => `Log (${v.n} line${S(v.n)})`,
-
- 'ap.title': 'Audio',
- 'ap.loadingOpts': 'Loading options…',
- 'ap.stop': 'Stop preview',
- 'ap.making': 'Making preview',
- 'ap.voiceLoading': 'Generating a voice sample… (the first model load can take a few minutes)',
- 'ap.prevFail': "couldn't make a preview",
- 'ap.prevErr': 'Preview failed: ',
- 'ap.keep': 'Keep current',
- 'ap.music': 'Background music',
- 'ap.musicPrev': 'Preview music',
- 'ap.voice': 'Voiceover',
- 'ap.voicePrev': 'Preview voice',
- 'ap.sfx': 'Sound effects synced to motion',
- 'ap.pickMusic': 'Pick a specific music style to preview.',
- 'ap.pickVoice': 'Pick a specific voice to preview.',
- 'ap.vAuto': 'template voice',
- 'ap.vNone': 'no voice',
- 'ap.versions': 'Versions ({n})',
- 'ap.ver': 'Version {n}',
- 'ap.latest': ' · latest',
- 'ap.noSfx': ' · no SFX',
- 'ap.view': 'Play',
- 'ap.dl': 'Download',
- 'ap.mix': 'Remix audio',
- 'ap.mixNote': "Visuals aren't rebuilt and old versions are kept. If you pick a voice for a video with no script, AI writes a short one.",
- 'ap.lastErr': 'Last mix failed: ',
- 'ap.mixing': 'Mixing audio…',
- 'ap.mixingNote': 'Mixing (VieNeu voices can take a few minutes)…',
- 'ap.err': 'Error: ',
- 'ap.unknown': 'unknown',
- 'ap.done': 'Done — playing the latest version.',
- 'ap.summary': 'Audio · change music, voice',
- 'ap.loading': 'Loading…',
- 'ap.mixFail': "Couldn't mix: ",
- 'ap.errShort': 'error',
- 'vc.title': 'My voices',
- 'vc.optTag': 'cloned voice',
- 'vc.add': '+ Add voice',
- 'vc.loading': 'Loading your voices…',
- 'vc.loadErr': "Couldn't load your voices.",
- 'vc.retry': 'Retry',
- 'vc.empty': 'No voices yet. Upload or record 10 seconds to 3 minutes of speech and the app learns it, then reads your video script in that voice.',
- 'vc.needVieneu': 'Voice cloning needs VieNeu-TTS on this machine: pip install vieneu',
- 'vc.ready': 'Ready',
- 'vc.error': 'Error',
- 'vc.step.queued': 'Waiting…',
- 'vc.step.transcribe': 'Transcribing the sample…',
- 'vc.step.encode': 'Learning the voice + test read…',
- 'vc.play': 'Play sample of {name}',
- 'vc.stop': 'Stop',
- 'vc.rename': 'Rename voice {name}',
- 'vc.delete': 'Delete voice {name}',
- 'vc.newName': 'New name',
- 'vc.save': 'Save',
- 'vc.cancel': 'Cancel',
- 'vc.refSum': 'Sample the app picked',
- 'vc.refText': 'Words spoken in the sample',
- 'vc.byWhisper': '(auto-transcribed, fix if wrong)',
- 'vc.refTextPh': 'Type exactly what you say in the sample',
- 'vc.refTextHint': 'Optional for VieNeu v3 Turbo; helps you see what the sample says.',
- 'vc.saveText': 'Save text',
- 'vc.noWhisper': "Whisper isn't installed, so the sample wasn't transcribed. Open the sample to listen and type it (optional).",
- 'vc.srcAria': 'Voice source',
- 'vc.srcFile': 'Choose file',
- 'vc.srcRec': 'Record',
- 'vc.fileLabel': 'Voice audio file',
- 'vc.fileHint': 'wav, mp3, m4a, ogg or webm · 10 seconds to 3 minutes · up to {max} MB · one speaker, little background noise.',
- 'vc.readTip': 'Tip: read this aloud naturally (Vietnamese text, since cloned voices speak Vietnamese)',
- 'vc.readText': 'Hôm nay mình muốn kể cho bạn nghe một chuyện nhỏ. Sáng nào mình cũng dậy sớm, pha một ly cà phê, mở cửa sổ và nghe phố xá bắt đầu nhộn nhịp. Có hôm trời mưa, có hôm nắng gắt, nhưng mình vẫn giữ thói quen đó. Một, hai, ba, bốn, năm: thói quen nhỏ, kết quả lớn.',
- 'vc.recStart': 'Start recording',
- 'vc.recAgain': 'Record again',
- 'vc.recStop': 'Stop',
- 'vc.recHint': 'Record somewhere quiet, a hand-width from the mic, at least 20 seconds. Stops by itself at 3 minutes.',
- 'vc.recFile': 'recording',
- 'vc.nameLabel': 'Voice name',
- 'vc.namePh': 'e.g. My voice',
- 'vc.consent': "This is my voice, or I have that person's permission to use it",
- 'vc.langNote': 'Cloned voices speak Vietnamese. Pick one for English content and the voiceover is written in Vietnamese.',
- 'vc.create': 'Create voice',
- 'vc.sending': 'Uploading… {pct}%',
- 'vc.processing': 'Got voice {name}. Learning it now, about a minute.',
- 'vc.readyNote': 'Voice {name} is ready and selected as the voiceover. Press play to hear it.',
- 'vc.errNoFile': 'Choose an audio file.',
- 'vc.errNoRec': 'Record something first.',
- 'vc.errExt': 'Unsupported format. Use wav, mp3, m4a, ogg or webm.',
- 'vc.errBig': 'File too large (max {max} MB).',
- 'vc.errShort': 'Too short ({s} seconds). It needs at least 10 seconds.',
- 'vc.errLong': 'Longer than 3 minutes. Trim it and try again.',
- 'vc.errName': 'Give the voice a name.',
- 'vc.errNameLong': 'Name can be up to {max} characters.',
- 'vc.errConsent': 'Tick the confirmation to continue.',
- 'vc.errNoMic': "This browser can't record. Choose a file instead.",
- 'vc.errMicDenied': 'Microphone access was blocked. Allow it in the browser and try again.',
- 'vc.errUpload': 'Upload failed. Check the app is still running and try again.',
- 'vc.errDel': "Couldn't delete the voice.",
- 'vc.errSave': "Couldn't save.",
- 'vc.confirmDel': 'Delete voice "{name}"? Its files on this machine are removed for good.',
- 'vc.deleted': 'Deleted voice {name}.',
- 'vc.renamed': 'Renamed to {name}.',
- 'vc.textSaved': 'Sample text saved.',
-
- 'ed.aria': 'Edit your video',
- 'ed.setupH': "Video editing isn't installed",
- 'ed.noServer': "Can't reach the server.",
- 'ed.h': 'Your video',
- 'ed.dropAria': 'Choose or drop a video',
- 'ed.dropBig': 'Drop your video here',
- 'ed.dropSmall': 'or click to choose · mp4, mov, mkv… up to 2 GB · talking to camera, in Vietnamese',
- 'ed.fileLabel': 'Video file',
- 'ed.style': 'Edit style',
- 'ed.music': 'Background music',
- 'ed.musicOpt': '(ducks while you talk)',
- 'ed.noMusic': 'No music',
- 'ed.musicSynth': 'Generated: {id} — {desc}',
- 'ed.musicFile': 'Upload my own music…',
- 'ed.musicFileLabel': 'Music file',
- 'ed.names': 'Names and terms',
- 'ed.namesOpt': '(so AI spells captions right)',
- 'ed.namesPh': 'e.g. Lumfin, Hanoi, ETF',
- 'ed.notes': 'Extra notes',
- 'ed.notesOpt': '(optional)',
- 'ed.notesPh': 'e.g. cut the opening greeting, keep the follow call at the end',
- 'ed.draft': 'Quick draft (simple captions, ~1 min faster)',
- 'ed.go': 'Build',
- 'ed.empty': 'Pick a video on the left, then hit Build.',
- 'ed.steps': 'Steps',
- 'ed.fixesH': 'Words AI fixed in the captions — please check',
- 'ed.reviseH': 'Request changes',
- 'ed.reviseLabel': 'Change request',
- 'ed.revisePh': 'e.g. "cut the first 3 seconds", "less zoom"',
- 'ed.reviseBtn': 'Re-render',
- 'ed.p1': 'cut the first 3 seconds',
- 'ed.p2': 'less zoom',
- 'ed.p3': 'lower the music',
- 'ed.p4': 'captions 2 words at a time',
- 'ed.histH': 'Revisions',
- 'ed.log': 'Log',
- 'ed.delete': 'Delete this edit',
- 'ed.listH': 'Your edits',
- 'ed.st.queued': 'Queued',
- 'ed.st.running': 'Editing',
- 'ed.st.done': 'Done',
- 'ed.st.error': 'Error',
- 'ed.waitTurn': 'Waiting in line',
- 'ed.revising': 'Revising',
- 'ed.notVideo': "This file isn't a video (mp4, mov, mkv, webm…).",
- 'ed.tooBig': 'Video is {size}, too large (max 2 GB).',
- 'ed.changeFile': '{size} · click to change',
- 'ed.needMusic': 'Choose a music file, or switch to "No music".',
- 'ed.uploading': 'Uploading {p}%',
- 'ed.uploadCut': 'Upload interrupted. Check the server and try again.',
- 'ed.listEmpty': 'Nothing here yet.',
- 'ed.err': 'Error',
- 'ed.reviseErr': 'Change failed: {e}',
- 'ed.previewAlt': 'Preview frame grid',
- 'ed.mediaEmpty': 'Your video shows up here when it is done',
- 'ed.mp4': 'Download MP4',
- 'ed.gridOut': 'Output frame grid',
- 'ed.hidden': '(hidden from captions)',
- 'ed.checksEdl': '{out} s · cut {rm} s · {z} zooms',
- 'ed.overcut': 'clipped words: {v}',
- '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.',
- 'man.h': 'Manual edit',
- 'man.tabCap': 'Captions',
- 'man.tabAud': 'Music & sound',
- 'man.tabFx': 'Zoom & graphics',
- 'man.look': 'Caption look',
- 'man.hi': 'Highlights (words in *stars* get the accent colour)',
- 'man.capHint': 'Tap a time to jump the video there. Wrap a *word* to highlight it.',
- 'man.draftNote': "A draft burns captions into the picture, so they can't be edited by hand. Turn off \"draft\" and edit again.",
- 'man.music': 'Music',
- 'man.musicKeep': 'Keep current music ({name})',
- 'man.synth': 'Built-in music: {id}',
- 'man.uploaded': 'Uploaded: {name}',
- 'man.uploading': 'Uploading {name} ({size})…',
- 'man.uploadOk': 'Uploaded {name}. Press Apply to remix the sound.',
- 'man.uploadErr': "Couldn't upload the music: {e}",
- 'man.musicGain': 'Music volume',
- 'man.duck': 'Ducking: music dips while someone speaks',
- 'man.fade': 'Fade out at the end',
- 'man.start': 'Music starts at second',
- 'man.voice': 'Voice volume (vs. music)',
- 'man.loudHint': 'The whole mix is always normalised to −14 LUFS: a louder voice means relatively quieter music and effects.',
- 'man.sfx': (v) => `Sound effects${v.n ? ` · ${v.n}` : ' · none'}`,
- 'man.zooms': 'Zooms',
- 'man.gfx': 'Graphics',
- 'man.zoomKind': (v) => `${v.kind === 'punch' ? 'Punch zoom' : 'Push zoom'} ×${v.scale}`,
- 'man.noZoom': 'This edit has no zooms.',
- 'man.noGfx': 'This edit has no graphics.',
- 'man.noLines': 'This edit has no captions.',
- 'man.remove': 'Remove',
- 'man.undo': 'Keep',
- 'man.removeN': 'Remove {what}',
- 'man.undoN': 'Keep {what}',
- 'man.jump': 'Jump to {s} s',
- 'man.lineText': 'Text of line {n}',
- 'man.lineStart': 'Start of line {n} (seconds)',
- 'man.lineEnd': 'End of line {n} (seconds)',
- 'man.split': 'Split',
- 'man.merge': 'Merge ↓',
- 'man.splitN': 'Split line {n} in two',
- 'man.mergeN': 'Merge line {n} with the next',
- 'man.delN': 'Delete line {n}',
- 'man.cantSplit': 'This line has one word; nothing to split.',
- 'man.errShort': 'A line must last at least 0.1 s (end after start).',
- 'man.errAfter': 'Starts after the end of the video ({d} s).',
- 'man.errOverlap': 'Overlaps the line before: move its start later.',
- 'man.errEmpty': 'Empty line: type something or delete it.',
- 'man.fixFirst': (v) => `Fix ${v.n} line${S(v.n)} marked red before applying.`,
- 'man.dirty': (v) => `${v.n} change${S(v.n)} · redo: ${v.what}`,
- 'man.clean': 'No changes yet.',
- 'man.wCap': 'caption layer',
- 'man.wAud': 'sound',
- 'man.wBase': 'picture',
- 'man.reset': 'Discard changes',
- 'man.apply': 'Apply',
- 'man.applying': 'Rendering…',
- 'man.running': 'Rendering manual edit',
- 'man.loadErr': "Couldn't load manual editing: {e}",
- 'man.sendFail': "Couldn't send the manual edit.",
- 'man.tag': 'Manual',
- 'man.took': 'took {s} s',
- 'man.watch': 'Watch',
- 'man.original': 'First version',
- '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.more': 'More',
- 'ed.review': (v) => `Review (${v.n})`,
- 'ed.revFixes': 'AI-fixed words',
- 'ed.revFigs': 'Unsure numbers',
- 'ed.specs': 'Specs',
- 'ed.stepOf': '{i}/{n} · {step} · {p}%',
- 'ed.revisePhS': 'cut the first 3 seconds…',
- 'man.hiShort': 'Highlights',
- 'man.hiTip': 'Wrap *words* to highlight',
- 'man.gainS': 'Volume',
- 'man.fadeS': 'Fade out',
- 'man.startS': 'Start (s)',
- 'man.duckS': 'Duck under voice',
- 'man.voiceS': 'Voice',
- 'man.dirtyS': (v) => `${v.n} change${S(v.n)}`,
- 'ed.cutRepairs': (v) => `fixed ${v.n} cut${S(v.n)} that clipped words`,
-
- // ---- Create a template from a video (learn-panel.js) ----
- 'cat.mine': 'Mine',
- 'lp.open': 'Template from a video',
- 'lp.title': 'Create a template from a video',
- 'lp.lead': 'Give it one video from this computer. The AI learns its editing style (colours, layout, pacing, motion), builds one test video with different content, then you review it and save it as your own template.',
- 'lp.back': 'Back',
- 'lp.close': 'Close',
- 'lp.loadErr': "Couldn't load the draft. Try again later.",
- 'lp.noDrafts': 'No drafts yet.',
- 'lp.new': 'Start from a new video',
- 'lp.drop': 'Drop a video here',
- 'lp.dropHint': 'or click to choose · mp4, mov, webm · 4 seconds – 3 minutes · up to 200 MB',
- 'lp.change': 'Change video',
- 'lp.refVideo': 'Reference video',
- 'lp.from': 'Which 8 seconds to learn',
- 'lp.seg': '{a}–{b} s',
- 'lp.fromHint': 'Pick the part where the style shows best. The video loops over exactly this part.',
- 'lp.name': 'Template name',
- 'lp.optional': '(optional)',
- 'lp.namePh': 'For example: Old paper cards',
- 'lp.cat': 'Group',
- 'lp.catAuto': 'Let the AI choose',
- 'lp.note': 'What is this video',
- 'lp.notePh': 'For example: food promo, big text, fast cuts',
- 'lp.rulesH': 'Learn the style, never copy',
- 'lp.rule1': 'Only colours, layout, pacing, motion and the closest open font are learned.',
- 'lp.rule2': 'Text, channel names, logos and characters seen in the video are removed from the template by code.',
- 'lp.rule3': 'The reference video stays on this computer and is deleted when you Save or Discard. The thumbnail comes from the test video.',
- 'lp.consent': "This video is mine, or I only use it to learn the editing style. I won't copy other people's characters, logos, music or images.",
- 'lp.needConsent': 'Tick the confirmation box to start',
- 'lp.skipTest': "Skip the test build (faster and cheaper, but you won't know if the template renders right)",
- 'lp.est': 'About 7–13 minutes, about 1–2.5 USD of AI at API prices (includes one 8-second test video).',
- 'lp.estNoTest': 'About 2–3 minutes, about 0.2–0.4 USD of AI at API prices. The draft will say "not test-built".',
- 'lp.go': 'Start',
- 'lp.uploading': 'Uploading the video',
- 'lp.uploadingPct': 'Uploading {p}%',
- 'lp.started': 'Video received, measuring.',
- 'lp.err.ext': "This format isn't supported. Use mp4, mov or webm.",
- 'lp.err.big': 'The video is too large (200 MB max).',
- 'lp.err.short': 'The video is too short, it needs at least {min} seconds.',
- 'lp.err.long': 'The video is too long, 3 minutes max. Trim it and try again.',
- 'lp.err.upload': "Couldn't send the video. Check the server and try again.",
- 'lp.err.run': 'Creating the template failed.',
- 'lp.st.uploaded': 'Received',
- 'lp.st.measuring': 'Measuring',
- 'lp.st.writing': 'AI writing',
- 'lp.st.testing': 'Test building',
- 'lp.st.comparing': 'Comparing',
- 'lp.st.revising': 'AI revising',
- 'lp.st.ready': 'Ready',
- 'lp.st.readyNoTest': 'Ready (not test-built)',
- 'lp.st.error': 'Error',
- 'lp.st.saved': 'Saved',
- 'lp.st.discarded': 'Discarded',
- 'lp.step.measuring': 'Measure the video (colour, pacing, motion)',
- 'lp.step.writing': 'AI writes the template from the spec',
- 'lp.step.testing': 'Build one 8-second test video',
- 'lp.step.comparing': 'Compare the test with the original',
- 'lp.step.revising': 'AI revises the template once',
- 'lp.stepNow': '{e} / ~{est}',
- 'lp.stepEst': '~{est}',
- 'lp.progress': 'Template progress',
- 'lp.canClose': 'You can close this box, the work keeps running. Reopen it with the Template from a video button.',
- 'lp.draftH': 'Template draft',
- 'lp.totals': 'Time {t} · AI cost {c}',
- 'lp.fromFile': '{f} · seconds {a}–{b}',
- 'lp.noRef': 'Reference video deleted',
- 'lp.testVideo': 'Test video',
- 'lp.notTested': 'Not test-built',
- 'lp.sheets': 'See the 16 frames side by side',
- 'lp.refSheet': 'Original',
- 'lp.refSheetAlt': '16-frame grid of the reference video',
- 'lp.testSheet': 'Test video',
- 'lp.testSheetAlt': '16-frame grid of the test video',
- 'lp.cmpH': (v) => `Measurements: ${v.n}/${v.total} off by more than 25%`,
- 'lp.cmpMetric': 'Measure',
- 'lp.cmpRef': 'Original',
- 'lp.cmpTest': 'Test',
- 'lp.cmpDev': 'Off by',
- 'lp.off': 'off',
- 'lp.near': 'close',
- 'lp.m.palette': 'Main colours',
- 'lp.m.brightness': 'Brightness',
- 'lp.m.saturation': 'Colour strength',
- 'lp.m.events': 'New elements per second',
- 'lp.m.motion': 'Amount of motion',
- 'lp.m.cuts': 'Scene cuts',
- 'lp.m.still': 'Share of still time',
- 'lp.diffsH': 'Remaining differences (AI compared both grids)',
- 'lp.diffsFixed': 'Differences the AI found and fixed in the template',
- 'lp.selfH': 'Self-check: {ok}/{n} passed',
- 'lp.yes': 'yes',
- 'lp.no': 'no',
- 'lp.guideH': 'Template (guidance)',
- 'lp.guideHint': 'The scene-building AI reads this text. You can edit it.',
- 'lp.saveText': 'Save edits',
- 'lp.unsaved': 'You have unsaved edits',
- 'lp.seenHit': 'still has text from the original video: "{s}"',
- 'lp.textOk': 'Edits saved and passed the checks.',
- 'lp.textBad': 'Edits saved, but there are errors to fix before saving the template.',
- 'lp.saveH': 'Save as a "Mine" template',
- 'lp.saveName': 'Template name',
- 'lp.slug': 'Template code',
- 'lp.slugHint': 'Lowercase letters without accents, digits, hyphens. Used in: make --template local.mine/<code>',
- 'lp.save': 'Save template',
- 'lp.retest': 'Test-build again',
- 'lp.discard': 'Discard draft',
- 'lp.discardAsk': 'Discard this draft? The reference video and the draft will be deleted.',
- 'lp.discarded': 'Draft discarded.',
- 'lp.saveNote': 'After saving, the reference video and its frames are deleted from this computer. The template runs locked: the AI only reads and writes inside the folder of the video being built.',
- 'lp.errNoSave': 'The draft failed at the test build: fix the template, then click Test-build again before saving.',
- 'lp.savedH': 'Saved to Mine',
- 'lp.savedP': 'Template {ref} is in the template grid under "Mine". Build with any content, like the built-in templates.',
- 'lp.useNow': 'Use this template',
- // ---- create screen (studio/create.js) ----
- 'cr.title': 'New project',
- 'cr.backStep': 'Previous step',
- 'cr.stepsAria': 'Steps',
- 'cr.s1': 'Clip', 'cr.s2': 'Edit style', 'cr.s3': 'Build',
- 'cr.sideAria': 'Build settings',
- 'cr.yourClip': 'Your clip',
- 'cr.changeClip': 'Change clip',
- 'cr.noClip': 'No clip yet. Drop a video into the box on the right.',
- 'cr.musicStyle': 'Style default',
- 'cr.musicUpload': 'Upload music',
- 'cr.len': 'Output length',
- 'cr.lenAuto': 'Auto',
- 'cr.lenAutoOn': 'Set a length',
- 'cr.lenAutoV': 'Auto',
- 'cr.lenV': '~{s} s',
- 'cr.names': 'Names & terms',
- 'cr.namesWhy': 'so captions spell them right',
- 'cr.namePh': 'e.g. Lumfin (Enter to add)',
- 'cr.addName': 'Add',
- 'cr.removeName': 'Remove {n}',
- 'cr.h1': 'Pick a clip',
- 'cr.sub1': 'Talking-to-camera video in Vietnamese. AI cuts pauses, writes captions, adds zooms and graphics.',
- 'cr.h2': 'Pick an edit style',
- 'cr.sub2': 'Each style is a way of cutting, captioning and adding graphics. You can change it after the build.',
- 'cr.h3': 'Building',
- 'cr.open': 'Open Studio',
- 'cr.another': 'Build another clip',
- 'cr.next': 'Next: edit style',
- 'cr.eta': 'Takes about {m} min',
- 'cr.delete': 'Delete edit {name}',
- // ---- Studio (studio/*.js) ----
- 'st.fromReel': 'From reel (kept as is)',
- 'st.reelMusic': 'Reel music',
- 'st.reelLink': '↩ Reel: {title}',
- 'st.reelBack': 'Back to this reel in the From a template tab',
- 'st.videoHint': 'Click the Video track to pick a clip, drag to pick a range; S splits the clip at the playhead; Delete cuts the selected part.',
- 'st.videoPick': 'Nothing selected on the Video track.',
- 'st.cutThis': 'Cut this part',
- 'st.restoreCut': 'Restore this cut',
- 'st.splitClip': 'Split clip at playhead (S)',
- 'st.cutDone': 'Marked {a}–{b} to cut. Publish to apply.',
- 'st.noSplitHere': 'Can’t split here (too close to the start/end or inside a cut).',
- 'st.cutsPending': (v) => `${v.n} cut${v.n === 1 ? '' : 's'} waiting to publish (−${v.s} s). The preview already skips them.`,
- 'st.cutItem': 'Cut {a}–{b}',
- 'st.showCaps': 'Show captions',
- 'st.showCapsTip': 'Imported reels already have text in the scene, so captions start off; turn on to add captions from the voice-over.',
- 'job.studio': 'Keep editing in Studio',
- 'job.studioBusy': 'Opening Studio…',
- 'job.studioErr': 'Could not open Studio: {e}',
- 'st.back': 'Back to the list',
- 'st.versions': 'Versions',
- 'st.r0': 'orig',
- 'st.r0Tip': 'First build',
- 'st.undo': 'Undo (Ctrl+Z)',
- 'st.redo': 'Redo (Ctrl+Shift+Z)',
- 'st.needReview': 'Review',
- 'st.publish': (v) => `Publish new (${v.n} change${v.n === 1 ? '' : 's'})`,
- 'st.publishing': 'Publishing',
- 'st.published': 'Published r{n}. Now showing the new version.',
- 'st.resetAsk': 'Discard all unpublished changes?',
- 'st.tools': 'Tools',
- 'st.railAi': 'AI edit',
- 'st.trVideo': 'Video', 'st.trCap': 'Captions', 'st.trZoom': 'Zoom', 'st.trGfx': 'Graphics', 'st.trMusic': 'Music',
- 'st.timeline': 'Timeline',
- 'st.splitS': 'Split caption at playhead (S)',
- 'st.mergeNext': 'Merge with next line',
- 'st.delSel': 'Delete selected block (Delete)',
- 'st.addZoom': 'Add zoom at playhead',
- 'st.zoomIn': 'Zoom timeline in',
- 'st.zoomOut': 'Zoom timeline out',
- 'st.fitAll': 'Fit: show the whole video',
- 'st.tlZoom': 'Timeline zoom (Ctrl + wheel)',
- 'st.noMusic': 'No music',
- 'st.lineText': 'Edit caption text',
- 'st.play': 'Play', 'st.pause': 'Pause',
- 'st.prevFrame': 'Back 1 frame (←, Shift: 1 s)',
- 'st.nextFrame': 'Forward 1 frame (→, Shift: 1 s)',
- 'st.viewOut': 'Export',
- 'st.viewingOut': 'Watching the exported MP4',
- 'st.closeSheet': 'Close panel',
- 'st.readOnly': 'Viewing an older version: read only. Pick the latest version to edit.',
- 'st.capLines': 'Lines',
- 'st.capLook': 'Look',
- 'st.capReview': (v) => `Review · ${v.n}`,
- 'st.flagged': 'Has something to review',
- 'st.markHi': 'Highlight: wrap the selected words to color them',
- 'st.del': 'Delete',
- 'st.aiFixed': 'AI changed “{heard}” to “{text}”',
- 'st.figCheck': 'Number “{text}” — heard: “{said}”',
- 'st.lineErr.short': 'Line is shorter than 0.1 s.',
- 'st.lineErr.after': 'Line starts after the end of the video.',
- 'st.lineErr.overlap': 'Line overlaps the previous one.',
- 'st.lineErr.empty': 'Line has no text.',
- 'st.reviewH': 'Review',
- 'st.reviewNone': 'Nothing to review.',
- 'st.prevItem': 'Previous item', 'st.nextItem': 'Next item',
- 'st.rFix': 'AI fix', 'st.rFig': 'Number',
- 'st.rKeep': 'Keep', 'st.rEdit': 'Edit', 'st.rRevert': 'Revert',
- 'st.rNoRevert': 'Can’t revert: the line no longer has the AI-fixed words',
- 'st.rNoGfx': 'The graphic with this number is not in this version (dropped at build).',
- 'st.rGfxCell': '{g} cell: “{cell}” → Revert to “{to}” (what was heard)',
- 'st.rStatus.keep': 'Kept', 'st.rStatus.edit': 'Opened for editing', 'st.rStatus.revert': 'Reverted to what was heard',
- 'st.uploadMusic': 'Upload a track',
- 'st.gain': 'Music volume',
- 'st.zoomKind': 'Zoom type',
- 'st.push': 'Slow push', 'st.punch': 'Punch', 'st.pushS': 'Push', 'st.punchS': 'Punch',
- 'st.pushHint': 'Slowly zooms over the whole block, eases back at the end.',
- 'st.punchHint': 'Snaps in, holds, then snaps back.',
- 'st.zStrength': 'Strength',
- 'st.zLength': 'Length',
- 'st.zoomPick': 'Pick a zoom block on the timeline, or add one at the playhead.',
- 'st.zoomHere': 'The playhead is inside a zoom: selected it.',
- 'st.zoomNoRoom': 'Not enough room for a new zoom here.',
- 'st.gfxPick': 'Pick a graphic on the timeline to edit its text, numbers and timing.',
- 'st.gStart': 'Graphic start time', 'st.gEnd': 'Graphic end time',
- 'st.estimate': 'estimate',
- 'st.delGfx': 'Delete graphic',
- 'st.aiH': 'AI edit',
- 'st.aiHint': 'Say what to change; AI rebuilds from the latest version (a few minutes).',
- 'st.aiGo': 'Edit with AI',
- 'st.aiPending': (v) => `${v.n} unpublished change${v.n === 1 ? '' : 's'}: publish or discard them before an AI edit.`,
- 'st.noLineHere': 'The playhead is not on a caption line.',
- 'st.noMerge': 'Pick a line that has a next line to merge.',
- 'st.selFirst': 'Select a block on the timeline first.',
- 'st.fixFirst': (v) => `${v.n} caption line${v.n === 1 ? ' has' : 's have'} errors (red): fix before publishing.`,
- 'st.notFound': 'Could not open this edit: {e}',
- 'st.buildErr': 'This edit failed: {e}',
- 'gf.kicker': 'Kicker', 'gf.title': 'Title', 'gf.unit': 'Unit', 'gf.label': 'Label', 'gf.prefix': 'Prefix',
- 'gf.value': 'Number', 'gf.suffix': 'Suffix', 'gf.old': 'Old price', 'gf.text': 'Text', 'gf.a': 'Column A', 'gf.b': 'Column B',
- 'gf.row': 'Row {n}', 'gf.ok': 'Tick ✓',
- '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)',
- 'log.close': 'Close log', 'log.copy': 'Copy log', 'log.copied': 'Copied', 'log.copyManual': 'Text selected, press Ctrl+C',
- 'log.download': 'Download .txt', 'log.reload': 'Reload', 'log.loading': 'Reading the log…', 'log.loadErr': 'Could not read the log: {e}',
- 'log.step': 'Failed at step: {s}', 'log.rawError': 'Original error', 'log.whyUnknown': 'This error is not on the known list. The original message is below; copy the log and send it to support.',
- 'log.okDone': 'This job finished without errors.', 'log.okRunning': 'The job has not finished or failed yet. Hit Reload for new lines.',
- 'log.serverNote': (v) => `The last ${v.n} server log line${S(v.n)}. API keys, tokens and home-folder paths are hidden.`,
- 'log.rawHead': (v) => (v.total > v.n ? `Raw log: last ${v.n} of ${v.total} lines` : `Raw log: ${v.n} line${S(v.n)}`), 'log.empty': 'No log lines yet.',
- 'log.why.claude_login': 'Claude Code is not signed in.', 'log.fix.claude_login': 'Open a terminal, run claude and type /login. Once signed in, hit Re-render.',
- 'log.why.api_key': 'The Claude API key is wrong or revoked (error 401).', 'log.fix.api_key': 'Open "System check" (top button), paste a new key (get one at console.anthropic.com), click Save and check, then build again. Or pick "Claude Code" under Scene builder.',
- 'log.why.quota': 'The AI usage limit or rate limit was hit.', 'log.fix.quota': 'Top up / wait for the limit to reset, or switch to a cheaper model (Haiku) and build again.',
- 'log.why.overloaded': 'The AI servers are overloaded.', 'log.fix.overloaded': 'Wait a few minutes, then hit Re-render.',
- 'log.why.disk': 'The disk is full.', 'log.fix.disk': 'Delete old videos (jobs, edits) or free up disk space (a few GB), then build again.',
- 'log.why.cuda': 'GPU transcription failed (CUDA/cuDNN missing or the GPU ran out of memory).', 'log.fix.cuda': 'Update the NVIDIA driver, close apps using the GPU, or run node edit/setup.mjs again. Without a GPU the app transcribes on the CPU (slower).',
- 'log.why.ffmpeg': 'ffmpeg is not installed (or cannot be found).', 'log.fix.ffmpeg': 'Install ffmpeg (winget install ffmpeg on Windows, brew install ffmpeg on Mac), then restart the app.',
- 'log.why.python': 'Python or the Python packages for Edit video are missing.', 'log.fix.python': 'Install Python 3.10–3.12, then hit "Install now" in the Edit video tab (or run node edit/setup.mjs).',
- 'log.why.claude_missing': 'The claude command (Claude Code) was not found.', 'log.fix.claude_missing': 'Install Claude Code (npm i -g @anthropic-ai/claude-code), or pick "Claude API" if you have an API key.',
- 'log.why.timeout': 'It ran out of time (scene writing or rendering took too long).', 'log.fix.timeout': 'Shorten the video, pick a lighter 2D template, or build again when the computer is idle.',
- 'log.why.interrupted': 'The app was closed while the job was running.', 'log.fix.interrupted': 'Hit Re-render / Build again to continue.',
- 'log.why.network': 'No network, or the server could not be reached.', 'log.fix.network': 'Check the connection and try again.',
- 'log.why.no_scene': 'The AI did not finish the scene (scene/index.html missing).', 'log.fix.no_scene': 'Hit Re-render; if it fails again, check the raw log to see where the AI stopped.',
- 'log.why.scene_invalid': 'The scene the AI wrote has errors and cannot render.', 'log.fix.scene_invalid': 'Hit Re-render so the AI fixes it, or build again with a stronger model.',
- 'log.why.no_speech': 'No speech could be heard in the video.', 'log.fix.no_speech': 'Pick a clip with clear speech (Vietnamese), not just music.',
- 'log.why.bad_video': 'The video file is broken or in a format that cannot be read.', 'log.fix.bad_video': 'Export the video as MP4 (H.264) and upload it again.',
- 'log.why.edl_invalid': 'The AI cut plan came out inconsistent (cuts, zooms or sounds do not match).', 'log.fix.edl_invalid': 'Hit Build again; the AI will plan from scratch.',
- };
-
- // 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.
- const SRV_EN = {
- 'Tự chọn theo mẫu': 'Auto (by template)', 'Không nhạc': 'No music',
- 'Theo mẫu (chỉ đọc khi mẫu có lời)': 'Template default (only if it has a script)', 'Không lời đọc': 'No voiceover',
- 'Tiếng Việt': 'Vietnamese',
- nam: 'male', 'nữ': 'female', 'Bắc': 'North', Trung: 'Central', Nam: 'South',
- 'tự nhiên (mặc định)': 'natural (default)', 'kể chuyện, trầm': 'storytelling, deep', 'tự nhiên': 'natural', 'lầy': 'goofy',
- 'tin tức': 'news', 'kể chuyện': 'storytelling', 'đọc truyện': 'audiobook', 'cần mạng': 'needs internet',
- 'ấm, tự nhiên (mặc định)': 'warm, natural (default)', 'sáng, nhiều cảm xúc': 'bright, expressive', 'trầm, điềm đạm': 'deep, calm',
- 'khoẻ, dứt khoát': 'strong, crisp', 'nhẹ nhàng, rõ chữ': 'soft, clear', 'trầm, kể chuyện': 'deep, storytelling',
- 'lofi ấm, chậm, có tiếng đĩa than (78 BPM)': 'warm lo-fi, slow, vinyl crackle (78 BPM)',
- 'pop sáng, 4 phách đều, vui tươi (118 BPM)': 'bright pop, steady four-beat, cheerful (118 BPM)',
- 'drone căng, nhịp tim, tích tắc (70 BPM)': 'tense drone, heartbeat, ticking (70 BPM)',
- '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',
- // ghi chú bước của "Tạo mẫu từ video"
- 'đã sửa guidance': 'guidance revised', 'giữ nguyên guidance': 'guidance kept as is', 'lỗi': 'error',
- };
- // Mảnh câu trong gợi ý cài đặt / tên giọng ("Heart (US, nữ)").
- const SRV_EN_PARTS = [
- ['Cài giọng đọc: ', 'Install voices: '], ['Cài giọng Anh: ', 'Install English voices: '],
- [' (đang dùng edge-tts, cần mạng)', ' (using edge-tts for now, needs internet)'], [' (hoặc pip install edge-tts)', ' (or pip install edge-tts)'],
- [/, nữ(?=[,)])/g, ', female'], [/, nam(?=[,)])/g, ', male'],
- [/^(\d+) chỉ số lệch$/, '$1 measures off'],
- ];
-
- const TABLE = { vi, en };
- const KEY = 'lumreels.lang';
- let lang = 'vi';
- try { lang = localStorage.getItem(KEY) || ''; } catch { lang = ''; }
- if (lang !== 'vi' && lang !== 'en') lang = /^vi\b/i.test(navigator.language || '') ? 'vi' : 'en';
-
- function t(key, vars = {}) {
- let v = TABLE[lang][key];
- if (v === undefined) v = vi[key];
- if (v === undefined) return key;
- if (typeof v === 'function') return v(vars);
- return v.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
- }
- function srv(s) {
- if (lang === 'vi' || s == null) return s;
- const str = String(s);
- if (Object.prototype.hasOwnProperty.call(SRV_EN, str)) return SRV_EN[str];
- return SRV_EN_PARTS.reduce((acc, [a, b]) => (typeof a === 'string' ? acc.split(a).join(b) : acc.replace(a, b)), str);
- }
- function apply(root = document) {
- root.querySelectorAll('[data-i18n]').forEach((el) => { el.textContent = t(el.dataset.i18n); });
- root.querySelectorAll('[data-i18n-placeholder]').forEach((el) => { el.placeholder = t(el.dataset.i18nPlaceholder); });
- root.querySelectorAll('[data-i18n-aria]').forEach((el) => { el.setAttribute('aria-label', t(el.dataset.i18nAria)); });
- root.querySelectorAll('[data-i18n-title]').forEach((el) => { el.title = t(el.dataset.i18nTitle); });
- }
- function syncSwitch() {
- document.querySelectorAll('[data-lang]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.lang === lang)));
- }
- function set(next) {
- if (next !== 'vi' && next !== 'en') return;
- const changed = next !== lang;
- lang = next;
- try { localStorage.setItem(KEY, lang); } catch { /* bỏ qua */ }
- document.documentElement.lang = lang;
- apply();
- syncSwitch();
- if (changed) window.dispatchEvent(new CustomEvent('lumreels:lang', { detail: { lang } }));
- }
-
- /** Panel tự chứa thêm bảng chữ riêng: I18N.extend({ 'k': 'vi' }, { 'k': 'en' }). Khoá có sẵn không bị ghi đè. */
- function extend(moreVi = {}, moreEn = {}) {
- for (const [k, v] of Object.entries(moreVi)) if (!(k in vi)) vi[k] = v;
- for (const [k, v] of Object.entries(moreEn)) if (!(k in en)) en[k] = v;
- }
-
- window.I18N = {
- t, srv, set, apply, extend,
- get lang() { return lang; },
- /** Locale cho toLocaleString. */
- get locale() { return lang === 'vi' ? 'vi-VN' : 'en-GB'; },
- };
-
- document.addEventListener('click', (e) => { const b = e.target.closest?.('[data-lang]'); if (b) set(b.dataset.lang); });
- document.documentElement.lang = lang;
- apply();
- syncSwitch();
-})();
+// Ngôn ngữ giao diện VI / EN. Chỉ dịch chữ giao diện; tên mẫu, nội dung người dùng, lỗi server giữ nguyên.
+// HTML: data-i18n (textContent), data-i18n-placeholder, data-i18n-aria (aria-label).
+// JS: window.I18N.t(key, vars) · I18N.lang · I18N.set('vi'|'en') · I18N.srv(chuỗi server) · sự kiện window 'lumreels:lang'.
+// Giá trị trong bảng là chuỗi (thay {tên}) hoặc hàm (vars) => chuỗi (dùng cho số nhiều).
+(() => {
+ 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, 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)',
+
+ 'update.hide': 'Ẩn thông báo',
+ 'update.text': (v) => `Có ${v.n} cập nhật mới cho LumReels${v.first ? ` (${v.first}${v.n > 1 ? ', …' : ''})` : ''}. Tắt app rồi chạy lại `,
+ 'update.after': ' để cập nhật.',
+
+ 'tabs.aria': 'Chế độ',
+ 'tabs.tpl': 'Dựng từ mẫu',
+ 'tabs.edit': 'Edit video của bạn',
+ 'tabs.new': 'MỚI',
+
+ 'pick.h': 'Chọn mẫu',
+ 'pick.searchLabel': 'Tìm mẫu theo tên',
+ 'pick.searchPh': 'Tìm theo tên, thể loại…',
+ 'pick.chipsAria': 'Lọc theo nhóm',
+ 'cat.all': 'Tất cả',
+ 'cat.faceless': 'Faceless',
+ 'cat.ads': 'Quảng cáo',
+ 'cat.multi-style': 'Đa phong cách',
+ 'cat.viet-nam': 'Việt Nam hoá',
+ 'pick.readyOnly': 'Chỉ mẫu dùng được',
+ 'pick.multi': 'Chọn nhiều mẫu',
+ 'pick.multiHint': 'Bật lên thì bấm mẫu để chọn hoặc bỏ, tối đa 12 mẫu, mỗi mẫu ra 1 video cùng nội dung.',
+ 'pick.count': '{ready}/{total} mẫu dùng được',
+ 'pick.max': 'Tối đa {max} mẫu mỗi lần dựng. Bỏ bớt 1 mẫu rồi chọn tiếp.',
+ 'grid.loading': 'Đang tải mẫu…',
+ 'grid.loadErr': 'Không tải được danh sách mẫu. Kiểm tra server rồi tải lại trang.',
+ 'grid.empty': 'Không có mẫu khớp. Thử bỏ lọc hoặc đổi từ khoá.',
+ 'tpl.aria': (v) => `Mẫu ${v.id}: ${v.name}${v.ready ? '' : ' (chưa có guidance, chưa dùng được)'}${v.order ? `, đã chọn thứ ${v.order}` : ''}`,
+ 'tpl.noThumb': 'chưa có ảnh',
+ 'tpl.ready': 'Sẵn sàng',
+ 'tpl.noGuide': 'Chưa có guidance',
+ 'tpl.playDemo': 'Xem video demo mẫu {id}',
+ 'tpl.playRef': 'Xem video tham chiếu mẫu {id}',
+ // ---- gói mẫu (.lumpack) ----
+ 'src.builtin': 'Gốc',
+ 'src.local': 'Của tôi',
+ 'src.pack': 'Cộng đồng',
+ 'grid.emptySrc.local': 'Chưa có mẫu "Của tôi". Mẫu tự tạo hoặc nhập từ gói của bạn sẽ hiện ở đây.',
+ 'grid.emptySrc.pack': 'Chưa cài gói cộng đồng nào.',
+ 'pack.importBtn': 'Nhập gói',
+ 'pack.mineBtn': 'Gói của tôi',
+ 'pack.lockedNote': 'Mẫu ngoài chạy ở chế độ khoá: AI chỉ đọc/ghi trong thư mục của video này.',
+ 'kind.template': 'Mẫu dựng',
+ 'kind.edit-style': 'Cách dựng Edit',
+ 'prov.original': 'Tự sáng tác',
+ 'prov.own-video': 'Học từ video của chính tác giả',
+ 'prov.style-study': 'Học phong cách từ video khác',
+ 'pk.title': 'Nhập gói mẫu',
+ 'pk.close': 'Đóng',
+ 'pk.dropBig': 'Chọn file .lumpack',
+ 'pk.dropSmall': 'hoặc kéo thả vào đây · tối đa 12 MB · xem trước rồi mới cài',
+ 'pk.reading': 'Đang đọc và kiểm gói…',
+ 'pk.restricted': 'Mẫu cộng đồng chạy ở chế độ khoá: AI chỉ đọc/ghi trong thư mục của video này.',
+ 'pk.noName': '(không tên)',
+ 'pk.author': 'Tác giả',
+ 'pk.contact': 'Liên hệ',
+ 'pk.license': 'Giấy phép',
+ 'pk.provenance': 'Nguồn gốc',
+ 'pk.id': 'Mã gói',
+ 'pk.engine': 'Cần LumReels',
+ 'pk.items': 'Số mục',
+ 'pk.sha': 'Mã kiểm (sha256)',
+ 'pk.warnHead': (v) => `${v.n} mục có chữ cần đọc kỹ (tô vàng bên dưới). Chữ này không bị chặn, nhưng nên đọc trước khi cài.`,
+ 'pk.warnItem': 'cần đọc kỹ',
+ 'pk.showText': 'Xem nguyên văn',
+ 'pk.err.not-pack': 'File này không phải gói LumReels (.lumpack).',
+ 'pk.err.tooBig': 'File lớn hơn 12 MB.',
+ 'pk.err.engine': 'Gói này cần bản LumReels mới hơn. Cập nhật app rồi nhập lại.',
+ 'pk.err.rejected': 'Gói bị từ chối: nội dung không an toàn hoặc sai định dạng.',
+ 'pk.err.first': 'Lý do đầu tiên: {e}',
+ 'pk.err.more': 'Xem tất cả lỗi ({n})',
+ 'pk.err.expired': 'Bản xem trước đã hết hạn (10 phút). Chọn lại file.',
+ 'pk.err.net': 'Không gửi được tới app. Kiểm tra app còn chạy rồi thử lại.',
+ 'pk.st.installed': 'Gói này (bản {v}) đã cài rồi.',
+ 'pk.st.conflict': 'Đã cài {id} bản {v}, nhưng nội dung khác bản này: không cài đè được.',
+ 'pk.st.older': 'Máy đang có bản mới hơn ({v}).',
+ 'pk.st.upgrade': 'Máy đang có bản {v}.',
+ 'pk.replace': 'Thay bằng bản {v}',
+ 'pk.cancel': 'Huỷ',
+ 'pk.other': 'Chọn file khác',
+ 'pk.install': 'Cài',
+ 'pk.installing': 'Đang cài…',
+ 'pk.done': (v) => `Đã cài "${v.name}": ${v.n} mục. Mẫu hiện trong lưới với nhãn Cộng đồng.`,
+ 'pk.showGrid': 'Xem trong lưới',
+ 'mp.title': 'Gói của tôi',
+ 'mp.loading': 'Đang tải…',
+ 'mp.loadErr': 'Không tải được danh sách gói.',
+ 'mp.retry': 'Thử lại',
+ 'mp.empty': 'Chưa cài gói nào. Bấm Nhập gói để thêm mẫu từ file .lumpack.',
+ 'mp.items': '{n} mục',
+ 'mp.view': 'Xem',
+ 'mp.hide': 'Ẩn',
+ 'mp.verified': 'Đã duyệt',
+ 'mp.remove': 'Gỡ',
+ 'mp.removeQ': 'Gỡ gói "{name}"? Video đã dựng bằng gói này vẫn giữ nguyên.',
+ 'mp.removeYes': 'Gỡ gói',
+ 'mp.removed': 'Đã gỡ "{name}".',
+ 'mp.deleted': 'Đã xoá "{name}".',
+ 'mp.delItem': 'Xoá',
+ 'mp.delItemQ': 'Xoá "{name}" khỏi mẫu của tôi? Không lấy lại được.',
+ 'mp.export': 'Xuất gói',
+ 'ex.title': 'Xuất mẫu "Của tôi" ra file .lumpack',
+ 'ex.none': 'Chưa có mẫu "Của tôi" để xuất. Mẫu tự tạo (nút Tạo mẫu, sắp có) sẽ hiện ở đây.',
+ 'ex.pick': 'Chọn mục',
+ 'ex.name': 'Tên gói',
+ 'ex.id': 'Mã gói',
+ 'ex.idHint': 'Dạng tac-gia.ten-goi: chữ thường không dấu, số, gạch nối. Tự điền theo tác giả + tên.',
+ 'ex.author': 'Tác giả',
+ 'ex.contact': 'Liên hệ (không bắt buộc)',
+ 'ex.license': 'Giấy phép',
+ 'ex.version': 'Phiên bản',
+ 'ex.go': 'Tải file .lumpack',
+ 'ex.busy': 'Đang xuất…',
+ 'ex.ok': 'Đã xuất {file} ({kb}).',
+ 'ex.err.items': 'Chọn ít nhất 1 mục để xuất.',
+ 'ex.err.name': 'Điền tên gói.',
+ 'ex.err.author': 'Điền tên tác giả.',
+ 'ex.err.id': 'Mã gói phải dạng tac-gia.ten-goi, mỗi nửa 2–24 ký tự.',
+ 'ex.err.ver': 'Phiên bản phải dạng 1.0.0.',
+ 'ex.err.reserved': 'Tên tác giả này dành riêng cho LumReels. Đổi phần trước dấu chấm của mã gói.',
+
+ 'picked.none': 'Chưa chọn mẫu. Bấm 1 mẫu sáng màu bên trái.',
+ 'picked.noneMulti': 'Đang chọn nhiều: bấm các mẫu sáng màu bên trái (tối đa {max}), mỗi mẫu ra 1 video.',
+ 'picked.count': 'Đã chọn {n} mẫu',
+ 'picked.clear': 'Bỏ chọn hết',
+ 'picked.strip': 'Các mẫu đã chọn',
+ 'picked.remove': 'Bỏ mẫu {id}: {name}',
+
+ 'viewer.aria': 'Video minh hoạ của mẫu',
+ 'viewer.close': 'Đóng',
+ 'viewer.demo': 'Video demo dựng bằng LumReels. ',
+ 'viewer.ref': 'Video tham chiếu trên máy mày (không có trong repo). ',
+
+ 'compose.h': 'Nội dung',
+ 'compose.label': 'Nội dung video',
+ 'compose.ph': 'Ví dụ: Mỗi tháng bỏ 3 triệu vào quỹ chỉ số, lãi giả định 10%/năm, sau 20 năm có bao nhiêu? Kênh: Lumfin. CTA: Theo dõi để biết thêm mẹo tiền',
+ 'compose.charsTail': '/4000 ký tự · ghi luôn tên kênh và CTA nếu có',
+ 'rw.btn': 'Viết lại kịch bản',
+ 'rw.btnBusy': 'Đang viết lại',
+ 'rw.hint': 'Viết lại kịch bản: AI xếp nội dung vào đúng ô của mẫu đang chọn và thời lượng bên dưới, giữ nguyên số liệu, tên kênh, CTA.',
+ 'rw.hintMany': 'Viết lại kịch bản tắt vì đang chọn {n} mẫu: mỗi mẫu có ô nội dung khác nhau. Muốn AI viết lại thì chọn 1 mẫu; còn không, cả {n} video dùng chung nội dung đang gõ.',
+ 'rw.busy': 'Đang viết lại…',
+ 'rw.needOne': 'Chọn 1 mẫu trước',
+ 'rw.onlyOne': 'Chỉ viết lại được khi chọn 1 mẫu',
+ 'rw.needText': 'Gõ nội dung trước (tối thiểu 10 ký tự)',
+ 'rw.loading': 'Đang viết lại cho mẫu {id} · {d}… (thường 20–60 giây)',
+ 'rw.title': 'Bản viết lại · mẫu {id} · {d}',
+ 'rw.fallback': 'Đã chuyển sang Claude Code vì {why}.',
+ 'rw.use': 'Dùng bản này',
+ 'rw.drop': 'Bỏ',
+ 'rw.timeout': 'Quá 100 giây chưa xong, đã dừng chờ. Bấm lại thử.',
+ 'rw.replaced': 'Đã thay nội dung bằng bản viết lại.',
+ 'rw.undo': 'Hoàn tác',
+ 'rw.close': 'Đóng',
+ 'err.status': 'Lỗi {s}',
+
+ 'dur.label': 'Thời lượng',
+ 'dur.range': '(3 giây – 10 phút)',
+ 'dur.presets': 'Chọn nhanh thời lượng',
+ 'dur.hint': 'Gõ số giây (90) hoặc phút:giây (1:30).',
+ 'dur.errEmpty': 'Nhập thời lượng, vd 8 hoặc 1:30',
+ 'dur.errFmt': 'Gõ số giây (90) hoặc phút:giây (1:30)',
+ 'dur.errMin': 'Ngắn nhất 3 giây',
+ 'dur.errMax': 'Dài nhất 10 phút (10:00)',
+ 'dur.eqLong': '= {s} giây ({f}).',
+ 'dur.eq': '= {s} giây. Gõ số giây (90) hoặc phút:giây (1:30).',
+ 'dur.warn': 'Video dài {f}: render ước tính {range} (đo thực tế: video 8 giây mất 20–60 giây render), chưa tính lúc AI viết cảnh. AI phải viết khoảng {scenes} cảnh nối nhau nên tốn token và chi phí hơn hẳn video 8 giây.',
+ 'unit.sec': 'giây',
+ 'unit.min': 'phút',
+ 'unit.hour': 'giờ',
+ 'num.dec': ',',
+
+ 'audio.aria': 'Âm thanh',
+ 'mode.label': 'Ai dựng cảnh',
+ 'mode.auto': 'Tự động',
+ 'mode.manual': 'Agent ngoài',
+ 'modeLabel.auto': 'tự động',
+ 'modeLabel.manual': 'agent ngoài',
+ 'mode.hintAuto': 'Tự động: đang dùng {m}.',
+ 'mode.hintApi': 'Gọi Claude API bằng khoá Anthropic (nhập ở Kiểm tra máy hoặc .env; tốn tiền theo token, ghi chi phí vào job).',
+ 'mode.hintClaude': 'Chạy Claude Code trên máy này (dùng gói Claude của mày).',
+ 'mode.hintManual': 'Chỉ tạo đề bài; agent bên ngoài (MCP/CLI) viết cảnh rồi gọi render.',
+ 'mode.hintExport': ' Xong sẽ chép MP4 ra thư mục xuất.',
+ 'model.label': 'Model viết cảnh',
+ 'model.auto': 'Tự chọn theo mẫu',
+ 'model.autoRec': 'Tự chọn theo mẫu ({m})',
+ 'model.autoMany': 'Tự chọn theo từng mẫu',
+ 'model.opus': 'Opus (đẹp nhất, tốn nhất)',
+ 'model.sonnet': 'Sonnet (cân bằng)',
+ 'model.haiku': 'Haiku (rẻ nhất)',
+ 'model.rec': (v) => `Mẫu này ${v.heavy ? 'dựng 3D/shader' : 'là 2D'} → đề xuất ${v.m}.`,
+ 'model.pickFirst': 'Chọn mẫu để xem đề xuất.',
+ 'model.haikuWarn': ' Haiku hay làm phẳng cảnh 3D, nên dùng Opus.',
+ 'model.override': ' (đang chọn {m} thay vì đề xuất)',
+ 'model.agentNote': ' Agent ngoài thì model do agent đó quyết.',
+ 'model.manyLight': '{n} mẫu 2D → {m}',
+ 'model.manyHeavy': '{n} mẫu 3D/shader → {m}',
+ 'model.manyAuto': 'Mỗi video tự chọn theo mẫu: {parts}.',
+ 'model.manyFixed': 'Cả {n} video dùng {m} (đề xuất: {parts}).',
+ 'model.haikuWarnMany': ' Haiku hay làm phẳng cảnh 3D, nên dùng Opus cho mẫu 3D.',
+ 'runAt.label': 'Hẹn giờ dựng',
+ 'runAt.opt': '(bỏ trống = dựng ngay)',
+ 'runAt.clear': 'Bỏ hẹn',
+ 'runAt.clearAria': 'Bỏ hẹn giờ',
+ 'go.build': (v) => (v.n > 1 ? `Dựng ${v.n} video` : 'Dựng video'),
+ 'go.schedule': (v) => (v.n > 1 ? `Hẹn dựng ${v.n} video` : 'Hẹn dựng video'),
+ 'go.sending': 'Đang gửi',
+ 'go.needTpl': 'Chọn mẫu trước',
+ 'go.needText': 'Nội dung tối thiểu 10 ký tự',
+ 'go.badDur': 'Thời lượng chưa đúng',
+ 'form.jobErr': 'Tạo job lỗi',
+ 'form.retry': '. Sửa rồi bấm lại.',
+
+ 'jobs.h': 'Video đã dựng',
+ 'jobs.empty': 'Chưa có video nào. Chọn mẫu, dán nội dung rồi bấm <b>Dựng video</b>.',
+ 'jobs.less': 'Thu gọn',
+ 'jobs.more': 'Xem thêm ({n} video cũ hơn)',
+ 'st.scheduled': 'Đã hẹn',
+ 'st.queued': 'Đang chờ',
+ 'st.generating': 'AI đang viết cảnh',
+ 'st.waiting_agent': 'Chờ agent viết cảnh',
+ 'st.previewing': 'Đang dựng preview',
+ 'st.rendering': 'Đang render',
+ 'st.done': 'Xong',
+ 'st.error': 'Lỗi',
+ 'job.previewAlt': 'Preview 16 khung',
+ 'job.building': 'Đang dựng…',
+ 'job.waitScene': 'Chờ cảnh',
+ 'job.noImage': 'Chưa có hình',
+ 'job.tpl': 'Mẫu {id} · {name}',
+ 'job.at': 'Hẹn dựng lúc {t}',
+ 'job.api': 'API: {i}k vào · {o}k ra · ≈ ${c}',
+ 'job.exported': 'Đã chép ra: {p}',
+ 'job.errUnknown': 'Lỗi không rõ',
+ 'job.errTail': '. Xem log, sửa cảnh rồi bấm Render lại.',
+ 'job.agent': 'Agent đọc: {prompt}\nViết: {scene}\nRồi chạy: node cli.mjs render {id}',
+ 'job.mp4': 'Tải MP4',
+ 'job.preview': 'Preview 16 khung',
+ 'job.rerender': 'Render lại',
+ 'job.render': 'Render',
+ 'job.log': 'Log ({n} dòng)',
+
+ 'ap.title': 'Âm thanh',
+ 'ap.loadingOpts': 'Đang tải lựa chọn…',
+ 'ap.stop': 'Dừng nghe thử',
+ 'ap.making': 'Đang tạo bản nghe thử',
+ 'ap.voiceLoading': 'Đang tạo giọng mẫu… (lần đầu nạp mô hình có thể mất vài phút)',
+ 'ap.prevFail': 'không tạo được bản nghe thử',
+ 'ap.prevErr': 'Nghe thử lỗi: ',
+ 'ap.keep': 'Giữ như hiện tại',
+ 'ap.music': 'Nhạc nền',
+ 'ap.musicPrev': 'Nghe thử nhạc nền',
+ 'ap.voice': 'Giọng đọc',
+ 'ap.voicePrev': 'Nghe thử giọng đọc',
+ 'ap.sfx': 'Tiếng động gắn theo chuyển động',
+ 'ap.pickMusic': 'Chọn 1 kiểu nhạc cụ thể để nghe thử.',
+ 'ap.pickVoice': 'Chọn 1 giọng cụ thể để nghe thử.',
+ 'ap.vAuto': 'giọng theo mẫu',
+ 'ap.vNone': 'không lời',
+ 'ap.versions': 'Các bản ({n})',
+ 'ap.ver': 'Bản {n}',
+ 'ap.latest': ' · mới nhất',
+ 'ap.noSfx': ' · không sfx',
+ 'ap.view': 'Xem',
+ 'ap.dl': 'Tải',
+ 'ap.mix': 'Trộn tiếng mới',
+ 'ap.mixNote': 'Không dựng lại hình. Bản cũ được giữ lại; chọn giọng mà video chưa có lời thì AI viết lời ngắn.',
+ 'ap.lastErr': 'Lần trộn trước lỗi: ',
+ 'ap.mixing': 'Đang trộn tiếng…',
+ 'ap.mixingNote': 'Đang trộn (giọng VieNeu có thể mất vài phút)…',
+ 'ap.err': 'Lỗi: ',
+ 'ap.unknown': 'không rõ',
+ 'ap.done': 'Xong — đang phát bản mới nhất.',
+ 'ap.summary': 'Âm thanh · đổi nhạc, giọng đọc',
+ 'ap.loading': 'Đang tải…',
+ 'ap.mixFail': 'Không trộn được: ',
+ 'ap.errShort': 'lỗi',
+ 'vc.title': 'Giọng của tôi',
+ 'vc.optTag': 'giọng nhân bản',
+ 'vc.add': '+ Thêm giọng',
+ 'vc.loading': 'Đang tải giọng của bạn…',
+ 'vc.loadErr': 'Không tải được danh sách giọng.',
+ 'vc.retry': 'Thử lại',
+ 'vc.empty': 'Chưa có giọng nào. Tải lên hoặc thu 10 giây – 3 phút giọng nói, app học giọng rồi đọc lời video bằng chính giọng đó.',
+ 'vc.needVieneu': 'Cần VieNeu-TTS trên máy để nhân bản giọng: pip install vieneu',
+ 'vc.ready': 'Sẵn sàng',
+ 'vc.error': 'Lỗi',
+ 'vc.step.queued': 'Đang chờ…',
+ 'vc.step.transcribe': 'Đang chép lời đoạn mẫu…',
+ 'vc.step.encode': 'Đang học giọng + đọc thử…',
+ 'vc.play': 'Nghe thử giọng {name}',
+ 'vc.stop': 'Dừng nghe',
+ 'vc.rename': 'Đổi tên giọng {name}',
+ 'vc.delete': 'Xoá giọng {name}',
+ 'vc.newName': 'Tên mới',
+ 'vc.save': 'Lưu',
+ 'vc.cancel': 'Huỷ',
+ 'vc.refSum': 'Đoạn mẫu app đã chọn',
+ 'vc.refText': 'Lời của đoạn mẫu',
+ 'vc.byWhisper': '(máy tự chép, sửa nếu sai)',
+ 'vc.refTextPh': 'Gõ đúng những gì bạn nói trong đoạn mẫu',
+ 'vc.refTextHint': 'Không bắt buộc với VieNeu v3 Turbo; giúp nhận ra đoạn mẫu nói gì.',
+ 'vc.saveText': 'Lưu lời',
+ 'vc.noWhisper': 'Máy chưa có whisper nên chưa chép được lời đoạn mẫu. Mở "Đoạn mẫu" để nghe và gõ lời (không bắt buộc).',
+ 'vc.srcAria': 'Lấy giọng từ',
+ 'vc.srcFile': 'Chọn file',
+ 'vc.srcRec': 'Thu âm',
+ 'vc.fileLabel': 'File âm thanh giọng nói',
+ 'vc.fileHint': 'wav, mp3, m4a, ogg hoặc webm · 10 giây – 3 phút · tối đa {max} MB · chỉ 1 người nói, ít tạp âm.',
+ 'vc.readTip': 'Gợi ý: đọc to đoạn này, tự nhiên như đang nói chuyện',
+ 'vc.readText': 'Hôm nay mình muốn kể cho bạn nghe một chuyện nhỏ. Sáng nào mình cũng dậy sớm, pha một ly cà phê, mở cửa sổ và nghe phố xá bắt đầu nhộn nhịp. Có hôm trời mưa, có hôm nắng gắt, nhưng mình vẫn giữ thói quen đó. Một, hai, ba, bốn, năm: thói quen nhỏ, kết quả lớn.',
+ 'vc.recStart': 'Bắt đầu thu',
+ 'vc.recAgain': 'Thu lại',
+ 'vc.recStop': 'Dừng',
+ 'vc.recHint': 'Thu ở chỗ yên tĩnh, cách micro một gang tay, ít nhất 20 giây. Tự dừng sau 3 phút.',
+ 'vc.recFile': 'thu-am',
+ 'vc.nameLabel': 'Tên giọng',
+ 'vc.namePh': 'Ví dụ: Giọng Nam',
+ 'vc.consent': 'Đây là giọng của tôi, hoặc tôi được người đó cho phép dùng',
+ 'vc.langNote': 'Giọng nhân bản đọc tiếng Việt. Chọn giọng này cho nội dung tiếng Anh thì lời đọc được viết bằng tiếng Việt.',
+ 'vc.create': 'Tạo giọng',
+ 'vc.sending': 'Đang gửi… {pct}%',
+ 'vc.processing': 'Đã nhận giọng {name}. Đang học giọng, khoảng 1 phút.',
+ 'vc.readyNote': 'Giọng {name} đã sẵn sàng và được chọn làm giọng đọc. Bấm nút phát để nghe thử.',
+ 'vc.errNoFile': 'Chọn 1 file âm thanh.',
+ 'vc.errNoRec': 'Thu âm trước đã.',
+ 'vc.errExt': 'Định dạng chưa hỗ trợ. Dùng wav, mp3, m4a, ogg hoặc webm.',
+ 'vc.errBig': 'File quá lớn (tối đa {max} MB).',
+ 'vc.errShort': 'Ngắn quá ({s} giây). Cần ít nhất 10 giây.',
+ 'vc.errLong': 'Dài quá 3 phút. Cắt bớt rồi thử lại.',
+ 'vc.errName': 'Đặt tên cho giọng.',
+ 'vc.errNameLong': 'Tên tối đa {max} ký tự.',
+ 'vc.errConsent': 'Tick xác nhận để tiếp tục.',
+ 'vc.errNoMic': 'Trình duyệt này không thu âm được. Chọn file thay thế.',
+ 'vc.errMicDenied': 'Chưa được dùng micro. Cho phép micro trong trình duyệt rồi thử lại.',
+ 'vc.errUpload': 'Gửi không được. Kiểm tra app còn chạy rồi thử lại.',
+ 'vc.errDel': 'Không xoá được giọng.',
+ 'vc.errSave': 'Không lưu được.',
+ 'vc.confirmDel': 'Xoá giọng "{name}"? File giọng trên máy bị xoá hẳn, không khôi phục được.',
+ 'vc.deleted': 'Đã xoá giọng {name}.',
+ 'vc.renamed': 'Đã đổi tên thành {name}.',
+ 'vc.textSaved': 'Đã lưu lời đoạn mẫu.',
+
+ 'ed.aria': 'Edit video của bạn',
+ 'ed.setupH': 'Chưa cài phần Edit video',
+ 'ed.noServer': 'Không gọi được server.',
+ 'ed.h': 'Video của bạn',
+ 'ed.dropAria': 'Chọn hoặc kéo thả video',
+ 'ed.dropBig': 'Kéo thả video vào đây',
+ 'ed.dropSmall': 'hoặc bấm để chọn · mp4, mov, mkv… tối đa 2 GB · nói trước máy, tiếng Việt',
+ 'ed.fileLabel': 'File video',
+ 'ed.style': 'Kiểu edit',
+ 'ed.music': 'Nhạc nền',
+ 'ed.musicOpt': '(tự hạ khi bạn nói)',
+ 'ed.noMusic': 'Không nhạc',
+ 'ed.musicSynth': 'Nhạc tổng hợp: {id} — {desc}',
+ 'ed.musicFile': 'Tải file nhạc của tôi…',
+ 'ed.musicFileLabel': 'File nhạc',
+ 'ed.names': 'Tên riêng, thuật ngữ',
+ 'ed.namesOpt': '(để AI viết phụ đề đúng)',
+ 'ed.namesPh': 'Ví dụ: Lumfin, Hà Nội, ETF',
+ 'ed.notes': 'Dặn thêm',
+ 'ed.notesOpt': '(không bắt buộc)',
+ 'ed.notesPh': 'Ví dụ: bỏ câu chào đầu, giữ đoạn cuối kêu gọi theo dõi',
+ 'ed.draft': 'Bản nháp nhanh (phụ đề đơn giản, nhanh hơn ~1 phút)',
+ 'ed.go': 'Dựng',
+ 'ed.empty': 'Chọn video bên trái rồi bấm Dựng.',
+ 'ed.steps': 'Các bước',
+ 'ed.fixesH': 'Chữ AI đã sửa trong phụ đề, xem lại giúp',
+ 'ed.reviseH': 'Sửa bằng lời',
+ 'ed.reviseLabel': 'Lời sửa',
+ 'ed.revisePh': 'Ví dụ: "bỏ 3 giây đầu", "zoom ít lại"',
+ 'ed.reviseBtn': 'Render lại',
+ 'ed.p1': 'bỏ 3 giây đầu',
+ 'ed.p2': 'zoom ít lại',
+ 'ed.p3': 'nhạc nhỏ lại',
+ 'ed.p4': 'phụ đề 2 chữ một lần',
+ 'ed.histH': 'Các lần sửa',
+ 'ed.log': 'Nhật ký',
+ 'ed.delete': 'Xoá bản dựng này',
+ 'ed.listH': 'Các bản đã dựng',
+ 'ed.st.queued': 'Đang chờ',
+ 'ed.st.running': 'Đang dựng',
+ 'ed.st.done': 'Xong',
+ 'ed.st.error': 'Lỗi',
+ 'ed.waitTurn': 'Đang chờ lượt',
+ 'ed.revising': 'Đang sửa',
+ 'ed.notVideo': 'File này không phải video (mp4, mov, mkv, webm…).',
+ 'ed.tooBig': 'Video {size} quá lớn (tối đa 2 GB).',
+ 'ed.changeFile': '{size} · bấm để đổi file',
+ 'ed.needMusic': 'Chọn file nhạc, hoặc đổi sang "Không nhạc".',
+ 'ed.uploading': 'Đang tải lên {p}%',
+ 'ed.uploadCut': 'Tải lên bị ngắt. Kiểm tra server rồi thử lại.',
+ 'ed.listEmpty': 'Chưa có bản nào.',
+ 'ed.err': 'Lỗi',
+ 'ed.reviseErr': 'Sửa chưa được: {e}',
+ 'ed.previewAlt': 'Lưới khung xem trước',
+ 'ed.mediaEmpty': 'Video sẽ hiện ở đây khi dựng xong',
+ 'ed.mp4': 'Tải MP4',
+ 'ed.gridOut': 'Lưới khung bản ra',
+ 'ed.hidden': '(ẩn khỏi phụ đề)',
+ 'ed.checksEdl': '{out} s · bỏ {rm} s · {z} zoom',
+ 'ed.overcut': 'lẹm chữ: {v}',
+ '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.',
+ 'man.h': 'Chỉnh tay',
+ 'man.tabCap': 'Phụ đề',
+ 'man.tabAud': 'Nhạc & tiếng',
+ 'man.tabFx': 'Zoom & đồ hoạ',
+ 'man.look': 'Kiểu chữ',
+ 'man.hi': 'Chữ nhấn (chữ trong *sao* đổi màu)',
+ 'man.capHint': 'Bấm mốc giờ để video nhảy tới dòng đó. Bọc *chữ* để nhấn.',
+ 'man.draftNote': 'Bản nháp vẽ phụ đề thẳng vào nền nên chưa sửa tay được. Bỏ "nháp" rồi dựng lại.',
+ 'man.music': 'Nhạc',
+ 'man.musicKeep': 'Giữ nhạc đang dùng ({name})',
+ 'man.synth': 'Nhạc tổng hợp: {id}',
+ 'man.uploaded': 'Đã tải: {name}',
+ 'man.uploading': 'Đang tải {name} ({size})…',
+ 'man.uploadOk': 'Đã tải lên {name}. Bấm Áp dụng để trộn lại tiếng.',
+ 'man.uploadErr': 'Tải nhạc chưa được: {e}',
+ 'man.musicGain': 'Âm lượng nhạc',
+ 'man.duck': 'Ducking: nhạc nhỏ lại khi có tiếng nói',
+ 'man.fade': 'Fade out cuối',
+ 'man.start': 'Nhạc bắt đầu từ giây',
+ 'man.voice': 'Âm lượng giọng (so với nhạc)',
+ 'man.loudHint': 'Cả bản luôn chuẩn về −14 LUFS: tăng giọng tức là nhạc và tiếng động nhỏ đi tương đối.',
+ 'man.sfx': (v) => `Tiếng động${v.n ? ` · ${v.n}` : ' · không có'}`,
+ 'man.zooms': 'Zoom',
+ 'man.gfx': 'Đồ hoạ',
+ 'man.zoomKind': (v) => `${v.kind === 'punch' ? 'Zoom giật' : 'Zoom đẩy'} ×${v.scale}`,
+ 'man.noZoom': 'Bản này không có zoom.',
+ 'man.noGfx': 'Bản này không có đồ hoạ.',
+ 'man.noLines': 'Bản này không có phụ đề.',
+ 'man.remove': 'Xoá',
+ 'man.undo': 'Giữ lại',
+ 'man.removeN': 'Xoá {what}',
+ 'man.undoN': 'Giữ lại {what}',
+ 'man.jump': 'Nhảy tới giây {s}',
+ 'man.lineText': 'Chữ dòng {n}',
+ 'man.lineStart': 'Giây bắt đầu dòng {n}',
+ 'man.lineEnd': 'Giây kết thúc dòng {n}',
+ 'man.split': 'Tách',
+ 'man.merge': 'Gộp ↓',
+ 'man.splitN': 'Tách dòng {n} làm đôi',
+ 'man.mergeN': 'Gộp dòng {n} với dòng sau',
+ 'man.delN': 'Xoá dòng {n}',
+ 'man.cantSplit': 'Dòng chỉ có 1 chữ, không tách được.',
+ 'man.errShort': 'Dòng phải dài ít nhất 0,1 giây (kết thúc sau bắt đầu).',
+ 'man.errAfter': 'Bắt đầu sau cuối video ({d} s).',
+ 'man.errOverlap': 'Đè lên dòng trước: dời giờ bắt đầu ra sau.',
+ 'man.errEmpty': 'Dòng trống: gõ chữ hoặc xoá dòng.',
+ 'man.fixFirst': (v) => `Sửa ${v.n} dòng báo đỏ trước khi áp dụng.`,
+ 'man.dirty': (v) => `${v.n} thay đổi · dựng lại: ${v.what}`,
+ 'man.clean': 'Chưa có thay đổi.',
+ 'man.wCap': 'lớp chữ',
+ 'man.wAud': 'tiếng',
+ 'man.wBase': 'nền',
+ 'man.reset': 'Bỏ thay đổi',
+ 'man.apply': 'Áp dụng',
+ 'man.applying': 'Đang dựng…',
+ 'man.running': 'Đang dựng bản chỉnh tay',
+ 'man.loadErr': 'Không tải được phần chỉnh tay: {e}',
+ 'man.sendFail': 'Không gửi được phần chỉnh tay.',
+ 'man.tag': 'Chỉnh tay',
+ 'man.took': 'dựng {s} giây',
+ 'man.watch': 'Xem',
+ 'man.original': 'Bản đầu tiên',
+ '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.more': 'Thêm',
+ 'ed.review': (v) => `Cần xem lại (${v.n})`,
+ 'ed.revFixes': 'Chữ AI sửa',
+ 'ed.revFigs': 'Số chưa chắc',
+ 'ed.specs': 'Thông số',
+ 'ed.stepOf': '{i}/{n} · {step} · {p}%',
+ 'ed.revisePhS': 'bỏ 3 giây đầu…',
+ 'man.hiShort': 'Chữ nhấn',
+ 'man.hiTip': 'Bọc *chữ* để đổi màu',
+ 'man.gainS': 'Âm lượng',
+ 'man.fadeS': 'Fade cuối',
+ 'man.startS': 'Bắt đầu (s)',
+ 'man.duckS': 'Tự hạ khi nói',
+ 'man.voiceS': 'Giọng',
+ 'man.dirtyS': (v) => `${v.n} thay đổi`,
+ 'ed.cutRepairs': (v) => `đã sửa ${v.n} vết cắt lẹm chữ`,
+
+ // ---- Tạo mẫu từ video (learn-panel.js) ----
+ 'cat.mine': 'Của tôi',
+ 'lp.open': 'Tạo mẫu từ video',
+ 'lp.title': 'Tạo mẫu từ video',
+ 'lp.lead': 'Đưa 1 video trên máy, AI học phong cách dựng (màu, bố cục, nhịp, chuyển động), dựng thử 1 bản với nội dung khác, rồi bạn xem và lưu thành mẫu của mình.',
+ 'lp.back': 'Quay lại',
+ 'lp.close': 'Đóng',
+ 'lp.loadErr': 'Không tải được nháp. Thử lại sau.',
+ 'lp.noDrafts': 'Chưa có nháp nào.',
+ 'lp.new': 'Tạo từ video mới',
+ 'lp.drop': 'Kéo thả video vào đây',
+ 'lp.dropHint': 'hoặc bấm để chọn · mp4, mov, webm · 4 giây – 3 phút · tối đa 200 MB',
+ 'lp.change': 'Đổi video',
+ 'lp.refVideo': 'Video tham khảo',
+ 'lp.from': 'Học đoạn 8 giây nào',
+ 'lp.seg': '{a}–{b} s',
+ 'lp.fromHint': 'Chọn đoạn có phong cách rõ nhất. Video đang phát lặp đúng đoạn này.',
+ 'lp.name': 'Tên mẫu',
+ 'lp.optional': '(không bắt buộc)',
+ 'lp.namePh': 'Ví dụ: Thẻ bài giấy cũ',
+ 'lp.cat': 'Nhóm',
+ 'lp.catAuto': 'Để AI chọn',
+ 'lp.note': 'Đây là video gì',
+ 'lp.notePh': 'Ví dụ: video giới thiệu món ăn, chữ to, cắt nhanh',
+ 'lp.rulesH': 'Học phong cách, không chép',
+ 'lp.rule1': 'Chỉ học màu, bố cục, nhịp, kiểu chuyển động, kiểu chữ gần nhất trong font mở.',
+ 'lp.rule2': 'Chữ, tên kênh, logo, nhân vật nhìn thấy trong video được gỡ khỏi mẫu bằng máy.',
+ 'lp.rule3': 'Video tham khảo chỉ nằm trên máy này, bị xoá khi bạn Lưu hoặc Bỏ. Ảnh đại diện lấy từ bản dựng thử.',
+ 'lp.consent': 'Video này của tôi, hoặc tôi chỉ dùng nó để học phong cách dựng. Tôi không sao chép nhân vật, logo, nhạc hay hình ảnh của người khác.',
+ 'lp.needConsent': 'Tick ô xác nhận để bắt đầu',
+ 'lp.skipTest': 'Bỏ dựng thử (nhanh và rẻ hơn, nhưng chưa biết mẫu có ra hình đúng không)',
+ 'lp.est': 'Khoảng 7–13 phút, chi phí AI khoảng 1–2,5 USD theo giá API (có dựng thử 1 video 8 giây).',
+ 'lp.estNoTest': 'Khoảng 2–3 phút, chi phí AI khoảng 0,2–0,4 USD theo giá API. Nháp sẽ ghi "chưa dựng thử".',
+ 'lp.go': 'Bắt đầu',
+ 'lp.uploading': 'Đang tải video lên',
+ 'lp.uploadingPct': 'Đang tải lên {p}%',
+ 'lp.started': 'Đã nhận video, đang đo.',
+ 'lp.err.ext': 'Định dạng này chưa hỗ trợ. Dùng mp4, mov hoặc webm.',
+ 'lp.err.big': 'Video quá nặng (tối đa 200 MB).',
+ 'lp.err.short': 'Video quá ngắn, cần ít nhất {min} giây.',
+ 'lp.err.long': 'Video quá dài, tối đa 3 phút. Cắt bớt rồi thử lại.',
+ 'lp.err.upload': 'Không gửi được video. Kiểm tra server rồi thử lại.',
+ 'lp.err.run': 'Tạo mẫu bị lỗi.',
+ 'lp.st.uploaded': 'Đã nhận',
+ 'lp.st.measuring': 'Đang đo',
+ 'lp.st.writing': 'AI đang viết',
+ 'lp.st.testing': 'Đang dựng thử',
+ 'lp.st.comparing': 'Đang so',
+ 'lp.st.revising': 'AI đang sửa',
+ 'lp.st.ready': 'Sẵn sàng',
+ 'lp.st.readyNoTest': 'Sẵn sàng (chưa dựng thử)',
+ 'lp.st.error': 'Lỗi',
+ 'lp.st.saved': 'Đã lưu',
+ 'lp.st.discarded': 'Đã bỏ',
+ 'lp.step.measuring': 'Đo video (màu, nhịp, chuyển động)',
+ 'lp.step.writing': 'AI viết mẫu theo khuôn',
+ 'lp.step.testing': 'Dựng thử 1 video 8 giây',
+ 'lp.step.comparing': 'So bản dựng thử với video gốc',
+ 'lp.step.revising': 'AI sửa mẫu 1 vòng',
+ 'lp.stepNow': '{e} / ~{est}',
+ 'lp.stepEst': '~{est}',
+ 'lp.progress': 'Tiến độ tạo mẫu',
+ 'lp.canClose': 'Có thể đóng hộp này, việc vẫn chạy. Mở lại bằng nút Tạo mẫu từ video.',
+ 'lp.draftH': 'Nháp mẫu',
+ 'lp.totals': 'Thời gian {t} · chi phí AI {c}',
+ 'lp.fromFile': '{f} · đoạn {a}–{b} s',
+ 'lp.noRef': 'Video tham khảo đã xoá',
+ 'lp.testVideo': 'Bản dựng thử',
+ 'lp.notTested': 'Chưa dựng thử',
+ 'lp.sheets': 'Xem 16 khung cạnh nhau',
+ 'lp.refSheet': 'Gốc',
+ 'lp.refSheetAlt': 'Lưới 16 khung của video tham khảo',
+ 'lp.testSheet': 'Bản dựng thử',
+ 'lp.testSheetAlt': 'Lưới 16 khung của bản dựng thử',
+ 'lp.cmpH': (v) => `So số đo: ${v.n}/${v.total} chỉ số lệch quá 25%`,
+ 'lp.cmpMetric': 'Chỉ số',
+ 'lp.cmpRef': 'Gốc',
+ 'lp.cmpTest': 'Dựng thử',
+ 'lp.cmpDev': 'Lệch',
+ 'lp.off': 'lệch',
+ 'lp.near': 'gần',
+ 'lp.m.palette': 'Bảng màu chính',
+ 'lp.m.brightness': 'Độ sáng',
+ 'lp.m.saturation': 'Độ đậm màu',
+ 'lp.m.events': 'Phần tử mới mỗi giây',
+ 'lp.m.motion': 'Mức chuyển động',
+ 'lp.m.cuts': 'Số lần cắt cảnh',
+ 'lp.m.still': 'Tỉ lệ đứng im',
+ 'lp.diffsH': 'Điểm còn lệch (AI nhìn 2 lưới)',
+ 'lp.diffsFixed': 'Điểm lệch AI thấy và đã sửa vào mẫu',
+ 'lp.selfH': 'Tự kiểm: {ok}/{n} câu đạt',
+ 'lp.yes': 'có',
+ 'lp.no': 'không',
+ 'lp.guideH': 'Mẫu (guidance)',
+ 'lp.guideHint': 'AI dựng cảnh đọc chữ này. Sửa tay được.',
+ 'lp.saveText': 'Lưu chỗ sửa',
+ 'lp.unsaved': 'Có chỗ sửa chưa lưu',
+ 'lp.seenHit': 'còn chữ của video gốc: "{s}"',
+ 'lp.textOk': 'Đã lưu chỗ sửa, qua bộ kiểm.',
+ 'lp.textBad': 'Đã lưu chỗ sửa, còn lỗi cần sửa trước khi lưu mẫu.',
+ 'lp.saveH': 'Lưu thành mẫu "Của tôi"',
+ 'lp.saveName': 'Tên mẫu',
+ 'lp.slug': 'Mã mẫu',
+ 'lp.slugHint': 'Chữ thường không dấu, số, gạch nối. Dùng trong lệnh: make --template local.mine/<mã>',
+ 'lp.save': 'Lưu thành mẫu',
+ 'lp.retest': 'Dựng thử lại',
+ 'lp.discard': 'Bỏ nháp',
+ 'lp.discardAsk': 'Bỏ nháp này? Video tham khảo và bản nháp sẽ bị xoá.',
+ 'lp.discarded': 'Đã bỏ nháp.',
+ 'lp.saveNote': 'Lưu xong, video tham khảo và khung hình bị xoá khỏi máy. Mẫu chạy ở chế độ khoá: AI chỉ đọc/ghi trong thư mục của video đang dựng.',
+ 'lp.errNoSave': 'Nháp lỗi ở bước dựng thử: sửa mẫu rồi bấm Dựng thử lại trước khi lưu.',
+ 'lp.savedH': 'Đã lưu vào Của tôi',
+ 'lp.savedP': 'Mẫu {ref} nằm trong lưới mẫu, lọc "Của tôi". Dựng với nội dung bất kỳ như mẫu gốc.',
+ 'lp.useNow': 'Dùng mẫu này',
+ // ---- màn tạo mới (studio/create.js) ----
+ 'cr.title': 'Dự án mới',
+ 'cr.backStep': 'Về bước trước',
+ 'cr.stepsAria': 'Các bước',
+ 'cr.s1': 'Clip', 'cr.s2': 'Cách dựng', 'cr.s3': 'Dựng',
+ 'cr.sideAria': 'Thiết lập bản dựng',
+ 'cr.yourClip': 'Clip của bạn',
+ 'cr.changeClip': 'Đổi clip',
+ 'cr.noClip': 'Chưa chọn clip. Kéo thả video vào ô bên phải.',
+ 'cr.musicStyle': 'Theo cách dựng',
+ 'cr.musicUpload': 'Tải nhạc',
+ 'cr.len': 'Độ dài bản ra',
+ 'cr.lenAuto': 'Tự động',
+ 'cr.lenAutoOn': 'Đặt độ dài',
+ 'cr.lenAutoV': 'Tự động',
+ 'cr.lenV': '~{s} giây',
+ 'cr.names': 'Tên riêng',
+ 'cr.namesWhy': 'để phụ đề viết đúng',
+ 'cr.namePh': 'Ví dụ: Lumfin (Enter để thêm)',
+ 'cr.addName': 'Thêm',
+ 'cr.removeName': 'Bỏ tên riêng {n}',
+ 'cr.h1': 'Chọn clip',
+ 'cr.sub1': 'Video nói trước máy, tiếng Việt. AI cắt khoảng lặng, làm phụ đề, zoom và đồ hoạ.',
+ 'cr.h2': 'Chọn cách dựng',
+ 'cr.sub2': 'Mỗi cách là một kiểu cắt, phụ đề và đồ hoạ. Đổi lại được sau khi dựng.',
+ 'cr.h3': 'Đang dựng',
+ 'cr.open': 'Mở Studio',
+ 'cr.another': 'Dựng clip khác',
+ 'cr.next': 'Tiếp: chọn cách dựng',
+ 'cr.eta': 'Mất khoảng {m} phút',
+ 'cr.delete': 'Xoá bản dựng {name}',
+ // ---- Studio (studio/*.js) ----
+ 'st.fromReel': 'Từ reel (giữ nguyên)',
+ 'st.reelMusic': 'Nhạc của reel',
+ 'st.reelLink': '↩ Reel: {title}',
+ 'st.reelBack': 'Quay về video reel này ở tab Dựng từ mẫu',
+ 'st.videoHint': 'Bấm track Video để chọn clip, kéo để chọn vùng; S tách clip tại đầu phát; Delete cắt bỏ đoạn đang chọn.',
+ 'st.videoPick': 'Chưa chọn đoạn nào trên track Video.',
+ 'st.cutThis': 'Cắt bỏ đoạn này',
+ 'st.restoreCut': 'Trả lại đoạn đã cắt',
+ 'st.splitClip': 'Tách clip tại đầu phát (S)',
+ 'st.cutDone': 'Đã đánh dấu cắt {a}–{b}. Xuất bản mới để áp dụng.',
+ 'st.noSplitHere': 'Không tách được ở đây (sát đầu/cuối hoặc trong chỗ đã cắt).',
+ 'st.cutsPending': (v) => `${v.n} chỗ cắt chờ xuất bản (−${v.s} s). Xem trước đã nhảy qua.`,
+ 'st.cutItem': 'Cắt {a}–{b}',
+ 'st.showCaps': 'Hiện phụ đề',
+ 'st.showCapsTip': 'Reel nhập vào đã có chữ trong cảnh nên phụ đề tắt sẵn; bật để vẽ thêm phụ đề từ lời đọc.',
+ 'job.studio': 'Sửa tiếp trong Studio',
+ 'job.studioBusy': 'Đang mở Studio…',
+ 'job.studioErr': 'Không mở được Studio: {e}',
+ 'st.back': 'Quay lại danh sách',
+ 'st.versions': 'Phiên bản',
+ 'st.r0': 'gốc',
+ 'st.r0Tip': 'Bản dựng đầu tiên',
+ 'st.undo': 'Hoàn tác (Ctrl+Z)',
+ 'st.redo': 'Làm lại (Ctrl+Shift+Z)',
+ 'st.needReview': 'Cần xem lại',
+ 'st.publish': (v) => `Xuất bản mới (${v.n} thay đổi)`,
+ 'st.publishing': 'Đang xuất bản',
+ 'st.published': 'Đã xuất bản r{n}. Đang xem bản mới.',
+ 'st.resetAsk': 'Bỏ hết thay đổi chưa xuất bản?',
+ 'st.tools': 'Công cụ',
+ 'st.railAi': 'Sửa lời',
+ 'st.trVideo': 'Video', 'st.trCap': 'Phụ đề', 'st.trZoom': 'Zoom', 'st.trGfx': 'Đồ hoạ', 'st.trMusic': 'Nhạc',
+ 'st.timeline': 'Dòng thời gian',
+ 'st.splitS': 'Tách phụ đề tại đầu phát (S)',
+ 'st.mergeNext': 'Gộp với dòng sau',
+ 'st.delSel': 'Xoá khối đang chọn (Delete)',
+ 'st.addZoom': 'Thêm zoom tại đầu phát',
+ 'st.zoomIn': 'Phóng to timeline',
+ 'st.zoomOut': 'Thu nhỏ timeline',
+ 'st.fitAll': 'Vừa khung: xem toàn bộ video',
+ 'st.tlZoom': 'Độ phóng timeline (Ctrl + lăn chuột)',
+ 'st.noMusic': 'Không nhạc',
+ 'st.lineText': 'Sửa chữ dòng phụ đề',
+ 'st.play': 'Phát', 'st.pause': 'Dừng',
+ 'st.prevFrame': 'Lùi 1 khung (←, Shift: 1 giây)',
+ 'st.nextFrame': 'Tới 1 khung (→, Shift: 1 giây)',
+ 'st.viewOut': 'Bản xuất',
+ 'st.viewingOut': 'Đang xem MP4 đã xuất',
+ 'st.closeSheet': 'Đóng bảng',
+ 'st.readOnly': 'Đang xem bản cũ: chỉ xem. Chọn bản mới nhất để chỉnh.',
+ 'st.capLines': 'Dòng chữ',
+ 'st.capLook': 'Kiểu chữ',
+ 'st.capReview': (v) => `Xem lại · ${v.n}`,
+ 'st.flagged': 'Có chỗ cần xem lại',
+ 'st.markHi': 'Nhấn chữ: bọc chữ đang chọn để đổi màu',
+ 'st.del': 'Xoá',
+ 'st.aiFixed': 'AI sửa “{heard}” thành “{text}”',
+ 'st.figCheck': 'Số “{text}” — nghe được: “{said}”',
+ 'st.lineErr.short': 'Dòng ngắn hơn 0,1 giây.',
+ 'st.lineErr.after': 'Dòng bắt đầu sau cuối video.',
+ 'st.lineErr.overlap': 'Dòng đè lên dòng trước.',
+ 'st.lineErr.empty': 'Dòng không có chữ.',
+ 'st.reviewH': 'Cần xem lại',
+ 'st.reviewNone': 'Không có gì cần xem lại.',
+ 'st.prevItem': 'Mục trước', 'st.nextItem': 'Mục sau',
+ 'st.rFix': 'AI sửa', 'st.rFig': 'Số',
+ 'st.rKeep': 'Giữ', 'st.rEdit': 'Sửa', 'st.rRevert': 'Trả lại',
+ 'st.rNoRevert': 'Không trả lại được: dòng không còn chữ AI đã sửa',
+ 'st.rNoGfx': 'Đồ hoạ có số này không còn trong bản (đã bị bỏ khi dựng).',
+ 'st.rGfxCell': 'Ô {g}: “{cell}” → Trả lại thành “{to}” (số nghe được)',
+ 'st.rStatus.keep': 'Đã giữ', 'st.rStatus.edit': 'Đã mở sửa', 'st.rStatus.revert': 'Đã trả lại chữ gốc',
+ 'st.uploadMusic': 'Tải bài lên',
+ 'st.gain': 'Âm lượng nhạc',
+ 'st.zoomKind': 'Kiểu zoom',
+ 'st.push': 'Đẩy chậm', 'st.punch': 'Giật nhanh', 'st.pushS': 'Đẩy', 'st.punchS': 'Giật',
+ 'st.pushHint': 'Phóng chậm suốt khối, lùi về ở cuối.',
+ 'st.punchHint': 'Phóng tức thì, giữ, rồi trả về.',
+ 'st.zStrength': 'Độ mạnh',
+ 'st.zLength': 'Độ dài',
+ 'st.zoomPick': 'Chọn 1 khối zoom trên timeline, hoặc thêm zoom tại đầu phát.',
+ 'st.zoomHere': 'Đầu phát đang ở trong 1 zoom: đã chọn zoom đó.',
+ 'st.zoomNoRoom': 'Không đủ chỗ cho zoom mới ở đây.',
+ 'st.gfxPick': 'Chọn 1 đồ hoạ trên timeline để sửa chữ, số và giờ hiện.',
+ 'st.gStart': 'Giờ bắt đầu đồ hoạ', 'st.gEnd': 'Giờ kết thúc đồ hoạ',
+ 'st.estimate': 'ước tính',
+ 'st.delGfx': 'Xoá đồ hoạ',
+ 'st.aiH': 'Sửa bằng lời (AI)',
+ 'st.aiHint': 'Nói điều muốn đổi, AI dựng lại từ bản mới nhất (vài phút).',
+ 'st.aiGo': 'Sửa bằng AI',
+ 'st.aiPending': (v) => `Còn ${v.n} thay đổi chưa xuất bản: xuất bản hoặc bỏ thay đổi trước khi sửa bằng lời.`,
+ 'st.noLineHere': 'Đầu phát không nằm trên dòng phụ đề nào.',
+ 'st.noMerge': 'Chọn 1 dòng còn dòng sau để gộp.',
+ 'st.selFirst': 'Chọn 1 khối trên timeline trước.',
+ 'st.fixFirst': (v) => `Còn ${v.n} dòng phụ đề lỗi (đỏ): sửa xong mới xuất bản được.`,
+ 'st.notFound': 'Không mở được bản này: {e}',
+ 'st.buildErr': 'Bản này dựng lỗi: {e}',
+ 'gf.kicker': 'Dòng nhỏ trên', 'gf.title': 'Tiêu đề', 'gf.unit': 'Đơn vị', 'gf.label': 'Nhãn', 'gf.prefix': 'Trước số',
+ 'gf.value': 'Số', 'gf.suffix': 'Sau số', 'gf.old': 'Giá cũ', 'gf.text': 'Chữ', 'gf.a': 'Cột A', 'gf.b': 'Cột B',
+ 'gf.row': 'Dòng {n}', 'gf.ok': 'Đánh dấu ✓',
+ '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)',
+ 'log.close': 'Đóng nhật ký', 'log.copy': 'Chép nhật ký', 'log.copied': 'Đã chép', 'log.copyManual': 'Đã chọn chữ, bấm Ctrl+C',
+ 'log.download': 'Tải file .txt', 'log.reload': 'Tải lại', 'log.loading': 'Đang đọc nhật ký…', 'log.loadErr': 'Không đọc được nhật ký: {e}',
+ 'log.step': 'Hỏng ở bước: {s}', 'log.rawError': 'Câu lỗi gốc', 'log.whyUnknown': 'Lỗi chưa có trong danh sách quen. Câu lỗi gốc ở dưới, chép nhật ký gửi người hỗ trợ.',
+ 'log.okDone': 'Job này chạy xong, không có lỗi.', 'log.okRunning': 'Job chưa xong hoặc chưa lỗi. Bấm Tải lại để xem dòng mới.',
+ 'log.serverNote': (v) => `${v.n} dòng log gần nhất của server. Khoá API, token và đường dẫn thư mục nhà đã được ẩn.`,
+ 'log.rawHead': (v) => (v.total > v.n ? `Log thô: ${v.n} dòng cuối (trong ${v.total} dòng)` : `Log thô: ${v.n} dòng`), 'log.empty': 'Chưa có dòng log nào.',
+ 'log.why.claude_login': 'Claude Code chưa đăng nhập.', 'log.fix.claude_login': 'Mở terminal, chạy lệnh claude rồi gõ /login, đăng nhập xong bấm Render lại.',
+ 'log.why.api_key': 'Khoá Claude API sai hoặc đã bị thu hồi (lỗi 401).', 'log.fix.api_key': 'Mở "Kiểm tra máy" (nút trên cùng), dán khoá mới (lấy ở console.anthropic.com), bấm Lưu và kiểm tra rồi dựng lại. Hoặc chọn "Claude Code" ở ô Ai dựng cảnh.',
+ 'log.why.quota': 'Hết hạn mức hoặc bị giới hạn tốc độ của AI.', 'log.fix.quota': 'Nạp thêm tiền / chờ hạn mức mở lại, hoặc đổi sang model rẻ hơn (Haiku) rồi dựng lại.',
+ 'log.why.overloaded': 'Máy chủ AI đang quá tải.', 'log.fix.overloaded': 'Chờ vài phút rồi bấm Render lại.',
+ 'log.why.disk': 'Ổ đĩa hết chỗ trống.', 'log.fix.disk': 'Xoá bớt video cũ (job, bản edit) hoặc dọn ổ đĩa, cần trống vài GB, rồi dựng lại.',
+ 'log.why.cuda': 'Chép lời bằng GPU lỗi (thiếu CUDA/cuDNN hoặc GPU hết bộ nhớ).', 'log.fix.cuda': 'Cập nhật driver NVIDIA, đóng app đang dùng GPU, hoặc chạy lại node edit/setup.mjs. Không có GPU thì app tự chép lời bằng CPU (chậm hơn).',
+ 'log.why.ffmpeg': 'Máy chưa có ffmpeg (hoặc không tìm thấy).', 'log.fix.ffmpeg': 'Cài ffmpeg (winget install ffmpeg trên Windows, brew install ffmpeg trên Mac) rồi khởi động lại app.',
+ 'log.why.python': 'Thiếu Python hoặc gói Python cho phần Edit video.', 'log.fix.python': 'Cài Python 3.10–3.12, rồi bấm "Cài ngay" ở tab Edit video (hoặc chạy node edit/setup.mjs).',
+ 'log.why.claude_missing': 'Không tìm thấy lệnh claude (Claude Code).', 'log.fix.claude_missing': 'Cài Claude Code (npm i -g @anthropic-ai/claude-code), hoặc chọn "Claude API" nếu đã có khoá API.',
+ 'log.why.timeout': 'Quá thời gian cho phép (AI viết cảnh hoặc render chạy quá lâu).', 'log.fix.timeout': 'Rút ngắn thời lượng, chọn mẫu 2D nhẹ hơn, hoặc dựng lại lúc máy rảnh.',
+ 'log.why.interrupted': 'App bị tắt khi job đang chạy.', 'log.fix.interrupted': 'Bấm Render lại / Dựng lại để chạy tiếp.',
+ 'log.why.network': 'Mất mạng hoặc không kết nối được máy chủ.', 'log.fix.network': 'Kiểm tra mạng rồi thử lại.',
+ 'log.why.no_scene': 'AI chưa viết xong cảnh (thiếu scene/index.html).', 'log.fix.no_scene': 'Bấm Render lại; nếu vẫn lỗi, xem log thô để biết AI dừng ở đâu.',
+ 'log.why.scene_invalid': 'Cảnh AI viết có lỗi nên không render được.', 'log.fix.scene_invalid': 'Bấm Render lại để AI sửa, hoặc dựng lại với model mạnh hơn.',
+ 'log.why.no_speech': 'Video không có tiếng nói nghe được.', 'log.fix.no_speech': 'Chọn clip có người nói rõ (tiếng Việt), không phải nhạc nền.',
+ 'log.why.bad_video': 'File video hỏng hoặc định dạng không đọc được.', 'log.fix.bad_video': 'Xuất lại video sang MP4 (H.264) rồi tải lên lại.',
+ 'log.why.edl_invalid': 'Bản dựng AI lập bị lệch (đoạn cắt, zoom, tiếng không khớp).', 'log.fix.edl_invalid': 'Bấm Dựng lại; lần sau AI sẽ lập lại từ đầu.',
+ };
+
+ 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, or 16:9, 4:3, 3:4.',
+ 'lang.group': 'Interface language',
+ 'lang.vi': 'Vietnamese (VI)',
+ 'lang.en': 'English (EN)',
+
+ 'update.hide': 'Dismiss',
+ 'update.text': (v) => `${v.n} new update${S(v.n)} for LumReels${v.first ? ` (${v.first}${v.n > 1 ? ', …' : ''})` : ''}. Quit the app and run `,
+ 'update.after': ' to update.',
+
+ 'tabs.aria': 'Mode',
+ 'tabs.tpl': 'From a template',
+ 'tabs.edit': 'Edit your video',
+ 'tabs.new': 'NEW',
+
+ 'pick.h': 'Pick a template',
+ 'pick.searchLabel': 'Search templates by name',
+ 'pick.searchPh': 'Search by name or genre…',
+ 'pick.chipsAria': 'Filter by group',
+ 'cat.all': 'All',
+ 'cat.faceless': 'Faceless',
+ 'cat.ads': 'Ads',
+ 'cat.multi-style': 'Multi-style',
+ 'cat.viet-nam': 'Vietnam edition',
+ 'pick.readyOnly': 'Ready only',
+ 'pick.multi': 'Pick several',
+ 'pick.multiHint': 'When on, tap templates to add or remove them, up to 12. Each one makes a video from the same text.',
+ 'pick.count': '{ready}/{total} templates ready',
+ 'pick.max': 'Up to {max} templates per run. Remove one to pick another.',
+ 'grid.loading': 'Loading templates…',
+ 'grid.loadErr': "Couldn't load templates. Check the server, then reload the page.",
+ 'grid.empty': 'No matching templates. Clear the filters or try another word.',
+ 'tpl.aria': (v) => `Template ${v.id}: ${v.name}${v.ready ? '' : ' (no guidance yet, not usable)'}${v.order ? `, picked #${v.order}` : ''}`,
+ 'tpl.noThumb': 'no image',
+ 'tpl.ready': 'Ready',
+ 'tpl.noGuide': 'No guidance',
+ 'tpl.playDemo': 'Play demo video for template {id}',
+ 'tpl.playRef': 'Play reference video for template {id}',
+ // ---- template packs (.lumpack) ----
+ 'src.builtin': 'Built-in',
+ 'src.local': 'Mine',
+ 'src.pack': 'Community',
+ 'grid.emptySrc.local': 'No templates of your own yet. Ones you create or import from your own pack show up here.',
+ 'grid.emptySrc.pack': 'No community packs installed yet.',
+ 'pack.importBtn': 'Import pack',
+ 'pack.mineBtn': 'My packs',
+ 'pack.lockedNote': 'Outside templates run locked: the AI can only read/write inside this video’s folder.',
+ 'kind.template': 'Template',
+ 'kind.edit-style': 'Edit style',
+ 'prov.original': 'Original work',
+ 'prov.own-video': 'Learned from the author’s own video',
+ 'prov.style-study': 'Style study of another video',
+ 'pk.title': 'Import a template pack',
+ 'pk.close': 'Close',
+ 'pk.dropBig': 'Choose a .lumpack file',
+ 'pk.dropSmall': 'or drop it here · up to 12 MB · you preview it before installing',
+ 'pk.reading': 'Reading and checking the pack…',
+ 'pk.restricted': 'Community templates run locked: the AI can only read/write inside this video’s folder.',
+ 'pk.noName': '(no name)',
+ 'pk.author': 'Author',
+ 'pk.contact': 'Contact',
+ 'pk.license': 'License',
+ 'pk.provenance': 'Origin',
+ 'pk.id': 'Pack ID',
+ 'pk.engine': 'Needs LumReels',
+ 'pk.items': 'Items',
+ 'pk.sha': 'Checksum (sha256)',
+ 'pk.warnHead': (v) => `${v.n} item${S(v.n)} contain${v.n === 1 ? 's' : ''} words worth reading closely (highlighted below). They aren’t blocked, but read them before installing.`,
+ 'pk.warnItem': 'read closely',
+ 'pk.showText': 'Show full text',
+ 'pk.err.not-pack': 'This file isn’t a LumReels pack (.lumpack).',
+ 'pk.err.tooBig': 'The file is larger than 12 MB.',
+ 'pk.err.engine': 'This pack needs a newer LumReels. Update the app, then import again.',
+ 'pk.err.rejected': 'Pack rejected: unsafe content or wrong format.',
+ 'pk.err.first': 'First reason: {e}',
+ 'pk.err.more': 'Show all errors ({n})',
+ 'pk.err.expired': 'The preview expired (10 minutes). Choose the file again.',
+ 'pk.err.net': 'Couldn’t reach the app. Check it’s still running, then try again.',
+ 'pk.st.installed': 'This pack (version {v}) is already installed.',
+ 'pk.st.conflict': '{id} version {v} is installed with different content: can’t overwrite it.',
+ 'pk.st.older': 'A newer version ({v}) is already installed.',
+ 'pk.st.upgrade': 'Version {v} is installed.',
+ 'pk.replace': 'Replace it with version {v}',
+ 'pk.cancel': 'Cancel',
+ 'pk.other': 'Choose another file',
+ 'pk.install': 'Install',
+ 'pk.installing': 'Installing…',
+ 'pk.done': (v) => `Installed "${v.name}": ${v.n} item${S(v.n)}. They show in the grid with the Community label.`,
+ 'pk.showGrid': 'Show in grid',
+ 'mp.title': 'My packs',
+ 'mp.loading': 'Loading…',
+ 'mp.loadErr': 'Couldn’t load the pack list.',
+ 'mp.retry': 'Try again',
+ 'mp.empty': 'No packs installed. Click Import pack to add templates from a .lumpack file.',
+ 'mp.items': (v) => `${v.n} item${S(v.n)}`,
+ 'mp.view': 'View',
+ 'mp.hide': 'Hide',
+ 'mp.verified': 'Reviewed',
+ 'mp.remove': 'Remove',
+ 'mp.removeQ': 'Remove pack "{name}"? Videos already made with it stay as they are.',
+ 'mp.removeYes': 'Remove pack',
+ 'mp.removed': 'Removed "{name}".',
+ 'mp.deleted': 'Deleted "{name}".',
+ 'mp.delItem': 'Delete',
+ 'mp.delItemQ': 'Delete "{name}" from your templates? This can’t be undone.',
+ 'mp.export': 'Export pack',
+ 'ex.title': 'Export your own templates to a .lumpack file',
+ 'ex.none': 'Nothing of your own to export yet. Templates you create (Create template button, coming soon) show up here.',
+ 'ex.pick': 'Choose items',
+ 'ex.name': 'Pack name',
+ 'ex.id': 'Pack ID',
+ 'ex.idHint': 'Format author.pack-name: lowercase without accents, digits, hyphens. Filled in from author + name.',
+ 'ex.author': 'Author',
+ 'ex.contact': 'Contact (optional)',
+ 'ex.license': 'License',
+ 'ex.version': 'Version',
+ 'ex.go': 'Download .lumpack',
+ 'ex.busy': 'Exporting…',
+ 'ex.ok': 'Exported {file} ({kb}).',
+ 'ex.err.items': 'Pick at least 1 item to export.',
+ 'ex.err.name': 'Enter a pack name.',
+ 'ex.err.author': 'Enter the author name.',
+ 'ex.err.id': 'Pack ID must look like author.pack-name, each half 2–24 characters.',
+ 'ex.err.ver': 'Version must look like 1.0.0.',
+ 'ex.err.reserved': 'That author name is reserved for LumReels. Change the part before the dot.',
+
+ 'picked.none': 'No template yet. Tap a bright one on the left.',
+ 'picked.noneMulti': 'Multi-pick on: tap bright templates on the left (up to {max}). Each makes one video.',
+ 'picked.count': (v) => `${v.n} template${S(v.n)} picked`,
+ 'picked.clear': 'Clear all',
+ 'picked.strip': 'Picked templates',
+ 'picked.remove': 'Remove template {id}: {name}',
+
+ 'viewer.aria': 'Template preview video',
+ 'viewer.close': 'Close',
+ 'viewer.demo': 'Demo video made with LumReels. ',
+ 'viewer.ref': 'Reference video on your machine (not in the repo). ',
+
+ 'compose.h': 'Your text',
+ 'compose.label': 'Video text',
+ 'compose.ph': 'Example: Put $100 a month into an index fund at an assumed 10% a year. How much after 20 years? Channel: Lumfin. CTA: Follow for more money tips',
+ 'compose.charsTail': '/4000 characters · include your channel name and CTA if you have them',
+ 'rw.btn': 'Rewrite script',
+ 'rw.btnBusy': 'Rewriting',
+ 'rw.hint': 'Rewrite script: AI fits your text into the slots of the picked template and the length below, keeping numbers, channel name and CTA.',
+ 'rw.hintMany': 'Rewrite is off because {n} templates are picked and each has different slots. Pick 1 template to use it; otherwise all {n} videos share the text you typed.',
+ 'rw.busy': 'Rewriting…',
+ 'rw.needOne': 'Pick 1 template first',
+ 'rw.onlyOne': 'Rewrite works with 1 template only',
+ 'rw.needText': 'Type your text first (at least 10 characters)',
+ 'rw.loading': 'Rewriting for template {id} · {d}… (usually 20–60 seconds)',
+ 'rw.title': 'Rewrite · template {id} · {d}',
+ 'rw.fallback': 'Switched to Claude Code because: {why}.',
+ 'rw.use': 'Use this',
+ 'rw.drop': 'Discard',
+ 'rw.timeout': 'Still not done after 100 seconds, so we stopped waiting. Try again.',
+ 'rw.replaced': 'Your text was replaced with the rewrite.',
+ 'rw.undo': 'Undo',
+ 'rw.close': 'Close',
+ 'err.status': 'Error {s}',
+
+ 'dur.label': 'Length',
+ 'dur.range': '(3 s – 10 min)',
+ 'dur.presets': 'Quick lengths',
+ 'dur.hint': 'Type seconds (90) or min:sec (1:30).',
+ 'dur.errEmpty': 'Enter a length, e.g. 8 or 1:30',
+ 'dur.errFmt': 'Type seconds (90) or min:sec (1:30)',
+ 'dur.errMin': 'Minimum 3 seconds',
+ 'dur.errMax': 'Maximum 10 minutes (10:00)',
+ 'dur.eqLong': '= {s} seconds ({f}).',
+ 'dur.eq': '= {s} seconds. Type seconds (90) or min:sec (1:30).',
+ 'dur.warn': 'A {f} video takes about {range} to render (measured: an 8-second video takes 20–60 seconds), not counting the time AI spends writing scenes. AI has to write about {scenes} connected scenes, so it costs far more tokens than an 8-second video.',
+ 'unit.sec': 'seconds',
+ 'unit.min': 'min',
+ 'unit.hour': 'hours',
+ 'num.dec': '.',
+
+ 'audio.aria': 'Audio',
+ 'mode.label': 'Scene builder',
+ 'mode.auto': 'Auto',
+ 'mode.manual': 'External agent',
+ 'modeLabel.auto': 'auto',
+ 'modeLabel.manual': 'external agent',
+ 'mode.hintAuto': 'Auto: using {m}.',
+ 'mode.hintApi': 'Calls the Claude API with your Anthropic key (set in System check or .env; billed per token, cost is saved on the job).',
+ 'mode.hintClaude': 'Runs Claude Code on this machine (uses your Claude plan).',
+ 'mode.hintManual': 'Only writes the brief; an external agent (MCP/CLI) writes the scenes and calls render.',
+ 'mode.hintExport': ' When done, the MP4 is copied to your export folder.',
+ 'model.label': 'Scene model',
+ 'model.auto': 'Auto (by template)',
+ 'model.autoRec': 'Auto by template ({m})',
+ 'model.autoMany': 'Auto per template',
+ 'model.opus': 'Opus (best, priciest)',
+ 'model.sonnet': 'Sonnet (balanced)',
+ 'model.haiku': 'Haiku (cheapest)',
+ 'model.rec': (v) => `This template ${v.heavy ? 'uses 3D/shaders' : 'is 2D'} → ${v.m} recommended.`,
+ 'model.pickFirst': 'Pick a template to see a recommendation.',
+ 'model.haikuWarn': ' Haiku tends to flatten 3D scenes; use Opus.',
+ 'model.override': ' (using {m} instead of the recommendation)',
+ 'model.agentNote': ' With an external agent, that agent picks the model.',
+ 'model.manyLight': '{n} 2D → {m}',
+ 'model.manyHeavy': '{n} 3D/shader → {m}',
+ 'model.manyAuto': 'Each video picks by its template: {parts}.',
+ 'model.manyFixed': 'All {n} videos use {m} (recommended: {parts}).',
+ 'model.haikuWarnMany': ' Haiku tends to flatten 3D scenes; use Opus for 3D templates.',
+ 'runAt.label': 'Schedule',
+ 'runAt.opt': '(leave blank to build now)',
+ 'runAt.clear': 'Clear',
+ 'runAt.clearAria': 'Clear schedule',
+ 'go.build': (v) => (v.n > 1 ? `Build ${v.n} videos` : 'Build video'),
+ 'go.schedule': (v) => (v.n > 1 ? `Schedule ${v.n} videos` : 'Schedule video'),
+ 'go.sending': 'Sending',
+ 'go.needTpl': 'Pick a template first',
+ 'go.needText': 'Text needs at least 10 characters',
+ 'go.badDur': 'Length is not valid',
+ 'form.jobErr': "Couldn't create the job",
+ 'form.retry': '. Fix it and try again.',
+
+ 'jobs.h': 'Your videos',
+ 'jobs.empty': 'No videos yet. Pick a template, paste your text, then hit <b>Build video</b>.',
+ 'jobs.less': 'Show less',
+ 'jobs.more': (v) => `Show more (${v.n} older video${S(v.n)})`,
+ 'st.scheduled': 'Scheduled',
+ 'st.queued': 'Queued',
+ 'st.generating': 'AI writing scenes',
+ 'st.waiting_agent': 'Waiting for agent',
+ 'st.previewing': 'Building preview',
+ 'st.rendering': 'Rendering',
+ 'st.done': 'Done',
+ 'st.error': 'Error',
+ 'job.previewAlt': '16-frame preview',
+ 'job.building': 'Building…',
+ 'job.waitScene': 'Waiting for scenes',
+ 'job.noImage': 'No image yet',
+ 'job.tpl': 'Template {id} · {name}',
+ 'job.at': 'Scheduled for {t}',
+ 'job.api': 'API: {i}k in · {o}k out · ≈ ${c}',
+ 'job.exported': 'Copied to: {p}',
+ 'job.errUnknown': 'Unknown error',
+ 'job.errTail': '. Check the log, fix the scenes, then hit Re-render.',
+ 'job.agent': 'Agent reads: {prompt}\nWrites: {scene}\nThen run: node cli.mjs render {id}',
+ 'job.mp4': 'Download MP4',
+ 'job.preview': '16-frame preview',
+ 'job.rerender': 'Re-render',
+ 'job.render': 'Render',
+ 'job.log': (v) => `Log (${v.n} line${S(v.n)})`,
+
+ 'ap.title': 'Audio',
+ 'ap.loadingOpts': 'Loading options…',
+ 'ap.stop': 'Stop preview',
+ 'ap.making': 'Making preview',
+ 'ap.voiceLoading': 'Generating a voice sample… (the first model load can take a few minutes)',
+ 'ap.prevFail': "couldn't make a preview",
+ 'ap.prevErr': 'Preview failed: ',
+ 'ap.keep': 'Keep current',
+ 'ap.music': 'Background music',
+ 'ap.musicPrev': 'Preview music',
+ 'ap.voice': 'Voiceover',
+ 'ap.voicePrev': 'Preview voice',
+ 'ap.sfx': 'Sound effects synced to motion',
+ 'ap.pickMusic': 'Pick a specific music style to preview.',
+ 'ap.pickVoice': 'Pick a specific voice to preview.',
+ 'ap.vAuto': 'template voice',
+ 'ap.vNone': 'no voice',
+ 'ap.versions': 'Versions ({n})',
+ 'ap.ver': 'Version {n}',
+ 'ap.latest': ' · latest',
+ 'ap.noSfx': ' · no SFX',
+ 'ap.view': 'Play',
+ 'ap.dl': 'Download',
+ 'ap.mix': 'Remix audio',
+ 'ap.mixNote': "Visuals aren't rebuilt and old versions are kept. If you pick a voice for a video with no script, AI writes a short one.",
+ 'ap.lastErr': 'Last mix failed: ',
+ 'ap.mixing': 'Mixing audio…',
+ 'ap.mixingNote': 'Mixing (VieNeu voices can take a few minutes)…',
+ 'ap.err': 'Error: ',
+ 'ap.unknown': 'unknown',
+ 'ap.done': 'Done — playing the latest version.',
+ 'ap.summary': 'Audio · change music, voice',
+ 'ap.loading': 'Loading…',
+ 'ap.mixFail': "Couldn't mix: ",
+ 'ap.errShort': 'error',
+ 'vc.title': 'My voices',
+ 'vc.optTag': 'cloned voice',
+ 'vc.add': '+ Add voice',
+ 'vc.loading': 'Loading your voices…',
+ 'vc.loadErr': "Couldn't load your voices.",
+ 'vc.retry': 'Retry',
+ 'vc.empty': 'No voices yet. Upload or record 10 seconds to 3 minutes of speech and the app learns it, then reads your video script in that voice.',
+ 'vc.needVieneu': 'Voice cloning needs VieNeu-TTS on this machine: pip install vieneu',
+ 'vc.ready': 'Ready',
+ 'vc.error': 'Error',
+ 'vc.step.queued': 'Waiting…',
+ 'vc.step.transcribe': 'Transcribing the sample…',
+ 'vc.step.encode': 'Learning the voice + test read…',
+ 'vc.play': 'Play sample of {name}',
+ 'vc.stop': 'Stop',
+ 'vc.rename': 'Rename voice {name}',
+ 'vc.delete': 'Delete voice {name}',
+ 'vc.newName': 'New name',
+ 'vc.save': 'Save',
+ 'vc.cancel': 'Cancel',
+ 'vc.refSum': 'Sample the app picked',
+ 'vc.refText': 'Words spoken in the sample',
+ 'vc.byWhisper': '(auto-transcribed, fix if wrong)',
+ 'vc.refTextPh': 'Type exactly what you say in the sample',
+ 'vc.refTextHint': 'Optional for VieNeu v3 Turbo; helps you see what the sample says.',
+ 'vc.saveText': 'Save text',
+ 'vc.noWhisper': "Whisper isn't installed, so the sample wasn't transcribed. Open the sample to listen and type it (optional).",
+ 'vc.srcAria': 'Voice source',
+ 'vc.srcFile': 'Choose file',
+ 'vc.srcRec': 'Record',
+ 'vc.fileLabel': 'Voice audio file',
+ 'vc.fileHint': 'wav, mp3, m4a, ogg or webm · 10 seconds to 3 minutes · up to {max} MB · one speaker, little background noise.',
+ 'vc.readTip': 'Tip: read this aloud naturally (Vietnamese text, since cloned voices speak Vietnamese)',
+ 'vc.readText': 'Hôm nay mình muốn kể cho bạn nghe một chuyện nhỏ. Sáng nào mình cũng dậy sớm, pha một ly cà phê, mở cửa sổ và nghe phố xá bắt đầu nhộn nhịp. Có hôm trời mưa, có hôm nắng gắt, nhưng mình vẫn giữ thói quen đó. Một, hai, ba, bốn, năm: thói quen nhỏ, kết quả lớn.',
+ 'vc.recStart': 'Start recording',
+ 'vc.recAgain': 'Record again',
+ 'vc.recStop': 'Stop',
+ 'vc.recHint': 'Record somewhere quiet, a hand-width from the mic, at least 20 seconds. Stops by itself at 3 minutes.',
+ 'vc.recFile': 'recording',
+ 'vc.nameLabel': 'Voice name',
+ 'vc.namePh': 'e.g. My voice',
+ 'vc.consent': "This is my voice, or I have that person's permission to use it",
+ 'vc.langNote': 'Cloned voices speak Vietnamese. Pick one for English content and the voiceover is written in Vietnamese.',
+ 'vc.create': 'Create voice',
+ 'vc.sending': 'Uploading… {pct}%',
+ 'vc.processing': 'Got voice {name}. Learning it now, about a minute.',
+ 'vc.readyNote': 'Voice {name} is ready and selected as the voiceover. Press play to hear it.',
+ 'vc.errNoFile': 'Choose an audio file.',
+ 'vc.errNoRec': 'Record something first.',
+ 'vc.errExt': 'Unsupported format. Use wav, mp3, m4a, ogg or webm.',
+ 'vc.errBig': 'File too large (max {max} MB).',
+ 'vc.errShort': 'Too short ({s} seconds). It needs at least 10 seconds.',
+ 'vc.errLong': 'Longer than 3 minutes. Trim it and try again.',
+ 'vc.errName': 'Give the voice a name.',
+ 'vc.errNameLong': 'Name can be up to {max} characters.',
+ 'vc.errConsent': 'Tick the confirmation to continue.',
+ 'vc.errNoMic': "This browser can't record. Choose a file instead.",
+ 'vc.errMicDenied': 'Microphone access was blocked. Allow it in the browser and try again.',
+ 'vc.errUpload': 'Upload failed. Check the app is still running and try again.',
+ 'vc.errDel': "Couldn't delete the voice.",
+ 'vc.errSave': "Couldn't save.",
+ 'vc.confirmDel': 'Delete voice "{name}"? Its files on this machine are removed for good.',
+ 'vc.deleted': 'Deleted voice {name}.',
+ 'vc.renamed': 'Renamed to {name}.',
+ 'vc.textSaved': 'Sample text saved.',
+
+ 'ed.aria': 'Edit your video',
+ 'ed.setupH': "Video editing isn't installed",
+ 'ed.noServer': "Can't reach the server.",
+ 'ed.h': 'Your video',
+ 'ed.dropAria': 'Choose or drop a video',
+ 'ed.dropBig': 'Drop your video here',
+ 'ed.dropSmall': 'or click to choose · mp4, mov, mkv… up to 2 GB · talking to camera, in Vietnamese',
+ 'ed.fileLabel': 'Video file',
+ 'ed.style': 'Edit style',
+ 'ed.music': 'Background music',
+ 'ed.musicOpt': '(ducks while you talk)',
+ 'ed.noMusic': 'No music',
+ 'ed.musicSynth': 'Generated: {id} — {desc}',
+ 'ed.musicFile': 'Upload my own music…',
+ 'ed.musicFileLabel': 'Music file',
+ 'ed.names': 'Names and terms',
+ 'ed.namesOpt': '(so AI spells captions right)',
+ 'ed.namesPh': 'e.g. Lumfin, Hanoi, ETF',
+ 'ed.notes': 'Extra notes',
+ 'ed.notesOpt': '(optional)',
+ 'ed.notesPh': 'e.g. cut the opening greeting, keep the follow call at the end',
+ 'ed.draft': 'Quick draft (simple captions, ~1 min faster)',
+ 'ed.go': 'Build',
+ 'ed.empty': 'Pick a video on the left, then hit Build.',
+ 'ed.steps': 'Steps',
+ 'ed.fixesH': 'Words AI fixed in the captions — please check',
+ 'ed.reviseH': 'Request changes',
+ 'ed.reviseLabel': 'Change request',
+ 'ed.revisePh': 'e.g. "cut the first 3 seconds", "less zoom"',
+ 'ed.reviseBtn': 'Re-render',
+ 'ed.p1': 'cut the first 3 seconds',
+ 'ed.p2': 'less zoom',
+ 'ed.p3': 'lower the music',
+ 'ed.p4': 'captions 2 words at a time',
+ 'ed.histH': 'Revisions',
+ 'ed.log': 'Log',
+ 'ed.delete': 'Delete this edit',
+ 'ed.listH': 'Your edits',
+ 'ed.st.queued': 'Queued',
+ 'ed.st.running': 'Editing',
+ 'ed.st.done': 'Done',
+ 'ed.st.error': 'Error',
+ 'ed.waitTurn': 'Waiting in line',
+ 'ed.revising': 'Revising',
+ 'ed.notVideo': "This file isn't a video (mp4, mov, mkv, webm…).",
+ 'ed.tooBig': 'Video is {size}, too large (max 2 GB).',
+ 'ed.changeFile': '{size} · click to change',
+ 'ed.needMusic': 'Choose a music file, or switch to "No music".',
+ 'ed.uploading': 'Uploading {p}%',
+ 'ed.uploadCut': 'Upload interrupted. Check the server and try again.',
+ 'ed.listEmpty': 'Nothing here yet.',
+ 'ed.err': 'Error',
+ 'ed.reviseErr': 'Change failed: {e}',
+ 'ed.previewAlt': 'Preview frame grid',
+ 'ed.mediaEmpty': 'Your video shows up here when it is done',
+ 'ed.mp4': 'Download MP4',
+ 'ed.gridOut': 'Output frame grid',
+ 'ed.hidden': '(hidden from captions)',
+ 'ed.checksEdl': '{out} s · cut {rm} s · {z} zooms',
+ 'ed.overcut': 'clipped words: {v}',
+ '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.',
+ 'man.h': 'Manual edit',
+ 'man.tabCap': 'Captions',
+ 'man.tabAud': 'Music & sound',
+ 'man.tabFx': 'Zoom & graphics',
+ 'man.look': 'Caption look',
+ 'man.hi': 'Highlights (words in *stars* get the accent colour)',
+ 'man.capHint': 'Tap a time to jump the video there. Wrap a *word* to highlight it.',
+ 'man.draftNote': "A draft burns captions into the picture, so they can't be edited by hand. Turn off \"draft\" and edit again.",
+ 'man.music': 'Music',
+ 'man.musicKeep': 'Keep current music ({name})',
+ 'man.synth': 'Built-in music: {id}',
+ 'man.uploaded': 'Uploaded: {name}',
+ 'man.uploading': 'Uploading {name} ({size})…',
+ 'man.uploadOk': 'Uploaded {name}. Press Apply to remix the sound.',
+ 'man.uploadErr': "Couldn't upload the music: {e}",
+ 'man.musicGain': 'Music volume',
+ 'man.duck': 'Ducking: music dips while someone speaks',
+ 'man.fade': 'Fade out at the end',
+ 'man.start': 'Music starts at second',
+ 'man.voice': 'Voice volume (vs. music)',
+ 'man.loudHint': 'The whole mix is always normalised to −14 LUFS: a louder voice means relatively quieter music and effects.',
+ 'man.sfx': (v) => `Sound effects${v.n ? ` · ${v.n}` : ' · none'}`,
+ 'man.zooms': 'Zooms',
+ 'man.gfx': 'Graphics',
+ 'man.zoomKind': (v) => `${v.kind === 'punch' ? 'Punch zoom' : 'Push zoom'} ×${v.scale}`,
+ 'man.noZoom': 'This edit has no zooms.',
+ 'man.noGfx': 'This edit has no graphics.',
+ 'man.noLines': 'This edit has no captions.',
+ 'man.remove': 'Remove',
+ 'man.undo': 'Keep',
+ 'man.removeN': 'Remove {what}',
+ 'man.undoN': 'Keep {what}',
+ 'man.jump': 'Jump to {s} s',
+ 'man.lineText': 'Text of line {n}',
+ 'man.lineStart': 'Start of line {n} (seconds)',
+ 'man.lineEnd': 'End of line {n} (seconds)',
+ 'man.split': 'Split',
+ 'man.merge': 'Merge ↓',
+ 'man.splitN': 'Split line {n} in two',
+ 'man.mergeN': 'Merge line {n} with the next',
+ 'man.delN': 'Delete line {n}',
+ 'man.cantSplit': 'This line has one word; nothing to split.',
+ 'man.errShort': 'A line must last at least 0.1 s (end after start).',
+ 'man.errAfter': 'Starts after the end of the video ({d} s).',
+ 'man.errOverlap': 'Overlaps the line before: move its start later.',
+ 'man.errEmpty': 'Empty line: type something or delete it.',
+ 'man.fixFirst': (v) => `Fix ${v.n} line${S(v.n)} marked red before applying.`,
+ 'man.dirty': (v) => `${v.n} change${S(v.n)} · redo: ${v.what}`,
+ 'man.clean': 'No changes yet.',
+ 'man.wCap': 'caption layer',
+ 'man.wAud': 'sound',
+ 'man.wBase': 'picture',
+ 'man.reset': 'Discard changes',
+ 'man.apply': 'Apply',
+ 'man.applying': 'Rendering…',
+ 'man.running': 'Rendering manual edit',
+ 'man.loadErr': "Couldn't load manual editing: {e}",
+ 'man.sendFail': "Couldn't send the manual edit.",
+ 'man.tag': 'Manual',
+ 'man.took': 'took {s} s',
+ 'man.watch': 'Watch',
+ 'man.original': 'First version',
+ '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.more': 'More',
+ 'ed.review': (v) => `Review (${v.n})`,
+ 'ed.revFixes': 'AI-fixed words',
+ 'ed.revFigs': 'Unsure numbers',
+ 'ed.specs': 'Specs',
+ 'ed.stepOf': '{i}/{n} · {step} · {p}%',
+ 'ed.revisePhS': 'cut the first 3 seconds…',
+ 'man.hiShort': 'Highlights',
+ 'man.hiTip': 'Wrap *words* to highlight',
+ 'man.gainS': 'Volume',
+ 'man.fadeS': 'Fade out',
+ 'man.startS': 'Start (s)',
+ 'man.duckS': 'Duck under voice',
+ 'man.voiceS': 'Voice',
+ 'man.dirtyS': (v) => `${v.n} change${S(v.n)}`,
+ 'ed.cutRepairs': (v) => `fixed ${v.n} cut${S(v.n)} that clipped words`,
+
+ // ---- Create a template from a video (learn-panel.js) ----
+ 'cat.mine': 'Mine',
+ 'lp.open': 'Template from a video',
+ 'lp.title': 'Create a template from a video',
+ 'lp.lead': 'Give it one video from this computer. The AI learns its editing style (colours, layout, pacing, motion), builds one test video with different content, then you review it and save it as your own template.',
+ 'lp.back': 'Back',
+ 'lp.close': 'Close',
+ 'lp.loadErr': "Couldn't load the draft. Try again later.",
+ 'lp.noDrafts': 'No drafts yet.',
+ 'lp.new': 'Start from a new video',
+ 'lp.drop': 'Drop a video here',
+ 'lp.dropHint': 'or click to choose · mp4, mov, webm · 4 seconds – 3 minutes · up to 200 MB',
+ 'lp.change': 'Change video',
+ 'lp.refVideo': 'Reference video',
+ 'lp.from': 'Which 8 seconds to learn',
+ 'lp.seg': '{a}–{b} s',
+ 'lp.fromHint': 'Pick the part where the style shows best. The video loops over exactly this part.',
+ 'lp.name': 'Template name',
+ 'lp.optional': '(optional)',
+ 'lp.namePh': 'For example: Old paper cards',
+ 'lp.cat': 'Group',
+ 'lp.catAuto': 'Let the AI choose',
+ 'lp.note': 'What is this video',
+ 'lp.notePh': 'For example: food promo, big text, fast cuts',
+ 'lp.rulesH': 'Learn the style, never copy',
+ 'lp.rule1': 'Only colours, layout, pacing, motion and the closest open font are learned.',
+ 'lp.rule2': 'Text, channel names, logos and characters seen in the video are removed from the template by code.',
+ 'lp.rule3': 'The reference video stays on this computer and is deleted when you Save or Discard. The thumbnail comes from the test video.',
+ 'lp.consent': "This video is mine, or I only use it to learn the editing style. I won't copy other people's characters, logos, music or images.",
+ 'lp.needConsent': 'Tick the confirmation box to start',
+ 'lp.skipTest': "Skip the test build (faster and cheaper, but you won't know if the template renders right)",
+ 'lp.est': 'About 7–13 minutes, about 1–2.5 USD of AI at API prices (includes one 8-second test video).',
+ 'lp.estNoTest': 'About 2–3 minutes, about 0.2–0.4 USD of AI at API prices. The draft will say "not test-built".',
+ 'lp.go': 'Start',
+ 'lp.uploading': 'Uploading the video',
+ 'lp.uploadingPct': 'Uploading {p}%',
+ 'lp.started': 'Video received, measuring.',
+ 'lp.err.ext': "This format isn't supported. Use mp4, mov or webm.",
+ 'lp.err.big': 'The video is too large (200 MB max).',
+ 'lp.err.short': 'The video is too short, it needs at least {min} seconds.',
+ 'lp.err.long': 'The video is too long, 3 minutes max. Trim it and try again.',
+ 'lp.err.upload': "Couldn't send the video. Check the server and try again.",
+ 'lp.err.run': 'Creating the template failed.',
+ 'lp.st.uploaded': 'Received',
+ 'lp.st.measuring': 'Measuring',
+ 'lp.st.writing': 'AI writing',
+ 'lp.st.testing': 'Test building',
+ 'lp.st.comparing': 'Comparing',
+ 'lp.st.revising': 'AI revising',
+ 'lp.st.ready': 'Ready',
+ 'lp.st.readyNoTest': 'Ready (not test-built)',
+ 'lp.st.error': 'Error',
+ 'lp.st.saved': 'Saved',
+ 'lp.st.discarded': 'Discarded',
+ 'lp.step.measuring': 'Measure the video (colour, pacing, motion)',
+ 'lp.step.writing': 'AI writes the template from the spec',
+ 'lp.step.testing': 'Build one 8-second test video',
+ 'lp.step.comparing': 'Compare the test with the original',
+ 'lp.step.revising': 'AI revises the template once',
+ 'lp.stepNow': '{e} / ~{est}',
+ 'lp.stepEst': '~{est}',
+ 'lp.progress': 'Template progress',
+ 'lp.canClose': 'You can close this box, the work keeps running. Reopen it with the Template from a video button.',
+ 'lp.draftH': 'Template draft',
+ 'lp.totals': 'Time {t} · AI cost {c}',
+ 'lp.fromFile': '{f} · seconds {a}–{b}',
+ 'lp.noRef': 'Reference video deleted',
+ 'lp.testVideo': 'Test video',
+ 'lp.notTested': 'Not test-built',
+ 'lp.sheets': 'See the 16 frames side by side',
+ 'lp.refSheet': 'Original',
+ 'lp.refSheetAlt': '16-frame grid of the reference video',
+ 'lp.testSheet': 'Test video',
+ 'lp.testSheetAlt': '16-frame grid of the test video',
+ 'lp.cmpH': (v) => `Measurements: ${v.n}/${v.total} off by more than 25%`,
+ 'lp.cmpMetric': 'Measure',
+ 'lp.cmpRef': 'Original',
+ 'lp.cmpTest': 'Test',
+ 'lp.cmpDev': 'Off by',
+ 'lp.off': 'off',
+ 'lp.near': 'close',
+ 'lp.m.palette': 'Main colours',
+ 'lp.m.brightness': 'Brightness',
+ 'lp.m.saturation': 'Colour strength',
+ 'lp.m.events': 'New elements per second',
+ 'lp.m.motion': 'Amount of motion',
+ 'lp.m.cuts': 'Scene cuts',
+ 'lp.m.still': 'Share of still time',
+ 'lp.diffsH': 'Remaining differences (AI compared both grids)',
+ 'lp.diffsFixed': 'Differences the AI found and fixed in the template',
+ 'lp.selfH': 'Self-check: {ok}/{n} passed',
+ 'lp.yes': 'yes',
+ 'lp.no': 'no',
+ 'lp.guideH': 'Template (guidance)',
+ 'lp.guideHint': 'The scene-building AI reads this text. You can edit it.',
+ 'lp.saveText': 'Save edits',
+ 'lp.unsaved': 'You have unsaved edits',
+ 'lp.seenHit': 'still has text from the original video: "{s}"',
+ 'lp.textOk': 'Edits saved and passed the checks.',
+ 'lp.textBad': 'Edits saved, but there are errors to fix before saving the template.',
+ 'lp.saveH': 'Save as a "Mine" template',
+ 'lp.saveName': 'Template name',
+ 'lp.slug': 'Template code',
+ 'lp.slugHint': 'Lowercase letters without accents, digits, hyphens. Used in: make --template local.mine/<code>',
+ 'lp.save': 'Save template',
+ 'lp.retest': 'Test-build again',
+ 'lp.discard': 'Discard draft',
+ 'lp.discardAsk': 'Discard this draft? The reference video and the draft will be deleted.',
+ 'lp.discarded': 'Draft discarded.',
+ 'lp.saveNote': 'After saving, the reference video and its frames are deleted from this computer. The template runs locked: the AI only reads and writes inside the folder of the video being built.',
+ 'lp.errNoSave': 'The draft failed at the test build: fix the template, then click Test-build again before saving.',
+ 'lp.savedH': 'Saved to Mine',
+ 'lp.savedP': 'Template {ref} is in the template grid under "Mine". Build with any content, like the built-in templates.',
+ 'lp.useNow': 'Use this template',
+ // ---- create screen (studio/create.js) ----
+ 'cr.title': 'New project',
+ 'cr.backStep': 'Previous step',
+ 'cr.stepsAria': 'Steps',
+ 'cr.s1': 'Clip', 'cr.s2': 'Edit style', 'cr.s3': 'Build',
+ 'cr.sideAria': 'Build settings',
+ 'cr.yourClip': 'Your clip',
+ 'cr.changeClip': 'Change clip',
+ 'cr.noClip': 'No clip yet. Drop a video into the box on the right.',
+ 'cr.musicStyle': 'Style default',
+ 'cr.musicUpload': 'Upload music',
+ 'cr.len': 'Output length',
+ 'cr.lenAuto': 'Auto',
+ 'cr.lenAutoOn': 'Set a length',
+ 'cr.lenAutoV': 'Auto',
+ 'cr.lenV': '~{s} s',
+ 'cr.names': 'Names & terms',
+ 'cr.namesWhy': 'so captions spell them right',
+ 'cr.namePh': 'e.g. Lumfin (Enter to add)',
+ 'cr.addName': 'Add',
+ 'cr.removeName': 'Remove {n}',
+ 'cr.h1': 'Pick a clip',
+ 'cr.sub1': 'Talking-to-camera video in Vietnamese. AI cuts pauses, writes captions, adds zooms and graphics.',
+ 'cr.h2': 'Pick an edit style',
+ 'cr.sub2': 'Each style is a way of cutting, captioning and adding graphics. You can change it after the build.',
+ 'cr.h3': 'Building',
+ 'cr.open': 'Open Studio',
+ 'cr.another': 'Build another clip',
+ 'cr.next': 'Next: edit style',
+ 'cr.eta': 'Takes about {m} min',
+ 'cr.delete': 'Delete edit {name}',
+ // ---- Studio (studio/*.js) ----
+ 'st.fromReel': 'From reel (kept as is)',
+ 'st.reelMusic': 'Reel music',
+ 'st.reelLink': '↩ Reel: {title}',
+ 'st.reelBack': 'Back to this reel in the From a template tab',
+ 'st.videoHint': 'Click the Video track to pick a clip, drag to pick a range; S splits the clip at the playhead; Delete cuts the selected part.',
+ 'st.videoPick': 'Nothing selected on the Video track.',
+ 'st.cutThis': 'Cut this part',
+ 'st.restoreCut': 'Restore this cut',
+ 'st.splitClip': 'Split clip at playhead (S)',
+ 'st.cutDone': 'Marked {a}–{b} to cut. Publish to apply.',
+ 'st.noSplitHere': 'Can’t split here (too close to the start/end or inside a cut).',
+ 'st.cutsPending': (v) => `${v.n} cut${v.n === 1 ? '' : 's'} waiting to publish (−${v.s} s). The preview already skips them.`,
+ 'st.cutItem': 'Cut {a}–{b}',
+ 'st.showCaps': 'Show captions',
+ 'st.showCapsTip': 'Imported reels already have text in the scene, so captions start off; turn on to add captions from the voice-over.',
+ 'job.studio': 'Keep editing in Studio',
+ 'job.studioBusy': 'Opening Studio…',
+ 'job.studioErr': 'Could not open Studio: {e}',
+ 'st.back': 'Back to the list',
+ 'st.versions': 'Versions',
+ 'st.r0': 'orig',
+ 'st.r0Tip': 'First build',
+ 'st.undo': 'Undo (Ctrl+Z)',
+ 'st.redo': 'Redo (Ctrl+Shift+Z)',
+ 'st.needReview': 'Review',
+ 'st.publish': (v) => `Publish new (${v.n} change${v.n === 1 ? '' : 's'})`,
+ 'st.publishing': 'Publishing',
+ 'st.published': 'Published r{n}. Now showing the new version.',
+ 'st.resetAsk': 'Discard all unpublished changes?',
+ 'st.tools': 'Tools',
+ 'st.railAi': 'AI edit',
+ 'st.trVideo': 'Video', 'st.trCap': 'Captions', 'st.trZoom': 'Zoom', 'st.trGfx': 'Graphics', 'st.trMusic': 'Music',
+ 'st.timeline': 'Timeline',
+ 'st.splitS': 'Split caption at playhead (S)',
+ 'st.mergeNext': 'Merge with next line',
+ 'st.delSel': 'Delete selected block (Delete)',
+ 'st.addZoom': 'Add zoom at playhead',
+ 'st.zoomIn': 'Zoom timeline in',
+ 'st.zoomOut': 'Zoom timeline out',
+ 'st.fitAll': 'Fit: show the whole video',
+ 'st.tlZoom': 'Timeline zoom (Ctrl + wheel)',
+ 'st.noMusic': 'No music',
+ 'st.lineText': 'Edit caption text',
+ 'st.play': 'Play', 'st.pause': 'Pause',
+ 'st.prevFrame': 'Back 1 frame (←, Shift: 1 s)',
+ 'st.nextFrame': 'Forward 1 frame (→, Shift: 1 s)',
+ 'st.viewOut': 'Export',
+ 'st.viewingOut': 'Watching the exported MP4',
+ 'st.closeSheet': 'Close panel',
+ 'st.readOnly': 'Viewing an older version: read only. Pick the latest version to edit.',
+ 'st.capLines': 'Lines',
+ 'st.capLook': 'Look',
+ 'st.capReview': (v) => `Review · ${v.n}`,
+ 'st.flagged': 'Has something to review',
+ 'st.markHi': 'Highlight: wrap the selected words to color them',
+ 'st.del': 'Delete',
+ 'st.aiFixed': 'AI changed “{heard}” to “{text}”',
+ 'st.figCheck': 'Number “{text}” — heard: “{said}”',
+ 'st.lineErr.short': 'Line is shorter than 0.1 s.',
+ 'st.lineErr.after': 'Line starts after the end of the video.',
+ 'st.lineErr.overlap': 'Line overlaps the previous one.',
+ 'st.lineErr.empty': 'Line has no text.',
+ 'st.reviewH': 'Review',
+ 'st.reviewNone': 'Nothing to review.',
+ 'st.prevItem': 'Previous item', 'st.nextItem': 'Next item',
+ 'st.rFix': 'AI fix', 'st.rFig': 'Number',
+ 'st.rKeep': 'Keep', 'st.rEdit': 'Edit', 'st.rRevert': 'Revert',
+ 'st.rNoRevert': 'Can’t revert: the line no longer has the AI-fixed words',
+ 'st.rNoGfx': 'The graphic with this number is not in this version (dropped at build).',
+ 'st.rGfxCell': '{g} cell: “{cell}” → Revert to “{to}” (what was heard)',
+ 'st.rStatus.keep': 'Kept', 'st.rStatus.edit': 'Opened for editing', 'st.rStatus.revert': 'Reverted to what was heard',
+ 'st.uploadMusic': 'Upload a track',
+ 'st.gain': 'Music volume',
+ 'st.zoomKind': 'Zoom type',
+ 'st.push': 'Slow push', 'st.punch': 'Punch', 'st.pushS': 'Push', 'st.punchS': 'Punch',
+ 'st.pushHint': 'Slowly zooms over the whole block, eases back at the end.',
+ 'st.punchHint': 'Snaps in, holds, then snaps back.',
+ 'st.zStrength': 'Strength',
+ 'st.zLength': 'Length',
+ 'st.zoomPick': 'Pick a zoom block on the timeline, or add one at the playhead.',
+ 'st.zoomHere': 'The playhead is inside a zoom: selected it.',
+ 'st.zoomNoRoom': 'Not enough room for a new zoom here.',
+ 'st.gfxPick': 'Pick a graphic on the timeline to edit its text, numbers and timing.',
+ 'st.gStart': 'Graphic start time', 'st.gEnd': 'Graphic end time',
+ 'st.estimate': 'estimate',
+ 'st.delGfx': 'Delete graphic',
+ 'st.aiH': 'AI edit',
+ 'st.aiHint': 'Say what to change; AI rebuilds from the latest version (a few minutes).',
+ 'st.aiGo': 'Edit with AI',
+ 'st.aiPending': (v) => `${v.n} unpublished change${v.n === 1 ? '' : 's'}: publish or discard them before an AI edit.`,
+ 'st.noLineHere': 'The playhead is not on a caption line.',
+ 'st.noMerge': 'Pick a line that has a next line to merge.',
+ 'st.selFirst': 'Select a block on the timeline first.',
+ 'st.fixFirst': (v) => `${v.n} caption line${v.n === 1 ? ' has' : 's have'} errors (red): fix before publishing.`,
+ 'st.notFound': 'Could not open this edit: {e}',
+ 'st.buildErr': 'This edit failed: {e}',
+ 'gf.kicker': 'Kicker', 'gf.title': 'Title', 'gf.unit': 'Unit', 'gf.label': 'Label', 'gf.prefix': 'Prefix',
+ 'gf.value': 'Number', 'gf.suffix': 'Suffix', 'gf.old': 'Old price', 'gf.text': 'Text', 'gf.a': 'Column A', 'gf.b': 'Column B',
+ 'gf.row': 'Row {n}', 'gf.ok': 'Tick ✓',
+ '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)',
+ 'log.close': 'Close log', 'log.copy': 'Copy log', 'log.copied': 'Copied', 'log.copyManual': 'Text selected, press Ctrl+C',
+ 'log.download': 'Download .txt', 'log.reload': 'Reload', 'log.loading': 'Reading the log…', 'log.loadErr': 'Could not read the log: {e}',
+ 'log.step': 'Failed at step: {s}', 'log.rawError': 'Original error', 'log.whyUnknown': 'This error is not on the known list. The original message is below; copy the log and send it to support.',
+ 'log.okDone': 'This job finished without errors.', 'log.okRunning': 'The job has not finished or failed yet. Hit Reload for new lines.',
+ 'log.serverNote': (v) => `The last ${v.n} server log line${S(v.n)}. API keys, tokens and home-folder paths are hidden.`,
+ 'log.rawHead': (v) => (v.total > v.n ? `Raw log: last ${v.n} of ${v.total} lines` : `Raw log: ${v.n} line${S(v.n)}`), 'log.empty': 'No log lines yet.',
+ 'log.why.claude_login': 'Claude Code is not signed in.', 'log.fix.claude_login': 'Open a terminal, run claude and type /login. Once signed in, hit Re-render.',
+ 'log.why.api_key': 'The Claude API key is wrong or revoked (error 401).', 'log.fix.api_key': 'Open "System check" (top button), paste a new key (get one at console.anthropic.com), click Save and check, then build again. Or pick "Claude Code" under Scene builder.',
+ 'log.why.quota': 'The AI usage limit or rate limit was hit.', 'log.fix.quota': 'Top up / wait for the limit to reset, or switch to a cheaper model (Haiku) and build again.',
+ 'log.why.overloaded': 'The AI servers are overloaded.', 'log.fix.overloaded': 'Wait a few minutes, then hit Re-render.',
+ 'log.why.disk': 'The disk is full.', 'log.fix.disk': 'Delete old videos (jobs, edits) or free up disk space (a few GB), then build again.',
+ 'log.why.cuda': 'GPU transcription failed (CUDA/cuDNN missing or the GPU ran out of memory).', 'log.fix.cuda': 'Update the NVIDIA driver, close apps using the GPU, or run node edit/setup.mjs again. Without a GPU the app transcribes on the CPU (slower).',
+ 'log.why.ffmpeg': 'ffmpeg is not installed (or cannot be found).', 'log.fix.ffmpeg': 'Install ffmpeg (winget install ffmpeg on Windows, brew install ffmpeg on Mac), then restart the app.',
+ 'log.why.python': 'Python or the Python packages for Edit video are missing.', 'log.fix.python': 'Install Python 3.10–3.12, then hit "Install now" in the Edit video tab (or run node edit/setup.mjs).',
+ 'log.why.claude_missing': 'The claude command (Claude Code) was not found.', 'log.fix.claude_missing': 'Install Claude Code (npm i -g @anthropic-ai/claude-code), or pick "Claude API" if you have an API key.',
+ 'log.why.timeout': 'It ran out of time (scene writing or rendering took too long).', 'log.fix.timeout': 'Shorten the video, pick a lighter 2D template, or build again when the computer is idle.',
+ 'log.why.interrupted': 'The app was closed while the job was running.', 'log.fix.interrupted': 'Hit Re-render / Build again to continue.',
+ 'log.why.network': 'No network, or the server could not be reached.', 'log.fix.network': 'Check the connection and try again.',
+ 'log.why.no_scene': 'The AI did not finish the scene (scene/index.html missing).', 'log.fix.no_scene': 'Hit Re-render; if it fails again, check the raw log to see where the AI stopped.',
+ 'log.why.scene_invalid': 'The scene the AI wrote has errors and cannot render.', 'log.fix.scene_invalid': 'Hit Re-render so the AI fixes it, or build again with a stronger model.',
+ 'log.why.no_speech': 'No speech could be heard in the video.', 'log.fix.no_speech': 'Pick a clip with clear speech (Vietnamese), not just music.',
+ 'log.why.bad_video': 'The video file is broken or in a format that cannot be read.', 'log.fix.bad_video': 'Export the video as MP4 (H.264) and upload it again.',
+ 'log.why.edl_invalid': 'The AI cut plan came out inconsistent (cuts, zooms or sounds do not match).', 'log.fix.edl_invalid': 'Hit Build again; the AI will plan from scratch.',
+ };
+
+ // 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.
+ const SRV_EN = {
+ 'Tự chọn theo mẫu': 'Auto (by template)', 'Không nhạc': 'No music',
+ 'Theo mẫu (chỉ đọc khi mẫu có lời)': 'Template default (only if it has a script)', 'Không lời đọc': 'No voiceover',
+ 'Tiếng Việt': 'Vietnamese',
+ nam: 'male', 'nữ': 'female', 'Bắc': 'North', Trung: 'Central', Nam: 'South',
+ 'tự nhiên (mặc định)': 'natural (default)', 'kể chuyện, trầm': 'storytelling, deep', 'tự nhiên': 'natural', 'lầy': 'goofy',
+ 'tin tức': 'news', 'kể chuyện': 'storytelling', 'đọc truyện': 'audiobook', 'cần mạng': 'needs internet',
+ 'ấm, tự nhiên (mặc định)': 'warm, natural (default)', 'sáng, nhiều cảm xúc': 'bright, expressive', 'trầm, điềm đạm': 'deep, calm',
+ 'khoẻ, dứt khoát': 'strong, crisp', 'nhẹ nhàng, rõ chữ': 'soft, clear', 'trầm, kể chuyện': 'deep, storytelling',
+ 'lofi ấm, chậm, có tiếng đĩa than (78 BPM)': 'warm lo-fi, slow, vinyl crackle (78 BPM)',
+ 'pop sáng, 4 phách đều, vui tươi (118 BPM)': 'bright pop, steady four-beat, cheerful (118 BPM)',
+ 'drone căng, nhịp tim, tích tắc (70 BPM)': 'tense drone, heartbeat, ticking (70 BPM)',
+ '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',
+ // ghi chú bước của "Tạo mẫu từ video"
+ 'đã sửa guidance': 'guidance revised', 'giữ nguyên guidance': 'guidance kept as is', 'lỗi': 'error',
+ };
+ // Mảnh câu trong gợi ý cài đặt / tên giọng ("Heart (US, nữ)").
+ const SRV_EN_PARTS = [
+ ['Cài giọng đọc: ', 'Install voices: '], ['Cài giọng Anh: ', 'Install English voices: '],
+ [' (đang dùng edge-tts, cần mạng)', ' (using edge-tts for now, needs internet)'], [' (hoặc pip install edge-tts)', ' (or pip install edge-tts)'],
+ [/, nữ(?=[,)])/g, ', female'], [/, nam(?=[,)])/g, ', male'],
+ [/^(\d+) chỉ số lệch$/, '$1 measures off'],
+ ];
+
+ const TABLE = { vi, en };
+ const KEY = 'lumreels.lang';
+ let lang = 'vi';
+ try { lang = localStorage.getItem(KEY) || ''; } catch { lang = ''; }
+ if (lang !== 'vi' && lang !== 'en') lang = /^vi\b/i.test(navigator.language || '') ? 'vi' : 'en';
+
+ function t(key, vars = {}) {
+ let v = TABLE[lang][key];
+ if (v === undefined) v = vi[key];
+ if (v === undefined) return key;
+ if (typeof v === 'function') return v(vars);
+ return v.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
+ }
+ function srv(s) {
+ if (lang === 'vi' || s == null) return s;
+ const str = String(s);
+ if (Object.prototype.hasOwnProperty.call(SRV_EN, str)) return SRV_EN[str];
+ return SRV_EN_PARTS.reduce((acc, [a, b]) => (typeof a === 'string' ? acc.split(a).join(b) : acc.replace(a, b)), str);
+ }
+ function apply(root = document) {
+ root.querySelectorAll('[data-i18n]').forEach((el) => { el.textContent = t(el.dataset.i18n); });
+ root.querySelectorAll('[data-i18n-placeholder]').forEach((el) => { el.placeholder = t(el.dataset.i18nPlaceholder); });
+ root.querySelectorAll('[data-i18n-aria]').forEach((el) => { el.setAttribute('aria-label', t(el.dataset.i18nAria)); });
+ root.querySelectorAll('[data-i18n-title]').forEach((el) => { el.title = t(el.dataset.i18nTitle); });
+ }
+ function syncSwitch() {
+ document.querySelectorAll('[data-lang]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.lang === lang)));
+ }
+ function set(next) {
+ if (next !== 'vi' && next !== 'en') return;
+ const changed = next !== lang;
+ lang = next;
+ try { localStorage.setItem(KEY, lang); } catch { /* bỏ qua */ }
+ document.documentElement.lang = lang;
+ apply();
+ syncSwitch();
+ if (changed) window.dispatchEvent(new CustomEvent('lumreels:lang', { detail: { lang } }));
+ }
+
+ /** Panel tự chứa thêm bảng chữ riêng: I18N.extend({ 'k': 'vi' }, { 'k': 'en' }). Khoá có sẵn không bị ghi đè. */
+ function extend(moreVi = {}, moreEn = {}) {
+ for (const [k, v] of Object.entries(moreVi)) if (!(k in vi)) vi[k] = v;
+ for (const [k, v] of Object.entries(moreEn)) if (!(k in en)) en[k] = v;
+ }
+
+ window.I18N = {
+ t, srv, set, apply, extend,
+ get lang() { return lang; },
+ /** Locale cho toLocaleString. */
+ get locale() { return lang === 'vi' ? 'vi-VN' : 'en-GB'; },
+ };
+
+ document.addEventListener('click', (e) => { const b = e.target.closest?.('[data-lang]'); if (b) set(b.dataset.lang); });
+ document.documentElement.lang = lang;
+ apply();
+ syncSwitch();
+})();
diff --git a/server/public/index.html b/server/public/index.html
index 31c32ac..9b7f2bf 100644
--- a/server/public/index.html
+++ b/server/public/index.html
@@ -1,297 +1,297 @@
-<!doctype html>
-<html lang="vi">
-<head>
-<meta charset="UTF-8" />
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
-<title data-i18n="meta.title">LumReels — dựng video dọc từ mẫu</title>
-<link rel="icon" href="data:," />
-<link rel="stylesheet" href="/fonts/fonts.css" />
-<link rel="stylesheet" href="/style.css" />
-<link rel="stylesheet" href="/studio/create.css" />
-<link rel="stylesheet" href="/studio/studio.css" />
-<link rel="stylesheet" href="/packs-panel.css" />
-<link rel="stylesheet" href="/doctor-panel.css" />
-</head>
-<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, 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>
- <button type="button" data-lang="en" aria-pressed="false" aria-label="Tiếng Anh" data-i18n-aria="lang.en">EN</button>
- </div>
-</header>
-<div id="update-banner" class="update-banner" role="status" hidden>
- <span class="ub-text"></span>
- <button type="button" class="ub-close" aria-label="Ẩn thông báo" data-i18n-aria="update.hide">×</button>
-</div>
-
-<nav class="tabs" role="tablist" aria-label="Chế độ" data-i18n-aria="tabs.aria">
- <button type="button" class="tab" role="tab" data-tab="tpl" aria-selected="true" aria-controls="tplTab"><span data-i18n="tabs.tpl">Dựng từ mẫu</span></button>
- <button type="button" class="tab" role="tab" data-tab="edit" aria-selected="false" aria-controls="editTab"><span data-i18n="tabs.edit">Edit video của bạn</span><span class="new" data-i18n="tabs.new">MỚI</span></button>
-</nav>
-
-<main class="layout" id="tplTab" role="tabpanel">
- <section class="pick" aria-labelledby="h-pick">
- <div class="sec-head">
- <h2 id="h-pick"><span class="step">1</span><span data-i18n="pick.h">Chọn mẫu</span></h2>
- <span class="count" id="tplCount"></span>
- </div>
- <div class="filters">
- <label class="search">
- <span class="sr" data-i18n="pick.searchLabel">Tìm mẫu theo tên</span>
- <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
- <input id="q" type="search" placeholder="Tìm theo tên, thể loại…" data-i18n-placeholder="pick.searchPh" autocomplete="off" />
- </label>
- <div class="pack-act">
- <button type="button" class="ghost" id="packImport" data-pack-import aria-haspopup="dialog">
- <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v12m0 0-4-4m4 4 4-4"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/></svg>
- <span data-i18n="pack.importBtn">Nhập gói</span>
- </button>
- </div>
- <div class="chips" role="radiogroup" aria-label="Lọc theo nhóm" data-i18n-aria="pick.chipsAria">
- <button class="chip on" data-cat="" role="radio" aria-checked="true" data-i18n="cat.all">Tất cả</button>
- <button class="chip" data-cat="faceless" role="radio" aria-checked="false" data-i18n="cat.faceless">Faceless</button>
- <button class="chip" data-cat="ads" role="radio" aria-checked="false" data-i18n="cat.ads">Quảng cáo</button>
- <button class="chip" data-cat="multi-style" role="radio" aria-checked="false" data-i18n="cat.multi-style">Đa phong cách</button>
- <button class="chip" data-cat="viet-nam" role="radio" aria-checked="false" data-i18n="cat.viet-nam">Việt Nam hoá</button>
- <button class="chip" data-src="local" role="radio" aria-checked="false" data-i18n="src.local">Của tôi</button>
- <button class="chip" data-src="pack" role="radio" aria-checked="false" data-i18n="src.pack">Cộng đồng</button>
- </div>
- <label class="toggle"><input type="checkbox" id="readyOnly" /> <span data-i18n="pick.readyOnly">Chỉ mẫu dùng được</span></label>
- <label class="toggle switch"><input type="checkbox" id="multiPick" role="switch" aria-describedby="multiHint" /> <span data-i18n="pick.multi">Chọn nhiều mẫu</span></label>
- <span class="sr" id="multiHint" data-i18n="pick.multiHint">Bật lên thì bấm mẫu để chọn hoặc bỏ, tối đa 12 mẫu, mỗi mẫu ra 1 video cùng nội dung.</span>
- </div>
- <p class="pick-note" id="pickNote" role="status" aria-live="polite"></p>
- <div id="grid" class="grid" aria-live="polite"></div>
- </section>
-
- <aside class="compose" aria-labelledby="h-compose">
- <div class="sticky">
- <h2 id="h-compose"><span class="step">2</span><span data-i18n="compose.h">Nội dung</span></h2>
- <div id="picked" class="picked empty">Chưa chọn mẫu. Bấm 1 mẫu sáng màu bên trái.</div>
- <div class="field-head">
- <label class="field" for="content" data-i18n="compose.label">Nội dung video</label>
- <button type="button" id="rewrite" class="ghost" disabled aria-describedby="rwHint">
- <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 20h4L19 9l-4-4L4 16z"/><path d="m13.5 6.5 4 4"/></svg>
- <span data-i18n="rw.btn">Viết lại kịch bản</span>
- </button>
- </div>
- <textarea id="content" rows="7" maxlength="4000" data-i18n-placeholder="compose.ph" placeholder="Ví dụ: Mỗi tháng bỏ 3 triệu vào quỹ chỉ số, lãi giả định 10%/năm, sau 20 năm có bao nhiêu? Kênh: Lumfin. CTA: Theo dõi để biết thêm mẹo tiền"></textarea>
- <div class="hint"><span id="chars">0</span><span data-i18n="compose.charsTail">/4000 ký tự · ghi luôn tên kênh và CTA nếu có</span></div>
- <div class="hint" id="rwHint">Viết lại kịch bản: AI xếp nội dung vào đúng ô của mẫu đang chọn và thời lượng bên dưới, giữ nguyên số liệu, tên kênh, CTA.</div>
- <div id="rwBox" class="rw" hidden aria-live="polite"></div>
-
- <label class="field" for="duration"><span data-i18n="dur.label">Thời lượng</span> <span class="opt" data-i18n="dur.range">(3 giây – 10 phút)</span></label>
- <div class="dur">
- <input id="duration" type="text" inputmode="numeric" autocomplete="off" spellcheck="false" value="8"
- placeholder="8" aria-describedby="durHint" />
- <div class="presets" role="group" aria-label="Chọn nhanh thời lượng" data-i18n-aria="dur.presets">
- <button type="button" class="pre on" data-dur="8">8s</button>
- <button type="button" class="pre" data-dur="15">15s</button>
- <button type="button" class="pre" data-dur="30">30s</button>
- <button type="button" class="pre" data-dur="60">60s</button>
- </div>
- </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">
- <label class="field" for="mode" data-i18n="mode.label">Ai dựng cảnh</label>
- <select id="mode">
- <option value="auto" data-i18n="mode.auto">Tự động</option>
- <option value="api">Claude API</option>
- <option value="claude">Claude Code</option>
- <option value="manual" data-i18n="mode.manual">Agent ngoài</option>
- </select>
- </div>
- <div class="span2">
- <label class="field" for="model" data-i18n="model.label">Model viết cảnh</label>
- <select id="model">
- <option value="auto">Tự chọn theo mẫu</option>
- <option value="opus" data-i18n="model.opus">Opus (đẹp nhất, tốn nhất)</option>
- <option value="sonnet" data-i18n="model.sonnet">Sonnet (cân bằng)</option>
- <option value="haiku" data-i18n="model.haiku">Haiku (rẻ nhất)</option>
- </select>
- </div>
- </div>
- <div class="hint" id="modelHint"></div>
- <label class="field" for="runAt"><span data-i18n="runAt.label">Hẹn giờ dựng</span> <span class="opt" data-i18n="runAt.opt">(bỏ trống = dựng ngay)</span></label>
- <div class="when">
- <input id="runAt" type="datetime-local" step="60" />
- <button type="button" id="clearAt" class="mini" aria-label="Bỏ hẹn giờ" data-i18n-aria="runAt.clearAria" data-i18n="runAt.clear">Bỏ hẹn</button>
- </div>
- <div class="hint" id="modeHint"></div>
- <p class="err" id="formErr" role="alert"></p>
- <button id="go" class="go" disabled>
- <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4v16l13-8z"/></svg>
- <span>Dựng video</span>
- </button>
- </div>
- </aside>
-
- <section class="jobs" aria-labelledby="h-jobs">
- <div class="sec-head"><h2 id="h-jobs" data-i18n="jobs.h">Video đã dựng</h2></div>
- <div id="firstVideo" hidden></div>
- <div id="jobs" class="job-list"></div>
- </section>
-</main>
-
-<section class="edit-wrap cr" id="editTab" role="tabpanel" aria-label="Edit video của bạn" data-i18n-aria="ed.aria" hidden>
- <div class="ed-card ed-setup" id="edSetup" hidden>
- <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" 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 data-i18n="ed.installDetails">Xem chi tiết</summary><pre id="edInstallLog"></pre></details>
- </div>
- <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="cr-shell">
- <div class="cr-top">
- <button type="button" class="cr-back" id="crBack" aria-label="Về bước trước" data-i18n-aria="cr.backStep" hidden>
- <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 19l-7-7 7-7M19 12H5"/></svg>
- </button>
- <b data-i18n="cr.title">Dự án mới</b>
- <ol class="cr-steps" id="crSteps" aria-label="Các bước" data-i18n-aria="cr.stepsAria">
- <li data-step="1"><button type="button"><i class="n">1</i><span data-i18n="cr.s1">Clip</span></button></li>
- <li class="ln" aria-hidden="true"></li>
- <li data-step="2"><button type="button"><i class="n">2</i><span data-i18n="cr.s2">Cách dựng</span></button></li>
- <li class="ln" aria-hidden="true"></li>
- <li data-step="3"><button type="button"><i class="n">3</i><span data-i18n="cr.s3">Dựng</span></button></li>
- </ol>
- </div>
- <div class="cr-body">
- <aside class="cr-side" id="crSide" aria-label="Thiết lập" data-i18n-aria="cr.sideAria">
- <div class="cr-blk">
- <div class="cr-h"><span data-i18n="cr.yourClip">Clip của bạn</span><button type="button" class="cr-link" id="crChange" data-i18n="cr.changeClip" hidden>Đổi clip</button></div>
- <div class="cr-clip" id="crClip">
- <div class="th"><video id="crClipVid" muted playsinline preload="metadata"></video><span class="d mono" id="crClipDur"></span></div>
- <div class="meta"><div><b id="crClipName"></b><span id="crClipInfo"></span></div><span class="ok" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg></span></div>
- </div>
- <p class="cr-none" id="crClipNone" data-i18n="cr.noClip">Chưa chọn clip.</p>
- </div>
- <div class="cr-blk">
- <div class="cr-h"><span id="crMusicH" data-i18n="ed.music">Nhạc nền</span><small data-i18n="ed.musicOpt">(tự hạ khi bạn nói)</small></div>
- <div class="cr-chips" id="crMusic" role="radiogroup" aria-labelledby="crMusicH"></div>
- <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>
- </div>
- <div class="cr-blk">
- <div class="cr-h"><span id="crNamesH" data-i18n="cr.names">Tên riêng</span><small data-i18n="cr.namesWhy">để phụ đề viết đúng</small></div>
- <div class="cr-chips" id="crNames" aria-labelledby="crNamesH"></div>
- <input class="ed-in cr-namein" id="edNames" type="text" maxlength="60" placeholder="Ví dụ: Lumfin" data-i18n-placeholder="cr.namePh" autocomplete="off" hidden aria-label="Thêm tên riêng" data-i18n-aria="cr.addName" />
- </div>
- <div class="cr-blk">
- <div class="cr-h"><label for="edNotes" data-i18n="ed.notes">Dặn thêm</label><small data-i18n="ed.notesOpt">(không bắt buộc)</small></div>
- <textarea id="edNotes" rows="3" maxlength="2000" placeholder="Ví dụ: bỏ câu chào đầu, giữ đoạn cuối kêu gọi theo dõi" data-i18n-placeholder="ed.notesPh"></textarea>
- <label class="ed-check" for="edDraft"><input type="checkbox" id="edDraft" /> <span data-i18n="ed.draft">Bản nháp nhanh (phụ đề đơn giản, nhanh hơn ~1 phút)</span></label>
- </div>
- </aside>
-
- <main class="cr-main">
- <div class="cr-pane" data-pane="1">
- <h1 data-i18n="cr.h1">Chọn clip</h1>
- <p class="cr-sub" data-i18n="cr.sub1">Video nói trước máy, tiếng Việt. AI cắt khoảng lặng, làm phụ đề, zoom và đồ hoạ.</p>
- <div class="drop" id="edDrop" role="button" tabindex="0" aria-label="Chọn hoặc kéo thả video" data-i18n-aria="ed.dropAria">
- <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 16V4m0 0-4 4m4-4 4 4"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/></svg>
- <span class="big">Kéo thả video vào đây</span>
- <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 />
- <div class="cr-listh"><h2 data-i18n="ed.listH">Các bản đã dựng</h2><span class="cr-count mono" id="crCount"></span></div>
- <div class="cr-list" id="edList"></div>
- </div>
- <div class="cr-pane" data-pane="2" hidden>
- <h1 id="edStyleLbl" data-i18n="cr.h2">Chọn cách dựng</h1>
- <p class="cr-sub" data-i18n="cr.sub2">Mỗi cách là một kiểu cắt, phụ đề và đồ hoạ. Đổi lại được sau khi dựng.</p>
- <div class="cr-grid" id="edStyles" role="radiogroup" aria-labelledby="edStyleLbl" aria-describedby="edStyleDesc"></div>
- <p class="sty-desc" id="edStyleDesc" aria-live="polite"></p>
- </div>
- <div class="cr-pane" data-pane="3" hidden>
- <h1 data-i18n="cr.h3">Đang dựng</h1>
- <p class="cr-sub" id="crBuildSub"></p>
- <div class="cr-build" id="crBuild">
- <div class="cr-bthumb" id="crBuildThumb" aria-hidden="true"></div>
- <div class="cr-binfo">
- <b id="crBuildName"></b>
- <span class="st" id="crBuildStatus" role="status" aria-live="polite"></span>
- <div class="cr-bar"><i id="crBuildBar"></i></div>
- <span class="cr-bstep mono" id="crBuildStep"></span>
- <p class="err" id="crBuildErr" role="alert"></p>
- <div class="cr-bact">
- <a class="btn pri" id="crOpen" hidden><span data-i18n="cr.open">Mở Studio</span></a>
- <button type="button" class="btn ghost" id="crAnother" data-i18n="cr.another">Dựng clip khác</button>
- <button type="button" class="log-btn" id="crLog" data-log-kind="edit" data-log-id="" data-i18n="log.btn">Nhật ký</button>
- </div>
- </div>
- </div>
- </div>
- </main>
- </div>
- <div class="cr-foot">
- <div class="cr-sum" id="crSum"></div>
- <span class="cr-eta" id="crEta"></span>
- <p class="err" id="edErr" role="alert"></p>
- <button id="edGo" class="btn pri cr-go" disabled>
- <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M11 3.5l1.8 5.2 5.2 1.8-5.2 1.8L11 17.5l-1.8-5.2L4 10.5l5.2-1.8zM19 15v5M16.5 17.5h5"/></svg>
- <span>Dựng video</span>
- </button>
- </div>
- </div>
-</section>
-
-<footer class="app-foot">
- <button type="button" data-log-kind="server" data-i18n="log.appBtn">Nhật ký app</button>
-</footer>
-
-<dialog id="viewer" aria-label="Video minh hoạ của mẫu" data-i18n-aria="viewer.aria">
- <div class="dlg-head"><strong id="vTitle"></strong><button class="x" id="vClose" aria-label="Đóng" data-i18n-aria="viewer.close">×</button></div>
- <video id="vVideo" controls playsinline preload="metadata"></video>
- <p class="dlg-desc" id="vDesc"></p>
-</dialog>
-
-<script src="/i18n.js"></script>
-<script src="/log-panel.js"></script>
-<script src="/audio-panel.js"></script>
-<script src="/voice-clone.js"></script>
-<script src="/app.js"></script>
-<script src="/doctor-panel.js"></script>
-<script type="module" src="/studio/create.js"></script>
-<script type="module" src="/studio/studio.js"></script>
-<script type="module" src="/studio/from-reel.js"></script>
-<script src="/packs-panel.js"></script>
-<script src="/learn-panel.js"></script>
-</body>
-</html>
+<!doctype html>
+<html lang="vi">
+<head>
+<meta charset="UTF-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+<title data-i18n="meta.title">LumReels — dựng video dọc từ mẫu</title>
+<link rel="icon" href="data:," />
+<link rel="stylesheet" href="/fonts/fonts.css" />
+<link rel="stylesheet" href="/style.css" />
+<link rel="stylesheet" href="/studio/create.css" />
+<link rel="stylesheet" href="/studio/studio.css" />
+<link rel="stylesheet" href="/packs-panel.css" />
+<link rel="stylesheet" href="/doctor-panel.css" />
+</head>
+<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, 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>
+ <button type="button" data-lang="en" aria-pressed="false" aria-label="Tiếng Anh" data-i18n-aria="lang.en">EN</button>
+ </div>
+</header>
+<div id="update-banner" class="update-banner" role="status" hidden>
+ <span class="ub-text"></span>
+ <button type="button" class="ub-close" aria-label="Ẩn thông báo" data-i18n-aria="update.hide">×</button>
+</div>
+
+<nav class="tabs" role="tablist" aria-label="Chế độ" data-i18n-aria="tabs.aria">
+ <button type="button" class="tab" role="tab" data-tab="tpl" aria-selected="true" aria-controls="tplTab"><span data-i18n="tabs.tpl">Dựng từ mẫu</span></button>
+ <button type="button" class="tab" role="tab" data-tab="edit" aria-selected="false" aria-controls="editTab"><span data-i18n="tabs.edit">Edit video của bạn</span><span class="new" data-i18n="tabs.new">MỚI</span></button>
+</nav>
+
+<main class="layout" id="tplTab" role="tabpanel">
+ <section class="pick" aria-labelledby="h-pick">
+ <div class="sec-head">
+ <h2 id="h-pick"><span class="step">1</span><span data-i18n="pick.h">Chọn mẫu</span></h2>
+ <span class="count" id="tplCount"></span>
+ </div>
+ <div class="filters">
+ <label class="search">
+ <span class="sr" data-i18n="pick.searchLabel">Tìm mẫu theo tên</span>
+ <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
+ <input id="q" type="search" placeholder="Tìm theo tên, thể loại…" data-i18n-placeholder="pick.searchPh" autocomplete="off" />
+ </label>
+ <div class="pack-act">
+ <button type="button" class="ghost" id="packImport" data-pack-import aria-haspopup="dialog">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v12m0 0-4-4m4 4 4-4"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/></svg>
+ <span data-i18n="pack.importBtn">Nhập gói</span>
+ </button>
+ </div>
+ <div class="chips" role="radiogroup" aria-label="Lọc theo nhóm" data-i18n-aria="pick.chipsAria">
+ <button class="chip on" data-cat="" role="radio" aria-checked="true" data-i18n="cat.all">Tất cả</button>
+ <button class="chip" data-cat="faceless" role="radio" aria-checked="false" data-i18n="cat.faceless">Faceless</button>
+ <button class="chip" data-cat="ads" role="radio" aria-checked="false" data-i18n="cat.ads">Quảng cáo</button>
+ <button class="chip" data-cat="multi-style" role="radio" aria-checked="false" data-i18n="cat.multi-style">Đa phong cách</button>
+ <button class="chip" data-cat="viet-nam" role="radio" aria-checked="false" data-i18n="cat.viet-nam">Việt Nam hoá</button>
+ <button class="chip" data-src="local" role="radio" aria-checked="false" data-i18n="src.local">Của tôi</button>
+ <button class="chip" data-src="pack" role="radio" aria-checked="false" data-i18n="src.pack">Cộng đồng</button>
+ </div>
+ <label class="toggle"><input type="checkbox" id="readyOnly" /> <span data-i18n="pick.readyOnly">Chỉ mẫu dùng được</span></label>
+ <label class="toggle switch"><input type="checkbox" id="multiPick" role="switch" aria-describedby="multiHint" /> <span data-i18n="pick.multi">Chọn nhiều mẫu</span></label>
+ <span class="sr" id="multiHint" data-i18n="pick.multiHint">Bật lên thì bấm mẫu để chọn hoặc bỏ, tối đa 12 mẫu, mỗi mẫu ra 1 video cùng nội dung.</span>
+ </div>
+ <p class="pick-note" id="pickNote" role="status" aria-live="polite"></p>
+ <div id="grid" class="grid" aria-live="polite"></div>
+ </section>
+
+ <aside class="compose" aria-labelledby="h-compose">
+ <div class="sticky">
+ <h2 id="h-compose"><span class="step">2</span><span data-i18n="compose.h">Nội dung</span></h2>
+ <div id="picked" class="picked empty">Chưa chọn mẫu. Bấm 1 mẫu sáng màu bên trái.</div>
+ <div class="field-head">
+ <label class="field" for="content" data-i18n="compose.label">Nội dung video</label>
+ <button type="button" id="rewrite" class="ghost" disabled aria-describedby="rwHint">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 20h4L19 9l-4-4L4 16z"/><path d="m13.5 6.5 4 4"/></svg>
+ <span data-i18n="rw.btn">Viết lại kịch bản</span>
+ </button>
+ </div>
+ <textarea id="content" rows="7" maxlength="4000" data-i18n-placeholder="compose.ph" placeholder="Ví dụ: Mỗi tháng bỏ 3 triệu vào quỹ chỉ số, lãi giả định 10%/năm, sau 20 năm có bao nhiêu? Kênh: Lumfin. CTA: Theo dõi để biết thêm mẹo tiền"></textarea>
+ <div class="hint"><span id="chars">0</span><span data-i18n="compose.charsTail">/4000 ký tự · ghi luôn tên kênh và CTA nếu có</span></div>
+ <div class="hint" id="rwHint">Viết lại kịch bản: AI xếp nội dung vào đúng ô của mẫu đang chọn và thời lượng bên dưới, giữ nguyên số liệu, tên kênh, CTA.</div>
+ <div id="rwBox" class="rw" hidden aria-live="polite"></div>
+
+ <label class="field" for="duration"><span data-i18n="dur.label">Thời lượng</span> <span class="opt" data-i18n="dur.range">(3 giây – 10 phút)</span></label>
+ <div class="dur">
+ <input id="duration" type="text" inputmode="numeric" autocomplete="off" spellcheck="false" value="8"
+ placeholder="8" aria-describedby="durHint" />
+ <div class="presets" role="group" aria-label="Chọn nhanh thời lượng" data-i18n-aria="dur.presets">
+ <button type="button" class="pre on" data-dur="8">8s</button>
+ <button type="button" class="pre" data-dur="15">15s</button>
+ <button type="button" class="pre" data-dur="30">30s</button>
+ <button type="button" class="pre" data-dur="60">60s</button>
+ </div>
+ </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">
+ <label class="field" for="mode" data-i18n="mode.label">Ai dựng cảnh</label>
+ <select id="mode">
+ <option value="auto" data-i18n="mode.auto">Tự động</option>
+ <option value="api">Claude API</option>
+ <option value="claude">Claude Code</option>
+ <option value="manual" data-i18n="mode.manual">Agent ngoài</option>
+ </select>
+ </div>
+ <div class="span2">
+ <label class="field" for="model" data-i18n="model.label">Model viết cảnh</label>
+ <select id="model">
+ <option value="auto">Tự chọn theo mẫu</option>
+ <option value="opus" data-i18n="model.opus">Opus (đẹp nhất, tốn nhất)</option>
+ <option value="sonnet" data-i18n="model.sonnet">Sonnet (cân bằng)</option>
+ <option value="haiku" data-i18n="model.haiku">Haiku (rẻ nhất)</option>
+ </select>
+ </div>
+ </div>
+ <div class="hint" id="modelHint"></div>
+ <label class="field" for="runAt"><span data-i18n="runAt.label">Hẹn giờ dựng</span> <span class="opt" data-i18n="runAt.opt">(bỏ trống = dựng ngay)</span></label>
+ <div class="when">
+ <input id="runAt" type="datetime-local" step="60" />
+ <button type="button" id="clearAt" class="mini" aria-label="Bỏ hẹn giờ" data-i18n-aria="runAt.clearAria" data-i18n="runAt.clear">Bỏ hẹn</button>
+ </div>
+ <div class="hint" id="modeHint"></div>
+ <p class="err" id="formErr" role="alert"></p>
+ <button id="go" class="go" disabled>
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4v16l13-8z"/></svg>
+ <span>Dựng video</span>
+ </button>
+ </div>
+ </aside>
+
+ <section class="jobs" aria-labelledby="h-jobs">
+ <div class="sec-head"><h2 id="h-jobs" data-i18n="jobs.h">Video đã dựng</h2></div>
+ <div id="firstVideo" hidden></div>
+ <div id="jobs" class="job-list"></div>
+ </section>
+</main>
+
+<section class="edit-wrap cr" id="editTab" role="tabpanel" aria-label="Edit video của bạn" data-i18n-aria="ed.aria" hidden>
+ <div class="ed-card ed-setup" id="edSetup" hidden>
+ <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" 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 data-i18n="ed.installDetails">Xem chi tiết</summary><pre id="edInstallLog"></pre></details>
+ </div>
+ <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="cr-shell">
+ <div class="cr-top">
+ <button type="button" class="cr-back" id="crBack" aria-label="Về bước trước" data-i18n-aria="cr.backStep" hidden>
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 19l-7-7 7-7M19 12H5"/></svg>
+ </button>
+ <b data-i18n="cr.title">Dự án mới</b>
+ <ol class="cr-steps" id="crSteps" aria-label="Các bước" data-i18n-aria="cr.stepsAria">
+ <li data-step="1"><button type="button"><i class="n">1</i><span data-i18n="cr.s1">Clip</span></button></li>
+ <li class="ln" aria-hidden="true"></li>
+ <li data-step="2"><button type="button"><i class="n">2</i><span data-i18n="cr.s2">Cách dựng</span></button></li>
+ <li class="ln" aria-hidden="true"></li>
+ <li data-step="3"><button type="button"><i class="n">3</i><span data-i18n="cr.s3">Dựng</span></button></li>
+ </ol>
+ </div>
+ <div class="cr-body">
+ <aside class="cr-side" id="crSide" aria-label="Thiết lập" data-i18n-aria="cr.sideAria">
+ <div class="cr-blk">
+ <div class="cr-h"><span data-i18n="cr.yourClip">Clip của bạn</span><button type="button" class="cr-link" id="crChange" data-i18n="cr.changeClip" hidden>Đổi clip</button></div>
+ <div class="cr-clip" id="crClip">
+ <div class="th"><video id="crClipVid" muted playsinline preload="metadata"></video><span class="d mono" id="crClipDur"></span></div>
+ <div class="meta"><div><b id="crClipName"></b><span id="crClipInfo"></span></div><span class="ok" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg></span></div>
+ </div>
+ <p class="cr-none" id="crClipNone" data-i18n="cr.noClip">Chưa chọn clip.</p>
+ </div>
+ <div class="cr-blk">
+ <div class="cr-h"><span id="crMusicH" data-i18n="ed.music">Nhạc nền</span><small data-i18n="ed.musicOpt">(tự hạ khi bạn nói)</small></div>
+ <div class="cr-chips" id="crMusic" role="radiogroup" aria-labelledby="crMusicH"></div>
+ <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>
+ </div>
+ <div class="cr-blk">
+ <div class="cr-h"><span id="crNamesH" data-i18n="cr.names">Tên riêng</span><small data-i18n="cr.namesWhy">để phụ đề viết đúng</small></div>
+ <div class="cr-chips" id="crNames" aria-labelledby="crNamesH"></div>
+ <input class="ed-in cr-namein" id="edNames" type="text" maxlength="60" placeholder="Ví dụ: Lumfin" data-i18n-placeholder="cr.namePh" autocomplete="off" hidden aria-label="Thêm tên riêng" data-i18n-aria="cr.addName" />
+ </div>
+ <div class="cr-blk">
+ <div class="cr-h"><label for="edNotes" data-i18n="ed.notes">Dặn thêm</label><small data-i18n="ed.notesOpt">(không bắt buộc)</small></div>
+ <textarea id="edNotes" rows="3" maxlength="2000" placeholder="Ví dụ: bỏ câu chào đầu, giữ đoạn cuối kêu gọi theo dõi" data-i18n-placeholder="ed.notesPh"></textarea>
+ <label class="ed-check" for="edDraft"><input type="checkbox" id="edDraft" /> <span data-i18n="ed.draft">Bản nháp nhanh (phụ đề đơn giản, nhanh hơn ~1 phút)</span></label>
+ </div>
+ </aside>
+
+ <main class="cr-main">
+ <div class="cr-pane" data-pane="1">
+ <h1 data-i18n="cr.h1">Chọn clip</h1>
+ <p class="cr-sub" data-i18n="cr.sub1">Video nói trước máy, tiếng Việt. AI cắt khoảng lặng, làm phụ đề, zoom và đồ hoạ.</p>
+ <div class="drop" id="edDrop" role="button" tabindex="0" aria-label="Chọn hoặc kéo thả video" data-i18n-aria="ed.dropAria">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 16V4m0 0-4 4m4-4 4 4"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/></svg>
+ <span class="big">Kéo thả video vào đây</span>
+ <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 />
+ <div class="cr-listh"><h2 data-i18n="ed.listH">Các bản đã dựng</h2><span class="cr-count mono" id="crCount"></span></div>
+ <div class="cr-list" id="edList"></div>
+ </div>
+ <div class="cr-pane" data-pane="2" hidden>
+ <h1 id="edStyleLbl" data-i18n="cr.h2">Chọn cách dựng</h1>
+ <p class="cr-sub" data-i18n="cr.sub2">Mỗi cách là một kiểu cắt, phụ đề và đồ hoạ. Đổi lại được sau khi dựng.</p>
+ <div class="cr-grid" id="edStyles" role="radiogroup" aria-labelledby="edStyleLbl" aria-describedby="edStyleDesc"></div>
+ <p class="sty-desc" id="edStyleDesc" aria-live="polite"></p>
+ </div>
+ <div class="cr-pane" data-pane="3" hidden>
+ <h1 data-i18n="cr.h3">Đang dựng</h1>
+ <p class="cr-sub" id="crBuildSub"></p>
+ <div class="cr-build" id="crBuild">
+ <div class="cr-bthumb" id="crBuildThumb" aria-hidden="true"></div>
+ <div class="cr-binfo">
+ <b id="crBuildName"></b>
+ <span class="st" id="crBuildStatus" role="status" aria-live="polite"></span>
+ <div class="cr-bar"><i id="crBuildBar"></i></div>
+ <span class="cr-bstep mono" id="crBuildStep"></span>
+ <p class="err" id="crBuildErr" role="alert"></p>
+ <div class="cr-bact">
+ <a class="btn pri" id="crOpen" hidden><span data-i18n="cr.open">Mở Studio</span></a>
+ <button type="button" class="btn ghost" id="crAnother" data-i18n="cr.another">Dựng clip khác</button>
+ <button type="button" class="log-btn" id="crLog" data-log-kind="edit" data-log-id="" data-i18n="log.btn">Nhật ký</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </main>
+ </div>
+ <div class="cr-foot">
+ <div class="cr-sum" id="crSum"></div>
+ <span class="cr-eta" id="crEta"></span>
+ <p class="err" id="edErr" role="alert"></p>
+ <button id="edGo" class="btn pri cr-go" disabled>
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M11 3.5l1.8 5.2 5.2 1.8-5.2 1.8L11 17.5l-1.8-5.2L4 10.5l5.2-1.8zM19 15v5M16.5 17.5h5"/></svg>
+ <span>Dựng video</span>
+ </button>
+ </div>
+ </div>
+</section>
+
+<footer class="app-foot">
+ <button type="button" data-log-kind="server" data-i18n="log.appBtn">Nhật ký app</button>
+</footer>
+
+<dialog id="viewer" aria-label="Video minh hoạ của mẫu" data-i18n-aria="viewer.aria">
+ <div class="dlg-head"><strong id="vTitle"></strong><button class="x" id="vClose" aria-label="Đóng" data-i18n-aria="viewer.close">×</button></div>
+ <video id="vVideo" controls playsinline preload="metadata"></video>
+ <p class="dlg-desc" id="vDesc"></p>
+</dialog>
+
+<script src="/i18n.js"></script>
+<script src="/log-panel.js"></script>
+<script src="/audio-panel.js"></script>
+<script src="/voice-clone.js"></script>
+<script src="/app.js"></script>
+<script src="/doctor-panel.js"></script>
+<script type="module" src="/studio/create.js"></script>
+<script type="module" src="/studio/studio.js"></script>
+<script type="module" src="/studio/from-reel.js"></script>
+<script src="/packs-panel.js"></script>
+<script src="/learn-panel.js"></script>
+</body>
+</html>
diff --git a/server/server.mjs b/server/server.mjs
index 0688f5f..f89d83d 100644
--- a/server/server.mjs
+++ b/server/server.mjs
@@ -1,407 +1,407 @@
-// Server API + UI. Chỉ bind 127.0.0.1:4400. Không framework.
-import http from 'node:http';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { spawn } from 'node:child_process';
-import {
- ROOT, JOBS, TEMPLATES, loadCatalog, templateName, createJob, runJob, renderJob, readJob, listJobs, readLog, markStale,
- dueJobs, resolveMode, submitScene, previewJob, createJobs, MAX_BATCH,
-} from '../generator/jobs.mjs';
-import { findClaude } from '../generator/claude.mjs';
-import { rewriteScript, resolveRewriteEngine, REWRITE_MAX_CHARS } from '../generator/rewrite.mjs';
-import { config } from '../generator/config.mjs';
-import { reAudio, listVersions, audioBusy, saveAudioSpec } from '../generator/audio-job.mjs';
-import { audioOptions, normalizeAudioPrefs, voiceEngine, sampleTextFor } from '../engine/audio/prefs.mjs';
-import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
-import { synthVoice } from '../engine/audio/voice.mjs';
-import { handleEditRoute, initEdits } from '../edit/http.mjs';
-import { handleVoiceRoute, initVoices } from './voices-http.mjs';
-import { handlePackRoute } from '../packs/http.mjs';
-import { listTemplates, resolveTemplate, parsePackRef, BUILTIN_TEMPLATE_RE } from '../packs/registry.mjs';
-import { originOk } from '../edit/http.mjs';
-import { isCloneVoice, cloneRef } from '../engine/audio/voice-store.mjs';
-import { handleDraftRoute, initDrafts } from '../packs/drafts-http.mjs';
-import { handleLogRoute, installLogCapture, redact } from './logs.mjs';
-import { readEditJob, EDITS } from '../edit/jobs.mjs';
-import { handleDoctorRoute } from './doctor.mjs';
-
-installLogCapture(ROOT); // log server vào ring buffer (GET /api/logs/server)
-
-const AUDIO_SAMPLES = path.join(ROOT, 'engine', 'audio', 'samples');
-/** File nghe thử (cache trong engine/audio/samples/, chỉ sinh khi chưa có). Trả đường dẫn tuyệt đối. */
-async function audioPreviewFile(q) {
- const style = q.get('style'), voice = q.get('voice');
- if (style) {
- if (!MUSIC_STYLES.includes(style)) throw new Error('style nhạc không có: ' + style);
- const f = path.join(AUDIO_SAMPLES, `music-${style}.wav`);
- if (!fs.existsSync(f)) { fs.mkdirSync(AUDIO_SAMPLES, { recursive: true }); writeMusic(style, f, 8, 1); }
- return f;
- }
- if (voice) {
- const { voice: v } = normalizeAudioPrefs({ voice });
- const text = String(q.get('text') || sampleTextFor(v)).trim().slice(0, 160);
- if (v === 'auto' || v === 'none') throw new Error('chọn 1 giọng cụ thể để nghe thử');
- // giọng nhân bản: câu nghe thử đã đọc sẵn lúc tạo giọng
- if (isCloneVoice(v) && !q.get('text')) { const f = path.join(path.dirname(cloneRef(v).wav), 'sample.wav'); if (fs.existsSync(f)) return f; }
- const ve = voiceEngine(v);
- const [r] = await synthVoice([{ t: 0, text }], path.join(AUDIO_SAMPLES, 'voices'), { engine: ve.engine, voice: ve.speaker, log: (l) => console.log('[audio] ' + l) });
- return r.file;
- }
- throw new Error('cần ?style=<nhạc> hoặc ?voice=<giọng>&text=...');
-}
-
-const HOST = '127.0.0.1';
-const PORT = Number(process.env.PORT) || 4400;
-const PUBLIC = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
-const DEFAULT_MODE = process.env.VIDEOAI_MODE || 'auto';
-const ALLOWED_HOSTS = new Set([`127.0.0.1:${PORT}`, `localhost:${PORT}`]);
-// L9: trang chỉ chạy script của chính app (file ngoài, index.html không có script nội tuyến); chữ của gói không thành code được.
-const PAGE_CSP = "default-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
-
-const FRAME_CSP = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'none'; object-src 'none'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'";
-
-const MIME = {
- '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
- '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
- '.png': 'image/png', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.m4a': 'audio/mp4', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.aac': 'audio/aac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg', '.flac': 'audio/flac', '.woff2': 'font/woff2', '.md': 'text/markdown; charset=utf-8',
-};
-
-// ---- hàng đợi: mỗi lúc chỉ 1 job chạy (render nặng) ----
-const queue = [];
-let busy = false;
-const queuedIds = new Set();
-/** Xếp 1 job vào hàng (không xếp trùng). */
-function enqueueJob(id, fn) {
- if (queuedIds.has(id)) return;
- queuedIds.add(id);
- enqueue(async () => { try { await fn(); } finally { queuedIds.delete(id); } });
-}
-function enqueue(fn) {
- queue.push(fn);
- pump();
-}
-async function pump() {
- if (busy) return;
- const fn = queue.shift();
- if (!fn) return;
- busy = true;
- try { await fn(); } catch (e) { console.error('[queue]', e); }
- busy = false;
- pump();
-}
-
-function send(res, code, body, type = 'application/json; charset=utf-8') {
- const data = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body);
- res.writeHead(code, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
- res.end(data);
-}
-
-/** Phục vụ file tĩnh trong baseDir (chặn ../), hỗ trợ Range cho video. */
-function serveFile(req, res, baseDir, rel) {
- const file = path.resolve(baseDir, '.' + path.sep + rel);
- if (!file.startsWith(path.resolve(baseDir) + path.sep)) return send(res, 403, { error: 'forbidden' });
- let st;
- try { st = fs.statSync(file); } catch { return send(res, 404, { error: 'không thấy file' }); }
- if (!st.isFile()) return send(res, 404, { error: 'không thấy file' });
- const type = MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
- const range = req.headers.range && /bytes=(\d*)-(\d*)/.exec(req.headers.range);
- const headers = { 'Content-Type': type, 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' };
- // khung xem trước đồ hoạ của Studio (studio/gfx-frame.html) được nhúng vào chính trang app (iframe sandbox): frame-ancestors 'self'
- if (type.startsWith('text/html')) headers['Content-Security-Policy'] = path.basename(file) === 'gfx-frame.html' ? FRAME_CSP : PAGE_CSP;
- if (range) {
- const start = range[1] ? Number(range[1]) : 0;
- const end = range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;
- if (start >= st.size || start > end) { res.writeHead(416, { 'Content-Range': `bytes */${st.size}` }); return res.end(); }
- res.writeHead(206, { ...headers, 'Content-Range': `bytes ${start}-${end}/${st.size}`, 'Content-Length': end - start + 1 });
- return fs.createReadStream(file, { start, end }).pipe(res);
- }
- res.writeHead(200, { ...headers, 'Content-Length': st.size });
- if (req.method === 'HEAD') return res.end();
- fs.createReadStream(file).pipe(res);
-}
-
-function readBody(req, limit = 64 * 1024) {
- return new Promise((resolve, reject) => {
- let size = 0; const chunks = [];
- req.on('data', (c) => { size += c.length; if (size > limit) { reject(new Error('body quá lớn')); req.destroy(); } else chunks.push(c); });
- req.on('end', () => {
- try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')); } catch { reject(new Error('JSON không hợp lệ')); }
- });
- req.on('error', reject);
- });
-}
-
-// Ảnh/video minh hoạ mỗi mẫu, theo thứ tự ưu tiên:
-// ảnh: 1. site/dist/media/<id>.webp (poster video demo, sinh bởi site/build.mjs — không có trong repo)
-// 2. templates/thumbs/<id>.webp (khung keyframe 360×640 có sẵn trong repo; tạo bằng scripts/make-thumbs.mjs)
-// 3. khung video tham chiếu riêng trên máy (templates/ref/<id>/frames, tools/fetch_refs.py — không có trong repo)
-// 4. poster SVG tự dựng (/poster/<id>.svg) từ tên + nhóm của mẫu
-// video: demo (site/dist/media/<id>.mp4) → video tham chiếu riêng → không có
-const DEMO = path.join(ROOT, 'site', 'dist', 'media');
-const THUMBS = path.join(TEMPLATES, 'thumbs');
-// LUMREELS_NO_REF=1: bỏ qua templates/ref (giả lập máy vừa clone repo; dùng khi chụp ảnh docs).
-const USE_REF = process.env.LUMREELS_NO_REF !== '1';
-function templateList() {
- // gốc + gói (packs/registry.mjs). Mẫu gói: ảnh từ gói (/pack-thumbs/…) hoặc poster SVG; không có video demo.
- return listTemplates().map((t) => {
- if (t.source !== 'builtin') {
- const pr = parsePackRef(t.ref);
- const r = resolveTemplate(t.ref);
- return {
- id: t.ref, ref: t.ref, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre || '', technique: t.technique || [],
- difficulty: t.difficulty, narration: !!t.narration, source: t.source, packId: t.packId, restricted: true, hasGuidance: true,
- thumb: r?.thumbFile ? `/pack-thumbs/${pr.packId}/template-${pr.slug}.webp` : `/poster/p/${pr.packId}/${pr.slug}.svg`,
- video: null, videoKind: null,
- };
- }
- const ref = path.join(TEMPLATES, 'ref', t.id);
- const refThumb = USE_REF && ['f_08.jpg', 'f_09.jpg', 'f_07.jpg'].find((f) => fs.existsSync(path.join(ref, 'frames', f)));
- const demo = fs.existsSync(path.join(DEMO, `${t.id}.mp4`));
- const demoPoster = fs.existsSync(path.join(DEMO, `${t.id}.webp`));
- const keyThumb = fs.existsSync(path.join(THUMBS, `${t.id}.webp`));
- const refVideo = USE_REF && fs.existsSync(path.join(ref, 'video.mp4'));
- return {
- id: t.id, ref: t.id, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre, technique: t.technique,
- difficulty: t.difficulty, narration: t.narration, source: 'builtin', restricted: t.restricted,
- hasGuidance: t.hasGuidance,
- thumb: demoPoster ? `/demo/${t.id}.webp` : keyThumb ? `/thumbs/${t.id}.webp` : refThumb ? `/ref/${t.id}/frames/${refThumb}` : `/poster/${t.id}.svg`,
- video: demo ? `/demo/${t.id}.mp4` : refVideo ? `/ref/${t.id}/video.mp4` : null,
- videoKind: demo ? 'demo' : refVideo ? 'ref' : null,
- source: 'builtin',
- };
- });
-}
-
-/** Poster SVG cho mẫu chưa có video demo: nền gradient theo id, tên phong cách, nhóm. */
-const CAT_LABEL = { faceless: 'Faceless', ads: 'Quảng cáo', 'multi-style': 'Đa phong cách', 'viet-nam': 'Việt Nam hoá' };
-function posterSvg(t) {
- const n = BUILTIN_TEMPLATE_RE.test(t.id) ? Number(t.id) : [...String(t.id)].reduce((a, c) => (a * 31 + c.charCodeAt(0)) % 997, 7);
- const h1 = (n * 47) % 360, h2 = (h1 + 40 + (n % 5) * 12) % 360;
- const x = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
- // ngắt tên thành tối đa 4 dòng ~12 ký tự
- const words = String(t.name).split(/\s+/); const lines = [''];
- for (const w of words) { if ((lines.at(-1) + ' ' + w).trim().length > 12 && lines.at(-1)) lines.push(w); else lines[lines.length - 1] = (lines.at(-1) + ' ' + w).trim(); }
- const shown = lines.slice(0, 4);
- const tech = (t.technique || []).includes('three') ? '3D' : (t.technique || []).includes('webgl-shader') ? 'Shader' : '2D';
- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 540 960" width="540" height="960">
-<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="hsl(${h1} 45% 22%)"/><stop offset="1" stop-color="hsl(${h2} 55% 12%)"/></linearGradient></defs>
-<rect width="540" height="960" fill="url(#g)"/>
-<circle cx="${380 + (n % 7) * 10}" cy="${260 + (n % 4) * 30}" r="170" fill="hsl(${h2} 70% 60% / .18)"/>
-<rect x="44" y="300" width="72" height="8" rx="4" fill="hsl(${h1} 80% 70%)"/>
-<text x="44" y="270" font-family="'Be Vietnam Pro',sans-serif" font-size="30" font-weight="600" fill="#fff" fill-opacity=".7">${BUILTIN_TEMPLATE_RE.test(t.id) ? '#' + x(t.id) : x(String(t.id).split('/')[1] || '')}</text>
-${shown.map((l, i) => `<text x="44" y="${390 + i * 74}" font-family="'Be Vietnam Pro',sans-serif" font-size="60" font-weight="800" fill="#fff">${x(l)}</text>`).join('\n')}
-<text x="44" y="880" font-family="'Be Vietnam Pro',sans-serif" font-size="28" font-weight="500" fill="#fff" fill-opacity=".75">${x(CAT_LABEL[t.category] || t.category)} · ${tech}</text>
-</svg>`;
-}
-
-function jobView(job, withLog = false) {
- const dir = path.join(JOBS, job.id);
- const has = (f) => fs.existsSync(path.join(dir, f));
- const v = {
- ...job,
- templateTitle: templateName(job.templateId) || job.templateTitle,
- queued: queue.length,
- versions: listVersions(job.id).map((v) => ({ ...v, url: `/jobs/${job.id}/${v.file}` })),
- audioBusy: audioBusy(job.id),
- links: {
- mp4: has('out.mp4') && job.status === 'done' ? `/jobs/${job.id}/out.mp4` : null,
- preview: has('preview.jpg') ? `/jobs/${job.id}/preview.jpg` : null,
- prompt: `/jobs/${job.id}/PROMPT.md`,
- brief: has('brief.json') ? `/jobs/${job.id}/brief.json` : null,
- },
- paths: { dir, prompt: path.join(dir, 'PROMPT.md'), scene: path.join(dir, 'scene', 'index.html') },
- };
- if (v.error) v.error = redact(v.error);
- if (withLog) v.log = readLog(job.id, 120).map(redact);
- return v;
-}
-
-/** Job vừa tạo: hẹn giờ thì để bộ hẹn giờ lo; manual chỉ chuyển sang waiting_agent; còn lại xếp hàng chạy. */
-async function startJob(job) {
- if (job.status === 'scheduled') return; // bộ hẹn giờ sẽ chạy khi tới giờ
- if (resolveMode(job.mode) === 'manual') await runJob(job.id);
- else enqueueJob(job.id, () => runJob(job.id));
-}
-
-/** Job dựng thử của nháp "Tạo mẫu từ video": xếp vào hàng đợi chung, trả job khi xong. */
-function draftTestRunner(id) {
- return new Promise((resolve) => {
- enqueueJob(id, async () => {
- try { resolve(await runJob(id, { force: true })); } catch (e) { console.error('[draft-test]', id, e.message); resolve(readJob(id)); }
- });
- });
-}
-
-let rewriteBusy = false;
-let rewriteLast = 0;
-
-const server = http.createServer(async (req, res) => {
- const url = new URL(req.url, `http://${HOST}`);
- const p = decodeURIComponent(url.pathname);
- // Chống DNS rebinding: chỉ nhận Host là 127.0.0.1/localhost đúng cổng.
- if (!ALLOWED_HOSTS.has(String(req.headers.host || '').toLowerCase())) return send(res, 421, { error: 'host không hợp lệ' });
- // Trang web lạ không gửi lệnh ghi vào được (tạo job, cài gói, xoá…): Origin phải là chính app (không có Origin = curl/agent cục bộ).
- if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && !originOk(req, ALLOWED_HOSTS)) {
- res.setHeader('Connection', 'close'); res.on('finish', () => req.destroy());
- return send(res, 403, { error: 'origin không hợp lệ' });
- }
- try {
- // ---- Nhật ký (server/logs.mjs): chỉ đọc, đã lọc bí mật ----
- if (handleLogRoute(req, res, p, url, { send, originOk: (r) => originOk(r, ALLOWED_HOSTS), jobsDir: JOBS, editsDir: EDITS, readJob, readEdit: readEditJob })) return;
- // ---- Gói mẫu .lumpack (packs/http.mjs) ----
- if (await handlePackRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
- // ---- Edit video của bạn (edit/http.mjs) ----
- if (await handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
- // ---- Giọng của tôi (server/voices-http.mjs) ----
- if (await handleVoiceRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
- // ---- Tạo mẫu từ video (packs/drafts-http.mjs): job dựng thử đi qua hàng đợi chung ----
- if (await handleDraftRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS, runTest: draftTestRunner })) return;
- // ---- Kiểm tra máy + khoá Anthropic (server/doctor.mjs) ----
- if (await handleDoctorRoute(req, res, p, url, { send, readBody, originOk: (r) => originOk(r, ALLOWED_HOSTS) })) return;
- // ---- API ----
- if (p === '/api/templates' && req.method === 'GET') return send(res, 200, templateList());
- if (p === '/api/version' && req.method === 'GET') return send(res, 200, { version: PKG_VERSION, update: updateState });
- if (p === '/api/config' && req.method === 'GET') {
- return send(res, 200, { defaultMode: DEFAULT_MODE, autoResolves: resolveMode('auto'), claudeAvailable: !!findClaude(), apiAvailable: config.hasApiKey(), outputDir: !!config.outputDir(), rewriteEngine: resolveRewriteEngine() });
- }
- if (p === '/api/rewrite' && req.method === 'POST') {
- // Chống bấm liên tục: mỗi lúc 1 lượt, cách nhau ≥ 3 giây.
- if (rewriteBusy) return send(res, 429, { error: 'Đang viết lại 1 bản, chờ xong rồi bấm tiếp' });
- if (Date.now() - rewriteLast < 3000) return send(res, 429, { error: 'Bấm chậm lại chút (cách nhau 3 giây)' });
- const body = await readBody(req);
- if (String(body.content || '').length > REWRITE_MAX_CHARS) return send(res, 413, { error: `Nội dung quá dài (tối đa ${REWRITE_MAX_CHARS} ký tự)` });
- rewriteBusy = true;
- try {
- const r = await rewriteScript({ templateId: body.templateId, content: body.content, durationS: body.durationS });
- console.log(`[rewrite] mẫu ${r.templateId}, ${r.durationS}s, ${r.engine}${r.fallbackFrom ? ' (sau khi ' + r.fallbackFrom + ')' : ''}`);
- return send(res, 200, r);
- } catch (e) {
- return send(res, /chưa cấu hình AI/i.test(e.message) ? 503 : 422, { error: e.message });
- } finally {
- rewriteBusy = false; rewriteLast = Date.now();
- }
- }
- if (p === '/api/jobs' && req.method === 'GET') return send(res, 200, listJobs().map((j) => jobView(j)));
- if (p === '/api/jobs' && req.method === 'POST') {
- const body = await readBody(req);
- const job = createJob({ templateId: body.templateId, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
- await startJob(job);
- return send(res, 201, jobView(readJob(job.id), true));
- }
- if (p === '/api/jobs/batch' && req.method === 'POST') {
- // Chọn nhiều mẫu: 1 job / mẫu, cùng nội dung + tuỳ chọn. Kiểm cả lô trước, sai 1 id là từ chối hết.
- const body = await readBody(req);
- if (!Array.isArray(body.templateIds)) return send(res, 400, { error: 'templateIds phải là mảng id mẫu' });
- if (body.templateIds.length > MAX_BATCH) return send(res, 400, { error: `Tối đa ${MAX_BATCH} mẫu mỗi lô` });
- let jobs;
- try {
- jobs = createJobs({ templateIds: body.templateIds, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
- } catch (e) { return send(res, 400, { error: e.message, badIds: e.badIds || [] }); }
- for (const job of jobs) await startJob(job);
- console.log(`[batch] ${jobs.length} job: ${jobs.map((j) => j.templateId).join(', ')}`);
- return send(res, 201, { jobs: jobs.map((j) => jobView(readJob(j.id))) });
- }
- let ms = /^\/api\/jobs\/([\w-]+)\/scene$/.exec(p);
- if (ms && req.method === 'POST') {
- const body = await readBody(req, 2_500_000);
- if (body.audio !== undefined && body.audio !== null) await saveAudioSpec(ms[1], body.audio); // scene/audio.json (AUTHORING §9)
- const r = submitScene(ms[1], body.html, body.brief);
- return send(res, r.ok ? 200 : 422, r);
- }
- ms = /^\/api\/jobs\/([\w-]+)\/preview$/.exec(p);
- if (ms && req.method === 'POST') {
- const r = await previewJob(ms[1]);
- return send(res, r.ok ? 200 : 422, { ok: r.ok, errors: r.errors, preview: r.ok ? `/jobs/${ms[1]}/preview.jpg` : null });
- }
- let m = /^\/api\/jobs\/([\w-]+)$/.exec(p);
- if (m && req.method === 'GET') {
- const job = readJob(m[1]);
- return job ? send(res, 200, jobView(job, true)) : send(res, 404, { error: 'không thấy job' });
- }
- m = /^\/api\/jobs\/([\w-]+)\/render$/.exec(p);
- if (m && req.method === 'POST') {
- const job = readJob(m[1]);
- if (!job) return send(res, 404, { error: 'không thấy job' });
- enqueueJob(job.id, () => renderJob(job.id));
- return send(res, 202, jobView(job, true));
- }
- // ---- âm thanh ----
- if (p === '/api/audio/options' && req.method === 'GET') return send(res, 200, audioOptions());
- if (p === '/api/audio/preview' && req.method === 'GET') {
- const f = await audioPreviewFile(url.searchParams);
- return serveFile(req, res, path.dirname(f), path.basename(f));
- }
- m = /^\/api\/jobs\/([\w-]+)\/audio$/.exec(p);
- if (m && req.method === 'POST') {
- const job = readJob(m[1]);
- if (!job) return send(res, 404, { error: 'không thấy job' });
- if (job.status !== 'done' && !fs.existsSync(path.join(JOBS, job.id, 'out.mp4'))) return send(res, 409, { error: 'video chưa dựng xong' });
- if (audioBusy(job.id)) return send(res, 409, { error: 'đang trộn tiếng cho video này' });
- const body = await readBody(req);
- const prefs = { music: body.music, voice: body.voice, sfx: body.sfx };
- normalizeAudioPrefs({ ...prefs }); // kiểm sớm, sai thì 400
- reAudio(job.id, prefs).catch((e) => console.error('[audio]', job.id, e.message)); // chạy nền; UI hỏi lại GET /api/jobs/:id
- return send(res, 202, { ...jobView(readJob(job.id), true), audioBusy: true });
- }
- m = /^\/api\/jobs\/([\w-]+)\/versions$/.exec(p);
- if (m && req.method === 'GET') return send(res, 200, listVersions(m[1]).map((v) => ({ ...v, url: `/jobs/${m[1]}/${v.file}` })));
- if (p.startsWith('/api/')) return send(res, 404, { error: 'không có API này' });
-
- // ---- file ----
- if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, { error: 'method' });
- if (p.startsWith('/ref/') && USE_REF) return serveFile(req, res, path.join(TEMPLATES, 'ref'), p.slice(5));
- m = /^\/demo\/(\d{3}\.(?:mp4|webp))$/.exec(p);
- if (m) return serveFile(req, res, DEMO, m[1]);
- m = /^\/thumbs\/(\d{3}\.webp)$/.exec(p);
- if (m) return serveFile(req, res, THUMBS, m[1]);
- m = /^\/poster\/(\d{3})\.svg$/.exec(p);
- if (m) {
- const t = loadCatalog().find((x) => x.id === m[1]);
- return t ? send(res, 200, posterSvg(t), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });
- }
- m = /^\/poster\/p\/([a-z0-9.-]{5,49})\/([a-z][a-z0-9-]{1,31})\.svg$/.exec(p);
- if (m) {
- const r = parsePackRef(`${m[1]}/${m[2]}`) && resolveTemplate(`${m[1]}/${m[2]}`);
- return r ? send(res, 200, posterSvg({ id: r.ref, name: r.meta.name, category: r.meta.category, technique: r.meta.technique }), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });
- }
- m = /^\/jobs\/([\w-]+)\/(versions\/out-\d{1,4}\.mp4)$/.exec(p);
- if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);
- m = /^\/jobs\/([\w-]+)\/(out\.mp4|preview\.jpg|PROMPT\.md|brief\.json)$/.exec(p);
- if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);
- // font: khung xem trước đồ hoạ của Studio chạy sandbox (origin rỗng) → tải font cần CORS
- if (p.startsWith('/fonts/')) { res.setHeader('Access-Control-Allow-Origin', '*'); return serveFile(req, res, path.join(ROOT, 'engine', 'fonts'), p.slice(7)); }
- return serveFile(req, res, PUBLIC, p === '/' ? 'index.html' : p.slice(1));
- } catch (e) {
- return send(res, 400, { error: e.message });
- }
-});
-
-markStale();
-initEdits(); // edit đang chạy dở khi server tắt → báo lỗi để bấm lại
-initVoices(); // giọng nhân bản đang xử lý dở → báo lỗi
-initDrafts(); // nháp "Tạo mẫu từ video" đang chạy dở → báo lỗi
-// Job queued còn sót (server tắt trước khi kịp chạy) → chạy lại.
-for (const j of listJobs()) if (j.status === 'queued' && resolveMode(j.mode) !== 'manual') enqueueJob(j.id, () => runJob(j.id));
-// Bộ hẹn giờ: 15 giây kiểm 1 lần, job tới giờ thì xếp hàng chạy.
-function tick() { for (const j of dueJobs()) enqueueJob(j.id, () => runJob(j.id, { force: true })); }
-setInterval(tick, 15000);
-tick();
-
-// Kiểm bản mới trên GitHub (chạy nền, không chặn app): lúc khởi động và 6 giờ/lần. Giao diện đọc qua /api/version.
-const PKG_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
-let updateState = null;
-function checkUpdateBg() {
- if (process.env.LUMREELS_SKIP_UPDATE === '1') return;
- const p = spawn(process.execPath, [fileURLToPath(new URL('../scripts/update.mjs', import.meta.url)), '--json'], { windowsHide: true });
- let out = '';
- p.stdout.on('data', (d) => { out += d; });
- p.on('error', () => {});
- p.on('close', () => { try { updateState = JSON.parse(out); } catch { /* bỏ qua */ } });
-}
-setTimeout(checkUpdateBg, 3000);
-setInterval(checkUpdateBg, 6 * 3600 * 1000).unref();
-
-server.listen(PORT, HOST, () => {
- console.log(`LumReels: http://${HOST}:${PORT} (chế độ mặc định: ${DEFAULT_MODE} → ${resolveMode(DEFAULT_MODE)}; OUTPUT_DIR ${config.outputDir() ? 'có' : 'chưa đặt'})`);
-});
+// Server API + UI. Chỉ bind 127.0.0.1:4400. Không framework.
+import http from 'node:http';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { spawn } from 'node:child_process';
+import {
+ ROOT, JOBS, TEMPLATES, loadCatalog, templateName, createJob, runJob, renderJob, readJob, listJobs, readLog, markStale,
+ dueJobs, resolveMode, submitScene, previewJob, createJobs, MAX_BATCH,
+} from '../generator/jobs.mjs';
+import { findClaude } from '../generator/claude.mjs';
+import { rewriteScript, resolveRewriteEngine, REWRITE_MAX_CHARS } from '../generator/rewrite.mjs';
+import { config } from '../generator/config.mjs';
+import { reAudio, listVersions, audioBusy, saveAudioSpec } from '../generator/audio-job.mjs';
+import { audioOptions, normalizeAudioPrefs, voiceEngine, sampleTextFor } from '../engine/audio/prefs.mjs';
+import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
+import { synthVoice } from '../engine/audio/voice.mjs';
+import { handleEditRoute, initEdits } from '../edit/http.mjs';
+import { handleVoiceRoute, initVoices } from './voices-http.mjs';
+import { handlePackRoute } from '../packs/http.mjs';
+import { listTemplates, resolveTemplate, parsePackRef, BUILTIN_TEMPLATE_RE } from '../packs/registry.mjs';
+import { originOk } from '../edit/http.mjs';
+import { isCloneVoice, cloneRef } from '../engine/audio/voice-store.mjs';
+import { handleDraftRoute, initDrafts } from '../packs/drafts-http.mjs';
+import { handleLogRoute, installLogCapture, redact } from './logs.mjs';
+import { readEditJob, EDITS } from '../edit/jobs.mjs';
+import { handleDoctorRoute } from './doctor.mjs';
+
+installLogCapture(ROOT); // log server vào ring buffer (GET /api/logs/server)
+
+const AUDIO_SAMPLES = path.join(ROOT, 'engine', 'audio', 'samples');
+/** File nghe thử (cache trong engine/audio/samples/, chỉ sinh khi chưa có). Trả đường dẫn tuyệt đối. */
+async function audioPreviewFile(q) {
+ const style = q.get('style'), voice = q.get('voice');
+ if (style) {
+ if (!MUSIC_STYLES.includes(style)) throw new Error('style nhạc không có: ' + style);
+ const f = path.join(AUDIO_SAMPLES, `music-${style}.wav`);
+ if (!fs.existsSync(f)) { fs.mkdirSync(AUDIO_SAMPLES, { recursive: true }); writeMusic(style, f, 8, 1); }
+ return f;
+ }
+ if (voice) {
+ const { voice: v } = normalizeAudioPrefs({ voice });
+ const text = String(q.get('text') || sampleTextFor(v)).trim().slice(0, 160);
+ if (v === 'auto' || v === 'none') throw new Error('chọn 1 giọng cụ thể để nghe thử');
+ // giọng nhân bản: câu nghe thử đã đọc sẵn lúc tạo giọng
+ if (isCloneVoice(v) && !q.get('text')) { const f = path.join(path.dirname(cloneRef(v).wav), 'sample.wav'); if (fs.existsSync(f)) return f; }
+ const ve = voiceEngine(v);
+ const [r] = await synthVoice([{ t: 0, text }], path.join(AUDIO_SAMPLES, 'voices'), { engine: ve.engine, voice: ve.speaker, log: (l) => console.log('[audio] ' + l) });
+ return r.file;
+ }
+ throw new Error('cần ?style=<nhạc> hoặc ?voice=<giọng>&text=...');
+}
+
+const HOST = '127.0.0.1';
+const PORT = Number(process.env.PORT) || 4400;
+const PUBLIC = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
+const DEFAULT_MODE = process.env.VIDEOAI_MODE || 'auto';
+const ALLOWED_HOSTS = new Set([`127.0.0.1:${PORT}`, `localhost:${PORT}`]);
+// L9: trang chỉ chạy script của chính app (file ngoài, index.html không có script nội tuyến); chữ của gói không thành code được.
+const PAGE_CSP = "default-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
+
+const FRAME_CSP = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'none'; object-src 'none'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'";
+
+const MIME = {
+ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
+ '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
+ '.png': 'image/png', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.m4a': 'audio/mp4', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.aac': 'audio/aac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg', '.flac': 'audio/flac', '.woff2': 'font/woff2', '.md': 'text/markdown; charset=utf-8',
+};
+
+// ---- hàng đợi: mỗi lúc chỉ 1 job chạy (render nặng) ----
+const queue = [];
+let busy = false;
+const queuedIds = new Set();
+/** Xếp 1 job vào hàng (không xếp trùng). */
+function enqueueJob(id, fn) {
+ if (queuedIds.has(id)) return;
+ queuedIds.add(id);
+ enqueue(async () => { try { await fn(); } finally { queuedIds.delete(id); } });
+}
+function enqueue(fn) {
+ queue.push(fn);
+ pump();
+}
+async function pump() {
+ if (busy) return;
+ const fn = queue.shift();
+ if (!fn) return;
+ busy = true;
+ try { await fn(); } catch (e) { console.error('[queue]', e); }
+ busy = false;
+ pump();
+}
+
+function send(res, code, body, type = 'application/json; charset=utf-8') {
+ const data = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body);
+ res.writeHead(code, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
+ res.end(data);
+}
+
+/** Phục vụ file tĩnh trong baseDir (chặn ../), hỗ trợ Range cho video. */
+function serveFile(req, res, baseDir, rel) {
+ const file = path.resolve(baseDir, '.' + path.sep + rel);
+ if (!file.startsWith(path.resolve(baseDir) + path.sep)) return send(res, 403, { error: 'forbidden' });
+ let st;
+ try { st = fs.statSync(file); } catch { return send(res, 404, { error: 'không thấy file' }); }
+ if (!st.isFile()) return send(res, 404, { error: 'không thấy file' });
+ const type = MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
+ const range = req.headers.range && /bytes=(\d*)-(\d*)/.exec(req.headers.range);
+ const headers = { 'Content-Type': type, 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' };
+ // khung xem trước đồ hoạ của Studio (studio/gfx-frame.html) được nhúng vào chính trang app (iframe sandbox): frame-ancestors 'self'
+ if (type.startsWith('text/html')) headers['Content-Security-Policy'] = path.basename(file) === 'gfx-frame.html' ? FRAME_CSP : PAGE_CSP;
+ if (range) {
+ const start = range[1] ? Number(range[1]) : 0;
+ const end = range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;
+ if (start >= st.size || start > end) { res.writeHead(416, { 'Content-Range': `bytes */${st.size}` }); return res.end(); }
+ res.writeHead(206, { ...headers, 'Content-Range': `bytes ${start}-${end}/${st.size}`, 'Content-Length': end - start + 1 });
+ return fs.createReadStream(file, { start, end }).pipe(res);
+ }
+ res.writeHead(200, { ...headers, 'Content-Length': st.size });
+ if (req.method === 'HEAD') return res.end();
+ fs.createReadStream(file).pipe(res);
+}
+
+function readBody(req, limit = 64 * 1024) {
+ return new Promise((resolve, reject) => {
+ let size = 0; const chunks = [];
+ req.on('data', (c) => { size += c.length; if (size > limit) { reject(new Error('body quá lớn')); req.destroy(); } else chunks.push(c); });
+ req.on('end', () => {
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')); } catch { reject(new Error('JSON không hợp lệ')); }
+ });
+ req.on('error', reject);
+ });
+}
+
+// Ảnh/video minh hoạ mỗi mẫu, theo thứ tự ưu tiên:
+// ảnh: 1. site/dist/media/<id>.webp (poster video demo, sinh bởi site/build.mjs — không có trong repo)
+// 2. templates/thumbs/<id>.webp (khung keyframe 360×640 có sẵn trong repo; tạo bằng scripts/make-thumbs.mjs)
+// 3. khung video tham chiếu riêng trên máy (templates/ref/<id>/frames, tools/fetch_refs.py — không có trong repo)
+// 4. poster SVG tự dựng (/poster/<id>.svg) từ tên + nhóm của mẫu
+// video: demo (site/dist/media/<id>.mp4) → video tham chiếu riêng → không có
+const DEMO = path.join(ROOT, 'site', 'dist', 'media');
+const THUMBS = path.join(TEMPLATES, 'thumbs');
+// LUMREELS_NO_REF=1: bỏ qua templates/ref (giả lập máy vừa clone repo; dùng khi chụp ảnh docs).
+const USE_REF = process.env.LUMREELS_NO_REF !== '1';
+function templateList() {
+ // gốc + gói (packs/registry.mjs). Mẫu gói: ảnh từ gói (/pack-thumbs/…) hoặc poster SVG; không có video demo.
+ return listTemplates().map((t) => {
+ if (t.source !== 'builtin') {
+ const pr = parsePackRef(t.ref);
+ const r = resolveTemplate(t.ref);
+ return {
+ id: t.ref, ref: t.ref, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre || '', technique: t.technique || [],
+ difficulty: t.difficulty, narration: !!t.narration, source: t.source, packId: t.packId, restricted: true, hasGuidance: true,
+ thumb: r?.thumbFile ? `/pack-thumbs/${pr.packId}/template-${pr.slug}.webp` : `/poster/p/${pr.packId}/${pr.slug}.svg`,
+ video: null, videoKind: null,
+ };
+ }
+ const ref = path.join(TEMPLATES, 'ref', t.id);
+ const refThumb = USE_REF && ['f_08.jpg', 'f_09.jpg', 'f_07.jpg'].find((f) => fs.existsSync(path.join(ref, 'frames', f)));
+ const demo = fs.existsSync(path.join(DEMO, `${t.id}.mp4`));
+ const demoPoster = fs.existsSync(path.join(DEMO, `${t.id}.webp`));
+ const keyThumb = fs.existsSync(path.join(THUMBS, `${t.id}.webp`));
+ const refVideo = USE_REF && fs.existsSync(path.join(ref, 'video.mp4'));
+ return {
+ id: t.id, ref: t.id, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre, technique: t.technique,
+ difficulty: t.difficulty, narration: t.narration, source: 'builtin', restricted: t.restricted,
+ hasGuidance: t.hasGuidance,
+ thumb: demoPoster ? `/demo/${t.id}.webp` : keyThumb ? `/thumbs/${t.id}.webp` : refThumb ? `/ref/${t.id}/frames/${refThumb}` : `/poster/${t.id}.svg`,
+ video: demo ? `/demo/${t.id}.mp4` : refVideo ? `/ref/${t.id}/video.mp4` : null,
+ videoKind: demo ? 'demo' : refVideo ? 'ref' : null,
+ source: 'builtin',
+ };
+ });
+}
+
+/** Poster SVG cho mẫu chưa có video demo: nền gradient theo id, tên phong cách, nhóm. */
+const CAT_LABEL = { faceless: 'Faceless', ads: 'Quảng cáo', 'multi-style': 'Đa phong cách', 'viet-nam': 'Việt Nam hoá' };
+function posterSvg(t) {
+ const n = BUILTIN_TEMPLATE_RE.test(t.id) ? Number(t.id) : [...String(t.id)].reduce((a, c) => (a * 31 + c.charCodeAt(0)) % 997, 7);
+ const h1 = (n * 47) % 360, h2 = (h1 + 40 + (n % 5) * 12) % 360;
+ const x = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ // ngắt tên thành tối đa 4 dòng ~12 ký tự
+ const words = String(t.name).split(/\s+/); const lines = [''];
+ for (const w of words) { if ((lines.at(-1) + ' ' + w).trim().length > 12 && lines.at(-1)) lines.push(w); else lines[lines.length - 1] = (lines.at(-1) + ' ' + w).trim(); }
+ const shown = lines.slice(0, 4);
+ const tech = (t.technique || []).includes('three') ? '3D' : (t.technique || []).includes('webgl-shader') ? 'Shader' : '2D';
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 540 960" width="540" height="960">
+<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="hsl(${h1} 45% 22%)"/><stop offset="1" stop-color="hsl(${h2} 55% 12%)"/></linearGradient></defs>
+<rect width="540" height="960" fill="url(#g)"/>
+<circle cx="${380 + (n % 7) * 10}" cy="${260 + (n % 4) * 30}" r="170" fill="hsl(${h2} 70% 60% / .18)"/>
+<rect x="44" y="300" width="72" height="8" rx="4" fill="hsl(${h1} 80% 70%)"/>
+<text x="44" y="270" font-family="'Be Vietnam Pro',sans-serif" font-size="30" font-weight="600" fill="#fff" fill-opacity=".7">${BUILTIN_TEMPLATE_RE.test(t.id) ? '#' + x(t.id) : x(String(t.id).split('/')[1] || '')}</text>
+${shown.map((l, i) => `<text x="44" y="${390 + i * 74}" font-family="'Be Vietnam Pro',sans-serif" font-size="60" font-weight="800" fill="#fff">${x(l)}</text>`).join('\n')}
+<text x="44" y="880" font-family="'Be Vietnam Pro',sans-serif" font-size="28" font-weight="500" fill="#fff" fill-opacity=".75">${x(CAT_LABEL[t.category] || t.category)} · ${tech}</text>
+</svg>`;
+}
+
+function jobView(job, withLog = false) {
+ const dir = path.join(JOBS, job.id);
+ const has = (f) => fs.existsSync(path.join(dir, f));
+ const v = {
+ ...job,
+ templateTitle: templateName(job.templateId) || job.templateTitle,
+ queued: queue.length,
+ versions: listVersions(job.id).map((v) => ({ ...v, url: `/jobs/${job.id}/${v.file}` })),
+ audioBusy: audioBusy(job.id),
+ links: {
+ mp4: has('out.mp4') && job.status === 'done' ? `/jobs/${job.id}/out.mp4` : null,
+ preview: has('preview.jpg') ? `/jobs/${job.id}/preview.jpg` : null,
+ prompt: `/jobs/${job.id}/PROMPT.md`,
+ brief: has('brief.json') ? `/jobs/${job.id}/brief.json` : null,
+ },
+ paths: { dir, prompt: path.join(dir, 'PROMPT.md'), scene: path.join(dir, 'scene', 'index.html') },
+ };
+ if (v.error) v.error = redact(v.error);
+ if (withLog) v.log = readLog(job.id, 120).map(redact);
+ return v;
+}
+
+/** Job vừa tạo: hẹn giờ thì để bộ hẹn giờ lo; manual chỉ chuyển sang waiting_agent; còn lại xếp hàng chạy. */
+async function startJob(job) {
+ if (job.status === 'scheduled') return; // bộ hẹn giờ sẽ chạy khi tới giờ
+ if (resolveMode(job.mode) === 'manual') await runJob(job.id);
+ else enqueueJob(job.id, () => runJob(job.id));
+}
+
+/** Job dựng thử của nháp "Tạo mẫu từ video": xếp vào hàng đợi chung, trả job khi xong. */
+function draftTestRunner(id) {
+ return new Promise((resolve) => {
+ enqueueJob(id, async () => {
+ try { resolve(await runJob(id, { force: true })); } catch (e) { console.error('[draft-test]', id, e.message); resolve(readJob(id)); }
+ });
+ });
+}
+
+let rewriteBusy = false;
+let rewriteLast = 0;
+
+const server = http.createServer(async (req, res) => {
+ const url = new URL(req.url, `http://${HOST}`);
+ const p = decodeURIComponent(url.pathname);
+ // Chống DNS rebinding: chỉ nhận Host là 127.0.0.1/localhost đúng cổng.
+ if (!ALLOWED_HOSTS.has(String(req.headers.host || '').toLowerCase())) return send(res, 421, { error: 'host không hợp lệ' });
+ // Trang web lạ không gửi lệnh ghi vào được (tạo job, cài gói, xoá…): Origin phải là chính app (không có Origin = curl/agent cục bộ).
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && !originOk(req, ALLOWED_HOSTS)) {
+ res.setHeader('Connection', 'close'); res.on('finish', () => req.destroy());
+ return send(res, 403, { error: 'origin không hợp lệ' });
+ }
+ try {
+ // ---- Nhật ký (server/logs.mjs): chỉ đọc, đã lọc bí mật ----
+ if (handleLogRoute(req, res, p, url, { send, originOk: (r) => originOk(r, ALLOWED_HOSTS), jobsDir: JOBS, editsDir: EDITS, readJob, readEdit: readEditJob })) return;
+ // ---- Gói mẫu .lumpack (packs/http.mjs) ----
+ if (await handlePackRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
+ // ---- Edit video của bạn (edit/http.mjs) ----
+ if (await handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
+ // ---- Giọng của tôi (server/voices-http.mjs) ----
+ if (await handleVoiceRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
+ // ---- Tạo mẫu từ video (packs/drafts-http.mjs): job dựng thử đi qua hàng đợi chung ----
+ if (await handleDraftRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS, runTest: draftTestRunner })) return;
+ // ---- Kiểm tra máy + khoá Anthropic (server/doctor.mjs) ----
+ if (await handleDoctorRoute(req, res, p, url, { send, readBody, originOk: (r) => originOk(r, ALLOWED_HOSTS) })) return;
+ // ---- API ----
+ if (p === '/api/templates' && req.method === 'GET') return send(res, 200, templateList());
+ if (p === '/api/version' && req.method === 'GET') return send(res, 200, { version: PKG_VERSION, update: updateState });
+ if (p === '/api/config' && req.method === 'GET') {
+ return send(res, 200, { defaultMode: DEFAULT_MODE, autoResolves: resolveMode('auto'), claudeAvailable: !!findClaude(), apiAvailable: config.hasApiKey(), outputDir: !!config.outputDir(), rewriteEngine: resolveRewriteEngine() });
+ }
+ if (p === '/api/rewrite' && req.method === 'POST') {
+ // Chống bấm liên tục: mỗi lúc 1 lượt, cách nhau ≥ 3 giây.
+ if (rewriteBusy) return send(res, 429, { error: 'Đang viết lại 1 bản, chờ xong rồi bấm tiếp' });
+ if (Date.now() - rewriteLast < 3000) return send(res, 429, { error: 'Bấm chậm lại chút (cách nhau 3 giây)' });
+ const body = await readBody(req);
+ if (String(body.content || '').length > REWRITE_MAX_CHARS) return send(res, 413, { error: `Nội dung quá dài (tối đa ${REWRITE_MAX_CHARS} ký tự)` });
+ rewriteBusy = true;
+ try {
+ const r = await rewriteScript({ templateId: body.templateId, content: body.content, durationS: body.durationS });
+ console.log(`[rewrite] mẫu ${r.templateId}, ${r.durationS}s, ${r.engine}${r.fallbackFrom ? ' (sau khi ' + r.fallbackFrom + ')' : ''}`);
+ return send(res, 200, r);
+ } catch (e) {
+ return send(res, /chưa cấu hình AI/i.test(e.message) ? 503 : 422, { error: e.message });
+ } finally {
+ rewriteBusy = false; rewriteLast = Date.now();
+ }
+ }
+ if (p === '/api/jobs' && req.method === 'GET') return send(res, 200, listJobs().map((j) => jobView(j)));
+ if (p === '/api/jobs' && req.method === 'POST') {
+ const body = await readBody(req);
+ const job = createJob({ templateId: body.templateId, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
+ await startJob(job);
+ return send(res, 201, jobView(readJob(job.id), true));
+ }
+ if (p === '/api/jobs/batch' && req.method === 'POST') {
+ // Chọn nhiều mẫu: 1 job / mẫu, cùng nội dung + tuỳ chọn. Kiểm cả lô trước, sai 1 id là từ chối hết.
+ const body = await readBody(req);
+ if (!Array.isArray(body.templateIds)) return send(res, 400, { error: 'templateIds phải là mảng id mẫu' });
+ if (body.templateIds.length > MAX_BATCH) return send(res, 400, { error: `Tối đa ${MAX_BATCH} mẫu mỗi lô` });
+ let jobs;
+ try {
+ jobs = createJobs({ templateIds: body.templateIds, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
+ } catch (e) { return send(res, 400, { error: e.message, badIds: e.badIds || [] }); }
+ for (const job of jobs) await startJob(job);
+ console.log(`[batch] ${jobs.length} job: ${jobs.map((j) => j.templateId).join(', ')}`);
+ return send(res, 201, { jobs: jobs.map((j) => jobView(readJob(j.id))) });
+ }
+ let ms = /^\/api\/jobs\/([\w-]+)\/scene$/.exec(p);
+ if (ms && req.method === 'POST') {
+ const body = await readBody(req, 2_500_000);
+ if (body.audio !== undefined && body.audio !== null) await saveAudioSpec(ms[1], body.audio); // scene/audio.json (AUTHORING §9)
+ const r = submitScene(ms[1], body.html, body.brief);
+ return send(res, r.ok ? 200 : 422, r);
+ }
+ ms = /^\/api\/jobs\/([\w-]+)\/preview$/.exec(p);
+ if (ms && req.method === 'POST') {
+ const r = await previewJob(ms[1]);
+ return send(res, r.ok ? 200 : 422, { ok: r.ok, errors: r.errors, preview: r.ok ? `/jobs/${ms[1]}/preview.jpg` : null });
+ }
+ let m = /^\/api\/jobs\/([\w-]+)$/.exec(p);
+ if (m && req.method === 'GET') {
+ const job = readJob(m[1]);
+ return job ? send(res, 200, jobView(job, true)) : send(res, 404, { error: 'không thấy job' });
+ }
+ m = /^\/api\/jobs\/([\w-]+)\/render$/.exec(p);
+ if (m && req.method === 'POST') {
+ const job = readJob(m[1]);
+ if (!job) return send(res, 404, { error: 'không thấy job' });
+ enqueueJob(job.id, () => renderJob(job.id));
+ return send(res, 202, jobView(job, true));
+ }
+ // ---- âm thanh ----
+ if (p === '/api/audio/options' && req.method === 'GET') return send(res, 200, audioOptions());
+ if (p === '/api/audio/preview' && req.method === 'GET') {
+ const f = await audioPreviewFile(url.searchParams);
+ return serveFile(req, res, path.dirname(f), path.basename(f));
+ }
+ m = /^\/api\/jobs\/([\w-]+)\/audio$/.exec(p);
+ if (m && req.method === 'POST') {
+ const job = readJob(m[1]);
+ if (!job) return send(res, 404, { error: 'không thấy job' });
+ if (job.status !== 'done' && !fs.existsSync(path.join(JOBS, job.id, 'out.mp4'))) return send(res, 409, { error: 'video chưa dựng xong' });
+ if (audioBusy(job.id)) return send(res, 409, { error: 'đang trộn tiếng cho video này' });
+ const body = await readBody(req);
+ const prefs = { music: body.music, voice: body.voice, sfx: body.sfx };
+ normalizeAudioPrefs({ ...prefs }); // kiểm sớm, sai thì 400
+ reAudio(job.id, prefs).catch((e) => console.error('[audio]', job.id, e.message)); // chạy nền; UI hỏi lại GET /api/jobs/:id
+ return send(res, 202, { ...jobView(readJob(job.id), true), audioBusy: true });
+ }
+ m = /^\/api\/jobs\/([\w-]+)\/versions$/.exec(p);
+ if (m && req.method === 'GET') return send(res, 200, listVersions(m[1]).map((v) => ({ ...v, url: `/jobs/${m[1]}/${v.file}` })));
+ if (p.startsWith('/api/')) return send(res, 404, { error: 'không có API này' });
+
+ // ---- file ----
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, { error: 'method' });
+ if (p.startsWith('/ref/') && USE_REF) return serveFile(req, res, path.join(TEMPLATES, 'ref'), p.slice(5));
+ m = /^\/demo\/(\d{3}\.(?:mp4|webp))$/.exec(p);
+ if (m) return serveFile(req, res, DEMO, m[1]);
+ m = /^\/thumbs\/(\d{3}\.webp)$/.exec(p);
+ if (m) return serveFile(req, res, THUMBS, m[1]);
+ m = /^\/poster\/(\d{3})\.svg$/.exec(p);
+ if (m) {
+ const t = loadCatalog().find((x) => x.id === m[1]);
+ return t ? send(res, 200, posterSvg(t), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });
+ }
+ m = /^\/poster\/p\/([a-z0-9.-]{5,49})\/([a-z][a-z0-9-]{1,31})\.svg$/.exec(p);
+ if (m) {
+ const r = parsePackRef(`${m[1]}/${m[2]}`) && resolveTemplate(`${m[1]}/${m[2]}`);
+ return r ? send(res, 200, posterSvg({ id: r.ref, name: r.meta.name, category: r.meta.category, technique: r.meta.technique }), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });
+ }
+ m = /^\/jobs\/([\w-]+)\/(versions\/out-\d{1,4}\.mp4)$/.exec(p);
+ if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);
+ m = /^\/jobs\/([\w-]+)\/(out\.mp4|preview\.jpg|PROMPT\.md|brief\.json)$/.exec(p);
+ if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);
+ // font: khung xem trước đồ hoạ của Studio chạy sandbox (origin rỗng) → tải font cần CORS
+ if (p.startsWith('/fonts/')) { res.setHeader('Access-Control-Allow-Origin', '*'); return serveFile(req, res, path.join(ROOT, 'engine', 'fonts'), p.slice(7)); }
+ return serveFile(req, res, PUBLIC, p === '/' ? 'index.html' : p.slice(1));
+ } catch (e) {
+ return send(res, 400, { error: e.message });
+ }
+});
+
+markStale();
+initEdits(); // edit đang chạy dở khi server tắt → báo lỗi để bấm lại
+initVoices(); // giọng nhân bản đang xử lý dở → báo lỗi
+initDrafts(); // nháp "Tạo mẫu từ video" đang chạy dở → báo lỗi
+// Job queued còn sót (server tắt trước khi kịp chạy) → chạy lại.
+for (const j of listJobs()) if (j.status === 'queued' && resolveMode(j.mode) !== 'manual') enqueueJob(j.id, () => runJob(j.id));
+// Bộ hẹn giờ: 15 giây kiểm 1 lần, job tới giờ thì xếp hàng chạy.
+function tick() { for (const j of dueJobs()) enqueueJob(j.id, () => runJob(j.id, { force: true })); }
+setInterval(tick, 15000);
+tick();
+
+// Kiểm bản mới trên GitHub (chạy nền, không chặn app): lúc khởi động và 6 giờ/lần. Giao diện đọc qua /api/version.
+const PKG_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
+let updateState = null;
+function checkUpdateBg() {
+ if (process.env.LUMREELS_SKIP_UPDATE === '1') return;
+ const p = spawn(process.execPath, [fileURLToPath(new URL('../scripts/update.mjs', import.meta.url)), '--json'], { windowsHide: true });
+ let out = '';
+ p.stdout.on('data', (d) => { out += d; });
+ p.on('error', () => {});
+ p.on('close', () => { try { updateState = JSON.parse(out); } catch { /* bỏ qua */ } });
+}
+setTimeout(checkUpdateBg, 3000);
+setInterval(checkUpdateBg, 6 * 3600 * 1000).unref();
+
+server.listen(PORT, HOST, () => {
+ console.log(`LumReels: http://${HOST}:${PORT} (chế độ mặc định: ${DEFAULT_MODE} → ${resolveMode(DEFAULT_MODE)}; OUTPUT_DIR ${config.outputDir() ? 'có' : 'chưa đặt'})`);
+});