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,246 @@
|
||||
"""Catálogo de vozes + verificação dos modelos (sha256).
|
||||
|
||||
Duas fontes:
|
||||
- `voices/catalog.json` (versionado): vozes base. Motor `piper` (pesos no models.lock.json) ou `edge`
|
||||
(Edge TTS, online, sem arquivo local).
|
||||
- `data/voice/user-voices.json` (local, escrito pelo painel): vozes de personagem = uma voz base + um modelo
|
||||
RVC (.pth/.index) adicionado pelo usuário. O sha256 de cada arquivo é gravado na hora de adicionar e
|
||||
conferido em toda subida, como o lock faz com os pesos oficiais.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import dataclass, replace
|
||||
from pathlib import Path
|
||||
|
||||
from .config import ConfigError
|
||||
|
||||
log = logging.getLogger("cenaforge_voice")
|
||||
|
||||
ENGINES = ("piper", "edge", "kokoro", "google", "azure", "clone", "fake")
|
||||
# Voz clonada: áudio de referência + parâmetros do Chatterbox (o processo de clonagem lê o arquivo).
|
||||
CLONE_DEFAULTS = {"exaggeration": 0.5, "cfgWeight": 0.5}
|
||||
# Motores que mandam o texto para fora (precisam de internet e costumam ser mais lentos).
|
||||
ONLINE_ENGINES = ("edge", "google", "azure")
|
||||
RVC_DEFAULTS = {"pitch": 0, "f0Method": "rmvpe", "indexRate": 0.5, "protect": 0.33}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Voice:
|
||||
id: str
|
||||
name: str
|
||||
language: str
|
||||
engine: str
|
||||
model: Path | None
|
||||
config: Path | None
|
||||
sample_rate: int
|
||||
default: bool
|
||||
source: str
|
||||
license: str
|
||||
revision: str # sha256 do modelo (prefixo); entra na chave de cache
|
||||
rvc: dict | None = None # {"modelPath": Path, "indexPath": Path|None, "pitch", "f0Method", "indexRate", "protect"}
|
||||
description: str | None = None
|
||||
gender: str | None = None # female|male|neutral
|
||||
age_range: str | None = None # child|young|adult|senior
|
||||
accent: str | None = None
|
||||
edge_voice: str | None = None # nome da voz no Edge TTS (ex.: pt-BR-FranciscaNeural)
|
||||
engine_voice: str | None = None # kokoro: estilo (ex.: pf_dora); google: domínio (ex.: com.br); azure: voz
|
||||
engine_lang: str | None = None # kokoro: idioma do espeak (ex.: pt-br); google: idioma (ex.: pt)
|
||||
base_voice: str | None = None # voz base de uma voz de personagem (RVC)
|
||||
clone: dict | None = None # voz clonada: {"exaggeration", "cfgWeight"}; o áudio de referência fica em `model`
|
||||
user: bool = False # adicionada pelo painel
|
||||
|
||||
|
||||
# Hash já calculado por (caminho, mtime, tamanho): várias vozes Kokoro dividem o mesmo modelo de ~160 MB e a
|
||||
# recarga automática do catálogo não deve re-hashear tudo a cada mudança.
|
||||
_HASH_CACHE: dict[tuple[str, int, int], str] = {}
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
info = path.stat()
|
||||
key = (str(path.resolve()), info.st_mtime_ns, info.st_size)
|
||||
cached = _HASH_CACHE.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for block in iter(lambda: handle.read(1 << 20), b""):
|
||||
digest.update(block)
|
||||
_HASH_CACHE[key] = digest.hexdigest()
|
||||
return _HASH_CACHE[key]
|
||||
|
||||
|
||||
def _short_hash(*parts: str) -> str:
|
||||
return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
def load_lock(lock_path: Path) -> dict[str, dict]:
|
||||
data = json.loads(lock_path.read_text(encoding="utf-8"))
|
||||
return {entry["path"]: entry for entry in data["files"]}
|
||||
|
||||
|
||||
def _check_locked(voice_id: str, rel: str, lock: dict, models_dir: Path, verify: bool) -> None:
|
||||
if rel not in lock:
|
||||
raise ConfigError(f"voz {voice_id}: {rel} não está no models.lock.json")
|
||||
path = models_dir / rel
|
||||
if not path.is_file():
|
||||
raise ConfigError(f"voz {voice_id}: modelo ausente ({rel}); rode o setup.bat (ou scripts/fetch_models.py)")
|
||||
if verify and sha256_file(path) != lock[rel]["sha256"]:
|
||||
raise ConfigError(f"voz {voice_id}: checksum diferente do lock ({rel})")
|
||||
|
||||
|
||||
def _base_voice(item: dict, lock: dict, models_dir: Path, verify: bool) -> Voice:
|
||||
engine = item["engine"]
|
||||
if engine not in ENGINES:
|
||||
raise ConfigError(f"voz {item['id']}: motor desconhecido {engine!r} (válidos: {', '.join(ENGINES)})")
|
||||
model = config = edge_voice = engine_voice = engine_lang = None
|
||||
if engine == "edge":
|
||||
edge_voice = item.get("edgeVoice")
|
||||
if not edge_voice:
|
||||
raise ConfigError(f"voz {item['id']}: motor edge exige edgeVoice")
|
||||
revision = _short_hash("edge", edge_voice)
|
||||
elif engine == "azure":
|
||||
engine_voice = item.get("azureVoice")
|
||||
if not engine_voice:
|
||||
raise ConfigError(f"voz {item['id']}: motor azure exige azureVoice")
|
||||
revision = _short_hash("azure", engine_voice)
|
||||
elif engine == "google":
|
||||
engine_lang, engine_voice = item.get("googleLang", "pt"), item.get("googleTld", "com.br")
|
||||
revision = _short_hash("google", engine_lang, engine_voice)
|
||||
else:
|
||||
# piper/kokoro/fake: pesos locais conferidos contra o lock. No kokoro, `config` é o voices.bin.
|
||||
for rel in (item["model"], item["config"]):
|
||||
_check_locked(item["id"], rel, lock, models_dir, verify)
|
||||
model, config = models_dir / item["model"], models_dir / item["config"]
|
||||
revision = lock[item["model"]]["sha256"][:16]
|
||||
if engine == "kokoro":
|
||||
engine_voice, engine_lang = item.get("kokoroVoice"), item.get("kokoroLang", "pt-br")
|
||||
if not engine_voice:
|
||||
raise ConfigError(f"voz {item['id']}: motor kokoro exige kokoroVoice")
|
||||
revision = _short_hash(revision, engine_voice, engine_lang)
|
||||
return Voice(
|
||||
id=item["id"],
|
||||
name=item["name"],
|
||||
language=item["language"],
|
||||
engine=engine,
|
||||
model=model,
|
||||
config=config,
|
||||
sample_rate=int(item["sampleRate"]),
|
||||
default=bool(item.get("default", False)),
|
||||
source=item["source"],
|
||||
license=item["license"],
|
||||
revision=revision,
|
||||
description=item.get("description"),
|
||||
gender=item.get("gender"),
|
||||
age_range=item.get("ageRange"),
|
||||
accent=item.get("accent"),
|
||||
edge_voice=edge_voice,
|
||||
engine_voice=engine_voice,
|
||||
engine_lang=engine_lang,
|
||||
)
|
||||
|
||||
|
||||
def _user_file(voice_id: str, rel: str, expected: str, models_dir: Path, verify: bool) -> Path:
|
||||
"""Arquivo de voz do usuário: dentro da pasta de modelos, presente e com o sha256 gravado ao adicionar."""
|
||||
path = (models_dir / rel).resolve()
|
||||
if models_dir.resolve() not in path.parents:
|
||||
raise ConfigError(f"voz {voice_id}: caminho fora da pasta de modelos ({rel})")
|
||||
if not path.is_file():
|
||||
raise ConfigError(f"voz {voice_id}: arquivo ausente ({rel})")
|
||||
if verify and sha256_file(path) != expected:
|
||||
raise ConfigError(f"voz {voice_id}: checksum diferente do registrado ({rel})")
|
||||
return path
|
||||
|
||||
|
||||
def _clone_voice(item: dict, models_dir: Path, verify: bool) -> Voice:
|
||||
voice_id = item["id"]
|
||||
raw = item.get("clone") or {}
|
||||
if not raw.get("reference"):
|
||||
raise ConfigError(f"voz {voice_id}: clone.reference é obrigatório")
|
||||
if item.get("consent") is not True:
|
||||
raise ConfigError(f"voz {voice_id}: voz clonada sem autorização registrada (consent)")
|
||||
expected = raw.get("referenceSha256", "")
|
||||
path = _user_file(voice_id, raw["reference"], expected, models_dir, verify)
|
||||
params = {key: float(raw.get(key, default)) for key, default in CLONE_DEFAULTS.items()}
|
||||
return Voice(
|
||||
id=voice_id, name=item["name"], language=item.get("language", "pt-BR"), engine="clone",
|
||||
model=path, config=None, sample_rate=24000, default=False,
|
||||
source=item.get("source", "gravação enviada pelo painel"), license=item.get("license", "informada pelo usuário"),
|
||||
revision=_short_hash("clone", expected, json.dumps(params, sort_keys=True)),
|
||||
description=item.get("description"), gender=item.get("gender"), age_range=item.get("ageRange"),
|
||||
accent=item.get("accent", "pt-BR"), engine_lang=raw.get("language", "pt"), clone=params, user=True,
|
||||
)
|
||||
|
||||
|
||||
def _user_voice(item: dict, bases: dict[str, Voice], models_dir: Path, verify: bool) -> Voice:
|
||||
voice_id = item["id"]
|
||||
if item.get("kind") == "clone":
|
||||
return _clone_voice(item, models_dir, verify)
|
||||
base = bases.get(item.get("baseVoice", ""))
|
||||
if base is None:
|
||||
raise ConfigError(f"voz {voice_id}: baseVoice {item.get('baseVoice')!r} não existe no catálogo")
|
||||
raw = item.get("rvc") or {}
|
||||
files: dict[str, Path | None] = {}
|
||||
hashes: list[str] = []
|
||||
for field in ("model", "index"):
|
||||
rel = raw.get(field)
|
||||
if not rel:
|
||||
if field == "model":
|
||||
raise ConfigError(f"voz {voice_id}: rvc.model é obrigatório")
|
||||
files[field] = None
|
||||
continue
|
||||
path = (models_dir / rel).resolve()
|
||||
if models_dir.resolve() not in path.parents:
|
||||
raise ConfigError(f"voz {voice_id}: caminho fora da pasta de modelos ({rel})")
|
||||
if not path.is_file():
|
||||
raise ConfigError(f"voz {voice_id}: arquivo ausente ({rel})")
|
||||
expected = raw.get(f"{field}Sha256", "")
|
||||
if verify and sha256_file(path) != expected:
|
||||
raise ConfigError(f"voz {voice_id}: checksum diferente do registrado ({rel})")
|
||||
files[field] = path
|
||||
hashes.append(expected)
|
||||
rvc = {key: raw.get(key, default) for key, default in RVC_DEFAULTS.items()}
|
||||
rvc.update(modelPath=files["model"], indexPath=files["index"])
|
||||
params = json.dumps({k: rvc[k] for k in RVC_DEFAULTS}, sort_keys=True)
|
||||
return replace(
|
||||
base,
|
||||
id=voice_id,
|
||||
name=item["name"],
|
||||
default=False,
|
||||
source=item.get("source", "adicionada pelo painel"),
|
||||
license=item.get("license", "informada pelo usuário"),
|
||||
revision=_short_hash(base.revision, *hashes, params),
|
||||
rvc=rvc,
|
||||
description=item.get("description"),
|
||||
gender=item.get("gender", base.gender),
|
||||
age_range=item.get("ageRange", base.age_range),
|
||||
accent=item.get("accent", base.accent),
|
||||
base_voice=base.id,
|
||||
user=True,
|
||||
)
|
||||
|
||||
|
||||
def load_catalog(
|
||||
catalog_path: Path, lock_path: Path, models_dir: Path, verify: bool = True, user_catalog_path: Path | None = None
|
||||
) -> dict[str, Voice]:
|
||||
lock = load_lock(lock_path)
|
||||
raw = json.loads(catalog_path.read_text(encoding="utf-8"))
|
||||
voices: dict[str, Voice] = {}
|
||||
for item in raw["voices"]:
|
||||
voices[item["id"]] = _base_voice(item, lock, models_dir, verify)
|
||||
if sum(v.default for v in voices.values()) != 1:
|
||||
raise ConfigError("o catálogo precisa de exatamente uma voz padrão")
|
||||
if user_catalog_path is not None and user_catalog_path.is_file():
|
||||
bases = dict(voices)
|
||||
for item in json.loads(user_catalog_path.read_text(encoding="utf-8")).get("voices", []):
|
||||
# Voz do usuário com defeito fica de fora (com aviso); não derruba as vozes base.
|
||||
try:
|
||||
if item.get("id") in voices:
|
||||
raise ConfigError(f"voz {item.get('id')}: id repetido entre o catálogo e as vozes do usuário")
|
||||
voices[item["id"]] = _user_voice(item, bases, models_dir, verify)
|
||||
except (ConfigError, KeyError) as exc:
|
||||
log.warning("voz do usuário ignorada: %s", exc)
|
||||
return voices
|
||||
Reference in New Issue
Block a user