A facility for config and config files. It supports common file formats as configs: python/json/yaml. The interface is the same as a dict object and also allows access config values as attributes. Example: >>> cfg = Config(dict(a=1, b=dict(c=[1,2,3], d='dd'))) >>> c
| 88 | |
| 89 | |
| 90 | class Config: |
| 91 | """A facility for config and config files. |
| 92 | |
| 93 | It supports common file formats as configs: python/json/yaml. The interface |
| 94 | is the same as a dict object and also allows access config values as |
| 95 | attributes. |
| 96 | |
| 97 | Example: |
| 98 | >>> cfg = Config(dict(a=1, b=dict(c=[1,2,3], d='dd'))) |
| 99 | >>> cfg.a |
| 100 | 1 |
| 101 | >>> cfg.b |
| 102 | {'c': [1, 2, 3], 'd': 'dd'} |
| 103 | >>> cfg.b.d |
| 104 | 'dd' |
| 105 | >>> cfg = Config.from_file('configs/examples/configuration.json') |
| 106 | >>> cfg.filename |
| 107 | 'configs/examples/configuration.json' |
| 108 | >>> cfg.b |
| 109 | {'c': [1, 2, 3], 'd': 'dd'} |
| 110 | >>> cfg = Config.from_file('configs/examples/configuration.py') |
| 111 | >>> cfg.filename |
| 112 | "configs/examples/configuration.py" |
| 113 | >>> cfg = Config.from_file('configs/examples/configuration.yaml') |
| 114 | >>> cfg.filename |
| 115 | "configs/examples/configuration.yaml" |
| 116 | """ |
| 117 | |
| 118 | @staticmethod |
| 119 | def _file2dict(filename, trust_remote_code: bool = False, model_dir=None): |
| 120 | filename = osp.abspath(osp.expanduser(filename)) |
| 121 | if not osp.exists(filename): |
| 122 | raise ValueError(f'File does not exists {filename}') |
| 123 | fileExtname = osp.splitext(filename)[1] |
| 124 | if fileExtname not in ['.py', '.json', '.yaml', '.yml']: |
| 125 | raise IOError('Only py/yml/yaml/json type are supported now!') |
| 126 | |
| 127 | check_trust_remote_code_for_config( |
| 128 | filename, trust_remote_code=trust_remote_code, model_dir=model_dir) |
| 129 | |
| 130 | with tempfile.TemporaryDirectory() as tmp_cfg_dir: |
| 131 | tmp_cfg_file = tempfile.NamedTemporaryFile( |
| 132 | dir=tmp_cfg_dir, suffix=fileExtname) |
| 133 | if platform.system() == 'Windows': |
| 134 | tmp_cfg_file.close() |
| 135 | tmp_cfg_name = osp.basename(tmp_cfg_file.name) |
| 136 | shutil.copyfile(filename, tmp_cfg_file.name) |
| 137 | |
| 138 | if filename.endswith('.py'): |
| 139 | # import as needed. |
| 140 | from modelscope.utils.import_utils import import_modules_from_file |
| 141 | module_nanme, mod = import_modules_from_file( |
| 142 | osp.join(tmp_cfg_dir, tmp_cfg_name)) |
| 143 | cfg_dict = {} |
| 144 | for name, value in mod.__dict__.items(): |
| 145 | if not name.startswith('__') and \ |
| 146 | not isinstance(value, types.ModuleType) and \ |
| 147 | not isinstance(value, types.FunctionType): |
no outgoing calls
searching dependent graphs…