config.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # time: 2023/3/2 10:28
  4. # file: config.py
  5. # author: David
  6. # company: shenyang JY
  7. """
  8. 模型调参及系统功能配置
  9. """
  10. import os
  11. import argparse, yaml
  12. class myargparse(argparse.ArgumentParser):
  13. def __init__(self, discription, add_help):
  14. super(myargparse, self).__init__(description=discription, add_help=add_help)
  15. # default_config_parser = parser = argparse.ArgumentParser(
  16. # description='Training Config', add_help=False)
  17. self.add_argument(
  18. '-c',
  19. '--config_yaml',
  20. default=
  21. 'config.yml',
  22. type=str,
  23. metavar='FILE',
  24. help='YAML config file specifying default arguments')
  25. # self.add_argument(
  26. # '-f',
  27. # '--feature_yaml',
  28. # default='feature.yml',
  29. # type=str,
  30. # metavar='FILE',
  31. # help='YAML feature norm file for clustering'
  32. # )
  33. def _parse_args_and_yaml(self):
  34. given_configs, remaining = self.parse_known_args()
  35. current_path = os.path.dirname(__file__)
  36. if given_configs.config_yaml:
  37. with open(current_path + '/' + given_configs.config_yaml, 'r', encoding='utf-8') as f:
  38. cfg = yaml.safe_load(f)
  39. self.set_defaults(**cfg)
  40. # if given_configs.feature_yaml:
  41. # with open(current_path + '/' + given_configs.feature_yaml, 'r', encoding='utf-8') as f:
  42. # cfg = yaml.safe_load(f)
  43. # self.set_defaults(**cfg)
  44. # The main arg parser parses the rest of the args, the usual
  45. # defaults will have been overridden if config file specified.
  46. opt = self.parse_args(remaining)
  47. # Cache the args as a text string to save them in the output dir later
  48. opt_text = yaml.safe_dump(opt.__dict__, default_flow_style=False)
  49. # print("opt", opt)
  50. return opt, opt_text
  51. def parse_args_and_yaml(self):
  52. return self._parse_args_and_yaml()[0]
  53. def save_args_yml(self, opt, isdict=False):
  54. current_path = os.path.dirname(__file__)
  55. current_path = './j00645-w-xch'
  56. if isdict:
  57. with open(current_path + '/' + 'config.yml', mode='w', encoding='utf-8') as f:
  58. yaml.safe_dump(opt, f)
  59. else:
  60. with open(current_path + '/' + 'config.yml', mode='w', encoding='utf-8') as f:
  61. yaml.safe_dump(vars(opt), f)
  62. if __name__ == '__main__':
  63. args = myargparse(discription="场站端配置", add_help=False)
  64. opt = args.parse_args_and_yaml()