|
| 1 | +# Copyright 2017-present, Facebook, Inc. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +from functools import partial |
| 8 | +import numpy as np |
| 9 | +import os |
| 10 | + |
| 11 | +import torch |
| 12 | +import torch.utils.data as data |
| 13 | + |
| 14 | + |
| 15 | +# Taken from |
| 16 | +# https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/Dataset.py |
| 17 | +def batchify(data): |
| 18 | + out, lengths = None, None |
| 19 | + |
| 20 | + lengths = [x.size(0) for x in data] |
| 21 | + max_length = max(lengths) |
| 22 | + |
| 23 | + if data[0].dim() == 1: |
| 24 | + out = data[0].new(len(data), max_length).fill_(0) |
| 25 | + for i in range(len(data)): |
| 26 | + data_length = data[i].size(0) |
| 27 | + out[i].narrow(0, 0, data_length).copy_(data[i]) |
| 28 | + else: |
| 29 | + feat_size = data[0].size(1) |
| 30 | + out = data[0].new(len(data), max_length, feat_size).fill_(0) |
| 31 | + for i in range(len(data)): |
| 32 | + data_length = data[i].size(0) |
| 33 | + out[i].narrow(0, 0, data_length).copy_(data[i]) |
| 34 | + |
| 35 | + return out, lengths |
| 36 | + |
| 37 | + |
| 38 | +def collate_by_input_length(batch, max_seq_len): |
| 39 | + "Puts each data field into a tensor with outer dimension batch size" |
| 40 | + if torch.is_tensor(batch[0]): |
| 41 | + return batchify(batch) |
| 42 | + elif isinstance(batch[0], int): |
| 43 | + return torch.LongTensor(batch) |
| 44 | + else: |
| 45 | + new_batch = [x for x in batch if x[1].size(0) < max_seq_len] |
| 46 | + if len(batch) == 0: |
| 47 | + return (None, None), (None, None), None |
| 48 | + |
| 49 | + batch = new_batch |
| 50 | + transposed = zip(*batch) |
| 51 | + (srcBatch, srcLengths), (tgtBatch, tgtLengths), speakers = \ |
| 52 | + [collate_by_input_length(samples, max_seq_len) |
| 53 | + for samples in transposed] |
| 54 | + |
| 55 | + # within batch sorting by decreasing length for variable length rnns |
| 56 | + batch = zip(srcBatch, tgtBatch, tgtLengths, speakers) |
| 57 | + batch, srcLengths = zip(*sorted(zip(batch, srcLengths), |
| 58 | + key=lambda x: -x[1])) |
| 59 | + srcBatch, tgtBatch, tgtLengths, speakers = zip(*batch) |
| 60 | + |
| 61 | + srcBatch = torch.stack(srcBatch, 0).transpose(0, 1).contiguous() |
| 62 | + tgtBatch = torch.stack(tgtBatch, 0).transpose(0, 1).contiguous() |
| 63 | + srcLengths = torch.LongTensor(srcLengths) |
| 64 | + tgtLengths = torch.LongTensor(tgtLengths) |
| 65 | + speakers = torch.LongTensor(speakers).view(-1, 1) |
| 66 | + |
| 67 | + return (srcBatch, srcLengths), (tgtBatch, tgtLengths), speakers |
| 68 | + |
| 69 | + raise TypeError(("batch must contain tensors, numbers, dicts or \ |
| 70 | + lists; found {}".format(type(batch[0])))) |
| 71 | + |
| 72 | + |
| 73 | +class NpzFolder(data.Dataset): |
| 74 | + NPZ_EXTENSION = 'npz' |
| 75 | + |
| 76 | + def __init__(self, root): |
| 77 | + self.root = root |
| 78 | + self.npzs = self.make_dataset(self.root) |
| 79 | + |
| 80 | + if len(self.npzs) == 0: |
| 81 | + raise(RuntimeError("Found 0 npz in subfolders of: " + root + "\n" |
| 82 | + "Supported image extensions are: " + |
| 83 | + self.NPZ_EXTENSION)) |
| 84 | + |
| 85 | + self.speakers = [] |
| 86 | + for fname in self.npzs: |
| 87 | + self.speakers += [os.path.basename(fname).split('_')[0]] |
| 88 | + self.speakers = list(set(self.speakers)) |
| 89 | + self.speakers.sort() |
| 90 | + self.speakers = {v: i for i, v in enumerate(self.speakers)} |
| 91 | + |
| 92 | + code2phone = np.load(self.npzs[0])['code2phone'] |
| 93 | + self.dict = {v: k for k, v in enumerate(code2phone)} |
| 94 | + |
| 95 | + def __getitem__(self, index): |
| 96 | + path = self.npzs[index] |
| 97 | + txt, feat, spkr = self.loader(path) |
| 98 | + |
| 99 | + return txt, feat, self.speakers[spkr] |
| 100 | + |
| 101 | + def __len__(self): |
| 102 | + return len(self.npzs) |
| 103 | + |
| 104 | + def make_dataset(self, dir): |
| 105 | + images = [] |
| 106 | + |
| 107 | + for root, _, fnames in sorted(os.walk(dir)): |
| 108 | + for fname in fnames: |
| 109 | + if self.NPZ_EXTENSION in fname: |
| 110 | + path = os.path.join(root, fname) |
| 111 | + images.append(path) |
| 112 | + |
| 113 | + return images |
| 114 | + |
| 115 | + def loader(self, path): |
| 116 | + feat = np.load(path) |
| 117 | + |
| 118 | + txt = feat['phonemes'].astype('int64') |
| 119 | + txt = torch.from_numpy(txt) |
| 120 | + |
| 121 | + audio = feat['audio_features'] |
| 122 | + audio = torch.from_numpy(audio) |
| 123 | + |
| 124 | + spkr = os.path.basename(path).split('_')[0] |
| 125 | + |
| 126 | + return txt, audio, spkr |
| 127 | + |
| 128 | + |
| 129 | +class NpzLoader(data.DataLoader): |
| 130 | + def __init__(self, *args, **kwargs): |
| 131 | + kwargs['collate_fn'] = partial(collate_by_input_length, |
| 132 | + max_seq_len=kwargs['max_seq_len']) |
| 133 | + del kwargs['max_seq_len'] |
| 134 | + |
| 135 | + data.DataLoader.__init__(self, *args, **kwargs) |
| 136 | + |
| 137 | + |
| 138 | +class TBPTTIter(object): |
| 139 | + """ |
| 140 | + Iterator for truncated batch propagation through time(tbptt) training. |
| 141 | + Target sequence is segmented while input sequence remains the same. |
| 142 | + """ |
| 143 | + def __init__(self, src, trgt, spkr, seq_len): |
| 144 | + self.seq_len = seq_len |
| 145 | + self.start = True |
| 146 | + |
| 147 | + self.speakers = spkr |
| 148 | + self.srcBatch = src[0] |
| 149 | + self.srcLenths = src[1] |
| 150 | + |
| 151 | + # split batch |
| 152 | + self.tgtBatch = list(torch.split(trgt[0], self.seq_len, 0)) |
| 153 | + self.tgtBatch.reverse() |
| 154 | + self.len = len(self.tgtBatch) |
| 155 | + |
| 156 | + # split length list |
| 157 | + batch_seq_len = len(self.tgtBatch) |
| 158 | + self.tgtLenths = [self.split_length(l, batch_seq_len) for l in trgt[1]] |
| 159 | + self.tgtLenths = torch.stack(self.tgtLenths) |
| 160 | + self.tgtLenths = list(torch.split(self.tgtLenths, 1, 1)) |
| 161 | + self.tgtLenths = [x.squeeze() for x in self.tgtLenths] |
| 162 | + self.tgtLenths.reverse() |
| 163 | + |
| 164 | + assert len(self.tgtLenths) == len(self.tgtBatch) |
| 165 | + |
| 166 | + def split_length(self, seq_size, batch_seq_len): |
| 167 | + seq = [self.seq_len] * (seq_size / self.seq_len) |
| 168 | + if seq_size % self.seq_len != 0: |
| 169 | + seq += [seq_size % self.seq_len] |
| 170 | + seq += [0] * (batch_seq_len - len(seq)) |
| 171 | + return torch.LongTensor(seq) |
| 172 | + |
| 173 | + def __next__(self): |
| 174 | + if len(self.tgtBatch) == 0: |
| 175 | + raise StopIteration() |
| 176 | + |
| 177 | + if self.len > len(self.tgtBatch): |
| 178 | + self.start = False |
| 179 | + |
| 180 | + return (self.srcBatch, self.srcLenths), \ |
| 181 | + (self.tgtBatch.pop(), self.tgtLenths.pop()), \ |
| 182 | + self.speakers, self.start |
| 183 | + |
| 184 | + next = __next__ |
| 185 | + |
| 186 | + def __iter__(self): |
| 187 | + return self |
| 188 | + |
| 189 | + def __len__(self): |
| 190 | + return self.len |
0 commit comments