| 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 | """ |
| 14 | Configuration loader - Pure YAML |
| 15 | |
| 16 | Handles loading and saving configuration from/to YAML files. |
| 17 | """ |
| 18 | from pathlib import Path |
| 19 | import yaml |
| 20 | from loguru import logger |
| 21 | |
| 22 | |
| 23 | def load_config_dict(config_path: str = "config.yaml") -> dict: |
| 24 | """ |
| 25 | Load configuration from YAML file |
| 26 | |
| 27 | Args: |
| 28 | config_path: Path to config file |
| 29 | |
| 30 | Returns: |
| 31 | Configuration dictionary |
| 32 | """ |
| 33 | config_file = Path(config_path) |
| 34 | |
| 35 | if not config_file.exists(): |
| 36 | logger.warning(f"Config file not found: {config_path}") |
| 37 | logger.info("Using default configuration") |
| 38 | return {} |
| 39 | |
| 40 | try: |
| 41 | with open(config_file, 'r', encoding='utf-8') as f: |
| 42 | data = yaml.safe_load(f) or {} |
| 43 | logger.info(f"Configuration loaded from {config_path}") |
| 44 | return data |
| 45 | except Exception as e: |
| 46 | logger.error(f"Failed to load config: {e}") |
| 47 | return {} |
| 48 | |
| 49 | |
| 50 | def save_config_dict(config: dict, config_path: str = "config.yaml"): |
| 51 | """ |
| 52 | Save configuration to YAML file |
| 53 | |
| 54 | Args: |
| 55 | config: Configuration dictionary |
| 56 | config_path: Path to config file |
| 57 | """ |
| 58 | try: |
| 59 | with open(config_path, 'w', encoding='utf-8') as f: |
| 60 | yaml.dump(config, f, allow_unicode=True, default_flow_style=False, sort_keys=False) |
| 61 | logger.info(f"Configuration saved to {config_path}") |
| 62 | except Exception as e: |
| 63 | logger.error(f"Failed to save config: {e}") |
| 64 | raise |
| 65 | |
| 66 |