-
Notifications
You must be signed in to change notification settings - Fork 43
/
loader.py
192 lines (150 loc) · 5.63 KB
/
loader.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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""
Copyright 2019-present NAVER Corp.
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.
"""
#-*- coding: utf-8 -*-
import os
import sys
import math
import wavio
import time
import torch
import random
import threading
import logging
from torch.utils.data import Dataset, DataLoader
logger = logging.getLogger('root')
FORMAT = "[%(asctime)s %(filename)s:%(lineno)s - %(funcName)s()] %(message)s"
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=FORMAT)
logger.setLevel(logging.INFO)
PAD = 0
N_FFT = 512
SAMPLE_RATE = 16000
target_dict = dict()
def load_targets(path):
with open(path, 'r') as f:
for no, line in enumerate(f):
key, target = line.strip().split(',')
target_dict[key] = target
def get_spectrogram_feature(filepath):
(rate, width, sig) = wavio.readwav(filepath)
sig = sig.ravel()
stft = torch.stft(torch.FloatTensor(sig),
N_FFT,
hop_length=int(0.01*SAMPLE_RATE),
win_length=int(0.030*SAMPLE_RATE),
window=torch.hamming_window(int(0.030*SAMPLE_RATE)),
center=False,
normalized=False,
onesided=True)
stft = (stft[:,:,0].pow(2) + stft[:,:,1].pow(2)).pow(0.5);
amag = stft.numpy();
feat = torch.FloatTensor(amag)
feat = torch.FloatTensor(feat).transpose(0, 1)
return feat
def get_script(filepath, bos_id, eos_id):
key = filepath.split('/')[-1].split('.')[0]
script = target_dict[key]
tokens = script.split(' ')
result = list()
result.append(bos_id)
for i in range(len(tokens)):
if len(tokens[i]) > 0:
result.append(int(tokens[i]))
result.append(eos_id)
return result
class BaseDataset(Dataset):
def __init__(self, wav_paths, script_paths, bos_id=1307, eos_id=1308):
self.wav_paths = wav_paths
self.script_paths = script_paths
self.bos_id, self.eos_id = bos_id, eos_id
def __len__(self):
return len(self.wav_paths)
def count(self):
return len(self.wav_paths)
def getitem(self, idx):
feat = get_spectrogram_feature(self.wav_paths[idx])
script = get_script(self.script_paths[idx], self.bos_id, self.eos_id)
return feat, script
def _collate_fn(batch):
def seq_length_(p):
return len(p[0])
def target_length_(p):
return len(p[1])
seq_lengths = [len(s[0]) for s in batch]
target_lengths = [len(s[1]) for s in batch]
max_seq_sample = max(batch, key=seq_length_)[0]
max_target_sample = max(batch, key=target_length_)[1]
max_seq_size = max_seq_sample.size(0)
max_target_size = len(max_target_sample)
feat_size = max_seq_sample.size(1)
batch_size = len(batch)
seqs = torch.zeros(batch_size, max_seq_size, feat_size)
targets = torch.zeros(batch_size, max_target_size).to(torch.long)
targets.fill_(PAD)
for x in range(batch_size):
sample = batch[x]
tensor = sample[0]
target = sample[1]
seq_length = tensor.size(0)
seqs[x].narrow(0, 0, seq_length).copy_(tensor)
targets[x].narrow(0, 0, len(target)).copy_(torch.LongTensor(target))
return seqs, targets, seq_lengths, target_lengths
class BaseDataLoader(threading.Thread):
def __init__(self, dataset, queue, batch_size, thread_id):
threading.Thread.__init__(self)
self.collate_fn = _collate_fn
self.dataset = dataset
self.queue = queue
self.index = 0
self.batch_size = batch_size
self.dataset_count = dataset.count()
self.thread_id = thread_id
def count(self):
return math.ceil(self.dataset_count / self.batch_size)
def create_empty_batch(self):
seqs = torch.zeros(0, 0, 0)
targets = torch.zeros(0, 0).to(torch.long)
seq_lengths = list()
target_lengths = list()
return seqs, targets, seq_lengths, target_lengths
def run(self):
logger.debug('loader %d start' % (self.thread_id))
while True:
items = list()
for i in range(self.batch_size):
if self.index >= self.dataset_count:
break
items.append(self.dataset.getitem(self.index))
self.index += 1
if len(items) == 0:
batch = self.create_empty_batch()
self.queue.put(batch)
break
random.shuffle(items)
batch = self.collate_fn(items)
self.queue.put(batch)
logger.debug('loader %d stop' % (self.thread_id))
class MultiLoader():
def __init__(self, dataset_list, queue, batch_size, worker_size):
self.dataset_list = dataset_list
self.queue = queue
self.batch_size = batch_size
self.worker_size = worker_size
self.loader = list()
for i in range(self.worker_size):
self.loader.append(BaseDataLoader(self.dataset_list[i], self.queue, self.batch_size, i))
def start(self):
for i in range(self.worker_size):
self.loader[i].start()
def join(self):
for i in range(self.worker_size):
self.loader[i].join()