neutts 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- neutts/__init__.py +3 -0
- neutts/neutts.py +465 -0
- neutts-0.1.0.dist-info/METADATA +16 -0
- neutts-0.1.0.dist-info/RECORD +9 -0
- neutts-0.1.0.dist-info/WHEEL +5 -0
- neutts-0.1.0.dist-info/licenses/LICENSE +119 -0
- neutts-0.1.0.dist-info/top_level.txt +2 -0
- neuttsair/__init__.py +3 -0
- neuttsair/neutts.py +11 -0
neutts/__init__.py
ADDED
neutts/neutts.py
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Generator
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import librosa
|
|
5
|
+
import numpy as np
|
|
6
|
+
import torch
|
|
7
|
+
import re
|
|
8
|
+
import platform
|
|
9
|
+
import glob
|
|
10
|
+
import warnings
|
|
11
|
+
from phonemizer.backend import EspeakBackend
|
|
12
|
+
from neucodec import NeuCodec, DistillNeuCodec
|
|
13
|
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _configure_espeak_library():
|
|
17
|
+
"""Auto-detect and configure espeak library on macOS."""
|
|
18
|
+
if platform.system() != "Darwin":
|
|
19
|
+
return # Only needed on macOS
|
|
20
|
+
|
|
21
|
+
# Common Homebrew installation paths
|
|
22
|
+
search_paths = [
|
|
23
|
+
"/opt/homebrew/Cellar/espeak/*/lib/libespeak.*.dylib", # Apple Silicon
|
|
24
|
+
"/usr/local/Cellar/espeak/*/lib/libespeak.*.dylib", # Intel
|
|
25
|
+
"/opt/homebrew/Cellar/espeak-ng/*/lib/libespeak-ng.*.dylib", # Apple Silicon
|
|
26
|
+
"/usr/local/Cellar/espeak-ng/*/lib/libespeak-ng.*.dylib",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
for pattern in search_paths:
|
|
30
|
+
matches = glob.glob(pattern)
|
|
31
|
+
if matches:
|
|
32
|
+
try:
|
|
33
|
+
from phonemizer.backend.espeak.wrapper import EspeakWrapper
|
|
34
|
+
|
|
35
|
+
EspeakWrapper.set_library(matches[0])
|
|
36
|
+
return
|
|
37
|
+
except Exception:
|
|
38
|
+
# If this fails, phonemizer will try its default detection
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# Call before using phonemizer
|
|
43
|
+
_configure_espeak_library()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _linear_overlap_add(frames: list[np.ndarray], stride: int) -> np.ndarray:
|
|
47
|
+
# original impl --> https://github.com/facebookresearch/encodec/blob/main/encodec/utils.py
|
|
48
|
+
assert len(frames)
|
|
49
|
+
dtype = frames[0].dtype
|
|
50
|
+
shape = frames[0].shape[:-1]
|
|
51
|
+
|
|
52
|
+
total_size = 0
|
|
53
|
+
for i, frame in enumerate(frames):
|
|
54
|
+
frame_end = stride * i + frame.shape[-1]
|
|
55
|
+
total_size = max(total_size, frame_end)
|
|
56
|
+
|
|
57
|
+
sum_weight = np.zeros(total_size, dtype=dtype)
|
|
58
|
+
out = np.zeros(*shape, total_size, dtype=dtype)
|
|
59
|
+
|
|
60
|
+
offset: int = 0
|
|
61
|
+
for frame in frames:
|
|
62
|
+
frame_length = frame.shape[-1]
|
|
63
|
+
t = np.linspace(0, 1, frame_length + 2, dtype=dtype)[1:-1]
|
|
64
|
+
weight = np.abs(0.5 - (t - 0.5))
|
|
65
|
+
|
|
66
|
+
out[..., offset : offset + frame_length] += weight * frame
|
|
67
|
+
sum_weight[offset : offset + frame_length] += weight
|
|
68
|
+
offset += stride
|
|
69
|
+
assert sum_weight.min() > 0
|
|
70
|
+
return out / sum_weight
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class NeuTTS:
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
backbone_repo="neuphonic/neutts-nano",
|
|
78
|
+
backbone_device="cpu",
|
|
79
|
+
codec_repo="neuphonic/neucodec",
|
|
80
|
+
codec_device="cpu",
|
|
81
|
+
):
|
|
82
|
+
|
|
83
|
+
# Consts
|
|
84
|
+
self.sample_rate = 24_000
|
|
85
|
+
self.max_context = 2048
|
|
86
|
+
self.hop_length = 480
|
|
87
|
+
self.streaming_overlap_frames = 1
|
|
88
|
+
self.streaming_frames_per_chunk = 25
|
|
89
|
+
self.streaming_lookforward = 5
|
|
90
|
+
self.streaming_lookback = 50
|
|
91
|
+
self.streaming_stride_samples = self.streaming_frames_per_chunk * self.hop_length
|
|
92
|
+
|
|
93
|
+
# ggml & onnx flags
|
|
94
|
+
self._is_quantized_model = False
|
|
95
|
+
self._is_onnx_codec = False
|
|
96
|
+
|
|
97
|
+
# HF tokenizer
|
|
98
|
+
self.tokenizer = None
|
|
99
|
+
|
|
100
|
+
# Load phonemizer + models
|
|
101
|
+
print("Loading phonemizer...")
|
|
102
|
+
self.phonemizer = EspeakBackend(
|
|
103
|
+
language="en-us", preserve_punctuation=True, with_stress=True
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
self._load_backbone(backbone_repo, backbone_device)
|
|
107
|
+
|
|
108
|
+
self._load_codec(codec_repo, codec_device)
|
|
109
|
+
|
|
110
|
+
# Load watermarker (optional)
|
|
111
|
+
try:
|
|
112
|
+
import perth
|
|
113
|
+
|
|
114
|
+
self.watermarker = perth.PerthImplicitWatermarker()
|
|
115
|
+
except (ImportError, AttributeError) as e:
|
|
116
|
+
warnings.warn(
|
|
117
|
+
f"Perth watermarking unavailable: {e}. "
|
|
118
|
+
"Audio will not be watermarked. "
|
|
119
|
+
"Install with: pip install perth>=0.2.0"
|
|
120
|
+
)
|
|
121
|
+
self.watermarker = None
|
|
122
|
+
|
|
123
|
+
def _load_backbone(self, backbone_repo, backbone_device):
|
|
124
|
+
print(f"Loading backbone from: {backbone_repo} on {backbone_device} ...")
|
|
125
|
+
|
|
126
|
+
# GGUF loading
|
|
127
|
+
if backbone_repo.endswith("gguf"):
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
from llama_cpp import Llama
|
|
131
|
+
except ImportError as e:
|
|
132
|
+
raise ImportError(
|
|
133
|
+
"Failed to import `llama_cpp`. "
|
|
134
|
+
"Please install it with:\n"
|
|
135
|
+
" pip install llama-cpp-python"
|
|
136
|
+
) from e
|
|
137
|
+
|
|
138
|
+
# If backbone_repo is a local file path, load it directly with llama.cpp
|
|
139
|
+
if os.path.isfile(backbone_repo):
|
|
140
|
+
self.backbone = Llama(
|
|
141
|
+
model_path=backbone_repo,
|
|
142
|
+
verbose=False,
|
|
143
|
+
n_gpu_layers=-1 if backbone_device == "gpu" else 0,
|
|
144
|
+
n_ctx=self.max_context,
|
|
145
|
+
mlock=True,
|
|
146
|
+
flash_attn=True if backbone_device == "gpu" else False,
|
|
147
|
+
)
|
|
148
|
+
else:
|
|
149
|
+
# Fallback: treat it as a HF repo id (keeps original behavior if ever needed)
|
|
150
|
+
self.backbone = Llama.from_pretrained(
|
|
151
|
+
repo_id=backbone_repo,
|
|
152
|
+
filename="*.gguf",
|
|
153
|
+
verbose=False,
|
|
154
|
+
n_gpu_layers=-1 if backbone_device == "gpu" else 0,
|
|
155
|
+
n_ctx=self.max_context,
|
|
156
|
+
mlock=True,
|
|
157
|
+
flash_attn=True if backbone_device == "gpu" else False,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
self._is_quantized_model = True
|
|
161
|
+
|
|
162
|
+
else:
|
|
163
|
+
self.tokenizer = AutoTokenizer.from_pretrained(backbone_repo)
|
|
164
|
+
self.backbone = AutoModelForCausalLM.from_pretrained(backbone_repo).to(
|
|
165
|
+
torch.device(backbone_device)
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def _load_codec(self, codec_repo, codec_device):
|
|
169
|
+
|
|
170
|
+
print(f"Loading codec from: {codec_repo} on {codec_device} ...")
|
|
171
|
+
|
|
172
|
+
# 1) Local ONNX path (offline, recommended for embedded)
|
|
173
|
+
if codec_repo.endswith(".onnx") and os.path.isfile(codec_repo):
|
|
174
|
+
try:
|
|
175
|
+
from neucodec import NeuCodecOnnxDecoder
|
|
176
|
+
except ImportError as e:
|
|
177
|
+
raise ImportError(
|
|
178
|
+
"Failed to import NeuCodecOnnxDecoder. "
|
|
179
|
+
"Make sure `neucodec` and `onnxruntime` are installed."
|
|
180
|
+
) from e
|
|
181
|
+
|
|
182
|
+
self.codec = NeuCodecOnnxDecoder(codec_repo)
|
|
183
|
+
self._is_onnx_codec = True
|
|
184
|
+
|
|
185
|
+
# 2) Original HF-based behavior (use only if you really want remote download)
|
|
186
|
+
match codec_repo:
|
|
187
|
+
case "neuphonic/neucodec":
|
|
188
|
+
self.codec = NeuCodec.from_pretrained(codec_repo)
|
|
189
|
+
self.codec.eval().to(codec_device)
|
|
190
|
+
case "neuphonic/distill-neucodec":
|
|
191
|
+
self.codec = DistillNeuCodec.from_pretrained(codec_repo)
|
|
192
|
+
self.codec.eval().to(codec_device)
|
|
193
|
+
case "neuphonic/neucodec-onnx-decoder":
|
|
194
|
+
|
|
195
|
+
if codec_device != "cpu":
|
|
196
|
+
raise ValueError("Onnx decoder only currently runs on CPU.")
|
|
197
|
+
|
|
198
|
+
try:
|
|
199
|
+
from neucodec import NeuCodecOnnxDecoder
|
|
200
|
+
except ImportError as e:
|
|
201
|
+
raise ImportError(
|
|
202
|
+
"Failed to import the onnx decoder."
|
|
203
|
+
" Ensure you have onnxruntime installed as well as neucodec >= 0.0.4."
|
|
204
|
+
) from e
|
|
205
|
+
|
|
206
|
+
self.codec = NeuCodecOnnxDecoder.from_pretrained(codec_repo)
|
|
207
|
+
self._is_onnx_codec = True
|
|
208
|
+
|
|
209
|
+
case _:
|
|
210
|
+
raise ValueError(
|
|
211
|
+
"Invalid codec repo! Must be one of:"
|
|
212
|
+
" 'neuphonic/neucodec', 'neuphonic/distill-neucodec',"
|
|
213
|
+
" 'neuphonic/neucodec-onnx-decoder'."
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
def infer(self, text: str, ref_codes: np.ndarray | torch.Tensor, ref_text: str) -> np.ndarray:
|
|
217
|
+
"""
|
|
218
|
+
Perform inference to generate speech from text using the TTS model and reference audio.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
text (str): Input text to be converted to speech.
|
|
222
|
+
ref_codes (np.ndarray | torch.tensor): Encoded reference.
|
|
223
|
+
ref_text (str): Reference text for reference audio. Defaults to None.
|
|
224
|
+
Returns:
|
|
225
|
+
np.ndarray: Generated speech waveform.
|
|
226
|
+
"""
|
|
227
|
+
|
|
228
|
+
# Generate tokens
|
|
229
|
+
if self._is_quantized_model:
|
|
230
|
+
output_str = self._infer_ggml(ref_codes, ref_text, text)
|
|
231
|
+
else:
|
|
232
|
+
prompt_ids = self._apply_chat_template(ref_codes, ref_text, text)
|
|
233
|
+
output_str = self._infer_torch(prompt_ids)
|
|
234
|
+
|
|
235
|
+
# Decode
|
|
236
|
+
wav = self._decode(output_str)
|
|
237
|
+
watermarked_wav = (
|
|
238
|
+
wav
|
|
239
|
+
if self.watermarker is None
|
|
240
|
+
else self.watermarker.apply_watermark(wav, sample_rate=24_000)
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
return watermarked_wav
|
|
244
|
+
|
|
245
|
+
def infer_stream(
|
|
246
|
+
self, text: str, ref_codes: np.ndarray | torch.Tensor, ref_text: str
|
|
247
|
+
) -> Generator[np.ndarray, None, None]:
|
|
248
|
+
"""
|
|
249
|
+
Perform streaming inference to generate speech from
|
|
250
|
+
text using the TTS model and reference audio.
|
|
251
|
+
|
|
252
|
+
Args:
|
|
253
|
+
text (str): Input text to be converted to speech.
|
|
254
|
+
ref_codes (np.ndarray | torch.tensor): Encoded reference.
|
|
255
|
+
ref_text (str): Reference text for reference audio. Defaults to None.
|
|
256
|
+
Yields:
|
|
257
|
+
np.ndarray: Generated speech waveform.
|
|
258
|
+
"""
|
|
259
|
+
|
|
260
|
+
if self._is_quantized_model:
|
|
261
|
+
return self._infer_stream_ggml(ref_codes, ref_text, text)
|
|
262
|
+
|
|
263
|
+
else:
|
|
264
|
+
raise NotImplementedError("Streaming is not implemented for the torch backend!")
|
|
265
|
+
|
|
266
|
+
def encode_reference(self, ref_audio_path: str | Path):
|
|
267
|
+
wav, _ = librosa.load(ref_audio_path, sr=16000, mono=True)
|
|
268
|
+
wav_tensor = torch.from_numpy(wav).float().unsqueeze(0).unsqueeze(0) # [1, 1, T]
|
|
269
|
+
with torch.no_grad():
|
|
270
|
+
ref_codes = self.codec.encode_code(audio_or_path=wav_tensor).squeeze(0).squeeze(0)
|
|
271
|
+
return ref_codes
|
|
272
|
+
|
|
273
|
+
def _decode(self, codes: str):
|
|
274
|
+
|
|
275
|
+
# Extract speech token IDs using regex
|
|
276
|
+
speech_ids = [int(num) for num in re.findall(r"<\|speech_(\d+)\|>", codes)]
|
|
277
|
+
|
|
278
|
+
if len(speech_ids) > 0:
|
|
279
|
+
|
|
280
|
+
# Onnx decode
|
|
281
|
+
if self._is_onnx_codec:
|
|
282
|
+
codes = np.array(speech_ids, dtype=np.int32)[np.newaxis, np.newaxis, :]
|
|
283
|
+
recon = self.codec.decode_code(codes)
|
|
284
|
+
|
|
285
|
+
# Torch decode
|
|
286
|
+
else:
|
|
287
|
+
with torch.no_grad():
|
|
288
|
+
codes = torch.tensor(speech_ids, dtype=torch.long)[None, None, :].to(
|
|
289
|
+
self.codec.device
|
|
290
|
+
)
|
|
291
|
+
recon = self.codec.decode_code(codes).cpu().numpy()
|
|
292
|
+
|
|
293
|
+
return recon[0, 0, :]
|
|
294
|
+
else:
|
|
295
|
+
raise ValueError("No valid speech tokens found in the output.")
|
|
296
|
+
|
|
297
|
+
def _to_phones(self, text: str) -> str:
|
|
298
|
+
phones = self.phonemizer.phonemize([text])
|
|
299
|
+
phones = phones[0].split()
|
|
300
|
+
phones = " ".join(phones)
|
|
301
|
+
return phones
|
|
302
|
+
|
|
303
|
+
def _apply_chat_template(
|
|
304
|
+
self, ref_codes: list[int], ref_text: str, input_text: str
|
|
305
|
+
) -> list[int]:
|
|
306
|
+
|
|
307
|
+
input_text = self._to_phones(ref_text) + " " + self._to_phones(input_text)
|
|
308
|
+
speech_replace = self.tokenizer.convert_tokens_to_ids("<|SPEECH_REPLACE|>")
|
|
309
|
+
speech_gen_start = self.tokenizer.convert_tokens_to_ids("<|SPEECH_GENERATION_START|>")
|
|
310
|
+
text_replace = self.tokenizer.convert_tokens_to_ids("<|TEXT_REPLACE|>")
|
|
311
|
+
text_prompt_start = self.tokenizer.convert_tokens_to_ids("<|TEXT_PROMPT_START|>")
|
|
312
|
+
text_prompt_end = self.tokenizer.convert_tokens_to_ids("<|TEXT_PROMPT_END|>")
|
|
313
|
+
|
|
314
|
+
input_ids = self.tokenizer.encode(input_text, add_special_tokens=False)
|
|
315
|
+
chat = """user: Convert the text to speech:<|TEXT_REPLACE|>\nassistant:<|SPEECH_REPLACE|>"""
|
|
316
|
+
ids = self.tokenizer.encode(chat)
|
|
317
|
+
|
|
318
|
+
text_replace_idx = ids.index(text_replace)
|
|
319
|
+
ids = (
|
|
320
|
+
ids[:text_replace_idx]
|
|
321
|
+
+ [text_prompt_start]
|
|
322
|
+
+ input_ids
|
|
323
|
+
+ [text_prompt_end]
|
|
324
|
+
+ ids[text_replace_idx + 1 :] # noqa
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
speech_replace_idx = ids.index(speech_replace)
|
|
328
|
+
codes_str = "".join([f"<|speech_{i}|>" for i in ref_codes])
|
|
329
|
+
codes = self.tokenizer.encode(codes_str, add_special_tokens=False)
|
|
330
|
+
ids = ids[:speech_replace_idx] + [speech_gen_start] + list(codes)
|
|
331
|
+
|
|
332
|
+
return ids
|
|
333
|
+
|
|
334
|
+
def _infer_torch(self, prompt_ids: list[int]) -> str:
|
|
335
|
+
prompt_tensor = torch.tensor(prompt_ids).unsqueeze(0).to(self.backbone.device)
|
|
336
|
+
speech_end_id = self.tokenizer.convert_tokens_to_ids("<|SPEECH_GENERATION_END|>")
|
|
337
|
+
with torch.no_grad():
|
|
338
|
+
output_tokens = self.backbone.generate(
|
|
339
|
+
prompt_tensor,
|
|
340
|
+
max_length=self.max_context,
|
|
341
|
+
eos_token_id=speech_end_id,
|
|
342
|
+
do_sample=True,
|
|
343
|
+
temperature=1.0,
|
|
344
|
+
top_k=50,
|
|
345
|
+
use_cache=True,
|
|
346
|
+
min_new_tokens=50,
|
|
347
|
+
)
|
|
348
|
+
input_length = prompt_tensor.shape[-1]
|
|
349
|
+
output_str = self.tokenizer.decode(
|
|
350
|
+
output_tokens[0, input_length:].cpu().numpy().tolist(), add_special_tokens=False
|
|
351
|
+
)
|
|
352
|
+
return output_str
|
|
353
|
+
|
|
354
|
+
def _infer_ggml(self, ref_codes: list[int], ref_text: str, input_text: str) -> str:
|
|
355
|
+
ref_text = self._to_phones(ref_text)
|
|
356
|
+
input_text = self._to_phones(input_text)
|
|
357
|
+
|
|
358
|
+
codes_str = "".join([f"<|speech_{idx}|>" for idx in ref_codes])
|
|
359
|
+
prompt = (
|
|
360
|
+
f"user: Convert the text to speech:<|TEXT_PROMPT_START|>{ref_text} {input_text}"
|
|
361
|
+
f"<|TEXT_PROMPT_END|>\nassistant:<|SPEECH_GENERATION_START|>{codes_str}"
|
|
362
|
+
)
|
|
363
|
+
output = self.backbone(
|
|
364
|
+
prompt,
|
|
365
|
+
max_tokens=self.max_context,
|
|
366
|
+
temperature=1.0,
|
|
367
|
+
top_k=50,
|
|
368
|
+
stop=["<|SPEECH_GENERATION_END|>"],
|
|
369
|
+
)
|
|
370
|
+
output_str = output["choices"][0]["text"]
|
|
371
|
+
return output_str
|
|
372
|
+
|
|
373
|
+
def _infer_stream_ggml(
|
|
374
|
+
self, ref_codes: torch.Tensor, ref_text: str, input_text: str
|
|
375
|
+
) -> Generator[np.ndarray, None, None]:
|
|
376
|
+
ref_text = self._to_phones(ref_text)
|
|
377
|
+
input_text = self._to_phones(input_text)
|
|
378
|
+
|
|
379
|
+
codes_str = "".join([f"<|speech_{idx}|>" for idx in ref_codes])
|
|
380
|
+
prompt = (
|
|
381
|
+
f"user: Convert the text to speech:<|TEXT_PROMPT_START|>{ref_text} {input_text}"
|
|
382
|
+
f"<|TEXT_PROMPT_END|>\nassistant:<|SPEECH_GENERATION_START|>{codes_str}"
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
audio_cache: list[np.ndarray] = []
|
|
386
|
+
token_cache: list[str] = [f"<|speech_{idx}|>" for idx in ref_codes]
|
|
387
|
+
n_decoded_samples: int = 0
|
|
388
|
+
n_decoded_tokens: int = len(ref_codes)
|
|
389
|
+
|
|
390
|
+
for item in self.backbone(
|
|
391
|
+
prompt,
|
|
392
|
+
max_tokens=self.max_context,
|
|
393
|
+
temperature=1.0,
|
|
394
|
+
top_k=50,
|
|
395
|
+
stop=["<|SPEECH_GENERATION_END|>"],
|
|
396
|
+
stream=True,
|
|
397
|
+
):
|
|
398
|
+
output_str = item["choices"][0]["text"]
|
|
399
|
+
token_cache.append(output_str)
|
|
400
|
+
|
|
401
|
+
if (
|
|
402
|
+
len(token_cache[n_decoded_tokens:])
|
|
403
|
+
>= self.streaming_frames_per_chunk + self.streaming_lookforward
|
|
404
|
+
):
|
|
405
|
+
|
|
406
|
+
# decode chunk
|
|
407
|
+
tokens_start = max(
|
|
408
|
+
n_decoded_tokens - self.streaming_lookback - self.streaming_overlap_frames, 0
|
|
409
|
+
)
|
|
410
|
+
tokens_end = (
|
|
411
|
+
n_decoded_tokens
|
|
412
|
+
+ self.streaming_frames_per_chunk
|
|
413
|
+
+ self.streaming_lookforward
|
|
414
|
+
+ self.streaming_overlap_frames
|
|
415
|
+
)
|
|
416
|
+
sample_start = (n_decoded_tokens - tokens_start) * self.hop_length
|
|
417
|
+
sample_end = (
|
|
418
|
+
sample_start
|
|
419
|
+
+ (self.streaming_frames_per_chunk + 2 * self.streaming_overlap_frames)
|
|
420
|
+
* self.hop_length
|
|
421
|
+
)
|
|
422
|
+
curr_codes = token_cache[tokens_start:tokens_end]
|
|
423
|
+
recon = self._decode("".join(curr_codes))
|
|
424
|
+
recon = (
|
|
425
|
+
recon
|
|
426
|
+
if self.watermarker is None
|
|
427
|
+
else self.watermarker.apply_watermark(recon, sample_rate=24_000)
|
|
428
|
+
)
|
|
429
|
+
recon = recon[sample_start:sample_end]
|
|
430
|
+
audio_cache.append(recon)
|
|
431
|
+
|
|
432
|
+
# postprocess
|
|
433
|
+
processed_recon = _linear_overlap_add(
|
|
434
|
+
audio_cache, stride=self.streaming_stride_samples
|
|
435
|
+
)
|
|
436
|
+
new_samples_end = len(audio_cache) * self.streaming_stride_samples
|
|
437
|
+
processed_recon = processed_recon[n_decoded_samples:new_samples_end]
|
|
438
|
+
n_decoded_samples = new_samples_end
|
|
439
|
+
n_decoded_tokens += self.streaming_frames_per_chunk
|
|
440
|
+
yield processed_recon
|
|
441
|
+
|
|
442
|
+
# final decoding handled seperately as non-constant chunk size
|
|
443
|
+
remaining_tokens = len(token_cache) - n_decoded_tokens
|
|
444
|
+
if len(token_cache) > n_decoded_tokens:
|
|
445
|
+
tokens_start = max(
|
|
446
|
+
len(token_cache)
|
|
447
|
+
- (self.streaming_lookback + self.streaming_overlap_frames + remaining_tokens),
|
|
448
|
+
0,
|
|
449
|
+
)
|
|
450
|
+
sample_start = (
|
|
451
|
+
len(token_cache) - tokens_start - remaining_tokens - self.streaming_overlap_frames
|
|
452
|
+
) * self.hop_length
|
|
453
|
+
curr_codes = token_cache[tokens_start:]
|
|
454
|
+
recon = self._decode("".join(curr_codes))
|
|
455
|
+
recon = (
|
|
456
|
+
recon
|
|
457
|
+
if self.watermarker is None
|
|
458
|
+
else self.watermarker.apply_watermark(recon, sample_rate=24_000)
|
|
459
|
+
)
|
|
460
|
+
recon = recon[sample_start:]
|
|
461
|
+
audio_cache.append(recon)
|
|
462
|
+
|
|
463
|
+
processed_recon = _linear_overlap_add(audio_cache, stride=self.streaming_stride_samples)
|
|
464
|
+
processed_recon = processed_recon[n_decoded_samples:]
|
|
465
|
+
yield processed_recon
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: neutts
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: NeuTTS - a package for text-to-speech generation using Neuphonics TTS models.
|
|
5
|
+
Author-email: neuphonic <general@neuphonic.com>
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: librosa==0.11.0
|
|
9
|
+
Requires-Dist: neucodec>=0.0.4
|
|
10
|
+
Requires-Dist: numpy~=2.2.6
|
|
11
|
+
Requires-Dist: phonemizer>=3.0.0
|
|
12
|
+
Requires-Dist: resemble-perth==1.0.1
|
|
13
|
+
Requires-Dist: soundfile==0.13.1
|
|
14
|
+
Requires-Dist: torch>=2.8.0
|
|
15
|
+
Requires-Dist: transformers~=4.56.1
|
|
16
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
neutts/__init__.py,sha256=hddhq1_HdIr30GtoeYhARPumA4ET1W7QW5hgqMVQT8o,49
|
|
2
|
+
neutts/neutts.py,sha256=TMpshBT_yoInKrz6_WV9dnzQgvvT50djaGzwAKfxfzI,17747
|
|
3
|
+
neutts-0.1.0.dist-info/licenses/LICENSE,sha256=7CGCbnYiDp_SkdQn1VHp-Vx5NKdGWLOjrIQxGwpoZaw,11085
|
|
4
|
+
neuttsair/__init__.py,sha256=Z1fqgoEL9bkcUtwHcO6y4ly0vINa99pISVFZKFO9_UQ,55
|
|
5
|
+
neuttsair/neutts.py,sha256=1GakVYRZZnlTtlsZGvRxDRY5768sywURonLHLBSjeiU,257
|
|
6
|
+
neutts-0.1.0.dist-info/METADATA,sha256=sWlF41oo1V7zCiR0ZZS7ix9-xCnNlQL5cHW63nioheE,509
|
|
7
|
+
neutts-0.1.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
|
|
8
|
+
neutts-0.1.0.dist-info/top_level.txt,sha256=eyRQcARniW63_drAEjVvpLnnki4ngBSPkRNuw5jlHXQ,17
|
|
9
|
+
neutts-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
NeuTTS License
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
The NeuTTS Open License v1.0 sets out the terms under which you can use our models.
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
Last Updated: 11 December 2025
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
NeuTTS Open License v1.0
|
|
11
|
+
Purpose: This License is intended to allow free research use and limited commercial use, while requiring a paid license for large-revenue commercial deployments.
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
15
|
+
1. Definitions.
|
|
16
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
"Licensor" shall mean Neuphonic Limited
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work.
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
"Commercial Use" shall mean any use of the Work for direct or indirect commercial advantage or monetary compensation.
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
"Qualified Non-Profit Organization" shall mean a Legal Entity that is organized and operated exclusively for religious, charitable, scientific, testing for public safety, literary, or educational purposes, and which is exempt from federal income tax under Section 501(c)(3) of the United States Internal Revenue Code of 1986, as amended, or any equivalent non-profit or charitable organization in a foreign jurisdiction, including UK registered charities and EU public-benefit organizations.
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
"Non-Commercial or Research Purposes" shall mean purposes that do not involve any use of the Work or a Derivative Work for Commercial Use.
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
"Threshold" shall mean annual revenue of 5 million United States dollars ($5,000,000) or more.
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
“Output” shall mean any data, text, audio, or other content generated by the Work.
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
2. Grant of Copyright License.
|
|
62
|
+
Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
3. Grant of Patent License.
|
|
66
|
+
Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
4. Redistribution.
|
|
70
|
+
You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
5. Commercial Use Limitation.
|
|
89
|
+
(a) The rights granted under this License for Commercial Use of the Work, Derivative Works, or Outputs are conditioned upon You or Your Legal Entity not exceeding the Threshold.
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
(b) Any Commercial Use of the Work or a Derivative Work by a Legal Entity that exceeds the Threshold is not licensed under this Agreement.
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
(c) The Threshold shall not apply to a Qualified Non-Profit Organization's use of the Work or a Derivative Work for Non-Commercial or Research Purposes.
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
6. Submission of Contributions.
|
|
99
|
+
Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
7. Trademarks.
|
|
103
|
+
This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except for the reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
8. Disclaimer of Warranty.
|
|
107
|
+
Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
9. Limitation of Liability.
|
|
111
|
+
In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
10. Accepting Warranty or Additional Liability.
|
|
115
|
+
While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
11. Termination.
|
|
119
|
+
This License will terminate automatically and immediately if You fail to comply with any of its terms and conditions. Upon termination, You must cease all use of the Work and any Derivative Works and delete all copies in Your possession.
|
neuttsair/__init__.py
ADDED
neuttsair/neutts.py
ADDED