"""High-level PyTorch inference synthesizer for Lua Nova V1.""" from __future__ import annotations from collections.abc import Iterator from pathlib import Path import numpy as np import soundfile as sf import torch from ..models.bigvgan import BigVGANVocoderWrapper from ..models.cfm import LuaNovaCFM from ..text.phonemizer import phonemize from ..training.common import load_cfm_model from ..utils.audio import ( DEFAULT_FADE_MS, DEFAULT_TARGET_RMS_DB, pcm16, postprocess_audio, ) from .streaming import iter_speakable_pieces, stream_vocoder_chunks class Synthesizer: """End-to-end Brazilian Portuguese TTS pipeline (CFM v5 + BigVGAN 24 kHz).""" def __init__(self, cfm: LuaNovaCFM, vocoder: BigVGANVocoderWrapper, device: str = "cpu") -> None: self.cfm = cfm.to(device).eval() self.vocoder = vocoder.to(device).eval() self.device = str(device) self.sample_rate = int(self.cfm.config.sample_rate) self.hop = int(self.cfm.config.hop) @classmethod def from_checkpoints( cls, cfm_path: Path | str, vocoder_path_or_id: Path | str = "nvidia/bigvgan_base_24khz_100band", device: str = "cpu", ) -> "Synthesizer": """Load acoustic CFM weights and either a local fine-tuned vocoder `.pt` or Hugging Face repo ID.""" cfm = load_cfm_model(cfm_path, device=device, load_vocos=False) voc_target = Path(vocoder_path_or_id) if voc_target.is_file(): voc = BigVGANVocoderWrapper(ckpt_path=voc_target, device=device) else: voc = BigVGANVocoderWrapper(model_id=str(vocoder_path_or_id), device=device) return cls(cfm=cfm, vocoder=voc, device=device) def _predict_piece_mel( self, piece: str, voice: str, n_steps: int, temperature: float, cfg_scale: float, sway_coef: float, solver: str, pitch_range: float | None, speed: float, pitch_shift: float, seed: int, ) -> tuple[torch.Tensor, torch.Tensor]: if voice not in self.cfm.config.speakers: raise ValueError(f"unknown speaker {voice!r}; available: {self.cfm.config.speakers}") phones = phonemize(piece) tok = torch.tensor([phones.ids], device=self.device) st = torch.tensor([phones.stress], device=self.device) ln = torch.tensor([len(phones)], device=self.device) sp = torch.tensor([self.cfm.config.speakers.index(voice)], device=self.device) with torch.inference_mode(): phys_mel, flen, _ = self.cfm.predict_physical_mel( tok, st, ln, sp, speed=speed, pitch_shift=pitch_shift, seed=seed, pitch_range=pitch_range, n_steps=n_steps, cfg_scale=cfg_scale, temperature=temperature, solver=solver, sway_coef=sway_coef, ) return phys_mel, flen def _decode_mel_slice(self, mel_chunk: np.ndarray) -> np.ndarray: mel_t = torch.from_numpy(mel_chunk[None, :, :]).to(device=self.device, dtype=torch.float32) flen = torch.tensor([mel_t.shape[1]], device=self.device, dtype=torch.long) with torch.inference_mode(): wav = self.vocoder.decode_raw_mel(mel_t, flen)[0, : int(flen[0]) * self.hop] return wav.cpu().numpy() def speak( self, text: str, voice: str = "F1", n_steps: int = 8, temperature: float = 0.35, cfg_scale: float = 1.0, sway_coef: float = -0.5, solver: str = "midpoint", pitch_range: float | None = 1.05, speed: float = 1.0, pitch_shift: float = 0.0, normalize: bool = True, postprocess: bool = True, pause_ms: float = 120.0, seed: int = 0, ) -> np.ndarray: """Synthesize arbitrary-length PT-BR text into a mono 24 kHz float32 waveform in [-1, 1].""" pieces = iter_speakable_pieces(text, self.cfm.config.max_tokens, normalize=normalize) waves: list[torch.Tensor] = [] for idx, piece in enumerate(pieces): phys_mel, flen = self._predict_piece_mel( piece, voice, n_steps, temperature, cfg_scale, sway_coef, solver, pitch_range, speed, pitch_shift, seed + idx, ) with torch.inference_mode(): wav = self.vocoder.decode_raw_mel(phys_mel, flen)[0, : int(flen[0]) * self.hop] waves.append(wav.cpu()) if len(waves) == 1: combined = waves[0] else: gap = torch.zeros(int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0)), dtype=torch.float32) parts: list[torch.Tensor] = [] for idx, w in enumerate(waves): if idx > 0 and gap.numel(): parts.append(gap) parts.append(w) combined = torch.cat(parts, dim=0) if postprocess: combined = postprocess_audio( combined, sample_rate=self.sample_rate, target_rms_db=DEFAULT_TARGET_RMS_DB, fade_ms=DEFAULT_FADE_MS, ) pcm, _ = pcm16(combined) return pcm.astype(np.float32) def speak_stream( self, text: str, voice: str = "F1", n_steps: int = 8, temperature: float = 0.35, cfg_scale: float = 1.0, sway_coef: float = -0.5, solver: str = "midpoint", pitch_range: float | None = 1.05, speed: float = 1.0, pitch_shift: float = 0.0, normalize: bool = True, pause_ms: float = 120.0, seed: int = 0, chunk_frames: int = 36, context_frames: int = 8, fade_frames: int = 4, ) -> Iterator[np.ndarray]: """Yield low-latency 24 kHz waveform chunks via overlap-crossfaded mel streaming.""" pieces = iter_speakable_pieces(text, self.cfm.config.max_tokens, normalize=normalize) gap_samples = int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0)) for idx, piece in enumerate(pieces): if idx > 0 and gap_samples > 0: yield np.zeros(gap_samples, dtype=np.float32) phys_mel, flen = self._predict_piece_mel( piece, voice, n_steps, temperature, cfg_scale, sway_coef, solver, pitch_range, speed, pitch_shift, seed + idx, ) mel_np = phys_mel[0, : int(flen[0]), :].cpu().numpy() yield from stream_vocoder_chunks( self._decode_mel_slice, mel_np, hop=self.hop, chunk_frames=chunk_frames, context_frames=context_frames, fade_frames=fade_frames, ) def save_wav(self, path: Path | str, wav: np.ndarray) -> Path: """Save synthesized audio as 16-bit 24 kHz PCM WAV.""" out_path = Path(path) out_path.parent.mkdir(parents=True, exist_ok=True) pcm, _ = pcm16(wav) sf.write(out_path, pcm, self.sample_rate, subtype="PCM_16") return out_path