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:
2026-11-17 21:36:48 -03:00
co-authored by Claude Opus 5.5
parent e7ccc91736
commit 0050cf60a7
55 changed files with 5808 additions and 50 deletions
+174
View File
@@ -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)));