Spaces:
Runtime error
Runtime error
fcyai
commited on
Commit
•
408ebe4
1
Parent(s):
f089553
init
Browse files- ChatTTS/.gitattributes +2 -0
- ChatTTS/.github/workflows/checksum.yml +45 -0
- {abc → ChatTTS}/.gitignore +8 -0
- ChatTTS/ChatTTS/__init__.py +1 -0
- ChatTTS/ChatTTS/core.py +314 -0
- ChatTTS/ChatTTS/experimental/llm.py +40 -0
- ChatTTS/ChatTTS/infer/api.py +128 -0
- ChatTTS/ChatTTS/model/dvae.py +155 -0
- ChatTTS/ChatTTS/model/gpt.py +301 -0
- ChatTTS/ChatTTS/res/homophones_map.json +0 -0
- ChatTTS/ChatTTS/utils/download.py +191 -0
- ChatTTS/ChatTTS/utils/gpu_utils.py +27 -0
- ChatTTS/ChatTTS/utils/infer_utils.py +179 -0
- ChatTTS/ChatTTS/utils/io_utils.py +14 -0
- ChatTTS/LICENSE +407 -0
- {abc → ChatTTS}/README.md +115 -42
- ChatTTS/docs/cn/README.md +228 -0
- ChatTTS/docs/jp/README.md +132 -0
- ChatTTS/docs/ru/README.md +134 -0
- ChatTTS/examples/cmd/run.py +51 -0
- ChatTTS/examples/ipynb/colab.ipynb +759 -0
- ChatTTS/examples/ipynb/example.ipynb +247 -0
- ChatTTS/examples/web/webui.py +155 -0
- {abc → ChatTTS}/requirements.txt +8 -1
- ChatTTS/setup.py +16 -0
- ChatTTS/sha256.env +12 -0
- ChatTTS/tools/checksum/main.go +38 -0
- ChatTTS/tools/checksum/tmpl.go +30 -0
- README.md +121 -15
- abc/LICENSE +0 -157
- abc/README_CN.md +0 -133
- abc/infer.ipynb +0 -0
- requirements.txt +1 -11
ChatTTS/.gitattributes
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
# ignore jupyter notebooks in the language bar on github
|
2 |
+
**/*.ipynb linguist-vendored
|
ChatTTS/.github/workflows/checksum.yml
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Calculate and Sync SHA256
|
2 |
+
on:
|
3 |
+
push:
|
4 |
+
branches:
|
5 |
+
- main
|
6 |
+
- dev
|
7 |
+
jobs:
|
8 |
+
checksum:
|
9 |
+
runs-on: ubuntu-latest
|
10 |
+
steps:
|
11 |
+
- uses: actions/checkout@master
|
12 |
+
|
13 |
+
- name: Setup Go Environment
|
14 |
+
uses: actions/setup-go@master
|
15 |
+
|
16 |
+
- name: Run RVC-Models-Downloader
|
17 |
+
run: |
|
18 |
+
wget https://github.com/fumiama/RVC-Models-Downloader/releases/download/v0.2.5/rvcmd_linux_amd64.deb
|
19 |
+
sudo apt -y install ./rvcmd_linux_amd64.deb
|
20 |
+
rm -f ./rvcmd_linux_amd64.deb
|
21 |
+
rvcmd -notrs -w 1 -notui assets/chtts
|
22 |
+
|
23 |
+
- name: Calculate all Checksums
|
24 |
+
run: go run tools/checksum/*.go
|
25 |
+
|
26 |
+
- name: Commit back
|
27 |
+
if: ${{ !github.head_ref }}
|
28 |
+
id: commitback
|
29 |
+
continue-on-error: true
|
30 |
+
run: |
|
31 |
+
git config --local user.name 'github-actions[bot]'
|
32 |
+
git config --local user.email 'github-actions[bot]@users.noreply.github.com'
|
33 |
+
git add --all
|
34 |
+
git commit -m "chore(env): sync checksum on ${{github.ref_name}}"
|
35 |
+
|
36 |
+
- name: Create Pull Request
|
37 |
+
if: steps.commitback.outcome == 'success'
|
38 |
+
continue-on-error: true
|
39 |
+
uses: peter-evans/create-pull-request@v5
|
40 |
+
with:
|
41 |
+
delete-branch: true
|
42 |
+
body: "Automatically sync checksum in .env"
|
43 |
+
title: "chore(env): sync checksum on ${{github.ref_name}}"
|
44 |
+
commit-message: "chore(env): sync checksum on ${{github.ref_name}}"
|
45 |
+
branch: checksum-${{github.ref_name}}
|
{abc → ChatTTS}/.gitignore
RENAMED
@@ -161,3 +161,11 @@ cython_debug/
|
|
161 |
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
162 |
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
163 |
#.idea/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
161 |
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
162 |
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
163 |
#.idea/
|
164 |
+
|
165 |
+
# assets and configs of ChatTTS
|
166 |
+
|
167 |
+
/asset
|
168 |
+
/config
|
169 |
+
|
170 |
+
# inferred result
|
171 |
+
*.wav
|
ChatTTS/ChatTTS/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .core import Chat
|
ChatTTS/ChatTTS/core.py
ADDED
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import os
|
3 |
+
import json
|
4 |
+
import logging
|
5 |
+
from functools import partial
|
6 |
+
from typing import Literal
|
7 |
+
import tempfile
|
8 |
+
|
9 |
+
import torch
|
10 |
+
from omegaconf import OmegaConf
|
11 |
+
from vocos import Vocos
|
12 |
+
from huggingface_hub import snapshot_download
|
13 |
+
|
14 |
+
from .model.dvae import DVAE
|
15 |
+
from .model.gpt import GPT_warpper
|
16 |
+
from .utils.gpu_utils import select_device
|
17 |
+
from .utils.infer_utils import count_invalid_characters, detect_language, apply_character_map, apply_half2full_map, HomophonesReplacer
|
18 |
+
from .utils.io_utils import get_latest_modified_file
|
19 |
+
from .infer.api import refine_text, infer_code
|
20 |
+
from .utils.download import check_all_assets, download_all_assets
|
21 |
+
|
22 |
+
logging.basicConfig(level = logging.INFO)
|
23 |
+
|
24 |
+
|
25 |
+
class Chat:
|
26 |
+
def __init__(self, ):
|
27 |
+
self.pretrain_models = {}
|
28 |
+
self.normalizer = {}
|
29 |
+
self.homophones_replacer = None
|
30 |
+
self.logger = logging.getLogger(__name__)
|
31 |
+
|
32 |
+
def check_model(self, level = logging.INFO, use_decoder = False):
|
33 |
+
not_finish = False
|
34 |
+
check_list = ['vocos', 'gpt', 'tokenizer']
|
35 |
+
|
36 |
+
if use_decoder:
|
37 |
+
check_list.append('decoder')
|
38 |
+
else:
|
39 |
+
check_list.append('dvae')
|
40 |
+
|
41 |
+
for module in check_list:
|
42 |
+
if module not in self.pretrain_models:
|
43 |
+
self.logger.log(logging.WARNING, f'{module} not initialized.')
|
44 |
+
not_finish = True
|
45 |
+
|
46 |
+
if not not_finish:
|
47 |
+
self.logger.log(level, f'All initialized.')
|
48 |
+
|
49 |
+
return not not_finish
|
50 |
+
|
51 |
+
def load_models(
|
52 |
+
self,
|
53 |
+
source: Literal['huggingface', 'local', 'custom']='local',
|
54 |
+
force_redownload=False,
|
55 |
+
custom_path='<LOCAL_PATH>',
|
56 |
+
**kwargs,
|
57 |
+
):
|
58 |
+
if source == 'local':
|
59 |
+
download_path = os.getcwd()
|
60 |
+
if not check_all_assets(update=True):
|
61 |
+
with tempfile.TemporaryDirectory() as tmp:
|
62 |
+
download_all_assets(tmpdir=tmp)
|
63 |
+
if not check_all_assets(update=False):
|
64 |
+
logging.error("counld not satisfy all assets needed.")
|
65 |
+
exit(1)
|
66 |
+
elif source == 'huggingface':
|
67 |
+
hf_home = os.getenv('HF_HOME', os.path.expanduser("~/.cache/huggingface"))
|
68 |
+
try:
|
69 |
+
download_path = get_latest_modified_file(os.path.join(hf_home, 'hub/models--2Noise--ChatTTS/snapshots'))
|
70 |
+
except:
|
71 |
+
download_path = None
|
72 |
+
if download_path is None or force_redownload:
|
73 |
+
self.logger.log(logging.INFO, f'Download from HF: https://huggingface.co/2Noise/ChatTTS')
|
74 |
+
download_path = snapshot_download(repo_id="2Noise/ChatTTS", allow_patterns=["*.pt", "*.yaml"])
|
75 |
+
else:
|
76 |
+
self.logger.log(logging.INFO, f'Load from cache: {download_path}')
|
77 |
+
elif source == 'custom':
|
78 |
+
self.logger.log(logging.INFO, f'Load from local: {custom_path}')
|
79 |
+
download_path = custom_path
|
80 |
+
|
81 |
+
self._load(**{k: os.path.join(download_path, v) for k, v in OmegaConf.load(os.path.join(download_path, 'config', 'path.yaml')).items()}, **kwargs)
|
82 |
+
|
83 |
+
def _load(
|
84 |
+
self,
|
85 |
+
vocos_config_path: str = None,
|
86 |
+
vocos_ckpt_path: str = None,
|
87 |
+
dvae_config_path: str = None,
|
88 |
+
dvae_ckpt_path: str = None,
|
89 |
+
gpt_config_path: str = None,
|
90 |
+
gpt_ckpt_path: str = None,
|
91 |
+
decoder_config_path: str = None,
|
92 |
+
decoder_ckpt_path: str = None,
|
93 |
+
tokenizer_path: str = None,
|
94 |
+
device: str = None,
|
95 |
+
compile: bool = True,
|
96 |
+
):
|
97 |
+
if not device:
|
98 |
+
device = select_device(4096)
|
99 |
+
self.logger.log(logging.INFO, f'use {device}')
|
100 |
+
|
101 |
+
if vocos_config_path:
|
102 |
+
vocos = Vocos.from_hparams(vocos_config_path).to(
|
103 |
+
# vocos on mps will crash, use cpu fallback
|
104 |
+
"cpu" if torch.backends.mps.is_available() else device
|
105 |
+
).eval()
|
106 |
+
assert vocos_ckpt_path, 'vocos_ckpt_path should not be None'
|
107 |
+
vocos.load_state_dict(torch.load(vocos_ckpt_path))
|
108 |
+
self.pretrain_models['vocos'] = vocos
|
109 |
+
self.logger.log(logging.INFO, 'vocos loaded.')
|
110 |
+
|
111 |
+
if dvae_config_path:
|
112 |
+
cfg = OmegaConf.load(dvae_config_path)
|
113 |
+
dvae = DVAE(**cfg).to(device).eval()
|
114 |
+
assert dvae_ckpt_path, 'dvae_ckpt_path should not be None'
|
115 |
+
dvae.load_state_dict(torch.load(dvae_ckpt_path))
|
116 |
+
self.pretrain_models['dvae'] = dvae
|
117 |
+
self.logger.log(logging.INFO, 'dvae loaded.')
|
118 |
+
|
119 |
+
if gpt_config_path:
|
120 |
+
cfg = OmegaConf.load(gpt_config_path)
|
121 |
+
gpt = GPT_warpper(**cfg).to(device).eval()
|
122 |
+
assert gpt_ckpt_path, 'gpt_ckpt_path should not be None'
|
123 |
+
gpt.load_state_dict(torch.load(gpt_ckpt_path))
|
124 |
+
if compile and 'cuda' in str(device):
|
125 |
+
try:
|
126 |
+
gpt.gpt.forward = torch.compile(gpt.gpt.forward, backend='inductor', dynamic=True)
|
127 |
+
except RuntimeError as e:
|
128 |
+
logging.warning(f'Compile failed,{e}. fallback to normal mode.')
|
129 |
+
self.pretrain_models['gpt'] = gpt
|
130 |
+
spk_stat_path = os.path.join(os.path.dirname(gpt_ckpt_path), 'spk_stat.pt')
|
131 |
+
assert os.path.exists(spk_stat_path), f'Missing spk_stat.pt: {spk_stat_path}'
|
132 |
+
self.pretrain_models['spk_stat'] = torch.load(spk_stat_path).to(device)
|
133 |
+
self.logger.log(logging.INFO, 'gpt loaded.')
|
134 |
+
|
135 |
+
if decoder_config_path:
|
136 |
+
cfg = OmegaConf.load(decoder_config_path)
|
137 |
+
decoder = DVAE(**cfg).to(device).eval()
|
138 |
+
assert decoder_ckpt_path, 'decoder_ckpt_path should not be None'
|
139 |
+
decoder.load_state_dict(torch.load(decoder_ckpt_path, map_location='cpu'))
|
140 |
+
self.pretrain_models['decoder'] = decoder
|
141 |
+
self.logger.log(logging.INFO, 'decoder loaded.')
|
142 |
+
|
143 |
+
if tokenizer_path:
|
144 |
+
tokenizer = torch.load(tokenizer_path, map_location='cpu')
|
145 |
+
tokenizer.padding_side = 'left'
|
146 |
+
self.pretrain_models['tokenizer'] = tokenizer
|
147 |
+
self.logger.log(logging.INFO, 'tokenizer loaded.')
|
148 |
+
|
149 |
+
self.check_model()
|
150 |
+
|
151 |
+
def _infer(
|
152 |
+
self,
|
153 |
+
text,
|
154 |
+
skip_refine_text=False,
|
155 |
+
refine_text_only=False,
|
156 |
+
params_refine_text={},
|
157 |
+
params_infer_code={'prompt':'[speed_5]'},
|
158 |
+
use_decoder=True,
|
159 |
+
do_text_normalization=True,
|
160 |
+
lang=None,
|
161 |
+
stream=False,
|
162 |
+
do_homophone_replacement=True
|
163 |
+
):
|
164 |
+
|
165 |
+
assert self.check_model(use_decoder=use_decoder)
|
166 |
+
|
167 |
+
if not isinstance(text, list):
|
168 |
+
text = [text]
|
169 |
+
if do_text_normalization:
|
170 |
+
for i, t in enumerate(text):
|
171 |
+
_lang = detect_language(t) if lang is None else lang
|
172 |
+
if self.init_normalizer(_lang):
|
173 |
+
text[i] = self.normalizer[_lang](t)
|
174 |
+
if _lang == 'zh':
|
175 |
+
text[i] = apply_half2full_map(text[i])
|
176 |
+
for i, t in enumerate(text):
|
177 |
+
invalid_characters = count_invalid_characters(t)
|
178 |
+
if len(invalid_characters):
|
179 |
+
self.logger.log(logging.WARNING, f'Invalid characters found! : {invalid_characters}')
|
180 |
+
text[i] = apply_character_map(t)
|
181 |
+
if do_homophone_replacement and self.init_homophones_replacer():
|
182 |
+
text[i] = self.homophones_replacer.replace(t)
|
183 |
+
if t != text[i]:
|
184 |
+
self.logger.log(logging.INFO, f'Homophones replace: {t} -> {text[i]}')
|
185 |
+
|
186 |
+
if not skip_refine_text:
|
187 |
+
text_tokens = refine_text(
|
188 |
+
self.pretrain_models,
|
189 |
+
text,
|
190 |
+
**params_refine_text,
|
191 |
+
)['ids']
|
192 |
+
text_tokens = [i[i < self.pretrain_models['tokenizer'].convert_tokens_to_ids('[break_0]')] for i in text_tokens]
|
193 |
+
text = self.pretrain_models['tokenizer'].batch_decode(text_tokens)
|
194 |
+
if refine_text_only:
|
195 |
+
yield text
|
196 |
+
return
|
197 |
+
|
198 |
+
text = [params_infer_code.get('prompt', '') + i for i in text]
|
199 |
+
params_infer_code.pop('prompt', '')
|
200 |
+
result_gen = infer_code(self.pretrain_models, text, **params_infer_code, return_hidden=use_decoder, stream=stream)
|
201 |
+
if use_decoder:
|
202 |
+
field = 'hiddens'
|
203 |
+
docoder_name = 'decoder'
|
204 |
+
else:
|
205 |
+
field = 'ids'
|
206 |
+
docoder_name = 'dvae'
|
207 |
+
vocos_decode = lambda spec: [self.pretrain_models['vocos'].decode(
|
208 |
+
i.cpu() if torch.backends.mps.is_available() else i
|
209 |
+
).cpu().numpy() for i in spec]
|
210 |
+
if stream:
|
211 |
+
|
212 |
+
length = 0
|
213 |
+
for result in result_gen:
|
214 |
+
chunk_data = result[field][0]
|
215 |
+
assert len(result[field]) == 1
|
216 |
+
start_seek = length
|
217 |
+
length = len(chunk_data)
|
218 |
+
self.logger.debug(f'{start_seek=} total len: {length}, new len: {length - start_seek = }')
|
219 |
+
chunk_data = chunk_data[start_seek:]
|
220 |
+
if not len(chunk_data):
|
221 |
+
continue
|
222 |
+
self.logger.debug(f'new hidden {len(chunk_data)=}')
|
223 |
+
mel_spec = [self.pretrain_models[docoder_name](i[None].permute(0,2,1)) for i in [chunk_data]]
|
224 |
+
wav = vocos_decode(mel_spec)
|
225 |
+
self.logger.debug(f'yield wav chunk {len(wav[0])=} {len(wav[0][0])=}')
|
226 |
+
yield wav
|
227 |
+
return
|
228 |
+
mel_spec = [self.pretrain_models[docoder_name](i[None].permute(0,2,1)) for i in next(result_gen)[field]]
|
229 |
+
yield vocos_decode(mel_spec)
|
230 |
+
|
231 |
+
def infer(
|
232 |
+
self,
|
233 |
+
text,
|
234 |
+
skip_refine_text=False,
|
235 |
+
refine_text_only=False,
|
236 |
+
params_refine_text={},
|
237 |
+
params_infer_code={'prompt':'[speed_5]'},
|
238 |
+
use_decoder=True,
|
239 |
+
do_text_normalization=True,
|
240 |
+
lang=None,
|
241 |
+
stream=False,
|
242 |
+
do_homophone_replacement=True,
|
243 |
+
):
|
244 |
+
res_gen = self._infer(
|
245 |
+
text,
|
246 |
+
skip_refine_text,
|
247 |
+
refine_text_only,
|
248 |
+
params_refine_text,
|
249 |
+
params_infer_code,
|
250 |
+
use_decoder,
|
251 |
+
do_text_normalization,
|
252 |
+
lang,
|
253 |
+
stream,
|
254 |
+
do_homophone_replacement,
|
255 |
+
)
|
256 |
+
if stream:
|
257 |
+
return res_gen
|
258 |
+
else:
|
259 |
+
return next(res_gen)
|
260 |
+
|
261 |
+
def sample_random_speaker(self, ):
|
262 |
+
|
263 |
+
dim = self.pretrain_models['gpt'].gpt.layers[0].mlp.gate_proj.in_features
|
264 |
+
std, mean = self.pretrain_models['spk_stat'].chunk(2)
|
265 |
+
return torch.randn(dim, device=std.device) * std + mean
|
266 |
+
|
267 |
+
def init_normalizer(self, lang) -> bool:
|
268 |
+
|
269 |
+
if lang in self.normalizer:
|
270 |
+
return True
|
271 |
+
|
272 |
+
if lang == 'zh':
|
273 |
+
try:
|
274 |
+
from tn.chinese.normalizer import Normalizer
|
275 |
+
self.normalizer[lang] = Normalizer().normalize
|
276 |
+
return True
|
277 |
+
except:
|
278 |
+
self.logger.log(
|
279 |
+
logging.WARNING,
|
280 |
+
'Package WeTextProcessing not found!',
|
281 |
+
)
|
282 |
+
self.logger.log(
|
283 |
+
logging.WARNING,
|
284 |
+
'Run: conda install -c conda-forge pynini=2.1.5 && pip install WeTextProcessing',
|
285 |
+
)
|
286 |
+
else:
|
287 |
+
try:
|
288 |
+
from nemo_text_processing.text_normalization.normalize import Normalizer
|
289 |
+
self.normalizer[lang] = partial(Normalizer(input_case='cased', lang=lang).normalize, verbose=False, punct_post_process=True)
|
290 |
+
return True
|
291 |
+
except:
|
292 |
+
self.logger.log(
|
293 |
+
logging.WARNING,
|
294 |
+
'Package nemo_text_processing not found!',
|
295 |
+
)
|
296 |
+
self.logger.log(
|
297 |
+
logging.WARNING,
|
298 |
+
'Run: conda install -c conda-forge pynini=2.1.5 && pip install nemo_text_processing',
|
299 |
+
)
|
300 |
+
return False
|
301 |
+
|
302 |
+
def init_homophones_replacer(self):
|
303 |
+
if self.homophones_replacer:
|
304 |
+
return True
|
305 |
+
else:
|
306 |
+
try:
|
307 |
+
self.homophones_replacer = HomophonesReplacer(os.path.join(os.path.dirname(__file__), 'res', 'homophones_map.json'))
|
308 |
+
self.logger.log(logging.INFO, 'homophones_replacer loaded.')
|
309 |
+
return True
|
310 |
+
except (IOError, json.JSONDecodeError) as e:
|
311 |
+
self.logger.log(logging.WARNING, f'Error loading homophones map: {e}')
|
312 |
+
except Exception as e:
|
313 |
+
self.logger.log(logging.WARNING, f'Error loading homophones_replacer: {e}')
|
314 |
+
return False
|
ChatTTS/ChatTTS/experimental/llm.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from openai import OpenAI
|
3 |
+
|
4 |
+
prompt_dict = {
|
5 |
+
'kimi': [ {"role": "system", "content": "你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。"},
|
6 |
+
{"role": "user", "content": "你好,请注意你现在生成的文字要按照人日常生活的口吻,你的回复将会后续用TTS模型转为语音,并且请把回答控制在100字以内。并且标点符号仅包含逗号和句号,将数字等转为文字回答。"},
|
7 |
+
{"role": "assistant", "content": "好的,我现在生成的文字将按照人日常生活的口吻, 并且我会把回答控制在一百字以内, 标点符号仅包含逗号和句号,将阿拉伯数字等转为中文文字回答。下面请开始对话。"},],
|
8 |
+
'deepseek': [
|
9 |
+
{"role": "system", "content": "You are a helpful assistant"},
|
10 |
+
{"role": "user", "content": "你好,请注意你现在生成的文字要按照人日常生活的口吻,你的回复将会后续用TTS模型转为语音,并且请把回答控制在100字以内。并且标点符号仅包含逗号和句号,将数字等转为文字回答。"},
|
11 |
+
{"role": "assistant", "content": "好的,我现在生成的文字将按照人日常生活的口吻, 并且我会把回答控制在一百字以内, 标点符号仅包含逗号和句号,将阿拉伯数字等转为中文文字回答。下面请开始对话。"},],
|
12 |
+
'deepseek_TN': [
|
13 |
+
{"role": "system", "content": "You are a helpful assistant"},
|
14 |
+
{"role": "user", "content": "你好,现在我们在处理TTS的文本输入,下面将会给你输入一段文本,请你将其中的阿拉伯数字等等转为文字表达,并且输出的文本里仅包含逗号和句号这两个标点符号"},
|
15 |
+
{"role": "assistant", "content": "好的,我现在对TTS的文本输入进行处理。这一般叫做text normalization。下面请输入"},
|
16 |
+
{"role": "user", "content": "We paid $123 for this desk."},
|
17 |
+
{"role": "assistant", "content": "We paid one hundred and twenty three dollars for this desk."},
|
18 |
+
{"role": "user", "content": "详询请拨打010-724654"},
|
19 |
+
{"role": "assistant", "content": "详询请拨打零幺零,七二四六五四"},
|
20 |
+
{"role": "user", "content": "罗森宣布将于7月24日退市,在华门店超6000家!"},
|
21 |
+
{"role": "assistant", "content": "罗森宣布将于七月二十四日退市,在华门店超过六千家。"},
|
22 |
+
],
|
23 |
+
}
|
24 |
+
|
25 |
+
class llm_api:
|
26 |
+
def __init__(self, api_key, base_url, model):
|
27 |
+
self.client = OpenAI(
|
28 |
+
api_key = api_key,
|
29 |
+
base_url = base_url,
|
30 |
+
)
|
31 |
+
self.model = model
|
32 |
+
def call(self, user_question, temperature = 0.3, prompt_version='kimi', **kwargs):
|
33 |
+
|
34 |
+
completion = self.client.chat.completions.create(
|
35 |
+
model = self.model,
|
36 |
+
messages = prompt_dict[prompt_version]+[{"role": "user", "content": user_question},],
|
37 |
+
temperature = temperature,
|
38 |
+
**kwargs
|
39 |
+
)
|
40 |
+
return completion.choices[0].message.content
|
ChatTTS/ChatTTS/infer/api.py
ADDED
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import torch
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from transformers.generation import TopKLogitsWarper, TopPLogitsWarper
|
5 |
+
from ..utils.infer_utils import CustomRepetitionPenaltyLogitsProcessorRepeat
|
6 |
+
|
7 |
+
def infer_code(
|
8 |
+
models,
|
9 |
+
text,
|
10 |
+
spk_emb = None,
|
11 |
+
top_P = 0.7,
|
12 |
+
top_K = 20,
|
13 |
+
temperature = 0.3,
|
14 |
+
repetition_penalty = 1.05,
|
15 |
+
max_new_token = 2048,
|
16 |
+
stream=False,
|
17 |
+
**kwargs
|
18 |
+
):
|
19 |
+
|
20 |
+
device = next(models['gpt'].parameters()).device
|
21 |
+
|
22 |
+
if not isinstance(text, list):
|
23 |
+
text = [text]
|
24 |
+
|
25 |
+
if not isinstance(temperature, list):
|
26 |
+
temperature = [temperature] * models['gpt'].num_vq
|
27 |
+
|
28 |
+
if spk_emb is not None:
|
29 |
+
text = [f'[Stts][spk_emb]{i}[Ptts]' for i in text]
|
30 |
+
else:
|
31 |
+
text = [f'[Stts][empty_spk]{i}[Ptts]' for i in text]
|
32 |
+
|
33 |
+
text_token = models['tokenizer'](text, return_tensors='pt', add_special_tokens=False, padding=True).to(device)
|
34 |
+
input_ids = text_token['input_ids'][...,None].expand(-1, -1, models['gpt'].num_vq)
|
35 |
+
text_mask = torch.ones(text_token['input_ids'].shape, dtype=bool, device=device)
|
36 |
+
|
37 |
+
inputs = {
|
38 |
+
'input_ids': input_ids,
|
39 |
+
'text_mask': text_mask,
|
40 |
+
'attention_mask': text_token['attention_mask'],
|
41 |
+
}
|
42 |
+
|
43 |
+
emb = models['gpt'].get_emb(**inputs)
|
44 |
+
if spk_emb is not None:
|
45 |
+
emb[inputs['input_ids'][..., 0] == models['tokenizer'].convert_tokens_to_ids('[spk_emb]')] = \
|
46 |
+
F.normalize(spk_emb.to(device).to(emb.dtype)[None].expand(len(text), -1), p=2.0, dim=1, eps=1e-12)
|
47 |
+
|
48 |
+
num_code = models['gpt'].emb_code[0].num_embeddings - 1
|
49 |
+
|
50 |
+
LogitsWarpers = []
|
51 |
+
if top_P is not None:
|
52 |
+
LogitsWarpers.append(TopPLogitsWarper(top_P, min_tokens_to_keep=3))
|
53 |
+
if top_K is not None:
|
54 |
+
LogitsWarpers.append(TopKLogitsWarper(top_K, min_tokens_to_keep=3))
|
55 |
+
|
56 |
+
LogitsProcessors = []
|
57 |
+
if repetition_penalty is not None and repetition_penalty != 1:
|
58 |
+
LogitsProcessors.append(CustomRepetitionPenaltyLogitsProcessorRepeat(\
|
59 |
+
repetition_penalty, num_code, 16))
|
60 |
+
|
61 |
+
result = models['gpt'].generate(
|
62 |
+
emb, inputs['input_ids'],
|
63 |
+
temperature = torch.tensor(temperature, device=device),
|
64 |
+
attention_mask = inputs['attention_mask'],
|
65 |
+
LogitsWarpers = LogitsWarpers,
|
66 |
+
LogitsProcessors = LogitsProcessors,
|
67 |
+
eos_token = num_code,
|
68 |
+
max_new_token = max_new_token,
|
69 |
+
infer_text = False,
|
70 |
+
stream = stream,
|
71 |
+
**kwargs
|
72 |
+
)
|
73 |
+
|
74 |
+
return result
|
75 |
+
|
76 |
+
|
77 |
+
def refine_text(
|
78 |
+
models,
|
79 |
+
text,
|
80 |
+
top_P = 0.7,
|
81 |
+
top_K = 20,
|
82 |
+
temperature = 0.7,
|
83 |
+
repetition_penalty = 1.0,
|
84 |
+
max_new_token = 384,
|
85 |
+
prompt = '',
|
86 |
+
**kwargs
|
87 |
+
):
|
88 |
+
|
89 |
+
device = next(models['gpt'].parameters()).device
|
90 |
+
|
91 |
+
if not isinstance(text, list):
|
92 |
+
text = [text]
|
93 |
+
|
94 |
+
assert len(text), 'text should not be empty'
|
95 |
+
|
96 |
+
text = [f"[Sbreak]{i}[Pbreak]{prompt}" for i in text]
|
97 |
+
text_token = models['tokenizer'](text, return_tensors='pt', add_special_tokens=False, padding=True).to(device)
|
98 |
+
text_mask = torch.ones(text_token['input_ids'].shape, dtype=bool, device=device)
|
99 |
+
|
100 |
+
inputs = {
|
101 |
+
'input_ids': text_token['input_ids'][...,None].expand(-1, -1, models['gpt'].num_vq),
|
102 |
+
'text_mask': text_mask,
|
103 |
+
'attention_mask': text_token['attention_mask'],
|
104 |
+
}
|
105 |
+
|
106 |
+
LogitsWarpers = []
|
107 |
+
if top_P is not None:
|
108 |
+
LogitsWarpers.append(TopPLogitsWarper(top_P, min_tokens_to_keep=3))
|
109 |
+
if top_K is not None:
|
110 |
+
LogitsWarpers.append(TopKLogitsWarper(top_K, min_tokens_to_keep=3))
|
111 |
+
|
112 |
+
LogitsProcessors = []
|
113 |
+
if repetition_penalty is not None and repetition_penalty != 1:
|
114 |
+
LogitsProcessors.append(CustomRepetitionPenaltyLogitsProcessorRepeat(repetition_penalty, len(models['tokenizer']), 16))
|
115 |
+
|
116 |
+
result = models['gpt'].generate(
|
117 |
+
models['gpt'].get_emb(**inputs), inputs['input_ids'],
|
118 |
+
temperature = torch.tensor([temperature,], device=device),
|
119 |
+
attention_mask = inputs['attention_mask'],
|
120 |
+
LogitsWarpers = LogitsWarpers,
|
121 |
+
LogitsProcessors = LogitsProcessors,
|
122 |
+
eos_token = torch.tensor(models['tokenizer'].convert_tokens_to_ids('[Ebreak]'), device=device)[None],
|
123 |
+
max_new_token = max_new_token,
|
124 |
+
infer_text = True,
|
125 |
+
stream = False,
|
126 |
+
**kwargs
|
127 |
+
)
|
128 |
+
return next(result)
|
ChatTTS/ChatTTS/model/dvae.py
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from einops import rearrange
|
3 |
+
from vector_quantize_pytorch import GroupedResidualFSQ
|
4 |
+
|
5 |
+
import torch
|
6 |
+
import torch.nn as nn
|
7 |
+
import torch.nn.functional as F
|
8 |
+
|
9 |
+
class ConvNeXtBlock(nn.Module):
|
10 |
+
def __init__(
|
11 |
+
self,
|
12 |
+
dim: int,
|
13 |
+
intermediate_dim: int,
|
14 |
+
kernel, dilation,
|
15 |
+
layer_scale_init_value: float = 1e-6,
|
16 |
+
):
|
17 |
+
# ConvNeXt Block copied from Vocos.
|
18 |
+
super().__init__()
|
19 |
+
self.dwconv = nn.Conv1d(dim, dim,
|
20 |
+
kernel_size=kernel, padding=dilation*(kernel//2),
|
21 |
+
dilation=dilation, groups=dim
|
22 |
+
) # depthwise conv
|
23 |
+
|
24 |
+
self.norm = nn.LayerNorm(dim, eps=1e-6)
|
25 |
+
self.pwconv1 = nn.Linear(dim, intermediate_dim) # pointwise/1x1 convs, implemented with linear layers
|
26 |
+
self.act = nn.GELU()
|
27 |
+
self.pwconv2 = nn.Linear(intermediate_dim, dim)
|
28 |
+
self.gamma = (
|
29 |
+
nn.Parameter(layer_scale_init_value * torch.ones(dim), requires_grad=True)
|
30 |
+
if layer_scale_init_value > 0
|
31 |
+
else None
|
32 |
+
)
|
33 |
+
|
34 |
+
def forward(self, x: torch.Tensor, cond = None) -> torch.Tensor:
|
35 |
+
residual = x
|
36 |
+
x = self.dwconv(x)
|
37 |
+
x = x.transpose(1, 2) # (B, C, T) -> (B, T, C)
|
38 |
+
x = self.norm(x)
|
39 |
+
x = self.pwconv1(x)
|
40 |
+
x = self.act(x)
|
41 |
+
x = self.pwconv2(x)
|
42 |
+
if self.gamma is not None:
|
43 |
+
x = self.gamma * x
|
44 |
+
x = x.transpose(1, 2) # (B, T, C) -> (B, C, T)
|
45 |
+
|
46 |
+
x = residual + x
|
47 |
+
return x
|
48 |
+
|
49 |
+
|
50 |
+
|
51 |
+
class GFSQ(nn.Module):
|
52 |
+
|
53 |
+
def __init__(self,
|
54 |
+
dim, levels, G, R, eps=1e-5, transpose = True
|
55 |
+
):
|
56 |
+
super(GFSQ, self).__init__()
|
57 |
+
self.quantizer = GroupedResidualFSQ(
|
58 |
+
dim=dim,
|
59 |
+
levels=levels,
|
60 |
+
num_quantizers=R,
|
61 |
+
groups=G,
|
62 |
+
)
|
63 |
+
self.n_ind = math.prod(levels)
|
64 |
+
self.eps = eps
|
65 |
+
self.transpose = transpose
|
66 |
+
self.G = G
|
67 |
+
self.R = R
|
68 |
+
|
69 |
+
def _embed(self, x):
|
70 |
+
if self.transpose:
|
71 |
+
x = x.transpose(1,2)
|
72 |
+
x = rearrange(
|
73 |
+
x, "b t (g r) -> g b t r", g = self.G, r = self.R,
|
74 |
+
)
|
75 |
+
feat = self.quantizer.get_output_from_indices(x)
|
76 |
+
return feat.transpose(1,2) if self.transpose else feat
|
77 |
+
|
78 |
+
def forward(self, x,):
|
79 |
+
if self.transpose:
|
80 |
+
x = x.transpose(1,2)
|
81 |
+
feat, ind = self.quantizer(x)
|
82 |
+
ind = rearrange(
|
83 |
+
ind, "g b t r ->b t (g r)",
|
84 |
+
)
|
85 |
+
embed_onehot = F.one_hot(ind.long(), self.n_ind).to(x.dtype)
|
86 |
+
e_mean = torch.mean(embed_onehot, dim=[0,1])
|
87 |
+
e_mean = e_mean / (e_mean.sum(dim=1) + self.eps).unsqueeze(1)
|
88 |
+
perplexity = torch.exp(-torch.sum(e_mean * torch.log(e_mean + self.eps), dim=1))
|
89 |
+
|
90 |
+
return (
|
91 |
+
torch.zeros(perplexity.shape, dtype=x.dtype, device=x.device),
|
92 |
+
feat.transpose(1,2) if self.transpose else feat,
|
93 |
+
perplexity,
|
94 |
+
None,
|
95 |
+
ind.transpose(1,2) if self.transpose else ind,
|
96 |
+
)
|
97 |
+
|
98 |
+
class DVAEDecoder(nn.Module):
|
99 |
+
def __init__(self, idim, odim,
|
100 |
+
n_layer = 12, bn_dim = 64, hidden = 256,
|
101 |
+
kernel = 7, dilation = 2, up = False
|
102 |
+
):
|
103 |
+
super().__init__()
|
104 |
+
self.up = up
|
105 |
+
self.conv_in = nn.Sequential(
|
106 |
+
nn.Conv1d(idim, bn_dim, 3, 1, 1), nn.GELU(),
|
107 |
+
nn.Conv1d(bn_dim, hidden, 3, 1, 1)
|
108 |
+
)
|
109 |
+
self.decoder_block = nn.ModuleList([
|
110 |
+
ConvNeXtBlock(hidden, hidden* 4, kernel, dilation,)
|
111 |
+
for _ in range(n_layer)])
|
112 |
+
self.conv_out = nn.Conv1d(hidden, odim, kernel_size=1, bias=False)
|
113 |
+
|
114 |
+
def forward(self, input, conditioning=None):
|
115 |
+
# B, T, C
|
116 |
+
x = input.transpose(1, 2)
|
117 |
+
x = self.conv_in(x)
|
118 |
+
for f in self.decoder_block:
|
119 |
+
x = f(x, conditioning)
|
120 |
+
|
121 |
+
x = self.conv_out(x)
|
122 |
+
return x.transpose(1, 2)
|
123 |
+
|
124 |
+
|
125 |
+
class DVAE(nn.Module):
|
126 |
+
def __init__(
|
127 |
+
self, decoder_config, vq_config, dim=512
|
128 |
+
):
|
129 |
+
super().__init__()
|
130 |
+
self.register_buffer('coef', torch.randn(1, 100, 1))
|
131 |
+
|
132 |
+
self.decoder = DVAEDecoder(**decoder_config)
|
133 |
+
self.out_conv = nn.Conv1d(dim, 100, 3, 1, 1, bias=False)
|
134 |
+
if vq_config is not None:
|
135 |
+
self.vq_layer = GFSQ(**vq_config)
|
136 |
+
else:
|
137 |
+
self.vq_layer = None
|
138 |
+
|
139 |
+
def forward(self, inp):
|
140 |
+
|
141 |
+
if self.vq_layer is not None:
|
142 |
+
vq_feats = self.vq_layer._embed(inp)
|
143 |
+
else:
|
144 |
+
vq_feats = inp.detach().clone()
|
145 |
+
|
146 |
+
vq_feats = vq_feats.view(
|
147 |
+
(vq_feats.size(0), 2, vq_feats.size(1)//2, vq_feats.size(2)),
|
148 |
+
).permute(0, 2, 3, 1).flatten(2)
|
149 |
+
|
150 |
+
vq_feats = vq_feats.transpose(1, 2)
|
151 |
+
dec_out = self.decoder(input=vq_feats)
|
152 |
+
dec_out = self.out_conv(dec_out.transpose(1, 2))
|
153 |
+
mel = dec_out * self.coef
|
154 |
+
|
155 |
+
return mel
|
ChatTTS/ChatTTS/model/gpt.py
ADDED
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
3 |
+
|
4 |
+
import logging
|
5 |
+
from tqdm import tqdm
|
6 |
+
from einops import rearrange
|
7 |
+
from transformers.cache_utils import Cache
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
import torch.nn.functional as F
|
12 |
+
import torch.nn.utils.parametrize as P
|
13 |
+
from torch.nn.utils.parametrizations import weight_norm
|
14 |
+
from transformers import LlamaModel, LlamaConfig
|
15 |
+
|
16 |
+
|
17 |
+
class LlamaMLP(nn.Module):
|
18 |
+
def __init__(self, hidden_size, intermediate_size):
|
19 |
+
super().__init__()
|
20 |
+
self.hidden_size = hidden_size
|
21 |
+
self.intermediate_size = intermediate_size
|
22 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
23 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
24 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
25 |
+
self.act_fn = F.silu
|
26 |
+
|
27 |
+
def forward(self, x):
|
28 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
29 |
+
return down_proj
|
30 |
+
|
31 |
+
|
32 |
+
class GPT_warpper(nn.Module):
|
33 |
+
def __init__(
|
34 |
+
self,
|
35 |
+
gpt_config,
|
36 |
+
num_audio_tokens,
|
37 |
+
num_text_tokens,
|
38 |
+
num_vq=4,
|
39 |
+
):
|
40 |
+
super().__init__()
|
41 |
+
|
42 |
+
self.logger = logging.getLogger(__name__)
|
43 |
+
self.gpt = self.build_model(gpt_config)
|
44 |
+
self.model_dim = self.gpt.config.hidden_size
|
45 |
+
|
46 |
+
self.num_vq = num_vq
|
47 |
+
self.emb_code = nn.ModuleList([nn.Embedding(num_audio_tokens, self.model_dim) for i in range(self.num_vq)])
|
48 |
+
self.emb_text = nn.Embedding(num_text_tokens, self.model_dim)
|
49 |
+
self.head_text = weight_norm(nn.Linear(self.model_dim, num_text_tokens, bias=False), name='weight')
|
50 |
+
self.head_code = nn.ModuleList([weight_norm(nn.Linear(self.model_dim, num_audio_tokens, bias=False), name='weight') for i in range(self.num_vq)])
|
51 |
+
|
52 |
+
def build_model(self, config):
|
53 |
+
|
54 |
+
configuration = LlamaConfig(**config)
|
55 |
+
model = LlamaModel(configuration)
|
56 |
+
del model.embed_tokens
|
57 |
+
|
58 |
+
return model
|
59 |
+
|
60 |
+
def get_emb(self, input_ids, text_mask, **kwargs):
|
61 |
+
|
62 |
+
emb_text = self.emb_text(input_ids[text_mask][:, 0])
|
63 |
+
|
64 |
+
emb_code = [self.emb_code[i](input_ids[~text_mask][:, i]) for i in range(self.num_vq)]
|
65 |
+
emb_code = torch.stack(emb_code, 2).sum(2)
|
66 |
+
|
67 |
+
emb = torch.zeros((input_ids.shape[:-1])+(emb_text.shape[-1],), device=emb_text.device, dtype=emb_text.dtype)
|
68 |
+
emb[text_mask] = emb_text
|
69 |
+
emb[~text_mask] = emb_code.to(emb.dtype)
|
70 |
+
|
71 |
+
return emb
|
72 |
+
|
73 |
+
def prepare_inputs_for_generation(
|
74 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
|
75 |
+
):
|
76 |
+
# With static cache, the `past_key_values` is None
|
77 |
+
# TODO joao: standardize interface for the different Cache classes and remove of this if
|
78 |
+
has_static_cache = False
|
79 |
+
if past_key_values is None:
|
80 |
+
past_key_values = getattr(self.gpt.layers[0].self_attn, "past_key_value", None)
|
81 |
+
has_static_cache = past_key_values is not None
|
82 |
+
|
83 |
+
past_length = 0
|
84 |
+
if past_key_values is not None:
|
85 |
+
if isinstance(past_key_values, Cache):
|
86 |
+
past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
|
87 |
+
max_cache_length = (
|
88 |
+
torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
|
89 |
+
if past_key_values.get_max_length() is not None
|
90 |
+
else None
|
91 |
+
)
|
92 |
+
cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
|
93 |
+
# TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
|
94 |
+
else:
|
95 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
96 |
+
max_cache_length = None
|
97 |
+
|
98 |
+
# Keep only the unprocessed tokens:
|
99 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
100 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
101 |
+
# input)
|
102 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
103 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
104 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
105 |
+
# input_ids based on the past_length.
|
106 |
+
elif past_length < input_ids.shape[1]:
|
107 |
+
input_ids = input_ids[:, past_length:]
|
108 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
109 |
+
|
110 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
111 |
+
if (
|
112 |
+
max_cache_length is not None
|
113 |
+
and attention_mask is not None
|
114 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
115 |
+
):
|
116 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
117 |
+
|
118 |
+
position_ids = kwargs.get("position_ids", None)
|
119 |
+
if attention_mask is not None and position_ids is None:
|
120 |
+
# create position_ids on the fly for batch generation
|
121 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
122 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
123 |
+
if past_key_values:
|
124 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
125 |
+
|
126 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
127 |
+
if inputs_embeds is not None and past_key_values is None:
|
128 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
129 |
+
else:
|
130 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
131 |
+
# recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
|
132 |
+
# TODO: use `next_tokens` directly instead.
|
133 |
+
model_inputs = {"input_ids": input_ids.contiguous()}
|
134 |
+
|
135 |
+
input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
|
136 |
+
if cache_position is None:
|
137 |
+
cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
|
138 |
+
else:
|
139 |
+
cache_position = cache_position[-input_length:]
|
140 |
+
|
141 |
+
if has_static_cache:
|
142 |
+
past_key_values = None
|
143 |
+
|
144 |
+
model_inputs.update(
|
145 |
+
{
|
146 |
+
"position_ids": position_ids,
|
147 |
+
"cache_position": cache_position,
|
148 |
+
"past_key_values": past_key_values,
|
149 |
+
"use_cache": kwargs.get("use_cache"),
|
150 |
+
"attention_mask": attention_mask,
|
151 |
+
}
|
152 |
+
)
|
153 |
+
return model_inputs
|
154 |
+
|
155 |
+
def generate(
|
156 |
+
self,
|
157 |
+
emb,
|
158 |
+
inputs_ids,
|
159 |
+
temperature,
|
160 |
+
eos_token,
|
161 |
+
attention_mask = None,
|
162 |
+
max_new_token = 2048,
|
163 |
+
min_new_token = 0,
|
164 |
+
LogitsWarpers = [],
|
165 |
+
LogitsProcessors = [],
|
166 |
+
infer_text=False,
|
167 |
+
return_attn=False,
|
168 |
+
return_hidden=False,
|
169 |
+
stream=False,
|
170 |
+
):
|
171 |
+
|
172 |
+
with torch.no_grad():
|
173 |
+
|
174 |
+
attentions = []
|
175 |
+
hiddens = []
|
176 |
+
|
177 |
+
start_idx, end_idx = inputs_ids.shape[1], torch.zeros(inputs_ids.shape[0], device=inputs_ids.device, dtype=torch.long)
|
178 |
+
finish = torch.zeros(inputs_ids.shape[0], device=inputs_ids.device).bool()
|
179 |
+
|
180 |
+
temperature = temperature[None].expand(inputs_ids.shape[0], -1)
|
181 |
+
temperature = rearrange(temperature, "b n -> (b n) 1")
|
182 |
+
|
183 |
+
attention_mask_cache = torch.ones((inputs_ids.shape[0], inputs_ids.shape[1]+max_new_token,), dtype=torch.bool, device=inputs_ids.device)
|
184 |
+
if attention_mask is not None:
|
185 |
+
attention_mask_cache[:, :attention_mask.shape[1]] = attention_mask
|
186 |
+
|
187 |
+
with tqdm(total=max_new_token) as pbar:
|
188 |
+
|
189 |
+
past_key_values = None
|
190 |
+
|
191 |
+
for i in range(max_new_token):
|
192 |
+
pbar.update(1)
|
193 |
+
model_input = self.prepare_inputs_for_generation(
|
194 |
+
inputs_ids,
|
195 |
+
past_key_values,
|
196 |
+
attention_mask_cache[:, :inputs_ids.shape[1]],
|
197 |
+
use_cache=True,
|
198 |
+
)
|
199 |
+
|
200 |
+
if i == 0:
|
201 |
+
model_input['inputs_embeds'] = emb
|
202 |
+
else:
|
203 |
+
if infer_text:
|
204 |
+
model_input['inputs_embeds'] = self.emb_text(model_input['input_ids'][:,:,0])
|
205 |
+
else:
|
206 |
+
code_emb = [self.emb_code[i](model_input['input_ids'][:,:,i]) for i in range(self.num_vq)]
|
207 |
+
model_input['inputs_embeds'] = torch.stack(code_emb, 3).sum(3)
|
208 |
+
|
209 |
+
model_input['input_ids'] = None
|
210 |
+
outputs = self.gpt.forward(**model_input, output_attentions=return_attn)
|
211 |
+
del model_input
|
212 |
+
attentions.append(outputs.attentions)
|
213 |
+
hidden_states = outputs[0] # 🐻
|
214 |
+
past_key_values = outputs.past_key_values
|
215 |
+
del outputs
|
216 |
+
if return_hidden:
|
217 |
+
hiddens.append(hidden_states[:, -1])
|
218 |
+
|
219 |
+
with P.cached():
|
220 |
+
if infer_text:
|
221 |
+
logits = self.head_text(hidden_states)
|
222 |
+
else:
|
223 |
+
logits = torch.stack([self.head_code[i](hidden_states) for i in range(self.num_vq)], 3)
|
224 |
+
|
225 |
+
logits = logits[:, -1].float()
|
226 |
+
|
227 |
+
if not infer_text:
|
228 |
+
logits = rearrange(logits, "b c n -> (b n) c")
|
229 |
+
logits_token = rearrange(inputs_ids[:, start_idx:], "b c n -> (b n) c")
|
230 |
+
else:
|
231 |
+
logits_token = inputs_ids[:, start_idx:, 0]
|
232 |
+
|
233 |
+
logits = logits / temperature
|
234 |
+
|
235 |
+
for logitsProcessors in LogitsProcessors:
|
236 |
+
logits = logitsProcessors(logits_token, logits)
|
237 |
+
|
238 |
+
for logitsWarpers in LogitsWarpers:
|
239 |
+
logits = logitsWarpers(logits_token, logits)
|
240 |
+
|
241 |
+
del logits_token
|
242 |
+
|
243 |
+
if i < min_new_token:
|
244 |
+
logits[:, eos_token] = -torch.inf
|
245 |
+
|
246 |
+
scores = F.softmax(logits, dim=-1)
|
247 |
+
|
248 |
+
del logits
|
249 |
+
|
250 |
+
idx_next = torch.multinomial(scores, num_samples=1)
|
251 |
+
|
252 |
+
if not infer_text:
|
253 |
+
idx_next = rearrange(idx_next, "(b n) 1 -> b n", n=self.num_vq)
|
254 |
+
finish_or = (idx_next == eos_token).any(1)
|
255 |
+
finish |= finish_or
|
256 |
+
del finish_or
|
257 |
+
inputs_ids = torch.cat([inputs_ids, idx_next.unsqueeze(1)], 1)
|
258 |
+
else:
|
259 |
+
finish_or = (idx_next == eos_token).any(1)
|
260 |
+
finish |= finish_or
|
261 |
+
del finish_or
|
262 |
+
inputs_ids = torch.cat([inputs_ids, idx_next.unsqueeze(-1).expand(-1, -1, self.num_vq)], 1)
|
263 |
+
|
264 |
+
del idx_next
|
265 |
+
|
266 |
+
end_idx += (~finish).int().to(end_idx.device)
|
267 |
+
if stream:
|
268 |
+
if end_idx % 24 and not finish.all():
|
269 |
+
continue
|
270 |
+
y_inputs_ids = [inputs_ids[idx, start_idx: start_idx+i] for idx, i in enumerate(end_idx.int())]
|
271 |
+
y_inputs_ids = [i[:, 0] for i in y_inputs_ids] if infer_text else y_inputs_ids
|
272 |
+
y_hiddens = [[]]
|
273 |
+
if return_hidden:
|
274 |
+
y_hiddens = torch.stack(hiddens, 1)
|
275 |
+
y_hiddens = [y_hiddens[idx, :i] for idx, i in enumerate(end_idx.int())]
|
276 |
+
yield {
|
277 |
+
'ids': y_inputs_ids,
|
278 |
+
'attentions': attentions,
|
279 |
+
'hiddens':y_hiddens,
|
280 |
+
}
|
281 |
+
if finish.all():
|
282 |
+
pbar.update(max_new_token-i-1)
|
283 |
+
break
|
284 |
+
|
285 |
+
inputs_ids = [inputs_ids[idx, start_idx: start_idx+i] for idx, i in enumerate(end_idx.int())]
|
286 |
+
inputs_ids = [i[:, 0] for i in inputs_ids] if infer_text else inputs_ids
|
287 |
+
|
288 |
+
if return_hidden:
|
289 |
+
hiddens = torch.stack(hiddens, 1)
|
290 |
+
hiddens = [hiddens[idx, :i] for idx, i in enumerate(end_idx.int())]
|
291 |
+
|
292 |
+
if not finish.all():
|
293 |
+
self.logger.warn(f'Incomplete result. hit max_new_token: {max_new_token}')
|
294 |
+
|
295 |
+
del finish
|
296 |
+
|
297 |
+
yield {
|
298 |
+
'ids': inputs_ids,
|
299 |
+
'attentions': attentions,
|
300 |
+
'hiddens':hiddens,
|
301 |
+
}
|
ChatTTS/ChatTTS/res/homophones_map.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
ChatTTS/ChatTTS/utils/download.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from pathlib import Path
|
3 |
+
import hashlib
|
4 |
+
import requests
|
5 |
+
from io import BytesIO
|
6 |
+
import logging
|
7 |
+
|
8 |
+
logger = logging.getLogger(__name__)
|
9 |
+
|
10 |
+
|
11 |
+
def sha256(f) -> str:
|
12 |
+
sha256_hash = hashlib.sha256()
|
13 |
+
# Read and update hash in chunks of 4M
|
14 |
+
for byte_block in iter(lambda: f.read(4 * 1024 * 1024), b""):
|
15 |
+
sha256_hash.update(byte_block)
|
16 |
+
return sha256_hash.hexdigest()
|
17 |
+
|
18 |
+
|
19 |
+
def check_model(
|
20 |
+
dir_name: Path, model_name: str, hash: str, remove_incorrect=False
|
21 |
+
) -> bool:
|
22 |
+
target = dir_name / model_name
|
23 |
+
relname = target.as_posix()
|
24 |
+
logger.debug(f"checking {relname}...")
|
25 |
+
if not os.path.exists(target):
|
26 |
+
logger.info(f"{target} not exist.")
|
27 |
+
return False
|
28 |
+
with open(target, "rb") as f:
|
29 |
+
digest = sha256(f)
|
30 |
+
bakfile = f"{target}.bak"
|
31 |
+
if digest != hash:
|
32 |
+
logger.warn(f"{target} sha256 hash mismatch.")
|
33 |
+
logger.info(f"expected: {hash}")
|
34 |
+
logger.info(f"real val: {digest}")
|
35 |
+
logger.warn("please add parameter --update to download the latest assets.")
|
36 |
+
if remove_incorrect:
|
37 |
+
if not os.path.exists(bakfile):
|
38 |
+
os.rename(str(target), bakfile)
|
39 |
+
else:
|
40 |
+
os.remove(str(target))
|
41 |
+
return False
|
42 |
+
if remove_incorrect and os.path.exists(bakfile):
|
43 |
+
os.remove(bakfile)
|
44 |
+
return True
|
45 |
+
|
46 |
+
|
47 |
+
def check_all_assets(update=False) -> bool:
|
48 |
+
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
49 |
+
|
50 |
+
logger.info("checking assets...")
|
51 |
+
current_dir = BASE_DIR / "asset"
|
52 |
+
names = [
|
53 |
+
"Decoder.pt",
|
54 |
+
"DVAE.pt",
|
55 |
+
"GPT.pt",
|
56 |
+
"spk_stat.pt",
|
57 |
+
"tokenizer.pt",
|
58 |
+
"Vocos.pt",
|
59 |
+
]
|
60 |
+
for model in names:
|
61 |
+
menv = model.replace(".", "_")
|
62 |
+
if not check_model(
|
63 |
+
current_dir, model, os.environ[f"sha256_asset_{menv}"], update
|
64 |
+
):
|
65 |
+
return False
|
66 |
+
|
67 |
+
logger.info("checking configs...")
|
68 |
+
current_dir = BASE_DIR / "config"
|
69 |
+
names = [
|
70 |
+
"decoder.yaml",
|
71 |
+
"dvae.yaml",
|
72 |
+
"gpt.yaml",
|
73 |
+
"path.yaml",
|
74 |
+
"vocos.yaml",
|
75 |
+
]
|
76 |
+
for model in names:
|
77 |
+
menv = model.replace(".", "_")
|
78 |
+
if not check_model(
|
79 |
+
current_dir, model, os.environ[f"sha256_config_{menv}"], update
|
80 |
+
):
|
81 |
+
return False
|
82 |
+
|
83 |
+
logger.info("all assets are already latest.")
|
84 |
+
return True
|
85 |
+
|
86 |
+
|
87 |
+
def download_and_extract_tar_gz(url: str, folder: str):
|
88 |
+
import tarfile
|
89 |
+
|
90 |
+
logger.info(f"downloading {url}")
|
91 |
+
response = requests.get(url, stream=True, timeout=(5, 10))
|
92 |
+
with BytesIO() as out_file:
|
93 |
+
out_file.write(response.content)
|
94 |
+
out_file.seek(0)
|
95 |
+
logger.info(f"downloaded.")
|
96 |
+
with tarfile.open(fileobj=out_file, mode="r:gz") as tar:
|
97 |
+
tar.extractall(folder)
|
98 |
+
logger.info(f"extracted into {folder}")
|
99 |
+
|
100 |
+
|
101 |
+
def download_and_extract_zip(url: str, folder: str):
|
102 |
+
import zipfile
|
103 |
+
|
104 |
+
logger.info(f"downloading {url}")
|
105 |
+
response = requests.get(url, stream=True, timeout=(5, 10))
|
106 |
+
with BytesIO() as out_file:
|
107 |
+
out_file.write(response.content)
|
108 |
+
out_file.seek(0)
|
109 |
+
logger.info(f"downloaded.")
|
110 |
+
with zipfile.ZipFile(out_file) as zip_ref:
|
111 |
+
zip_ref.extractall(folder)
|
112 |
+
logger.info(f"extracted into {folder}")
|
113 |
+
|
114 |
+
|
115 |
+
def download_dns_yaml(url: str, folder: str):
|
116 |
+
logger.info(f"downloading {url}")
|
117 |
+
response = requests.get(url, stream=True, timeout=(5, 10))
|
118 |
+
with open(os.path.join(folder, "dns.yaml"), "wb") as out_file:
|
119 |
+
out_file.write(response.content)
|
120 |
+
logger.info(f"downloaded into {folder}")
|
121 |
+
|
122 |
+
|
123 |
+
def download_all_assets(tmpdir: str, version="0.2.5"):
|
124 |
+
import subprocess
|
125 |
+
import platform
|
126 |
+
|
127 |
+
archs = {
|
128 |
+
"aarch64": "arm64",
|
129 |
+
"armv8l": "arm64",
|
130 |
+
"arm64": "arm64",
|
131 |
+
"x86": "386",
|
132 |
+
"i386": "386",
|
133 |
+
"i686": "386",
|
134 |
+
"386": "386",
|
135 |
+
"x86_64": "amd64",
|
136 |
+
"x64": "amd64",
|
137 |
+
"amd64": "amd64",
|
138 |
+
}
|
139 |
+
system_type = platform.system().lower()
|
140 |
+
architecture = platform.machine().lower()
|
141 |
+
is_win = system_type == "windows"
|
142 |
+
|
143 |
+
architecture = archs.get(architecture, None)
|
144 |
+
if not architecture:
|
145 |
+
logger.error(f"architecture {architecture} is not supported")
|
146 |
+
exit(1)
|
147 |
+
try:
|
148 |
+
BASE_URL = "https://github.com/fumiama/RVC-Models-Downloader/releases/download/"
|
149 |
+
suffix = "zip" if is_win else "tar.gz"
|
150 |
+
RVCMD_URL = BASE_URL + f"v{version}/rvcmd_{system_type}_{architecture}.{suffix}"
|
151 |
+
cmdfile = os.path.join(tmpdir, "rvcmd")
|
152 |
+
if is_win:
|
153 |
+
download_and_extract_zip(RVCMD_URL, tmpdir)
|
154 |
+
cmdfile += ".exe"
|
155 |
+
else:
|
156 |
+
download_and_extract_tar_gz(RVCMD_URL, tmpdir)
|
157 |
+
os.chmod(cmdfile, 0o755)
|
158 |
+
subprocess.run([cmdfile, "-notui", "-w", "0", "assets/chtts"])
|
159 |
+
except Exception:
|
160 |
+
BASE_URL = "https://raw.gitcode.com/u011570312/RVC-Models-Downloader/assets/"
|
161 |
+
suffix = {
|
162 |
+
"darwin_amd64": "555",
|
163 |
+
"darwin_arm64": "556",
|
164 |
+
"linux_386": "557",
|
165 |
+
"linux_amd64": "558",
|
166 |
+
"linux_arm64": "559",
|
167 |
+
"windows_386": "562",
|
168 |
+
"windows_amd64": "563",
|
169 |
+
}[f"{system_type}_{architecture}"]
|
170 |
+
RVCMD_URL = BASE_URL + suffix
|
171 |
+
download_dns_yaml(
|
172 |
+
"https://raw.gitcode.com/u011570312/RVC-Models-Downloader/raw/main/dns.yaml",
|
173 |
+
tmpdir,
|
174 |
+
)
|
175 |
+
if is_win:
|
176 |
+
download_and_extract_zip(RVCMD_URL, tmpdir)
|
177 |
+
cmdfile += ".exe"
|
178 |
+
else:
|
179 |
+
download_and_extract_tar_gz(RVCMD_URL, tmpdir)
|
180 |
+
os.chmod(cmdfile, 0o755)
|
181 |
+
subprocess.run(
|
182 |
+
[
|
183 |
+
cmdfile,
|
184 |
+
"-notui",
|
185 |
+
"-w",
|
186 |
+
"0",
|
187 |
+
"-dns",
|
188 |
+
os.path.join(tmpdir, "dns.yaml"),
|
189 |
+
"assets/chtts",
|
190 |
+
]
|
191 |
+
)
|
ChatTTS/ChatTTS/utils/gpu_utils.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import torch
|
3 |
+
import logging
|
4 |
+
|
5 |
+
def select_device(min_memory=2048):
|
6 |
+
logger = logging.getLogger(__name__)
|
7 |
+
if torch.cuda.is_available():
|
8 |
+
available_gpus = []
|
9 |
+
for i in range(torch.cuda.device_count()):
|
10 |
+
props = torch.cuda.get_device_properties(i)
|
11 |
+
free_memory = props.total_memory - torch.cuda.memory_reserved(i)
|
12 |
+
available_gpus.append((i, free_memory))
|
13 |
+
selected_gpu, max_free_memory = max(available_gpus, key=lambda x: x[1])
|
14 |
+
device = torch.device(f'cuda:{selected_gpu}')
|
15 |
+
free_memory_mb = max_free_memory / (1024 * 1024)
|
16 |
+
if free_memory_mb < min_memory:
|
17 |
+
logger.warning(f'GPU {selected_gpu} has {round(free_memory_mb, 2)} MB memory left. Switching to CPU.')
|
18 |
+
device = torch.device('cpu')
|
19 |
+
elif torch.backends.mps.is_available():
|
20 |
+
# For Apple M1/M2 chips with Metal Performance Shaders
|
21 |
+
logger.info('Apple GPU found, using MPS.')
|
22 |
+
device = torch.device('mps')
|
23 |
+
else:
|
24 |
+
logger.warning('No GPU found, use CPU instead')
|
25 |
+
device = torch.device('cpu')
|
26 |
+
|
27 |
+
return device
|
ChatTTS/ChatTTS/utils/infer_utils.py
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import re
|
3 |
+
import torch
|
4 |
+
import torch.nn.functional as F
|
5 |
+
import os
|
6 |
+
import json
|
7 |
+
|
8 |
+
|
9 |
+
class CustomRepetitionPenaltyLogitsProcessorRepeat():
|
10 |
+
|
11 |
+
def __init__(self, penalty: float, max_input_ids, past_window):
|
12 |
+
if not isinstance(penalty, float) or not (penalty > 0):
|
13 |
+
raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
|
14 |
+
|
15 |
+
self.penalty = penalty
|
16 |
+
self.max_input_ids = max_input_ids
|
17 |
+
self.past_window = past_window
|
18 |
+
|
19 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
20 |
+
|
21 |
+
input_ids = input_ids[:, -self.past_window:]
|
22 |
+
freq = F.one_hot(input_ids, scores.size(1)).sum(1)
|
23 |
+
freq[self.max_input_ids:] = 0
|
24 |
+
alpha = self.penalty**freq
|
25 |
+
scores = scores.contiguous()
|
26 |
+
scores = torch.where(scores < 0, scores*alpha, scores/alpha)
|
27 |
+
|
28 |
+
return scores
|
29 |
+
|
30 |
+
class CustomRepetitionPenaltyLogitsProcessor():
|
31 |
+
|
32 |
+
def __init__(self, penalty: float, max_input_ids, past_window):
|
33 |
+
if not isinstance(penalty, float) or not (penalty > 0):
|
34 |
+
raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
|
35 |
+
|
36 |
+
self.penalty = penalty
|
37 |
+
self.max_input_ids = max_input_ids
|
38 |
+
self.past_window = past_window
|
39 |
+
|
40 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
41 |
+
|
42 |
+
input_ids = input_ids[:, -self.past_window:]
|
43 |
+
score = torch.gather(scores, 1, input_ids)
|
44 |
+
_score = score.detach().clone()
|
45 |
+
score = torch.where(score < 0, score * self.penalty, score / self.penalty)
|
46 |
+
score[input_ids>=self.max_input_ids] = _score[input_ids>=self.max_input_ids]
|
47 |
+
scores.scatter_(1, input_ids, score)
|
48 |
+
|
49 |
+
return scores
|
50 |
+
|
51 |
+
class HomophonesReplacer:
|
52 |
+
"""
|
53 |
+
Homophones Replacer
|
54 |
+
|
55 |
+
Replace the mispronounced characters with correctly pronounced ones.
|
56 |
+
|
57 |
+
Creation process of homophones_map.json:
|
58 |
+
|
59 |
+
1. Establish a word corpus using the [Tencent AI Lab Embedding Corpora v0.2.0 large] with 12 million entries. After cleaning, approximately 1.8 million entries remain. Use ChatTTS to infer the text.
|
60 |
+
2. Record discrepancies between the inferred and input text, identifying about 180,000 misread words.
|
61 |
+
3. Create a pinyin to common characters mapping using correctly read characters by ChatTTS.
|
62 |
+
4. For each discrepancy, extract the correct pinyin using [python-pinyin] and find homophones with the correct pronunciation from the mapping.
|
63 |
+
|
64 |
+
Thanks to:
|
65 |
+
[Tencent AI Lab Embedding Corpora for Chinese and English Words and Phrases](https://ai.tencent.com/ailab/nlp/en/embedding.html)
|
66 |
+
[python-pinyin](https://github.com/mozillazg/python-pinyin)
|
67 |
+
|
68 |
+
"""
|
69 |
+
def __init__(self, map_file_path):
|
70 |
+
self.homophones_map = self.load_homophones_map(map_file_path)
|
71 |
+
|
72 |
+
def load_homophones_map(self, map_file_path):
|
73 |
+
with open(map_file_path, 'r', encoding='utf-8') as f:
|
74 |
+
homophones_map = json.load(f)
|
75 |
+
return homophones_map
|
76 |
+
|
77 |
+
def replace(self, text):
|
78 |
+
result = []
|
79 |
+
for char in text:
|
80 |
+
if char in self.homophones_map:
|
81 |
+
result.append(self.homophones_map[char])
|
82 |
+
else:
|
83 |
+
result.append(char)
|
84 |
+
return ''.join(result)
|
85 |
+
|
86 |
+
def count_invalid_characters(s):
|
87 |
+
|
88 |
+
s = re.sub(r'\[uv_break\]|\[laugh\]|\[lbreak\]', '', s)
|
89 |
+
pattern = re.compile(r'[^\u4e00-\u9fffA-Za-z,。、,\. ]')
|
90 |
+
non_alphabetic_chinese_chars = pattern.findall(s)
|
91 |
+
return set(non_alphabetic_chinese_chars)
|
92 |
+
|
93 |
+
def detect_language(sentence):
|
94 |
+
|
95 |
+
chinese_char_pattern = re.compile(r'[\u4e00-\u9fff]')
|
96 |
+
english_word_pattern = re.compile(r'\b[A-Za-z]+\b')
|
97 |
+
|
98 |
+
chinese_chars = chinese_char_pattern.findall(sentence)
|
99 |
+
english_words = english_word_pattern.findall(sentence)
|
100 |
+
|
101 |
+
if len(chinese_chars) > len(english_words):
|
102 |
+
return "zh"
|
103 |
+
else:
|
104 |
+
return "en"
|
105 |
+
|
106 |
+
|
107 |
+
character_map = {
|
108 |
+
':': ',',
|
109 |
+
';': ',',
|
110 |
+
'!': '。',
|
111 |
+
'(': ',',
|
112 |
+
')': ',',
|
113 |
+
'【': ',',
|
114 |
+
'】': ',',
|
115 |
+
'『': ',',
|
116 |
+
'』': ',',
|
117 |
+
'「': ',',
|
118 |
+
'」': ',',
|
119 |
+
'《': ',',
|
120 |
+
'》': ',',
|
121 |
+
'-': ',',
|
122 |
+
'‘': '',
|
123 |
+
'“': '',
|
124 |
+
'’': '',
|
125 |
+
'”': '',
|
126 |
+
':': ',',
|
127 |
+
';': ',',
|
128 |
+
'!': '.',
|
129 |
+
'(': ',',
|
130 |
+
')': ',',
|
131 |
+
'[': ',',
|
132 |
+
']': ',',
|
133 |
+
'>': ',',
|
134 |
+
'<': ',',
|
135 |
+
'-': ',',
|
136 |
+
}
|
137 |
+
|
138 |
+
halfwidth_2_fullwidth_map = {
|
139 |
+
'!': '!',
|
140 |
+
'"': '“',
|
141 |
+
"'": '‘',
|
142 |
+
'#': '#',
|
143 |
+
'$': '$',
|
144 |
+
'%': '%',
|
145 |
+
'&': '&',
|
146 |
+
'(': '(',
|
147 |
+
')': ')',
|
148 |
+
',': ',',
|
149 |
+
'-': '-',
|
150 |
+
'*': '*',
|
151 |
+
'+': '+',
|
152 |
+
'.': '。',
|
153 |
+
'/': '/',
|
154 |
+
':': ':',
|
155 |
+
';': ';',
|
156 |
+
'<': '<',
|
157 |
+
'=': '=',
|
158 |
+
'>': '>',
|
159 |
+
'?': '?',
|
160 |
+
'@': '@',
|
161 |
+
# '[': '[',
|
162 |
+
'\\': '\',
|
163 |
+
# ']': ']',
|
164 |
+
'^': '^',
|
165 |
+
# '_': '_',
|
166 |
+
'`': '`',
|
167 |
+
'{': '{',
|
168 |
+
'|': '|',
|
169 |
+
'}': '}',
|
170 |
+
'~': '~'
|
171 |
+
}
|
172 |
+
|
173 |
+
def apply_half2full_map(text):
|
174 |
+
translation_table = str.maketrans(halfwidth_2_fullwidth_map)
|
175 |
+
return text.translate(translation_table)
|
176 |
+
|
177 |
+
def apply_character_map(text):
|
178 |
+
translation_table = str.maketrans(character_map)
|
179 |
+
return text.translate(translation_table)
|
ChatTTS/ChatTTS/utils/io_utils.py
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import os
|
3 |
+
import logging
|
4 |
+
|
5 |
+
def get_latest_modified_file(directory):
|
6 |
+
logger = logging.getLogger(__name__)
|
7 |
+
|
8 |
+
files = [os.path.join(directory, f) for f in os.listdir(directory)]
|
9 |
+
if not files:
|
10 |
+
logger.log(logging.WARNING, f'No files found in the directory: {directory}')
|
11 |
+
return None
|
12 |
+
latest_file = max(files, key=os.path.getmtime)
|
13 |
+
|
14 |
+
return latest_file
|
ChatTTS/LICENSE
ADDED
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Attribution-NonCommercial 4.0 International
|
2 |
+
|
3 |
+
=======================================================================
|
4 |
+
|
5 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
6 |
+
does not provide legal services or legal advice. Distribution of
|
7 |
+
Creative Commons public licenses does not create a lawyer-client or
|
8 |
+
other relationship. Creative Commons makes its licenses and related
|
9 |
+
information available on an "as-is" basis. Creative Commons gives no
|
10 |
+
warranties regarding its licenses, any material licensed under their
|
11 |
+
terms and conditions, or any related information. Creative Commons
|
12 |
+
disclaims all liability for damages resulting from their use to the
|
13 |
+
fullest extent possible.
|
14 |
+
|
15 |
+
Using Creative Commons Public Licenses
|
16 |
+
|
17 |
+
Creative Commons public licenses provide a standard set of terms and
|
18 |
+
conditions that creators and other rights holders may use to share
|
19 |
+
original works of authorship and other material subject to copyright
|
20 |
+
and certain other rights specified in the public license below. The
|
21 |
+
following considerations are for informational purposes only, are not
|
22 |
+
exhaustive, and do not form part of our licenses.
|
23 |
+
|
24 |
+
Considerations for licensors: Our public licenses are
|
25 |
+
intended for use by those authorized to give the public
|
26 |
+
permission to use material in ways otherwise restricted by
|
27 |
+
copyright and certain other rights. Our licenses are
|
28 |
+
irrevocable. Licensors should read and understand the terms
|
29 |
+
and conditions of the license they choose before applying it.
|
30 |
+
Licensors should also secure all rights necessary before
|
31 |
+
applying our licenses so that the public can reuse the
|
32 |
+
material as expected. Licensors should clearly mark any
|
33 |
+
material not subject to the license. This includes other CC-
|
34 |
+
licensed material, or material used under an exception or
|
35 |
+
limitation to copyright. More considerations for licensors:
|
36 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
37 |
+
|
38 |
+
Considerations for the public: By using one of our public
|
39 |
+
licenses, a licensor grants the public permission to use the
|
40 |
+
licensed material under specified terms and conditions. If
|
41 |
+
the licensor's permission is not necessary for any reason--for
|
42 |
+
example, because of any applicable exception or limitation to
|
43 |
+
copyright--then that use is not regulated by the license. Our
|
44 |
+
licenses grant only permissions under copyright and certain
|
45 |
+
other rights that a licensor has authority to grant. Use of
|
46 |
+
the licensed material may still be restricted for other
|
47 |
+
reasons, including because others have copyright or other
|
48 |
+
rights in the material. A licensor may make special requests,
|
49 |
+
such as asking that all changes be marked or described.
|
50 |
+
Although not required by our licenses, you are encouraged to
|
51 |
+
respect those requests where reasonable. More considerations
|
52 |
+
for the public:
|
53 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
54 |
+
|
55 |
+
=======================================================================
|
56 |
+
|
57 |
+
Creative Commons Attribution-NonCommercial 4.0 International Public
|
58 |
+
License
|
59 |
+
|
60 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
61 |
+
to be bound by the terms and conditions of this Creative Commons
|
62 |
+
Attribution-NonCommercial 4.0 International Public License ("Public
|
63 |
+
License"). To the extent this Public License may be interpreted as a
|
64 |
+
contract, You are granted the Licensed Rights in consideration of Your
|
65 |
+
acceptance of these terms and conditions, and the Licensor grants You
|
66 |
+
such rights in consideration of benefits the Licensor receives from
|
67 |
+
making the Licensed Material available under these terms and
|
68 |
+
conditions.
|
69 |
+
|
70 |
+
|
71 |
+
Section 1 -- Definitions.
|
72 |
+
|
73 |
+
a. Adapted Material means material subject to Copyright and Similar
|
74 |
+
Rights that is derived from or based upon the Licensed Material
|
75 |
+
and in which the Licensed Material is translated, altered,
|
76 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
77 |
+
permission under the Copyright and Similar Rights held by the
|
78 |
+
Licensor. For purposes of this Public License, where the Licensed
|
79 |
+
Material is a musical work, performance, or sound recording,
|
80 |
+
Adapted Material is always produced where the Licensed Material is
|
81 |
+
synched in timed relation with a moving image.
|
82 |
+
|
83 |
+
b. Adapter's License means the license You apply to Your Copyright
|
84 |
+
and Similar Rights in Your contributions to Adapted Material in
|
85 |
+
accordance with the terms and conditions of this Public License.
|
86 |
+
|
87 |
+
c. Copyright and Similar Rights means copyright and/or similar rights
|
88 |
+
closely related to copyright including, without limitation,
|
89 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
90 |
+
Rights, without regard to how the rights are labeled or
|
91 |
+
categorized. For purposes of this Public License, the rights
|
92 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
93 |
+
Rights.
|
94 |
+
d. Effective Technological Measures means those measures that, in the
|
95 |
+
absence of proper authority, may not be circumvented under laws
|
96 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
97 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
98 |
+
agreements.
|
99 |
+
|
100 |
+
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
101 |
+
any other exception or limitation to Copyright and Similar Rights
|
102 |
+
that applies to Your use of the Licensed Material.
|
103 |
+
|
104 |
+
f. Licensed Material means the artistic or literary work, database,
|
105 |
+
or other material to which the Licensor applied this Public
|
106 |
+
License.
|
107 |
+
|
108 |
+
g. Licensed Rights means the rights granted to You subject to the
|
109 |
+
terms and conditions of this Public License, which are limited to
|
110 |
+
all Copyright and Similar Rights that apply to Your use of the
|
111 |
+
Licensed Material and that the Licensor has authority to license.
|
112 |
+
|
113 |
+
h. Licensor means the individual(s) or entity(ies) granting rights
|
114 |
+
under this Public License.
|
115 |
+
|
116 |
+
i. NonCommercial means not primarily intended for or directed towards
|
117 |
+
commercial advantage or monetary compensation. For purposes of
|
118 |
+
this Public License, the exchange of the Licensed Material for
|
119 |
+
other material subject to Copyright and Similar Rights by digital
|
120 |
+
file-sharing or similar means is NonCommercial provided there is
|
121 |
+
no payment of monetary compensation in connection with the
|
122 |
+
exchange.
|
123 |
+
|
124 |
+
j. Share means to provide material to the public by any means or
|
125 |
+
process that requires permission under the Licensed Rights, such
|
126 |
+
as reproduction, public display, public performance, distribution,
|
127 |
+
dissemination, communication, or importation, and to make material
|
128 |
+
available to the public including in ways that members of the
|
129 |
+
public may access the material from a place and at a time
|
130 |
+
individually chosen by them.
|
131 |
+
|
132 |
+
k. Sui Generis Database Rights means rights other than copyright
|
133 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
134 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
135 |
+
as amended and/or succeeded, as well as other essentially
|
136 |
+
equivalent rights anywhere in the world.
|
137 |
+
|
138 |
+
l. You means the individual or entity exercising the Licensed Rights
|
139 |
+
under this Public License. Your has a corresponding meaning.
|
140 |
+
|
141 |
+
|
142 |
+
Section 2 -- Scope.
|
143 |
+
|
144 |
+
a. License grant.
|
145 |
+
|
146 |
+
1. Subject to the terms and conditions of this Public License,
|
147 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
148 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
149 |
+
exercise the Licensed Rights in the Licensed Material to:
|
150 |
+
|
151 |
+
a. reproduce and Share the Licensed Material, in whole or
|
152 |
+
in part, for NonCommercial purposes only; and
|
153 |
+
|
154 |
+
b. produce, reproduce, and Share Adapted Material for
|
155 |
+
NonCommercial purposes only.
|
156 |
+
|
157 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
158 |
+
Exceptions and Limitations apply to Your use, this Public
|
159 |
+
License does not apply, and You do not need to comply with
|
160 |
+
its terms and conditions.
|
161 |
+
|
162 |
+
3. Term. The term of this Public License is specified in Section
|
163 |
+
6(a).
|
164 |
+
|
165 |
+
4. Media and formats; technical modifications allowed. The
|
166 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
167 |
+
all media and formats whether now known or hereafter created,
|
168 |
+
and to make technical modifications necessary to do so. The
|
169 |
+
Licensor waives and/or agrees not to assert any right or
|
170 |
+
authority to forbid You from making technical modifications
|
171 |
+
necessary to exercise the Licensed Rights, including
|
172 |
+
technical modifications necessary to circumvent Effective
|
173 |
+
Technological Measures. For purposes of this Public License,
|
174 |
+
simply making modifications authorized by this Section 2(a)
|
175 |
+
(4) never produces Adapted Material.
|
176 |
+
|
177 |
+
5. Downstream recipients.
|
178 |
+
|
179 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
180 |
+
recipient of the Licensed Material automatically
|
181 |
+
receives an offer from the Licensor to exercise the
|
182 |
+
Licensed Rights under the terms and conditions of this
|
183 |
+
Public License.
|
184 |
+
|
185 |
+
b. No downstream restrictions. You may not offer or impose
|
186 |
+
any additional or different terms or conditions on, or
|
187 |
+
apply any Effective Technological Measures to, the
|
188 |
+
Licensed Material if doing so restricts exercise of the
|
189 |
+
Licensed Rights by any recipient of the Licensed
|
190 |
+
Material.
|
191 |
+
|
192 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
193 |
+
may be construed as permission to assert or imply that You
|
194 |
+
are, or that Your use of the Licensed Material is, connected
|
195 |
+
with, or sponsored, endorsed, or granted official status by,
|
196 |
+
the Licensor or others designated to receive attribution as
|
197 |
+
provided in Section 3(a)(1)(A)(i).
|
198 |
+
|
199 |
+
b. Other rights.
|
200 |
+
|
201 |
+
1. Moral rights, such as the right of integrity, are not
|
202 |
+
licensed under this Public License, nor are publicity,
|
203 |
+
privacy, and/or other similar personality rights; however, to
|
204 |
+
the extent possible, the Licensor waives and/or agrees not to
|
205 |
+
assert any such rights held by the Licensor to the limited
|
206 |
+
extent necessary to allow You to exercise the Licensed
|
207 |
+
Rights, but not otherwise.
|
208 |
+
|
209 |
+
2. Patent and trademark rights are not licensed under this
|
210 |
+
Public License.
|
211 |
+
|
212 |
+
3. To the extent possible, the Licensor waives any right to
|
213 |
+
collect royalties from You for the exercise of the Licensed
|
214 |
+
Rights, whether directly or through a collecting society
|
215 |
+
under any voluntary or waivable statutory or compulsory
|
216 |
+
licensing scheme. In all other cases the Licensor expressly
|
217 |
+
reserves any right to collect such royalties, including when
|
218 |
+
the Licensed Material is used other than for NonCommercial
|
219 |
+
purposes.
|
220 |
+
|
221 |
+
|
222 |
+
Section 3 -- License Conditions.
|
223 |
+
|
224 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
225 |
+
following conditions.
|
226 |
+
|
227 |
+
a. Attribution.
|
228 |
+
|
229 |
+
1. If You Share the Licensed Material (including in modified
|
230 |
+
form), You must:
|
231 |
+
|
232 |
+
a. retain the following if it is supplied by the Licensor
|
233 |
+
with the Licensed Material:
|
234 |
+
|
235 |
+
i. identification of the creator(s) of the Licensed
|
236 |
+
Material and any others designated to receive
|
237 |
+
attribution, in any reasonable manner requested by
|
238 |
+
the Licensor (including by pseudonym if
|
239 |
+
designated);
|
240 |
+
|
241 |
+
ii. a copyright notice;
|
242 |
+
|
243 |
+
iii. a notice that refers to this Public License;
|
244 |
+
|
245 |
+
iv. a notice that refers to the disclaimer of
|
246 |
+
warranties;
|
247 |
+
|
248 |
+
v. a URI or hyperlink to the Licensed Material to the
|
249 |
+
extent reasonably practicable;
|
250 |
+
|
251 |
+
b. indicate if You modified the Licensed Material and
|
252 |
+
retain an indication of any previous modifications; and
|
253 |
+
|
254 |
+
c. indicate the Licensed Material is licensed under this
|
255 |
+
Public License, and include the text of, or the URI or
|
256 |
+
hyperlink to, this Public License.
|
257 |
+
|
258 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
259 |
+
reasonable manner based on the medium, means, and context in
|
260 |
+
which You Share the Licensed Material. For example, it may be
|
261 |
+
reasonable to satisfy the conditions by providing a URI or
|
262 |
+
hyperlink to a resource that includes the required
|
263 |
+
information.
|
264 |
+
|
265 |
+
3. If requested by the Licensor, You must remove any of the
|
266 |
+
information required by Section 3(a)(1)(A) to the extent
|
267 |
+
reasonably practicable.
|
268 |
+
|
269 |
+
4. If You Share Adapted Material You produce, the Adapter's
|
270 |
+
License You apply must not prevent recipients of the Adapted
|
271 |
+
Material from complying with this Public License.
|
272 |
+
|
273 |
+
|
274 |
+
Section 4 -- Sui Generis Database Rights.
|
275 |
+
|
276 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
277 |
+
apply to Your use of the Licensed Material:
|
278 |
+
|
279 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
280 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
281 |
+
portion of the contents of the database for NonCommercial purposes
|
282 |
+
only;
|
283 |
+
|
284 |
+
b. if You include all or a substantial portion of the database
|
285 |
+
contents in a database in which You have Sui Generis Database
|
286 |
+
Rights, then the database in which You have Sui Generis Database
|
287 |
+
Rights (but not its individual contents) is Adapted Material; and
|
288 |
+
|
289 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
290 |
+
all or a substantial portion of the contents of the database.
|
291 |
+
|
292 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
293 |
+
replace Your obligations under this Public License where the Licensed
|
294 |
+
Rights include other Copyright and Similar Rights.
|
295 |
+
|
296 |
+
|
297 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
298 |
+
|
299 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
300 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
301 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
302 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
303 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
304 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
305 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
306 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
307 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
308 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
309 |
+
|
310 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
311 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
312 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
313 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
314 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
315 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
316 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
317 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
318 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
319 |
+
|
320 |
+
c. The disclaimer of warranties and limitation of liability provided
|
321 |
+
above shall be interpreted in a manner that, to the extent
|
322 |
+
possible, most closely approximates an absolute disclaimer and
|
323 |
+
waiver of all liability.
|
324 |
+
|
325 |
+
|
326 |
+
Section 6 -- Term and Termination.
|
327 |
+
|
328 |
+
a. This Public License applies for the term of the Copyright and
|
329 |
+
Similar Rights licensed here. However, if You fail to comply with
|
330 |
+
this Public License, then Your rights under this Public License
|
331 |
+
terminate automatically.
|
332 |
+
|
333 |
+
b. Where Your right to use the Licensed Material has terminated under
|
334 |
+
Section 6(a), it reinstates:
|
335 |
+
|
336 |
+
1. automatically as of the date the violation is cured, provided
|
337 |
+
it is cured within 30 days of Your discovery of the
|
338 |
+
violation; or
|
339 |
+
|
340 |
+
2. upon express reinstatement by the Licensor.
|
341 |
+
|
342 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
343 |
+
right the Licensor may have to seek remedies for Your violations
|
344 |
+
of this Public License.
|
345 |
+
|
346 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
347 |
+
Licensed Material under separate terms or conditions or stop
|
348 |
+
distributing the Licensed Material at any time; however, doing so
|
349 |
+
will not terminate this Public License.
|
350 |
+
|
351 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
352 |
+
License.
|
353 |
+
|
354 |
+
|
355 |
+
Section 7 -- Other Terms and Conditions.
|
356 |
+
|
357 |
+
a. The Licensor shall not be bound by any additional or different
|
358 |
+
terms or conditions communicated by You unless expressly agreed.
|
359 |
+
|
360 |
+
b. Any arrangements, understandings, or agreements regarding the
|
361 |
+
Licensed Material not stated herein are separate from and
|
362 |
+
independent of the terms and conditions of this Public License.
|
363 |
+
|
364 |
+
|
365 |
+
Section 8 -- Interpretation.
|
366 |
+
|
367 |
+
a. For the avoidance of doubt, this Public License does not, and
|
368 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
369 |
+
conditions on any use of the Licensed Material that could lawfully
|
370 |
+
be made without permission under this Public License.
|
371 |
+
|
372 |
+
b. To the extent possible, if any provision of this Public License is
|
373 |
+
deemed unenforceable, it shall be automatically reformed to the
|
374 |
+
minimum extent necessary to make it enforceable. If the provision
|
375 |
+
cannot be reformed, it shall be severed from this Public License
|
376 |
+
without affecting the enforceability of the remaining terms and
|
377 |
+
conditions.
|
378 |
+
|
379 |
+
c. No term or condition of this Public License will be waived and no
|
380 |
+
failure to comply consented to unless expressly agreed to by the
|
381 |
+
Licensor.
|
382 |
+
|
383 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
384 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
385 |
+
that apply to the Licensor or You, including from the legal
|
386 |
+
processes of any jurisdiction or authority.
|
387 |
+
|
388 |
+
=======================================================================
|
389 |
+
|
390 |
+
Creative Commons is not a party to its public
|
391 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
392 |
+
its public licenses to material it publishes and in those instances
|
393 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
394 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
395 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
396 |
+
material is shared under a Creative Commons public license or as
|
397 |
+
otherwise permitted by the Creative Commons policies published at
|
398 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
399 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
400 |
+
of Creative Commons without its prior written consent including,
|
401 |
+
without limitation, in connection with any unauthorized modifications
|
402 |
+
to any of its public licenses or any other arrangements,
|
403 |
+
understandings, or agreements concerning use of licensed material. For
|
404 |
+
the avoidance of doubt, this paragraph does not form part of the
|
405 |
+
public licenses.
|
406 |
+
|
407 |
+
Creative Commons may be contacted at creativecommons.org.
|
{abc → ChatTTS}/README.md
RENAMED
@@ -1,53 +1,124 @@
|
|
|
|
|
|
|
|
|
|
1 |
# ChatTTS
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
---
|
9 |
-
## Highlights
|
10 |
1. **Conversational TTS**: ChatTTS is optimized for dialogue-based tasks, enabling natural and expressive speech synthesis. It supports multiple speakers, facilitating interactive conversations.
|
11 |
2. **Fine-grained Control**: The model could predict and control fine-grained prosodic features, including laughter, pauses, and interjections.
|
12 |
3. **Better Prosody**: ChatTTS surpasses most of open-source TTS models in terms of prosody. We provide pretrained models to support further research and development.
|
13 |
|
14 |
-
|
|
|
|
|
15 |
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
-
|
|
|
|
|
19 |
|
20 |
-
|
21 |
|
22 |
ChatTTS is a powerful text-to-speech system. However, it is very important to utilize this technology responsibly and ethically. To limit the use of ChatTTS, we added a small amount of high-frequency noise during the training of the 40,000-hour model, and compressed the audio quality as much as possible using MP3 format, to prevent malicious actors from potentially using it for criminal purposes. At the same time, we have internally trained a detection model and plan to open-source it in the future.
|
23 |
|
|
|
|
|
24 |
|
25 |
-
|
26 |
-
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
```python
|
31 |
import ChatTTS
|
32 |
from IPython.display import Audio
|
|
|
33 |
|
34 |
chat = ChatTTS.Chat()
|
35 |
-
chat.load_models()
|
36 |
|
37 |
-
texts = ["
|
38 |
|
39 |
-
wavs = chat.infer(texts,
|
40 |
-
|
|
|
41 |
```
|
42 |
|
43 |
-
|
44 |
|
45 |
```python
|
46 |
###################################
|
47 |
# Sample a speaker from Gaussian.
|
48 |
-
|
49 |
-
|
50 |
-
rand_spk = torch.randn(768) * std + mean
|
51 |
|
52 |
params_infer_code = {
|
53 |
'spk_emb': rand_spk, # add sampled speaker
|
@@ -65,13 +136,13 @@ params_refine_text = {
|
|
65 |
'prompt': '[oral_2][laugh_0][break_6]'
|
66 |
}
|
67 |
|
68 |
-
|
69 |
|
70 |
###################################
|
71 |
# For word level manual control.
|
72 |
text = 'What is [uv_break]your favorite english food?[laugh][lbreak]'
|
73 |
-
|
74 |
-
|
75 |
```
|
76 |
|
77 |
<details open>
|
@@ -90,42 +161,44 @@ capabilities with precise control over prosodic elements [laugh]like like
|
|
90 |
params_refine_text = {
|
91 |
'prompt': '[oral_2][laugh_0][break_4]'
|
92 |
}
|
93 |
-
audio_array_cn = chat.infer(inputs_cn, params_refine_text=params_refine_text)
|
94 |
audio_array_en = chat.infer(inputs_en, params_refine_text=params_refine_text)
|
|
|
95 |
```
|
96 |
[male speaker](https://github.com/2noise/ChatTTS/assets/130631963/e0f51251-db7f-4d39-a0e9-3e095bb65de1)
|
97 |
|
98 |
[female speaker](https://github.com/2noise/ChatTTS/assets/130631963/f5dcdd01-1091-47c5-8241-c4f6aaaa8bbd)
|
99 |
</details>
|
100 |
|
101 |
-
---
|
102 |
-
## Roadmap
|
103 |
-
- [x] Open-source the 40k hour base model and spk_stats file
|
104 |
-
- [ ] Open-source VQ encoder and Lora training code
|
105 |
-
- [ ] Streaming audio generation without refining the text*
|
106 |
-
- [ ] Open-source the 40k hour version with multi-emotion control
|
107 |
-
- [ ] ChatTTS.cpp maybe? (PR or new repo are welcomed.)
|
108 |
-
|
109 |
-
----
|
110 |
## FAQ
|
111 |
|
112 |
-
|
113 |
-
For a 30-second audio clip, at least 4GB of GPU memory is required. For the
|
114 |
|
115 |
-
|
116 |
|
117 |
-
This is a problem that typically occurs with autoregressive models(for bark and valle). It's generally difficult to avoid. One can try multiple samples to find a suitable result.
|
118 |
|
119 |
-
|
120 |
|
121 |
-
In the current released model, the only token-level control units are [laugh]
|
122 |
|
123 |
-
---
|
124 |
## Acknowledgements
|
125 |
-
- [bark](https://github.com/suno-ai/bark), [XTTSv2](https://github.com/coqui-ai/TTS) and [valle](https://arxiv.org/abs/2301.02111) demostrate a remarkable TTS result by
|
126 |
- [fish-speech](https://github.com/fishaudio/fish-speech) reveals capability of GVQ as audio tokenizer for LLM modeling.
|
127 |
- [vocos](https://github.com/gemelo-ai/vocos) which is used as a pretrained vocoder.
|
128 |
|
129 |
-
---
|
130 |
## Special Appreciation
|
131 |
- [wlu-audio lab](https://audio.westlake.edu.cn/) for early algorithm experiments.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<div align="center">
|
2 |
+
|
3 |
+
<a href="https://trendshift.io/repositories/10489" target="_blank"><img src="https://trendshift.io/api/badge/repositories/10489" alt="2noise%2FChatTTS | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
4 |
+
|
5 |
# ChatTTS
|
6 |
+
A generative speech model for daily dialogue.
|
7 |
+
|
8 |
+
[![Licence](https://img.shields.io/badge/LICENSE-CC%20BY--NC%204.0-green.svg?style=for-the-badge)](https://github.com/2noise/ChatTTS/blob/main/LICENSE)
|
9 |
+
|
10 |
+
[![Huggingface](https://img.shields.io/badge/🤗%20-Models-yellow.svg?style=for-the-badge)](https://huggingface.co/2Noise/ChatTTS)
|
11 |
+
[![Open In Colab](https://img.shields.io/badge/Colab-F9AB00?style=for-the-badge&logo=googlecolab&color=525252)](https://colab.research.google.com/github/2noise/ChatTTS/blob/main/examples/ipynb/colab.ipynb)
|
12 |
+
|
13 |
+
**English** | [**简体中文**](docs/cn/README.md) | [**日本語**](docs/jp/README.md) | [**Русский**](docs/ru/README.md)
|
14 |
|
15 |
+
</div>
|
16 |
|
17 |
+
## Introduction
|
18 |
+
ChatTTS is a text-to-speech model designed specifically for dialogue scenarios such as LLM assistant.
|
19 |
+
|
20 |
+
### Supported Languages
|
21 |
+
- [x] English
|
22 |
+
- [x] Chinese
|
23 |
+
- [ ] Coming Soon...
|
24 |
+
|
25 |
+
### Highlights
|
26 |
+
> You can refer to **[this video on Bilibili](https://www.bilibili.com/video/BV1zn4y1o7iV)** for the detailed description.
|
27 |
|
|
|
|
|
28 |
1. **Conversational TTS**: ChatTTS is optimized for dialogue-based tasks, enabling natural and expressive speech synthesis. It supports multiple speakers, facilitating interactive conversations.
|
29 |
2. **Fine-grained Control**: The model could predict and control fine-grained prosodic features, including laughter, pauses, and interjections.
|
30 |
3. **Better Prosody**: ChatTTS surpasses most of open-source TTS models in terms of prosody. We provide pretrained models to support further research and development.
|
31 |
|
32 |
+
### Dataset & Model
|
33 |
+
- The main model is trained with Chinese and English audio data of 100,000+ hours.
|
34 |
+
- The open-source version on **[HuggingFace](https://huggingface.co/2Noise/ChatTTS)** is a 40,000 hours pre-trained model without SFT.
|
35 |
|
36 |
+
### Roadmap
|
37 |
+
- [x] Open-source the 40k hour base model and spk_stats file
|
38 |
+
- [ ] Open-source VQ encoder and Lora training code
|
39 |
+
- [ ] Streaming audio generation without refining the text*
|
40 |
+
- [ ] Open-source the 40k hour version with multi-emotion control
|
41 |
+
- [ ] ChatTTS.cpp maybe? (PR or new repo are welcomed.)
|
42 |
|
43 |
+
### Disclaimer
|
44 |
+
> [!Important]
|
45 |
+
> This repo is for academic purposes only.
|
46 |
|
47 |
+
It is intended for educational and research use, and should not be used for any commercial or legal purposes. The authors do not guarantee the accuracy, completeness, or reliability of the information. The information and data used in this repo, are for academic and research purposes only. The data obtained from publicly available sources, and the authors do not claim any ownership or copyright over the data.
|
48 |
|
49 |
ChatTTS is a powerful text-to-speech system. However, it is very important to utilize this technology responsibly and ethically. To limit the use of ChatTTS, we added a small amount of high-frequency noise during the training of the 40,000-hour model, and compressed the audio quality as much as possible using MP3 format, to prevent malicious actors from potentially using it for criminal purposes. At the same time, we have internally trained a detection model and plan to open-source it in the future.
|
50 |
|
51 |
+
### Contact
|
52 |
+
> GitHub issues/PRs are always welcomed.
|
53 |
|
54 |
+
#### Formal Inquiries
|
55 |
+
For formal inquiries about the model and roadmap, please contact us at **[email protected]**.
|
56 |
|
57 |
+
#### Online Chat
|
58 |
+
##### 1. QQ Group (Chinese Social APP)
|
59 |
+
- **Group 1**, 808364215 (Full)
|
60 |
+
- **Group 2**, 230696694 (Full)
|
61 |
+
- **Group 3**, 933639842
|
62 |
+
|
63 |
+
## Installation (WIP)
|
64 |
+
> Will be uploaded to pypi soon according to https://github.com/2noise/ChatTTS/issues/269
|
65 |
+
#### 1. Install Directly
|
66 |
+
```bash
|
67 |
+
pip install git+https://github.com/2noise/ChatTTS
|
68 |
+
```
|
69 |
+
|
70 |
+
#### 2. Install from conda
|
71 |
+
```bash
|
72 |
+
git clone https://github.com/2noise/ChatTTS
|
73 |
+
cd ChatTTS
|
74 |
+
conda create -n chattts
|
75 |
+
conda activate chattts
|
76 |
+
pip install -r requirements.txt
|
77 |
+
```
|
78 |
+
|
79 |
+
## Get Started
|
80 |
+
### Install requirements
|
81 |
+
```bash
|
82 |
+
pip install --upgrade -r requirements.txt
|
83 |
+
```
|
84 |
+
|
85 |
+
### Quick Start
|
86 |
+
#### 1. Launch WebUI
|
87 |
+
```bash
|
88 |
+
python examples/web/webui.py
|
89 |
+
```
|
90 |
+
|
91 |
+
#### 2. Infer by Command Line
|
92 |
+
> It will save audio to `./output_audio_xxx.wav`
|
93 |
+
|
94 |
+
```bash
|
95 |
+
python examples/cmd/run.py "Please input your text."
|
96 |
+
```
|
97 |
+
|
98 |
+
### Basic
|
99 |
|
100 |
```python
|
101 |
import ChatTTS
|
102 |
from IPython.display import Audio
|
103 |
+
import torchaudio
|
104 |
|
105 |
chat = ChatTTS.Chat()
|
106 |
+
chat.load_models(compile=False) # Set to True for better performance
|
107 |
|
108 |
+
texts = ["PUT YOUR TEXT HERE",]
|
109 |
|
110 |
+
wavs = chat.infer(texts, )
|
111 |
+
|
112 |
+
torchaudio.save("output1.wav", torch.from_numpy(wavs[0]), 24000)
|
113 |
```
|
114 |
|
115 |
+
### Advanced
|
116 |
|
117 |
```python
|
118 |
###################################
|
119 |
# Sample a speaker from Gaussian.
|
120 |
+
|
121 |
+
rand_spk = chat.sample_random_speaker()
|
|
|
122 |
|
123 |
params_infer_code = {
|
124 |
'spk_emb': rand_spk, # add sampled speaker
|
|
|
136 |
'prompt': '[oral_2][laugh_0][break_6]'
|
137 |
}
|
138 |
|
139 |
+
wavs = chat.infer(texts, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
|
140 |
|
141 |
###################################
|
142 |
# For word level manual control.
|
143 |
text = 'What is [uv_break]your favorite english food?[laugh][lbreak]'
|
144 |
+
wavs = chat.infer(text, skip_refine_text=True, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
|
145 |
+
torchaudio.save("output2.wav", torch.from_numpy(wavs[0]), 24000)
|
146 |
```
|
147 |
|
148 |
<details open>
|
|
|
161 |
params_refine_text = {
|
162 |
'prompt': '[oral_2][laugh_0][break_4]'
|
163 |
}
|
164 |
+
# audio_array_cn = chat.infer(inputs_cn, params_refine_text=params_refine_text)
|
165 |
audio_array_en = chat.infer(inputs_en, params_refine_text=params_refine_text)
|
166 |
+
torchaudio.save("output3.wav", torch.from_numpy(audio_array_en[0]), 24000)
|
167 |
```
|
168 |
[male speaker](https://github.com/2noise/ChatTTS/assets/130631963/e0f51251-db7f-4d39-a0e9-3e095bb65de1)
|
169 |
|
170 |
[female speaker](https://github.com/2noise/ChatTTS/assets/130631963/f5dcdd01-1091-47c5-8241-c4f6aaaa8bbd)
|
171 |
</details>
|
172 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
173 |
## FAQ
|
174 |
|
175 |
+
#### 1. How much VRAM do I need? How about infer speed?
|
176 |
+
For a 30-second audio clip, at least 4GB of GPU memory is required. For the 4090 GPU, it can generate audio corresponding to approximately 7 semantic tokens per second. The Real-Time Factor (RTF) is around 0.3.
|
177 |
|
178 |
+
#### 2. Model stability is not good enough, with issues such as multi speakers or poor audio quality.
|
179 |
|
180 |
+
This is a problem that typically occurs with autoregressive models (for bark and valle). It's generally difficult to avoid. One can try multiple samples to find a suitable result.
|
181 |
|
182 |
+
#### 3. Besides laughter, can we control anything else? Can we control other emotions?
|
183 |
|
184 |
+
In the current released model, the only token-level control units are `[laugh]`, `[uv_break]`, and `[lbreak]`. In future versions, we may open-source models with additional emotional control capabilities.
|
185 |
|
|
|
186 |
## Acknowledgements
|
187 |
+
- [bark](https://github.com/suno-ai/bark), [XTTSv2](https://github.com/coqui-ai/TTS) and [valle](https://arxiv.org/abs/2301.02111) demostrate a remarkable TTS result by an autoregressive-style system.
|
188 |
- [fish-speech](https://github.com/fishaudio/fish-speech) reveals capability of GVQ as audio tokenizer for LLM modeling.
|
189 |
- [vocos](https://github.com/gemelo-ai/vocos) which is used as a pretrained vocoder.
|
190 |
|
|
|
191 |
## Special Appreciation
|
192 |
- [wlu-audio lab](https://audio.westlake.edu.cn/) for early algorithm experiments.
|
193 |
+
|
194 |
+
## Related Resources
|
195 |
+
- [Awesome-ChatTTS](https://github.com/libukai/Awesome-ChatTTS)
|
196 |
+
|
197 |
+
## Thanks to all contributors for their efforts
|
198 |
+
[![contributors](https://contrib.rocks/image?repo=2noise/ChatTTS)](https://github.com/2noise/ChatTTS/graphs/contributors)
|
199 |
+
|
200 |
+
<div align="center">
|
201 |
+
|
202 |
+
![counter](https://counter.seku.su/cmoe?name=chattts&theme=mbs)
|
203 |
+
|
204 |
+
</div>
|
ChatTTS/docs/cn/README.md
ADDED
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<div align="center">
|
2 |
+
|
3 |
+
<a href="https://trendshift.io/repositories/10489" target="_blank"><img src="https://trendshift.io/api/badge/repositories/10489" alt="2noise%2FChatTTS | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
4 |
+
|
5 |
+
# ChatTTS
|
6 |
+
一款用于日常对话的生成式语音模型。
|
7 |
+
|
8 |
+
[![Licence](https://img.shields.io/badge/LICENSE-CC%20BY--NC%204.0-green.svg?style=for-the-badge)](https://github.com/2noise/ChatTTS/blob/main/LICENSE)
|
9 |
+
|
10 |
+
[![Huggingface](https://img.shields.io/badge/🤗%20-Models-yellow.svg?style=for-the-badge)](https://huggingface.co/2Noise/ChatTTS)
|
11 |
+
[![Open In Colab](https://img.shields.io/badge/Colab-F9AB00?style=for-the-badge&logo=googlecolab&color=525252)](https://colab.research.google.com/github/2noise/ChatTTS/blob/main/examples/ipynb/colab.ipynb)
|
12 |
+
|
13 |
+
[**English**](../../README.md) | **简体中文** | [**日本語**](../jp/README.md) | [**Русский**](../ru/README.md)
|
14 |
+
|
15 |
+
</div>
|
16 |
+
|
17 |
+
## 简介
|
18 |
+
|
19 |
+
ChatTTS 是一款专门为对话场景(例如 LLM 助手)设计的文本转语音模型。
|
20 |
+
|
21 |
+
### 支持的语种
|
22 |
+
|
23 |
+
- [x] 英语
|
24 |
+
- [x] 中文
|
25 |
+
- [ ] 敬请期待...
|
26 |
+
|
27 |
+
### 亮点
|
28 |
+
|
29 |
+
> 你可以参考 **[Bilibili](https://www.bilibili.com/video/BV1zn4y1o7iV)** 上的这个视频了解详细的介绍.
|
30 |
+
|
31 |
+
1. **对话式 TTS**: ChatTTS 针对对话式任务进行了优化,能够实现自然且富有表现力的合成语音。它支持多个说话者,便于生成互动式对话。
|
32 |
+
2. **精细的控制**: 该模型可以预测和控制精细的韵律特征,包括笑声、停顿和插入语。
|
33 |
+
3. **更好的韵律**: ChatTTS 在韵律方面超越了大多数开源 TTS 模型。我们提供预训练模型以支持进一步的研究和开发。
|
34 |
+
|
35 |
+
### 数据集和模型
|
36 |
+
|
37 |
+
- 主要模型使用 100,000+ 小时的中文和英文音频数据进行训练。
|
38 |
+
- **[HuggingFace](https://huggingface.co/2Noise/ChatTTS)** 上的开源版本是一个在 40,000 小时数据上进行无监督微调的预训练模型。。
|
39 |
+
|
40 |
+
### 路线图
|
41 |
+
|
42 |
+
- [x] 开源 4 万小时基础模型和 spk_stats 文件
|
43 |
+
- [ ] 开源 VQ 编码器和 Lora 训练代码
|
44 |
+
- [ ] 无需细化文本即可进行流式音频生成
|
45 |
+
- [ ] 开源具有多情感控制功能的 4 万小时版本
|
46 |
+
- [ ] 也许会有 ChatTTS.cpp ?(欢迎 PR 或新建仓库)
|
47 |
+
|
48 |
+
### 免责声明
|
49 |
+
|
50 |
+
> [!Important]
|
51 |
+
> 此仓库仅供学术用途。
|
52 |
+
|
53 |
+
本项目旨在用于教育和研究目的,不应用于任何商业或法律目的。作者不保证信息的准确性、完整性或可靠性。此仓库中使用的信息和数据仅供学术和研究目的。数据来自公开来源,作者不声称对数据拥有任何所有权或版权。
|
54 |
+
|
55 |
+
ChatTTS 是一款强大的文本转语音系统。但是,负责任和道德地使用这项技术非常重要。为了限制 ChatTTS 的使用,我们在 40,000 小时模型的训练过程中添加了少量高频噪声,并使用 MP3 格式尽可能压缩音频质量,以防止恶意行为者将其用于犯罪目的。同时,我们内部训练了一个检测模型,并计划在未来开源它。
|
56 |
+
|
57 |
+
### 联系方式
|
58 |
+
|
59 |
+
> 欢迎随时提交 GitHub issues/PRs。
|
60 |
+
|
61 |
+
#### 合作洽谈
|
62 |
+
|
63 |
+
如就模型和路线图进行合作洽谈,请发送邮件至 **[email protected]**。
|
64 |
+
|
65 |
+
#### 线上讨论
|
66 |
+
|
67 |
+
##### 1. 官方 QQ 群
|
68 |
+
|
69 |
+
- **群 1**, 808364215 (已满)
|
70 |
+
- **群 2**, 230696694 (已满)
|
71 |
+
- **群 3**, 933639842
|
72 |
+
|
73 |
+
## 安装教程 (丰富中)
|
74 |
+
|
75 |
+
> 将在近期上传至 pypi,详情请查看 https://github.com/2noise/ChatTTS/issues/269 上的讨论。
|
76 |
+
|
77 |
+
#### 1. 使用源代码安装
|
78 |
+
|
79 |
+
```bash
|
80 |
+
pip install git+https://github.com/2noise/ChatTTS
|
81 |
+
```
|
82 |
+
|
83 |
+
#### 2. 使用 conda 安装
|
84 |
+
|
85 |
+
```bash
|
86 |
+
git clone https://github.com/2noise/ChatTTS
|
87 |
+
cd ChatTTS
|
88 |
+
conda create -n chattts
|
89 |
+
conda activate chattts
|
90 |
+
pip install -r requirements.txt
|
91 |
+
```
|
92 |
+
|
93 |
+
## 使用教程
|
94 |
+
|
95 |
+
### 安装依赖
|
96 |
+
|
97 |
+
```bash
|
98 |
+
pip install --upgrade -r requirements.txt
|
99 |
+
```
|
100 |
+
|
101 |
+
### 快速开始
|
102 |
+
|
103 |
+
#### 1. 启动 WebUI
|
104 |
+
|
105 |
+
```bash
|
106 |
+
python examples/web/webui.py
|
107 |
+
```
|
108 |
+
|
109 |
+
#### 2. 使用命令行
|
110 |
+
|
111 |
+
> 生成的音频将保存至 `./output_audio_xxx.wav`
|
112 |
+
|
113 |
+
```bash
|
114 |
+
python examples/cmd/run.py "Please input your text."
|
115 |
+
```
|
116 |
+
|
117 |
+
### 基础用法
|
118 |
+
|
119 |
+
```python
|
120 |
+
import ChatTTS
|
121 |
+
from IPython.display import Audio
|
122 |
+
import torchaudio
|
123 |
+
|
124 |
+
chat = ChatTTS.Chat()
|
125 |
+
chat.load_models(compile=False) # Set to True for better performance
|
126 |
+
|
127 |
+
texts = ["PUT YOUR TEXT HERE",]
|
128 |
+
|
129 |
+
wavs = chat.infer(texts, )
|
130 |
+
|
131 |
+
torchaudio.save("output1.wav", torch.from_numpy(wavs[0]), 24000)
|
132 |
+
```
|
133 |
+
|
134 |
+
### 高级用法
|
135 |
+
|
136 |
+
```python
|
137 |
+
###################################
|
138 |
+
# Sample a speaker from Gaussian.
|
139 |
+
|
140 |
+
rand_spk = chat.sample_random_speaker()
|
141 |
+
|
142 |
+
params_infer_code = {
|
143 |
+
'spk_emb': rand_spk, # add sampled speaker
|
144 |
+
'temperature': .3, # using custom temperature
|
145 |
+
'top_P': 0.7, # top P decode
|
146 |
+
'top_K': 20, # top K decode
|
147 |
+
}
|
148 |
+
|
149 |
+
###################################
|
150 |
+
# For sentence level manual control.
|
151 |
+
|
152 |
+
# use oral_(0-9), laugh_(0-2), break_(0-7)
|
153 |
+
# to generate special token in text to synthesize.
|
154 |
+
params_refine_text = {
|
155 |
+
'prompt': '[oral_2][laugh_0][break_6]'
|
156 |
+
}
|
157 |
+
|
158 |
+
wavs = chat.infer(texts, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
|
159 |
+
|
160 |
+
###################################
|
161 |
+
# For word level manual control.
|
162 |
+
text = 'What is [uv_break]your favorite english food?[laugh][lbreak]'
|
163 |
+
wavs = chat.infer(text, skip_refine_text=True, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
|
164 |
+
torchaudio.save("output2.wav", torch.from_numpy(wavs[0]), 24000)
|
165 |
+
```
|
166 |
+
|
167 |
+
<details open>
|
168 |
+
<summary><h4>示例: 自我介绍</h4></summary>
|
169 |
+
|
170 |
+
```python
|
171 |
+
inputs_en = """
|
172 |
+
chat T T S is a text to speech model designed for dialogue applications.
|
173 |
+
[uv_break]it supports mixed language input [uv_break]and offers multi speaker
|
174 |
+
capabilities with precise control over prosodic elements [laugh]like like
|
175 |
+
[uv_break]laughter[laugh], [uv_break]pauses, [uv_break]and intonation.
|
176 |
+
[uv_break]it delivers natural and expressive speech,[uv_break]so please
|
177 |
+
[uv_break] use the project responsibly at your own risk.[uv_break]
|
178 |
+
""".replace('\n', '') # English is still experimental.
|
179 |
+
|
180 |
+
params_refine_text = {
|
181 |
+
'prompt': '[oral_2][laugh_0][break_4]'
|
182 |
+
}
|
183 |
+
# audio_array_cn = chat.infer(inputs_cn, params_refine_text=params_refine_text)
|
184 |
+
audio_array_en = chat.infer(inputs_en, params_refine_text=params_refine_text)
|
185 |
+
torchaudio.save("output3.wav", torch.from_numpy(audio_array_en[0]), 24000)
|
186 |
+
```
|
187 |
+
|
188 |
+
[男性音色](https://github.com/2noise/ChatTTS/assets/130631963/e0f51251-db7f-4d39-a0e9-3e095bb65de1)
|
189 |
+
|
190 |
+
[女性音色](https://github.com/2noise/ChatTTS/assets/130631963/f5dcdd01-1091-47c5-8241-c4f6aaaa8bbd)
|
191 |
+
|
192 |
+
</details>
|
193 |
+
|
194 |
+
## 常见问题
|
195 |
+
|
196 |
+
#### 1. 我需要多少 VRAM? 推理速度如何?
|
197 |
+
|
198 |
+
对于 30 秒的音频片段,至少需要 4GB 的 GPU 内存。 对于 4090 GPU,它可以每秒生成大约 7 个语义 token 对应的音频。实时因子 (RTF) 约为 0.3。
|
199 |
+
|
200 |
+
#### 2. 模型稳定性不够好,存在多个说话者或音频质量差等问题。
|
201 |
+
|
202 |
+
这是一个通常发生在自回归模型(例如 bark 和 valle)中的问题,通常很难避免。可以尝试多个样本以找到合适的结果。
|
203 |
+
|
204 |
+
#### 3. 除了笑声,我们还能控制其他东西吗?我们能控制其他情绪吗?
|
205 |
+
|
206 |
+
在当前发布的模型中,可用的 token 级控制单元是 `[laugh]`, `[uv_break]` 和 `[lbreak]`。未来的版本中,我们可能会开源具有更多情绪控制功能的模型。
|
207 |
+
|
208 |
+
## 致谢
|
209 |
+
|
210 |
+
- [bark](https://github.com/suno-ai/bark), [XTTSv2](https://github.com/coqui-ai/TTS) 和 [valle](https://arxiv.org/abs/2301.02111) 通过自回归式系统展示了非凡的 TTS 效果。
|
211 |
+
- [fish-speech](https://github.com/fishaudio/fish-speech) 揭示了 GVQ 作为 LLM 建模的音频分词器的能力。
|
212 |
+
- [vocos](https://github.com/gemelo-ai/vocos) vocos 被用作预训练声码器。
|
213 |
+
|
214 |
+
## 特别鸣谢
|
215 |
+
|
216 |
+
- [wlu-audio lab](https://audio.westlake.edu.cn/) 对于早期算法实验的支持。
|
217 |
+
|
218 |
+
## 相关资源
|
219 |
+
|
220 |
+
- [Awesome-ChatTTS](https://github.com/libukai/Awesome-ChatTTS) 一个 ChatTTS 的资源汇总列表。
|
221 |
+
|
222 |
+
## 感谢所有贡献者的付出
|
223 |
+
|
224 |
+
[![contributors](https://contrib.rocks/image?repo=2noise/ChatTTS)](https://github.com/2noise/ChatTTS/graphs/contributors)
|
225 |
+
|
226 |
+
## Star 趋势
|
227 |
+
|
228 |
+
[![Star History Chart](https://api.star-history.com/svg?repos=2noise/ChatTTS&type=Date)](https://star-history.com/#2noise/ChatTTS&Date)
|
ChatTTS/docs/jp/README.md
ADDED
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ChatTTS
|
2 |
+
> [!NOTE]
|
3 |
+
> 以下の内容は最新情報ではない可能性がありますのでご了承ください。全ての内容は英語版に基準することになります。
|
4 |
+
|
5 |
+
[![Huggingface](https://img.shields.io/badge/🤗%20-Models-yellow.svg?style=for-the-badge)](https://huggingface.co/2Noise/ChatTTS)
|
6 |
+
|
7 |
+
[**English**](../../README.md) | [**简体中文**](../cn/README.md) | **日本語** | [**Русский**](../ru/README.md)
|
8 |
+
|
9 |
+
ChatTTSは、LLMアシスタントなどの対話シナリオ用に特別に設計されたテキストから音声へのモデルです。英語と中国語の両方をサポートしています。私たちのモデルは、中国語と英語で構成される100,000時間以上でトレーニングされています。**[HuggingFace](https://huggingface.co/2Noise/ChatTTS)**でオープンソース化されているバージョンは、40,000時間の事前トレーニングモデルで、SFTは行われていません。
|
10 |
+
|
11 |
+
モデルやロードマップについての正式なお問い合わせは、**[email protected]**までご連絡ください。QQグループ:808364215に参加してディスカッションすることもできます。GitHubでの問題提起も歓迎します。
|
12 |
+
|
13 |
+
---
|
14 |
+
## ハイライト
|
15 |
+
1. **会話型TTS**: ChatTTSは対話ベースのタスクに最適化されており、自然で表現豊かな音声合成を実現します。複数の話者をサポートし、対話型の会話を容易にします。
|
16 |
+
2. **細かい制御**: このモデルは、笑い、一時停止、間投詞などの細かい韻律特徴を予測および制御することができます。
|
17 |
+
3. **より良い韻律**: ChatTTSは、韻律の面でほとんどのオープンソースTTSモデルを超えています。さらなる研究と開発をサポートするために、事前トレーニングされたモデルを提供しています。
|
18 |
+
|
19 |
+
モデルの詳細な説明については、**[Bilibiliのビデオ](https://www.bilibili.com/video/BV1zn4y1o7iV)**を参照してください。
|
20 |
+
|
21 |
+
---
|
22 |
+
|
23 |
+
## 免責事項
|
24 |
+
|
25 |
+
このリポジトリは学術目的のみのためです。教育および研究用途にのみ使用され、商業的または法的な目的には使用されません。著者は情報の正確性、完全性、または信頼性を保証しません。このリポジトリで使用される情報およびデータは、学術および研究目的のみのためのものです。データは公開されているソースから取得され、著者はデータに対する所有権または著作権を主張しません。
|
26 |
+
|
27 |
+
ChatTTSは強力なテキストから音声へのシステムです。しかし、この技術を責任を持って、倫理的に利用することが非常に重要です。ChatTTSの使用を制限するために、40,000時間のモデルのトレーニング中に少量の高周波ノイズを追加し、MP3形式を使用して音質を可能な限り圧縮しました。これは、悪意のあるアクターが潜在的に犯罪目的で使用することを防ぐためです。同時に、私たちは内部的に検出モデルをトレーニングしており、将来的にオープンソース化する予定です。
|
28 |
+
|
29 |
+
---
|
30 |
+
## 使用方法
|
31 |
+
|
32 |
+
<h4>基本的な使用方法</h4>
|
33 |
+
|
34 |
+
```python
|
35 |
+
import ChatTTS
|
36 |
+
from IPython.display import Audio
|
37 |
+
|
38 |
+
chat = ChatTTS.Chat()
|
39 |
+
chat.load_models(compile=False) # より良いパフォーマンスのためにTrueに設定
|
40 |
+
|
41 |
+
texts = ["ここにテキストを入力してください",]
|
42 |
+
|
43 |
+
wavs = chat.infer(texts, )
|
44 |
+
|
45 |
+
torchaudio.save("output1.wav", torch.from_numpy(wavs[0]), 24000)
|
46 |
+
```
|
47 |
+
|
48 |
+
<h4>高度な使用方法</h4>
|
49 |
+
|
50 |
+
```python
|
51 |
+
###################################
|
52 |
+
# ガウス分布から話者をサンプリングします。
|
53 |
+
|
54 |
+
rand_spk = chat.sample_random_speaker()
|
55 |
+
|
56 |
+
params_infer_code = {
|
57 |
+
'spk_emb': rand_spk, # サンプリングされた話者を追加
|
58 |
+
'temperature': .3, # カスタム温度を使用
|
59 |
+
'top_P': 0.7, # トップPデコード
|
60 |
+
'top_K': 20, # トップKデコード
|
61 |
+
}
|
62 |
+
|
63 |
+
###################################
|
64 |
+
# 文レベルの手動制御のために。
|
65 |
+
|
66 |
+
# 特別なトークンを生成するためにテキストにoral_(0-9)、laugh_(0-2)、break_(0-7)を使用します。
|
67 |
+
params_refine_text = {
|
68 |
+
'prompt': '[oral_2][laugh_0][break_6]'
|
69 |
+
}
|
70 |
+
|
71 |
+
wav = chat.infer(texts, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
|
72 |
+
|
73 |
+
###################################
|
74 |
+
# 単語レベルの手動制御のために。
|
75 |
+
text = 'あなたの好きな英語の食べ物は何ですか?[uv_break][laugh][lbreak]'
|
76 |
+
wav = chat.infer(text, skip_refine_text=True, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
|
77 |
+
torchaudio.save("output2.wav", torch.from_numpy(wavs[0]), 24000)
|
78 |
+
```
|
79 |
+
|
80 |
+
<details open>
|
81 |
+
<summary><h4>例:自己紹介</h4></summary>
|
82 |
+
|
83 |
+
```python
|
84 |
+
inputs_jp = """
|
85 |
+
ChatTTSは、対話アプリケーション用に設計されたテキストから音声へのモデルです。
|
86 |
+
[uv_break]混合言語入力をサポートし[uv_break]、韻律要素[laugh]の正確な制御を提供します
|
87 |
+
[uv_break]笑い[laugh]、[uv_break]一時停止、[uv_break]およびイントネーション。[uv_break]自然で表現豊かな音声を提供します
|
88 |
+
[uv_break]したがって、自己責任でプロジェクトを責任を持って使用してください。[uv_break]
|
89 |
+
""".replace('\n', '') # 英語はまだ実験的です。
|
90 |
+
|
91 |
+
params_refine_text = {
|
92 |
+
'prompt': '[oral_2][laugh_0][break_4]'
|
93 |
+
}
|
94 |
+
audio_array_jp = chat.infer(inputs_jp, params_refine_text=params_refine_text)
|
95 |
+
torchaudio.save("output3.wav", torch.from_numpy(audio_array_jp[0]), 24000)
|
96 |
+
```
|
97 |
+
[男性話者](https://github.com/2noise/ChatTTS/assets/130631963/e0f51251-db7f-4d39-a0e9-3e095bb65de1)
|
98 |
+
|
99 |
+
[女性話者](https://github.com/2noise/ChatTTS/assets/130631963/f5dcdd01-1091-47c5-8241-c4f6aaaa8bbd)
|
100 |
+
</details>
|
101 |
+
|
102 |
+
---
|
103 |
+
## ロードマップ
|
104 |
+
- [x] 40k時間のベースモデルとspk_statsファイルをオープンソース化
|
105 |
+
- [ ] VQエンコーダーとLoraトレーニングコードをオープンソース化
|
106 |
+
- [ ] テキストをリファインせずにストリーミングオーディオ生成*
|
107 |
+
- [ ] 複数の感情制御を備えた40k時間バージョンをオープンソース化
|
108 |
+
- [ ] ChatTTS.cppもしかしたら?(PRや新しいリポジトリが歓迎されます。)
|
109 |
+
|
110 |
+
----
|
111 |
+
## FAQ
|
112 |
+
|
113 |
+
##### VRAMはどれくらい必要ですか?推論速度はどうですか?
|
114 |
+
30秒のオーディオクリップには、少なくとも4GBのGPUメモリが必要です。4090 GPUの場合、約7つの意味トークンに対応するオーディオを1秒あたり生成できます。リアルタイムファクター(RTF)は約0.3です。
|
115 |
+
|
116 |
+
##### モデルの安定性が十分でなく、複数の話者や音質が悪いという問題があります。
|
117 |
+
|
118 |
+
これは、自己回帰モデル(barkおよびvalleの場合)で一般的に発生する問題です。一般的に避けるのは難しいです。複数のサンプルを試して、適切な結果を見つけることができます。
|
119 |
+
|
120 |
+
##### 笑い以外に何か制御できますか?他の感情を制御できますか?
|
121 |
+
|
122 |
+
現在リリースされているモデルでは、トークンレベルの制御ユニットは[laugh]、[uv_break]、および[lbreak]のみです。将来のバージョンでは、追加の感情制御機能を備えたモデルをオープンソース化する可能性があります。
|
123 |
+
|
124 |
+
---
|
125 |
+
## 謝辞
|
126 |
+
- [bark](https://github.com/suno-ai/bark)、[XTTSv2](https://github.com/coqui-ai/TTS)、および[valle](https://arxiv.org/abs/2301.02111)は、自己回帰型システムによる顕著なTTS結果を示しました。
|
127 |
+
- [fish-speech](https://github.com/fishaudio/fish-speech)は、LLMモデリングのためのオーディオトークナイザーとしてのGVQの能力を明らかにしました。
|
128 |
+
- 事前トレーニングされたボコーダーとして使用される[vocos](https://github.com/gemelo-ai/vocos)。
|
129 |
+
|
130 |
+
---
|
131 |
+
## 特別感謝
|
132 |
+
- 初期のアルゴリズム実験をサポートしてくれた[wlu-audio lab](https://audio.westlake.edu.cn/)。
|
ChatTTS/docs/ru/README.md
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ChatTTS
|
2 |
+
> [!NOTE]
|
3 |
+
> Следующая информация может быть не самой последней, пожалуйста, смотрите английскую версию для актуальных данных.
|
4 |
+
|
5 |
+
[![Huggingface](https://img.shields.io/badge/🤗%20-Models-yellow.svg?style=for-the-badge)](https://huggingface.co/2Noise/ChatTTS)
|
6 |
+
|
7 |
+
[**English**](../../README.md) | [**简体中文**](../cn/README.md) | [**日本語**](../jp/README.md) | **Русский**
|
8 |
+
|
9 |
+
ChatTTS - это модель преобразования текста в речь, специально разработанная для диалоговых сценариев, таких как помощник LLM. Она поддерживает как английский, так и китайский языки. Наша модель обучена на более чем 100 000 часах английского и китайского языков. Открытая версия на **[HuggingFace](https://huggingface.co/2Noise/ChatTTS)** - это предварительно обученная модель с 40 000 часами без SFT.
|
10 |
+
|
11 |
+
Для официальных запросов о модели и плане развития, пожалуйста, свяжитесь с нами по адресу **[email protected]**. Вы можете присоединиться к нашей группе QQ: 808364215 для обсуждения. Добавление вопросов на GitHub также приветствуется.
|
12 |
+
|
13 |
+
---
|
14 |
+
## Особенности
|
15 |
+
1. **Диалоговый TTS**: ChatTTS оптимизирован для задач, основанных на диалогах, что позволяет создавать натуральную и выразительную речь. Он поддерживает несколько говорящих, облегчая интерактивные беседы.
|
16 |
+
2. **Тонкий контроль**: Модель может предсказывать и контролировать тонкие просодические особенности, включая смех, паузы и вставные слова.
|
17 |
+
3. **Лучшая просодия**: ChatTTS превосходит большинство открытых моделей TTS с точки зрения просодии. Мы предоставляем предварительно обученные модели для поддержки дальнейших исследований и разработок.
|
18 |
+
|
19 |
+
Для подробного описания модели вы можете обратиться к **[видео на Bilibili](https://www.bilibili.com/video/BV1zn4y1o7iV)**
|
20 |
+
|
21 |
+
---
|
22 |
+
|
23 |
+
## Отказ от ответственности
|
24 |
+
|
25 |
+
Этот репозиторий предназначен только для академических целей. Он предназначен для образовательного и исследовательского использования и не должен использоваться в коммерческих или юридических целях. Авторы не гарантируют точность, полноту или надежность информации. Информация и данные, использованные в этом репозитории, предназначены только для академических и исследовательских целей. Данные получены из общедоступных источников, и авторы не заявляют о каких-либо правах собственности или авторских правах на данные.
|
26 |
+
|
27 |
+
ChatTTS - мощная система преобразования текста в речь. Однако очень важно использовать эту технологию ответственно и этично. Чтобы ограничить использование ChatTTS, мы добавили небольшое количество высокочастотного шума во время обучения модели на 40 000 часов и сжали качество аудио как можно больше с помощью формата MP3, чтобы предотвратить возможное использование злоумышленниками в преступных целях. В то же время мы внутренне обучили модель обнаружения и планируем открыть ее в будущем.
|
28 |
+
|
29 |
+
---
|
30 |
+
## Использование
|
31 |
+
|
32 |
+
<h4>Базовое использование</h4>
|
33 |
+
|
34 |
+
```python
|
35 |
+
import ChatTTS
|
36 |
+
from IPython.display import Audio
|
37 |
+
|
38 |
+
chat = ChatTTS.Chat()
|
39 |
+
chat.load_models(compile=False) # Установите значение True для лучшей производительности
|
40 |
+
|
41 |
+
texts = ["ВВЕДИТЕ ВАШ ТЕКСТ ЗДЕСЬ",]
|
42 |
+
|
43 |
+
wavs = chat.infer(texts)
|
44 |
+
|
45 |
+
torchaudio.save("output1.wav", torch.from_numpy(wavs[0]), 24000)
|
46 |
+
```
|
47 |
+
|
48 |
+
<h4>Продвинутое использование</h4>
|
49 |
+
|
50 |
+
```python
|
51 |
+
###################################
|
52 |
+
# Выборка говорящего из Гауссиана.
|
53 |
+
|
54 |
+
rand_spk = chat.sample_random_speaker()
|
55 |
+
|
56 |
+
params_infer_code = {
|
57 |
+
'spk_emb': rand_spk, # добавить выбранного говорящего
|
58 |
+
'temperature': .3, # использовать пользовательскую температуру
|
59 |
+
'top_P': 0.7, # декодирование top P
|
60 |
+
'top_K': 20, # декодирование top K
|
61 |
+
}
|
62 |
+
|
63 |
+
###################################
|
64 |
+
# Для контроля на уровне предложений.
|
65 |
+
|
66 |
+
# используйте oral_(0-9), laugh_(0-2), break_(0-7)
|
67 |
+
# для генерации специального токена в тексте для синтеза.
|
68 |
+
params_refine_text = {
|
69 |
+
'prompt': '[oral_2][laugh_0][break_6]'
|
70 |
+
}
|
71 |
+
|
72 |
+
wav = chat.infer(texts, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
|
73 |
+
|
74 |
+
###################################
|
75 |
+
# Для контроля на уровне слов.
|
76 |
+
text = 'Какая ваша любимая английская еда?[uv_break]your favorite english food?[laugh][lbreak]'
|
77 |
+
wav = chat.infer(text, skip_refine_text=True, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
|
78 |
+
torchaudio.save("output2.wav", torch.from_numpy(wavs[0]), 24000)
|
79 |
+
```
|
80 |
+
|
81 |
+
<details open>
|
82 |
+
<summary><h4>Пример: самопрезентация</h4></summary>
|
83 |
+
|
84 |
+
```python
|
85 |
+
inputs_ru = """
|
86 |
+
ChatTTS - это модель преобразования текста в речь, разработанная для диалоговых приложений.
|
87 |
+
[uv_break]Она поддерживает смешанный языковой ввод [uv_break]и предлагает возможности множественных говорящих
|
88 |
+
с точным контролем над просодическими элементами [laugh]как [uv_break]смех[laugh], [uv_break]паузы, [uv_break]и интонацию.
|
89 |
+
[uv_break]Она обеспечивает натуральную и выразительную речь,[uv_break]поэтому, пожалуйста,
|
90 |
+
[uv_break] используйте проект ответственно и на свой страх и риск.[uv_break]
|
91 |
+
""".replace('\n', '') # Русский язык все еще находится в экспериментальной стадии.
|
92 |
+
|
93 |
+
params_refine_text = {
|
94 |
+
'prompt': '[oral_2][laugh_0][break_4]'
|
95 |
+
}
|
96 |
+
audio_array_ru = chat.infer(inputs_ru, params_refine_text=params_refine_text)
|
97 |
+
torchaudio.save("output3.wav", torch.from_numpy(audio_array_ru[0]), 24000)
|
98 |
+
```
|
99 |
+
[мужской говорящий](https://github.com/2noise/ChatTTS/assets/130631963/e0f51251-db7f-4d39-a0e9-3e095bb65de1)
|
100 |
+
|
101 |
+
[женский говорящий](https://github.com/2noise/ChatTTS/assets/130631963/f5dcdd01-1091-47c5-8241-c4f6aaaa8bbd)
|
102 |
+
</details>
|
103 |
+
|
104 |
+
---
|
105 |
+
## План развития
|
106 |
+
- [x] Открыть исходный код базовой модели на 40 тысяч часов и файла spk_stats
|
107 |
+
- [ ] Открыть исходный код кодировщика VQ и кода обучения Lora
|
108 |
+
- [ ] Потоковая генерация аудио без уточнения текста*
|
109 |
+
- [ ] Открыть исходный код версии на 40 тысяч часов с управлением множественными эмоциями
|
110 |
+
- [ ] ChatTTS.cpp возможно? (PR или новый репозиторий приветствуются.)
|
111 |
+
|
112 |
+
----
|
113 |
+
## Часто задаваемые вопросы
|
114 |
+
|
115 |
+
##### Сколько VRAM мне нужно? Как насчет скорости инференса?
|
116 |
+
Для 30-секундного аудиоклипа требуется как минимум 4 ГБ памяти GPU. Для GPU 4090, он может генерировать аудио, соответствующее примерно 7 семантическим токенам в секунду. Фактор реального времени (RTF) составляет около 0.3.
|
117 |
+
|
118 |
+
##### Стабильность модели кажется недостаточно хорошей, возникают проблемы с множественными говорящими или плохим качеством аудио.
|
119 |
+
|
120 |
+
Это проблема, которая обычно возникает с авторегрессивными моделями (для bark и valle). Это обычно трудно избежать. Можно попробовать несколько образцов, чтобы найти подходящий результат.
|
121 |
+
|
122 |
+
##### Помимо смеха, можем ли мы контролировать что-то еще? Можем ли мы контролировать другие эмоции?
|
123 |
+
|
124 |
+
В текущей выпущенной модели единственными элементами управления на уровне токенов являются [laugh], [uv_break] и [lbreak]. В будущих версиях мы можем открыть модели с дополнительными возможностями контроля эмоций.
|
125 |
+
|
126 |
+
---
|
127 |
+
## Благодарности
|
128 |
+
- [bark](https://github.com/suno-ai/bark), [XTTSv2](https://github.com/coqui-ai/TTS) и [valle](https://arxiv.org/abs/2301.02111) демонстрируют замечательный результат TTS с помощью системы авторегрессивного стиля.
|
129 |
+
- [fish-speech](https://github.com/fishaudio/fish-speech) показывает возможности GVQ как аудио токенизатора для моделирования LLM.
|
130 |
+
- [vocos](https://github.com/gemelo-ai/vocos), который используется в качестве предварительно обученного вокодера.
|
131 |
+
|
132 |
+
---
|
133 |
+
## Особая благодарность
|
134 |
+
- [wlu-audio lab](https://audio.westlake.edu.cn/) за ранние эксперименты с алгоритмами.
|
ChatTTS/examples/cmd/run.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, sys
|
2 |
+
|
3 |
+
if sys.platform == "darwin":
|
4 |
+
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
|
5 |
+
|
6 |
+
now_dir = os.getcwd()
|
7 |
+
sys.path.append(now_dir)
|
8 |
+
|
9 |
+
from dotenv import load_dotenv
|
10 |
+
load_dotenv("sha256.env")
|
11 |
+
|
12 |
+
import wave
|
13 |
+
import ChatTTS
|
14 |
+
from IPython.display import Audio
|
15 |
+
|
16 |
+
def save_wav_file(wav, index):
|
17 |
+
wav_filename = f"output_audio_{index}.wav"
|
18 |
+
# Convert numpy array to bytes and write to WAV file
|
19 |
+
wav_bytes = (wav * 32768).astype('int16').tobytes()
|
20 |
+
with wave.open(wav_filename, "wb") as wf:
|
21 |
+
wf.setnchannels(1) # Mono channel
|
22 |
+
wf.setsampwidth(2) # Sample width in bytes
|
23 |
+
wf.setframerate(24000) # Sample rate in Hz
|
24 |
+
wf.writeframes(wav_bytes)
|
25 |
+
print(f"Audio saved to {wav_filename}")
|
26 |
+
|
27 |
+
def main():
|
28 |
+
# Retrieve text from command line argument
|
29 |
+
text_input = sys.argv[1] if len(sys.argv) > 1 else "<YOUR TEXT HERE>"
|
30 |
+
print("Received text input:", text_input)
|
31 |
+
|
32 |
+
chat = ChatTTS.Chat()
|
33 |
+
print("Initializing ChatTTS...")
|
34 |
+
chat.load_models()
|
35 |
+
print("Models loaded successfully.")
|
36 |
+
|
37 |
+
texts = [text_input]
|
38 |
+
print("Text prepared for inference:", texts)
|
39 |
+
|
40 |
+
wavs = chat.infer(texts, use_decoder=True)
|
41 |
+
print("Inference completed. Audio generation successful.")
|
42 |
+
# Save each generated wav file to a local file
|
43 |
+
for index, wav in enumerate(wavs):
|
44 |
+
save_wav_file(wav, index)
|
45 |
+
|
46 |
+
return Audio(wavs[0], rate=24_000, autoplay=True)
|
47 |
+
|
48 |
+
if __name__ == "__main__":
|
49 |
+
print("Starting the TTS application...")
|
50 |
+
main()
|
51 |
+
print("TTS application finished.")
|
ChatTTS/examples/ipynb/colab.ipynb
ADDED
@@ -0,0 +1,759 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": null,
|
6 |
+
"metadata": {
|
7 |
+
"colab": {
|
8 |
+
"base_uri": "https://localhost:8080/"
|
9 |
+
},
|
10 |
+
"id": "hegwDOfffwzw",
|
11 |
+
"outputId": "1e221210-152b-4f5b-f009-9b9ffec2fa9f"
|
12 |
+
},
|
13 |
+
"outputs": [],
|
14 |
+
"source": [
|
15 |
+
"!rm -rf /content/ChatTTS\n",
|
16 |
+
"!git clone https://github.com/2noise/ChatTTS.git\n",
|
17 |
+
"!pip install -r /content/ChatTTS/requirements.txt\n",
|
18 |
+
"!pip install nemo_text_processing WeTextProcessing\n",
|
19 |
+
"!ldconfig /usr/lib64-nvidia"
|
20 |
+
]
|
21 |
+
},
|
22 |
+
{
|
23 |
+
"cell_type": "code",
|
24 |
+
"execution_count": null,
|
25 |
+
"metadata": {
|
26 |
+
"id": "lDSQ6Xf-bSre"
|
27 |
+
},
|
28 |
+
"outputs": [],
|
29 |
+
"source": [
|
30 |
+
"from dotenv import load_dotenv\n",
|
31 |
+
"load_dotenv(\"sha256.env\")\n",
|
32 |
+
"\n",
|
33 |
+
"import torch\n",
|
34 |
+
"torch._dynamo.config.cache_size_limit = 64\n",
|
35 |
+
"torch._dynamo.config.suppress_errors = True\n",
|
36 |
+
"torch.set_float32_matmul_precision('high')\n",
|
37 |
+
"\n",
|
38 |
+
"from ChatTTS import ChatTTS\n",
|
39 |
+
"from IPython.display import Audio"
|
40 |
+
]
|
41 |
+
},
|
42 |
+
{
|
43 |
+
"cell_type": "markdown",
|
44 |
+
"metadata": {
|
45 |
+
"id": "vBzG5gxcbSrf"
|
46 |
+
},
|
47 |
+
"source": [
|
48 |
+
"## Load Models"
|
49 |
+
]
|
50 |
+
},
|
51 |
+
{
|
52 |
+
"cell_type": "code",
|
53 |
+
"execution_count": null,
|
54 |
+
"metadata": {
|
55 |
+
"colab": {
|
56 |
+
"base_uri": "https://localhost:8080/",
|
57 |
+
"height": 49,
|
58 |
+
"referenced_widgets": [
|
59 |
+
"c365a95346ec4b09a1e6467bf313baf7",
|
60 |
+
"d79fd51849fd463cb08b83fdb8e5ca0c",
|
61 |
+
"d247683a0a61441b971dfb39062e1fbf",
|
62 |
+
"1da23fc236034f32adcaf6bb2e0e7d80",
|
63 |
+
"4b2126d97c514795ab2a90f7357a203c",
|
64 |
+
"9775ce64008b417fac3edd55b9e999d9",
|
65 |
+
"96c9bb2eff4043b2a5dbd1e3e65375e5",
|
66 |
+
"20aa0031b7bb45bf82443b48b3694166",
|
67 |
+
"67252ea545d64392a1bd6ac40852e65f",
|
68 |
+
"2f920c00bcac4787a0078ee035e97b43",
|
69 |
+
"ba592297ff5347aebae298770a29fb8c"
|
70 |
+
]
|
71 |
+
},
|
72 |
+
"id": "e0QSkngRbSrg",
|
73 |
+
"outputId": "138ac28b-6a33-4c31-8fe3-8481bb213d02"
|
74 |
+
},
|
75 |
+
"outputs": [],
|
76 |
+
"source": [
|
77 |
+
"chat = ChatTTS.Chat()\n",
|
78 |
+
"\n",
|
79 |
+
"# Use force_redownload=True if the weights updated.\n",
|
80 |
+
"chat.load_models(force_redownload=True)\n",
|
81 |
+
"\n",
|
82 |
+
"# If you download the weights manually, set source='locals'.\n",
|
83 |
+
"# chat.load_models(source='local', local_path='YOUR LOCAL PATH')"
|
84 |
+
]
|
85 |
+
},
|
86 |
+
{
|
87 |
+
"cell_type": "markdown",
|
88 |
+
"metadata": {
|
89 |
+
"id": "bAUs0rGQbSrh"
|
90 |
+
},
|
91 |
+
"source": [
|
92 |
+
"## Inference"
|
93 |
+
]
|
94 |
+
},
|
95 |
+
{
|
96 |
+
"cell_type": "markdown",
|
97 |
+
"metadata": {
|
98 |
+
"id": "NPZ2SFksbSrh"
|
99 |
+
},
|
100 |
+
"source": [
|
101 |
+
"### Batch infer"
|
102 |
+
]
|
103 |
+
},
|
104 |
+
{
|
105 |
+
"cell_type": "code",
|
106 |
+
"execution_count": null,
|
107 |
+
"metadata": {
|
108 |
+
"colab": {
|
109 |
+
"base_uri": "https://localhost:8080/"
|
110 |
+
},
|
111 |
+
"id": "Su9FmUYAbSrh",
|
112 |
+
"outputId": "7c2aa0c1-1f99-4da1-b2e5-bbcb93465d89"
|
113 |
+
},
|
114 |
+
"outputs": [],
|
115 |
+
"source": [
|
116 |
+
"texts = [\"So we found being competitive and collaborative was a huge way of staying motivated towards our goals, so one person to call when you fall off, one person who gets you back on then one person to actually do the activity with.\",]*3 \\\n",
|
117 |
+
" + [\"我觉得像我们这些写程序的人,他,我觉得多多少少可能会对开源有一种情怀在吧我觉得开源是一个很好的形式。现在其实最先进的技术掌握在一些公司的手里的话,就他们并不会轻易的开放给所有的人用。\"]*3\n",
|
118 |
+
"\n",
|
119 |
+
"wavs = chat.infer(texts)"
|
120 |
+
]
|
121 |
+
},
|
122 |
+
{
|
123 |
+
"cell_type": "code",
|
124 |
+
"execution_count": null,
|
125 |
+
"metadata": {
|
126 |
+
"colab": {
|
127 |
+
"base_uri": "https://localhost:8080/",
|
128 |
+
"height": 76
|
129 |
+
},
|
130 |
+
"id": "YQRwB8lpbSri",
|
131 |
+
"outputId": "62ca9282-2755-44a5-ffca-c05c5e35ce76"
|
132 |
+
},
|
133 |
+
"outputs": [],
|
134 |
+
"source": [
|
135 |
+
"Audio(wavs[0], rate=24_000, autoplay=True)"
|
136 |
+
]
|
137 |
+
},
|
138 |
+
{
|
139 |
+
"cell_type": "code",
|
140 |
+
"execution_count": null,
|
141 |
+
"metadata": {
|
142 |
+
"colab": {
|
143 |
+
"base_uri": "https://localhost:8080/",
|
144 |
+
"height": 76
|
145 |
+
},
|
146 |
+
"id": "LuFG6m7AbSri",
|
147 |
+
"outputId": "d8e0e3a2-d9fe-44db-e1f4-e2596289270e"
|
148 |
+
},
|
149 |
+
"outputs": [],
|
150 |
+
"source": [
|
151 |
+
"Audio(wavs[3], rate=24_000, autoplay=True)"
|
152 |
+
]
|
153 |
+
},
|
154 |
+
{
|
155 |
+
"cell_type": "markdown",
|
156 |
+
"metadata": {
|
157 |
+
"id": "oLhAGvkfbSrj"
|
158 |
+
},
|
159 |
+
"source": [
|
160 |
+
"### Custom params"
|
161 |
+
]
|
162 |
+
},
|
163 |
+
{
|
164 |
+
"cell_type": "code",
|
165 |
+
"execution_count": null,
|
166 |
+
"metadata": {
|
167 |
+
"colab": {
|
168 |
+
"base_uri": "https://localhost:8080/"
|
169 |
+
},
|
170 |
+
"id": "kma0HBEBbSrj",
|
171 |
+
"outputId": "b80b9d2f-8248-41ee-f1d7-eb3bf331ee69"
|
172 |
+
},
|
173 |
+
"outputs": [],
|
174 |
+
"source": [
|
175 |
+
"params_infer_code = {'prompt':'[speed_5]', 'temperature':.3}\n",
|
176 |
+
"params_refine_text = {'prompt':'[oral_2][laugh_0][break_6]'}\n",
|
177 |
+
"\n",
|
178 |
+
"wav = chat.infer('四川美食可多了,有麻辣火锅、宫保鸡丁、麻婆豆腐、担担面、回锅肉、夫妻肺片等,每样都让人垂涎三尺。', \\\n",
|
179 |
+
" params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
|
180 |
+
]
|
181 |
+
},
|
182 |
+
{
|
183 |
+
"cell_type": "code",
|
184 |
+
"execution_count": null,
|
185 |
+
"metadata": {
|
186 |
+
"colab": {
|
187 |
+
"base_uri": "https://localhost:8080/",
|
188 |
+
"height": 76
|
189 |
+
},
|
190 |
+
"id": "Nl_mT9KpbSrj",
|
191 |
+
"outputId": "1bfcc06a-5246-4d25-fc19-3d125362fa59"
|
192 |
+
},
|
193 |
+
"outputs": [],
|
194 |
+
"source": [
|
195 |
+
"Audio(wav[0], rate=24_000, autoplay=True)"
|
196 |
+
]
|
197 |
+
},
|
198 |
+
{
|
199 |
+
"cell_type": "markdown",
|
200 |
+
"metadata": {
|
201 |
+
"id": "JfAba-tTbSrk"
|
202 |
+
},
|
203 |
+
"source": [
|
204 |
+
"### fix random speaker"
|
205 |
+
]
|
206 |
+
},
|
207 |
+
{
|
208 |
+
"cell_type": "code",
|
209 |
+
"execution_count": null,
|
210 |
+
"metadata": {
|
211 |
+
"colab": {
|
212 |
+
"base_uri": "https://localhost:8080/"
|
213 |
+
},
|
214 |
+
"id": "Qh7dcWrAbSrk",
|
215 |
+
"outputId": "3b936323-170a-496b-c4c2-6caa97a8d514"
|
216 |
+
},
|
217 |
+
"outputs": [],
|
218 |
+
"source": [
|
219 |
+
"rand_spk = chat.sample_random_speaker()\n",
|
220 |
+
"params_infer_code = {'spk_emb' : rand_spk, }\n",
|
221 |
+
"\n",
|
222 |
+
"wav = chat.infer('四川美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。', \\\n",
|
223 |
+
" params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
|
224 |
+
]
|
225 |
+
},
|
226 |
+
{
|
227 |
+
"cell_type": "code",
|
228 |
+
"execution_count": null,
|
229 |
+
"metadata": {
|
230 |
+
"colab": {
|
231 |
+
"base_uri": "https://localhost:8080/",
|
232 |
+
"height": 76
|
233 |
+
},
|
234 |
+
"id": "0ljWDWzabSrk",
|
235 |
+
"outputId": "8ade2469-c226-44ae-c3a7-ff034e2bffbf"
|
236 |
+
},
|
237 |
+
"outputs": [],
|
238 |
+
"source": [
|
239 |
+
"Audio(wav[0], rate=24_000, autoplay=True)"
|
240 |
+
]
|
241 |
+
},
|
242 |
+
{
|
243 |
+
"cell_type": "markdown",
|
244 |
+
"metadata": {
|
245 |
+
"id": "u1q-BcUKbSrl"
|
246 |
+
},
|
247 |
+
"source": [
|
248 |
+
"### Two stage control"
|
249 |
+
]
|
250 |
+
},
|
251 |
+
{
|
252 |
+
"cell_type": "code",
|
253 |
+
"execution_count": null,
|
254 |
+
"metadata": {
|
255 |
+
"colab": {
|
256 |
+
"base_uri": "https://localhost:8080/"
|
257 |
+
},
|
258 |
+
"id": "3hAAc0lJbSrl",
|
259 |
+
"outputId": "8dc45586-fb2a-4e81-ee53-0ce6df2fc43a"
|
260 |
+
},
|
261 |
+
"outputs": [],
|
262 |
+
"source": [
|
263 |
+
"text = \"So we found being competitive and collaborative was a huge way of staying motivated towards our goals, so one person to call when you fall off, one person who gets you back on then one person to actually do the activity with.\"\n",
|
264 |
+
"refined_text = chat.infer(text, refine_text_only=True)\n",
|
265 |
+
"refined_text"
|
266 |
+
]
|
267 |
+
},
|
268 |
+
{
|
269 |
+
"cell_type": "code",
|
270 |
+
"execution_count": null,
|
271 |
+
"metadata": {
|
272 |
+
"colab": {
|
273 |
+
"base_uri": "https://localhost:8080/"
|
274 |
+
},
|
275 |
+
"id": "0GVJxhd3BKQX",
|
276 |
+
"outputId": "f1484519-7130-450a-b7d8-09de5fe2ffd1"
|
277 |
+
},
|
278 |
+
"outputs": [],
|
279 |
+
"source": [
|
280 |
+
"wav = chat.infer(refined_text)"
|
281 |
+
]
|
282 |
+
},
|
283 |
+
{
|
284 |
+
"cell_type": "code",
|
285 |
+
"execution_count": null,
|
286 |
+
"metadata": {
|
287 |
+
"colab": {
|
288 |
+
"base_uri": "https://localhost:8080/",
|
289 |
+
"height": 76
|
290 |
+
},
|
291 |
+
"id": "ngyMht74BicY",
|
292 |
+
"outputId": "8c7447ad-9ac7-4264-9f53-057d47d43931"
|
293 |
+
},
|
294 |
+
"outputs": [],
|
295 |
+
"source": [
|
296 |
+
"Audio(wav[0], rate=24_000, autoplay=True)"
|
297 |
+
]
|
298 |
+
},
|
299 |
+
{
|
300 |
+
"cell_type": "code",
|
301 |
+
"execution_count": null,
|
302 |
+
"metadata": {
|
303 |
+
"colab": {
|
304 |
+
"base_uri": "https://localhost:8080/"
|
305 |
+
},
|
306 |
+
"id": "R2WjuVrWbSrl",
|
307 |
+
"outputId": "0d644cb9-4d65-4147-bd99-d5451439be02"
|
308 |
+
},
|
309 |
+
"outputs": [],
|
310 |
+
"source": [
|
311 |
+
"text = 'so we found being competitive and collaborative [uv_break] was a huge way of staying [uv_break] motivated towards our goals, [uv_break] so [uv_break] one person to call [uv_break] when you fall off, [uv_break] one person who [uv_break] gets you back [uv_break] on then [uv_break] one person [uv_break] to actually do the activity with.'\n",
|
312 |
+
"wav = chat.infer(text, skip_refine_text=True)"
|
313 |
+
]
|
314 |
+
},
|
315 |
+
{
|
316 |
+
"cell_type": "code",
|
317 |
+
"execution_count": null,
|
318 |
+
"metadata": {
|
319 |
+
"colab": {
|
320 |
+
"base_uri": "https://localhost:8080/",
|
321 |
+
"height": 76
|
322 |
+
},
|
323 |
+
"id": "71Y4pBdl-_Yd",
|
324 |
+
"outputId": "d44fdf1a-c9e8-42ff-ab96-8712986418fa"
|
325 |
+
},
|
326 |
+
"outputs": [],
|
327 |
+
"source": [
|
328 |
+
"Audio(wav[0], rate=24_000, autoplay=True)"
|
329 |
+
]
|
330 |
+
},
|
331 |
+
{
|
332 |
+
"cell_type": "markdown",
|
333 |
+
"metadata": {
|
334 |
+
"id": "GG5AMbQbbSrl"
|
335 |
+
},
|
336 |
+
"source": [
|
337 |
+
"## LLM Call"
|
338 |
+
]
|
339 |
+
},
|
340 |
+
{
|
341 |
+
"cell_type": "code",
|
342 |
+
"execution_count": null,
|
343 |
+
"metadata": {
|
344 |
+
"id": "3rkfwc3UbSrl"
|
345 |
+
},
|
346 |
+
"outputs": [],
|
347 |
+
"source": [
|
348 |
+
"from ChatTTS.experimental.llm import llm_api\n",
|
349 |
+
"\n",
|
350 |
+
"API_KEY = ''\n",
|
351 |
+
"client = llm_api(api_key=API_KEY,\n",
|
352 |
+
" base_url=\"https://api.deepseek.com\",\n",
|
353 |
+
" model=\"deepseek-chat\")"
|
354 |
+
]
|
355 |
+
},
|
356 |
+
{
|
357 |
+
"cell_type": "code",
|
358 |
+
"execution_count": null,
|
359 |
+
"metadata": {
|
360 |
+
"id": "TTkIsXozbSrm"
|
361 |
+
},
|
362 |
+
"outputs": [],
|
363 |
+
"source": [
|
364 |
+
"user_question = '四川有哪些好吃的美食呢?'\n",
|
365 |
+
"text = client.call(user_question, prompt_version = 'deepseek')\n",
|
366 |
+
"print(text)\n",
|
367 |
+
"text = client.call(text, prompt_version = 'deepseek_TN')\n",
|
368 |
+
"print(text)"
|
369 |
+
]
|
370 |
+
},
|
371 |
+
{
|
372 |
+
"cell_type": "code",
|
373 |
+
"execution_count": null,
|
374 |
+
"metadata": {
|
375 |
+
"id": "qNhCJG4VbSrm"
|
376 |
+
},
|
377 |
+
"outputs": [],
|
378 |
+
"source": [
|
379 |
+
"params_infer_code = {'spk_emb' : rand_spk, 'temperature':.3}\n",
|
380 |
+
"\n",
|
381 |
+
"wav = chat.infer(text, params_infer_code=params_infer_code)"
|
382 |
+
]
|
383 |
+
}
|
384 |
+
],
|
385 |
+
"metadata": {
|
386 |
+
"accelerator": "GPU",
|
387 |
+
"colab": {
|
388 |
+
"collapsed_sections": [
|
389 |
+
"bAUs0rGQbSrh"
|
390 |
+
],
|
391 |
+
"gpuType": "T4",
|
392 |
+
"provenance": []
|
393 |
+
},
|
394 |
+
"kernelspec": {
|
395 |
+
"display_name": "Python 3",
|
396 |
+
"name": "python3"
|
397 |
+
},
|
398 |
+
"language_info": {
|
399 |
+
"codemirror_mode": {
|
400 |
+
"name": "ipython",
|
401 |
+
"version": 3
|
402 |
+
},
|
403 |
+
"file_extension": ".py",
|
404 |
+
"mimetype": "text/x-python",
|
405 |
+
"name": "python",
|
406 |
+
"nbconvert_exporter": "python",
|
407 |
+
"pygments_lexer": "ipython3",
|
408 |
+
"version": "3.10.8"
|
409 |
+
},
|
410 |
+
"widgets": {
|
411 |
+
"application/vnd.jupyter.widget-state+json": {
|
412 |
+
"1da23fc236034f32adcaf6bb2e0e7d80": {
|
413 |
+
"model_module": "@jupyter-widgets/controls",
|
414 |
+
"model_module_version": "1.5.0",
|
415 |
+
"model_name": "HTMLModel",
|
416 |
+
"state": {
|
417 |
+
"_dom_classes": [],
|
418 |
+
"_model_module": "@jupyter-widgets/controls",
|
419 |
+
"_model_module_version": "1.5.0",
|
420 |
+
"_model_name": "HTMLModel",
|
421 |
+
"_view_count": null,
|
422 |
+
"_view_module": "@jupyter-widgets/controls",
|
423 |
+
"_view_module_version": "1.5.0",
|
424 |
+
"_view_name": "HTMLView",
|
425 |
+
"description": "",
|
426 |
+
"description_tooltip": null,
|
427 |
+
"layout": "IPY_MODEL_2f920c00bcac4787a0078ee035e97b43",
|
428 |
+
"placeholder": "",
|
429 |
+
"style": "IPY_MODEL_ba592297ff5347aebae298770a29fb8c",
|
430 |
+
"value": " 11/11 [00:00<00:00, 762.51it/s]"
|
431 |
+
}
|
432 |
+
},
|
433 |
+
"20aa0031b7bb45bf82443b48b3694166": {
|
434 |
+
"model_module": "@jupyter-widgets/base",
|
435 |
+
"model_module_version": "1.2.0",
|
436 |
+
"model_name": "LayoutModel",
|
437 |
+
"state": {
|
438 |
+
"_model_module": "@jupyter-widgets/base",
|
439 |
+
"_model_module_version": "1.2.0",
|
440 |
+
"_model_name": "LayoutModel",
|
441 |
+
"_view_count": null,
|
442 |
+
"_view_module": "@jupyter-widgets/base",
|
443 |
+
"_view_module_version": "1.2.0",
|
444 |
+
"_view_name": "LayoutView",
|
445 |
+
"align_content": null,
|
446 |
+
"align_items": null,
|
447 |
+
"align_self": null,
|
448 |
+
"border": null,
|
449 |
+
"bottom": null,
|
450 |
+
"display": null,
|
451 |
+
"flex": null,
|
452 |
+
"flex_flow": null,
|
453 |
+
"grid_area": null,
|
454 |
+
"grid_auto_columns": null,
|
455 |
+
"grid_auto_flow": null,
|
456 |
+
"grid_auto_rows": null,
|
457 |
+
"grid_column": null,
|
458 |
+
"grid_gap": null,
|
459 |
+
"grid_row": null,
|
460 |
+
"grid_template_areas": null,
|
461 |
+
"grid_template_columns": null,
|
462 |
+
"grid_template_rows": null,
|
463 |
+
"height": null,
|
464 |
+
"justify_content": null,
|
465 |
+
"justify_items": null,
|
466 |
+
"left": null,
|
467 |
+
"margin": null,
|
468 |
+
"max_height": null,
|
469 |
+
"max_width": null,
|
470 |
+
"min_height": null,
|
471 |
+
"min_width": null,
|
472 |
+
"object_fit": null,
|
473 |
+
"object_position": null,
|
474 |
+
"order": null,
|
475 |
+
"overflow": null,
|
476 |
+
"overflow_x": null,
|
477 |
+
"overflow_y": null,
|
478 |
+
"padding": null,
|
479 |
+
"right": null,
|
480 |
+
"top": null,
|
481 |
+
"visibility": null,
|
482 |
+
"width": null
|
483 |
+
}
|
484 |
+
},
|
485 |
+
"2f920c00bcac4787a0078ee035e97b43": {
|
486 |
+
"model_module": "@jupyter-widgets/base",
|
487 |
+
"model_module_version": "1.2.0",
|
488 |
+
"model_name": "LayoutModel",
|
489 |
+
"state": {
|
490 |
+
"_model_module": "@jupyter-widgets/base",
|
491 |
+
"_model_module_version": "1.2.0",
|
492 |
+
"_model_name": "LayoutModel",
|
493 |
+
"_view_count": null,
|
494 |
+
"_view_module": "@jupyter-widgets/base",
|
495 |
+
"_view_module_version": "1.2.0",
|
496 |
+
"_view_name": "LayoutView",
|
497 |
+
"align_content": null,
|
498 |
+
"align_items": null,
|
499 |
+
"align_self": null,
|
500 |
+
"border": null,
|
501 |
+
"bottom": null,
|
502 |
+
"display": null,
|
503 |
+
"flex": null,
|
504 |
+
"flex_flow": null,
|
505 |
+
"grid_area": null,
|
506 |
+
"grid_auto_columns": null,
|
507 |
+
"grid_auto_flow": null,
|
508 |
+
"grid_auto_rows": null,
|
509 |
+
"grid_column": null,
|
510 |
+
"grid_gap": null,
|
511 |
+
"grid_row": null,
|
512 |
+
"grid_template_areas": null,
|
513 |
+
"grid_template_columns": null,
|
514 |
+
"grid_template_rows": null,
|
515 |
+
"height": null,
|
516 |
+
"justify_content": null,
|
517 |
+
"justify_items": null,
|
518 |
+
"left": null,
|
519 |
+
"margin": null,
|
520 |
+
"max_height": null,
|
521 |
+
"max_width": null,
|
522 |
+
"min_height": null,
|
523 |
+
"min_width": null,
|
524 |
+
"object_fit": null,
|
525 |
+
"object_position": null,
|
526 |
+
"order": null,
|
527 |
+
"overflow": null,
|
528 |
+
"overflow_x": null,
|
529 |
+
"overflow_y": null,
|
530 |
+
"padding": null,
|
531 |
+
"right": null,
|
532 |
+
"top": null,
|
533 |
+
"visibility": null,
|
534 |
+
"width": null
|
535 |
+
}
|
536 |
+
},
|
537 |
+
"4b2126d97c514795ab2a90f7357a203c": {
|
538 |
+
"model_module": "@jupyter-widgets/base",
|
539 |
+
"model_module_version": "1.2.0",
|
540 |
+
"model_name": "LayoutModel",
|
541 |
+
"state": {
|
542 |
+
"_model_module": "@jupyter-widgets/base",
|
543 |
+
"_model_module_version": "1.2.0",
|
544 |
+
"_model_name": "LayoutModel",
|
545 |
+
"_view_count": null,
|
546 |
+
"_view_module": "@jupyter-widgets/base",
|
547 |
+
"_view_module_version": "1.2.0",
|
548 |
+
"_view_name": "LayoutView",
|
549 |
+
"align_content": null,
|
550 |
+
"align_items": null,
|
551 |
+
"align_self": null,
|
552 |
+
"border": null,
|
553 |
+
"bottom": null,
|
554 |
+
"display": null,
|
555 |
+
"flex": null,
|
556 |
+
"flex_flow": null,
|
557 |
+
"grid_area": null,
|
558 |
+
"grid_auto_columns": null,
|
559 |
+
"grid_auto_flow": null,
|
560 |
+
"grid_auto_rows": null,
|
561 |
+
"grid_column": null,
|
562 |
+
"grid_gap": null,
|
563 |
+
"grid_row": null,
|
564 |
+
"grid_template_areas": null,
|
565 |
+
"grid_template_columns": null,
|
566 |
+
"grid_template_rows": null,
|
567 |
+
"height": null,
|
568 |
+
"justify_content": null,
|
569 |
+
"justify_items": null,
|
570 |
+
"left": null,
|
571 |
+
"margin": null,
|
572 |
+
"max_height": null,
|
573 |
+
"max_width": null,
|
574 |
+
"min_height": null,
|
575 |
+
"min_width": null,
|
576 |
+
"object_fit": null,
|
577 |
+
"object_position": null,
|
578 |
+
"order": null,
|
579 |
+
"overflow": null,
|
580 |
+
"overflow_x": null,
|
581 |
+
"overflow_y": null,
|
582 |
+
"padding": null,
|
583 |
+
"right": null,
|
584 |
+
"top": null,
|
585 |
+
"visibility": null,
|
586 |
+
"width": null
|
587 |
+
}
|
588 |
+
},
|
589 |
+
"67252ea545d64392a1bd6ac40852e65f": {
|
590 |
+
"model_module": "@jupyter-widgets/controls",
|
591 |
+
"model_module_version": "1.5.0",
|
592 |
+
"model_name": "ProgressStyleModel",
|
593 |
+
"state": {
|
594 |
+
"_model_module": "@jupyter-widgets/controls",
|
595 |
+
"_model_module_version": "1.5.0",
|
596 |
+
"_model_name": "ProgressStyleModel",
|
597 |
+
"_view_count": null,
|
598 |
+
"_view_module": "@jupyter-widgets/base",
|
599 |
+
"_view_module_version": "1.2.0",
|
600 |
+
"_view_name": "StyleView",
|
601 |
+
"bar_color": null,
|
602 |
+
"description_width": ""
|
603 |
+
}
|
604 |
+
},
|
605 |
+
"96c9bb2eff4043b2a5dbd1e3e65375e5": {
|
606 |
+
"model_module": "@jupyter-widgets/controls",
|
607 |
+
"model_module_version": "1.5.0",
|
608 |
+
"model_name": "DescriptionStyleModel",
|
609 |
+
"state": {
|
610 |
+
"_model_module": "@jupyter-widgets/controls",
|
611 |
+
"_model_module_version": "1.5.0",
|
612 |
+
"_model_name": "DescriptionStyleModel",
|
613 |
+
"_view_count": null,
|
614 |
+
"_view_module": "@jupyter-widgets/base",
|
615 |
+
"_view_module_version": "1.2.0",
|
616 |
+
"_view_name": "StyleView",
|
617 |
+
"description_width": ""
|
618 |
+
}
|
619 |
+
},
|
620 |
+
"9775ce64008b417fac3edd55b9e999d9": {
|
621 |
+
"model_module": "@jupyter-widgets/base",
|
622 |
+
"model_module_version": "1.2.0",
|
623 |
+
"model_name": "LayoutModel",
|
624 |
+
"state": {
|
625 |
+
"_model_module": "@jupyter-widgets/base",
|
626 |
+
"_model_module_version": "1.2.0",
|
627 |
+
"_model_name": "LayoutModel",
|
628 |
+
"_view_count": null,
|
629 |
+
"_view_module": "@jupyter-widgets/base",
|
630 |
+
"_view_module_version": "1.2.0",
|
631 |
+
"_view_name": "LayoutView",
|
632 |
+
"align_content": null,
|
633 |
+
"align_items": null,
|
634 |
+
"align_self": null,
|
635 |
+
"border": null,
|
636 |
+
"bottom": null,
|
637 |
+
"display": null,
|
638 |
+
"flex": null,
|
639 |
+
"flex_flow": null,
|
640 |
+
"grid_area": null,
|
641 |
+
"grid_auto_columns": null,
|
642 |
+
"grid_auto_flow": null,
|
643 |
+
"grid_auto_rows": null,
|
644 |
+
"grid_column": null,
|
645 |
+
"grid_gap": null,
|
646 |
+
"grid_row": null,
|
647 |
+
"grid_template_areas": null,
|
648 |
+
"grid_template_columns": null,
|
649 |
+
"grid_template_rows": null,
|
650 |
+
"height": null,
|
651 |
+
"justify_content": null,
|
652 |
+
"justify_items": null,
|
653 |
+
"left": null,
|
654 |
+
"margin": null,
|
655 |
+
"max_height": null,
|
656 |
+
"max_width": null,
|
657 |
+
"min_height": null,
|
658 |
+
"min_width": null,
|
659 |
+
"object_fit": null,
|
660 |
+
"object_position": null,
|
661 |
+
"order": null,
|
662 |
+
"overflow": null,
|
663 |
+
"overflow_x": null,
|
664 |
+
"overflow_y": null,
|
665 |
+
"padding": null,
|
666 |
+
"right": null,
|
667 |
+
"top": null,
|
668 |
+
"visibility": null,
|
669 |
+
"width": null
|
670 |
+
}
|
671 |
+
},
|
672 |
+
"ba592297ff5347aebae298770a29fb8c": {
|
673 |
+
"model_module": "@jupyter-widgets/controls",
|
674 |
+
"model_module_version": "1.5.0",
|
675 |
+
"model_name": "DescriptionStyleModel",
|
676 |
+
"state": {
|
677 |
+
"_model_module": "@jupyter-widgets/controls",
|
678 |
+
"_model_module_version": "1.5.0",
|
679 |
+
"_model_name": "DescriptionStyleModel",
|
680 |
+
"_view_count": null,
|
681 |
+
"_view_module": "@jupyter-widgets/base",
|
682 |
+
"_view_module_version": "1.2.0",
|
683 |
+
"_view_name": "StyleView",
|
684 |
+
"description_width": ""
|
685 |
+
}
|
686 |
+
},
|
687 |
+
"c365a95346ec4b09a1e6467bf313baf7": {
|
688 |
+
"model_module": "@jupyter-widgets/controls",
|
689 |
+
"model_module_version": "1.5.0",
|
690 |
+
"model_name": "HBoxModel",
|
691 |
+
"state": {
|
692 |
+
"_dom_classes": [],
|
693 |
+
"_model_module": "@jupyter-widgets/controls",
|
694 |
+
"_model_module_version": "1.5.0",
|
695 |
+
"_model_name": "HBoxModel",
|
696 |
+
"_view_count": null,
|
697 |
+
"_view_module": "@jupyter-widgets/controls",
|
698 |
+
"_view_module_version": "1.5.0",
|
699 |
+
"_view_name": "HBoxView",
|
700 |
+
"box_style": "",
|
701 |
+
"children": [
|
702 |
+
"IPY_MODEL_d79fd51849fd463cb08b83fdb8e5ca0c",
|
703 |
+
"IPY_MODEL_d247683a0a61441b971dfb39062e1fbf",
|
704 |
+
"IPY_MODEL_1da23fc236034f32adcaf6bb2e0e7d80"
|
705 |
+
],
|
706 |
+
"layout": "IPY_MODEL_4b2126d97c514795ab2a90f7357a203c"
|
707 |
+
}
|
708 |
+
},
|
709 |
+
"d247683a0a61441b971dfb39062e1fbf": {
|
710 |
+
"model_module": "@jupyter-widgets/controls",
|
711 |
+
"model_module_version": "1.5.0",
|
712 |
+
"model_name": "FloatProgressModel",
|
713 |
+
"state": {
|
714 |
+
"_dom_classes": [],
|
715 |
+
"_model_module": "@jupyter-widgets/controls",
|
716 |
+
"_model_module_version": "1.5.0",
|
717 |
+
"_model_name": "FloatProgressModel",
|
718 |
+
"_view_count": null,
|
719 |
+
"_view_module": "@jupyter-widgets/controls",
|
720 |
+
"_view_module_version": "1.5.0",
|
721 |
+
"_view_name": "ProgressView",
|
722 |
+
"bar_style": "success",
|
723 |
+
"description": "",
|
724 |
+
"description_tooltip": null,
|
725 |
+
"layout": "IPY_MODEL_20aa0031b7bb45bf82443b48b3694166",
|
726 |
+
"max": 11,
|
727 |
+
"min": 0,
|
728 |
+
"orientation": "horizontal",
|
729 |
+
"style": "IPY_MODEL_67252ea545d64392a1bd6ac40852e65f",
|
730 |
+
"value": 11
|
731 |
+
}
|
732 |
+
},
|
733 |
+
"d79fd51849fd463cb08b83fdb8e5ca0c": {
|
734 |
+
"model_module": "@jupyter-widgets/controls",
|
735 |
+
"model_module_version": "1.5.0",
|
736 |
+
"model_name": "HTMLModel",
|
737 |
+
"state": {
|
738 |
+
"_dom_classes": [],
|
739 |
+
"_model_module": "@jupyter-widgets/controls",
|
740 |
+
"_model_module_version": "1.5.0",
|
741 |
+
"_model_name": "HTMLModel",
|
742 |
+
"_view_count": null,
|
743 |
+
"_view_module": "@jupyter-widgets/controls",
|
744 |
+
"_view_module_version": "1.5.0",
|
745 |
+
"_view_name": "HTMLView",
|
746 |
+
"description": "",
|
747 |
+
"description_tooltip": null,
|
748 |
+
"layout": "IPY_MODEL_9775ce64008b417fac3edd55b9e999d9",
|
749 |
+
"placeholder": "",
|
750 |
+
"style": "IPY_MODEL_96c9bb2eff4043b2a5dbd1e3e65375e5",
|
751 |
+
"value": "Fetching 11 files: 100%"
|
752 |
+
}
|
753 |
+
}
|
754 |
+
}
|
755 |
+
}
|
756 |
+
},
|
757 |
+
"nbformat": 4,
|
758 |
+
"nbformat_minor": 0
|
759 |
+
}
|
ChatTTS/examples/ipynb/example.ipynb
ADDED
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {},
|
6 |
+
"source": [
|
7 |
+
"## Import packages"
|
8 |
+
]
|
9 |
+
},
|
10 |
+
{
|
11 |
+
"cell_type": "code",
|
12 |
+
"execution_count": null,
|
13 |
+
"metadata": {},
|
14 |
+
"outputs": [],
|
15 |
+
"source": [
|
16 |
+
"from dotenv import load_dotenv\n",
|
17 |
+
"load_dotenv(\"sha256.env\")\n",
|
18 |
+
"\n",
|
19 |
+
"import torch\n",
|
20 |
+
"torch._dynamo.config.cache_size_limit = 64\n",
|
21 |
+
"torch._dynamo.config.suppress_errors = True\n",
|
22 |
+
"torch.set_float32_matmul_precision('high')\n",
|
23 |
+
"\n",
|
24 |
+
"import ChatTTS\n",
|
25 |
+
"from IPython.display import Audio"
|
26 |
+
]
|
27 |
+
},
|
28 |
+
{
|
29 |
+
"cell_type": "markdown",
|
30 |
+
"metadata": {},
|
31 |
+
"source": [
|
32 |
+
"## Load Models"
|
33 |
+
]
|
34 |
+
},
|
35 |
+
{
|
36 |
+
"cell_type": "code",
|
37 |
+
"execution_count": null,
|
38 |
+
"metadata": {},
|
39 |
+
"outputs": [],
|
40 |
+
"source": [
|
41 |
+
"chat = ChatTTS.Chat()\n",
|
42 |
+
"chat.load_models()\n",
|
43 |
+
"\n",
|
44 |
+
"# Use force_redownload=True if the weights updated.\n",
|
45 |
+
"# chat.load_models(force_redownload=True)\n",
|
46 |
+
"\n",
|
47 |
+
"# If you download the weights manually, set source='locals'.\n",
|
48 |
+
"# chat.load_models(source='local', local_path='YOUR LOCAL PATH')"
|
49 |
+
]
|
50 |
+
},
|
51 |
+
{
|
52 |
+
"cell_type": "markdown",
|
53 |
+
"metadata": {},
|
54 |
+
"source": [
|
55 |
+
"## Inference"
|
56 |
+
]
|
57 |
+
},
|
58 |
+
{
|
59 |
+
"cell_type": "markdown",
|
60 |
+
"metadata": {},
|
61 |
+
"source": [
|
62 |
+
"### Batch infer"
|
63 |
+
]
|
64 |
+
},
|
65 |
+
{
|
66 |
+
"cell_type": "code",
|
67 |
+
"execution_count": null,
|
68 |
+
"metadata": {},
|
69 |
+
"outputs": [],
|
70 |
+
"source": [
|
71 |
+
"texts = [\"So we found being competitive and collaborative was a huge way of staying motivated towards our goals, so one person to call when you fall off, one person who gets you back on then one person to actually do the activity with.\",]*3 \\\n",
|
72 |
+
" + [\"我觉得像我们这些写程序的人,他,我觉得多多少少可能会对开源有一种情怀在吧我觉得开源是一个很好的形式。现在其实最先进的技术掌握在一些公司的手里的话,就他们并不会轻易的开放给所有的人用。\"]*3 \n",
|
73 |
+
" \n",
|
74 |
+
"wavs = chat.infer(texts)"
|
75 |
+
]
|
76 |
+
},
|
77 |
+
{
|
78 |
+
"cell_type": "code",
|
79 |
+
"execution_count": null,
|
80 |
+
"metadata": {},
|
81 |
+
"outputs": [],
|
82 |
+
"source": [
|
83 |
+
"Audio(wavs[0], rate=24_000, autoplay=True)"
|
84 |
+
]
|
85 |
+
},
|
86 |
+
{
|
87 |
+
"cell_type": "code",
|
88 |
+
"execution_count": null,
|
89 |
+
"metadata": {},
|
90 |
+
"outputs": [],
|
91 |
+
"source": [
|
92 |
+
"Audio(wavs[3], rate=24_000, autoplay=True)"
|
93 |
+
]
|
94 |
+
},
|
95 |
+
{
|
96 |
+
"cell_type": "markdown",
|
97 |
+
"metadata": {},
|
98 |
+
"source": [
|
99 |
+
"### Custom params"
|
100 |
+
]
|
101 |
+
},
|
102 |
+
{
|
103 |
+
"cell_type": "code",
|
104 |
+
"execution_count": null,
|
105 |
+
"metadata": {},
|
106 |
+
"outputs": [],
|
107 |
+
"source": [
|
108 |
+
"params_infer_code = {'prompt':'[speed_5]', 'temperature':.3}\n",
|
109 |
+
"params_refine_text = {'prompt':'[oral_2][laugh_0][break_6]'}\n",
|
110 |
+
"\n",
|
111 |
+
"wav = chat.infer('四川美食可多了,有麻辣火锅、宫保鸡丁、麻婆豆腐、担担面、回锅肉、夫妻肺片等,每样都让人垂涎三尺。', \\\n",
|
112 |
+
" params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
|
113 |
+
]
|
114 |
+
},
|
115 |
+
{
|
116 |
+
"cell_type": "code",
|
117 |
+
"execution_count": null,
|
118 |
+
"metadata": {},
|
119 |
+
"outputs": [],
|
120 |
+
"source": [
|
121 |
+
"Audio(wav[0], rate=24_000, autoplay=True)"
|
122 |
+
]
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"cell_type": "markdown",
|
126 |
+
"metadata": {},
|
127 |
+
"source": [
|
128 |
+
"### Fix random speaker"
|
129 |
+
]
|
130 |
+
},
|
131 |
+
{
|
132 |
+
"cell_type": "code",
|
133 |
+
"execution_count": null,
|
134 |
+
"metadata": {},
|
135 |
+
"outputs": [],
|
136 |
+
"source": [
|
137 |
+
"rand_spk = chat.sample_random_speaker()\n",
|
138 |
+
"params_infer_code = {'spk_emb' : rand_spk, }\n",
|
139 |
+
"\n",
|
140 |
+
"wav = chat.infer('四川美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。', \\\n",
|
141 |
+
" params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
|
142 |
+
]
|
143 |
+
},
|
144 |
+
{
|
145 |
+
"cell_type": "code",
|
146 |
+
"execution_count": null,
|
147 |
+
"metadata": {},
|
148 |
+
"outputs": [],
|
149 |
+
"source": [
|
150 |
+
"Audio(wav[0], rate=24_000, autoplay=True)"
|
151 |
+
]
|
152 |
+
},
|
153 |
+
{
|
154 |
+
"cell_type": "markdown",
|
155 |
+
"metadata": {},
|
156 |
+
"source": [
|
157 |
+
"### Two stage control"
|
158 |
+
]
|
159 |
+
},
|
160 |
+
{
|
161 |
+
"cell_type": "code",
|
162 |
+
"execution_count": null,
|
163 |
+
"metadata": {},
|
164 |
+
"outputs": [],
|
165 |
+
"source": [
|
166 |
+
"text = \"So we found being competitive and collaborative was a huge way of staying motivated towards our goals, so one person to call when you fall off, one person who gets you back on then one person to actually do the activity with.\"\n",
|
167 |
+
"chat.infer(text, refine_text_only=True)"
|
168 |
+
]
|
169 |
+
},
|
170 |
+
{
|
171 |
+
"cell_type": "code",
|
172 |
+
"execution_count": null,
|
173 |
+
"metadata": {},
|
174 |
+
"outputs": [],
|
175 |
+
"source": [
|
176 |
+
"text = 'so we found being competitive and collaborative [uv_break] was a huge way of staying [uv_break] motivated towards our goals, [uv_break] so [uv_break] one person to call [uv_break] when you fall off, [uv_break] one person who [uv_break] gets you back [uv_break] on then [uv_break] one person [uv_break] to actually do the activity with.'\n",
|
177 |
+
"wav = chat.infer(text, skip_refine_text=True)"
|
178 |
+
]
|
179 |
+
},
|
180 |
+
{
|
181 |
+
"cell_type": "markdown",
|
182 |
+
"metadata": {},
|
183 |
+
"source": [
|
184 |
+
"## LLM Call"
|
185 |
+
]
|
186 |
+
},
|
187 |
+
{
|
188 |
+
"cell_type": "code",
|
189 |
+
"execution_count": null,
|
190 |
+
"metadata": {},
|
191 |
+
"outputs": [],
|
192 |
+
"source": [
|
193 |
+
"from ChatTTS.experimental.llm import llm_api\n",
|
194 |
+
"\n",
|
195 |
+
"API_KEY = ''\n",
|
196 |
+
"client = llm_api(api_key=API_KEY,\n",
|
197 |
+
" base_url=\"https://api.deepseek.com\",\n",
|
198 |
+
" model=\"deepseek-chat\")"
|
199 |
+
]
|
200 |
+
},
|
201 |
+
{
|
202 |
+
"cell_type": "code",
|
203 |
+
"execution_count": null,
|
204 |
+
"metadata": {},
|
205 |
+
"outputs": [],
|
206 |
+
"source": [
|
207 |
+
"user_question = '四川有哪些好吃的美食呢?'\n",
|
208 |
+
"text = client.call(user_question, prompt_version = 'deepseek')\n",
|
209 |
+
"print(text)\n",
|
210 |
+
"text = client.call(text, prompt_version = 'deepseek_TN')\n",
|
211 |
+
"print(text)"
|
212 |
+
]
|
213 |
+
},
|
214 |
+
{
|
215 |
+
"cell_type": "code",
|
216 |
+
"execution_count": null,
|
217 |
+
"metadata": {},
|
218 |
+
"outputs": [],
|
219 |
+
"source": [
|
220 |
+
"params_infer_code = {'spk_emb' : rand_spk, 'temperature':.3}\n",
|
221 |
+
"\n",
|
222 |
+
"wav = chat.infer(text, params_infer_code=params_infer_code)"
|
223 |
+
]
|
224 |
+
}
|
225 |
+
],
|
226 |
+
"metadata": {
|
227 |
+
"kernelspec": {
|
228 |
+
"display_name": "Python 3 (ipykernel)",
|
229 |
+
"language": "python",
|
230 |
+
"name": "python3"
|
231 |
+
},
|
232 |
+
"language_info": {
|
233 |
+
"codemirror_mode": {
|
234 |
+
"name": "ipython",
|
235 |
+
"version": 3
|
236 |
+
},
|
237 |
+
"file_extension": ".py",
|
238 |
+
"mimetype": "text/x-python",
|
239 |
+
"name": "python",
|
240 |
+
"nbconvert_exporter": "python",
|
241 |
+
"pygments_lexer": "ipython3",
|
242 |
+
"version": "3.10.8"
|
243 |
+
}
|
244 |
+
},
|
245 |
+
"nbformat": 4,
|
246 |
+
"nbformat_minor": 4
|
247 |
+
}
|
ChatTTS/examples/web/webui.py
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, sys
|
2 |
+
|
3 |
+
if sys.platform == "darwin":
|
4 |
+
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
|
5 |
+
|
6 |
+
now_dir = os.getcwd()
|
7 |
+
sys.path.append(now_dir)
|
8 |
+
|
9 |
+
import random
|
10 |
+
import argparse
|
11 |
+
|
12 |
+
import torch
|
13 |
+
import gradio as gr
|
14 |
+
import numpy as np
|
15 |
+
|
16 |
+
from dotenv import load_dotenv
|
17 |
+
load_dotenv("sha256.env")
|
18 |
+
|
19 |
+
import ChatTTS
|
20 |
+
|
21 |
+
# 音色选项:用于预置合适的音色
|
22 |
+
voices = {
|
23 |
+
"默认": {"seed": 2},
|
24 |
+
"音色1": {"seed": 1111},
|
25 |
+
"音色2": {"seed": 2222},
|
26 |
+
"音色3": {"seed": 3333},
|
27 |
+
"音色4": {"seed": 4444},
|
28 |
+
"音色5": {"seed": 5555},
|
29 |
+
"音色6": {"seed": 6666},
|
30 |
+
"音色7": {"seed": 7777},
|
31 |
+
"音色8": {"seed": 8888},
|
32 |
+
"音色9": {"seed": 9999},
|
33 |
+
"音色10": {"seed": 11111},
|
34 |
+
}
|
35 |
+
|
36 |
+
def generate_seed():
|
37 |
+
new_seed = random.randint(1, 100000000)
|
38 |
+
return {
|
39 |
+
"__type__": "update",
|
40 |
+
"value": new_seed
|
41 |
+
}
|
42 |
+
|
43 |
+
# 返回选择音色对应的seed
|
44 |
+
def on_voice_change(vocie_selection):
|
45 |
+
return voices.get(vocie_selection)['seed']
|
46 |
+
|
47 |
+
def generate_audio(text, temperature, top_P, top_K, audio_seed_input, text_seed_input, refine_text_flag):
|
48 |
+
|
49 |
+
torch.manual_seed(audio_seed_input)
|
50 |
+
rand_spk = chat.sample_random_speaker()
|
51 |
+
params_infer_code = {
|
52 |
+
'spk_emb': rand_spk,
|
53 |
+
'temperature': temperature,
|
54 |
+
'top_P': top_P,
|
55 |
+
'top_K': top_K,
|
56 |
+
}
|
57 |
+
params_refine_text = {'prompt': '[oral_2][laugh_0][break_6]'}
|
58 |
+
|
59 |
+
torch.manual_seed(text_seed_input)
|
60 |
+
|
61 |
+
if refine_text_flag:
|
62 |
+
text = chat.infer(text,
|
63 |
+
skip_refine_text=False,
|
64 |
+
refine_text_only=True,
|
65 |
+
params_refine_text=params_refine_text,
|
66 |
+
params_infer_code=params_infer_code
|
67 |
+
)
|
68 |
+
|
69 |
+
wav = chat.infer(text,
|
70 |
+
skip_refine_text=True,
|
71 |
+
params_refine_text=params_refine_text,
|
72 |
+
params_infer_code=params_infer_code
|
73 |
+
)
|
74 |
+
|
75 |
+
audio_data = np.array(wav[0]).flatten()
|
76 |
+
sample_rate = 24000
|
77 |
+
text_data = text[0] if isinstance(text, list) else text
|
78 |
+
|
79 |
+
return [(sample_rate, audio_data), text_data]
|
80 |
+
|
81 |
+
|
82 |
+
def main():
|
83 |
+
|
84 |
+
with gr.Blocks() as demo:
|
85 |
+
gr.Markdown("# ChatTTS Webui")
|
86 |
+
gr.Markdown("ChatTTS Model: [2noise/ChatTTS](https://github.com/2noise/ChatTTS)")
|
87 |
+
|
88 |
+
default_text = "四川美食确实以辣闻名,但也有不辣的选择。[uv_break]比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。[laugh]"
|
89 |
+
text_input = gr.Textbox(label="Input Text", lines=4, placeholder="Please Input Text...", value=default_text)
|
90 |
+
|
91 |
+
with gr.Row():
|
92 |
+
refine_text_checkbox = gr.Checkbox(label="Refine text", value=True)
|
93 |
+
temperature_slider = gr.Slider(minimum=0.00001, maximum=1.0, step=0.00001, value=0.3, label="Audio temperature")
|
94 |
+
top_p_slider = gr.Slider(minimum=0.1, maximum=0.9, step=0.05, value=0.7, label="top_P")
|
95 |
+
top_k_slider = gr.Slider(minimum=1, maximum=20, step=1, value=20, label="top_K")
|
96 |
+
|
97 |
+
with gr.Row():
|
98 |
+
voice_options = {}
|
99 |
+
voice_selection = gr.Dropdown(label="音色", choices=voices.keys(), value='默认')
|
100 |
+
audio_seed_input = gr.Number(value=2, label="Audio Seed")
|
101 |
+
generate_audio_seed = gr.Button("\U0001F3B2")
|
102 |
+
text_seed_input = gr.Number(value=42, label="Text Seed")
|
103 |
+
generate_text_seed = gr.Button("\U0001F3B2")
|
104 |
+
|
105 |
+
generate_button = gr.Button("Generate")
|
106 |
+
|
107 |
+
text_output = gr.Textbox(label="Output Text", interactive=False)
|
108 |
+
audio_output = gr.Audio(label="Output Audio")
|
109 |
+
|
110 |
+
# 使用Gradio的回调功能来更新数值输入框
|
111 |
+
voice_selection.change(fn=on_voice_change, inputs=voice_selection, outputs=audio_seed_input)
|
112 |
+
|
113 |
+
generate_audio_seed.click(generate_seed,
|
114 |
+
inputs=[],
|
115 |
+
outputs=audio_seed_input)
|
116 |
+
|
117 |
+
generate_text_seed.click(generate_seed,
|
118 |
+
inputs=[],
|
119 |
+
outputs=text_seed_input)
|
120 |
+
|
121 |
+
generate_button.click(generate_audio,
|
122 |
+
inputs=[text_input, temperature_slider, top_p_slider, top_k_slider, audio_seed_input, text_seed_input, refine_text_checkbox],
|
123 |
+
outputs=[audio_output, text_output])
|
124 |
+
|
125 |
+
gr.Examples(
|
126 |
+
examples=[
|
127 |
+
["四川美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。", 0.3, 0.7, 20, 2, 42, True],
|
128 |
+
["What is [uv_break]your favorite english food?[laugh][lbreak]", 0.5, 0.5, 10, 245, 531, True],
|
129 |
+
["chat T T S is a text to speech model designed for dialogue applications. [uv_break]it supports mixed language input [uv_break]and offers multi speaker capabilities with precise control over prosodic elements [laugh]like like [uv_break]laughter[laugh], [uv_break]pauses, [uv_break]and intonation. [uv_break]it delivers natural and expressive speech,[uv_break]so please[uv_break] use the project responsibly at your own risk.[uv_break]", 0.2, 0.6, 15, 67, 165, True],
|
130 |
+
],
|
131 |
+
inputs=[text_input, temperature_slider, top_p_slider, top_k_slider, audio_seed_input, text_seed_input, refine_text_checkbox],
|
132 |
+
)
|
133 |
+
|
134 |
+
parser = argparse.ArgumentParser(description='ChatTTS demo Launch')
|
135 |
+
parser.add_argument('--server_name', type=str, default='0.0.0.0', help='Server name')
|
136 |
+
parser.add_argument('--server_port', type=int, default=8080, help='Server port')
|
137 |
+
parser.add_argument('--root_path', type=str, default=None, help='Root Path')
|
138 |
+
parser.add_argument('--custom_path', type=str, default=None, help='the custom model path')
|
139 |
+
args = parser.parse_args()
|
140 |
+
|
141 |
+
print("loading ChatTTS model...")
|
142 |
+
global chat
|
143 |
+
chat = ChatTTS.Chat()
|
144 |
+
|
145 |
+
if args.custom_path == None:
|
146 |
+
chat.load_models()
|
147 |
+
else:
|
148 |
+
print('local model path:', args.custom_path)
|
149 |
+
chat.load_models('custom', custom_path=args.custom_path)
|
150 |
+
|
151 |
+
demo.launch(server_name=args.server_name, server_port=args.server_port, root_path=args.root_path, inbrowser=True)
|
152 |
+
|
153 |
+
|
154 |
+
if __name__ == '__main__':
|
155 |
+
main()
|
{abc → ChatTTS}/requirements.txt
RENAMED
@@ -1,7 +1,14 @@
|
|
|
|
1 |
omegaconf~=2.3.0
|
2 |
-
torch~=2.0
|
3 |
tqdm
|
4 |
einops
|
5 |
vector_quantize_pytorch
|
6 |
transformers~=4.41.1
|
7 |
vocos
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
numpy<2.0.0
|
2 |
omegaconf~=2.3.0
|
3 |
+
torch~=2.1.0
|
4 |
tqdm
|
5 |
einops
|
6 |
vector_quantize_pytorch
|
7 |
transformers~=4.41.1
|
8 |
vocos
|
9 |
+
IPython
|
10 |
+
gradio
|
11 |
+
python-dotenv
|
12 |
+
pynini==2.1.5
|
13 |
+
WeTextProcessing
|
14 |
+
nemo_text_processing
|
ChatTTS/setup.py
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from setuptools import setup, find_packages
|
2 |
+
setup(name='chattts',
|
3 |
+
version='0.0.1',
|
4 |
+
author='2noise',
|
5 |
+
url='https://github.com/2noise/ChatTTS',
|
6 |
+
install_requires=['omegaconf>=2.3.0',
|
7 |
+
'torch>=2.1.0',
|
8 |
+
'tqdm',
|
9 |
+
'einops',
|
10 |
+
'vector_quantize_pytorch',
|
11 |
+
'transformers>=4.41.1',
|
12 |
+
'vocos',
|
13 |
+
'IPython',
|
14 |
+
], # 定义依赖哪些模块
|
15 |
+
packages=find_packages(), # 系统自动从当前目录开始找包
|
16 |
+
)
|
ChatTTS/sha256.env
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
sha256_asset_Decoder_pt = 9964e36e840f0e3a748c5f716fe6de6490d2135a5f5155f4a642d51860e2ec38
|
2 |
+
sha256_asset_DVAE_pt = 613cb128adf89188c93ea5880ea0b798e66b1fe6186d0c535d99bcd87bfd6976
|
3 |
+
sha256_asset_GPT_pt = d7d4ee6461ea097a2be23eb40d73fb94ad3b3d39cb64fbb50cb3357fd466cadb
|
4 |
+
sha256_asset_spk_stat_pt = 3228d8a4cbbf349d107a1b76d2f47820865bd3c9928c4bdfe1cefd5c7071105f
|
5 |
+
sha256_asset_tokenizer_pt = e911ae7c6a7c27953433f35c44227a67838fe229a1f428503bdb6cd3d1bcc69c
|
6 |
+
sha256_asset_Vocos_pt = 09a670eda1c08b740013679c7a90ebb7f1a97646ea7673069a6838e6b51d6c58
|
7 |
+
|
8 |
+
sha256_config_decoder_yaml = 0890ab719716b0ad8abcb9eba0a9bf52c59c2e45ddedbbbb5ed514ff87bff369
|
9 |
+
sha256_config_dvae_yaml = 1b3a5aa0c6a314f766d4432ab36f84e882e29561648d837f71c04c7bea494fc6
|
10 |
+
sha256_config_gpt_yaml = 0c3c7277b674094bdd00b63b18b18aa3156502101dbd03c7f802e0fcf26cff51
|
11 |
+
sha256_config_path_yaml = 79829705c2d2a29b3f55e3b3f228bb81875e4e265211595fb50a73eb6434684b
|
12 |
+
sha256_config_vocos_yaml = 1ca837ce790dd8b55bdd5a16c6af8f813926b9c9b48f2a4da305e7e9ff0c9b0c
|
ChatTTS/tools/checksum/main.go
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
package main
|
2 |
+
|
3 |
+
import (
|
4 |
+
"crypto/sha256"
|
5 |
+
"encoding/hex"
|
6 |
+
"fmt"
|
7 |
+
"io"
|
8 |
+
"os"
|
9 |
+
)
|
10 |
+
|
11 |
+
func main() {
|
12 |
+
var buf [32]byte
|
13 |
+
h := sha256.New()
|
14 |
+
lst := make([]any, 0, 64)
|
15 |
+
for _, fname := range files {
|
16 |
+
f, err := os.Open(fname)
|
17 |
+
if err != nil {
|
18 |
+
panic(err)
|
19 |
+
}
|
20 |
+
_, err = io.Copy(h, f)
|
21 |
+
if err != nil {
|
22 |
+
panic(err)
|
23 |
+
}
|
24 |
+
s := hex.EncodeToString(h.Sum(buf[:0]))
|
25 |
+
fmt.Println("sha256 of", fname, "=", s)
|
26 |
+
lst = append(lst, s)
|
27 |
+
h.Reset()
|
28 |
+
f.Close()
|
29 |
+
}
|
30 |
+
f, err := os.Create("sha256.env")
|
31 |
+
if err != nil {
|
32 |
+
panic(err)
|
33 |
+
}
|
34 |
+
_, err = fmt.Fprintf(f, envtmpl, lst...)
|
35 |
+
if err != nil {
|
36 |
+
panic(err)
|
37 |
+
}
|
38 |
+
}
|
ChatTTS/tools/checksum/tmpl.go
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
package main
|
2 |
+
|
3 |
+
var files = [...]string{
|
4 |
+
"asset/Decoder.pt",
|
5 |
+
"asset/DVAE.pt",
|
6 |
+
"asset/GPT.pt",
|
7 |
+
"asset/spk_stat.pt",
|
8 |
+
"asset/tokenizer.pt",
|
9 |
+
"asset/Vocos.pt",
|
10 |
+
|
11 |
+
"config/decoder.yaml",
|
12 |
+
"config/dvae.yaml",
|
13 |
+
"config/gpt.yaml",
|
14 |
+
"config/path.yaml",
|
15 |
+
"config/vocos.yaml",
|
16 |
+
}
|
17 |
+
|
18 |
+
const envtmpl = `sha256_asset_Decoder_pt = %s
|
19 |
+
sha256_asset_DVAE_pt = %s
|
20 |
+
sha256_asset_GPT_pt = %s
|
21 |
+
sha256_asset_spk_stat_pt = %s
|
22 |
+
sha256_asset_tokenizer_pt = %s
|
23 |
+
sha256_asset_Vocos_pt = %s
|
24 |
+
|
25 |
+
sha256_config_decoder_yaml = %s
|
26 |
+
sha256_config_dvae_yaml = %s
|
27 |
+
sha256_config_gpt_yaml = %s
|
28 |
+
sha256_config_path_yaml = %s
|
29 |
+
sha256_config_vocos_yaml = %s
|
30 |
+
`
|
README.md
CHANGED
@@ -1,15 +1,121 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ChatTTS_colab
|
2 |
+
|
3 |
+
🚀 一键部署(含win离线整合包)!基于 [ChatTTS](https://github.com/2noise/ChatTTS) ,支持音色抽卡、长音频生成和分角色朗读。简单易用,无需复杂安装。。
|
4 |
+
|
5 |
+
**🏆 2000条说话人音色库已开源 🏆** 项目地址: [ChatTTS_Speaker](https://github.com/6drf21e/ChatTTS_Speaker)
|
6 |
+
|
7 |
+
> 支持按男女、年龄、特征查找稳定音色。
|
8 |
+
|
9 |
+
# 下载地址
|
10 |
+
|
11 |
+
| 版本 | 地址 | 介绍 |
|
12 |
+
|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------|
|
13 |
+
| 在线Colab版 | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/6drf21e/ChatTTS_colab/blob/main/chattts_webui_mix.ipynb) | 可以在 Google Colab 上一键运行,需要 Google账号,Colab 自带15GB的GPU |
|
14 |
+
| 离线整合版 | [百度网盘](https://pan.baidu.com/s/1-hGiPLs6ORM8sZv0xTdxFA?pwd=h3c5) 提取码: h3c5 | 下载本地运行,支持 GPU/CPU,适用 Windows 10 及以上 |
|
15 |
+
| 离线整合版 | [夸克网盘](https://pan.quark.cn/s/c963e147f204) | 下载本地运行,支持 GPU/CPU,适用 Windows 10 及以上 |
|
16 |
+
|
17 |
+
# 演示视频
|
18 |
+
|
19 |
+
[![演示视频](https://img.youtube.com/vi/199fyU7NfUQ/0.jpg)](https://www.youtube.com/watch?v=199fyU7NfUQ)
|
20 |
+
|
21 |
+
欢迎关注 [氪学家频道](https://www.youtube.com/@kexue) ,获取更多有趣的科技视频。
|
22 |
+
|
23 |
+
## 特点
|
24 |
+
|
25 |
+
- **Colab 一键运行**:无需复杂的环境配置,只需点击上方的 Colab 按钮,即可在浏览器中直接运行项目。
|
26 |
+
- **音色抽卡功能**:批量生成多个音色,并可保存自己喜欢的音色。
|
27 |
+
- **支持生成长音频**:适合生成较长的语音内容。
|
28 |
+
- **字符处理**:对数字和朗读错误的标点做了初步处理。
|
29 |
+
- **分角色朗读功能** :支持对不同角色的文本进行分角色朗读,并支持大模型一键生产脚本。
|
30 |
+
|
31 |
+
## 功能展示
|
32 |
+
|
33 |
+
### 分角色朗读功能
|
34 |
+
|
35 |
+
![分角色朗读功能](assets/shot3.png)
|
36 |
+
|
37 |
+
### 音色抽卡功能
|
38 |
+
|
39 |
+
![音色抽卡功能](assets/shot1.png)
|
40 |
+
|
41 |
+
### 支持生成长音频
|
42 |
+
|
43 |
+
![生成长音频](assets/shot2.png)
|
44 |
+
|
45 |
+
## 快速开始
|
46 |
+
|
47 |
+
### 在 Colab 运行
|
48 |
+
|
49 |
+
1. 点击最上方的 "Open In Colab" 按钮,打开 Colab 笔记本。
|
50 |
+
2. 点击菜单栏的–代码执行程序–全部运行即可
|
51 |
+
3. 执行后在下方的日志中找到类似
|
52 |
+
Running on public URL: https://**********.gradio.live
|
53 |
+
4. https://**********.gradio.live 就是可以访问的公网地址
|
54 |
+
|
55 |
+
### 在 macOS 上运行
|
56 |
+
|
57 |
+
1. 安装 [Conda](https://docs.conda.io/projects/conda/en/latest/user-guide/install/macos.html)(如果尚未安装)。
|
58 |
+
2. 打开终端,创建一个新的 conda 环境:
|
59 |
+
```bash
|
60 |
+
conda create -n "ChatTTS_colab" python=3.11
|
61 |
+
```
|
62 |
+
3. 激活刚创建的环境:
|
63 |
+
```bash
|
64 |
+
conda activate ChatTTS_colab
|
65 |
+
```
|
66 |
+
3. 克隆本项目仓库到本地:
|
67 |
+
```bash
|
68 |
+
git clone [email protected]:6drf21e/ChatTTS_colab.git
|
69 |
+
```
|
70 |
+
4. 手动安装 ChatTTS 依赖到项目目录:
|
71 |
+
```bash
|
72 |
+
cd ChatTTS_colab
|
73 |
+
git clone https://github.com/2noise/ChatTTS
|
74 |
+
cd ChatTTS
|
75 |
+
git checkout -q f4c8329
|
76 |
+
cd ..
|
77 |
+
mv ChatTTS temp
|
78 |
+
mv temp/ChatTTS ./ChatTTS
|
79 |
+
rm -rf temp
|
80 |
+
```
|
81 |
+
5. 在项目目录安装 ChatTTS_colab 所需的依赖:
|
82 |
+
```bash
|
83 |
+
pip install -r requirements-macos.txt
|
84 |
+
```
|
85 |
+
6. 运行项目,等待自动下载模型:
|
86 |
+
```bash
|
87 |
+
python webui_mix.py
|
88 |
+
# Loading ChatTTS model...
|
89 |
+
```
|
90 |
+
一切正常的话会自动打开浏览器。
|
91 |
+
|
92 |
+
## 常见问题:
|
93 |
+
|
94 |
+
1. 第一次运行项目,ChatTTS 会自动从 huggingface 下载模型,如果因为网络问题下载失败,那么 ChatTTS 是无法自行重新下载的,需要清除缓存后重新触发下载。
|
95 |
+
错误信息示例:
|
96 |
+
```log
|
97 |
+
FileNotFoundError: [Errno 2] No such file or directory: '~/.cache/huggingface/hub/models--2Noise--ChatTTS/snapshots/d7474137acb4f988874e5d57ad88d81bcb7e10b6/asset/Vocos.pt'
|
98 |
+
```
|
99 |
+
清除缓存的方法:
|
100 |
+
```bash
|
101 |
+
rm -rf ~/.cache/huggingface/hub/models--2Noise--ChatTTS
|
102 |
+
```
|
103 |
+
清除缓存后,再次执行 `python webui_mix.py`,就会重新下载模型。
|
104 |
+
|
105 |
+
如果多次下载都无法成功,可以手动将**离线包**里的 models 拷贝到项目目录,从本地加载模型
|
106 |
+
```bash
|
107 |
+
python webui_mix.py --source local --local_path models
|
108 |
+
```
|
109 |
+
2. 如果下载模型速度慢,建议使用赛博活菩萨 [@padeoe](https://github.com/padeoe) 的镜像加速 https://hf-mirror.com/
|
110 |
+
```bash
|
111 |
+
export HF_ENDPOINT=https://hf-mirror.com
|
112 |
+
```
|
113 |
+
|
114 |
+
## 贡献
|
115 |
+
|
116 |
+
欢迎对本项目提出建议或贡献代码。请通过 GitHub Issues 提出问题,或提交 Pull Request。
|
117 |
+
|
118 |
+
## 许可证
|
119 |
+
|
120 |
+
本项目使用 MIT 许可证。
|
121 |
+
|
abc/LICENSE
DELETED
@@ -1,157 +0,0 @@
|
|
1 |
-
# Attribution-NonCommercial-NoDerivatives 4.0 International
|
2 |
-
|
3 |
-
> *Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.*
|
4 |
-
>
|
5 |
-
> ### Using Creative Commons Public Licenses
|
6 |
-
>
|
7 |
-
> Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
|
8 |
-
>
|
9 |
-
> * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
|
10 |
-
>
|
11 |
-
> * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
|
12 |
-
|
13 |
-
## Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License
|
14 |
-
|
15 |
-
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
16 |
-
|
17 |
-
### Section 1 – Definitions.
|
18 |
-
|
19 |
-
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
20 |
-
|
21 |
-
b. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
|
22 |
-
|
23 |
-
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
24 |
-
|
25 |
-
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
26 |
-
|
27 |
-
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
28 |
-
|
29 |
-
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
30 |
-
|
31 |
-
h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
|
32 |
-
|
33 |
-
i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
|
34 |
-
|
35 |
-
j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
|
36 |
-
|
37 |
-
k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
38 |
-
|
39 |
-
l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
40 |
-
|
41 |
-
### Section 2 – Scope.
|
42 |
-
|
43 |
-
a. ___License grant.___
|
44 |
-
|
45 |
-
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
46 |
-
|
47 |
-
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
48 |
-
|
49 |
-
B. produce and reproduce, but not Share, Adapted Material for NonCommercial purposes only.
|
50 |
-
|
51 |
-
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
52 |
-
|
53 |
-
3. __Term.__ The term of this Public License is specified in Section 6(a).
|
54 |
-
|
55 |
-
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
56 |
-
|
57 |
-
5. __Downstream recipients.__
|
58 |
-
|
59 |
-
A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
60 |
-
|
61 |
-
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
62 |
-
|
63 |
-
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
|
64 |
-
|
65 |
-
b. ___Other rights.___
|
66 |
-
|
67 |
-
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
68 |
-
|
69 |
-
2. Patent and trademark rights are not licensed under this Public License.
|
70 |
-
|
71 |
-
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
|
72 |
-
|
73 |
-
### Section 3 – License Conditions.
|
74 |
-
|
75 |
-
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
76 |
-
|
77 |
-
a. ___Attribution.___
|
78 |
-
|
79 |
-
1. If You Share the Licensed Material, You must:
|
80 |
-
|
81 |
-
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
82 |
-
|
83 |
-
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
84 |
-
|
85 |
-
ii. a copyright notice;
|
86 |
-
|
87 |
-
iii. a notice that refers to this Public License;
|
88 |
-
|
89 |
-
iv. a notice that refers to the disclaimer of warranties;
|
90 |
-
|
91 |
-
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
92 |
-
|
93 |
-
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
94 |
-
|
95 |
-
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
96 |
-
|
97 |
-
For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.
|
98 |
-
|
99 |
-
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
100 |
-
|
101 |
-
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
102 |
-
|
103 |
-
### Section 4 – Sui Generis Database Rights.
|
104 |
-
|
105 |
-
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
106 |
-
|
107 |
-
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only and provided You do not Share Adapted Material;
|
108 |
-
|
109 |
-
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
|
110 |
-
|
111 |
-
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
112 |
-
|
113 |
-
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
114 |
-
|
115 |
-
### Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
116 |
-
|
117 |
-
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
|
118 |
-
|
119 |
-
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
|
120 |
-
|
121 |
-
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
122 |
-
|
123 |
-
### Section 6 – Term and Termination.
|
124 |
-
|
125 |
-
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
126 |
-
|
127 |
-
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
128 |
-
|
129 |
-
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
130 |
-
|
131 |
-
2. upon express reinstatement by the Licensor.
|
132 |
-
|
133 |
-
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
134 |
-
|
135 |
-
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
136 |
-
|
137 |
-
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
138 |
-
|
139 |
-
### Section 7 – Other Terms and Conditions.
|
140 |
-
|
141 |
-
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
142 |
-
|
143 |
-
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
144 |
-
|
145 |
-
### Section 8 – Interpretation.
|
146 |
-
|
147 |
-
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
148 |
-
|
149 |
-
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
150 |
-
|
151 |
-
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
152 |
-
|
153 |
-
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
154 |
-
|
155 |
-
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
|
156 |
-
>
|
157 |
-
> Creative Commons may be contacted at [creativecommons.org](http://creativecommons.org).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
abc/README_CN.md
DELETED
@@ -1,133 +0,0 @@
|
|
1 |
-
# ChatTTS
|
2 |
-
[**English**](./README.md) | [**中文简体**](./README_CN.md)
|
3 |
-
|
4 |
-
ChatTTS是专门为对话场景设计的文本转语音模型,例如LLM助手对话任务。它支持英文和中文两种语言。最大的模型使用了10万小时以上的中英文数据进行训练。在HuggingFace中开源的版本为4万小时训练且未SFT的版本.
|
5 |
-
|
6 |
-
如需就模型进行正式商业咨询,请发送邮件至 [email protected]。对于中文用户,您可以加入我们的QQ群:808364215 进行讨论。同时欢迎在GitHub上提出问题。如果遇到无法使用HuggingFace的情况,可以在[modelscope](https://www.modelscope.cn/models/pzc163/chatTTS)上进行下载.
|
7 |
-
|
8 |
-
---
|
9 |
-
## 亮点
|
10 |
-
1. **对话式 TTS**: ChatTTS针对对话式任务进行了优化,实现了自然流畅的语音合成,同时支持多说话人。
|
11 |
-
2. **细粒度控制**: 该模型能够预测和控制细粒度的韵律特征,包括笑声、停顿和插入词等。
|
12 |
-
3. **更好的韵律**: ChatTTS在韵律方面超越了大部分开源TTS模型。同时提供预训练模型,支持进一步的研究。
|
13 |
-
|
14 |
-
对于模型的具体介绍, 可以参考B站的[宣传视频](https://www.bilibili.com/video/BV1zn4y1o7iV)
|
15 |
-
|
16 |
-
---
|
17 |
-
|
18 |
-
## 免责声明
|
19 |
-
本文件中的信息仅供学术交流使用。其目的是用于教育和研究,不得用于任何商业或法律目的。作者不保证信息的准确性、完整性或可靠性。本文件中使用的信息和数据,仅用于学术研究目的。这些数据来自公开可用的来源,作者不对数据的所有权或版权提出任何主张。
|
20 |
-
|
21 |
-
ChatTTS是一个强大的文本转语音系统。然而,负责任地和符合伦理地利用这项技术是非常重要的。为了限制ChatTTS的使用,我们在4w小时模型的训练过程中添加了少量额外的高频噪音,并用mp3格式尽可能压低了音质,以防不法分子用于潜在的犯罪可能。同时我们在内部训练了检测模型,并计划在未来开放。
|
22 |
-
|
23 |
-
---
|
24 |
-
## 用法
|
25 |
-
|
26 |
-
<h4>基本用法</h4>
|
27 |
-
|
28 |
-
```python
|
29 |
-
import ChatTTS
|
30 |
-
from IPython.display import Audio
|
31 |
-
|
32 |
-
chat = ChatTTS.Chat()
|
33 |
-
chat.load_models()
|
34 |
-
|
35 |
-
texts = ["<PUT YOUR TEXT HERE>",]
|
36 |
-
|
37 |
-
wavs = chat.infer(texts, use_decoder=True)
|
38 |
-
Audio(wavs[0], rate=24_000, autoplay=True)
|
39 |
-
```
|
40 |
-
|
41 |
-
<h4>进阶用法</h4>
|
42 |
-
|
43 |
-
```python
|
44 |
-
###################################
|
45 |
-
# Sample a speaker from Gaussian.
|
46 |
-
import torch
|
47 |
-
std, mean = torch.load('ChatTTS/asset/spk_stat.pt').chunk(2)
|
48 |
-
rand_spk = torch.randn(768) * std + mean
|
49 |
-
|
50 |
-
params_infer_code = {
|
51 |
-
'spk_emb': rand_spk, # add sampled speaker
|
52 |
-
'temperature': .3, # using custom temperature
|
53 |
-
'top_P': 0.7, # top P decode
|
54 |
-
'top_K': 20, # top K decode
|
55 |
-
}
|
56 |
-
|
57 |
-
###################################
|
58 |
-
# For sentence level manual control.
|
59 |
-
|
60 |
-
# use oral_(0-9), laugh_(0-2), break_(0-7)
|
61 |
-
# to generate special token in text to synthesize.
|
62 |
-
params_refine_text = {
|
63 |
-
'prompt': '[oral_2][laugh_0][break_6]'
|
64 |
-
}
|
65 |
-
|
66 |
-
wav = chat.infer("<PUT YOUR TEXT HERE>", params_refine_text=params_refine_text, params_infer_code=params_infer_code)
|
67 |
-
|
68 |
-
###################################
|
69 |
-
# For word level manual control.
|
70 |
-
# use_decoder=False to infer faster with a bit worse quality
|
71 |
-
text = 'What is [uv_break]your favorite english food?[laugh][lbreak]'
|
72 |
-
wav = chat.infer(text, skip_refine_text=True, params_infer_code=params_infer_code, use_decoder=False)
|
73 |
-
|
74 |
-
```
|
75 |
-
|
76 |
-
<details open>
|
77 |
-
<summary><h4>自我介绍样例</h4></summary>
|
78 |
-
|
79 |
-
```python
|
80 |
-
inputs_cn = """
|
81 |
-
chat T T S 是一款强大的对话式文本转语音模型。它有中英混读和多说话人的能力。
|
82 |
-
chat T T S 不仅能够生成自然流畅的语音,还能控制[laugh]笑声啊[laugh],
|
83 |
-
停顿啊[uv_break]语气词啊等副语言现象[uv_break]。这个韵律超越了许多开源模型[uv_break]。
|
84 |
-
请注意,chat T T S 的使用应遵守法律和伦理准则,避免滥用的安全风险。[uv_break]'
|
85 |
-
""".replace('\n', '')
|
86 |
-
|
87 |
-
params_refine_text = {
|
88 |
-
'prompt': '[oral_2][laugh_0][break_4]'
|
89 |
-
}
|
90 |
-
audio_array_cn = chat.infer(inputs_cn, params_refine_text=params_refine_text)
|
91 |
-
audio_array_en = chat.infer(inputs_en, params_refine_text=params_refine_text)
|
92 |
-
```
|
93 |
-
[男说话人](https://github.com/2noise/ChatTTS/assets/130631963/bbfa3b83-2b67-4bb6-9315-64c992b63788)
|
94 |
-
|
95 |
-
[女说话人](https://github.com/2noise/ChatTTS/assets/130631963/e061f230-0e05-45e6-8e4e-0189f2d260c4)
|
96 |
-
</details>
|
97 |
-
|
98 |
-
|
99 |
-
---
|
100 |
-
## 计划路线
|
101 |
-
- [x] 开源4w小时基础模型和spk_stats文件
|
102 |
-
- [ ] 开源VQ encoder和Lora 训练代码
|
103 |
-
- [ ] 在非refine text情况下, 流式生成音频*
|
104 |
-
- [ ] 开源多情感可控的4w小时版本
|
105 |
-
- [ ] ChatTTS.cpp maybe? (欢迎社区PR或独立的新repo)
|
106 |
-
|
107 |
-
---
|
108 |
-
## 常见问题
|
109 |
-
|
110 |
-
##### 连不上HuggingFace
|
111 |
-
请使用[modelscope](https://www.modelscope.cn/models/pzc163/chatTTS)的版本. 并设置cache的位置:
|
112 |
-
```python
|
113 |
-
|
114 |
-
```
|
115 |
-
|
116 |
-
##### 我要多少显存? Infer的速度是怎么样的?
|
117 |
-
对于30s的音频, 至少需要4G的显存. 对于4090D, 1s生成约7个字所对应的音频. RTF约0.65.
|
118 |
-
|
119 |
-
##### 模型稳定性似乎不够好, 会出现其他说话人或音质很差的现象.
|
120 |
-
这是自回归模型通常都会出现的问题. 说话人可能会在中间变化, 可能会采样到音质非常差的结果, 这通常难以避免. 可以多采样几次来找到合适的结果.
|
121 |
-
|
122 |
-
##### 除了笑声还能控制什么吗? 还能控制其他情感吗?
|
123 |
-
在现在放出的模型版本中, 只有[laugh]和[uv_break], [lbreak]作为字级别的控制单元. 在未来的版本中我们可能会开源其他情感控制的版本.
|
124 |
-
|
125 |
-
---
|
126 |
-
## 致谢
|
127 |
-
- [bark](https://github.com/suno-ai/bark),[XTTSv2](https://github.com/coqui-ai/TTS)和[valle](https://arxiv.org/abs/2301.02111)展示了自回归任务用于TTS任务的可能性.
|
128 |
-
- [fish-speech](https://github.com/fishaudio/fish-speech)一个优秀的自回归TTS模型, 揭示了GVQ用于LLM任务的可能性.
|
129 |
-
- [vocos](https://github.com/gemelo-ai/vocos)作为模型中的vocoder.
|
130 |
-
|
131 |
-
---
|
132 |
-
## 特别致谢
|
133 |
-
- [wlu-audio lab](https://audio.westlake.edu.cn/)为我们提供了早期算法试验的支持.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
abc/infer.ipynb
DELETED
The diff for this file is too large to render.
See raw diff
|
|
requirements.txt
CHANGED
@@ -1,14 +1,4 @@
|
|
1 |
cn2an
|
2 |
pypinyin
|
3 |
openai
|
4 |
-
|
5 |
-
vector_quantize_pytorch
|
6 |
-
gradio
|
7 |
-
omegaconf~=2.3.0
|
8 |
-
torch~=2.1.0
|
9 |
-
tqdm
|
10 |
-
einops
|
11 |
-
transformers~=4.41.1
|
12 |
-
IPython
|
13 |
-
WeTextProcessing
|
14 |
-
jieba
|
|
|
1 |
cn2an
|
2 |
pypinyin
|
3 |
openai
|
4 |
+
WeTextProcessing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|