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>
114 lines
4.6 KiB
Python
114 lines
4.6 KiB
Python
"""Orquestra um pedido de síntese: idempotência → cache → deduplicação em voo → fila → motor → Opus."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import time
|
|
from dataclasses import dataclass
|
|
|
|
from .audio import encode
|
|
from .catalog import Voice
|
|
from .config import Settings
|
|
from .engine import TtsEngine
|
|
from .errors import IdempotencyConflict, TextTooLong, VoiceNotFound
|
|
from .schemas import SynthesizeRequest
|
|
from .store import CachedAudio, Store
|
|
from .work_queue import WorkQueue
|
|
|
|
log = logging.getLogger("cenaforge_voice")
|
|
|
|
CACHE_SCHEMA = 3 # suba quando mudar o formato de saída ou o pipeline
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class SynthesisResult:
|
|
audio: CachedAudio
|
|
cache_hit: bool
|
|
replay: bool
|
|
|
|
|
|
def cache_key_for(voice: Voice, engine_name: str, text: str, speed: float, fmt: str, bitrate: int) -> str:
|
|
payload = {
|
|
"schema": CACHE_SCHEMA,
|
|
"engine": engine_name,
|
|
"voice": voice.id,
|
|
"voiceRev": voice.revision,
|
|
"text": text,
|
|
"params": {"speed": round(speed, 2), "format": fmt, "bitrate": bitrate},
|
|
}
|
|
return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()
|
|
|
|
|
|
class VoiceService:
|
|
def __init__(self, settings: Settings, voices: dict[str, Voice], engine: TtsEngine, store: Store, queue: WorkQueue):
|
|
self.settings = settings
|
|
self.voices = voices
|
|
self.engine = engine
|
|
self.store = store
|
|
self.queue = queue
|
|
# Deduplicação em voo por (keyId, chave de cache): uma chave nunca herda a espera (nem o erro de fila)
|
|
# da outra. O cache em disco segue global por conteúdo.
|
|
self._inflight: dict[tuple[str, str], asyncio.Future[CachedAudio]] = {}
|
|
|
|
async def synthesize(self, req: SynthesizeRequest, key_id: str) -> SynthesisResult:
|
|
voice = self.voices.get(req.voiceId)
|
|
if voice is None:
|
|
raise VoiceNotFound()
|
|
if len(req.text) > self.settings.max_text_chars:
|
|
raise TextTooLong(f"Texto acima de {self.settings.max_text_chars} caracteres.")
|
|
|
|
speed = round(req.params.speed, 2)
|
|
key = cache_key_for(voice, self.engine.name, req.text, speed, req.params.format, self.settings.opus_bitrate)
|
|
|
|
is_new, bound_key = self.store.bind_request(key_id, req.requestId, key)
|
|
if bound_key != key:
|
|
raise IdempotencyConflict()
|
|
replay = not is_new
|
|
|
|
cached = self.store.get(key)
|
|
if cached is not None:
|
|
self._log(req, key_id, voice, "hit", replay, cached.duration_ms, 0.0)
|
|
return SynthesisResult(cached, cache_hit=True, replay=replay)
|
|
|
|
# Mesmo conteúdo já sendo gerado (outro requestId ou retry): espera o mesmo resultado.
|
|
inflight_key = (key_id, key)
|
|
pending = self._inflight.get(inflight_key)
|
|
if pending is not None:
|
|
audio = await asyncio.shield(pending)
|
|
self._log(req, key_id, voice, "inflight", replay, audio.duration_ms, 0.0)
|
|
return SynthesisResult(audio, cache_hit=True, replay=replay)
|
|
|
|
future: asyncio.Future[CachedAudio] = asyncio.get_running_loop().create_future()
|
|
self._inflight[inflight_key] = future
|
|
started = time.perf_counter()
|
|
try:
|
|
audio = await self.queue.run(
|
|
lambda: self._render(voice, req.text, speed, req.params.format, key), owner=key_id
|
|
)
|
|
future.set_result(audio)
|
|
except BaseException as exc:
|
|
future.set_exception(exc)
|
|
future.exception() # marca como lida; quem esperava recebe o mesmo erro
|
|
raise
|
|
finally:
|
|
self._inflight.pop(inflight_key, None)
|
|
|
|
self._log(req, key_id, voice, "miss", replay, audio.duration_ms, time.perf_counter() - started)
|
|
return SynthesisResult(audio, cache_hit=False, replay=replay)
|
|
|
|
def _render(self, voice: Voice, text: str, speed: float, fmt: str, key: str) -> CachedAudio:
|
|
pcm = self.engine.synthesize(voice, text, speed, self.settings.max_audio_s)
|
|
data = encode(pcm, fmt, self.settings.opus_bitrate)
|
|
digest = hashlib.sha256(data).hexdigest()
|
|
return self.store.put(key, data, int(pcm.duration_s * 1000), digest)
|
|
|
|
def _log(self, req: SynthesizeRequest, key_id: str, voice: Voice, cache: str, replay: bool, duration_ms: int, seconds: float) -> None:
|
|
# Nunca o texto: só tamanho, voz e métricas.
|
|
log.info(
|
|
"synthesize request_id=%s key_id=%s voice=%s chars=%d cache=%s replay=%s audio_ms=%d wall_ms=%d",
|
|
req.requestId, key_id, voice.id, len(req.text), cache, replay, duration_ms, int(seconds * 1000),
|
|
)
|