config_utils.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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 sub_keys[0] in config, (
  35. "the sub_keys can only be one of global_config: {}, but get: "
  36. "{}, please check your running command".format(
  37. config.keys(), sub_keys[0]
  38. )
  39. )
  40. cur = config[sub_keys[0]]
  41. for idx, sub_key in enumerate(sub_keys[1:]):
  42. if idx == len(sub_keys) - 2:
  43. cur[sub_key] = value
  44. else:
  45. cur = cur[sub_key]
  46. return config