data.py 7.9 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 18 19 20 21 22 23 24 25
from pathlib import Path
import numpy as np
import pandas as pd
import librosa
import csv

from paddle import fluid
from parakeet import g2p
from parakeet import audio
from parakeet.data.sampler import *
from parakeet.data.datacargo import DataCargo
from parakeet.data.batch import TextIDBatcher, SpecBatcher
26 27
from parakeet.data.dataset import DatasetMixin, TransformDataset, CacheDataset
from parakeet.models.transformer_tts.utils import *
L
lifuchen 已提交
28

L
lifuchen 已提交
29

L
lifuchen 已提交
30
class LJSpeechLoader:
L
lifuchen 已提交
31 32 33 34 35 36 37
    def __init__(self,
                 config,
                 args,
                 nranks,
                 rank,
                 is_vocoder=False,
                 shuffle=True):
L
lifuchen 已提交
38
        place = fluid.CUDAPlace(rank) if args.use_gpu else fluid.CPUPlace()
L
lifuchen 已提交
39

L
lifuchen 已提交
40
        LJSPEECH_ROOT = Path(args.data_path)
L
lifuchen 已提交
41 42 43
        metadata = LJSpeechMetaData(LJSPEECH_ROOT)
        transformer = LJSpeech(config)
        dataset = TransformDataset(metadata, transformer)
44 45
        dataset = CacheDataset(dataset)

L
lifuchen 已提交
46 47
        sampler = DistributedSampler(
            len(metadata), nranks, rank, shuffle=shuffle)
L
lifuchen 已提交
48

L
lifuchen 已提交
49 50
        assert args.batch_size % nranks == 0
        each_bs = args.batch_size // nranks
L
lifuchen 已提交
51
        if is_vocoder:
L
lifuchen 已提交
52 53 54 55 56 57 58
            dataloader = DataCargo(
                dataset,
                sampler=sampler,
                batch_size=each_bs,
                shuffle=shuffle,
                batch_fn=batch_examples_vocoder,
                drop_last=True)
L
lifuchen 已提交
59
        else:
L
lifuchen 已提交
60 61 62 63 64 65 66 67
            dataloader = DataCargo(
                dataset,
                sampler=sampler,
                batch_size=each_bs,
                shuffle=shuffle,
                batch_fn=batch_examples,
                drop_last=True)

L
lifuchen 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
        self.reader = fluid.io.DataLoader.from_generator(
            capacity=32,
            iterable=True,
            use_double_buffer=True,
            return_list=True)
        self.reader.set_batch_generator(dataloader, place)


class LJSpeechMetaData(DatasetMixin):
    def __init__(self, root):
        self.root = Path(root)
        self._wav_dir = self.root.joinpath("wavs")
        csv_path = self.root.joinpath("metadata.csv")
        self._table = pd.read_csv(
            csv_path,
            sep="|",
            header=None,
            quoting=csv.QUOTE_NONE,
            names=["fname", "raw_text", "normalized_text"])

    def get_example(self, i):
        fname, raw_text, normalized_text = self._table.iloc[i]
        fname = str(self._wav_dir.joinpath(fname + ".wav"))
        return fname, raw_text, normalized_text

    def __len__(self):
        return len(self._table)


class LJSpeech(object):
    def __init__(self, config):
        super(LJSpeech, self).__init__()
        self.config = config
        self._ljspeech_processor = audio.AudioProcessor(
L
lifuchen 已提交
102 103 104 105 106 107 108
            sample_rate=config['audio']['sr'],
            num_mels=config['audio']['num_mels'],
            min_level_db=config['audio']['min_level_db'],
            ref_level_db=config['audio']['ref_level_db'],
            n_fft=config['audio']['n_fft'],
            win_length=config['audio']['win_length'],
            hop_length=config['audio']['hop_length'],
L
lifuchen 已提交
109 110
            power=config['audio']['power'],
            preemphasis=config['audio']['preemphasis'],
L
lifuchen 已提交
111 112 113 114 115 116 117 118 119
            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)
L
lifuchen 已提交
120

L
lifuchen 已提交
121 122 123 124 125 126 127 128
    def __call__(self, metadatum):
        """All the code for generating an Example from a metadatum. If you want a 
        different preprocessing pipeline, you can override this method. 
        This method may require several processor, each of which has a lot of options.
        In this case, you'd better pass a composed transform and pass it to the init
        method.
        """
        fname, raw_text, normalized_text = metadatum
L
lifuchen 已提交
129

L
lifuchen 已提交
130 131 132 133
        # load -> trim -> preemphasis -> stft -> magnitude -> mel_scale -> logscale -> normalize
        wav = self._ljspeech_processor.load_wav(str(fname))
        mag = self._ljspeech_processor.spectrogram(wav).astype(np.float32)
        mel = self._ljspeech_processor.melspectrogram(wav).astype(np.float32)
L
lifuchen 已提交
134 135 136 137
        phonemes = np.array(
            g2p.en.text_to_sequence(normalized_text), dtype=np.int64)
        return (mag, mel, phonemes
                )  # maybe we need to implement it as a map in the future
L
lifuchen 已提交
138 139 140 141 142 143 144 145 146 147 148 149


def batch_examples(batch):
    texts = []
    mels = []
    mel_inputs = []
    mel_lens = []
    text_lens = []
    pos_texts = []
    pos_mels = []
    for data in batch:
        _, mel, text = data
L
lifuchen 已提交
150 151 152 153
        mel_inputs.append(
            np.concatenate(
                [np.zeros([mel.shape[0], 1], np.float32), mel[:, :-1]],
                axis=-1))
L
lifuchen 已提交
154 155 156 157 158 159
        mel_lens.append(mel.shape[1])
        text_lens.append(len(text))
        pos_texts.append(np.arange(1, len(text) + 1))
        pos_mels.append(np.arange(1, mel.shape[1] + 1))
        mels.append(mel)
        texts.append(text)
L
lifuchen 已提交
160

L
lifuchen 已提交
161
    # Sort by text_len in descending order
L
lifuchen 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    texts = [
        i
        for i, _ in sorted(
            zip(texts, text_lens), key=lambda x: x[1], reverse=True)
    ]
    mels = [
        i
        for i, _ in sorted(
            zip(mels, text_lens), key=lambda x: x[1], reverse=True)
    ]
    mel_inputs = [
        i
        for i, _ in sorted(
            zip(mel_inputs, text_lens), key=lambda x: x[1], reverse=True)
    ]
    mel_lens = [
        i
        for i, _ in sorted(
            zip(mel_lens, text_lens), key=lambda x: x[1], reverse=True)
    ]
    pos_texts = [
        i
        for i, _ in sorted(
            zip(pos_texts, text_lens), key=lambda x: x[1], reverse=True)
    ]
    pos_mels = [
        i
        for i, _ in sorted(
            zip(pos_mels, text_lens), key=lambda x: x[1], reverse=True)
    ]
L
lifuchen 已提交
192 193 194
    text_lens = sorted(text_lens, reverse=True)

    # Pad sequence with largest len of the batch
L
lifuchen 已提交
195 196 197 198 199 200 201
    texts = TextIDBatcher(pad_id=0)(texts)  #(B, T)
    pos_texts = TextIDBatcher(pad_id=0)(pos_texts)  #(B,T)
    pos_mels = TextIDBatcher(pad_id=0)(pos_mels)  #(B,T)
    mels = np.transpose(
        SpecBatcher(pad_value=0.)(mels), axes=(0, 2, 1))  #(B,T,num_mels)
    mel_inputs = np.transpose(
        SpecBatcher(pad_value=0.)(mel_inputs), axes=(0, 2, 1))  #(B,T,num_mels)
202 203
    enc_slf_mask = get_attn_key_pad_mask(pos_texts, texts).astype(np.float32)
    enc_query_mask = get_non_pad_mask(pos_texts).astype(np.float32)
204 205 206 207
    dec_slf_mask = get_dec_attn_key_pad_mask(pos_mels,
                                             mel_inputs).astype(np.float32)
    enc_dec_mask = get_attn_key_pad_mask(enc_query_mask[:, :, 0],
                                         mel_inputs).astype(np.float32)
208 209 210
    dec_query_slf_mask = get_non_pad_mask(pos_mels).astype(np.float32)
    dec_query_mask = get_non_pad_mask(pos_mels).astype(np.float32)

L
lifuchen 已提交
211
    return (texts, mels, mel_inputs, pos_texts, pos_mels, np.array(text_lens),
212 213
            np.array(mel_lens), enc_slf_mask, enc_query_mask, dec_slf_mask,
            enc_dec_mask, dec_query_slf_mask, dec_query_mask)
L
lifuchen 已提交
214

L
lifuchen 已提交
215 216

def batch_examples_vocoder(batch):
L
lifuchen 已提交
217 218
    mels = []
    mags = []
L
lifuchen 已提交
219 220 221 222 223
    for data in batch:
        mag, mel, _ = data
        mels.append(mel)
        mags.append(mag)

L
lifuchen 已提交
224 225
    mels = np.transpose(SpecBatcher(pad_value=0.)(mels), axes=(0, 2, 1))
    mags = np.transpose(SpecBatcher(pad_value=0.)(mags), axes=(0, 2, 1))
L
lifuchen 已提交
226 227

    return (mels, mags)