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 6.8 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. # Copyright 2019 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. """Common Tools."""
  16. import imghdr
  17. import math
  18. import os
  19. from numbers import Number
  20. from urllib.parse import unquote
  21. from mindinsight.datavisual.common.exceptions import MaxCountExceededError
  22. from mindinsight.datavisual.common.log import logger
  23. from mindinsight.utils import exceptions
  24. from mindinsight.utils.exceptions import UnknownError
  25. _IMG_EXT_TO_MIMETYPE = {
  26. 'bmp': 'image/bmp',
  27. 'gif': 'image/gif',
  28. 'jpeg': 'image/jpeg',
  29. 'png': 'image/png',
  30. }
  31. _DEFAULT_IMAGE_MIMETYPE = 'application/octet-stream'
  32. def find_app_package():
  33. """Find package in current directory."""
  34. backend_dir = os.path.realpath(os.path.join(__file__, os.pardir, os.pardir, os.pardir, "backend"))
  35. packages = []
  36. for file in os.listdir(backend_dir):
  37. file_path = os.path.join(backend_dir, file)
  38. if os.path.isfile(file_path):
  39. continue
  40. if not os.path.isfile(os.path.join(file_path, '__init__.py')):
  41. continue
  42. rel_path = os.path.relpath(file_path, backend_dir)
  43. package = rel_path.replace(os.path.sep, '.')
  44. package = f"mindinsight.backend.{package}"
  45. packages.append(package)
  46. return packages
  47. def to_str(bytes_or_text, encode="utf-8"):
  48. """Bytes transform string."""
  49. if isinstance(bytes_or_text, bytes):
  50. return bytes_or_text.decode(encode)
  51. if isinstance(bytes_or_text, str):
  52. return bytes_or_text
  53. raise TypeError("Param isn't str or bytes type, param={}".format(bytes_or_text))
  54. def to_int(param, param_name):
  55. """
  56. Transfer param to int type.
  57. Args:
  58. param (Any): A param transformed.
  59. param_name (str): Param name.
  60. Returns:
  61. int, value after transformed.
  62. """
  63. try:
  64. param = int(param)
  65. except ValueError:
  66. raise exceptions.ParamTypeError(param_name, 'Integer')
  67. return param
  68. def str_to_bool(param, param_name):
  69. """
  70. Check param and transform it to bool.
  71. Args:
  72. param (str): 'true' or 'false' is valid.
  73. param_name (str): Param name.
  74. Returns:
  75. bool, if param is 'true', case insensitive.
  76. Raises:
  77. ParamValueError: If the value of param is not 'false' and 'true'.
  78. """
  79. if not isinstance(param, str):
  80. raise exceptions.ParamTypeError(param_name, 'str')
  81. if param.lower() not in ['false', 'true']:
  82. raise exceptions.ParamValueError("The value of %s must be 'false' or 'true'." % param_name)
  83. param = (param.lower() == 'true')
  84. return param
  85. def get_img_mimetype(img_data):
  86. """
  87. Recognize image headers and generate image MIMETYPE.
  88. Args:
  89. img_data (bin): Binary character stream of image.
  90. Returns:
  91. str, a MIMETYPE of the give image.
  92. """
  93. image_type = imghdr.what(None, img_data)
  94. mimetype = _IMG_EXT_TO_MIMETYPE.get(image_type, _DEFAULT_IMAGE_MIMETYPE)
  95. return mimetype
  96. def get_train_id(request):
  97. """
  98. Get train ID from requst query string and unquote content.
  99. Args:
  100. request (FlaskRequest): Http request instance.
  101. Returns:
  102. str, unquoted train ID.
  103. """
  104. train_id = request.args.get('train_id')
  105. if train_id is not None:
  106. try:
  107. train_id = unquote(train_id, errors='strict')
  108. except UnicodeDecodeError:
  109. raise exceptions.UrlDecodeError('Unquote train id error with strict mode')
  110. return train_id
  111. def get_profiler_dir(request):
  112. """
  113. Get train ID from requst query string and unquote content.
  114. Args:
  115. request (FlaskRequest): Http request instance.
  116. Returns:
  117. str, unquoted train ID.
  118. """
  119. profiler_dir = request.args.get('profile')
  120. if profiler_dir is not None:
  121. try:
  122. profiler_dir = unquote(profiler_dir, errors='strict')
  123. except UnicodeDecodeError:
  124. raise exceptions.UrlDecodeError('Unquote profiler_dir error with strict mode')
  125. return profiler_dir
  126. def unquote_args(request, arg_name):
  127. """
  128. Get args from requst query string and unquote content.
  129. Args:
  130. request (FlaskRequest): Http request instance.
  131. arg_name (str): The name of arg.
  132. Returns:
  133. str, unquoted arg.
  134. """
  135. arg_value = request.args.get(arg_name, "")
  136. if arg_value is not None:
  137. try:
  138. arg_value = unquote(arg_value, errors='strict')
  139. except UnicodeDecodeError:
  140. raise exceptions.ParamValueError('Unquote error with strict mode')
  141. return arg_value
  142. def get_device_id(request):
  143. """
  144. Get device ID from requst query string and unquote content.
  145. Args:
  146. request (FlaskRequest): Http request instance.
  147. Returns:
  148. str, unquoted device ID.
  149. """
  150. device_id = request.args.get('device_id')
  151. if device_id is not None:
  152. try:
  153. device_id = unquote(device_id, errors='strict')
  154. except UnicodeDecodeError:
  155. raise exceptions.UrlDecodeError('Unquote train id error with strict mode')
  156. else:
  157. device_id = "0"
  158. return device_id
  159. def if_nan_inf_to_none(name, value):
  160. """
  161. Transform value to None if it is NaN or Inf.
  162. Args:
  163. name (str): Name of value.
  164. value (float): A number transformed.
  165. Returns:
  166. float, if value is NaN or Inf, return None.
  167. """
  168. if not isinstance(value, Number):
  169. raise exceptions.ParamTypeError(name, 'number')
  170. if math.isnan(value) or math.isinf(value):
  171. value = None
  172. return value
  173. def exception_wrapper(func):
  174. def wrapper(*args, **kwargs):
  175. try:
  176. func(*args, **kwargs)
  177. except Exception as exc:
  178. logger.exception(exc)
  179. raise UnknownError(str(exc))
  180. return wrapper
  181. class Counter:
  182. """Count accumulator with limit checking."""
  183. def __init__(self, max_count=None, init_count=0):
  184. self._count = init_count
  185. self._max_count = max_count
  186. def add(self, value=1):
  187. """Add value."""
  188. if self._max_count is not None and self._count + value > self._max_count:
  189. raise MaxCountExceededError()
  190. self._count += value