Clipador: dublagem em português por TTS no vídeo de revisão (dev.dub)

- app/dub.py: frases traduzidas → uma fala TTS por frase no serviço de voz
  (POST /v1/synthesize, WAV), cache em disco por (voz, velocidade, texto),
  encaixe sem sincronia labial (velocidade natural, escorre até 1,5 s sem
  acumular atraso, acelera no máximo 1,2× e corta com fade só se preciso,
  nunca duas falas juntas), frase partida no meio vira uma fala só, voz
  reserva offline e faixa única do trecho nivelada pelo volume do corte.
- editor_render.render_project: o áudio original abaixa (dubDuck, rampa
  de 0,15 s) só onde há dublagem; nada muda com dev=False. Devolve resumo.
- layout: dev.dubVoice, dev.dubVoiceOther (speaker "other") e dev.dubDuck.
- editor_api: prévia e render da fila passam o dublador; translation_for
  também traduz quando só a dublagem está ligada.
- Painel: switch "Dublagem em português (teste)", vozes TTS prontas (sem
  clone) e volume do original.
- doc/clipador/DUBLAGEM.md e tests/test_dub.py (TTS falso).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Mateuus
2026-11-18 03:45:14 -03:00
co-authored by Claude Opus 5.5
parent 54eac7cebf
commit 7a428ee5da
9 changed files with 935 additions and 19 deletions
+389
View File
@@ -0,0 +1,389 @@
"""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` (outro agente): "streamer" | "other"; 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: `speaker == "other"` usa a segunda voz; sem o campo (ou qualquer outro valor), a padrão."""
return opts["voiceOther"] if line.get("speaker") == 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
+9 -6
View File
@@ -21,7 +21,7 @@ from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from . import editor, editor_render, layout, media
from . import dub, editor, editor_render, layout, media
from .config import REPO_ROOT
from .db import loads, now
from .judge import JudgeError, _chat_block, _transcript
@@ -113,7 +113,7 @@ def render_clip_edit(engine, clip: dict, session: dict, edit: dict, out: Path, t
cover = None
editor_render.render_project(ffmpeg, engine.settings.ffprobe, engine._encoder, segments, project, base, credit, out,
REPO_ROOT, chat=chat_for(engine, project), cover_file=cover,
translation=translation_for(engine, clip, project, base))
translation=translation_for(engine, clip, project, base), dubber=dub.for_engine(engine))
total = editor.output_duration(project["cuts"])
media.thumbnail(ffmpeg, out, min(3.0, total / 2), thumb)
# Formato em que ESTE arquivo saiu (camadas padrão ← canal ← sessão ← projeto): a fila desenha o player por ele.
@@ -122,10 +122,12 @@ def render_clip_edit(engine, clip: dict, session: dict, edit: dict, out: Path, t
def translation_for(engine, clip: dict, project: dict, base: dict, dev: bool = True) -> list[dict] | None:
"""Frases traduzidas para a legenda de desenvolvimento (doc/clipador/IDIOMAS.md): só com `dev.translation`
ligado, render de desenvolvimento e fonte em inglês. Traduz o trecho do projeto se ainda não houver tradução."""
"""Frases traduzidas para a legenda de desenvolvimento (doc/clipador/IDIOMAS.md) e a dublagem
(doc/clipador/DUBLAGEM.md): só com `dev.translation` ou `dev.dub` ligado, render de desenvolvimento e fonte em
inglês. Traduz o trecho do projeto se ainda não houver tradução."""
cfg = editor.effective_settings(base, project)
if not layout.dev_flags(cfg, dev)["translation"]:
flags = layout.dev_flags(cfg, dev)
if not (flags["translation"] or flags["dub"]):
return None
ps = editor.pieces(project["cuts"])
if not ps:
@@ -380,7 +382,8 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
editor_render.render_project(ffmpeg, settings.ffprobe, ["-c:v", "libx264", "-preset", "veryfast", "-crf", "24"],
segments, project, base, credit, out, REPO_ROOT,
out_range=(a, b), timeout=180, chat=chat_for(engine, project), cover_file=cover,
translation=translation_for(engine, clip, project, base))
translation=translation_for(engine, clip, project, base),
dubber=dub.for_engine(engine))
took = time.monotonic() - t
return {"file": out.relative_to(REPO_ROOT).as_posix(), "fromS": a, "toS": b, "seconds": round(took, 1), "version": now()}
+56 -7
View File
@@ -9,15 +9,19 @@ só entram números formatados aqui e nomes de arquivo relativos gerados por nó
from __future__ import annotations
import logging
import re
import shutil
import subprocess
from array import array
from pathlib import Path
from . import layout, media, reframe
from . import dub, layout, media, reframe
from .editor import Piece, effective_settings, emphasized, output_duration, output_words, pieces, slice_pieces, to_output
from .scoring import Word
from .subtitles import _escape, _ts, caption_blocks, clean_words
log = logging.getLogger("cenaforge_clipper.editor_render")
W, H = layout.W, layout.H # quadro do vertical (padrão dos parâmetros); o formato real vem da configuração
FPS = 30
PEAKS_PER_S = 50
@@ -416,12 +420,14 @@ def zoom_filter(project: dict, t0: float = 0.0, size: tuple[int, int] = (W, H))
class AudioInput:
"""Entrada de áudio extra (narração, música, efeito): arquivo + onde entra (tempo de saída) + volume."""
"""Entrada de áudio extra (narração, música, efeito, dublagem): arquivo + onde entra (tempo de saída) + volume.
`spans` (só `dub`) = intervalos em que a voz original abaixa para `duck`, com rampa (`dub.duck_factors`)."""
def __init__(self, file: Path, at: float, volume: float, kind: str, trim_start: float = 0.0, duck: float = 1.0,
length: float = 0.0):
length: float = 0.0, spans: list[tuple[float, float]] | None = None):
self.file, self.at, self.volume, self.kind = file, at, volume, kind
self.trim_start, self.duck, self.length = trim_start, duck, length
self.spans = spans or []
COVER_INTRO_S = 2 / FPS # capa nos 2 primeiros quadros (as redes usam o quadro 0 como miniatura padrão)
@@ -477,13 +483,17 @@ def build_filter(project: dict, cfg: dict, ps: list[Piece], in0: float, ass_name
g.append(f"[{cover_input}:v]scale={fw}:{fh},setsar=1,format=yuv420p[cv]")
g.append(f"[vbase][cv]overlay=enable='lt(t,{COVER_INTRO_S:.4f})':eof_action=pass,format=yuv420p[v]")
# Áudio: original (com volume e abaixado sob a narração) + narração + efeitos; música por baixo com ducking.
# Áudio: original (com volume e abaixado sob a narração/dublagem) + narração + dublagem + efeitos; música por
# baixo com ducking. A dublagem (camada de desenvolvimento) abaixa o original com rampa só onde ela fala.
narr = [(k, x) for k, x in enumerate(extras, start=1) if x.kind == "narration"]
vol_expr = f"{original_volume:.3f}"
for _, x in narr:
end = x.at + (x.length or 0)
if x.duck < 1 and x.length:
vol_expr = f"{vol_expr}*if(between(t,{x.at:.3f},{end:.3f}),{x.duck:.3f},1)"
for x in extras:
if x.kind == "dub":
vol_expr = "*".join([vol_expr, *dub.duck_factors(x.spans, x.duck)])
g.append(f"[acat]volume='{vol_expr}':eval=frame[aorig]")
voice_labels = ["[aorig]"]
music_label = None
@@ -608,13 +618,33 @@ def has_audio_stream(ffprobe: str | None, file: Path) -> bool:
return bool(out.strip())
def mean_volume(ffmpeg: str, segs: list[tuple[Path, float, float]], start: float, end: float, work: Path,
stem: str) -> float | None:
"""Volume médio (dB RMS, `volumedetect`) do áudio original de [start, end] da sessão; None se não der para medir.
Só o áudio é decodificado (~0,1 s num corte de 1 min)."""
if not segs:
return None
args, concat = _concat_input(work, f"{stem}.level", segs, start, end - start)
try:
result = subprocess.run([ffmpeg, "-v", "info", "-nostats", *args, "-vn", "-af", "volumedetect", "-f", "null", "-"],
capture_output=True, timeout=120, cwd=work, creationflags=media.NO_WINDOW)
except (OSError, subprocess.TimeoutExpired):
return None
finally:
concat.unlink(missing_ok=True)
match = re.search(rb"mean_volume:\s*(-?[\d.]+) dB", result.stderr)
return float(match.group(1)) if match and result.returncode == 0 else None
def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segments: list[tuple[Path, float, float]],
project: dict, base_cfg: dict, credit: str, out_file: Path, repo_root: Path,
out_range: tuple[float, float] | None = None, timeout: float = 900, chat: list | None = None,
cover_file: Path | None = None, translation: list[dict] | None = None, dev: bool = True) -> None:
cover_file: Path | None = None, translation: list[dict] | None = None, dev: bool = True,
dubber: "dub.Dubber | None" = None) -> dict:
"""Renderiza o projeto (ou só a saída [a, b] para a prévia real). `segments` = (arquivo, início, fim) da sessão.
`chat` = mensagens da sessão (para o chat na tela); `cover_file` = capa já renderizada, posta nos 2 primeiros
quadros quando o projeto pede (`cover.atStart`)."""
quadros quando o projeto pede (`cover.atStart`). `dubber` = dublagem em português (`dev.dub`, só com `dev=True`
e `translation`; app/dub.py). Devolve um resumo (`{"dub": {...} | None}`) — quem chama pode ignorar."""
cfg = effective_settings(base_cfg, project)
total = output_duration(project["cuts"])
t0, t1 = out_range if out_range else (0.0, total)
@@ -649,6 +679,21 @@ def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segment
if music:
extras.append(AudioInput(repo_root / music["file"], 0.0, music["volume"], "music", trim_start=t0,
duck=0.5 if music["duck"] else 1.0))
dub_track: dub.DubTrack | None = None
if dubber is not None and translation and layout.dev_flags(cfg, dev)["dub"]:
try:
# Volume do original no corte INTEIRO (a prévia de 5 s nivela igual ao render da fila).
full = pieces(project["cuts"])
level = mean_volume(ffmpeg, _segments_for(segments, full[0].start, full[-1].end), full[0].start,
full[-1].end, work, stem)
dub_track = dubber.build(translation, project["cuts"], cfg, t0, t1, work, stem, level_db=level)
except (media.MediaError, OSError) as exc: # camada de teste: o vídeo sai mesmo sem ela
log.warning("dublagem falhou (%s): o vídeo sai sem dublagem", exc)
if dub_track:
extras.append(AudioInput(dub_track.file, 0.0, 1.0, "dub", duck=dub_track.duck, length=t1 - t0,
spans=dub_track.spans))
log.info("dublagem: %d falas, %d sintetizadas agora, %.1f s", dub_track.cues, dub_track.synthesized,
dub_track.seconds)
extra_args: list[str] = []
for x in extras:
extra_args += (["-stream_loop", "-1"] if x.kind == "music" else []) + ["-i", str(x.file)]
@@ -689,8 +734,12 @@ def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segment
"-t", f"{t1 - t0:.3f}", "-movflags", "+faststart", tmp.name], timeout=timeout, cwd=work)
tmp.replace(out_file)
finally:
for f in (ass_file, concat, tmp, graph_file, *helper_files, *([uniform] if uniform else [])):
for f in (ass_file, concat, tmp, graph_file, *helper_files, *([uniform] if uniform else []),
*([dub_track.file] if dub_track else [])):
f.unlink(missing_ok=True)
return {"dub": None if dub_track is None else {
"cues": dub_track.cues, "synthesized": dub_track.synthesized, "seconds": dub_track.seconds,
"failed": len(dub_track.failed)}}
def make_proxy(ffmpeg: str, segments: list[tuple[Path, float, float]], lo: float, hi: float, out_file: Path) -> None:
+25 -3
View File
@@ -85,6 +85,12 @@ HOOK_FONT = "Luckiest Guy" if "Luckiest Guy" in PACKAGED_FONTS else "Arial Black
# +0,1 s de folga cobre o arredondamento de quadro e do contêiner no arquivo final.
DURATION_MARGIN_S = 1.0
DURATION_SLACK_S = 0.1
# Dublagem de desenvolvimento (app/dub.py): voz masculina pt-BR natural do serviço de voz (Edge, online); a das
# falas de outra pessoa é outra voz pt-BR nativa (Kokoro, offline), para não parecer o mesmo falando sozinho.
DUB_VOICE = "pt-br-antonio"
DUB_VOICE_OTHER = "kokoro-pm-alex"
DUB_DUCK = 0.25
VOICE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,47}$") # mesmo padrão do serviço de voz
DEFAULTS: dict = {
"layout": {"mode": "auto", "cam": None, "game": None, "camHeight": 0.34},
@@ -96,8 +102,11 @@ DEFAULTS: dict = {
},
# Camadas SÓ DE DESENVOLVIMENTO (doc/clipador/IDIOMAS.md): entram no vídeo de revisão (antes de aprovar) e NUNCA no
# vídeo final — o render com `dev=False` ignora este grupo inteiro. `translation`: português embaixo da legenda;
# `dub`: dublagem em português por TTS com a voz original abaixada.
"dev": {"translation": False, "dub": False},
# `dub`: dublagem em português por TTS com a voz original abaixada (app/dub.py, doc/clipador/DUBLAGEM.md):
# `dubVoice` = voz TTS pronta do catálogo (nunca clone do streamer), `dubVoiceOther` = voz das falas com
# `speaker: "other"`, `dubDuck` = volume do áudio original enquanto a dublagem toca (0–1).
"dev": {"translation": False, "dub": False, "dubVoice": DUB_VOICE, "dubVoiceOther": DUB_VOICE_OTHER,
"dubDuck": DUB_DUCK},
"credit": {"enabled": True, "position": "top", "size": 44},
"duration": {"minS": 60, "maxS": 90, "backtrackS": 120},
"format": {"aspect": "vertical"},
@@ -197,7 +206,20 @@ def validate(settings: dict) -> dict:
if dev is not None:
if not isinstance(dev, dict):
raise LayoutError("dev precisa ser um objeto")
out["dev"] = {k: bool(dev[k]) for k in ("translation", "dub") if k in dev}
o = {k: bool(dev[k]) for k in ("translation", "dub") if k in dev}
for key in ("dubVoice", "dubVoiceOther"):
if key in dev:
if not VOICE_ID_RE.match(str(dev[key] or "")):
raise LayoutError(f"dev.{key} precisa ser o id de uma voz do serviço de voz (ex.: {DUB_VOICE})")
o[key] = str(dev[key])
if "dubDuck" in dev:
try:
o["dubDuck"] = round(float(dev["dubDuck"]), 3)
except (TypeError, ValueError) as exc:
raise LayoutError("dev.dubDuck precisa ser número de 0 a 1") from exc
if not 0 <= o["dubDuck"] <= 1:
raise LayoutError("dev.dubDuck vai de 0 a 1 (volume do áudio original durante a dublagem)")
out["dev"] = o
cred = settings.get("credit")
if cred is not None:
o = {}
+329
View File
@@ -0,0 +1,329 @@
"""Dublagem em português (camada de desenvolvimento, doc/clipador/DUBLAGEM.md) — sempre com TTS falso."""
import io
import math
import shutil
import struct
import wave
from array import array
from pathlib import Path
import pytest
from app import dub, editor, editor_render, layout, media
FFMPEG = shutil.which("ffmpeg")
CUTS = [{"start": 10.0, "end": 20.0, "mode": None}, {"start": 25.0, "end": 40.0, "mode": None}] # 25 s de saída
def fake_wav(seconds: float, rate: int = 24000, freq: float = 440.0) -> bytes:
"""WAV mono 16 bits com um seno (o "TTS" dos testes)."""
n = int(seconds * rate)
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(rate)
w.writeframes(b"".join(struct.pack("<h", int(12000 * math.sin(2 * math.pi * freq * i / rate))) for i in range(n)))
return buf.getvalue()
class FakeSynth:
"""Duração da fala proporcional ao texto (0,08 s por letra); registra cada chamada."""
def __init__(self, per_char: float = 0.08, fail_voices: tuple[str, ...] = ()):
self.per_char, self.fail_voices, self.calls = per_char, fail_voices, []
def __call__(self, text: str, voice: str) -> bytes:
self.calls.append((voice, text))
if voice in self.fail_voices:
raise dub.DubError(f"voz {voice} respondeu 502")
return fake_wav(max(0.2, len(text) * self.per_char))
def opts(**over):
return {**dub.options(layout.merge({"dev": {"dub": True}})), **over}
# ---------------------------------------------------------------- plano no tempo de saída
def test_lines_go_to_output_time_and_skip_removed_parts():
lines = [
{"s": 11.0, "e": 12.0, "text": "a", "pt": "primeira"},
{"s": 21.0, "e": 23.0, "text": "b", "pt": "no trecho removido"}, # 20–25 foi cortado
{"s": 26.0, "e": 27.0, "text": "c", "pt": " depois do corte "},
{"s": 30.0, "e": 31.0, "text": "d", "pt": ""}, # sem tradução: não dubla
]
plan = dub.plan_lines(lines, CUTS, opts())
assert [(p.at, p.text) for p in plan] == [(1.0, "primeira"), (11.0, "depois do corte")]
assert all(p.voice == layout.DUB_VOICE for p in plan)
def test_speaker_other_uses_second_voice_and_missing_falls_back():
lines = [{"s": 11, "e": 12, "pt": "eu"}, {"s": 13, "e": 14, "pt": "outro", "speaker": "other"},
{"s": 15, "e": 16, "pt": "eu de novo", "speaker": "streamer"}, {"s": 17, "e": 18, "pt": "?", "speaker": "x"}]
plan = dub.plan_lines(lines, CUTS, opts(voice="pt-br-antonio", voiceOther="pt-br-cadu"))
assert [p.voice for p in plan] == ["pt-br-antonio", "pt-br-cadu", "pt-br-antonio", "pt-br-antonio"]
assert plan[1].speaker == "other"
# Sem `dubVoiceOther` na configuração salva: a padrão do Clipador; vazio = a mesma voz do streamer.
assert dub.options(layout.merge({}))["voiceOther"] == layout.DUB_VOICE_OTHER
assert dub.options({"dev": {"dubVoice": "pt-br-faber", "dubVoiceOther": ""}})["voiceOther"] == "pt-br-faber"
# ---------------------------------------------------------------- encaixe
def _line(at: float) -> dub.DubLine:
return dub.DubLine(at, "x", "v")
def test_fit_prefers_natural_speed_spills_over_and_never_overlaps_or_drifts():
lines = [_line(0.0), _line(2.0), _line(4.0), _line(5.0), _line(8.0), _line(9.0), _line(10.0)]
durations = [1.5, 2.6, 3.0, 0.9, 5.0, 0.5, 0.5]
cues = dub.fit(lines, durations, total=14.0)
by = {c.index: c for c in cues}
assert by[0].tempo == 1.0 and by[0].length == 1.5 and not by[0].cut # cabe: natural
assert by[1].tempo == 1.0 and by[1].at + by[1].length > 4.0 # escorre além da próxima frase, sem acelerar
assert by[2].at > 4.0 and by[2].at <= 4.0 + dub.MAX_LATE_S # começa depois da anterior, perto da original
# 3 s sem espaço nem escorrendo: acelera pouco (no máximo MAX_TEMPO) e corta com fade.
assert 1.0 < by[2].tempo <= dub.MAX_TEMPO and by[2].cut
for c in cues: # o atraso de cada fala é limitado pela PRÓPRIA frase original: não acumula
assert lines[c.index].at <= c.at <= lines[c.index].at + dub.MAX_LATE_S
assert c.tempo <= dub.MAX_TEMPO and c.at + c.length <= 14.0
ordered = sorted(cues, key=lambda c: c.at)
for a, b in zip(ordered, ordered[1:]):
assert a.at + a.length + dub.GAP_S <= b.at + 1e-6
def test_phrase_split_mid_sentence_is_joined():
lines = [{"s": 11.0, "e": 12.8, "pt": "se a gente fizer rápido deve dar"}, {"s": 12.9, "e": 13.1, "pt": "tudo certo."},
{"s": 13.2, "e": 13.6, "pt": "Beleza."}, # frase completa antes: não junta
{"s": 13.7, "e": 14.0, "pt": "Como assim"}, {"s": 14.1, "e": 14.5, "pt": "mano?", "speaker": "other"}]
plan = dub.plan_lines(lines, CUTS, opts())
assert [(p.at, p.text) for p in plan] == [(1.0, "se a gente fizer rápido deve dar tudo certo."), (3.2, "Beleza."),
(3.7, "Como assim"), (4.1, "mano?")] # falante diferente: não junta
def test_fit_skips_phrase_without_room_or_audio():
cues = dub.fit([_line(0.0), _line(0.05), _line(3.0)], [2.0, 0.0, 1.0], total=3.2)
assert [c.index for c in cues] == [0] # 1 falhou (não limita a 0); 2 com 0,2 s até o fim: não dá para entender
# Frase fora do trecho (None): não toca, mas segura a anterior no lugar dela.
cues = dub.fit([_line(0.0), _line(1.0)], [2.0, None], total=5.0)
assert [c.index for c in cues] == [0] and cues[0].at + cues[0].length <= 1.0 + dub.MAX_LATE_S
def test_duck_spans_merge_short_gaps_and_ramp_expression():
cues = [dub.Cue(1.0, 1.0, 1.0, False, 0), dub.Cue(2.3, 1.0, 1.0, False, 1), dub.Cue(6.0, 1.0, 1.0, False, 2)]
spans = dub.duck_spans(cues)
assert spans == [(1.0, 3.3), (6.0, 7.0)]
factors = dub.duck_factors(spans, 0.25)
env = {"clip": lambda x, lo, hi: max(lo, min(hi, x)), "min": min}
def gain(t: float) -> float:
value = 1.0
for f in factors:
value *= eval(f, env, {"t": t}) # noqa: S307 — expressão gerada pelo próprio teste
return value
assert gain(0.0) == 1.0 and gain(5.0) == 1.0 and gain(9.0) == 1.0 # fora das falas: normal
assert gain(2.0) == pytest.approx(0.25) and gain(6.5) == pytest.approx(0.25)
assert 0.25 < gain(1.0 - dub.RAMP_S / 2) < 1.0 # rampa antes de começar
assert dub.duck_factors(spans, 1.0) == []
def test_gain_follows_original_level():
assert dub.gain_for(None) == 0.0
assert dub.gain_for(-32.0) == pytest.approx(-32.0 + dub.LEVEL_OVER_ORIGINAL_DB - dub.TTS_LEVEL_DB) # live baixa
assert dub.gain_for(-5.0) == dub.GAIN_RANGE_DB[1] and dub.gain_for(-90.0) == dub.GAIN_RANGE_DB[0]
# ---------------------------------------------------------------- cache
def test_cache_synthesizes_once_per_voice_and_text(tmp_path):
synth = FakeSynth()
cache = dub.TtsCache(tmp_path / "dub", synth, ffmpeg=None)
f1, d1 = cache.get("pt-br-antonio", "olha isso")
f2, d2 = cache.get("pt-br-antonio", "olha isso")
assert f1 == f2 and d1 == d2 == pytest.approx(len("olha isso") * 0.08, abs=0.01)
assert len(synth.calls) == 1
cache.get("pt-br-cadu", "olha isso")
assert len(synth.calls) == 2 and len(list((tmp_path / "dub").glob("*.wav"))) == 2
# Outro processo (render da fila depois da prévia) acha o mesmo arquivo.
again = dub.TtsCache(tmp_path / "dub", FakeSynth(), ffmpeg=None)
assert again.get("pt-br-antonio", "olha isso")[0] == f1 and again.synth_calls == 0
# Limpeza: só o que está sem uso há mais de 30 dias.
import os
import time
old = cache.path("pt-br-cadu", "olha isso")
os.utime(old, (time.time() - 40 * 86400,) * 2)
assert cache.prune() == 1 and not old.exists() and f1.exists()
def test_voice_failure_falls_back_to_offline_voice(tmp_path):
synth = FakeSynth(fail_voices=("pt-br-antonio",))
dubber = dub.Dubber(dub.TtsCache(tmp_path, synth, ffmpeg=None), ffmpeg=None)
path, _ = dubber._speech(dub.DubLine(0.0, "oi", "pt-br-antonio"))
assert synth.calls[-1] == (dub.FALLBACK_VOICE, "oi") and path.is_file()
def test_engine_without_voice_service_builds_nothing(tmp_path):
synth = dub.voice_synth(None, None)
with pytest.raises(dub.DubError):
synth("oi", "pt-br-antonio")
dubber = dub.Dubber(dub.TtsCache(tmp_path, synth, ffmpeg="ffmpeg"), ffmpeg="ffmpeg")
cfg = layout.merge({"dev": {"dub": True}})
assert dubber.build([{"s": 11, "e": 12, "pt": "oi"}], CUTS, cfg, 0, 25, tmp_path, "x") is None
# ---------------------------------------------------------------- configuração
def test_dev_group_validates_new_keys():
ok = layout.validate({"dev": {"dub": True, "dubVoice": "pt-br-faber", "dubVoiceOther": "kokoro-pm-alex", "dubDuck": 0.3}})
assert ok["dev"] == {"dub": True, "dubVoice": "pt-br-faber", "dubVoiceOther": "kokoro-pm-alex", "dubDuck": 0.3}
for bad in ({"dubVoice": "../x"}, {"dubVoiceOther": ""}, {"dubDuck": 1.5}, {"dubDuck": "alto"}):
with pytest.raises(layout.LayoutError):
layout.validate({"dev": bad})
merged = layout.merge({"dev": {"dub": True, "dubDuck": 0.1}})
assert merged["dev"]["dubDuck"] == 0.1 and merged["dev"]["dubVoice"] == layout.DUB_VOICE
assert layout.dev_flags(merged, dev=False) == {"translation": False, "dub": False}
# ---------------------------------------------------------------- render: só no vídeo de revisão
class SpyDubber:
def __init__(self):
self.calls, self.level = 0, None
def build(self, translation, cuts, cfg, t0, t1, work, stem, level_db=None):
self.calls, self.level = self.calls + 1, level_db
file = work / f"{stem}.dub.wav"
file.write_bytes(fake_wav(0.5))
return dub.DubTrack(file, [(1.0, 2.0)], 0.25, 1, 0.1, 1)
def _validated(tmp_path: Path) -> dict:
data = {"schema": 1, "source": {"sessionId": 1, "lo": 0, "hi": 60}, "settings": {}, "cuts": CUTS,
"captions": {"enabled": False, "preset": "pop", "style": {}, "emphColor": "#22E36B", "words": []},
"overlays": [], "progress": {"enabled": False, "color": "#FF7A1A", "height": 12},
"audio": {"volume": 1, "narration": [], "music": None, "sfx": []}, "cover": {"enabled": False, "t": 12, "text": ""}}
return editor.validate_project(data, session_id=1, session_duration=100, repo_root=tmp_path, tts_dir=tmp_path / "tts",
assets_dir=tmp_path / "assets")
@pytest.mark.parametrize("dev_render", [True, False])
def test_render_mixes_dub_only_in_review_video(tmp_path, monkeypatch, dev_render):
seen: list[list[str]] = []
def fake_run(args, timeout, cwd=None):
seen.append(args)
(Path(cwd) / args[-1]).write_bytes(b"mp4")
return b""
monkeypatch.setattr(media, "run", fake_run)
monkeypatch.setattr(editor_render, "mean_volume", lambda *a, **k: -32.0)
(tmp_path / "seg.ts").write_bytes(b"")
spy = SpyDubber()
lines = [{"s": 11.0, "e": 12.0, "text": "No way.", "pt": "Não acredito."}]
info = editor_render.render_project(
"ffmpeg", None, [], [(tmp_path / "seg.ts", 0.0, 100.0)], _validated(tmp_path),
layout.merge({"dev": {"dub": True}}), "x", tmp_path / "out" / "clip.mp4", tmp_path,
translation=lines, dev=dev_render, dubber=spy)
graph = seen[-1][seen[-1].index("-filter_complex") + 1]
if dev_render:
assert spy.calls == 1 and info["dub"]["cues"] == 1 and spy.level == -32.0 # nivelada pelo original
assert any(a.endswith("clip.dub.wav") for a in seen[-1]) and "0.750*clip(" in graph
assert not (tmp_path / "out" / "clip.dub.wav").exists() # faixa temporária apagada
else: # vídeo final (depois de aprovar): nada da dublagem
assert spy.calls == 0 and info["dub"] is None
assert "clip(" not in graph and not any("dub" in a for a in seen[-1])
def test_render_without_dub_flag_does_not_call_dubber(tmp_path, monkeypatch):
monkeypatch.setattr(media, "run", lambda args, timeout, cwd=None: (Path(cwd) / args[-1]).write_bytes(b"x") and b"")
(tmp_path / "seg.ts").write_bytes(b"")
spy = SpyDubber()
editor_render.render_project("ffmpeg", None, [], [(tmp_path / "seg.ts", 0.0, 100.0)], _validated(tmp_path),
layout.merge({}), "x", tmp_path / "out" / "c.mp4", tmp_path,
translation=[{"s": 11, "e": 12, "pt": "oi"}], dubber=spy)
assert spy.calls == 0
# ---------------------------------------------------------------- FFmpeg de verdade (faixa)
def _samples(file: Path) -> tuple[array, int, int]:
with wave.open(str(file)) as w:
data = array("h", w.readframes(w.getnframes()))
return data, w.getframerate(), w.getnchannels()
def _peak(data: array, rate: int, channels: int, a: float, b: float) -> int:
chunk = data[int(a * rate) * channels:int(b * rate) * channels]
return max((abs(x) for x in chunk), default=0)
@pytest.mark.skipif(not FFMPEG, reason="FFmpeg não instalado")
def test_track_places_speech_at_phrase_start_and_uses_cache(tmp_path):
synth = FakeSynth(per_char=0.1)
dubber = dub.Dubber(dub.TtsCache(tmp_path / "cache", synth, FFMPEG), FFMPEG)
cfg = layout.merge({"dev": {"dub": True}})
lines = [{"s": 11.0, "e": 12.0, "pt": "frase um"}, # saída 1,0 s; ~0,8 s de fala
{"s": 22.0, "e": 23.0, "pt": "removida"}, # trecho removido: não dubla
{"s": 27.0, "e": 28.0, "pt": "frase dois"}] # saída 12,0 s
track = dubber.build(lines, CUTS, cfg, 0.0, 25.0, tmp_path, "full")
assert track and track.cues == 2 and track.synthesized == 2
data, rate, channels = _samples(track.file)
assert channels == 2 and abs(len(data) / channels / rate - 25.0) < 0.05
assert _peak(data, rate, channels, 0.0, 0.95) < 200 # silêncio antes da 1ª frase
assert _peak(data, rate, channels, 1.1, 1.6) > 3000 # fala no lugar
assert _peak(data, rate, channels, 3.0, 11.9) < 200
assert _peak(data, rate, channels, 12.1, 12.6) > 3000
assert track.spans[0][0] == pytest.approx(1.0, abs=0.01)
# Prévia de 5 s a partir de 10 s: só a frase que toca ali; tudo do cache.
preview = dubber.build(lines, CUTS, cfg, 10.0, 15.0, tmp_path, "preview")
assert preview and preview.cues == 1 and preview.synthesized == 0 and len(synth.calls) == 2
data, rate, channels = _samples(preview.file)
assert abs(len(data) / channels / rate - 5.0) < 0.05 and _peak(data, rate, channels, 2.1, 2.6) > 3000
assert preview.spans[0][0] == pytest.approx(2.0, abs=0.01)
@pytest.mark.skipif(not FFMPEG, reason="FFmpeg não instalado")
def test_real_render_with_dub(tmp_path):
import subprocess
seg = tmp_path / "seg.ts"
subprocess.run([FFMPEG, "-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=s=640x360:r=30:d=8", "-f", "lavfi", "-i",
"sine=frequency=300:d=8", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest",
"-f", "mpegts", str(seg)], check=True, capture_output=True)
project = _validated(tmp_path)
project["cuts"] = [{"start": 0.0, "end": 3.0, "mode": None, "muted": False}, {"start": 5.0, "end": 8.0, "mode": None, "muted": False}]
dubber = dub.Dubber(dub.TtsCache(tmp_path / "cache", FakeSynth(), FFMPEG), FFMPEG)
out = tmp_path / "out" / "clip.mp4"
info = editor_render.render_project(
FFMPEG, shutil.which("ffprobe"), ["-c:v", "libx264", "-preset", "ultrafast"], [(seg, 0.0, 8.0)], project,
layout.merge({"dev": {"dub": True}}), "x", out, tmp_path, translation=[{"s": 1.0, "e": 2.0, "pt": "olha só"},
{"s": 5.5, "e": 6.5, "pt": "voltou"}],
dubber=dubber)
assert out.is_file() and info["dub"]["cues"] == 2
assert media.probe_duration(shutil.which("ffprobe"), out) == pytest.approx(6.0, abs=0.25)
assert not list((tmp_path / "out").glob("*.dub.wav"))
# ---------------------------------------------------------------- rotas: prévia do editor e render da fila
from .test_editor import _lavfi_segments, api # noqa: E402,F401 — fixture do editor (sessão, blocos, corte 7)
@pytest.mark.skipif(not FFMPEG, reason="FFmpeg não instalado")
def test_preview_and_queue_render_dub_the_same_way(api, monkeypatch):
from .test_sources_and_api import KEY
client, engine, root = api
_lavfi_segments(root / "data" / "s1")
h = {"X-Service-Key": KEY}
monkeypatch.setattr(engine.intel, "settings_for", lambda session: layout.merge({"dev": {"dub": True}}))
lines = [{"s": 3.0, "e": 4.0, "text": "No way.", "pt": "Não acredito."},
{"s": 6.0, "e": 7.0, "text": "Bro.", "pt": "Mano.", "speaker": "other"}]
monkeypatch.setattr(engine, "translate_clip", lambda clip_id, lo=None, hi=None, force=False: {"lines": lines})
synth = FakeSynth()
engine._dubber = dub.Dubber(dub.TtsCache(root / "data" / "dub", synth, FFMPEG), FFMPEG)
assert dub.for_engine(engine) is engine._dubber
project = client.get("/v1/clips/7/edit", headers=h).json()["project"]
assert client.put("/v1/clips/7/edit", headers=h, json={"project": project, "rev": 0}).status_code == 200
prev = client.post("/v1/clips/7/preview-render", headers=h, json={"fromS": 0, "durationS": 3})
assert prev.status_code == 200, prev.text
assert synth.calls == [(layout.DUB_VOICE, "Não acredito.")] # a prévia só sintetiza o que toca nela
client.post("/v1/clips/7/export", headers=h)
engine.render_pending()
clip = client.get("/v1/clips/7", headers=h).json()
assert clip["status"] == "ready", clip["error"]
# Fila: a 1ª fala veio do cache da prévia; a do "other" saiu com a segunda voz.
assert synth.calls == [(layout.DUB_VOICE, "Não acredito."), (layout.DUB_VOICE_OTHER, "Mano.")]
+1 -1
View File
@@ -152,7 +152,7 @@ def test_voice_language_maps_audience_codes_to_whisper_codes():
def test_dev_layers_never_reach_the_final_render(tmp_path):
"""Contrato `dev` (18/11/2026): camadas de desenvolvimento só no vídeo de revisão; `dev=False` = vídeo final limpo."""
assert layout.DEFAULTS["dev"] == {"translation": False, "dub": False}
assert {k: layout.DEFAULTS["dev"][k] for k in ("translation", "dub")} == {"translation": False, "dub": False}
assert layout.validate({"dev": {"translation": True, "dub": True, "x": 1}})["dev"] == {"translation": True, "dub": True}
cfg = layout.merge({"dev": {"translation": True, "dub": True}})
assert layout.dev_flags(cfg) == {"translation": True, "dub": True}