|
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
|
|
|
""" |
|
42
|
|
|
List models available for download by processor |
|
43
|
|
|
""" |
|
44
|
|
|
if executable: |
|
45
|
|
|
return [(executable, self.database[executable])] |
|
46
|
|
|
return [(x, y) for x, y in self.database.items()] |
|
47
|
|
|
|
|
48
|
|
|
def list_installed(self, executable=None): |
|
49
|
|
|
""" |
|
50
|
|
|
List installed resources, matching with registry by ``name`` |
|
51
|
|
|
""" |
|
52
|
|
|
ret = [] |
|
53
|
|
|
for executable in [executable] if executable else self.database.keys(): |
|
54
|
|
|
reslist = [] |
|
55
|
|
|
for res_filename in list_all_resources(executable): |
|
56
|
|
|
res_name = Path(res_filename).name |
|
57
|
|
|
resdict = [x for x in self.database[executable] if x['name'] == res_name] |
|
58
|
|
|
if not resdict: |
|
59
|
|
|
resdict = [{'name': res_name, 'url': '???', 'description': '???', 'version_range': '???'}] |
|
60
|
|
|
reslist.append(resdict[0]) |
|
61
|
|
|
ret.append((executable, reslist)) |
|
62
|
|
|
return ret |
|
63
|
|
|
|