open-source commit

This commit is contained in:
Jiameng Gao
2025-10-02 13:49:54 +01:00
commit 3e9415df12
18 changed files with 1205 additions and 0 deletions

213
.gitignore vendored Normal file
View File

@@ -0,0 +1,213 @@
# MacOS
**.DS_Store
# Emacs
*~
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py.cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
#poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
#pdm.lock
#pdm.toml
.pdm-python
.pdm-build/
# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
#pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.envrc
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/
# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# you could uncomment the following to ignore the entire vscode folder
# .vscode/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
# Cursor
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
# refer to https://docs.cursor.com/context/ignore-files
.cursorignore
.cursorindexingignore
# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/

22
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,22 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0 # Use the latest tag from the repo
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: requirements-txt-fixer
- repo: https://github.com/psf/black
rev: 24.4.2 # Use the appropriate version of black
hooks:
- id: black
language_version: python3
args: [--line-length=100]
- repo: https://github.com/PyCQA/flake8
rev: 7.0.0
hooks:
- id: flake8
args: [--max-line-length=100]

201
LICENSE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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
(an example is provided in the Appendix below).
"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.
"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."
"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.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, 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.
3. Grant of Patent License. Subject to the terms and conditions of
this License, 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.
4. Redistribution. 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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.
5. Submission of Contributions. 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.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. 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.
8. Limitation of Liability. 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.
9. Accepting Warranty or Additional Liability. 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.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

194
README.md Normal file
View File

@@ -0,0 +1,194 @@
# NeuTTS Air
||VIDEO||
*Click the image above to watch NeuTTS Air in action on YouTube!*
*Created by [Neuphonic](http://neuphonic.com/) - building faster, smaller, on-device voice AI*
State-of-the-art Voice AI has been locked behind web APIs for too long. NeuTTS Air is the worlds first super-realistic, on-device, TTS speech language model with instant voice cloning. Built off a 0.5B LLM backbone, NeuTTS Air 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.
## Key Features
- 🗣Best-in-class realism for its size - produces natural, ultra-realistic voices that sound human
- 📱Optimised for on-device deployment - provided in GGML format, ready to run on phones, laptops, or even Raspberry Pis
- 👫Instant voice cloning - create your own speaker with as little as 3 seconds of audio
- 🚄Simple LM + codec architecture built off a 0.5B backbone - the sweet spot between speed, size, and quality for real-world applications
## Model Details
NeuTTS Air is built off Qwen 0.5B - a lightweight yet capable language model optimised for text understanding and generation - as well as a powerful combination of technologies designed for efficiency and quality:
- **Audio Codec**: [NeuCodec](https://huggingface.co/neuphonic/neucodec) - our proprietary neural audio codec that achieves exceptional audio quality at low bitrates using a single codebook
- **Format**: Available in GGML format for efficient on-device inference
- **Responsibility**: Watermarked outputs
- **Inference Speed**: Real-time generation on mid-range devices
- **Power Consumption**: Optimised for mobile and embedded devices
## Get Started
1. **Clone Git Repo**
```bash
git clone https://github.com/neuphonic/neutts-air.git
```
```bash
cd neuttsair
```
2. **Install `espeak` (required dependency)**
Please refer to the following link for instructions on how to install `espeak`:
https://github.com/espeak-ng/espeak-ng/blob/master/docs/guide.md
```bash
# Mac OS
brew install espeak
# Ubuntu/Debian
sudo apt install espeak
```
Mac users may need to put the following lines at the top of the neutts.py file.
```python
from phonemizer.backend.espeak.wrapper import EspeakWrapper
_ESPEAK_LIBRARY = '/opt/homebrew/Cellar/espeak/1.48.04_1/lib/libespeak.1.1.48.dylib' #use the Path to the library.
EspeakWrapper.set_library(_ESPEAK_LIBRARY)
```
3. **Install Python dependencies**
The requirements file includes the dependencies needed to run the model with PyTorch.
When using an ONNX decoder or a GGML model, some dependencies (such as PyTorch) are no longer required.
The inference is compatible and tested on `python>=3.11`.
```
pip install -r requirements.txt
```
4. **(Optional) Install Llama-cpp-python to use the `GGUF` models.**
```
pip install llama-cpp-python
```
To run llama-cpp with GPU suport (CUDA, MPS) support please refer to:
https://pypi.org/project/llama-cpp-python/
5. **(Optional) Install onnxruntime to use the `.onnx` decoder.**
If you wnat to run the onnxdecoder
```
pip install onnxruntime
```
## Basic Example
Run the basic example script to synthesize speech:
```bash
python -m examples.basic_example \
--input_text "My name is Dave, and um, I'm from London" \
--ref_audio samples/dave.wav \
--ref_text samples/dave.txt
```
To specify a particular model repo for the backbone or codec, add the `--backbone` argument. Available backbones are listed in [NeuTTS-Air huggingface collection](https://huggingface.co/collections/neuphonic/neutts-air-68cc14b7033b4c56197ef350).
Several examples are available, including a Jupyter notebook in the `examples` folder.
### Simple One-Code Block Usage
```python
from neuttsair.neutts import NeuTTSAir
import soundfile as sf
tts = NeuTTSAir( backbone_repo="neuphonic/neutts-air-q4-gguf", backbone_device="cpu", codec_repo="neuphonic/neucodec", codec_device="cpu")
input_text = "My name is Dave, and um, I'm from London."
ref_text = "samples/dave.txt"
ref_audio_path = "samples/dave.wav"
ref_text = open(ref_text, "r").read().strip()
ref_codes = tts.encode_reference(ref_audio_path)
wav = tts.infer(input_text, ref_codes, ref_text)
sf.write("test.wav", wav, 24000)
```
## Advanced Examples
### GGML Backbone Example
```bash
python -m examples.basic_example \
--input_text "My name is Dave, and um, I'm from London" \
--ref_audio ./samples/dave.wav \
--ref_text ./samples/dave.txt \
--backbone neuphonic/neutts-air-q4-gguf
```
### Onnx Decoder Example
Make sure you have installed ```onnxruntime```
```bash
python -m examples.onnx_example \
--input_text "My name is Dave, and um, I'm from London" \
--ref_codes samples/dave.pt \
--ref_text samples/dave.txt
```
To run the model with the onnx decoder you need to encode the reference sample. Please refer to the encode_reference example.
#### Encode reference
You only need to provide a reference audio for the reference encoding.
```bash
python -m examples.encode_reference \
--ref_audio ./samples/dave.wav \
--output_path encoded_reference.pt
```
## Prepare References for Cloning
NeuTTS Air requires two inputs:
1. A reference audio sample (`.wav` file)
2. A text string
The model then synthesises the text as speech in the style of the reference audio. This is what enables NeuTTS Airs instant voice cloning capability.
### Example Reference Files
You can find some ready-to-use samples in the `examples` folder:
- `samples/dave.wav`
- `samples/jo.wav`
### Guidelines for Best Results
For optimal performance, reference audio samples should be:
1. **Mono channel**
2. **16-44 kHz sample rate**
3. **315 seconds in length**
4. **Saved as a `.wav` file**
5. **Clean** — minimal to no background noise
6. **Natural, continuous speech** — like a monologue or conversation, with few pauses, so the model can capture tone effectively
## Responsibility
Every audio file generated by NeuTTS Air includes [Perth (Perceptual Threshold) Watermarker](https://github.com/resemble-ai/perth).
## Disclaimer
Don't use this model to do bad things… please.
## Developer Requirements
To run the pre commit hooks to contribute to this project run:
```bash
pip install pre-commit
```
Then:
```bash
pre-commit install
```

0
examples/__init__.py Normal file
View File

76
examples/basic_example.py Normal file
View File

@@ -0,0 +1,76 @@
import os
import soundfile as sf
from neuttsair.neutts import NeuTTSAir
def main(input_text, ref_audio_path, ref_text, backbone, output_path="output.wav"):
if not ref_audio_path or not ref_text:
print("No reference audio or text provided.")
return None
# Initialize NeuTTSAir with the desired model and codec
tts = NeuTTSAir(
backbone_repo=backbone,
backbone_device="cpu",
codec_repo="neuphonic/neucodec",
codec_device="cpu"
)
# Check if ref_text is a path if it is read it if not just return string
if ref_text and os.path.exists(ref_text):
with open(ref_text, "r") as f:
ref_text = f.read().strip()
print("Encoding reference audio")
ref_codes = tts.encode_reference(ref_audio_path)
print(f"Generating audio for input text: {input_text}")
wav = tts.infer(input_text, ref_codes, ref_text)
print(f"Saving output to {output_path}")
sf.write(output_path, wav, 24000)
if __name__ == "__main__":
# get arguments from command line
import argparse
parser = argparse.ArgumentParser(description="NeuTTSAir Example")
parser.add_argument(
"--input_text",
type=str,
required=True,
help="Input text to be converted to speech"
)
parser.add_argument(
"--ref_audio",
type=str,
default="./samples/dave.wav",
help="Path to reference audio file"
)
parser.add_argument(
"--ref_text",
type=str,
default="./samples/dave.txt",
help="Reference text corresponding to the reference audio",
)
parser.add_argument(
"--output_path",
type=str,
default="output.wav",
help="Path to save the output audio"
)
parser.add_argument(
"--backbone",
type=str,
default="neuphonic/neutts-air",
help="Huggingface repo containing the backbone checkpoint"
)
args = parser.parse_args()
main(
input_text=args.input_text,
ref_audio_path=args.ref_audio,
ref_text=args.ref_text,
backbone=args.backbone,
output_path=args.output_path,
)

View File

@@ -0,0 +1,47 @@
# This file contains an example of how to use the NeuTTSAir class to generate codes
import torch
from librosa import load
from neucodec import NeuCodec
def main(ref_audio_path, output_path="output.wav"):
print("Encoding reference audio")
# Make sure output path ends with .pt
if not output_path.endswith(".pt"):
print("Output path should end with .pt to save the codes.")
return
# Initialize codec
codec = NeuCodec.from_pretrained("neuphonic/neucodec")
codec.eval().to("cpu")
# Load and encode reference audio
wav, _ = load(ref_audio_path, sr=16000, mono=True) # load as 16kHz
wav_tensor = torch.from_numpy(wav).float().unsqueeze(0).unsqueeze(0) # [1, 1, T]
ref_codes = codec.encode_code(audio_or_path=wav_tensor).squeeze(0).squeeze(0)
# Save the codes
torch.save(ref_codes, output_path)
if __name__ == "__main__":
# get arguments from command line
import argparse
parser = argparse.ArgumentParser(description="NeuTTSAir Reference Encoding Example")
parser.add_argument(
"--ref_audio", type=str, default="./samples/dave.wav", help="Path to reference audio"
)
parser.add_argument(
"--output_path",
type=str,
default="encoded_reference.pt",
help="Path to save the output codes",
)
args = parser.parse_args()
main(
ref_audio_path=args.ref_audio,
output_path=args.output_path,
)

View File

@@ -0,0 +1,114 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "a0fa9718",
"metadata": {},
"source": [
"Import required libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "939f4fdc",
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"#Append the parent directory to the sys.path to allow imports from neuttsair package\n",
"sys.path.append('..')\n",
"from neuttsair.neutts import NeuTTSAir\n",
"from IPython.display import Audio"
]
},
{
"cell_type": "markdown",
"id": "e4e61937",
"metadata": {},
"source": [
"Downloads files and loads the model into memory"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cfabf9dd",
"metadata": {},
"outputs": [],
"source": [
"%%capture\n",
"tts = NeuTTSAir(\n",
" backbone_repo=\"neuphonic/neutts-air-q8-gguf\",\n",
" backbone_device=\"cpu\",\n",
" codec_repo=\"neuphonic/neucodec\",\n",
" codec_device=\"cpu\"\n",
")"
]
},
{
"cell_type": "markdown",
"id": "75c87818",
"metadata": {},
"source": [
"Pick your speaker and type up your input text - and generate!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "914e5e00",
"metadata": {},
"outputs": [],
"source": [
"speaker = \"dave\" # default speakers are 'dave' and 'jo'\n",
"input_text = \"Hey there, I'm 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.\"\n",
"\n",
"ref_text = f\"../samples/{speaker}.txt\"\n",
"ref_audio_path = f\"../samples/{speaker}.wav\"\n",
"\n",
"ref_text = open(ref_text, \"r\").read().strip()\n",
"ref_codes = tts.encode_reference(ref_audio_path)\n",
"wav = tts.infer(input_text, ref_codes, ref_text)"
]
},
{
"cell_type": "markdown",
"id": "e8da4a9d",
"metadata": {},
"source": [
"Listen to your generation!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "21774af1",
"metadata": {},
"outputs": [],
"source": [
"Audio(wav, rate=24000)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

77
examples/onnx_example.py Normal file
View File

@@ -0,0 +1,77 @@
import os
import soundfile as sf
import torch
from neuttsair.neutts import NeuTTSAir
def main(input_text, ref_codes_path, ref_text, backbone, output_path="output.wav"):
if not ref_codes_path or not ref_text:
print("No reference audio or text provided.")
return None
# Initialize NeuTTSAir with the desired model and codec
tts = NeuTTSAir(
backbone_repo=backbone,
backbone_device="cpu",
codec_repo="neuphonic/neucodec-onnx-decoder",
codec_device="cpu"
)
# Check if ref_text is a path if it is read it if not just return string
if ref_text and os.path.exists(ref_text):
with open(ref_text, "r") as f:
ref_text = f.read().strip()
if ref_codes_path and os.path.exists(ref_codes_path):
ref_codes = torch.load(ref_codes_path)
print(f"Generating audio for input text: {input_text}")
wav = tts.infer(input_text, ref_codes, ref_text)
print(f"Saving output to {output_path}")
sf.write(output_path, wav, 24000)
if __name__ == "__main__":
# get arguments from command line
import argparse
parser = argparse.ArgumentParser(description="NeuTTSAir Example")
parser.add_argument(
"--input_text",
type=str,
required=True,
help="Input text to be converted to speech"
)
parser.add_argument(
"--ref_codes",
type=str,
default="./samples/dave.pt",
help="Path to pre-encoded reference audio"
)
parser.add_argument(
"--ref_text",
type=str,
default="./samples/dave.txt",
help="Reference text corresponding to the reference audio",
)
parser.add_argument(
"--output_path",
type=str,
default="output.wav",
help="Path to save the output audio"
)
parser.add_argument(
"--backbone",
type=str,
default="neuphonic/neutts-air",
help="Huggingface repo containing the backbone checkpoint"
)
args = parser.parse_args()
main(
input_text=args.input_text,
ref_codes_path=args.ref_codes,
ref_text=args.ref_text,
backbone=args.backbone,
output_path=args.output_path,
)

0
neuttsair/__init__.py Normal file
View File

241
neuttsair/neutts.py Normal file
View File

@@ -0,0 +1,241 @@
from pathlib import Path
import librosa
import numpy as np
import torch
import re
import perth
from neucodec import NeuCodec, DistillNeuCodec
from phonemizer.backend import EspeakBackend
from transformers import AutoTokenizer, AutoModelForCausalLM
class NeuTTSAir:
def __init__(
self,
backbone_repo="neuphonic/neutts-air",
backbone_device="cpu",
codec_repo="neuphonic/neucodec",
codec_device="cpu",
):
# Consts
self.sample_rate = 24_000
self.max_context = 2048
# ggml & onnx flags
self._grammar = None # set with a ggml model
self._is_quantized_model = False
self._is_onnx_codec = False
# HF tokenizer
self.tokenizer = None
# Load phonemizer + models
print("Loading phonemizer...")
self.phonemizer = EspeakBackend(
language="en-us", preserve_punctuation=True, with_stress=True
)
self._load_backbone(backbone_repo, backbone_device)
self._load_codec(codec_repo, codec_device)
# Load watermarker
self.watermarker = perth.PerthImplicitWatermarker()
def _load_backbone(self, backbone_repo, backbone_device):
print(f"Loading backbone from: {backbone_repo} on {backbone_device} ...")
# GGUF loading
if backbone_repo.endswith("gguf"):
try:
from llama_cpp import Llama
except ImportError as e:
raise ImportError(
"Failed to import `llama_cpp`. "
"Please install it with:\n"
" pip install llama-cpp-python"
) from e
self.backbone = Llama.from_pretrained(
repo_id=backbone_repo,
filename="*.gguf",
verbose=False,
n_gpu_layers=-1 if backbone_device == "gpu" else 0,
n_ctx=self.max_context,
mlock=True,
flash_attn=True if backbone_device == "gpu" else False,
)
self._is_quantized_model = True
else:
self.tokenizer = AutoTokenizer.from_pretrained(backbone_repo)
self.backbone = AutoModelForCausalLM.from_pretrained(backbone_repo).to(
torch.device(backbone_device)
)
def _load_codec(self, codec_repo, codec_device):
print(f"Loading codec from: {codec_repo} on {codec_device} ...")
match codec_repo:
case "neuphonic/neucodec":
self.codec = NeuCodec.from_pretrained(codec_repo)
self.codec.eval().to(codec_device)
case "neuphonic/distill-neucodec":
self.codec = DistillNeuCodec.from_pretrained(codec_repo)
self.codec.eval().to(codec_device)
case "neuphonic/neucodec-onnx-decoder":
if codec_device != "cpu":
raise ValueError("Onnx decoder only currently runs on CPU.")
try:
from neucodec import NeuCodecOnnxDecoder
except ImportError as e:
raise ImportError(
"Failed to import the onnx decoder."
" Ensure you have onnxruntime installed as well as neucodec >= 0.0.4."
) from e
self.codec = NeuCodecOnnxDecoder.from_pretrained(codec_repo)
self._is_onnx_codec = True
case _:
raise ValueError(
"Invalid codec repo! Must be one of:"
" 'neuphonic/neucodec', 'neuphonic/distill-neucodec',"
" 'neuphonic/neucodec-onnx-decoder'."
)
def infer(self, text: str, ref_codes: np.ndarray | torch.Tensor, ref_text: str) -> np.ndarray:
"""
Perform inference to generate speech from text using the TTS model and reference audio.
Args:
text (str): Input text to be converted to speech.
ref_codes (np.ndarray | torch.tensor): Encoded reference.
ref_text (str): Reference text for reference audio. Defaults to None.
Returns:
np.ndarray: Generated speech waveform.
"""
# Generate tokens
if self._is_quantized_model:
output_str = self._infer_ggml(ref_codes, ref_text, text)
else:
prompt_ids = self._apply_chat_template(ref_codes, ref_text, text)
output_str = self._infer_torch(prompt_ids)
# Decode
wav = self._decode(output_str)
watermarked_wav = self.watermarker.apply_watermark(wav, sample_rate=24_000)
return watermarked_wav
def encode_reference(self, ref_audio_path: str | Path):
wav, _ = librosa.load(ref_audio_path, sr=16000, mono=True)
wav_tensor = torch.from_numpy(wav).float().unsqueeze(0).unsqueeze(0) # [1, 1, T]
ref_codes = self.codec.encode_code(audio_or_path=wav_tensor).squeeze(0).squeeze(0)
return ref_codes
def _decode(self, codes: str):
# Extract speech token IDs using regex
speech_ids = [int(num) for num in re.findall(r"<\|speech_(\d+)\|>", codes)]
if len(speech_ids) > 0:
# Onnx decode
if self._is_onnx_codec:
codes = np.array(speech_ids, dtype=np.int32)[np.newaxis, np.newaxis, :]
recon = self.codec.decode_code(codes)
# Torch decode
else:
with torch.no_grad():
codes = torch.tensor(speech_ids, dtype=torch.long)[None, None, :].to(
self.codec.device
)
recon = self.codec.decode_code(codes).cpu().numpy()
return recon[0, 0, :]
else:
raise ValueError("No valid speech tokens found in the output.")
def _to_phones(self, text: str) -> str:
phones = self.phonemizer.phonemize([text])
phones = phones[0].split()
phones = " ".join(phones)
return phones
def _apply_chat_template(
self, ref_codes: list[int], ref_text: str, input_text: str
) -> list[int]:
input_text = self._to_phones(ref_text) + " " + self._to_phones(input_text)
speech_replace = self.tokenizer.convert_tokens_to_ids("<|SPEECH_REPLACE|>")
speech_gen_start = self.tokenizer.convert_tokens_to_ids("<|SPEECH_GENERATION_START|>")
text_replace = self.tokenizer.convert_tokens_to_ids("<|TEXT_REPLACE|>")
text_prompt_start = self.tokenizer.convert_tokens_to_ids("<|TEXT_PROMPT_START|>")
text_prompt_end = self.tokenizer.convert_tokens_to_ids("<|TEXT_PROMPT_END|>")
input_ids = self.tokenizer.encode(input_text, add_special_tokens=False)
chat = """user: Convert the text to speech:<|TEXT_REPLACE|>\nassistant:<|SPEECH_REPLACE|>"""
ids = self.tokenizer.encode(chat)
text_replace_idx = ids.index(text_replace)
ids = (
ids[:text_replace_idx]
+ [text_prompt_start]
+ input_ids
+ [text_prompt_end]
+ ids[text_replace_idx + 1 :] # noqa
)
speech_replace_idx = ids.index(speech_replace)
codes_str = "".join([f"<|speech_{i}|>" for i in ref_codes])
codes = self.tokenizer.encode(codes_str, add_special_tokens=False)
ids = ids[:speech_replace_idx] + [speech_gen_start] + list(codes)
return ids
def _infer_torch(self, prompt_ids: list[int]) -> str:
prompt_tensor = torch.tensor(prompt_ids).unsqueeze(0).to(self.backbone.device)
speech_end_id = self.tokenizer.convert_tokens_to_ids("<|SPEECH_GENERATION_END|>")
with torch.no_grad():
output_tokens = self.backbone.generate(
prompt_tensor,
max_length=self.max_context,
eos_token_id=speech_end_id,
do_sample=True,
temperature=1.0,
top_k=50,
use_cache=True,
min_new_tokens=50,
)
input_length = prompt_tensor.shape[-1]
output_str = self.tokenizer.decode(
output_tokens[0, input_length:].cpu().numpy().tolist(), add_special_tokens=False
)
return output_str
def _infer_ggml(self, ref_codes: list[int], ref_text: str, input_text: str) -> str:
ref_text = self._to_phones(ref_text)
input_text = self._to_phones(input_text)
codes_str = "".join([f"<|speech_{idx}|>" for idx in ref_codes])
prompt = (
f"user: Convert the text to speech:<|TEXT_PROMPT_START|>{ref_text} {input_text}"
f"<|TEXT_PROMPT_END|>\nassistant:<|SPEECH_GENERATION_START|>{codes_str}"
)
output = self.backbone(
prompt,
max_tokens=self.max_context,
temperature=1.0,
top_k=50,
stop=["<|SPEECH_GENERATION_END|>"],
)
output_str = output["choices"][0]["text"]
return output_str

18
requirements.txt Normal file
View File

@@ -0,0 +1,18 @@
datasets==4.0.0
librosa==0.11.0
neucodec>=0.0.3
numpy==2.2.6
pandas==2.3.2
phonemizer==3.3.0
requests==2.32.5
scipy>=1.15
soundfile==0.13.1
torch==2.8.0
torchao==0.13.0
torchaudio==2.8.0
torchtune==0.6.1
tqdm==4.67.1
transformers==4.56.1
vector-quantize-pytorch==1.17.8
resemble-perth==1.0.1
accelerate==1.10.1

BIN
samples/dave.pt Normal file

Binary file not shown.

1
samples/dave.txt Normal file
View File

@@ -0,0 +1 @@
So I'm live on radio. And I say, well, my dear friend James here clearly, and the whole room just froze. Turns out I'd completely misspoken and mentioned our other friend.

BIN
samples/dave.wav Normal file

Binary file not shown.

BIN
samples/jo.pt Normal file

Binary file not shown.

1
samples/jo.txt Normal file
View File

@@ -0,0 +1 @@
So I just tried Neuphonic and Im genuinely impressed. It's super responsive, it sounds clean, supports voice cloning, and the agent feature is fun to play with too. Highly recommend it for podcasts, conversations, or even just messing around with voiceovers.

BIN
samples/jo.wav Normal file

Binary file not shown.