File size: 2,030 Bytes
a6326c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""
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__)
        # if "_auto_class" in output:
        #     del output["_auto_class"]

        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")