Files
CenaForge/clipper/app/dub.py
T
MateuusandClaude Opus 5.5 439e111052 Integração: falantes + dublagem + vídeo final
- editor_api: importa dub e speakers juntos.
- voice_chunks (falantes) vira a migração v15, depois da v14 do vídeo final (antes era criada fora das migrações).
- dub.voice_for: qualquer voz que não é o streamer (other1, other2…) usa a segunda voz da dublagem.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:59:44 -03:00

392 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Dublagem em português por TTS — camada SÓ de desenvolvimento (doc/clipador/DUBLAGEM.md).
Pedido do dono (18/11/2026): fonte em inglês → "quando ele estiver falando, a gente dubla em português; baixa o áudio
dele, deixa um pouco baixo para escutar o som do carro, do ambiente do jogo". Só entra no vídeo de REVISÃO
(`dev.dub`); o vídeo final, depois de aprovar, sai com o áudio original (`layout.dev_flags(cfg, dev=False)`).
Fluxo: frases traduzidas (`clips.translation_json` → `[{s, e, text, pt, speaker?}]`, tempo da sessão) → tempo de
saída (`editor.to_output`, respeita os trechos removidos) → uma fala TTS por frase pelo serviço de voz local
(`POST /v1/synthesize`, WAV), com cache em disco por (voz, velocidade, texto) → encaixe no tempo (`fit`) → UMA faixa
WAV do trecho renderizado (`Dubber.build`) que o `editor_render` mistura com a voz original abaixada (`duck_factors`).
Voz: TTS PRONTA do catálogo (padrão `pt-br-antonio`, masculina, Edge). Nunca clonar a voz do streamer — é um
terceiro sem consentimento; o projeto só aceita clonagem com consentimento de quem fala.
"""
from __future__ import annotations
import hashlib
import io
import logging
import os
import threading
import time
import uuid
import wave
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
import httpx
from . import layout, media
from .editor import to_output
log = logging.getLogger("cenaforge_clipper.dub")
FALLBACK_VOICE = "pt-br-faber" # Piper, offline: quando a voz escolhida (Edge, online) falha
SPEAKER_OTHER = "other" # `lines[].speaker` (FALANTES.md): "streamer" | "other1", "other2"…; ausente = streamer
# Esclarecimento do dono (18/11/2026): NÃO é dublagem de filme — é para a equipe entender o contexto. Nada de
# sincronia labial: cada fala começa perto do início da original, em velocidade natural (inteligível primeiro), e pode
# escorrer depois da fala original. Duas nunca tocam juntas e o atraso não acumula (limite por frase, `MAX_LATE_S`).
TTS_SPEED = 1.05 # quase natural: o português traduzido costuma ser mais longo que o inglês falado
MAX_TEMPO = 1.2 # aceleração máxima (atempo), só quando nem escorrendo cabe; acima disso fica difícil de entender
MAX_LATE_S = 1.5 # quanto uma fala pode começar depois da original (porque a anterior escorreu); nunca acumula
# Frase PARTIDA no meio pela transcrição (a 1ª não termina em . ! ? …), do mesmo falante e colada (vão menor que
# MERGE_GAP_S), vira uma fala só. Juntar frases completas foi medido pior (corte 259: 8,5 s perdidos contra 3,0 s).
MERGE_GAP_S = 0.4
MERGE_MAX_S = 7.0 # …desde que a junção não passe disso (tempo da fala original)
MERGE_MAX_CHARS = 140
SENTENCE_END = (".", "!", "?", "…", ".\"", "?\"", "!\"")
GAP_S = 0.08 # silêncio mínimo entre duas dublagens (nunca duas tocando juntas)
MIN_SLOT_S = 0.45 # espaço menor que isso: a frase não é dublada (não daria para entender)
FADE_S = 0.12 # fade de saída quando a fala precisa ser cortada
RAMP_S = 0.15 # rampa do ducking (desce antes da dublagem começar, sobe depois que ela acaba)
DUCK_HOLD_S = 0.6 # vão entre duas dublagens menor que isso: a voz original continua baixa (sem "bombear")
SAMPLE_RATE = 48000
# Nível da dublagem: cada fala é guardada a −16 LUFS (média ≈ −16,5 dB RMS sem as pausas). No render, ela é posta
# `LEVEL_OVER_ORIGINAL_DB` acima do volume médio do próprio corte (medido no áudio original) — live baixa (medido no
# corte 259 do tfue: −32 dB) não ganha uma voz 14 dB mais alta que ele. Ganho entre `GAIN_RANGE_DB`; limitador no fim.
TTS_LEVEL_DB = -16.5
LEVEL_OVER_ORIGINAL_DB = 6.0
GAIN_RANGE_DB = (-20.0, 3.0)
WORKERS = 3 # sínteses em paralelo (Edge é online; o serviço tem fila por chave)
SYNTH_TIMEOUT_S = 120
CACHE_KEEP_DAYS = 30 # fala do cache sem uso há mais que isso é apagada quando o serviço sobe
class DubError(RuntimeError):
"""Falha ao sintetizar uma frase (serviço fora, voz inexistente…)."""
# ---------------------------------------------------------------- configuração
def options(cfg: dict) -> dict:
"""Vozes e volume da dublagem a partir da configuração efetiva do corte (grupo `dev`)."""
group = {**layout.DEFAULTS["dev"], **(cfg.get("dev") or {})}
return {"voice": group["dubVoice"], "voiceOther": group["dubVoiceOther"] or group["dubVoice"],
"duck": float(group["dubDuck"])}
def voice_for(line: dict, opts: dict) -> str:
"""Voz da frase: qualquer voz que não é o streamer (`other`, `other1`, `other2`…) usa a segunda voz; sem o
campo, a padrão."""
speaker = line.get("speaker")
return opts["voiceOther"] if isinstance(speaker, str) and speaker.startswith(SPEAKER_OTHER) else opts["voice"]
# ---------------------------------------------------------------- plano (contas puras, sem áudio)
@dataclass(frozen=True)
class DubLine:
at: float # início da frase no tempo de SAÍDA (do corte inteiro)
text: str # português
voice: str
speaker: str | None = None
end: float = 0.0 # fim da fala original (tempo de saída); 0 = desconhecido
@dataclass(frozen=True)
class Cue:
"""Uma dublagem posicionada: começa em `at` (tempo de saída), toca `length` s, acelerada por `tempo`."""
at: float
length: float
tempo: float
cut: bool # não coube nem acelerada: termina com fade
index: int # posição em `lines`
def plan_lines(lines: list[dict], cuts: list[dict], opts: dict) -> list[DubLine]:
"""Frases da tradução (tempo da sessão) → frases no tempo de saída, em ordem. Frase sem português, ou que caiu
inteira num trecho removido (nada dela na saída), fica de fora; fala curta ("Okay." de 0,18 s) é dublada.
Frase partida no meio + continuação (mesmo falante, colada) viram uma fala só (ex.: "…deve dar" + "tudo certo.")."""
out: list[DubLine] = []
for line in lines or []:
text = " ".join(str(line.get("pt") or "").split())
if not text:
continue
try:
s, e = float(line["s"]), float(line["e"])
except (KeyError, TypeError, ValueError):
continue
a, _ = to_output(s, cuts)
b, _ = to_output(e, cuts)
if b - a < 0.05:
continue
speaker = line.get("speaker") if isinstance(line.get("speaker"), str) else None
out.append(DubLine(round(a, 3), text, voice_for(line, opts), speaker, round(b, 3)))
out.sort(key=lambda x: x.at)
merged: list[DubLine] = []
for line in out:
prev = merged[-1] if merged else None
if (prev and prev.voice == line.voice and not prev.text.endswith(SENTENCE_END)
and line.at - prev.end < MERGE_GAP_S and line.end - prev.at <= MERGE_MAX_S
and len(prev.text) + len(line.text) < MERGE_MAX_CHARS):
merged[-1] = DubLine(prev.at, f"{prev.text} {line.text}", prev.voice, prev.speaker, max(prev.end, line.end))
else:
merged.append(line)
return merged
def fit(lines: list[DubLine], durations: list[float | None], total: float) -> list[Cue]:
"""Encaixa cada fala no tempo. `durations[i]` = duração natural do TTS da frase i: 0 = a síntese falhou (a frase
some e não limita a anterior); None = não sintetizada neste render (fora do trecho: não toca, mas ainda é o
limite da anterior).
- Começa no início da frase original (ou logo depois da dublagem anterior, se ela escorreu).
- Toca em velocidade natural e pode escorrer até `MAX_LATE_S` depois do começo da próxima frase (que começa
depois dela). O limite é contado de cada frase original: o atraso nunca acumula.
- Só se nem assim couber: acelera até `MAX_TEMPO`; se ainda não couber, corta com fade.
- Nunca duas tocando juntas (`GAP_S` entre elas) e nunca depois do fim do corte."""
cues: list[Cue] = []
cursor = float("-inf")
for i, (line, natural) in enumerate(zip(lines, durations)):
if not natural or natural <= 0:
continue
start = max(line.at, cursor + GAP_S)
nxt = next((lines[j].at for j in range(i + 1, len(lines)) if durations[j] is None or durations[j] > 0), None)
limit = min(total, nxt + MAX_LATE_S - GAP_S) if nxt is not None else total
room = limit - start
if room < MIN_SLOT_S or start >= total:
log.info("dublagem: frase %d sem espaço (%.2f s) — fica sem dublar", i, room)
continue
tempo = 1.0 if natural <= room else min(MAX_TEMPO, natural / room)
length = natural / tempo
cut = length > room + 1e-6
if cut:
length = room
cues.append(Cue(round(start, 3), round(length, 3), round(tempo, 3), cut, i))
cursor = start + length
return cues
def duck_spans(cues: list[Cue], merge_gap: float = DUCK_HOLD_S) -> list[tuple[float, float]]:
"""Intervalos em que a voz original fica baixa (as dublagens, com vãos curtos emendados)."""
spans: list[list[float]] = []
for c in sorted(cues, key=lambda c: c.at):
a, b = c.at, c.at + c.length
if spans and a - spans[-1][1] < merge_gap + 2 * RAMP_S:
spans[-1][1] = max(spans[-1][1], b)
else:
spans.append([a, b])
return [(round(a, 3), round(b, 3)) for a, b in spans]
def duck_factors(spans: list[tuple[float, float]], duck: float, ramp: float = RAMP_S) -> list[str]:
"""Fatores (expressões do FFmpeg em `t`) que multiplicam o volume da voz original: 1 fora das falas dubladas,
`duck` durante, com rampa de `ramp` s antes e depois. Vão no `volume='…':eval=frame` do `editor_render`."""
if duck >= 1 or not spans:
return []
depth, r = 1 - max(0.0, duck), max(0.01, ramp)
return [f"(1-{depth:.3f}*clip(min((t-{a - r:.3f})/{r:.3f},({b + r:.3f}-t)/{r:.3f}),0,1))" for a, b in spans]
# ---------------------------------------------------------------- síntese com cache
def wav_duration(data: bytes) -> float:
with wave.open(io.BytesIO(data)) as w:
return w.getnframes() / float(w.getframerate() or 1)
def voice_synth(url: str | None, key: str | None) -> Callable[[str, str], bytes]:
"""Função (texto, voz) → WAV pelo serviço de voz local (`POST /v1/synthesize`, mesma chave do `VoiceClient`)."""
def synth(text: str, voice: str) -> bytes:
if not (url and key):
raise DubError("serviço de voz não instalado")
try:
response = httpx.post(f"{url}/v1/synthesize", timeout=SYNTH_TIMEOUT_S, headers={"X-Service-Key": key},
json={"requestId": f"clipper-dub-{uuid.uuid4().hex[:24]}", "text": text, "voiceId": voice,
"params": {"speed": TTS_SPEED, "format": "wav"}})
except httpx.HTTPError as exc:
raise DubError(f"serviço de voz fora do ar ({url})") from exc
if response.status_code != 200:
raise DubError(f"voz {voice} respondeu {response.status_code}: {response.text[:160]}")
return response.content
return synth
class TtsCache:
"""Fala TTS por (voz, velocidade, texto) em disco — prévia e render seguintes não sintetizam de novo.
Com FFmpeg, cada fala é guardada já limpa: sem o silêncio do começo/fim (o Edge põe ~0,5 s), volume igualado
(loudnorm −16 LUFS, vozes de motores diferentes ficam parecidas) e 48 kHz mono."""
def __init__(self, folder: Path, synth: Callable[[str, str], bytes], ffmpeg: str | None):
self.folder, self.synth, self.ffmpeg = folder, synth, ffmpeg
self.synth_calls = 0
self._guard = threading.Lock()
self._locks: dict[str, threading.Lock] = {}
def path(self, voice: str, text: str) -> Path:
digest = hashlib.sha256(f"{voice}|{TTS_SPEED:.2f}|{text}".encode("utf-8")).hexdigest()[:24]
return self.folder / f"{digest}.wav"
def get(self, voice: str, text: str) -> tuple[Path, float]:
"""(arquivo, duração em s) da fala; sintetiza só se ainda não estiver no cache."""
out = self.path(voice, text)
with self._guard:
lock = self._locks.setdefault(out.name, threading.Lock())
with lock:
if not out.is_file():
raw = self.synth(text, voice)
with self._guard:
self.synth_calls += 1
self.folder.mkdir(parents=True, exist_ok=True)
tmp = out.with_suffix(".tmp.wav")
if self.ffmpeg:
raw_file = out.with_suffix(".raw.wav")
raw_file.write_bytes(raw)
try:
trim = "silenceremove=start_periods=1:start_threshold=-50dB"
media.run([self.ffmpeg, "-y", "-v", "error", "-i", str(raw_file), "-af",
f"{trim},areverse,{trim},areverse,loudnorm=I=-16:TP=-1.5:LRA=11,aresample={SAMPLE_RATE}",
"-ac", "1", "-c:a", "pcm_s16le", str(tmp)], timeout=60)
finally:
raw_file.unlink(missing_ok=True)
else:
tmp.write_bytes(raw)
tmp.replace(out)
else:
try:
os.utime(out) # "usada agora": a limpeza (`prune`) apaga só o que ninguém usa há tempo
except OSError:
pass
return out, wav_duration(out.read_bytes())
def prune(self, keep_days: float = CACHE_KEEP_DAYS) -> int:
"""Apaga as falas sem uso há mais de `keep_days` dias. Devolve quantas apagou."""
limit = time.time() - keep_days * 86400
removed = 0
for file in self.folder.glob("*.wav") if self.folder.is_dir() else []:
try:
if file.stat().st_mtime < limit:
file.unlink()
removed += 1
except OSError:
continue
return removed
# ---------------------------------------------------------------- faixa do trecho renderizado
def gain_for(level_db: float | None) -> float:
"""Ganho (dB) da faixa de dublagem para o volume médio `level_db` do áudio original (None = sem medida: 0 dB)."""
if level_db is None:
return 0.0
lo, hi = GAIN_RANGE_DB
return round(min(hi, max(lo, level_db + LEVEL_OVER_ORIGINAL_DB - TTS_LEVEL_DB)), 1)
@dataclass
class DubTrack:
file: Path # WAV 48 kHz estéreo, do tamanho do trecho (t1 − t0), começando em t0
spans: list[tuple[float, float]] # ducking, em tempo relativo a t0
duck: float
cues: int
seconds: float # quanto a dublagem custou neste render (síntese + faixa)
synthesized: int # falas sintetizadas agora (o resto veio do cache)
failed: list[str] = field(default_factory=list)
class Dubber:
def __init__(self, cache: TtsCache, ffmpeg: str | None):
self.cache, self.ffmpeg = cache, ffmpeg
def _speech(self, line: DubLine) -> tuple[Path, float] | None:
try:
return self.cache.get(line.voice, line.text)
except (DubError, media.MediaError, OSError, wave.Error, EOFError) as exc:
if line.voice != FALLBACK_VOICE and not str(exc).startswith("serviço de voz"):
log.warning("dublagem: voz %s falhou (%s); tentando %s", line.voice, exc, FALLBACK_VOICE)
try:
return self.cache.get(FALLBACK_VOICE, line.text)
except (DubError, media.MediaError, OSError, wave.Error, EOFError) as exc2:
exc = exc2
log.warning("dublagem: frase sem áudio (%s)", exc)
return None
def build(self, translation: list[dict], cuts: list[dict], cfg: dict, t0: float, t1: float, work: Path,
stem: str, level_db: float | None = None) -> DubTrack | None:
"""Faixa da dublagem da saída [t0, t1]. Só sintetiza as frases que tocam nesse trecho (prévia de 5 s não
sintetiza o corte inteiro). `level_db` = volume médio do áudio original do corte (nivela a dublagem; ver
`gain_for`). None = nada para dublar (ou serviço de voz fora)."""
if not self.ffmpeg:
return None
started = time.monotonic()
before = self.cache.synth_calls
opts = options(cfg)
lines = plan_lines(translation, cuts, opts)
if not lines:
return None
total = round(sum(c["end"] - c["start"] for c in cuts), 3)
# Frases que podem tocar em [t0, t1]: começam antes de t1 e a próxima (+ atraso máximo) passa de t0.
wanted = [i for i, ln in enumerate(lines)
if ln.at < t1 and (lines[i + 1].at + MAX_LATE_S if i + 1 < len(lines) else total) > t0]
if wanted and wanted[0] > 0: # a anterior decide se a 1ª atrasa: entra na conta (não na faixa)
wanted.insert(0, wanted[0] - 1)
speech: dict[int, tuple[Path, float] | None] = {}
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
for i, result in zip(wanted, pool.map(lambda i: self._speech(lines[i]), wanted)):
speech[i] = result
failed = [lines[i].text for i in wanted if speech.get(i) is None]
if wanted and len(failed) == len(wanted):
log.warning("dublagem: nenhuma fala sintetizada (%d frases) — vídeo sai sem dublagem", len(wanted))
return None
durations = [(speech[i][1] if speech[i] else 0.0) if i in speech else None for i in range(len(lines))]
# Fora de `wanted` a duração não é conhecida (None): a frase vizinha usa o começo dela (`at`) como limite, que
# é o que importa; essas frases não entram na faixa.
cues = [c for c in fit(lines, durations, total) if c.at < t1 and c.at + c.length > t0]
if not cues:
return None
out = work / f"{stem}.dub.wav"
self._mix(cues, [speech[c.index][0] for c in cues], t0, t1, out, gain_for(level_db)) # type: ignore[index]
spans = [(round(a - t0, 3), round(b - t0, 3)) for a, b in duck_spans(cues)]
return DubTrack(out, spans, opts["duck"], len(cues), round(time.monotonic() - started, 2),
self.cache.synth_calls - before, failed)
def _mix(self, cues: list[Cue], files: list[Path], t0: float, t1: float, out: Path, gain_db: float = 0.0) -> None:
"""Uma faixa só (48 kHz estéreo, `t1 − t0` s): cada fala acelerada/cortada e posta no lugar, com `gain_db`."""
length = t1 - t0
args: list[str] = [self.ffmpeg or "ffmpeg", "-y", "-v", "error"]
graph = [f"aevalsrc=0:s={SAMPLE_RATE}:d={length:.3f}[base]"]
for k, (cue, file) in enumerate(zip(cues, files)):
args += ["-i", str(file)]
chain = f"[{k}:a]aformat=sample_rates={SAMPLE_RATE}:channel_layouts=mono"
if cue.tempo > 1.001:
chain += f",atempo={cue.tempo:.3f}"
chain += f",atrim=end={cue.length:.3f}"
if cue.cut:
chain += f",afade=t=out:st={max(0.0, cue.length - FADE_S):.3f}:d={FADE_S:.3f}"
skip = t0 - cue.at
if skip > 0: # prévia que começa no meio desta fala
chain += f",atrim=start={skip:.3f}"
chain += f",asetpts=PTS-STARTPTS,adelay=delays={int(round(max(0.0, -skip) * 1000))}:all=1[d{k}]"
graph.append(chain)
graph.append("[base]" + "".join(f"[d{k}]" for k in range(len(cues)))
+ f"amix=inputs={len(cues) + 1}:duration=first:normalize=0,volume={gain_db:.1f}dB,"
f"alimiter=limit=0.9:level=0,aformat=channel_layouts=stereo[out]")
out.parent.mkdir(parents=True, exist_ok=True)
media.run([*args, "-filter_complex", ";".join(graph), "-map", "[out]", "-c:a", "pcm_s16le", "-t", f"{length:.3f}",
str(out)], timeout=120)
def for_engine(engine) -> Dubber:
"""Dublador do motor (um por processo, criado na 1ª vez): cache em `data/clipper/dub/`, voz pelo serviço local."""
dubber = getattr(engine, "_dubber", None)
if dubber is None:
settings = engine.settings
voice = getattr(engine, "voice", None)
synth = voice_synth(getattr(voice, "url", None) or settings.voice_url, getattr(voice, "key", None) or settings.voice_key)
cache = TtsCache(settings.data_dir / "dub", synth, settings.ffmpeg)
if cache.prune():
log.info("dublagem: cache limpo (falas sem uso há %d dias)", CACHE_KEEP_DAYS)
dubber = Dubber(cache, settings.ffmpeg)
engine._dubber = dubber
return dubber