You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tools.py 5.3 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """
  16. Description: This file is used for some common util.
  17. """
  18. import io
  19. import json
  20. import os
  21. import shutil
  22. from pathlib import Path
  23. from urllib.parse import urlencode
  24. import yaml
  25. import numpy as np
  26. from PIL import Image
  27. from mindinsight.lineagemgr.common.exceptions.exceptions import LineageParamValueError
  28. def get_url(url, params):
  29. """
  30. Concatenate the URL and params.
  31. Args:
  32. url (str): A link requested. For example, http://example.com.
  33. params (dict): A dict consists of params. For example, {'offset': 1, 'limit': 100}.
  34. Returns:
  35. str, like http://example.com?offset=1&limit=100
  36. """
  37. return url + '?' + urlencode(params)
  38. def delete_files_or_dirs(path_list):
  39. """Delete files or dirs in path_list."""
  40. for path in path_list:
  41. if os.path.isdir(path):
  42. shutil.rmtree(path)
  43. else:
  44. os.remove(path)
  45. def get_image_tensor_from_bytes(image_string):
  46. """Get image tensor from bytes."""
  47. img = Image.open(io.BytesIO(image_string))
  48. image_tensor = np.array(img)
  49. return image_tensor
  50. def compare_result_with_file(result, expected_file_path):
  51. """Compare result with file which contain the expected results."""
  52. with open(expected_file_path, 'r') as file:
  53. expected_results = json.load(file)
  54. assert result == expected_results
  55. def compare_result_with_binary_file(result, expected_file_path):
  56. """Compare result with binary file which contain the expected results."""
  57. with open(expected_file_path, 'rb') as file:
  58. expected_results = file.read()
  59. assert result == expected_results
  60. def deal_float_for_dict(res: dict, expected_res: dict, decimal_num):
  61. """
  62. Deal float rounded to specified decimals in dict.
  63. For example:
  64. res:{
  65. "model_lineages": {
  66. "metric": {"acc": 0.1234561}
  67. }
  68. }
  69. expected_res:
  70. {
  71. "model_lineages": {
  72. "metric": {"acc": 0.1234562}
  73. }
  74. }
  75. After:
  76. res:{
  77. "model_lineages": {
  78. "metric": {"acc": 0.12346}
  79. }
  80. }
  81. expected_res:
  82. {
  83. "model_lineages": {
  84. "metric": {"acc": 0.12346}
  85. }
  86. }
  87. Args:
  88. res (dict): e.g.
  89. {
  90. "model_lineages": {
  91. "metric": {"acc": 0.1234561}
  92. }
  93. }
  94. expected_res (dict):
  95. {
  96. "model_lineages": {
  97. "metric": {"acc": 0.1234562}
  98. }
  99. }
  100. decimal_num (int): decimal rounded digits.
  101. """
  102. for key in res:
  103. value = res[key]
  104. expected_value = expected_res[key]
  105. if isinstance(value, dict):
  106. deal_float_for_dict(value, expected_value, decimal_num)
  107. elif isinstance(value, float):
  108. res[key] = round(value, decimal_num)
  109. expected_res[key] = round(expected_value, decimal_num)
  110. def _deal_float_for_list(list1, list2, decimal_num):
  111. """Deal float for list1 and list2."""
  112. index = 0
  113. for _ in list1:
  114. deal_float_for_dict(list1[index], list2[index], decimal_num)
  115. index += 1
  116. def assert_equal_lineages(lineages1, lineages2, assert_func, decimal_num=5):
  117. """Assert lineages."""
  118. if isinstance(lineages1, list) and isinstance(lineages2, list):
  119. _deal_float_for_list(lineages1, lineages2, decimal_num)
  120. elif lineages1.get('object') is not None and lineages2.get('object') is not None:
  121. _deal_float_for_list(lineages1['object'], lineages2['object'], decimal_num)
  122. else:
  123. deal_float_for_dict(lineages1, lineages2, decimal_num)
  124. assert_func(lineages1, lineages2)
  125. def get_relative_path(path, base_path):
  126. """
  127. Get relative path based on base_path.
  128. Args:
  129. path (str): absolute path.
  130. base_path: absolute base path.
  131. Returns:
  132. str, relative path based on base_path.
  133. """
  134. try:
  135. r_path = str(Path(path).relative_to(Path(base_path)))
  136. except ValueError:
  137. raise LineageParamValueError("The path %r does not start with %r." % (path, base_path))
  138. if r_path == ".":
  139. r_path = ""
  140. return os.path.join("./", r_path)
  141. def convert_dict_to_yaml(value: dict, output_dir, file_name='config.yaml'):
  142. """Write dict to yaml file."""
  143. yaml_file = os.path.join(output_dir, file_name)
  144. with open(yaml_file, 'w', encoding='utf-8') as file:
  145. yaml.dump(value, file)
  146. return yaml_file