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.
// Tạo giọng nhân bản từ 1 file âm thanh người dùng tải lên / thu âm:
// 1. prepareClone: ffmpeg → mono 48 kHz, kiểm 10 s – 3 phút, cắt im lặng, chọn đoạn sạch 8–15 s → ref.wav (nhanh, chạy trong request)
// 2. finishClone: lời đoạn mẫu (whisper nếu máy có), VieNeu mã hoá tham chiếu (ref.npz) + đọc 1 câu nghe thử (sample.wav)
// Kho file: voice-store.mjs. Đọc bằng giọng nhân bản: voice.mjs + tts_vieneu.py (voice = id "vc-…").
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { run } from '../lib.mjs';
import { readWav, writeWav, normalizeRms } from './dsp.mjs';
import { synthVoice } from './voice.mjs';
import { ttsAvailable } from './prefs.mjs';
import { venvPython, WHISPER_MODEL } from '../../edit/env.mjs';
import { cloneDir, newCloneId, cleanName, cleanRefText, readClone, writeClone, VOICES_DIR } from './voice-store.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const PY = process.env.LUMREELS_PYTHON || 'python';
const SR = 48000;
export const CLONE_LIMITS = { minS: 10, maxS: 180, maxBytes: 30 * 1024 * 1024, refMinS: 8, refMaxS: 15 };
export const CLONE_EXT = new Set(['.wav', '.mp3', '.m4a', '.ogg', '.webm', '.oga', '.opus']);
export const CLONE_SAMPLE_TEXT = 'Xin chào, đây là giọng nói của tôi được nhân bản ngay trên máy. Bạn nghe thử xem có giống không nhé.';
const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
// ---------- whisper (tuỳ máy) ----------
const hasModule = (py, m) => {
try { return spawnSync(py, ['-c', `import importlib.util,sys;sys.exit(0 if importlib.util.find_spec('${m}') else 1)`], { windowsHide: true, timeout: 20000 }).status === 0; } catch { return false; }
};
let whisperPy;
/** Python có faster-whisper: edit/.venv (LumReels Edit) trước, rồi Python của máy. null = không có. */
export function whisperPython() {
if (whisperPy !== undefined) return whisperPy;
const cands = [venvPython(), PY].filter((p, i, a) => a.indexOf(p) === i && (p === PY || fs.existsSync(p)));
whisperPy = cands.find((p) => hasModule(p, 'faster_whisper')) || null;
return whisperPy;
}
/** Chép lời 1 file (tiếng Việt mặc định). Trả {text, device} hoặc null khi máy không có whisper / lỗi. */
export async function transcribe(file, { lang = 'vi', log = () => {} } = {}) {
const py = whisperPython();
if (!py) return null;
const model = process.env.LUMREELS_WHISPER || WHISPER_MODEL;
const r = await run(py, ['-X', 'utf8', path.join(HERE, 'whisper_ref.py'), file, model, lang], { env: { ...process.env, PYTHONIOENCODING: 'utf-8', HF_HUB_DISABLE_TELEMETRY: '1' }, timeoutMs: 10 * 60 * 1000 });
const line = r.out.split(/\r?\n/).reverse().find((l) => l.startsWith('{"ok"'));
try {
const j = JSON.parse(line);
if (j.ok) return { text: j.text, device: j.device };
log('whisper lỗi: ' + String(j.error).slice(0, 300));
} catch { log('whisper lỗi: ' + r.out.trim().split(/\r?\n/).slice(-2).join(' ').slice(0, 300)); }
return null;
}
/** Chỗ có tiếng người nói [[giây đầu, giây cuối], …] bằng Silero VAD (đi kèm faster-whisper). null = máy không có / lỗi. */
export async function detectSpeech(file) {
const py = whisperPython();
if (!py) return null;
const r = await run(py, ['-X', 'utf8', path.join(HERE, 'whisper_ref.py'), '--vad', file], { env: { ...process.env, PYTHONIOENCODING: 'utf-8' }, timeoutMs: 120000 });
try { const j = JSON.parse(r.out.split(/\r?\n/).reverse().find((l) => l.startsWith('{"ok"'))); return j.ok ? j.speech : null; } catch { return null; }
}
// ---------- chọn đoạn mẫu ----------
const FR = Math.round(0.02 * SR); // khung 20 ms
/** Năng lượng từng khung (dBFS) + đỉnh. */
function frames(x) {
const n = Math.floor(x.length / FR), db = new Float32Array(n), peak = new Float32Array(n);
for (let i = 0; i < n; i++) {
let s = 0, p = 0;
for (let j = i * FR; j < (i + 1) * FR; j++) { const v = x[j]; s += v * v; const a = v < 0 ? -v : v; if (a > p) p = a; }
db[i] = 10 * Math.log10(s / FR + 1e-12); peak[i] = p;
}
return { db, peak, n };
}
const pct = (arr, q) => { const a = Array.from(arr).sort((p, r) => p - r); return a[Math.min(a.length - 1, Math.floor(q * a.length))]; };
/**
* Chọn đoạn sạch nhất dài 8–15 s (ưu tiên ~10–12 s): nhiều tiếng nói, ít khoảng lặng dài, không vỡ tiếng,
* bắt đầu/kết thúc ở chỗ ngắt hơi. 8 s đầu càng dày tiếng nói càng tốt (VieNeu chỉ học 8 s đầu).
* speech: kết quả VAD (nếu có) — khi đó chỉ khung nằm trong đoạn nói mới tính là tiếng nói (nhạc nền/nhạc chuyển cảnh
* to cỡ nào cũng không bị chọn). Không có VAD thì dựa vào năng lượng.
* Trả {startS, endS, speechS, by: 'vad'|'energy'} theo giây trong x.
*/
export function pickSegment(x, speech = null) {
const { db, peak, n } = frames(x);
if (!n) throw httpErr(422, 'File âm thanh trống');
const floor = pct(db, 0.1), loud = pct(db, 0.95);
const th = Math.max(floor + Math.max(6, 0.3 * (loud - floor)), -55);
const voiced = Array.from(db, (d) => d > th);
if (speech?.length) {
const inSpeech = new Uint8Array(n);
for (const [a, b] of speech) for (let i = Math.max(0, Math.floor(a / 0.02)); i < Math.min(n, Math.ceil(b / 0.02)); i++) inSpeech[i] = 1;
for (let i = 0; i < n; i++) voiced[i] = voiced[i] && inSpeech[i] === 1;
}
// nối khe ngắn < 120 ms (giữa các âm tiết) để không coi là khoảng lặng
for (let i = 0, gap = 0; i < n; i++) {
if (!voiced[i]) gap++;
else { if (gap > 0 && gap <= 6 && i - gap - 1 >= 0 && voiced[i - gap - 1]) for (let k = i - gap; k < i; k++) voiced[k] = true; gap = 0; }
}
const speechS = voiced.filter(Boolean).length * 0.02;
if (speechS < CLONE_LIMITS.refMinS) throw httpErr(422, `File có quá ít tiếng nói (nghe ra ${speechS.toFixed(1)} s, cần ≥ ${CLONE_LIMITS.refMinS} s nói rõ). Thu lại ở chỗ yên tĩnh, nói liền mạch.`);
// tổng tiền tố để tính nhanh
const cv = new Int32Array(n + 1), cc = new Int32Array(n + 1);
for (let i = 0; i < n; i++) { cv[i + 1] = cv[i] + (voiced[i] ? 1 : 0); cc[i + 1] = cc[i] + (peak[i] > 0.985 ? 1 : 0); }
const onsets = [], offsets = [];
for (let i = 0; i < n; i++) {
if (voiced[i] && (i === 0 || !voiced[i - 1])) onsets.push(i);
if (voiced[i] && (i === n - 1 || !voiced[i + 1])) offsets.push(i + 1);
}
const minF = CLONE_LIMITS.refMinS / 0.02, maxF = CLONE_LIMITS.refMaxS / 0.02, head = 8 / 0.02;
const longPause = (a, b) => { // tổng giây của các khoảng lặng > 0,6 s trong [a, b)
let tot = 0, run0 = 0;
for (let i = a; i < b; i++) { if (!voiced[i]) run0++; else { if (run0 > 30) tot += run0 * 0.02; run0 = 0; } }
return tot;
};
let best = null;
const score = (a, b) => {
const L = b - a, vr = (cv[b] - cv[a]) / L, hr = (cv[Math.min(b, a + head)] - cv[a]) / Math.min(L, head);
const clip = (cc[b] - cc[a]) / L;
const sLen = L * 0.02;
return vr + 0.6 * hr - 4 * clip - 0.08 * longPause(a, b) - 0.01 * Math.abs(sLen - 11);
};
for (const a of onsets) {
for (const b of offsets) {
if (b - a < minF) continue;
if (b - a > maxF) break;
const s = score(a, b);
if (!best || s > best.s) best = { a, b, s };
}
}
if (!best) {
// nói liền không ngắt hơi đủ chỗ: cửa sổ trượt 11 s (hoặc cả đoạn nếu ngắn hơn)
const L = Math.min(n, Math.round(11 / 0.02));
for (let a = 0; a + L <= n; a += 25) { const s = score(a, a + L); if (!best || s > best.s) best = { a, b: a + L, s }; }
}
return { startS: best.a * 0.02, endS: best.b * 0.02, speechS, by: speech?.length ? 'vad' : 'energy' };
}
// ---------- 1. nhận file ----------
/**
* Đổi file về mono 48 kHz, kiểm độ dài, chọn đoạn mẫu → ref.wav. Lỗi đầu vào → throw có .code (4xx).
* src: file đã tải lên (sẽ bị xoá sau khi xử lý). Trả meta (status "processing").
*/
export async function prepareClone({ src, filename, name, consent, refText, id = newCloneId() }) {
const nm = cleanName(name);
if (!(consent === true || consent === '1' || consent === 'true' || consent === 'on')) throw httpErr(400, 'Cần tick xác nhận: đây là giọng của bạn, hoặc bạn được người đó cho phép dùng');
const ext = path.extname(String(filename || src)).toLowerCase();
if (!CLONE_EXT.has(ext)) throw httpErr(415, `Định dạng ${ext || '?'} chưa hỗ trợ (wav, mp3, m4a, ogg, webm)`);
const st = fs.statSync(src);
if (st.size > CLONE_LIMITS.maxBytes) throw httpErr(413, 'File quá lớn (tối đa 30 MB)');
const text = cleanRefText(refText);
const dir = cloneDir(id);
fs.mkdirSync(dir, { recursive: true });
const full = path.join(dir, 'full.wav');
try {
// highpass bỏ ù nền; giới hạn đọc 200 s (file dài hơn 3 phút là bị từ chối)
const r = await run('ffmpeg', ['-y', '-v', 'error', '-i', src, '-t', '200', '-vn', '-ac', '1', '-ar', String(SR), '-af', 'highpass=f=70', '-c:a', 'pcm_s16le', full], { timeoutMs: 120000 });
if (r.code !== 0 || !fs.existsSync(full)) throw httpErr(415, 'Không đọc được file âm thanh (file hỏng hoặc không phải âm thanh)');
const x = readWav(full).chans[0];
const durS = x.length / SR;
if (durS < CLONE_LIMITS.minS) throw httpErr(422, `File ngắn quá (${durS.toFixed(1)} s). Cần 10 giây – 3 phút.`);
if (durS > CLONE_LIMITS.maxS + 0.5) throw httpErr(422, 'File dài quá (hơn 3 phút). Cắt bớt còn 10 giây – 3 phút.');
const seg = pickSegment(x, await detectSpeech(full));
const pad = Math.round(0.08 * SR);
const a = Math.max(0, Math.round(seg.startS * SR) - pad), b = Math.min(x.length, Math.round(seg.endS * SR) + pad);
const y = x.slice(a, b);
const f = Math.round(0.01 * SR);
for (let i = 0; i < f; i++) { y[i] *= i / f; y[y.length - 1 - i] *= i / f; }
normalizeRms([y], -20, -1);
writeWav(path.join(dir, 'ref.wav'), [y], SR);
if (text) fs.writeFileSync(path.join(dir, 'ref.txt'), text + '\n');
const refHash = crypto.createHash('sha1').update(fs.readFileSync(path.join(dir, 'ref.wav'))).digest('hex').slice(0, 12);
return writeClone(id, {
name: nm, status: 'processing', step: 'queued', error: null, createdAt: new Date().toISOString(), refHash,
source: { filename: path.basename(String(filename || '')).slice(0, 120), bytes: st.size, durS: +durS.toFixed(2) },
ref: { startS: +(a / SR).toFixed(2), durS: +(y.length / SR).toFixed(2), speechS: +seg.speechS.toFixed(1), by: seg.by },
refText: text, refTextSource: text ? 'user' : null,
consent: { at: new Date().toISOString(), text: 'Đây là giọng của tôi, hoặc tôi được người đó cho phép dùng' },
});
} catch (e) {
fs.rmSync(dir, { recursive: true, force: true });
throw e;
} finally {
fs.rmSync(full, { force: true });
}
}
// ---------- 2. lời mẫu + mã hoá + câu nghe thử ----------
export const activeClones = new Set();
/** Chạy nền sau prepareClone. Không throw: lỗi ghi vào meta (status "error"). */
export async function finishClone(id, { log = () => {} } = {}) {
activeClones.add(id);
const dir = cloneDir(id);
try {
const m = readClone(id);
if (!m) throw new Error('không thấy giọng');
if (!m.refText) {
writeClone(id, { step: 'transcribe' });
const t = await transcribe(path.join(dir, 'ref.wav'), { log });
if (t?.text) { fs.writeFileSync(path.join(dir, 'ref.txt'), t.text + '\n'); writeClone(id, { refText: t.text, refTextSource: 'whisper' }); log(`giọng ${id}: lời mẫu (whisper ${t.device}): ${t.text}`); }
}
writeClone(id, { step: 'encode' });
const cache = path.join(dir, 'cache');
const [r] = await synthVoice([{ t: 0, text: CLONE_SAMPLE_TEXT }], cache, { engine: 'vieneu', voice: id, fallback: false, log });
fs.copyFileSync(r.file, path.join(dir, 'sample.wav'));
fs.rmSync(cache, { recursive: true, force: true });
if (!fs.existsSync(path.join(dir, 'ref.npz'))) log(`giọng ${id}: VieNeu không mã hoá sẵn được tham chiếu, mỗi lần đọc sẽ mã hoá lại (chậm hơn chút)`);
return writeClone(id, { status: 'ready', step: null, error: null, encoded: fs.existsSync(path.join(dir, 'ref.npz')) });
} catch (e) {
log(`giọng ${id} lỗi: ${e.message}`);
if (fs.existsSync(dir)) return writeClone(id, { status: 'error', step: null, error: String(e.message).slice(0, 400) });
return null;
} finally {
activeClones.delete(id);
}
}
/** Đủ để tạo giọng nhân bản không (VieNeu trên máy). */
export function cloneSupport() {
return { vieneu: ttsAvailable().vieneu, whisper: !!whisperPython(), dir: VOICES_DIR };
}