-
Notifications
You must be signed in to change notification settings - Fork 9
/
dataset.py
169 lines (130 loc) · 5.9 KB
/
dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
from torch.utils import data
import torch
import glob
import os
from os.path import join, basename, dirname, split, exists
import numpy as np
import json
import csv
import random
from torch.utils.data import DataLoader
from collections import defaultdict
def get_dataloader(config):
train_dataset = Dataset(config, config['train_meta'], config['train_set'])
dev_dataset = Dataset(config, config['dev_meta'], config['dev_set'])
train_loader = DataLoader(
train_dataset,
batch_size = config['batch_size'],
shuffle = True,
collate_fn = train_dataset.collate_fn,
num_workers = config['num_workers']
)
dev_loader = DataLoader(
dev_dataset,
batch_size = config['batch_size'],
shuffle = False,
collate_fn = dev_dataset.collate_fn,
num_workers = config['num_workers']
)
return train_loader, dev_loader
def pad_1D(inputs, length, PAD = 0):
def pad_data(x, length, PAD):
x_padded = np.pad(
x, (0, length - x.shape[0]), mode = 'constant', constant_values = PAD
)
return x_padded
max_len = max(len(x) for x in inputs)
padded = np.stack([pad_data(x, max_len, PAD) for x in inputs])
return padded
def pad_2D(inputs, maxlen = None):
def pad(x, max_len):
PAD = 0
if np.shape(x)[0] > max_len:
raise ValueError(f'shape {x.shape[0]} excceed max_len {max_len}')
s = np.shape(x)[1]
x_padded = np.pad(
x, (0, max_len - x.shape[0]), mode = 'constant', constant_values = PAD
)
return x_padded[:,:s]
if maxlen:
output = np.stack([pad(x,maxlen) for x in inputs])
else:
max_len = max([x.shape[0] for x in inputs])
output = np.stack([pad(x, max_len) for x in inputs])
return output
class Dataset(data.Dataset):
def __init__(self, config, metadata_csv, split):
super().__init__()
self.metadata = []
# read metadata
with open(metadata_csv) as f:
reader = csv.DictReader(f, delimiter = ',')
for row in reader:
# remove utterances that are too long for training.
if config['rm_long_utt']:
_duration = row['duration']
if float(_duration) <= config['max_utt_duration']:
self.metadata.append(row)
f.close()
self.batch_size = config['batch_size']
self.drop_last = config['drop_last']
# feature dirs
self.mel_dir = os.path.join(config['dump_dir'], config['dataset'], split, 'mel')
self.ling_enc = config['ling_enc']
self.ling_rep_dir = os.path.join(config['dump_dir'], config['dataset'], split, self.ling_enc)
self.spk_enc = config['spk_enc']
self.spk_emb_dir = os.path.join(config['dump_dir'], config['dataset'], split, self.spk_enc)
self.pros_enc = config['pros_enc']
self.pros_rep_dir = os.path.join(config['dump_dir'], config['dataset'], split, self.pros_enc)
def __len__(self):
return len(self.metadata)
def __getitem__(self, idx):
row = self.metadata[idx]
ID = row['ID']
spk = row['spk']
# feature path
mel_path = os.path.join(self.mel_dir, spk, ID + '.npy')
ling_rep_path = os.path.join(self.ling_rep_dir, spk, ID+'.npy')
spk_emb_path = os.path.join(self.spk_emb_dir, spk, ID+'.npy')
pros_rep_path = os.path.join(self.pros_rep_dir, spk, ID + '.npy')
assert os.path.exists(mel_path), f"{mel_path}"
assert os.path.exists(ling_rep_path), f'{ling_rep_path}'
assert os.path.exists(spk_emb_path), f'{spk_emb_path}'
assert os.path.exists(pros_rep_path), f'{pros_rep_path}'
# load feature
mel = np.load(mel_path)
mel_duration = mel.shape[0]
ling_rep = np.load(ling_rep_path)
ling_duration = ling_rep.shape[0]
spk_emb = np.load(spk_emb_path)
pros_rep = np.expand_dims(np.load(pros_rep_path), axis = 1)
pros_duration = pros_rep.shape[0]
# match length between mel and ling_rep
if mel_duration > ling_duration:
pad_vec = np.expand_dims(ling_rep[-1,:], axis = 0)
ling_rep = np.concatenate((ling_rep, np.repeat(pad_vec, mel_duration - ling_duration, 0)),0)
elif mel_duration < ling_duration:
ling_rep = ling_rep[:mel_duration,:]
# match length between mel and pros_rep
if mel_duration > pros_duration:
pad_vec = np.expand_dims(pros_rep[-1,:],axis = 0)
pros_rep = np.concatenate((pros_rep, np.repeat(pad_vec, mel_duration - pros_duration, 0)),0)
elif mel_duration < pros_duration:
pros_rep = pros_rep[:mel_duration,:]
return (mel, ling_rep, pros_rep, spk_emb, mel_duration)
def collate_fn(self, data):
batch_size = len(data)
# sort in batch
mel = [ data[id][0] for id in range(batch_size)]
ling_rep = [ data[id][1] for id in range(batch_size)]
pros_rep = [ data[id][2] for id in range(batch_size)]
spk_emb = [ data[id][3] for id in range(batch_size)]
length = [ data[id][4] for id in range(batch_size) ]
max_len = max(length)
padded_mel = torch.FloatTensor(pad_2D(mel))
padded_ling_rep = torch.FloatTensor(pad_2D(ling_rep))
padded_pros_rep = torch.FloatTensor(pad_2D(pros_rep))
spk_emb_tensor = torch.FloatTensor(np.array(spk_emb)).unsqueeze(1)
length = torch.LongTensor(np.array(length))
output = (padded_mel, padded_ling_rep, padded_pros_rep, spk_emb_tensor, length, max_len)
return output