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.8 KB
Raw Blame
// Môi trường Python riêng của LumReels Edit: đường dẫn venv, biến môi trường khi gọi Python,
// và hàm chạy `lumedit` (CLI Python) theo giao thức dòng: "@progress {...}" và dòng cuối "@result {...}".
import fs from 'node:fs';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';

export const EDIT = path.dirname(fileURLToPath(import.meta.url));
export const ROOT = path.dirname(EDIT);
export const PACK = path.join(EDIT, 'askeditor'); // mã AskEditor đã chép vào (MIT)
export const VENV = path.join(EDIT, '.venv');
export const LUMEDIT = path.join(EDIT, 'py', 'lumedit.py');
export const WHISPER_MODEL = process.env.LUMEDIT_WHISPER || 'large-v3';

/** Python trong venv riêng (không bao giờ là Python hệ thống). */
export function venvPython() {
  const win = path.join(VENV, 'Scripts', 'python.exe');
  const nix = path.join(VENV, 'bin', 'python');
  return process.platform === 'win32' ? win : nix;
}

export const READY_MARK = path.join(VENV, '.lumedit-ready.json');
/**
 * Đã cài đủ chưa: python trong venv + dấu READY của setup + các file nó ghi nhận (model whisper, model mặt/người,
 * font) vẫn còn. Trả {ready, missing[]}. Gói Python được setup kiểm bằng import trước khi ghi dấu.
 */
export function setupStatus() {
  const missing = [];
  if (!fs.existsSync(venvPython())) missing.push('môi trường Python edit/.venv');
  let mark = null;
  try { mark = JSON.parse(fs.readFileSync(READY_MARK, 'utf8')); } catch { /* chưa có */ }
  if (!mark) missing.push('dấu cài xong (chạy lại setup)');
  else for (const f of mark.files || []) if (!fs.existsSync(f)) missing.push(path.basename(path.dirname(f)) + '/' + path.basename(f));
  return { ready: missing.length === 0, missing };
}
export function venvReady() { return setupStatus().ready; }

/** Thư mục chứa thư viện CUDA của wheel nvidia-* trong venv (Linux cần LD_LIBRARY_PATH trước khi Python chạy). */
function cudaLibDirs() {
  if (process.platform !== 'linux') return [];
  const lib = path.join(VENV, 'lib');
  if (!fs.existsSync(lib)) return [];
  const out = [];
  for (const py of fs.readdirSync(lib)) {
    const nv = path.join(lib, py, 'site-packages', 'nvidia');
    if (!fs.existsSync(nv)) continue;
    for (const sub of fs.readdirSync(nv)) {
      const d = path.join(nv, sub, 'lib');
      if (fs.existsSync(d)) out.push(d);
    }
  }
  return out;
}

/** Biến môi trường cho mọi tiến trình Python của Edit. */
export function pyEnv(extra = {}) {
  const env = { ...process.env };
  delete env.ANTHROPIC_API_KEY;
  const libs = cudaLibDirs();
  return {
    ...env,
    PYTHONUTF8: '1', // Windows: mặc định cp1252 làm vỡ chữ Việt
    PYTHONIOENCODING: 'utf-8',
    PYTHONPATH: PACK + (env.PYTHONPATH ? path.delimiter + env.PYTHONPATH : ''),
    FX_LANG: env.FX_LANG || 'vi',
    FX_WHISPER: env.FX_WHISPER || WHISPER_MODEL,
    FX_DEVICE: env.FX_DEVICE || 'auto',
    GLOG_minloglevel: '2',
    TF_CPP_MIN_LOG_LEVEL: '3',
    HF_HUB_DISABLE_SYMLINKS_WARNING: '1',
    HF_HUB_DISABLE_TELEMETRY: '1',
    ...(libs.length ? { LD_LIBRARY_PATH: [...libs, env.LD_LIBRARY_PATH].filter(Boolean).join(':') } : {}),
    ...extra,
  };
}

/**
 * Chạy `python -X utf8 edit/py/lumedit.py <args>`. onProgress nhận object của mỗi dòng "@progress". env: biến thêm (vd FX_VCODEC_ARGS).
 * Trả {ok, result, code, log}. result = JSON của dòng "@result" cuối cùng.
 */
export function runLumedit(args, { onProgress, onLine, env = {}, timeoutMs = 3 * 60 * 60 * 1000 } = {}) {
  return new Promise((resolve) => {
    if (!venvReady()) return resolve({ ok: false, code: 3, error: 'Chưa cài môi trường Edit: chạy node edit/setup.mjs', log: '' });
    const p = spawn(venvPython(), ['-X', 'utf8', LUMEDIT, ...args], { cwd: PACK, env: pyEnv(env), windowsHide: true });
    let log = ''; let buf = ''; let result = null;
    const timer = setTimeout(() => { log += '\n[lumedit] quá thời gian, dừng\n'; p.kill(); }, timeoutMs);
    const feed = (d) => {
      const s = d.toString();
      log += s; buf += s;
      let i;
      while ((i = buf.indexOf('\n')) >= 0) {
        const line = buf.slice(0, i).replace(/\r$/, ''); buf = buf.slice(i + 1);
        if (line.startsWith('@progress ')) { try { onProgress?.(JSON.parse(line.slice(10))); } catch { /* bỏ qua */ } }
        else if (line.startsWith('@result ')) { try { result = JSON.parse(line.slice(8)); } catch { /* bỏ qua */ } }
        else if (line.trim()) onLine?.(line);
      }
    };
    p.stdout.on('data', feed);
    p.stderr.on('data', feed);
    p.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, code: -1, error: String(e), log }); });
    p.on('close', (code) => {
      clearTimeout(timer);
      if (buf.startsWith('@result ')) { try { result = JSON.parse(buf.slice(8)); } catch { /* bỏ qua */ } }
      const ok = code === 0 && result?.ok === true;
      resolve({ ok, code, result, log, error: ok ? undefined : (result?.error || log.trim().split(/\r?\n/).slice(-6).join('\n')) });
    });
  });
}

/** Tổng dung lượng 1 thư mục (byte), đi theo cây thư mục, bỏ symlink. */
export function dirSize(dir) {
  let total = 0;
  if (!fs.existsSync(dir)) return 0;
  const stack = [dir];
  while (stack.length) {
    const d = stack.pop();
    let ents = [];
    try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }
    for (const e of ents) {
      const f = path.join(d, e.name);
      if (e.isSymbolicLink()) continue;
      if (e.isDirectory()) stack.push(f);
      else { try { total += fs.statSync(f).size; } catch { /* bỏ qua */ } }
    }
  }
  return total;
}

export const fmtBytes = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(2)} GB` : n >= 1e6 ? `${Math.round(n / 1e6)} MB` : `${Math.round(n / 1e3)} KB`);