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.

10.5 KB
Raw Blame
// Viết lại nội dung người dùng thành kịch bản hợp với 1 mẫu + thời lượng.
// Dùng chung cho REST (POST /api/rewrite), CLI (node cli.mjs rewrite) và MCP (rewrite_script).
// Engine: api (Anthropic API, REWRITE_MODEL) → claude (Claude Code headless, không tool) → lỗi "chưa cấu hình AI".
// Không bao giờ ghi khoá API ra log/file.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import Anthropic from '@anthropic-ai/sdk';
import { config, costOf } from './config.mjs';
import { markKeyRejected } from './user-key.mjs';
import { findClaude, spawnClaude } from './claude.mjs';
import crypto from 'node:crypto';
import { parseDuration, fmtDuration } from './jobs.mjs';
import { resolveTemplate, readGuidance, wrapUntrusted } from '../packs/registry.mjs';

export const REWRITE_MAX_CHARS = 4000;
export const REWRITE_TIMEOUT_MS = 90_000;
export const REWRITE_ENGINES = ['auto', 'api', 'claude'];

/** Lấy frontmatter title + các mục §1, §2, §3, §10 của guidance (bỏ phần còn lại để prompt gọn). */
export function guidanceForRewrite(id) {
  const md = readGuidance(id);
  if (md === null) throw new Error(`Mẫu ${id} chưa có guidance`);
  const title = (/^title:\s*(.+)$/m.exec(md) || [])[1]?.trim() || '';
  const narration = /^narration:\s*true/m.test(md);
  const parts = md.split(/^(?=## )/m);
  const keep = parts.filter((p) => /^## (1|2|3|10)\.\s/.test(p)).map((p) => p.trim());
  return { title, narration, text: keep.join('\n\n') };
}

export function buildRewritePrompt({ templateId, content, durationS }) {
  const g = guidanceForRewrite(templateId);
  const D = durationS;
  const scenes = D > 12 ? Math.max(2, Math.round(D / 8)) : 1;
  const shape = scenes > 1
    ? `Video dài ${fmtDuration(D)} (${D} giây): chia kịch bản thành khoảng ${scenes} cảnh nối nhau, mỗi cảnh 6–10 giây, theo §10 của guidance. Mỗi cảnh ghi 1 dòng "Cảnh k (từ–đến giây):" rồi giá trị từng ô nội dung §3 cho cảnh đó. Phần tử xuyên suốt (tên kênh, nhãn…) ghi 1 lần ở đầu. CTA chỉ ở cảnh cuối.`
    : `Video ${D} giây = 1 màn. Ghi giá trị từng ô nội dung §3, mỗi ô 1 dòng "tên_ô: giá trị".`;
  return `Mày là biên kịch video dọc ngắn. Viết lại NỘI DUNG NGƯỜI DÙNG dưới đây thành kịch bản dùng được ngay cho mẫu ${templateId} "${g.title}".

## Luật (bắt buộc)
- Giữ đúng ý chính, MỌI con số, tên thương hiệu/kênh và CTA người dùng đưa. Không đổi số, không thêm số liệu thật (giá, lãi suất, thống kê) mà người dùng không đưa. Cần phép tính thì tính từ số người dùng đưa và ghi rõ "giả định" nếu phải tự đặt.
- Tên thương hiệu, sản phẩm, kênh người dùng nêu phải còn nguyên ở ít nhất 1 ô (ô quá ngắn thì đặt vào ô khác hợp hơn, không bỏ hẳn).
- Viết tiếng Việt đủ dấu, câu ngắn, hợp giọng mẫu.
- Bám §3 "Ô nội dung": đúng tên ô, đúng giới hạn ký tự/in hoa của từng ô; ô bắt buộc phải có. Nội dung thiếu ô bắt buộc thì tự đặt hợp lý theo chính nội dung đó và nói trong phần ghi chú.
- KHÔNG chép chữ ở cột "Ví dụ" của §3 hay ví dụ nào trong guidance: chúng chỉ để hiểu định dạng.
- Nội dung không hợp mẫu (xem §2 "Không hợp") thì vẫn viết bản gần nhất có thể và nói rõ trong ghi chú.
- ${shape}${g.narration ? '\n- Mẫu có lời đọc: thêm dòng "loi_doc:" cho từng cảnh, câu ngắn, đọc xong trong thời lượng cảnh.' : ''}

## Trả lời ĐÚNG dạng này, không thêm gì khác
<kich_ban>
(kịch bản: các dòng "tên_ô: giá trị" theo §3${scenes > 1 ? ', nhóm theo cảnh' : ''})
</kich_ban>
<ghi_chu>
(1–4 gạch đầu dòng ngắn, không xưng "tôi": chỗ đã rút gọn, ô tự đặt, giả định, chỗ nội dung không hợp mẫu)
</ghi_chu>

## Nội dung người dùng (nguyên văn)
"""
${content}
"""

${resolveTemplate(templateId)?.source === 'builtin' ? `## Guidance mẫu ${templateId} (§1–§3, §10)
${g.text}` : wrapUntrusted(g.text, crypto.randomBytes(8).toString('hex'), `Guidance mẫu ${templateId} (§1–§3, §10)`)}
`;
}

/** Tách <kich_ban> và <ghi_chu> từ câu trả lời. */
export function parseRewrite(text) {
  const tag = (n) => (new RegExp(`<${n}>\\s*([\\s\\S]*?)\\s*</${n}>`, 'i').exec(text) || [])[1];
  const script = tag('kich_ban') ?? (/<kich_ban>\s*([\s\S]*)$/i.exec(text) || [])[1]?.trim();
  return { script: script?.trim() || '', notes: tag('ghi_chu')?.trim() || '' };
}

function validate(input) {
  const t = resolveTemplate(String(input.templateId || '').trim());
  if (!t) throw new Error(`Không có mẫu ${String(input.templateId || '').trim()}`);
  const templateId = t.ref;
  if (!t.file) throw new Error(`Mẫu ${templateId} chưa có guidance`);
  const content = String(input.content || '').trim();
  if (content.length < 10) throw new Error('Nội dung quá ngắn để viết lại (tối thiểu 10 ký tự)');
  if (content.length > REWRITE_MAX_CHARS) throw new Error(`Nội dung quá dài (tối đa ${REWRITE_MAX_CHARS} ký tự)`);
  return { templateId, content, durationS: parseDuration(input.durationS) };
}

/** auto → api (có ANTHROPIC_API_KEY) → claude (có lệnh claude) → null (chưa cấu hình). */
export function resolveRewriteEngine(engine = process.env.REWRITE_ENGINE || 'auto') {
  if (!REWRITE_ENGINES.includes(engine)) throw new Error(`engine không hợp lệ: ${engine} (auto|api|claude)`);
  if (engine === 'api') return config.hasApiKey() ? 'api' : null;
  if (engine === 'claude') return findClaude() ? 'claude' : null;
  if (config.hasApiKey()) return 'api';
  if (findClaude()) return 'claude';
  return null;
}

const NO_AI = 'Chưa cấu hình AI: mở "Kiểm tra máy" để dán khoá Anthropic, hoặc cài Claude Code (lệnh claude / CLAUDE_BIN).';

async function viaApi(prompt) {
  const model = process.env.REWRITE_MODEL || 'claude-haiku-5-5';
  const apiKey = process.env.ANTHROPIC_API_KEY;
  const client = new Anthropic({ apiKey, maxRetries: 1, timeout: REWRITE_TIMEOUT_MS });
  let msg;
  try {
    msg = await client.messages.create({ model, max_tokens: 4000, messages: [{ role: 'user', content: prompt }] });
  } catch (e) {
    if (e instanceof Anthropic.APIError && (e.status === 401 || e.status === 403)) markKeyRejected(apiKey, e.status); // Kiểm tra máy báo đúng ngay
    throw e;
  }
  if (msg.stop_reason === 'refusal') throw new Error(`${model} từ chối viết lại`);
  const text = (msg.content || []).filter((b) => b.type === 'text').map((b) => b.text).join('\n');
  const u = msg.usage || {};
  return { text, usage: { model, inputTokens: u.input_tokens || 0, outputTokens: u.output_tokens || 0, costUSD: +costOf(model, u).toFixed(5) } };
}

/** Claude Code headless: không tool nào (--tools ""), không MCP, không lưu phiên, prompt qua stdin, chỉ lấy text. */
function viaClaude(prompt) {
  const bin = findClaude();
  const args = [
    '-p', '--output-format', 'json',
    '--permission-mode', 'default',
    '--tools', '',
    '--setting-sources', 'project',
    '--strict-mcp-config',
    '--no-session-persistence',
    '--max-turns', '2',
  ];
  if (process.env.REWRITE_CLAUDE_MODEL) args.push('--model', process.env.REWRITE_CLAUDE_MODEL);
  // Thư mục trống riêng: không đọc CLAUDE.md / cấu hình dự án nào.
  const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'lumreels-rewrite-'));
  return new Promise((resolve, reject) => {
    const p = spawnClaude(args, { cwd, windowsHide: true, env: (({ ANTHROPIC_API_KEY, ...e }) => e)(process.env) });
    let out = ''; let err = '';
    const timer = setTimeout(() => { p.kill(); reject(new Error(`Claude Code quá ${REWRITE_TIMEOUT_MS / 1000}s, đã dừng`)); }, REWRITE_TIMEOUT_MS);
    p.stdout.on('data', (d) => { out += d; });
    p.stderr.on('data', (d) => { err += d; });
    p.on('error', (e) => { clearTimeout(timer); reject(new Error('spawn claude lỗi: ' + e.message)); });
    p.on('close', (code) => {
      clearTimeout(timer);
      fs.rm(cwd, { recursive: true, force: true }, () => {});
      let r = null;
      try { r = JSON.parse(out.trim().split(/\r?\n/).pop()); } catch { /* không phải JSON */ }
      if (code !== 0 || !r || r.is_error) {
        const why = (r?.result || err || out || '').toString().trim().slice(-600);
        return reject(new Error(`claude thoát mã ${code}: ${why || 'không có thông báo'}`));
      }
      const u = r.usage || {};
      resolve({ text: String(r.result || ''), usage: {
        model: 'claude-code', inputTokens: (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0),
        outputTokens: u.output_tokens || 0, costUSD: typeof r.total_cost_usd === 'number' ? +r.total_cost_usd.toFixed(5) : null,
      } });
    });
    p.stdin.end(prompt);
  });
}

/**
 * Viết lại kịch bản. input = {templateId, content, durationS?, engine?: auto|api|claude}
 * Trả {script, notes, engine, usage, templateId, durationS}. Lỗi → throw Error (thông báo tiếng Việt).
 * auto: api lỗi xác thực (401/403) mà máy có Claude Code → thử claude, ghi lại trong fallbackFrom.
 */
export async function rewriteScript(input) {
  const v = validate(input);
  const want = input.engine || process.env.REWRITE_ENGINE || 'auto';
  const engine = resolveRewriteEngine(want);
  if (!engine) throw new Error(NO_AI);
  const prompt = buildRewritePrompt(v);
  let used = engine; let fallbackFrom = null; let r;
  try {
    r = engine === 'api' ? await viaApi(prompt) : await viaClaude(prompt);
  } catch (e) {
    const auth = e instanceof Anthropic.APIError && (e.status === 401 || e.status === 403);
    if (engine === 'api' && want === 'auto' && auth && findClaude()) {
      fallbackFrom = `api lỗi ${e.status} (khoá Anthropic không hợp lệ)`;
      used = 'claude';
      r = await viaClaude(prompt);
    } else if (e instanceof Anthropic.APIError) {
      throw new Error(`API ${e.status ?? ''} ${e.name}: ${String(e.message).slice(0, 300)}`);
    } else throw e;
  }
  const { script, notes } = parseRewrite(r.text);
  if (!script) throw new Error('AI không trả kịch bản đúng dạng <kich_ban>…</kich_ban>. Bấm lại thử.');
  return { script, notes, engine: used, ...(fallbackFrom ? { fallbackFrom } : {}), usage: r.usage, templateId: v.templateId, durationS: v.durationS };
}