recordio_writer.py 4.6 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 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
import os
Y
Yu Yang 已提交
16
import core
Y
Yu Yang 已提交
17
import contextlib
18 19 20
__all__ = [
    'convert_reader_to_recordio_file', 'convert_reader_to_recordio_files'
]
Y
Yu Yang 已提交
21 22


Y
Yu Yang 已提交
23 24 25 26 27 28 29
@contextlib.contextmanager
def create_recordio_writer(filename,
                           compressor=core.RecordIOWriter.Compressor.Snappy,
                           max_num_records=1000):
    writer = core.RecordIOWriter(filename, compressor, max_num_records)
    yield writer
    writer.close()
Y
Yu Yang 已提交
30 31 32 33 34 35 36 37 38


def convert_reader_to_recordio_file(
        filename,
        reader_creator,
        feeder,
        compressor=core.RecordIOWriter.Compressor.Snappy,
        max_num_records=1000,
        feed_order=None):
Y
yuyang18 已提交
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
    """
    Convert a Python Reader to a recordio file.

    Please see :ref:`api_guide_python_reader` and :ref:`api_guide_reader_op` for
    details.

    Examples:

        >>> import paddle.fluid as fluid
        >>> import paddle.dataset.mnist as mnist
        >>> import paddle
        >>>
        >>> tmp_program = fluid.Program()
        >>> with fluid.program_guard(tmp_program):
        >>>     img = fluid.layers.data(name='img', shape=[784])
        >>>     label = fluid.layers.data(name='label', shape=[1], dtype='int64')
        >>> feeder = fluid.DataFeeder(feed_list=[img, label], place=fluid.CPUPlace())
        >>> # mnist.recordio will be generated in current directory
        >>> fluid.recordio_writer.convert_reader_to_recordio_file(
        >>>                     filename="mnist.recordio",
        >>>                     reader_creator=paddle.batch(mnist.train(), batch_size=32),
        >>>                     feeder=feeder)

    Args:
        filename(str): The recordio filename.
        reader_creator(callable): The Python Reader Creator. See
            :ref:`api_guide_python_reader`.
        feeder(DataFeeder): The DataFeeder instance. Used to convert
            :code:`reader_creator` to :code: `lod_tensor`
        compressor: Must in fluid.core.RecordIOWriter.Compressor.Snappy or
            fluid.core.RecordIOWriter.Compressor.NoCompress. Use :code:`Snappy`
            by default.
        max_num_records(int): Maximum number of records in one chuck. Each record
            is each return value from reader function
        feed_order(list): The order of variable names that the reader returns

    Returns:
        int: the number of record that saved.
    """
Y
Yu Yang 已提交
78 79
    if feed_order is None:
        feed_order = feeder.feed_names
Y
Yu Yang 已提交
80
    counter = 0
Y
Yu Yang 已提交
81 82
    with create_recordio_writer(filename, compressor,
                                max_num_records) as writer:
Y
Yu Yang 已提交
83 84
        for batch in reader_creator():
            res = feeder.feed(batch)
Y
Yu Yang 已提交
85 86
            for each in feed_order:
                writer.append_tensor(res[each])
Y
Yu Yang 已提交
87
            writer.complete_append_tensor()
Y
Yu Yang 已提交
88 89
            counter += 1
    return counter
Y
Yancey1989 已提交
90 91 92


def convert_reader_to_recordio_files(
93
        filename,
Y
Yancey1989 已提交
94 95 96 97 98 99
        batch_per_file,
        reader_creator,
        feeder,
        compressor=core.RecordIOWriter.Compressor.Snappy,
        max_num_records=1000,
        feed_order=None):
Y
yuyang18 已提交
100 101 102 103 104 105 106
    """
    convert a python reader to many recordio files.

    This API is basically same as :code:`convert_reader_to_recordio_file`,
    instead of it will create many recordio files. Each file contains at
    most :code:`batch_per_file` records.
    """
Y
Yancey1989 已提交
107 108
    if feed_order is None:
        feed_order = feeder.feed_names
109 110 111
    f_name, f_ext = os.path.splitext(filename)
    assert (f_ext == ".recordio")

Y
Yancey1989 已提交
112 113 114 115 116 117
    lines = []
    f_idx = 0
    counter = 0
    for idx, batch in enumerate(reader_creator()):
        lines.append(batch)
        if idx >= batch_per_file and idx % batch_per_file == 0:
118
            filename = "%s-%05d%s" % (f_name, f_idx, f_ext)
Y
Yancey1989 已提交
119 120 121 122 123 124 125 126 127 128 129
            with create_recordio_writer(filename, compressor,
                                        max_num_records) as writer:
                for l in lines:
                    res = feeder.feed(l)
                    for each in feed_order:
                        writer.append_tensor(res[each])
                    writer.complete_append_tensor()
                    counter += 1
                lines = []
                f_idx += 1
    return counter