recordio_writer.py 4.7 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 16
from __future__ import print_function

17
import os
Y
Yu Yang 已提交
18
import contextlib
19
from . import core
20 21 22
__all__ = [
    'convert_reader_to_recordio_file', 'convert_reader_to_recordio_files'
]
Y
Yu Yang 已提交
23 24


Y
Yu Yang 已提交
25 26 27 28 29 30 31
@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 已提交
32 33 34 35 36 37 38 39 40


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

    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 已提交
77 78
    if feed_order is None:
        feed_order = feeder.feed_names
Y
Yu Yang 已提交
79
    counter = 0
Y
Yu Yang 已提交
80 81
    with create_recordio_writer(filename, compressor,
                                max_num_records) as writer:
Y
Yu Yang 已提交
82 83
        for batch in reader_creator():
            res = feeder.feed(batch)
Y
Yu Yang 已提交
84 85
            for each in feed_order:
                writer.append_tensor(res[each])
Y
Yu Yang 已提交
86
            writer.complete_append_tensor()
Y
Yu Yang 已提交
87 88
            counter += 1
    return counter
Y
Yancey1989 已提交
89 90 91


def convert_reader_to_recordio_files(
92
        filename,
Y
Yancey1989 已提交
93 94 95 96 97 98
        batch_per_file,
        reader_creator,
        feeder,
        compressor=core.RecordIOWriter.Compressor.Snappy,
        max_num_records=1000,
        feed_order=None):
Y
yuyang18 已提交
99 100 101 102 103 104
    """
    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
yuyang18 已提交
105 106 107 108

    Please reference
    :ref:`api_fluid_recordio_writer_convert_reader_to_recordio_file` for more
    details.
Y
yuyang18 已提交
109
    """
Y
Yancey1989 已提交
110 111
    if feed_order is None:
        feed_order = feeder.feed_names
112 113 114
    f_name, f_ext = os.path.splitext(filename)
    assert (f_ext == ".recordio")

Y
Yancey1989 已提交
115 116 117 118 119 120
    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:
121
            filename = "%s-%05d%s" % (f_name, f_idx, f_ext)
Y
Yancey1989 已提交
122 123 124 125 126 127 128 129 130 131 132
            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