-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_gen.py
166 lines (135 loc) · 6.04 KB
/
data_gen.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
# A greatly stripped down version of the data generator from
# https://github.com/robmsmt/KerasDeepSpeech/blob/master/generator.py
import math
import matplotlib.pyplot as plt
from scipy.io import wavfile
from datagen_utils.spectrogram_func import *
from sklearn.utils import shuffle
class WavAudio(object):
def __init__(self, audio_path, window_length=0.02, skip_window=0.01,
fft_length=None, freq_max=8000):
fs, audio = wavfile.read(audio_path)
audio = audio.astype(np.float32)
self.audio = audio
self.fs = fs
self.fft_length = fft_length or 2 ** math.ceil(math.log2(self.fs * window_length))
(p_sgram, p_maxtime, p_maxfreq) = sgram(audio, int(skip_window * fs),
int(window_length * fs), self.fft_length,
fs, freq_max)
self.specgram = np.asarray(p_sgram)
self.maxtime = p_maxtime
self.maxfreq = p_maxfreq
def plot(self):
return plt.imshow(np.transpose(np.array(self.specgram)),
origin='lower',
extent=(0, self.maxtime, 0, self.maxfreq),
aspect='auto')
class BatchGen(object):
def __init__(self, manifest, batch_size=16, win_len=0.02, skip_len=0.01,
shuffling=True):
self.cur_index = 0
self.batch_size = batch_size
self.win_len = win_len
self.skip_len = skip_len
self.manifest = manifest
self.shuffling = shuffling
audiopath = []
for i in range(len(self.manifest)):
audiopath.append(self.manifest[i]['audio_filepath'])
self.audiopaths = audiopath
duration = []
for i in range(len(self.manifest)):
duration.append(self.manifest[i]['duration'])
self.durations = duration
spec_length = []
for i in range(len(self.durations)):
spec_length.append(int((self.durations[i] * 100 - win_len) / (skip_len * 100)))
self.spec_lengths = spec_length
transcript = []
for i in range(len(self.manifest)):
transcript.append(manifest[i]['transcript'])
self.transcripts = transcript
transcript_len = []
for i in range(len(self.manifest)):
transcript_len.append(len(self.manifest[i]['transcript']))
self.max_transcript_len = max(transcript_len)
del audiopath
del duration
del spec_length
del transcript
del transcript_len
def get_batch(self, idx):
batch_x = self.audiopaths[idx * self.batch_size:(idx + 1) * self.batch_size]
batch_y_trans = self.transcripts[idx * self.batch_size:(idx + 1) * self.batch_size]
try:
assert (len(batch_x) == self.batch_size)
assert (len(batch_y_trans) == self.batch_size)
except Exception as e:
print(e)
print(batch_x)
print(batch_y_trans)
batch_input = self.input_gen(batch_x, batch_y_trans)
return batch_input
def next_batch(self):
while 1:
assert (self.batch_size <= len(self.audiopaths))
if (self.cur_index + 1) * self.batch_size >= len(self.audiopaths) - self.batch_size:
self.cur_index = 0
if(self.shuffling==True):
print("SHUFFLING as reached end of data")
self.genshuffle()
try:
ret = self.get_batch(self.cur_index)
except:
print("data error - this shouldn't happen - try next batch")
self.cur_index += 1
ret = self.get_batch(self.cur_index)
self.cur_index += 1
yield ret
def genshuffle(self):
self.audiopaths, self.transcripts = shuffle(self.audiopaths, self.transcripts)
def input_gen(self, audio_paths, transcripts, normalize=True):
#print("audio length: {}. transcription length: {}".format(len(audio_paths), len(transcripts)))
assert (len(audio_paths) == len(transcripts))
spec = []
sentence_lengths = []
spec_lengths = []
for i in range(len(audio_paths)):
audio = WavAudio(audio_paths[i][0], window_length=self.win_len,
skip_window=self.skip_len)
spec.append(audio.specgram)
sentence_lengths.append(len(transcripts[i]))
spec_lengths.append(len(spec[i]))
spec = np.asarray(spec)
input_data = np.zeros([spec.shape[0], max(self.spec_lengths), spec[0].shape[1]])
targets = np.ones([len(transcripts), self.max_transcript_len]) * 28 # 28 for coding blank
label_length = np.zeros([len(transcripts), 1])
input_length = np.zeros([spec.shape[0], 1])
for i in range(len(transcripts)):
input_spec = spec[i]
target = np.asarray(transcripts[i])
input_data[i, :input_spec.shape[0], :] = input_spec[i]
targets[i, :len(target)] = target
label_length[i] = int(len(target))
input_length[i] = int(spec[i].shape[0])
if normalize:
input_data_norm = self.norm(input_data)
inputs = {
'input': input_data_norm.astype('float32'),
'the_labels': targets.astype('int16'),
'input_length': input_length.astype('int16'),
'label_length': label_length.astype('int16')
}
outputs = {'ctc': np.zeros([self.batch_size])}
return (inputs, outputs)
else:
inputs = {
'input': input_data.astype('float32'),
'the_labels': targets.astype('int16'),
'input_length': input_length.astype('int16'),
'label_length': label_length.astype('int16')
}
outputs = {'ctc': np.zeros([self.batch_size])}
return (inputs,outputs)
def norm(self, data_array, eps=1e-14):
return np.asarray((data_array - data_array.mean()) / (data_array.std() + eps))