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

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
W
wuzewu 已提交
19

W
wuzewu 已提交
20
import sys
W
wuzewu 已提交
21
import os
Z
Zeyu Chen 已提交
22
import multiprocessing
23
import hashlib
24
import platform
走神的阿圆's avatar
走神的阿圆 已提交
25
import base64
W
wuzewu 已提交
26

W
wuzewu 已提交
27
import paddle.fluid as fluid
W
wuzewu 已提交
28
import six
走神的阿圆's avatar
走神的阿圆 已提交
29 30
import numpy as np
import cv2
W
wuzewu 已提交
31 32 33 34

from paddlehub.module import module_desc_pb2
from paddlehub.common.logger import logger

W
wuzewu 已提交
35

W
wuzewu 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
def version_compare(version1, version2):
    version1 = version1.split(".")
    version2 = version2.split(".")
    num = min(len(version1), len(version2))
    for index in range(num):
        try:
            vn1 = int(version1[index])
        except:
            vn1 = 0
        try:
            vn2 = int(version2[index])
        except:
            vn2 = 0

        if vn1 > vn2:
            return True
        elif vn1 < vn2:
            return False
    return len(version1) > len(version2)


走神的阿圆's avatar
走神的阿圆 已提交
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
def base64s_to_cvmats(base64s):
    for index, value in enumerate(base64s):
        value = bytes(value, encoding="utf8")
        value = base64.b64decode(value)
        value = np.fromstring(value, np.uint8)
        value = cv2.imdecode(value, 1)

        base64s[index] = value
    return base64s


def handle_mask_results(results):
    result = []
    if len(results) <= 0:
        return results
    _id = results[0]["id"]
    _item = {
        "data": [],
        "path": results[0].get("path", ""),
        "id": results[0]["id"]
    }
    for item in results:
        if item["id"] == _id:
            _item["data"].append(item["data"])
        else:
            result.append(_item)
            _id = _id + 1
            _item = {
                "data": [item["data"]],
                "path": item.get("path", ""),
                "id": item.get("id", _id)
            }
    result.append(_item)
    return result


93 94 95 96 97 98 99 100
def get_platform():
    return platform.platform()


def is_windows():
    return get_platform().lower().startswith("windows")


W
wuzewu 已提交
101 102 103 104 105 106
def to_list(input):
    if not isinstance(input, list):
        if not isinstance(input, tuple):
            input = [input]

    return input
W
wuzewu 已提交
107 108


W
wuzewu 已提交
109 110 111 112 113
def mkdir(path):
    """ the same as the shell command mkdir -p "
    """
    if not os.path.exists(path):
        os.makedirs(path)
114 115


116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
def md5_of_file(file):
    md5 = hashlib.md5()
    with open(file, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            md5.update(chunk)

    return md5.hexdigest()


def md5(text):
    if isinstance(text, str):
        text = text.encode("utf8")
    md5 = hashlib.md5()
    md5.update(text)
    return md5.hexdigest()


133 134 135 136 137 138 139 140 141 142 143 144
def get_keyed_type_of_pyobj(pyobj):
    if isinstance(pyobj, bool):
        return module_desc_pb2.BOOLEAN
    elif isinstance(pyobj, int):
        return module_desc_pb2.INT
    elif isinstance(pyobj, str):
        return module_desc_pb2.STRING
    elif isinstance(pyobj, float):
        return module_desc_pb2.FLOAT
    return module_desc_pb2.STRING


W
wuzewu 已提交
145 146
def get_pykey(key, keyed_type):
    if keyed_type == module_desc_pb2.BOOLEAN:
W
wuzewu 已提交
147
        return key == "True"
W
wuzewu 已提交
148 149 150 151 152 153 154 155 156
    elif keyed_type == module_desc_pb2.INT:
        return int(key)
    elif keyed_type == module_desc_pb2.STRING:
        return str(key)
    elif keyed_type == module_desc_pb2.FLOAT:
        return float(key)
    return str(key)


W
wuzewu 已提交
157
def from_pyobj_to_module_attr(pyobj, module_attr, obj_filter=None):
W
wuzewu 已提交
158 159
    if obj_filter and obj_filter(pyobj):
        return
160
    if isinstance(pyobj, bool):
W
wuzewu 已提交
161 162
        module_attr.type = module_desc_pb2.BOOLEAN
        module_attr.b = pyobj
W
wuzewu 已提交
163
    elif isinstance(pyobj, six.integer_types):
W
wuzewu 已提交
164 165
        module_attr.type = module_desc_pb2.INT
        module_attr.i = pyobj
W
wuzewu 已提交
166 167 168 169
    elif isinstance(pyobj, six.text_type):
        module_attr.type = module_desc_pb2.STRING
        module_attr.s = pyobj
    elif isinstance(pyobj, six.binary_type):
W
wuzewu 已提交
170 171
        module_attr.type = module_desc_pb2.STRING
        module_attr.s = pyobj
172
    elif isinstance(pyobj, float):
W
wuzewu 已提交
173 174
        module_attr.type = module_desc_pb2.FLOAT
        module_attr.f = pyobj
175
    elif isinstance(pyobj, list) or isinstance(pyobj, tuple):
W
wuzewu 已提交
176
        module_attr.type = module_desc_pb2.LIST
177
        for index, obj in enumerate(pyobj):
W
wuzewu 已提交
178 179
            from_pyobj_to_module_attr(obj, module_attr.list.data[str(index)],
                                      obj_filter)
180
    elif isinstance(pyobj, set):
W
wuzewu 已提交
181
        module_attr.type = module_desc_pb2.SET
182
        for index, obj in enumerate(list(pyobj)):
W
wuzewu 已提交
183 184
            from_pyobj_to_module_attr(obj, module_attr.set.data[str(index)],
                                      obj_filter)
185
    elif isinstance(pyobj, dict):
W
wuzewu 已提交
186
        module_attr.type = module_desc_pb2.MAP
187
        for key, value in pyobj.items():
W
wuzewu 已提交
188 189 190
            from_pyobj_to_module_attr(value, module_attr.map.data[str(key)],
                                      obj_filter)
            module_attr.map.key_type[str(key)] = get_keyed_type_of_pyobj(key)
191
    elif isinstance(pyobj, type(None)):
W
wuzewu 已提交
192
        module_attr.type = module_desc_pb2.NONE
193
    else:
W
wuzewu 已提交
194 195
        module_attr.type = module_desc_pb2.OBJECT
        module_attr.name = str(pyobj.__class__.__name__)
W
wuzewu 已提交
196 197
        if not hasattr(pyobj, "__dict__"):
            logger.warning(
W
wuzewu 已提交
198
                "python obj %s has not __dict__ attr" % module_attr.name)
W
wuzewu 已提交
199
            return
200
        for key, value in pyobj.__dict__.items():
W
wuzewu 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
            from_pyobj_to_module_attr(value, module_attr.object.data[str(key)],
                                      obj_filter)
            module_attr.object.key_type[str(key)] = get_keyed_type_of_pyobj(key)


def from_module_attr_to_pyobj(module_attr):
    if module_attr.type == module_desc_pb2.BOOLEAN:
        result = module_attr.b
    elif module_attr.type == module_desc_pb2.INT:
        result = module_attr.i
    elif module_attr.type == module_desc_pb2.STRING:
        result = module_attr.s
    elif module_attr.type == module_desc_pb2.FLOAT:
        result = module_attr.f
    elif module_attr.type == module_desc_pb2.LIST:
216
        result = []
W
wuzewu 已提交
217
        for index in range(len(module_attr.list.data)):
218
            result.append(
W
wuzewu 已提交
219 220
                from_module_attr_to_pyobj(module_attr.list.data[str(index)]))
    elif module_attr.type == module_desc_pb2.SET:
221
        result = set()
W
wuzewu 已提交
222
        for index in range(len(module_attr.set.data)):
223
            result.add(
W
wuzewu 已提交
224 225
                from_module_attr_to_pyobj(module_attr.set.data[str(index)]))
    elif module_attr.type == module_desc_pb2.MAP:
226
        result = {}
W
wuzewu 已提交
227 228 229 230
        for key, value in module_attr.map.data.items():
            key = get_pykey(key, module_attr.map.key_type[key])
            result[key] = from_module_attr_to_pyobj(value)
    elif module_attr.type == module_desc_pb2.NONE:
231
        result = None
W
wuzewu 已提交
232
    elif module_attr.type == module_desc_pb2.OBJECT:
233
        result = None
W
wuzewu 已提交
234
        logger.warning("can't tran module attr to python object")
235 236
    else:
        result = None
W
wuzewu 已提交
237
        logger.warning("unknown type of module attr")
238 239

    return result
W
wuzewu 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261


def check_path(path):
    pass


def check_url(url):
    pass


def get_file_ext(file_path):
    return os.path.splitext(file_path)[-1]


def is_csv_file(file_path):
    return get_file_ext(file_path) == ".csv"


def is_yaml_file(file_path):
    return get_file_ext(file_path) == ".yml"


Z
Zeyu Chen 已提交
262 263 264 265 266 267 268 269 270
def get_running_device_info(config):
    if config.use_cuda:
        place = fluid.CUDAPlace(0)
        dev_count = fluid.core.get_cuda_device_count()
    else:
        place = fluid.CPUPlace()
        dev_count = int(os.environ.get('CPU_NUM', multiprocessing.cpu_count()))

    return place, dev_count
W
wuzewu 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296


def get_platform_default_encoding():
    if platform.platform().lower().startswith("windows"):
        return "gbk"
    return "utf8"


def sys_stdin_encoding():
    encoding = sys.stdin.encoding
    if encoding is None:
        encoding = sys.getdefaultencoding()

    if encoding is None:
        encoding = get_platform_default_encoding()
    return encoding


def sys_stdout_encoding():
    encoding = sys.stdout.encoding
    if encoding is None:
        encoding = sys.getdefaultencoding()

    if encoding is None:
        encoding = get_platform_default_encoding()
    return encoding
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331


def version_sum(version):
    """
    get sum(version), eg: version_sum(1.4.5) = 1*100*100*100 + 4*100*100 + 5*100
    :param version: string("1.3.6")
    :return:
    """
    sum = 0
    version_list = version.split(".")
    for i in version_list:
        sum = (sum + int(i)) * 100
    return sum


def sort_version_key(version_a, version_b):
    if version_sum(version_a[1]) > version_sum(version_b[1]):
        return -1
    elif version_sum(version_a[1]) == version_sum(version_b[1]):
        return 0
    else:
        return 1


def strflist_version(version_list):
    version_list = version_list[1:-1].split(",")
    result = ""
    if version_list[0] != "-1.0.0":
        result = ">" + version_list[0]
    if version_list[1] != "99.0.0":
        if result != "":
            result = result + ", " + "<" + version_list[1]
        else:
            result = "<" + version_list[1]
    return result if result != "" else "-"