299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562 | class Config(dict):
def __init__(self, *args, **kwargs):
if len(args) == 1 and isinstance(args[0], dict):
assert len(kwargs) == 0
kwargs = args[0]
path = kwargs.pop("__path__", None)
kwargs = {
key: Config(value)
if isinstance(value, dict) and not isinstance(value, Config)
else value
for key, value in kwargs.items()
}
super().__init__(**kwargs)
self.__path__ = path
@classmethod
def from_str(cls, s: str, resolve: bool = False) -> "Config":
parser = ConfigParser()
parser.optionxform = str
parser.read_string(s)
config = Config()
for section in parser.sections():
parts = split_path(section)
current = config
for part in parts:
if part not in current:
current[part] = current = Config()
else:
current = current[part]
current.clear()
current.update(
{k: config_literal_eval(v) for k, v in parser.items(section)}
)
if resolve:
return config.resolve()
return config
@classmethod
def from_disk(cls, path: Union[str, Path], resolve: bool = False) -> "Config":
s = Path(path).read_text()
return cls.from_str(s, resolve=resolve)
def to_disk(self, path: Union[str, Path]):
s = self.to_str()
Path(path).write_text(s)
def serialize(self):
"""
Try to convert non-serializable objects using the RESOLVED object
back to their original catalogue + params form
Returns
-------
Config
"""
refs = {}
def rec(o, path=()):
if o is None or isinstance(
o, (str, int, float, bool, tuple, list, Reference)
):
return o
if isinstance(o, collections.Mapping):
serialized = {k: rec(v, (*path, k)) for k, v in o.items()}
if isinstance(o, Config):
serialized = Config(serialized)
serialized.__path__ = o.__path__
return serialized
cfg = None
try:
cfg = o.cfg
except AttributeError:
try:
cfg = RESOLVED[o]
except KeyError:
pass
if cfg is not None:
if id(o) in refs:
return refs[id(o)]
else:
refs[id(o)] = Reference(join_path(path))
return rec(cfg, path)
raise TypeError(f"Cannot dump {o!r}")
result = rec(self)
return result
def to_str(self):
additional_sections = {}
def rec(o, path=()):
if isinstance(o, collections.Mapping):
if isinstance(o, Config) and o.__path__ is not None:
res = {k: rec(v, (*o.__path__, k)) for k, v in o.items()}
current = additional_sections
for part in o.__path__[:-1]:
current = current.setdefault(part, Config())
current[o.__path__[-1]] = res
return Reference(join_path(o.__path__))
else:
return {k: rec(v, (*path, k)) for k, v in o.items()}
return o
prepared = flatten_sections(rec(self.serialize()))
prepared.update(flatten_sections(additional_sections))
parser = ConfigParser()
parser.optionxform = str
for section_name, section in prepared.items():
parser.add_section(section_name)
parser[section_name].update(
{k: config_literal_dump(v) for k, v in section.items()}
)
s = StringIO()
parser.write(s)
return s.getvalue()
def resolve(self, _path=(), leaves=None, deep=True):
from .registry import registry # local import because circular deps
copy = Config(**self)
if leaves is None:
leaves = {}
missing = []
items = [(k, v) for k, v in copy.items()] if deep else []
last_count = len(leaves)
while len(items):
traced_missing_values = []
for key, value in items:
try:
if isinstance(value, Config):
if (*_path, key) not in leaves:
leaves[(*_path, key)] = value.resolve((*_path, key), leaves)
copy[key] = leaves[(*_path, key)]
elif isinstance(value, Reference):
try:
leaves[(*_path, key)] = leaves[tuple(split_path(value))]
except KeyError:
raise MissingReference([value])
else:
copy[key] = leaves[(*_path, key)]
except MissingReference as e:
traced_missing_values.extend(e.references)
missing.append((key, value))
if len(missing) > 0 and len(leaves) <= last_count:
raise MissingReference(dedup(traced_missing_values))
items = list(missing)
last_count = len(leaves)
missing = []
registries = [
(key, value, registry._catalogue[key[1:]])
for key, value in copy.items()
if key.startswith("@")
]
assert len(registries) <= 1, (
f"Cannot resolve using multiple " f"registries at {'.'.join(_path)}"
)
def patch_errors(errors: Union[Sequence[ErrorWrapper], ErrorWrapper]):
if isinstance(errors, list):
res = []
for error in errors:
res.append(patch_errors(error))
return res
return ErrorWrapper(errors.exc, (*_path, *errors.loc_tuple()))
if len(registries) == 1:
params = dict(copy)
params.pop(registries[0][0])
fn = registries[0][2].get(registries[0][1])
try:
resolved = fn(**params)
try:
resolved.cfg
except Exception:
try:
RESOLVED[resolved] = self
except Exception:
print(f"Could not store original config for {resolved}")
pass
return resolved
except ValidationError as e:
raise ValidationError(patch_errors(e.raw_errors), e.model)
return copy
def merge(
self,
*updates: Union[Dict[str, Any], "Config"],
remove_extra: bool = False,
) -> "Config":
"""
Deep merge two configs. Largely inspired from spaCy config merge function.
Parameters
----------
updates: Union[Config, Dict]
Configs to update the original config
remove_extra:
If true, restricts update to keys that existed in the original config
Returns
-------
The new config
"""
def deep_set(current, path, val):
try:
path = split_path(path)
for part in path[:-1]:
current = (
current[part] if remove_extra else current.setdefault(part, {})
)
except KeyError:
return
if path[-1] not in current and remove_extra:
return
current[path[-1]] = val
def rec(old, new):
for key, new_val in list(new.items()):
if "." in key:
deep_set(old, key, new_val)
continue
if key not in old:
if remove_extra:
continue
else:
old[key] = new_val
continue
old_val = old[key]
if isinstance(old_val, dict) and isinstance(new_val, dict):
old_resolver = next((k for k in old_val if k.startswith("@")), None)
new_resolver = next((k for k in new_val if k.startswith("@")), None)
if (
new_resolver is not None
and old_resolver is not None
and (
old_resolver != new_resolver
or old_val.get(old_resolver) != new_val.get(new_resolver)
)
):
old[key] = new_val
else:
rec(old[key], new_val)
else:
old[key] = new_val
return old
config = deepcopy(self)
for u in updates:
u = deepcopy(u)
rec(config, u)
return Config(**config)
|