Skip to content

edspdf.config

Config

Bases: dict

Source code in edspdf/config.py
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)

serialize()

Try to convert non-serializable objects using the RESOLVED object back to their original catalogue + params form

RETURNS DESCRIPTION
Config
Source code in edspdf/config.py
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
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

merge(*updates, remove_extra=False)

Deep merge two configs. Largely inspired from spaCy config merge function.

PARAMETER DESCRIPTION
updates

Configs to update the original config

TYPE: Union[Dict[str, Any], Config] DEFAULT: ()

remove_extra

If true, restricts update to keys that existed in the original config

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
The new config
Source code in edspdf/config.py
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
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)

resolve_non_dict(model, values)

Iterates over the model fields and try to resolve the matching values if they are not type hinted as dictionaries.

Source code in edspdf/config.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def resolve_non_dict(model: pydantic.BaseModel, values: Dict[str, Any]):
    """
    Iterates over the model fields and try to resolve the matching values
    if they are not type hinted as dictionaries.
    """
    values = dict(values)
    for field in model.__fields__.values():
        if field.name not in values:
            continue
        if field.shape not in pydantic.fields.MAPPING_LIKE_SHAPES and isinstance(
            values[field.name], dict
        ):
            values[field.name] = Config(values[field.name]).resolve(deep=False)
    return values

validate_arguments(func=None, *, config=None, save_params=None)

Decorator to validate the arguments passed to a function.

PARAMETER DESCRIPTION
func

The function or class to call

TYPE: Optional[Callable] DEFAULT: None

config

The validation configuration object

TYPE: Dict DEFAULT: None

save_params

Should we save the function parameters

TYPE: Optional[Dict] DEFAULT: None

RETURNS DESCRIPTION
Any
Source code in edspdf/config.py
 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
def validate_arguments(
    func: Optional[Callable] = None,
    *,
    config: Dict = None,
    save_params: Optional[Dict] = None,
) -> Any:
    """
    Decorator to validate the arguments passed to a function.

    Parameters
    ----------
    func: Callable
        The function or class to call
    config: Dict
        The validation configuration object
    save_params: bool
        Should we save the function parameters

    Returns
    -------
    Any
    """
    if config is None:
        config = {}
    config = {**config, "arbitrary_types_allowed": True}

    def validate(_func: Callable) -> Callable:

        if isinstance(_func, type):

            if hasattr(_func, "raw_function"):
                vd = pydantic.decorator.ValidatedFunction(_func.raw_function, config)
            else:
                vd = pydantic.decorator.ValidatedFunction(_func.__init__, config)
            vd.model.__name__ = _func.__name__
            vd.model.__fields__["self"].required = False

            def __get_validators__():
                def validate(value):
                    params = value
                    if isinstance(value, dict):
                        value = Config(value).resolve(deep=False)

                    if not isinstance(value, dict):
                        return value

                    m = vd.init_model_instance(**value)
                    d = {
                        k: v
                        for k, v in m._iter()
                        if k in m.__fields_set__ or m.__fields__[k].default_factory
                    }
                    var_kwargs = d.pop(vd.v_kwargs_name, {})
                    resolved = _func(**d, **var_kwargs)

                    if save_params is not None:
                        RESOLVED[resolved] = {**save_params, **params}

                    return resolved

                yield validate

            @wraps(vd.raw_function)
            def wrapper_function(*args: Any, **kwargs: Any) -> Any:
                values = vd.build_values(args, kwargs)
                if save_params is not None:
                    if set(values.keys()) & {
                        ALT_V_ARGS,
                        ALT_V_KWARGS,
                        V_POSITIONAL_ONLY_NAME,
                        V_DUPLICATE_KWARGS,
                        "args",
                        "kwargs",
                    }:
                        print("VALUES", values.keys(), values["kwargs"])
                        raise Exception(
                            f"{func} must not have positional only args, "
                            f"kwargs or duplicated kwargs"
                        )
                    params = dict(values)
                    resolved = params.pop("self")
                    RESOLVED[resolved] = {**save_params, **params}
                return vd.execute(vd.model(**resolve_non_dict(vd.model, values)))

            _func.vd = vd  # type: ignore
            # _func.validate = vd.init_model_instance  # type: ignore
            _func.__get_validators__ = __get_validators__  # type: ignore
            _func.raw_function = vd.raw_function  # type: ignore
            _func.model = vd.model  # type: ignore
            _func.__init__ = wrapper_function
            return _func

        else:
            vd = pydantic.decorator.ValidatedFunction(_func, config)

            @wraps(_func)
            def wrapper_function(*args: Any, **kwargs: Any) -> Any:
                values = vd.build_values(args, kwargs)
                resolved = vd.execute(vd.model(**resolve_non_dict(vd.model, values)))
                if save_params is not None:
                    if set(values.keys()) & {
                        ALT_V_ARGS,
                        ALT_V_KWARGS,
                        V_POSITIONAL_ONLY_NAME,
                        V_DUPLICATE_KWARGS,
                        "args",
                        "kwargs",
                    }:
                        raise Exception(
                            f"{func} must not have positional only args, "
                            f"kwargs or duplicated kwargs"
                        )
                    RESOLVED[resolved] = {**save_params, **values}
                return resolved

            wrapper_function.vd = vd  # type: ignore
            wrapper_function.validate = vd.init_model_instance  # type: ignore
            wrapper_function.raw_function = vd.raw_function  # type: ignore
            wrapper_function.model = vd.model  # type: ignore
            return wrapper_function

    if func:
        return validate(func)
    else:
        return validate