Spaces:
Running
on
Zero
Running
on
Zero
File size: 7,632 Bytes
2d9a728 |
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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
from __future__ import annotations
import argparse
import ast
import json
import os
import os.path as osp
import re
import shutil
import sys
import tempfile
from copy import deepcopy
from importlib import import_module
import yaml
from .easydict import EasyDict
__all__ = ["Config", "pretty_text"]
BASE_KEY = "_base_"
# BASE_CONFIG = {"OUTPUT_DIR": "./workspace", "SESSION": "base", "LOG_FILE": "log.txt"}
BASE_CONFIG = {}
cfg = None
class Config(object):
"""config"""
@classmethod
def pretty_text(cls, cfg: dict, indent=2) -> str:
"""format dict to a string
Args:
cfg (EasyDict): the params.
Returns: The string to display.
"""
msg = "{\n"
for i, (k, v) in enumerate(cfg.items()):
if isinstance(v, dict):
v = cls.pretty_text(v, indent + 4)
spaces = " " * indent
msg += spaces + "{}: {}".format(k, v)
if i == len(cfg) - 1:
msg += " }"
else:
msg += "\n"
return msg
@classmethod
def dump(cls, cfg, savepath=None):
"""dump cfg to `json` file.
Args:
cfg (dict): The dict to dump.
savepath (str): The filepath to save the dumped dict.
Returns: TODO
"""
if savepath is None:
savepath = osp.join(cfg.WORKSPACE, "config.json")
json.dump(cfg, open(savepath, "w"), indent=2)
@classmethod
def get_config(cls, default_config: dict = None):
"""get a `Config` instance.
Args:
default_config (dict): The default config. `default_config` will be overrided
by config file `--cfg`, `--cfg` will be overrided by commandline args.
Returns: an EasyDict.
"""
global cfg
if cfg is not None:
return cfg
# define arg parser.
parser = argparse.ArgumentParser()
# parser.add_argument("--cfg", help="load configs from yaml file", default="", type=str)
parser.add_argument(
"config_file", help="the configuration file to load. support: .yaml, .json, .py"
)
parser.add_argument(
"opts",
default=None,
nargs="*",
help="overrided configs. List. Format: 'key1 name1 key2 name2'",
)
args = parser.parse_args()
cfg = EasyDict(BASE_CONFIG)
if osp.isfile(args.config_file):
cfg_from_file = cls.from_file(args.config_file)
cfg = merge_a_into_b(cfg_from_file, cfg)
cfg = cls.merge_list(cfg, args.opts)
cfg = eval_dict_leaf(cfg)
# update some keys to make them show at the last
for k in BASE_CONFIG:
cfg[k] = cfg.pop(k)
return cfg
@classmethod
def from_file(cls, filepath: str) -> EasyDict:
"""Build config from file. Supported filetypes: `.py`,`.yaml`,`.json`.
Args:
filepath (str): The config file path.
Returns: TODO
"""
filepath = osp.abspath(osp.expanduser(filepath))
if not osp.isfile(filepath):
raise IOError(f"File does not exist: {filepath}")
if filepath.endswith(".py"):
sys.path.insert(0, osp.dirname(filepath))
mod = import_module(osp.splitext(osp.basename(filepath))[0])
cfg_dict = {
name: value
for name, value in mod.__dict__.items()
if not name.startswith("__")
}
elif filepath.endswith((".yml", ".yaml")):
cfg_dict = yaml.load(open(filepath, "r"), Loader=yaml.Loader)
elif filepath.endswith(".json"):
cfg_dict = json.load(open(filepath, "r"))
else:
raise IOError("Only py/yml/yaml/json type are supported now!")
cfg_text = filepath + "\n"
with open(filepath, "r") as f:
cfg_text += f.read()
if BASE_KEY in cfg_dict: # load configs in `BASE_KEY`
cfg_dir = osp.dirname(filepath)
base_filename = cfg_dict.pop(BASE_KEY)
base_filename = (
base_filename if isinstance(base_filename, list) else [base_filename]
)
cfg_dict_list = list()
for f in base_filename:
_cfg_dict = Config.from_file(osp.join(cfg_dir, f))
cfg_dict_list.append(_cfg_dict)
base_cfg_dict = dict()
for c in cfg_dict_list:
if len(base_cfg_dict.keys() & c.keys()) > 0:
raise KeyError("Duplicate key is not allowed among bases")
base_cfg_dict.update(c)
cfg_dict = merge_a_into_b(cfg_dict, base_cfg_dict)
return EasyDict(cfg_dict)
@classmethod
def merge_list(cls, cfg, opts: list):
"""merge commandline opts.
Args:
cfg: (dict): The config to be merged.
opts (list): The list to merge. Format: [key1, name1, key2, name2,...].
The keys can be nested. For example, ["a.b", v] will be considered
as `dict(a=dict(b=v))`.
Returns: dict.
"""
assert len(opts) % 2 == 0, f"length of opts must be even. Got: {opts}"
for i in range(0, len(opts), 2):
full_k, v = opts[i], opts[i + 1]
keys = full_k.split(".")
sub_d = cfg
for i, k in enumerate(keys):
if not hasattr(sub_d, k):
raise ValueError(f"The key {k} not exist in the config. Full key:{full_k}")
if i != len(keys) - 1:
sub_d = sub_d[k]
else:
sub_d[k] = v
return cfg
def merge_a_into_b(a, b, inplace=False):
"""The values in a will override values in b.
Args:
a (dict): source dict.
b (dict): target dict.
Returns: dict. recursively merge dict a into dict b.
"""
if not inplace:
b = deepcopy(b)
for key in a:
if key in b:
if isinstance(a[key], dict) and isinstance(b[key], dict):
b[key] = merge_a_into_b(a[key], b[key], inplace=True)
else:
b[key] = a[key]
else:
b[key] = a[key]
return b
def eval_dict_leaf(d, orig_dict=None):
"""eval values of dict leaf.
Args:
d (dict): The dict to eval.
Returns: dict.
"""
if orig_dict is None:
orig_dict = d
for k, v in d.items():
if not isinstance(v, dict):
d[k] = eval_string(v, orig_dict)
else:
eval_dict_leaf(v, orig_dict)
return d
def eval_string(string, d):
"""automatically evaluate string to corresponding types.
For example:
not a string -> return the original input
'0' -> 0
'0.2' -> 0.2
'[0, 1, 2]' -> [0,1,2]
'eval(1+2)' -> 3
'eval(range(5))' -> [0,1,2,3,4]
'${a}' -> d.a
Args:
string (str): The value to evaluate.
d (dict): The
Returns: the corresponding type
"""
if not isinstance(string, str):
return string
# if len(string) > 1 and string[0] == "[" and string[-1] == "]":
# return eval(string)
if string[0:5] == "eval(":
return eval(string[5:-1])
s0 = string
s1 = re.sub(r"\${(.*)}", r"d.\1", s0)
if s1 != s0:
while s1 != s0:
s0 = s1
s1 = re.sub(r"\${(.*)}", r"d.\1", s0)
return eval(s1)
try:
v = ast.literal_eval(string)
except:
v = string
return v
|