utils.py 11.1 KB
Newer Older
L
lifuchen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

C
chenfeiyu 已提交
15 16
import os
import numpy as np
17
from matplotlib import cm
C
chenfeiyu 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
import matplotlib.pyplot as plt
import librosa
from scipy import signal
from librosa import display
import soundfile as sf

from paddle import fluid
import paddle.fluid.dygraph as dg
import paddle.fluid.initializer as I

from parakeet.g2p import en
from parakeet.models.deepvoice3.encoder import ConvSpec
from parakeet.models.deepvoice3 import Encoder, Decoder, Converter, DeepVoice3, WindowRange
from parakeet.utils.layer_tools import freeze


@fluid.framework.dygraph_only
def make_model(n_speakers, speaker_dim, speaker_embed_std, embed_dim,
               padding_idx, embedding_std, max_positions, n_vocab,
               freeze_embedding, filter_size, encoder_channels, mel_dim,
               decoder_channels, r, trainable_positional_encodings,
               use_memory_mask, query_position_rate, key_position_rate,
               window_behind, window_ahead, key_projection, value_projection,
               downsample_factor, linear_dim, use_decoder_states,
               converter_channels, dropout):
    """just a simple function to create a deepvoice 3 model"""
    if n_speakers > 1:
L
lifuchen 已提交
45 46 47
        spe = dg.Embedding(
            (n_speakers, speaker_dim),
            param_attr=I.Normal(scale=speaker_embed_std))
C
chenfeiyu 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    else:
        spe = None

    h = encoder_channels
    k = filter_size
    encoder_convolutions = (
        ConvSpec(h, k, 1),
        ConvSpec(h, k, 3),
        ConvSpec(h, k, 9),
        ConvSpec(h, k, 27),
        ConvSpec(h, k, 1),
        ConvSpec(h, k, 3),
        ConvSpec(h, k, 9),
        ConvSpec(h, k, 27),
        ConvSpec(h, k, 1),
L
lifuchen 已提交
63 64 65 66 67 68 69 70 71 72
        ConvSpec(h, k, 3), )
    enc = Encoder(
        n_vocab,
        embed_dim,
        n_speakers,
        speaker_dim,
        padding_idx=None,
        embedding_weight_std=embedding_std,
        convolutions=encoder_convolutions,
        dropout=dropout)
C
chenfeiyu 已提交
73 74 75 76 77 78 79 80 81 82
    if freeze_embedding:
        freeze(enc.embed)

    h = decoder_channels
    prenet_convolutions = (ConvSpec(h, k, 1), ConvSpec(h, k, 3))
    attentive_convolutions = (
        ConvSpec(h, k, 1),
        ConvSpec(h, k, 3),
        ConvSpec(h, k, 9),
        ConvSpec(h, k, 27),
L
lifuchen 已提交
83
        ConvSpec(h, k, 1), )
C
chenfeiyu 已提交
84 85
    attention = [True, False, False, False, True]
    force_monotonic_attention = [True, False, False, False, True]
L
lifuchen 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    dec = Decoder(
        n_speakers,
        speaker_dim,
        embed_dim,
        mel_dim,
        r=r,
        max_positions=max_positions,
        preattention=prenet_convolutions,
        convolutions=attentive_convolutions,
        attention=attention,
        dropout=dropout,
        use_memory_mask=use_memory_mask,
        force_monotonic_attention=force_monotonic_attention,
        query_position_rate=query_position_rate,
        key_position_rate=key_position_rate,
        window_range=WindowRange(window_behind, window_ahead),
        key_projection=key_projection,
        value_projection=value_projection)
C
chenfeiyu 已提交
104 105 106 107 108 109 110 111 112
    if not trainable_positional_encodings:
        freeze(dec.embed_keys_positions)
        freeze(dec.embed_query_positions)

    h = converter_channels
    postnet_convolutions = (
        ConvSpec(h, k, 1),
        ConvSpec(h, k, 3),
        ConvSpec(2 * h, k, 1),
L
lifuchen 已提交
113 114 115 116 117 118 119 120 121
        ConvSpec(2 * h, k, 3), )
    cvt = Converter(
        n_speakers,
        speaker_dim,
        dec.state_dim if use_decoder_states else mel_dim,
        linear_dim,
        time_upsampling=downsample_factor,
        convolutions=postnet_convolutions,
        dropout=dropout)
C
chenfeiyu 已提交
122 123 124 125 126 127 128 129 130
    dv3 = DeepVoice3(enc, dec, cvt, spe, use_decoder_states)
    return dv3


@fluid.framework.dygraph_only
def eval_model(model, text, replace_pronounciation_prob, min_level_db,
               ref_level_db, power, n_iter, win_length, hop_length,
               preemphasis):
    """generate waveform from text using a deepvoice 3 model"""
L
lifuchen 已提交
131 132 133 134
    text = np.array(
        en.text_to_sequence(
            text, p=replace_pronounciation_prob),
        dtype=np.int64)
C
chenfeiyu 已提交
135 136 137 138 139 140
    length = len(text)
    print("text sequence's length: {}".format(length))
    text_positions = np.arange(1, 1 + length)

    text = np.expand_dims(text, 0)
    text_positions = np.expand_dims(text_positions, 0)
141
    model.eval()
C
chenfeiyu 已提交
142 143
    mel_outputs, linear_outputs, alignments, done = model.transduce(
        dg.to_variable(text), dg.to_variable(text_positions))
144

C
chenfeiyu 已提交
145
    linear_outputs_np = linear_outputs.numpy()[0].T  # (C, T)
146 147 148
    wav = spec_to_waveform(linear_outputs_np, min_level_db, ref_level_db,
                           power, n_iter, win_length, hop_length, preemphasis)
    alignments_np = alignments.numpy()[0]  # batch_size = 1
C
chenfeiyu 已提交
149
    print("linear_outputs's shape: ", linear_outputs_np.shape)
150 151 152
    print("alignmnets' shape:", alignments.shape)
    return wav, alignments_np

C
chenfeiyu 已提交
153

154 155 156 157 158 159 160 161
def spec_to_waveform(spec, min_level_db, ref_level_db, power, n_iter,
                     win_length, hop_length, preemphasis):
    """Convert output linear spec to waveform using griffin-lim vocoder.
    
    Args:
        spec (ndarray): the output linear spectrogram, shape(C, T), where C means n_fft, T means frames.
    """
    denoramlized = np.clip(spec, 0, 1) * (-min_level_db) + min_level_db
C
chenfeiyu 已提交
162
    lin_scaled = np.exp((denoramlized + ref_level_db) / 20 * np.log(10))
L
lifuchen 已提交
163 164 165 166 167
    wav = librosa.griffinlim(
        lin_scaled**power,
        n_iter=n_iter,
        hop_length=hop_length,
        win_length=win_length)
168 169 170
    if preemphasis > 0:
        wav = signal.lfilter([1.], [1., -preemphasis], wav)
    return wav
C
chenfeiyu 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187


def make_output_tree(output_dir):
    print("creating output tree: {}".format(output_dir))
    ckpt_dir = os.path.join(output_dir, "checkpoints")
    state_dir = os.path.join(output_dir, "states")
    log_dir = os.path.join(output_dir, "log")

    for x in [ckpt_dir, state_dir]:
        if not os.path.exists(x):
            os.makedirs(x)
    for x in ["alignments", "waveform", "lin_spec", "mel_spec"]:
        p = os.path.join(state_dir, x)
        if not os.path.exists(p):
            os.makedirs(p)


188
def plot_alignment(alignment, path):
C
chenfeiyu 已提交
189 190
    """
    Plot an attention layer's alignment for a sentence.
191
    alignment: shape(T_dec, T_enc).
C
chenfeiyu 已提交
192 193
    """

194 195 196 197 198
    plt.figure()
    plt.imshow(alignment)
    plt.colorbar()
    plt.xlabel('Encoder timestep')
    plt.ylabel('Decoder timestep')
C
chenfeiyu 已提交
199 200 201 202 203
    plt.savefig(path)
    plt.close()


def save_state(save_dir,
204
               writer,
C
chenfeiyu 已提交
205 206 207 208 209 210
               global_step,
               mel_input=None,
               mel_output=None,
               lin_input=None,
               lin_output=None,
               alignments=None,
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
               win_length=1024,
               hop_length=256,
               min_level_db=-100,
               ref_level_db=20,
               power=1.4,
               n_iter=32,
               preemphasis=0.97,
               sample_rate=22050):
    """Save training intermediate results. Save states for the first sentence in the batch, including
    mel_spec(predicted, target), lin_spec(predicted, target), attn, waveform.
    
    Args:
        save_dir (str): directory to save results.
        writer (SummaryWriter): tensorboardX summary writer
        global_step (int): global step.
        mel_input (Variable, optional): Defaults to None. Shape(B, T_mel, C_mel)
        mel_output (Variable, optional): Defaults to None. Shape(B, T_mel, C_mel)
        lin_input (Variable, optional): Defaults to None. Shape(B, T_lin, C_lin)
        lin_output (Variable, optional): Defaults to None. Shape(B, T_lin, C_lin)
        alignments (Variable, optional): Defaults to None. Shape(N, B, T_dec, C_enc)
        wav ([type], optional): Defaults to None. [description]
    """
C
chenfeiyu 已提交
233 234

    if mel_input is not None and mel_output is not None:
235 236
        mel_input = mel_input[0].numpy().T
        mel_output = mel_output[0].numpy().T
C
chenfeiyu 已提交
237

238
        path = os.path.join(save_dir, "mel_spec")
C
chenfeiyu 已提交
239 240 241 242 243
        plt.figure(figsize=(10, 3))
        display.specshow(mel_input)
        plt.colorbar()
        plt.title("mel_input")
        plt.savefig(
L
lifuchen 已提交
244 245
            os.path.join(path, "target_mel_spec_step{:09d}.png".format(
                global_step)))
C
chenfeiyu 已提交
246 247
        plt.close()

L
lifuchen 已提交
248 249 250 251 252
        writer.add_image(
            "target/mel_spec",
            cm.viridis(mel_input),
            global_step,
            dataformats="HWC")
253

C
chenfeiyu 已提交
254 255 256
        plt.figure(figsize=(10, 3))
        display.specshow(mel_output)
        plt.colorbar()
257
        plt.title("mel_output")
C
chenfeiyu 已提交
258
        plt.savefig(
L
lifuchen 已提交
259 260
            os.path.join(path, "predicted_mel_spec_step{:09d}.png".format(
                global_step)))
C
chenfeiyu 已提交
261 262
        plt.close()

L
lifuchen 已提交
263 264 265 266 267
        writer.add_image(
            "predicted/mel_spec",
            cm.viridis(mel_output),
            global_step,
            dataformats="HWC")
268

C
chenfeiyu 已提交
269
    if lin_input is not None and lin_output is not None:
270 271
        lin_input = lin_input[0].numpy().T
        lin_output = lin_output[0].numpy().T
C
chenfeiyu 已提交
272 273 274 275 276 277 278
        path = os.path.join(save_dir, "lin_spec")

        plt.figure(figsize=(10, 3))
        display.specshow(lin_input)
        plt.colorbar()
        plt.title("mel_input")
        plt.savefig(
L
lifuchen 已提交
279 280
            os.path.join(path, "target_lin_spec_step{:09d}.png".format(
                global_step)))
C
chenfeiyu 已提交
281 282
        plt.close()

L
lifuchen 已提交
283 284 285 286 287
        writer.add_image(
            "target/lin_spec",
            cm.viridis(lin_input),
            global_step,
            dataformats="HWC")
288

C
chenfeiyu 已提交
289 290 291 292 293
        plt.figure(figsize=(10, 3))
        display.specshow(lin_output)
        plt.colorbar()
        plt.title("mel_input")
        plt.savefig(
L
lifuchen 已提交
294 295
            os.path.join(path, "predicted_lin_spec_step{:09d}.png".format(
                global_step)))
C
chenfeiyu 已提交
296 297
        plt.close()

L
lifuchen 已提交
298 299 300 301 302
        writer.add_image(
            "predicted/lin_spec",
            cm.viridis(lin_output),
            global_step,
            dataformats="HWC")
C
chenfeiyu 已提交
303

304 305 306 307 308 309 310 311 312
    if alignments is not None and len(alignments.shape) == 4:
        path = os.path.join(save_dir, "alignments")
        alignments = alignments[:, 0, :, :].numpy()
        for idx, attn_layer in enumerate(alignments):
            save_path = os.path.join(
                path,
                "train_attn_layer_{}_step_{}.png".format(idx, global_step))
            plot_alignment(attn_layer, save_path)

L
lifuchen 已提交
313 314 315 316 317
            writer.add_image(
                "train_attn/layer_{}".format(idx),
                cm.viridis(attn_layer),
                global_step,
                dataformats="HWC")
318 319 320 321

    if lin_output is not None:
        wav = spec_to_waveform(lin_output, min_level_db, ref_level_db, power,
                               n_iter, win_length, hop_length, preemphasis)
C
chenfeiyu 已提交
322
        path = os.path.join(save_dir, "waveform")
323 324 325
        save_path = os.path.join(
            path, "train_sample_step_{:09d}.wav".format(global_step))
        sf.write(save_path, wav, sample_rate)
L
lifuchen 已提交
326 327
        writer.add_audio(
            "train_sample", wav, global_step, sample_rate=sample_rate)