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.
Xuất bản nhanh: nền chỉ băm phần vẽ trong nền, đồ hoạ thành lớp riêng, phụ đề render lại từng đoạn
Lumtek8e994ae0d5cd
diff --git a/edit/captions-hf.mjs b/edit/captions-hf.mjsindex da888d8..65a554b 100644--- a/edit/captions-hf.mjs+++ b/edit/captions-hf.mjs@@ -1,397 +1,446 @@-// Phụ đề bản chính: một cảnh HyperFrames nền trong suốt (chỉ có chữ), render ra WebM VP9 có alpha,-// rồi ffmpeg chồng lên video nền. Font tiếng Việt lấy từ engine/fonts (fonts.css của LumReels).-// Mốc chữ đổi từ giây nguồn sang giây bản ra theo keep[] của EDL — cùng luật chia thẻ với phụ đề nháp (lumedit.py).-// Có câu móc (edl.hook) thì bản ra = [móc] + keep: timelineOf(edl) dời mọi mốc; móc lặp lại (repeat) thì chữ của-// câu móc hiện 2 lần (đầu clip và chỗ cũ). Mọi kiểu hiện chữ là hàm của t − c.start (render(t) thuần, gsap seek).-import fs from 'node:fs';-import path from 'node:path';-import { syncLib, runHF } from '../engine/lib.mjs';-import { toOutputNearest, outputDuration, timelineOf, SAFE, OUT } from './edl.mjs';-import { graphicsScene, GFX_RUNTIME } from './graphics.mjs';--const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));--/** Chia chữ thành nhóm (cùng luật với caption_cards trong edit/py/lumedit.py). */-function groupWords(words, maxWords) {- const groups = []; let cur = [];- words.forEach((w, n) => {- cur.push(w);- const nx = words[n + 1];- const ends = /[.?!,:;…]$/.test(w.w.trim());- const gap = nx ? nx.start - w.end : 99;- if (cur.length >= maxWords || ends || gap > 0.45 || !nx) { groups.push(cur); cur = []; }- });- return groups;-}--/** Cùng luật với caption_cards trong edit/py/lumedit.py. */-export function captionCards(edl) {- const cap = edl.captions; const tl = timelineOf(edl); const H = edl.hook;- // phụ đề chỉnh tay (giây bản ra, edit/manual.mjs): dùng nguyên dòng người dùng đặt, chỉ kiểm không đè nhau- if (cap.lines) {- const cards = cap.lines.map((l) => ({ start: l.start, end: l.end, words: l.words.map((w) => ({ w: w.w, i: -1, o: w.o, hl: w.hi })), wordOut: l.words.map((w) => Math.max(l.start, w.o)) }));- const bad = cardOverlaps(cards);- if (bad.length) throw new Error('phụ đề chỉnh tay chồng nhau: ' + bad.join('; '));- return cards;- }- // mỗi chữ mang giây bản ra (o) của chính nó: chữ câu móc lặp lại có 2 chỗ trên bản ra- const mk = (ws, map) => groupWords(ws, cap.maxWords).map((g) => ({ words: g.map((w) => ({ ...w, o: map(w.start) })), start: map(g[0].start), end: map(g[g.length - 1].end) }));- const cards = mk(cap.words, (t) => toOutputNearest(tl, t)).sort((a, b) => a.start - b.start);- if (!H) return finishCards(cards, tl);- // có câu móc: thẻ của câu móc (0 … hookDur) và thẻ phần sau làm riêng, để thẻ móc không kéo dài qua chỗ nối- const hd = H.end - H.start;- const inH = H.repeat ? cap.words.filter((w) => (w.start + w.end) / 2 >= H.start && (w.start + w.end) / 2 <= H.end) : [];- const head = H.repeat ? mk(inH, (t) => Math.min(hd, Math.max(0, t - H.start))) : cards.filter((c) => c.start < hd - 1e-6);- const rest = cards.filter((c) => c.start >= hd - 1e-6);- for (const c of head) c.end = Math.min(c.end, hd);- const a = head.length ? finishCards(head, tl) : [];- for (const c of a) c.end = Math.min(c.end, hd);- return a.concat(rest.length ? finishCards(rest, tl) : []);-}--export const MIN_CARD = 0.25; // một nhóm chữ hiện ít nhất chừng này (nếu chưa tới nhóm sau)-export const MERGE_BELOW = 0.1; // nhóm bị ép ngắn hơn chừng này (chữ nói rất nhanh) thì gộp vào nhóm sau--/**- * Luật thời gian của nhóm phụ đề (giống caption_cards trong lumedit.py):- * nối khe < 0,4 s; kéo dài tối thiểu MIN_CARD; KHÔNG BAO GIỜ chồng lên nhóm sau (cắt end về start của nhóm sau);- * nhóm còn < MERGE_BELOW thì gộp chữ vào nhóm sau. Lỗi cũ: kéo dài tối thiểu 0,25 s chạy SAU bước nối khe nên- * "TRÀ" (0,22 s) đè lên "SỮA" — 2 nhóm cùng hiện ở cùng chỗ.- */-export function finishCards(cards, keep) {- for (let k = 0; k + 1 < cards.length; k++) {- const gap = cards[k + 1].start - cards[k].end;- if (gap >= 0 && gap < 0.4) cards[k].end = cards[k + 1].start;- }- for (const c of cards) c.end = Math.max(c.end, c.start + MIN_CARD);- for (let k = 0; k + 1 < cards.length; k++) cards[k].end = Math.min(cards[k].end, cards[k + 1].start);- const out = [];- for (let k = 0; k < cards.length; k++) {- const c = cards[k]; const nx = cards[k + 1];- if (nx && c.end - c.start < MERGE_BELOW) { nx.words = c.words.concat(nx.words); nx.start = c.start; continue; }- out.push(c);- }- for (const c of out) c.wordOut = c.words.map((w) => Math.max(c.start, w.o ?? toOutputNearest(keep, w.start)));- const bad = cardOverlaps(out);- if (bad.length) throw new Error('phụ đề chồng nhau: ' + bad.join('; '));- return out;-}--/** Luật kiểm: không bao giờ 2 nhóm phụ đề hiện cùng lúc (mọi nhóm cùng 1 vị trí). Trả danh sách lỗi. */-export function cardOverlaps(cards) {- const errs = [];- for (let k = 0; k + 1 < cards.length; k++) {- if (cards[k].end > cards[k + 1].start + 1e-6) errs.push(`"${cards[k].words.map((w) => w.w).join(' ')}" (${cards[k].start.toFixed(2)}–${cards[k].end.toFixed(2)} s) đè "${cards[k + 1].words.map((w) => w.w).join(' ')}" (từ ${cards[k + 1].start.toFixed(2)} s)`);- if (cards[k].end <= cards[k].start) errs.push(`nhóm ${k} dài 0 s`);- }- return errs;-}--// Khoá: font, weight, size (px), upper, color, hi (chữ nhấn/karaoke), karaoke, cy (tâm dòng, phần khung),-// enter (fade | pop | pop-soft | slide-left | typewriter | ticker | slam | fade-slow),-// stroke (px viền, mặc định 10 chữ hoa / 8), shadow (CSS text-shadow), box (thanh tin), quote (trích dẫn).-// Chép từ khối "look" của edit-styles/<id>.md.-export const LOOKS = {- 'sach-gon': { font: "'Be Vietnam Pro'", weight: 800, size: 76, upper: false, color: '#FFFFFF', hi: '#FCE802', karaoke: false, cy: 0.70, enter: 'fade' },- 'thong-tin-do-hoa': { font: "'Be Vietnam Pro'", weight: 800, size: 68, upper: false, color: '#FFFFFF', hi: '#FCE802', karaoke: false, cy: 0.745, enter: 'pop-soft' },- 'phu-de-nay-mau': { font: "'Anton'", weight: 400, size: 150, upper: true, color: '#FFFFFF', hi: '#FCE802', karaoke: true, cy: 0.58, enter: 'pop' },- 'podcast-trich-doan': { font: "'Montserrat'", weight: 800, size: 96, upper: false, color: '#FFFFFF', hi: '#FF8A3D', karaoke: false, cy: 0.56, enter: 'fade' },- 'ke-chuyen': { font: "'Nunito'", weight: 800, size: 80, upper: false, color: '#FFFFFF', hi: '#7CF0C8', karaoke: true, cy: 0.66, enter: 'pop-soft' },- 'top-danh-sach': { font: "'Bungee'", weight: 400, size: 78, upper: true, color: '#FFFFFF', hi: '#FF2E93', karaoke: false, cy: 0.74, enter: 'slide-left' },- 'review-san-pham': { font: "'Oswald'", weight: 700, size: 88, upper: true, color: '#FFFFFF', hi: '#A78BFA', karaoke: false, cy: 0.77, enter: 'pop-soft' },- 'huong-dan-buoc': { font: "'Space Grotesk'", weight: 700, size: 70, upper: false, color: '#FFFFFF', hi: '#5EA2FF', karaoke: false, cy: 0.72, enter: 'typewriter' },- 'ban-tin-nhanh': {- font: "'Barlow Condensed'", weight: 700, size: 64, upper: true, color: '#FFFFFF', hi: '#00E5FF', karaoke: false, cy: 0.775, enter: 'ticker',- box: { bg: '#0B1E3F', full: true, align: 'left', stroke: 0, tag: 'TIN NÓNG', tagBg: '#E8202A' },- },- 'quan-diem-gat': { font: "'Alfa Slab One'", weight: 400, size: 104, upper: true, color: '#FFFFFF', hi: '#FF1F1F', karaoke: true, cy: 0.50, enter: 'slam' },- 'chot-don-livestream': { font: "'Baloo 2'", weight: 800, size: 96, upper: false, color: '#FFFFFF', hi: '#FFB020', karaoke: false, cy: 0.62, enter: 'pop' },- 'vlog-nhe': { font: "'Patrick Hand'", weight: 400, size: 60, upper: false, color: '#FFFDF7', hi: '#F5C6A5', karaoke: false, cy: 0.77, enter: 'fade-slow', stroke: 3, shadow: '0 3px 10px rgba(0,0,0,.45)' },- 'meo-15s': { font: "'Bangers'", weight: 400, size: 128, upper: true, color: '#FFFFFF', hi: '#00FF87', karaoke: false, cy: 0.64, enter: 'pop' },- 'cau-noi-hay': {- font: "'Lora'", weight: 600, size: 66, upper: false, color: '#F5F1E8', hi: '#D4AF37', karaoke: false, cy: 0.74, enter: 'fade-slow',- quote: { font: "'Playfair Display'", weight: 700, italic: true, size: 88, cy: 0.48, color: '#F5F1E8', marks: '#D4AF37', dimTo: 0.35, blurPx: 8, dimIn: 0.8, wordStagger: 0.12 },- },-};-export const lookOf = (captionStyle) => LOOKS[captionStyle] || LOOKS['sach-gon'];--// thanh tin (ticker): ô tag bên trái, chữ căn trái sau tag, cả thanh cao 1,5 em ở cy-const TICKER = { tagX: 60, tagPad: 22, tagEm: 0.62, gap: 24, right: Math.round(SAFE.x1 * OUT.width) };-const tickerTagW = (look) => Math.round([...look.box.tag].length * 0.56 * look.size * TICKER.tagEm + 2 * TICKER.tagPad);--/** Mép trên (px) của dòng phụ đề kiểu này — đồ hoạ đặt phía trên mép này. */-export function captionTop(captionStyle) {- const look = lookOf(captionStyle);- if (look.enter === 'ticker') return Math.round(look.cy * OUT.height - 0.75 * look.size) - 8;- return Math.round(look.cy * OUT.height - 0.6 * look.size * 1.18) - 8;-}--/** Cỡ chữ cho khối chữ tự xuống dòng: thu nhỏ tới khi ước số dòng ≤ maxLines (ước theo bề rộng trung bình 1 ký tự). */-export function fitBlock(text, widthPx, max, { maxLines = 4, em = 0.5, min = 40 } = {}) {- const n = [...text].length;- let size = max;- while (size > min && Math.ceil((n * em * size * 1.1) / widthPx) > maxLines) size -= 2;- return size;-}--/** Chữ móc: "*3 GIÂY* LÀ XONG" → [{t, hi}] (chữ trong *…* là chữ nhấn). */-export function hookTextParts(text) {- const parts = []; const re = /\*([^*]+)\*|([^*]+)/g; let m;- while ((m = re.exec(String(text)))) { if (m[1]) parts.push({ t: m[1], hi: true }); else if (m[2]) parts.push({ t: m[2], hi: false }); }- return parts;-}--/** Khoảng câu trích dẫn trên bản ra: {q0, q1, end, words:[{w, i, o}]} hoặc null. */-export function quoteSpan(edl, dur) {- const q = edl.quote; if (!q) return null;- const look = lookOf(edl.captions.style).quote || LOOKS['cau-noi-hay'].quote;- const tl = timelineOf(edl);- const q0 = toOutputNearest(tl, q.start); const q1 = toOutputNearest(tl, q.end);- const hold = q1 >= dur - 2.0; // câu chốt ở cuối: giữ tối tới hết clip- const end = hold ? dur : Math.min(dur, q1 + 0.8);- let last = -Infinity;- const words = edl.captions.words.filter((w) => (w.start + w.end) / 2 >= q.start - 1e-6 && (w.start + w.end) / 2 <= q.end + 1e-6).map((w) => {- const o = Math.max(q0, toOutputNearest(tl, w.start), last + look.wordStagger); last = o;- return { w: w.w, i: w.i, o };- });- return { q0, q1, end, hold, words };-}--/**- * Ghi cảnh vào sceneDir. Trả {duration, cards, graphics, box}.- * opts.captions=false: chỉ lớp đồ hoạ (bản nháp: phụ đề đã vẽ PIL trong nền). opts.accent: màu nhấn của đồ hoạ.- * opts.style: thẻ kiểu (chữ móc hook.text, thanh bước graphics.stepTracker).- */-export function writeCaptionScene(edl, sceneDir, { captions = true, accent, style = null } = {}) {- const look = lookOf(edl.captions.style);- const tlk = timelineOf(edl);- const dur = Math.max(1 / OUT.fps, Math.round(outputDuration(tlk) * OUT.fps) / OUT.fps);- let cards = captions && edl.captions.words.length ? captionCards(edl) : [];- const gfx = (edl.graphics || []).length ? graphicsScene(edl, { accent: accent || look.hi, stepTracker: !!style?.graphics?.stepTracker, dur }) : null;- const hiSet = new Set(edl.captions.hiOff ? [] : edl.captions.highlights);- // chữ nhấn: dòng chỉnh tay mang cờ hl riêng; tắt chữ nhấn (hiOff) thì không chữ nào nhấn- const hi = { has: (i, wd) => !edl.captions.hiOff && (wd?.hl ?? hiSet.has(i)) };- const x0 = Math.round(SAFE.x0 * OUT.width); const w = Math.round((SAFE.x1 - SAFE.x0) * OUT.width);- const cy = Math.round(look.cy * OUT.height); const yMax = Math.round(SAFE.y1 * OUT.height);-- // câu trích dẫn: phụ đề thường tắt trong lúc đó- const qs = captions ? quoteSpan(edl, dur) : null;- if (qs) {- cards = cards.filter((c) => !(c.start >= qs.q0 - 1e-3 && c.start < qs.end));- for (const c of cards) if (c.start < qs.q0 && c.end > qs.q0) c.end = qs.q0;- }- const ticker = look.enter === 'ticker' && look.box;- const tagW = ticker ? tickerTagW(look) : 0;- const tkLeft = TICKER.tagX + tagW + TICKER.gap; const tkW = TICKER.right - tkLeft;- const stroke = look.box ? (look.box.stroke ?? 0) : (look.stroke ?? (look.upper ? 10 : 8));- const shadow = look.shadow || (ticker ? 'none' : '0 6px 18px rgba(0,0,0,.55)');-- const html = cards.map((c, ci) => {- // dấu , . ; : cuối chữ không hiện trên phụ đề (giữ ? ! …)- const text = c.words.map((wd) => { const t = wd.w.replace(/[,.;:]+$/u, '') || wd.w; return look.upper ? t.toUpperCase() : t; });- let size;- if (ticker) {- // thanh tin: 1 dòng, thu cỡ theo bề ngang còn lại sau ô tag (Barlow Condensed ~0,46 em mỗi ký tự hoa)- const n = text.join(' ').length;- size = Math.max(34, Math.min(look.size, Math.floor(tkW / (n * 0.46 + 0.4))));- } else {- // thẻ 1 chữ dài thì thu nhỏ để vừa vùng an toàn (Anton ~0,48 em mỗi ký tự hoa)- const longest = Math.max(...text.map((t) => t.length));- size = c.words.length === 1 ? Math.min(look.size, Math.floor(w / (longest * 0.5 + 0.5))) : look.size;- }- const inner = (t) => (look.enter === 'typewriter' ? [...t].map((ch) => `<i class="ch">${esc(ch)}</i>`).join('') : esc(t));- const spans = c.words.map((wd, k) => `<span class="w${hi.has(wd.i, wd) ? ' hi' : ''}" id="c${ci}w${k}">${inner(text[k])}</span>`).join(' ');- return `<div class="card${ticker ? ' tk' : ''}" id="c${ci}" style="font-size:${size}px">${spans}</div>`;- }).join('\n ');-- // thanh tin: mỗi câu (chuỗi thẻ liền nhau tới dấu kết câu / khoảng lặng > 0,5 s) là 1 lượt thanh trượt vào- const runs = [];- if (ticker) {- cards.forEach((c, ci) => {- const prev = cards[ci - 1];- const brk = !prev || /[.?!…]$/.test(prev.words[prev.words.length - 1].w.trim()) || c.start - prev.end > 0.5;- if (brk) runs.push({ first: ci, start: c.start, end: c.end }); else runs[runs.length - 1].end = c.end;- });- }- const firstOfRun = new Set(runs.map((r) => r.first));-- const timeline = cards.map((c, ci) => {- const t0 = c.start.toFixed(3);- const lines = [`tl.set('#c${ci}', {autoAlpha: 1}, ${t0});`];- switch (look.enter) {- case 'pop': lines.push(`tl.fromTo('#c${ci}', {scale: 0.55}, {scale: 1, duration: 0.18, ease: 'back.out(3)'}, ${t0});`); break;- case 'pop-soft': lines.push(`tl.fromTo('#c${ci}', {scale: 0.86, opacity: 0}, {scale: 1, opacity: 1, duration: 0.14, ease: 'back.out(2.2)'}, ${t0});`); break;- case 'slide-left': lines.push(`tl.fromTo('#c${ci}', {x: 80, opacity: 0}, {x: 0, opacity: 1, duration: 0.16, ease: 'power3.out'}, ${t0});`); break;- case 'slam': {- lines.push(`tl.fromTo('#c${ci}', {scale: 1.6, opacity: 0.4}, {scale: 1, opacity: 1, duration: 0.12, ease: 'power4.in'}, ${t0});`);- [6, -6, 6, 0].forEach((x, k) => lines.push(`tl.to('#c${ci}', {x: ${x}, duration: 0.025, ease: 'none'}, ${(c.start + 0.12 + k * 0.025).toFixed(3)});`));- break;- }- case 'fade-slow': {- lines.push(`tl.fromTo('#c${ci}', {opacity: 0}, {opacity: 1, duration: 0.3, ease: 'power1.out'}, ${t0});`);- const nx = cards[ci + 1];- if ((!nx || nx.start - c.end >= 0.3) && c.end - c.start > 0.55) lines.push(`tl.to('#c${ci}', {opacity: 0, duration: 0.25, ease: 'power1.in'}, ${(c.end - 0.25).toFixed(3)});`);- break;- }- case 'typewriter': {- // ký tự k hiện ở c.start + k × min(0,035, (end − start) × 0,6 / số ký tự)- const n = c.words.reduce((s, wd) => s + [...(wd.w.replace(/[,.;:]+$/u, '') || wd.w)].length, 0);- const stepS = Math.min(0.035, ((c.end - c.start) * 0.6) / Math.max(1, n));- lines.push(`tl.set('#c${ci} .ch', {opacity: 0}, ${t0});`);- lines.push(`gsap.utils.toArray('#c${ci} .ch').forEach(function (el, k) { tl.set(el, {opacity: 1}, ${t0} + k * ${stepS.toFixed(4)}); });`);- break;- }- case 'ticker': {- if (!firstOfRun.has(ci)) lines.push(`tl.fromTo('#c${ci}', {opacity: 0}, {opacity: 1, duration: 0.08, ease: 'none'}, ${t0});`);- break;- }- default: lines.push(`tl.fromTo('#c${ci}', {y: 18, opacity: 0}, {y: 0, opacity: 1, duration: 0.12, ease: 'power2.out'}, ${t0});`);- }- if (look.karaoke && c.words.length > 1) {- c.words.forEach((wd, k) => {- const a = c.wordOut[k]; const b = k + 1 < c.words.length ? c.wordOut[k + 1] : c.end;- lines.push(`tl.set('#c${ci}w${k}', {color: '${look.hi}'}, ${a.toFixed(3)}); tl.set('#c${ci}w${k}', {color: '${hi.has(wd.i, wd) ? look.hi : look.color}'}, ${b.toFixed(3)});`);- });- }- lines.push(`tl.set('#c${ci}', {autoAlpha: 0}, ${c.end.toFixed(3)});`);- return lines.join(' ');- });- runs.forEach((r, k) => {- timeline.push(`tl.set('#tbar', {autoAlpha: 1}, ${r.start.toFixed(3)}); tl.fromTo('#tbar', {x: -${OUT.width}}, {x: 0, duration: 0.2, ease: 'power3.out'}, ${r.start.toFixed(3)});`);- const nx = runs[k + 1];- if (!nx || nx.start > r.end + 0.02) timeline.push(`tl.set('#tbar', {autoAlpha: 0}, ${r.end.toFixed(3)});`);- });-- // câu trích dẫn to giữa khung- let quoteHtml = ''; let quoteCss = '';- if (qs && qs.words.length) {- const q = look.quote || LOOKS['cau-noi-hay'].quote;- const text = qs.words.map((x) => x.w).join(' ');- const qsize = fitBlock(`“${text}”`, w, q.size, { maxLines: 4, em: 0.5, min: 44 });- quoteHtml = `<div id="quote" style="font-size:${qsize}px"><span class="qm" id="qmo">“</span>${qs.words.map((x, k) => `<span class="qw${hi.has(x.i) ? ' hi' : ''}" id="qw${k}">${esc(x.w)}</span>`).join(' ')}<span class="qm" id="qmc">”</span></div>`;- quoteCss = `- #quote { position:absolute; left:${x0}px; width:${w}px; top:${Math.round(q.cy * OUT.height)}px; transform:translateY(-50%); text-align:center; line-height:1.25;- font-family:${q.font}, serif; font-weight:${q.weight}; font-style:${q.italic ? 'italic' : 'normal'}; color:${q.color};- text-shadow:0 4px 24px rgba(0,0,0,.6); visibility:hidden; opacity:0; }- #quote .qw { display:inline-block; opacity:0; }- #quote .qw.hi { color:${q.marks}; }- #quote .qm { color:${q.marks}; font-size:1.3em; line-height:0; opacity:0; padding:0 .06em; }`;- timeline.push(`tl.set('#quote', {autoAlpha: 1}, ${qs.q0.toFixed(3)}); tl.to('#qmo', {opacity: 1, duration: 0.3}, ${qs.q0.toFixed(3)});`);- qs.words.forEach((x, k) => timeline.push(`tl.fromTo('#qw${k}', {opacity: 0, y: 14}, {opacity: 1, y: 0, duration: 0.2, ease: 'power2.out'}, ${x.o.toFixed(3)});`));- const lastO = qs.words[qs.words.length - 1].o;- timeline.push(`tl.to('#qmc', {opacity: 1, duration: 0.3}, ${(lastO + 0.15).toFixed(3)});`);- if (!qs.hold) timeline.push(`tl.to('#quote', {opacity: 0, duration: 0.3}, ${Math.max(lastO + 0.4, qs.end - 0.3).toFixed(3)}); tl.set('#quote', {autoAlpha: 0}, ${qs.end.toFixed(3)});`);- }-- // chữ móc to 0 → until (kiểu meo-15s)- let hookHtml = ''; let hookCss = '';- if (captions && edl.hookText) {- const ht = { font: "'Bangers'", size: 150, cy: 0.22, color: '#FFFFFF', hi: look.hi, ...(style?.hook?.text || {}) };- const parts = hookTextParts(edl.hookText.text.toUpperCase());- const plain = parts.map((p) => p.t).join('');- const hsize = fitBlock(plain, w, ht.size, { maxLines: 2, em: 0.46, min: 70 });- hookHtml = `<div id="hooktext" style="font-size:${hsize}px">${parts.map((p) => `<span${p.hi ? ' class="hi"' : ''}>${esc(p.t)}</span>`).join('')}</div>`;- hookCss = `- #hooktext { position:absolute; left:${x0}px; width:${w}px; top:${Math.round(ht.cy * OUT.height)}px; margin-top:-0.55em; text-align:center; line-height:1.05;- font-family:${ht.font}, sans-serif; color:${ht.color}; -webkit-text-stroke:12px #000; paint-order:stroke fill;- text-shadow:0 8px 24px rgba(0,0,0,.55); transform-origin:50% 50%; visibility:hidden; opacity:0; }- #hooktext .hi { color:${ht.hi}; }`;- const until = Math.min(edl.hookText.until, dur);- timeline.push(`tl.set('#hooktext', {autoAlpha: 1}, 0); tl.fromTo('#hooktext', {scale: 0.4, rotation: -4}, {scale: 1, rotation: -2, duration: 0.3, ease: 'back.out(2.6)'}, 0); tl.to('#hooktext', {opacity: 0, scale: 1.08, duration: 0.18}, ${Math.max(0.35, until - 0.18).toFixed(3)}); tl.set('#hooktext', {autoAlpha: 0}, ${until.toFixed(3)});`);- }-- const tickerHtml = ticker ? `<div id="tbar"><div class="tag">${esc(look.box.tag)}</div>\n ${html}\n </div>` : '';- const tickerCss = ticker ? `- #tbar { position:absolute; left:0; width:${OUT.width}px; top:${cy}px; height:${Math.round(1.5 * look.size)}px; margin-top:-${Math.round(0.75 * look.size)}px;- background:${look.box.bg}; visibility:hidden; opacity:0; box-shadow:0 10px 30px rgba(0,0,0,.35); }- #tbar .tag { position:absolute; left:${TICKER.tagX}px; top:0; height:100%; width:${tagW}px; box-sizing:border-box; padding:0 ${TICKER.tagPad}px; background:${look.box.tagBg};- color:#fff; font-family:${look.font}, sans-serif; font-weight:800; font-size:${Math.round(look.size * TICKER.tagEm)}px; line-height:${Math.round(1.5 * look.size)}px; letter-spacing:.04em; white-space:nowrap; text-align:center; }- #tbar .card.tk { left:${tkLeft}px; width:${tkW}px; top:0; margin-top:0; height:100%; line-height:${Math.round(1.5 * look.size)}px; text-align:left; white-space:nowrap; max-height:none; overflow:hidden; }` : '';-- const doc = `<!doctype html>-<html lang="vi">-<head>-<meta charset="UTF-8" />-<meta name="viewport" content="width=${OUT.width}, height=${OUT.height}" />-<link rel="stylesheet" href="./lib/fonts/fonts.css" />-<script src="./lib/vendor/gsap.min.js"></script>-<style>- html, body { margin:0; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }- #root { position:relative; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }- .card { position:absolute; left:${x0}px; width:${w}px; top:${cy}px; transform-origin:50% 50%;- margin-top:-0.6em; text-align:center; line-height:1.18; visibility:hidden; opacity:0;- font-family:${look.font}, sans-serif; font-weight:${look.weight}; color:${look.color};- -webkit-text-stroke: ${stroke}px #000; paint-order: stroke fill;- text-shadow: ${shadow}; max-height:${yMax - cy}px; }- .card .w { display:inline-block; }- .card .ch { font-style:normal; }- .card .hi { color:${look.hi}; }${tickerCss}${quoteCss}${hookCss}${gfx ? gfx.css : ''}-</style>-</head>-<body>-<div id="root" data-composition-id="main" data-start="0" data-duration="${dur.toFixed(3)}" data-fps="${OUT.fps}" data-width="${OUT.width}" data-height="${OUT.height}">- ${gfx ? gfx.html : ''}- ${ticker ? tickerHtml : html}- ${quoteHtml}- ${hookHtml}-</div>-${gfx ? `<script src="./lib/runtime/scene.js"></script>-<script>- const tl = gsap.timeline({ paused: true });- tl.set({}, {}, ${dur.toFixed(3)});- ${timeline.join('\n ')}- const G = ${JSON.stringify(gfx.data)};- const S = ${JSON.stringify(gfx.steps || null)};- ${GFX_RUNTIME}- VideoScene.define({ duration: ${dur.toFixed(3)}, fps: ${OUT.fps}, width: ${OUT.width}, height: ${OUT.height},- render(t) { tl.seek(t, false); gfxRender(t, G); stepsRender(t, S); } });-</script>` : `<script>- const tl = gsap.timeline({ paused: true });- tl.set({}, {}, ${dur.toFixed(3)});- ${timeline.join('\n ')}- window.__timelines = window.__timelines || {};- window.__timelines.main = tl;-</script>`}-</body>-</html>-`;- fs.mkdirSync(sceneDir, { recursive: true });- fs.writeFileSync(path.join(sceneDir, 'index.html'), doc);- syncLib(sceneDir);- return { duration: dur, cards: cards.length, graphics: (edl.graphics || []).length, box: { x0, x1: x0 + w, cy, yMax }, quote: !!qs, hookText: !!hookHtml, ticker: !!ticker };-}--// Định dạng lớp chữ trong suốt (HyperFrames → ffmpeg chồng lên nền). LUMREELS_CAPTION_LAYER=png|webm|webm-fast|mov.-// Đo lớp chữ 32 s (967 khung) trên máy 20 luồng + RTX 3070 Ti, HF render / cỡ / ghép (overlay + NVENC):-// webm VP9 alpha 63,7 s / 0,9 MB / 5,7 s · webm --vp9-cpu-used 8 64,5 s (không nhanh hơn: chậm ở chụp khung, không ở VP9)-// mov ProRes 4444 55,7 s / 87 MB / 6,3 s · png (chuỗi PNG RGBA, không mã hoá video) 45,3 s / 33 MB / 5,9 s → mặc định png.-// Alpha: PNG không mất dữ liệu (VP9 alpha có mất), bản ghép png và webm giống nhau (SSIM 0,995, khác ở khung chữ đang mờ dần).-export const LAYERS = {- webm: { name: 'webm', file: 'captions.webm', hf: ['--format', 'webm'], input: ['-c:v', 'libvpx-vp9'] },- 'webm-fast': { name: 'webm-fast', file: 'captions.webm', hf: ['--format', 'webm', '--vp9-cpu-used', '8'], input: ['-c:v', 'libvpx-vp9'] },- png: { name: 'png', file: 'captions-png', hf: ['--format', 'png-sequence'], input: null },- mov: { name: 'mov', file: 'captions.mov', hf: ['--format', 'mov'], input: [] },-};-export const LAYER = LAYERS[String(process.env.LUMREELS_CAPTION_LAYER || '').trim().toLowerCase()] || LAYERS.png;--/** Tham số ffmpeg đọc lớp chữ (chuỗi PNG: mẫu tên file + số khung đầu). */-export function layerInput(layer, file) {- if (layer.input) return [...layer.input, '-i', file];- const files = fs.readdirSync(file).filter((f) => /\.png$/i.test(f)).sort();- const m = /^(.*?)(\d+)(\.png)$/i.exec(files[0] || '');- if (!m) throw new Error('lớp chữ PNG rỗng: ' + file);- return ['-framerate', String(OUT.fps), '-start_number', String(Number(m[2])), '-i', path.join(file, `${m[1]}%0${m[2].length}d${m[3]}`)];-}--/** Render lớp chữ trong suốt (định dạng LAYER: WebM VP9 alpha / chuỗi PNG / ProRes 4444). */-export async function renderCaptionLayer(sceneDir, outWebm, { log = console.log, onPct, format = LAYER.hf } = {}) {- let last = -1;- const r = await runHF(['render', sceneDir, '-o', outWebm, ...format, '-f', String(OUT.fps), '-q', 'looks', '--quiet'], {- onLine: (l) => {- const m = /^@hf-progress (.*)$/.exec(l);- if (m) { try { const p = JSON.parse(m[1]); onPct?.(p.pct); const b = Math.floor(p.pct / 20) * 20; if (b !== last) { last = b; log(`phụ đề HyperFrames ${p.pct}% ${p.code}`); } } catch { /* bỏ qua */ } }- },- });- if (r.code !== 0 || !fs.existsSync(outWebm)) throw new Error('HyperFrames render phụ đề lỗi: ' + r.out.trim().split(/\r?\n/).slice(-5).join(' | '));- return outWebm;-}+// Phụ đề bản chính: một cảnh HyperFrames nền trong suốt (chỉ có chữ), render ra WebM VP9 có alpha,+// rồi ffmpeg chồng lên video nền. Font tiếng Việt lấy từ engine/fonts (fonts.css của LumReels).+// Mốc chữ đổi từ giây nguồn sang giây bản ra theo keep[] của EDL — cùng luật chia thẻ với phụ đề nháp (lumedit.py).+// Có câu móc (edl.hook) thì bản ra = [móc] + keep: timelineOf(edl) dời mọi mốc; móc lặp lại (repeat) thì chữ của+// câu móc hiện 2 lần (đầu clip và chỗ cũ). Mọi kiểu hiện chữ là hàm của t − c.start (render(t) thuần, gsap seek).+import fs from 'node:fs';+import path from 'node:path';+import { syncLib, runHF } from '../engine/lib.mjs';+import { toOutputNearest, outputDuration, timelineOf, SAFE, OUT } from './edl.mjs';+import { graphicsScene, GFX_RUNTIME } from './graphics.mjs';++const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));++/** Chia chữ thành nhóm (cùng luật với caption_cards trong edit/py/lumedit.py). */+function groupWords(words, maxWords) {+ const groups = []; let cur = [];+ words.forEach((w, n) => {+ cur.push(w);+ const nx = words[n + 1];+ const ends = /[.?!,:;…]$/.test(w.w.trim());+ const gap = nx ? nx.start - w.end : 99;+ if (cur.length >= maxWords || ends || gap > 0.45 || !nx) { groups.push(cur); cur = []; }+ });+ return groups;+}++/** Cùng luật với caption_cards trong edit/py/lumedit.py. */+export function captionCards(edl) {+ const cap = edl.captions; const tl = timelineOf(edl); const H = edl.hook;+ // phụ đề chỉnh tay (giây bản ra, edit/manual.mjs): dùng nguyên dòng người dùng đặt, chỉ kiểm không đè nhau+ if (cap.lines) {+ const cards = cap.lines.map((l) => ({ start: l.start, end: l.end, words: l.words.map((w) => ({ w: w.w, i: -1, o: w.o, hl: w.hi })), wordOut: l.words.map((w) => Math.max(l.start, w.o)) }));+ const bad = cardOverlaps(cards);+ if (bad.length) throw new Error('phụ đề chỉnh tay chồng nhau: ' + bad.join('; '));+ return cards;+ }+ // mỗi chữ mang giây bản ra (o) của chính nó: chữ câu móc lặp lại có 2 chỗ trên bản ra+ const mk = (ws, map) => groupWords(ws, cap.maxWords).map((g) => ({ words: g.map((w) => ({ ...w, o: map(w.start) })), start: map(g[0].start), end: map(g[g.length - 1].end) }));+ const cards = mk(cap.words, (t) => toOutputNearest(tl, t)).sort((a, b) => a.start - b.start);+ if (!H) return finishCards(cards, tl);+ // có câu móc: thẻ của câu móc (0 … hookDur) và thẻ phần sau làm riêng, để thẻ móc không kéo dài qua chỗ nối+ const hd = H.end - H.start;+ const inH = H.repeat ? cap.words.filter((w) => (w.start + w.end) / 2 >= H.start && (w.start + w.end) / 2 <= H.end) : [];+ const head = H.repeat ? mk(inH, (t) => Math.min(hd, Math.max(0, t - H.start))) : cards.filter((c) => c.start < hd - 1e-6);+ const rest = cards.filter((c) => c.start >= hd - 1e-6);+ for (const c of head) c.end = Math.min(c.end, hd);+ const a = head.length ? finishCards(head, tl) : [];+ for (const c of a) c.end = Math.min(c.end, hd);+ return a.concat(rest.length ? finishCards(rest, tl) : []);+}++export const MIN_CARD = 0.25; // một nhóm chữ hiện ít nhất chừng này (nếu chưa tới nhóm sau)+export const MERGE_BELOW = 0.1; // nhóm bị ép ngắn hơn chừng này (chữ nói rất nhanh) thì gộp vào nhóm sau++/**+ * Luật thời gian của nhóm phụ đề (giống caption_cards trong lumedit.py):+ * nối khe < 0,4 s; kéo dài tối thiểu MIN_CARD; KHÔNG BAO GIỜ chồng lên nhóm sau (cắt end về start của nhóm sau);+ * nhóm còn < MERGE_BELOW thì gộp chữ vào nhóm sau. Lỗi cũ: kéo dài tối thiểu 0,25 s chạy SAU bước nối khe nên+ * "TRÀ" (0,22 s) đè lên "SỮA" — 2 nhóm cùng hiện ở cùng chỗ.+ */+export function finishCards(cards, keep) {+ for (let k = 0; k + 1 < cards.length; k++) {+ const gap = cards[k + 1].start - cards[k].end;+ if (gap >= 0 && gap < 0.4) cards[k].end = cards[k + 1].start;+ }+ for (const c of cards) c.end = Math.max(c.end, c.start + MIN_CARD);+ for (let k = 0; k + 1 < cards.length; k++) cards[k].end = Math.min(cards[k].end, cards[k + 1].start);+ const out = [];+ for (let k = 0; k < cards.length; k++) {+ const c = cards[k]; const nx = cards[k + 1];+ if (nx && c.end - c.start < MERGE_BELOW) { nx.words = c.words.concat(nx.words); nx.start = c.start; continue; }+ out.push(c);+ }+ for (const c of out) c.wordOut = c.words.map((w) => Math.max(c.start, w.o ?? toOutputNearest(keep, w.start)));+ const bad = cardOverlaps(out);+ if (bad.length) throw new Error('phụ đề chồng nhau: ' + bad.join('; '));+ return out;+}++/** Luật kiểm: không bao giờ 2 nhóm phụ đề hiện cùng lúc (mọi nhóm cùng 1 vị trí). Trả danh sách lỗi. */+export function cardOverlaps(cards) {+ const errs = [];+ for (let k = 0; k + 1 < cards.length; k++) {+ if (cards[k].end > cards[k + 1].start + 1e-6) errs.push(`"${cards[k].words.map((w) => w.w).join(' ')}" (${cards[k].start.toFixed(2)}–${cards[k].end.toFixed(2)} s) đè "${cards[k + 1].words.map((w) => w.w).join(' ')}" (từ ${cards[k + 1].start.toFixed(2)} s)`);+ if (cards[k].end <= cards[k].start) errs.push(`nhóm ${k} dài 0 s`);+ }+ return errs;+}++// Khoá: font, weight, size (px), upper, color, hi (chữ nhấn/karaoke), karaoke, cy (tâm dòng, phần khung),+// enter (fade | pop | pop-soft | slide-left | typewriter | ticker | slam | fade-slow),+// stroke (px viền, mặc định 10 chữ hoa / 8), shadow (CSS text-shadow), box (thanh tin), quote (trích dẫn).+// Chép từ khối "look" của edit-styles/<id>.md.+export const LOOKS = {+ 'sach-gon': { font: "'Be Vietnam Pro'", weight: 800, size: 76, upper: false, color: '#FFFFFF', hi: '#FCE802', karaoke: false, cy: 0.70, enter: 'fade' },+ 'thong-tin-do-hoa': { font: "'Be Vietnam Pro'", weight: 800, size: 68, upper: false, color: '#FFFFFF', hi: '#FCE802', karaoke: false, cy: 0.745, enter: 'pop-soft' },+ 'phu-de-nay-mau': { font: "'Anton'", weight: 400, size: 150, upper: true, color: '#FFFFFF', hi: '#FCE802', karaoke: true, cy: 0.58, enter: 'pop' },+ 'podcast-trich-doan': { font: "'Montserrat'", weight: 800, size: 96, upper: false, color: '#FFFFFF', hi: '#FF8A3D', karaoke: false, cy: 0.56, enter: 'fade' },+ 'ke-chuyen': { font: "'Nunito'", weight: 800, size: 80, upper: false, color: '#FFFFFF', hi: '#7CF0C8', karaoke: true, cy: 0.66, enter: 'pop-soft' },+ 'top-danh-sach': { font: "'Bungee'", weight: 400, size: 78, upper: true, color: '#FFFFFF', hi: '#FF2E93', karaoke: false, cy: 0.74, enter: 'slide-left' },+ 'review-san-pham': { font: "'Oswald'", weight: 700, size: 88, upper: true, color: '#FFFFFF', hi: '#A78BFA', karaoke: false, cy: 0.77, enter: 'pop-soft' },+ 'huong-dan-buoc': { font: "'Space Grotesk'", weight: 700, size: 70, upper: false, color: '#FFFFFF', hi: '#5EA2FF', karaoke: false, cy: 0.72, enter: 'typewriter' },+ 'ban-tin-nhanh': {+ font: "'Barlow Condensed'", weight: 700, size: 64, upper: true, color: '#FFFFFF', hi: '#00E5FF', karaoke: false, cy: 0.775, enter: 'ticker',+ box: { bg: '#0B1E3F', full: true, align: 'left', stroke: 0, tag: 'TIN NÓNG', tagBg: '#E8202A' },+ },+ 'quan-diem-gat': { font: "'Alfa Slab One'", weight: 400, size: 104, upper: true, color: '#FFFFFF', hi: '#FF1F1F', karaoke: true, cy: 0.50, enter: 'slam' },+ 'chot-don-livestream': { font: "'Baloo 2'", weight: 800, size: 96, upper: false, color: '#FFFFFF', hi: '#FFB020', karaoke: false, cy: 0.62, enter: 'pop' },+ 'vlog-nhe': { font: "'Patrick Hand'", weight: 400, size: 60, upper: false, color: '#FFFDF7', hi: '#F5C6A5', karaoke: false, cy: 0.77, enter: 'fade-slow', stroke: 3, shadow: '0 3px 10px rgba(0,0,0,.45)' },+ 'meo-15s': { font: "'Bangers'", weight: 400, size: 128, upper: true, color: '#FFFFFF', hi: '#00FF87', karaoke: false, cy: 0.64, enter: 'pop' },+ 'cau-noi-hay': {+ font: "'Lora'", weight: 600, size: 66, upper: false, color: '#F5F1E8', hi: '#D4AF37', karaoke: false, cy: 0.74, enter: 'fade-slow',+ quote: { font: "'Playfair Display'", weight: 700, italic: true, size: 88, cy: 0.48, color: '#F5F1E8', marks: '#D4AF37', dimTo: 0.35, blurPx: 8, dimIn: 0.8, wordStagger: 0.12 },+ },+};+export const lookOf = (captionStyle) => LOOKS[captionStyle] || LOOKS['sach-gon'];++// thanh tin (ticker): ô tag bên trái, chữ căn trái sau tag, cả thanh cao 1,5 em ở cy+const TICKER = { tagX: 60, tagPad: 22, tagEm: 0.62, gap: 24, right: Math.round(SAFE.x1 * OUT.width) };+const tickerTagW = (look) => Math.round([...look.box.tag].length * 0.56 * look.size * TICKER.tagEm + 2 * TICKER.tagPad);++/** Mép trên (px) của dòng phụ đề kiểu này — đồ hoạ đặt phía trên mép này. */+export function captionTop(captionStyle) {+ const look = lookOf(captionStyle);+ if (look.enter === 'ticker') return Math.round(look.cy * OUT.height - 0.75 * look.size) - 8;+ return Math.round(look.cy * OUT.height - 0.6 * look.size * 1.18) - 8;+}++/** Cỡ chữ cho khối chữ tự xuống dòng: thu nhỏ tới khi ước số dòng ≤ maxLines (ước theo bề rộng trung bình 1 ký tự). */+export function fitBlock(text, widthPx, max, { maxLines = 4, em = 0.5, min = 40 } = {}) {+ const n = [...text].length;+ let size = max;+ while (size > min && Math.ceil((n * em * size * 1.1) / widthPx) > maxLines) size -= 2;+ return size;+}++/** Chữ móc: "*3 GIÂY* LÀ XONG" → [{t, hi}] (chữ trong *…* là chữ nhấn). */+export function hookTextParts(text) {+ const parts = []; const re = /\*([^*]+)\*|([^*]+)/g; let m;+ while ((m = re.exec(String(text)))) { if (m[1]) parts.push({ t: m[1], hi: true }); else if (m[2]) parts.push({ t: m[2], hi: false }); }+ return parts;+}++/** Khoảng câu trích dẫn trên bản ra: {q0, q1, end, words:[{w, i, o}]} hoặc null. */+export function quoteSpan(edl, dur) {+ const q = edl.quote; if (!q) return null;+ const look = lookOf(edl.captions.style).quote || LOOKS['cau-noi-hay'].quote;+ const tl = timelineOf(edl);+ const q0 = toOutputNearest(tl, q.start); const q1 = toOutputNearest(tl, q.end);+ const hold = q1 >= dur - 2.0; // câu chốt ở cuối: giữ tối tới hết clip+ const end = hold ? dur : Math.min(dur, q1 + 0.8);+ let last = -Infinity;+ const words = edl.captions.words.filter((w) => (w.start + w.end) / 2 >= q.start - 1e-6 && (w.start + w.end) / 2 <= q.end + 1e-6).map((w) => {+ const o = Math.max(q0, toOutputNearest(tl, w.start), last + look.wordStagger); last = o;+ return { w: w.w, i: w.i, o };+ });+ return { q0, q1, end, hold, words };+}++/**+ * Ghi cảnh vào sceneDir. Trả {duration, cards, graphics, box}.+ * opts.captions=false: chỉ lớp đồ hoạ (bản nháp: phụ đề đã vẽ PIL trong nền). opts.accent: màu nhấn của đồ hoạ.+ * opts.style: thẻ kiểu (chữ móc hook.text, thanh bước graphics.stepTracker).+ */+export function writeCaptionScene(edl, sceneDir, { captions = true, accent, style = null } = {}) {+ const look = lookOf(edl.captions.style);+ const tlk = timelineOf(edl);+ const dur = Math.max(1 / OUT.fps, Math.round(outputDuration(tlk) * OUT.fps) / OUT.fps);+ let cards = captions && edl.captions.words.length ? captionCards(edl) : [];+ const gfx = (edl.graphics || []).length ? graphicsScene(edl, { accent: accent || look.hi, stepTracker: !!style?.graphics?.stepTracker, dur }) : null;+ const hiSet = new Set(edl.captions.hiOff ? [] : edl.captions.highlights);+ // chữ nhấn: dòng chỉnh tay mang cờ hl riêng; tắt chữ nhấn (hiOff) thì không chữ nào nhấn+ const hi = { has: (i, wd) => !edl.captions.hiOff && (wd?.hl ?? hiSet.has(i)) };+ const x0 = Math.round(SAFE.x0 * OUT.width); const w = Math.round((SAFE.x1 - SAFE.x0) * OUT.width);+ const cy = Math.round(look.cy * OUT.height); const yMax = Math.round(SAFE.y1 * OUT.height);++ // câu trích dẫn: phụ đề thường tắt trong lúc đó+ const qs = captions ? quoteSpan(edl, dur) : null;+ if (qs) {+ cards = cards.filter((c) => !(c.start >= qs.q0 - 1e-3 && c.start < qs.end));+ for (const c of cards) if (c.start < qs.q0 && c.end > qs.q0) c.end = qs.q0;+ }+ const ticker = look.enter === 'ticker' && look.box;+ const tagW = ticker ? tickerTagW(look) : 0;+ const tkLeft = TICKER.tagX + tagW + TICKER.gap; const tkW = TICKER.right - tkLeft;+ const stroke = look.box ? (look.box.stroke ?? 0) : (look.stroke ?? (look.upper ? 10 : 8));+ const shadow = look.shadow || (ticker ? 'none' : '0 6px 18px rgba(0,0,0,.55)');++ const cardHtml = cards.map((c, ci) => {+ // dấu , . ; : cuối chữ không hiện trên phụ đề (giữ ? ! …)+ const text = c.words.map((wd) => { const t = wd.w.replace(/[,.;:]+$/u, '') || wd.w; return look.upper ? t.toUpperCase() : t; });+ let size;+ if (ticker) {+ // thanh tin: 1 dòng, thu cỡ theo bề ngang còn lại sau ô tag (Barlow Condensed ~0,46 em mỗi ký tự hoa)+ const n = text.join(' ').length;+ size = Math.max(34, Math.min(look.size, Math.floor(tkW / (n * 0.46 + 0.4))));+ } else {+ // thẻ 1 chữ dài thì thu nhỏ để vừa vùng an toàn (Anton ~0,48 em mỗi ký tự hoa)+ const longest = Math.max(...text.map((t) => t.length));+ size = c.words.length === 1 ? Math.min(look.size, Math.floor(w / (longest * 0.5 + 0.5))) : look.size;+ }+ const inner = (t) => (look.enter === 'typewriter' ? [...t].map((ch) => `<i class="ch">${esc(ch)}</i>`).join('') : esc(t));+ const spans = c.words.map((wd, k) => `<span class="w${hi.has(wd.i, wd) ? ' hi' : ''}" id="c${ci}w${k}">${inner(text[k])}</span>`).join(' ');+ return `<div class="card${ticker ? ' tk' : ''}" id="c${ci}" style="font-size:${size}px">${spans}</div>`;+ });+ const html = cardHtml.join('\n ');++ // thanh tin: mỗi câu (chuỗi thẻ liền nhau tới dấu kết câu / khoảng lặng > 0,5 s) là 1 lượt thanh trượt vào+ const runs = [];+ if (ticker) {+ cards.forEach((c, ci) => {+ const prev = cards[ci - 1];+ const brk = !prev || /[.?!…]$/.test(prev.words[prev.words.length - 1].w.trim()) || c.start - prev.end > 0.5;+ if (brk) runs.push({ first: ci, start: c.start, end: c.end }); else runs[runs.length - 1].end = c.end;+ });+ }+ const firstOfRun = new Set(runs.map((r) => r.first));++ const timeline = cards.map((c, ci) => {+ const t0 = c.start.toFixed(3);+ const lines = [`tl.set('#c${ci}', {autoAlpha: 1}, ${t0});`];+ switch (look.enter) {+ case 'pop': lines.push(`tl.fromTo('#c${ci}', {scale: 0.55}, {scale: 1, duration: 0.18, ease: 'back.out(3)'}, ${t0});`); break;+ case 'pop-soft': lines.push(`tl.fromTo('#c${ci}', {scale: 0.86, opacity: 0}, {scale: 1, opacity: 1, duration: 0.14, ease: 'back.out(2.2)'}, ${t0});`); break;+ case 'slide-left': lines.push(`tl.fromTo('#c${ci}', {x: 80, opacity: 0}, {x: 0, opacity: 1, duration: 0.16, ease: 'power3.out'}, ${t0});`); break;+ case 'slam': {+ lines.push(`tl.fromTo('#c${ci}', {scale: 1.6, opacity: 0.4}, {scale: 1, opacity: 1, duration: 0.12, ease: 'power4.in'}, ${t0});`);+ [6, -6, 6, 0].forEach((x, k) => lines.push(`tl.to('#c${ci}', {x: ${x}, duration: 0.025, ease: 'none'}, ${(c.start + 0.12 + k * 0.025).toFixed(3)});`));+ break;+ }+ case 'fade-slow': {+ lines.push(`tl.fromTo('#c${ci}', {opacity: 0}, {opacity: 1, duration: 0.3, ease: 'power1.out'}, ${t0});`);+ const nx = cards[ci + 1];+ if ((!nx || nx.start - c.end >= 0.3) && c.end - c.start > 0.55) lines.push(`tl.to('#c${ci}', {opacity: 0, duration: 0.25, ease: 'power1.in'}, ${(c.end - 0.25).toFixed(3)});`);+ break;+ }+ case 'typewriter': {+ // ký tự k hiện ở c.start + k × min(0,035, (end − start) × 0,6 / số ký tự)+ const n = c.words.reduce((s, wd) => s + [...(wd.w.replace(/[,.;:]+$/u, '') || wd.w)].length, 0);+ const stepS = Math.min(0.035, ((c.end - c.start) * 0.6) / Math.max(1, n));+ lines.push(`tl.set('#c${ci} .ch', {opacity: 0}, ${t0});`);+ lines.push(`gsap.utils.toArray('#c${ci} .ch').forEach(function (el, k) { tl.set(el, {opacity: 1}, ${t0} + k * ${stepS.toFixed(4)}); });`);+ break;+ }+ case 'ticker': {+ if (!firstOfRun.has(ci)) lines.push(`tl.fromTo('#c${ci}', {opacity: 0}, {opacity: 1, duration: 0.08, ease: 'none'}, ${t0});`);+ break;+ }+ default: lines.push(`tl.fromTo('#c${ci}', {y: 18, opacity: 0}, {y: 0, opacity: 1, duration: 0.12, ease: 'power2.out'}, ${t0});`);+ }+ if (look.karaoke && c.words.length > 1) {+ c.words.forEach((wd, k) => {+ const a = c.wordOut[k]; const b = k + 1 < c.words.length ? c.wordOut[k + 1] : c.end;+ lines.push(`tl.set('#c${ci}w${k}', {color: '${look.hi}'}, ${a.toFixed(3)}); tl.set('#c${ci}w${k}', {color: '${hi.has(wd.i, wd) ? look.hi : look.color}'}, ${b.toFixed(3)});`);+ });+ }+ lines.push(`tl.set('#c${ci}', {autoAlpha: 0}, ${c.end.toFixed(3)});`);+ return lines.join(' ');+ });+ runs.forEach((r, k) => {+ timeline.push(`tl.set('#tbar', {autoAlpha: 1}, ${r.start.toFixed(3)}); tl.fromTo('#tbar', {x: -${OUT.width}}, {x: 0, duration: 0.2, ease: 'power3.out'}, ${r.start.toFixed(3)});`);+ const nx = runs[k + 1];+ if (!nx || nx.start > r.end + 0.02) timeline.push(`tl.set('#tbar', {autoAlpha: 0}, ${r.end.toFixed(3)});`);+ });++ // câu trích dẫn to giữa khung+ let quoteHtml = ''; let quoteCss = '';+ if (qs && qs.words.length) {+ const q = look.quote || LOOKS['cau-noi-hay'].quote;+ const text = qs.words.map((x) => x.w).join(' ');+ const qsize = fitBlock(`“${text}”`, w, q.size, { maxLines: 4, em: 0.5, min: 44 });+ quoteHtml = `<div id="quote" style="font-size:${qsize}px"><span class="qm" id="qmo">“</span>${qs.words.map((x, k) => `<span class="qw${hi.has(x.i) ? ' hi' : ''}" id="qw${k}">${esc(x.w)}</span>`).join(' ')}<span class="qm" id="qmc">”</span></div>`;+ quoteCss = `+ #quote { position:absolute; left:${x0}px; width:${w}px; top:${Math.round(q.cy * OUT.height)}px; transform:translateY(-50%); text-align:center; line-height:1.25;+ font-family:${q.font}, serif; font-weight:${q.weight}; font-style:${q.italic ? 'italic' : 'normal'}; color:${q.color};+ text-shadow:0 4px 24px rgba(0,0,0,.6); visibility:hidden; opacity:0; }+ #quote .qw { display:inline-block; opacity:0; }+ #quote .qw.hi { color:${q.marks}; }+ #quote .qm { color:${q.marks}; font-size:1.3em; line-height:0; opacity:0; padding:0 .06em; }`;+ timeline.push(`tl.set('#quote', {autoAlpha: 1}, ${qs.q0.toFixed(3)}); tl.to('#qmo', {opacity: 1, duration: 0.3}, ${qs.q0.toFixed(3)});`);+ qs.words.forEach((x, k) => timeline.push(`tl.fromTo('#qw${k}', {opacity: 0, y: 14}, {opacity: 1, y: 0, duration: 0.2, ease: 'power2.out'}, ${x.o.toFixed(3)});`));+ const lastO = qs.words[qs.words.length - 1].o;+ timeline.push(`tl.to('#qmc', {opacity: 1, duration: 0.3}, ${(lastO + 0.15).toFixed(3)});`);+ if (!qs.hold) timeline.push(`tl.to('#quote', {opacity: 0, duration: 0.3}, ${Math.max(lastO + 0.4, qs.end - 0.3).toFixed(3)}); tl.set('#quote', {autoAlpha: 0}, ${qs.end.toFixed(3)});`);+ }++ // chữ móc to 0 → until (kiểu meo-15s)+ let hookHtml = ''; let hookCss = '';+ if (captions && edl.hookText) {+ const ht = { font: "'Bangers'", size: 150, cy: 0.22, color: '#FFFFFF', hi: look.hi, ...(style?.hook?.text || {}) };+ const parts = hookTextParts(edl.hookText.text.toUpperCase());+ const plain = parts.map((p) => p.t).join('');+ const hsize = fitBlock(plain, w, ht.size, { maxLines: 2, em: 0.46, min: 70 });+ hookHtml = `<div id="hooktext" style="font-size:${hsize}px">${parts.map((p) => `<span${p.hi ? ' class="hi"' : ''}>${esc(p.t)}</span>`).join('')}</div>`;+ hookCss = `+ #hooktext { position:absolute; left:${x0}px; width:${w}px; top:${Math.round(ht.cy * OUT.height)}px; margin-top:-0.55em; text-align:center; line-height:1.05;+ font-family:${ht.font}, sans-serif; color:${ht.color}; -webkit-text-stroke:12px #000; paint-order:stroke fill;+ text-shadow:0 8px 24px rgba(0,0,0,.55); transform-origin:50% 50%; visibility:hidden; opacity:0; }+ #hooktext .hi { color:${ht.hi}; }`;+ const until = Math.min(edl.hookText.until, dur);+ timeline.push(`tl.set('#hooktext', {autoAlpha: 1}, 0); tl.fromTo('#hooktext', {scale: 0.4, rotation: -4}, {scale: 1, rotation: -2, duration: 0.3, ease: 'back.out(2.6)'}, 0); tl.to('#hooktext', {opacity: 0, scale: 1.08, duration: 0.18}, ${Math.max(0.35, until - 0.18).toFixed(3)}); tl.set('#hooktext', {autoAlpha: 0}, ${until.toFixed(3)});`);+ }++ const tickerHtml = ticker ? `<div id="tbar"><div class="tag">${esc(look.box.tag)}</div>\n ${html}\n </div>` : '';+ const tickerCss = ticker ? `+ #tbar { position:absolute; left:0; width:${OUT.width}px; top:${cy}px; height:${Math.round(1.5 * look.size)}px; margin-top:-${Math.round(0.75 * look.size)}px;+ background:${look.box.bg}; visibility:hidden; opacity:0; box-shadow:0 10px 30px rgba(0,0,0,.35); }+ #tbar .tag { position:absolute; left:${TICKER.tagX}px; top:0; height:100%; width:${tagW}px; box-sizing:border-box; padding:0 ${TICKER.tagPad}px; background:${look.box.tagBg};+ color:#fff; font-family:${look.font}, sans-serif; font-weight:800; font-size:${Math.round(look.size * TICKER.tagEm)}px; line-height:${Math.round(1.5 * look.size)}px; letter-spacing:.04em; white-space:nowrap; text-align:center; }+ #tbar .card.tk { left:${tkLeft}px; width:${tkW}px; top:0; margin-top:0; height:100%; line-height:${Math.round(1.5 * look.size)}px; text-align:left; white-space:nowrap; max-height:none; overflow:hidden; }` : '';++ const doc = `<!doctype html>+<html lang="vi">+<head>+<meta charset="UTF-8" />+<meta name="viewport" content="width=${OUT.width}, height=${OUT.height}" />+<link rel="stylesheet" href="./lib/fonts/fonts.css" />+<script src="./lib/vendor/gsap.min.js"></script>+<style>+ html, body { margin:0; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }+ #root { position:relative; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }+ .card { position:absolute; left:${x0}px; width:${w}px; top:${cy}px; transform-origin:50% 50%;+ margin-top:-0.6em; text-align:center; line-height:1.18; visibility:hidden; opacity:0;+ font-family:${look.font}, sans-serif; font-weight:${look.weight}; color:${look.color};+ -webkit-text-stroke: ${stroke}px #000; paint-order: stroke fill;+ text-shadow: ${shadow}; max-height:${yMax - cy}px; }+ .card .w { display:inline-block; }+ .card .ch { font-style:normal; }+ .card .hi { color:${look.hi}; }${tickerCss}${quoteCss}${hookCss}${gfx ? gfx.css : ''}+</style>+</head>+<body>+<div id="root" data-composition-id="main" data-start="0" data-duration="${dur.toFixed(3)}" data-fps="${OUT.fps}" data-width="${OUT.width}" data-height="${OUT.height}">+ ${gfx ? gfx.html : ''}+ ${ticker ? tickerHtml : html}+ ${quoteHtml}+ ${hookHtml}+</div>+${gfx ? `<script src="./lib/runtime/scene.js"></script>+<script>+ const tl = gsap.timeline({ paused: true });+ tl.set({}, {}, ${dur.toFixed(3)});+ ${timeline.join('\n ')}+ const G = ${JSON.stringify(gfx.data)};+ const S = ${JSON.stringify(gfx.steps || null)};+ ${GFX_RUNTIME}+ VideoScene.define({ duration: ${dur.toFixed(3)}, fps: ${OUT.fps}, width: ${OUT.width}, height: ${OUT.height},+ render(t) { tl.seek(t, false); gfxRender(t, G); stepsRender(t, S); } });+</script>` : `<script>+ const tl = gsap.timeline({ paused: true });+ tl.set({}, {}, ${dur.toFixed(3)});+ ${timeline.join('\n ')}+ window.__timelines = window.__timelines || {};+ window.__timelines.main = tl;+</script>`}+</body>+</html>+`;+ fs.mkdirSync(sceneDir, { recursive: true });+ fs.writeFileSync(path.join(sceneDir, 'index.html'), doc);+ syncLib(sceneDir);+ // để render lại từng đoạn (chỉ thẻ đổi): khoá mỗi thẻ = HTML + lệnh timeline của nó (bỏ id theo số thứ tự)+ const noId = (x) => x.replace(/ id="c\d+(w\d+)?"/g, '').replace(/#c\d+(w\d+)?/g, '#c');+ const cardsMeta = cards.map((c, ci) => ({ s: +c.start.toFixed(3), e: +c.end.toFixed(3), k: noId(cardHtml[ci]) + '|' + noId(timeline[ci] || '') }));+ const global = JSON.stringify([edl.captions.style, look, quoteHtml, hookHtml, gfx ? gfx.html : null, gfx ? gfx.data : null, !!ticker, dur]);+ return { duration: dur, cards: cards.length, graphics: (edl.graphics || []).length, box: { x0, x1: x0 + w, cy, yMax }, quote: !!qs, hookText: !!hookHtml, ticker: !!ticker, cardsMeta, global };+}++/**+ * Cảnh HyperFrames của RIÊNG 1 đồ hoạ, chỉ dài đúng khoảng nó hiện [from, from + dur) giây bản ra (lớp đồ hoạ tách khỏi+ * lớp phụ đề: sửa chữ/số/giờ 1 đồ hoạ chỉ render lại vài giây của nó). render(t) = gfxRender(from + t) — cùng HTML/CSS/+ * runtime với cảnh gộp, nên hình giống hệt. Có gsap để scene.js đăng ký window.__timelines.main (thiếu thì HyperFrames chờ+ * 45 s mới chụp).+ */+export function writeGraphicScene(edl, g, sceneDir, { accent, from, dur }) {+ const look = lookOf(edl.captions.style);+ const total = outputDuration(timelineOf(edl));+ const gfx = graphicsScene({ ...edl, graphics: [JSON.parse(JSON.stringify(g))] }, { accent: accent || look.hi, stepTracker: false, dur: total });+ const d = Math.max(1 / OUT.fps, Math.round(dur * OUT.fps) / OUT.fps);+ const doc = `<!doctype html>+<html lang="vi">+<head>+<meta charset="UTF-8" />+<meta name="viewport" content="width=${OUT.width}, height=${OUT.height}" />+<link rel="stylesheet" href="./lib/fonts/fonts.css" />+<script src="./lib/vendor/gsap.min.js"></script>+<style>+ html, body { margin:0; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }+ #root { position:relative; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }${gfx.css}+</style>+</head>+<body>+<div id="root" data-composition-id="main" data-start="0" data-duration="${d.toFixed(3)}" data-fps="${OUT.fps}" data-width="${OUT.width}" data-height="${OUT.height}">+ ${gfx.html}+</div>+<script src="./lib/runtime/scene.js"></script>+<script>+ const G = ${JSON.stringify(gfx.data)};+ const S = null;+ ${GFX_RUNTIME}+ VideoScene.define({ duration: ${d.toFixed(3)}, fps: ${OUT.fps}, width: ${OUT.width}, height: ${OUT.height},+ render(t) { gfxRender(${from.toFixed(3)} + t, G); } });+</script>+</body>+</html>+`;+ fs.mkdirSync(sceneDir, { recursive: true });+ fs.writeFileSync(path.join(sceneDir, 'index.html'), doc);+ syncLib(sceneDir);+ return { duration: d };+}++// Định dạng lớp chữ trong suốt (HyperFrames → ffmpeg chồng lên nền). LUMREELS_CAPTION_LAYER=png|webm|webm-fast|mov.+// Đo lớp chữ 32 s (967 khung) trên máy 20 luồng + RTX 3070 Ti, HF render / cỡ / ghép (overlay + NVENC):+// webm VP9 alpha 63,7 s / 0,9 MB / 5,7 s · webm --vp9-cpu-used 8 64,5 s (không nhanh hơn: chậm ở chụp khung, không ở VP9)+// mov ProRes 4444 55,7 s / 87 MB / 6,3 s · png (chuỗi PNG RGBA, không mã hoá video) 45,3 s / 33 MB / 5,9 s → mặc định png.+// Alpha: PNG không mất dữ liệu (VP9 alpha có mất), bản ghép png và webm giống nhau (SSIM 0,995, khác ở khung chữ đang mờ dần).+export const LAYERS = {+ webm: { name: 'webm', file: 'captions.webm', hf: ['--format', 'webm'], input: ['-c:v', 'libvpx-vp9'] },+ 'webm-fast': { name: 'webm-fast', file: 'captions.webm', hf: ['--format', 'webm', '--vp9-cpu-used', '8'], input: ['-c:v', 'libvpx-vp9'] },+ png: { name: 'png', file: 'captions-png', hf: ['--format', 'png-sequence'], input: null },+ mov: { name: 'mov', file: 'captions.mov', hf: ['--format', 'mov'], input: [] },+};+export const LAYER = LAYERS[String(process.env.LUMREELS_CAPTION_LAYER || '').trim().toLowerCase()] || LAYERS.png;++/** Tham số ffmpeg đọc lớp chữ (chuỗi PNG: mẫu tên file + số khung đầu). */+export function layerInput(layer, file) {+ if (layer.input) return [...layer.input, '-i', file];+ const files = fs.readdirSync(file).filter((f) => /\.png$/i.test(f)).sort();+ const m = /^(.*?)(\d+)(\.png)$/i.exec(files[0] || '');+ if (!m) throw new Error('lớp chữ PNG rỗng: ' + file);+ return ['-framerate', String(OUT.fps), '-start_number', String(Number(m[2])), '-i', path.join(file, `${m[1]}%0${m[2].length}d${m[3]}`)];+}++/** Render lớp chữ trong suốt (định dạng LAYER: WebM VP9 alpha / chuỗi PNG / ProRes 4444). */+export async function renderCaptionLayer(sceneDir, outWebm, { log = console.log, onPct, format = LAYER.hf } = {}) {+ let last = -1;+ const r = await runHF(['render', sceneDir, '-o', outWebm, ...format, '-f', String(OUT.fps), '-q', 'looks', '--quiet'], {+ onLine: (l) => {+ const m = /^@hf-progress (.*)$/.exec(l);+ if (m) { try { const p = JSON.parse(m[1]); onPct?.(p.pct); const b = Math.floor(p.pct / 20) * 20; if (b !== last) { last = b; log(`phụ đề HyperFrames ${p.pct}% ${p.code}`); } } catch { /* bỏ qua */ } }+ },+ });+ if (r.code !== 0 || !fs.existsSync(outWebm)) throw new Error('HyperFrames render phụ đề lỗi: ' + r.out.trim().split(/\r?\n/).slice(-5).join(' | '));+ return outWebm;+}diff --git a/edit/http.mjs b/edit/http.mjsindex 1dcc4c5..3be897c 100644--- a/edit/http.mjs+++ b/edit/http.mjs@@ -26,6 +26,10 @@ import {} from './jobs.mjs';import { installStatus, startInstall } from './setup-run.mjs';import { stripOf, waveOf, musicFileFor, isMusicName } from './studio-media.mjs';+import { previewGraphics } from './manual.mjs';+import { graphicsScene, GFX_RUNTIME } from './graphics.mjs';+import { loadStyle } from './planner.mjs';+import { lookOf } from './captions-hf.mjs';export const MAX_UPLOAD = 2 * 1024 ** 3; // 2 GBconst MAX_BODY = MAX_UPLOAD + 200 * 1024 ** 2; // + nhạc + trường chữ@@ -153,6 +157,14 @@ const musicUploading = new Set(); // id đang nhận nhạc cho chỉnh tay/** Trả true nếu đã xử lý route. */export async function handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts }) {// ảnh minh hoạ của thẻ kiểu edit (lưới chọn kiểu)+ // hàm vẽ đồ hoạ (GFX_RUNTIME) cho khung xem trước của Studio: file JS tĩnh (CSP script-src 'self', không eval)+ if (p === '/edit-runtime/gfx.js' && (req.method === 'GET' || req.method === 'HEAD')) {+ res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' });+ res.end(req.method === 'HEAD' ? undefined : `${GFX_RUNTIME}+window.gfxRender = gfxRender;+`);+ return true;+ }const th = /^\/edit-styles\/thumbs\/([a-z0-9-]{1,40}\.webp)$/.exec(p);if (th && (req.method === 'GET' || req.method === 'HEAD')) { serveFile(req, res, STYLE_THUMBS, th[1]); return true; }if (!p.startsWith('/api/edit') && !p.startsWith('/edits/')) return false;@@ -322,6 +334,19 @@ export async function handleEditRoute(req, res, p, { send, readBody, serveFile,} finally { musicUploading.delete(id); }return true;}+ // ---- Studio: cảnh xem trước đồ hoạ (cùng HTML/CSS với lớp HyperFrames) ----+ m = /^\/api\/edits\/([\w-]+)\/gfx-preview$/.exec(p);+ if (m && req.method === 'POST') {+ let body;+ try { body = await readBody(req, 128 * 1024); } catch { sendAndClose(res, req, send, 400, { error: 'JSON không hợp lệ' }); return true; }+ try {+ if (!ID_RE.test(m[1]) || !readEditJob(m[1])) throw httpErr(404, 'không thấy edit');+ const edl = JSON.parse(fs.readFileSync(path.join(editDir(m[1]), 'edl.json'), 'utf8'));+ let accent; try { accent = loadStyle(edl.style).graphics?.accent; } catch { /* kiểu đã xoá */ }+ send(res, 200, previewGraphics(edl, body, { accent: accent || lookOf(edl.captions.style).hi, graphicsScene }));+ } catch (e) { send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message }); }+ return true;+ }// ---- Studio: dải ảnh khung + đỉnh sóng nhạc ----m = /^\/api\/edits\/([\w-]+)\/(strip|wave)$/.exec(p);if (m && req.method === 'GET') {@@ -343,7 +368,7 @@ export async function handleEditRoute(req, res, p, { send, readBody, serveFile,if (p.startsWith('/api/')) return false;// ---- file ----m = /^\/edits\/([\w-]+)\/(out(?:-r\d{1,4})?\.mp4|preview\.jpg|preview-final\.jpg|edl\.json|base\.mp4|strip-out(?:-r\d{1,4})?\.jpg|[\w.-]{1,60})$/.exec(p);- const fileOk = (f) => /^(out(-r\d{1,4})?\.mp4|preview\.jpg|preview-final\.jpg|edl\.json|base\.mp4|strip-out(-r\d{1,4})?\.jpg)$/.test(f) || isMusicName(f);+ const fileOk = (f) => /^(out(-r\d{1,4})?\.mp4|preview\.jpg|preview-final\.jpg|edl\.json|base\.mp4|preview-clean\.mp4|strip-out(-r\d{1,4})?\.jpg)$/.test(f) || isMusicName(f);if (m && (req.method === 'GET' || req.method === 'HEAD') && ID_RE.test(m[1]) && fileOk(m[2])) { serveFile(req, res, editDir(m[1]), m[2]); return true; }send(res, 404, { error: 'không thấy file' });return true;diff --git a/edit/jobs.mjs b/edit/jobs.mjsindex 6db8489..9a27b0b 100644--- a/edit/jobs.mjs+++ b/edit/jobs.mjs@@ -3,7 +3,7 @@// đã chết được gỡ dưới một khoá phụ cũng "wx" nên hai tiến trình không thể cùng gỡ/cùng giữ).import fs from 'node:fs';import path from 'node:path';-import { EDITS, editDir, newEditId, editVideo, reviseEdit, manualEdit, STEPS, baseSig } from './pipeline.mjs';+import { EDITS, editDir, newEditId, editVideo, reviseEdit, manualEdit, STEPS, baseSig, cleanSig, CLEAN, manualStartStep } from './pipeline.mjs';import { parseManual, manualView, applyPatch } from './manual.mjs';import { isMusicName } from './studio-media.mjs';import { LAYER } from './captions-hf.mjs';@@ -186,7 +186,7 @@ export function cleanupEdit(id) {fs.rmSync(f, { recursive: true, force: true });} catch { /* không có */ }};- for (const f of ['proxy.mov', 'base.words.json', 'base.face.json', path.join('captions', 'lib'), 'qc.jpg', 'proxy.mov.part']) rm(f);+ for (const f of ['proxy.mov', 'base.words.json', 'base.face.json', path.join('captions', 'lib'), 'gfx-scene', 'qc.jpg', 'proxy.mov.part', 'preview-clean.v.mp4', 'preview-clean.part.mp4']) rm(f);for (const f of ['captions.webm', 'captions.mov', 'captions-png']) if (f !== LAYER.file) rm(f); // lớp chữ định dạng kháctry { for (const f of fs.readdirSync(path.join(dir, 'audio'))) if (f !== 'mix.wav') rm(path.join('audio', f)); } catch { /* chưa có */ }try { for (const f of fs.readdirSync(dir)) if (/\.part\.mp4$|\.tmp$/.test(f)) rm(f); } catch { /* bỏ qua */ }@@ -296,12 +296,16 @@ export function manualState(id, rev = null) {const outOf = (k) => (k === 0 ? 'out.mp4' : revs[k - 1]?.out);const sig = readJson(path.join(dir, 'render.sig.json'), {});const baseOk = n === latest && has('base.mp4') && sig.base === baseSig(edl, state.draft);+ const cleanOk = n === latest && has(CLEAN) && sig.clean === cleanSig(edl);const mf = edl.music?.file && path.dirname(path.resolve(edl.music.file)) === path.resolve(dir) && isMusicName(path.basename(edl.music.file)) ? path.basename(edl.music.file) : null;v.rev = n; v.latest = latest; v.readOnly = n !== latest;v.media = {out: outOf(n) && has(outOf(n)) ? url(outOf(n)) : null, outName: outOf(n) || null,- base: baseOk ? url('base.mp4') : null, music: mf && has(mf) ? url(mf) : null, musicFile: mf && has(mf) ? mf : null,+ base: baseOk ? url('base.mp4') : null, clean: cleanOk ? url(CLEAN) : null, music: mf && has(mf) ? url(mf) : null, musicFile: mf && has(mf) ? mf : null,};+ // khung mặt bản ra (lumedit faces, mỗi 0,25 s): tâm zoom xem trước bằng CSS (như lumedit Zooms: tâm đầu lúc zoom bắt đầu)+ const fo = readJson(path.join(dir, 'faces-out.json'));+ v.faces = fo && Array.isArray(fo.boxes) ? { step: fo.step || 0.25, boxes: fo.boxes.map(([tt, b]) => [+Number(tt).toFixed(2), Array.isArray(b) ? b.map((x) => Math.round(x)) : null]) } : null;v.versions = [{ n: 0, out: has('out.mp4') ? 'out.mp4' : null }, ...revs.map((r) => ({ n: r.n, out: r.out && has(r.out) ? r.out : null, manual: !!r.manual, instruction: r.instruction || '', at: r.at || null }))];return v;}@@ -320,10 +324,11 @@ export function manualEditJob(id, body, { log = () => {} } = {}) {const dir = editDir(id);const st = readJson(path.join(dir, 'state.json'), {});let style = null; try { style = loadStyle(st.style); } catch { /* kiểu đã xoá */ }- applyPatch(readJson(path.join(dir, 'edl.json')), st, patch, { dir, style, uploads: musicUploads(id) });- writeJob(id, { status: 'queued', action: 'manual', instruction: null, reviseError: null, pid: process.pid, stepFrom: patch.zooms || patch.graphics ? 4 : 5 });+ const ap = applyPatch(readJson(path.join(dir, 'edl.json')), st, patch, { dir, style, uploads: musicUploads(id) });+ const from = manualStartStep(dir, ap.edl, st.draft);+ writeJob(id, { status: 'queued', action: 'manual', instruction: null, reviseError: null, pid: process.pid, stepFrom: from, stepIndex: from, step: STEPS[from], pct: 0 });return withLock(id, async () => {- writeJob(id, { status: 'running', startedAt: new Date().toISOString(), stepIndex: 4, pct: 0, pid: process.pid });+ writeJob(id, { status: 'running', startedAt: new Date().toISOString(), stepIndex: from, step: STEPS[from], pct: 0, pid: process.pid });let r;try { r = await manualEdit(id, patch, { log, progress: onProgress(id), uploads: musicUploads(id) }); } catch (e) { r = { ok: false, id, error: e.message }; }const freed = cleanupEdit(id);diff --git a/edit/manual.mjs b/edit/manual.mjsindex ac77971..dcd35ea 100644--- a/edit/manual.mjs+++ b/edit/manual.mjs@@ -148,6 +148,19 @@ export function buildLines(input, prevLines, dur) {return out;}+/**+ * Khoá so dòng: giờ + chữ đã chuẩn hoá qua lineTokens. Chữ AI sửa thành 2 từ ("RTX 5060" là 1 chữ trong EDL, nhấn) in ra+ * "*RTX 5060*" nhưng tách lại thành "*RTX* *5060*" — không chuẩn hoá thì dòng không sửa cũng bị đếm là "đổi".+ */+export const lineKey = (l) => `${r2(l.start)}|${r2(l.end)}|${lineText(lineTokens(lineText(l.words)))}`;+/** Số dòng đổi: dòng mới không có trong bản cũ (đếm theo bội) + số dòng bị bớt. */+export function changedLines(before, after) {+ const left = new Map(); for (const x of before) left.set(x, (left.get(x) || 0) + 1);+ let n = 0;+ for (const x of after) { const c = left.get(x) || 0; if (c) left.set(x, c - 1); else n++; }+ return n + Math.max(0, before.length - after.length);+}+/** Chữ ký phần cắt (keep + móc): dòng phụ đề chỉnh tay (giây bản ra) chỉ còn đúng khi phần cắt không đổi. */export const cutSig = (edl) => JSON.stringify([edl.keep.map((k) => [r2(k.start), r2(k.end)]), edl.hook ? [r2(edl.hook.start), r2(edl.hook.end), !!edl.hook.repeat] : null]);@@ -171,7 +184,7 @@ export function cutsOf(edl) {return out;}/** Thông số kiểu chữ cho lớp xem trước HTML của Studio (gần đúng với lớp chữ HyperFrames). */-const lookCss = (l) => ({ font: l.font, weight: l.weight, size: l.size, upper: !!l.upper, color: l.color, hi: l.hi, cy: l.cy, karaoke: !!l.karaoke, stroke: l.stroke ?? null, shadow: l.shadow || null, box: l.box ? { bg: l.box.bg, tag: l.box.tag || null, tagBg: l.box.tagBg || null } : null });+const lookCss = (l) => ({ font: l.font, weight: l.weight, size: l.size, upper: !!l.upper, color: l.color, hi: l.hi, cy: l.cy, karaoke: !!l.karaoke, enter: l.enter, stroke: l.stroke ?? null, shadow: l.shadow || null, box: l.box ? { bg: l.box.bg, tag: l.box.tag || null, tagBg: l.box.tagBg || null, stroke: l.box.stroke ?? null } : null });/** Mọi thứ chỉnh tay được của bản hiện tại (UI vẽ bảng từ đây). */export function manualView(edl, state, { lookNames = {}, uploads = {} } = {}) {@@ -183,7 +196,8 @@ export function manualView(edl, state, { lookNames = {}, uploads = {} } = {}) {return {duration: dur, draft: !!state.draft, cuts: cutsOf(edl),captions: {- lines: currentLines(edl).map((l) => ({ start: l.start, end: l.end, text: lineText(l.words) })),+ // wo: giây bản ra của từng chữ (karaoke xem trước)+ lines: currentLines(edl).map((l) => ({ start: l.start, end: l.end, text: lineText(l.words), wo: l.words.map((w) => w.o) })),edited: !!edl.captions.lines, highlights: !edl.captions.hiOff, look: edl.captions.style,looks: LOOK_IDS.map((id) => ({ id, name: lookNames[id]?.name || id, nameEn: lookNames[id]?.nameEn || lookNames[id]?.name || id, hi: LOOKS[id].hi, css: lookCss(LOOKS[id]) })),},@@ -267,7 +281,7 @@ function applyZooms(edl, p, { dur, man, redo, summary }) {}const REQUIRED_TEXT = { sticker: ['text'], title_card: ['title'] };-function patchGfxData(g, d) {+export function patchGfxData(g, d) {const cur = g.data; const changed = [];const put = (obj, k, v, where, required) => {if (!(k in obj)) throw httpErr(400, `đồ hoạ ${g.id} (${g.type}) không có ô ${where}`);@@ -331,6 +345,34 @@ function applyGraphicsSet(edl, list, { dur, dir, style, man, redo, summary, warn} else warnings.push('không có khung mặt đã đo (faces-out.json): đồ hoạ giữ vị trí cũ');}+/**+ * Cảnh xem trước đồ hoạ cho Studio (POST /api/edits/:id/gfx-preview): đồ hoạ của bản hiện tại với giờ (giây bản ra) và ô+ * chữ/số đang sửa ở máy. Kiểm như bản vá (GfxData, kiểu khớp). Không ghi gì. Trả {css, html, data} của graphicsScene.+ */+export const GfxPreviewSchema = z.object({+ graphics: z.array(z.object({ id: z.string().min(1).max(80), at: sec, until: sec, data: GfxData.optional() }).strict()).max(60),+}).strict();+export function previewGraphics(edl, body, { accent, graphicsScene }) {+ const r = GfxPreviewSchema.safeParse(body);+ if (!r.success) throw httpErr(400, 'xem trước đồ hoạ không hợp lệ: ' + r.error.issues.slice(0, 3).map((i) => `${i.path.join('.')}: ${i.message}`).join('; '));+ const tl = timelineOf(edl); const dur = outputDuration(tl);+ const list = r.data.graphics.map((x) => {+ const g0 = (edl.graphics || []).find((g) => g.id === x.id);+ if (!g0) throw httpErr(400, `không có đồ hoạ ${x.id}`);+ const g = JSON.parse(JSON.stringify(g0));+ if (x.data) patchGfxData(g, x.data);+ // giờ mới: dời mốc nội bộ theo đầu đồ hoạ (như applyGraphicsSet)+ const o0 = toOutputNearest(tl, g.start); const a = Math.min(x.at, dur); const b = Math.min(Math.max(x.until, a + 0.1), dur);+ const move = (src) => +outputToSource(tl, Math.min(b - 0.2, Math.max(a, toOutputNearest(tl, src) + a - o0))).toFixed(3);+ g.data.at = move(g.data.at ?? g.start);+ for (const arr of [g.data.items, g.data.points, g.data.rows]) if (Array.isArray(arr)) for (const it of arr) if (Number.isFinite(it.at)) it.at = move(it.at);+ g.start = +outputToSource(tl, a).toFixed(3); g.end = +outputToSource(tl, b).toFixed(3);+ return g;+ });+ const sc = graphicsScene({ ...edl, graphics: list }, { accent, stepTracker: false, dur });+ return { css: sc.css, html: sc.html, data: sc.data, ids: list.map((g) => g.id) };+}+// ---- áp bản vá -------------------------------------------------------------------------------------------------/*** Áp bản vá lên bản sao EDL. Trả {edl, manual (để lưu vào state), music (đường dẫn nhạc cho state), redo: {base, layer, mix},@@ -351,9 +393,8 @@ export function applyPatch(edlIn, state, patch, { dir, style = null, uploads = {if (c.lines) {const prev = currentLines(edl);const lines = buildLines(c.lines, prev, dur);- const before = prev.map((l) => `${l.start}|${l.end}|${lineText(l.words)}`);- const after = lines.map((l) => `${l.start}|${l.end}|${lineText(l.words)}`);- const changed = after.filter((x) => !before.includes(x)).length + Math.max(0, before.length - after.length);+ const before = prev.map(lineKey); const after = lines.map(lineKey);+ const changed = changedLines(before, after);if (changed || before.length !== after.length) {edl.captions.lines = lines; man.lines = { sig: cutSig(edl), lines };redo.layer = true; summary.push(`phụ đề: ${changed} dòng đổi (${before.length} → ${after.length} dòng)`);diff --git a/edit/pipeline.mjs b/edit/pipeline.mjsindex 1e7deb3..2eb115c 100644--- a/edit/pipeline.mjs+++ b/edit/pipeline.mjs@@ -11,7 +11,7 @@import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';-import { run } from '../engine/lib.mjs';+import { run, runHF } from '../engine/lib.mjs';import { SFX_NAMES } from '../engine/audio/sfx.mjs';import { measureLoudness } from '../engine/audio/mix.mjs';import { ROOT, runLumedit } from './env.mjs';@@ -23,7 +23,7 @@ import {import { selectSegments, planGraphics, layoutGraphics, fillUnits, figureList, checkFigures, dropLowFigures } from './graphics.mjs';import { fmtVi } from './numbers.mjs';import { validateEdl, toOutputNearest, outputDuration, timelineOf, inKeep, OUT } from './edl.mjs';-import { writeCaptionScene, renderCaptionLayer, captionTop, LAYER, layerInput } from './captions-hf.mjs';+import { writeCaptionScene, writeGraphicScene, renderCaptionLayer, captionTop, LAYER, LAYERS, layerInput } from './captions-hf.mjs';import { buildEditMix } from './audio.mjs';import { pickEncoder, videoArgs } from './encoder.mjs';import { applyPatch, applyManual } from './manual.mjs';@@ -315,8 +315,15 @@ async function renderEdl({ dir, edl, draft, R, outName = 'out.mp4', repair = nulasync function renderBase({ edlFile, base, draft, R, check = true }) {const { log, timings, checks, step } = R;const enc = await pickEncoder();+ const dir = path.dirname(base);+ const edl = readJson(edlFile);+ // bản sạch 540×960 cho Studio (trước zoom/thu hình/kính): chỉ ghi khi phần cắt/khung đổi (cùng lượt đọc, gần như miễn phí)+ const cSig = cleanSig(edl);+ const wantClean = !(sigOk(dir, 'clean', cSig) && fs.existsSync(path.join(dir, CLEAN)));+ const cleanTmp = path.join(dir, 'preview-clean.v.mp4');const rb = await step('render nền', async (pg) => {- const go = (kind) => runLumedit(['render', edlFile, '--out', base, ...(draft ? ['--draft-captions'] : []), ...(check ? [] : ['--no-check'])], {+ const go = (kind) => runLumedit(['render', edlFile, '--out', base, '--no-glass', ...(wantClean ? ['--clean-out', cleanTmp] : []),+ ...(draft ? ['--draft-captions'] : []), ...(check ? [] : ['--no-check'])], {env: kind === 'gpu' ? { FX_VCODEC_ARGS: JSON.stringify(videoArgs('gpu', { quality: 18 })) } : {},onProgress: (p) => {if (p.step === 'render') { pg(Math.round(p.pct * 0.6), `${p.done}/${p.total} khung`); if (p.pct % 25 === 0) log(` render ${p.pct}% (${p.done}/${p.total})`); }@@ -332,12 +339,99 @@ async function renderBase({ edlFile, base, draft, R, check = true }) {if (rb.seconds.overcut_check !== undefined) timings['kiểm lẹm chữ (nghe lại)'] = rb.seconds.overcut_check;(checks.encoders ||= {}).base = rb.encoder === 'gpu' ? 'h264_nvenc' : 'libx264';if (check) { checks.overcut = rb.overcut; log(` lẹm chữ: ${rb.overcut?.verdict}`); }- saveSig(path.dirname(base), 'base', baseSig(readJson(edlFile), draft));- saveSig(path.dirname(base), 'baseSeconds', rb.seconds_out);+ saveSig(dir, 'base', baseSig(edl, draft));+ saveSig(dir, 'baseSeconds', rb.seconds_out);+ if (wantClean && fs.existsSync(cleanTmp)) {+ // tiếng gốc của nền vào bản sạch (chép luồng, không mã hoá lại)+ const tmp = path.join(dir, 'preview-clean.part.mp4');+ const r = await run('ffmpeg', ['-hide_banner', '-y', '-i', cleanTmp, '-i', base, '-map', '0:v:0', '-map', '1:a:0?', '-c', 'copy', '-shortest', '-movflags', '+faststart', tmp]);+ fs.rmSync(cleanTmp, { force: true });+ try {+ if (r.code !== 0) throw new Error(r.out.trim().split(/\r?\n/).pop());+ fs.rmSync(path.join(dir, CLEAN), { force: true }); fs.renameSync(tmp, path.join(dir, CLEAN));+ saveSig(dir, 'clean', cSig);+ } catch (e) { log(` bản sạch xem trước: không ghi được (${e.message})`); fs.rmSync(tmp, { force: true }); }+ }return rb;}+/** Bản xem trước không zoom/kính/thu hình (Studio vẽ zoom bằng CSS). */+export const CLEAN = 'preview-clean.mp4';++// ---- kính mờ dưới đồ hoạ: vẽ ở bước ghép bằng ffmpeg (như lumedit Glass: mờ ¼ cỡ σ6, bo góc 38·scale, mờ vào 0,15 s / ra 0,22 s) ----+/** Vùng kính của từng đồ hoạ (giây bản ra, px). Tem giá / sticker / thẻ ghim không có kính. */+export function glassItems(edl) {+ const tl = timelineOf(edl); const out = [];+ for (const g of edl.graphics || []) {+ const b = g.box;+ if (!b || ['price_tag', 'sticker'].includes(g.type) || g.data?.pin) continue;+ const x0 = Math.max(0, Math.round(b.x)); const y0 = Math.max(0, Math.round(b.y));+ const x1 = Math.min(OUT.width, Math.round(b.x + b.w)); const y1 = Math.min(OUT.height, Math.round(b.y + b.h));+ if (x1 - x0 < 8 || y1 - y0 < 8) continue;+ out.push({ x: x0, y: y0, w: x1 - x0, h: y1 - y0, r: Math.max(4, Math.trunc(38 * (b.scale ?? 1))), t0: +toOutputNearest(tl, g.start).toFixed(3), t1: +toOutputNearest(tl, g.end).toFixed(3) });+ }+ return out;+}+async function glassMask(dir, { w, h, r }) {+ const f = path.join(dir, 'glass', `mask-${w}x${h}-${r}.png`);+ if (fs.existsSync(f)) return f;+ fs.mkdirSync(path.dirname(f), { recursive: true });+ const R = r;+ const expr = `255*clip(${R}+0.5-hypot(max(max(${R}-X\\,X-(W-1-${R}))\\,0)\\,max(max(${R}-Y\\,Y-(H-1-${R}))\\,0))\\,0\\,1)`;+ const q = await run('ffmpeg', ['-hide_banner', '-y', '-f', 'lavfi', '-i', `color=c=black:s=${w}x${h}:d=1:r=1,format=gray,geq=lum='${expr}'`, '-frames:v', '1', f]);+ if (q.code !== 0) throw new Error('mặt nạ kính lỗi: ' + q.out.trim().split(/\r?\n/).pop());+ return f;+}++/** Khoảng bản ra của 1 đồ hoạ, theo khung (lớp đồ hoạ riêng chỉ render đúng khoảng này). */+export function gfxWindow(edl, g) {+ const tl = timelineOf(edl); const dur = outputDuration(tl);+ const a = Math.max(0, Math.floor(toOutputNearest(tl, g.start) * OUT.fps) / OUT.fps);+ const b = Math.min(Math.ceil(dur * OUT.fps) / OUT.fps, Math.ceil(toOutputNearest(tl, g.end) * OUT.fps) / OUT.fps);+ return { from: +a.toFixed(4), dur: +Math.max(1 / OUT.fps, b - a).toFixed(4) };+}+/**+ * Khoảng (giây bản ra) phải render lại lớp phụ đề: thẻ có ở bản này mà không có y hệt ở bản trước, và ngược lại+ * (+0,05 s trước, +0,35 s sau cho hiệu ứng vào/ra). null = render cả lớp (đổi kiểu chữ, trích dẫn, chữ móc, độ dài,+ * hoặc khoảng đổi chiếm > 55% thời lượng).+ */+export function dirtyRanges(prev, sc) {+ if (!prev || prev.global !== sc.global || Math.abs(prev.duration - sc.duration) > 1e-6 || !Array.isArray(prev.cards)) return null;+ const key = (c) => `${c.s}|${c.e}|${c.k}`;+ const left = new Map(); for (const c of prev.cards) left.set(key(c), (left.get(key(c)) || 0) + 1);+ const spans = [];+ for (const c of sc.cardsMeta) { const n = left.get(key(c)) || 0; if (n) left.set(key(c), n - 1); else spans.push([c.s, c.e]); }+ for (const c of prev.cards) { const n = left.get(key(c)) || 0; if (n) { left.set(key(c), n - 1); spans.push([c.s, c.e]); } }+ if (!spans.length) return [];+ const d = sc.duration;+ const rs = spans.map(([a, b]) => [Math.max(0, Math.floor((a - 0.05) * OUT.fps) / OUT.fps), Math.min(d, Math.ceil((b + 0.35) * OUT.fps) / OUT.fps)]).sort((x, y) => x[0] - y[0]);+ const merged = [];+ for (const r of rs) { const m = merged[merged.length - 1]; if (m && r[0] <= m[1] + 3) m[1] = Math.max(m[1], r[1]); else merged.push([...r]); }+ // mỗi lượt HyperFrames tốn ~15 s khởi động: nhiều khoảng thì gộp thành 1+ const out = merged.length > 2 ? [[merged[0][0], merged[merged.length - 1][1]]] : merged;+ return out.reduce((s, [a, b]) => s + b - a, 0) > 0.55 * d ? null : out;+}+async function renderLayerRange(sceneDir, layerDir, a, b, { onPct } = {}) {+ const tmp = layerDir + '.part';+ fs.rmSync(tmp, { recursive: true, force: true });+ const r = await runHF(['render', sceneDir, '-o', tmp, ...LAYERS.png.hf, '-f', String(OUT.fps), '-q', 'looks', '--quiet', '--start', a.toFixed(3), '--end', b.toFixed(3)], {+ onLine: (l) => { const m = /^@hf-progress (.*)$/.exec(l); if (m) { try { onPct?.(JSON.parse(m[1]).pct); } catch { /* bỏ qua */ } } },+ });+ if (r.code !== 0 || !fs.existsSync(tmp)) throw new Error('HyperFrames render lại đoạn phụ đề lỗi: ' + r.out.trim().split(/\r?\n/).slice(-3).join(' | '));+ const first = Math.round(a * OUT.fps); // khung k (từ 1) của đoạn = khung first + k của lớp đầy đủ+ for (const f of fs.readdirSync(tmp)) {+ const m = /^frame_(\d+)\.png$/.exec(f); if (!m) continue;+ const dst = path.join(layerDir, `frame_${String(first + Number(m[1])).padStart(6, '0')}.png`);+ if (fs.existsSync(dst)) fs.copyFileSync(path.join(tmp, f), dst);+ }+ fs.rmSync(tmp, { recursive: true, force: true });+}++/** Đồ hoạ vẽ chung lớp phụ đề (cũ) khi kiểu có thanh bước (stepTracker: cần thấy mọi đồ hoạ cùng lúc). */+const gfxInCaptions = (style) => !!style?.graphics?.stepTracker;+/**+ * Tiếng động theo giây bản ra./*** Tiếng động theo giây bản ra. Câu móc lặp lại (repeat): tiếng nằm trong khoảng móc phát cả ở đầu clip lẫn chỗ cũ;* tiếng riêng của câu móc (hook.sfx, vd "boom") chỉ phát ở đầu clip.*/@@ -357,23 +451,65 @@ async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName, reconst { log, timings, checks, warnings, step } = R;const layerFile = path.join(dir, LAYER.file);const mixFile = path.join(dir, 'audio', 'mix.wav');+ let style = null; try { style = loadStyle(edl.style); } catch { /* kiểu đã bị xoá: màu mặc định */ }+ const accent = style?.graphics?.accent;+ const comb = gfxInCaptions(style);// dùng lại chỉ khi chữ ký khớp đúng EDL hiện tại (lượt trước hỏng giữa chừng thì file cũ không khớp → dựng lại)- const lSig = layerSig(edl, draft); const mSig = mixSig(edl);-- let overlay = null;- const hasLayer = () => (edl.graphics || []).length > 0 || (!draft && edl.captions.words.length > 0);- if (reuse.layer !== false && sigOk(dir, 'layer', lSig) && (!hasLayer() || fs.existsSync(layerFile))) {- overlay = hasLayer() ? layerFile : null; log(' phụ đề: dùng lại lớp chữ lượt trước (không đổi)');- } else await step('phụ đề', async (pg) => {- fs.rmSync(layerFile, { force: true, recursive: true });- if (!hasLayer()) { pg(100, draft ? 'phụ đề nháp đã vẽ trong nền' : 'không có chữ'); saveSig(dir, 'layer', lSig); return; }- let accent; let style = null;- try { style = loadStyle(edl.style); accent = style.graphics?.accent; } catch { /* kiểu đã bị xoá: màu mặc định */ }- const sc = writeCaptionScene(edl, path.join(dir, 'captions'), { captions: !draft, accent, style });- checks.captions = { cards: sc.cards, graphics: sc.graphics, overlaps: 0, box: sc.box, safeZone: 'trong 120–960 px, đáy ≤ 80% khung', quote: sc.quote, hookText: sc.hookText, ticker: sc.ticker, layer: LAYER.name };- overlay = await renderCaptionLayer(path.join(dir, 'captions'), layerFile, { log, onPct: (p) => pg(p, 'HyperFrames'), format: LAYER.hf });- saveSig(dir, 'layer', lSig);+ const lSig = layerSig(edl, draft, comb); const mSig = mixSig(edl);+ const capEdl = comb ? edl : { ...edl, graphics: [] };+ const hasLayer = () => (comb && (edl.graphics || []).length > 0) || (!draft && (edl.captions.words.length > 0 || !!edl.hookText || !!edl.quote));+ const capFresh = reuse.layer !== false && sigOk(dir, 'layer', lSig) && (!hasLayer() || fs.existsSync(layerFile));+ // lớp riêng từng đồ hoạ: chỉ khoảng nó hiện, chữ ký riêng (sửa 1 đồ hoạ không render lại phụ đề / đồ hoạ khác)+ const gl = comb ? [] : (edl.graphics || []).map((g) => {+ const w = gfxWindow(edl, g); const sig = gfxSig(g, accent, w);+ return { g, ...w, sig, dir: path.join(dir, 'gfx-layers', sig.slice(0, 16)) };+ });+ const gfxFresh = (x) => { try { return fs.readdirSync(x.dir).some((f) => /\.png$/i.test(f)); } catch { return false; } };+ const todo = gl.filter((x) => !gfxFresh(x));+ let overlay = capFresh ? (hasLayer() ? layerFile : null) : null;+ if (capFresh) log(' phụ đề: dùng lại lớp chữ lượt trước (không đổi)');+ if (gl.length && !todo.length) log(` đồ hoạ: dùng lại ${gl.length} lớp đồ hoạ (không đổi)`);+ if (!capFresh || todo.length) await step('phụ đề', async (pg) => {+ const parts = (capFresh ? 0 : 1) + todo.length; let done = 0;+ const sub = (p) => pg(Math.round(((done + p / 100) / Math.max(1, parts)) * 100), 'HyperFrames');+ if (!capFresh) {+ if (!hasLayer()) { fs.rmSync(layerFile, { force: true, recursive: true }); overlay = null; saveSig(dir, 'layer', lSig); }+ else {+ const sc = writeCaptionScene(capEdl, path.join(dir, 'captions'), { captions: !draft, accent, style });+ checks.captions = { cards: sc.cards, graphics: (edl.graphics || []).length, overlaps: 0, box: sc.box, safeZone: 'trong 120–960 px, đáy ≤ 80% khung', quote: sc.quote, hookText: sc.hookText, ticker: sc.ticker, layer: LAYER.name, gfxLayers: comb ? 0 : gl.length };+ const metaFile = path.join(dir, 'captions.meta.json');+ const prev = readJson(metaFile);+ const ranges = LAYER.name === 'png' && fs.existsSync(layerFile) && sigOk(dir, 'layerMeta', prev ? sha(prev) : '-') ? dirtyRanges(prev, sc) : null;+ fs.rmSync(metaFile, { force: true });+ if (ranges) {+ // chỉ render lại khoảng có thẻ đổi (HyperFrames --start/--end), chép khung đè vào lớp cũ+ const t = Date.now();+ for (const [a, b] of ranges) await renderLayerRange(path.join(dir, 'captions'), layerFile, a, b, { onPct: sub });+ log(` phụ đề: render lại ${ranges.map(([a, b]) => `${a.toFixed(2)}–${b.toFixed(2)} s`).join(', ')} (${((Date.now() - t) / 1000).toFixed(1)} s), giữ phần còn lại`);+ overlay = layerFile;+ } else {+ fs.rmSync(layerFile, { force: true, recursive: true });+ overlay = await renderCaptionLayer(path.join(dir, 'captions'), layerFile, { log, onPct: sub, format: LAYER.hf });+ }+ const meta = { global: sc.global, cards: sc.cardsMeta, duration: sc.duration };+ fs.writeFileSync(metaFile, JSON.stringify(meta));+ saveSig(dir, 'layer', lSig); saveSig(dir, 'layerMeta', sha(meta));+ }+ done++;+ }+ for (const x of todo) {+ const scene = path.join(dir, 'gfx-scene');+ fs.rmSync(scene, { recursive: true, force: true }); fs.rmSync(x.dir, { recursive: true, force: true });+ writeGraphicScene(edl, x.g, scene, { accent, from: x.from, dur: x.dur });+ const t = Date.now();+ await renderCaptionLayer(scene, x.dir, { log: () => {}, onPct: sub, format: LAYERS.png.hf });+ log(` đồ hoạ ${x.g.id} (${x.g.type}) ${x.from.toFixed(2)}–${(x.from + x.dur).toFixed(2)} s: ${((Date.now() - t) / 1000).toFixed(1)} s`);+ done++;+ }});+ // dọn lớp đồ hoạ không còn dùng+ try { const keepDirs = new Set(gl.map((x) => path.basename(x.dir))); for (const f of fs.readdirSync(path.join(dir, 'gfx-layers'))) if (!keepDirs.has(f)) fs.rmSync(path.join(dir, 'gfx-layers', f), { recursive: true, force: true }); } catch { /* chưa có */ }+ const glass = glassItems(edl);const duration = rb.seconds_out;let mix;@@ -390,7 +526,10 @@ async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName, reconst enc = await pickEncoder();// hình bản ra = nền + lớp chữ: cả hai không đổi so với bản trước (chỉ chỉnh tiếng) → chép luồng hình của bản trước, không mã hoá lạiconst sigs = readJson(sigFile(dir), {});- const vSig = sha([sigs.base || null, lSig, !!overlay]);+ const vSig = sha([sigs.base || null, lSig, !!overlay, gl.map((x) => [x.sig, x.from]), glass]);+ const masks = [];+ for (const gi of glass) masks.push(await glassMask(dir, gi));+ const fx = !!overlay || gl.length > 0 || glass.length > 0;const prevVideo = sigs.video === vSig && sigs.videoFile && sigs.videoFile !== outName && fs.existsSync(path.join(dir, sigs.videoFile)) ? path.join(dir, sigs.videoFile) : null;await step('ghép', async () => {const tmp = out.replace(/\.mp4$/, '.part.mp4');@@ -400,18 +539,35 @@ async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName, re'-shortest', '-movflags', '+faststart', tmp], { timeoutMs: 60 * 60e3 });}const args = ['-hide_banner', '-y', '-i', base];- if (overlay) args.push(...layerInput(LAYER, overlay));+ const D = (rb.seconds_out + 1).toFixed(2);+ let n = 1; const fc = []; let cur = '[0:v]';+ // kính mờ (vùng ¼ cỡ, gblur σ6, mặt nạ bo góc, alpha mờ vào/ra) — trên nền, dưới thẻ đồ hoạ+ glass.forEach((gi, k) => {+ args.push('-loop', '1', '-framerate', String(OUT.fps), '-t', D, '-i', masks[k]);+ const m = n++; const t1o = Math.max(gi.t0, gi.t1 - 0.22);+ fc.push(`${cur}split[gk${k}][gs${k}]`,+ `[gs${k}]crop=${gi.w}:${gi.h}:${gi.x}:${gi.y},scale=${Math.max(1, Math.floor(gi.w / 4))}:${Math.max(1, Math.floor(gi.h / 4))}:flags=area,gblur=sigma=6,scale=${gi.w}:${gi.h}:flags=bilinear,format=yuva420p[gb${k}]`,+ `[${m}:v]format=gray,scale=${gi.w}:${gi.h}[gm${k}]`,+ `[gb${k}][gm${k}]alphamerge,fade=t=in:st=${gi.t0.toFixed(3)}:d=0.15:alpha=1,fade=t=out:st=${t1o.toFixed(3)}:d=0.22:alpha=1[ga${k}]`,+ `[gk${k}][ga${k}]overlay=${gi.x}:${gi.y}:format=auto:enable='between(t,${gi.t0.toFixed(3)},${gi.t1.toFixed(3)})'[gv${k}]`);+ cur = `[gv${k}]`;+ });+ gl.forEach((x, k) => {+ args.push('-itsoffset', x.from.toFixed(4), ...layerInput(LAYERS.png, x.dir));+ const i = n++; fc.push(`${cur}[${i}:v]overlay=0:0:format=auto:eof_action=pass[ov${k}]`); cur = `[ov${k}]`;+ });+ if (overlay) { args.push(...layerInput(LAYER, overlay)); const i = n++; fc.push(`${cur}[${i}:v]overlay=0:0:format=auto:eof_action=pass[oc]`); cur = '[oc]'; }args.push('-i', mix.wav);- const ai = overlay ? 2 : 1;- if (overlay) args.push('-filter_complex', '[0:v][1:v]overlay=0:0:format=auto:eof_action=pass,format=yuv420p[v]', '-map', '[v]', ...videoArgs(kind, { quality: 18 }), '-pix_fmt', 'yuv420p', '-r', String(OUT.fps));+ const ai = n;+ if (fx) { fc.push(`${cur}format=yuv420p[v]`); args.push('-filter_complex', fc.join(';'), '-map', '[v]', ...videoArgs(kind, { quality: 18 }), '-pix_fmt', 'yuv420p', '-r', String(OUT.fps)); }else args.push('-map', '0:v:0', '-c:v', 'copy');args.push('-map', `${ai}:a:0`, '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2', '-shortest', '-movflags', '+faststart', tmp);return run('ffmpeg', args, { timeoutMs: 60 * 60e3 });};- let kind = prevVideo ? 'reuse' : overlay ? enc.kind : 'copy';+ let kind = prevVideo ? 'reuse' : fx ? enc.kind : 'copy';if (prevVideo) log(` ghép: hình không đổi, chép luồng hình của ${path.basename(prevVideo)} (không mã hoá lại)`);let r = await mux(kind);- if (r.code !== 0 && kind === 'reuse') { kind = overlay ? enc.kind : 'copy'; r = await mux(kind); }+ if (r.code !== 0 && kind === 'reuse') { kind = fx ? enc.kind : 'copy'; r = await mux(kind); }if (r.code !== 0 && kind === 'gpu') { log(` ghép bằng NVENC lỗi (${r.out.trim().split(/\r?\n/).pop()}), làm lại bằng libx264`); kind = 'cpu'; r = await mux('cpu'); }if (r.code !== 0) throw new Error('ghép lỗi: ' + r.out.trim().split(/\r?\n/).slice(-3).join(' | '));(checks.encoders ||= {}).mux = kind === 'gpu' ? 'h264_nvenc' : kind === 'cpu' ? 'libx264' : kind === 'reuse' ? 'chép hình bản trước' : 'copy';@@ -509,10 +665,18 @@ export async function reviseEdit(id, instruction, opts = {}) {// cho script kiểm thử: dựng lại EDL + render từ state.json đã có (không gọi LLM, không phân tích lại)// ---- chữ ký từng lớp (render.sig.json): lớp nào chưa đổi so với EDL hiện tại thì chỉnh tay dùng lại được -------------const sha = (x) => crypto.createHash('sha1').update(JSON.stringify(x)).digest('hex');-/** Nền: phần cắt, móc, zoom, khung, đồ hoạ (kính mờ + thu khung vẽ trong nền), trích dẫn, phụ đề nháp (vẽ PIL trong nền). */-export const baseSig = (edl, draft) => sha([edl.proxy.file, edl.keep, edl.hook, edl.zooms, edl.reframe, edl.graphics || [], edl.quote, draft ? edl.captions : null, !!draft]);-/** Lớp chữ: phụ đề + đồ hoạ + chữ móc + trích dẫn trên trục bản ra. */-export const layerSig = (edl, draft) => sha([LAYER.name, edl.style, edl.keep, edl.hook, edl.captions, edl.graphics || [], edl.hookText, edl.quote, !!draft]);+/**+ * Nền: CHỈ những gì vẽ trong nền — phần cắt, móc, zoom, khung, thu hình của đồ hoạ (squeeze), trích dẫn, phụ đề nháp.+ * Chữ/số/giờ đồ hoạ và kính mờ không ở đây (lớp đồ hoạ riêng + kính vẽ lúc ghép) → sửa đồ hoạ không render lại nền.+ */+const squeezes = (edl) => (edl.graphics || []).filter((g) => g.squeeze).map((g) => [g.start, g.end, g.squeeze]);+export const baseSig = (edl, draft) => sha(['nền-v2', edl.proxy.file, edl.keep, edl.hook, edl.zooms, edl.reframe, squeezes(edl), edl.quote, draft ? edl.captions : null, !!draft]);+/** Bản sạch xem trước: phần cắt + khung. */+export const cleanSig = (edl) => sha(['sạch-v1', edl.proxy.file, edl.keep, edl.hook, edl.reframe]);+/** Lớp phụ đề: phụ đề + chữ móc + trích dẫn (+ đồ hoạ khi kiểu có thanh bước). */+export const layerSig = (edl, draft, comb = false) => sha([LAYER.name, 'chữ-v2', edl.style, edl.keep, edl.hook, edl.captions, comb ? edl.graphics || [] : null, edl.hookText, edl.quote, !!draft]);+/** Lớp 1 đồ hoạ: chính đồ hoạ (chữ, số, mốc, vị trí) + màu nhấn + khoảng render. */+export const gfxSig = (g, accent, w) => sha([LAYERS.png.name, 'đh-v1', g, accent || null, w.from, w.dur]);/** Tiếng: giọng gốc (theo phần cắt) + nhạc + sfx + giọng/sfx chỉnh tay + LUFS. */export const mixSig = (edl) => sha([edl.keep, edl.hook, edl.audio, edl.music, edl.audio?.sfxOff ? [] : outputSfx(edl), edl.output.lufs]);const sigFile = (dir) => path.join(dir, 'render.sig.json');@@ -596,4 +760,19 @@ export async function manualEdit(id, patch, opts = {}) {return result;}+/** Bước đầu tiên chỉnh tay phải chạy (để thanh tiến độ bắt đầu đúng chỗ): nền → phụ đề → tiếng → ghép. */+export function manualStartStep(dir, edl, draft) {+ if (!fs.existsSync(path.join(dir, 'base.mp4')) || !sigOk(dir, 'base', baseSig(edl, draft))) return STEPS.indexOf('render nền');+ let style = null; try { style = loadStyle(edl.style); } catch { /* bỏ qua */ }+ const comb = gfxInCaptions(style);+ const capOk = sigOk(dir, 'layer', layerSig(edl, draft, comb));+ const gfxOk = comb || (edl.graphics || []).every((g) => {+ const w = gfxWindow(edl, g); const d = path.join(dir, 'gfx-layers', gfxSig(g, style?.graphics?.accent, w).slice(0, 16));+ try { return fs.readdirSync(d).some((f) => /\.png$/i.test(f)); } catch { return false; }+ });+ if (!capOk || !gfxOk) return STEPS.indexOf('phụ đề');+ if (!sigOk(dir, 'mix', mixSig(edl))) return STEPS.indexOf('tiếng');+ return STEPS.indexOf('ghép');+}+export const _internal = { buildEdl, renderEdl, runner };diff --git a/edit/py/lumedit.py b/edit/py/lumedit.pyindex c5c757b..279fabd 100644--- a/edit/py/lumedit.py+++ b/edit/py/lumedit.py@@ -1,714 +1,732 @@-"""LumReels Edit: the Python side, built on the AskEditor pack's core (edit/askeditor/fx, MIT).-- python -X utf8 lumedit.py analyze <proxy.mp4> --out analysis.json- python -X utf8 lumedit.py render <edl.json> --out base.mp4 [--draft-captions] [--no-check]- python -X utf8 lumedit.py stills <edl.json> --out preview.jpg [--count 16] [--draft-captions]- python -X utf8 lumedit.py hear <proxy.mp4> --spans a-b,c-d --out heard.json- python -X utf8 lumedit.py qc <final.mp4> --out qc.json--Talks to Node line by line: `@progress {json}` while it works, and one `@result {json}` at the end-({"ok": true, ...} or {"ok": false, "error": "..."}). Exit 0 on success, 2 on bad input, 3 when setup-is missing, 1 on any other failure.--Everything in an EDL is in source seconds; the proxy shares the source's time axis. The render is-one pass: AskEditor's Timeline (the kept stretches, with the source sound joined by 20 ms-crossfades) and Framing (9:16 window following the face), then our zooms and draft captions drawn-on each output frame.-"""--from __future__ import annotations--import argparse-import json-import math-import os-import sys-import time-import traceback-from functools import lru_cache-from pathlib import Path--PACK = Path(__file__).resolve().parents[1] / "askeditor"-sys.path.insert(0, str(PACK))-os.environ.setdefault("GLOG_minloglevel", "2")-os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3")--OUT_W, OUT_H, OUT_FPS = 1080, 1920, 30-SAFE = (120 / 1080, 0.10, 960 / 1080, 0.80) # x0, y0, x1, y1 as shares of the frame---def emit(kind: str, obj: dict) -> None:- print(f"@{kind} " + json.dumps(obj, ensure_ascii=False), flush=True)---def progress(step: str, **kw) -> None:- emit("progress", {"step": step, **kw})---# ---- analyze -----------------------------------------------------------------------------------------------def cmd_analyze(proxy: Path, out: Path) -> dict:- from fx.core.clip import Clip- from fx.core import words as wordsmod-- t0 = time.time()- clip = Clip(proxy)- info = clip.info- progress("words", note=f"chép lời ({os.environ.get('FX_WHISPER') or 'small.en'}, {wordsmod.LANG})")- ws = clip.words- t_words = time.time() - t0- try: # where whisper ran (cuda float16 | cpu int8 (why)), recorded in the words cache by fx.core.words- from fx.core import paths as pathsmod- device = json.loads(pathsmod.beside(proxy.resolve(), "words.json").read_text(encoding="utf-8")).get("device") or "?"- except (OSError, ValueError):- device = "?"- progress("words", note=f"whisper {device}")- progress("quiet")- quiet = clip.quiet- progress("face")- t1 = time.time()- face = clip.face- t_face = time.time() - t1- fps = info.rate- faces = []- step = max(1, int(round(fps / 2)))- for i in range(0, info.frames, step):- b = face.box(i) if face.any() else None- faces.append(None if b is None else [round(i / fps, 2), round(b.x0), round(b.y0), round(b.w), round(b.h)])- data = {- "proxy": str(proxy), "duration": round(info.duration, 3), "fps": fps, "frames": info.frames,- "width": info.width, "height": info.height,- "words": [{"i": i, "w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "p": round(w.prob, 3)}- for i, w in enumerate(ws)],- "unsure": [{"w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "why": w.unsure} for w in clip.unsure],- "quiet": [[round(a, 3), round(b, 3)] for a, b in quiet],- "face": {"found_share": round(float(face.found_share), 3) if face.any() else 0.0,- "every_half_second": [f for f in faces if f is not None]},- # The speech-band loudness in 10 ms steps (whole dB), so the planner can put every cut at a real break in- # the voice instead of at the transcriber's word edges, which run up to 0.2 s off on Vietnamese.- "env": {"hop": clip.envelope.hop, "floor": round(clip.envelope.floor, 2), "speech": round(clip.envelope.speech, 2),- "threshold": round(clip.envelope.threshold, 2), "db": [int(round(float(x))) for x in clip.envelope.db]},- "hesitations": sorted(wordsmod.HESITATIONS),- "model": wordsmod.model_key("small.en"), "lang": wordsmod.LANG,- "seconds": {"words": round(t_words, 1), "face": round(t_face, 1), "total": round(time.time() - t0, 1)},- "whisper_device": device,- }- out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")- return {"out": str(out), "words": len(ws), "unsure": len(clip.unsure), "seconds": data["seconds"], "device": device}---# ---- shared: the EDL as AskEditor objects --------------------------------------------------------------------def load_edl(path: Path) -> dict:- edl = json.loads(path.read_text(encoding="utf-8"))- if edl.get("version") != 1:- raise ValueError(f"EDL version {edl.get('version')!r} is not supported (want 1)")- return edl---def build(edl: dict, draft_captions: bool):- from fx.core import framing as framing_mod- from fx.core.clip import Clip- from fx.core.timeline import Timeline-- clip = Clip(edl["proxy"]["file"])- info = clip.info- if abs(info.rate - OUT_FPS) > 0.01:- raise ValueError(f"the proxy runs at {info.rate} fps; it must be the 30 fps proxy")- segs = tuple((float(k["start"]), min(float(k["end"]), info.duration)) for k in edl["keep"])- segs = tuple((a, b) for a, b in segs if b - a > 1e-3)- tl = hook_timeline(Timeline, segs, edl.get("hook"), info.duration)- mode = edl["reframe"]["mode"]- face = clip.face if mode == "face" else None- fr = framing_mod.plan(info.width, info.height, info.rate, info.frames, face, shape="9:16",- size=(OUT_W, OUT_H), mode={"face": "track", "center": "center", "fill": "fill",- "none": "center"}[mode])- if (fr.out_w, fr.out_h) != (OUT_W, OUT_H):- fr.out_w, fr.out_h = OUT_W, OUT_H- zooms = Zooms(edl, tl, fr, clip)- glass = Glass(edl, tl) if edl.get("graphics") else None- squeeze = Squeeze(edl, tl) if any(g.get("squeeze") for g in edl.get("graphics", [])) else None- caps = DraftCaptions(edl, tl) if draft_captions and edl["captions"]["words"] else None- quote = QuoteDim(edl, tl) if edl.get("quote") else None- hook = edl.get("hook") or None- flash_at = (float(hook["end"]) - float(hook["start"])) if hook and hook.get("flash") else None-- def draw(frame, j, t):- zooms.apply(frame, j, t)- if squeeze is not None:- squeeze.apply(frame, t)- if quote is not None:- quote.apply(frame, t)- if glass is not None:- glass.apply(frame, t)- if caps is not None:- caps.draw(frame, t)- # chớp trắng 2 khung ở chỗ nối câu móc → clip- if flash_at is not None and flash_at - 1e-3 <= t < flash_at + 2.0 / OUT_FPS - 1e-3:- frame[:] = 255-- return clip, tl, fr, draw---# ---- the hook pulled to the front -----------------------------------------------------------------------------def hook_timeline(Timeline, segs, hook, duration):- """The output plays the hook (edl.hook, source seconds) first, then the kept stretches. Playing (to_source,- sample_ranges, joins) works on any order of segments; only source → output needs care: a moment inside a kept- stretch lands there (after the hook), a moment only in the hook (repeat: false) lands at 0 … hook length."""- if not hook:- return Timeline(segs)- from dataclasses import dataclass-- @dataclass(frozen=True)- class HookTimeline(Timeline):- def _play(self, t):- (h0, h1), rest = self.segments[0], self.segments[1:]- acc = h1 - h0- for a, b in rest:- if t < a - 1e-9:- break- if t <= b + 1e-9:- return acc + (t - a)- acc += b - a- if h0 - 1e-9 <= t <= h1 + 1e-9:- return t - h0- return None-- def to_output_nearest(self, t):- got = self.to_output(t)- if got is not None:- return got- best, best_d = 0.0, math.inf- for a, b in self.segments[1:]:- for src in (a, b):- if abs(src - t) < best_d:- best, best_d = self.to_output(src), abs(src - t)- return best-- h = (float(hook["start"]), min(float(hook["end"]), duration))- return HookTimeline((h,) + tuple(segs))---class QuoteDim:- """edl.quote: while the quote is on screen the video dims to `dimTo` and blurs `blurPx`, eased in over `dimIn` s;- held to the end when the quote closes the clip, else eased back out in 0.4 s (the quote block itself is drawn in- the HyperFrames layer)."""-- def __init__(self, edl: dict, tl):- q = edl["quote"]- self.t0 = tl.to_output_nearest(float(q["start"]))- q1 = tl.to_output_nearest(float(q["end"]))- self.t1 = tl.duration + 1.0 if q1 >= tl.duration - 2.0 else min(tl.duration, q1 + 0.8)- self.dim, self.blur, self.din = float(q["dimTo"]), float(q["blurPx"]), max(0.1, float(q["dimIn"]))-- def apply(self, frame, t: float) -> None:- if not (self.t0 <= t < self.t1):- return- e = min(_ease((t - self.t0) / self.din), _ease((self.t1 - t) / 0.4))- if e <= 0.01:- return- import cv2- import numpy as np-- img = frame- sigma = self.blur * e- if sigma > 0.3:- small = cv2.resize(frame, (OUT_W // 4, OUT_H // 4), interpolation=cv2.INTER_AREA)- img = cv2.resize(cv2.GaussianBlur(small, (0, 0), sigma / 4), (OUT_W, OUT_H), interpolation=cv2.INTER_LINEAR)- k = 1.0 - (1.0 - self.dim) * e- frame[:] = (img.astype(np.float32) * k).astype(np.uint8)---# ---- zooms -----------------------------------------------------------------------------------------------------def _ease(x: float) -> float:- x = min(1.0, max(0.0, x))- return x * x * (3 - 2 * x)---class Zooms:- """Each zoom of the EDL on the output picture: a punch (in fast, hold, out) or a slow push, about- the face where the zoom begins (or the upper middle of the frame when no face is found)."""-- PUNCH_IN, PUNCH_OUT = 0.08, 0.12-- def __init__(self, edl: dict, tl, fr, clip):- self.items = []- fps = clip.info.rate- hook = edl.get("hook") or None- hd = float(hook["end"]) - float(hook["start"]) if hook else 0.0- for z in edl["zooms"]:- at = float(z["at"])- t_out = [(tl.to_output_nearest(at), float(z["dur"]))]- # câu móc lặp lại: cú zoom trong câu móc chạy cả ở đầu clip (không tràn qua chỗ nối)- if hook and hook.get("repeat") and float(hook["start"]) <= at <= float(hook["end"]):- t_h = at - float(hook["start"])- t_out.append((t_h, min(float(z["dur"]), hd - t_h)))- for t0, dur in t_out:- k = tl.source_frame(int(round(t0 * fps)), fps, clip.info.frames)- cx, cy = OUT_W / 2, OUT_H * 0.40- head = clip.face.head(k) if clip.face.any() else None- if head is not None:- r = fr.to_output(head, k)- cx, cy = (r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2- self.items.append((t0, max(0.2, dur), float(z["scale"]), z["kind"], cx, cy))- self.items.sort(key=lambda x: x[0])-- def scale_at(self, t: float):- for t0, dur, s, kind, cx, cy in self.items:- if t0 <= t < t0 + dur:- u = t - t0- if kind == "punch":- k = _ease(u / self.PUNCH_IN) if u < self.PUNCH_IN else 1.0- if u > dur - self.PUNCH_OUT:- k = min(k, _ease((dur - u) / self.PUNCH_OUT))- else: # push: a slow ease in over the whole stretch, a short way back at the end- back = min(0.3, dur * 0.2)- k = _ease(u / (dur - back)) if u < dur - back else _ease((dur - u) / back)- return 1.0 + (s - 1.0) * k, cx, cy- return 1.0, 0.0, 0.0-- def apply(self, frame, j: int, t: float) -> None:- s, cx, cy = self.scale_at(t)- if s <= 1.001:- return- import cv2- import numpy as np-- w, h = OUT_W / s, OUT_H / s- x0 = min(max(cx - w / 2, 0.0), OUT_W - w)- y0 = min(max(cy - h * 0.42, 0.0), OUT_H - h)- m = np.array([[s, 0.0, -x0 * s], [0.0, s, -y0 * s]], np.float64)- frame[:] = cv2.warpAffine(frame, m, (OUT_W, OUT_H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)---# ---- squeeze the picture while a graphic needs the room above a close face ------------------------------------------class Squeeze:- """edit/graphics.mjs sets `squeeze` {scale, anchorY} on a graphic when the face fills the frame: during that- graphic the whole picture shrinks about (centre, anchorY) — the chin stays put, the top of the head comes down —- eased in 0.3 s and out 0.25 s; around it, the same picture blurred and darkened."""-- IN, OUT_ = 0.3, 0.25-- def __init__(self, edl: dict, tl):- self.items = [(tl.to_output_nearest(float(g["start"])), tl.to_output_nearest(float(g["end"])),- float(g["squeeze"]["scale"]), float(g["squeeze"]["anchorY"]))- for g in edl.get("graphics", []) if g.get("squeeze")]-- def at(self, t: float):- for t0, t1, k, ay in self.items:- if t0 <= t < t1:- e = min(_ease((t - t0) / self.IN), _ease((t1 - t) / self.OUT_))- return 1.0 - (1.0 - k) * e, ay- return 1.0, 0.0-- def apply(self, frame, t: float) -> None:- s, ay = self.at(t)- if s > 0.999:- return- import cv2- import numpy as np-- small = cv2.resize(frame, (OUT_W // 10, OUT_H // 10), interpolation=cv2.INTER_AREA)- bg = cv2.resize(cv2.GaussianBlur(small, (0, 0), 4), (OUT_W, OUT_H), interpolation=cv2.INTER_LINEAR)- m = np.array([[s, 0.0, OUT_W / 2 * (1 - s)], [0.0, s, ay * (1 - s)]], np.float64)- fg = cv2.warpAffine(frame, m, (OUT_W, OUT_H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)- x0, y0 = int(np.ceil(OUT_W / 2 * (1 - s))), int(np.ceil(ay * (1 - s)))- x1, y1 = int(np.floor(x0 + OUT_W * s)) - 1, int(np.floor(y0 + OUT_H * s)) - 1- out = (bg.astype(np.float32) * 0.5).astype(np.uint8)- out[y0:y1, x0:x1] = fg[y0:y1, x0:x1]- frame[:] = out---# ---- frosted glass under the graphics (edit/graphics.mjs draws the card itself in the HyperFrames layer) ------------class Glass:- """Blurs the video under each graphic's card (rounded box), fading in/out with the card, so the semi-dark card of the- overlay reads as frosted glass. Price tags and stickers are solid and get no glass."""-- ENTER, LEAVE, RADIUS = 0.15, 0.22, 38-- def __init__(self, edl: dict, tl):- import numpy as np-- self.items = []- for g in edl.get("graphics", []):- b = g.get("box")- # thẻ ghim (pinFirst) thu về 0,8× sau 3 s: vùng kính cố định sẽ lệch khỏi thẻ, nên không làm kính- if not b or g["type"] in ("price_tag", "sticker") or (g.get("data") or {}).get("pin"):- continue- x0, y0 = max(0, int(round(b["x"]))), max(0, int(round(b["y"])))- x1, y1 = min(OUT_W, int(round(b["x"] + b["w"]))), min(OUT_H, int(round(b["y"] + b["h"])))- if x1 - x0 < 8 or y1 - y0 < 8:- continue- r = max(4, int(self.RADIUS * float(b.get("scale", 1))))- yy, xx = np.mgrid[0:y1 - y0, 0:x1 - x0]- w, h = x1 - x0, y1 - y0- dx = np.maximum(np.maximum(r - xx, xx - (w - 1 - r)), 0)- dy = np.maximum(np.maximum(r - yy, yy - (h - 1 - r)), 0)- mask = np.clip(r + 0.5 - np.sqrt(dx * dx + dy * dy), 0, 1).astype(np.float32)[..., None]- self.items.append((tl.to_output_nearest(float(g["start"])), tl.to_output_nearest(float(g["end"])), x0, y0, x1, y1, mask))-- def apply(self, frame, t: float) -> None:- import cv2- import numpy as np-- for t0, t1, x0, y0, x1, y1, mask in self.items:- if not (t0 <= t < t1):- continue- a = min(_ease((t - t0) / self.ENTER), _ease((t1 - t) / self.LEAVE))- if a <= 0.01:- continue- reg = frame[y0:y1, x0:x1]- small = cv2.resize(reg, ((x1 - x0) // 4 or 1, (y1 - y0) // 4 or 1), interpolation=cv2.INTER_AREA)- blur = cv2.resize(cv2.GaussianBlur(small, (0, 0), 6), (x1 - x0, y1 - y0), interpolation=cv2.INTER_LINEAR)- m = mask * a- frame[y0:y1, x0:x1] = (reg.astype(np.float32) * (1 - m) + blur.astype(np.float32) * m).astype(np.uint8)---# ---- draft captions (PIL) ---------------------------------------------------------------------------------------STYLE_DRAFT = {- # text colour, highlight colour, active-word colour (None = no karaoke), size, uppercase- "sach-gon": ((255, 255, 255), (252, 232, 2), None, 76, False),- "phu-de-nay-mau": ((255, 255, 255), (252, 232, 2), (252, 232, 2), 92, True),-}---@lru_cache(maxsize=8)-def _font(size: int):- from PIL import ImageFont-- path = PACK / "fonts" / "BeVietnamPro" / "BeVietnamPro-800.ttf"- if not path.exists():- raise FileNotFoundError("Be Vietnam Pro is missing: run node edit/setup.mjs")- return ImageFont.truetype(str(path), size)---MIN_CARD, MERGE_BELOW = 0.25, 0.1---def caption_cards(edl: dict, tl) -> list[dict]:- """The caption words in cards of at most maxWords, broken at a sentence end or a pause, timed- in output seconds. Shared by the draft and (through the same rule in Node) the main captions."""- cap = edl["captions"]- most = int(cap["maxWords"])- cards, cur = [], []- words = cap["words"]- for n, w in enumerate(words):- cur.append(w)- nxt = words[n + 1] if n + 1 < len(words) else None- ends = w["w"].rstrip().endswith((".", "?", "!", ",", ":", ";", "…"))- gap = (nxt["start"] - w["end"]) if nxt else 99- if len(cur) >= most or ends or gap > 0.45 or nxt is None:- cards.append(cur)- cur = []- out = []- for c in cards:- out.append({"words": c, "start": tl.to_output_nearest(c[0]["start"]),- "end": tl.to_output_nearest(c[-1]["end"])})- out.sort(key=lambda c: c["start"])- # Same rule as finishCards in edit/captions-hf.mjs: bridge short gaps, at least MIN_CARD on screen,- # never past the next card's start (two cards are never on screen together), a card squeezed- # under MERGE_BELOW joins the next one.- for a, b in zip(out, out[1:]):- if 0 <= b["start"] - a["end"] < 0.4:- a["end"] = b["start"]- for c in out:- c["end"] = max(c["end"], c["start"] + MIN_CARD)- for a, b in zip(out, out[1:]):- a["end"] = min(a["end"], b["start"])- merged = []- for k, c in enumerate(out):- nxt = out[k + 1] if k + 1 < len(out) else None- if nxt is not None and c["end"] - c["start"] < MERGE_BELOW:- nxt["words"] = c["words"] + nxt["words"]- nxt["start"] = c["start"]- continue- merged.append(c)- for c in merged:- c["word_out"] = [max(c["start"], tl.to_output_nearest(w["start"])) for w in c["words"]]- for a, b in zip(merged, merged[1:]):- if a["end"] > b["start"] + 1e-6:- raise ValueError(f"captions overlap at {b['start']:.2f} s")- return merged---class DraftCaptions:- def __init__(self, edl: dict, tl):- cap = edl["captions"]- self.cards = caption_cards(edl, tl)- self.hi = set(cap["highlights"])- self.base, self.hcol, self.active, self.size, self.upper = STYLE_DRAFT.get(cap["style"], STYLE_DRAFT["sach-gon"])- self.cy = OUT_H * (0.70 if cap["position"] == "lower" else 0.58)- self.cache: dict = {}-- def sprite(self, ci: int, active: int):- key = (ci, active)- if key in self.cache:- return self.cache[key]- import numpy as np- from PIL import Image, ImageDraw-- card = self.cards[ci]- font = _font(self.size)- maxw = (SAFE[2] - SAFE[0]) * OUT_W - 20- # trailing , . ; : are not shown (? ! … stay), as in the HyperFrames captions- toks = [((w["w"].rstrip(",.;:") or w["w"]), w["i"]) for w in card["words"]]- toks = [(t.upper() if self.upper else t, i) for t, i in toks]- space = font.getlength(" ")- lines, line, lw = [], [], 0.0- for text, i in toks:- tw = font.getlength(text)- if line and lw + space + tw > maxw:- lines.append(line)- line, lw = [], 0.0- line.append((text, i, tw))- lw += (space if len(line) > 1 else 0) + tw- if line:- lines.append(line)- lh = int(self.size * 1.22)- stroke = max(4, self.size // 11)- W, H = int(maxw + 2 * stroke + 8), lh * len(lines) + 2 * stroke + 8- img = Image.new("RGBA", (W, H), (0, 0, 0, 0))- d = ImageDraw.Draw(img)- for li, ln in enumerate(lines):- total = sum(t[2] for t in ln) + space * (len(ln) - 1)- x = (W - total) / 2- y = stroke + 4 + li * lh- for k, (text, i, tw) in enumerate(ln):- col = self.base- if i in self.hi:- col = self.hcol- if self.active is not None and i == active:- col = self.active- d.text((x, y), text, font=font, fill=col + (255,), stroke_width=stroke, stroke_fill=(0, 0, 0, 255))- x += tw + space- arr = np.asarray(img)- self.cache[key] = arr- return arr-- def rect(self, ci: int):- a = self.sprite(ci, -1)- h, w = a.shape[:2]- x0 = int(round((OUT_W - w) / 2))- y0 = int(round(min(self.cy - h / 2, SAFE[3] * OUT_H - h)))- return x0, y0, w, h-- def draw(self, frame, t: float) -> None:- import numpy as np-- for ci, c in enumerate(self.cards):- if c["start"] <= t < c["end"]:- active = -1- for w, wo in zip(c["words"], c["word_out"]):- if t >= wo:- active = w["i"]- spr = self.sprite(ci, active)- x0, y0, w, h = self.rect(ci)- region = frame[y0:y0 + h, x0:x0 + w]- alpha = spr[:, :, 3:4].astype(np.float32) / 255.0- region[:] = (spr[:, :, :3] * alpha + region * (1 - alpha)).astype(np.uint8)- return---# ---- render / stills ----------------------------------------------------------------------------------------------def cmd_render(edl_path: Path, out: Path, draft_captions: bool, check: bool) -> dict:- from fx.core import render as rmod-- edl = load_edl(edl_path)- t0 = time.time()- clip, tl, fr, draw = build(edl, draft_captions)- n = tl.output_frames(clip.info.rate)- last = [0.0]-- def drawing(frame, j, t):- draw(frame, j, t)- now = time.time()- if now - last[0] > 2.0 or j == n - 1:- last[0] = now- progress("render", done=j + 1, total=n, pct=round(100 * (j + 1) / n))-- out.parent.mkdir(parents=True, exist_ok=True)- fade = float(edl["audio"]["crossfadeMs"]) / 1000.0- res = rmod.render(clip, tl, fr, drawing, out, fade=fade, crf=18)- t_render = time.time() - t0- result = {"out": res["path"], "frames": res["frames"], "seconds_out": res["seconds_out"],- "joins": len(tl.joins), "framing": fr.note, "seconds": {"render": round(t_render, 1)}}- if check:- progress("overcut-check", note="nghe lại bản cắt, so từng chữ")- from fx.effects.clean_cut import overcut_check-- t1 = time.time()- kept = [w for w in clip.words if tl.to_output((w.start + w.end) / 2) is not None]- oc = overcut_check(clip, kept, tl, Path(out), None)- result["overcut"] = {k: oc[k] for k in ("verdict", "lost", "chopped", "left_at_cut", "matched", "kept",- "joins", "joins_cut_in_silence", "median_start_offset_s")}- result["seconds"]["overcut_check"] = round(time.time() - t1, 1)- return result---def cmd_stills(edl_path: Path, out: Path, count: int, draft_captions: bool) -> dict:- from PIL import Image, ImageDraw-- from fx.core import render as rmod-- edl = load_edl(edl_path)- clip, tl, fr, draw = build(edl, draft_captions)- dur = tl.duration- times = [dur * (i + 0.5) / count for i in range(count)]- frames = rmod.still_frames(clip, tl, fr, draw, times)- cols = int(math.ceil(math.sqrt(count)))- rows = int(math.ceil(count / cols))- tw, th = 270, 480- sheet = Image.new("RGB", (cols * tw + (cols + 1) * 6, rows * (th + 32) + (rows + 1) * 6), (24, 24, 24))- d = ImageDraw.Draw(sheet)- for n, (t, f) in enumerate(frames):- img = Image.fromarray(f).resize((tw, th), Image.LANCZOS)- x, y = 6 + (n % cols) * (tw + 6), 6 + (n // cols) * (th + 32)- sheet.paste(img, (x, y))- d.text((x + 4, y + th + 6), f"{t:5.2f} s", fill=(230, 230, 230))- sheet.save(out, quality=88)- return {"out": str(out), "times": [round(t, 2) for t in times]}---# What a graphic must keep clear of: the detector's own box (BlazeFace's box already runs wide of the cheeks and-# below the chin) grown upward for the hair. Measured on the founder's review clip (28/11/2026): `head()` (+60% up,-# +20% sides) came out about twice the visible head and left no room for any graphic in a close talking-head shot.-GRAPHIC_HEAD = {"left": 0.04, "top": 0.20, "right": 0.04, "bottom": 0.04}---def _graphic_head(face, k: int, near: int):- """The face at source frame k from the detector's own boxes (the nearest within `near` frames; the detector runs- on every frame but misses some), so B-roll without a face leaves the whole frame to the graphics; None when no- face is there. Boxes of implausible size are ignored."""- import numpy as np-- from fx.core.layout import Rect-- lo, hi = max(0, k - near), min(face.n - 1, k + near)- best = None- for i in range(lo, hi + 1):- x = face.raw[i, 0]- if not np.isnan(x) and not (0.05 * face.height <= face.raw[i, 3] <= 0.7 * face.height):- continue- if np.isnan(x) or (best is not None and abs(i - k) >= abs(best - k)):- continue- best = i- if best is None:- return None- x, y, w, h, _ = face.raw[best]- g = GRAPHIC_HEAD- return Rect(x - g["left"] * w, y - g["top"] * h, x + w + g["right"] * w, y + h + g["bottom"] * h)---def cmd_faces(edl_path: Path, out: Path, step: float) -> dict:- """Head box in OUTPUT pixels (after reframe and zoom) every `step` s of the output: what graphics must avoid."""- edl = load_edl(edl_path)- clip, tl, fr, _draw = build(edl, False)- zooms = Zooms(edl, tl, fr, clip)- fps = clip.info.rate- rows = []- n = int(tl.duration / step) + 1- face = clip.face if clip.face.any() else None- near = int(round(0.5 * fps))- for m in range(n):- t = min(tl.duration, m * step)- k = tl.source_frame(int(round(t * fps)), fps, clip.info.frames)- head = _graphic_head(face, k, near) if face is not None else None- if head is None:- rows.append([round(t, 3), None])- continue- r = fr.to_output(head, k)- x0, y0, x1, y1 = r.x0, r.y0, r.x1, r.y1- s, cx, cy = zooms.scale_at(t)- if s > 1.001:- w, h = OUT_W / s, OUT_H / s- ox = min(max(cx - w / 2, 0.0), OUT_W - w)- oy = min(max(cy - h * 0.42, 0.0), OUT_H - h)- x0, x1, y0, y1 = (x0 - ox) * s, (x1 - ox) * s, (y0 - oy) * s, (y1 - oy) * s- bx = [round(max(0, x0)), round(max(0, y0)), round(min(OUT_W, x1)), round(min(OUT_H, y1))]- rows.append([round(t, 3), bx if bx[2] - bx[0] > 8 and bx[3] - bx[1] > 8 else None])- data = {"step": step, "found_share": round(float(clip.face.found_share), 3) if clip.face.any() else 0.0, "boxes": rows}- out.write_text(json.dumps(data), encoding="utf-8")- return {"out": str(out), "samples": len(rows)}---# ---- hear stretches again on their own --------------------------------------------------------------------------def cmd_hear(proxy: Path, spans_arg: str, out: Path) -> dict:- """Each span of the proxy heard on its own (the pack's second listen, cached in the words cache): what the- planner uses to check a figure before it goes on a graphic. spans_arg: "a-b,c-d" in source seconds."""- from fx.core import words as wordsmod-- spans = []- for part in spans_arg.split(","):- a, b = part.split("-")- spans.append((round(float(a), 2), round(float(b), 2)))- heard = wordsmod.relisten(proxy, spans, "small.en")- data = {k: [{"text": seg["text"], "avg_logprob": round(float(seg["avg_logprob"]), 3),- "words": [{"w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "p": round(w.prob, 3)} for w in seg["words"]]}- for seg in segs] for k, segs in heard.items()}- out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")- return {"out": str(out), "spans": len(data)}---# ---- qc -----------------------------------------------------------------------------------------------------------def cmd_qc(video_path: Path, out: Path) -> dict:- from fx.effects import qc_check-- r = qc_check.check(video_path, None, "reels", False, out.with_suffix(".md"))- findings = [{"check": f.check, "level": f.level, "what": f.what, "fix": f.fix} for f in r["findings"]]- data = {"verdict": r["verdict"], "findings": findings, "report": str(r["report"]), "sheet": str(r["sheet"]),- "seconds": round(r["seconds"], 1)}- out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")- return data---def main(argv=None) -> int:- ap = argparse.ArgumentParser(prog="lumedit")- sub = ap.add_subparsers(dest="cmd", required=True)- a = sub.add_parser("analyze"); a.add_argument("proxy"); a.add_argument("--out", required=True)- r = sub.add_parser("render"); r.add_argument("edl"); r.add_argument("--out", required=True)- r.add_argument("--draft-captions", action="store_true"); r.add_argument("--no-check", action="store_true")- s = sub.add_parser("stills"); s.add_argument("edl"); s.add_argument("--out", required=True)- s.add_argument("--count", type=int, default=16); s.add_argument("--draft-captions", action="store_true")- f = sub.add_parser("faces"); f.add_argument("edl"); f.add_argument("--out", required=True)- f.add_argument("--step", type=float, default=0.25)- h = sub.add_parser("hear"); h.add_argument("proxy"); h.add_argument("--spans", required=True)- h.add_argument("--out", required=True)- q = sub.add_parser("qc"); q.add_argument("video"); q.add_argument("--out", required=True)- args = ap.parse_args(argv)- try:- if args.cmd == "analyze":- res = cmd_analyze(Path(args.proxy).resolve(), Path(args.out).resolve())- elif args.cmd == "render":- res = cmd_render(Path(args.edl).resolve(), Path(args.out).resolve(), args.draft_captions, not args.no_check)- elif args.cmd == "stills":- res = cmd_stills(Path(args.edl).resolve(), Path(args.out).resolve(), args.count, args.draft_captions)- elif args.cmd == "hear":- res = cmd_hear(Path(args.proxy).resolve(), args.spans, Path(args.out).resolve())- elif args.cmd == "faces":- res = cmd_faces(Path(args.edl).resolve(), Path(args.out).resolve(), args.step)- else:- res = cmd_qc(Path(args.video).resolve(), Path(args.out).resolve())- except (ValueError, KeyError, FileNotFoundError) as e:- emit("result", {"ok": False, "error": f"{type(e).__name__}: {e}"})- traceback.print_exc()- return 2- except Exception as e: # noqa: BLE001- from fx.core.paths import NeedSetup-- emit("result", {"ok": False, "error": f"{type(e).__name__}: {e}"})- traceback.print_exc()- return 3 if isinstance(e, NeedSetup) else 1- emit("result", {"ok": True, **res})- return 0---if __name__ == "__main__":- sys.exit(main())+"""LumReels Edit: the Python side, built on the AskEditor pack's core (edit/askeditor/fx, MIT).++ python -X utf8 lumedit.py analyze <proxy.mp4> --out analysis.json+ python -X utf8 lumedit.py render <edl.json> --out base.mp4 [--draft-captions] [--no-check]+ python -X utf8 lumedit.py stills <edl.json> --out preview.jpg [--count 16] [--draft-captions]+ python -X utf8 lumedit.py hear <proxy.mp4> --spans a-b,c-d --out heard.json+ python -X utf8 lumedit.py qc <final.mp4> --out qc.json++Talks to Node line by line: `@progress {json}` while it works, and one `@result {json}` at the end+({"ok": true, ...} or {"ok": false, "error": "..."}). Exit 0 on success, 2 on bad input, 3 when setup+is missing, 1 on any other failure.++Everything in an EDL is in source seconds; the proxy shares the source's time axis. The render is+one pass: AskEditor's Timeline (the kept stretches, with the source sound joined by 20 ms+crossfades) and Framing (9:16 window following the face), then our zooms and draft captions drawn+on each output frame.+"""++from __future__ import annotations++import argparse+import json+import math+import os+import sys+import time+import traceback+from functools import lru_cache+from pathlib import Path++PACK = Path(__file__).resolve().parents[1] / "askeditor"+sys.path.insert(0, str(PACK))+os.environ.setdefault("GLOG_minloglevel", "2")+os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3")++OUT_W, OUT_H, OUT_FPS = 1080, 1920, 30+SAFE = (120 / 1080, 0.10, 960 / 1080, 0.80) # x0, y0, x1, y1 as shares of the frame+++def emit(kind: str, obj: dict) -> None:+ print(f"@{kind} " + json.dumps(obj, ensure_ascii=False), flush=True)+++def progress(step: str, **kw) -> None:+ emit("progress", {"step": step, **kw})+++# ---- analyze ---------------------------------------------------------------------------------------------++def cmd_analyze(proxy: Path, out: Path) -> dict:+ from fx.core.clip import Clip+ from fx.core import words as wordsmod++ t0 = time.time()+ clip = Clip(proxy)+ info = clip.info+ progress("words", note=f"chép lời ({os.environ.get('FX_WHISPER') or 'small.en'}, {wordsmod.LANG})")+ ws = clip.words+ t_words = time.time() - t0+ try: # where whisper ran (cuda float16 | cpu int8 (why)), recorded in the words cache by fx.core.words+ from fx.core import paths as pathsmod+ device = json.loads(pathsmod.beside(proxy.resolve(), "words.json").read_text(encoding="utf-8")).get("device") or "?"+ except (OSError, ValueError):+ device = "?"+ progress("words", note=f"whisper {device}")+ progress("quiet")+ quiet = clip.quiet+ progress("face")+ t1 = time.time()+ face = clip.face+ t_face = time.time() - t1+ fps = info.rate+ faces = []+ step = max(1, int(round(fps / 2)))+ for i in range(0, info.frames, step):+ b = face.box(i) if face.any() else None+ faces.append(None if b is None else [round(i / fps, 2), round(b.x0), round(b.y0), round(b.w), round(b.h)])+ data = {+ "proxy": str(proxy), "duration": round(info.duration, 3), "fps": fps, "frames": info.frames,+ "width": info.width, "height": info.height,+ "words": [{"i": i, "w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "p": round(w.prob, 3)}+ for i, w in enumerate(ws)],+ "unsure": [{"w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "why": w.unsure} for w in clip.unsure],+ "quiet": [[round(a, 3), round(b, 3)] for a, b in quiet],+ "face": {"found_share": round(float(face.found_share), 3) if face.any() else 0.0,+ "every_half_second": [f for f in faces if f is not None]},+ # The speech-band loudness in 10 ms steps (whole dB), so the planner can put every cut at a real break in+ # the voice instead of at the transcriber's word edges, which run up to 0.2 s off on Vietnamese.+ "env": {"hop": clip.envelope.hop, "floor": round(clip.envelope.floor, 2), "speech": round(clip.envelope.speech, 2),+ "threshold": round(clip.envelope.threshold, 2), "db": [int(round(float(x))) for x in clip.envelope.db]},+ "hesitations": sorted(wordsmod.HESITATIONS),+ "model": wordsmod.model_key("small.en"), "lang": wordsmod.LANG,+ "seconds": {"words": round(t_words, 1), "face": round(t_face, 1), "total": round(time.time() - t0, 1)},+ "whisper_device": device,+ }+ out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")+ return {"out": str(out), "words": len(ws), "unsure": len(clip.unsure), "seconds": data["seconds"], "device": device}+++# ---- shared: the EDL as AskEditor objects ------------------------------------------------------------------++def load_edl(path: Path) -> dict:+ edl = json.loads(path.read_text(encoding="utf-8"))+ if edl.get("version") != 1:+ raise ValueError(f"EDL version {edl.get('version')!r} is not supported (want 1)")+ return edl+++def build(edl: dict, draft_captions: bool, glass_on: bool = True):+ from fx.core import framing as framing_mod+ from fx.core.clip import Clip+ from fx.core.timeline import Timeline++ clip = Clip(edl["proxy"]["file"])+ info = clip.info+ if abs(info.rate - OUT_FPS) > 0.01:+ raise ValueError(f"the proxy runs at {info.rate} fps; it must be the 30 fps proxy")+ segs = tuple((float(k["start"]), min(float(k["end"]), info.duration)) for k in edl["keep"])+ segs = tuple((a, b) for a, b in segs if b - a > 1e-3)+ tl = hook_timeline(Timeline, segs, edl.get("hook"), info.duration)+ mode = edl["reframe"]["mode"]+ face = clip.face if mode == "face" else None+ fr = framing_mod.plan(info.width, info.height, info.rate, info.frames, face, shape="9:16",+ size=(OUT_W, OUT_H), mode={"face": "track", "center": "center", "fill": "fill",+ "none": "center"}[mode])+ if (fr.out_w, fr.out_h) != (OUT_W, OUT_H):+ fr.out_w, fr.out_h = OUT_W, OUT_H+ zooms = Zooms(edl, tl, fr, clip)+ # glass_on=False: kính mờ dưới đồ hoạ vẽ ở bước ghép (ffmpeg), dời giờ đồ hoạ không phải render lại nền+ glass = Glass(edl, tl) if glass_on and edl.get("graphics") else None+ squeeze = Squeeze(edl, tl) if any(g.get("squeeze") for g in edl.get("graphics", [])) else None+ caps = DraftCaptions(edl, tl) if draft_captions and edl["captions"]["words"] else None+ quote = QuoteDim(edl, tl) if edl.get("quote") else None+ hook = edl.get("hook") or None+ flash_at = (float(hook["end"]) - float(hook["start"])) if hook and hook.get("flash") else None++ def draw(frame, j, t):+ zooms.apply(frame, j, t)+ if squeeze is not None:+ squeeze.apply(frame, t)+ if quote is not None:+ quote.apply(frame, t)+ if glass is not None:+ glass.apply(frame, t)+ if caps is not None:+ caps.draw(frame, t)+ # chớp trắng 2 khung ở chỗ nối câu móc → clip+ if flash_at is not None and flash_at - 1e-3 <= t < flash_at + 2.0 / OUT_FPS - 1e-3:+ frame[:] = 255++ return clip, tl, fr, draw+++# ---- the hook pulled to the front ---------------------------------------------------------------------------++def hook_timeline(Timeline, segs, hook, duration):+ """The output plays the hook (edl.hook, source seconds) first, then the kept stretches. Playing (to_source,+ sample_ranges, joins) works on any order of segments; only source → output needs care: a moment inside a kept+ stretch lands there (after the hook), a moment only in the hook (repeat: false) lands at 0 … hook length."""+ if not hook:+ return Timeline(segs)+ from dataclasses import dataclass++ @dataclass(frozen=True)+ class HookTimeline(Timeline):+ def _play(self, t):+ (h0, h1), rest = self.segments[0], self.segments[1:]+ acc = h1 - h0+ for a, b in rest:+ if t < a - 1e-9:+ break+ if t <= b + 1e-9:+ return acc + (t - a)+ acc += b - a+ if h0 - 1e-9 <= t <= h1 + 1e-9:+ return t - h0+ return None++ def to_output_nearest(self, t):+ got = self.to_output(t)+ if got is not None:+ return got+ best, best_d = 0.0, math.inf+ for a, b in self.segments[1:]:+ for src in (a, b):+ if abs(src - t) < best_d:+ best, best_d = self.to_output(src), abs(src - t)+ return best++ h = (float(hook["start"]), min(float(hook["end"]), duration))+ return HookTimeline((h,) + tuple(segs))+++class QuoteDim:+ """edl.quote: while the quote is on screen the video dims to `dimTo` and blurs `blurPx`, eased in over `dimIn` s;+ held to the end when the quote closes the clip, else eased back out in 0.4 s (the quote block itself is drawn in+ the HyperFrames layer)."""++ def __init__(self, edl: dict, tl):+ q = edl["quote"]+ self.t0 = tl.to_output_nearest(float(q["start"]))+ q1 = tl.to_output_nearest(float(q["end"]))+ self.t1 = tl.duration + 1.0 if q1 >= tl.duration - 2.0 else min(tl.duration, q1 + 0.8)+ self.dim, self.blur, self.din = float(q["dimTo"]), float(q["blurPx"]), max(0.1, float(q["dimIn"]))++ def apply(self, frame, t: float) -> None:+ if not (self.t0 <= t < self.t1):+ return+ e = min(_ease((t - self.t0) / self.din), _ease((self.t1 - t) / 0.4))+ if e <= 0.01:+ return+ import cv2+ import numpy as np++ img = frame+ sigma = self.blur * e+ if sigma > 0.3:+ small = cv2.resize(frame, (OUT_W // 4, OUT_H // 4), interpolation=cv2.INTER_AREA)+ img = cv2.resize(cv2.GaussianBlur(small, (0, 0), sigma / 4), (OUT_W, OUT_H), interpolation=cv2.INTER_LINEAR)+ k = 1.0 - (1.0 - self.dim) * e+ frame[:] = (img.astype(np.float32) * k).astype(np.uint8)+++# ---- zooms ---------------------------------------------------------------------------------------------------++def _ease(x: float) -> float:+ x = min(1.0, max(0.0, x))+ return x * x * (3 - 2 * x)+++class Zooms:+ """Each zoom of the EDL on the output picture: a punch (in fast, hold, out) or a slow push, about+ the face where the zoom begins (or the upper middle of the frame when no face is found)."""++ PUNCH_IN, PUNCH_OUT = 0.08, 0.12++ def __init__(self, edl: dict, tl, fr, clip):+ self.items = []+ fps = clip.info.rate+ hook = edl.get("hook") or None+ hd = float(hook["end"]) - float(hook["start"]) if hook else 0.0+ for z in edl["zooms"]:+ at = float(z["at"])+ t_out = [(tl.to_output_nearest(at), float(z["dur"]))]+ # câu móc lặp lại: cú zoom trong câu móc chạy cả ở đầu clip (không tràn qua chỗ nối)+ if hook and hook.get("repeat") and float(hook["start"]) <= at <= float(hook["end"]):+ t_h = at - float(hook["start"])+ t_out.append((t_h, min(float(z["dur"]), hd - t_h)))+ for t0, dur in t_out:+ k = tl.source_frame(int(round(t0 * fps)), fps, clip.info.frames)+ cx, cy = OUT_W / 2, OUT_H * 0.40+ head = clip.face.head(k) if clip.face.any() else None+ if head is not None:+ r = fr.to_output(head, k)+ cx, cy = (r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2+ self.items.append((t0, max(0.2, dur), float(z["scale"]), z["kind"], cx, cy))+ self.items.sort(key=lambda x: x[0])++ def scale_at(self, t: float):+ for t0, dur, s, kind, cx, cy in self.items:+ if t0 <= t < t0 + dur:+ u = t - t0+ if kind == "punch":+ k = _ease(u / self.PUNCH_IN) if u < self.PUNCH_IN else 1.0+ if u > dur - self.PUNCH_OUT:+ k = min(k, _ease((dur - u) / self.PUNCH_OUT))+ else: # push: a slow ease in over the whole stretch, a short way back at the end+ back = min(0.3, dur * 0.2)+ k = _ease(u / (dur - back)) if u < dur - back else _ease((dur - u) / back)+ return 1.0 + (s - 1.0) * k, cx, cy+ return 1.0, 0.0, 0.0++ def apply(self, frame, j: int, t: float) -> None:+ s, cx, cy = self.scale_at(t)+ if s <= 1.001:+ return+ import cv2+ import numpy as np++ w, h = OUT_W / s, OUT_H / s+ x0 = min(max(cx - w / 2, 0.0), OUT_W - w)+ y0 = min(max(cy - h * 0.42, 0.0), OUT_H - h)+ m = np.array([[s, 0.0, -x0 * s], [0.0, s, -y0 * s]], np.float64)+ frame[:] = cv2.warpAffine(frame, m, (OUT_W, OUT_H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)+++# ---- squeeze the picture while a graphic needs the room above a close face ----------------------------------------++class Squeeze:+ """edit/graphics.mjs sets `squeeze` {scale, anchorY} on a graphic when the face fills the frame: during that+ graphic the whole picture shrinks about (centre, anchorY) — the chin stays put, the top of the head comes down —+ eased in 0.3 s and out 0.25 s; around it, the same picture blurred and darkened."""++ IN, OUT_ = 0.3, 0.25++ def __init__(self, edl: dict, tl):+ self.items = [(tl.to_output_nearest(float(g["start"])), tl.to_output_nearest(float(g["end"])),+ float(g["squeeze"]["scale"]), float(g["squeeze"]["anchorY"]))+ for g in edl.get("graphics", []) if g.get("squeeze")]++ def at(self, t: float):+ for t0, t1, k, ay in self.items:+ if t0 <= t < t1:+ e = min(_ease((t - t0) / self.IN), _ease((t1 - t) / self.OUT_))+ return 1.0 - (1.0 - k) * e, ay+ return 1.0, 0.0++ def apply(self, frame, t: float) -> None:+ s, ay = self.at(t)+ if s > 0.999:+ return+ import cv2+ import numpy as np++ small = cv2.resize(frame, (OUT_W // 10, OUT_H // 10), interpolation=cv2.INTER_AREA)+ bg = cv2.resize(cv2.GaussianBlur(small, (0, 0), 4), (OUT_W, OUT_H), interpolation=cv2.INTER_LINEAR)+ m = np.array([[s, 0.0, OUT_W / 2 * (1 - s)], [0.0, s, ay * (1 - s)]], np.float64)+ fg = cv2.warpAffine(frame, m, (OUT_W, OUT_H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)+ x0, y0 = int(np.ceil(OUT_W / 2 * (1 - s))), int(np.ceil(ay * (1 - s)))+ x1, y1 = int(np.floor(x0 + OUT_W * s)) - 1, int(np.floor(y0 + OUT_H * s)) - 1+ out = (bg.astype(np.float32) * 0.5).astype(np.uint8)+ out[y0:y1, x0:x1] = fg[y0:y1, x0:x1]+ frame[:] = out+++# ---- frosted glass under the graphics (edit/graphics.mjs draws the card itself in the HyperFrames layer) ----------++class Glass:+ """Blurs the video under each graphic's card (rounded box), fading in/out with the card, so the semi-dark card of the+ overlay reads as frosted glass. Price tags and stickers are solid and get no glass."""++ ENTER, LEAVE, RADIUS = 0.15, 0.22, 38++ def __init__(self, edl: dict, tl):+ import numpy as np++ self.items = []+ for g in edl.get("graphics", []):+ b = g.get("box")+ # thẻ ghim (pinFirst) thu về 0,8× sau 3 s: vùng kính cố định sẽ lệch khỏi thẻ, nên không làm kính+ if not b or g["type"] in ("price_tag", "sticker") or (g.get("data") or {}).get("pin"):+ continue+ x0, y0 = max(0, int(round(b["x"]))), max(0, int(round(b["y"])))+ x1, y1 = min(OUT_W, int(round(b["x"] + b["w"]))), min(OUT_H, int(round(b["y"] + b["h"])))+ if x1 - x0 < 8 or y1 - y0 < 8:+ continue+ r = max(4, int(self.RADIUS * float(b.get("scale", 1))))+ yy, xx = np.mgrid[0:y1 - y0, 0:x1 - x0]+ w, h = x1 - x0, y1 - y0+ dx = np.maximum(np.maximum(r - xx, xx - (w - 1 - r)), 0)+ dy = np.maximum(np.maximum(r - yy, yy - (h - 1 - r)), 0)+ mask = np.clip(r + 0.5 - np.sqrt(dx * dx + dy * dy), 0, 1).astype(np.float32)[..., None]+ self.items.append((tl.to_output_nearest(float(g["start"])), tl.to_output_nearest(float(g["end"])), x0, y0, x1, y1, mask))++ def apply(self, frame, t: float) -> None:+ import cv2+ import numpy as np++ for t0, t1, x0, y0, x1, y1, mask in self.items:+ if not (t0 <= t < t1):+ continue+ a = min(_ease((t - t0) / self.ENTER), _ease((t1 - t) / self.LEAVE))+ if a <= 0.01:+ continue+ reg = frame[y0:y1, x0:x1]+ small = cv2.resize(reg, ((x1 - x0) // 4 or 1, (y1 - y0) // 4 or 1), interpolation=cv2.INTER_AREA)+ blur = cv2.resize(cv2.GaussianBlur(small, (0, 0), 6), (x1 - x0, y1 - y0), interpolation=cv2.INTER_LINEAR)+ m = mask * a+ frame[y0:y1, x0:x1] = (reg.astype(np.float32) * (1 - m) + blur.astype(np.float32) * m).astype(np.uint8)+++# ---- draft captions (PIL) -------------------------------------------------------------------------------------++STYLE_DRAFT = {+ # text colour, highlight colour, active-word colour (None = no karaoke), size, uppercase+ "sach-gon": ((255, 255, 255), (252, 232, 2), None, 76, False),+ "phu-de-nay-mau": ((255, 255, 255), (252, 232, 2), (252, 232, 2), 92, True),+}+++@lru_cache(maxsize=8)+def _font(size: int):+ from PIL import ImageFont++ path = PACK / "fonts" / "BeVietnamPro" / "BeVietnamPro-800.ttf"+ if not path.exists():+ raise FileNotFoundError("Be Vietnam Pro is missing: run node edit/setup.mjs")+ return ImageFont.truetype(str(path), size)+++MIN_CARD, MERGE_BELOW = 0.25, 0.1+++def caption_cards(edl: dict, tl) -> list[dict]:+ """The caption words in cards of at most maxWords, broken at a sentence end or a pause, timed+ in output seconds. Shared by the draft and (through the same rule in Node) the main captions."""+ cap = edl["captions"]+ most = int(cap["maxWords"])+ cards, cur = [], []+ words = cap["words"]+ for n, w in enumerate(words):+ cur.append(w)+ nxt = words[n + 1] if n + 1 < len(words) else None+ ends = w["w"].rstrip().endswith((".", "?", "!", ",", ":", ";", "…"))+ gap = (nxt["start"] - w["end"]) if nxt else 99+ if len(cur) >= most or ends or gap > 0.45 or nxt is None:+ cards.append(cur)+ cur = []+ out = []+ for c in cards:+ out.append({"words": c, "start": tl.to_output_nearest(c[0]["start"]),+ "end": tl.to_output_nearest(c[-1]["end"])})+ out.sort(key=lambda c: c["start"])+ # Same rule as finishCards in edit/captions-hf.mjs: bridge short gaps, at least MIN_CARD on screen,+ # never past the next card's start (two cards are never on screen together), a card squeezed+ # under MERGE_BELOW joins the next one.+ for a, b in zip(out, out[1:]):+ if 0 <= b["start"] - a["end"] < 0.4:+ a["end"] = b["start"]+ for c in out:+ c["end"] = max(c["end"], c["start"] + MIN_CARD)+ for a, b in zip(out, out[1:]):+ a["end"] = min(a["end"], b["start"])+ merged = []+ for k, c in enumerate(out):+ nxt = out[k + 1] if k + 1 < len(out) else None+ if nxt is not None and c["end"] - c["start"] < MERGE_BELOW:+ nxt["words"] = c["words"] + nxt["words"]+ nxt["start"] = c["start"]+ continue+ merged.append(c)+ for c in merged:+ c["word_out"] = [max(c["start"], tl.to_output_nearest(w["start"])) for w in c["words"]]+ for a, b in zip(merged, merged[1:]):+ if a["end"] > b["start"] + 1e-6:+ raise ValueError(f"captions overlap at {b['start']:.2f} s")+ return merged+++class DraftCaptions:+ def __init__(self, edl: dict, tl):+ cap = edl["captions"]+ self.cards = caption_cards(edl, tl)+ self.hi = set(cap["highlights"])+ self.base, self.hcol, self.active, self.size, self.upper = STYLE_DRAFT.get(cap["style"], STYLE_DRAFT["sach-gon"])+ self.cy = OUT_H * (0.70 if cap["position"] == "lower" else 0.58)+ self.cache: dict = {}++ def sprite(self, ci: int, active: int):+ key = (ci, active)+ if key in self.cache:+ return self.cache[key]+ import numpy as np+ from PIL import Image, ImageDraw++ card = self.cards[ci]+ font = _font(self.size)+ maxw = (SAFE[2] - SAFE[0]) * OUT_W - 20+ # trailing , . ; : are not shown (? ! … stay), as in the HyperFrames captions+ toks = [((w["w"].rstrip(",.;:") or w["w"]), w["i"]) for w in card["words"]]+ toks = [(t.upper() if self.upper else t, i) for t, i in toks]+ space = font.getlength(" ")+ lines, line, lw = [], [], 0.0+ for text, i in toks:+ tw = font.getlength(text)+ if line and lw + space + tw > maxw:+ lines.append(line)+ line, lw = [], 0.0+ line.append((text, i, tw))+ lw += (space if len(line) > 1 else 0) + tw+ if line:+ lines.append(line)+ lh = int(self.size * 1.22)+ stroke = max(4, self.size // 11)+ W, H = int(maxw + 2 * stroke + 8), lh * len(lines) + 2 * stroke + 8+ img = Image.new("RGBA", (W, H), (0, 0, 0, 0))+ d = ImageDraw.Draw(img)+ for li, ln in enumerate(lines):+ total = sum(t[2] for t in ln) + space * (len(ln) - 1)+ x = (W - total) / 2+ y = stroke + 4 + li * lh+ for k, (text, i, tw) in enumerate(ln):+ col = self.base+ if i in self.hi:+ col = self.hcol+ if self.active is not None and i == active:+ col = self.active+ d.text((x, y), text, font=font, fill=col + (255,), stroke_width=stroke, stroke_fill=(0, 0, 0, 255))+ x += tw + space+ arr = np.asarray(img)+ self.cache[key] = arr+ return arr++ def rect(self, ci: int):+ a = self.sprite(ci, -1)+ h, w = a.shape[:2]+ x0 = int(round((OUT_W - w) / 2))+ y0 = int(round(min(self.cy - h / 2, SAFE[3] * OUT_H - h)))+ return x0, y0, w, h++ def draw(self, frame, t: float) -> None:+ import numpy as np++ for ci, c in enumerate(self.cards):+ if c["start"] <= t < c["end"]:+ active = -1+ for w, wo in zip(c["words"], c["word_out"]):+ if t >= wo:+ active = w["i"]+ spr = self.sprite(ci, active)+ x0, y0, w, h = self.rect(ci)+ region = frame[y0:y0 + h, x0:x0 + w]+ alpha = spr[:, :, 3:4].astype(np.float32) / 255.0+ region[:] = (spr[:, :, :3] * alpha + region * (1 - alpha)).astype(np.uint8)+ return+++# ---- render / stills --------------------------------------------------------------------------------------------++def cmd_render(edl_path: Path, out: Path, draft_captions: bool, check: bool, glass_on: bool = True,+ clean_out: Path | None = None) -> dict:+ from fx.core import render as rmod+ from fx.core import video as vmod++ edl = load_edl(edl_path)+ t0 = time.time()+ clip, tl, fr, draw = build(edl, draft_captions, glass_on)+ n = tl.output_frames(clip.info.rate)+ last = [0.0]+ # clean_out: cùng lượt đọc, ghi thêm bản 540×960 TRƯỚC zoom/thu hình/kính/chữ nháp (Studio xem trước, zoom chạy bằng CSS)+ clean = vmod.FrameWriter(clean_out, OUT_W // 2, OUT_H // 2, clip.info.fps, audio=None, crf=26, preset="veryfast") if clean_out else None++ def drawing(frame, j, t):+ if clean is not None:+ import cv2++ clean.write(cv2.resize(frame, (OUT_W // 2, OUT_H // 2), interpolation=cv2.INTER_AREA))+ draw(frame, j, t)+ now = time.time()+ if now - last[0] > 2.0 or j == n - 1:+ last[0] = now+ progress("render", done=j + 1, total=n, pct=round(100 * (j + 1) / n))++ out.parent.mkdir(parents=True, exist_ok=True)+ fade = float(edl["audio"]["crossfadeMs"]) / 1000.0+ try:+ res = rmod.render(clip, tl, fr, drawing, out, fade=fade, crf=18)+ except BaseException:+ if clean is not None:+ clean.abort()+ raise+ if clean is not None:+ clean.close()+ t_render = time.time() - t0+ result = {"out": res["path"], "frames": res["frames"], "seconds_out": res["seconds_out"],+ "joins": len(tl.joins), "framing": fr.note, "seconds": {"render": round(t_render, 1)}}+ if check:+ progress("overcut-check", note="nghe lại bản cắt, so từng chữ")+ from fx.effects.clean_cut import overcut_check++ t1 = time.time()+ kept = [w for w in clip.words if tl.to_output((w.start + w.end) / 2) is not None]+ oc = overcut_check(clip, kept, tl, Path(out), None)+ result["overcut"] = {k: oc[k] for k in ("verdict", "lost", "chopped", "left_at_cut", "matched", "kept",+ "joins", "joins_cut_in_silence", "median_start_offset_s")}+ result["seconds"]["overcut_check"] = round(time.time() - t1, 1)+ return result+++def cmd_stills(edl_path: Path, out: Path, count: int, draft_captions: bool) -> dict:+ from PIL import Image, ImageDraw++ from fx.core import render as rmod++ edl = load_edl(edl_path)+ clip, tl, fr, draw = build(edl, draft_captions)+ dur = tl.duration+ times = [dur * (i + 0.5) / count for i in range(count)]+ frames = rmod.still_frames(clip, tl, fr, draw, times)+ cols = int(math.ceil(math.sqrt(count)))+ rows = int(math.ceil(count / cols))+ tw, th = 270, 480+ sheet = Image.new("RGB", (cols * tw + (cols + 1) * 6, rows * (th + 32) + (rows + 1) * 6), (24, 24, 24))+ d = ImageDraw.Draw(sheet)+ for n, (t, f) in enumerate(frames):+ img = Image.fromarray(f).resize((tw, th), Image.LANCZOS)+ x, y = 6 + (n % cols) * (tw + 6), 6 + (n // cols) * (th + 32)+ sheet.paste(img, (x, y))+ d.text((x + 4, y + th + 6), f"{t:5.2f} s", fill=(230, 230, 230))+ sheet.save(out, quality=88)+ return {"out": str(out), "times": [round(t, 2) for t in times]}+++# What a graphic must keep clear of: the detector's own box (BlazeFace's box already runs wide of the cheeks and+# below the chin) grown upward for the hair. Measured on the founder's review clip (28/11/2026): `head()` (+60% up,+# +20% sides) came out about twice the visible head and left no room for any graphic in a close talking-head shot.+GRAPHIC_HEAD = {"left": 0.04, "top": 0.20, "right": 0.04, "bottom": 0.04}+++def _graphic_head(face, k: int, near: int):+ """The face at source frame k from the detector's own boxes (the nearest within `near` frames; the detector runs+ on every frame but misses some), so B-roll without a face leaves the whole frame to the graphics; None when no+ face is there. Boxes of implausible size are ignored."""+ import numpy as np++ from fx.core.layout import Rect++ lo, hi = max(0, k - near), min(face.n - 1, k + near)+ best = None+ for i in range(lo, hi + 1):+ x = face.raw[i, 0]+ if not np.isnan(x) and not (0.05 * face.height <= face.raw[i, 3] <= 0.7 * face.height):+ continue+ if np.isnan(x) or (best is not None and abs(i - k) >= abs(best - k)):+ continue+ best = i+ if best is None:+ return None+ x, y, w, h, _ = face.raw[best]+ g = GRAPHIC_HEAD+ return Rect(x - g["left"] * w, y - g["top"] * h, x + w + g["right"] * w, y + h + g["bottom"] * h)+++def cmd_faces(edl_path: Path, out: Path, step: float) -> dict:+ """Head box in OUTPUT pixels (after reframe and zoom) every `step` s of the output: what graphics must avoid."""+ edl = load_edl(edl_path)+ clip, tl, fr, _draw = build(edl, False)+ zooms = Zooms(edl, tl, fr, clip)+ fps = clip.info.rate+ rows = []+ n = int(tl.duration / step) + 1+ face = clip.face if clip.face.any() else None+ near = int(round(0.5 * fps))+ for m in range(n):+ t = min(tl.duration, m * step)+ k = tl.source_frame(int(round(t * fps)), fps, clip.info.frames)+ head = _graphic_head(face, k, near) if face is not None else None+ if head is None:+ rows.append([round(t, 3), None])+ continue+ r = fr.to_output(head, k)+ x0, y0, x1, y1 = r.x0, r.y0, r.x1, r.y1+ s, cx, cy = zooms.scale_at(t)+ if s > 1.001:+ w, h = OUT_W / s, OUT_H / s+ ox = min(max(cx - w / 2, 0.0), OUT_W - w)+ oy = min(max(cy - h * 0.42, 0.0), OUT_H - h)+ x0, x1, y0, y1 = (x0 - ox) * s, (x1 - ox) * s, (y0 - oy) * s, (y1 - oy) * s+ bx = [round(max(0, x0)), round(max(0, y0)), round(min(OUT_W, x1)), round(min(OUT_H, y1))]+ rows.append([round(t, 3), bx if bx[2] - bx[0] > 8 and bx[3] - bx[1] > 8 else None])+ data = {"step": step, "found_share": round(float(clip.face.found_share), 3) if clip.face.any() else 0.0, "boxes": rows}+ out.write_text(json.dumps(data), encoding="utf-8")+ return {"out": str(out), "samples": len(rows)}+++# ---- hear stretches again on their own ------------------------------------------------------------------------++def cmd_hear(proxy: Path, spans_arg: str, out: Path) -> dict:+ """Each span of the proxy heard on its own (the pack's second listen, cached in the words cache): what the+ planner uses to check a figure before it goes on a graphic. spans_arg: "a-b,c-d" in source seconds."""+ from fx.core import words as wordsmod++ spans = []+ for part in spans_arg.split(","):+ a, b = part.split("-")+ spans.append((round(float(a), 2), round(float(b), 2)))+ heard = wordsmod.relisten(proxy, spans, "small.en")+ data = {k: [{"text": seg["text"], "avg_logprob": round(float(seg["avg_logprob"]), 3),+ "words": [{"w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "p": round(w.prob, 3)} for w in seg["words"]]}+ for seg in segs] for k, segs in heard.items()}+ out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")+ return {"out": str(out), "spans": len(data)}+++# ---- qc ---------------------------------------------------------------------------------------------------------++def cmd_qc(video_path: Path, out: Path) -> dict:+ from fx.effects import qc_check++ r = qc_check.check(video_path, None, "reels", False, out.with_suffix(".md"))+ findings = [{"check": f.check, "level": f.level, "what": f.what, "fix": f.fix} for f in r["findings"]]+ data = {"verdict": r["verdict"], "findings": findings, "report": str(r["report"]), "sheet": str(r["sheet"]),+ "seconds": round(r["seconds"], 1)}+ out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")+ return data+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(prog="lumedit")+ sub = ap.add_subparsers(dest="cmd", required=True)+ a = sub.add_parser("analyze"); a.add_argument("proxy"); a.add_argument("--out", required=True)+ r = sub.add_parser("render"); r.add_argument("edl"); r.add_argument("--out", required=True)+ r.add_argument("--draft-captions", action="store_true"); r.add_argument("--no-check", action="store_true")+ r.add_argument("--no-glass", action="store_true"); r.add_argument("--clean-out", default=None)+ s = sub.add_parser("stills"); s.add_argument("edl"); s.add_argument("--out", required=True)+ s.add_argument("--count", type=int, default=16); s.add_argument("--draft-captions", action="store_true")+ f = sub.add_parser("faces"); f.add_argument("edl"); f.add_argument("--out", required=True)+ f.add_argument("--step", type=float, default=0.25)+ h = sub.add_parser("hear"); h.add_argument("proxy"); h.add_argument("--spans", required=True)+ h.add_argument("--out", required=True)+ q = sub.add_parser("qc"); q.add_argument("video"); q.add_argument("--out", required=True)+ args = ap.parse_args(argv)+ try:+ if args.cmd == "analyze":+ res = cmd_analyze(Path(args.proxy).resolve(), Path(args.out).resolve())+ elif args.cmd == "render":+ res = cmd_render(Path(args.edl).resolve(), Path(args.out).resolve(), args.draft_captions, not args.no_check,+ not args.no_glass, Path(args.clean_out).resolve() if args.clean_out else None)+ elif args.cmd == "stills":+ res = cmd_stills(Path(args.edl).resolve(), Path(args.out).resolve(), args.count, args.draft_captions)+ elif args.cmd == "hear":+ res = cmd_hear(Path(args.proxy).resolve(), args.spans, Path(args.out).resolve())+ elif args.cmd == "faces":+ res = cmd_faces(Path(args.edl).resolve(), Path(args.out).resolve(), args.step)+ else:+ res = cmd_qc(Path(args.video).resolve(), Path(args.out).resolve())+ except (ValueError, KeyError, FileNotFoundError) as e:+ emit("result", {"ok": False, "error": f"{type(e).__name__}: {e}"})+ traceback.print_exc()+ return 2+ except Exception as e: # noqa: BLE001+ from fx.core.paths import NeedSetup++ emit("result", {"ok": False, "error": f"{type(e).__name__}: {e}"})+ traceback.print_exc()+ return 3 if isinstance(e, NeedSetup) else 1+ emit("result", {"ok": True, **res})+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/edit/test/studio-check.mjs b/edit/test/studio-check.mjsindex 6aa6c12..4901c10 100644--- a/edit/test/studio-check.mjs+++ b/edit/test/studio-check.mjs@@ -7,7 +7,8 @@ import http from 'node:http';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import { parseManual, applyPatch, applyManual, manualView } from '../manual.mjs';+import { parseManual, applyPatch, applyManual, manualView, changedLines } from '../manual.mjs';+import { baseSig, cleanSig, glassItems, gfxWindow, gfxSig, dirtyRanges } from '../pipeline.mjs';import { validateEdl } from '../edl.mjs';let fails = 0;@@ -80,6 +81,50 @@ const rg = rebuilt.graphics.find((g) => g.id === 'g1');check(rg.start === 3.5 && rg.end === 6.5 && rg.data.title === 'Giá mới', 'dựng lại: giữ đồ hoạ đã dời + sửa chữ');fs.rmSync(tmp, { recursive: true, force: true });+// ---- mục 6: đếm dòng đổi đúng (chữ AI sửa thành 2 từ, nhấn) ----+{+ const e6 = JSON.parse(JSON.stringify(edl));+ e6.graphics = []; e6.zooms = [];+ e6.captions.words = e6.captions.words.map((w) => (w.i === 1 ? { ...w, w: 'RTX 5060' } : w));+ e6.captions.highlights = [1];+ const v6 = manualView(e6, state);+ check(v6.captions.lines.some((l) => l.text.includes('*RTX 5060*')), 'chữ AI sửa thành 2 từ hiện "*RTX 5060*" trong dòng');+ const ls = v6.captions.lines.map((l) => ({ start: l.start, end: l.end, text: l.text }));+ const k = ls.findIndex((l) => !l.text.includes('RTX'));+ ls[k].text += ' nhé';+ const r6 = applyPatch(e6, state, parseManual({ captions: { lines: ls } }), { dir: os.tmpdir() });+ check(/phụ đề: 1 dòng đổi/.test(r6.summary.join('; ')), `sửa 1 dòng → lịch sử "${r6.summary[0]}" (trước đây đếm cả dòng *RTX 5060* thành đổi)`);+ check(changedLines(['a', 'a', 'b'], ['a', 'b', 'b']) === 1 && changedLines(['a', 'b'], ['a']) === 1, 'đếm dòng đổi theo bội (dòng trùng chữ)');+}++// ---- mục 5: chữ ký nền chỉ băm phần vẽ trong nền; lớp phụ đề render lại từng đoạn ----+{+ const e5 = JSON.parse(JSON.stringify(edl));+ const b0 = baseSig(e5, false);+ const e5b = JSON.parse(JSON.stringify(e5)); e5b.graphics[0].data.title = 'khác'; e5b.graphics[0].start += 0.5; e5b.graphics[0].box.y += 10;+ check(baseSig(e5b, false) === b0, 'sửa chữ / giờ / vị trí đồ hoạ: chữ ký nền KHÔNG đổi (không render lại nền)');+ const e5c = JSON.parse(JSON.stringify(e5)); e5c.captions.lines = [{ start: 0, end: 1, words: [{ w: 'a', o: 0, hi: false }] }];+ check(baseSig(e5c, false) === b0, 'sửa phụ đề: chữ ký nền không đổi');+ const e5d = JSON.parse(JSON.stringify(e5)); e5d.zooms[0].scale = 1.3;+ check(baseSig(e5d, false) !== b0, 'đổi zoom: chữ ký nền đổi');+ const e5e = JSON.parse(JSON.stringify(e5)); e5e.graphics[0].squeeze = { scale: 0.8, anchorY: 900 };+ check(baseSig(e5e, false) !== b0, 'đồ hoạ thu hình (squeeze): chữ ký nền đổi');+ check(cleanSig(e5d) === cleanSig(e5), 'bản sạch xem trước không đổi khi chỉ đổi zoom');+ const gi = glassItems(e5);+ check(gi.length === 1 && gi[0].w === 840 && gi[0].t0 === 1.5 && gi[0].r === 38, `kính mờ vẽ lúc ghép: bảng có kính, tem giá không (${JSON.stringify(gi)})`);+ const w1 = gfxWindow(e5, e5.graphics[0]);+ check(w1.from === 1.5 && Math.abs(w1.dur - 3) < 0.05, `lớp đồ hoạ riêng chỉ render khoảng nó hiện (${JSON.stringify(w1)})`);+ check(gfxSig(e5.graphics[0], '#fff', w1) !== gfxSig(e5b.graphics[0], '#fff', w1), 'sửa chữ đồ hoạ: chữ ký lớp đồ hoạ đổi');+ const card = (s, e, k) => ({ s, e, k });+ const prev = { global: 'G', duration: 30, cards: [card(1, 2, 'a'), card(2, 3, 'b'), card(10, 11, 'c')] };+ const dr = dirtyRanges(prev, { global: 'G', duration: 30, cardsMeta: [card(1, 2, 'a'), card(2, 3, 'B'), card(10, 11, 'c')] });+ check(dr.length === 1 && dr[0][0] <= 1.95 && dr[0][0] >= 1.9 && dr[0][1] >= 3.3 && dr[0][1] <= 3.4, `khoảng render lại quanh thẻ đổi: ${JSON.stringify(dr)}`);+ check(dirtyRanges(prev, { global: 'G2', duration: 30, cardsMeta: prev.cards }) === null, 'đổi kiểu chữ (global) → render cả lớp');+ check(JSON.stringify(dirtyRanges(prev, { global: 'G', duration: 30, cardsMeta: prev.cards })) === '[]', 'không thẻ nào đổi → không render gì');+ const many = { global: 'G', duration: 30, cardsMeta: [card(0, 20, 'x')] };+ check(dirtyRanges(prev, many) === null, 'đổi > 55% thời lượng → render cả lớp');+}+// ---- REST ----const PORT = Number(process.argv[2]); const ID = process.argv[3];if (PORT) {diff --git a/server/server.mjs b/server/server.mjsindex 17d490b..f035878 100644--- a/server/server.mjs+++ b/server/server.mjs@@ -356,7 +356,8 @@ const server = http.createServer(async (req, res) => {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]);- if (p.startsWith('/fonts/')) return serveFile(req, res, path.join(ROOT, 'engine', 'fonts'), p.slice(7));+ // 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 });