async_data_reader.py 19.9 KB
Newer Older
1
"""This module contains data processing related logic.
Z
zhxfl 已提交
2
"""
3 4 5 6
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

Z
zhxfl 已提交
7 8
import random
import struct
Y
yangyaming 已提交
9 10 11 12
import Queue
import time
import numpy as np
from threading import Thread
Y
yangyaming 已提交
13
import signal
Y
yangyaming 已提交
14
from multiprocessing import Manager, Process
15 16
import data_utils.augmentor.trans_mean_variance_norm as trans_mean_variance_norm
import data_utils.augmentor.trans_add_delta as trans_add_delta
Y
yangyaming 已提交
17
from data_utils.util import suppress_complaints, suppress_signal
18
from data_utils.util import CriticalException, ForceExitWrapper
19 20 21


class SampleInfo(object):
Y
yangyaming 已提交
22
    """SampleInfo holds the necessary information to load a sample from disk.
23

24 25 26 27 28 29 30
    Args:
        feature_bin_path (str): File containing the feature data.
        feature_start (int): Start position of the sample's feature data.
        feature_size (int): Byte count of the sample's feature data.
        feature_frame_num (int): Time length of the sample.
        feature_dim (int): Feature dimension of one frame.
        label_bin_path (str): File containing the label data.
Y
Yibing Liu 已提交
31
        label_size (int): Byte count of the sample's label data.
32
        label_frame_num (int): Label number of the sample.
Z
zhxfl 已提交
33
        sample_name (str): Key of the sample
Z
zhxfl 已提交
34 35
    """

36 37
    def __init__(self, feature_bin_path, feature_start, feature_size,
                 feature_frame_num, feature_dim, label_bin_path, label_start,
Z
zhxfl 已提交
38
                 label_size, label_frame_num, sample_name):
39 40 41 42 43 44 45 46 47 48
        self.feature_bin_path = feature_bin_path
        self.feature_start = feature_start
        self.feature_size = feature_size
        self.feature_frame_num = feature_frame_num
        self.feature_dim = feature_dim

        self.label_bin_path = label_bin_path
        self.label_start = label_start
        self.label_size = label_size
        self.label_frame_num = label_frame_num
Z
zhxfl 已提交
49
        self.sample_name = sample_name
50 51 52 53


class SampleInfoBucket(object):
    """SampleInfoBucket contains paths of several description files. Feature
Y
Yibing Liu 已提交
54 55 56
    description file contains necessary information (including path of binary
    data, sample start position, sample byte number etc.) to access samples'
    feature data and the same with the label description file. SampleInfoBucket
Y
yangyaming 已提交
57
    is the minimum unit to do shuffle.
58

59
    Args:
Y
Yibing Liu 已提交
60
        feature_bin_paths (list|tuple): Files containing the binary feature
61
                                        data.
Y
Yibing Liu 已提交
62 63
        feature_desc_paths (list|tuple): Files containing the description of
                                         samples' feature data.
64 65 66
        label_bin_paths (list|tuple): Files containing the binary label data.
        label_desc_paths (list|tuple): Files containing the description of
                                       samples' label data.
Y
Yibing Liu 已提交
67
        split_perturb(int): Maximum perturbation value for length of
Z
zhxfl 已提交
68
                            sub-sentence when splitting long sentence.
Y
Yibing Liu 已提交
69
        split_sentence_threshold(int): Sentence whose length larger than
Z
zhxfl 已提交
70
                                the value will trigger split operation.
Y
Yibing Liu 已提交
71
        split_sub_sentence_len(int): sub-sentence length is equal to
72 73
                                    (split_sub_sentence_len
                                     + rand() % split_perturb).
Z
zhxfl 已提交
74
    """
75

76 77 78 79 80 81 82 83
    def __init__(self,
                 feature_bin_paths,
                 feature_desc_paths,
                 label_bin_paths,
                 label_desc_paths,
                 split_perturb=50,
                 split_sentence_threshold=512,
                 split_sub_sentence_len=256):
84 85 86 87 88 89 90 91 92 93
        block_num = len(label_bin_paths)
        assert len(label_desc_paths) == block_num
        assert len(feature_bin_paths) == block_num
        assert len(feature_desc_paths) == block_num
        self._block_num = block_num

        self._feature_bin_paths = feature_bin_paths
        self._feature_desc_paths = feature_desc_paths
        self._label_bin_paths = label_bin_paths
        self._label_desc_paths = label_desc_paths
94 95 96
        self._split_perturb = split_perturb
        self._split_sentence_threshold = split_sentence_threshold
        self._split_sub_sentence_len = split_sub_sentence_len
Z
zhxfl 已提交
97
        self._rng = random.Random(0)
98 99 100 101 102 103 104 105 106 107 108

    def generate_sample_info_list(self):
        sample_info_list = []
        for block_idx in xrange(self._block_num):
            label_bin_path = self._label_bin_paths[block_idx]
            label_desc_path = self._label_desc_paths[block_idx]
            feature_bin_path = self._feature_bin_paths[block_idx]
            feature_desc_path = self._feature_desc_paths[block_idx]

            feature_desc_lines = open(feature_desc_path).readlines()

Z
zhxfl 已提交
109 110 111 112 113 114 115
            label_desc_lines = []
            if label_desc_path != "":
                label_desc_lines = open(label_desc_path).readlines()
            sample_num = int(feature_desc_lines[0].split()[1])

            if label_desc_path != "":
                assert sample_num == int(label_desc_lines[0].split()[1])
116 117 118

            for i in xrange(sample_num):
                feature_desc_split = feature_desc_lines[i + 1].split()
Z
zhxfl 已提交
119
                sample_name = feature_desc_split[0]
120 121 122 123 124
                feature_start = int(feature_desc_split[2])
                feature_size = int(feature_desc_split[3])
                feature_frame_num = int(feature_desc_split[4])
                feature_dim = int(feature_desc_split[5])

Z
zhxfl 已提交
125 126 127 128 129 130 131 132 133
                label_start = -1
                label_size = -1
                label_frame_num = feature_frame_num
                if label_desc_path != "":
                    label_desc_split = label_desc_lines[i + 1].split()
                    label_start = int(label_desc_split[2])
                    label_size = int(label_desc_split[3])
                    label_frame_num = int(label_desc_split[4])
                    assert feature_frame_num == label_frame_num
134

Z
zhxfl 已提交
135 136 137 138
                if self._split_sentence_threshold == -1 or \
                        self._split_perturb == -1 or \
                        self._split_sub_sentence_len == -1 \
                        or self._split_sentence_threshold >= feature_frame_num:
139 140 141 142
                    sample_info_list.append(
                        SampleInfo(feature_bin_path, feature_start,
                                   feature_size, feature_frame_num, feature_dim,
                                   label_bin_path, label_start, label_size,
Z
zhxfl 已提交
143
                                   label_frame_num, sample_name))
Y
Yibing Liu 已提交
144
                #split sentence
145 146 147 148 149 150
                else:
                    cur_frame_pos = 0
                    cur_frame_len = 0
                    remain_frame_num = feature_frame_num
                    while True:
                        if remain_frame_num > self._split_sentence_threshold:
Z
zhxfl 已提交
151 152
                            cur_frame_len = self._split_sub_sentence_len + \
                                    self._rng.randint(0, self._split_perturb)
153 154 155 156 157 158 159 160 161 162 163
                            if cur_frame_len > remain_frame_num:
                                cur_frame_len = remain_frame_num
                        else:
                            cur_frame_len = remain_frame_num

                        sample_info_list.append(
                            SampleInfo(
                                feature_bin_path, feature_start + cur_frame_pos
                                * feature_dim * 4, cur_frame_len * feature_dim *
                                4, cur_frame_len, feature_dim, label_bin_path,
                                label_start + cur_frame_pos * 4, cur_frame_len *
Z
zhxfl 已提交
164
                                4, cur_frame_len, sample_name))
165 166 167 168 169

                        remain_frame_num -= cur_frame_len
                        cur_frame_pos += cur_frame_len
                        if remain_frame_num <= 0:
                            break
170 171 172
        return sample_info_list


173 174 175 176
class EpochEndSignal():
    pass


177
class AsyncDataReader(object):
178
    """DataReader provides basic audio sample preprocessing pipeline including
Y
yangyaming 已提交
179
    data loading and data augmentation.
180

181
    Args:
Y
yangyaming 已提交
182 183
        feature_file_list (str): File containing paths of feature data file and
                                 corresponding description file.
Y
Yibing Liu 已提交
184
        label_file_list (str): File containing paths of label data file and
Y
yangyaming 已提交
185 186
                               corresponding description file.
        drop_frame_len (int): Samples whose label length above the value will be
187
                              dropped.(Using '-1' to disable the policy)
188
        proc_num (int): Number of processes for processing data.
Y
Yibing Liu 已提交
189
        sample_buffer_size (int): Buffer size to indicate the maximum samples
190
                                  cached.
Y
Yibing Liu 已提交
191
        sample_info_buffer_size (int): Buffer size to indicate the maximum
192
                                       sample information cached.
Y
Yibing Liu 已提交
193
        batch_buffer_size (int): Buffer size to indicate the maximum batch
Y
yangyaming 已提交
194
                                 cached.
Y
Yibing Liu 已提交
195
        shuffle_block_num (int): Block number indicating the minimum unit to do
196 197
                                 shuffle.
        random_seed (int): Random seed.
Y
Yibing Liu 已提交
198 199
        verbose (int): If set to 0, complaints including exceptions and signal
                       traceback from sub-process will be suppressed. If set
Y
yangyaming 已提交
200
                       to 1, all complaints will be printed.
Z
zhxfl 已提交
201 202
    """

Z
zhxfl 已提交
203 204
    def __init__(self,
                 feature_file_list,
Z
zhxfl 已提交
205
                 label_file_list="",
Z
zhxfl 已提交
206
                 drop_frame_len=512,
207
                 proc_num=10,
Z
zhxfl 已提交
208 209
                 sample_buffer_size=1024,
                 sample_info_buffer_size=1024,
210
                 batch_buffer_size=10,
211
                 shuffle_block_num=10,
212 213
                 random_seed=0,
                 verbose=0):
214 215 216 217 218 219 220 221 222 223
        self._feature_file_list = feature_file_list
        self._label_file_list = label_file_list
        self._drop_frame_len = drop_frame_len
        self._shuffle_block_num = shuffle_block_num
        self._block_info_list = None
        self._rng = random.Random(random_seed)
        self._bucket_list = None
        self.generate_bucket_list(True)
        self._order_id = 0
        self._manager = Manager()
224 225
        self._sample_buffer_size = sample_buffer_size
        self._sample_info_buffer_size = sample_info_buffer_size
Y
yangyaming 已提交
226
        self._batch_buffer_size = batch_buffer_size
227
        self._proc_num = proc_num
228
        self._verbose = verbose
229
        self._force_exit = ForceExitWrapper(self._manager.Value('b', False))
230 231 232 233 234

    def generate_bucket_list(self, is_shuffle):
        if self._block_info_list is None:
            block_feature_info_lines = open(self._feature_file_list).readlines()
            self._block_info_list = []
Z
zhxfl 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
            if self._label_file_list != "":
                block_label_info_lines = open(self._label_file_list).readlines()
                assert len(block_feature_info_lines) == len(
                    block_label_info_lines)
                for i in xrange(0, len(block_feature_info_lines), 2):
                    block_info = (block_feature_info_lines[i],
                                  block_feature_info_lines[i + 1],
                                  block_label_info_lines[i],
                                  block_label_info_lines[i + 1])
                    self._block_info_list.append(
                        map(lambda line: line.strip(), block_info))
            else:
                for i in xrange(0, len(block_feature_info_lines), 2):
                    block_info = (block_feature_info_lines[i],
                                  block_feature_info_lines[i + 1], "", "")
                    self._block_info_list.append(
                        map(lambda line: line.strip(), block_info))
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

        if is_shuffle:
            self._rng.shuffle(self._block_info_list)

        self._bucket_list = []
        for i in xrange(0, len(self._block_info_list), self._shuffle_block_num):
            bucket_block_info = self._block_info_list[i:i +
                                                      self._shuffle_block_num]
            self._bucket_list.append(
                SampleInfoBucket(
                    map(lambda info: info[0], bucket_block_info),
                    map(lambda info: info[1], bucket_block_info),
                    map(lambda info: info[2], bucket_block_info),
                    map(lambda info: info[3], bucket_block_info)))

    # @TODO make this configurable
    def set_transformers(self, transformers):
        self._transformers = transformers

271 272 273
    def _sample_generator(self):
        sample_info_queue = self._manager.Queue(self._sample_info_buffer_size)
        sample_queue = self._manager.Queue(self._sample_buffer_size)
274 275
        self._order_id = 0

276
        @suppress_complaints(verbose=self._verbose, notify=self._force_exit)
Y
yangyaming 已提交
277
        def ordered_feeding_task(sample_info_queue):
278
            for sample_info_bucket in self._bucket_list:
279 280 281 282 283 284 285 286 287 288
                try:
                    sample_info_list = \
                            sample_info_bucket.generate_sample_info_list()
                except Exception as e:
                    raise CriticalException(e)
                else:
                    self._rng.shuffle(sample_info_list)  # do shuffle here
                    for sample_info in sample_info_list:
                        sample_info_queue.put((sample_info, self._order_id))
                        self._order_id += 1
289

290
            for i in xrange(self._proc_num):
291 292
                sample_info_queue.put(EpochEndSignal())

293 294 295 296
        feeding_thread = Thread(
            target=ordered_feeding_task, args=(sample_info_queue, ))
        feeding_thread.daemon = True
        feeding_thread.start()
297

298
        @suppress_complaints(verbose=self._verbose, notify=self._force_exit)
Y
yangyaming 已提交
299
        def ordered_processing_task(sample_info_queue, sample_queue, out_order):
Y
yangyaming 已提交
300
            if self._verbose == 0:
301 302
                signal.signal(signal.SIGTERM, suppress_signal)
                signal.signal(signal.SIGINT, suppress_signal)
Y
yangyaming 已提交
303

304
            def read_bytes(fpath, start, size):
305 306 307 308 309 310 311 312
                try:
                    f = open(fpath, 'r')
                    f.seek(start, 0)
                    binary_bytes = f.read(size)
                    f.close()
                    return binary_bytes
                except Exception as e:
                    raise CriticalException(e)
313 314 315 316 317 318 319 320 321 322

            ins = sample_info_queue.get()

            while not isinstance(ins, EpochEndSignal):
                sample_info, order_id = ins

                feature_bytes = read_bytes(sample_info.feature_bin_path,
                                           sample_info.feature_start,
                                           sample_info.feature_size)

323
                assert sample_info.feature_frame_num \
324 325 326 327 328 329
                       * sample_info.feature_dim * 4 \
                        == len(feature_bytes), \
                        (sample_info.feature_bin_path,
                         sample_info.feature_frame_num,
                         sample_info.feature_dim,
                         len(feature_bytes))
Z
zhxfl 已提交
330

Z
zhxfl 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
                label_data = None
                if sample_info.label_bin_path != "":
                    label_bytes = read_bytes(sample_info.label_bin_path,
                                             sample_info.label_start,
                                             sample_info.label_size)

                    assert sample_info.label_frame_num * 4 == len(
                        label_bytes), (sample_info.label_bin_path,
                                       sample_info.label_array,
                                       len(label_bytes))

                    label_array = struct.unpack(
                        'I' * sample_info.label_frame_num, label_bytes)
                    label_data = np.array(
                        label_array, dtype='int64').reshape(
                            (sample_info.label_frame_num, 1))
                else:
                    label_data = np.zeros(
                        (sample_info.label_frame_num, 1), dtype='int64')
350 351 352 353 354 355 356 357 358

                feature_frame_num = sample_info.feature_frame_num
                feature_dim = sample_info.feature_dim
                assert feature_frame_num * feature_dim * 4 == len(feature_bytes)
                feature_array = struct.unpack('f' * feature_frame_num *
                                              feature_dim, feature_bytes)
                feature_data = np.array(
                    feature_array, dtype='float32').reshape((
                        sample_info.feature_frame_num, sample_info.feature_dim))
Z
zhxfl 已提交
359 360
                sample_data = (feature_data, label_data,
                               sample_info.sample_name)
361 362 363 364 365 366 367
                for transformer in self._transformers:
                    # @TODO(pkuyym) to make transfomer only accept feature_data
                    sample_data = transformer.perform_trans(sample_data)
                while order_id != out_order[0]:
                    time.sleep(0.001)

                # drop long sentence
Z
zhxfl 已提交
368 369
                if self._drop_frame_len == -1 or \
                        self._drop_frame_len >= sample_data[0].shape[0]:
370 371 372 373 374 375 376 377
                    sample_queue.put(sample_data)

                out_order[0] += 1
                ins = sample_info_queue.get()

            sample_queue.put(EpochEndSignal())

        out_order = self._manager.list([0])
378 379 380 381 382 383
        args = (sample_info_queue, sample_queue, out_order)
        workers = [
            Process(
                target=ordered_processing_task, args=args)
            for _ in xrange(self._proc_num)
        ]
384

385 386 387
        for w in workers:
            w.daemon = True
            w.start()
388

389
        finished_proc_num = 0
Y
yangyaming 已提交
390

391 392 393 394 395 396
        while self._force_exit == False:
            try:
                sample = sample_queue.get_nowait()
            except Queue.Empty:
                time.sleep(0.001)
            else:
397
                if isinstance(sample, EpochEndSignal):
398 399 400 401 402
                    finished_proc_num += 1
                    if finished_proc_num >= self._proc_num:
                        break
                    else:
                        continue
403

404
                yield sample
Y
yangyaming 已提交
405

406 407 408 409 410 411 412
    def batch_iterator(self, batch_size, minimum_batch_size):
        def batch_to_ndarray(batch_samples, lod):
            assert len(batch_samples)
            frame_dim = batch_samples[0][0].shape[1]
            batch_feature = np.zeros((lod[-1], frame_dim), dtype="float32")
            batch_label = np.zeros((lod[-1], 1), dtype="int64")
            start = 0
Z
zhxfl 已提交
413
            name_lst = []
414 415 416 417 418
            for sample in batch_samples:
                frame_num = sample[0].shape[0]
                batch_feature[start:start + frame_num, :] = sample[0]
                batch_label[start:start + frame_num, :] = sample[1]
                start += frame_num
Z
zhxfl 已提交
419 420
                name_lst.append(sample[2])
            return (batch_feature, batch_label, name_lst)
421

422 423 424 425 426 427 428 429
        @suppress_complaints(verbose=self._verbose, notify=self._force_exit)
        def batch_assembling_task(sample_generator, batch_queue):
            batch_samples = []
            lod = [0]
            for sample in sample_generator():
                batch_samples.append(sample)
                lod.append(lod[-1] + sample[0].shape[0])
                if len(batch_samples) == batch_size:
Z
zhxfl 已提交
430
                    (batch_feature, batch_label, name_lst) = batch_to_ndarray(
431
                        batch_samples, lod)
Z
zhxfl 已提交
432
                    batch_queue.put((batch_feature, batch_label, lod, name_lst))
433 434
                    batch_samples = []
                    lod = [0]
435

436
            if len(batch_samples) >= minimum_batch_size:
Z
zhxfl 已提交
437 438 439
                (batch_feature, batch_label, name_lst) = batch_to_ndarray(
                    batch_samples, lod)
                batch_queue.put((batch_feature, batch_label, lod, name_lst))
Y
yangyaming 已提交
440 441 442

            batch_queue.put(EpochEndSignal())

443
        batch_queue = Queue.Queue(self._batch_buffer_size)
Y
yangyaming 已提交
444

445
        assembling_thread = Thread(
Y
yangyaming 已提交
446
            target=batch_assembling_task,
447 448 449
            args=(self._sample_generator, batch_queue))
        assembling_thread.daemon = True
        assembling_thread.start()
Y
yangyaming 已提交
450

451
        while self._force_exit == False:
452
            try:
453
                batch_data = batch_queue.get_nowait()
454 455 456 457 458 459
            except Queue.Empty:
                time.sleep(0.001)
            else:
                if isinstance(batch_data, EpochEndSignal):
                    break
                yield batch_data