paddleclas.py 20.5 KB
Newer Older
T
Tingquan Gao 已提交
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
C
chenziheng 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# 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 os
import sys
__dir__ = os.path.dirname(__file__)
T
Tingquan Gao 已提交
18 19 20
sys.path.append(os.path.join(__dir__, ""))
sys.path.append(os.path.join(__dir__, "deploy"))

T
Tingquan Gao 已提交
21 22
import argparse
import shutil
T
Tingquan Gao 已提交
23
import textwrap
T
Tingquan Gao 已提交
24 25 26 27
import tarfile
import requests
import warnings
from functools import partial
T
Tingquan Gao 已提交
28
from difflib import SequenceMatcher
C
chenziheng 已提交
29 30 31 32

import cv2
import numpy as np
from tqdm import tqdm
T
Tingquan Gao 已提交
33 34 35 36 37 38 39 40 41
from prettytable import PrettyTable

from deploy.python.predict_cls import ClsPredictor
from deploy.utils.get_image_list import get_image_list
from deploy.utils import config

from ppcls.arch.backbone import *

__all__ = ["PaddleClas"]
T
Tingquan Gao 已提交
42

C
chenziheng 已提交
43
BASE_DIR = os.path.expanduser("~/.paddleclas/")
T
Tingquan Gao 已提交
44 45 46 47
BASE_INFERENCE_MODEL_DIR = os.path.join(BASE_DIR, "inference_model")
BASE_IMAGES_DIR = os.path.join(BASE_DIR, "images")
BASE_DOWNLOAD_URL = "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/inference/{}_infer.tar"
MODEL_SERIES = {
T
Tingquan Gao 已提交
48 49 50
    "AlexNet": ["AlexNet"],
    "DarkNet": ["DarkNet53"],
    "DeiT": [
T
Tingquan Gao 已提交
51 52 53 54
        "DeiT_base_distilled_patch16_224", "DeiT_base_distilled_patch16_384",
        "DeiT_base_patch16_224", "DeiT_base_patch16_384",
        "DeiT_small_distilled_patch16_224", "DeiT_small_patch16_224",
        "DeiT_tiny_distilled_patch16_224", "DeiT_tiny_patch16_224"
T
Tingquan Gao 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 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 111 112 113 114 115 116 117 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
    ],
    "DenseNet": [
        "DenseNet121", "DenseNet161", "DenseNet169", "DenseNet201",
        "DenseNet264"
    ],
    "DPN": ["DPN68", "DPN92", "DPN98", "DPN107", "DPN131"],
    "EfficientNet": [
        "EfficientNetB0", "EfficientNetB0_small", "EfficientNetB1",
        "EfficientNetB2", "EfficientNetB3", "EfficientNetB4", "EfficientNetB5",
        "EfficientNetB6", "EfficientNetB7"
    ],
    "GhostNet":
    ["GhostNet_x0_5", "GhostNet_x1_0", "GhostNet_x1_3", "GhostNet_x1_3_ssld"],
    "HRNet": [
        "HRNet_W18_C", "HRNet_W30_C", "HRNet_W32_C", "HRNet_W40_C",
        "HRNet_W44_C", "HRNet_W48_C", "HRNet_W64_C", "HRNet_W18_C_ssld",
        "HRNet_W48_C_ssld"
    ],
    "Inception": ["GoogLeNet", "InceptionV3", "InceptionV4"],
    "MobileNetV1": [
        "MobileNetV1_x0_25", "MobileNetV1_x0_5", "MobileNetV1_x0_75",
        "MobileNetV1", "MobileNetV1_ssld"
    ],
    "MobileNetV2": [
        "MobileNetV2_x0_25", "MobileNetV2_x0_5", "MobileNetV2_x0_75",
        "MobileNetV2", "MobileNetV2_x1_5", "MobileNetV2_x2_0",
        "MobileNetV2_ssld"
    ],
    "MobileNetV3": [
        "MobileNetV3_small_x0_35", "MobileNetV3_small_x0_5",
        "MobileNetV3_small_x0_75", "MobileNetV3_small_x1_0",
        "MobileNetV3_small_x1_25", "MobileNetV3_large_x0_35",
        "MobileNetV3_large_x0_5", "MobileNetV3_large_x0_75",
        "MobileNetV3_large_x1_0", "MobileNetV3_large_x1_25",
        "MobileNetV3_small_x1_0_ssld", "MobileNetV3_large_x1_0_ssld"
    ],
    "RegNet": ["RegNetX_4GF"],
    "Res2Net": [
        "Res2Net50_14w_8s", "Res2Net50_26w_4s", "Res2Net50_vd_26w_4s",
        "Res2Net200_vd_26w_4s", "Res2Net101_vd_26w_4s",
        "Res2Net50_vd_26w_4s_ssld", "Res2Net101_vd_26w_4s_ssld",
        "Res2Net200_vd_26w_4s_ssld"
    ],
    "ResNeSt": ["ResNeSt50", "ResNeSt50_fast_1s1x64d"],
    "ResNet": [
        "ResNet18", "ResNet18_vd", "ResNet34", "ResNet34_vd", "ResNet50",
        "ResNet50_vc", "ResNet50_vd", "ResNet50_vd_v2", "ResNet101",
        "ResNet101_vd", "ResNet152", "ResNet152_vd", "ResNet200_vd",
        "ResNet34_vd_ssld", "ResNet50_vd_ssld", "ResNet50_vd_ssld_v2",
        "ResNet101_vd_ssld", "Fix_ResNet50_vd_ssld_v2", "ResNet50_ACNet_deploy"
    ],
    "ResNeXt": [
        "ResNeXt50_32x4d", "ResNeXt50_vd_32x4d", "ResNeXt50_64x4d",
        "ResNeXt50_vd_64x4d", "ResNeXt101_32x4d", "ResNeXt101_vd_32x4d",
        "ResNeXt101_32x8d_wsl", "ResNeXt101_32x16d_wsl",
        "ResNeXt101_32x32d_wsl", "ResNeXt101_32x48d_wsl",
        "Fix_ResNeXt101_32x48d_wsl", "ResNeXt101_64x4d", "ResNeXt101_vd_64x4d",
        "ResNeXt152_32x4d", "ResNeXt152_vd_32x4d", "ResNeXt152_64x4d",
        "ResNeXt152_vd_64x4d"
    ],
    "SENet": [
        "SENet154_vd", "SE_HRNet_W64_C_ssld", "SE_ResNet18_vd",
        "SE_ResNet34_vd", "SE_ResNet50_vd", "SE_ResNeXt50_32x4d",
        "SE_ResNeXt50_vd_32x4d", "SE_ResNeXt101_32x4d"
    ],
    "ShuffleNetV2": [
        "ShuffleNetV2_swish", "ShuffleNetV2_x0_25", "ShuffleNetV2_x0_33",
        "ShuffleNetV2_x0_5", "ShuffleNetV2_x1_0", "ShuffleNetV2_x1_5",
        "ShuffleNetV2_x2_0"
    ],
    "SqueezeNet": ["SqueezeNet1_0", "SqueezeNet1_1"],
    "SwinTransformer": [
        "SwinTransformer_large_patch4_window7_224_22kto1k",
        "SwinTransformer_large_patch4_window12_384_22kto1k",
        "SwinTransformer_base_patch4_window7_224_22kto1k",
        "SwinTransformer_base_patch4_window12_384_22kto1k",
        "SwinTransformer_base_patch4_window12_384",
        "SwinTransformer_base_patch4_window7_224",
        "SwinTransformer_small_patch4_window7_224",
        "SwinTransformer_tiny_patch4_window7_224"
    ],
    "VGG": ["VGG11", "VGG13", "VGG16", "VGG19"],
    "VisionTransformer": [
        "ViT_base_patch16_224", "ViT_base_patch16_384", "ViT_base_patch32_384",
        "ViT_large_patch16_224", "ViT_large_patch16_384",
        "ViT_large_patch32_384", "ViT_small_patch16_224"
    ],
    "Xception": [
        "Xception41", "Xception41_deeplab", "Xception65", "Xception65_deeplab",
        "Xception71"
    ]
C
chenziheng 已提交
146 147 148
}


T
Tingquan Gao 已提交
149 150
class ImageTypeError(Exception):
    """ImageTypeError.
T
Tingquan Gao 已提交
151 152
    """

T
Tingquan Gao 已提交
153
    def __init__(self, message=""):
T
Tingquan Gao 已提交
154 155 156
        super().__init__(message)


T
Tingquan Gao 已提交
157 158 159 160 161 162 163 164
class InputModelError(Exception):
    """InputModelError.
    """

    def __init__(self, message=""):
        super().__init__(message)


T
Tingquan Gao 已提交
165 166 167 168 169 170 171 172 173
def init_config(model_name,
                inference_model_dir,
                use_gpu=True,
                batch_size=1,
                topk=5,
                **kwargs):
    imagenet1k_map_path = os.path.join(
        os.path.abspath(__dir__), "ppcls/utils/imagenet1k_label_list.txt")
    cfg = {
T
Tingquan Gao 已提交
174
        "Global": {
T
Tingquan Gao 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
            "infer_imgs": kwargs["infer_imgs"]
            if "infer_imgs" in kwargs else False,
            "model_name": model_name,
            "inference_model_dir": inference_model_dir,
            "batch_size": batch_size,
            "use_gpu": use_gpu,
            "enable_mkldnn": kwargs["enable_mkldnn"]
            if "enable_mkldnn" in kwargs else False,
            "cpu_num_threads": kwargs["cpu_num_threads"]
            if "cpu_num_threads" in kwargs else 1,
            "enable_benchmark": False,
            "use_fp16": kwargs["use_fp16"] if "use_fp16" in kwargs else False,
            "ir_optim": True,
            "use_tensorrt": kwargs["use_tensorrt"]
            if "use_tensorrt" in kwargs else False,
            "gpu_mem": kwargs["gpu_mem"] if "gpu_mem" in kwargs else 8000,
T
Tingquan Gao 已提交
191 192 193 194 195
            "enable_profile": False
        },
        "PreProcess": {
            "transform_ops": [{
                "ResizeImage": {
T
Tingquan Gao 已提交
196 197
                    "resize_short": kwargs["resize_short"]
                    if "resize_short" in kwargs else 256
T
Tingquan Gao 已提交
198 199 200
                }
            }, {
                "CropImage": {
T
Tingquan Gao 已提交
201 202
                    "size": kwargs["crop_size"]
                    if "crop_size" in kwargs else 224
T
Tingquan Gao 已提交
203 204 205 206 207 208
                }
            }, {
                "NormalizeImage": {
                    "scale": 0.00392157,
                    "mean": [0.485, 0.456, 0.406],
                    "std": [0.229, 0.224, 0.225],
T
Tingquan Gao 已提交
209
                    "order": ''
T
Tingquan Gao 已提交
210 211 212 213 214 215
                }
            }, {
                "ToCHWImage": None
            }]
        },
        "PostProcess": {
T
Tingquan Gao 已提交
216 217 218 219 220
            "main_indicator": "Topk",
            "Topk": {
                "topk": topk,
                "class_id_map_file": imagenet1k_map_path
            }
T
Tingquan Gao 已提交
221 222
        }
    }
T
Tingquan Gao 已提交
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 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    if "save_dir" in kwargs:
        if kwargs["save_dir"] is not None:
            cfg["PostProcess"]["SavePreLabel"] = {
                "save_dir": kwargs["save_dir"]
            }
    if "class_id_map_file" in kwargs:
        if kwargs["class_id_map_file"] is not None:
            cfg["PostProcess"]["Topk"]["class_id_map_file"] = kwargs[
                "class_id_map_file"]

    cfg = config.AttrDict(cfg)
    config.create_attr_dict(cfg)
    return cfg


def args_cfg():
    def str2bool(v):
        return v.lower() in ("true", "t", "1")

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--infer_imgs",
        type=str,
        required=True,
        help="The image(s) to be predicted.")
    parser.add_argument(
        "--model_name", type=str, help="The model name to be used.")
    parser.add_argument(
        "--inference_model_dir",
        type=str,
        help="The directory of model files. Valid when model_name not specifed."
    )
    parser.add_argument(
        "--use_gpu", type=str, default=True, help="Whether use GPU.")
    parser.add_argument("--gpu_mem", type=int, default=8000, help="")
    parser.add_argument(
        "--enable_mkldnn",
        type=str2bool,
        default=False,
        help="Whether use MKLDNN. Valid when use_gpu is False")
    parser.add_argument("--cpu_num_threads", type=int, default=1, help="")
    parser.add_argument(
        "--use_tensorrt", type=str2bool, default=False, help="")
    parser.add_argument("--use_fp16", type=str2bool, default=False, help="")
    parser.add_argument(
        "--batch_size", type=int, default=1, help="Batch size. Default by 1.")
    parser.add_argument(
        "--topk",
        type=int,
        default=5,
        help="Return topk score(s) and corresponding results. Default by 5.")
    parser.add_argument(
        "--class_id_map_file",
        type=str,
        help="The path of file that map class_id and label.")
    parser.add_argument(
        "--save_dir",
        type=str,
        help="The directory to save prediction results as pre-label.")
G
gaotingquan 已提交
282 283 284 285 286 287 288
    parser.add_argument(
        "--resize_short",
        type=int,
        default=256,
        help="Resize according to short size.")
    parser.add_argument(
        "--crop_size", type=int, default=224, help="Centor crop size.")
T
Tingquan Gao 已提交
289 290 291

    args = parser.parse_args()
    return vars(args)
T
Tingquan Gao 已提交
292 293


T
Tingquan Gao 已提交
294
def print_info():
T
Tingquan Gao 已提交
295 296 297
    """Print list of supported models in formatted.
    """
    table = PrettyTable(["Series", "Name"])
T
Tingquan Gao 已提交
298 299 300 301 302
    try:
        sz = os.get_terminal_size()
        width = sz.columns - 30 if sz.columns > 50 else 10
    except OSError:
        width = 100
T
Tingquan Gao 已提交
303 304
    for series in MODEL_SERIES:
        names = textwrap.fill("  ".join(MODEL_SERIES[series]), width=width)
T
Tingquan Gao 已提交
305
        table.add_row([series, names])
T
Tingquan Gao 已提交
306 307 308
    width = len(str(table).split("\n")[0])
    print("{}".format("-" * width))
    print("Models supported by PaddleClas".center(width))
T
Tingquan Gao 已提交
309
    print(table)
T
Tingquan Gao 已提交
310 311
    print("Powered by PaddlePaddle!".rjust(width))
    print("{}".format("-" * width))
T
Tingquan Gao 已提交
312 313 314


def get_model_names():
T
Tingquan Gao 已提交
315 316
    """Get the model names list.
    """
T
Tingquan Gao 已提交
317
    model_names = []
T
Tingquan Gao 已提交
318 319
    for series in MODEL_SERIES:
        model_names += (MODEL_SERIES[series])
T
Tingquan Gao 已提交
320 321 322
    return model_names


T
Tingquan Gao 已提交
323 324
def similar_architectures(name="", names=[], thresh=0.1, topk=10):
    """Find the most similar topk model names.
T
Tingquan Gao 已提交
325 326 327
    """
    scores = []
    for idx, n in enumerate(names):
T
Tingquan Gao 已提交
328
        if n.startswith("__"):
T
Tingquan Gao 已提交
329 330 331 332 333 334 335 336 337
            continue
        score = SequenceMatcher(None, n.lower(), name.lower()).quick_ratio()
        if score > thresh:
            scores.append((idx, score))
    scores.sort(key=lambda x: x[1], reverse=True)
    similar_names = [names[s[0]] for s in scores[:min(topk, len(scores))]]
    return similar_names


C
chenziheng 已提交
338
def download_with_progressbar(url, save_path):
T
Tingquan Gao 已提交
339 340 341 342
    """Download from url with progressbar.
    """
    if os.path.isfile(save_path):
        os.remove(save_path)
C
chenziheng 已提交
343
    response = requests.get(url, stream=True)
T
Tingquan Gao 已提交
344
    total_size_in_bytes = int(response.headers.get("content-length", 0))
C
chenziheng 已提交
345
    block_size = 1024  # 1 Kibibyte
T
Tingquan Gao 已提交
346 347
    progress_bar = tqdm(total=total_size_in_bytes, unit="iB", unit_scale=True)
    with open(save_path, "wb") as file:
C
chenziheng 已提交
348 349 350 351
        for data in response.iter_content(block_size):
            progress_bar.update(len(data))
            file.write(data)
    progress_bar.close()
T
Tingquan Gao 已提交
352 353
    if total_size_in_bytes == 0 or progress_bar.n != total_size_in_bytes or not os.path.isfile(
            save_path):
T
Tingquan Gao 已提交
354
        raise Exception(
T
Tingquan Gao 已提交
355
            f"Something went wrong while downloading file from {url}")
C
chenziheng 已提交
356 357


T
Tingquan Gao 已提交
358 359 360 361 362 363 364
def check_model_file(model_name):
    """Check the model files exist and download and untar when no exist. 
    """
    storage_directory = partial(os.path.join, BASE_INFERENCE_MODEL_DIR,
                                model_name)
    url = BASE_DOWNLOAD_URL.format(model_name)

C
chenziheng 已提交
365
    tar_file_name_list = [
T
Tingquan Gao 已提交
366
        "inference.pdiparams", "inference.pdiparams.info", "inference.pdmodel"
C
chenziheng 已提交
367
    ]
T
Tingquan Gao 已提交
368 369 370 371 372 373 374
    model_file_path = storage_directory("inference.pdmodel")
    params_file_path = storage_directory("inference.pdiparams")
    if not os.path.exists(model_file_path) or not os.path.exists(
            params_file_path):
        tmp_path = storage_directory(url.split("/")[-1])
        print(f"download {url} to {tmp_path}")
        os.makedirs(storage_directory(), exist_ok=True)
C
chenziheng 已提交
375
        download_with_progressbar(url, tmp_path)
T
Tingquan Gao 已提交
376
        with tarfile.open(tmp_path, "r") as tarObj:
C
chenziheng 已提交
377 378 379 380 381 382 383 384
            for member in tarObj.getmembers():
                filename = None
                for tar_file_name in tar_file_name_list:
                    if tar_file_name in member.name:
                        filename = tar_file_name
                if filename is None:
                    continue
                file = tarObj.extractfile(member)
T
Tingquan Gao 已提交
385
                with open(storage_directory(filename), "wb") as f:
C
chenziheng 已提交
386 387
                    f.write(file.read())
        os.remove(tmp_path)
T
Tingquan Gao 已提交
388 389 390 391 392
    if not os.path.exists(model_file_path) or not os.path.exists(
            params_file_path):
        raise Exception(
            f"Something went wrong while praparing the model[{model_name}] files!"
        )
C
chenziheng 已提交
393

T
Tingquan Gao 已提交
394
    return storage_directory()
C
chenziheng 已提交
395

T
Tingquan Gao 已提交
396

C
chenziheng 已提交
397
class PaddleClas(object):
T
Tingquan Gao 已提交
398 399 400
    """PaddleClas.
    """

T
Tingquan Gao 已提交
401
    print_info()
C
chenziheng 已提交
402

T
Tingquan Gao 已提交
403 404 405
    def __init__(self,
                 model_name: str=None,
                 inference_model_dir: str=None,
T
Tingquan Gao 已提交
406 407 408 409
                 use_gpu: bool=True,
                 batch_size: int=1,
                 topk: int=5,
                 **kwargs):
T
Tingquan Gao 已提交
410
        """Init PaddleClas with config.
T
Tingquan Gao 已提交
411

T
Tingquan Gao 已提交
412 413 414
        Args:
            model_name: The model name supported by PaddleClas, default by None. If specified, override config.
            inference_model_dir: The directory that contained model file and params file to be used, default by None. If specified, override config.
G
gaotingquan 已提交
415
            use_gpu: Whether use GPU, default by None. If specified, override config.
T
Tingquan Gao 已提交
416
            batch_size: The batch size to pridict, default by None. If specified, override config.
T
Tingquan Gao 已提交
417
            topk: Return the top k prediction results with the highest score.
T
Tingquan Gao 已提交
418 419
        """
        super().__init__()
T
Tingquan Gao 已提交
420 421
        self._config = init_config(model_name, inference_model_dir, use_gpu,
                                   batch_size, topk, **kwargs)
T
Tingquan Gao 已提交
422 423 424 425 426
        self._check_input_model()
        self.cls_predictor = ClsPredictor(self._config)

    def get_config(self):
        """Get the config.
C
chenziheng 已提交
427
        """
T
Tingquan Gao 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441
        return self._config

    def _check_input_model(self):
        """Check input model name or model files.
        """
        candidate_model_names = get_model_names()
        input_model_name = self._config.Global.get("model_name", None)
        inference_model_dir = self._config.Global.get("inference_model_dir",
                                                      None)
        if input_model_name is not None:
            similar_names = similar_architectures(input_model_name,
                                                  candidate_model_names)
            similar_names_str = ", ".join(similar_names)
            if input_model_name not in candidate_model_names:
T
Tingquan Gao 已提交
442
                err = f"{input_model_name} is not provided by PaddleClas. \nMaybe you want: [{similar_names_str}]. \nIf you want to use your own model, please specify inference_model_dir!"
T
Tingquan Gao 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
                raise InputModelError(err)
            self._config.Global.inference_model_dir = check_model_file(
                input_model_name)
            return
        elif inference_model_dir is not None:
            model_file_path = os.path.join(inference_model_dir,
                                           "inference.pdmodel")
            params_file_path = os.path.join(inference_model_dir,
                                            "inference.pdiparams")
            if not os.path.isfile(model_file_path) or not os.path.isfile(
                    params_file_path):
                err = f"There is no model file or params file in this directory: {inference_model_dir}"
                raise InputModelError(err)
            return
        else:
T
Tingquan Gao 已提交
458
            err = f"Please specify the model name supported by PaddleClas or directory contained model files(inference.pdmodel, inference.pdiparams)."
T
Tingquan Gao 已提交
459 460 461
            raise InputModelError(err)
        return

T
Tingquan Gao 已提交
462 463 464
    def predict(self, input_data, print_pred=False):
        """Predict input_data.

C
chenziheng 已提交
465
        Args:
T
Tingquan Gao 已提交
466
            input_data (str | NumPy.array): The path of image, or the directory containing images, or the URL of image from Internet.
G
gaotingquan 已提交
467
            print_pred (bool, optional): Whether print the prediction result. Defaults to False.
T
Tingquan Gao 已提交
468 469 470 471 472 473 474

        Raises:
            ImageTypeError: Illegal input_data.

        Yields:
            list: The prediction result(s) of input_data by batch_size. For every one image, prediction result(s) is zipped as a dict, that includs topk "class_ids", "scores" and "label_names". The format is as follow:
            [{"class_ids": [...], "scores": [...], "label_names": [...]}, ...]
C
chenziheng 已提交
475
        """
T
Tingquan Gao 已提交
476
        if isinstance(input_data, np.ndarray):
T
Tingquan Gao 已提交
477 478
            outputs = self.cls_predictor.predict(input_data)
            yield self.cls_predictor.postprocess(outputs)
T
Tingquan Gao 已提交
479
        elif isinstance(input_data, str):
T
Tingquan Gao 已提交
480
            if input_data.startswith("http") or input_data.startswith("https"):
T
Tingquan Gao 已提交
481 482 483 484 485 486 487 488 489 490 491 492
                image_storage_dir = partial(os.path.join, BASE_IMAGES_DIR)
                if not os.path.exists(image_storage_dir()):
                    os.makedirs(image_storage_dir())
                image_save_path = image_storage_dir("tmp.jpg")
                download_with_progressbar(input_data, image_save_path)
                input_data = image_save_path
                warnings.warn(
                    f"Image to be predicted from Internet: {input_data}, has been saved to: {image_save_path}"
                )
            image_list = get_image_list(input_data)

            batch_size = self._config.Global.get("batch_size", 1)
T
Tingquan Gao 已提交
493
            topk = self._config.PostProcess.get('topk', 1)
T
Tingquan Gao 已提交
494 495

            img_list = []
T
Tingquan Gao 已提交
496 497 498 499 500
            img_path_list = []
            cnt = 0
            for idx, img_path in enumerate(image_list):
                img = cv2.imread(img_path)
                if img is None:
T
Tingquan Gao 已提交
501 502 503
                    warnings.warn(
                        f"Image file failed to read and has been skipped. The path: {img_path}"
                    )
T
Tingquan Gao 已提交
504
                    continue
T
Tingquan Gao 已提交
505 506 507 508 509 510
                img_list.append(img)
                img_path_list.append(img_path)
                cnt += 1

                if cnt % batch_size == 0 or (idx + 1) == len(image_list):
                    outputs = self.cls_predictor.predict(img_list)
T
Tingquan Gao 已提交
511 512 513
                    preds = self.cls_predictor.postprocess(outputs,
                                                           img_path_list)
                    if print_pred and preds:
G
gaotingquan 已提交
514 515
                        for pred in preds:
                            filename = pred.pop("file_name")
T
Tingquan Gao 已提交
516 517 518
                            pred_str = ", ".join(
                                [f"{k}: {pred[k]}" for k in pred])
                            print(
G
gaotingquan 已提交
519
                                f"filename: {filename}, top-{topk}, {pred_str}")
T
Tingquan Gao 已提交
520

T
Tingquan Gao 已提交
521
                    img_list = []
T
Tingquan Gao 已提交
522
                    img_path_list = []
T
Tingquan Gao 已提交
523
                    yield preds
C
chenziheng 已提交
524
        else:
T
Tingquan Gao 已提交
525 526 527
            err = "Please input legal image! The type of image supported by PaddleClas are: NumPy.ndarray and string of local path or Ineternet URL"
            raise ImageTypeError(err)
        return
C
chenziheng 已提交
528 529


T
Tingquan Gao 已提交
530
# for CLI
C
chenziheng 已提交
531
def main():
T
Tingquan Gao 已提交
532 533 534
    """Function API used for commad line.
    """
    cfg = args_cfg()
T
Tingquan Gao 已提交
535 536 537 538 539
    clas_engine = PaddleClas(**cfg)
    res = clas_engine.predict(cfg["infer_imgs"], print_pred=True)
    for _ in res:
        pass
    print("Predict complete!")
T
Tingquan Gao 已提交
540
    return
C
chenziheng 已提交
541 542


T
Tingquan Gao 已提交
543
if __name__ == "__main__":
C
chenziheng 已提交
544
    main()