| | """ |
| | Base config supporting save and load. Refer to https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py. |
| | Author: md |
| | """ |
| |
|
| | from typing import Dict, Any |
| | import copy |
| | import json |
| |
|
| |
|
| | class BaseConfig(object): |
| | def __init__( |
| | self, |
| | logger_name: str = None, |
| | log_file: str = None, |
| | log_mode: str = "a", |
| | formatter: str = "%(asctime)s | %(levelname)s | %(message)s", |
| | ) -> None: |
| | """ |
| | params: |
| | ------ |
| | |
| | logger_name: logger name |
| | log_file: the file to ouput log. If `None`, output to stdout |
| | log_mode: mode to write to the log file, `a` is appending. |
| | formatter: logging formatter. |
| | """ |
| | self.logger_name = logger_name |
| | self.log_file = log_file |
| | self.log_mode = log_mode |
| | self.formatter = formatter |
| |
|
| | def to_json_string(self) -> Dict[str, Any]: |
| | output = self.to_dict() |
| | return json.dumps(output) |
| |
|
| | def to_dict(self) -> Dict[str, Any]: |
| | """ |
| | Serializes this instance to a Python dictionary. |
| | |
| | Returns: |
| | `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance. |
| | """ |
| | output = copy.deepcopy(self.__dict__) |
| | |
| | |
| |
|
| | return output |
| |
|
| | def from_dict(self, config_dict: Dict[str, Any]) -> None: |
| | self.__dict__.update(config_dict) |
| |
|
| | def save(self, save_path: str, indent: int = 4) -> None: |
| | with open(save_path, "w") as writer: |
| | json.dump(self.to_dict(), writer, indent=indent) |
| |
|
| | def load(self, load_path: str) -> None: |
| | with open(load_path, "r") as reader: |
| | self.__dict__.update(json.load(reader)) |
| |
|
| |
|
| | if __name__ == "__main__": |
| | config = BaseConfig() |
| |
|
| | config.from_dict({"a": 1, "b": 2, "c": "test", "d": True, "e": 3.2}) |
| | config.save("../../test/test1.json") |
| | config.load("../../test/test1.json") |
| | config.save("../../test/test2.json") |
| |
|