gen_doc.py 7.8 KB
Newer Older
R
root 已提交
1 2 3 4 5 6 7 8 9 10 11 12
import paddle
import os
import shutil
import time
import pkgutil
import types
import contextlib
import argparse

en_suffix = "_en.rst"
cn_suffix = "_cn.rst"
file_path_dict = {}
C
chentianyu03 已提交
13 14 15 16 17
same_api_map = {}
alias_api_map = {}
not_display_doc_map = {}
display_doc_map = {}
api_set = set()
R
root 已提交
18 19


C
chentianyu03 已提交
20
def get_all_api(root_path='paddle'):
R
root 已提交
21 22 23 24 25 26 27 28
    for filefiner, name, ispkg in pkgutil.walk_packages(
            path=paddle.__path__, prefix=paddle.__name__ + '.'):
        try:
            m = eval(name)
        except AttributeError:
            pass
        else:
            if hasattr(eval(name), "__all__"):
C
chentianyu03 已提交
29
                #may have duplication of api
R
root 已提交
30
                for api in list(set(eval(name).__all__)):
C
chentianyu03 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
                    api_all = name + "." + api
                    if "," in api:
                        continue

                    try:
                        fc_id = id(eval(api_all))
                    except AttributeError:
                        pass
                    else:
                        api_set.add(api_all)


def get_all_same_api():
    for api in api_set:
        fc_id = id(eval(api))
        if fc_id in same_api_map:
            same_api_map[fc_id].append(api)
        else:
            same_api_map[fc_id] = [api]
R
root 已提交
50 51


C
chentianyu03 已提交
52 53 54 55 56
def get_not_display_doc_list(file="./not_display_doc_list"):
    with open(file, 'r') as f:
        for line in f.readlines():
            line = line.strip()
            not_display_doc_map[line] = 1
R
root 已提交
57 58


C
chentianyu03 已提交
59 60 61 62 63
def get_display_doc_map(file="./display_doc_list"):
    with open(file, 'r') as f:
        for line in f.readlines():
            line = line.strip()
            display_doc_map[line] = 1
R
root 已提交
64

C
chentianyu03 已提交
65 66 67 68 69 70

def get_alias_mapping(file="./alias_api_mapping"):
    with open(file, 'r') as f:
        for line in f.readlines():
            t = line.strip().split('\t')
            real_api = t[0].strip()
C
chentianyu03 已提交
71 72
            alias_apis = t[1].strip().split(',')
            alias_api_map[real_api] = alias_apis
C
chentianyu03 已提交
73 74 75 76 77 78 79


def is_filter_api(api):
    #if api in display_list, just return False
    if api in display_doc_map:
        return False

C
chentianyu03 已提交
80
    #check api in not_display_list
C
chentianyu03 已提交
81 82 83 84 85 86 87 88 89 90 91 92
    for key in not_display_doc_map:
        #find the api
        if key == api:
            return True
        #find the module
        if api.startswith(key):
            k_segs = key.split(".")
            a_segs = api.split(".")
            if k_segs[len(k_segs) - 1] == a_segs[len(k_segs) - 1]:
                return True

    #check api in alias map
C
chentianyu03 已提交
93
    if api in alias_api_map:
C
chentianyu03 已提交
94 95 96 97
        return False

    same_apis = same_api_map[id(eval(api))]

C
chentianyu03 已提交
98
    #api not in alias map
C
chentianyu03 已提交
99 100
    #if the api in alias_map key, others api is alias api
    for x in same_apis:
C
chentianyu03 已提交
101
        if x in alias_api_map:
C
chentianyu03 已提交
102 103 104 105 106 107 108 109 110 111 112 113
            return True

    if len(same_apis) > 1:
        # find shortest path of api as the real api
        # others api as the alias api
        shortest = len(same_apis[0].split("."))
        for x in same_apis:
            if len(x.split(".")) < shortest:
                shortest = len(x.split("."))

        if len(api.split(".")) == shortest:
            return False
R
root 已提交
114
        else:
C
chentianyu03 已提交
115 116
            return True
    return False
R
root 已提交
117 118


C
chentianyu03 已提交
119
def gen_en_files(root_path='paddle', api_label_file="api_label"):
C
chentianyu03 已提交
120
    backup_path = root_path + "_" + str(int(time.time()))
C
chentianyu03 已提交
121
    api_f = open(api_label_file, 'w')
C
chentianyu03 已提交
122 123 124 125

    for api in api_set:
        if is_filter_api(api):
            continue
C
chentianyu03 已提交
126 127
        module_name = ".".join(api.split(".")[0:-1])
        doc_file = api.split(".")[-1]
R
root 已提交
128

C
chentianyu03 已提交
129 130
        if isinstance(eval(module_name + "." + doc_file), types.ModuleType):
            continue
C
chentianyu03 已提交
131

C
chentianyu03 已提交
132 133 134 135
        path = "/".join(api.split(".")[0:-1])
        if not os.path.exists(path):
            os.makedirs(path)
        f = api.replace(".", "/")
C
chentianyu03 已提交
136 137
        if os.path.exists(f + en_suffix):
            continue
C
chentianyu03 已提交
138 139 140
        os.mknod(f + en_suffix)
        gen = EnDocGenerator()
        with gen.guard(f + en_suffix):
C
chentianyu03 已提交
141
            gen.module_name = module_name
C
chentianyu03 已提交
142 143 144
            gen.api = doc_file
            gen.print_header_reminder()
            gen.print_item()
C
chentianyu03 已提交
145 146 147
            api_f.write(doc_file + "\t" + ".. _api_{0}_{1}:\n".format("_".join(
                gen.module_name.split(".")), gen.api))
    api_f.close()
R
root 已提交
148 149


C
chentianyu03 已提交
150
def clean_en_files(path="./paddle"):
R
root 已提交
151 152
    for root, dirs, files in os.walk(path):
        for file in files:
C
chentianyu03 已提交
153 154
            if file.endswith(en_suffix):
                os.remove(os.path.join(root, file))
R
root 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198


def check_cn_en_match(path="./paddle", diff_file="en_cn_files_diff"):
    fo = open(diff_file, 'w')
    fo.write("exist\tnot_exits\n")
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(en_suffix):
                cf = file.replace(en_suffix, cn_suffix)
                if not os.path.exists(root + "/" + cf):
                    fo.write(
                        os.path.join(root, file) + "\t" + os.path.join(
                            root, cf) + "\n")

            elif file.endswith(cn_suffix):
                ef = file.replace(cn_suffix, en_suffix)
                if not os.path.exists(root + "/" + ef):
                    fo.write(
                        os.path.join(root, file) + "\t" + os.path.join(
                            root, ef) + "\n")
    fo.close()


class EnDocGenerator(object):
    def __init__(self, name=None, api=None):
        self.module_name = name
        self.api = api
        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

    def print_item(self):
        try:
            m = eval(self.module_name + "." + self.api)
        except AttributeError:
            #print("attribute error: module_name=" + self.module_name  + ", api=" + self.api)
            pass
        else:
C
chentianyu03 已提交
199
            if isinstance(eval(self.module_name + "." + self.api), type):
R
root 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
                self.print_class()
            elif isinstance(
                    eval(self.module_name + "." + self.api),
                    types.FunctionType):
                self.print_function()

    def print_header_reminder(self):
        self.stream.write('''..  THIS FILE IS GENERATED BY `gen_doc.{py|sh}`
    !DO NOT EDIT THIS FILE MANUALLY!

''')

    def _print_ref_(self):
        self.stream.write(".. _api_{0}_{1}:\n\n".format("_".join(
            self.module_name.split(".")), self.api))

    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_class(self):
        self._print_ref_()
        self._print_header_(self.api, dot='-', is_title=False)
        if "fluid.dygraph" in self.module_name:
            self.stream.write('''..  autoclass:: paddle.{0}.{1}
    :members:
    :noindex:

'''.format(self.module_name, self.api))
        elif "fluid.optimizer" in self.module_name:
            self.stream.write('''..  autoclass:: paddle.{0}.{1}
    :members:
    :inherited-members:
    :exclude-members: apply_gradients, apply_optimize, backward, load
    :noindex:

'''.format(self.module_name, self.api))
        else:
            self.stream.write('''..  autoclass:: paddle.{0}.{1}
    :members:
    :inherited-members:
    :noindex:

'''.format(self.module_name, self.api))

    def print_function(self):
        self._print_ref_()
        self._print_header_(self.api, dot='-', is_title=False)
C
chentianyu03 已提交
255
        self.stream.write('''..  autofunction:: {0}.{1}
R
root 已提交
256 257 258 259 260 261
    :noindex:

'''.format(self.module_name, self.api))


if __name__ == "__main__":
C
chentianyu03 已提交
262 263 264 265 266
    get_all_api()
    get_not_display_doc_list()
    get_display_doc_map()
    get_all_same_api()
    get_alias_mapping()
R
root 已提交
267 268

    clean_en_files()
C
chentianyu03 已提交
269 270
    gen_en_files()
    check_cn_en_match()