decorator.py 4.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2016 PaddlePaddle 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.

15
__all__ = ['buffered', 'compose', 'chain', 'shuffle', 'ComposeNotAligned']
16 17 18

from Queue import Queue
from threading import Thread
19 20
import itertools
import random
21 22


H
Helin Wang 已提交
23 24
def shuffle(reader, buf_size):
    """Creates a data reader whose data output is suffled.
25

H
Helin Wang 已提交
26
    Output from the iterator that created by original reader will be
27 28 29 30
    buffered into shuffle buffer, and then shuffled. The size of shuffle buffer
    is determined by argument buf_size.

    Args:
H
Helin Wang 已提交
31
        reader: the original reader whose output will be
32 33 34 35
            shuffled.
        buf_size: shuffle buffer size.

    Returns:
H
Helin Wang 已提交
36
        the new reader whose output is shuffled.
37 38
    """

H
Helin Wang 已提交
39
    def data_reader():
40
        buf = []
H
Helin Wang 已提交
41
        for e in reader():
42 43 44 45 46 47 48 49 50 51 52 53
            buf.append(e)
            if len(buf) >= buf_size:
                random.shuffle(buf)
                for b in buf:
                    yield b
                buf = []

        if len(buf) > 0:
            random.shuffle(buf)
            for b in buf:
                yield b

H
Helin Wang 已提交
54
    return data_reader
55 56


H
Helin Wang 已提交
57 58 59
def chain(*readers):
    """Creates a data reader whose output is the outputs of input data
       readers chained together.
60

H
Helin Wang 已提交
61
    If input readers output following data entries:
62 63 64
    [0, 0, 0]
    [1, 1, 1]
    [2, 2, 2]
H
Helin Wang 已提交
65
    The chained reader will output:
66 67 68
    [0, 0, 0, 1, 1, 1, 2, 2, 2]

    Args:
H
Helin Wang 已提交
69
        readerss: input readers.
70 71

    Returns:
H
Helin Wang 已提交
72
        the new data reader.
73 74
    """

H
Helin Wang 已提交
75
    def reader():
76
        rs = []
H
Helin Wang 已提交
77
        for r in readers:
78 79 80 81 82
            rs.append(r())

        for e in itertools.chain(*rs):
            yield e

H
Helin Wang 已提交
83
    return reader
84 85 86 87 88 89


class ComposeNotAligned:
    pass


H
Helin Wang 已提交
90 91
def compose(*readers, **kwargs):
    """Creates a data reader whose output is the combination of input readers.
92

H
Helin Wang 已提交
93
    If input readers output following data entries:
94
    (1, 2)    3    (4, 5)
H
Helin Wang 已提交
95
    The composed reader will output:
96 97 98
    (1, 2, 3, 4, 5)

    Args:
H
Helin Wang 已提交
99 100
        *readers: readers that will be composed together.
        check_alignment: If True, will check if input readers are aligned
101 102 103 104
            correctly. If False, will not check alignment and trailing outputs
            will be discarded. Defaults to True.

    Returns:
H
Helin Wang 已提交
105
        the new data reader.
106 107

    Raises:
H
Helin Wang 已提交
108
        ComposeNotAligned: outputs of readers are not aligned.
109 110 111 112 113 114 115 116 117 118
            Will not raise when check_alignment is set to False.
    """
    check_alignment = kwargs.pop('check_alignment', True)

    def make_tuple(x):
        if isinstance(x, tuple):
            return x
        else:
            return (x, )

H
Helin Wang 已提交
119
    def reader():
120
        rs = []
H
Helin Wang 已提交
121
        for r in readers:
122 123 124 125 126 127 128 129 130 131 132 133
            rs.append(r())
        if not check_alignment:
            for outputs in itertools.izip(*rs):
                yield sum(map(make_tuple, outputs), ())
        else:
            for outputs in itertools.izip_longest(*rs):
                for o in outputs:
                    if o is None:
                        # None will be not be present if compose is aligned
                        raise ComposeNotAligned
                yield sum(map(make_tuple, outputs), ())

H
Helin Wang 已提交
134
    return reader
135 136


H
Helin Wang 已提交
137 138
def buffered(reader, size):
    """Creates a buffered data reader.
139

H
Helin Wang 已提交
140 141
    The buffered data reader will read and save data entries into a
    buffer. Reading from the buffered data reader will proceed as long
142
    as the buffer is not empty.
143 144
    
    Args:
H
Helin Wang 已提交
145
        reader: the data reader to read from.
146 147 148
        size: max buffer size.
    
    Returns:
H
Helin Wang 已提交
149
        The buffered data reader.
150 151 152 153 154 155 156 157 158 159 160 161
    """

    class EndSignal():
        pass

    end = EndSignal()

    def read_worker(r, q):
        for d in r:
            q.put(d)
        q.put(end)

H
Helin Wang 已提交
162 163
    def data_reader():
        r = reader()
164 165 166 167 168 169 170 171 172 173 174 175
        q = Queue(maxsize=size)
        t = Thread(
            target=read_worker, args=(
                r,
                q, ))
        t.daemon = True
        t.start()
        e = q.get()
        while e != end:
            yield e
            e = q.get()

H
Helin Wang 已提交
176
    return data_reader