config_utils.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # !/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. ################################################################################
  4. #
  5. # Copyright (c) 2024 Baidu.com, Inc. All Rights Reserved
  6. #
  7. ################################################################################
  8. """
  9. Author: PaddlePaddle Authors
  10. """
  11. import os
  12. import yaml
  13. def load_config(file_path):
  14. """ load_config """
  15. # Refer to https://github.com/PaddlePaddle/PaddleOCR/blob/366ad29d6c202a79bad103c72556c1186915c9c8/tools/program.py#L75
  16. _, ext = os.path.splitext(file_path)
  17. assert ext in ['.yml', '.yaml'], "only support yaml files for now"
  18. config = yaml.load(open(file_path, 'rb'), Loader=yaml.Loader)
  19. return config
  20. def merge_config(config, opts):
  21. """ merge_config """
  22. # Refer to https://github.com/PaddlePaddle/PaddleOCR/blob/366ad29d6c202a79bad103c72556c1186915c9c8/tools/program.py#L88
  23. for key, value in opts.items():
  24. if "." not in key:
  25. if isinstance(value, dict) and key in config:
  26. config[key].update(value)
  27. else:
  28. config[key] = value
  29. else:
  30. sub_keys = key.split('.')
  31. assert (
  32. sub_keys[0] in config
  33. ), "the sub_keys can only be one of global_config: {}, but get: " \
  34. "{}, please check your running command".format(
  35. config.keys(), sub_keys[0])
  36. cur = config[sub_keys[0]]
  37. for idx, sub_key in enumerate(sub_keys[1:]):
  38. if idx == len(sub_keys) - 2:
  39. cur[sub_key] = value
  40. else:
  41. cur = cur[sub_key]
  42. return config