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.

config.py 4.5 kB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. """Parse arguments"""
  16. import os
  17. import ast
  18. import argparse
  19. from pprint import pformat
  20. from cv2 import DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS
  21. import yaml
  22. class Config:
  23. """
  24. Configuration namespace. Convert dictionary to members.
  25. """
  26. #data_dir=""
  27. def __init__(self, cfg_dict):
  28. for k, v in cfg_dict.items():
  29. if isinstance(v, (list, tuple)):
  30. setattr(self, k, [Config(x) if isinstance(x, dict) else x for x in v])
  31. else:
  32. setattr(self, k, Config(v) if isinstance(v, dict) else v)
  33. def __str__(self):
  34. return pformat(self.__dict__)
  35. def __repr__(self):
  36. return self.__str__()
  37. def parse_cli_to_yaml(parser, cfg, helper=None, choices=None, cfg_path="default_config.yaml"):
  38. """
  39. Parse command line arguments to the configuration according to the default yaml.
  40. Args:
  41. parser: Parent parser.
  42. cfg: Base configuration.
  43. helper: Helper description.
  44. cfg_path: Path to the default yaml config.
  45. """
  46. parser = argparse.ArgumentParser(description="[REPLACE THIS at config.py]",
  47. parents=[parser])
  48. helper = {} if helper is None else helper
  49. choices = {} if choices is None else choices
  50. for item in cfg:
  51. if not isinstance(cfg[item], list) and not isinstance(cfg[item], dict):
  52. help_description = helper[item] if item in helper else "Please reference to {}".format(cfg_path)
  53. choice = choices[item] if item in choices else None
  54. if isinstance(cfg[item], bool):
  55. parser.add_argument("--" + item, type=ast.literal_eval, default=cfg[item], choices=choice,
  56. help=help_description)
  57. else:
  58. parser.add_argument("--" + item, type=type(cfg[item]), default=cfg[item], choices=choice,
  59. help=help_description)
  60. args = parser.parse_args()
  61. return args
  62. def parse_yaml(yaml_path):
  63. """
  64. Parse the yaml config file.
  65. Args:
  66. yaml_path: Path to the yaml config.
  67. """
  68. with open(yaml_path, 'r') as fin:
  69. try:
  70. cfgs = yaml.load_all(fin.read(), Loader=yaml.FullLoader)
  71. cfgs = [x for x in cfgs]
  72. if len(cfgs) == 1:
  73. cfg_helper = {}
  74. cfg = cfgs[0]
  75. cfg_choices = {}
  76. elif len(cfgs) == 2:
  77. cfg, cfg_helper = cfgs
  78. cfg_choices = {}
  79. elif len(cfgs) == 3:
  80. cfg, cfg_helper, cfg_choices = cfgs
  81. else:
  82. raise ValueError("At most 3 docs (config, description for help, choices) are supported in config yaml")
  83. print(cfg_helper)
  84. except:
  85. raise ValueError("Failed to parse yaml")
  86. return cfg, cfg_helper, cfg_choices
  87. def merge(args, cfg):
  88. """
  89. Merge the base config from yaml file and command line arguments.
  90. Args:
  91. args: Command line arguments.
  92. cfg: Base configuration.
  93. """
  94. args_var = vars(args)
  95. for item in args_var:
  96. cfg[item] = args_var[item]
  97. return cfg
  98. def get_config():
  99. """
  100. Get Config according to the yaml file and cli arguments.
  101. """
  102. parser = argparse.ArgumentParser(description="default name", add_help=False)
  103. current_dir = os.path.dirname(os.path.abspath(__file__))
  104. parser.add_argument("--config_path", type=str, default=os.path.join(current_dir, "../default_config.yaml"),
  105. help="Config file path")
  106. path_args, _ = parser.parse_known_args()
  107. default, helper, choices = parse_yaml(path_args.config_path)
  108. args = parse_cli_to_yaml(parser=parser, cfg=default, helper=helper, choices=choices, cfg_path=path_args.config_path)
  109. final_config = merge(args, default)
  110. return Config(final_config)
  111. config = get_config()

随着人工智能和大数据的发展,任一方面对自动化工具有着一定的需求,在当下疫情防控期间,使用mindspore来实现yolo模型来进行目标检测及语义分割,对视频或图片都可以进行口罩佩戴检测和行人社交距离检测,来对公共场所的疫情防控来实行自动化管理。