app_single.py 21.1 KB
Newer Older
走神的阿圆's avatar
走神的阿圆 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# coding: utf-8
# Copyright (c) 2019  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
from flask import Flask, request, render_template
走神的阿圆's avatar
走神的阿圆 已提交
15 16
from paddlehub.serving.model_service.base_model_service import cv_module_info
from paddlehub.serving.model_service.base_model_service import nlp_module_info
走神的阿圆's avatar
走神的阿圆 已提交
17
from paddlehub.common import utils
走神的阿圆's avatar
走神的阿圆 已提交
18
import functools
走神的阿圆's avatar
走神的阿圆 已提交
19 20 21 22
import time
import os
import base64
import logging
走神的阿圆's avatar
走神的阿圆 已提交
23 24 25
import glob


26 27 28 29
def gen_result(status, msg, data):
    return {"status": status, "msg": msg, "results": data}


走神的阿圆's avatar
走神的阿圆 已提交
30 31 32
def predict_v2(module_info, input):
    serving_method_name = module_info["method_name"]
    serving_method = getattr(module_info["module"], serving_method_name)
走神的阿圆's avatar
走神的阿圆 已提交
33
    predict_args = module_info["predict_args"].copy()
走神的阿圆's avatar
走神的阿圆 已提交
34 35 36 37 38
    predict_args.update({"data": input})

    for item in serving_method.__code__.co_varnames:
        if item in module_info.keys():
            predict_args.update({item: module_info[item]})
39 40 41 42 43 44 45
    try:
        output = serving_method(**predict_args)
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
        return gen_result("-1", "Please check data format!", "")
    return gen_result("0", "", output)
走神的阿圆's avatar
走神的阿圆 已提交
46 47


走神的阿圆's avatar
走神的阿圆 已提交
48 49 50
def predict_v2_advanced(module_info, input):
    serving_method_name = module_info["method_name"]
    serving_method = getattr(module_info["module"], serving_method_name)
走神的阿圆's avatar
走神的阿圆 已提交
51
    predict_args = module_info["predict_args"].copy()
走神的阿圆's avatar
走神的阿圆 已提交
52 53 54 55 56
    predict_args.update(input)

    for item in serving_method.__code__.co_varnames:
        if item in module_info.keys():
            predict_args.update({item: module_info[item]})
57 58 59 60 61 62 63
    try:
        output = serving_method(**predict_args)
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
        return gen_result("-1", "Please check data format!", "")
    return gen_result("0", "", output)
走神的阿圆's avatar
走神的阿圆 已提交
64 65


走神的阿圆's avatar
走神的阿圆 已提交
66 67 68 69
def predict_nlp(module_info, input_text, req_id, extra=None):
    method_name = module_info["method_name"]
    predict_method = getattr(module_info["module"], method_name)

70 71
    predict_args = module_info["predict_args"].copy()
    predict_args.update({"data": input_text})
走神的阿圆's avatar
走神的阿圆 已提交
72 73 74 75 76 77 78 79 80 81
    if isinstance(predict_method, functools.partial):
        predict_method = predict_method.func
        predict_args.update({"sign_name": method_name})

    for item in predict_method.__code__.co_varnames:
        if item in module_info.keys():
            predict_args.update({item: module_info[item]})

    if module_info["name"] == "lac" and extra.get("user_dict", []) != []:
        predict_args.update({"user_dict": extra.get("user_dict", [])[0]})
82

走神的阿圆's avatar
走神的阿圆 已提交
83
    try:
走神的阿圆's avatar
走神的阿圆 已提交
84
        res = predict_method(**predict_args)
走神的阿圆's avatar
走神的阿圆 已提交
85 86 87
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
88
        return gen_result("-1", "Please check data format!", "")
S
shenyuhan 已提交
89 90 91 92 93
    finally:
        user_dict = extra.get("user_dict", [])
        for item in user_dict:
            if os.path.exists(item):
                os.remove(item)
94
    return gen_result("0", "", res)
走神的阿圆's avatar
走神的阿圆 已提交
95 96


走神的阿圆's avatar
走神的阿圆 已提交
97 98 99
def predict_classification(module_info, input_img, id, extra={}):
    method_name = module_info["method_name"]
    module = module_info["module"]
走神的阿圆's avatar
走神的阿圆 已提交
100
    predict_method = getattr(module, method_name)
101 102 103

    predict_args = module_info["predict_args"].copy()
    predict_args.update({"data": {"image": input_img}})
走神的阿圆's avatar
走神的阿圆 已提交
104 105 106 107 108 109
    if isinstance(predict_method, functools.partial):
        predict_method = predict_method.func
        predict_args.update({"sign_name": method_name})
    for item in predict_method.__code__.co_varnames:
        if item in module_info.keys():
            predict_args.update({item: module_info[item]})
走神的阿圆's avatar
走神的阿圆 已提交
110
    try:
走神的阿圆's avatar
走神的阿圆 已提交
111
        results = predict_method(**predict_args)
走神的阿圆's avatar
走神的阿圆 已提交
112 113 114
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
115
        return gen_result("-1", "Please check data format!", "")
S
shenyuhan 已提交
116
    finally:
走神的阿圆's avatar
走神的阿圆 已提交
117
        for item in input_img:
S
shenyuhan 已提交
118 119
            if os.path.exists(item):
                os.remove(item)
120
    return gen_result("0", "", str(results))
走神的阿圆's avatar
走神的阿圆 已提交
121 122


走神的阿圆's avatar
走神的阿圆 已提交
123 124 125
def predict_gan(module_info, input_img, id, extra={}):
    method_name = module_info["method_name"]
    module = module_info["module"]
走神的阿圆's avatar
走神的阿圆 已提交
126
    predict_method = getattr(module, method_name)
127 128 129

    predict_args = module_info["predict_args"].copy()
    predict_args.update({"data": {"image": input_img}})
走神的阿圆's avatar
走神的阿圆 已提交
130 131 132 133 134 135 136 137
    predict_args["data"].update(extra)
    if isinstance(predict_method, functools.partial):
        predict_method = predict_method.func
        predict_args.update({"sign_name": method_name})
    for item in predict_method.__code__.co_varnames:
        if item in module_info.keys():
            predict_args.update({item: module_info[item]})
    results = predict_method(**predict_args)
走神的阿圆's avatar
走神的阿圆 已提交
138
    try:
走神的阿圆's avatar
走神的阿圆 已提交
139
        pass
走神的阿圆's avatar
走神的阿圆 已提交
140 141 142
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
143
        return gen_result("-1", "Please check data format!", "")
S
shenyuhan 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    finally:
        base64_list = []
        results_pack = []
        for index in range(len(input_img)):
            item = input_img[index]
            output_file = results[index].split(" ")[-1]
            with open(output_file, "rb") as fp:
                b_head = "data:image/" + item.split(".")[-1] + ";base64"
                b_body = base64.b64encode(fp.read())
                b_body = str(b_body).replace("b'", "").replace("'", "")
                b_img = b_head + "," + b_body
                base64_list.append(b_img)
                results[index] = results[index].replace(id + "_", "")
                results[index] = {"path": results[index]}
                results[index].update({"base64": b_img})
                results_pack.append(results[index])
            os.remove(item)
            os.remove(output_file)
162
    return gen_result("0", "", str(results_pack))
走神的阿圆's avatar
走神的阿圆 已提交
163 164


165
def predict_mask(module_info, input_img, id, extra=None, r_img=False):
走神的阿圆's avatar
走神的阿圆 已提交
166
    output_folder = "detection_result"
走神的阿圆's avatar
走神的阿圆 已提交
167 168
    method_name = module_info["method_name"]
    module = module_info["module"]
走神的阿圆's avatar
走神的阿圆 已提交
169
    predict_method = getattr(module, method_name)
走神的阿圆's avatar
走神的阿圆 已提交
170 171 172 173 174 175 176
    data_len = len(input_img) if input_img is not None else 0
    data = {}
    if input_img is not None:
        input_img = {"image": input_img}
        data.update(input_img)
    if extra is not None:
        data.update(extra)
177 178 179 180
        r_img = True if "visual_result" in extra.keys() else False

    predict_args = module_info["predict_args"].copy()
    predict_args.update({"data": data})
走神的阿圆's avatar
走神的阿圆 已提交
181 182 183 184 185 186
    if isinstance(predict_method, functools.partial):
        predict_method = predict_method.func
        predict_args.update({"sign_name": method_name})
    for item in predict_method.__code__.co_varnames:
        if item in module_info.keys():
            predict_args.update({item: module_info[item]})
走神的阿圆's avatar
走神的阿圆 已提交
187
    try:
走神的阿圆's avatar
走神的阿圆 已提交
188 189
        results = predict_method(**predict_args)
        results = utils.handle_mask_results(results, data_len)
走神的阿圆's avatar
走神的阿圆 已提交
190 191 192
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
193
        return gen_result("-1", "Please check data format!", "")
走神的阿圆's avatar
走神的阿圆 已提交
194 195 196 197 198 199 200 201
    finally:
        base64_list = []
        results_pack = []
        if input_img is not None:
            if r_img is False:
                for index in range(len(results)):
                    results[index]["path"] = ""
                results_pack = results
走神的阿圆's avatar
走神的阿圆 已提交
202 203 204 205 206
                str_id = id + "*"
                files_deleted = glob.glob(str_id)
                for path in files_deleted:
                    if os.path.exists(path):
                        os.remove(path)
走神的阿圆's avatar
走神的阿圆 已提交
207 208 209 210
            else:
                input_img = input_img.get("image", [])
                for index in range(len(input_img)):
                    item = input_img[index]
走神的阿圆's avatar
走神的阿圆 已提交
211 212
                    file_path = os.path.join(output_folder, item)
                    if not os.path.exists(file_path):
走神的阿圆's avatar
走神的阿圆 已提交
213
                        results_pack.append(results[index])
走神的阿圆's avatar
走神的阿圆 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
                        os.remove(item)
                    else:
                        with open(file_path, "rb") as fp:
                            b_head = "data:image/" + item.split(
                                ".")[-1] + ";base64"
                            b_body = base64.b64encode(fp.read())
                            b_body = str(b_body).replace("b'", "").replace(
                                "'", "")
                            b_img = b_head + "," + b_body
                            base64_list.append(b_img)
                            results[index]["path"] = results[index]["path"].replace(
                                id + "_", "") if results[index]["path"] != "" \
                                else ""

                            results[index].update({"base64": b_img})
                            results_pack.append(results[index])
                        os.remove(item)
                        os.remove(os.path.join(output_folder, item))
走神的阿圆's avatar
走神的阿圆 已提交
232 233 234
        else:
            results_pack = results

235
    return gen_result("0", "", str(results_pack))
走神的阿圆's avatar
走神的阿圆 已提交
236 237


走神的阿圆's avatar
走神的阿圆 已提交
238
def predict_object_detection(module_info, input_img, id, extra={}):
走神的阿圆's avatar
走神的阿圆 已提交
239
    output_folder = "detection_result"
走神的阿圆's avatar
走神的阿圆 已提交
240 241
    method_name = module_info["method_name"]
    module = module_info["module"]
走神的阿圆's avatar
走神的阿圆 已提交
242
    predict_method = getattr(module, method_name)
243 244 245 246

    predict_args = module_info["predict_args"].copy()
    predict_args.update({"data": {"image": input_img}})

走神的阿圆's avatar
走神的阿圆 已提交
247 248 249 250 251 252
    if isinstance(predict_method, functools.partial):
        predict_method = predict_method.func
        predict_args.update({"sign_name": method_name})
    for item in predict_method.__code__.co_varnames:
        if item in module_info.keys():
            predict_args.update({item: module_info[item]})
走神的阿圆's avatar
走神的阿圆 已提交
253
    try:
走神的阿圆's avatar
走神的阿圆 已提交
254
        results = predict_method(**predict_args)
走神的阿圆's avatar
走神的阿圆 已提交
255 256 257
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
258
        return gen_result("-1", "Please check data format!", "")
S
shenyuhan 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    finally:
        base64_list = []
        results_pack = []
        for index in range(len(input_img)):
            item = input_img[index]
            with open(os.path.join(output_folder, item), "rb") as fp:
                b_head = "data:image/" + item.split(".")[-1] + ";base64"
                b_body = base64.b64encode(fp.read())
                b_body = str(b_body).replace("b'", "").replace("'", "")
                b_img = b_head + "," + b_body
                base64_list.append(b_img)
                results[index]["path"] = results[index]["path"].replace(
                    id + "_", "")
                results[index].update({"base64": b_img})
                results_pack.append(results[index])
            os.remove(item)
            os.remove(os.path.join(output_folder, item))
276
    return gen_result("0", "", str(results_pack))
走神的阿圆's avatar
走神的阿圆 已提交
277 278


走神的阿圆's avatar
走神的阿圆 已提交
279 280 281
def predict_semantic_segmentation(module_info, input_img, id, extra={}):
    method_name = module_info["method_name"]
    module = module_info["module"]
走神的阿圆's avatar
走神的阿圆 已提交
282
    predict_method = getattr(module, method_name)
283 284 285 286

    predict_args = module_info["predict_args"].copy()
    predict_args.update({"data": {"image": input_img}})

走神的阿圆's avatar
走神的阿圆 已提交
287 288 289 290 291 292
    if isinstance(predict_method, functools.partial):
        predict_method = predict_method.func
        predict_args.update({"sign_name": method_name})
    for item in predict_method.__code__.co_varnames:
        if item in module_info.keys():
            predict_args.update({item: module_info[item]})
走神的阿圆's avatar
走神的阿圆 已提交
293
    try:
走神的阿圆's avatar
走神的阿圆 已提交
294
        results = predict_method(**predict_args)
走神的阿圆's avatar
走神的阿圆 已提交
295 296 297
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
298
        return gen_result("-1", "Please check data format!", "")
S
shenyuhan 已提交
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    finally:
        base64_list = []
        results_pack = []
        for index in range(len(input_img)):
            item = input_img[index]
            with open(results[index]["processed"], "rb") as fp:
                b_head = "data:image/png;base64"
                b_body = base64.b64encode(fp.read())
                b_body = str(b_body).replace("b'", "").replace("'", "")
                b_img = b_head + "," + b_body
                base64_list.append(b_img)
                output_file_path = results[index]["processed"]
                results[index]["origin"] = results[index]["origin"].replace(
                    id + "_", "")
                results[index]["processed"] = results[index][
                    "processed"].replace(id + "_", "")
                results[index].update({"base64": b_img})
                results_pack.append(results[index])
            os.remove(item)
            if output_file_path != "":
                os.remove(output_file_path)
320
    return gen_result("0", "", str(results_pack))
走神的阿圆's avatar
走神的阿圆 已提交
321 322


323 324 325 326
def create_app(init_flag=False, configs=None):
    if init_flag is False:
        if configs is None:
            raise RuntimeError("Lack of necessary configs.")
走神的阿圆's avatar
走神的阿圆 已提交
327
        config_with_file(configs)
328

走神的阿圆's avatar
走神的阿圆 已提交
329 330
    app_instance = Flask(__name__)
    app_instance.config["JSON_AS_ASCII"] = False
走神的阿圆's avatar
走神的阿圆 已提交
331
    logging.basicConfig()
走神的阿圆's avatar
走神的阿圆 已提交
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    gunicorn_logger = logging.getLogger('gunicorn.error')
    app_instance.logger.handlers = gunicorn_logger.handlers
    app_instance.logger.setLevel(gunicorn_logger.level)

    @app_instance.route("/", methods=["GET", "POST"])
    def index():
        return render_template("main.html")

    @app_instance.before_request
    def before_request():
        request.data = {"id": utils.md5(request.remote_addr + str(time.time()))}

    @app_instance.route("/get/modules", methods=["GET", "POST"])
    def get_modules_info():
        module_info = {}
走神的阿圆's avatar
走神的阿圆 已提交
347
        if len(nlp_module_info.nlp_modules) > 0:
走神的阿圆's avatar
走神的阿圆 已提交
348
            module_info.update({"nlp_module": [{"Choose...": "Choose..."}]})
走神的阿圆's avatar
走神的阿圆 已提交
349
            for item in nlp_module_info.nlp_modules:
走神的阿圆's avatar
走神的阿圆 已提交
350
                module_info["nlp_module"].append({item: item})
走神的阿圆's avatar
走神的阿圆 已提交
351
        if len(cv_module_info.cv_modules) > 0:
走神的阿圆's avatar
走神的阿圆 已提交
352
            module_info.update({"cv_module": [{"Choose...": "Choose..."}]})
走神的阿圆's avatar
走神的阿圆 已提交
353
            for item in cv_module_info.cv_modules:
走神的阿圆's avatar
走神的阿圆 已提交
354 355 356 357 358
                module_info["cv_module"].append({item: item})
        return {"module_info": module_info}

    @app_instance.route("/predict/image/<module_name>", methods=["POST"])
    def predict_image(module_name):
走神的阿圆's avatar
走神的阿圆 已提交
359
        if request.path.split("/")[-1] not in cv_module_info.modules_info:
S
shenyuhan 已提交
360
            return {"error": "Module {} is not available.".format(module_name)}
走神的阿圆's avatar
走神的阿圆 已提交
361 362 363 364 365 366 367 368 369 370
        module_info = cv_module_info.get_module_info(module_name)
        if module_info["code_version"] == "v2":
            results = {}
            # results = predict_v2(module_info, inputs)
            results.update({
                "Warnning":
                "This usage is out of date, please "
                "use 'application/json' as "
                "content-type to post to "
                "/predict/%s. See "
371
                "'https://github.com/PaddlePaddle/PaddleHub/blob/release/v1.6/docs/tutorial/serving.md' for more details."
走神的阿圆's avatar
走神的阿圆 已提交
372 373
                % (module_name)
            })
374
            return gen_result("-1", results, "")
走神的阿圆's avatar
走神的阿圆 已提交
375 376
        req_id = request.data.get("id")
        img_base64 = request.form.getlist("image")
S
shenyuhan 已提交
377 378 379
        extra_info = {}
        for item in list(request.form.keys()):
            extra_info.update({item: request.form.getlist(item)})
走神的阿圆's avatar
走神的阿圆 已提交
380 381 382 383 384 385 386 387

        for key in extra_info.keys():
            if isinstance(extra_info[key], list):
                extra_info[key] = utils.base64s_to_cvmats(
                    eval(extra_info[key][0])["b64s"]) if isinstance(
                        extra_info[key][0], str
                    ) and "b64s" in extra_info[key][0] else extra_info[key]

走神的阿圆's avatar
走神的阿圆 已提交
388 389 390 391 392
        file_name_list = []
        if img_base64 != []:
            for item in img_base64:
                ext = item.split(";")[0].split("/")[-1]
                if ext not in ["jpeg", "jpg", "png"]:
393
                    return gen_result("-1", "Unrecognized file type", "")
走神的阿圆's avatar
走神的阿圆 已提交
394
                filename = req_id + "_" \
走神的阿圆's avatar
走神的阿圆 已提交
395
                           + utils.md5(str(time.time()) + item[0:20]) \
走神的阿圆's avatar
走神的阿圆 已提交
396 397 398 399 400 401 402 403 404 405 406 407
                           + "." \
                           + ext
                img_data = base64.b64decode(item.split(',')[-1])
                file_name_list.append(filename)
                with open(filename, "wb") as fp:
                    fp.write(img_data)
        else:
            file = request.files.getlist("image")
            for item in file:
                file_name = req_id + "_" + item.filename
                item.save(file_name)
                file_name_list.append(file_name)
408

走神的阿圆's avatar
走神的阿圆 已提交
409 410
        module = module_info["module"]
        predict_func_name = cv_module_info.cv_module_method.get(module_name, "")
走神的阿圆's avatar
走神的阿圆 已提交
411 412 413 414 415
        if predict_func_name != "":
            predict_func = eval(predict_func_name)
        else:
            module_type = module.type.split("/")[-1].replace("-", "_").lower()
            predict_func = eval("predict_" + module_type)
走神的阿圆's avatar
走神的阿圆 已提交
416 417 418 419
        if file_name_list == []:
            file_name_list = None
        if extra_info == {}:
            extra_info = None
走神的阿圆's avatar
走神的阿圆 已提交
420
        results = predict_func(module_info, file_name_list, req_id, extra_info)
421 422

        return results
走神的阿圆's avatar
走神的阿圆 已提交
423 424 425

    @app_instance.route("/predict/text/<module_name>", methods=["POST"])
    def predict_text(module_name):
走神的阿圆's avatar
走神的阿圆 已提交
426
        if request.path.split("/")[-1] not in nlp_module_info.nlp_modules:
S
shenyuhan 已提交
427
            return {"error": "Module {} is not available.".format(module_name)}
走神的阿圆's avatar
走神的阿圆 已提交
428 429
        module_info = nlp_module_info.get_module_info(module_name)
        if module_info["code_version"] == "v2":
S
Steffy-zxf 已提交
430
            results = "This usage is out of date, please use 'application/json' as content-type to post to /predict/%s. See 'https://github.com/PaddlePaddle/PaddleHub/blob/release/v1.6/docs/tutorial/serving.md' for more details." % (
431 432
                module_name)
            return gen_result("-1", results, "")
走神的阿圆's avatar
走神的阿圆 已提交
433
        req_id = request.data.get("id")
S
shenyuhan 已提交
434 435 436 437 438 439 440 441 442 443
        inputs = {}
        for item in list(request.form.keys()):
            inputs.update({item: request.form.getlist(item)})
        files = {}
        for file_key in list(request.files.keys()):
            files[file_key] = []
            for file in request.files.getlist(file_key):
                file_name = req_id + "_" + file.filename
                files[file_key].append(file_name)
                file.save(file_name)
走神的阿圆's avatar
走神的阿圆 已提交
444

走神的阿圆's avatar
走神的阿圆 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457
        results = predict_nlp(
            module_info=module_info,
            input_text=inputs,
            req_id=req_id,
            extra=files)
        return results

    @app_instance.route("/predict/<module_name>", methods=["POST"])
    def predict_modulev2(module_name):
        if module_name in nlp_module_info.nlp_modules:
            module_info = nlp_module_info.get_module_info(module_name)
        elif module_name in cv_module_info.cv_modules:
            module_info = cv_module_info.get_module_info(module_name)
走神的阿圆's avatar
走神的阿圆 已提交
458
        else:
459 460
            msg = "Module {} is not available.".format(module_name)
            return gen_result("-1", msg, "")
走神的阿圆's avatar
走神的阿圆 已提交
461
        inputs = request.json
462
        if inputs is None:
S
Steffy-zxf 已提交
463
            results = "This usage is out of date, please use 'application/json' as content-type to post to /predict/%s. See 'https://github.com/PaddlePaddle/PaddleHub/blob/release/v1.6/docs/tutorial/serving.md' for more details." % (
464 465 466
                module_name)
            return gen_result("-1", results, "")

走神的阿圆's avatar
走神的阿圆 已提交
467
        results = predict_v2_advanced(module_info, inputs)
S
shenyuhan 已提交
468
        return results
走神的阿圆's avatar
走神的阿圆 已提交
469 470 471 472 473

    return app_instance


def config_with_file(configs):
走神的阿圆's avatar
走神的阿圆 已提交
474 475 476 477 478 479 480 481 482
    for key, value in configs.items():
        if "CV" == value["category"]:
            cv_module_info.add_module(key, {key: value})
        elif "NLP" == value["category"]:
            nlp_module_info.add_module(key, {key: value})
        print(key, "==", value["version"])


def run(configs=None, port=8866):
走神的阿圆's avatar
走神的阿圆 已提交
483 484 485 486 487
    if configs is not None:
        config_with_file(configs)
    else:
        print("Start failed cause of missing configuration.")
        return
488 489
    my_app = create_app(init_flag=True)
    my_app.run(host="0.0.0.0", port=port, debug=False, threaded=False)
走神的阿圆's avatar
走神的阿圆 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    print("PaddleHub-Serving has been stopped.")


if __name__ == "__main__":
    configs = [{
        'category': 'NLP',
        u'queue_size': 20,
        u'version': u'1.0.0',
        u'module': 'lac',
        u'batch_size': 20
    },
               {
                   'category': 'NLP',
                   u'queue_size': 20,
                   u'version': u'1.0.0',
                   u'module': 'senta_lstm',
                   u'batch_size': 20
               },
               {
                   'category': 'CV',
                   u'queue_size': 20,
                   u'version': u'1.0.0',
                   u'module': 'yolov3_coco2017',
                   u'batch_size': 20
               },
               {
                   'category': 'CV',
                   u'queue_size': 20,
                   u'version': u'1.0.0',
                   u'module': 'faster_rcnn_coco2017',
                   u'batch_size': 20
               }]
    run(is_use_gpu=False, configs=configs)