Passed
Push — issue844-exclude-rules ( 22f810...85c329 )
by Osma
03:08
created

annif.vocab.rules   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 39
rs 10
c 0
b 0
f 0
wmc 12

4 Functions

Rating   Name   Duplication   Size   Complexity  
C kwargs_to_exclude_uris() 0 18 9
A uris_by_type() 0 2 1
A uris_by_scheme() 0 2 1
A uris_by_collection() 0 2 1
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 kwargs_to_exclude_uris(graph: Graph, kwargs: dict[str, str]) -> set[str]:
22
    exclude_uris = set()
23
    for key, value in kwargs.items():
24
        vals = value.split("|")
25
        if key == "exclude":
26
            exclude_uris.update(vals)
27
        elif key == "exclude_type":
28
            for val in vals:
29
                exclude_uris.update(uris_by_type(graph, val))
30
        elif key == "exclude_scheme":
31
            for val in vals:
32
                exclude_uris.update(uris_by_scheme(graph, val))
33
        elif key == "exclude_collection":
34
            for val in vals:
35
                exclude_uris.update(uris_by_collection(graph, val))
36
        else:
37
            raise ConfigurationException(f"unknown vocab keyword argument {key}")
38
    return exclude_uris
39