app_single.py 17.5 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
shenyuhan 已提交
15
from paddlehub.serving.model_service.model_manage import default_module_manager
走神的阿圆's avatar
走神的阿圆 已提交
16 17 18 19 20
from paddlehub.common import utils
import time
import os
import base64
import logging
走神的阿圆's avatar
走神的阿圆 已提交
21
import shutil
走神的阿圆's avatar
走神的阿圆 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

cv_module_method = {
    "vgg19_imagenet": "predict_classification",
    "vgg16_imagenet": "predict_classification",
    "vgg13_imagenet": "predict_classification",
    "vgg11_imagenet": "predict_classification",
    "shufflenet_v2_imagenet": "predict_classification",
    "se_resnext50_32x4d_imagenet": "predict_classification",
    "se_resnext101_32x4d_imagenet": "predict_classification",
    "resnet_v2_50_imagenet": "predict_classification",
    "resnet_v2_34_imagenet": "predict_classification",
    "resnet_v2_18_imagenet": "predict_classification",
    "resnet_v2_152_imagenet": "predict_classification",
    "resnet_v2_101_imagenet": "predict_classification",
    "pnasnet_imagenet": "predict_classification",
    "nasnet_imagenet": "predict_classification",
    "mobilenet_v2_imagenet": "predict_classification",
    "googlenet_imagenet": "predict_classification",
    "alexnet_imagenet": "predict_classification",
    "yolov3_coco2017": "predict_object_detection",
    "ultra_light_fast_generic_face_detector_1mb_640":
    "predict_object_detection",
    "ultra_light_fast_generic_face_detector_1mb_320":
    "predict_object_detection",
    "ssd_mobilenet_v1_pascal": "predict_object_detection",
    "pyramidbox_face_detection": "predict_object_detection",
    "faster_rcnn_coco2017": "predict_object_detection",
    "cyclegan_cityscapes": "predict_gan",
    "deeplabv3p_xception65_humanseg": "predict_semantic_segmentation",
走神的阿圆's avatar
走神的阿圆 已提交
51 52 53
    "ace2p": "predict_semantic_segmentation",
    "pyramidbox_lite_server_mask": "predict_mask",
    "pyramidbox_lite_mobile_mask": "predict_mask"
走神的阿圆's avatar
走神的阿圆 已提交
54 55 56
}


S
shenyuhan 已提交
57
def predict_nlp(module, input_text, req_id, batch_size, extra=None):
走神的阿圆's avatar
走神的阿圆 已提交
58 59 60
    method_name = module.desc.attr.map.data['default_signature'].s
    predict_method = getattr(module, method_name)
    try:
S
shenyuhan 已提交
61 62 63
        data = input_text
        if module.name == "lac" and extra.get("user_dict", []) != []:
            res = predict_method(
64
                data=data,
S
shenyuhan 已提交
65
                user_dict=extra.get("user_dict", [])[0],
66 67
                use_gpu=use_gpu,
                batch_size=batch_size)
S
shenyuhan 已提交
68 69 70
        else:
            res = predict_method(
                data=data, use_gpu=use_gpu, batch_size=batch_size)
走神的阿圆's avatar
走神的阿圆 已提交
71 72 73
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
S
shenyuhan 已提交
74 75 76 77 78 79 80
        return {"results": "Please check data format!"}
    finally:
        user_dict = extra.get("user_dict", [])
        for item in user_dict:
            if os.path.exists(item):
                os.remove(item)
    return {"results": res}
走神的阿圆's avatar
走神的阿圆 已提交
81 82


S
shenyuhan 已提交
83
def predict_classification(module, input_img, id, batch_size, extra={}):
走神的阿圆's avatar
走神的阿圆 已提交
84 85 86 87 88
    global use_gpu
    method_name = module.desc.attr.map.data['default_signature'].s
    predict_method = getattr(module, method_name)
    try:
        input_img = {"image": input_img}
89 90
        results = predict_method(
            data=input_img, use_gpu=use_gpu, batch_size=batch_size)
走神的阿圆's avatar
走神的阿圆 已提交
91 92 93 94
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
        return {"result": "Please check data format!"}
S
shenyuhan 已提交
95 96 97 98
    finally:
        for item in input_img["image"]:
            if os.path.exists(item):
                os.remove(item)
走神的阿圆's avatar
走神的阿圆 已提交
99 100 101
    return results


102
def predict_gan(module, input_img, id, batch_size, extra={}):
走神的阿圆's avatar
走神的阿圆 已提交
103 104 105 106 107
    output_folder = module.name.split("_")[0] + "_" + "output"
    global use_gpu
    method_name = module.desc.attr.map.data['default_signature'].s
    predict_method = getattr(module, method_name)
    try:
S
shenyuhan 已提交
108
        extra.update({"image": input_img})
走神的阿圆's avatar
走神的阿圆 已提交
109
        input_img = {"image": input_img}
110
        results = predict_method(
S
shenyuhan 已提交
111
            data=extra, use_gpu=use_gpu, batch_size=batch_size)
走神的阿圆's avatar
走神的阿圆 已提交
112 113 114 115
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
        return {"result": "Please check data format!"}
S
shenyuhan 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    finally:
        base64_list = []
        results_pack = []
        input_img = input_img.get("image", [])
        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)
走神的阿圆's avatar
走神的阿圆 已提交
135 136 137
    return results_pack


走神的阿圆's avatar
走神的阿圆 已提交
138 139 140 141 142 143 144 145 146 147 148 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 185 186 187 188 189 190
def predict_mask(module, input_img, id, batch_size, extra=None, r_img=False):
    output_folder = "detection_result"
    global use_gpu
    method_name = module.desc.attr.map.data['default_signature'].s
    predict_method = getattr(module, method_name)
    try:
        data = {}
        if input_img is not None:
            input_img = {"image": input_img}
            data.update(input_img)
        if extra is not None:
            data.update(extra)
            r_img = True if "r_img" in extra.keys() else False
        results = predict_method(
            data=data, use_gpu=use_gpu, batch_size=batch_size)
        results = utils.handle_mask_results(results)
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
        return {"result": "Please check data format!"}
    finally:
        base64_list = []
        results_pack = []
        if input_img is not None:
            if r_img is False:
                shutil.rmtree(output_folder)
                for index in range(len(results)):
                    results[index]["path"] = ""
                results_pack = results
            else:
                input_img = input_img.get("image", [])
                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 + "_", "") 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))
        else:
            results_pack = results

    return results_pack


S
shenyuhan 已提交
191
def predict_object_detection(module, input_img, id, batch_size, extra={}):
走神的阿圆's avatar
走神的阿圆 已提交
192
    output_folder = "detection_result"
走神的阿圆's avatar
走神的阿圆 已提交
193 194 195 196 197
    global use_gpu
    method_name = module.desc.attr.map.data['default_signature'].s
    predict_method = getattr(module, method_name)
    try:
        input_img = {"image": input_img}
198 199
        results = predict_method(
            data=input_img, use_gpu=use_gpu, batch_size=batch_size)
走神的阿圆's avatar
走神的阿圆 已提交
200 201 202 203
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
        return {"result": "Please check data format!"}
S
shenyuhan 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    finally:
        base64_list = []
        results_pack = []
        input_img = input_img.get("image", [])
        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))
走神的阿圆's avatar
走神的阿圆 已提交
222 223 224
    return results_pack


S
shenyuhan 已提交
225
def predict_semantic_segmentation(module, input_img, id, batch_size, extra={}):
走神的阿圆's avatar
走神的阿圆 已提交
226 227 228 229 230 231
    output_folder = module.name.split("_")[-1] + "_" + "output"
    global use_gpu
    method_name = module.desc.attr.map.data['default_signature'].s
    predict_method = getattr(module, method_name)
    try:
        input_img = {"image": input_img}
232 233
        results = predict_method(
            data=input_img, use_gpu=use_gpu, batch_size=batch_size)
走神的阿圆's avatar
走神的阿圆 已提交
234 235 236 237
    except Exception as err:
        curr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(curr, " - ", err)
        return {"result": "Please check data format!"}
S
shenyuhan 已提交
238 239 240 241 242
    finally:
        base64_list = []
        results_pack = []
        input_img = input_img.get("image", [])
        for index in range(len(input_img)):
走神的阿圆's avatar
走神的阿圆 已提交
243
            # special
S
shenyuhan 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
            item = input_img[index]
            output_file_path = ""
            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)
走神的阿圆's avatar
走神的阿圆 已提交
262 263 264
    return results_pack


265 266 267 268 269 270 271 272 273
def create_app(init_flag=False, configs=None):
    if init_flag is False:
        if configs is None:
            raise RuntimeError("Lack of necessary configs.")
        global use_gpu, time_out
        time_out = 60
        use_gpu = configs.get("use_gpu", False)
        config_with_file(configs.get("modules_info", []))

走神的阿圆's avatar
走神的阿圆 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    app_instance = Flask(__name__)
    app_instance.config["JSON_AS_ASCII"] = False
    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():
        global nlp_module, cv_module
        module_info = {}
        if len(nlp_module) > 0:
            module_info.update({"nlp_module": [{"Choose...": "Choose..."}]})
            for item in nlp_module:
                module_info["nlp_module"].append({item: item})
        if len(cv_module) > 0:
            module_info.update({"cv_module": [{"Choose...": "Choose..."}]})
            for item in cv_module:
                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
shenyuhan 已提交
304 305
        if request.path.split("/")[-1] not in cv_module:
            return {"error": "Module {} is not available.".format(module_name)}
走神的阿圆's avatar
走神的阿圆 已提交
306
        req_id = request.data.get("id")
307
        global use_gpu, batch_size_dict
走神的阿圆's avatar
走神的阿圆 已提交
308
        img_base64 = request.form.getlist("image")
S
shenyuhan 已提交
309 310 311
        extra_info = {}
        for item in list(request.form.keys()):
            extra_info.update({item: request.form.getlist(item)})
走神的阿圆's avatar
走神的阿圆 已提交
312 313 314 315 316 317 318 319

        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
走神的阿圆 已提交
320 321 322 323 324 325 326
        file_name_list = []
        if img_base64 != []:
            for item in img_base64:
                ext = item.split(";")[0].split("/")[-1]
                if ext not in ["jpeg", "jpg", "png"]:
                    return {"result": "Unrecognized file type"}
                filename = req_id + "_" \
走神的阿圆's avatar
走神的阿圆 已提交
327
                           + utils.md5(str(time.time()) + item[0:20]) \
走神的阿圆's avatar
走神的阿圆 已提交
328 329 330 331 332 333 334 335 336 337 338 339
                           + "." \
                           + 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)
S
shenyuhan 已提交
340
        module = default_module_manager.get_module(module_name)
走神的阿圆's avatar
走神的阿圆 已提交
341 342 343 344 345 346
        predict_func_name = cv_module_method.get(module_name, "")
        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)
347
        batch_size = batch_size_dict.get(module_name, 1)
走神的阿圆's avatar
走神的阿圆 已提交
348 349 350 351
        if file_name_list == []:
            file_name_list = None
        if extra_info == {}:
            extra_info = None
S
shenyuhan 已提交
352 353
        results = predict_func(module, file_name_list, req_id, batch_size,
                               extra_info)
走神的阿圆's avatar
走神的阿圆 已提交
354 355 356 357 358
        r = {"results": str(results)}
        return r

    @app_instance.route("/predict/text/<module_name>", methods=["POST"])
    def predict_text(module_name):
S
shenyuhan 已提交
359 360
        if request.path.split("/")[-1] not in nlp_module:
            return {"error": "Module {} is not available.".format(module_name)}
走神的阿圆's avatar
走神的阿圆 已提交
361
        req_id = request.data.get("id")
S
shenyuhan 已提交
362 363 364 365 366 367 368 369 370 371
        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
shenyuhan 已提交
372
        module = default_module_manager.get_module(module_name)
S
shenyuhan 已提交
373 374 375 376 377 378 379
        results = predict_nlp(
            module=module,
            input_text=inputs,
            req_id=req_id,
            batch_size=batch_size_dict.get(module_name, 1),
            extra=files)
        return results
走神的阿圆's avatar
走神的阿圆 已提交
380 381 382 383 384

    return app_instance


def config_with_file(configs):
385
    global nlp_module, cv_module, batch_size_dict
走神的阿圆's avatar
走神的阿圆 已提交
386 387
    nlp_module = []
    cv_module = []
388
    batch_size_dict = {}
走神的阿圆's avatar
走神的阿圆 已提交
389 390 391 392 393 394
    for item in configs:
        print(item)
        if item["category"] == "CV":
            cv_module.append(item["module"])
        elif item["category"] == "NLP":
            nlp_module.append(item["module"])
395
        batch_size_dict.update({item["module"]: item["batch_size"]})
S
shenyuhan 已提交
396
        default_module_manager.load_module([item["module"]])
走神的阿圆's avatar
走神的阿圆 已提交
397 398 399 400 401 402 403 404 405 406 407


def run(is_use_gpu=False, configs=None, port=8866, timeout=60):
    global use_gpu, time_out
    time_out = timeout
    use_gpu = is_use_gpu
    if configs is not None:
        config_with_file(configs)
    else:
        print("Start failed cause of missing configuration.")
        return
408 409
    my_app = create_app(init_flag=True)
    my_app.run(host="0.0.0.0", port=port, debug=False, threaded=False)
走神的阿圆's avatar
走神的阿圆 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    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)