Total Complexity | 7 |
Total Lines | 32 |
Duplicated Lines | 0 % |
Changes | 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 VERSION |
||
8 | import ocrd_utils |
||
9 | from ocrd_validators import OcrdConfigValidator |
||
10 | from ocrd_models.ocrd_config import DEFAULT_CONFIG |
||
11 | |||
12 | def load_config_file(basedir=None): |
||
13 | """ |
||
14 | Load the configuration file |
||
15 | """ |
||
16 | if not basedir: |
||
17 | basedir = ocrd_utils.XDG_CONFIG_HOME |
||
18 | fpath = Path(basedir, 'ocrd', 'config.yml') |
||
19 | if not fpath.parent.exists(): |
||
20 | fpath.parent.mkdir(parents=True) |
||
21 | obj = DEFAULT_CONFIG |
||
22 | if not fpath.exists(): |
||
23 | with open(str(fpath), 'w', encoding='utf-8') as f_out: |
||
24 | f_out.write("# Generated by OCR-D/core %s on %s\n" % (VERSION, datetime.now())) |
||
25 | f_out.write(safe_dump(obj)) |
||
26 | with open(str(fpath), 'r', encoding='utf-8') as f_in: |
||
27 | obj = {**obj, **safe_load(f_in.read())} |
||
28 | report = OcrdConfigValidator.validate(obj) |
||
29 | if not report.is_valid: |
||
30 | raise ValueError("The configuration is invalid: %s" % report.errors) |
||
31 | return OcrdConfig(obj) |
||
32 |