dataset.py 9.26 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#  Copyright 2018 The TensorFlow 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.
# ==============================================================================
"""Generate tf.data.Dataset object for deep speech training/evaluation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

20
21
22
import math
import random
# pylint: disable=g-bad-import-order
23
24
import numpy as np
from six.moves import xrange  # pylint: disable=redefined-builtin
25
import soundfile
26
import tensorflow as tf
27
from absl import logging
28
# pylint: enable=g-bad-import-order
29

30
import data.featurizer as featurizer  # pylint: disable=g-bad-import-order
31
32
33
34
35
36
37


class AudioConfig(object):
  """Configs for spectrogram extraction from audio."""

  def __init__(self,
               sample_rate,
38
39
40
               window_ms,
               stride_ms,
               normalize=False):
41
42
43
44
    """Initialize the AudioConfig class.

    Args:
      sample_rate: an integer denoting the sample rate of the input waveform.
45
46
      window_ms: an integer for the length of a spectrogram frame, in ms.
      stride_ms: an integer for the frame stride, in ms.
47
      normalize: a boolean for whether apply normalization on the audio feature.
48
49
50
    """

    self.sample_rate = sample_rate
51
52
    self.window_ms = window_ms
    self.stride_ms = stride_ms
53
54
55
56
57
58
    self.normalize = normalize


class DatasetConfig(object):
  """Config class for generating the DeepSpeechDataset."""

59
  def __init__(self, audio_config, data_path, vocab_file_path, sortagrad):
60
61
62
63
64
65
    """Initialize the configs for deep speech dataset.

    Args:
      audio_config: AudioConfig object specifying the audio-related configs.
      data_path: a string denoting the full path of a manifest file.
      vocab_file_path: a string specifying the vocabulary file path.
66
67
68
      sortagrad: a boolean, if set to true, audio sequences will be fed by
                increasing length in the first training epoch, which will
                expedite network convergence.
69
70
71
72
73
74

    Raises:
      RuntimeError: file path not exist.
    """

    self.audio_config = audio_config
75
76
    assert tf.io.gfile.exists(data_path)
    assert tf.io.gfile.exists(vocab_file_path)
77
78
    self.data_path = data_path
    self.vocab_file_path = vocab_file_path
79
    self.sortagrad = sortagrad
80
81


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def _normalize_audio_feature(audio_feature):
  """Perform mean and variance normalization on the spectrogram feature.

  Args:
    audio_feature: a numpy array for the spectrogram feature.

  Returns:
    a numpy array of the normalized spectrogram.
  """
  mean = np.mean(audio_feature, axis=0)
  var = np.var(audio_feature, axis=0)
  normalized = (audio_feature - mean) / (np.sqrt(var) + 1e-6)

  return normalized


98
99
100
def _preprocess_audio(audio_file_path, audio_featurizer, normalize):
  """Load the audio file and compute spectrogram feature."""
  data, _ = soundfile.read(audio_file_path)
101
  feature = featurizer.compute_spectrogram_feature(
102
103
104
      data, audio_featurizer.sample_rate, audio_featurizer.stride_ms,
      audio_featurizer.window_ms)
  # Feature normalization
105
106
107
  if normalize:
    feature = _normalize_audio_feature(feature)

108
109
110
  # Adding Channel dimension for conv2D input.
  feature = np.expand_dims(feature, axis=2)
  return feature
111
112


113
114
def _preprocess_data(file_path):
  """Generate a list of tuples (wav_filename, wav_filesize, transcript).
115
116
117
118
119
120
121
122

  Each dataset file contains three columns: "wav_filename", "wav_filesize",
  and "transcript". This function parses the csv file and stores each example
  by the increasing order of audio length (indicated by wav_filesize).
  AS the waveforms are ordered in increasing length, audio samples in a
  mini-batch have similar length.

  Args:
123
    file_path: a string specifying the csv file path for a dataset.
124
125

  Returns:
126
127
    A list of tuples (wav_filename, wav_filesize, transcript) sorted by
    file_size.
128
  """
129
  logging.info("Loading data set {}".format(file_path))
130
  with tf.io.gfile.GFile(file_path, "r") as f:
131
    lines = f.read().splitlines()
132
  # Skip the csv header in lines[0].
133
  lines = lines[1:]
134
135
136
  # The metadata file is tab separated.
  lines = [line.split("\t", 2) for line in lines]
  # Sort input data by the length of audio sequence.
137
138
  lines.sort(key=lambda item: int(item[1]))

139
  return [tuple(line) for line in lines]
140
141


142
143
144
145
class DeepSpeechDataset(object):
  """Dataset class for training/evaluation of DeepSpeech model."""

  def __init__(self, dataset_config):
146
    """Initialize the DeepSpeechDataset class.
147
148
149
150
151
152

    Args:
      dataset_config: DatasetConfig object.
    """
    self.config = dataset_config
    # Instantiate audio feature extractor.
153
    self.audio_featurizer = featurizer.AudioFeaturizer(
154
        sample_rate=self.config.audio_config.sample_rate,
155
156
        window_ms=self.config.audio_config.window_ms,
        stride_ms=self.config.audio_config.stride_ms)
157
    # Instantiate text feature extractor.
158
    self.text_featurizer = featurizer.TextFeaturizer(
159
160
161
        vocab_file=self.config.vocab_file_path)

    self.speech_labels = self.text_featurizer.speech_labels
162
163
164
165
    self.entries = _preprocess_data(self.config.data_path)
    # The generated spectrogram will have 161 feature bins.
    self.num_feature_bins = 161

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
192
193
194
195
196
197
198
199
200
def batch_wise_dataset_shuffle(entries, epoch_index, sortagrad, batch_size):
  """Batch-wise shuffling of the data entries.

  Each data entry is in the format of (audio_file, file_size, transcript).
  If epoch_index is 0 and sortagrad is true, we don't perform shuffling and
  return entries in sorted file_size order. Otherwise, do batch_wise shuffling.

  Args:
    entries: a list of data entries.
    epoch_index: an integer of epoch index
    sortagrad: a boolean to control whether sorting the audio in the first
      training epoch.
    batch_size: an integer for the batch size.

  Returns:
    The shuffled data entries.
  """
  shuffled_entries = []
  if epoch_index == 0 and sortagrad:
    # No need to shuffle.
    shuffled_entries = entries
  else:
    # Shuffle entries batch-wise.
    max_buckets = int(math.floor(len(entries) / batch_size))
    total_buckets = [i for i in xrange(max_buckets)]
    random.shuffle(total_buckets)
    shuffled_entries = []
    for i in total_buckets:
      shuffled_entries.extend(entries[i * batch_size : (i + 1) * batch_size])
    # If the last batch doesn't contain enough batch_size examples,
    # just append it to the shuffled_entries.
    shuffled_entries.extend(entries[max_buckets * batch_size:])

  return shuffled_entries
201
202
203
204
205
206
207
208
209
210
211
212
213


def input_fn(batch_size, deep_speech_dataset, repeat=1):
  """Input function for model training and evaluation.

  Args:
    batch_size: an integer denoting the size of a batch.
    deep_speech_dataset: DeepSpeechDataset object.
    repeat: an integer for how many times to repeat the dataset.

  Returns:
    a tf.data.Dataset object for model to consume.
  """
214
215
  # Dataset properties
  data_entries = deep_speech_dataset.entries
216
  num_feature_bins = deep_speech_dataset.num_feature_bins
217
218
219
  audio_featurizer = deep_speech_dataset.audio_featurizer
  feature_normalize = deep_speech_dataset.config.audio_config.normalize
  text_featurizer = deep_speech_dataset.text_featurizer
220
221

  def _gen_data():
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
    """Dataset generator function."""
    for audio_file, _, transcript in data_entries:
      features = _preprocess_audio(
          audio_file, audio_featurizer, feature_normalize)
      labels = featurizer.compute_label_feature(
          transcript, text_featurizer.token_to_index)
      input_length = [features.shape[0]]
      label_length = [len(labels)]
      # Yield a tuple of (features, labels) where features is a dict containing
      # all info about the actual data features.
      yield (
          {
              "features": features,
              "input_length": input_length,
              "label_length": label_length
          },
          labels)
239
240
241

  dataset = tf.data.Dataset.from_generator(
      _gen_data,
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
      output_types=(
          {
              "features": tf.float32,
              "input_length": tf.int32,
              "label_length": tf.int32
          },
          tf.int32),
      output_shapes=(
          {
              "features": tf.TensorShape([None, num_feature_bins, 1]),
              "input_length": tf.TensorShape([1]),
              "label_length": tf.TensorShape([1])
          },
          tf.TensorShape([None]))
  )
257
258
259

  # Repeat and batch the dataset
  dataset = dataset.repeat(repeat)
260

261
262
263
  # Padding the features to its max length dimensions.
  dataset = dataset.padded_batch(
      batch_size=batch_size,
264
265
266
267
268
269
270
271
      padded_shapes=(
          {
              "features": tf.TensorShape([None, num_feature_bins, 1]),
              "input_length": tf.TensorShape([1]),
              "label_length": tf.TensorShape([1])
          },
          tf.TensorShape([None]))
  )
272
273

  # Prefetch to improve speed of input pipeline.
274
  dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
275
  return dataset