convert.py 6.7 KB
Newer Older
走神的阿圆's avatar
走神的阿圆 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#coding:utf-8
# Copyright (c) 2020  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.
import argparse
import os
import time
import tarfile
import shutil
from string import Template

from paddlehub.common import tmp_dir
from paddlehub.commands.base_command import BaseCommand, ENTRY
24
from paddlehub.common.hub_server import CacheUpdater
走神的阿圆's avatar
走神的阿圆 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

INIT_FILE = '__init__.py'
MODULE_FILE = 'module.py'
SERVING_FILE = 'serving_client_demo.py'
TMPL_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tmpl')


class ConvertCommand(BaseCommand):
    name = "convert"

    def __init__(self, name):
        super(ConvertCommand, self).__init__(name)
        self.show_in_help = True
        self.description = "Convert model to PaddleHub-Module."
        self.parser = argparse.ArgumentParser(
            description=self.__class__.__doc__,
            prog='%s %s [COMMAND]' % (ENTRY, name),
            usage='%(prog)s',
            add_help=True)
        self.parser.add_argument('command')
        self.parser.add_argument('--module_name', '-n')
L
Leowolfking 已提交
46 47 48 49
        self.parser.add_argument('--module_version',
                                 '-v',
                                 nargs='?',
                                 default='1.0.0')
走神的阿圆's avatar
走神的阿圆 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
        self.parser.add_argument('--model_dir', '-d')
        self.parser.add_argument('--output_dir', '-o')

    def create_module_tar(self):
        if not os.path.exists(self.dest):
            os.makedirs(self.dest)
        tar_file = os.path.join(self.dest, '{}.tar.gz'.format(self.module))
        with tarfile.open(tar_file, 'w:gz') as tfp:
            tfp.add(self.dest, recursive=False, arcname=self.module)
            for root, dir, files in os.walk(self.src):
                for file in files:
                    fullpath = os.path.join(root, file)
                    arcname = os.path.join(self.module, 'assets', file)
                    tfp.add(fullpath, arcname=arcname)

L
Leowolfking 已提交
65 66 67 68 69 70
            tfp.add(self.model_file,
                    arcname=os.path.join(self.module, MODULE_FILE))
            tfp.add(self.serving_file,
                    arcname=os.path.join(self.module, SERVING_FILE))
            tfp.add(self.init_file,
                    arcname=os.path.join(self.module, INIT_FILE))
走神的阿圆's avatar
走神的阿圆 已提交
71 72

    def create_module_py(self):
L
Leowolfking 已提交
73 74 75
        template_file = open(os.path.join(TMPL_DIR, 'x_model.tmpl'),
                             'r',
                             encoding='utf-8')
走神的阿圆's avatar
走神的阿圆 已提交
76 77 78 79
        tmpl = Template(template_file.read())
        lines = []

        lines.append(
L
Leowolfking 已提交
80 81 82 83 84 85
            tmpl.substitute(NAME="'{}'".format(self.module),
                            TYPE="'CV'",
                            AUTHOR="'Baidu'",
                            SUMMARY="''",
                            VERSION="'{}'".format(self.version),
                            EMAIL="''"))
走神的阿圆's avatar
走神的阿圆 已提交
86 87 88 89 90 91 92
        # self.model_file = os.path.join(self.dest, MODULE_FILE)
        self.model_file = os.path.join(self._tmp_dir, MODULE_FILE)
        if os.path.exists(self.model_file):
            raise RuntimeError(
                'File `{MODULE_FILE}` is already exists in src dir.'.format(
                    MODULE_FILE))

L
Leowolfking 已提交
93
        with open(self.model_file, 'w', encoding='utf-8') as fp:
走神的阿圆's avatar
走神的阿圆 已提交
94 95 96 97 98 99 100 101 102 103
            fp.writelines(lines)

    def create_init_py(self):
        # self.init_file = os.path.join(self.dest, INIT_FILE)
        self.init_file = os.path.join(self._tmp_dir, INIT_FILE)
        if os.path.exists(self.init_file):
            return
        shutil.copyfile(os.path.join(TMPL_DIR, 'init_py.tmpl'), self.init_file)

    def create_serving_demo_py(self):
L
Leowolfking 已提交
104 105 106
        template_file = open(os.path.join(TMPL_DIR, 'serving_demo.tmpl'),
                             'r',
                             encoding='utf-8')
走神的阿圆's avatar
走神的阿圆 已提交
107 108 109 110 111 112 113 114 115 116
        tmpl = Template(template_file.read())
        lines = []

        lines.append(tmpl.substitute(MODULE_NAME=self.module))
        # self.serving_file = os.path.join(self.dest, SERVING_FILE)
        self.serving_file = os.path.join(self._tmp_dir, SERVING_FILE)
        if os.path.exists(self.serving_file):
            raise RuntimeError(
                'File `{}` is already exists in src dir.'.format(SERVING_FILE))

L
Leowolfking 已提交
117
        with open(self.serving_file, 'w', encoding='utf-8') as fp:
走神的阿圆's avatar
走神的阿圆 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
            fp.writelines(lines)

    @staticmethod
    def show_help():
        str = "convert --module <module> [--version <version>] --dest dest_dir --src srd_dir\n"
        str += "\tConvert model to PaddleHub-Module.\n"
        str += "--model_dir\n"
        str += "\tDir of model you want to export.\n"
        str += "--module_name:\n"
        str += "\tSet name of module.\n"
        str += "--module_version\n"
        str += "\tSet version of module, default is `1.0.0`.\n"
        str += "--output_dir\n"
        str += "\tDir to save PaddleHub-Module after exporting, default is `.`.\n"
        print(str)

        return

    def execute(self, argv):
        args = self.parser.parse_args()

        if not args.module_name or not args.model_dir:
            ConvertCommand.show_help()
            return False
        self.module = args.module_name
        self.version = args.module_version if args.module_version is not None else '1.0.0'
        self.src = args.model_dir
        self.dest = args.output_dir if args.output_dir is not None else os.path.join(
            '{}_{}'.format(self.module, str(time.time())))

148
        CacheUpdater("hub_convert", self.module, self.version).start()
走神的阿圆's avatar
走神的阿圆 已提交
149 150 151 152 153 154 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
        os.makedirs(self.dest)

        with tmp_dir() as _dir:
            self._tmp_dir = _dir
            self.create_module_py()
            self.create_init_py()
            self.create_serving_demo_py()
            self.create_module_tar()

        print('The converted module is stored in `{}`.'.format(self.dest))

        return True

    def run(self, module, version, src, dest):

        self.module = module
        self.version = version
        self.src = src
        self.dest = dest

        os.makedirs(self.dest)

        with tmp_dir() as _dir:
            self._tmp_dir = _dir
            self.create_module_py()
            self.create_init_py()
            self.create_serving_demo_py()
            self.create_module_tar()

        return True


command = ConvertCommand.instance()

if __name__ == '__main__':
    command.run('test_module_name', '1.1.1', './new_model', './new_module')