synthesis.py 6.5 KB
Newer Older
L
lifuchen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
L
lifuchen 已提交
14 15 16 17
import os
from scipy.io.wavfile import write
import numpy as np
from tqdm import tqdm
18
from matplotlib import cm
L
lifuchen 已提交
19
from tensorboardX import SummaryWriter
L
lifuchen 已提交
20
from ruamel import yaml
L
lifuchen 已提交
21
from pathlib import Path
L
lifuchen 已提交
22
import argparse
L
lifuchen 已提交
23
from pprint import pprint
24 25 26
import paddle.fluid as fluid
import paddle.fluid.dygraph as dg
from parakeet.g2p.en import text_to_sequence
27
from parakeet.models.transformer_tts.utils import *
L
lifuchen 已提交
28
from parakeet import audio
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
from parakeet.models.transformer_tts import Vocoder
from parakeet.models.transformer_tts import TransformerTTS
from parakeet.utils import io


def add_config_options_to_parser(parser):
    parser.add_argument("--config", type=str, help="path of the config file")
    parser.add_argument("--use_gpu", type=int, default=0, help="device to use")
    parser.add_argument(
        "--max_len",
        type=int,
        default=200,
        help="The max length of audio when synthsis.")

    parser.add_argument(
        "--checkpoint_transformer",
        type=str,
        help="transformer_tts checkpoint to synthesis")
    parser.add_argument(
        "--checkpoint_vocoder",
        type=str,
        help="vocoder checkpoint to synthesis")

    parser.add_argument(
        "--output",
        type=str,
        default="synthesis",
        help="path to save experiment results")
L
lifuchen 已提交
57

L
lifuchen 已提交
58

L
lifuchen 已提交
59
def synthesis(text_input, args):
60 61
    local_rank = dg.parallel.Env().local_rank
    place = (fluid.CUDAPlace(local_rank) if args.use_gpu else fluid.CPUPlace())
L
lifuchen 已提交
62

63
    with open(args.config) as f:
L
lifuchen 已提交
64
        cfg = yaml.load(f, Loader=yaml.Loader)
L
lifuchen 已提交
65 66

    # tensorboard
67 68
    if not os.path.exists(args.output):
        os.mkdir(args.output)
L
lifuchen 已提交
69

70
    writer = SummaryWriter(os.path.join(args.output, 'log'))
L
lifuchen 已提交
71 72

    with dg.guard(place):
L
lifuchen 已提交
73
        with fluid.unique_name.guard():
74 75 76 77 78 79 80 81 82 83 84
            network_cfg = cfg['network']
            model = TransformerTTS(
                network_cfg['embedding_size'], network_cfg['hidden_size'],
                network_cfg['encoder_num_head'],
                network_cfg['encoder_n_layers'], cfg['audio']['num_mels'],
                network_cfg['outputs_per_step'],
                network_cfg['decoder_num_head'],
                network_cfg['decoder_n_layers'])
            # Load parameters.
            global_step = io.load_parameters(
                model=model, checkpoint_path=args.checkpoint_transformer)
L
lifuchen 已提交
85
            model.eval()
L
lifuchen 已提交
86

L
lifuchen 已提交
87
        with fluid.unique_name.guard():
88 89 90 91 92 93
            model_vocoder = Vocoder(
                cfg['train']['batch_size'], cfg['vocoder']['hidden_size'],
                cfg['audio']['num_mels'], cfg['audio']['n_fft'])
            # Load parameters.
            global_step = io.load_parameters(
                model=model_vocoder, checkpoint_path=args.checkpoint_vocoder)
L
lifuchen 已提交
94
            model_vocoder.eval()
L
lifuchen 已提交
95 96
        # init input
        text = np.asarray(text_to_sequence(text_input))
L
lifuchen 已提交
97 98 99 100
        text = fluid.layers.unsqueeze(dg.to_variable(text), [0])
        mel_input = dg.to_variable(np.zeros([1, 1, 80])).astype(np.float32)
        pos_text = np.arange(1, text.shape[1] + 1)
        pos_text = fluid.layers.unsqueeze(dg.to_variable(pos_text), [0])
L
lifuchen 已提交
101

L
lifuchen 已提交
102
        pbar = tqdm(range(args.max_len))
L
lifuchen 已提交
103
        for i in pbar:
L
lifuchen 已提交
104 105 106
            pos_mel = np.arange(1, mel_input.shape[1] + 1)
            pos_mel = fluid.layers.unsqueeze(dg.to_variable(pos_mel), [0])
            mel_pred, postnet_pred, attn_probs, stop_preds, attn_enc, attn_dec = model(
107
                text, mel_input, pos_text, pos_mel)
L
lifuchen 已提交
108 109
            mel_input = fluid.layers.concat(
                [mel_input, postnet_pred[:, -1:, :]], axis=1)
110

L
lifuchen 已提交
111
        mag_pred = model_vocoder(postnet_pred)
L
lifuchen 已提交
112

L
lifuchen 已提交
113
        _ljspeech_processor = audio.AudioProcessor(
L
lifuchen 已提交
114 115 116 117 118 119 120
            sample_rate=cfg['audio']['sr'],
            num_mels=cfg['audio']['num_mels'],
            min_level_db=cfg['audio']['min_level_db'],
            ref_level_db=cfg['audio']['ref_level_db'],
            n_fft=cfg['audio']['n_fft'],
            win_length=cfg['audio']['win_length'],
            hop_length=cfg['audio']['hop_length'],
L
lifuchen 已提交
121 122
            power=cfg['audio']['power'],
            preemphasis=cfg['audio']['preemphasis'],
L
lifuchen 已提交
123 124 125 126 127 128 129 130 131 132
            signal_norm=True,
            symmetric_norm=False,
            max_norm=1.,
            mel_fmin=0,
            mel_fmax=None,
            clip_norm=True,
            griffin_lim_iters=60,
            do_trim_silence=False,
            sound_norm=False)

133
        # synthesis with cbhg
L
lifuchen 已提交
134 135 136
        wav = _ljspeech_processor.inv_spectrogram(
            fluid.layers.transpose(
                fluid.layers.squeeze(mag_pred, [0]), [1, 0]).numpy())
137 138 139 140
        global_step = 0
        for i, prob in enumerate(attn_probs):
            for j in range(4):
                x = np.uint8(cm.viridis(prob.numpy()[j]) * 255)
141 142 143 144 145
                writer.add_image(
                    'Attention_%d_0' % global_step,
                    x,
                    i * 4 + j,
                    dataformats="HWC")
146

147 148 149 150 151 152 153 154 155 156 157 158 159
        writer.add_audio(text_input + '(cbhg)', wav, 0, cfg['audio']['sr'])

        if not os.path.exists(os.path.join(args.output, 'samples')):
            os.mkdir(os.path.join(args.output, 'samples'))
        write(
            os.path.join(os.path.join(args.output, 'samples'), 'cbhg.wav'),
            cfg['audio']['sr'], wav)

        # synthesis with griffin-lim
        wav = _ljspeech_processor.inv_melspectrogram(
            fluid.layers.transpose(
                fluid.layers.squeeze(postnet_pred, [0]), [1, 0]).numpy())
        writer.add_audio(text_input + '(griffin)', wav, 0, cfg['audio']['sr'])
160

L
lifuchen 已提交
161
        write(
162 163 164
            os.path.join(os.path.join(args.output, 'samples'), 'griffin.wav'),
            cfg['audio']['sr'], wav)
        print("Synthesis completed !!!")
L
lifuchen 已提交
165
    writer.close()
L
lifuchen 已提交
166

L
lifuchen 已提交
167

L
lifuchen 已提交
168
if __name__ == '__main__':
L
lifuchen 已提交
169
    parser = argparse.ArgumentParser(description="Synthesis model")
L
lifuchen 已提交
170
    add_config_options_to_parser(parser)
L
lifuchen 已提交
171
    args = parser.parse_args()
172 173
    # Print the whole config setting.
    pprint(vars(args))
174 175
    synthesis("Parakeet stands for Paddle PARAllel text-to-speech toolkit.",
              args)