loader.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (C) 2025 AIDC-AI
  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. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. """
  13. Configuration loader - Pure YAML
  14. Handles loading and saving configuration from/to YAML files.
  15. """
  16. from pathlib import Path
  17. import yaml
  18. from loguru import logger
  19. def load_config_dict(config_path: str = "config.yaml") -> dict:
  20. """
  21. Load configuration from YAML file
  22. Args:
  23. config_path: Path to config file
  24. Returns:
  25. Configuration dictionary
  26. """
  27. config_file = Path(config_path)
  28. if not config_file.exists():
  29. logger.warning(f"Config file not found: {config_path}")
  30. logger.info("Using default configuration")
  31. return {}
  32. try:
  33. with open(config_file, 'r', encoding='utf-8') as f:
  34. data = yaml.safe_load(f) or {}
  35. logger.info(f"Configuration loaded from {config_path}")
  36. return data
  37. except Exception as e:
  38. logger.error(f"Failed to load config: {e}")
  39. return {}
  40. def save_config_dict(config: dict, config_path: str = "config.yaml"):
  41. """
  42. Save configuration to YAML file
  43. Args:
  44. config: Configuration dictionary
  45. config_path: Path to config file
  46. """
  47. try:
  48. with open(config_path, 'w', encoding='utf-8') as f:
  49. yaml.dump(config, f, allow_unicode=True, default_flow_style=False, sort_keys=False)
  50. logger.info(f"Configuration saved to {config_path}")
  51. except Exception as e:
  52. logger.error(f"Failed to save config: {e}")
  53. raise