Skip to content

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

5.6 KB
Raw Blame
// Kho "Giọng của tôi" (giọng nhân bản): mỗi giọng 1 thư mục ngoài repo, mặc định ~/.lumreels/voices/<id>/
//   meta.json  tên, trạng thái (processing | ready | error), đoạn mẫu đã chọn, xác nhận quyền dùng giọng
//   ref.wav    đoạn mẫu sạch 8–15 s, mono 48 kHz (VieNeu v3 Turbo lấy 8 s đầu để học giọng)
//   ref.npz    tham chiếu đã mã hoá sẵn (speaker embedding + mã âm), tts_vieneu.py tự ghi lần đầu dùng
//   ref.txt    lời của đoạn mẫu (whisper chép, hoặc người dùng gõ). v3 Turbo không cần, giữ cho bản VieNeu khác
//   sample.wav câu nghe thử
// Đổi chỗ lưu: LUMREELS_VOICES_DIR. Module này chỉ đọc/ghi file, không gọi mô hình (xem voice-clone.mjs).
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';

export const VOICES_DIR = process.env.LUMREELS_VOICES_DIR || path.join(os.homedir(), '.lumreels', 'voices');
/** Id giọng nhân bản: "vc-" + 8 hex. Chỉ dạng này mới thành đường dẫn (không lọt ../). */
export const CLONE_ID_RE = /^vc-[a-f0-9]{8}$/;
export const isCloneVoice = (v) => CLONE_ID_RE.test(String(v || ''));
export const NAME_MAX = 40;

const httpErr = (code, msg) => Object.assign(new Error(msg), { code });

export function cloneDir(id) {
  if (!isCloneVoice(id)) throw httpErr(400, 'id giọng không hợp lệ');
  return path.join(VOICES_DIR, id);
}
export function newCloneId() {
  for (;;) {
    const id = 'vc-' + crypto.randomBytes(4).toString('hex');
    if (!fs.existsSync(path.join(VOICES_DIR, id))) return id;
  }
}

/** Tên giọng: bỏ khoảng trắng thừa + ký tự điều khiển, 1–40 ký tự. */
export function cleanName(name) {
  const s = String(name ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim();
  if (!s) throw httpErr(400, 'Đặt tên cho giọng (1–40 ký tự)');
  if ([...s].length > NAME_MAX) throw httpErr(400, `Tên giọng tối đa ${NAME_MAX} ký tự`);
  return s;
}
/** Lời đoạn mẫu người dùng gõ: tối đa 600 ký tự. Trống → null. */
export function cleanRefText(t) {
  const s = String(t ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim();
  if (s.length > 600) throw httpErr(400, 'Lời đoạn mẫu tối đa 600 ký tự');
  return s || null;
}

export function readClone(id) {
  if (!isCloneVoice(id)) return null;
  try { return JSON.parse(fs.readFileSync(path.join(VOICES_DIR, id, 'meta.json'), 'utf8')); } catch { return null; }
}
export function writeClone(id, patch) {
  const dir = cloneDir(id);
  fs.mkdirSync(dir, { recursive: true });
  const cur = readClone(id) || {};
  const next = { ...cur, ...patch, id, updatedAt: new Date().toISOString() };
  const f = path.join(dir, 'meta.json');
  fs.writeFileSync(f + '.tmp', JSON.stringify(next, null, 2));
  fs.renameSync(f + '.tmp', f);
  return next;
}

/** Danh sách giọng (mới trước). */
export function listClones() {
  let ids = [];
  try { ids = fs.readdirSync(VOICES_DIR).filter((d) => CLONE_ID_RE.test(d)); } catch { return []; }
  return ids.map(readClone).filter(Boolean).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
}
export const cloneReady = (id) => readClone(id)?.status === 'ready';

/** Đường dẫn tham chiếu cho TTS. Giọng chưa xong / đã xoá → lỗi rõ ràng. */
export function cloneRef(id) {
  const m = readClone(id);
  if (!m) throw new Error(`Giọng nhân bản "${id}" không còn (đã xoá?). Chọn giọng khác.`);
  const dir = cloneDir(id);
  const wav = path.join(dir, 'ref.wav');
  if (!fs.existsSync(wav)) throw new Error(`Giọng "${m.name}" chưa có đoạn mẫu (đang xử lý hoặc lỗi).`);
  const txt = path.join(dir, 'ref.txt');
  return { id, name: m.name, wav, npz: path.join(dir, 'ref.npz'), text: fs.existsSync(txt) ? fs.readFileSync(txt, 'utf8').trim() : '', stamp: m.refHash || m.createdAt };
}

export function renameClone(id, name) {
  if (!readClone(id)) throw httpErr(404, 'không thấy giọng');
  return writeClone(id, { name: cleanName(name) });
}
export function setRefText(id, text) {
  if (!readClone(id)) throw httpErr(404, 'không thấy giọng');
  const t = cleanRefText(text);
  const f = path.join(cloneDir(id), 'ref.txt');
  if (t) fs.writeFileSync(f, t + '\n'); else fs.rmSync(f, { force: true });
  return writeClone(id, { refText: t, refTextSource: t ? 'user' : null });
}
export function deleteClone(id) {
  if (!readClone(id)) throw httpErr(404, 'không thấy giọng');
  fs.rmSync(cloneDir(id), { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
}

/** Giọng đang "processing" khi tiến trình đã tắt → lỗi, để người dùng tải lại. */
export function markStaleClones(activeIds = new Set()) {
  for (const c of listClones()) {
    if (c.status === 'processing' && !activeIds.has(c.id)) writeClone(c.id, { status: 'error', error: 'Bị ngắt giữa chừng (app tắt). Xoá rồi tải lại file.' });
  }
}

/** Dạng gửi cho UI/API (không lộ đường dẫn máy). */
export function cloneView(m) {
  if (!m) return null;
  const has = (f) => fs.existsSync(path.join(VOICES_DIR, m.id, f));
  return {
    id: m.id, name: m.name, status: m.status, step: m.step || null, error: m.error || null, createdAt: m.createdAt, updatedAt: m.updatedAt,
    refText: m.refText || null, refTextSource: m.refTextSource || null, ref: m.ref || null, sourceDurS: m.source?.durS ?? null,
    lang: 'vi',
    sample: has('sample.wav') ? `/api/voices/mine/${m.id}/sample.wav` : null,
    refAudio: has('ref.wav') ? `/api/voices/mine/${m.id}/ref.wav` : null,
  };
}