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.

mi_validator_helpers.py 4.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. # Copyright 2021 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. General Validator Helper Functions.
  17. """
  18. import os
  19. import inspect
  20. UINT32_MAX = 4294967295
  21. UINT32_MIN = 0
  22. UINT64_MAX = 18446744073709551615
  23. UINT64_MIN = 0
  24. def pad_arg_name(arg_name):
  25. if arg_name != "":
  26. arg_name = arg_name + " "
  27. return arg_name
  28. def check_value(arg, valid_range, arg_name=""):
  29. arg_name = pad_arg_name(arg_name)
  30. if arg < valid_range[0] or arg > valid_range[1]:
  31. raise ValueError(
  32. "Input {0}is not within the required interval of ({1} to {2}).".format(arg_name,
  33. valid_range[0], valid_range[1]))
  34. def check_uint32(arg, arg_name=""):
  35. type_check(arg, (int,), arg_name)
  36. check_value(arg, [UINT32_MIN, UINT32_MAX])
  37. def check_uint64(arg, arg_name=""):
  38. type_check(arg, (int,), arg_name)
  39. check_value(arg, [UINT64_MIN, UINT64_MAX])
  40. def check_dir(dataset_dir):
  41. if not os.path.isdir(dataset_dir) or not os.access(dataset_dir, os.R_OK):
  42. raise ValueError("The folder {} does not exist or permission denied!".format(dataset_dir))
  43. def parse_user_args(method, *args, **kwargs):
  44. """
  45. Parse user arguments in a function.
  46. Args:
  47. method (method): a callable function.
  48. args: user passed args.
  49. kwargs: user passed kwargs.
  50. Returns:
  51. user_filled_args (list): values of what the user passed in for the arguments.
  52. ba.arguments (Ordered Dict): ordered dict of parameter and argument for what the user has passed.
  53. """
  54. sig = inspect.signature(method)
  55. if 'self' in sig.parameters or 'cls' in sig.parameters:
  56. ba = sig.bind(method, *args, **kwargs)
  57. ba.apply_defaults()
  58. params = list(sig.parameters.keys())[1:]
  59. else:
  60. ba = sig.bind(*args, **kwargs)
  61. ba.apply_defaults()
  62. params = list(sig.parameters.keys())
  63. user_filled_args = [ba.arguments.get(arg_value) for arg_value in params]
  64. return user_filled_args, ba.arguments
  65. def type_check(arg, types, arg_name):
  66. """
  67. Check the type of the parameter.
  68. Args:
  69. arg (Any) : any variable.
  70. types (tuple): tuple of all valid types for arg.
  71. arg_name (str): the name of arg.
  72. Returns:
  73. Exception: when the type is not correct, otherwise nothing.
  74. """
  75. # handle special case of booleans being a subclass of ints
  76. print_value = '\"\"' if repr(arg) == repr('') else arg
  77. if int in types and bool not in types:
  78. if isinstance(arg, bool):
  79. raise TypeError("Argument {0} with value {1} is not of type {2}.".format(arg_name, print_value, types))
  80. if not isinstance(arg, types):
  81. raise TypeError("Argument {0} with value {1} is not of type {2}.".format(arg_name, print_value, types))
  82. def type_check_list(args, types, arg_names):
  83. """
  84. Check the type of each parameter in the list.
  85. Args:
  86. args (Union[list, tuple]): a list or tuple of any variable.
  87. types (tuple): tuple of all valid types for arg.
  88. arg_names (Union[list, tuple of str]): the names of args.
  89. Returns:
  90. Exception: when the type is not correct, otherwise nothing.
  91. """
  92. type_check(args, (list, tuple,), arg_names)
  93. if len(args) != len(arg_names) and not isinstance(arg_names, str):
  94. raise ValueError("List of arguments is not the same length as argument_names.")
  95. if isinstance(arg_names, str):
  96. arg_names = ["{0}[{1}]".format(arg_names, i) for i in range(len(args))]
  97. for arg, arg_name in zip(args, arg_names):
  98. type_check(arg, types, arg_name)