config_utils.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. _, ext = os.path.splitext(file_path)
  19. assert ext in [".yml", ".yaml"], "only support yaml files for now"
  20. config = yaml.load(open(file_path, "rb"), Loader=yaml.Loader)
  21. return config
  22. def merge_config(config, opts):
  23. """merge_config"""
  24. for key, value in opts.items():
  25. if "." not in key:
  26. if isinstance(value, dict) and key in config:
  27. config[key].update(value)
  28. else:
  29. config[key] = value
  30. else:
  31. sub_keys = key.split(".")
  32. assert 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. )
  37. )
  38. cur = config[sub_keys[0]]
  39. for idx, sub_key in enumerate(sub_keys[1:]):
  40. if idx == len(sub_keys) - 2:
  41. cur[sub_key] = value
  42. else:
  43. cur = cur[sub_key]
  44. return config