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:
@@ -0,0 +1,215 @@
|
||||
"""Configuração do serviço de voz do CenaForge, lida de variáveis de ambiente e de `voice/.env`.
|
||||
|
||||
Roda nativo no PC (sem Docker): as pastas padrão ficam em `data/voice/` na raiz do projeto.
|
||||
Falha fechado: sem chave de serviço forte o processo não sobe (o setup gera uma no `voice/.env`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
MIN_KEY_LENGTH = 32
|
||||
# Variáveis que deixaram de valer: a fila virou cota por chave (`*_PER_KEY`). Avisamos no boot para o
|
||||
# operador não achar que o valor antigo continua limitando alguma coisa.
|
||||
# Timeout do cliente HTTP (painel e render do CenaForge). A síntese é síncrona: espera na fila + execução
|
||||
# precisa caber nele, ou o cliente desiste antes da resposta.
|
||||
BACKEND_CLIENT_TIMEOUT_S = 300.0
|
||||
VOICE_ROOT = Path(__file__).resolve().parent.parent
|
||||
PROJECT_ROOT = VOICE_ROOT.parent
|
||||
STT_MODELS = ("base", "small", "medium", "large-v3-turbo")
|
||||
DEVICES = ("auto", "cuda", "cpu")
|
||||
# A espera na fila precisa cobrir pelo menos este múltiplo da execução: com a CPU em rodízio, a outra chave pode
|
||||
# pegar um trabalho no teto na frente (e a vaga só volta quando a thread termina, um pouco depois do teto).
|
||||
QUEUE_TO_RUN_RATIO = 2.0
|
||||
RETIRED_VARS = {"VOICE_MAX_QUEUE": "VOICE_MAX_QUEUE_PER_KEY", "VOICE_STT_MAX_QUEUE": "VOICE_STT_MAX_QUEUE_PER_KEY"}
|
||||
|
||||
|
||||
class ConfigError(RuntimeError):
|
||||
"""Configuração inválida; o serviço não deve subir."""
|
||||
|
||||
|
||||
def load_dotenv(path: Path) -> None:
|
||||
"""Carrega `CHAVE=valor` de um arquivo .env sem sobrescrever o que já está no ambiente."""
|
||||
if not path.is_file():
|
||||
return
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
name, value = line.split("=", 1)
|
||||
os.environ.setdefault(name.strip(), value.strip().strip('"').strip("'"))
|
||||
|
||||
|
||||
def _path(name: str, default: Path) -> Path:
|
||||
raw = os.environ.get(name, "")
|
||||
if not raw:
|
||||
return default
|
||||
value = Path(raw)
|
||||
return value if value.is_absolute() else PROJECT_ROOT / value
|
||||
|
||||
|
||||
def _int(name: str, default: int, minimum: int = 1) -> int:
|
||||
raw = os.environ.get(name)
|
||||
value = default if raw in (None, "") else int(raw)
|
||||
if value < minimum:
|
||||
raise ConfigError(f"{name} precisa ser >= {minimum}")
|
||||
return value
|
||||
|
||||
|
||||
def _float(name: str, default: float, minimum: float = 0.1) -> float:
|
||||
raw = os.environ.get(name)
|
||||
value = default if raw in (None, "") else float(raw)
|
||||
if value < minimum:
|
||||
raise ConfigError(f"{name} precisa ser >= {minimum}")
|
||||
return value
|
||||
|
||||
|
||||
def _azure_region() -> str:
|
||||
region = os.environ.get("VOICE_AZURE_REGION", "eastus").strip().lower() or "eastus"
|
||||
if not region.isascii() or not region.isalnum():
|
||||
raise ConfigError(f"VOICE_AZURE_REGION inválida: {region!r} (ex.: eastus, brazilsouth)")
|
||||
return region
|
||||
|
||||
|
||||
def _clone_port() -> int:
|
||||
port = _int("VOICE_CLONE_PORT", 4511)
|
||||
if not 4500 <= port <= 4599:
|
||||
raise ConfigError(f"VOICE_CLONE_PORT={port} fora da faixa 4500–4599 do CenaForge")
|
||||
return port
|
||||
|
||||
|
||||
def _choice(name: str, default: str, allowed: tuple[str, ...]) -> str:
|
||||
value = os.environ.get(name) or default
|
||||
if value not in allowed:
|
||||
raise ConfigError(f"{name} precisa ser um de {allowed}")
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
service_key: str
|
||||
models_dir: Path
|
||||
data_dir: Path
|
||||
catalog_path: Path
|
||||
lock_path: Path
|
||||
max_concurrency: int = 1
|
||||
# Cota de espera POR CHAVE de serviço: a fila cheia de uma chave nunca recusa a outra.
|
||||
max_queue_per_key: int = 8
|
||||
# Uma fala de episódio (até 2 min) com RVC em CPU leva ~1 min. 180 + 90 = 270 s < 300 s do cliente.
|
||||
queue_timeout_s: float = 180.0
|
||||
synth_timeout_s: float = 90.0
|
||||
max_text_chars: int = 2000
|
||||
max_audio_s: float = 120.0
|
||||
cache_max_mb: int = 512
|
||||
idempotency_ttl_h: int = 72
|
||||
onnx_threads: int = 2
|
||||
opus_bitrate: int = 48000
|
||||
verify_models: bool = True
|
||||
enable_rvc: bool = False
|
||||
# Azure Speech (opcional): sem chave, as vozes do motor azure ficam fora do catálogo.
|
||||
azure_key: str = ""
|
||||
azure_region: str = "eastus"
|
||||
# Processo de clonagem (Chatterbox, venv próprio): porta local na faixa do CenaForge.
|
||||
clone_port: int = 4511
|
||||
applio_dir: Path = VOICE_ROOT / "vendor" / "applio"
|
||||
# auto = CUDA quando houver GPU NVIDIA utilizável; senão CPU. Vale para Whisper e RVC.
|
||||
device: str = "auto"
|
||||
# Vozes adicionadas pelo painel (fora do models.lock.json; o sha256 é gravado na hora de adicionar).
|
||||
user_catalog_path: Path | None = None
|
||||
# Transcrição (faster-whisper). Fila própria: STT não toma a vaga do TTS.
|
||||
enable_stt: bool = False
|
||||
stt_model: str = "small"
|
||||
stt_compute_type: str = "auto"
|
||||
stt_threads: int = 2
|
||||
stt_beam_size: int = 1
|
||||
stt_vad: bool = True
|
||||
stt_max_bytes: int = 256 * 1024 * 1024
|
||||
# Episódio inteiro: até 30 min. small int8 em CPU ≈ 0,25 s de CPU por 1 s de fala (≈ 8 min para 30 min).
|
||||
stt_max_audio_s: float = 1800.0
|
||||
stt_max_concurrency: int = 1
|
||||
stt_max_queue_per_key: int = 4
|
||||
# O job é assíncrono (o POST espera só stt_sync_wait_s), então a espera na fila não conta no timeout HTTP.
|
||||
stt_queue_timeout_s: float = 1200.0
|
||||
stt_timeout_s: float = 600.0
|
||||
stt_sync_wait_s: float = 10.0
|
||||
stt_job_ttl_s: int = 3600
|
||||
stt_max_chars: int = 200_000
|
||||
|
||||
def timeout_warnings(self) -> list[str]:
|
||||
"""Relações de timeout que, se não valerem, deixam uma chave levar `queue_timeout` por trabalho da outra."""
|
||||
warnings = []
|
||||
pairs = (
|
||||
("VOICE_QUEUE_TIMEOUT_S", self.queue_timeout_s, "VOICE_SYNTH_TIMEOUT_S", self.synth_timeout_s),
|
||||
("VOICE_STT_QUEUE_TIMEOUT_S", self.stt_queue_timeout_s, "VOICE_STT_TIMEOUT_S", self.stt_timeout_s),
|
||||
)
|
||||
for queue_name, queue_s, run_name, run_s in pairs:
|
||||
if queue_s < QUEUE_TO_RUN_RATIO * run_s:
|
||||
warnings.append(
|
||||
f"{queue_name}={queue_s:g} abaixo de {QUEUE_TO_RUN_RATIO:g}x {run_name}={run_s:g}: "
|
||||
"uma chave pode levar queue_timeout atrás de trabalho longo de outra"
|
||||
)
|
||||
if self.queue_timeout_s + self.synth_timeout_s >= BACKEND_CLIENT_TIMEOUT_S:
|
||||
warnings.append(
|
||||
f"VOICE_QUEUE_TIMEOUT_S + VOICE_SYNTH_TIMEOUT_S = {self.queue_timeout_s + self.synth_timeout_s:g} s "
|
||||
f"não cabe no timeout do backend ({BACKEND_CLIENT_TIMEOUT_S:g} s): ele desiste antes da resposta"
|
||||
)
|
||||
return warnings
|
||||
|
||||
@staticmethod
|
||||
def retired_vars_in_env() -> list[tuple[str, str]]:
|
||||
"""(variável antiga, substituta) para cada variável aposentada ainda presente no ambiente."""
|
||||
return [(old, new) for old, new in RETIRED_VARS.items() if os.environ.get(old, "") != ""]
|
||||
|
||||
@staticmethod
|
||||
def from_env() -> "Settings":
|
||||
load_dotenv(VOICE_ROOT / ".env")
|
||||
key = os.environ.get("VOICE_SERVICE_KEY", "")
|
||||
if len(key) < MIN_KEY_LENGTH:
|
||||
raise ConfigError(
|
||||
f"VOICE_SERVICE_KEY ausente ou curta (mínimo {MIN_KEY_LENGTH} caracteres); rode o setup.bat"
|
||||
)
|
||||
root = VOICE_ROOT
|
||||
data = PROJECT_ROOT / "data" / "voice"
|
||||
return Settings(
|
||||
service_key=key,
|
||||
models_dir=_path("VOICE_MODELS_DIR", data / "models"),
|
||||
data_dir=_path("VOICE_DATA_DIR", data / "state"),
|
||||
catalog_path=_path("VOICE_CATALOG", root / "voices" / "catalog.json"),
|
||||
lock_path=_path("VOICE_MODELS_LOCK", root / "models.lock.json"),
|
||||
user_catalog_path=_path("VOICE_USER_CATALOG", data / "user-voices.json"),
|
||||
max_concurrency=_int("VOICE_MAX_CONCURRENCY", 1),
|
||||
max_queue_per_key=_int("VOICE_MAX_QUEUE_PER_KEY", 8, minimum=0),
|
||||
queue_timeout_s=_float("VOICE_QUEUE_TIMEOUT_S", 180.0),
|
||||
synth_timeout_s=_float("VOICE_SYNTH_TIMEOUT_S", 90.0),
|
||||
max_text_chars=_int("VOICE_MAX_TEXT_CHARS", 2000),
|
||||
max_audio_s=_float("VOICE_MAX_AUDIO_S", 120.0),
|
||||
cache_max_mb=_int("VOICE_CACHE_MAX_MB", 512),
|
||||
idempotency_ttl_h=_int("VOICE_IDEMPOTENCY_TTL_H", 72),
|
||||
onnx_threads=_int("VOICE_ONNX_THREADS", 2),
|
||||
opus_bitrate=_int("VOICE_OPUS_BITRATE", 48000, minimum=6000),
|
||||
verify_models=os.environ.get("VOICE_VERIFY_MODELS", "1") != "0",
|
||||
enable_rvc=os.environ.get("VOICE_ENABLE_RVC", "0") == "1",
|
||||
azure_key=os.environ.get("VOICE_AZURE_KEY", "").strip(),
|
||||
azure_region=_azure_region(),
|
||||
clone_port=_clone_port(),
|
||||
applio_dir=_path("VOICE_APPLIO_DIR", root / "vendor" / "applio"),
|
||||
device=_choice("VOICE_DEVICE", "auto", DEVICES),
|
||||
enable_stt=os.environ.get("VOICE_ENABLE_STT", "1") == "1",
|
||||
stt_model=_choice("VOICE_STT_MODEL", "small", STT_MODELS),
|
||||
stt_compute_type=_choice(
|
||||
"VOICE_STT_COMPUTE_TYPE", "auto", ("auto", "int8", "int8_float32", "int8_float16", "float16", "float32")
|
||||
),
|
||||
stt_threads=_int("VOICE_STT_THREADS", 2),
|
||||
stt_beam_size=_int("VOICE_STT_BEAM_SIZE", 1),
|
||||
stt_vad=os.environ.get("VOICE_STT_VAD", "1") != "0",
|
||||
stt_max_bytes=_int("VOICE_STT_MAX_BYTES", 256 * 1024 * 1024, minimum=1024),
|
||||
stt_max_audio_s=_float("VOICE_STT_MAX_AUDIO_S", 1800.0),
|
||||
stt_max_concurrency=_int("VOICE_STT_MAX_CONCURRENCY", 1),
|
||||
stt_max_queue_per_key=_int("VOICE_STT_MAX_QUEUE_PER_KEY", 4, minimum=0),
|
||||
stt_queue_timeout_s=_float("VOICE_STT_QUEUE_TIMEOUT_S", 1200.0),
|
||||
stt_timeout_s=_float("VOICE_STT_TIMEOUT_S", 600.0),
|
||||
stt_sync_wait_s=_float("VOICE_STT_SYNC_WAIT_S", 10.0, minimum=0.0),
|
||||
stt_job_ttl_s=_int("VOICE_STT_JOB_TTL_S", 3600, minimum=60),
|
||||
)
|
||||
Reference in New Issue
Block a user