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

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