File size: 10,374 Bytes
29439fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16f0b6b
 
29439fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16f0b6b
 
29439fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Local-only inference for the complete, merged TTS-V4 checkpoint.

    tts = TTSV4()                                         # this directory
    audio, sr = tts.synthesize('您好……', voice='service_female')        # offline
    session = tts.stream(voice='service_female', mode='icl')            # bidirectional streaming
    session.push_text('您好,'); session.push_text('您的账单……'); session.end()
    for pcm in session.audio(): ...                       # float32 chunks at 24 kHz
"""
import json
import os
from pathlib import Path

# Inference never downloads a second model. Download the complete snapshot once.
os.environ['HF_HUB_OFFLINE'] = '1'
os.environ['TRANSFORMERS_OFFLINE'] = '1'

import numpy as np
import torch

torch.backends.cuda.enable_cudnn_sdp(False)  # sporadic cuDNN SDPA failures on shared GPUs

from text_normalization import normalize_text

ROOT = Path(__file__).resolve().parent
REQUIRED = (
    'config.json', 'generation_config.json', 'model.safetensors',
    'preprocessor_config.json', 'tokenizer_config.json', 'vocab.json', 'merges.txt',
    'speech_tokenizer/config.json', 'speech_tokenizer/model.safetensors',
    'speech_tokenizer/preprocessor_config.json', 'data/voices.json',
)
# Sampling used for all published V4 evaluations (see MODEL_CARD.md).
DEFAULT_TEMPERATURE = 0.8


class TTSV4:
    """One complete local model: six reference voices or a custom real reference (audio + transcript)."""

    def __init__(self, model_dir=ROOT, device='cuda:0', threads=2):
        self.root = Path(model_dir).expanduser().resolve()
        missing = [name for name in REQUIRED if not (self.root / name).is_file()]
        if missing:
            raise FileNotFoundError('完整模型目录缺少文件:' + ', '.join(missing))
        if device.startswith('cuda') and not torch.cuda.is_available():
            raise RuntimeError('CUDA不可用;请安装匹配的PyTorch/CUDA运行环境')
        torch.set_num_threads(threads)
        from stream_engine import StreamingTTS
        self.engine = StreamingTTS(self.root, device=device)
        self.model = self.engine.tts
        self.voices = self.engine.voice_info
        self.prompts = {}

    def _prompt(self, voice, ref_audio, ref_text):
        if voice is not None:
            if ref_audio is not None or ref_text is not None:
                raise ValueError('固定voice和自定义参考不能同时指定')
            if voice not in self.voices:
                raise ValueError(f'未知voice:{voice};可用:{list(self.voices)}')
            if voice not in self.prompts:
                self.prompts[voice] = self.model.create_voice_clone_prompt(
                    ref_audio=str(self.root / 'data/voices' / f'{voice}.wav'),
                    ref_text=self.voices[voice]['text'], x_vector_only_mode=False)
            return self.prompts[voice]
        if ref_audio is None or not isinstance(ref_text, str) or not ref_text.strip():
            raise ValueError('请指定voice,或同时提供ref_audio和ref_text')
        path = Path(ref_audio).expanduser().resolve()
        if not path.is_file():
            raise FileNotFoundError(path)
        return self.model.create_voice_clone_prompt(ref_audio=str(path), ref_text=ref_text, x_vector_only_mode=False)

    def synthesize(self, text, voice=None, ref_audio=None, ref_text=None, seed=5000,
                   temperature=DEFAULT_TEMPERATURE, speed=1.0, max_new_tokens=2048):
        """Offline (whole text known): native non-streaming ICL generation.

        speed: pitch-preserving speaking-rate change applied to the output (0.5-2.0, recommended 0.8-1.3).
        """
        if not isinstance(text, str) or not text.strip():
            raise ValueError('text不能为空')
        prompt = self._prompt(voice, ref_audio, ref_text)
        torch.manual_seed(seed)
        with self.engine.lock:
            waves, sample_rate = self.model.generate_voice_clone(
                text=normalize_text(text), language='Chinese', voice_clone_prompt=prompt,
                non_streaming_mode=True, max_new_tokens=max_new_tokens,
                temperature=temperature, subtalker_temperature=temperature)
        audio = np.asarray(waves[0], dtype=np.float32).reshape(-1)
        if len(audio) == 0 or not np.isfinite(audio).all():
            raise RuntimeError('模型返回空音频或非有限采样值')
        if speed != 1.0:
            from speed import change_speed
            audio = change_speed(audio, sample_rate, speed)
        from stream_engine import level_audio
        audio = level_audio(audio, sample_rate)
        return audio, sample_rate

    def stream(self, voice=None, ref_audio=None, ref_text=None, mode='icl', segment=None, seed=None,
               temperature=DEFAULT_TEMPERATURE, speed=1.0, **kw):
        """Bidirectional streaming session (push_text/end/cancel + audio() generator).

        mode='xvec': speaker embedding only; starts after the first text token (lowest latency).
        mode='icl' : reference audio + transcript (richer acoustic reference; naturalness requires listening).
        segment='token'   : text is fed to the model as it arrives; icl then starts once
                            icl_start_tokens() tokens exist, or when end() is called.
        segment='sentence': each complete sentence is generated with its full text known;
                            icl starts ~0.2-0.4 s after the first sentence is complete.
        segment=None      : 'sentence' for icl, 'token' for xvec (same default as stream_server.py).
        speed             : pitch-preserving speaking-rate change of the output (0.5-2.0; 1.0 = unchanged).
        """
        if segment is None:
            segment = 'sentence' if mode == 'icl' else 'token'
        sampling = dict(temperature=temperature, subtalker_temperature=temperature)
        return self.engine.session(voice, ref_audio=ref_audio, ref_text=ref_text, mode=mode, segment=segment,
                                    speed=speed, seed=seed, sampling=sampling, **kw)

    def synthesize_batch(self, texts, voice=None, ref_audio=None, ref_text=None, seed=5000,
                         temperature=DEFAULT_TEMPERATURE, speed=1.0, batch_size=8, max_new_tokens=2048):
        """Offline GPU batching via native generate_voice_clone(text=list).

        Returns (list[float32 ndarray], sample_rate), in input order. voice can
        be one fixed voice or a list matching texts. Custom ref_audio/ref_text
        may likewise be scalar or lists. This returns completed audio, not
        per-request streaming chunks. Batch grouping affects sampled outputs.
        """
        if not isinstance(texts, (list, tuple)) or not texts:
            raise ValueError('texts必须是非空文本列表')
        if any(not isinstance(text, str) or not text.strip() for text in texts):
            raise ValueError('texts中的每项必须是非空字符串')
        if not isinstance(batch_size, int) or isinstance(batch_size, bool) or batch_size < 1:
            raise ValueError('batch_size必须是正整数')
        if not 0.5 <= speed <= 2.0:
            raise ValueError('speed必须在0.5–2.0之间')

        def expand(value, name):
            if isinstance(value, (list, tuple)):
                if len(value) != len(texts):
                    raise ValueError(f'{name}列表长度必须与texts一致')
                return list(value)
            return [value] * len(texts)

        voices = expand(voice, 'voice')
        audios = expand(ref_audio, 'ref_audio')
        transcripts = expand(ref_text, 'ref_text')
        prompts = [self._prompt(v, a, r)[0] for v, a, r in zip(voices, audios, transcripts)]
        normalized = [normalize_text(text) for text in texts]
        result = []
        sample_rate = self.engine.sample_rate
        for offset in range(0, len(texts), batch_size):
            group = normalized[offset:offset + batch_size]
            with self.engine.lock:
                if seed is not None:
                    torch.manual_seed(seed + offset)
                waves, sample_rate = self.model.generate_voice_clone(
                    text=group, language=['Chinese'] * len(group),
                    voice_clone_prompt=prompts[offset:offset + batch_size],
                    non_streaming_mode=True, max_new_tokens=max_new_tokens,
                    temperature=temperature, subtalker_temperature=temperature)
            if len(waves) != len(group):
                raise RuntimeError('模型返回音频条数与输入不一致')
            for wave in waves:
                pcm = np.asarray(wave, dtype=np.float32).reshape(-1)
                if not len(pcm) or not np.isfinite(pcm).all():
                    raise RuntimeError('模型返回空音频或非有限采样值')
                if speed != 1.0:
                    from speed import change_speed
                    pcm = change_speed(pcm, sample_rate, speed)
                from stream_engine import level_audio
                pcm = level_audio(pcm, sample_rate)
                result.append(pcm)
        return result, sample_rate

    def icl_start_tokens(self, voice=None, ref_audio=None, ref_text=None):
        """Text tokens an icl stream must receive before its first audio frame (unless end() comes first)."""
        from streaming_layout import required_target_tokens
        v = self.engine.voice(voice, ref_audio, ref_text)
        return required_target_tokens('icl', v.ref_ids, v.ref_codes)

    def stream_sentences(self, text_pieces, voice=None, ref_audio=None, ref_text=None, mode='icl',
                         seed=None, temperature=DEFAULT_TEMPERATURE, speed=1.0, max_chars=60):
        """Convenience: consume an iterable of text pieces (e.g. LLM deltas) in a background
        thread and yield audio chunks, using segment='sentence'."""
        import threading
        s = self.stream(voice=voice, ref_audio=ref_audio, ref_text=ref_text, mode=mode, seed=seed,
                        temperature=temperature, segment='sentence', speed=speed, max_chars=max_chars)

        def reader():
            try:
                for piece in text_pieces:
                    s.push_text(piece or '')
            finally:
                s.end()
        threading.Thread(target=reader, daemon=True).start()
        yield from s.audio()


TTSV8 = TTSV4