ParakeetRebeccaRosario/examples/transformer_tts/synthesis.py

162 lines
6.0 KiB
Python
Raw Normal View History

2020-02-26 21:03:51 +08:00
# 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.
2019-12-16 17:04:22 +08:00
import os
from scipy.io.wavfile import write
from parakeet.g2p.en import text_to_sequence
import numpy as np
from tqdm import tqdm
from matplotlib import cm
2019-12-16 17:04:22 +08:00
from tensorboardX import SummaryWriter
2020-02-13 14:48:21 +08:00
from ruamel import yaml
2019-12-16 17:04:22 +08:00
import paddle.fluid as fluid
import paddle.fluid.dygraph as dg
from pathlib import Path
2020-02-13 14:48:21 +08:00
import argparse
2019-12-16 17:04:22 +08:00
from parse import add_config_options_to_parser
from pprint import pprint
2020-01-22 15:46:35 +08:00
from collections import OrderedDict
from parakeet.models.transformer_tts.utils import *
2020-01-22 15:46:35 +08:00
from parakeet import audio
2020-02-13 14:48:21 +08:00
from parakeet.models.transformer_tts.vocoder import Vocoder
2020-02-13 20:46:21 +08:00
from parakeet.models.transformer_tts.transformer_tts import TransformerTTS
2019-12-16 17:04:22 +08:00
2020-02-26 21:03:51 +08:00
2019-12-16 17:04:22 +08:00
def load_checkpoint(step, model_path):
2020-01-22 15:46:35 +08:00
model_dict, _ = fluid.dygraph.load_dygraph(os.path.join(model_path, step))
new_state_dict = OrderedDict()
for param in model_dict:
if param.startswith('_layers.'):
new_state_dict[param[8:]] = model_dict[param]
else:
new_state_dict[param] = model_dict[param]
return new_state_dict
2019-12-16 17:04:22 +08:00
2020-02-26 21:03:51 +08:00
2020-02-13 14:48:21 +08:00
def synthesis(text_input, args):
place = (fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace())
with open(args.config_path) as f:
cfg = yaml.load(f, Loader=yaml.Loader)
2019-12-16 17:04:22 +08:00
# tensorboard
2020-02-13 14:48:21 +08:00
if not os.path.exists(args.log_dir):
2020-02-26 21:03:51 +08:00
os.mkdir(args.log_dir)
path = os.path.join(args.log_dir, 'synthesis')
2019-12-16 17:04:22 +08:00
writer = SummaryWriter(path)
with dg.guard(place):
2020-01-15 14:10:27 +08:00
with fluid.unique_name.guard():
model = TransformerTTS(cfg)
2020-02-26 21:03:51 +08:00
model.set_dict(
load_checkpoint(
str(args.transformer_step),
os.path.join(args.checkpoint_path, "transformer")))
2020-01-15 14:10:27 +08:00
model.eval()
2020-02-26 21:03:51 +08:00
2020-01-15 14:10:27 +08:00
with fluid.unique_name.guard():
2020-02-18 11:49:36 +08:00
model_vocoder = Vocoder(cfg, args.batch_size)
2020-02-26 21:03:51 +08:00
model_vocoder.set_dict(
load_checkpoint(
str(args.vocoder_step),
os.path.join(args.checkpoint_path, "vocoder")))
2020-02-18 11:49:36 +08:00
model_vocoder.eval()
2019-12-16 17:04:22 +08:00
# init input
text = np.asarray(text_to_sequence(text_input))
2020-02-26 21:03:51 +08:00
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])
2019-12-16 17:04:22 +08:00
2020-02-13 14:48:21 +08:00
pbar = tqdm(range(args.max_len))
2019-12-16 17:04:22 +08:00
for i in pbar:
dec_slf_mask = get_triu_tensor(
mel_input.numpy(), mel_input.numpy()).astype(np.float32)
dec_slf_mask = fluid.layers.cast(
dg.to_variable(dec_slf_mask != 0), np.float32) * (-2**32 + 1)
2020-02-26 21:03:51 +08:00
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(
text, mel_input, pos_text, pos_mel, dec_slf_mask)
2020-02-26 21:03:51 +08:00
mel_input = fluid.layers.concat(
[mel_input, postnet_pred[:, -1:, :]], axis=1)
2020-02-18 11:49:36 +08:00
mag_pred = model_vocoder(postnet_pred)
2019-12-16 17:04:22 +08:00
2020-01-22 15:46:35 +08:00
_ljspeech_processor = audio.AudioProcessor(
2020-02-26 21:03:51 +08:00
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'],
2020-02-13 14:48:21 +08:00
power=cfg['audio']['power'],
preemphasis=cfg['audio']['preemphasis'],
2020-01-22 15:46:35 +08:00
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)
2020-02-26 21:03:51 +08:00
wav = _ljspeech_processor.inv_spectrogram(
fluid.layers.transpose(
fluid.layers.squeeze(mag_pred, [0]), [1, 0]).numpy())
global_step = 0
for i, prob in enumerate(attn_probs):
for j in range(4):
x = np.uint8(cm.viridis(prob.numpy()[j]) * 255)
writer.add_image(
'Attention_%d_0' % global_step,
x,
i * 4 + j,
dataformats="HWC")
for i, prob in enumerate(attn_enc):
for j in range(4):
x = np.uint8(cm.viridis(prob.numpy()[j]) * 255)
writer.add_image(
'Attention_enc_%d_0' % global_step,
x,
i * 4 + j,
dataformats="HWC")
for i, prob in enumerate(attn_dec):
for j in range(4):
x = np.uint8(cm.viridis(prob.numpy()[j]) * 255)
writer.add_image(
'Attention_dec_%d_0' % global_step,
x,
i * 4 + j,
dataformats="HWC")
2020-02-13 14:48:21 +08:00
writer.add_audio(text_input, wav, 0, cfg['audio']['sr'])
if not os.path.exists(args.sample_path):
os.mkdir(args.sample_path)
2020-02-26 21:03:51 +08:00
write(
os.path.join(args.sample_path, 'test.wav'), cfg['audio']['sr'],
wav)
2020-01-22 15:46:35 +08:00
writer.close()
2019-12-16 17:04:22 +08:00
2020-02-26 21:03:51 +08:00
2019-12-16 17:04:22 +08:00
if __name__ == '__main__':
2020-02-13 14:48:21 +08:00
parser = argparse.ArgumentParser(description="Synthesis model")
2019-12-16 17:04:22 +08:00
add_config_options_to_parser(parser)
2020-02-13 14:48:21 +08:00
args = parser.parse_args()
synthesis("Parakeet stands for Paddle PARAllel text-to-speech toolkit.",
args)