CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+256
@@ -0,0 +1,256 @@
|
||||
// `pnpm dev` (ou start.bat): sobe o serviço de voz (127.0.0.1:4510), o Clipador (127.0.0.1:4520), o Publicador
|
||||
// (127.0.0.1:4530) e o painel (127.0.0.1:4500) juntos. Ctrl+C encerra todos. Serviço que o setup ainda não
|
||||
// instalou é pulado com aviso.
|
||||
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const voiceDir = path.join(root, "voice");
|
||||
const python = path.join(voiceDir, ".venv", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
||||
const PORT_RANGE = [4500, 4599] as const; // faixa do CenaForge (ver CLAUDE.md)
|
||||
|
||||
function readEnv(file: string): Record<string, string> {
|
||||
if (!fs.existsSync(file)) return {};
|
||||
const entries = fs
|
||||
.readFileSync(file, "utf8")
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line.includes("=") && !line.trimStart().startsWith("#"))
|
||||
.map((line) => {
|
||||
const at = line.indexOf("=");
|
||||
return [line.slice(0, at).trim(), line.slice(at + 1).trim()] as [string, string];
|
||||
});
|
||||
return Object.fromEntries(entries);
|
||||
}
|
||||
|
||||
const voiceOnly = process.argv.includes("--voice-only");
|
||||
const envFile = path.join(voiceDir, ".env");
|
||||
const children: ChildProcess[] = [];
|
||||
let voiceChild: ChildProcess | null = null;
|
||||
let clipperChild: ChildProcess | null = null;
|
||||
let cloneChild: ChildProcess | null = null;
|
||||
let publisherChild: ChildProcess | null = null;
|
||||
// Clonagem de voz (Chatterbox): venv próprio porque fixa torch/numpy/transformers diferentes do serviço de voz.
|
||||
const clonePython = path.join(voiceDir, ".venv-clone", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
||||
const clipperDir = path.join(root, "clipper");
|
||||
const clipperPython = path.join(clipperDir, ".venv", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
||||
const publisherDir = path.join(root, "publisher");
|
||||
const publisherPython = path.join(publisherDir, ".venv", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
||||
// Processos de voz parados de propósito (reinício): o "exit" deles chega depois, de forma assíncrona,
|
||||
// e não pode encerrar o lançador no modo --voice-only.
|
||||
const replaced = new WeakSet<ChildProcess>();
|
||||
|
||||
function prefixed(name: string, color: number, child: ChildProcess): void {
|
||||
const tag = `\x1b[${color}m[${name}]\x1b[0m `;
|
||||
for (const stream of [child.stdout, child.stderr]) {
|
||||
let pending = "";
|
||||
stream?.setEncoding("utf8");
|
||||
stream?.on("data", (chunk: string) => {
|
||||
const lines = (pending + chunk).split(/\r?\n/);
|
||||
pending = lines.pop() ?? "";
|
||||
for (const line of lines) process.stdout.write(tag + line + "\n");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function stop(child: ChildProcess): void {
|
||||
if (child.exitCode !== null || child.pid === undefined) return;
|
||||
// No Windows o painel roda via shell (pnpm.cmd): só o taskkill /T derruba a árvore inteira.
|
||||
if (process.platform === "win32") spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
else child.kill("SIGTERM");
|
||||
}
|
||||
|
||||
function stopAll(): void {
|
||||
const services = [voiceChild, clipperChild, cloneChild, publisherChild].filter((child): child is ChildProcess => child !== null);
|
||||
for (const child of [...children, ...services]) stop(child);
|
||||
}
|
||||
|
||||
/** A porta está livre em 127.0.0.1? (tenta ouvir nela e solta em seguida) */
|
||||
function portFree(port: number): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const probe = net.createServer();
|
||||
probe.once("error", () => resolve(false));
|
||||
probe.listen(port, "127.0.0.1", () => probe.close(() => resolve(true)));
|
||||
});
|
||||
}
|
||||
|
||||
async function waitPortFree(port: number, timeoutMs: number): Promise<boolean> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
if (await portFree(port)) return true;
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
}
|
||||
return portFree(port);
|
||||
}
|
||||
|
||||
async function startVoice(): Promise<void> {
|
||||
const env = readEnv(envFile);
|
||||
if (!fs.existsSync(python) || !env.VOICE_SERVICE_KEY) {
|
||||
console.warn("\x1b[33m[voz]\x1b[0m serviço de voz não instalado; rode setup.bat. Subindo só o painel.");
|
||||
return;
|
||||
}
|
||||
const port = Number(env.VOICE_PORT || 4510);
|
||||
if (!(port >= PORT_RANGE[0] && port <= PORT_RANGE[1])) {
|
||||
throw new Error(`VOICE_PORT=${port} fora da faixa ${PORT_RANGE[0]}–${PORT_RANGE[1]} do CenaForge`);
|
||||
}
|
||||
// No reinício o Windows leva um instante para soltar a porta; fora dele, porta ocupada = outro CenaForge aberto.
|
||||
if (!(await waitPortFree(port, 10_000))) {
|
||||
console.warn(
|
||||
`\x1b[33m[voz]\x1b[0m porta ${port} ocupada (outro CenaForge ou serviço de voz já aberto?). ` +
|
||||
"Feche o outro processo; o painel segue sem iniciar uma segunda voz.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const child = spawn(
|
||||
python,
|
||||
["-m", "uvicorn", "app.main:build", "--factory", "--host", "127.0.0.1", "--port", String(port), "--no-access-log"],
|
||||
{ cwd: voiceDir, env: { ...process.env, PYTHONUTF8: "1" } },
|
||||
);
|
||||
voiceChild = child;
|
||||
prefixed("voz", 35, child);
|
||||
child.on("exit", (code) => {
|
||||
console.log(`\x1b[35m[voz]\x1b[0m encerrado (código ${code})`);
|
||||
if (voiceChild === child) voiceChild = null;
|
||||
if (voiceOnly && !replaced.has(child)) process.exit(code ?? 0);
|
||||
});
|
||||
}
|
||||
|
||||
/** Clonagem de voz (opcional: setup.bat -Clone). Só ouve 127.0.0.1 e exige a mesma chave do serviço de voz. */
|
||||
async function startClone(): Promise<void> {
|
||||
const env = readEnv(envFile);
|
||||
if (!fs.existsSync(clonePython) || !env.VOICE_SERVICE_KEY) return; // não instalada: as vozes clonadas avisam no painel
|
||||
const port = Number(env.VOICE_CLONE_PORT || 4511);
|
||||
if (!(port >= PORT_RANGE[0] && port <= PORT_RANGE[1])) {
|
||||
throw new Error(`VOICE_CLONE_PORT=${port} fora da faixa ${PORT_RANGE[0]}–${PORT_RANGE[1]} do CenaForge`);
|
||||
}
|
||||
if (!(await waitPortFree(port, 10_000))) {
|
||||
console.warn(`\x1b[34m[clone]\x1b[0m porta ${port} ocupada (outro CenaForge aberto?). Seguindo sem a clonagem.`);
|
||||
return;
|
||||
}
|
||||
const child = spawn(clonePython, [path.join(voiceDir, "clone", "worker.py")], {
|
||||
cwd: voiceDir,
|
||||
env: { ...process.env, ...env, VOICE_CLONE_PORT: String(port), PYTHONUTF8: "1" },
|
||||
});
|
||||
cloneChild = child;
|
||||
prefixed("clone", 34, child);
|
||||
child.on("exit", (code) => {
|
||||
console.log(`\x1b[34m[clone]\x1b[0m encerrado (código ${code})`);
|
||||
if (cloneChild === child) cloneChild = null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Clipador (cortes de live): grava, lê o chat, transcreve pela voz e renderiza. Opcional como a voz. */
|
||||
async function startClipper(): Promise<void> {
|
||||
const env = readEnv(path.join(clipperDir, ".env"));
|
||||
if (!fs.existsSync(clipperPython) || !env.CLIPPER_SERVICE_KEY) {
|
||||
console.warn("[33m[clip][0m Clipador não instalado; rode setup.bat. Seguindo sem ele.");
|
||||
return;
|
||||
}
|
||||
const port = Number(env.CLIPPER_PORT || 4520);
|
||||
if (!(port >= PORT_RANGE[0] && port <= PORT_RANGE[1])) {
|
||||
throw new Error(`CLIPPER_PORT=${port} fora da faixa ${PORT_RANGE[0]}–${PORT_RANGE[1]} do CenaForge`);
|
||||
}
|
||||
if (!(await waitPortFree(port, 5_000))) {
|
||||
console.warn(`[33m[clip][0m porta ${port} ocupada (outro Clipador aberto?). Seguindo sem iniciar um segundo.`);
|
||||
return;
|
||||
}
|
||||
const child = spawn(
|
||||
clipperPython,
|
||||
["-m", "uvicorn", "app.main:build", "--factory", "--host", "127.0.0.1", "--port", String(port), "--no-access-log"],
|
||||
{ cwd: clipperDir, env: { ...process.env, PYTHONUTF8: "1" } },
|
||||
);
|
||||
clipperChild = child;
|
||||
prefixed("clip", 33, child);
|
||||
child.on("exit", (code) => {
|
||||
console.log(`[33m[clip][0m encerrado (código ${code})`);
|
||||
if (clipperChild === child) clipperChild = null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Publicador (envio para YouTube, TikTok e Instagram): cofre de tokens, OAuth, navegador do modo sessão. Opcional. */
|
||||
async function startPublisher(): Promise<void> {
|
||||
const env = readEnv(path.join(publisherDir, ".env"));
|
||||
if (!fs.existsSync(publisherPython) || !env.PUBLISHER_SERVICE_KEY) {
|
||||
console.warn("\x1b[33m[pub]\x1b[0m Publicador não instalado; rode setup.bat. Seguindo sem ele (nada é publicado).");
|
||||
return;
|
||||
}
|
||||
const port = Number(env.PUBLISHER_PORT || 4530);
|
||||
if (!(port >= PORT_RANGE[0] && port <= PORT_RANGE[1])) {
|
||||
throw new Error(`PUBLISHER_PORT=${port} fora da faixa ${PORT_RANGE[0]}–${PORT_RANGE[1]} do CenaForge`);
|
||||
}
|
||||
if (!(await waitPortFree(port, 5_000))) {
|
||||
console.warn(`\x1b[33m[pub]\x1b[0m porta ${port} ocupada (outro Publicador aberto?). Seguindo sem iniciar um segundo.`);
|
||||
return;
|
||||
}
|
||||
const child = spawn(
|
||||
publisherPython,
|
||||
["-m", "uvicorn", "app.main:build", "--factory", "--host", "127.0.0.1", "--port", String(port), "--no-access-log"],
|
||||
{ cwd: publisherDir, env: { ...process.env, PYTHONUTF8: "1" } },
|
||||
);
|
||||
publisherChild = child;
|
||||
prefixed("pub", 32, child);
|
||||
child.on("exit", (code) => {
|
||||
console.log(`\x1b[32m[pub]\x1b[0m encerrado (código ${code})`);
|
||||
if (publisherChild === child) publisherChild = null;
|
||||
});
|
||||
}
|
||||
|
||||
// O painel grava as configurações da voz no voice/.env: quando ele muda, o serviço reinicia sozinho.
|
||||
function watchVoiceEnv(): void {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
fs.watchFile(envFile, { interval: 1000 }, (current, previous) => {
|
||||
if (current.mtimeMs === previous.mtimeMs) return;
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
console.log("\x1b[35m[voz]\x1b[0m voice/.env mudou: reiniciando o serviço de voz");
|
||||
if (voiceChild) {
|
||||
replaced.add(voiceChild);
|
||||
stop(voiceChild);
|
||||
}
|
||||
voiceChild = null;
|
||||
void startVoice();
|
||||
// A clonagem lê o mesmo .env (dispositivo, chave): reinicia junto.
|
||||
if (cloneChild) {
|
||||
stop(cloneChild);
|
||||
cloneChild = null;
|
||||
}
|
||||
void startClone();
|
||||
}, 1500);
|
||||
});
|
||||
}
|
||||
|
||||
function startPanel(): void {
|
||||
// Argumentos fixos (nada vem de fora): o shell só existe para achar o pnpm.cmd no Windows.
|
||||
const child = spawn("pnpm", ["--filter", "cenaforge-panel", "dev"], { cwd: root, shell: true });
|
||||
children.push(child);
|
||||
prefixed("painel", 36, child);
|
||||
child.on("exit", (code) => {
|
||||
console.log(`\x1b[36m[painel]\x1b[0m encerrado (código ${code})`);
|
||||
stopAll();
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
}
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
stopAll();
|
||||
process.exit(0);
|
||||
});
|
||||
process.on("SIGTERM", () => {
|
||||
stopAll();
|
||||
process.exit(0);
|
||||
});
|
||||
// Qualquer saída (inclusive por erro) leva os filhos junto: nada de serviço de voz órfão segurando a porta.
|
||||
process.on("exit", stopAll);
|
||||
|
||||
await startVoice();
|
||||
await startClone();
|
||||
watchVoiceEnv();
|
||||
if (voiceOnly) {
|
||||
if (!voiceChild) process.exit(1);
|
||||
} else {
|
||||
await startClipper();
|
||||
await startPublisher();
|
||||
startPanel();
|
||||
}
|
||||
Reference in New Issue
Block a user