File size: 7,760 Bytes
d4101a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""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