File size: 4,930 Bytes
e17c9f2
 
 
0b619bd
e17c9f2
0b619bd
e17c9f2
 
0b619bd
 
e17c9f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8709b2
e17c9f2
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
r"""_summary_
-*- coding: utf-8 -*-

Module : configs.reader

File Name : reader.py

Description : Load the config file, which supports referencing other configuration files. If a circular reference occurs, an exception will be thrown

Creation Date : 2024-07-13

Author : Frank Kang([email protected])
"""
import pathlib
import json

import os
import warnings

from typing import Union, Any, IO
from omegaconf import OmegaConf, DictConfig, ListConfig

from .utils import get_dir

class ConfigReader:
    """_summary_
    Load the config file, which supports referencing other configuration files. If a circular reference occurs, an exception will be thrown

    for examples:
    ```
    config = ConfigReader.load(file)
    ```
    """

    def __init__(
        self,
        file_: Union[str, pathlib.Path, IO[Any]],
        included: set | None = None
    ) -> None:
        """_summary_

        Args:
            file_ (Union[str, pathlib.Path, IO[Any]]): config
            included (set | None, optional): Include config file. Defaults to None.

        Raises:
            FileNotFoundError: If the configuration file cannot be found
            RecursionError: If there is a loop include
        """
        fname = ''
        self.included = included if included is not None else set()
        if isinstance(file_, str):
            fname = file_
            if not os.path.exists(fname):
                template_path = '{}.template'.format(fname)
                if os.path.exists(template_path):
                    with open(fname, 'w', encoding='utf8') as wf:
                        with open(template_path, 'r', encoding='utf8') as rf:
                            wf.write(rf.read())
                    warnings.warn(
                        'cannot find file {}. Auto generate from {}'.format(
                            fname, template_path))
                else:
                    raise FileNotFoundError(
                        'cannot find file {}'.format(fname))
        else:
            fname = file_.name

        suffix = fname.split('.')[-1]
        if suffix == 'yaml':
            config = OmegaConf.load(fname)
        elif suffix == 'json':
            if isinstance(file_, (str, IO[Any])):
                with open(file_, 'r', encoding='utf8') as f:
                    config = json.load(f)
            else:
                config = json.load(file_)
            config = DictConfig(config)
        if fname not in self.included:
            self.included.add(fname)
        else:
            raise RecursionError()
        self.__config = config
        self.complied = False

    def complie(self, config: DictConfig | None = None):
        """_summary_

        Resolve config to make include effective

        Args:
            config (DictConfig | None, optional): dict config. Defaults to None.

        Raises:
            RecursionError: If there is a loop include
        """
        modify_flag = False
        if config is None:
            config = self.__config
            modify_flag = True

        include_item = None

        for key in config.keys():
            value = config.get(key)
            if isinstance(value, DictConfig):
                self.complie(value)

        if include_item is not None:
            if isinstance(include_item, str):
                included = self.included.copy()
                if include_item in included:
                    print(include_item, included)
                    raise RecursionError()
                included.add(include_item)
                config.merge_with(ConfigReader.load(include_item, included))

            else:
                for item in include_item:
                    included = self.included.copy()
                    if item in included:
                        print(include_item, included)
                        raise RecursionError()
                    config.merge_with(ConfigReader.load(item, included))
                    included.add(item)

        if modify_flag:
            self.complied = True

    @property
    def config(self) -> DictConfig:
        """_summary_

        Obtain parsed dict config

        Returns:
            DictConfig: parsed dict config
        """
        if not self.complied:
            self.complie()
        return self.__config

    @staticmethod
    def load(
        file_: Union[str, pathlib.Path, IO[Any]],
        included: set | None = None,
        **kwargs
    ) -> DictConfig:
        """_summary_

        Class method loading configuration file

        Args:
            file_ (Union[str, pathlib.Path, IO[Any]]): config
            included (set | None, optional): Include config file. Defaults to None.

        Returns:
            DictConfig: parsed dict config
        """
        config = ConfigReader(file_, included).config
        for k, v in kwargs.items():
            config.get(k, {}).update(v)
        return config