File size: 7,015 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
"""Pure-CPU ONNX Runtime synthesizer and chunked streaming engine for Lua Nova V1."""
from __future__ import annotations

from collections.abc import Iterator
import json
import os
from pathlib import Path

import numpy as np
import soundfile as sf

from ..text.phonemizer import phonemize
from ..utils.audio import DEFAULT_FADE_MS, DEFAULT_TARGET_RMS_DB, pcm16, postprocess_audio
from .streaming import iter_speakable_pieces, stream_vocoder_chunks


class OnnxSynthesizer:
    """Fast CPU TTS engine running split ``cfm_v5.onnx`` + ``bigvgan.onnx`` via ONNX Runtime."""

    def __init__(

        self,

        cfm_onnx_path: Path | str,

        vocoder_onnx_path: Path | str,

        threads: int | None = None,

        speakers: tuple[str, ...] | None = None,

        sample_rate: int | None = None,

        hop: int | None = None,

        max_tokens: int | None = None,

    ) -> None:
        import onnxruntime as ort

        cfm_path = Path(cfm_onnx_path)
        voc_path = Path(vocoder_onnx_path)
        meta_path = cfm_path.with_suffix(".meta.json")
        meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.is_file() else {}

        self.speakers = tuple(speakers or meta.get("speakers", ("F1",)))
        self.sample_rate = int(sample_rate or meta.get("sample_rate", 24000))
        self.hop = int(hop or meta.get("hop", 256))
        self.max_tokens = int(max_tokens or meta.get("max_tokens", 512))
        self.threads = int(threads) if threads is not None else max(1, (os.cpu_count() or 4) // 2)

        opts = ort.SessionOptions()
        opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
        opts.intra_op_num_threads = self.threads
        opts.inter_op_num_threads = 1
        opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL

        self.cfm_sess = ort.InferenceSession(str(cfm_path), sess_options=opts, providers=["CPUExecutionProvider"])
        self.voc_sess = ort.InferenceSession(str(voc_path), sess_options=opts, providers=["CPUExecutionProvider"])
        self.cfm_meta = meta

    def predict_mel(

        self,

        piece: str,

        voice: str = "F1",

        speed: float = 1.0,

        pitch_shift: float = 0.0,

        pitch_range: float = 1.05,

    ) -> np.ndarray:
        """Predict unnormalized physical 100-band log-mel ``[T, 100]`` for one phrase piece."""
        if voice not in self.speakers:
            raise ValueError(f"unknown speaker {voice!r}; available: {self.speakers}")
        phones = phonemize(piece)
        feed = {
            "tokens": np.asarray([phones.ids], dtype=np.int64),
            "stress": np.asarray([phones.stress], dtype=np.int64),
            "voice": np.asarray([self.speakers.index(voice)], dtype=np.int64),
            "speed": np.asarray([speed], dtype=np.float32),
            "pitch_shift": np.asarray([pitch_shift], dtype=np.float32),
            "pitch_range": np.asarray([pitch_range], dtype=np.float32),
        }
        phys_mel, flen = self.cfm_sess.run(["phys_mel", "frame_lengths"], feed)
        n_frames = int(flen[0])
        return phys_mel[0, :n_frames, :].astype(np.float32, copy=False)

    def decode_mel(self, phys_mel: np.ndarray) -> np.ndarray:
        """Decode physical log-mel ``[T, 100]`` (or ``[1, T, 100]``) to mono 24 kHz float32 audio."""
        mel = np.asarray(phys_mel, dtype=np.float32)
        if mel.ndim == 2:
            mel = mel[None, :, :]
        (wav,) = self.voc_sess.run(["audio"], {"mel": mel})
        return wav[0].astype(np.float32, copy=False)

    def decode_mel_stream(

        self,

        phys_mel: np.ndarray,

        chunk_frames: int = 36,

        context_frames: int = 8,

        fade_frames: int = 4,

    ) -> Iterator[np.ndarray]:
        """Yield overlap-crossfaded 24 kHz waveform chunks from physical log-mel ``[T, 100]``."""
        return stream_vocoder_chunks(
            self.decode_mel,
            phys_mel,
            hop=self.hop,
            chunk_frames=chunk_frames,
            context_frames=context_frames,
            fade_frames=fade_frames,
        )

    def speak(

        self,

        text: str,

        voice: str = "F1",

        speed: float = 1.0,

        pitch_shift: float = 0.0,

        pitch_range: float = 1.05,

        normalize: bool = True,

        postprocess: bool = True,

        pause_ms: float = 120.0,

    ) -> np.ndarray:
        """Synthesize full-utterance mono 24 kHz float32 waveform in ``[-1, 1]``."""
        pieces = iter_speakable_pieces(text, self.max_tokens, normalize=normalize)
        waves = [self.decode_mel(self.predict_mel(p, voice, speed, pitch_shift, pitch_range)) for p in pieces]
        if len(waves) == 1:
            combined = waves[0]
        else:
            gap = np.zeros(int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0)), dtype=np.float32)
            parts: list[np.ndarray] = []
            for idx, w in enumerate(waves):
                if idx > 0 and gap.size:
                    parts.append(gap)
                parts.append(w)
            combined = np.concatenate(parts, axis=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",

        speed: float = 1.0,

        pitch_shift: float = 0.0,

        pitch_range: float = 1.05,

        normalize: bool = True,

        pause_ms: float = 120.0,

        chunk_frames: int = 36,

        context_frames: int = 8,

        fade_frames: int = 4,

    ) -> Iterator[np.ndarray]:
        """Stream 24 kHz mono float32 audio chunks phrase-by-phrase and mel-chunk-by-chunk."""
        pieces = iter_speakable_pieces(text, self.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)
            mel = self.predict_mel(piece, voice=voice, speed=speed, pitch_shift=pitch_shift, pitch_range=pitch_range)
            yield from self.decode_mel_stream(
                mel,
                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