gen_doc.py 7.3 KB
Newer Older
W
Wang,Jeff 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   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.

from __future__ import print_function
import argparse
import sys
import types
Z
Zeng Jinle 已提交
19 20
import os
import contextlib
D
dongdaxiang 已提交
21
import paddle.fleet as fleet
W
Wang,Jeff 已提交
22
import paddle.fluid as fluid
23
import paddle.tensor as tensor
24
import paddle.nn as nn
25
import paddle.complex as complex
26
#import paddle.framework as framework
W
Wang,Jeff 已提交
27 28 29 30 31

def parse_arg():
    parser = argparse.ArgumentParser()
    parser.add_argument('--submodules', nargs="*")
    parser.add_argument(
Z
Zeng Jinle 已提交
32
        '--module_name', type=str, help='Generate the documentation of which module')
Z
Zeng Jinle 已提交
33 34
    parser.add_argument(
        '--module_prefix', type=str, help='Generate the prefix of module')
Z
Zeng Jinle 已提交
35 36
    parser.add_argument(
        '--output', type=str, help='Output file or output directory for output rst')
37 38
    parser.add_argument(
        '--output_name', type=str, help='Output file or output directory for output rst')
39 40
    parser.add_argument(
        '--output_dir', type=str, help='Output file or output directory for output rst')
Z
Zeng Jinle 已提交
41 42
    parser.add_argument(
        '--to_multiple_files', type=bool, default=False, help='Whether to separate to multiple files')
43

W
Wang,Jeff 已提交
44 45
    return parser.parse_args()

Z
Zeng Jinle 已提交
46 47 48 49 50 51 52 53
    def print_item(self, name):
        item = getattr(self.module, name, None)
        if item is None:
            return
        if isinstance(item, types.TypeType):
            self.print_class(name)
        elif isinstance(item, types.FunctionType):
            self.print_method(name)
W
Wang,Jeff 已提交
54
        else:
Z
Zeng Jinle 已提交
55
            pass
W
Wang,Jeff 已提交
56

Z
Zeng Jinle 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69
class DocGenerator(object):
    def __init__(self, module_name=None, module_prefix=None): 
        self.module_name = module_name
        self.module_prefix = module_prefix
        self.stream = None

    @contextlib.contextmanager
    def guard(self, filename):
        assert self.stream is None, "stream must be None"
        self.stream = open(filename, 'w') 
        yield
        self.stream.close()
        self.stream = None
W
Wang,Jeff 已提交
70 71 72 73 74 75 76

    def print_submodule(self, submodule_name):
        submodule = getattr(self.module, submodule_name)
        if submodule is None:
            raise ValueError("Cannot find submodule {0}".format(submodule_name))
        self.print_section(submodule_name)

T
tink2123 已提交
77
        for item in sorted(submodule.__all__,key=str.lower):
W
Wang,Jeff 已提交
78 79 80
            self.print_item(item)

    def print_current_module(self):
T
tink2123 已提交
81
        for item in sorted(self.module.__all__,key=str.lower):
W
Wang,Jeff 已提交
82 83 84 85 86
            self.print_item(item)

    def print_section(self, name):
        self._print_header_(name, dot='=', is_title=False)

T
tianshuo78520a 已提交
87
    def print_item(self, name, output_name):
W
Wang,Jeff 已提交
88 89 90 91 92 93
        item = getattr(self.module, name, None)
        if isinstance(item, types.TypeType):
            self.print_class(name)
        elif isinstance(item, types.FunctionType):
            self.print_method(name)
        else:
T
tianshuo78520a 已提交
94
            self.stream.close()
T
tianshuo78520a 已提交
95
            path = os.getcwd()+"/"+output_name+"/"+name+".rst"
Y
Yucheng 已提交
96 97
            if name != "PipeReader":
                os.remove(path)
W
Wang,Jeff 已提交
98 99 100 101

    def print_class(self, name):
        self._print_ref_(name)
        self._print_header_(name, dot='-', is_title=False)
L
lujun 已提交
102 103 104 105 106
        if "fluid.dygraph" in self.module_prefix:
            self.stream.write('''..  autoclass:: paddle.{0}.{1}
    :members:
    :noindex:

107 108 109 110 111 112 113 114
'''.format(self.module_prefix, name))
        elif "fluid.optimizer" in self.module_prefix:
            self.stream.write('''..  autoclass:: paddle.{0}.{1}
    :members:
    :inherited-members:
    :exclude-members: apply_gradients, apply_optimize, backward, load
    :noindex:

L
lujun 已提交
115 116 117
'''.format(self.module_prefix, name))
        else:
            self.stream.write('''..  autoclass:: paddle.{0}.{1}
W
Wang,Jeff 已提交
118
    :members:
119
    :inherited-members:
W
Wang,Jeff 已提交
120 121
    :noindex:

Z
Zeng Jinle 已提交
122
'''.format(self.module_prefix, name))
W
Wang,Jeff 已提交
123 124 125 126 127 128 129

    def print_method(self, name):
        self._print_ref_(name)
        self._print_header_(name, dot='-', is_title=False)
        self.stream.write('''..  autofunction:: paddle.{0}.{1}
    :noindex:

Z
Zeng Jinle 已提交
130
'''.format(self.module_prefix, name))
W
Wang,Jeff 已提交
131

Z
Zeng Jinle 已提交
132 133 134 135 136 137
    def print_header_reminder(self):
        self.stream.write('''..  THIS FILE IS GENERATED BY `gen_doc.{py|sh}`
    !DO NOT EDIT THIS FILE MANUALLY!

''')

W
Wang,Jeff 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150
    def _print_header_(self, name, dot, is_title):
        dot_line = dot * len(name)
        if is_title:
            self.stream.write(dot_line)
            self.stream.write('\n')
        self.stream.write(name)
        self.stream.write('\n')
        self.stream.write(dot_line)
        self.stream.write('\n')
        self.stream.write('\n')

    def _print_ref_(self, name):
        self.stream.write(".. _api_{0}_{1}:\n\n".format("_".join(
Z
Zeng Jinle 已提交
151
            self.module_prefix.split(".")), name))
W
Wang,Jeff 已提交
152

153
def generate_doc(module_name, module_prefix, output, output_name, to_multiple_files, output_dir):
Z
Zeng Jinle 已提交
154 155 156 157 158 159 160 161 162
    if module_name == "":
        module_name = None

    if module_prefix == "":
        module_prefix = None

    gen = DocGenerator()

    if module_name is None:
163 164
        gen.module = eval(output_name)
        gen.module_name = str(output_name)
Z
Zeng Jinle 已提交
165
    else:
166
        gen.module = eval(output_name)
Z
Zeng Jinle 已提交
167 168 169 170 171 172
        for each_module_name in module_name.split('.'):
            if not hasattr(gen.module, each_module_name):
                raise ValueError("Cannot find fluid.{0}".format(module_name))
            else:
                gen.module = getattr(gen.module, each_module_name)

173
        gen.module_name = output_name + "." + module_name
Z
Zeng Jinle 已提交
174 175 176 177

    if module_prefix is None:
        gen.module_prefix = gen.module_name
    else:
178
        gen.module_prefix = output_name + "." + module_prefix
Z
Zeng Jinle 已提交
179 180

    dirname = output if to_multiple_files else os.path.dirname(output) 
181 182 183 184 185

    if output_dir != None:
        dirname = output_dir + "/" + dirname
        output = output_dir + "/" + output

Z
Zeng Jinle 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    if len(dirname) > 0 and (not os.path.exists(dirname) or not os.path.isdir(dirname)): 
        os.makedirs(dirname)

    if not to_multiple_files:
        header_name = gen.module_name
        if module_prefix is not None:
            prefix_len = len(gen.module_prefix)
            assert gen.module_prefix == gen.module_name[0:prefix_len],    \
                "module_prefix must be prefix of module_name"
            diff_name = gen.module_name[prefix_len+1:]
            if diff_name != "":
                header_name = diff_name
    else:
        header_name = None

    if not to_multiple_files:
        with gen.guard(output):
            gen.print_header_reminder()
            gen._print_header_(header_name, dot='=', is_title=True)
            gen.print_current_module()
    else:
        apis = sorted(gen.module.__all__,key=str.lower)
        for api in apis:
            header_name = api
            with gen.guard(os.path.join(output, api + '.rst')):
                gen.print_header_reminder()
T
tianshuo78520a 已提交
212
                gen.print_item(api, output_name)
Z
Zeng Jinle 已提交
213

W
Wang,Jeff 已提交
214 215 216

def main():
    args = parse_arg()
217
    generate_doc(args.module_name, args.module_prefix, args.output, args.output_name, args.to_multiple_files, args.output_dir)
W
Wang,Jeff 已提交
218 219 220 221


if __name__ == '__main__':
    main()