neutts 0.1.0__tar.gz
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-0.1.0/LICENSE +119 -0
- neutts-0.1.0/PKG-INFO +16 -0
- neutts-0.1.0/README.md +264 -0
- neutts-0.1.0/neutts/__init__.py +3 -0
- neutts-0.1.0/neutts/neutts.py +465 -0
- neutts-0.1.0/neutts.egg-info/PKG-INFO +16 -0
- neutts-0.1.0/neutts.egg-info/SOURCES.txt +13 -0
- neutts-0.1.0/neutts.egg-info/dependency_links.txt +1 -0
- neutts-0.1.0/neutts.egg-info/requires.txt +8 -0
- neutts-0.1.0/neutts.egg-info/top_level.txt +2 -0
- neutts-0.1.0/neuttsair/__init__.py +3 -0
- neutts-0.1.0/neuttsair/neutts.py +11 -0
- neutts-0.1.0/pyproject.toml +25 -0
- neutts-0.1.0/setup.cfg +4 -0
- neutts-0.1.0/tests/test_neutts.py +85 -0
neutts-0.1.0/LICENSE
ADDED
|
@@ -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.
|
neutts-0.1.0/PKG-INFO
ADDED
|
@@ -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
|
neutts-0.1.0/README.md
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
# NeuTTS
|
|
2
|
+
|
|
3
|
+
HuggingFace 🤗:
|
|
4
|
+
|
|
5
|
+
- NeuTTS-Air: [Model](https://huggingface.co/neuphonic/neutts-air), [Q8 GGUF](https://huggingface.co/neuphonic/neutts-air-q8-gguf), [Q4 GGUF](https://huggingface.co/neuphonic/neutts-air-q4-gguf), [Spaces](https://huggingface.co/spaces/neuphonic/neutts-air)
|
|
6
|
+
- NeuTTS-Nano: [Model](https://huggingface.co/neuphonic/neutts-nano), [Q8 GGUF](https://huggingface.co/neuphonic/neutts-nano-q8-gguf), [Q4 GGUF](https://huggingface.co/neuphonic/neutts-nano-q4-gguf), [Spaces](https://huggingface.co/spaces/neuphonic/neutts-nano)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
[NeuTTS-Nano Demo Video](https://github.com/user-attachments/assets/629ec5b2-4818-4fa6-987a-99fcbadc56bc)
|
|
10
|
+
|
|
11
|
+
_Created by [Neuphonic](http://neuphonic.com/) - building faster, smaller, on-device voice AI_
|
|
12
|
+
|
|
13
|
+
State-of-the-art Voice AI has been locked behind web APIs for too long. NeuTTS is a collection of open source, on-device, TTS speech language models with instant voice cloning. Built off of LLM backbones, NeuTTS brings natural-sounding speech, real-time performance, built-in security and speaker cloning to your local device - unlocking a new category of embedded voice agents, assistants, toys, and compliance-safe apps.
|
|
14
|
+
|
|
15
|
+
## Key Features
|
|
16
|
+
|
|
17
|
+
- 🗣Best-in-class realism for their size - produce natural, ultra-realistic voices that sound human, at the sweet spot between speed, size, and quality for real-world applications
|
|
18
|
+
- 📱Optimised for on-device deployment - provided in GGML format, ready to run on phones, laptops, or even Raspberry Pis
|
|
19
|
+
- 👫Instant voice cloning - create your own speaker with as little as 3 seconds of audio
|
|
20
|
+
- 🚄Simple LM + codec architecture - making development and deployment simple
|
|
21
|
+
|
|
22
|
+
> [!CAUTION]
|
|
23
|
+
> Websites like neutts.com are popping up and they're not affliated with Neuphonic, our github or this repo.
|
|
24
|
+
>
|
|
25
|
+
> We are on neuphonic.com only. Please be careful out there! 🙏
|
|
26
|
+
|
|
27
|
+
## Model Details
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
NeuTTS models are built from small LLM backbones - lightweight yet capable language models optimised for text understanding and generation - as well as a powerful combination of technologies designed for efficiency and quality:
|
|
32
|
+
|
|
33
|
+
- **Supported Languages**: English
|
|
34
|
+
- **Audio Codec**: [NeuCodec](https://huggingface.co/neuphonic/neucodec) - our 50hz neural audio codec that achieves exceptional audio quality at low bitrates using a single codebook
|
|
35
|
+
- **Context Window**: 2048 tokens, enough for processing ~30 seconds of audio (including prompt duration)
|
|
36
|
+
- **Format**: Available in GGML format for efficient on-device inference
|
|
37
|
+
- **Responsibility**: Watermarked outputs
|
|
38
|
+
- **Inference Speed**: Real-time generation on mid-range devices
|
|
39
|
+
- **Power Consumption**: Optimised for mobile and embedded devices
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
| | NeuTTSAir | NeuTTSNano |
|
|
43
|
+
|---|---:|---:|
|
|
44
|
+
| **# Params (Active)** | ~360m | ~120m |
|
|
45
|
+
| **# Params (Emb + Active)** | ~552m | ~229m |
|
|
46
|
+
| **Cloning** | Yes | Yes |
|
|
47
|
+
| **License** | Apache 2.0 | NeuTTS Open License 1.0 |
|
|
48
|
+
|
|
49
|
+
## Throughput Benchmarking
|
|
50
|
+
|
|
51
|
+
The two models were benchmarked using the Q4 quantisations [neutts-air-Q4-0](https://huggingface.co/neuphonic/neutts-air-q4-gguf) and [neutts-nano-Q4-0](https://huggingface.co/neuphonic/neutts-nano-q4-gguf).
|
|
52
|
+
Benchmarks on CPU were run through llama-bench (llama.cpp) to measure prefill and decode throughput at multiple context sizes.
|
|
53
|
+
|
|
54
|
+
For GPU's (specifically RTX 4090), we leverage vLLM to maximise throughput. We run benchmarks using the [vLLM benchmark](https://docs.vllm.ai/en/stable/cli/bench/throughput/).
|
|
55
|
+
|
|
56
|
+
We include benchmarks on four devices: Galaxy A25 5G, AMD Ryzen 9HX 370, iMac M4 16GB, NVIDIA GeForce RTX 4090.
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
| | NeuTTSAir | NeuTTSNano |
|
|
60
|
+
|---|---:|---:|
|
|
61
|
+
| **Galaxy A25 5G (CPU only)** | 20 tokens/s | 45 tokens/s|
|
|
62
|
+
| **AMD Ryzen 9 HX 370 (CPU only)** | 119 tokens/s | 221 tokens/s |
|
|
63
|
+
| **iMAc M4 16 GB (CPU only)** | 111 tokens/s | 195 tokens/s |
|
|
64
|
+
| **RTX 4090** | 16194 tokens/s | 19268 tokens/s |
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
> [!NOTE]
|
|
68
|
+
> llama-bench used 14 threads for prefill and 16 threads for decode (as configured in the benchmark run) on AMD Ryzen 9HX 370 and iMac M4 16GB, and 6 threads for each on the Galaxy A25 5G. The tokens/s reported are when having 500 prefill tokens and generating 250 output tokens.
|
|
69
|
+
|
|
70
|
+
> [!NOTE]
|
|
71
|
+
> Please note that these benchmarks only include the Speech Language Model and do not include the Codec which is needed for a full audio generation pipeline.
|
|
72
|
+
|
|
73
|
+
## Get Started with NeuTTS
|
|
74
|
+
|
|
75
|
+
> [!NOTE]
|
|
76
|
+
> We have added a [streaming example](examples/basic_streaming_example.py) using the `llama-cpp-python` library as well as a [finetuning script](examples/finetune.py). For finetuning, please refer to the [finetune guide](TRAINING.md) for more details.
|
|
77
|
+
|
|
78
|
+
1. **Clone Git Repo**
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
git clone https://github.com/neuphonic/neutts.git
|
|
82
|
+
cd neutts
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
2. **Install `espeak` (required dependency)**
|
|
86
|
+
|
|
87
|
+
Please refer to the following link for instructions on how to install `espeak`:
|
|
88
|
+
|
|
89
|
+
https://github.com/espeak-ng/espeak-ng/blob/master/docs/guide.md
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
# Mac OS
|
|
93
|
+
brew install espeak-ng
|
|
94
|
+
|
|
95
|
+
# Ubuntu/Debian
|
|
96
|
+
sudo apt install espeak-ng
|
|
97
|
+
|
|
98
|
+
# Windows install
|
|
99
|
+
# via chocolatey (https://community.chocolatey.org/packages?page=1&prerelease=False&moderatorQueue=False&tags=espeak)
|
|
100
|
+
choco install espeak-ng
|
|
101
|
+
# via wingit
|
|
102
|
+
winget install -e --id eSpeak-NG.eSpeak-NG
|
|
103
|
+
# via msi (need to add to path or folow the "Windows users who installed via msi" below)
|
|
104
|
+
# find the msi at https://github.com/espeak-ng/espeak-ng/releases
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Windows users who installed via msi / do not have their install on path need to run the following (see https://github.com/bootphon/phonemizer/issues/163)
|
|
108
|
+
```pwsh
|
|
109
|
+
$env:PHONEMIZER_ESPEAK_LIBRARY = "c:\Program Files\eSpeak NG\libespeak-ng.dll"
|
|
110
|
+
$env:PHONEMIZER_ESPEAK_PATH = "c:\Program Files\eSpeak NG"
|
|
111
|
+
setx PHONEMIZER_ESPEAK_LIBRARY "c:\Program Files\eSpeak NG\libespeak-ng.dll"
|
|
112
|
+
setx PHONEMIZER_ESPEAK_PATH "c:\Program Files\eSpeak NG"
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
3. **Install Python dependencies**
|
|
116
|
+
|
|
117
|
+
The requirements file includes the dependencies needed to run the model with PyTorch.
|
|
118
|
+
When using an ONNX decoder or a GGML model, some dependencies (such as PyTorch) are no longer required.
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
pip install -r requirements.txt
|
|
122
|
+
```
|
|
123
|
+
> [!CAUTION]
|
|
124
|
+
> The inference is compatible and tested on `python">=3.11, <=3.13"`. This is restricted due to pytorch compatibility. [PyTorch Compatibility Matrix](https://github.com/pytorch/pytorch/blob/main/RELEASE.md#release-compatibility-matrix)
|
|
125
|
+
|
|
126
|
+
4. **(Optional) Install Llama-cpp-python to use the `GGUF` models.**
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
pip install llama-cpp-python
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
To run llama-cpp with GPU suport (CUDA, MPS) support please refer to:
|
|
133
|
+
https://pypi.org/project/llama-cpp-python/
|
|
134
|
+
|
|
135
|
+
5. **(Optional) Install onnxruntime to use the `.onnx` decoder.**
|
|
136
|
+
If you want to run the onnxdecoder
|
|
137
|
+
```bash
|
|
138
|
+
pip install onnxruntime
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Running the Model
|
|
142
|
+
|
|
143
|
+
Run the basic example script to synthesize speech:
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
python -m examples.basic_example \
|
|
147
|
+
--input_text "My name is Andy. I'm 25 and I just moved to London. The underground is pretty confusing, but it gets me around in no time at all." \
|
|
148
|
+
--ref_audio samples/jo.wav \
|
|
149
|
+
--ref_text samples/jo.txt
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
To specify a particular model repo for the backbone or codec, add the `--backbone` argument. Available backbones are listed in [NeuTTS-Air](https://huggingface.co/collections/neuphonic/neutts-air) and [NeuTTS-Nano](https://huggingface.co/collections/neuphonic/neutts-nano) huggingface collections.
|
|
153
|
+
|
|
154
|
+
Several examples are available, including a Jupyter notebook in the `examples` folder.
|
|
155
|
+
|
|
156
|
+
### One-Code Block Usage
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from neutts import NeuTTS
|
|
160
|
+
import soundfile as sf
|
|
161
|
+
|
|
162
|
+
tts = NeuTTS(
|
|
163
|
+
backbone_repo="neuphonic/neutts-nano", # or 'neutts-nano-q4-gguf' with llama-cpp-python installed
|
|
164
|
+
backbone_device="cpu",
|
|
165
|
+
codec_repo="neuphonic/neucodec",
|
|
166
|
+
codec_device="cpu"
|
|
167
|
+
)
|
|
168
|
+
input_text = "My name is Andy. I'm 25 and I just moved to London. The underground is pretty confusing, but it gets me around in no time at all."
|
|
169
|
+
|
|
170
|
+
ref_text = "samples/jo.txt"
|
|
171
|
+
ref_audio_path = "samples/jo.wav"
|
|
172
|
+
|
|
173
|
+
ref_text = open(ref_text, "r").read().strip()
|
|
174
|
+
ref_codes = tts.encode_reference(ref_audio_path)
|
|
175
|
+
|
|
176
|
+
wav = tts.infer(input_text, ref_codes, ref_text)
|
|
177
|
+
sf.write("test.wav", wav, 24000)
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### Streaming
|
|
181
|
+
|
|
182
|
+
Speech can also be synthesised in _streaming mode_, where audio is generated in chunks and plays as generated. Note that this requires pyaudio to be installed. To do this, run:
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
python -m examples.basic_streaming_example \
|
|
186
|
+
--input_text "My name is Andy. I'm 25 and I just moved to London. The underground is pretty confusing, but it gets me around in no time at all." \
|
|
187
|
+
--ref_codes samples/jo.pt \
|
|
188
|
+
--ref_text samples/jo.txt
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Again, a particular model repo can be specified with the `--backbone` argument - note that for streaming the model must be in GGUF format.
|
|
192
|
+
|
|
193
|
+
## Preparing References for Cloning
|
|
194
|
+
|
|
195
|
+
NeuTTS requires two inputs:
|
|
196
|
+
|
|
197
|
+
1. A reference audio sample (`.wav` file)
|
|
198
|
+
2. A text string
|
|
199
|
+
|
|
200
|
+
The model then synthesises the text as speech in the style of the reference audio. This is what enables NeuTTS models instant voice cloning capability.
|
|
201
|
+
|
|
202
|
+
### Example Reference Files
|
|
203
|
+
|
|
204
|
+
You can find some ready-to-use samples in the `examples` folder:
|
|
205
|
+
|
|
206
|
+
- `samples/dave.wav`
|
|
207
|
+
- `samples/jo.wav`
|
|
208
|
+
|
|
209
|
+
### Guidelines for Best Results
|
|
210
|
+
|
|
211
|
+
For optimal performance, reference audio samples should be:
|
|
212
|
+
|
|
213
|
+
1. **Mono channel**
|
|
214
|
+
2. **16-44 kHz sample rate**
|
|
215
|
+
3. **3–15 seconds in length**
|
|
216
|
+
4. **Saved as a `.wav` file**
|
|
217
|
+
5. **Clean** — minimal to no background noise
|
|
218
|
+
6. **Natural, continuous speech** — like a monologue or conversation, with few pauses, so the model can capture tone effectively
|
|
219
|
+
|
|
220
|
+
## Guidelines for minimizing Latency
|
|
221
|
+
|
|
222
|
+
For optimal performance on-device:
|
|
223
|
+
|
|
224
|
+
1. Use the GGUF model backbones
|
|
225
|
+
2. Pre-encode references
|
|
226
|
+
3. Use the [onnx codec decoder](https://huggingface.co/neuphonic/neucodec-onnx-decoder)
|
|
227
|
+
|
|
228
|
+
Take a look at this example [examples README](examples/README.md###minimal-latency-example) to get started.
|
|
229
|
+
|
|
230
|
+
## Responsibility
|
|
231
|
+
|
|
232
|
+
Every audio file generated by NeuTTS includes [Perth (Perceptual Threshold) Watermarker](https://github.com/resemble-ai/perth).
|
|
233
|
+
|
|
234
|
+
## Disclaimer
|
|
235
|
+
|
|
236
|
+
Don't use this model to do bad things… please.
|
|
237
|
+
|
|
238
|
+
## Developer Requirements
|
|
239
|
+
|
|
240
|
+
To run the pre commit hooks to contribute to this project run:
|
|
241
|
+
|
|
242
|
+
```bash
|
|
243
|
+
pip install pre-commit
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Then:
|
|
247
|
+
|
|
248
|
+
```bash
|
|
249
|
+
pre-commit install
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Running Tests
|
|
253
|
+
|
|
254
|
+
First, install the dev requirements:
|
|
255
|
+
|
|
256
|
+
```
|
|
257
|
+
pip install -r requirements-dev.txt
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
To run the tests:
|
|
261
|
+
|
|
262
|
+
```
|
|
263
|
+
pytest tests/
|
|
264
|
+
```
|
|
@@ -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,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
neutts/__init__.py
|
|
5
|
+
neutts/neutts.py
|
|
6
|
+
neutts.egg-info/PKG-INFO
|
|
7
|
+
neutts.egg-info/SOURCES.txt
|
|
8
|
+
neutts.egg-info/dependency_links.txt
|
|
9
|
+
neutts.egg-info/requires.txt
|
|
10
|
+
neutts.egg-info/top_level.txt
|
|
11
|
+
neuttsair/__init__.py
|
|
12
|
+
neuttsair/neutts.py
|
|
13
|
+
tests/test_neutts.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "neutts"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name="neuphonic", email="general@neuphonic.com" },
|
|
10
|
+
]
|
|
11
|
+
description = "NeuTTS - a package for text-to-speech generation using Neuphonics TTS models."
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
dependencies = [
|
|
14
|
+
"librosa==0.11.0",
|
|
15
|
+
"neucodec>=0.0.4",
|
|
16
|
+
"numpy~=2.2.6",
|
|
17
|
+
"phonemizer>=3.0.0",
|
|
18
|
+
"resemble-perth==1.0.1",
|
|
19
|
+
"soundfile==0.13.1",
|
|
20
|
+
"torch>=2.8.0",
|
|
21
|
+
"transformers~=4.56.1",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
include = ["neutts*"]
|
neutts-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pytest
|
|
4
|
+
from neuttsair import NeuTTSAir
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
BACKBONES = [
|
|
8
|
+
"neuphonic/neutts-air",
|
|
9
|
+
"neuphonic/neutts-air-q8-gguf",
|
|
10
|
+
"neuphonic/neutts-air-q4-gguf",
|
|
11
|
+
"neuphonic/neutts-nano",
|
|
12
|
+
"neuphonic/neutts-nano-q8-gguf",
|
|
13
|
+
"neuphonic/neutts-nano-q4-gguf",
|
|
14
|
+
]
|
|
15
|
+
GGUF_BACKBONES = [
|
|
16
|
+
i for i in BACKBONES
|
|
17
|
+
if i.endswith(".gguf")
|
|
18
|
+
]
|
|
19
|
+
CODECS = [
|
|
20
|
+
"neuphonic/neucodec",
|
|
21
|
+
"neuphonic/distill-neucodec",
|
|
22
|
+
"neuphonic/neucodec-onnx-decoder",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@pytest.fixture()
|
|
27
|
+
def reference_data() -> tuple[torch.Tensor, str]:
|
|
28
|
+
ref_codes = torch.load("./samples/dave.pt")
|
|
29
|
+
with open("./samples/dave.txt", "r") as f:
|
|
30
|
+
ref_text = f.read()
|
|
31
|
+
return ref_codes, ref_text
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@pytest.mark.parametrize("backbone", BACKBONES)
|
|
35
|
+
@pytest.mark.parametrize("codec", CODECS)
|
|
36
|
+
def test_model_loading_and_inference(backbone, codec, reference_data, tmp_path):
|
|
37
|
+
"""
|
|
38
|
+
Tests every combination of backbone and codec.
|
|
39
|
+
Ensures a valid numpy audio array is returned.
|
|
40
|
+
"""
|
|
41
|
+
ref_codes, ref_text = reference_data
|
|
42
|
+
input_text = "Testing."
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
model = NeuTTSAir(
|
|
46
|
+
backbone_repo=backbone,
|
|
47
|
+
backbone_device="cpu",
|
|
48
|
+
codec_repo=codec,
|
|
49
|
+
codec_device="cpu"
|
|
50
|
+
)
|
|
51
|
+
except Exception as e:
|
|
52
|
+
pytest.fail(f"Failed to load combination {backbone} + {codec}: {e}")
|
|
53
|
+
|
|
54
|
+
audio = model.infer(text=input_text, ref_codes=ref_codes, ref_text=ref_text)
|
|
55
|
+
assert isinstance(audio, np.ndarray), "Output should be a numpy array"
|
|
56
|
+
assert len(audio) > 0, "Generated audio should not be empty"
|
|
57
|
+
assert not np.isnan(audio).any(), "Audio contains NaN values"
|
|
58
|
+
assert audio.dtype in [np.float32, np.float64]
|
|
59
|
+
|
|
60
|
+
print(f"Successfully generated {len(audio)/24000:.2f}s of audio for {codec}")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@pytest.mark.parametrize("backbone", GGUF_BACKBONES)
|
|
64
|
+
@pytest.mark.parametrize("codec", CODECS)
|
|
65
|
+
def test_streaming_ggml(backbone, codec, reference_data):
|
|
66
|
+
ref_codes, ref_text = reference_data
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
model = NeuTTSAir(
|
|
70
|
+
backbone_repo=backbone,
|
|
71
|
+
backbone_device="cpu",
|
|
72
|
+
codec_repo=codec,
|
|
73
|
+
codec_device="cpu"
|
|
74
|
+
)
|
|
75
|
+
except Exception as e:
|
|
76
|
+
pytest.fail(f"Failed to load combination {backbone} + {codec}: {e}")
|
|
77
|
+
|
|
78
|
+
gen = model.infer_stream("This is a streaming test that should be comprised of multple chunks.", ref_codes, ref_text)
|
|
79
|
+
|
|
80
|
+
chunks = []
|
|
81
|
+
for chunk in gen:
|
|
82
|
+
assert isinstance(chunk, np.ndarray)
|
|
83
|
+
chunks.append(chunk)
|
|
84
|
+
|
|
85
|
+
assert len(chunks) > 0, "Stream yielded no audio chunks"
|