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.3 KB
Raw Blame
// Chạy lô thử Lumfin bằng Anthropic API (khóa trong .env).
//  - Mẫu đã "rendered" → bỏ qua.
//  - Mẫu "coded" (đã có scene) → chỉ render (không tốn API).
//  - Mẫu chưa có gì → Haiku viết kịch bản (nếu chưa có) → job mode api (Haiku dựng cảnh, Opus duyệt 2 vòng) → render.
// Dùng: node tools/batch-lumfin.mjs [--budget 40] [--concurrency 3] [--only 001,002]
import fs from 'node:fs';
import path from 'node:path';
import Anthropic from '@anthropic-ai/sdk';
import { config, costOf } from '../generator/config.mjs';
import { createJob, runJob, renderJob, readJob, loadCatalog, jobDir } from '../generator/jobs.mjs';

const ROOT = config.root;
const T = path.join(ROOT, 'tests', 'lumfin');
const RES = path.join(T, 'results');
const SCR = path.join(T, 'scripts');
const STATE = path.join(T, 'batch-state.json');
fs.mkdirSync(RES, { recursive: true });
fs.mkdirSync(SCR, { recursive: true });

const arg = (k, d) => { const i = process.argv.indexOf('--' + k); return i > 0 ? process.argv[i + 1] : d; };
const BUDGET = Number(arg('budget', 40));
const CONC = Number(arg('concurrency', 3));
const ONLY = arg('only', '') ? arg('only').split(',') : null;

const state = fs.existsSync(STATE) ? JSON.parse(fs.readFileSync(STATE, 'utf8')) : { spentUSD: 0, jobs: {} };
const saveState = () => fs.writeFileSync(STATE, JSON.stringify(state, null, 1));
const log = (...a) => console.log(new Date().toTimeString().slice(0, 8), ...a);
const readRes = (id) => { try { return JSON.parse(fs.readFileSync(path.join(RES, id + '.json'), 'utf8')); } catch { return null; } };
const writeRes = (id, d) => fs.writeFileSync(path.join(RES, id + '.json'), JSON.stringify({ ...(readRes(id) || {}), ...d }, null, 1));

const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, maxRetries: 3 });

const LUMFIN = `Lumfin là app quản lý tiền cá nhân cho người Việt trẻ: ghi chi tiêu mỗi ngày, đặt ngân sách, để dành theo mục tiêu, học kiến thức tiền bạc qua bài ngắn. Giọng: thẳng, gần gũi, hơi hài.`;

async function writeScript(id, guidance, category) {
  const kind = category === 'ads'
    ? 'Quảng cáo cho app Lumfin (một tính năng/lợi ích + CTA "Tải Lumfin miễn phí"). Giữ phong cách hình của mẫu, đổi chủ thể cho hợp với tiền bạc (heo đất, ví, hoá đơn, sổ chi tiêu...).'
    : 'Một mẩu chuyện / mẹo / phép tính về tiền, kết bằng "Lumfin – <câu chốt ngắn>".';
  const msg = await client.messages.create({
    model: config.genModel(), max_tokens: 1500,
    messages: [{ role: 'user', content: `${LUMFIN}

Viết kịch bản cho 1 video dọc 8 giây theo mẫu dưới. ${kind}
Luật: 3–6 câu tiếng Việt đủ dấu; hợp với mục 2 "Hợp với nội dung nào"; chữ trên màn hình vừa giới hạn ký tự của từng ô ở mục 3; số tròn, nhẩm được, phép tính đúng; không hứa lãi, không bịa thống kê như thật (cần lãi suất thì ghi "giả định"). Chỉ trả về kịch bản, không giải thích.

GUIDANCE MẪU ${id}:
${guidance.split(/\n## 4\./)[0]}` }],
  });
  const c = costOf(config.genModel(), msg.usage);
  state.spentUSD += c;
  return { text: msg.content.filter((b) => b.type === 'text').map((b) => b.text).join('\n').trim(), cost: c };
}

async function doOne(t) {
  const id = t.id;
  const r = readRes(id);
  if (r?.stage === 'rendered') return;
  // đã có cảnh → chỉ render
  if (r?.jobId && fs.existsSync(path.join(jobDir(r.jobId), 'scene', 'index.html'))) {
    log(id, 'render cảnh có sẵn', r.jobId);
    const j = await renderJob(r.jobId);
    writeRes(id, { stage: j.status === 'done' ? 'rendered' : 'render_failed', error: j.error });
    log(id, j.status, j.error || '');
    return;
  }
  if (state.spentUSD >= BUDGET) { log(id, 'bỏ qua: chạm trần', BUDGET); return; }
  const guidance = fs.readFileSync(path.join(ROOT, 'templates', 'guidance', id + '.md'), 'utf8');
  const sf = path.join(SCR, id + '.txt');
  let scriptCost = 0;
  if (!fs.existsSync(sf)) {
    const s = await writeScript(id, guidance, t.category);
    fs.writeFileSync(sf, s.text);
    scriptCost = s.cost;
  }
  const job = createJob({ templateId: id, content: fs.readFileSync(sf, 'utf8'), mode: 'api', source: 'batch-lumfin' });
  state.jobs[id] = job.id; saveState();
  writeRes(id, { id, jobId: job.id, stage: 'generating' });
  log(id, 'job', job.id);
  const done = await runJob(job.id);
  const cost = (done.usage?.costUSD || 0) + scriptCost;
  state.spentUSD += done.usage?.costUSD || 0; saveState();
  writeRes(id, { stage: done.status === 'done' ? 'rendered' : 'failed', engine: 'api', costUSD: +cost.toFixed(4), error: done.error });
  log(id, done.status, `$${cost.toFixed(3)}`, `tổng $${state.spentUSD.toFixed(2)}`, done.error || '');
}

const queue = loadCatalog().filter((t) => !ONLY || ONLY.includes(t.id));
log(`lô ${queue.length} mẫu, trần $${BUDGET}, đã tiêu $${state.spentUSD.toFixed(2)}, chạy song song ${CONC}`);
let i = 0;
await Promise.all(Array.from({ length: CONC }, async () => {
  while (i < queue.length) {
    const t = queue[i++];
    try { await doOne(t); } catch (e) { log(t.id, 'LỖI', e.message); writeRes(t.id, { id: t.id, stage: 'failed', error: e.message }); }
  }
}));
log(`XONG. Tổng đã tiêu ước tính $${state.spentUSD.toFixed(2)}`);