1
|
|
|
from pathlib import Path |
2
|
|
|
|
3
|
|
|
from yaml import safe_load |
4
|
|
|
|
5
|
|
|
from .constants import RESOURCE_LIST_FILENAME |
6
|
|
|
|
7
|
|
|
from ocrd_validators import OcrdResourceListValidator |
8
|
|
|
from ocrd_utils import getLogger |
9
|
|
|
from ocrd_utils.constants import HOME |
10
|
|
|
from ocrd_utils.os import list_resource_candidates, list_all_resources |
11
|
|
|
|
12
|
|
|
builtin_list_filename = Path(RESOURCE_LIST_FILENAME) |
13
|
|
|
user_list_filename = Path(HOME, 'ocrd', 'resources.yml') |
14
|
|
|
|
15
|
|
|
class OcrdResourceManager(): |
16
|
|
|
|
17
|
|
|
""" |
18
|
|
|
Managing processor resources |
19
|
|
|
""" |
20
|
|
|
def __init__(self): |
21
|
|
|
self.log = getLogger('ocrd.resource_manager') |
22
|
|
|
self.database = {} |
23
|
|
|
self.load_resource_list(builtin_list_filename) |
24
|
|
|
self.load_resource_list(user_list_filename) |
25
|
|
|
|
26
|
|
|
def load_resource_list(self, list_filename): |
27
|
|
|
if list_filename.is_file(): |
28
|
|
|
with open(list_filename, 'r', encoding='utf-8') as f: |
29
|
|
|
list_loaded = safe_load(f) |
30
|
|
|
report = OcrdResourceListValidator.validate(list_loaded) |
31
|
|
|
if not report.is_valid: |
32
|
|
|
self.log.error('\n'.join(report.errors)) |
33
|
|
|
raise ValueError("Resource list %s is invalid!" % (list_filename)) |
34
|
|
|
for executable, resource_list in list_loaded.items(): |
35
|
|
|
if executable not in self.database: |
36
|
|
|
self.database[executable] = [] |
37
|
|
|
# Prepend, so user provided is sorted before builtin |
38
|
|
|
self.database[executable] = list_loaded[executable] + self.database[executable] |
39
|
|
|
|
40
|
|
|
def list_available(self, executable=None): |
41
|
|
|
if executable: |
42
|
|
|
resources = [(executable, self.database[executable])] |
43
|
|
|
else: |
44
|
|
|
resources = [(x, y) for x, y in self.database.items()] |
45
|
|
|
return resources |
46
|
|
|
|
47
|
|
|
def list_installed(self, executable=None): |
48
|
|
|
ret = [] |
49
|
|
|
for executable in [executable] if executable else self.database.keys(): |
50
|
|
|
reslist = [] |
51
|
|
|
for res_filename in list_all_resources(executable): |
52
|
|
|
res_name = Path(res_filename).name |
53
|
|
|
resdict = [x for x in self.database[executable] if x['name'] == res_name] |
54
|
|
|
if not resdict: |
55
|
|
|
resdict = [{'name': res_name, 'url': '???', 'description': '???', 'version_range': '???'}] |
56
|
|
|
reslist.append(resdict[0]) |
57
|
|
|
ret.append((executable, reslist)) |
58
|
|
|
return ret |
59
|
|
|
|