tools.py 3.8 KB
Newer Older
1
# Copyright 2020 Huawei Technologies Co., Ltd
G
gaocongli 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#
# 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.
# ============================================================================
"""
Description: This file is used for some common util.
"""
import io
import os
import shutil
import time
22 23
import json

G
gaocongli 已提交
24
from urllib.parse import urlencode
25

G
gaocongli 已提交
26 27
import numpy as np
from PIL import Image
28

G
gaocongli 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
from mindinsight.datavisual.common.enums import DataManagerStatus


def get_url(url, params):
    """
    Concatenate the URL and params.

    Args:
        url (str): A link requested. For example, http://example.com.
        params (dict): A dict consists of params. For example, {'offset': 1, 'limit':'100}.

    Returns:
        str, like http://example.com?offset=1&limit=100

    """

    return url + '?' + urlencode(params)


def delete_files_or_dirs(path_list):
    """Delete files or dirs in path_list."""
    for path in path_list:
        if os.path.isdir(path):
            shutil.rmtree(path)
        else:
            os.remove(path)


def check_loading_done(data_manager, time_limit=15, first_sleep_time=0):
    """If loading data for more than `time_limit` seconds, exit."""
    if first_sleep_time > 0:
        time.sleep(first_sleep_time)
    start_time = time.time()
62
    while data_manager.status not in (DataManagerStatus.DONE.value, DataManagerStatus.INVALID.value):
G
gaocongli 已提交
63 64 65 66 67
        time_used = time.time() - start_time
        if time_used > time_limit:
            break
        time.sleep(0.1)
        continue
68
    return bool(data_manager.status == DataManagerStatus.DONE.value)
G
gaocongli 已提交
69 70 71 72 73 74 75 76


def get_image_tensor_from_bytes(image_string):
    """Get image tensor from bytes."""
    img = Image.open(io.BytesIO(image_string))
    image_tensor = np.array(img)

    return image_tensor
77 78 79 80 81 82 83


def compare_result_with_file(result, expected_file_path):
    """Compare result with file which contain the expected results."""
    with open(expected_file_path, 'r') as file:
        expected_results = json.load(file)
        assert result == expected_results
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


def deal_float_for_dict(res: dict, expected_res: dict):
    """
    Deal float rounded to five decimals in dict.

    For example:
        res:{
                "model_lineages": {
                    "metric": {"acc": 0.1234561}
                }
            }
        expected_res:
            {
                "model_lineages": {
                    "metric": {"acc": 0.1234562}
                }
            }
    After:
        res:{
                "model_lineages": {
                    "metric": {"acc": 0.12346}
                }
            }
        expected_res:
            {
                "model_lineages": {
                    "metric": {"acc": 0.12346}
                }
            }

    Args:
        res (dict): e.g.
            {
                "model_lineages": {
                    "metric": {"acc": 0.1234561}
                }
            }
        expected_res (dict):
            {
                "model_lineages": {
                    "metric": {"acc": 0.1234562}
                }
            }


    """
    decimal_num = 5
    for key in res:
        value = res[key]
        expected_value = expected_res[key]
        if isinstance(value, dict):
            deal_float_for_dict(value, expected_value)
        elif isinstance(value, float):
            res[key] = round(value, decimal_num)
            expected_res[key] = round(expected_value, decimal_num)