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.

6.2 KB
Raw Blame
// "Sửa tiếp trong Studio": nhập 1 reel đã dựng xong (tab Dựng từ mẫu, jobs/<id>/) thành 1 bản Edit kiểu "giữ nguyên":
// không LLM cắt, không tự thêm phụ đề (chữ đã nằm trong cảnh), vẫn chép lời (whisper) để có khối chữ nếu người dùng bật
// phụ đề, chữ sửa theo chính lời đọc (TTS) của reel. Reel còn giữ tiếng riêng (out.silent.mp4 + scene/audio.json + audio/)
// thì nhập TÁCH TRACK: nguồn = hình không tiếng + giọng/tiếng động (trộn lại không nhạc), nhạc = file nhạc của reel → chỉnh
// được âm lượng / thay bài thật. Không có thì nhập out.mp4 nguyên (nhạc đã trộn sẵn).
import fs from 'node:fs';
import path from 'node:path';
import { z } from 'zod';
import { jobDir, readJob } from '../generator/jobs.mjs';
import { buildMix } from '../engine/audio/mix.mjs';
import { run } from '../engine/lib.mjs';

const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
export const ReelImportSchema = z.object({ job: z.string().regex(/^[\w-]{1,80}$/) }).strict();

/** Chuẩn hoá để so chữ whisper với lời đọc: thường, bỏ dấu, bỏ dấu câu. */
const norm = (w) => String(w).toLowerCase().normalize('NFD').replace(/\p{M}/gu, '').replace(/đ/g, 'd').replace(/[^\p{L}\p{N}]/gu, '');
const strip = (w) => String(w).replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');

/**
 * Sửa chữ whisper theo lời đọc thật (kịch bản TTS): dóng hàng 2 dãy chữ (quy hoạch động, khớp khi giống sau chuẩn hoá),
 * chữ whisper thế chỗ 1-1 cho chữ kịch bản (khác chữ) hoặc chỉ sai dấu/hoa → fix {word, text}. words: [{i, w}].
 */
export function scriptFixes(words, script) {
  const S = String(script || '').split(/\s+/).map(strip).filter(Boolean);
  const W = words.map((w) => ({ i: w.i, w: strip(w.w) })).filter((w) => w.w);
  const n = W.length; const m = S.length;
  if (!n || !m || n * m > 4e6) return [];
  const D = Array.from({ length: n + 1 }, () => new Int32Array(m + 1));
  for (let i = 0; i <= n; i++) D[i][0] = i;
  for (let j = 0; j <= m; j++) D[0][j] = j;
  for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= m; j++) {
      const sub = norm(W[i - 1].w) === norm(S[j - 1]) ? 0 : 1;
      D[i][j] = Math.min(D[i - 1][j - 1] + sub, D[i - 1][j] + 1, D[i][j - 1] + 1);
    }
  }
  const fixes = [];
  let i = n; let j = m;
  while (i > 0 && j > 0) {
    const sub = norm(W[i - 1].w) === norm(S[j - 1]) ? 0 : 1;
    if (D[i][j] === D[i - 1][j - 1] + sub) {
      const w = W[i - 1]; const s = S[j - 1];
      if (w.w !== s) fixes.push({ word: w.i, text: s });
      i--; j--;
    } else if (D[i][j] === D[i - 1][j] + 1) i--; else j--;
  }
  return fixes.reverse();
}

/**
 * Chuẩn bị file cho bản Edit từ reel (chưa chạy pipeline). Trả {video, sourceName, music, musicName, musicGainDb,
 * script, reel, split}. dir: thư mục edit mới (đã tạo).
 */
export async function prepareReel(jobId, dir, { log = () => {} } = {}) {
  const job = readJob(jobId);
  if (!job) throw httpErr(404, 'không thấy video ' + jobId);
  if (job.status !== 'done') throw httpErr(409, 'video này chưa dựng xong');
  const jd = jobDir(jobId);
  const out = path.join(jd, job.output?.mp4 || 'out.mp4');
  if (!fs.existsSync(out)) throw httpErr(409, 'video này không còn file MP4');
  let spec = null; try { spec = JSON.parse(fs.readFileSync(path.join(jd, 'scene', 'audio.json'), 'utf8')); } catch { /* reel không có tiếng tách */ }
  const silent = path.join(jd, 'out.silent.mp4');
  const script = (spec?.voice?.lines || []).slice().sort((a, b) => a.t - b.t).map((l) => String(l.text || '').trim()).filter(Boolean).join(' ').slice(0, 4000);
  const title = String(job.templateTitle || job.templateId || jobId).slice(0, 80);
  const reel = { id: jobId, title, templateId: job.templateId || null, aspect: job.aspect || '9:16', mp4: `/jobs/${jobId}/${path.basename(out)}`, content: String(job.content || '').slice(0, 400) };
  const base = { sourceName: `${title} · ${jobId}.mp4`, script, reel };
  const musicFile = spec?.music ? fs.readdirSync(path.join(jd, 'audio')).find((f) => f.startsWith(`music-${spec.music.style}-`) && f.endsWith('.wav')) : null;
  if (!fs.existsSync(silent) || !spec) {
    log('reel không còn tiếng tách: nhập MP4 nguyên (nhạc đã trộn sẵn)');
    return { ...base, video: out, music: null, musicName: null, musicGainDb: null, split: false };
  }
  // giọng + tiếng động, không nhạc: trộn lại từ file giọng đã có (chép thư mục audio để dùng cache giọng, không đọc lại TTS)
  const work = path.join(dir, 'reel-audio');
  fs.cpSync(path.join(jd, 'audio'), work, { recursive: true });
  for (const f of ['mix.wav', 'premix.wav']) fs.rmSync(path.join(work, f), { force: true });
  const r0 = await run('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', silent]);
  const duration = parseFloat(r0.out);
  if (!(duration > 0)) throw httpErr(422, 'không đọc được độ dài video reel');
  let voiceWav = null;
  if (spec.voice?.lines?.length || spec.sfx?.length) {
    const mix = await buildMix(path.join(jd, 'scene'), { duration, workDir: work, log, spec: { ...spec, music: null }, seedKey: jobId });
    voiceWav = mix.wav;
  }
  const video = path.join(dir, 'reel.mp4');
  const args = ['-hide_banner', '-y', '-i', silent];
  if (voiceWav) args.push('-i', voiceWav); else args.push('-f', 'lavfi', '-t', String(duration), '-i', 'anullsrc=r=48000:cl=stereo');
  args.push('-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-shortest', '-movflags', '+faststart', video);
  const r = await run('ffmpeg', args);
  if (r.code !== 0) throw httpErr(422, 'ghép hình + giọng của reel lỗi: ' + r.out.trim().split(/\r?\n/).pop());
  let music = null;
  if (musicFile) { music = path.join(dir, 'music-reel.wav'); fs.copyFileSync(path.join(jd, 'audio', musicFile), music); }
  const gain = spec.music ? (spec.music.gain ?? (spec.voice?.lines?.length ? -12 : -6)) : null;
  fs.rmSync(work, { recursive: true, force: true });
  return { ...base, video, music, musicName: music ? `nhạc của reel (${spec.music.style})` : null, musicGainDb: gain == null ? null : Math.max(-40, Math.min(0, gain)), split: true };
}