module.py 13.6 KB
Newer Older
S
Steffy-zxf 已提交
1
# coding:utf-8
W
wuzewu 已提交
2
# Copyright (c) 2020  PaddlePaddle Authors. All Rights Reserved.
W
wuzewu 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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.

W
wuzewu 已提交
16
import ast
W
wuzewu 已提交
17
import builtins
18
import codecs
W
wuzewu 已提交
19
import inspect
W
wuzewu 已提交
20
import os
21
import re
W
wuzewu 已提交
22
import sys
W
wuzewu 已提交
23
from typing import Callable, Generic, List, Optional, Union
W
wuzewu 已提交
24

W
wuzewu 已提交
25 26
from easydict import EasyDict

27
import paddle
W
wuzewu 已提交
28
from paddlehub.utils import parser, log, utils
29
from paddlehub.compat import paddle_utils
W
wuzewu 已提交
30
from paddlehub.compat.module.module_v1 import ModuleV1
W
wuzewu 已提交
31

W
wuzewu 已提交
32

W
wuzewu 已提交
33
class InvalidHubModule(Exception):
34
    def __init__(self, directory: str):
W
wuzewu 已提交
35 36 37 38 39 40 41
        self.directory = directory

    def __str__(self):
        return '{} is not a valid HubModule'.format(self.directory)


_module_serving_func = {}
W
wuzewu 已提交
42
_module_runnable_func = {}
W
wuzewu 已提交
43 44


45
def runnable(func: Callable) -> Callable:
W
wuzewu 已提交
46
    '''Mark a Module method as runnable, when the command `hub run` is used, the method will be called.'''
W
wuzewu 已提交
47
    mod = func.__module__ + '.' + inspect.stack()[1][3]
W
wuzewu 已提交
48
    _module_runnable_func[mod] = func.__name__
W
wuzewu 已提交
49 50 51 52 53 54 55

    def _wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    return _wrapper


56
def serving(func: Callable) -> Callable:
W
wuzewu 已提交
57
    '''Mark a Module method as serving method, when the command `hub serving` is used, the method will be called.'''
W
wuzewu 已提交
58
    mod = func.__module__ + '.' + inspect.stack()[1][3]
走神的阿圆's avatar
走神的阿圆 已提交
59 60 61 62 63 64 65 66
    _module_serving_func[mod] = func.__name__

    def _wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    return _wrapper


W
wuzewu 已提交
67 68 69
class RunModule(object):
    '''The base class of PaddleHub Module, users can inherit this class to implement to realize custom class.'''

H
haoyuying 已提交
70 71 72
    def __init__(self, *args, **kwargs):
        super(RunModule, self).__init__()

W
wuzewu 已提交
73 74 75 76 77 78 79
    def _get_func_name(self, current_cls: Generic, module_func_dict: dict) -> Optional[str]:
        mod = current_cls.__module__ + '.' + current_cls.__name__
        if mod in module_func_dict:
            _func_name = module_func_dict[mod]
            return _func_name
        elif current_cls.__bases__:
            for base_class in current_cls.__bases__:
H
haoyuying 已提交
80 81 82
                base_run_func = self._get_func_name(base_class, module_func_dict)
                if base_run_func:
                    return base_run_func
W
wuzewu 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        else:
            return None

    # After the 2.0.0rc version, paddle uses the dynamic graph mode by default, which will cause the
    # execution of the static graph model to fail, so compatibility protection is required.
    def __getattribute__(self, attr):
        _attr = object.__getattribute__(self, attr)

        # If the acquired attribute is a built-in property of the object, skip it.
        if re.match('__.*__', attr):
            return _attr
        # If the module is a dynamic graph model, skip it.
        elif isinstance(self, paddle.nn.Layer):
            return _attr
        # If the acquired attribute is not a class method, skip it.
        elif not inspect.ismethod(_attr):
            return _attr

        return paddle_utils.run_in_static_mode(_attr)

    @classmethod
    def get_py_requirements(cls) -> List[str]:
        '''Get Module's python package dependency list.'''
        py_module = sys.modules[cls.__module__]
        directory = os.path.dirname(py_module.__file__)
        req_file = os.path.join(directory, 'requirements.txt')
        if not os.path.exists(req_file):
            return []
111
        with codecs.open(req_file, 'r', encoding='utf8') as file:
W
wuzewu 已提交
112
            return file.read().split('\n')
W
wuzewu 已提交
113

114 115 116 117 118 119 120 121
    @property
    def _run_func_name(self):
        return self._get_func_name(self.__class__, _module_runnable_func)

    @property
    def _run_func(self):
        return getattr(self, self._run_func_name) if self._run_func_name else None

W
wuzewu 已提交
122 123 124 125 126 127
    @property
    def is_runnable(self) -> bool:
        '''
        Whether the Module is runnable, in other words, whether can we execute the Module through the
        `hub run` command.
        '''
128
        return True if self._run_func else False
W
wuzewu 已提交
129

130 131
    @property
    def serving_func_name(self):
132
        return self._get_func_name(self.__class__, _module_serving_func)
W
wuzewu 已提交
133 134


W
wuzewu 已提交
135
class Module(object):
W
wuzewu 已提交
136
    '''
W
wuzewu 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    In PaddleHub, Module represents an executable module, which usually a pre-trained model that can be used for end-to-end
    prediction, such as a face detection model or a lexical analysis model, or a pre-trained model that requires finetuning,
    such as BERT/ERNIE. When loading a Module with a specified name, if the Module does not exist locally, PaddleHub will
    automatically request the server or the specified Git source to download the resource.

    Args:
        name(str): Module name.
        directory(str|optional): Directory of the module to be loaded, only takes effect when the `name` is not specified.
        version(str|optional): The version limit of the module, only takes effect when the `name` is specified. When the local
                               Module does not meet the specified version conditions, PaddleHub will re-request the server to
                               download the appropriate Module. Default to None, This means that the local Module will be used.
                               If the Module does not exist, PaddleHub will download the latest version available from the
                               server according to the usage environment.
        source(str|optional): Url of a git repository. If this parameter is specified, PaddleHub will no longer download the
                              specified Module from the default server, but will look for it in the specified repository.
                              Default to None.
        update(bool|optional): Whether to update the locally cached git repository, only takes effect when the `source`
                               is specified. Default to False.
        branch(str|optional): The branch of the specified git repository. Default to None.
W
wuzewu 已提交
156
    '''
W
wuzewu 已提交
157

W
wuzewu 已提交
158
    def __new__(cls,
W
wuzewu 已提交
159
                *,
W
wuzewu 已提交
160 161 162 163 164
                name: str = None,
                directory: str = None,
                version: str = None,
                source: str = None,
                update: bool = False,
W
wuzewu 已提交
165
                branch: str = None,
W
wuzewu 已提交
166
                **kwargs):
W
wuzewu 已提交
167
        if cls.__name__ == 'Module':
168
            from paddlehub.server.server import CacheUpdater
W
wuzewu 已提交
169
            # This branch come from hub.Module(name='xxx') or hub.Module(directory='xxx')
W
wuzewu 已提交
170
            if name:
W
wuzewu 已提交
171 172
                module = cls.init_with_name(
                    name=name, version=version, source=source, update=update, branch=branch, **kwargs)
173
                CacheUpdater("update_cache", module=name, version=version).start()
W
wuzewu 已提交
174
            elif directory:
W
wuzewu 已提交
175
                module = cls.init_with_directory(directory=directory, **kwargs)
176
                CacheUpdater("update_cache", module=directory, version="0.0.0").start()
177
        else:
W
wuzewu 已提交
178
            module = object.__new__(cls)
179

W
wuzewu 已提交
180 181 182
        return module

    @classmethod
183
    def load(cls, directory: str) -> Generic:
W
wuzewu 已提交
184
        '''Load the Module object defined in the specified directory.'''
W
wuzewu 已提交
185 186
        if directory.endswith(os.sep):
            directory = directory[:-1]
W
wuzewu 已提交
187

W
wuzewu 已提交
188
        # If the module description file existed, try to load as ModuleV1
W
wuzewu 已提交
189 190
        desc_file = os.path.join(directory, 'module_desc.pb')
        if os.path.exists(desc_file):
W
wuzewu 已提交
191
            return ModuleV1.load(directory)
W
wuzewu 已提交
192

W
wuzewu 已提交
193 194
        basename = os.path.split(directory)[-1]
        dirname = os.path.join(*list(os.path.split(directory)[:-1]))
W
wuzewu 已提交
195
        py_module = utils.load_py_module(dirname, '{}.module'.format(basename))
W
wuzewu 已提交
196 197 198 199 200

        for _item, _cls in inspect.getmembers(py_module, inspect.isclass):
            _item = py_module.__dict__[_item]
            if hasattr(_item, '_hook_by_hub') and issubclass(_item, RunModule):
                user_module_cls = _item
W
wuzewu 已提交
201
                break
W
wuzewu 已提交
202 203
        else:
            raise InvalidHubModule(directory)
W
wuzewu 已提交
204

W
wuzewu 已提交
205
        user_module_cls.directory = directory
W
wuzewu 已提交
206 207 208 209 210 211 212 213 214

        source_info_file = os.path.join(directory, '_source_info.yaml')
        if os.path.exists(source_info_file):
            info = parser.yaml_parser.parse(source_info_file)
            user_module_cls.source = info.get('source', '')
            user_module_cls.branch = info.get('branch', '')
        else:
            user_module_cls.source = ''
            user_module_cls.branch = ''
215 216 217 218 219 220

        # In the case of multiple cards, the following code can set each process to use the correct place.
        if issubclass(user_module_cls, paddle.nn.Layer):
            place = paddle.get_device().split(':')[0]
            paddle.set_device(place)

W
wuzewu 已提交
221
        return user_module_cls
W
wuzewu 已提交
222

W
wuzewu 已提交
223 224
    @classmethod
    def load_module_info(cls, directory: str) -> EasyDict:
W
wuzewu 已提交
225
        '''Load the infomation of Module object defined in the specified directory.'''
W
wuzewu 已提交
226 227 228 229 230 231 232
        # If is ModuleV1
        desc_file = os.path.join(directory, 'module_desc.pb')
        if os.path.exists(desc_file):
            return ModuleV1.load_module_info(directory)

        # If is ModuleV2
        module_file = os.path.join(directory, 'module.py')
233
        with codecs.open(module_file, 'r', encoding='utf8') as file:
W
wuzewu 已提交
234 235 236 237 238 239 240 241 242 243 244
            pycode = file.read()
            ast_module = ast.parse(pycode)

            for _body in ast_module.body:
                if not isinstance(_body, ast.ClassDef):
                    continue

                for _decorator in _body.decorator_list:
                    if _decorator.func.id != 'moduleinfo':
                        continue

W
wuzewu 已提交
245
                    info = {key.arg: key.value.s for key in _decorator.keywords if key.arg != 'meta'}
W
wuzewu 已提交
246 247 248 249
                    return EasyDict(info)
            else:
                raise InvalidHubModule(directory)

W
wuzewu 已提交
250
    @classmethod
W
wuzewu 已提交
251 252 253 254 255 256
    def init_with_name(cls,
                       name: str,
                       version: str = None,
                       source: str = None,
                       update: bool = False,
                       branch: str = None,
W
wuzewu 已提交
257 258
                       **kwargs) -> Union[RunModule, ModuleV1]:
        '''Initialize Module according to the specified name.'''
W
wuzewu 已提交
259 260
        from paddlehub.module.manager import LocalModuleManager
        manager = LocalModuleManager()
W
wuzewu 已提交
261
        user_module_cls = manager.search(name, source=source, branch=branch)
W
wuzewu 已提交
262
        if not user_module_cls or not user_module_cls.version.match(version):
W
wuzewu 已提交
263
            user_module_cls = manager.install(name=name, version=version, source=source, update=update, branch=branch)
W
wuzewu 已提交
264

W
wuzewu 已提交
265
        directory = manager._get_normalized_path(user_module_cls.name)
W
wuzewu 已提交
266 267 268 269 270 271 272 273 274 275

        # The HubModule in the old version will use the _initialize method to initialize,
        # this function will be obsolete in a future version
        if hasattr(user_module_cls, '_initialize'):
            log.logger.warning(
                'The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object'
            )
            user_module = user_module_cls(directory=directory)
            user_module._initialize(**kwargs)
            return user_module
W
wuzewu 已提交
276

277
        if issubclass(user_module_cls, ModuleV1):
W
wuzewu 已提交
278 279
            return user_module_cls(directory=directory, **kwargs)

W
wuzewu 已提交
280 281
        user_module_cls.directory = directory
        return user_module_cls(**kwargs)
W
wuzewu 已提交
282

W
wuzewu 已提交
283
    @classmethod
W
wuzewu 已提交
284 285
    def init_with_directory(cls, directory: str, **kwargs) -> Union[RunModule, ModuleV1]:
        '''Initialize Module according to the specified directory.'''
W
wuzewu 已提交
286
        user_module_cls = cls.load(directory)
W
wuzewu 已提交
287 288 289 290 291 292 293 294 295 296

        # The HubModule in the old version will use the _initialize method to initialize,
        # this function will be obsolete in a future version
        if hasattr(user_module_cls, '_initialize'):
            log.logger.warning(
                'The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object'
            )
            user_module = user_module_cls(directory=directory)
            user_module._initialize(**kwargs)
            return user_module
W
wuzewu 已提交
297

298
        if issubclass(user_module_cls, ModuleV1):
W
wuzewu 已提交
299 300
            return user_module_cls(directory=directory, **kwargs)

W
wuzewu 已提交
301 302
        user_module_cls.directory = directory
        return user_module_cls(**kwargs)
W
wuzewu 已提交
303

W
wuzewu 已提交
304

W
wuzewu 已提交
305 306 307 308 309 310
def moduleinfo(name: str,
               version: str,
               author: str = None,
               author_email: str = None,
               summary: str = None,
               type: str = None,
311
               meta=None) -> Callable:
W
wuzewu 已提交
312
    '''
W
wuzewu 已提交
313 314
    Mark Module information for a python class, and the class will automatically be extended to inherit HubModule. In other words, python classes
    marked with moduleinfo can be loaded through hub.Module.
W
wuzewu 已提交
315 316
    '''

317
    def _wrapper(cls: Generic) -> Generic:
W
wuzewu 已提交
318 319 320 321 322 323 324 325 326 327
        wrap_cls = cls
        _meta = RunModule if not meta else meta
        if not issubclass(cls, _meta):
            _bases = []
            for _b in cls.__bases__:
                if issubclass(_meta, _b):
                    continue
                _bases.append(_b)
            _bases.append(_meta)
            _bases = tuple(_bases)
W
wuzewu 已提交
328
            wrap_cls = builtins.type(cls.__name__, _bases, dict(cls.__dict__))
W
wuzewu 已提交
329 330 331 332 333 334 335 336 337

        wrap_cls.name = name
        wrap_cls.version = utils.Version(version)
        wrap_cls.author = author
        wrap_cls.author_email = author_email
        wrap_cls.summary = summary
        wrap_cls.type = type
        wrap_cls._hook_by_hub = True
        return wrap_cls
W
wuzewu 已提交
338

W
wuzewu 已提交
339
    return _wrapper