fcyai commited on
Commit
fc31c67
1 Parent(s): 0196a95
ChatTTS/core.py CHANGED
@@ -1,25 +1,32 @@
1
-
2
  import os
 
3
  import logging
4
- from omegaconf import OmegaConf
 
 
5
 
6
  import torch
 
7
  from vocos import Vocos
 
 
8
  from .model.dvae import DVAE
9
  from .model.gpt import GPT_warpper
10
  from .utils.gpu_utils import select_device
11
- from .utils.io_utils import get_latest_modified_file
 
12
  from .infer.api import refine_text, infer_code
13
-
14
- from huggingface_hub import snapshot_download
15
-
16
- logging.basicConfig(level = logging.INFO)
17
 
18
 
19
  class Chat:
20
- def __init__(self, ):
21
  self.pretrain_models = {}
22
- self.logger = logging.getLogger(__name__)
 
 
 
23
 
24
  def check_model(self, level = logging.INFO, use_decoder = False):
25
  not_finish = False
@@ -37,11 +44,25 @@ class Chat:
37
 
38
  if not not_finish:
39
  self.logger.log(level, f'All initialized.')
40
-
41
  return not not_finish
42
-
43
- def load_models(self, source='huggingface', force_redownload=False, local_path='<LOCAL_PATH>'):
44
- if source == 'huggingface':
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  hf_home = os.getenv('HF_HOME', os.path.expanduser("~/.cache/huggingface"))
46
  try:
47
  download_path = get_latest_modified_file(os.path.join(hf_home, 'hub/models--2Noise--ChatTTS/snapshots'))
@@ -52,10 +73,11 @@ class Chat:
52
  download_path = snapshot_download(repo_id="2Noise/ChatTTS", allow_patterns=["*.pt", "*.yaml"])
53
  else:
54
  self.logger.log(logging.INFO, f'Load from cache: {download_path}')
55
- self._load(**{k: os.path.join(download_path, v) for k, v in OmegaConf.load(os.path.join(download_path, 'config', 'path.yaml')).items()})
56
- elif source == 'local':
57
- self.logger.log(logging.INFO, f'Load from local: {local_path}')
58
- self._load(**{k: os.path.join(local_path, v) for k, v in OmegaConf.load(os.path.join(local_path, 'config', 'path.yaml')).items()})
 
59
 
60
  def _load(
61
  self,
@@ -68,14 +90,19 @@ class Chat:
68
  decoder_config_path: str = None,
69
  decoder_ckpt_path: str = None,
70
  tokenizer_path: str = None,
71
- device: str = None
 
72
  ):
73
- if not device:
74
  device = select_device(4096)
75
  self.logger.log(logging.INFO, f'use {device}')
76
-
 
77
  if vocos_config_path:
78
- vocos = Vocos.from_hparams(vocos_config_path).to(device).eval()
 
 
 
79
  assert vocos_ckpt_path, 'vocos_ckpt_path should not be None'
80
  vocos.load_state_dict(torch.load(vocos_ckpt_path))
81
  self.pretrain_models['vocos'] = vocos
@@ -85,15 +112,20 @@ class Chat:
85
  cfg = OmegaConf.load(dvae_config_path)
86
  dvae = DVAE(**cfg).to(device).eval()
87
  assert dvae_ckpt_path, 'dvae_ckpt_path should not be None'
88
- dvae.load_state_dict(torch.load(dvae_ckpt_path, map_location='cpu'))
89
  self.pretrain_models['dvae'] = dvae
90
  self.logger.log(logging.INFO, 'dvae loaded.')
91
 
92
  if gpt_config_path:
93
  cfg = OmegaConf.load(gpt_config_path)
94
- gpt = GPT_warpper(**cfg).to(device).eval()
95
  assert gpt_ckpt_path, 'gpt_ckpt_path should not be None'
96
- gpt.load_state_dict(torch.load(gpt_ckpt_path, map_location='cpu'))
 
 
 
 
 
97
  self.pretrain_models['gpt'] = gpt
98
  spk_stat_path = os.path.join(os.path.dirname(gpt_ckpt_path), 'spk_stat.pt')
99
  assert os.path.exists(spk_stat_path), f'Missing spk_stat.pt: {spk_stat_path}'
@@ -114,44 +146,190 @@ class Chat:
114
  self.pretrain_models['tokenizer'] = tokenizer
115
  self.logger.log(logging.INFO, 'tokenizer loaded.')
116
 
117
- self.check_model()
118
 
119
- def infer(
120
  self,
121
  text,
122
  skip_refine_text=False,
123
  refine_text_only=False,
124
  params_refine_text={},
125
- params_infer_code={},
126
- use_decoder=False
 
 
 
 
127
  ):
128
 
129
  assert self.check_model(use_decoder=use_decoder)
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  if not skip_refine_text:
132
- text_tokens = refine_text(self.pretrain_models, text, **params_refine_text)['ids']
 
 
 
 
 
133
  text_tokens = [i[i < self.pretrain_models['tokenizer'].convert_tokens_to_ids('[break_0]')] for i in text_tokens]
134
  text = self.pretrain_models['tokenizer'].batch_decode(text_tokens)
135
  if refine_text_only:
136
- return text
137
-
 
138
  text = [params_infer_code.get('prompt', '') + i for i in text]
139
  params_infer_code.pop('prompt', '')
140
- result = infer_code(self.pretrain_models, text, **params_infer_code, return_hidden=use_decoder)
141
-
 
 
 
 
 
 
142
  if use_decoder:
143
- mel_spec = [self.pretrain_models['decoder'](i[None].permute(0,2,1)) for i in result['hiddens']]
 
144
  else:
145
- mel_spec = [self.pretrain_models['dvae'](i[None].permute(0,2,1)) for i in result['ids']]
146
-
147
- wav = [self.pretrain_models['vocos'].decode(i).cpu().numpy() for i in mel_spec]
148
-
149
- return wav
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
  def sample_random_speaker(self, ):
152
 
153
  dim = self.pretrain_models['gpt'].gpt.layers[0].mlp.gate_proj.in_features
154
  std, mean = self.pretrain_models['spk_stat'].chunk(2)
155
  return torch.randn(dim, device=std.device) * std + mean
156
-
 
 
 
 
157
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import json
3
  import logging
4
+ import tempfile
5
+ from functools import partial
6
+ from typing import Literal, Optional
7
 
8
  import torch
9
+ from omegaconf import OmegaConf
10
  from vocos import Vocos
11
+ from huggingface_hub import snapshot_download
12
+
13
  from .model.dvae import DVAE
14
  from .model.gpt import GPT_warpper
15
  from .utils.gpu_utils import select_device
16
+ from .utils.infer_utils import count_invalid_characters, detect_language, apply_character_map, apply_half2full_map, HomophonesReplacer
17
+ from .utils.io import get_latest_modified_file, del_all
18
  from .infer.api import refine_text, infer_code
19
+ from .utils.download import check_all_assets, download_all_assets
20
+ from .utils.log import set_utils_logger
 
 
21
 
22
 
23
  class Chat:
24
+ def __init__(self, logger=logging.getLogger(__name__)):
25
  self.pretrain_models = {}
26
+ self.normalizer = {}
27
+ self.homophones_replacer = None
28
+ self.logger = logger
29
+ set_utils_logger(logger)
30
 
31
  def check_model(self, level = logging.INFO, use_decoder = False):
32
  not_finish = False
 
44
 
45
  if not not_finish:
46
  self.logger.log(level, f'All initialized.')
47
+
48
  return not not_finish
49
+
50
+ def load_models(
51
+ self,
52
+ source: Literal['huggingface', 'local', 'custom']='local',
53
+ force_redownload=False,
54
+ custom_path='<LOCAL_PATH>',
55
+ **kwargs,
56
+ ):
57
+ if source == 'local':
58
+ download_path = os.getcwd()
59
+ if not check_all_assets(update=True):
60
+ with tempfile.TemporaryDirectory() as tmp:
61
+ download_all_assets(tmpdir=tmp)
62
+ if not check_all_assets(update=False):
63
+ self.logger.error("counld not satisfy all assets needed.")
64
+ return False
65
+ elif source == 'huggingface':
66
  hf_home = os.getenv('HF_HOME', os.path.expanduser("~/.cache/huggingface"))
67
  try:
68
  download_path = get_latest_modified_file(os.path.join(hf_home, 'hub/models--2Noise--ChatTTS/snapshots'))
 
73
  download_path = snapshot_download(repo_id="2Noise/ChatTTS", allow_patterns=["*.pt", "*.yaml"])
74
  else:
75
  self.logger.log(logging.INFO, f'Load from cache: {download_path}')
76
+ elif source == 'custom':
77
+ self.logger.log(logging.INFO, f'Load from local: {custom_path}')
78
+ download_path = custom_path
79
+
80
+ return 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)
81
 
82
  def _load(
83
  self,
 
90
  decoder_config_path: str = None,
91
  decoder_ckpt_path: str = None,
92
  tokenizer_path: str = None,
93
+ device: Optional[torch.device] = None,
94
+ compile: bool = True,
95
  ):
96
+ if device is None:
97
  device = select_device(4096)
98
  self.logger.log(logging.INFO, f'use {device}')
99
+ self.device = 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 "mps" in str(device) 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
 
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, device=device, logger=self.logger).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
+ self.logger.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}'
 
146
  self.pretrain_models['tokenizer'] = tokenizer
147
  self.logger.log(logging.INFO, 'tokenizer loaded.')
148
 
149
+ return 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], replaced_words = self.homophones_replacer.replace(text[i])
183
+ if replaced_words:
184
+ repl_res = ', '.join([f'{_[0]}->{_[1]}' for _ in replaced_words])
185
+ self.logger.log(logging.INFO, f'Homophones replace: {repl_res}')
186
+
187
  if not skip_refine_text:
188
+ text_tokens = refine_text(
189
+ self.pretrain_models,
190
+ text,
191
+ device=self.device,
192
+ **params_refine_text,
193
+ )['ids']
194
  text_tokens = [i[i < self.pretrain_models['tokenizer'].convert_tokens_to_ids('[break_0]')] for i in text_tokens]
195
  text = self.pretrain_models['tokenizer'].batch_decode(text_tokens)
196
  if refine_text_only:
197
+ yield text
198
+ return
199
+
200
  text = [params_infer_code.get('prompt', '') + i for i in text]
201
  params_infer_code.pop('prompt', '')
202
+ result_gen = infer_code(
203
+ self.pretrain_models,
204
+ text,
205
+ device=self.device,
206
+ **params_infer_code,
207
+ return_hidden=use_decoder,
208
+ stream=stream,
209
+ )
210
  if use_decoder:
211
+ field = 'hiddens'
212
+ docoder_name = 'decoder'
213
  else:
214
+ field = 'ids'
215
+ docoder_name = 'dvae'
216
+ if "mps" in str(self.device):
217
+ vocos_decode = lambda spec: [self.pretrain_models['vocos'].decode(
218
+ i.cpu()
219
+ ).cpu().numpy() for i in spec]
220
+ else:
221
+ vocos_decode = lambda spec: [self.pretrain_models['vocos'].decode(
222
+ i
223
+ ).cpu().numpy() for i in spec]
224
+ if stream:
225
+
226
+ length = 0
227
+ for result in result_gen:
228
+ chunk_data = result[field][0]
229
+ assert len(result[field]) == 1
230
+ start_seek = length
231
+ length = len(chunk_data)
232
+ self.logger.debug(f'{start_seek=} total len: {length}, new len: {length - start_seek = }')
233
+ chunk_data = chunk_data[start_seek:]
234
+ if not len(chunk_data):
235
+ continue
236
+ self.logger.debug(f'new hidden {len(chunk_data)=}')
237
+ mel_spec = [self.pretrain_models[docoder_name](i[None].permute(0,2,1).to(self.device)) for i in [chunk_data]]
238
+ del_all(result)
239
+ del chunk_data
240
+ wav = vocos_decode(mel_spec)
241
+ del_all(mel_spec)
242
+ self.logger.debug(f'yield wav chunk {len(wav[0])=} {len(wav[0][0])=}')
243
+ yield wav
244
+ return
245
+ result = next(result_gen)
246
+ mel_spec = [self.pretrain_models[docoder_name](i[None].permute(0,2,1).to(self.device)) for i in result[field]]
247
+ del_all(result)
248
+ wav = vocos_decode(mel_spec)
249
+ del_all(mel_spec)
250
+ yield wav
251
+
252
+ def infer(
253
+ self,
254
+ text,
255
+ skip_refine_text=False,
256
+ refine_text_only=False,
257
+ params_refine_text={},
258
+ params_infer_code={'prompt':'[speed_5]'},
259
+ use_decoder=True,
260
+ do_text_normalization=True,
261
+ lang=None,
262
+ stream=False,
263
+ do_homophone_replacement=True,
264
+ ):
265
+ res_gen = self._infer(
266
+ text,
267
+ skip_refine_text,
268
+ refine_text_only,
269
+ params_refine_text,
270
+ params_infer_code,
271
+ use_decoder,
272
+ do_text_normalization,
273
+ lang,
274
+ stream,
275
+ do_homophone_replacement,
276
+ )
277
+ if stream:
278
+ return res_gen
279
+ else:
280
+ return next(res_gen)
281
 
282
  def sample_random_speaker(self, ):
283
 
284
  dim = self.pretrain_models['gpt'].gpt.layers[0].mlp.gate_proj.in_features
285
  std, mean = self.pretrain_models['spk_stat'].chunk(2)
286
  return torch.randn(dim, device=std.device) * std + mean
287
+
288
+ def init_normalizer(self, lang) -> bool:
289
+
290
+ if lang in self.normalizer:
291
+ return True
292
 
293
+ if lang == 'zh':
294
+ try:
295
+ from tn.chinese.normalizer import Normalizer
296
+ self.normalizer[lang] = Normalizer().normalize
297
+ return True
298
+ except:
299
+ self.logger.log(
300
+ logging.WARNING,
301
+ 'Package WeTextProcessing not found!',
302
+ )
303
+ self.logger.log(
304
+ logging.WARNING,
305
+ 'Run: conda install -c conda-forge pynini=2.1.5 && pip install WeTextProcessing',
306
+ )
307
+ else:
308
+ try:
309
+ from nemo_text_processing.text_normalization.normalize import Normalizer
310
+ self.normalizer[lang] = partial(Normalizer(input_case='cased', lang=lang).normalize, verbose=False, punct_post_process=True)
311
+ return True
312
+ except:
313
+ self.logger.log(
314
+ logging.WARNING,
315
+ 'Package nemo_text_processing not found!',
316
+ )
317
+ self.logger.log(
318
+ logging.WARNING,
319
+ 'Run: conda install -c conda-forge pynini=2.1.5 && pip install nemo_text_processing',
320
+ )
321
+ return False
322
+
323
+ def init_homophones_replacer(self):
324
+ if self.homophones_replacer:
325
+ return True
326
+ else:
327
+ try:
328
+ self.homophones_replacer = HomophonesReplacer(os.path.join(os.path.dirname(__file__), 'res', 'homophones_map.json'))
329
+ self.logger.log(logging.INFO, 'homophones_replacer loaded.')
330
+ return True
331
+ except (IOError, json.JSONDecodeError) as e:
332
+ self.logger.log(logging.WARNING, f'Error loading homophones map: {e}')
333
+ except Exception as e:
334
+ self.logger.log(logging.WARNING, f'Error loading homophones_replacer: {e}')
335
+ return False
ChatTTS/infer/api.py CHANGED
@@ -2,7 +2,10 @@
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,
@@ -13,39 +16,43 @@ def infer_code(
13
  temperature = 0.3,
14
  repetition_penalty = 1.05,
15
  max_new_token = 2048,
 
 
16
  **kwargs
17
  ):
18
-
19
- device = next(models['gpt'].parameters()).device
20
-
21
  if not isinstance(text, list):
22
  text = [text]
23
 
24
  if not isinstance(temperature, list):
25
- temperature = [temperature] * models['gpt'].num_vq
26
 
27
  if spk_emb is not None:
28
- text = [f'[Stts][spk_emb]{i}[uv_break][Ptts]' for i in text]
29
  else:
30
- text = [f'[Stts][empty_spk]{i}[uv_break][Ptts]' for i in text]
31
-
32
- text_token = models['tokenizer'](text, return_tensors='pt', add_special_tokens=False, padding=True).to(device)
33
- input_ids = text_token['input_ids'][...,None].expand(-1, -1, models['gpt'].num_vq)
34
- text_mask = torch.ones(text_token['input_ids'].shape, dtype=bool, device=device)
35
 
36
- inputs = {
37
- 'input_ids': input_ids,
38
- 'text_mask': text_mask,
39
- 'attention_mask': text_token['attention_mask'],
40
- }
 
 
 
 
 
 
41
 
42
- emb = models['gpt'].get_emb(**inputs)
43
  if spk_emb is not None:
44
- emb[inputs['input_ids'][..., 0] == models['tokenizer'].convert_tokens_to_ids('[spk_emb]')] = \
45
- F.normalize(spk_emb.to(device).to(emb.dtype)[None].expand(len(text), -1), p=2.0, dim=1, eps=1e-12)
46
-
47
- num_code = models['gpt'].emb_code[0].num_embeddings - 1
48
-
 
49
  LogitsWarpers = []
50
  if top_P is not None:
51
  LogitsWarpers.append(TopPLogitsWarper(top_P, min_tokens_to_keep=3))
@@ -57,18 +64,24 @@ def infer_code(
57
  LogitsProcessors.append(CustomRepetitionPenaltyLogitsProcessorRepeat(\
58
  repetition_penalty, num_code, 16))
59
 
60
- result = models['gpt'].generate(
61
- emb, inputs['input_ids'],
62
  temperature = torch.tensor(temperature, device=device),
63
- attention_mask = inputs['attention_mask'],
64
  LogitsWarpers = LogitsWarpers,
65
  LogitsProcessors = LogitsProcessors,
66
  eos_token = num_code,
67
  max_new_token = max_new_token,
68
  infer_text = False,
 
69
  **kwargs
70
  )
71
-
 
 
 
 
 
72
  return result
73
 
74
 
@@ -81,11 +94,12 @@ def refine_text(
81
  repetition_penalty = 1.0,
82
  max_new_token = 384,
83
  prompt = '',
 
84
  **kwargs
85
  ):
86
-
87
- device = next(models['gpt'].parameters()).device
88
-
89
  if not isinstance(text, list):
90
  text = [text]
91
 
@@ -95,11 +109,7 @@ def refine_text(
95
  text_token = models['tokenizer'](text, return_tensors='pt', add_special_tokens=False, padding=True).to(device)
96
  text_mask = torch.ones(text_token['input_ids'].shape, dtype=bool, device=device)
97
 
98
- inputs = {
99
- 'input_ids': text_token['input_ids'][...,None].expand(-1, -1, models['gpt'].num_vq),
100
- 'text_mask': text_mask,
101
- 'attention_mask': text_token['attention_mask'],
102
- }
103
 
104
  LogitsWarpers = []
105
  if top_P is not None:
@@ -110,16 +120,29 @@ def refine_text(
110
  LogitsProcessors = []
111
  if repetition_penalty is not None and repetition_penalty != 1:
112
  LogitsProcessors.append(CustomRepetitionPenaltyLogitsProcessorRepeat(repetition_penalty, len(models['tokenizer']), 16))
113
-
114
- result = models['gpt'].generate(
115
- models['gpt'].get_emb(**inputs), inputs['input_ids'],
 
 
 
 
 
 
116
  temperature = torch.tensor([temperature,], device=device),
117
- attention_mask = inputs['attention_mask'],
118
  LogitsWarpers = LogitsWarpers,
119
  LogitsProcessors = LogitsProcessors,
120
  eos_token = torch.tensor(models['tokenizer'].convert_tokens_to_ids('[Ebreak]'), device=device)[None],
121
  max_new_token = max_new_token,
122
  infer_text = True,
 
123
  **kwargs
124
  )
125
- return result
 
 
 
 
 
 
 
2
  import torch
3
  import torch.nn.functional as F
4
  from transformers.generation import TopKLogitsWarper, TopPLogitsWarper
5
+
6
  from ..utils.infer_utils import CustomRepetitionPenaltyLogitsProcessorRepeat
7
+ from ..utils.io import del_all
8
+ from ..model.gpt import GPT_warpper
9
 
10
  def infer_code(
11
  models,
 
16
  temperature = 0.3,
17
  repetition_penalty = 1.05,
18
  max_new_token = 2048,
19
+ stream=False,
20
+ device="cpu",
21
  **kwargs
22
  ):
23
+
24
+ gpt: GPT_warpper = models['gpt']
25
+
26
  if not isinstance(text, list):
27
  text = [text]
28
 
29
  if not isinstance(temperature, list):
30
+ temperature = [temperature] * gpt.num_vq
31
 
32
  if spk_emb is not None:
33
+ text = [f'[Stts][spk_emb]{i}[Ptts]' for i in text]
34
  else:
35
+ text = [f'[Stts][empty_spk]{i}[Ptts]' for i in text]
 
 
 
 
36
 
37
+ text_token_tmp = models['tokenizer'](text, return_tensors='pt', add_special_tokens=False, padding=True)
38
+ text_token = text_token_tmp.to(device)
39
+ del text_token_tmp
40
+ input_ids = text_token['input_ids'][...,None].expand(-1, -1, gpt.num_vq).to(gpt.device_gpt)
41
+ text_mask = torch.ones(text_token['input_ids'].shape, dtype=bool, device=gpt.device_gpt)
42
+
43
+ emb = gpt.get_emb(
44
+ input_ids=input_ids,
45
+ text_mask=text_mask,
46
+ )
47
+ del text_mask
48
 
 
49
  if spk_emb is not None:
50
+ n = F.normalize(spk_emb.to(emb.dtype)[None].expand(len(text), -1), p=2.0, dim=1, eps=1e-12).to(gpt.device_gpt)
51
+ emb[input_ids[..., 0] == models['tokenizer'].convert_tokens_to_ids('[spk_emb]')] = n
52
+ del n
53
+
54
+ num_code = int(gpt.emb_code[0].num_embeddings - 1)
55
+
56
  LogitsWarpers = []
57
  if top_P is not None:
58
  LogitsWarpers.append(TopPLogitsWarper(top_P, min_tokens_to_keep=3))
 
64
  LogitsProcessors.append(CustomRepetitionPenaltyLogitsProcessorRepeat(\
65
  repetition_penalty, num_code, 16))
66
 
67
+ result = gpt.generate(
68
+ emb, input_ids,
69
  temperature = torch.tensor(temperature, device=device),
70
+ attention_mask = text_token['attention_mask'],
71
  LogitsWarpers = LogitsWarpers,
72
  LogitsProcessors = LogitsProcessors,
73
  eos_token = num_code,
74
  max_new_token = max_new_token,
75
  infer_text = False,
76
+ stream = stream,
77
  **kwargs
78
  )
79
+
80
+ del_all(text_token)
81
+ del emb, text_token, input_ids
82
+ del_all(LogitsWarpers)
83
+ del_all(LogitsProcessors)
84
+
85
  return result
86
 
87
 
 
94
  repetition_penalty = 1.0,
95
  max_new_token = 384,
96
  prompt = '',
97
+ device="cpu",
98
  **kwargs
99
  ):
100
+
101
+ gpt: GPT_warpper = models['gpt']
102
+
103
  if not isinstance(text, list):
104
  text = [text]
105
 
 
109
  text_token = models['tokenizer'](text, return_tensors='pt', add_special_tokens=False, padding=True).to(device)
110
  text_mask = torch.ones(text_token['input_ids'].shape, dtype=bool, device=device)
111
 
112
+ input_ids = text_token['input_ids'][...,None].expand(-1, -1, gpt.num_vq)
 
 
 
 
113
 
114
  LogitsWarpers = []
115
  if top_P is not None:
 
120
  LogitsProcessors = []
121
  if repetition_penalty is not None and repetition_penalty != 1:
122
  LogitsProcessors.append(CustomRepetitionPenaltyLogitsProcessorRepeat(repetition_penalty, len(models['tokenizer']), 16))
123
+
124
+ emb = gpt.get_emb(
125
+ input_ids=input_ids,
126
+ text_mask=text_mask,
127
+ )
128
+ del text_mask
129
+
130
+ result = gpt.generate(
131
+ emb, input_ids,
132
  temperature = torch.tensor([temperature,], device=device),
133
+ attention_mask = text_token['attention_mask'],
134
  LogitsWarpers = LogitsWarpers,
135
  LogitsProcessors = LogitsProcessors,
136
  eos_token = torch.tensor(models['tokenizer'].convert_tokens_to_ids('[Ebreak]'), device=device)[None],
137
  max_new_token = max_new_token,
138
  infer_text = True,
139
+ stream = False,
140
  **kwargs
141
  )
142
+
143
+ del_all(text_token)
144
+ del emb, text_token, input_ids
145
+ del_all(LogitsWarpers)
146
+ del_all(LogitsProcessors)
147
+
148
+ return next(result)
ChatTTS/model/dvae.py CHANGED
@@ -1,5 +1,4 @@
1
  import math
2
- from einops import rearrange
3
  from vector_quantize_pytorch import GroupedResidualFSQ
4
 
5
  import torch
@@ -66,23 +65,32 @@ class GFSQ(nn.Module):
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))
@@ -143,9 +151,9 @@ class DVAE(nn.Module):
143
  else:
144
  vq_feats = inp.detach().clone()
145
 
146
- temp = torch.chunk(vq_feats, 2, dim=1) # flatten trick :)
147
- temp = torch.stack(temp, -1)
148
- vq_feats = temp.reshape(*temp.shape[:2], -1)
149
 
150
  vq_feats = vq_feats.transpose(1, 2)
151
  dec_out = self.decoder(input=vq_feats)
 
1
  import math
 
2
  from vector_quantize_pytorch import GroupedResidualFSQ
3
 
4
  import torch
 
65
  self.G = G
66
  self.R = R
67
 
68
+ def _embed(self, x: torch.Tensor):
69
  if self.transpose:
70
  x = x.transpose(1,2)
71
+ """
72
  x = rearrange(
73
  x, "b t (g r) -> g b t r", g = self.G, r = self.R,
74
+ )
75
+ """
76
+ x.view(-1, self.G, self.R).permute(2, 0, 1, 3)
77
  feat = self.quantizer.get_output_from_indices(x)
78
  return feat.transpose(1,2) if self.transpose else feat
79
+
80
  def forward(self, x,):
81
  if self.transpose:
82
  x = x.transpose(1,2)
83
  feat, ind = self.quantizer(x)
84
+ """
85
  ind = rearrange(
86
  ind, "g b t r ->b t (g r)",
87
+ )
88
+ """
89
+ ind = ind.permute(1, 2, 0, 3).contiguous()
90
+ ind = ind.view(ind.size(0), ind.size(1), -1)
91
+ embed_onehot_tmp = F.one_hot(ind.long(), self.n_ind)
92
+ embed_onehot = embed_onehot_tmp.to(x.dtype)
93
+ del embed_onehot_tmp
94
  e_mean = torch.mean(embed_onehot, dim=[0,1])
95
  e_mean = e_mean / (e_mean.sum(dim=1) + self.eps).unsqueeze(1)
96
  perplexity = torch.exp(-torch.sum(e_mean * torch.log(e_mean + self.eps), dim=1))
 
151
  else:
152
  vq_feats = inp.detach().clone()
153
 
154
+ vq_feats = vq_feats.view(
155
+ (vq_feats.size(0), 2, vq_feats.size(1)//2, vq_feats.size(2)),
156
+ ).permute(0, 2, 3, 1).flatten(2)
157
 
158
  vq_feats = vq_feats.transpose(1, 2)
159
  dec_out = self.decoder(input=vq_feats)
ChatTTS/model/gpt.py CHANGED
@@ -2,8 +2,10 @@ 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
@@ -12,8 +14,10 @@ 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__()
@@ -36,41 +40,67 @@ class GPT_warpper(nn.Module):
36
  num_audio_tokens,
37
  num_text_tokens,
38
  num_vq=4,
39
- **kwargs,
40
- ):
 
41
  super().__init__()
42
 
43
- self.logger = logging.getLogger(__name__)
44
- self.gpt = self.build_model(gpt_config)
 
 
 
 
45
  self.model_dim = self.gpt.config.hidden_size
 
 
 
 
 
 
46
 
47
- self.num_vq = num_vq
48
- self.emb_code = nn.ModuleList([nn.Embedding(num_audio_tokens, self.model_dim) for i in range(self.num_vq)])
49
- self.emb_text = nn.Embedding(num_text_tokens, self.model_dim)
50
- self.head_text = weight_norm(nn.Linear(self.model_dim, num_text_tokens, bias=False), name='weight')
51
- 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)])
 
 
 
 
 
 
 
 
 
52
 
53
- def build_model(self, config):
54
 
55
  configuration = LlamaConfig(**config)
56
  model = LlamaModel(configuration)
57
  del model.embed_tokens
58
 
59
- return model
60
-
61
- def get_emb(self, input_ids, text_mask, **kwargs):
62
 
63
- emb_text = self.emb_text(input_ids[text_mask][:, 0])
64
-
65
- emb_code = [self.emb_code[i](input_ids[~text_mask][:, i]) for i in range(self.num_vq)]
 
 
 
 
 
 
66
  emb_code = torch.stack(emb_code, 2).sum(2)
67
-
68
  emb = torch.zeros((input_ids.shape[:-1])+(emb_text.shape[-1],), device=emb_text.device, dtype=emb_text.dtype)
69
  emb[text_mask] = emb_text
70
  emb[~text_mask] = emb_code.to(emb.dtype)
71
-
 
 
72
  return emb
73
-
74
  def prepare_inputs_for_generation(
75
  self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
76
  ):
@@ -158,7 +188,7 @@ class GPT_warpper(nn.Module):
158
  emb,
159
  inputs_ids,
160
  temperature,
161
- eos_token,
162
  attention_mask = None,
163
  max_new_token = 2048,
164
  min_new_token = 0,
@@ -167,6 +197,7 @@ class GPT_warpper(nn.Module):
167
  infer_text=False,
168
  return_attn=False,
169
  return_hidden=False,
 
170
  ):
171
 
172
  with torch.no_grad():
@@ -177,77 +208,128 @@ class GPT_warpper(nn.Module):
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
- for i in tqdm(range(max_new_token)):
188
-
189
- model_input = self.prepare_inputs_for_generation(inputs_ids,
190
- outputs.past_key_values if i!=0 else None,
191
- attention_mask_cache[:, :inputs_ids.shape[1]], use_cache=True)
192
-
193
- if i == 0:
194
- model_input['inputs_embeds'] = emb
195
- else:
196
- if infer_text:
197
- model_input['inputs_embeds'] = self.emb_text(model_input['input_ids'][:,:,0])
 
 
 
198
  else:
199
- code_emb = [self.emb_code[i](model_input['input_ids'][:,:,i]) for i in range(self.num_vq)]
200
- model_input['inputs_embeds'] = torch.stack(code_emb, 3).sum(3)
201
-
202
- model_input['input_ids'] = None
203
- outputs = self.gpt.forward(**model_input, output_attentions=return_attn)
204
- attentions.append(outputs.attentions)
205
- hidden_states = outputs[0] # 🐻
206
- if return_hidden:
207
- hiddens.append(hidden_states[:, -1])
208
-
209
- with P.cached():
210
- if infer_text:
211
- logits = self.head_text(hidden_states)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  else:
213
- logits = torch.stack([self.head_code[i](hidden_states) for i in range(self.num_vq)], 3)
214
-
215
- logits = logits[:, -1].float()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
- if not infer_text:
218
- logits = rearrange(logits, "b c n -> (b n) c")
219
- logits_token = rearrange(inputs_ids[:, start_idx:], "b c n -> (b n) c")
220
- else:
221
- logits_token = inputs_ids[:, start_idx:, 0]
222
-
223
- logits = logits / temperature
224
-
225
- for logitsProcessors in LogitsProcessors:
226
- logits = logitsProcessors(logits_token, logits)
227
-
228
- for logitsWarpers in LogitsWarpers:
229
- logits = logitsWarpers(logits_token, logits)
230
-
231
- if i < min_new_token:
232
- logits[:, eos_token] = -torch.inf
233
-
234
- scores = F.softmax(logits, dim=-1)
235
-
236
- idx_next = torch.multinomial(scores, num_samples=1)
237
-
238
- if not infer_text:
239
- idx_next = rearrange(idx_next, "(b n) 1 -> b n", n=self.num_vq)
240
- finish = finish | (idx_next == eos_token).any(1)
241
- inputs_ids = torch.cat([inputs_ids, idx_next.unsqueeze(1)], 1)
242
- else:
243
- finish = finish | (idx_next == eos_token).any(1)
244
- inputs_ids = torch.cat([inputs_ids, idx_next.unsqueeze(-1).expand(-1, -1, self.num_vq)], 1)
245
-
246
- end_idx = end_idx + (~finish).int()
247
-
248
- if finish.all():
249
- break
250
-
251
  inputs_ids = [inputs_ids[idx, start_idx: start_idx+i] for idx, i in enumerate(end_idx.int())]
252
  inputs_ids = [i[:, 0] for i in inputs_ids] if infer_text else inputs_ids
253
 
@@ -256,10 +338,12 @@ class GPT_warpper(nn.Module):
256
  hiddens = [hiddens[idx, :i] for idx, i in enumerate(end_idx.int())]
257
 
258
  if not finish.all():
259
- self.logger.warn(f'Incomplete result. hit max_new_token: {max_new_token}')
260
-
261
- return {
 
 
262
  'ids': inputs_ids,
263
  'attentions': attentions,
264
  'hiddens':hiddens,
265
- }
 
2
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
3
 
4
  import logging
5
+ from typing import Union
6
+
7
+
8
  from tqdm import tqdm
 
9
  from transformers.cache_utils import Cache
10
 
11
  import torch
 
14
  import torch.nn.utils.parametrize as P
15
  from torch.nn.utils.parametrizations import weight_norm
16
  from transformers import LlamaModel, LlamaConfig
17
+
18
+ from ..utils.io import del_all
19
+
20
+
21
  class LlamaMLP(nn.Module):
22
  def __init__(self, hidden_size, intermediate_size):
23
  super().__init__()
 
40
  num_audio_tokens,
41
  num_text_tokens,
42
  num_vq=4,
43
+ device="cpu",
44
+ logger=logging.getLogger(__name__)
45
+ ):
46
  super().__init__()
47
 
48
+ self.logger = logger
49
+ self.device = device
50
+ self.device_gpt = device if "mps" not in str(device) else "cpu"
51
+ self.num_vq = num_vq
52
+
53
+ self.gpt = self.build_model(gpt_config, self.device_gpt)
54
  self.model_dim = self.gpt.config.hidden_size
55
+ self.emb_code = nn.ModuleList(
56
+ [nn.Embedding(
57
+ num_audio_tokens, self.model_dim, device=self.device_gpt,
58
+ ) for _ in range(num_vq)],
59
+ )
60
+ self.emb_text = nn.Embedding(num_text_tokens, self.model_dim, device=self.device_gpt)
61
 
62
+ self.head_text = weight_norm(
63
+ nn.Linear(
64
+ self.model_dim, num_text_tokens, bias=False, device=device,
65
+ ),
66
+ name='weight',
67
+ )
68
+ self.head_code = nn.ModuleList(
69
+ [weight_norm(
70
+ nn.Linear(
71
+ self.model_dim, num_audio_tokens, bias=False, device=device,
72
+ ),
73
+ name='weight',
74
+ ) for _ in range(self.num_vq)],
75
+ )
76
 
77
+ def build_model(self, config, device):
78
 
79
  configuration = LlamaConfig(**config)
80
  model = LlamaModel(configuration)
81
  del model.embed_tokens
82
 
83
+ return model.to(device)
 
 
84
 
85
+ def get_emb(self, input_ids, text_mask):
86
+
87
+ emb_text = self.emb_text(input_ids[text_mask][:, 0].to(self.device_gpt))
88
+
89
+ text_mask_inv = ~text_mask
90
+ masked_input_ids = input_ids[text_mask_inv].to(self.device_gpt)
91
+ del text_mask_inv
92
+
93
+ emb_code = [self.emb_code[i](masked_input_ids[:, i]) for i in range(self.num_vq)]
94
  emb_code = torch.stack(emb_code, 2).sum(2)
95
+
96
  emb = torch.zeros((input_ids.shape[:-1])+(emb_text.shape[-1],), device=emb_text.device, dtype=emb_text.dtype)
97
  emb[text_mask] = emb_text
98
  emb[~text_mask] = emb_code.to(emb.dtype)
99
+
100
+ del emb_text, emb_code
101
+
102
  return emb
103
+
104
  def prepare_inputs_for_generation(
105
  self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
106
  ):
 
188
  emb,
189
  inputs_ids,
190
  temperature,
191
+ eos_token: Union[int, torch.Tensor],
192
  attention_mask = None,
193
  max_new_token = 2048,
194
  min_new_token = 0,
 
197
  infer_text=False,
198
  return_attn=False,
199
  return_hidden=False,
200
+ stream=False,
201
  ):
202
 
203
  with torch.no_grad():
 
208
  start_idx, end_idx = inputs_ids.shape[1], torch.zeros(inputs_ids.shape[0], device=inputs_ids.device, dtype=torch.long)
209
  finish = torch.zeros(inputs_ids.shape[0], device=inputs_ids.device).bool()
210
 
211
+ temperature = temperature.unsqueeze_(0).expand(inputs_ids.shape[0], -1).contiguous().view(-1, 1)
212
+ # temperature = rearrange(temperature, "b n -> (b n) 1")
213
 
214
  attention_mask_cache = torch.ones((inputs_ids.shape[0], inputs_ids.shape[1]+max_new_token,), dtype=torch.bool, device=inputs_ids.device)
215
  if attention_mask is not None:
216
  attention_mask_cache[:, :attention_mask.shape[1]] = attention_mask
217
+
218
+ with tqdm(total=max_new_token) as pbar:
219
+
220
+ past_key_values = None
221
+
222
+ for i in range(max_new_token):
223
+ model_input = self.prepare_inputs_for_generation(
224
+ inputs_ids,
225
+ past_key_values,
226
+ attention_mask_cache[:, :inputs_ids.shape[1]],
227
+ use_cache=True,
228
+ )
229
+
230
+ if i == 0:
231
+ model_input['inputs_embeds'] = emb
232
  else:
233
+ inputs_ids_emb = model_input['input_ids'].to(self.device_gpt)
234
+ if infer_text:
235
+ model_input['inputs_embeds'] = self.emb_text(inputs_ids_emb[:,:,0])
236
+ else:
237
+ code_emb = [self.emb_code[i](inputs_ids_emb[:,:,i]) for i in range(self.num_vq)]
238
+ model_input['inputs_embeds'] = torch.stack(code_emb, 3).sum(3)
239
+ del inputs_ids_emb, model_input['input_ids']
240
+
241
+ outputs = self.gpt.forward(
242
+ attention_mask=model_input["attention_mask"].to(self.device_gpt),
243
+ position_ids=model_input["position_ids"].to(self.device_gpt),
244
+ past_key_values=model_input["past_key_values"],
245
+ inputs_embeds=model_input['inputs_embeds'].to(self.device_gpt),
246
+ use_cache=model_input['use_cache'],
247
+ output_attentions=return_attn,
248
+ cache_position=model_input['cache_position'].to(self.device_gpt),
249
+ )
250
+ del_all(model_input)
251
+ attentions.append(outputs.attentions)
252
+ hidden_states = outputs[0].to(self.device) # 🐻
253
+ past_key_values = outputs.past_key_values
254
+ del outputs
255
+ if return_hidden:
256
+ hiddens.append(hidden_states[:, -1])
257
+
258
+ with P.cached():
259
+ if infer_text:
260
+ logits = self.head_text(hidden_states)
261
+ else:
262
+ logits = torch.stack([self.head_code[i](hidden_states) for i in range(self.num_vq)], 3)
263
+
264
+ logits = logits[:, -1].float()
265
+
266
+ if not infer_text:
267
+ # logits = rearrange(logits, "b c n -> (b n) c")
268
+ logits = logits.permute(0, 2, 1)
269
+ logits = logits.reshape(-1, logits.size(2))
270
+ # logits_token = rearrange(inputs_ids[:, start_idx:], "b c n -> (b n) c")
271
+ inputs_ids_sliced = inputs_ids[:, start_idx:].permute(0, 2, 1)
272
+ logits_token = inputs_ids_sliced.reshape(
273
+ inputs_ids_sliced.size(0)*inputs_ids_sliced.size(1), -1,
274
+ )
275
  else:
276
+ logits_token = inputs_ids[:, start_idx:, 0]
277
+
278
+ logits = logits / temperature
279
+
280
+ for logitsProcessors in LogitsProcessors:
281
+ logits = logitsProcessors(logits_token, logits)
282
+
283
+ for logitsWarpers in LogitsWarpers:
284
+ logits = logitsWarpers(logits_token, logits)
285
+
286
+ del logits_token
287
+
288
+ if i < min_new_token:
289
+ logits[:, eos_token] = -torch.inf
290
+
291
+ scores = F.softmax(logits, dim=-1)
292
+
293
+ del logits
294
+
295
+ idx_next = torch.multinomial(scores, num_samples=1).to(finish.device)
296
+
297
+ if not infer_text:
298
+ # idx_next = rearrange(idx_next, "(b n) 1 -> b n", n=self.num_vq)
299
+ idx_next = idx_next.view(-1, self.num_vq)
300
+ finish_or = (idx_next == eos_token).any(1)
301
+ finish |= finish_or
302
+ del finish_or
303
+ inputs_ids = torch.cat([inputs_ids, idx_next.unsqueeze(1)], 1)
304
+ else:
305
+ finish_or = (idx_next == eos_token).any(1)
306
+ finish |= finish_or
307
+ del finish_or
308
+ inputs_ids = torch.cat([inputs_ids, idx_next.unsqueeze(-1).expand(-1, -1, self.num_vq)], 1)
309
+
310
+ del idx_next
311
+
312
+ end_idx += (~finish).int().to(end_idx.device)
313
+ if stream:
314
+ if end_idx % 24 and not finish.all():
315
+ continue
316
+ y_inputs_ids = [inputs_ids[idx, start_idx: start_idx+i] for idx, i in enumerate(end_idx.int())]
317
+ y_inputs_ids = [i[:, 0] for i in y_inputs_ids] if infer_text else y_inputs_ids
318
+ y_hiddens = [[]]
319
+ if return_hidden:
320
+ y_hiddens = torch.stack(hiddens, 1)
321
+ y_hiddens = [y_hiddens[idx, :i] for idx, i in enumerate(end_idx.int())]
322
+ yield {
323
+ 'ids': y_inputs_ids,
324
+ 'attentions': attentions,
325
+ 'hiddens':y_hiddens,
326
+ }
327
+
328
+ if finish.all():
329
+ pbar.update(max_new_token-i-1)
330
+ break
331
+ pbar.update(1)
332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  inputs_ids = [inputs_ids[idx, start_idx: start_idx+i] for idx, i in enumerate(end_idx.int())]
334
  inputs_ids = [i[:, 0] for i in inputs_ids] if infer_text else inputs_ids
335
 
 
338
  hiddens = [hiddens[idx, :i] for idx, i in enumerate(end_idx.int())]
339
 
340
  if not finish.all():
341
+ self.logger.warn(f'Incomplete result. hit max_new_token: {max_new_token}')
342
+
343
+ del finish
344
+
345
+ yield {
346
  'ids': inputs_ids,
347
  'attentions': attentions,
348
  'hiddens':hiddens,
349
+ }
ChatTTS/res/homophones_map.json ADDED
The diff for this file is too large to render. See raw diff
 
ChatTTS/utils/download.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ import hashlib
4
+ import requests
5
+ from io import BytesIO
6
+
7
+ from .log import logger
8
+
9
+ def sha256(f) -> str:
10
+ sha256_hash = hashlib.sha256()
11
+ # Read and update hash in chunks of 4M
12
+ for byte_block in iter(lambda: f.read(4 * 1024 * 1024), b""):
13
+ sha256_hash.update(byte_block)
14
+ return sha256_hash.hexdigest()
15
+
16
+
17
+ def check_model(
18
+ dir_name: Path, model_name: str, hash: str, remove_incorrect=False
19
+ ) -> bool:
20
+ target = dir_name / model_name
21
+ relname = target.as_posix()
22
+ logger.debug(f"checking {relname}...")
23
+ if not os.path.exists(target):
24
+ logger.info(f"{target} not exist.")
25
+ return False
26
+ with open(target, "rb") as f:
27
+ digest = sha256(f)
28
+ bakfile = f"{target}.bak"
29
+ if digest != hash:
30
+ logger.warn(f"{target} sha256 hash mismatch.")
31
+ logger.info(f"expected: {hash}")
32
+ logger.info(f"real val: {digest}")
33
+ logger.warn("please add parameter --update to download the latest assets.")
34
+ if remove_incorrect:
35
+ if not os.path.exists(bakfile):
36
+ os.rename(str(target), bakfile)
37
+ else:
38
+ os.remove(str(target))
39
+ return False
40
+ if remove_incorrect and os.path.exists(bakfile):
41
+ os.remove(bakfile)
42
+ return True
43
+
44
+
45
+ def check_all_assets(update=False) -> bool:
46
+ BASE_DIR = Path(__file__).resolve().parent.parent.parent
47
+
48
+ logger.info("checking assets...")
49
+ current_dir = BASE_DIR / "asset"
50
+ names = [
51
+ "Decoder.pt",
52
+ "DVAE.pt",
53
+ "GPT.pt",
54
+ "spk_stat.pt",
55
+ "tokenizer.pt",
56
+ "Vocos.pt",
57
+ ]
58
+ for model in names:
59
+ menv = model.replace(".", "_")
60
+ if not check_model(
61
+ current_dir, model, os.environ[f"sha256_asset_{menv}"], update
62
+ ):
63
+ return False
64
+
65
+ logger.info("checking configs...")
66
+ current_dir = BASE_DIR / "config"
67
+ names = [
68
+ "decoder.yaml",
69
+ "dvae.yaml",
70
+ "gpt.yaml",
71
+ "path.yaml",
72
+ "vocos.yaml",
73
+ ]
74
+ for model in names:
75
+ menv = model.replace(".", "_")
76
+ if not check_model(
77
+ current_dir, model, os.environ[f"sha256_config_{menv}"], update
78
+ ):
79
+ return False
80
+
81
+ logger.info("all assets are already latest.")
82
+ return True
83
+
84
+
85
+ def download_and_extract_tar_gz(url: str, folder: str):
86
+ import tarfile
87
+
88
+ logger.info(f"downloading {url}")
89
+ response = requests.get(url, stream=True, timeout=(5, 10))
90
+ with BytesIO() as out_file:
91
+ out_file.write(response.content)
92
+ out_file.seek(0)
93
+ logger.info(f"downloaded.")
94
+ with tarfile.open(fileobj=out_file, mode="r:gz") as tar:
95
+ tar.extractall(folder)
96
+ logger.info(f"extracted into {folder}")
97
+
98
+
99
+ def download_and_extract_zip(url: str, folder: str):
100
+ import zipfile
101
+
102
+ logger.info(f"downloading {url}")
103
+ response = requests.get(url, stream=True, timeout=(5, 10))
104
+ with BytesIO() as out_file:
105
+ out_file.write(response.content)
106
+ out_file.seek(0)
107
+ logger.info(f"downloaded.")
108
+ with zipfile.ZipFile(out_file) as zip_ref:
109
+ zip_ref.extractall(folder)
110
+ logger.info(f"extracted into {folder}")
111
+
112
+
113
+ def download_dns_yaml(url: str, folder: str):
114
+ logger.info(f"downloading {url}")
115
+ response = requests.get(url, stream=True, timeout=(5, 10))
116
+ with open(os.path.join(folder, "dns.yaml"), "wb") as out_file:
117
+ out_file.write(response.content)
118
+ logger.info(f"downloaded into {folder}")
119
+
120
+
121
+ def download_all_assets(tmpdir: str, version="0.2.5"):
122
+ import subprocess
123
+ import platform
124
+
125
+ archs = {
126
+ "aarch64": "arm64",
127
+ "armv8l": "arm64",
128
+ "arm64": "arm64",
129
+ "x86": "386",
130
+ "i386": "386",
131
+ "i686": "386",
132
+ "386": "386",
133
+ "x86_64": "amd64",
134
+ "x64": "amd64",
135
+ "amd64": "amd64",
136
+ }
137
+ system_type = platform.system().lower()
138
+ architecture = platform.machine().lower()
139
+ is_win = system_type == "windows"
140
+
141
+ architecture = archs.get(architecture, None)
142
+ if not architecture:
143
+ logger.error(f"architecture {architecture} is not supported")
144
+ exit(1)
145
+ try:
146
+ BASE_URL = "https://github.com/fumiama/RVC-Models-Downloader/releases/download/"
147
+ suffix = "zip" if is_win else "tar.gz"
148
+ RVCMD_URL = BASE_URL + f"v{version}/rvcmd_{system_type}_{architecture}.{suffix}"
149
+ cmdfile = os.path.join(tmpdir, "rvcmd")
150
+ if is_win:
151
+ download_and_extract_zip(RVCMD_URL, tmpdir)
152
+ cmdfile += ".exe"
153
+ else:
154
+ download_and_extract_tar_gz(RVCMD_URL, tmpdir)
155
+ os.chmod(cmdfile, 0o755)
156
+ subprocess.run([cmdfile, "-notui", "-w", "0", "assets/chtts"])
157
+ except Exception:
158
+ BASE_URL = "https://raw.gitcode.com/u011570312/RVC-Models-Downloader/assets/"
159
+ suffix = {
160
+ "darwin_amd64": "555",
161
+ "darwin_arm64": "556",
162
+ "linux_386": "557",
163
+ "linux_amd64": "558",
164
+ "linux_arm64": "559",
165
+ "windows_386": "562",
166
+ "windows_amd64": "563",
167
+ }[f"{system_type}_{architecture}"]
168
+ RVCMD_URL = BASE_URL + suffix
169
+ download_dns_yaml(
170
+ "https://raw.gitcode.com/u011570312/RVC-Models-Downloader/raw/main/dns.yaml",
171
+ tmpdir,
172
+ )
173
+ if is_win:
174
+ download_and_extract_zip(RVCMD_URL, tmpdir)
175
+ cmdfile += ".exe"
176
+ else:
177
+ download_and_extract_tar_gz(RVCMD_URL, tmpdir)
178
+ os.chmod(cmdfile, 0o755)
179
+ subprocess.run(
180
+ [
181
+ cmdfile,
182
+ "-notui",
183
+ "-w",
184
+ "0",
185
+ "-dns",
186
+ os.path.join(tmpdir, "dns.yaml"),
187
+ "assets/chtts",
188
+ ]
189
+ )
ChatTTS/utils/gpu_utils.py CHANGED
@@ -1,9 +1,9 @@
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()):
@@ -14,10 +14,14 @@ def select_device(min_memory = 2048):
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.log(logging.WARNING, f'GPU {selected_gpu} has {round(free_memory_mb, 2)} MB memory left.')
18
  device = torch.device('cpu')
 
 
 
 
19
  else:
20
- logger.log(logging.WARNING, f'No GPU found, use CPU instead')
21
  device = torch.device('cpu')
22
-
23
  return device
 
1
 
2
  import torch
 
3
 
4
+ from .log import logger
5
+
6
+ def select_device(min_memory=2048):
7
  if torch.cuda.is_available():
8
  available_gpus = []
9
  for i in range(torch.cuda.device_count()):
 
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/utils/infer_utils.py CHANGED
@@ -1,6 +1,8 @@
1
 
 
2
  import torch
3
  import torch.nn.functional as F
 
4
 
5
 
6
  class CustomRepetitionPenaltyLogitsProcessorRepeat():
@@ -19,6 +21,7 @@ class CustomRepetitionPenaltyLogitsProcessorRepeat():
19
  freq = F.one_hot(input_ids, scores.size(1)).sum(1)
20
  freq[self.max_input_ids:] = 0
21
  alpha = self.penalty**freq
 
22
  scores = torch.where(scores < 0, scores*alpha, scores/alpha)
23
 
24
  return scores
@@ -42,4 +45,137 @@ class CustomRepetitionPenaltyLogitsProcessor():
42
  score[input_ids>=self.max_input_ids] = _score[input_ids>=self.max_input_ids]
43
  scores.scatter_(1, input_ids, score)
44
 
45
- return scores
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ import re
3
  import torch
4
  import torch.nn.functional as F
5
+ import json
6
 
7
 
8
  class CustomRepetitionPenaltyLogitsProcessorRepeat():
 
21
  freq = F.one_hot(input_ids, scores.size(1)).sum(1)
22
  freq[self.max_input_ids:] = 0
23
  alpha = self.penalty**freq
24
+ scores = scores.contiguous()
25
  scores = torch.where(scores < 0, scores*alpha, scores/alpha)
26
 
27
  return scores
 
45
  score[input_ids>=self.max_input_ids] = _score[input_ids>=self.max_input_ids]
46
  scores.scatter_(1, input_ids, score)
47
 
48
+ return scores
49
+
50
+ class HomophonesReplacer:
51
+ """
52
+ Homophones Replacer
53
+
54
+ Replace the mispronounced characters with correctly pronounced ones.
55
+
56
+ Creation process of homophones_map.json:
57
+
58
+ 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.
59
+ 2. Record discrepancies between the inferred and input text, identifying about 180,000 misread words.
60
+ 3. Create a pinyin to common characters mapping using correctly read characters by ChatTTS.
61
+ 4. For each discrepancy, extract the correct pinyin using [python-pinyin] and find homophones with the correct pronunciation from the mapping.
62
+
63
+ Thanks to:
64
+ [Tencent AI Lab Embedding Corpora for Chinese and English Words and Phrases](https://ai.tencent.com/ailab/nlp/en/embedding.html)
65
+ [python-pinyin](https://github.com/mozillazg/python-pinyin)
66
+
67
+ """
68
+ def __init__(self, map_file_path):
69
+ self.homophones_map = self.load_homophones_map(map_file_path)
70
+
71
+ def load_homophones_map(self, map_file_path):
72
+ with open(map_file_path, 'r', encoding='utf-8') as f:
73
+ homophones_map = json.load(f)
74
+ return homophones_map
75
+
76
+ def replace(self, text):
77
+ result = []
78
+ replaced_words = []
79
+ for char in text:
80
+ if char in self.homophones_map:
81
+ repl_char = self.homophones_map[char]
82
+ result.append(repl_char)
83
+ replaced_words.append((char, repl_char))
84
+ else:
85
+ result.append(char)
86
+ return ''.join(result), replaced_words
87
+
88
+ def count_invalid_characters(s):
89
+
90
+ s = re.sub(r'\[uv_break\]|\[laugh\]|\[lbreak\]', '', s)
91
+ pattern = re.compile(r'[^\u4e00-\u9fffA-Za-z,。、,\. ]')
92
+ non_alphabetic_chinese_chars = pattern.findall(s)
93
+ return set(non_alphabetic_chinese_chars)
94
+
95
+ def detect_language(sentence):
96
+
97
+ chinese_char_pattern = re.compile(r'[\u4e00-\u9fff]')
98
+ english_word_pattern = re.compile(r'\b[A-Za-z]+\b')
99
+
100
+ chinese_chars = chinese_char_pattern.findall(sentence)
101
+ english_words = english_word_pattern.findall(sentence)
102
+
103
+ if len(chinese_chars) > len(english_words):
104
+ return "zh"
105
+ else:
106
+ return "en"
107
+
108
+
109
+ character_map = {
110
+ ':': ',',
111
+ ';': ',',
112
+ '!': '。',
113
+ '(': ',',
114
+ ')': ',',
115
+ '【': ',',
116
+ '】': ',',
117
+ '『': ',',
118
+ '』': ',',
119
+ '「': ',',
120
+ '」': ',',
121
+ '《': ',',
122
+ '》': ',',
123
+ '-': ',',
124
+ '‘': '',
125
+ '“': '',
126
+ '’': '',
127
+ '”': '',
128
+ ':': ',',
129
+ ';': ',',
130
+ '!': '.',
131
+ '(': ',',
132
+ ')': ',',
133
+ '[': ',',
134
+ ']': ',',
135
+ '>': ',',
136
+ '<': ',',
137
+ '-': ',',
138
+ }
139
+
140
+ halfwidth_2_fullwidth_map = {
141
+ '!': '!',
142
+ '"': '“',
143
+ "'": '‘',
144
+ '#': '#',
145
+ '$': '$',
146
+ '%': '%',
147
+ '&': '&',
148
+ '(': '(',
149
+ ')': ')',
150
+ ',': ',',
151
+ '-': '-',
152
+ '*': '*',
153
+ '+': '+',
154
+ '.': '。',
155
+ '/': '/',
156
+ ':': ':',
157
+ ';': ';',
158
+ '<': '<',
159
+ '=': '=',
160
+ '>': '>',
161
+ '?': '?',
162
+ '@': '@',
163
+ # '[': '[',
164
+ '\\': '\',
165
+ # ']': ']',
166
+ '^': '^',
167
+ # '_': '_',
168
+ '`': '`',
169
+ '{': '{',
170
+ '|': '|',
171
+ '}': '}',
172
+ '~': '~'
173
+ }
174
+
175
+ def apply_half2full_map(text):
176
+ translation_table = str.maketrans(halfwidth_2_fullwidth_map)
177
+ return text.translate(translation_table)
178
+
179
+ def apply_character_map(text):
180
+ translation_table = str.maketrans(character_map)
181
+ return text.translate(translation_table)
ChatTTS/utils/io.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import logging
4
+ from typing import Union
5
+
6
+ from .log import logger
7
+
8
+ def get_latest_modified_file(directory):
9
+
10
+ files = [os.path.join(directory, f) for f in os.listdir(directory)]
11
+ if not files:
12
+ logger.log(logging.WARNING, f'No files found in the directory: {directory}')
13
+ return None
14
+ latest_file = max(files, key=os.path.getmtime)
15
+
16
+ return latest_file
17
+
18
+ def del_all(d: Union[dict, list]):
19
+ if isinstance(d, dict):
20
+ lst = list(d.keys())
21
+ for k in lst:
22
+ x = d.pop(k)
23
+ if isinstance(x, dict) or isinstance(x, list):
24
+ del_all(x)
25
+ del x
26
+ return
27
+ elif isinstance(d, list):
28
+ while len(d):
29
+ x = d.pop()
30
+ if isinstance(x, dict) or isinstance(x, list):
31
+ del_all(x)
32
+ del x
33
+ return
ChatTTS/utils/log.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from pathlib import Path
3
+
4
+ logger = logging.getLogger(Path(__file__).parent.name)
5
+
6
+ def set_utils_logger(l: logging.Logger):
7
+ global logger
8
+ logger = l
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 CHANGED
@@ -1 +1 @@
1
- Subproject commit f4c8329f0d231b272b676e5e171fb9655b345f2e
 
1
+ Subproject commit f809de7289f740bc8fe2bab6f65fa3c73cf448fd
docs/cn/README.md ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ > [!NOTE]
18
+ > 注意此版本可能不是最新版,所有内容请以英文版为准。
19
+
20
+ ## 简介
21
+
22
+ ChatTTS 是一款专门为对话场景(例如 LLM 助手)设计的文本转语音模型。
23
+
24
+ ### 支持的语种
25
+
26
+ - [x] 英语
27
+ - [x] 中文
28
+ - [ ] 敬请期待...
29
+
30
+ ### 亮点
31
+
32
+ > 你可以参考 **[Bilibili](https://www.bilibili.com/video/BV1zn4y1o7iV)** 上的这个视频,了解本项目的详细情况。
33
+
34
+ 1. **对话式 TTS**: ChatTTS 针对对话式任务进行了优化,能够实现自然且富有表现力的合成语音。它支持多个说话者,便于生成互动式对话。
35
+ 2. **精细的控制**: 该模型可以预测和控制精细的韵律特征,包括笑声、停顿和插入语。
36
+ 3. **更好的韵律**: ChatTTS 在韵律方面超越了大多数开源 TTS 模型。我们提供预训练模型以支持进一步的研究和开发。
37
+
38
+ ### 数据集和模型
39
+
40
+ - 主模型使用了 100,000+ 小时的中文和英文音频数据进行训练。
41
+ - **[HuggingFace](https://huggingface.co/2Noise/ChatTTS)** 上的开源版本是一个在 40,000 小时数据上进行无监督微调的预训练模型。
42
+
43
+ ### 路线图
44
+
45
+ - [x] 开源 4 万小时基础模型和 spk_stats 文件
46
+ - [ ] 开源 VQ 编码器和 Lora 训练代码
47
+ - [ ] 无需细化文本即可进行流式音频生成
48
+ - [ ] 开源具有多情感控制功能的 4 万小时版本
49
+ - [ ] 也许会有 ChatTTS.cpp ?(欢迎 PR 或新建仓库)
50
+
51
+ ### 免责声明
52
+
53
+ > [!Important]
54
+ > 此仓库仅供学术用途。
55
+
56
+ 本项目旨在用于教育和研究目的,不适用于任何商业或法律目的。作者不保证信息的准确性、完整性和可靠性。此仓库中使用的信息和数据仅供学术和研究目的。数据来自公开来源,作者不声称对数据拥有任何所有权或版权。
57
+
58
+ ChatTTS 是一款强大的文本转语音系统。但是,负责任和道德地使用这项技术非常重要。为了限制 ChatTTS 的使用,我们在 40,000 小时模型的训练过程中添加了少量高频噪声,并使用 MP3 格式尽可能压缩音频质量,以防止恶意行为者将其用于犯罪目的。同时,我们内部训练了一个检测模型,并计划在未来开源它。
59
+
60
+ ### 联系方式
61
+
62
+ > 欢迎随时提交 GitHub issues/PRs。
63
+
64
+ #### 合作洽谈
65
+
66
+ 如需就模型和路线图进行合作洽谈,请发送邮件至 **open-source@2noise.com**。
67
+
68
+ #### 线上讨论
69
+
70
+ ##### 1. 官方 QQ 群
71
+
72
+ - **群 1**, 808364215 (已满)
73
+ - **群 2**, 230696694 (已满)
74
+ - **群 3**, 933639842
75
+
76
+ ## 安装教程 (丰富中)
77
+
78
+ > 将在近期上传至 pypi,详情请查看 https://github.com/2noise/ChatTTS/issues/269 上的讨论。
79
+
80
+ #### 1. 使用源代码安装
81
+
82
+ ```bash
83
+ pip install git+https://github.com/2noise/ChatTTS
84
+ ```
85
+
86
+ #### 2. 使用 conda 安装
87
+
88
+ ```bash
89
+ git clone https://github.com/2noise/ChatTTS
90
+ cd ChatTTS
91
+ conda create -n chattts
92
+ conda activate chattts
93
+ pip install -r requirements.txt
94
+ ```
95
+
96
+ ## 使用教程
97
+
98
+ ### 安装依赖
99
+
100
+ ```bash
101
+ pip install --upgrade -r requirements.txt
102
+ ```
103
+
104
+ ### 快速开始
105
+
106
+ #### 1. 启动 WebUI
107
+
108
+ ```bash
109
+ python examples/web/webui.py
110
+ ```
111
+
112
+ #### 2. 使用命令行
113
+
114
+ > 生成的音频将保存至 `./output_audio_xxx.wav`
115
+
116
+ ```bash
117
+ python examples/cmd/run.py "Please input your text."
118
+ ```
119
+
120
+ ### 基础用法
121
+
122
+ ```python
123
+ import ChatTTS
124
+ from IPython.display import Audio
125
+ import torchaudio
126
+
127
+ chat = ChatTTS.Chat()
128
+ chat.load_models(compile=False) # Set to True for better performance
129
+
130
+ texts = ["PUT YOUR TEXT HERE",]
131
+
132
+ wavs = chat.infer(texts, )
133
+
134
+ torchaudio.save("output1.wav", torch.from_numpy(wavs[0]), 24000)
135
+ ```
136
+
137
+ ### 进阶用法
138
+
139
+ ```python
140
+ ###################################
141
+ # Sample a speaker from Gaussian.
142
+
143
+ rand_spk = chat.sample_random_speaker()
144
+
145
+ params_infer_code = {
146
+ 'spk_emb': rand_spk, # add sampled speaker
147
+ 'temperature': .3, # using custom temperature
148
+ 'top_P': 0.7, # top P decode
149
+ 'top_K': 20, # top K decode
150
+ }
151
+
152
+ ###################################
153
+ # For sentence level manual control.
154
+
155
+ # use oral_(0-9), laugh_(0-2), break_(0-7)
156
+ # to generate special token in text to synthesize.
157
+ params_refine_text = {
158
+ 'prompt': '[oral_2][laugh_0][break_6]'
159
+ }
160
+
161
+ wavs = chat.infer(texts, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
162
+
163
+ ###################################
164
+ # For word level manual control.
165
+ text = 'What is [uv_break]your favorite english food?[laugh][lbreak]'
166
+ wavs = chat.infer(text, skip_refine_text=True, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
167
+ torchaudio.save("output2.wav", torch.from_numpy(wavs[0]), 24000)
168
+ ```
169
+
170
+ <details open>
171
+ <summary><h4>示例: 自我介绍</h4></summary>
172
+
173
+ ```python
174
+ inputs_en = """
175
+ chat T T S is a text to speech model designed for dialogue applications.
176
+ [uv_break]it supports mixed language input [uv_break]and offers multi speaker
177
+ capabilities with precise control over prosodic elements [laugh]like like
178
+ [uv_break]laughter[laugh], [uv_break]pauses, [uv_break]and intonation.
179
+ [uv_break]it delivers natural and expressive speech,[uv_break]so please
180
+ [uv_break] use the project responsibly at your own risk.[uv_break]
181
+ """.replace('\n', '') # English is still experimental.
182
+
183
+ params_refine_text = {
184
+ 'prompt': '[oral_2][laugh_0][break_4]'
185
+ }
186
+ # audio_array_cn = chat.infer(inputs_cn, params_refine_text=params_refine_text)
187
+ audio_array_en = chat.infer(inputs_en, params_refine_text=params_refine_text)
188
+ torchaudio.save("output3.wav", torch.from_numpy(audio_array_en[0]), 24000)
189
+ ```
190
+
191
+ [男性音色](https://github.com/2noise/ChatTTS/assets/130631963/e0f51251-db7f-4d39-a0e9-3e095bb65de1)
192
+
193
+ [女性音色](https://github.com/2noise/ChatTTS/assets/130631963/f5dcdd01-1091-47c5-8241-c4f6aaaa8bbd)
194
+
195
+ </details>
196
+
197
+ ## 常见问题
198
+
199
+ #### 1. 我需要多少 VRAM? 推理速度如何?
200
+
201
+ 对于 30 秒的音频片段,至少需要 4GB 的 GPU 内存。 对于 4090 GPU,它可以每秒生成大约 7 个语义 token 对应的音频。实时因子 (RTF) 约为 0.3。
202
+
203
+ #### 2. 模型稳定性不够好,存在多个说话者或音频质量差等问题。
204
+
205
+ 这是一个通常发生在自回归模型(例如 bark 和 valle)中的问题,通常很难避免。可以尝试多个样本以找到合适的结果。
206
+
207
+ #### 3. 除了笑声,我们还能控制其他东西吗?我们能控制其他情绪吗?
208
+
209
+ 在当前发布的模型中,可用的 token 级控制单元是 `[laugh]`, `[uv_break]` 和 `[lbreak]`。未来的版本中,我们可能会开源具有更多情绪控制功能的模型。
210
+
211
+ ## 致谢
212
+
213
+ - [bark](https://github.com/suno-ai/bark), [XTTSv2](https://github.com/coqui-ai/TTS) 和 [valle](https://arxiv.org/abs/2301.02111) 通过自回归式系统展示了非凡的 TTS 效果。
214
+ - [fish-speech](https://github.com/fishaudio/fish-speech) 揭示了 GVQ 作为 LLM 建模的音频分词器的能力。
215
+ - [vocos](https://github.com/gemelo-ai/vocos) vocos 被用作预训练声码器。
216
+
217
+ ## 特别鸣谢
218
+
219
+ - [wlu-audio lab](https://audio.westlake.edu.cn/) 对于早期算法实验的支持。
220
+
221
+ ## 相关资源
222
+
223
+ - [Awesome-ChatTTS](https://github.com/libukai/Awesome-ChatTTS) 一个 ChatTTS 的资源汇总列表。
224
+
225
+ ## 贡献者列表
226
+
227
+ [![contributors](https://contrib.rocks/image?repo=2noise/ChatTTS)](https://github.com/2noise/ChatTTS/graphs/contributors)
228
+
229
+ ## 项目浏览量
230
+
231
+ <div align="center">
232
+
233
+ ![counter](https://counter.seku.su/cmoe?name=chattts&theme=mbs)
234
+
235
+ </div>
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
+ モデルやロードマップについての正式なお問い合わせは、**open-source@2noise.com**までご連絡ください。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/)。
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
+ Для официальных запросов о модели и плане развития, пожалуйста, свяжитесь с нами по адресу **open-source@2noise.com**. Вы можете присоединиться к нашей группе 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/) за ранние эксперименты с алгоритмами.
examples/cmd/run.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from tools.logger import get_logger
17
+
18
+ logger = get_logger("Command")
19
+
20
+ def save_wav_file(wav, index):
21
+ wav_filename = f"output_audio_{index}.wav"
22
+ # Convert numpy array to bytes and write to WAV file
23
+ wav_bytes = (wav * 32768).astype('int16').tobytes()
24
+ with wave.open(wav_filename, "wb") as wf:
25
+ wf.setnchannels(1) # Mono channel
26
+ wf.setsampwidth(2) # Sample width in bytes
27
+ wf.setframerate(24000) # Sample rate in Hz
28
+ wf.writeframes(wav_bytes)
29
+ logger.info(f"Audio saved to {wav_filename}")
30
+
31
+ def main():
32
+ # Retrieve text from command line argument
33
+ text_input = sys.argv[1] if len(sys.argv) > 1 else "<YOUR TEXT HERE>"
34
+ logger.info("Received text input: %s", text_input)
35
+
36
+ chat = ChatTTS.Chat(get_logger("ChatTTS"))
37
+ logger.info("Initializing ChatTTS...")
38
+ if chat.load_models():
39
+ logger.info("Models loaded successfully.")
40
+ else:
41
+ logger.error("Models load failed.")
42
+ sys.exit(1)
43
+
44
+ texts = [text_input]
45
+ logger.info("Text prepared for inference: %s", texts)
46
+
47
+ wavs = chat.infer(texts, use_decoder=True)
48
+ logger.info("Inference completed. Audio generation successful.")
49
+ # Save each generated wav file to a local file
50
+ for index, wav in enumerate(wavs):
51
+ save_wav_file(wav, index)
52
+
53
+ return Audio(wavs[0], rate=24_000, autoplay=True)
54
+
55
+ if __name__ == "__main__":
56
+ logger.info("Starting the TTS application...")
57
+ main()
58
+ logger.info("TTS application finished.")
examples/ipynb/colab.ipynb ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "xYJFXKP9xhQM"
7
+ },
8
+ "source": [
9
+ "## Clone Repo"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {
16
+ "id": "hegwDOfffwzw"
17
+ },
18
+ "outputs": [],
19
+ "source": [
20
+ "!cd /content\n",
21
+ "!rm -rf /content/ChatTTS\n",
22
+ "!git clone https://github.com/2noise/ChatTTS.git\n",
23
+ "!pip install -r /content/ChatTTS/requirements.txt\n",
24
+ "!ldconfig /usr/lib64-nvidia"
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "markdown",
29
+ "metadata": {
30
+ "id": "zdzEFoknxqTH"
31
+ },
32
+ "source": [
33
+ "## Import Libs"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "execution_count": null,
39
+ "metadata": {
40
+ "id": "lDSQ6Xf-bSre"
41
+ },
42
+ "outputs": [],
43
+ "source": [
44
+ "from dotenv import load_dotenv\n",
45
+ "load_dotenv(\"ChatTTS/sha256.env\")\n",
46
+ "\n",
47
+ "import torch\n",
48
+ "torch._dynamo.config.cache_size_limit = 64\n",
49
+ "torch._dynamo.config.suppress_errors = True\n",
50
+ "torch.set_float32_matmul_precision('high')\n",
51
+ "\n",
52
+ "from ChatTTS import ChatTTS\n",
53
+ "from IPython.display import Audio"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "markdown",
58
+ "metadata": {
59
+ "id": "vBzG5gxcbSrf"
60
+ },
61
+ "source": [
62
+ "## Load Models"
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "execution_count": null,
68
+ "metadata": {
69
+ "id": "e0QSkngRbSrg"
70
+ },
71
+ "outputs": [],
72
+ "source": [
73
+ "chat = ChatTTS.Chat()"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "markdown",
78
+ "metadata": {},
79
+ "source": [
80
+ "### Here are three choices for loading models:"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "markdown",
85
+ "metadata": {},
86
+ "source": [
87
+ "#### 1. Load models from Hugging Face:"
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "execution_count": null,
93
+ "metadata": {},
94
+ "outputs": [],
95
+ "source": [
96
+ "# use force_redownload=True if the weights have been updated.\n",
97
+ "chat.load_models(source='huggingface', force_redownload=True)"
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "markdown",
102
+ "metadata": {},
103
+ "source": [
104
+ "#### 2. Load models from local directories 'asset' and 'config':"
105
+ ]
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "execution_count": null,
110
+ "metadata": {},
111
+ "outputs": [],
112
+ "source": [
113
+ "chat.load_models()\n",
114
+ "# chat.load_models(source='local') same as above"
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "markdown",
119
+ "metadata": {},
120
+ "source": [
121
+ "#### 3. Load models from a custom path:"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "metadata": {},
128
+ "outputs": [],
129
+ "source": [
130
+ "# write the model path into custom_path\n",
131
+ "chat.load_models(source='custom', custom_path='YOUR CUSTOM PATH')"
132
+ ]
133
+ },
134
+ {
135
+ "cell_type": "markdown",
136
+ "metadata": {
137
+ "id": "bAUs0rGQbSrh"
138
+ },
139
+ "source": [
140
+ "## Inference"
141
+ ]
142
+ },
143
+ {
144
+ "cell_type": "markdown",
145
+ "metadata": {
146
+ "id": "NPZ2SFksbSrh"
147
+ },
148
+ "source": [
149
+ "### Batch infer"
150
+ ]
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "execution_count": null,
155
+ "metadata": {
156
+ "id": "Su9FmUYAbSrh"
157
+ },
158
+ "outputs": [],
159
+ "source": [
160
+ "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",
161
+ " + [\"我觉得像我们这些写程序的人,他,我觉得多多少少可能会对开源有一种情怀在吧我觉得开源是一个很好的形式。现在其实最先进的技术掌握在一些公司的手里的话,就他们并不会轻易的开放给所有的人用。\"]*3\n",
162
+ "\n",
163
+ "wavs = chat.infer(texts)"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": null,
169
+ "metadata": {
170
+ "id": "YQRwB8lpbSri"
171
+ },
172
+ "outputs": [],
173
+ "source": [
174
+ "Audio(wavs[0], rate=24_000, autoplay=True)"
175
+ ]
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "execution_count": null,
180
+ "metadata": {
181
+ "id": "LuFG6m7AbSri"
182
+ },
183
+ "outputs": [],
184
+ "source": [
185
+ "Audio(wavs[3], rate=24_000, autoplay=True)"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "markdown",
190
+ "metadata": {
191
+ "id": "oLhAGvkfbSrj"
192
+ },
193
+ "source": [
194
+ "### Custom params"
195
+ ]
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "execution_count": null,
200
+ "metadata": {
201
+ "id": "kma0HBEBbSrj"
202
+ },
203
+ "outputs": [],
204
+ "source": [
205
+ "params_infer_code = {'prompt':'[speed_5]', 'temperature':.3}\n",
206
+ "params_refine_text = {'prompt':'[oral_2][laugh_0][break_6]'}\n",
207
+ "\n",
208
+ "wav = chat.infer('四川美食可多了,有麻辣火锅、宫保鸡丁、麻婆豆腐、担担面、回锅肉、夫妻肺片等,每样都让人垂涎三尺。', \\\n",
209
+ " params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
210
+ ]
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "execution_count": null,
215
+ "metadata": {
216
+ "id": "Nl_mT9KpbSrj"
217
+ },
218
+ "outputs": [],
219
+ "source": [
220
+ "Audio(wav[0], rate=24_000, autoplay=True)"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "markdown",
225
+ "metadata": {
226
+ "id": "JfAba-tTbSrk"
227
+ },
228
+ "source": [
229
+ "### fix random speaker"
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "execution_count": null,
235
+ "metadata": {
236
+ "id": "Qh7dcWrAbSrk"
237
+ },
238
+ "outputs": [],
239
+ "source": [
240
+ "rand_spk = chat.sample_random_speaker()\n",
241
+ "params_infer_code = {'spk_emb' : rand_spk, }\n",
242
+ "\n",
243
+ "wav = chat.infer('四川美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。', \\\n",
244
+ " params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
245
+ ]
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "execution_count": null,
250
+ "metadata": {
251
+ "id": "0ljWDWzabSrk"
252
+ },
253
+ "outputs": [],
254
+ "source": [
255
+ "Audio(wav[0], rate=24_000, autoplay=True)"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "markdown",
260
+ "metadata": {
261
+ "id": "u1q-BcUKbSrl"
262
+ },
263
+ "source": [
264
+ "### Two stage control"
265
+ ]
266
+ },
267
+ {
268
+ "cell_type": "code",
269
+ "execution_count": null,
270
+ "metadata": {
271
+ "id": "3hAAc0lJbSrl"
272
+ },
273
+ "outputs": [],
274
+ "source": [
275
+ "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",
276
+ "refined_text = chat.infer(text, refine_text_only=True)\n",
277
+ "refined_text"
278
+ ]
279
+ },
280
+ {
281
+ "cell_type": "code",
282
+ "execution_count": null,
283
+ "metadata": {
284
+ "id": "0GVJxhd3BKQX"
285
+ },
286
+ "outputs": [],
287
+ "source": [
288
+ "wav = chat.infer(refined_text)"
289
+ ]
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "execution_count": null,
294
+ "metadata": {
295
+ "id": "ngyMht74BicY"
296
+ },
297
+ "outputs": [],
298
+ "source": [
299
+ "Audio(wav[0], rate=24_000, autoplay=True)"
300
+ ]
301
+ },
302
+ {
303
+ "cell_type": "code",
304
+ "execution_count": null,
305
+ "metadata": {
306
+ "id": "R2WjuVrWbSrl"
307
+ },
308
+ "outputs": [],
309
+ "source": [
310
+ "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",
311
+ "wav = chat.infer(text, skip_refine_text=True)"
312
+ ]
313
+ },
314
+ {
315
+ "cell_type": "code",
316
+ "execution_count": null,
317
+ "metadata": {
318
+ "id": "71Y4pBdl-_Yd"
319
+ },
320
+ "outputs": [],
321
+ "source": [
322
+ "Audio(wav[0], rate=24_000, autoplay=True)"
323
+ ]
324
+ },
325
+ {
326
+ "cell_type": "markdown",
327
+ "metadata": {
328
+ "id": "GG5AMbQbbSrl"
329
+ },
330
+ "source": [
331
+ "## LLM Call"
332
+ ]
333
+ },
334
+ {
335
+ "cell_type": "code",
336
+ "execution_count": null,
337
+ "metadata": {
338
+ "id": "3rkfwc3UbSrl"
339
+ },
340
+ "outputs": [],
341
+ "source": [
342
+ "from ChatTTS.experimental.llm import llm_api\n",
343
+ "\n",
344
+ "API_KEY = ''\n",
345
+ "client = llm_api(api_key=API_KEY,\n",
346
+ " base_url=\"https://api.deepseek.com\",\n",
347
+ " model=\"deepseek-chat\")"
348
+ ]
349
+ },
350
+ {
351
+ "cell_type": "code",
352
+ "execution_count": null,
353
+ "metadata": {
354
+ "id": "TTkIsXozbSrm"
355
+ },
356
+ "outputs": [],
357
+ "source": [
358
+ "user_question = '四川有哪些好吃的美食呢?'\n",
359
+ "text = client.call(user_question, prompt_version = 'deepseek')\n",
360
+ "print(text)\n",
361
+ "text = client.call(text, prompt_version = 'deepseek_TN')\n",
362
+ "print(text)"
363
+ ]
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "execution_count": null,
368
+ "metadata": {
369
+ "id": "qNhCJG4VbSrm"
370
+ },
371
+ "outputs": [],
372
+ "source": [
373
+ "params_infer_code = {'spk_emb' : rand_spk, 'temperature':.3}\n",
374
+ "\n",
375
+ "wav = chat.infer(text, params_infer_code=params_infer_code)"
376
+ ]
377
+ }
378
+ ],
379
+ "metadata": {
380
+ "accelerator": "GPU",
381
+ "colab": {
382
+ "collapsed_sections": [
383
+ "bAUs0rGQbSrh"
384
+ ],
385
+ "gpuType": "T4",
386
+ "provenance": []
387
+ },
388
+ "kernelspec": {
389
+ "display_name": "Python 3",
390
+ "name": "python3"
391
+ },
392
+ "language_info": {
393
+ "codemirror_mode": {
394
+ "name": "ipython",
395
+ "version": 3
396
+ },
397
+ "file_extension": ".py",
398
+ "mimetype": "text/x-python",
399
+ "name": "python",
400
+ "nbconvert_exporter": "python",
401
+ "pygments_lexer": "ipython3",
402
+ "version": "3.10.8"
403
+ }
404
+ },
405
+ "nbformat": 4,
406
+ "nbformat_minor": 0
407
+ }
examples/ipynb/example.ipynb ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import os, sys\n",
17
+ "\n",
18
+ "if sys.platform == \"darwin\":\n",
19
+ " os.environ[\"PYTORCH_ENABLE_MPS_FALLBACK\"] = \"1\"\n",
20
+ "\n",
21
+ "if not \"root_dir\" in globals():\n",
22
+ " now_dir = os.getcwd() # skip examples/ipynb\n",
23
+ " root_dir = os.path.join(now_dir, \"../../\")\n",
24
+ " sys.path.append(root_dir)\n",
25
+ " print(\"init root dir to\", root_dir)\n",
26
+ "\n",
27
+ "from dotenv import load_dotenv\n",
28
+ "load_dotenv(os.path.join(root_dir, \"sha256.env\"))\n",
29
+ "\n",
30
+ "import torch\n",
31
+ "torch._dynamo.config.cache_size_limit = 64\n",
32
+ "torch._dynamo.config.suppress_errors = True\n",
33
+ "torch.set_float32_matmul_precision('high')\n",
34
+ "\n",
35
+ "import ChatTTS\n",
36
+ "from IPython.display import Audio"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "metadata": {},
42
+ "source": [
43
+ "## Load Models"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "execution_count": null,
49
+ "metadata": {},
50
+ "outputs": [],
51
+ "source": [
52
+ "os.chdir(root_dir)\n",
53
+ "\n",
54
+ "chat = ChatTTS.Chat()"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "markdown",
59
+ "metadata": {},
60
+ "source": [
61
+ "### Here are three choices for loading models:"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "markdown",
66
+ "metadata": {},
67
+ "source": [
68
+ "#### 1. Load models from Hugging Face:"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": null,
74
+ "metadata": {},
75
+ "outputs": [],
76
+ "source": [
77
+ "# use force_redownload=True if the weights have been updated.\n",
78
+ "chat.load_models(source='huggingface', force_redownload=True)"
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "markdown",
83
+ "metadata": {},
84
+ "source": [
85
+ "#### 2. Load models from local directories 'asset' and 'config':"
86
+ ]
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "execution_count": null,
91
+ "metadata": {},
92
+ "outputs": [],
93
+ "source": [
94
+ "chat.load_models()\n",
95
+ "# chat.load_models(source='local') same as above"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "markdown",
100
+ "metadata": {},
101
+ "source": [
102
+ "#### 3. Load models from a custom path:"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "execution_count": null,
108
+ "metadata": {},
109
+ "outputs": [],
110
+ "source": [
111
+ "# write the model path into custom_path\n",
112
+ "chat.load_models(source='custom', custom_path='YOUR CUSTOM PATH')"
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "markdown",
117
+ "metadata": {},
118
+ "source": [
119
+ "## Inference"
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "markdown",
124
+ "metadata": {},
125
+ "source": [
126
+ "### Batch infer"
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "execution_count": null,
132
+ "metadata": {},
133
+ "outputs": [],
134
+ "source": [
135
+ "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",
136
+ " + [\"我觉得像我们这些写程序的人,他,我觉得多多少少可能会对开源有一种情怀在吧我觉得开源是一个很好的形式。现在其实最先进的技术掌握在一些公司的手里的话,就他们并不会轻易的开放给所有的人用。\"]*3 \n",
137
+ "\n",
138
+ "wavs = chat.infer(texts)"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "execution_count": null,
144
+ "metadata": {},
145
+ "outputs": [],
146
+ "source": [
147
+ "Audio(wavs[0], rate=24_000, autoplay=True)"
148
+ ]
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "execution_count": null,
153
+ "metadata": {},
154
+ "outputs": [],
155
+ "source": [
156
+ "Audio(wavs[3], rate=24_000, autoplay=True)"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "markdown",
161
+ "metadata": {},
162
+ "source": [
163
+ "### Custom params"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": null,
169
+ "metadata": {},
170
+ "outputs": [],
171
+ "source": [
172
+ "params_infer_code = {'prompt':'[speed_5]', 'temperature':.3}\n",
173
+ "params_refine_text = {'prompt':'[oral_2][laugh_0][break_6]'}\n",
174
+ "\n",
175
+ "wav = chat.infer('四川美食可多了,有麻辣火锅、宫保鸡丁、麻婆豆腐、担担面、回锅肉、夫妻肺片等,每样都让人垂涎三尺。', \\\n",
176
+ " params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "execution_count": null,
182
+ "metadata": {},
183
+ "outputs": [],
184
+ "source": [
185
+ "Audio(wav[0], rate=24_000, autoplay=True)"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "markdown",
190
+ "metadata": {},
191
+ "source": [
192
+ "### Fix random speaker"
193
+ ]
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "execution_count": null,
198
+ "metadata": {},
199
+ "outputs": [],
200
+ "source": [
201
+ "rand_spk = chat.sample_random_speaker()\n",
202
+ "params_infer_code = {'spk_emb' : rand_spk, }\n",
203
+ "\n",
204
+ "wav = chat.infer('四���美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。', \\\n",
205
+ " params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "execution_count": null,
211
+ "metadata": {},
212
+ "outputs": [],
213
+ "source": [
214
+ "Audio(wav[0], rate=24_000, autoplay=True)"
215
+ ]
216
+ },
217
+ {
218
+ "cell_type": "markdown",
219
+ "metadata": {},
220
+ "source": [
221
+ "### Two stage control"
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "execution_count": null,
227
+ "metadata": {},
228
+ "outputs": [],
229
+ "source": [
230
+ "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",
231
+ "chat.infer(text, refine_text_only=True)"
232
+ ]
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "execution_count": null,
237
+ "metadata": {},
238
+ "outputs": [],
239
+ "source": [
240
+ "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",
241
+ "wav = chat.infer(text, skip_refine_text=True)"
242
+ ]
243
+ },
244
+ {
245
+ "cell_type": "markdown",
246
+ "metadata": {},
247
+ "source": [
248
+ "## LLM Call"
249
+ ]
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "execution_count": null,
254
+ "metadata": {},
255
+ "outputs": [],
256
+ "source": [
257
+ "from ChatTTS.experimental.llm import llm_api\n",
258
+ "\n",
259
+ "API_KEY = ''\n",
260
+ "client = llm_api(api_key=API_KEY,\n",
261
+ " base_url=\"https://api.deepseek.com\",\n",
262
+ " model=\"deepseek-chat\")"
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "execution_count": null,
268
+ "metadata": {},
269
+ "outputs": [],
270
+ "source": [
271
+ "user_question = '四川有哪些好吃的美食呢?'\n",
272
+ "text = client.call(user_question, prompt_version = 'deepseek')\n",
273
+ "print(text)\n",
274
+ "text = client.call(text, prompt_version = 'deepseek_TN')\n",
275
+ "print(text)"
276
+ ]
277
+ },
278
+ {
279
+ "cell_type": "code",
280
+ "execution_count": null,
281
+ "metadata": {},
282
+ "outputs": [],
283
+ "source": [
284
+ "params_infer_code = {'spk_emb' : rand_spk, 'temperature':.3}\n",
285
+ "\n",
286
+ "wav = chat.infer(text, params_infer_code=params_infer_code)"
287
+ ]
288
+ }
289
+ ],
290
+ "metadata": {
291
+ "kernelspec": {
292
+ "display_name": "Python 3 (ipykernel)",
293
+ "language": "python",
294
+ "name": "python3"
295
+ },
296
+ "language_info": {
297
+ "codemirror_mode": {
298
+ "name": "ipython",
299
+ "version": 3
300
+ },
301
+ "file_extension": ".py",
302
+ "mimetype": "text/x-python",
303
+ "name": "python",
304
+ "nbconvert_exporter": "python",
305
+ "pygments_lexer": "ipython3",
306
+ "version": "3.9.6"
307
+ }
308
+ },
309
+ "nbformat": 4,
310
+ "nbformat_minor": 4
311
+ }
examples/web/funcs.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import torch
4
+ import gradio as gr
5
+ import numpy as np
6
+
7
+ from tools.logger import get_logger
8
+ logger = get_logger(" WebUI ")
9
+
10
+ import ChatTTS
11
+ chat = ChatTTS.Chat(get_logger("ChatTTS"))
12
+
13
+ # 音色选项:用于预置合适的音色
14
+ voices = {
15
+ "默认": {"seed": 2},
16
+ "音色1": {"seed": 1111},
17
+ "音色2": {"seed": 2222},
18
+ "音色3": {"seed": 3333},
19
+ "音色4": {"seed": 4444},
20
+ "音色5": {"seed": 5555},
21
+ "音色6": {"seed": 6666},
22
+ "音色7": {"seed": 7777},
23
+ "音色8": {"seed": 8888},
24
+ "音色9": {"seed": 9999},
25
+ "音色10": {"seed": 11111},
26
+ }
27
+
28
+ def generate_seed():
29
+ return gr.update(value=random.randint(1, 100000000))
30
+
31
+ # 返回选择音色对应的seed
32
+ def on_voice_change(vocie_selection):
33
+ return voices.get(vocie_selection)['seed']
34
+
35
+ def refine_text(text, audio_seed_input, text_seed_input, refine_text_flag):
36
+ if not refine_text_flag:
37
+ return text
38
+
39
+ global chat
40
+
41
+ torch.manual_seed(audio_seed_input)
42
+ params_refine_text = {'prompt': '[oral_2][laugh_0][break_6]'}
43
+
44
+ torch.manual_seed(text_seed_input)
45
+
46
+ text = chat.infer(text,
47
+ skip_refine_text=False,
48
+ refine_text_only=True,
49
+ params_refine_text=params_refine_text,
50
+ )
51
+ return text[0] if isinstance(text, list) else text
52
+
53
+ def generate_audio(text, temperature, top_P, top_K, audio_seed_input, text_seed_input, stream):
54
+ if not text: return None
55
+
56
+ global chat
57
+
58
+ torch.manual_seed(audio_seed_input)
59
+ rand_spk = chat.sample_random_speaker()
60
+ params_infer_code = {
61
+ 'spk_emb': rand_spk,
62
+ 'temperature': temperature,
63
+ 'top_P': top_P,
64
+ 'top_K': top_K,
65
+ }
66
+ torch.manual_seed(text_seed_input)
67
+
68
+ wav = chat.infer(
69
+ text,
70
+ skip_refine_text=True,
71
+ params_infer_code=params_infer_code,
72
+ stream=stream,
73
+ )
74
+
75
+ if stream:
76
+ for gen in wav:
77
+ wavs = [np.array([[]])]
78
+ wavs[0] = np.hstack([wavs[0], np.array(gen[0])])
79
+ audio = wavs[0][0]
80
+
81
+ # normalize
82
+ am = np.abs(audio).max() * 32768
83
+ if am > 32768:
84
+ am = 32768 * 32768 / am
85
+ np.multiply(audio, am, audio)
86
+ audio = audio.astype(np.int16)
87
+
88
+ yield 24000, audio
89
+ return
90
+
91
+ audio_data = np.array(wav[0]).flatten()
92
+ # normalize
93
+ am = np.abs(audio_data).max() * 32768
94
+ if am > 32768:
95
+ am = 32768 * 32768 / am
96
+ np.multiply(audio_data, am, audio_data)
97
+ audio_data = audio_data.astype(np.int16)
98
+ sample_rate = 24000
99
+
100
+ yield sample_rate, audio_data
examples/web/webui.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
10
+
11
+ import gradio as gr
12
+
13
+ from dotenv import load_dotenv
14
+ load_dotenv("sha256.env")
15
+
16
+ from examples.web.funcs import *
17
+
18
+ def main():
19
+
20
+ with gr.Blocks() as demo:
21
+ gr.Markdown("# ChatTTS WebUI")
22
+ gr.Markdown("- **GitHub Repo**: https://github.com/2noise/ChatTTS")
23
+ gr.Markdown("- **HuggingFace Repo**: https://huggingface.co/2Noise/ChatTTS")
24
+
25
+ default_text = "四川美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。"
26
+ text_input = gr.Textbox(label="Input Text", lines=4, placeholder="Please Input Text...", value=default_text)
27
+
28
+ with gr.Row():
29
+ refine_text_checkbox = gr.Checkbox(label="Refine text", value=True)
30
+ temperature_slider = gr.Slider(minimum=0.00001, maximum=1.0, step=0.00001, value=0.3, label="Audio temperature", interactive=True)
31
+ top_p_slider = gr.Slider(minimum=0.1, maximum=0.9, step=0.05, value=0.7, label="top_P", interactive=True)
32
+ top_k_slider = gr.Slider(minimum=1, maximum=20, step=1, value=20, label="top_K", interactive=True)
33
+
34
+ with gr.Row():
35
+ voice_selection = gr.Dropdown(label="音色", choices=voices.keys(), value='默认')
36
+ audio_seed_input = gr.Number(value=2, label="Audio Seed")
37
+ generate_audio_seed = gr.Button("\U0001F3B2")
38
+ text_seed_input = gr.Number(value=42, label="Text Seed")
39
+ generate_text_seed = gr.Button("\U0001F3B2")
40
+
41
+ with gr.Row():
42
+ auto_play_checkbox = gr.Checkbox(label="Auto Play", value=False, scale=1)
43
+ stream_mode_checkbox = gr.Checkbox(label="Stream Mode", value=False, scale=1)
44
+ generate_button = gr.Button("Generate", scale=2)
45
+
46
+ text_output = gr.Textbox(label="Output Text", interactive=False)
47
+
48
+ # 使用Gradio的回调功能来更新数值输入框
49
+ voice_selection.change(fn=on_voice_change, inputs=voice_selection, outputs=audio_seed_input)
50
+
51
+ generate_audio_seed.click(generate_seed,
52
+ inputs=[],
53
+ outputs=audio_seed_input)
54
+
55
+ generate_text_seed.click(generate_seed,
56
+ inputs=[],
57
+ outputs=text_seed_input)
58
+
59
+ generate_button.click(fn=lambda: "", outputs=text_output)
60
+ generate_button.click(refine_text,
61
+ inputs=[text_input, audio_seed_input, text_seed_input, refine_text_checkbox],
62
+ outputs=text_output)
63
+
64
+ @gr.render(inputs=[auto_play_checkbox, stream_mode_checkbox])
65
+ def make_audio(autoplay, stream):
66
+ audio_output = gr.Audio(
67
+ label="Output Audio",
68
+ value=None,
69
+ autoplay=autoplay,
70
+ streaming=stream,
71
+ interactive=False,
72
+ show_label=True,
73
+ )
74
+ text_output.change(generate_audio,
75
+ inputs=[text_output, temperature_slider, top_p_slider, top_k_slider, audio_seed_input, text_seed_input, stream_mode_checkbox],
76
+ outputs=audio_output)
77
+
78
+ gr.Examples(
79
+ examples=[
80
+ ["四川美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。", 0.3, 0.7, 20, 2, 42, True],
81
+ ["What is [uv_break]your favorite english food?[laugh][lbreak]", 0.5, 0.5, 10, 245, 531, True],
82
+ ["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],
83
+ ],
84
+ inputs=[text_input, temperature_slider, top_p_slider, top_k_slider, audio_seed_input, text_seed_input, refine_text_checkbox],
85
+ )
86
+
87
+ parser = argparse.ArgumentParser(description='ChatTTS demo Launch')
88
+ parser.add_argument('--server_name', type=str, default='0.0.0.0', help='Server name')
89
+ parser.add_argument('--server_port', type=int, default=8080, help='Server port')
90
+ parser.add_argument('--root_path', type=str, default=None, help='Root Path')
91
+ parser.add_argument('--custom_path', type=str, default=None, help='the custom model path')
92
+ args = parser.parse_args()
93
+
94
+ logger.info("loading ChatTTS model...")
95
+
96
+ global chat
97
+
98
+ if args.custom_path == None:
99
+ ret = chat.load_models()
100
+ else:
101
+ logger.info('local model path: %s', args.custom_path)
102
+ ret = chat.load_models('custom', custom_path=args.custom_path)
103
+
104
+ if ret:
105
+ logger.info("Models loaded successfully.")
106
+ else:
107
+ logger.error("Models load failed.")
108
+ sys.exit(1)
109
+
110
+
111
+ demo.launch(server_name=args.server_name, server_port=args.server_port, root_path=args.root_path, inbrowser=True)
112
+
113
+
114
+ if __name__ == '__main__':
115
+ main()
setup.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 'vector_quantize_pytorch',
10
+ 'transformers>=4.41.1',
11
+ 'vocos',
12
+ 'IPython',
13
+ ], # 定义依赖哪些模块
14
+ packages=find_packages(), # 系统自动从当前目录开始找包
15
+ )
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
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
+ }
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
+ `
tools/logger/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .log import get_logger
tools/logger/log.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform
2
+ import logging
3
+ from datetime import datetime, timezone
4
+
5
+ # from https://github.com/FloatTech/ZeroBot-Plugin/blob/c70766a989698452e60e5e48fb2f802a2444330d/console/console_windows.go#L89-L96
6
+ colorCodePanic = "\x1b[1;31m"
7
+ colorCodeFatal = "\x1b[1;31m"
8
+ colorCodeError = "\x1b[31m"
9
+ colorCodeWarn = "\x1b[33m"
10
+ colorCodeInfo = "\x1b[37m"
11
+ colorCodeDebug = "\x1b[32m"
12
+ colorCodeTrace = "\x1b[36m"
13
+ colorReset = "\x1b[0m"
14
+
15
+ log_level_color_code = {
16
+ logging.DEBUG: colorCodeDebug,
17
+ logging.INFO: colorCodeInfo,
18
+ logging.WARN: colorCodeWarn,
19
+ logging.ERROR: colorCodeError,
20
+ logging.FATAL: colorCodeFatal,
21
+ }
22
+
23
+ log_level_msg_str = {
24
+ logging.DEBUG: "DEBU",
25
+ logging.INFO: "INFO",
26
+ logging.WARN: "WARN",
27
+ logging.ERROR: "ERRO",
28
+ logging.FATAL: "FATL",
29
+ }
30
+
31
+ class Formatter(logging.Formatter):
32
+ def __init__(self, color=platform.system().lower() != "windows"):
33
+ # https://stackoverflow.com/questions/2720319/python-figure-out-local-timezone
34
+ self.tz = datetime.now(timezone.utc).astimezone().tzinfo
35
+ self.color = color
36
+
37
+ def format(self, record: logging.LogRecord):
38
+ logstr = "[" + datetime.now(self.tz).strftime('%z %Y%m%d %H:%M:%S') + "] ["
39
+ if self.color:
40
+ logstr += log_level_color_code.get(record.levelno, colorCodeInfo)
41
+ logstr += log_level_msg_str.get(record.levelno, record.levelname)
42
+ if self.color:
43
+ logstr += colorReset
44
+ logstr += f"] {str(record.name)} | {str(record.msg)}"
45
+ return logstr
46
+
47
+ def get_logger(name: str, lv = logging.INFO):
48
+ logger = logging.getLogger(name)
49
+ syslog = logging.StreamHandler()
50
+ syslog.setFormatter(Formatter())
51
+ logger.setLevel(lv)
52
+ logger.addHandler(syslog)
53
+ return logger
webui_mix.py CHANGED
@@ -10,11 +10,13 @@ import pandas
10
  import numpy as np
11
  from tqdm import tqdm
12
  import random
13
- import os
14
  import gradio as gr
15
  import json
16
- from utils import combine_audio, save_audio, batch_split, normalize_zh
17
- from tts_model import load_chat_tts_model, clear_cuda_cache, deterministic, generate_audio_for_seed
 
 
 
18
  import spaces
19
 
20
  parser = argparse.ArgumentParser(description="Gradio ChatTTS MIX")
 
10
  import numpy as np
11
  from tqdm import tqdm
12
  import random
 
13
  import gradio as gr
14
  import json
15
+ from utils import normalize_zh, batch_split, normalize_audio, combine_audio
16
+ from tts_model import load_chat_tts_model, clear_cuda_cache, generate_audio_for_seed
17
+ from config import DEFAULT_BATCH_SIZE, DEFAULT_SPEED, DEFAULT_TEMPERATURE, DEFAULT_TOP_K, DEFAULT_TOP_P, DEFAULT_ORAL, \
18
+ DEFAULT_LAUGH, DEFAULT_BK, DEFAULT_SEG_LENGTH
19
+ import torch
20
  import spaces
21
 
22
  parser = argparse.ArgumentParser(description="Gradio ChatTTS MIX")