utils.py 8.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
W
wuzewu 已提交
25

W
wuzewu 已提交
26
import paddle.fluid as fluid
W
wuzewu 已提交
27
import six
W
wuzewu 已提交
28 29 30 31

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

W
wuzewu 已提交
32

W
wuzewu 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
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)


54 55 56 57 58 59 60 61
def get_platform():
    return platform.platform()


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


W
wuzewu 已提交
62 63 64 65 66 67
def to_list(input):
    if not isinstance(input, list):
        if not isinstance(input, tuple):
            input = [input]

    return input
W
wuzewu 已提交
68 69


W
wuzewu 已提交
70 71 72 73 74
def mkdir(path):
    """ the same as the shell command mkdir -p "
    """
    if not os.path.exists(path):
        os.makedirs(path)
75 76


77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
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()


94 95 96 97 98 99 100 101 102 103 104 105
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 已提交
106 107
def get_pykey(key, keyed_type):
    if keyed_type == module_desc_pb2.BOOLEAN:
W
wuzewu 已提交
108
        return key == "True"
W
wuzewu 已提交
109 110 111 112 113 114 115 116 117
    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 已提交
118
def from_pyobj_to_module_attr(pyobj, module_attr, obj_filter=None):
W
wuzewu 已提交
119 120
    if obj_filter and obj_filter(pyobj):
        return
121
    if isinstance(pyobj, bool):
W
wuzewu 已提交
122 123
        module_attr.type = module_desc_pb2.BOOLEAN
        module_attr.b = pyobj
W
wuzewu 已提交
124
    elif isinstance(pyobj, six.integer_types):
W
wuzewu 已提交
125 126
        module_attr.type = module_desc_pb2.INT
        module_attr.i = pyobj
W
wuzewu 已提交
127 128 129 130
    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 已提交
131 132
        module_attr.type = module_desc_pb2.STRING
        module_attr.s = pyobj
133
    elif isinstance(pyobj, float):
W
wuzewu 已提交
134 135
        module_attr.type = module_desc_pb2.FLOAT
        module_attr.f = pyobj
136
    elif isinstance(pyobj, list) or isinstance(pyobj, tuple):
W
wuzewu 已提交
137
        module_attr.type = module_desc_pb2.LIST
138
        for index, obj in enumerate(pyobj):
W
wuzewu 已提交
139 140
            from_pyobj_to_module_attr(obj, module_attr.list.data[str(index)],
                                      obj_filter)
141
    elif isinstance(pyobj, set):
W
wuzewu 已提交
142
        module_attr.type = module_desc_pb2.SET
143
        for index, obj in enumerate(list(pyobj)):
W
wuzewu 已提交
144 145
            from_pyobj_to_module_attr(obj, module_attr.set.data[str(index)],
                                      obj_filter)
146
    elif isinstance(pyobj, dict):
W
wuzewu 已提交
147
        module_attr.type = module_desc_pb2.MAP
148
        for key, value in pyobj.items():
W
wuzewu 已提交
149 150 151
            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)
152
    elif isinstance(pyobj, type(None)):
W
wuzewu 已提交
153
        module_attr.type = module_desc_pb2.NONE
154
    else:
W
wuzewu 已提交
155 156
        module_attr.type = module_desc_pb2.OBJECT
        module_attr.name = str(pyobj.__class__.__name__)
W
wuzewu 已提交
157 158
        if not hasattr(pyobj, "__dict__"):
            logger.warning(
W
wuzewu 已提交
159
                "python obj %s has not __dict__ attr" % module_attr.name)
W
wuzewu 已提交
160
            return
161
        for key, value in pyobj.__dict__.items():
W
wuzewu 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
            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:
177
        result = []
W
wuzewu 已提交
178
        for index in range(len(module_attr.list.data)):
179
            result.append(
W
wuzewu 已提交
180 181
                from_module_attr_to_pyobj(module_attr.list.data[str(index)]))
    elif module_attr.type == module_desc_pb2.SET:
182
        result = set()
W
wuzewu 已提交
183
        for index in range(len(module_attr.set.data)):
184
            result.add(
W
wuzewu 已提交
185 186
                from_module_attr_to_pyobj(module_attr.set.data[str(index)]))
    elif module_attr.type == module_desc_pb2.MAP:
187
        result = {}
W
wuzewu 已提交
188 189 190 191
        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:
192
        result = None
W
wuzewu 已提交
193
    elif module_attr.type == module_desc_pb2.OBJECT:
194
        result = None
W
wuzewu 已提交
195
        logger.warning("can't tran module attr to python object")
196 197
    else:
        result = None
W
wuzewu 已提交
198
        logger.warning("unknown type of module attr")
199 200

    return result
W
wuzewu 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222


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 已提交
223 224 225 226 227 228 229 230 231
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 已提交
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


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
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292


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 "-"