config_utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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. import os
  15. import yaml
  16. def load_config(file_path):
  17. """ load_config """
  18. # Refer to https://github.com/PaddlePaddle/PaddleOCR/blob/366ad29d6c202a79bad103c72556c1186915c9c8/tools/program.py#L75
  19. _, ext = os.path.splitext(file_path)
  20. assert ext in ['.yml', '.yaml'], "only support yaml files for now"
  21. config = yaml.load(open(file_path, 'rb'), Loader=yaml.Loader)
  22. return config
  23. def merge_config(config, opts):
  24. """ merge_config """
  25. # Refer to https://github.com/PaddlePaddle/PaddleOCR/blob/366ad29d6c202a79bad103c72556c1186915c9c8/tools/program.py#L88
  26. for key, value in opts.items():
  27. if "." not in key:
  28. if isinstance(value, dict) and key in config:
  29. config[key].update(value)
  30. else:
  31. config[key] = value
  32. else:
  33. sub_keys = key.split('.')
  34. assert (
  35. sub_keys[0] in config
  36. ), "the sub_keys can only be one of global_config: {}, but get: " \
  37. "{}, please check your running command".format(
  38. config.keys(), sub_keys[0])
  39. cur = config[sub_keys[0]]
  40. for idx, sub_key in enumerate(sub_keys[1:]):
  41. if idx == len(sub_keys) - 2:
  42. cur[sub_key] = value
  43. else:
  44. cur = cur[sub_key]
  45. return config