jbetker commited on
Commit
287debd
1 Parent(s): 9db06e1

port do_tts to use the API

Browse files
Files changed (2) hide show
  1. api.py +27 -4
  2. do_tts.py +9 -197
api.py CHANGED
@@ -151,10 +151,10 @@ class TextToSpeech:
151
 
152
  def tts(self, text, voice_samples, k=1,
153
  # autoregressive generation parameters follow
154
- num_autoregressive_samples=512, temperature=.9, length_penalty=1, repetition_penalty=1.0, top_k=50, top_p=.95,
155
  typical_sampling=False, typical_mass=.9,
156
  # diffusion generation parameters follow
157
- diffusion_iterations=100, cond_free=True, cond_free_k=1, diffusion_temperature=1,):
158
  text = torch.IntTensor(self.tokenizer.encode(text)).unsqueeze(0).cuda()
159
  text = F.pad(text, (0, 1)) # This may not be necessary.
160
 
@@ -181,7 +181,6 @@ class TextToSpeech:
181
  for b in tqdm(range(num_batches)):
182
  codes = self.autoregressive.inference_speech(conds, text,
183
  do_sample=True,
184
- top_k=top_k,
185
  top_p=top_p,
186
  temperature=temperature,
187
  num_return_sequences=self.autoregressive_batch_size,
@@ -220,4 +219,28 @@ class TextToSpeech:
220
 
221
  if len(wav_candidates) > 1:
222
  return wav_candidates
223
- return wav_candidates[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  def tts(self, text, voice_samples, k=1,
153
  # autoregressive generation parameters follow
154
+ num_autoregressive_samples=512, temperature=.5, length_penalty=2, repetition_penalty=2.0, top_p=.5,
155
  typical_sampling=False, typical_mass=.9,
156
  # diffusion generation parameters follow
157
+ diffusion_iterations=100, cond_free=True, cond_free_k=2, diffusion_temperature=.7,):
158
  text = torch.IntTensor(self.tokenizer.encode(text)).unsqueeze(0).cuda()
159
  text = F.pad(text, (0, 1)) # This may not be necessary.
160
 
 
181
  for b in tqdm(range(num_batches)):
182
  codes = self.autoregressive.inference_speech(conds, text,
183
  do_sample=True,
 
184
  top_p=top_p,
185
  temperature=temperature,
186
  num_return_sequences=self.autoregressive_batch_size,
 
219
 
220
  if len(wav_candidates) > 1:
221
  return wav_candidates
222
+ return wav_candidates[0]
223
+
224
+ def refine_for_intellibility(self, wav_candidates, corresponding_codes, output_path):
225
+ """
226
+ Further refine the remaining candidates using a ASR model to pick out the ones that are the most understandable.
227
+ TODO: finish this function
228
+ :param wav_candidates:
229
+ :return:
230
+ """
231
+ transcriber = ocotillo.Transcriber(on_cuda=True)
232
+ transcriptions = transcriber.transcribe_batch(torch.cat(wav_candidates, dim=0).squeeze(1), 24000)
233
+ best = 99999999
234
+ for i, transcription in enumerate(transcriptions):
235
+ dist = lev_distance(transcription, args.text.lower())
236
+ if dist < best:
237
+ best = dist
238
+ best_codes = corresponding_codes[i].unsqueeze(0)
239
+ best_wav = wav_candidates[i]
240
+ del transcriber
241
+ torchaudio.save(os.path.join(output_path, f'{voice}_poor.wav'), best_wav.squeeze(0).cpu(), 24000)
242
+
243
+ # Perform diffusion again with the high-quality diffuser.
244
+ mel = do_spectrogram_diffusion(diffusion, final_diffuser, best_codes, cond_diffusion, mean=False)
245
+ wav = vocoder.inference(mel)
246
+ torchaudio.save(os.path.join(args.output_path, f'{voice}.wav'), wav.squeeze(0).cpu(), 24000)
do_tts.py CHANGED
@@ -1,123 +1,13 @@
1
  import argparse
2
  import os
3
- import random
4
- from urllib import request
5
 
6
  import torch
7
  import torch.nn.functional as F
8
  import torchaudio
9
- import progressbar
10
- import ocotillo
11
-
12
- from models.diffusion_decoder import DiffusionTts
13
- from models.autoregressive import UnifiedVoice
14
- from tqdm import tqdm
15
-
16
- from models.arch_util import TorchMelSpectrogram
17
- from models.text_voice_clip import VoiceCLIP
18
- from models.vocoder import UnivNetGenerator
19
- from utils.audio import load_audio, wav_to_univnet_mel, denormalize_tacotron_mel
20
- from utils.diffusion import SpacedDiffusion, space_timesteps, get_named_beta_schedule
21
- from utils.tokenizer import VoiceBpeTokenizer, lev_distance
22
-
23
- pbar = None
24
- def download_models():
25
- MODELS = {
26
- 'clip.pth': 'https://huggingface.co/jbetker/tortoise-tts-clip/resolve/main/pytorch-model.bin',
27
- 'diffusion.pth': 'https://huggingface.co/jbetker/tortoise-tts-diffusion-v1/resolve/main/pytorch-model.bin',
28
- 'autoregressive.pth': 'https://huggingface.co/jbetker/tortoise-tts-autoregressive/resolve/main/pytorch-model.bin'
29
- }
30
- os.makedirs('.models', exist_ok=True)
31
- def show_progress(block_num, block_size, total_size):
32
- global pbar
33
- if pbar is None:
34
- pbar = progressbar.ProgressBar(maxval=total_size)
35
- pbar.start()
36
-
37
- downloaded = block_num * block_size
38
- if downloaded < total_size:
39
- pbar.update(downloaded)
40
- else:
41
- pbar.finish()
42
- pbar = None
43
- for model_name, url in MODELS.items():
44
- if os.path.exists(f'.models/{model_name}'):
45
- continue
46
- print(f'Downloading {model_name} from {url}...')
47
- request.urlretrieve(url, f'.models/{model_name}', show_progress)
48
- print('Done.')
49
-
50
-
51
- def load_discrete_vocoder_diffuser(trained_diffusion_steps=4000, desired_diffusion_steps=200, cond_free=True):
52
- """
53
- Helper function to load a GaussianDiffusion instance configured for use as a vocoder.
54
- """
55
- return SpacedDiffusion(use_timesteps=space_timesteps(trained_diffusion_steps, [desired_diffusion_steps]), model_mean_type='epsilon',
56
- model_var_type='learned_range', loss_type='mse', betas=get_named_beta_schedule('linear', trained_diffusion_steps),
57
- conditioning_free=cond_free, conditioning_free_k=1)
58
-
59
-
60
- def load_conditioning(path, sample_rate=22050, cond_length=132300):
61
- rel_clip = load_audio(path, sample_rate)
62
- gap = rel_clip.shape[-1] - cond_length
63
- if gap < 0:
64
- rel_clip = F.pad(rel_clip, pad=(0, abs(gap)))
65
- elif gap > 0:
66
- rand_start = random.randint(0, gap)
67
- rel_clip = rel_clip[:, rand_start:rand_start + cond_length]
68
- mel_clip = TorchMelSpectrogram()(rel_clip.unsqueeze(0)).squeeze(0)
69
- return mel_clip.unsqueeze(0).cuda(), rel_clip.unsqueeze(0).cuda()
70
-
71
-
72
- def fix_autoregressive_output(codes, stop_token):
73
- """
74
- This function performs some padding on coded audio that fixes a mismatch issue between what the diffusion model was
75
- trained on and what the autoregressive code generator creates (which has no padding or end).
76
- This is highly specific to the DVAE being used, so this particular coding will not necessarily work if used with
77
- a different DVAE. This can be inferred by feeding a audio clip padded with lots of zeros on the end through the DVAE
78
- and copying out the last few codes.
79
-
80
- Failing to do this padding will produce speech with a harsh end that sounds like "BLAH" or similar.
81
- """
82
- # Strip off the autoregressive stop token and add padding.
83
- stop_token_indices = (codes == stop_token).nonzero()
84
- if len(stop_token_indices) == 0:
85
- print("No stop tokens found, enjoy that output of yours!")
86
- return
87
- else:
88
- codes[stop_token_indices] = 83
89
- stm = stop_token_indices.min().item()
90
- codes[stm:] = 83
91
- if stm - 3 < codes.shape[0]:
92
- codes[-3] = 45
93
- codes[-2] = 45
94
- codes[-1] = 248
95
-
96
- return codes
97
-
98
-
99
- def do_spectrogram_diffusion(diffusion_model, diffuser, mel_codes, conditioning_input, mean=False):
100
- """
101
- Uses the specified diffusion model and DVAE model to convert the provided MEL & conditioning inputs into an audio clip.
102
- """
103
- with torch.no_grad():
104
- cond_mel = wav_to_univnet_mel(conditioning_input.squeeze(1), do_normalization=False)
105
- # Pad MEL to multiples of 32
106
- msl = mel_codes.shape[-1]
107
- dsl = 32
108
- gap = dsl - (msl % dsl)
109
- if gap > 0:
110
- mel = torch.nn.functional.pad(mel_codes, (0, gap))
111
-
112
- output_shape = (mel.shape[0], 100, mel.shape[-1]*4)
113
- precomputed_embeddings = diffusion_model.timestep_independent(mel_codes, cond_mel)
114
- if mean:
115
- mel = diffuser.p_sample_loop(diffusion_model, output_shape, noise=torch.zeros(output_shape, device=mel_codes.device),
116
- model_kwargs={'precomputed_aligned_embeddings': precomputed_embeddings})
117
- else:
118
- mel = diffuser.p_sample_loop(diffusion_model, output_shape, model_kwargs={'precomputed_aligned_embeddings': precomputed_embeddings})
119
- return denormalize_tacotron_mel(mel)[:,:,:msl*4]
120
 
 
 
 
121
 
122
  if __name__ == '__main__':
123
  # These are voices drawn randomly from the training set. You are free to substitute your own voices in, but testing
@@ -139,101 +29,23 @@ if __name__ == '__main__':
139
  parser.add_argument('-text', type=str, help='Text to speak.', default="I am a language model that has learned to speak.")
140
  parser.add_argument('-voice', type=str, help='Use a preset conditioning voice (defined above). Overrides cond_path.', default='dotrice,harris,lescault,otto,atkins,grace,kennard,mol')
141
  parser.add_argument('-num_samples', type=int, help='How many total outputs the autoregressive transformer should produce.', default=512)
142
- parser.add_argument('-num_batches', type=int, help='How many batches those samples should be produced over.', default=16)
143
  parser.add_argument('-num_diffusion_samples', type=int, help='Number of outputs that progress to the diffusion stage.', default=16)
144
  parser.add_argument('-output_path', type=str, help='Where to store outputs.', default='results/')
145
  args = parser.parse_args()
146
-
147
  os.makedirs(args.output_path, exist_ok=True)
148
- download_models()
 
149
 
150
  for voice in args.voice.split(','):
151
- print("Loading data..")
152
  tokenizer = VoiceBpeTokenizer()
153
  text = torch.IntTensor(tokenizer.encode(args.text)).unsqueeze(0).cuda()
154
  text = F.pad(text, (0,1)) # This may not be necessary.
155
  cond_paths = preselected_cond_voices[voice]
156
  conds = []
157
  for cond_path in cond_paths:
158
- c, cond_wav = load_conditioning(cond_path)
159
  conds.append(c)
160
- conds = torch.stack(conds, dim=1)
161
- cond_diffusion = cond_wav[:, :88200] # The diffusion model expects <= 88200 conditioning samples.
162
-
163
- print("Loading GPT TTS..")
164
- autoregressive = UnifiedVoice(max_mel_tokens=300, max_text_tokens=200, max_conditioning_inputs=2, layers=30, model_dim=1024,
165
- heads=16, number_text_tokens=256, start_text_token=255, checkpointing=False, train_solo_embeddings=False,
166
- average_conditioning_embeddings=True).cuda().eval()
167
- autoregressive.load_state_dict(torch.load('.models/autoregressive.pth'))
168
- stop_mel_token = autoregressive.stop_mel_token
169
-
170
- with torch.no_grad():
171
- print("Performing autoregressive inference..")
172
- samples = []
173
- for b in tqdm(range(args.num_batches)):
174
- codes = autoregressive.inference_speech(conds, text, num_beams=1, repetition_penalty=1.0, do_sample=True, top_k=50, top_p=.95,
175
- temperature=.9, num_return_sequences=args.num_samples//args.num_batches, length_penalty=1)
176
- padding_needed = 250 - codes.shape[1]
177
- codes = F.pad(codes, (0, padding_needed), value=stop_mel_token)
178
- samples.append(codes)
179
- del autoregressive
180
-
181
- print("Loading CLIP..")
182
- clip = VoiceCLIP(dim_text=512, dim_speech=512, dim_latent=512, num_text_tokens=256, text_enc_depth=12, text_seq_len=350, text_heads=8,
183
- num_speech_tokens=8192, speech_enc_depth=12, speech_heads=8, speech_seq_len=430, use_xformers=True).cuda().eval()
184
- clip.load_state_dict(torch.load('.models/clip.pth'))
185
- print("Performing CLIP filtering..")
186
- clip_results = []
187
- for batch in samples:
188
- for i in range(batch.shape[0]):
189
- batch[i] = fix_autoregressive_output(batch[i], stop_mel_token)
190
- clip_results.append(clip(text.repeat(batch.shape[0], 1), batch, return_loss=False))
191
- clip_results = torch.cat(clip_results, dim=0)
192
- samples = torch.cat(samples, dim=0)
193
- best_results = samples[torch.topk(clip_results, k=args.num_diffusion_samples).indices]
194
-
195
- # Delete the autoregressive and clip models to free up GPU memory
196
- del samples, clip
197
-
198
- print("Loading Diffusion Model..")
199
- diffusion = DiffusionTts(model_channels=512, in_channels=100, out_channels=200, in_latent_channels=1024,
200
- channel_mult=[1, 2, 3, 4], num_res_blocks=[3, 3, 3, 3], token_conditioning_resolutions=[1,4,8],
201
- dropout=0, attention_resolutions=[4,8], num_heads=8, kernel_size=3, scale_factor=2,
202
- time_embed_dim_multiplier=4, unconditioned_percentage=0, conditioning_dim_factor=2,
203
- conditioning_expansion=1)
204
- diffusion.load_state_dict(torch.load('.models/diffusion.pth'))
205
- diffusion = diffusion.cuda().eval()
206
- print("Loading vocoder..")
207
- vocoder = UnivNetGenerator()
208
- vocoder.load_state_dict(torch.load('.models/vocoder.pth')['model_g'])
209
- vocoder = vocoder.cuda()
210
- vocoder.eval(inference=True)
211
- initial_diffuser = load_discrete_vocoder_diffuser(desired_diffusion_steps=40, cond_free=False)
212
- final_diffuser = load_discrete_vocoder_diffuser(desired_diffusion_steps=500)
213
-
214
- print("Performing vocoding..")
215
- wav_candidates = []
216
- for b in range(best_results.shape[0]):
217
- code = best_results[b].unsqueeze(0)
218
- mel = do_spectrogram_diffusion(diffusion, initial_diffuser, code, cond_diffusion, mean=False)
219
- wav = vocoder.inference(mel)
220
- wav_candidates.append(wav.cpu())
221
-
222
- # Further refine the remaining candidates using a ASR model to pick out the ones that are the most understandable.
223
- transcriber = ocotillo.Transcriber(on_cuda=True)
224
- transcriptions = transcriber.transcribe_batch(torch.cat(wav_candidates, dim=0).squeeze(1), 24000)
225
- best = 99999999
226
- for i, transcription in enumerate(transcriptions):
227
- dist = lev_distance(transcription, args.text.lower())
228
- if dist < best:
229
- best = dist
230
- best_codes = best_results[i].unsqueeze(0)
231
- best_wav = wav_candidates[i]
232
- del transcriber
233
- torchaudio.save(os.path.join(args.output_path, f'{voice}_poor.wav'), best_wav.squeeze(0).cpu(), 24000)
234
-
235
- # Perform diffusion again with the high-quality diffuser.
236
- mel = do_spectrogram_diffusion(diffusion, final_diffuser, best_codes, cond_diffusion, mean=False)
237
- wav = vocoder.inference(mel)
238
- torchaudio.save(os.path.join(args.output_path, f'{voice}.wav'), wav.squeeze(0).cpu(), 24000)
239
 
 
1
  import argparse
2
  import os
 
 
3
 
4
  import torch
5
  import torch.nn.functional as F
6
  import torchaudio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ from api import TextToSpeech, load_conditioning
9
+ from utils.audio import load_audio
10
+ from utils.tokenizer import VoiceBpeTokenizer
11
 
12
  if __name__ == '__main__':
13
  # These are voices drawn randomly from the training set. You are free to substitute your own voices in, but testing
 
29
  parser.add_argument('-text', type=str, help='Text to speak.', default="I am a language model that has learned to speak.")
30
  parser.add_argument('-voice', type=str, help='Use a preset conditioning voice (defined above). Overrides cond_path.', default='dotrice,harris,lescault,otto,atkins,grace,kennard,mol')
31
  parser.add_argument('-num_samples', type=int, help='How many total outputs the autoregressive transformer should produce.', default=512)
32
+ parser.add_argument('-batch_size', type=int, help='How many samples to process at once in the autoregressive model.', default=16)
33
  parser.add_argument('-num_diffusion_samples', type=int, help='Number of outputs that progress to the diffusion stage.', default=16)
34
  parser.add_argument('-output_path', type=str, help='Where to store outputs.', default='results/')
35
  args = parser.parse_args()
 
36
  os.makedirs(args.output_path, exist_ok=True)
37
+
38
+ tts = TextToSpeech(autoregressive_batch_size=args.batch_size)
39
 
40
  for voice in args.voice.split(','):
 
41
  tokenizer = VoiceBpeTokenizer()
42
  text = torch.IntTensor(tokenizer.encode(args.text)).unsqueeze(0).cuda()
43
  text = F.pad(text, (0,1)) # This may not be necessary.
44
  cond_paths = preselected_cond_voices[voice]
45
  conds = []
46
  for cond_path in cond_paths:
47
+ c = load_audio(cond_path, 22050)
48
  conds.append(c)
49
+ gen = tts.tts(args.text, conds, num_autoregressive_samples=args.num_samples)
50
+ torchaudio.save(os.path.join(args.output_path, f'{voice}.wav'), gen.squeeze(0).cpu(), 24000)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51