inference.py 10.4 KB
Newer Older
1
2
3
4
5
6
7
8
"""
Text-to-speech pipeline using Tacotron2.
"""

import argparse
import os
import random
import sys
9
from functools import partial
10

11
import numpy as np
12
13
14
15
16
import torch
import torchaudio
from datasets import InverseSpectralNormalization
from text.text_preprocessing import (
    available_phonemizers,
17
    available_symbol_set,
18
19
20
    get_symbol_list,
    text_to_sequence,
)
21
from torchaudio.models import Tacotron2, tacotron2 as pretrained_tacotron2
22
from utils import prepare_input_sequence
23
24
25
26
27
28


def parse_args():
    r"""
    Parse commandline arguments.
    """
29
30
31
32
33
34
    from torchaudio.models.tacotron2 import (
        _MODEL_CONFIG_AND_URLS as tacotron2_config_and_urls,
    )
    from torchaudio.models.wavernn import (
        _MODEL_CONFIG_AND_URLS as wavernn_config_and_urls,
    )
35
36
37

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
38
        "--checkpoint-name",
39
40
41
        type=str,
        default=None,
        choices=list(tacotron2_config_and_urls.keys()),
42
        help="[string] The name of the checkpoint to load.",
43
    )
44
45
    parser.add_argument("--checkpoint-path", type=str, default=None, help="[string] Path to the checkpoint file.")
    parser.add_argument("--output-path", type=str, default="./audio.wav", help="[string] Path to the output .wav file.")
46
    parser.add_argument(
47
48
        "--input-text",
        "-i",
49
50
        type=str,
        default="Hello world",
51
        help="[string] Type in something here and TTS will generate it!",
52
53
    )
    parser.add_argument(
54
55
56
        "--vocoder",
        default="nvidia_waveglow",
        choices=["griffin_lim", "wavernn", "nvidia_waveglow"],
57
58
59
60
        type=str,
        help="Select the vocoder to use.",
    )
    parser.add_argument(
61
        "--jit", default=False, action="store_true", help="If used, the model and inference function is jitted."
62
63
    )

64
    preprocessor = parser.add_argument_group("text preprocessor setup")
65
    preprocessor.add_argument(
66
67
        "--text-preprocessor",
        default="english_characters",
68
69
        type=str,
        choices=available_symbol_set,
70
        help="select text preprocessor to use.",
71
72
    )
    preprocessor.add_argument(
73
        "--phonemizer",
74
75
76
        default="DeepPhonemizer",
        type=str,
        choices=available_phonemizers,
77
        help='select phonemizer to use, only used when text-preprocessor is "english_phonemes"',
78
79
    )
    preprocessor.add_argument(
80
        "--phonemizer-checkpoint",
81
82
        default="./en_us_cmudict_forward.pt",
        type=str,
83
84
        help="the path or name of the checkpoint for the phonemizer, "
        'only used when text-preprocessor is "english_phonemes"',
85
86
    )
    preprocessor.add_argument(
87
        "--cmudict-root", default="./", type=str, help="the root directory for storing CMU dictionary files"
88
89
    )

90
91
92
93
94
95
    audio = parser.add_argument_group("audio parameters")
    audio.add_argument("--sample-rate", default=22050, type=int, help="Sampling rate")
    audio.add_argument("--n-fft", default=1024, type=int, help="Filter length for STFT")
    audio.add_argument("--n-mels", default=80, type=int, help="")
    audio.add_argument("--mel-fmin", default=0.0, type=float, help="Minimum mel frequency")
    audio.add_argument("--mel-fmax", default=8000.0, type=float, help="Maximum mel frequency")
96
97

    # parameters for WaveRNN
98
    wavernn = parser.add_argument_group("WaveRNN parameters")
99
    wavernn.add_argument(
100
        "--wavernn-checkpoint-name",
101
102
        default="wavernn_10k_epochs_8bits_ljspeech",
        choices=list(wavernn_config_and_urls.keys()),
103
        help="Select the WaveRNN checkpoint.",
104
105
106
107
108
109
110
111
112
113
114
115
    )
    wavernn.add_argument(
        "--wavernn-loss",
        default="crossentropy",
        choices=["crossentropy"],
        type=str,
        help="The type of loss the WaveRNN pretrained model is trained on.",
    )
    wavernn.add_argument(
        "--wavernn-no-batch-inference",
        default=False,
        action="store_true",
116
        help="Don't use batch inference for WaveRNN inference.",
117
118
    )
    wavernn.add_argument(
119
        "--wavernn-no-mulaw", default=False, action="store_true", help="Don't use mulaw decoder to decode the signal."
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    )
    wavernn.add_argument(
        "--wavernn-batch-timesteps",
        default=11000,
        type=int,
        help="The time steps for each batch. Only used when batch inference is used",
    )
    wavernn.add_argument(
        "--wavernn-batch-overlap",
        default=550,
        type=int,
        help="The overlapping time steps between batches. Only used when batch inference is used",
    )

    return parser


def unwrap_distributed(state_dict):
    r"""torch.distributed.DistributedDataParallel wraps the model with an additional "module.".
    This function unwraps this layer so that the weights can be loaded on models with a single GPU.

    Args:
        state_dict: Original state_dict.

    Return:
        unwrapped_state_dict: Unwrapped state_dict.
    """

148
    return {k.replace("module.", ""): v for k, v in state_dict.items()}
149
150
151


def nvidia_waveglow_vocode(mel_specgram, device, jit=False):
152
    waveglow = torch.hub.load("NVIDIA/DeepLearningExamples:torchhub", "nvidia_waveglow", model_math="fp16")
153
154
155
156
157
158
159
160
161
162
163
164
165
    waveglow = waveglow.remove_weightnorm(waveglow)
    waveglow = waveglow.to(device)
    waveglow.eval()

    if args.jit:
        raise ValueError("Vocoder option `nvidia_waveglow is not jittable.")

    with torch.no_grad():
        waveform = waveglow.infer(mel_specgram).cpu()

    return waveform


166
167
168
169
170
171
172
173
174
175
176
def wavernn_vocode(
    mel_specgram,
    wavernn_checkpoint_name,
    wavernn_loss,
    wavernn_no_mulaw,
    wavernn_no_batch_inference,
    wavernn_batch_timesteps,
    wavernn_batch_overlap,
    device,
    jit,
):
177
    from torchaudio.models import wavernn
178

179
180
    sys.path.append(os.path.join(os.path.dirname(__file__), "../pipeline_wavernn"))
    from processing import NormalizeDB
181
    from wavernn_inference_wrapper import WaveRNNInferenceWrapper
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203

    wavernn_model = wavernn(wavernn_checkpoint_name).eval().to(device)
    wavernn_inference_model = WaveRNNInferenceWrapper(wavernn_model)

    if jit:
        wavernn_inference_model = torch.jit.script(wavernn_inference_model)

    # WaveRNN spectro setting for default checkpoint
    # n_fft = 2048
    # n_mels = 80
    # win_length = 1100
    # hop_length = 275
    # f_min = 40
    # f_max = 11025

    transforms = torch.nn.Sequential(
        InverseSpectralNormalization(),
        NormalizeDB(min_level_db=-100, normalization=True),
    )
    mel_specgram = transforms(mel_specgram.cpu())

    with torch.no_grad():
204
205
206
207
208
209
210
211
        waveform = wavernn_inference_model(
            mel_specgram.to(device),
            loss_name=wavernn_loss,
            mulaw=(not wavernn_no_mulaw),
            batched=(not wavernn_no_batch_inference),
            timesteps=wavernn_batch_timesteps,
            overlap=wavernn_batch_overlap,
        )
212
213
214
    return waveform.unsqueeze(0)


215
216
217
218
219
220
221
222
223
def griffin_lim_vocode(
    mel_specgram,
    n_fft,
    n_mels,
    sample_rate,
    mel_fmin,
    mel_fmax,
    jit,
):
224
225
226
227
228
229
230
231
232
233
    from torchaudio.transforms import GriffinLim, InverseMelScale

    inv_norm = InverseSpectralNormalization()
    inv_mel = InverseMelScale(
        n_stft=(n_fft // 2 + 1),
        n_mels=n_mels,
        sample_rate=sample_rate,
        f_min=mel_fmin,
        f_max=mel_fmax,
        mel_scale="slaney",
234
        norm="slaney",
235
236
237
238
239
240
241
242
    )
    griffin_lim = GriffinLim(
        n_fft=n_fft,
        power=1,
        hop_length=256,
        win_length=1024,
    )

243
    vocoder = torch.nn.Sequential(inv_norm, inv_mel, griffin_lim)
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261

    if jit:
        vocoder = torch.jit.script(vocoder)

    waveform = vocoder(mel_specgram.cpu())
    return waveform


def main(args):
    torch.manual_seed(0)
    random.seed(0)
    np.random.seed(0)

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

    if args.checkpoint_path is None and args.checkpoint_name is None:
        raise ValueError("Either --checkpoint-path or --checkpoint-name must be specified.")
    elif args.checkpoint_path is not None and args.checkpoint_name is not None:
262
        raise ValueError("Both --checkpoint-path and --checkpoint-name are specified, " "can only specify one.")
263
264
265
266
267
268
269
270
271
272
273
274
275

    n_symbols = len(get_symbol_list(args.text_preprocessor))
    text_preprocessor = partial(
        text_to_sequence,
        symbol_list=args.text_preprocessor,
        phonemizer=args.phonemizer,
        checkpoint=args.phonemizer_checkpoint,
        cmudict_root=args.cmudict_root,
    )

    if args.checkpoint_path is not None:
        tacotron2 = Tacotron2(n_symbol=n_symbols)
        tacotron2.load_state_dict(
276
277
            unwrap_distributed(torch.load(args.checkpoint_path, map_location=device)["state_dict"])
        )
278
279
280
281
282
        tacotron2 = tacotron2.to(device).eval()
    elif args.checkpoint_name is not None:
        tacotron2 = pretrained_tacotron2(args.checkpoint_name).to(device).eval()

        if n_symbols != tacotron2.n_symbols:
283
284
285
286
287
            raise ValueError(
                "the number of symbols for text_preprocessor ({n_symbols}) "
                "should match the number of symbols for the"
                "pretrained tacotron2 ({tacotron2.n_symbols})."
            )
288
289
290
291

    if args.jit:
        tacotron2 = torch.jit.script(tacotron2)

292
    sequences, lengths = prepare_input_sequence([args.input_text], text_processor=text_preprocessor)
293
294
295
296
297
298
299
300
    sequences, lengths = sequences.long().to(device), lengths.long().to(device)
    with torch.no_grad():
        mel_specgram, _, _ = tacotron2.infer(sequences, lengths)

    if args.vocoder == "nvidia_waveglow":
        waveform = nvidia_waveglow_vocode(mel_specgram=mel_specgram, device=device, jit=args.jit)

    elif args.vocoder == "wavernn":
301
302
303
304
305
306
307
308
309
310
311
        waveform = wavernn_vocode(
            mel_specgram=mel_specgram,
            wavernn_checkpoint_name=args.wavernn_checkpoint_name,
            wavernn_loss=args.wavernn_loss,
            wavernn_no_mulaw=args.wavernn_no_mulaw,
            wavernn_no_batch_inference=args.wavernn_no_batch_inference,
            wavernn_batch_timesteps=args.wavernn_batch_timesteps,
            wavernn_batch_overlap=args.wavernn_batch_overlap,
            device=device,
            jit=args.jit,
        )
312
313

    elif args.vocoder == "griffin_lim":
314
315
316
317
318
319
320
321
322
        waveform = griffin_lim_vocode(
            mel_specgram=mel_specgram,
            n_fft=args.n_fft,
            n_mels=args.n_mels,
            sample_rate=args.sample_rate,
            mel_fmin=args.mel_fmin,
            mel_fmax=args.mel_fmax,
            jit=args.jit,
        )
323
324
325
326
327
328
329
330
331

    torchaudio.save(args.output_path, waveform, args.sample_rate)


if __name__ == "__main__":
    parser = parse_args()
    args, _ = parser.parse_known_args()

    main(args)