Passed
Pull Request — master (#559)
by Konstantin
02:15
created

ocrd.config.load_config_file()   B

Complexity

Conditions 6

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 18
rs 8.6666
c 0
b 0
f 0
cc 6
nop 0
1
from pathlib import Path
2
from datetime import datetime
3
4
from yaml import safe_load, safe_dump
5
6
from ocrd_models import OcrdConfig
7
from ocrd_utils import XDG_CONFIG_HOME, VERSION
8
from ocrd_validators import OcrdConfigValidator
9
from ocrd_models.ocrd_config import DEFAULT_CONFIG
10
11
def load_config_file():
12
    """
13
    Load the configuration file
14
    """
15
    fpath = Path(XDG_CONFIG_HOME, 'ocrd', 'config.yml')
16
    if not fpath.parent.exists():
17
        fpath.parent.mkdir(parents=True)
18
    obj = DEFAULT_CONFIG
19
    if not fpath.exists():
20
        with open(str(fpath), 'w', encoding='utf-8') as f_out:
21
            f_out.write("# Generated by OCR-D/core %s on %s\n" % (VERSION, datetime.now()))
22
            f_out.write(safe_dump(obj))
23
    with open(str(fpath), 'r', encoding='utf-8') as f_in:
24
        obj = {**obj, **safe_load(f_in.read())}
25
        report = OcrdConfigValidator.validate(obj)
26
        if not report.is_valid:
27
            raise ValueError("The configuration is invalid: %s" % report.errors)
28
        return OcrdConfig(obj)
29