Estilo Cartoon (Remotion), personagens reaproveitáveis e hashtags do TikTok
Estilo Cartoon (novo, sem Godot) - Pacote cartoon/ (Remotion 4.0.535): cada trecho é um spec JSON desenhado em React/SVG e renderizado em MP4; render em lote (empacota uma vez) e imagem parada (--still). - Cenas montadas por peças, sem cenário pronto: paletas (noite, sépia, dia, entardecer, cinza), lugar com chão, interno/externo, névoa e 24 peças posicionadas por profundidade, foco de luz e vinheta; etiquetas, onomatopeias, ondas de som, X vermelho, painel do topo e legenda palavra por palavra. - Montagem documental: "Cartoon" como estilo do vídeo e tipo de visual do trecho; plano por regras pelo texto (lugar, objetos, expressão, pose), tempos das palavras pela transcrição do áudio, "Gerar de novo" por trecho, paleta da série e elenco da história. Personagens - Aba Personagens: criar pela descrição, ajustar peça por peça com prévia ao vivo, refinar com o agente (tarefa nova "Personagem"); fichas em assets/characters/ e elenco em stories/<id>/cast.json. O mesmo personagem sai igual em qualquer cena, mudando expressão, pose e objeto na mão. TikTok - Hashtags passam a ser digitadas e confirmadas na lista de sugestões do TikTok Studio (coladas, viravam texto). Diagnóstico de alcance em doc/publicacao/TIKTOK_DIAGNOSTICO.md. Docs: estudo das referências, doc/cartoon/ (personagens e cenas) e skill cenaforge 1.46.0. Testes: painel 77/77, cartoon 5/5, Publicador 87/87. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -45,7 +45,7 @@ const CLAUDE_LEAN_FLAGS = ["--setting-sources", "project,local", "--strict-mcp-c
|
||||
* custou US$ 3,09 no Opus e o padrão agora é o Sonnet. Ao atingir, a CLI encerra a execução e o
|
||||
* usuário pode continuar a conversa pelo painel.
|
||||
*/
|
||||
export const CLAUDE_BUDGET_USD: Record<AgentKind, number> = { story: 1.5, script: 1.5, branches: 2.5, scene: 1, godot: 3, free: 3 };
|
||||
export const CLAUDE_BUDGET_USD: Record<AgentKind, number> = { story: 1.5, script: 1.5, branches: 2.5, scene: 1, godot: 3, free: 3, character: 0.5 };
|
||||
|
||||
export type ModelOption = { id: string; label: string };
|
||||
|
||||
@@ -98,13 +98,13 @@ export function models(): Record<Provider, ModelOption[]> {
|
||||
/** Modelo sugerido por tipo de tarefa (economia de tokens). */
|
||||
// Vertentes: roteiro + cena de 2–4 episódios numa execução só → Sonnet (qualidade de roteiro sem o custo do Opus).
|
||||
// Cena no Godot: Sonnet (a cena dos náufragos no Opus custou US$ 3,09 e esgotou o limite de 5 h em 11 min).
|
||||
export const DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "", script: "", scene: "claude-sonnet-5-5", branches: "claude-sonnet-5-5", godot: "claude-sonnet-5-5" };
|
||||
export const DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "", script: "", scene: "claude-sonnet-5-5", branches: "claude-sonnet-5-5", godot: "claude-sonnet-5-5", character: "claude-sonnet-5-5" };
|
||||
|
||||
/**
|
||||
* Agente preferido por tarefa (decisão do usuário: enredo e roteiro com GPT, via Codex).
|
||||
* Se o preferido não estiver disponível, cai para o outro.
|
||||
*/
|
||||
export const PREFERRED_PROVIDER: Record<AgentKind, Provider> = { free: "claude", story: "codex", script: "codex", scene: "claude", branches: "codex", godot: "claude" };
|
||||
export const PREFERRED_PROVIDER: Record<AgentKind, Provider> = { free: "claude", story: "codex", script: "codex", scene: "claude", branches: "codex", godot: "claude", character: "claude" };
|
||||
|
||||
export function defaultProviderFor(kind: AgentKind): Provider {
|
||||
const list = providers();
|
||||
@@ -123,7 +123,7 @@ export function defaultModelFor(kind: AgentKind, provider: Provider): string {
|
||||
* "frontier" do config.toml (GPT-6-Astra, o mais caro). "" = o padrão do config.toml. Só vale se o
|
||||
* modelo existir na lista da CLI; senão cai no padrão.
|
||||
*/
|
||||
const CODEX_DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "gpt-6.1-sol", script: "gpt-6.1-sol", branches: "gpt-6.1-sol", scene: "", godot: "" };
|
||||
const CODEX_DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "gpt-6.1-sol", script: "gpt-6.1-sol", branches: "gpt-6.1-sol", scene: "", godot: "", character: "" };
|
||||
|
||||
/** `command` + `prefixArgs` é o que de fato executamos (ex.: node + codex.js no Windows). */
|
||||
type ProviderInfo = {
|
||||
@@ -381,7 +381,7 @@ export function readEvents(id: number): AgentEvent[] {
|
||||
* de fatos; fica "medium". A cena no Godot (#8) gastou 14,5 mil: "medium". A cena JSON só roda
|
||||
* um script: "low". "" = o do config.toml.
|
||||
*/
|
||||
const CODEX_EFFORT: Record<AgentKind, string> = { story: "medium", script: "medium", branches: "medium", godot: "medium", scene: "low", free: "" };
|
||||
const CODEX_EFFORT: Record<AgentKind, string> = { story: "medium", script: "medium", branches: "medium", godot: "medium", scene: "low", free: "", character: "low" };
|
||||
|
||||
/** Plugins do Codex que não servem ao repositório: o de computer-use põe a ferramenta `cua_repl` (~6,5 mil caracteres) em todo turno. */
|
||||
const CODEX_UNUSED_PLUGINS = ["computer-use@openai-bundled", "unified-computer-use@openai-bundled"];
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
// Biblioteca de personagens: assets/characters/<id>/character.json. Um personagem é criado uma vez (da
|
||||
// descrição, ajustado no formulário ou pelo agente) e reaproveitado em qualquer história: o elenco da história
|
||||
// fica em stories/<id>/cast.json e a montagem Cartoon usa a mesma aparência em todas as cenas.
|
||||
// O contrato da aparência é o do pacote cartoon (cartoon/src/character.ts), importado direto daqui.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import {
|
||||
DEFAULT_LOOK, EXPRESSIONS, POSES, validateLook, type Character, type CharacterLook, type Expression, type Pose,
|
||||
} from "cenaforge-cartoon/character";
|
||||
import { REPO_ROOT, SLUG_RE, rel, storyDir } from "./paths";
|
||||
import { UserError } from "./stories";
|
||||
|
||||
export type { Character, CharacterLook, Expression, Pose };
|
||||
export { EXPRESSIONS, POSES };
|
||||
|
||||
export const CHARACTERS_DIR = path.join(REPO_ROOT, "assets", "characters");
|
||||
const fileOf = (id: string) => path.join(CHARACTERS_DIR, id, "character.json");
|
||||
|
||||
function mustId(id: string): string {
|
||||
if (!SLUG_RE.test(id)) throw new UserError("Identificador de personagem inválido.");
|
||||
return id;
|
||||
}
|
||||
|
||||
export function slugify(name: string): string {
|
||||
return name.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "personagem";
|
||||
}
|
||||
|
||||
export function listCharacters(): Character[] {
|
||||
if (!fs.existsSync(CHARACTERS_DIR)) return [];
|
||||
return fs.readdirSync(CHARACTERS_DIR, { withFileTypes: true })
|
||||
.filter((d) => d.isDirectory() && SLUG_RE.test(d.name))
|
||||
.map((d) => readCharacter(d.name))
|
||||
.filter((c): c is Character => !!c)
|
||||
.sort((a, b) => a.name.localeCompare(b.name, "pt-BR"));
|
||||
}
|
||||
|
||||
function readCharacter(id: string): Character | null {
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(fileOf(id), "utf8")) as Character;
|
||||
if (data.schemaVersion !== 1 || data.id !== id || validateLook(data.look).length) return null;
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getCharacter(id: string): Character | null {
|
||||
return readCharacter(mustId(id));
|
||||
}
|
||||
|
||||
function clean(raw: unknown, max: number): string {
|
||||
return String(raw ?? "").replace(/\s+/g, " ").trim().slice(0, max);
|
||||
}
|
||||
|
||||
/** Cria (id novo) ou salva (id existente). A aparência é conferida pelo contrato do cartoon. */
|
||||
export function saveCharacter(input: { id?: unknown; name?: unknown; caption?: unknown; description?: unknown; kind?: unknown; look?: unknown; godot?: unknown }, create = false): Character {
|
||||
const name = clean(input.name, 40);
|
||||
if (name.length < 2) throw new UserError("Dê um nome ao personagem.");
|
||||
const kind = input.kind === "3d" ? "3d" : "cartoon";
|
||||
const look = (input.look ?? DEFAULT_LOOK) as CharacterLook;
|
||||
const errors = validateLook(look);
|
||||
if (errors.length) throw new UserError(`Aparência inválida: ${errors.join("; ")}`);
|
||||
let id = input.id ? mustId(String(input.id)) : slugify(name);
|
||||
const existing = fs.existsSync(fileOf(id)) ? readCharacter(id) : null;
|
||||
if (create && existing) {
|
||||
let n = 2;
|
||||
while (fs.existsSync(fileOf(`${id}-${n}`))) n++;
|
||||
id = `${id}-${n}`;
|
||||
}
|
||||
if (!create && !existing) throw new UserError("Personagem não encontrado.");
|
||||
const now = new Date().toISOString();
|
||||
const character: Character = {
|
||||
schemaVersion: 1, id, name, kind, look,
|
||||
caption: clean(input.caption, 50) || undefined,
|
||||
description: clean(input.description, 600) || undefined,
|
||||
...(kind === "3d" && input.godot && typeof input.godot === "object" ? { godot: input.godot as Record<string, unknown> } : {}),
|
||||
createdAt: create || !existing ? now : existing.createdAt, updatedAt: now,
|
||||
};
|
||||
fs.mkdirSync(path.dirname(fileOf(id)), { recursive: true });
|
||||
fs.writeFileSync(fileOf(id), JSON.stringify(character, null, 2) + "\n", "utf8");
|
||||
return character;
|
||||
}
|
||||
|
||||
export function deleteCharacter(id: string): void {
|
||||
const dir = path.join(CHARACTERS_DIR, mustId(id));
|
||||
if (!fs.existsSync(dir)) throw new UserError("Personagem não encontrado.");
|
||||
const used = listCastUsage(id);
|
||||
if (used.length) throw new UserError(`Este personagem está no elenco de: ${used.join(", ")}. Tire-o do elenco antes de apagar.`);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
// ---------- descrição → aparência (regras; o agente pode refinar depois) ----------
|
||||
const COLORS: [RegExp, string][] = [
|
||||
[/verde/, "#56704a"], [/azul/, "#2f6db3"], [/vermelh/, "#c8443a"], [/amarel/, "#e8b13a"], [/roxo|lilas/, "#8e6ad8"], [/rosa/, "#e27ba8"],
|
||||
[/preto|preta/, "#26262e"], [/branc/, "#e9ecef"], [/cinza/, "#7c828c"], [/laranja/, "#e07b39"], [/marrom/, "#7a5232"], [/bege/, "#cdb48a"],
|
||||
];
|
||||
const HAIR_COLORS: [RegExp, string][] = [
|
||||
[/grisalh|cabelo branco|cabelos brancos/, "#c9c9cf"], [/loir/, "#e8c35a"], [/ruiv/, "#b4532a"], [/castanh/, "#6b4226"], [/cabelo preto|cabelos pretos/, "#1e1612"],
|
||||
];
|
||||
const PROFESSIONS: [RegExp, { top: CharacterLook["top"]; caption: string }][] = [
|
||||
[/engenheir/, { top: { style: "uniform", color: "#56704a", accent: "#e8b13a" }, caption: "Engenheiro" }],
|
||||
[/policial|delegad/, { top: { style: "uniform", color: "#2b3a67", accent: "#e8b13a" }, caption: "Policial" }],
|
||||
[/medic|enfermeir/, { top: { style: "jacket", color: "#e9ecef", accent: "#4fb0e8" }, caption: "Saúde" }],
|
||||
[/bombeir/, { top: { style: "uniform", color: "#c8352f", accent: "#f2c230" }, caption: "Bombeiro" }],
|
||||
[/militar|soldad/, { top: { style: "uniform", color: "#5b6b3a", accent: "#3a4a2a" }, caption: "Militar" }],
|
||||
[/professor/, { top: { style: "jacket", color: "#7a5232", accent: "#e9ecef" }, caption: "Professor" }],
|
||||
];
|
||||
|
||||
/** Aparência e legenda a partir de uma descrição curta ("Otávio, 58, engenheiro, barba grisalha, óculos"). */
|
||||
export function describeToLook(description: string): { look: CharacterLook; caption?: string } {
|
||||
const t = description.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
||||
const age = Number(/\b(\d{1,2})\s*(anos)?\b/.exec(t)?.[1] ?? NaN);
|
||||
const female = /\b(ela|mulher|moca|senhora|dona|menina|garota|vo|avo|tia|mae|filha|esposa)\b/.test(t);
|
||||
const child = /\b(crianca|menino|menina|garoto|garota)\b/.test(t) || (age > 0 && age <= 12);
|
||||
const old = age >= 55 || /\b(idos|velh|senhor|senhora|vo|avo)\w*/.test(t);
|
||||
const hairColor = HAIR_COLORS.find(([re]) => re.test(t))?.[1] ?? (old ? "#c9c9cf" : "#3a2a1e");
|
||||
const style: CharacterLook["hair"]["style"] = /careca|calvo/.test(t) ? "bald" : /coque/.test(t) ? "bun" : /bone\b/.test(t) ? "cap"
|
||||
: /cachead|crespo|black power/.test(t) ? "curly" : /espetad/.test(t) ? "spiky" : /cabelo (longo|comprido)|cabelos longos/.test(t) ? "long"
|
||||
: /repartid|de lado/.test(t) ? "side" : female ? (old ? "bun" : "long") : "short";
|
||||
const beard: CharacterLook["beard"]["style"] = female ? "none" : /barba por fazer/.test(t) ? "stubble" : /cavanhaque/.test(t) ? "goatee"
|
||||
: /bigode/.test(t) && !/barba/.test(t) ? "mustache" : /barb/.test(t) ? "full" : "none";
|
||||
const skin = /\b(negr[oa]|pret[oa]|pele escura)\b/.test(t) ? "#8d5a3b" : /\b(moren[oa]|pard[oa])\b/.test(t) ? "#c98a5e"
|
||||
: /\b(branc[oa]|pele clara|loir[oa]|ruiv[oa])\b/.test(t) ? "#f1c7a3" : "#e0b48f";
|
||||
const profession = PROFESSIONS.find(([re]) => re.test(t))?.[1];
|
||||
const clothColor = COLORS.find(([re]) => new RegExp(`(roupa|camisa|camiseta|vestido|jaqueta|casaco|moletom|blusa)\\s+\\w*\\s*${re.source}`).test(t))?.[1];
|
||||
const topStyle: CharacterLook["top"]["style"] = /vestido/.test(t) ? "dress" : /jaqueta|casaco/.test(t) ? "jacket" : /moletom/.test(t) ? "hoodie"
|
||||
: /uniforme|macacao/.test(t) ? "uniform" : profession?.top.style ?? (female && old ? "dress" : "shirt");
|
||||
const top = { ...(profession?.top ?? { style: topStyle, color: "#4f7a4a" }), style: topStyle, ...(clothColor ? { color: clothColor } : {}) };
|
||||
const look: CharacterLook = {
|
||||
build: /\b(gord[oa]|fort[e]|robust[oa]|grand[e]|gordinh[oa])\b/.test(t) ? "heavy" : /\b(magr[oa]|magrel[oa]|franzin[oa])\b/.test(t) || child ? "slim" : "average",
|
||||
height: child ? 0.78 : /\b(alt[oa])\b/.test(t) ? 1.08 : /\b(baix[oa]|baixinh[oa])\b/.test(t) ? 0.92 : female ? 0.96 : 1,
|
||||
skin,
|
||||
hair: { style, color: style === "cap" ? (COLORS.find(([re]) => new RegExp(`bone\\s+${re.source}`).test(t))?.[1] ?? "#2f6db3") : hairColor },
|
||||
beard: { style: beard, color: hairColor === "#c9c9cf" ? "#a9a9b0" : hairColor },
|
||||
glasses: /oculos escuros/.test(t) ? "sun" : /oculos quadrad/.test(t) ? "square" : /oculos/.test(t) ? "round" : "none",
|
||||
brows: old || /sobrancelha grossa|bravo|serio/.test(t) ? "thick" : "thin",
|
||||
top: top as CharacterLook["top"],
|
||||
bottom: { style: /\b(short|bermuda)\b/.test(t) || child ? "shorts" : /\bsaia\b/.test(t) ? "skirt" : "pants", color: female && /saia/.test(t) ? top.color : "#2c3346" },
|
||||
shoes: child ? "#f2f2f2" : "#1d1d24",
|
||||
};
|
||||
const caption = [profession?.caption, age > 0 ? `${age} anos` : ""].filter(Boolean).join(" · ") || undefined;
|
||||
return { look, caption };
|
||||
}
|
||||
|
||||
// ---------- elenco da história ----------
|
||||
const castFile = (storyId: string) => path.join(storyDir(storyId), "cast.json");
|
||||
|
||||
/** Elenco da história: ids dos personagens da biblioteca (os que sumiram da biblioteca são ignorados). */
|
||||
export function getCast(storyId: string): Character[] {
|
||||
try {
|
||||
const ids = JSON.parse(fs.readFileSync(castFile(storyId), "utf8")) as { cast?: string[] };
|
||||
return (ids.cast ?? []).map((id) => (SLUG_RE.test(id) ? readCharacter(id) : null)).filter((c): c is Character => !!c);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function setCast(storyId: string, ids: unknown): Character[] {
|
||||
if (!Array.isArray(ids) || ids.length > 12) throw new UserError("Elenco inválido (até 12 personagens).");
|
||||
const valid = [...new Set(ids.map(String))].filter((id) => SLUG_RE.test(id) && readCharacter(id));
|
||||
fs.mkdirSync(storyDir(storyId), { recursive: true });
|
||||
fs.writeFileSync(castFile(storyId), JSON.stringify({ cast: valid }, null, 2) + "\n", "utf8");
|
||||
return getCast(storyId);
|
||||
}
|
||||
|
||||
function listCastUsage(id: string): string[] {
|
||||
const root = path.join(REPO_ROOT, "stories");
|
||||
if (!fs.existsSync(root)) return [];
|
||||
return fs.readdirSync(root).filter((s) => {
|
||||
try { return (JSON.parse(fs.readFileSync(castFile(s), "utf8")) as { cast?: string[] }).cast?.includes(id); } catch { return false; }
|
||||
});
|
||||
}
|
||||
|
||||
export const characterFileRel = (id: string) => rel(fileOf(mustId(id)));
|
||||
@@ -0,0 +1,86 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { describeToLook } from "./characters";
|
||||
import { cartoonKey, cartoonSpec, planCartoon, wordTimings } from "./montage-cartoon";
|
||||
|
||||
const shot = (narration: string, onScreen = "", index = 0) => ({ index, narration, onScreen, visualHint: "" });
|
||||
|
||||
describe("estilo Cartoon: plano por regras", () => {
|
||||
it("gerador com barulho: objeto tremendo com ondas, onomatopeia e rua acesa à noite", () => {
|
||||
const plan = planCartoon(shot("Já o gerador faz barulho de moto ligada. Com a rua em silêncio, dá pra ouvir de longe à noite."));
|
||||
assert.equal(plan.props?.[0].icon, "generator");
|
||||
assert.equal(plan.props?.[0].shake, true);
|
||||
assert.equal(plan.props?.[0].rings, true);
|
||||
assert.deepEqual(plan.texts?.find((t) => t.kind === "onomatopoeia")?.text, "Vrrrum");
|
||||
assert.equal(plan.scene.time, "night");
|
||||
});
|
||||
|
||||
it("personagem com nome vira pessoa com etiqueta; 'nunca' risca o objeto", () => {
|
||||
const plan = planCartoon(shot("A Dona Cida avisa: nunca ligue o gerador dentro de casa."));
|
||||
const person = plan.actors?.find((a) => a.kind === "person");
|
||||
assert.equal(person && "label" in person ? person.label : "", "Dona Cida");
|
||||
assert.equal(plan.props?.[0].crossed, true);
|
||||
assert.equal(plan.props?.[0].tone, "danger");
|
||||
});
|
||||
|
||||
it("texto na tela numérico vira número grande; o resto vira etiqueta; multidão vira silhuetas", () => {
|
||||
assert.equal(planCartoon(shot("Um galão de gasolina dura pouco.", "20 L")).texts?.[0].kind, "big");
|
||||
const crowd = planCartoon(shot("Já tem dez pessoas no portão da casa acesa.", "Pessoas no portão"));
|
||||
assert.equal(crowd.texts?.[0].kind, "tag");
|
||||
assert.ok(crowd.actors?.some((a) => a.kind === "crowd"));
|
||||
});
|
||||
|
||||
it("assunto técnico vai para o diagrama; a variação troca o arranjo e a semente", () => {
|
||||
const a = planCartoon(shot("Quando a rede cai, o inversor desliga sozinho."), {}, 0);
|
||||
const b = planCartoon(shot("Quando a rede cai, o inversor desliga sozinho."), {}, 1);
|
||||
assert.equal(a.scene.kind, "blueprint");
|
||||
assert.notEqual(a.scene.kind, b.scene.kind);
|
||||
assert.notEqual(a.seed, b.seed);
|
||||
});
|
||||
|
||||
it("lugar pelo texto: cemitério vira lugar montado por peças, com névoa e lápides", () => {
|
||||
const plan = planCartoon(shot("À noite, no cemitério, ninguém respondeu."));
|
||||
assert.equal(plan.scene.kind, "place");
|
||||
assert.equal(plan.place?.fog, true);
|
||||
assert.ok(plan.place?.elements.some((e) => e.kind === "gravestone"));
|
||||
});
|
||||
|
||||
it("elenco: o personagem da biblioteca entra com a aparência dele, expressão e pose pelo texto", () => {
|
||||
const look = describeToLook("Otávio, 58 anos, engenheiro, careca, barba grisalha, óculos").look;
|
||||
const ctx = { cast: [{ id: "otavio", name: "Otávio", caption: "Engenheiro · 58 anos", look }], palette: "sepia" as const };
|
||||
const plan = planCartoon(shot("Otávio ficou com medo quando o ar acabou no bunker."), ctx);
|
||||
const actor = plan.actors?.find((a) => a.kind === "person");
|
||||
assert.ok(actor && actor.kind === "person" && actor.character);
|
||||
assert.equal(actor.character!.look.hair.style, "bald");
|
||||
assert.equal(actor.expression, "scared");
|
||||
assert.equal(plan.palette, "sepia");
|
||||
assert.equal(plan.light, "spot");
|
||||
});
|
||||
|
||||
it("descrição → aparência: idade, profissão, cabelo, barba, óculos e roupa", () => {
|
||||
const { look, caption } = describeToLook("Dona Cida, 70 anos, gordinha, coque, óculos, vestido roxo");
|
||||
assert.deepEqual([look.hair.style, look.glasses, look.top.style, look.top.color, look.build, look.beard.style], ["bun", "round", "dress", "#8e6ad8", "heavy", "none"]);
|
||||
assert.equal(caption, "70 anos");
|
||||
assert.equal(describeToLook("menino de 9 anos, cabelo cacheado").look.height, 0.78);
|
||||
});
|
||||
|
||||
it("a chave muda com a cena, a duração e o áudio", () => {
|
||||
const plan = planCartoon(shot("A rua está escura."));
|
||||
const k = cartoonKey(plan, 3.2, "abc");
|
||||
assert.notEqual(k, cartoonKey(plan, 3.3, "abc"));
|
||||
assert.notEqual(k, cartoonKey(plan, 3.2, "abd"));
|
||||
assert.equal(k, cartoonKey(plan, 3.2, "abc"));
|
||||
});
|
||||
|
||||
it("sem o serviço de voz, reparte as palavras pela duração (em ordem, dentro do trecho, com cor)", async () => {
|
||||
const plan = planCartoon(shot("O gerador nunca fica dentro de casa."));
|
||||
const words = await wordTimings({ repoRoot: "/nao/existe", audio: "x.ogg", spoken: "O gerador nunca fica dentro de casa.", durationS: 3, scene: plan });
|
||||
assert.equal(words.length, 7);
|
||||
assert.ok(words.every((w, i) => w.endS > w.startS && (i === 0 || w.startS >= words[i - 1].endS - 1e-9)));
|
||||
assert.ok(words[words.length - 1].endS <= 3);
|
||||
assert.equal(words.find((w) => w.text === "gerador")?.tone, "key");
|
||||
assert.equal(words.find((w) => w.text === "nunca")?.tone, "danger");
|
||||
const spec = cartoonSpec(plan, 3.0004, words);
|
||||
assert.deepEqual([spec.schemaVersion, spec.width, spec.height, spec.fps, spec.durationS], [1, 1080, 1920, 30, 3]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
// Estilo "Cartoon" da montagem documental: cada trecho vira uma cena 2D vetorial renderizada pela Remotion
|
||||
// (pacote cartoon/ na raiz). Aqui ficam o plano por regras (texto do trecho → cena, objetos, etiquetas,
|
||||
// onomatopeia), os tempos de cada palavra (transcrição do áudio do trecho, para a legenda palavra por palavra)
|
||||
// e a chamada do render (todos os trechos numa execução só: empacota uma vez).
|
||||
//
|
||||
// Os tipos vêm do contrato do pacote cartoon (cartoon/src/spec.ts); o render valida de novo.
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import type { CharacterLook, Expression, Pose } from "cenaforge-cartoon/character";
|
||||
import type { IconId, ShotSpec, Word } from "cenaforge-cartoon/spec";
|
||||
import type { JobHook } from "./montage-ffmpeg";
|
||||
import { transcribe } from "./voice";
|
||||
|
||||
export type CartoonIcon = IconId;
|
||||
type Tone = "info" | "danger" | "ok";
|
||||
/** O que o plano decide por trecho: o spec sem tamanho, duração e palavras. */
|
||||
export type CartoonScene = Omit<ShotSpec, "schemaVersion" | "width" | "height" | "fps" | "durationS" | "words">;
|
||||
export type CartoonWord = Word;
|
||||
export type CartoonSpec = ShotSpec & { words: Word[] };
|
||||
type Place = NonNullable<ShotSpec["place"]>;
|
||||
type PaletteId = NonNullable<ShotSpec["palette"]>;
|
||||
/** Personagem do elenco da história (biblioteca), como entra no plano. */
|
||||
export type CastMember = { id: string; name: string; caption?: string; look: CharacterLook };
|
||||
export type PlanContext = { hud?: CartoonScene["hud"]; cast?: CastMember[]; palette?: PaletteId };
|
||||
|
||||
type ShotText = { index: number; narration: string; onScreen: string; visualHint: string };
|
||||
|
||||
const norm = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
||||
|
||||
/** Palavra do texto → objeto na cena (e etiqueta). A ordem é a prioridade. */
|
||||
const ICON_RULES: [RegExp, CartoonIcon, string][] = [
|
||||
[/\bgerador/, "generator", "Gerador"],
|
||||
[/gasolina|combustivel|diesel|galao/, "fuel", "Combustível"],
|
||||
[/bateria/, "battery", "Bateria"],
|
||||
[/celular|telefone|carregar o/, "phone", "Celular"],
|
||||
[/placa solar|painel solar|energia solar/, "solar", "Placa solar"],
|
||||
[/\bporta\b|portao/, "door", "Porta"],
|
||||
[/dinheiro|reais|r\$|\bpagar|preco|custa/, "money", "Dinheiro"],
|
||||
[/lanterna|lampada|\bluz\b|acesa|aceso/, "bulb", "Luz"],
|
||||
[/\bhoras?\b|minutos?\b|relogio/, "clock", "Tempo"],
|
||||
[/perigo|cuidado|risco|veneno|\bmata\b|morte|morre/, "warning", "Perigo"],
|
||||
[/\bver\b|olho|vigia|observ|enxerg|ninguem precisa ver/, "eye", "Olho"],
|
||||
];
|
||||
const DANGER = /\b(nunca|perigo|mata|morte|morre|morrer|risco|cuidado|proibido|veneno|alvo|visad\w*|ataque|roub\w*)\b/;
|
||||
const SOUNDS: [RegExp, string][] = [
|
||||
// Motor só quando o texto fala de motor/gerador/veículo; "um barulho" solto vira um estalo genérico.
|
||||
[/(gerador|motor|moto|carro|caminhao|onibus)\w*.{0,40}(barulho|ronco|ligad)|ronco do motor|moto ligada/, "Vrrrum"],
|
||||
[/\bbate\b|batida|bateu|bater na/, "Toc toc toc"],
|
||||
[/cachorro|\blate\b|latido/, "Au au"],
|
||||
[/explos|estouro|\btiros?\b/, "Bum!"],
|
||||
[/barulho|estalo|rangeu|range\b|passos/, "Crec"],
|
||||
];
|
||||
const OUTFITS = ["#9b7be0", "#f2c230", "#4fb0e8", "#e86a5c", "#5cc48a"];
|
||||
|
||||
type El = Place["elements"][number];
|
||||
/** Lugares reconhecidos pelo texto → chão, interno?, névoa, paleta sugerida e peças (posições variam pela semente). */
|
||||
const LOCATIONS: { re: RegExp; ground: Place["ground"]; indoor?: boolean; fog?: boolean; palette?: PaletteId; light?: ShotSpec["light"]; pieces: El["kind"][] }[] = [
|
||||
{ re: /cemiterio|tumulo|enterr|velorio/, ground: "dirt", fog: true, palette: "dusk", light: "vignette", pieces: ["gravestone", "gravestone", "cross", "deadtree", "fence", "gravestone"] },
|
||||
{ re: /bunker|porao|abrigo|subsolo|esconderijo/, ground: "floor", indoor: true, palette: "sepia", light: "spot", pieces: ["shelf", "crate", "crate", "door"] },
|
||||
{ re: /hospital|consultorio|escritorio|delegacia|escola|sala de aula/, ground: "floor", indoor: true, pieces: ["window", "table", "door", "shelf"] },
|
||||
{ re: /\b(casa|sala|quarto|cozinha|apartamento)\b/, ground: "floor", indoor: true, pieces: ["window", "table", "shelf", "door", "bed"] },
|
||||
{ re: /parque|praca|jardim/, ground: "grass", pieces: ["tree", "tree", "bench", "lamp", "bush", "cloud", "building", "pine"] },
|
||||
{ re: /floresta|mata\b|trilha|bosque|selva/, ground: "grass", pieces: ["pine", "pine", "tree", "rock", "bush", "pine", "mountain"] },
|
||||
{ re: /acampamento|fogueira|barraca/, ground: "grass", pieces: ["tent", "fire", "pine", "pine", "rock"] },
|
||||
{ re: /praia|litoral|areia|\bmar\b/, ground: "sand", pieces: ["rock", "cloud", "cloud", "rock"] },
|
||||
{ re: /sitio|fazenda|roca|campo\b|interior/, ground: "grass", pieces: ["house", "fence", "tree", "mountain", "bush", "cloud"] },
|
||||
{ re: /\b(rua|cidade|bairro|avenida|estrada|transito|vizinh)\w*/, ground: "street", pieces: ["building", "building", "lamp", "house", "car", "sign"] },
|
||||
];
|
||||
|
||||
/** Monta o lugar: peças espalhadas pela semente, longe do centro (onde fica o personagem). */
|
||||
function placeFor(text: string, seed: number, variant: number): { place: Place; palette?: PaletteId; light?: ShotSpec["light"] } | null {
|
||||
const loc = LOCATIONS.find((l) => l.re.test(text));
|
||||
if (!loc) return null;
|
||||
let a = (seed * 9301 + 49297 + variant * 233) % 233280;
|
||||
const rand = () => (a = (a * 9301 + 49297) % 233280) / 233280;
|
||||
const slots = [0.12, 0.88, 0.25, 0.75, 0.06, 0.94, 0.4, 0.62];
|
||||
const elements: El[] = loc.pieces.map((kind, i) => ({
|
||||
kind, x: slots[(i + variant) % slots.length] + (rand() - 0.5) * 0.06,
|
||||
z: kind === "mountain" || kind === "building" ? 0.95 : kind === "cloud" ? 0.3 + rand() * 0.4 : 0.25 + rand() * 0.6,
|
||||
flip: rand() > 0.5,
|
||||
}));
|
||||
return { place: { ground: loc.ground, indoor: loc.indoor, fog: loc.fog, elements }, palette: loc.palette, light: loc.light };
|
||||
}
|
||||
|
||||
function expressionOf(text: string): Expression {
|
||||
if (/\b(medo|apavorad|assust|pavor|terror|socorro)\w*/.test(text)) return "scared";
|
||||
if (/\b(raiva|bravo|brava|irritad|furios|grit)\w*/.test(text)) return "angry";
|
||||
if (/de repente|surpres|choc|nao acredit|inacredit/.test(text)) return "surprised";
|
||||
if (/\b(trist|chor|perdeu|saudade|sozinh)\w*/.test(text)) return "sad";
|
||||
if (DANGER.test(text) || /\b(preocup|problema|nervos|ansios)\w*/.test(text)) return "worried";
|
||||
if (/\b(feliz|alegr|comemor|sorri|riu|rindo|venceu|conseguiu)\w*/.test(text)) return "happy";
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
function poseOf(text: string, hasProp: boolean): Pose {
|
||||
if (/acen|tchau|chamou/.test(text)) return "wave";
|
||||
if (/comemor|venceu|gritou de alegria/.test(text)) return "arms_up";
|
||||
if (/pens|lembr|imagin|calcul|planej/.test(text)) return "think";
|
||||
if (/nao sabe|sem saber|nao entend/.test(text)) return "shrug";
|
||||
return hasProp ? "point" : "stand";
|
||||
}
|
||||
|
||||
/** Plano do trecho por regras do texto (narração + texto na tela + coluna Imagem). `variant` troca o arranjo. */
|
||||
export function planCartoon(shot: ShotText, ctx: PlanContext = {}, variant = 0): CartoonScene {
|
||||
const original = `${shot.narration} ${shot.onScreen} ${shot.visualHint}`;
|
||||
const text = norm(original);
|
||||
const time = /noite|madrugada|escuro|meia-noite/.test(text) ? "night"
|
||||
: /amanhecer|sol nasce|amanhece|de madrugada/.test(text) ? "dawn"
|
||||
: /\btarde\b|meio-dia|de dia\b|\bsol\b|ensolarad|\bmanha\b|domingo|claro\b/.test(text) ? "day" : "night";
|
||||
|
||||
const named = /\b(Dona|Seu|Tio|Tia|Doutor|Doutora)\s+([A-ZÁ-Ú][a-zá-ú]+)/.exec(original);
|
||||
const crowd = /\b(pessoas|gente|multidao|vizinhos|fila|moradores|todo mundo)\b/.test(text);
|
||||
const sound = SOUNDS.find(([re]) => re.test(text));
|
||||
const icons = ICON_RULES.filter(([re]) => re.test(text)).slice(0, named ? 1 : 2);
|
||||
const danger = DANGER.test(text);
|
||||
const negated = danger && /\b(nunca|nao)\b/.test(text);
|
||||
|
||||
const props: NonNullable<CartoonScene["props"]> = icons.map(([, icon, label], i) => {
|
||||
const x = named ? 0.7 : icons.length === 1 ? 0.5 : i === 0 ? 0.3 : 0.72;
|
||||
return {
|
||||
icon, x, y: 0.46, size: icons.length === 1 && !named ? 0.17 : 0.13, label, enterS: 0.3 + i * 0.5,
|
||||
tone: danger && i === 0 ? "danger" : "info",
|
||||
shake: !!sound && i === 0 && (icon === "generator" || icon === "door"),
|
||||
rings: (!!sound && i === 0) || /chama atencao|da pra ouvir|de longe/.test(text),
|
||||
crossed: negated && i === 0,
|
||||
};
|
||||
});
|
||||
const actors: NonNullable<CartoonScene["actors"]> = [];
|
||||
// Elenco da história: quem é citado pelo nome; sem citação e com um protagonista só, ele aparece nos trechos
|
||||
// pares ou quando o texto fala "ele/ela" (fio condutor, como o Otávio da referência).
|
||||
const cast = ctx.cast ?? [];
|
||||
const firstName = (n: string) => norm(n.split(/\s+/)[0]);
|
||||
let castIn = cast.filter((c) => new RegExp(`\\b${firstName(c.name)}\\b`).test(text));
|
||||
if (!castIn.length && cast.length === 1 && !crowd && (shot.index % 2 === 0 || /\b(ele|ela)\b/.test(text))) castIn = [cast[0]];
|
||||
castIn.slice(0, 2).forEach((c, i) => {
|
||||
actors.push({
|
||||
kind: "person", x: castIn.length > 1 ? (i === 0 ? 0.3 : 0.7) : props.length ? 0.34 : 0.5, y: 0.74, enterS: 0.15 + i * 0.3,
|
||||
character: { name: c.name, caption: i === 0 && shot.index === 0 ? c.caption : undefined, look: c.look },
|
||||
expression: expressionOf(text), pose: i === 0 ? poseOf(text, props.length > 0) : "stand",
|
||||
item: i === 0 && props.length === 1 && ["phone", "fuel", "battery", "money", "bulb"].includes(props[0].icon) ? props[0].icon : undefined,
|
||||
flip: i === 1,
|
||||
});
|
||||
});
|
||||
// Objeto que o personagem segura sai do chão; os outros vão para o lado oposto ao personagem.
|
||||
if (castIn.length) {
|
||||
const held = actors[0] && "item" in actors[0] ? actors[0].item : undefined;
|
||||
for (let i = props.length - 1; i >= 0; i--) if (props[i].icon === held) props.splice(i, 1);
|
||||
props.forEach((p) => { p.x = 0.74; p.y = 0.5; });
|
||||
}
|
||||
if (named && !castIn.length) {
|
||||
const older = /^(Dona|Tia)$/.test(named[1]);
|
||||
actors.push({ kind: "person", x: props.length ? 0.32 : 0.5, y: 0.6, label: `${named[1]} ${named[2]}`, enterS: 0.2,
|
||||
outfit: OUTFITS[(shot.index + variant) % OUTFITS.length], hair: older ? "bun" : "short",
|
||||
hairColor: older ? "#e8e8ee" : "#3a2a1e", glasses: older, pointing: props.length > 0 });
|
||||
}
|
||||
// Multidão atrás do personagem: entra primeiro (desenhada antes) e com os pés acima dos dele.
|
||||
if (crowd) actors.unshift({ kind: "crowd", count: 9 + (shot.index % 4), y: actors.some((a) => a.kind === "person") ? 0.6 : 0.66, enterS: 0.4 });
|
||||
|
||||
const technical = /funciona|liga\b|desliga|inversor|rede eletrica|circuito|sistema|corrente/.test(text);
|
||||
const kinds: CartoonScene["scene"]["kind"][] = technical ? ["blueprint", "plain"]
|
||||
: named || crowd ? (/portao|porta|frente|calcada/.test(text) ? ["house", "street"] : ["street", "house"])
|
||||
: props.length ? ["plain", "street"] : ["street", "plain"];
|
||||
let kind: CartoonScene["scene"]["kind"] = kinds[variant % kinds.length];
|
||||
// Lugar montado por peças quando o texto diz onde é (ou quando a história tem elenco/paleta: tudo vira lugar).
|
||||
const built = technical ? null : placeFor(text, shot.index * 7 + 1, variant)
|
||||
?? (cast.length || ctx.palette ? placeFor("rua", shot.index * 7 + 1, variant) : null);
|
||||
if (built) kind = "place";
|
||||
|
||||
const texts: NonNullable<CartoonScene["texts"]> = [];
|
||||
const onScreen = shot.onScreen.trim();
|
||||
if (onScreen) {
|
||||
const numeric = /^\W*[\d.,]+\s*\S{0,8}\W*$/.test(onScreen);
|
||||
texts.push(numeric
|
||||
? { kind: "big", text: onScreen, x: 0.5, y: 0.27, atS: 0.2, tone: danger ? "danger" : "info" }
|
||||
: { kind: "tag", text: onScreen.slice(0, 40), x: 0.5, y: 0.17, atS: 0.1, tone: danger ? "danger" : "info" });
|
||||
}
|
||||
// Onomatopeia longe da etiqueta do personagem (que fica acima da cabeça, perto do centro).
|
||||
if (sound) texts.push({ kind: "onomatopoeia", text: sound[1], x: props[0]?.x ?? (actors.some((a) => a.kind === "person") ? 0.76 : 0.62), y: props.length ? 0.33 : 0.24, atS: 0.7, rotate: -6 });
|
||||
|
||||
const timePalette: PaletteId = time === "day" ? "day" : time === "dawn" ? "dusk" : "night";
|
||||
return {
|
||||
seed: shot.index * 7 + variant * 101 + 1,
|
||||
scene: { kind, time, litHouse: kind === "street" && /acesa|aceso|luz|iluminad|gerador/.test(text) },
|
||||
...(built ? { place: built.place, palette: ctx.palette ?? built.palette ?? timePalette, ...(built.light ? { light: built.light } : {}) } : ctx.palette ? { palette: ctx.palette } : {}),
|
||||
camera: { push: 1.05 + ((shot.index + variant) % 3) * 0.02, panX: kind === "street" ? (shot.index % 2 ? 0.05 : -0.05) : 0 },
|
||||
...(ctx.hud ? { hud: ctx.hud } : {}),
|
||||
actors, props, texts,
|
||||
};
|
||||
}
|
||||
|
||||
/** Chave da versão renderizada: muda se a cena, a duração ou o áudio (texto falado, voz, velocidade) mudarem. */
|
||||
export function cartoonKey(scene: CartoonScene, durationS: number, audioKey: string): string {
|
||||
let h = 0;
|
||||
for (const ch of JSON.stringify([scene, Math.round(durationS * 1000), audioKey])) h = (Math.imul(h, 31) + ch.codePointAt(0)!) | 0;
|
||||
return (h >>> 0).toString(36);
|
||||
}
|
||||
|
||||
/** Cor da palavra na legenda: perigo em vermelho; número e as palavras dos objetos da cena em amarelo. */
|
||||
function toneOf(word: string, keywords: Set<string>): CartoonWord["tone"] {
|
||||
const w = norm(word).replace(/[^\p{L}\p{N}$]/gu, "");
|
||||
if (!w) return undefined;
|
||||
if (DANGER.test(w)) return "danger";
|
||||
if (/\d/.test(w) || keywords.has(w)) return "key";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function keywordsOf(scene: CartoonScene): Set<string> {
|
||||
const words = [...(scene.props ?? []).map((p) => p.label ?? ""), ...(scene.texts ?? []).map((t) => t.text)].join(" ");
|
||||
return new Set(norm(words).split(/[^\p{L}\p{N}]+/u).filter((w) => w.length > 3));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tempos de cada palavra da fala do trecho: transcreve o áudio gerado (o serviço de voz devolve palavras com
|
||||
* início/fim). Sem o serviço, reparte o texto falado pela duração (a legenda ainda acompanha, menos exata).
|
||||
*/
|
||||
export async function wordTimings(input: { repoRoot: string; audio: string; spoken: string; durationS: number; scene: CartoonScene; log?: (line: string) => void }): Promise<CartoonWord[]> {
|
||||
const keywords = keywordsOf(input.scene);
|
||||
try {
|
||||
const bytes = fs.readFileSync(path.join(input.repoRoot, input.audio));
|
||||
const result = await transcribe(new File([new Uint8Array(bytes)], path.basename(input.audio), { type: "audio/ogg" }), "pt-BR", "words");
|
||||
const words = (result.segments ?? []).flatMap((s) => s.words ?? []).filter((w) => w.text.trim());
|
||||
if (words.length) {
|
||||
return words.map((w) => ({ text: w.text.trim(), startS: Math.max(0, w.start), endS: Math.max(w.start, w.end), tone: toneOf(w.text, keywords) }));
|
||||
}
|
||||
} catch (error) {
|
||||
input.log?.(`tempos das palavras (${path.basename(input.audio)}): ${(error as Error).message}; repartindo pelo texto`);
|
||||
}
|
||||
const spoken = input.spoken.split(/\s+/).filter(Boolean);
|
||||
const span = Math.max(0.5, input.durationS - 0.4);
|
||||
const total = spoken.reduce((n, w) => n + w.length + 2, 0);
|
||||
let t = 0.05;
|
||||
return spoken.map((w) => {
|
||||
const d = (span * (w.length + 2)) / total;
|
||||
const word = { text: w, startS: t, endS: t + d, tone: toneOf(w, keywords) };
|
||||
t += d;
|
||||
return word;
|
||||
});
|
||||
}
|
||||
|
||||
/** Monta o spec completo de um trecho (o que o render recebe). */
|
||||
export function cartoonSpec(scene: CartoonScene, durationS: number, words: CartoonWord[]): CartoonSpec {
|
||||
return { schemaVersion: 1, width: 1080, height: 1920, fps: 30, durationS: Math.round(durationS * 1000) / 1000, ...scene, words };
|
||||
}
|
||||
|
||||
/**
|
||||
* Renderiza vários trechos numa execução do `cartoon/render.ts` (empacota a cena uma vez só). Grava cada spec
|
||||
* em `specDir`, devolve os MP4 (caminhos relativos à raiz) na mesma ordem.
|
||||
*/
|
||||
export async function renderCartoonShots(input: {
|
||||
repoRoot: string; specDir: string; outDir: string; shots: { name: string; spec: CartoonSpec }[]; hook?: JobHook; log?: (line: string) => void;
|
||||
}): Promise<string[]> {
|
||||
const tsxCli = path.join(input.repoRoot, "node_modules", "tsx", "dist", "cli.mjs");
|
||||
if (!fs.existsSync(tsxCli)) throw new Error("tsx não encontrado; rode pnpm install na raiz do projeto.");
|
||||
if (!fs.existsSync(path.join(input.repoRoot, "cartoon", "node_modules", "remotion"))) {
|
||||
throw new Error("O estilo Cartoon não está instalado: rode pnpm install na raiz do projeto.");
|
||||
}
|
||||
fs.mkdirSync(input.specDir, { recursive: true });
|
||||
fs.mkdirSync(input.outDir, { recursive: true });
|
||||
const relTo = (p: string) => path.relative(input.repoRoot, p).split(path.sep).join("/");
|
||||
const jobs = input.shots.map((s) => {
|
||||
const specFile = path.join(input.specDir, `${s.name}.json`);
|
||||
fs.writeFileSync(specFile, JSON.stringify(s.spec, null, 2) + "\n", "utf8");
|
||||
return { spec: relTo(specFile), out: relTo(path.join(input.outDir, `${s.name}.mp4`)) };
|
||||
});
|
||||
const jobsFile = path.join(input.specDir, "_jobs.json");
|
||||
fs.writeFileSync(jobsFile, JSON.stringify(jobs, null, 2) + "\n", "utf8");
|
||||
const output = await new Promise<string>((resolve, reject) => {
|
||||
const child = spawn(process.execPath, [tsxCli, "cartoon/render.ts", "--jobs", relTo(jobsFile)], {
|
||||
cwd: input.repoRoot, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
input.hook?.onChild(child);
|
||||
let out = "";
|
||||
child.stdout.on("data", (d) => { out += d; for (const line of String(d).split("\n")) if (line.startsWith("ok ")) input.log?.(`cartoon: ${line.trim()}`); });
|
||||
child.stderr.on("data", (d) => (out += d));
|
||||
child.on("error", reject);
|
||||
child.on("close", (code) => {
|
||||
input.hook?.onChild(null);
|
||||
if (input.hook?.cancelled()) return reject(new Error("cancelado pelo painel"));
|
||||
const report = out.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("{")).pop();
|
||||
let parsed: { ok?: boolean; error?: string } = {};
|
||||
try { parsed = report ? JSON.parse(report) : {}; } catch { /* sem relatório */ }
|
||||
if (code !== 0 || !parsed.ok) return reject(new Error(`render Cartoon: ${parsed.error ?? out.split("\n").filter(Boolean).slice(-4).join(" | ")}`));
|
||||
resolve(out);
|
||||
});
|
||||
});
|
||||
void output;
|
||||
return jobs.map((j) => {
|
||||
if (!fs.existsSync(path.resolve(input.repoRoot, j.out))) throw new Error(`render Cartoon: ${j.out} não foi gerado`);
|
||||
return j.out;
|
||||
});
|
||||
}
|
||||
+124
-16
@@ -2,7 +2,8 @@
|
||||
// - um ÁUDIO próprio, gerado parágrafo a parágrafo pelo serviço de voz (frase longa numa
|
||||
// tacada só deixa a voz estranha) a partir do "texto falado" (números por extenso);
|
||||
// - um VISUAL: imagem (com movimento lento), clipe de vídeo, cena 3D renderizada pelo Godot,
|
||||
// ou cartela de texto. O trecho dura o tempo do próprio áudio.
|
||||
// cena Cartoon (2D vetorial pela Remotion, pacote cartoon/) ou cartela de texto. O trecho dura o
|
||||
// tempo do próprio áudio.
|
||||
// Depois o FFmpeg monta um segmento por trecho (visual + texto na tela + legenda + áudio) e
|
||||
// concatena tudo num MP4 vertical 1080x1920. O estado fica em stories/<id>/<file_key>.montage.json.
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
@@ -14,6 +15,8 @@ import { DATA_DIR, OUTPUT_DIR, REPO_ROOT, STORIES_DIR, readTextIfExists, rel, re
|
||||
import { LAST_PAD_S, PAD_S, buildCredits, buildSegment, concatSegments, ffmpegBin, fontFile, probeDuration, type JobHook } from "./montage-ffmpeg";
|
||||
import { downloadImage, searchFirst } from "./image-search";
|
||||
import { DOC2D_TEMPLATES, planScene, planShot, planShot3d, renderGodotScene, sceneKey, scriptEntities, type Doc2DScene } from "./montage-godot";
|
||||
import { getCast } from "./characters";
|
||||
import { cartoonKey, cartoonSpec, planCartoon, renderCartoonShots, wordTimings, type CartoonScene, type PlanContext } from "./montage-cartoon";
|
||||
import { listLibrary, paramsFor } from "./scene-library";
|
||||
import { killTree } from "./proc";
|
||||
import { parseScript } from "./script-doc";
|
||||
@@ -22,7 +25,9 @@ import { UserError, getEpisodeById, getStory, touchStory } from "./stories";
|
||||
import type { AssetKind, EpisodeView, RenderJob } from "./types";
|
||||
import { getStatus, synthesize } from "./voice";
|
||||
|
||||
export type VisualKind = "image" | "video" | "godot3d" | "card" | "godot2d";
|
||||
export type VisualKind = "image" | "video" | "godot3d" | "card" | "godot2d" | "cartoon";
|
||||
/** "mixed": foto, 2D e 3D, o que combinar; "3d": tudo em cena 3D; "cartoon": tudo em desenho 2D chapado (Remotion). */
|
||||
export type MontageStyle = "mixed" | "3d" | "cartoon";
|
||||
|
||||
/** Estilos de visual por trecho (dá para misturar no mesmo vídeo). */
|
||||
export const VISUAL_KINDS: { id: VisualKind; label: string; available: boolean; hint: string }[] = [
|
||||
@@ -30,6 +35,7 @@ export const VISUAL_KINDS: { id: VisualKind; label: string; available: boolean;
|
||||
{ id: "godot2d", label: "Animação 2D", available: true, hint: "Mapa, infográfico ou título animados no Godot, com o tempo exato da fala." },
|
||||
{ id: "godot3d", label: "Cena 3D", available: true, hint: "Cena 3D da biblioteca do Godot (ilha, estádio...), com a câmera e as opções da cena." },
|
||||
{ id: "video", label: "Clipe", available: true, hint: "Um clipe enviado por você ou um vídeo já renderizado no painel." },
|
||||
{ id: "cartoon", label: "Cartoon", available: true, hint: "Desenho 2D chapado (rua, personagens, etiquetas, onomatopeias) com legenda palavra por palavra." },
|
||||
{ id: "card", label: "Cartela", available: true, hint: "Fundo escuro com o texto na tela em destaque." },
|
||||
];
|
||||
|
||||
@@ -39,6 +45,9 @@ export type ShotVisual = {
|
||||
scene?: Doc2DScene; sceneKey?: string;
|
||||
/** Imagem da internet: buscas usadas e qual resultado está em uso ("gerar de novo" pega o próximo). */
|
||||
search?: { queries: string[]; pick: number };
|
||||
/** cartoon: a cena planejada (cartoon/src/spec.ts, sem duração e palavras), a variação do "Gerar de novo" e a
|
||||
* chave da versão renderizada em "file". */
|
||||
cartoon?: CartoonScene; cartoonVariant?: number; cartoonKey?: string;
|
||||
/** Cartão de foto por cima da cena (modo 3D): a foto real da cobra sobre a ilha, por exemplo. */
|
||||
inset?: { file: string; credit: string; license: string; sourceUrl: string; search?: { queries: string[]; pick: number } } | null;
|
||||
/** Escolhido pelo modo automático (o "Refazer tudo do zero" replaneja só estes). */
|
||||
@@ -65,15 +74,20 @@ export type Montage = {
|
||||
voiceId: string;
|
||||
speed: number;
|
||||
captions: boolean;
|
||||
style: "mixed" | "3d";
|
||||
style: MontageStyle;
|
||||
cartoonPalette: string;
|
||||
shots: MontageShot[];
|
||||
/** Fontes do roteiro (domínios), para a cartela final. */
|
||||
sourceHosts: string[];
|
||||
};
|
||||
|
||||
type SavedShot = { spoken?: string; visual?: ShotVisual; audio?: ShotAudio };
|
||||
/** style: "mixed" (foto, 2D e 3D, o que combinar) ou "3d" (tudo em cena 3D; fotos em cartão por cima). */
|
||||
type SavedMontage = { version: 1; voiceId: string; speed: number; captions: boolean; style?: "mixed" | "3d"; shots: Record<string, SavedShot> };
|
||||
/** style: "mixed" (foto, 2D e 3D, o que combinar), "3d" (tudo em cena 3D; fotos em cartão por cima) ou "cartoon". */
|
||||
type SavedMontage = {
|
||||
version: 1; voiceId: string; speed: number; captions: boolean; style?: MontageStyle; shots: Record<string, SavedShot>;
|
||||
/** Paleta do estilo Cartoon escolhida para o vídeo (vazio = pela hora de cada trecho). */
|
||||
cartoonPalette?: (typeof CARTOON_PALETTES)[number];
|
||||
};
|
||||
|
||||
const EMPTY_VISUAL: ShotVisual = { kind: "image", file: null, credit: "", license: "", sourceUrl: "" };
|
||||
/** Pastas de onde um visual pode vir (nada fora do projeto). */
|
||||
@@ -135,12 +149,12 @@ export function loadMontage(episodeId: number): Montage {
|
||||
const sources = doc.sections.find((s) => s.role === "sources");
|
||||
const sourceHosts = [...new Set((sources ? JSON.stringify(sources.blocks) : "").match(/https?:\/\/[^/\s"]+/g) ?? [])]
|
||||
.map((u) => u.replace(/^https?:\/\/(www\.)?/, ""));
|
||||
return { episodeId, voiceId: saved.voiceId, speed: saved.speed, captions: saved.captions, style: saved.style ?? "mixed", shots, sourceHosts };
|
||||
return { episodeId, voiceId: saved.voiceId, speed: saved.speed, captions: saved.captions, style: saved.style ?? "mixed", cartoonPalette: saved.cartoonPalette ?? "", shots, sourceHosts };
|
||||
}
|
||||
|
||||
/** Ajustes da montagem: voz, velocidade, legenda e, por trecho, texto falado e visual. */
|
||||
export function updateMontage(episodeId: number, patch: {
|
||||
voiceId?: unknown; speed?: unknown; captions?: unknown; style?: unknown;
|
||||
voiceId?: unknown; speed?: unknown; captions?: unknown; style?: unknown; cartoonPalette?: unknown; replanCartoon?: unknown;
|
||||
shot?: { index?: unknown; spoken?: unknown; resetSpoken?: unknown; visual?: Partial<Record<keyof ShotVisual, unknown>> };
|
||||
}): Montage {
|
||||
const ep = episodeOrThrow(episodeId);
|
||||
@@ -157,7 +171,16 @@ export function updateMontage(episodeId: number, patch: {
|
||||
saved.speed = Math.round(speed * 100) / 100;
|
||||
}
|
||||
if (patch.captions !== undefined) saved.captions = Boolean(patch.captions);
|
||||
if (patch.style !== undefined) saved.style = patch.style === "3d" ? "3d" : "mixed";
|
||||
if (patch.cartoonPalette !== undefined) {
|
||||
const palette = String(patch.cartoonPalette);
|
||||
if (palette && !(CARTOON_PALETTES as readonly string[]).includes(palette)) throw new UserError("Paleta inválida.");
|
||||
saved.cartoonPalette = (palette || undefined) as SavedMontage["cartoonPalette"];
|
||||
}
|
||||
// Paleta ou elenco novos: o plano automático dos trechos Cartoon é refeito (cor e personagens fazem parte da cena).
|
||||
if (patch.cartoonPalette !== undefined || patch.replanCartoon) {
|
||||
for (const own of Object.values(saved.shots)) if (own.visual?.kind === "cartoon" && own.visual.auto !== false) delete own.visual.cartoon;
|
||||
}
|
||||
if (patch.style !== undefined) saved.style = patch.style === "3d" || patch.style === "cartoon" ? patch.style : "mixed";
|
||||
if (patch.shot) {
|
||||
const index = Number(patch.shot.index);
|
||||
const shot = current.shots.find((s) => s.index === index);
|
||||
@@ -199,6 +222,9 @@ export function updateMontage(episodeId: number, patch: {
|
||||
else if (first) next.scene = { kind: "doc3d", template: first.id, params: { ...paramsFor(first, shot.visualHint), variant: 0 } };
|
||||
else throw new UserError("A biblioteca de cenas 3D está vazia: peça uma cena ao agente (tarefa \"Cena no Godot\").");
|
||||
}
|
||||
// Cartoon: plano do trecho pelo texto (ou o que já estava).
|
||||
if (next.kind === "cartoon" && !next.cartoon) next.cartoon = planCartoon(shot, cartoonCtx(ep), next.cartoonVariant ?? 0);
|
||||
if (next.kind !== "cartoon") { delete next.cartoon; delete next.cartoonKey; delete next.cartoonVariant; }
|
||||
if (next.kind !== "godot2d" && next.kind !== "godot3d") { delete next.scene; delete next.sceneKey; }
|
||||
if (next.kind !== "image") delete next.search;
|
||||
next.auto = false;
|
||||
@@ -225,6 +251,58 @@ function shotDuration(montage: Montage, shot: MontageShot): number {
|
||||
return shot.audio!.durationMs / 1000 + (last ? LAST_PAD_S : PAD_S);
|
||||
}
|
||||
|
||||
/** Painel do topo das cenas Cartoon: nome da história e o número do vídeo. */
|
||||
function hudFor(ep: EpisodeView): CartoonScene["hud"] {
|
||||
const story = getStory(ep.story_id);
|
||||
const badge = (story?.title ?? ep.story_id).replace(/[^\p{L}\p{N} ]/gu, "").trim().split(/\s+/).slice(0, 2).join(" ").slice(0, 18);
|
||||
return { badge: badge || "História", label: `Ep. ${ep.number}` };
|
||||
}
|
||||
|
||||
/** Paletas do estilo Cartoon (a mesma em todos os trechos dá a "cara" da série). Vazio = pela hora do trecho. */
|
||||
export const CARTOON_PALETTES = ["night", "sepia", "day", "dusk", "gray"] as const;
|
||||
|
||||
/** Contexto do plano Cartoon: painel do topo, elenco da história (biblioteca de personagens) e paleta. */
|
||||
function cartoonCtx(ep: EpisodeView): PlanContext {
|
||||
const palette = readSaved(ep).cartoonPalette;
|
||||
return {
|
||||
hud: hudFor(ep),
|
||||
cast: getCast(ep.story_id).filter((c) => c.kind === "cartoon").map((c) => ({ id: c.id, name: c.name, caption: c.caption, look: c.look })),
|
||||
...(palette ? { palette } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** A cena Cartoon já renderizada vale para este trecho (mesma cena, duração e áudio)? */
|
||||
function cartoonIsCurrent(montage: Montage, shot: MontageShot): boolean {
|
||||
const v = shot.visual;
|
||||
return v.kind === "cartoon" && !!v.cartoon && !!v.file && !!shot.audio && !shot.audioStale &&
|
||||
v.cartoonKey === cartoonKey(v.cartoon, shotDuration(montage, shot), shot.audio.key) && fs.existsSync(path.join(REPO_ROOT, v.file));
|
||||
}
|
||||
|
||||
/** Renderiza as cenas Cartoon dos trechos pedidos numa execução só (precisa do áudio: tempos e duração da fala). */
|
||||
async function renderCartoonInternal(ep: EpisodeView, montage: Montage, shots: MontageShot[], hook?: JobHook, log?: (line: string) => void): Promise<void> {
|
||||
if (!shots.length) return;
|
||||
const jobs = [];
|
||||
for (const shot of shots) {
|
||||
if (!shot.audio || shot.audioStale) throw new UserError(`Gere o áudio do trecho ${shot.index + 1} antes: a cena dura o tempo da fala.`);
|
||||
const scene = shot.visual.cartoon ?? planCartoon(shot, cartoonCtx(ep), shot.visual.cartoonVariant ?? 0);
|
||||
const duration = shotDuration(montage, shot);
|
||||
const words = montage.captions
|
||||
? await wordTimings({ repoRoot: REPO_ROOT, audio: shot.audio.file, spoken: shot.spoken, durationS: duration, scene, log })
|
||||
: [];
|
||||
jobs.push({ shot, scene, duration, spec: cartoonSpec(scene, duration, words) });
|
||||
}
|
||||
const files = await renderCartoonShots({
|
||||
repoRoot: REPO_ROOT, specDir: path.join(storyDir(ep.story_id), "cartoon"), outDir: path.join(OUTPUT_DIR, "cartoon", `${ep.story_id}-${ep.file_key}`),
|
||||
shots: jobs.map((j) => ({ name: `${ep.file_key}-t${String(j.shot.index + 1).padStart(2, "0")}`, spec: j.spec })), hook, log,
|
||||
});
|
||||
const saved = readSaved(ep);
|
||||
jobs.forEach((j, i) => {
|
||||
const own = (saved.shots[String(j.shot.index)] ??= {});
|
||||
own.visual = { ...EMPTY_VISUAL, ...own.visual, kind: "cartoon", cartoon: j.scene, file: files[i], cartoonKey: cartoonKey(j.scene, j.duration, j.shot.audio!.key) };
|
||||
});
|
||||
writeSaved(ep, saved);
|
||||
}
|
||||
|
||||
/** A cena 2D já renderizada vale para este trecho (mesmo modelo, parâmetros e duração)? */
|
||||
function sceneIsCurrent(montage: Montage, shot: MontageShot): boolean {
|
||||
const v = shot.visual;
|
||||
@@ -253,8 +331,9 @@ export async function renderShotScene(episodeId: number, index: number): Promise
|
||||
const montage = loadMontage(episodeId);
|
||||
const shot = montage.shots.find((s) => s.index === index);
|
||||
if (!shot) throw new UserError("Trecho não encontrado.");
|
||||
if (shot.visual.kind !== "godot2d" && shot.visual.kind !== "godot3d") throw new UserError("Este trecho não usa cena do Godot.");
|
||||
await renderShotSceneInternal(ep, montage, shot);
|
||||
if (shot.visual.kind === "cartoon") await renderCartoonInternal(ep, montage, [shot]);
|
||||
else if (shot.visual.kind !== "godot2d" && shot.visual.kind !== "godot3d") throw new UserError("Este trecho não usa cena do Godot nem Cartoon.");
|
||||
else await renderShotSceneInternal(ep, montage, shot);
|
||||
return loadMontage(episodeId);
|
||||
}
|
||||
|
||||
@@ -371,6 +450,18 @@ export async function regenerateShot(episodeId: number, index: number, target: "
|
||||
if (!ok) throw new UserError("Não achei outra foto diferente das que já estão no vídeo.");
|
||||
return loadMontage(episodeId);
|
||||
}
|
||||
if (v.kind === "cartoon") {
|
||||
// Outra variação do arranjo (cena, câmera, roupa) e renderiza já, se o áudio estiver pronto.
|
||||
const variant = (v.cartoonVariant ?? 0) + 1;
|
||||
const saved = readSaved(ep);
|
||||
const own = (saved.shots[String(index)] ??= {});
|
||||
own.visual = { ...EMPTY_VISUAL, ...own.visual, kind: "cartoon", cartoonVariant: variant, cartoon: planCartoon(shot, cartoonCtx(ep), variant) };
|
||||
writeSaved(ep, saved);
|
||||
const fresh = loadMontage(episodeId);
|
||||
const freshShot = fresh.shots.find((s) => s.index === index)!;
|
||||
if (freshShot.audio && !freshShot.audioStale) await renderCartoonInternal(ep, fresh, [freshShot]);
|
||||
return loadMontage(episodeId);
|
||||
}
|
||||
if ((v.kind === "godot2d" || v.kind === "godot3d") && v.scene) {
|
||||
const variant = Number(v.scene.params.variant ?? 0) + 1;
|
||||
const saved = readSaved(ep);
|
||||
@@ -427,10 +518,11 @@ export function montageJob(episodeId: number): { renderId: number; progress: str
|
||||
}
|
||||
|
||||
/** Trecho sem visual escolhido pelo admin (imagem/clipe vazio): o modo automático usa cena 2D. */
|
||||
const needsVisual = (s: MontageShot) => s.visual.kind !== "card" && s.visual.kind !== "godot2d" && s.visual.kind !== "godot3d" && !s.visual.file;
|
||||
const needsVisual = (s: MontageShot) => s.visual.kind !== "card" && s.visual.kind !== "godot2d" && s.visual.kind !== "godot3d" && s.visual.kind !== "cartoon" && !s.visual.file;
|
||||
/** No "Refazer tudo do zero": o que o automático escolheu (ou cena do Godot sem marca, de versões antigas) é replanejado. */
|
||||
const replannable = (s: MontageShot) => needsVisual(s) || s.visual.auto === true || (s.visual.auto === undefined && (s.visual.kind === "godot2d" || s.visual.kind === "godot3d"));
|
||||
const replannable = (s: MontageShot) => needsVisual(s) || s.visual.auto === true || (s.visual.auto === undefined && (s.visual.kind === "godot2d" || s.visual.kind === "godot3d" || s.visual.kind === "cartoon"));
|
||||
const isGodot = (s: MontageShot) => s.visual.kind === "godot2d" || s.visual.kind === "godot3d";
|
||||
const isCartoon = (s: MontageShot) => s.visual.kind === "cartoon";
|
||||
|
||||
/** Voz pt-BR padrão do serviço (para o modo automático, quando nenhuma foi escolhida). */
|
||||
async function defaultVoice(): Promise<string> {
|
||||
@@ -491,6 +583,13 @@ export function startMontageRender(episodeId: number, options: { auto?: boolean;
|
||||
const style = readSaved(ep).style ?? "mixed";
|
||||
for (const shot of toPlan) {
|
||||
checkCancel();
|
||||
if (style === "cartoon") {
|
||||
// Tudo em Cartoon: o plano sai do texto do trecho; o render vem depois do áudio (precisa da duração).
|
||||
const savedC = readSaved(ep);
|
||||
(savedC.shots[String(shot.index)] ??= {}).visual = { ...EMPTY_VISUAL, kind: "cartoon", cartoon: planCartoon(shot, cartoonCtx(ep)), auto: true };
|
||||
writeSaved(ep, savedC);
|
||||
continue;
|
||||
}
|
||||
if (style === "3d") {
|
||||
// Tudo em 3D: cena 3D da biblioteca + cartão de foto real quando o trecho pede.
|
||||
const plan3d = planShot3d(shot, ctx, shot.index);
|
||||
@@ -534,9 +633,17 @@ export function startMontageRender(episodeId: number, options: { auto?: boolean;
|
||||
step(`Cena ${shot.visual.kind === "godot3d" ? "3D" : "2D"} no Godot ${i + 1} de ${needScene.length} (trecho ${shot.index + 1})`);
|
||||
await renderShotSceneInternal(ep, current, shot, hook);
|
||||
}
|
||||
// 3b) Cenas Cartoon desatualizadas: todas numa execução da Remotion (empacota uma vez).
|
||||
const afterGodot = loadMontage(episodeId);
|
||||
const needCartoon = afterGodot.shots.filter((s) => isCartoon(s) && s.audio && !s.audioStale && !cartoonIsCurrent(afterGodot, s));
|
||||
if (needCartoon.length) {
|
||||
checkCancel();
|
||||
step(`Cenas Cartoon: ${needCartoon.length} trecho${needCartoon.length === 1 ? "" : "s"}`);
|
||||
await renderCartoonInternal(ep, afterGodot, needCartoon, hook, log);
|
||||
}
|
||||
const montage = loadMontage(episodeId);
|
||||
const pending = montage.shots.filter((s) => !s.audio || s.audioStale || (s.visual.kind !== "card" && !s.visual.file) ||
|
||||
(isGodot(s) && !sceneIsCurrent(montage, s)));
|
||||
(isGodot(s) && !sceneIsCurrent(montage, s)) || (isCartoon(s) && !cartoonIsCurrent(montage, s)));
|
||||
if (pending.length) throw new UserError(`Trechos ainda sem áudio ou visual atualizado: ${pending.map((s) => s.index + 1).join(", ")}.`);
|
||||
// 4) Um segmento por trecho + créditos, depois junta tudo.
|
||||
const segments: string[] = [];
|
||||
@@ -546,9 +653,10 @@ export function startMontageRender(episodeId: number, options: { auto?: boolean;
|
||||
segments.push(await buildSegment({
|
||||
visual: shot.visual,
|
||||
inset: shot.visual.inset ? { file: shot.visual.inset.file, credit: shot.visual.inset.credit } : null,
|
||||
// A cena 2D já mostra o texto dela; não sobrepõe de novo.
|
||||
onScreen: shot.visual.kind === "godot2d" ? "" : shot.onScreen,
|
||||
narration: shot.narration, audio: shot.audio!.file, duration: shotDuration(montage, shot), index: shot.index, captions: montage.captions,
|
||||
// A cena 2D e a Cartoon já mostram o texto delas; a Cartoon traz a legenda palavra por palavra.
|
||||
onScreen: shot.visual.kind === "godot2d" || isCartoon(shot) ? "" : shot.onScreen,
|
||||
narration: shot.narration, audio: shot.audio!.file, duration: shotDuration(montage, shot), index: shot.index,
|
||||
captions: montage.captions && !isCartoon(shot),
|
||||
}, dir, font, REPO_ROOT, hook));
|
||||
}
|
||||
const credits = [...new Set(montage.shots.map((s) => s.visual.credit && `${s.visual.credit}${s.visual.license ? ` (${s.visual.license})` : ""}`).filter(Boolean))];
|
||||
|
||||
@@ -52,6 +52,7 @@ export function buildPrompt(input: { kind: AgentKind; provider: Provider; reques
|
||||
branches: "Leia SÓ: `doc/roteiro/comum.md`, `doc/roteiro/ficcao.md` e a pasta da história; para a cena, use o script `new_scene.py` indicado abaixo. Não carregue a skill inteira.",
|
||||
godot: "Leia SÓ: `doc/godot/cenas.md` e `doc/godot/api.md` (assinaturas das peças e cenas; NÃO leia os .gd inteiros de outras cenas). Não carregue a skill `cenaforge`.",
|
||||
scene: "Siga a skill `cenaforge` (.claude/skills/cenaforge/SKILL.md): leia só as seções que a tarefa pedir.",
|
||||
character: "Leia SÓ: `doc/cartoon/personagens.md`. Não carregue a skill `cenaforge`.",
|
||||
free: "Siga o CLAUDE.md; consulte a skill `cenaforge` (.claude/skills/cenaforge/SKILL.md) só no que a tarefa pedir.",
|
||||
};
|
||||
const lines: (string | null)[] = [
|
||||
@@ -116,6 +117,13 @@ export function buildPrompt(input: { kind: AgentKind; provider: Provider; reques
|
||||
story && documentary ? RESEARCH_ECONOMY : null,
|
||||
story ? scriptCheck(story.id) : null,
|
||||
"Não crie cena JSON nem renderize nesta tarefa.");
|
||||
} else if (kind === "character") {
|
||||
lines.push("", "## Tarefa: personagem do estilo Cartoon (biblioteca de personagens)",
|
||||
"O pedido traz o id e a descrição de um personagem. Monte a aparência por peças conforme `doc/cartoon/personagens.md` e grave a ficha.",
|
||||
"1. Leia `assets/characters/<id>/character.json` se existir (o painel cria um rascunho pelas regras); mantenha id, name e createdAt.",
|
||||
"2. Ajuste `look` (só os valores da tabela do guia; cores #rrggbb), `caption` curta (função · idade) e `description`.",
|
||||
"3. Escreva o arquivo com JSON válido. Não crie imagens, não renderize e não altere `cartoon/` nem `panel/`.",
|
||||
"Ao terminar: diga em 3 linhas o que escolheu e por quê (a marca que deixa o personagem reconhecível).");
|
||||
} else if (kind === "godot") {
|
||||
lines.push("", "## Tarefa: construir uma cena no Godot (biblioteca de cenas)",
|
||||
"O pedido descreve uma cena (lugar, objeto, personagem, animação). Construa-a no Godot e guarde na biblioteca, para este e para os próximos vídeos.",
|
||||
|
||||
@@ -125,8 +125,8 @@ export type Decision = {
|
||||
|
||||
export type Provider = "claude" | "codex";
|
||||
// godot: o agente constrói uma cena nova na biblioteca do Godot (godot/library/, doc/godot/cenas.md).
|
||||
export type AgentKind = "free" | "story" | "script" | "scene" | "branches" | "godot";
|
||||
export const AGENT_KINDS: AgentKind[] = ["free", "story", "script", "scene", "branches", "godot"];
|
||||
export type AgentKind = "free" | "story" | "script" | "scene" | "branches" | "godot" | "character";
|
||||
export const AGENT_KINDS: AgentKind[] = ["free", "story", "script", "scene", "branches", "godot", "character"];
|
||||
export type AgentStatus = "running" | "success" | "error" | "cancelled" | "interrupted";
|
||||
|
||||
export type AgentRun = {
|
||||
|
||||
Reference in New Issue
Block a user