tacotron2_pipeline_tutorial.py 10.4 KB
Newer Older
moto's avatar
moto committed
1
"""
moto's avatar
moto committed
2
3
Text-to-Speech with Tacotron2
=============================
moto's avatar
moto committed
4
5
6
7
8
9

**Author** `Yao-Yuan Yang <https://github.com/yangarbiter>`__,
`Moto Hira <moto@fb.com>`__

"""

10
11
12
13
import IPython
import matplotlib
import matplotlib.pyplot as plt

moto's avatar
moto committed
14
15
16
######################################################################
# Overview
# --------
17
#
moto's avatar
moto committed
18
19
# This tutorial shows how to build text-to-speech pipeline, using the
# pretrained Tacotron2 in torchaudio.
20
#
moto's avatar
moto committed
21
# The text-to-speech pipeline goes as follows:
22
#
moto's avatar
moto committed
23
# 1. Text preprocessing
24
#
moto's avatar
moto committed
25
26
#    First, the input text is encoded into a list of symbols. In this
#    tutorial, we will use English characters and phonemes as the symbols.
27
#
moto's avatar
moto committed
28
# 2. Spectrogram generation
29
#
moto's avatar
moto committed
30
31
#    From the encoded text, a spectrogram is generated. We use ``Tacotron2``
#    model for this.
32
#
moto's avatar
moto committed
33
# 3. Time-domain conversion
34
#
moto's avatar
moto committed
35
36
37
#    The last step is converting the spectrogram into the waveform. The
#    process to generate speech from spectrogram is also called Vocoder.
#    In this tutorial, three different vocoders are used,
moto's avatar
moto committed
38
39
#    :py:class:`~torchaudio.models.WaveRNN`,
#    :py:class:`~torchaudio.transforms.GriffinLim`, and
moto's avatar
moto committed
40
#    `Nvidia's WaveGlow <https://pytorch.org/hub/nvidia_deeplearningexamples_tacotron2/>`__.
41
42
#
#
moto's avatar
moto committed
43
# The following figure illustrates the whole process.
44
#
moto's avatar
moto committed
45
# .. image:: https://download.pytorch.org/torchaudio/tutorial-assets/tacotron2_tts_pipeline.png
46
#
47
# All the related components are bundled in :py:class:`torchaudio.pipelines.Tacotron2TTSBundle`,
moto's avatar
moto committed
48
49
50
51
52
# but this tutorial will also cover the process under the hood.

######################################################################
# Preparation
# -----------
53
#
moto's avatar
moto committed
54
55
56
# First, we install the necessary dependencies. In addition to
# ``torchaudio``, ``DeepPhonemizer`` is required to perform phoneme-based
# encoding.
57
#
moto's avatar
moto committed
58

moto's avatar
moto committed
59
60
61
62
63
# %%
#  .. code-block:: bash
#
#      %%bash
#      pip3 install deep_phonemizer
moto's avatar
moto committed
64
65
66
67

import torch
import torchaudio

68
matplotlib.rcParams["figure.figsize"] = [16.0, 4.8]
moto's avatar
moto committed
69
70
71
72
73
74
75
76
77
78
79
80

torch.random.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"

print(torch.__version__)
print(torchaudio.__version__)
print(device)


######################################################################
# Text Processing
# ---------------
81
#
moto's avatar
moto committed
82
83
84
85
86


######################################################################
# Character-based encoding
# ~~~~~~~~~~~~~~~~~~~~~~~~
87
#
moto's avatar
moto committed
88
89
# In this section, we will go through how the character-based encoding
# works.
90
#
moto's avatar
moto committed
91
92
93
# Since the pre-trained Tacotron2 model expects specific set of symbol
# tables, the same functionalities available in ``torchaudio``. This
# section is more for the explanation of the basis of encoding.
94
#
moto's avatar
moto committed
95
96
97
98
# Firstly, we define the set of symbols. For example, we can use
# ``'_-!\'(),.:;? abcdefghijklmnopqrstuvwxyz'``. Then, we will map the
# each character of the input text into the index of the corresponding
# symbol in the table.
99
#
moto's avatar
moto committed
100
101
# The following is an example of such processing. In the example, symbols
# that are not in the table are ignored.
102
#
moto's avatar
moto committed
103

104
symbols = "_-!'(),.:;? abcdefghijklmnopqrstuvwxyz"
moto's avatar
moto committed
105
106
107
look_up = {s: i for i, s in enumerate(symbols)}
symbols = set(symbols)

108

moto's avatar
moto committed
109
def text_to_sequence(text):
110
111
112
    text = text.lower()
    return [look_up[s] for s in text if s in symbols]

moto's avatar
moto committed
113
114
115
116
117
118
119
120
121
122

text = "Hello world! Text to speech!"
print(text_to_sequence(text))


######################################################################
# As mentioned in the above, the symbol table and indices must match
# what the pretrained Tacotron2 model expects. ``torchaudio`` provides the
# transform along with the pretrained model. For example, you can
# instantiate and use such transform as follow.
123
#
moto's avatar
moto committed
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

processor = torchaudio.pipelines.TACOTRON2_WAVERNN_CHAR_LJSPEECH.get_text_processor()

text = "Hello world! Text to speech!"
processed, lengths = processor(text)

print(processed)
print(lengths)


######################################################################
# The ``processor`` object takes either a text or list of texts as inputs.
# When a list of texts are provided, the returned ``lengths`` variable
# represents the valid length of each processed tokens in the output
# batch.
139
#
moto's avatar
moto committed
140
# The intermediate representation can be retrieved as follow.
141
#
moto's avatar
moto committed
142

143
print([processor.tokens[i] for i in processed[0, : lengths[0]]])
moto's avatar
moto committed
144
145
146
147
148


######################################################################
# Phoneme-based encoding
# ~~~~~~~~~~~~~~~~~~~~~~
149
#
moto's avatar
moto committed
150
151
152
# Phoneme-based encoding is similar to character-based encoding, but it
# uses a symbol table based on phonemes and a G2P (Grapheme-to-Phoneme)
# model.
153
#
moto's avatar
moto committed
154
155
# The detail of the G2P model is out of scope of this tutorial, we will
# just look at what the conversion looks like.
156
#
moto's avatar
moto committed
157
158
159
# Similar to the case of character-based encoding, the encoding process is
# expected to match what a pretrained Tacotron2 model is trained on.
# ``torchaudio`` has an interface to create the process.
160
#
moto's avatar
moto committed
161
162
163
164
# The following code illustrates how to make and use the process. Behind
# the scene, a G2P model is created using ``DeepPhonemizer`` package, and
# the pretrained weights published by the author of ``DeepPhonemizer`` is
# fetched.
165
#
moto's avatar
moto committed
166
167
168
169
170
171
172

bundle = torchaudio.pipelines.TACOTRON2_WAVERNN_PHONE_LJSPEECH

processor = bundle.get_text_processor()

text = "Hello world! Text to speech!"
with torch.inference_mode():
173
    processed, lengths = processor(text)
moto's avatar
moto committed
174
175
176
177
178
179
180
181

print(processed)
print(lengths)


######################################################################
# Notice that the encoded values are different from the example of
# character-based encoding.
182
#
moto's avatar
moto committed
183
# The intermediate representation looks like the following.
184
#
moto's avatar
moto committed
185

186
print([processor.tokens[i] for i in processed[0, : lengths[0]]])
moto's avatar
moto committed
187
188
189
190
191


######################################################################
# Spectrogram Generation
# ----------------------
192
#
moto's avatar
moto committed
193
194
195
# ``Tacotron2`` is the model we use to generate spectrogram from the
# encoded text. For the detail of the model, please refer to `the
# paper <https://arxiv.org/abs/1712.05884>`__.
196
#
moto's avatar
moto committed
197
198
199
# It is easy to instantiate a Tacotron2 model with pretrained weight,
# however, note that the input to Tacotron2 models need to be processed
# by the matching text processor.
200
#
201
# :py:class:`torchaudio.pipelines.Tacotron2TTSBundle` bundles the matching
moto's avatar
moto committed
202
# models and processors together so that it is easy to create the pipeline.
203
#
204
205
# For the available bundles, and its usage, please refer to
# :py:class:`~torchaudio.pipelines.Tacotron2TTSBundle`.
206
#
moto's avatar
moto committed
207
208
209
210
211
212
213
214

bundle = torchaudio.pipelines.TACOTRON2_WAVERNN_PHONE_LJSPEECH
processor = bundle.get_text_processor()
tacotron2 = bundle.get_tacotron2().to(device)

text = "Hello world! Text to speech!"

with torch.inference_mode():
215
216
217
218
    processed, lengths = processor(text)
    processed = processed.to(device)
    lengths = lengths.to(device)
    spec, _, _ = tacotron2.infer(processed, lengths)
moto's avatar
moto committed
219
220


moto's avatar
moto committed
221
_ = plt.imshow(spec[0].cpu().detach())
moto's avatar
moto committed
222
223
224
225
226


######################################################################
# Note that ``Tacotron2.infer`` method perfoms multinomial sampling,
# therefor, the process of generating the spectrogram incurs randomness.
227
#
moto's avatar
moto committed
228
229
230

fig, ax = plt.subplots(3, 1, figsize=(16, 4.3 * 3))
for i in range(3):
231
232
233
234
    with torch.inference_mode():
        spec, spec_lengths, _ = tacotron2.infer(processed, lengths)
    print(spec[0].shape)
    ax[i].imshow(spec[0].cpu().detach())
moto's avatar
moto committed
235
236
237
238
239
240
plt.show()


######################################################################
# Waveform Generation
# -------------------
241
#
moto's avatar
moto committed
242
243
# Once the spectrogram is generated, the last process is to recover the
# waveform from the spectrogram.
244
#
moto's avatar
moto committed
245
246
# ``torchaudio`` provides vocoders based on ``GriffinLim`` and
# ``WaveRNN``.
247
#
moto's avatar
moto committed
248
249
250
251
252


######################################################################
# WaveRNN
# ~~~~~~~
253
#
moto's avatar
moto committed
254
255
# Continuing from the previous section, we can instantiate the matching
# WaveRNN model from the same bundle.
256
#
moto's avatar
moto committed
257
258
259
260
261
262
263
264
265
266

bundle = torchaudio.pipelines.TACOTRON2_WAVERNN_PHONE_LJSPEECH

processor = bundle.get_text_processor()
tacotron2 = bundle.get_tacotron2().to(device)
vocoder = bundle.get_vocoder().to(device)

text = "Hello world! Text to speech!"

with torch.inference_mode():
267
268
269
270
271
    processed, lengths = processor(text)
    processed = processed.to(device)
    lengths = lengths.to(device)
    spec, spec_lengths, _ = tacotron2.infer(processed, lengths)
    waveforms, lengths = vocoder(spec, spec_lengths)
moto's avatar
moto committed
272
273
274
275
276

fig, [ax1, ax2] = plt.subplots(2, 1, figsize=(16, 9))
ax1.imshow(spec[0].cpu().detach())
ax2.plot(waveforms[0].cpu().detach())

277
IPython.display.Audio(waveforms[0:1].cpu(), rate=vocoder.sample_rate)
moto's avatar
moto committed
278
279
280
281
282


######################################################################
# Griffin-Lim
# ~~~~~~~~~~~
283
#
moto's avatar
moto committed
284
# Using the Griffin-Lim vocoder is same as WaveRNN. You can instantiate
285
286
287
# the vocode object with
# :py:func:`~torchaudio.pipelines.Tacotron2TTSBundle.get_vocoder`
# method and pass the spectrogram.
288
#
moto's avatar
moto committed
289
290
291
292
293
294
295
296

bundle = torchaudio.pipelines.TACOTRON2_GRIFFINLIM_PHONE_LJSPEECH

processor = bundle.get_text_processor()
tacotron2 = bundle.get_tacotron2().to(device)
vocoder = bundle.get_vocoder().to(device)

with torch.inference_mode():
297
298
299
300
    processed, lengths = processor(text)
    processed = processed.to(device)
    lengths = lengths.to(device)
    spec, spec_lengths, _ = tacotron2.infer(processed, lengths)
moto's avatar
moto committed
301
302
303
304
305
306
waveforms, lengths = vocoder(spec, spec_lengths)

fig, [ax1, ax2] = plt.subplots(2, 1, figsize=(16, 9))
ax1.imshow(spec[0].cpu().detach())
ax2.plot(waveforms[0].cpu().detach())

307
IPython.display.Audio(waveforms[0:1].cpu(), rate=vocoder.sample_rate)
moto's avatar
moto committed
308
309
310
311
312


######################################################################
# Waveglow
# ~~~~~~~~
313
#
314
315
# Waveglow is a vocoder published by Nvidia. The pretrained weights are
# published on Torch Hub. One can instantiate the model using ``torch.hub``
moto's avatar
moto committed
316
# module.
317
#
moto's avatar
moto committed
318
319
320

# Workaround to load model mapped on GPU
# https://stackoverflow.com/a/61840832
321
322
323
324
325
326
327
328
329
330
331
waveglow = torch.hub.load(
    "NVIDIA/DeepLearningExamples:torchhub",
    "nvidia_waveglow",
    model_math="fp32",
    pretrained=False,
)
checkpoint = torch.hub.load_state_dict_from_url(
    "https://api.ngc.nvidia.com/v2/models/nvidia/waveglowpyt_fp32/versions/1/files/nvidia_waveglowpyt_fp32_20190306.pth",  # noqa: E501
    progress=False,
    map_location=device,
)
332
state_dict = {key.replace("module.", ""): value for key, value in checkpoint["state_dict"].items()}
moto's avatar
moto committed
333
334
335
336
337
338
339

waveglow.load_state_dict(state_dict)
waveglow = waveglow.remove_weightnorm(waveglow)
waveglow = waveglow.to(device)
waveglow.eval()

with torch.no_grad():
340
    waveforms = waveglow.infer(spec)
moto's avatar
moto committed
341
342
343
344
345

fig, [ax1, ax2] = plt.subplots(2, 1, figsize=(16, 9))
ax1.imshow(spec[0].cpu().detach())
ax2.plot(waveforms[0].cpu().detach())

346
IPython.display.Audio(waveforms[0:1].cpu(), rate=22050)