data.py 13.9 KB
Newer Older
1 2
"""Contains data generator for orgnaizing various audio data preprocessing
pipeline and offering data reader interface of PaddlePaddle requirements.
3 4 5 6 7 8
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import random
9
import tarfile
10
import multiprocessing
11
import numpy as np
12
import paddle.v2 as paddle
13
from threading import local
14 15 16
from data_utils import utils
from data_utils.augmentor.augmentation import AugmentationPipeline
from data_utils.featurizer.speech_featurizer import SpeechFeaturizer
17
from data_utils.speech import SpeechSegment
18 19 20 21 22 23
from data_utils.normalizer import FeatureNormalizer


class DataGenerator(object):
    """
    DataGenerator provides basic audio data preprocessing pipeline, and offers
24
    data reader interfaces of PaddlePaddle requirements.
25

26 27
    :param vocab_filepath: Vocabulary filepath for indexing tokenized
                           transcripts.
28
    :type vocab_filepath: basestring
29 30 31 32 33 34 35
    :param mean_std_filepath: File containing the pre-computed mean and stddev.
    :type mean_std_filepath: None|basestring
    :param augmentation_config: Augmentation configuration in json string.
                                Details see AugmentationPipeline.__doc__.
    :type augmentation_config: str
    :param max_duration: Audio with duration (in seconds) greater than
                         this will be discarded.
36
    :type max_duration: float
37 38
    :param min_duration: Audio with duration (in seconds) smaller than
                         this will be discarded.
39 40 41
    :type min_duration: float
    :param stride_ms: Striding size (in milliseconds) for generating frames.
    :type stride_ms: float
42
    :param window_ms: Window size (in milliseconds) for generating frames.
43
    :type window_ms: float
44 45 46 47 48 49
    :param max_freq: Used when specgram_type is 'linear', only FFT bins
                     corresponding to frequencies between [0, max_freq] are
                     returned.
    :types max_freq: None|float
    :param specgram_type: Specgram feature type. Options: 'linear'.
    :type specgram_type: str
50 51 52
    :param use_dB_normalization: Whether to normalize the audio to -20 dB
                                before extracting the features.
    :type use_dB_normalization: bool
53 54
    :param num_threads: Number of CPU threads for processing data.
    :type num_threads: int
55 56
    :param random_seed: Random seed.
    :type random_seed: int
57 58 59 60 61 62 63 64 65 66 67
    """

    def __init__(self,
                 vocab_filepath,
                 mean_std_filepath,
                 augmentation_config='{}',
                 max_duration=float('inf'),
                 min_duration=0.0,
                 stride_ms=10.0,
                 window_ms=20.0,
                 max_freq=None,
68
                 specgram_type='linear',
69
                 use_dB_normalization=True,
70
                 num_threads=multiprocessing.cpu_count() // 2,
71 72 73 74 75 76 77 78
                 random_seed=0):
        self._max_duration = max_duration
        self._min_duration = min_duration
        self._normalizer = FeatureNormalizer(mean_std_filepath)
        self._augmentation_pipeline = AugmentationPipeline(
            augmentation_config=augmentation_config, random_seed=random_seed)
        self._speech_featurizer = SpeechFeaturizer(
            vocab_filepath=vocab_filepath,
79
            specgram_type=specgram_type,
80 81
            stride_ms=stride_ms,
            window_ms=window_ms,
82 83
            max_freq=max_freq,
            use_dB_normalization=use_dB_normalization)
84
        self._num_threads = num_threads
85 86
        self._rng = random.Random(random_seed)
        self._epoch = 0
87
        # for caching tar files info
88 89 90
        self._local_data = local()
        self._local_data.tar2info = {}
        self._local_data.tar2object = {}
W
wanghaoshuang 已提交
91

92 93 94 95
    def process_utterance(self, filename, transcript):
        """Load, augment, featurize and normalize for speech data.

        :param filename: Audio filepath
96
        :type filename: basestring | file
97 98 99
        :param transcript: Transcription text.
        :type transcript: basestring
        :return: Tuple of audio feature tensor and list of token ids for
100
                 transcription.
101 102 103 104 105 106 107 108
        :rtype: tuple of (2darray, list)
        """
        speech_segment = SpeechSegment.from_file(filename, transcript)
        self._augmentation_pipeline.transform_audio(speech_segment)
        specgram, text_ids = self._speech_featurizer.featurize(speech_segment)
        specgram = self._normalizer.apply(specgram)
        return specgram, text_ids

109 110 111
    def batch_reader_creator(self,
                             manifest_path,
                             batch_size,
112
                             min_batch_size=1,
113 114 115
                             padding_to=-1,
                             flatten=False,
                             sortagrad=False,
116
                             shuffle_method="batch_shuffle"):
117
        """
118 119
        Batch data reader creator for audio data. Return a callable generator
        function to produce batches of data.
W
wanghaoshuang 已提交
120

121 122
        Audio features within one batch will be padded with zeros to have the
        same shape, or a user-defined shape.
123

124
        :param manifest_path: Filepath of manifest for audio files.
125
        :type manifest_path: basestring
126
        :param batch_size: Number of instances in a batch.
127
        :type batch_size: int
128 129 130 131 132 133
        :param min_batch_size: Any batch with batch size smaller than this will
                               be discarded. (To be deprecated in the future.)
        :type min_batch_size: int
        :param padding_to:  If set -1, the maximun shape in the batch
                            will be used as the target shape for padding.
                            Otherwise, `padding_to` will be the target shape.
134
        :type padding_to: int
135
        :param flatten: If set True, audio features will be flatten to 1darray.
136
        :type flatten: bool
137 138
        :param sortagrad: If set True, sort the instances by audio duration
                          in the first epoch for speed up training.
139
        :type sortagrad: bool
140 141 142 143 144 145 146 147 148 149 150 151 152 153
        :param shuffle_method: Shuffle method. Options:
                                '' or None: no shuffle.
                                'instance_shuffle': instance-wise shuffle.
                                'batch_shuffle': similarly-sized instances are
                                                 put into batches, and then
                                                 batch-wise shuffle the batches.
                                                 For more details, please see
                                                 ``_batch_shuffle.__doc__``.
                                'batch_shuffle_clipped': 'batch_shuffle' with
                                                         head shift and tail
                                                         clipping. For more
                                                         details, please see
                                                         ``_batch_shuffle``.
                              If sortagrad is True, shuffle is disabled
154
                              for the first epoch.
155
        :type shuffle_method: None|str
156 157 158 159 160 161 162 163 164 165 166 167 168
        :return: Batch reader function, producing batches of data when called.
        :rtype: callable
        """

        def batch_reader():
            # read manifest
            manifest = utils.read_manifest(
                manifest_path=manifest_path,
                max_duration=self._max_duration,
                min_duration=self._min_duration)
            # sort (by duration) or batch-wise shuffle the manifest
            if self._epoch == 0 and sortagrad:
                manifest.sort(key=lambda x: x["duration"])
169 170 171 172 173 174 175 176 177
            else:
                if shuffle_method == "batch_shuffle":
                    manifest = self._batch_shuffle(
                        manifest, batch_size, clipped=False)
                elif shuffle_method == "batch_shuffle_clipped":
                    manifest = self._batch_shuffle(
                        manifest, batch_size, clipped=True)
                elif shuffle_method == "instance_shuffle":
                    self._rng.shuffle(manifest)
178
                elif shuffle_method == None:
179 180 181 182
                    pass
                else:
                    raise ValueError("Unknown shuffle method %s." %
                                     shuffle_method)
183 184 185 186 187 188 189 190
            # prepare batches
            instance_reader = self._instance_reader_creator(manifest)
            batch = []
            for instance in instance_reader():
                batch.append(instance)
                if len(batch) == batch_size:
                    yield self._padding_batch(batch, padding_to, flatten)
                    batch = []
191
            if len(batch) >= min_batch_size:
192 193 194 195 196 197 198
                yield self._padding_batch(batch, padding_to, flatten)
            self._epoch += 1

        return batch_reader

    @property
    def feeding(self):
199
        """Returns data reader's feeding dict.
W
wanghaoshuang 已提交
200

201
        :return: Data feeding dict.
W
wanghaoshuang 已提交
202
        :rtype: dict
203
        """
204 205 206 207
        return {"audio_spectrogram": 0, "transcript_text": 1}

    @property
    def vocab_size(self):
208 209 210 211 212
        """Return the vocabulary size.

        :return: Vocabulary size.
        :rtype: int
        """
213 214 215 216
        return self._speech_featurizer.vocab_size

    @property
    def vocab_list(self):
217 218 219 220 221
        """Return the vocabulary in list.

        :return: Vocabulary in list.
        :rtype: list
        """
222 223
        return self._speech_featurizer.vocab_list

W
wanghaoshuang 已提交
224
    def _parse_tar(self, file):
225 226
        """Parse a tar file to get a tarfile object
        and a map containing tarinfoes
W
wanghaoshuang 已提交
227 228 229 230 231 232 233
        """
        result = {}
        f = tarfile.open(file)
        for tarinfo in f.getmembers():
            result[tarinfo.name] = tarinfo
        return f, result

234 235
    def _get_file_object(self, file):
        """Get file object by file path.
W
wanghaoshuang 已提交
236

237
        If file startwith tar, it will return a tar file object
W
wanghaoshuang 已提交
238
        and cached tar file info for next reading request.
239
        It will return file directly, if the type of file is not str.
W
wanghaoshuang 已提交
240
        """
241 242
        if file.startswith('tar:'):
            tarpath, filename = file.split(':', 1)[1].split('#', 1)
243 244 245 246 247
            if 'tar2info' not in self._local_data.__dict__:
                self._local_data.tar2info = {}
            if 'tar2object' not in self._local_data.__dict__:
                self._local_data.tar2object = {}
            if tarpath not in self._local_data.tar2info:
W
wanghaoshuang 已提交
248
                object, infoes = self._parse_tar(tarpath)
249 250 251 252
                self._local_data.tar2info[tarpath] = infoes
                self._local_data.tar2object[tarpath] = object
            return self._local_data.tar2object[tarpath].extractfile(
                self._local_data.tar2info[tarpath][filename])
W
wanghaoshuang 已提交
253
        else:
W
wanghaoshuang 已提交
254
            return open(file, 'r')
255 256 257

    def _instance_reader_creator(self, manifest):
        """
258 259
        Instance reader creator. Create a callable function to produce
        instances of data.
260

261 262
        Instance: a tuple of ndarray of audio spectrogram and a list of
        token indices for transcript.
263 264 265 266
        """

        def reader():
            for instance in manifest:
267
                yield instance
268

269
        def mapper(instance):
270 271 272
            return self.process_utterance(
                self._get_file_object(instance["audio_filepath"]),
                instance["text"])
273 274 275

        return paddle.reader.xmap_readers(
            mapper, reader, self._num_threads, 1024, order=True)
276 277 278

    def _padding_batch(self, batch, padding_to=-1, flatten=False):
        """
279 280
        Padding audio features with zeros to make them have the same shape (or
        a user-defined shape) within one bach.
281

282 283 284
        If ``padding_to`` is -1, the maximun shape in the batch will be used
        as the target shape for padding. Otherwise, `padding_to` will be the
        target shape (only refers to the second axis).
285

286
        If `flatten` is True, features will be flatten to 1darray.
287 288 289 290 291 292
        """
        new_batch = []
        # get target shape
        max_length = max([audio.shape[1] for audio, text in batch])
        if padding_to != -1:
            if padding_to < max_length:
293 294
                raise ValueError("If padding_to is not -1, it should be larger "
                                 "than any instance's shape in the batch")
295 296 297 298 299 300 301 302 303 304
            max_length = padding_to
        # padding
        for audio, text in batch:
            padded_audio = np.zeros([audio.shape[0], max_length])
            padded_audio[:, :audio.shape[1]] = audio
            if flatten:
                padded_audio = padded_audio.flatten()
            new_batch.append((padded_audio, text))
        return new_batch

305
    def _batch_shuffle(self, manifest, batch_size, clipped=False):
306 307
        """Put similarly-sized instances into minibatches for better efficiency
        and make a batch-wise shuffle.
308 309 310

        1. Sort the audio clips by duration.
        2. Generate a random number `k`, k in [0, batch_size).
311 312
        3. Randomly shift `k` instances in order to create different batches
           for different epochs. Create minibatches.
313 314
        4. Shuffle the minibatches.

315
        :param manifest: Manifest contents. List of dict.
316 317 318 319
        :type manifest: list
        :param batch_size: Batch size. This size is also used for generate
                           a random number for batch shuffle.
        :type batch_size: int
320 321 322
        :param clipped: Whether to clip the heading (small shift) and trailing
                        (incomplete batch) instances.
        :type clipped: bool
323
        :return: Batch shuffled mainifest.
324 325 326 327 328 329 330
        :rtype: list
        """
        manifest.sort(key=lambda x: x["duration"])
        shift_len = self._rng.randint(0, batch_size - 1)
        batch_manifest = zip(*[iter(manifest[shift_len:])] * batch_size)
        self._rng.shuffle(batch_manifest)
        batch_manifest = list(sum(batch_manifest, ()))
331 332 333 334
        if not clipped:
            res_len = len(manifest) - shift_len - len(batch_manifest)
            batch_manifest.extend(manifest[-res_len:])
            batch_manifest.extend(manifest[0:shift_len])
335
        return batch_manifest