|
1
|
|
|
"""Support for exclude/include rules for subject vocabularies""" |
|
2
|
|
|
|
|
3
|
|
|
from rdflib import RDF, Graph, URIRef |
|
4
|
|
|
from rdflib.namespace import SKOS |
|
5
|
|
|
|
|
6
|
|
|
from annif.exception import ConfigurationException |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
|
|
def uris_by_type(graph: Graph, type: str) -> list[str]: |
|
10
|
|
|
return [str(uri) for uri in graph.subjects(RDF.type, URIRef(type))] |
|
11
|
|
|
|
|
12
|
|
|
|
|
13
|
|
|
def uris_by_scheme(graph: Graph, type: str) -> list[str]: |
|
14
|
|
|
return [str(uri) for uri in graph.subjects(SKOS.inScheme, URIRef(type))] |
|
15
|
|
|
|
|
16
|
|
|
|
|
17
|
|
|
def uris_by_collection(graph: Graph, type: str) -> list[str]: |
|
18
|
|
|
return [str(uri) for uri in graph.objects(URIRef(type), SKOS.member)] |
|
19
|
|
|
|
|
20
|
|
|
|
|
21
|
|
|
def add_uris( |
|
22
|
|
|
graph: Graph, uris_func: callable, uris_set: set[str], vals: list[str] |
|
23
|
|
|
) -> None: |
|
24
|
|
|
for val in vals: |
|
25
|
|
|
uris_set.update(uris_func(graph, val)) |
|
26
|
|
|
|
|
27
|
|
|
|
|
28
|
|
|
def remove_uris( |
|
29
|
|
|
graph: Graph, uris_func: callable, uris_set: set[str], vals: list[str] |
|
30
|
|
|
) -> None: |
|
31
|
|
|
for val in vals: |
|
32
|
|
|
for uri in uris_func(graph, val): |
|
33
|
|
|
uris_set.discard(uri) |
|
34
|
|
|
|
|
35
|
|
|
|
|
36
|
|
|
def kwargs_to_exclude_uris(graph: Graph, kwargs: dict[str, str]) -> set[str]: |
|
37
|
|
|
exclude_uris = set() |
|
38
|
|
|
actions = { |
|
39
|
|
|
"exclude": lambda vals: exclude_uris.update( |
|
40
|
|
|
vals if "*" not in vals else uris_by_type(graph, SKOS.Concept) |
|
41
|
|
|
), |
|
42
|
|
|
"exclude_type": lambda vals: add_uris(graph, uris_by_type, exclude_uris, vals), |
|
43
|
|
|
"exclude_scheme": lambda vals: add_uris( |
|
44
|
|
|
graph, uris_by_scheme, exclude_uris, vals |
|
45
|
|
|
), |
|
46
|
|
|
"exclude_collection": lambda vals: add_uris( |
|
47
|
|
|
graph, uris_by_collection, exclude_uris, vals |
|
48
|
|
|
), |
|
49
|
|
|
"include": lambda vals: exclude_uris.difference_update(vals), |
|
50
|
|
|
"include_type": lambda vals: remove_uris( |
|
51
|
|
|
graph, uris_by_type, exclude_uris, vals |
|
52
|
|
|
), |
|
53
|
|
|
"include_scheme": lambda vals: remove_uris( |
|
54
|
|
|
graph, uris_by_scheme, exclude_uris, vals |
|
55
|
|
|
), |
|
56
|
|
|
"include_collection": lambda vals: remove_uris( |
|
57
|
|
|
graph, uris_by_collection, exclude_uris, vals |
|
58
|
|
|
), |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
for key, value in kwargs.items(): |
|
62
|
|
|
vals = value.split("|") |
|
63
|
|
|
if key in actions: |
|
64
|
|
|
actions[key](vals) |
|
65
|
|
|
else: |
|
66
|
|
|
raise ConfigurationException(f"unknown vocab keyword argument {key}") |
|
67
|
|
|
|
|
68
|
|
|
return exclude_uris |
|
69
|
|
|
|