|
| 1 | +import json |
| 2 | +import os |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +from aishell.models import AiShellConfigModel |
| 6 | + |
| 7 | + |
| 8 | +class AiShellConfigManager: |
| 9 | + DEFAULT_CONFIG_PATH = os.path.expanduser('~/.aishell_config.json') |
| 10 | + |
| 11 | + def __init__( |
| 12 | + self, |
| 13 | + config_model: Optional[AiShellConfigModel] = None, |
| 14 | + config_path: Optional[str] = None, |
| 15 | + load_config: bool = False, |
| 16 | + ): |
| 17 | + ''' |
| 18 | + Initialize an instance of AiShellConfigManager |
| 19 | +
|
| 20 | + Args: |
| 21 | + config_model: \ |
| 22 | + An instance of AiShellConfigManager to use as the configuration.\ |
| 23 | + If None and load_config is True, loads the configuration from the configuration file. |
| 24 | + config_path: Path to the configuration file. \ |
| 25 | + If None, uses the default path "~/.aishell_config.json". |
| 26 | + load_config: If True and config_model is None, loads the configuration from the configuration file. |
| 27 | + ''' |
| 28 | + self.config_path = config_path or AiShellConfigManager.DEFAULT_CONFIG_PATH |
| 29 | + |
| 30 | + if config_model: |
| 31 | + self.update_config(config_model) |
| 32 | + elif load_config: |
| 33 | + self.load_config() |
| 34 | + |
| 35 | + @staticmethod |
| 36 | + def is_config_file_available(config_path: str) -> bool: |
| 37 | + return os.path.isfile(config_path) |
| 38 | + |
| 39 | + def update_config(self, config_model: AiShellConfigModel): |
| 40 | + self.config_model = config_model |
| 41 | + |
| 42 | + def load_config(self): |
| 43 | + self.config_model = AiShellConfigModel.parse_file(self.config_path) |
| 44 | + |
| 45 | + def save_config(self): |
| 46 | + with open(self.config_path, 'w') as aishell_config_path: |
| 47 | + config_dict = self.config_model.dict() |
| 48 | + aishell_config_path.write(json.dumps(config_dict, indent=4, sort_keys=True)) |
0 commit comments