ontolutils 0.27.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ontolutils/__init__.py +49 -0
- ontolutils/_cfg.py +40 -0
- ontolutils/_version.py +7 -0
- ontolutils/cache.py +12 -0
- ontolutils/classes/__init__.py +16 -0
- ontolutils/classes/decorator.py +119 -0
- ontolutils/classes/query_util.py +413 -0
- ontolutils/classes/thing.py +1260 -0
- ontolutils/classes/thingmodel.py +21 -0
- ontolutils/classes/urivalue.py +24 -0
- ontolutils/classes/utils.py +207 -0
- ontolutils/config.py +1 -0
- ontolutils/ex/__init__.py +0 -0
- ontolutils/ex/dcat/__init__.py +3 -0
- ontolutils/ex/dcat/resource.py +491 -0
- ontolutils/ex/dcat/role.py +12 -0
- ontolutils/ex/foaf/__init__.py +8 -0
- ontolutils/ex/foaf/agent.py +204 -0
- ontolutils/ex/hdf5/__init__.py +3 -0
- ontolutils/ex/hdf5/allotrope.py +71 -0
- ontolutils/ex/m4i/__init__.py +9 -0
- ontolutils/ex/m4i/m4i.py +532 -0
- ontolutils/ex/pimsii/__init__.py +6 -0
- ontolutils/ex/pimsii/property.py +8 -0
- ontolutils/ex/pimsii/variable.py +19 -0
- ontolutils/ex/prov/__init__.py +232 -0
- ontolutils/ex/prov/attribution.py +8 -0
- ontolutils/ex/qudt/__init__.py +121 -0
- ontolutils/ex/qudt/conversion.py +109 -0
- ontolutils/ex/qudt/utils.py +256 -0
- ontolutils/ex/schema/__init__.py +12 -0
- ontolutils/ex/schema/creative_work.py +110 -0
- ontolutils/ex/schema/project.py +51 -0
- ontolutils/ex/schema/thing.py +16 -0
- ontolutils/ex/sis/__init__.py +10 -0
- ontolutils/ex/sis/measurement_uncertainty.py +63 -0
- ontolutils/ex/skos/__init__.py +4 -0
- ontolutils/ex/skos/concept.py +66 -0
- ontolutils/ex/sosa/__init__.py +10 -0
- ontolutils/ex/spdx/__init__.py +4 -0
- ontolutils/ex/spdx/spdx.py +38 -0
- ontolutils/ex/ssn/__init__.py +25 -0
- ontolutils/ex/ssn/ssn.py +223 -0
- ontolutils/namespacelib/__dev.py +459 -0
- ontolutils/namespacelib/__init__.py +17 -0
- ontolutils/namespacelib/_iana_utils.py +122 -0
- ontolutils/namespacelib/codemeta.py +35 -0
- ontolutils/namespacelib/hdf5.py +387 -0
- ontolutils/namespacelib/m4i.py +173 -0
- ontolutils/namespacelib/obo.py +67 -0
- ontolutils/namespacelib/qudt_kind.py +1181 -0
- ontolutils/namespacelib/qudt_unit.py +2542 -0
- ontolutils/namespacelib/schema.py +2398 -0
- ontolutils/namespacelib/spdx.py +206 -0
- ontolutils/namespacelib/ssn_system.py +39 -0
- ontolutils/typing.py +205 -0
- ontolutils/utils/__init__.py +0 -0
- ontolutils/utils/qudt_units.py +270 -0
- ontolutils-0.27.1.dist-info/METADATA +200 -0
- ontolutils-0.27.1.dist-info/RECORD +63 -0
- ontolutils-0.27.1.dist-info/WHEEL +5 -0
- ontolutils-0.27.1.dist-info/licenses/LICENSE +21 -0
- ontolutils-0.27.1.dist-info/top_level.txt +1 -0
ontolutils/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Ontolutils package."""
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
from ._cfg import set_config, get_config
|
|
5
|
+
from ._version import __version__
|
|
6
|
+
from .classes import Thing, LangString, get_urirefs, get_namespaces, as_id, build, Property, namespaces, urirefs, query, \
|
|
7
|
+
dquery, URIValue
|
|
8
|
+
from .classes.thing import serialize
|
|
9
|
+
from .classes.utils import merge_jsonld
|
|
10
|
+
from .namespacelib import *
|
|
11
|
+
from .utils.qudt_units import parse_unit
|
|
12
|
+
|
|
13
|
+
DEFAULT_LOGGING_LEVEL = logging.WARNING
|
|
14
|
+
_formatter = logging.Formatter(
|
|
15
|
+
'%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
|
|
16
|
+
datefmt='%Y-%m-%d_%H:%M:%S'
|
|
17
|
+
)
|
|
18
|
+
logger = logging.getLogger('ontolutils')
|
|
19
|
+
_sh = logging.StreamHandler()
|
|
20
|
+
_sh.setFormatter(_formatter)
|
|
21
|
+
logger.addHandler(_sh)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def set_logging_level(level: str):
|
|
25
|
+
"""Set the logging level for the package and all its handlers."""
|
|
26
|
+
logger.setLevel(level)
|
|
27
|
+
for h in logger.handlers:
|
|
28
|
+
h.setLevel(level)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
set_logging_level(DEFAULT_LOGGING_LEVEL)
|
|
32
|
+
|
|
33
|
+
__all__ = ['Thing',
|
|
34
|
+
'LangString',
|
|
35
|
+
'__version__',
|
|
36
|
+
'namespaces',
|
|
37
|
+
'urirefs',
|
|
38
|
+
'query',
|
|
39
|
+
'set_logging_level',
|
|
40
|
+
'merge_jsonld',
|
|
41
|
+
'dquery',
|
|
42
|
+
'get_urirefs',
|
|
43
|
+
'get_namespaces',
|
|
44
|
+
'parse_unit',
|
|
45
|
+
'as_id',
|
|
46
|
+
'build',
|
|
47
|
+
'Property',
|
|
48
|
+
'set_config',
|
|
49
|
+
]
|
ontolutils/_cfg.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from typing import Dict
|
|
2
|
+
|
|
3
|
+
CONFIG = {
|
|
4
|
+
'blank_id_generator': None,
|
|
5
|
+
'show_lang_in_str': True
|
|
6
|
+
}
|
|
7
|
+
_VALIDATORS = {
|
|
8
|
+
'blank_id_generator': lambda x: callable(x) or x is None,
|
|
9
|
+
'show_lang_in_str': lambda x: isinstance(x, bool) or x is None,
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class set_config:
|
|
14
|
+
"""Set the configuration parameters."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, **kwargs):
|
|
17
|
+
self.old = {}
|
|
18
|
+
for k, v in kwargs.items():
|
|
19
|
+
if k in _VALIDATORS and not _VALIDATORS[k](v):
|
|
20
|
+
raise ValueError(f'Config parameter "{k}" has invalid value: "{v}"')
|
|
21
|
+
if k not in CONFIG:
|
|
22
|
+
raise KeyError(f'Not a configuration key: "{k}"')
|
|
23
|
+
self.old[k] = CONFIG[k]
|
|
24
|
+
self._update(kwargs)
|
|
25
|
+
|
|
26
|
+
def __enter__(self):
|
|
27
|
+
return
|
|
28
|
+
|
|
29
|
+
def __exit__(self, *args, **kwargs):
|
|
30
|
+
self._update(self.old)
|
|
31
|
+
|
|
32
|
+
def _update(self, options_dict: Dict):
|
|
33
|
+
CONFIG.update(options_dict)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def get_config(key=None):
|
|
37
|
+
"""Return the configuration parameters."""
|
|
38
|
+
if key is None:
|
|
39
|
+
return CONFIG
|
|
40
|
+
return CONFIG[key]
|
ontolutils/_version.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Version library for ontolutils package. Determines the version of the package."""
|
|
2
|
+
try:
|
|
3
|
+
from importlib.metadata import version as _version
|
|
4
|
+
except ImportError as e:
|
|
5
|
+
raise ImportError('Most likely you have python<3.9 installed. At least 3.9 is required.') from e
|
|
6
|
+
|
|
7
|
+
__version__ = _version('ontolutils')
|
ontolutils/cache.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import pathlib
|
|
2
|
+
|
|
3
|
+
import appdirs
|
|
4
|
+
|
|
5
|
+
package_user_dir = pathlib.Path(appdirs.user_data_dir('ontolutils'))
|
|
6
|
+
package_user_dir.mkdir(parents=True, exist_ok=True)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def get_cache_dir() -> pathlib.Path:
|
|
10
|
+
cache_dir = package_user_dir / 'cache'
|
|
11
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
12
|
+
return cache_dir
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Classes for working with ontology data"""
|
|
2
|
+
from .decorator import namespaces, urirefs
|
|
3
|
+
from .query_util import query, dquery
|
|
4
|
+
from .thing import Thing, get_urirefs, get_namespaces, build, Property, LangString
|
|
5
|
+
from .urivalue import URIValue
|
|
6
|
+
from .utils import as_id
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
'namespaces', 'urirefs',
|
|
10
|
+
'Thing', 'LangString',
|
|
11
|
+
'query', 'dquery',
|
|
12
|
+
'get_urirefs', 'get_namespaces',
|
|
13
|
+
'as_id', 'build',
|
|
14
|
+
'Property',
|
|
15
|
+
'URIValue'
|
|
16
|
+
]
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import pydantic
|
|
2
|
+
from pydantic import HttpUrl
|
|
3
|
+
from typing import Dict, Type
|
|
4
|
+
from . import utils
|
|
5
|
+
from .utils import split_uri
|
|
6
|
+
|
|
7
|
+
URIRefManager = utils.UNManager()
|
|
8
|
+
NamespaceManager = utils.UNManager()
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _is_http_url(url: str) -> bool:
|
|
12
|
+
"""Check if a string is a valid http url.
|
|
13
|
+
|
|
14
|
+
Parameters
|
|
15
|
+
----------
|
|
16
|
+
url : str
|
|
17
|
+
The string to check.
|
|
18
|
+
|
|
19
|
+
Returns
|
|
20
|
+
-------
|
|
21
|
+
bool
|
|
22
|
+
True if the string is a valid http url, False otherwise.
|
|
23
|
+
"""
|
|
24
|
+
if not str(url).startswith("http"):
|
|
25
|
+
return False
|
|
26
|
+
# now, check for pattern
|
|
27
|
+
try:
|
|
28
|
+
HttpUrl(url)
|
|
29
|
+
except pydantic.ValidationError:
|
|
30
|
+
return False
|
|
31
|
+
return True
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _add_namesapces(cls, namespaces: Dict):
|
|
35
|
+
for k, v in namespaces.items():
|
|
36
|
+
NamespaceManager[cls][k] = str(HttpUrl(v))
|
|
37
|
+
|
|
38
|
+
def namespaces(**kwargs):
|
|
39
|
+
"""Decorator for model classes. It assigns the namespaces used in the uri fields of the class.
|
|
40
|
+
|
|
41
|
+
Example:
|
|
42
|
+
--------
|
|
43
|
+
@namespaces(ex="https://example.com/")
|
|
44
|
+
@urirefs(name="ex:name")
|
|
45
|
+
class ExampleModel(ThingModel):
|
|
46
|
+
name: str
|
|
47
|
+
|
|
48
|
+
em = ExampleModel(name="test")
|
|
49
|
+
print(em.dump_jsonld())
|
|
50
|
+
# {
|
|
51
|
+
# "@context": {
|
|
52
|
+
# "ex": "https://example.com/"
|
|
53
|
+
# },
|
|
54
|
+
# "@graph": [
|
|
55
|
+
# {
|
|
56
|
+
# "@id": "ex:test",
|
|
57
|
+
# "ex:name": "test"
|
|
58
|
+
# }
|
|
59
|
+
# ]
|
|
60
|
+
# }
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def _decorator(cls):
|
|
64
|
+
"""The actual decorator function. It assigns the namespaces to the class."""
|
|
65
|
+
_add_namesapces(cls, kwargs)
|
|
66
|
+
return cls
|
|
67
|
+
|
|
68
|
+
return _decorator
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
_prefix_dict = {
|
|
72
|
+
'http://xmlns.com/foaf/0.1/': 'foaf',
|
|
73
|
+
'https://www.w3.org/ns/prov#': 'prov',
|
|
74
|
+
'https://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf',
|
|
75
|
+
'https://schema.org/': 'schema',
|
|
76
|
+
'http://w3id.org/nfdi4ing/metadata4ing#': 'm4i'
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
def _decorate_urirefs(cls, **kwargs):
|
|
80
|
+
fields = list(cls.model_fields.keys())
|
|
81
|
+
fields.append(cls.__name__)
|
|
82
|
+
|
|
83
|
+
# add fields to the class
|
|
84
|
+
for k, v in kwargs.items():
|
|
85
|
+
if not isinstance(v, str):
|
|
86
|
+
raise TypeError(f"{v} must be a string, not {type(v)}")
|
|
87
|
+
if _is_http_url(v):
|
|
88
|
+
ns, key = split_uri(v)
|
|
89
|
+
prefix = _prefix_dict.get(ns, None)
|
|
90
|
+
if prefix is None:
|
|
91
|
+
URIRefManager[cls][k] = str(v)
|
|
92
|
+
else:
|
|
93
|
+
NamespaceManager[cls][prefix] = str(ns)
|
|
94
|
+
if k not in fields:
|
|
95
|
+
raise KeyError(f"Field '{k}' not found in {cls.__name__}")
|
|
96
|
+
URIRefManager[cls][k] = f"{prefix}:{key}"
|
|
97
|
+
else:
|
|
98
|
+
if k not in fields:
|
|
99
|
+
raise KeyError(f"Field '{k}' not found in {cls.__name__}")
|
|
100
|
+
URIRefManager[cls][k] = v
|
|
101
|
+
|
|
102
|
+
def urirefs(**kwargs):
|
|
103
|
+
"""decorator for model classes. It assigns the URIRefs to the fields of the class.
|
|
104
|
+
|
|
105
|
+
Example:
|
|
106
|
+
--------
|
|
107
|
+
@urirefs(name=URIRef("https://example.com/name"))
|
|
108
|
+
class ExampleModel(ThingModel):
|
|
109
|
+
name: str
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
def _decorator(cls):
|
|
115
|
+
"""The actual decorator function. It assigns the URIRefs to the fields of the class."""
|
|
116
|
+
_decorate_urirefs(cls, **kwargs)
|
|
117
|
+
return cls
|
|
118
|
+
|
|
119
|
+
return _decorator
|
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
"""This module contains the query utility functions for the Thing class."""
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import pathlib
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import Union, Dict, List, Optional, Type
|
|
8
|
+
|
|
9
|
+
import rdflib
|
|
10
|
+
|
|
11
|
+
from .decorator import URIRefManager, NamespaceManager
|
|
12
|
+
from .thing import Thing
|
|
13
|
+
from .utils import split_uri
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger('ontolutils')
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def process_object(
|
|
19
|
+
_id,
|
|
20
|
+
predicate,
|
|
21
|
+
obj: Union[rdflib.URIRef, rdflib.BNode, rdflib.Literal],
|
|
22
|
+
graph,
|
|
23
|
+
add_type):
|
|
24
|
+
"""Process the object of a triple."""
|
|
25
|
+
if isinstance(obj, rdflib.Literal):
|
|
26
|
+
logger.debug(f'Object "{obj}" for predicate "{predicate}" is a literal.')
|
|
27
|
+
if obj.language:
|
|
28
|
+
return f"{obj}@{obj.language}"
|
|
29
|
+
return str(obj)
|
|
30
|
+
|
|
31
|
+
if isinstance(obj, rdflib.BNode):
|
|
32
|
+
logger.debug(f'"{predicate}" has blank node obj! not optimal... difficult to find children...')
|
|
33
|
+
# find children for predicate with blank node obj
|
|
34
|
+
sub_data = {}
|
|
35
|
+
# collection = []
|
|
36
|
+
for (s, p, o) in graph:
|
|
37
|
+
# logger.debug(s, p, o, obj)
|
|
38
|
+
if str(s) == str(obj):
|
|
39
|
+
if isinstance(o, rdflib.Literal):
|
|
40
|
+
_, key = split_uri(p)
|
|
41
|
+
sub_data[key] = str(o)
|
|
42
|
+
continue
|
|
43
|
+
|
|
44
|
+
if p == rdflib.RDF.first:
|
|
45
|
+
# first means we have a collection
|
|
46
|
+
logger.debug(f'Need to find children of first: {o}')
|
|
47
|
+
# get list:
|
|
48
|
+
qs = """PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
|
|
49
|
+
|
|
50
|
+
SELECT ?item
|
|
51
|
+
WHERE {
|
|
52
|
+
?a rdf:rest*/rdf:first ?item .
|
|
53
|
+
}"""
|
|
54
|
+
list_res = graph.query(qs)
|
|
55
|
+
|
|
56
|
+
_ids = list(set([str(_id[0]) for _id in list_res]))
|
|
57
|
+
_data = [_query_by_id(graph, _id, add_type) for _id in _ids]
|
|
58
|
+
return _data
|
|
59
|
+
|
|
60
|
+
if p == rdflib.RDF.type and add_type:
|
|
61
|
+
sub_data["@type"] = str(o)
|
|
62
|
+
else:
|
|
63
|
+
# may point to another blank node:
|
|
64
|
+
if isinstance(o, rdflib.BNode):
|
|
65
|
+
logger.debug(f'"{o}" is a blank node. Need to find children of it...')
|
|
66
|
+
_, key = split_uri(p)
|
|
67
|
+
if key in sub_data:
|
|
68
|
+
if isinstance(sub_data[key], list):
|
|
69
|
+
sub_data[key].append(process_object(_id, p, o, graph, add_type))
|
|
70
|
+
else:
|
|
71
|
+
sub_data[key] = [sub_data[key], process_object(_id, p, o, graph, add_type)]
|
|
72
|
+
else:
|
|
73
|
+
sub_data[key] = process_object(_id, p, o, graph, add_type)
|
|
74
|
+
elif str(o).startswith('http'):
|
|
75
|
+
# it might be a IRI which is defined inside the JSON-LD:
|
|
76
|
+
_sub_data = process_object(_id, p, o, graph, add_type)
|
|
77
|
+
if _sub_data:
|
|
78
|
+
_, key = split_uri(p)
|
|
79
|
+
sub_data[key] = _sub_data
|
|
80
|
+
else:
|
|
81
|
+
logger.debug(f'dont know what to do with {p} and {o}')
|
|
82
|
+
if predicate in sub_data:
|
|
83
|
+
return sub_data[predicate]
|
|
84
|
+
return sub_data
|
|
85
|
+
|
|
86
|
+
if isinstance(obj, rdflib.URIRef):
|
|
87
|
+
# could be a type definition or a web IRI
|
|
88
|
+
if _is_type_definition(graph, obj):
|
|
89
|
+
logger.debug('points to a type definition inside the data')
|
|
90
|
+
if obj == _id:
|
|
91
|
+
return str(obj)
|
|
92
|
+
return _query_by_id(graph=graph, _id=obj, add_type=True)
|
|
93
|
+
|
|
94
|
+
logger.debug(f'"{obj}" for predicate "{predicate}" is a simple data field.')
|
|
95
|
+
return str(obj)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def get_query_string(cls) -> str:
|
|
99
|
+
"""Return the query string for the class."""
|
|
100
|
+
|
|
101
|
+
def _get_namespace(key):
|
|
102
|
+
ns = URIRefManager[cls].get(key, f'local:{key}')
|
|
103
|
+
if ':' in ns:
|
|
104
|
+
return ns
|
|
105
|
+
return f'{ns}:{key}'
|
|
106
|
+
|
|
107
|
+
query_str = f"""
|
|
108
|
+
SELECT *
|
|
109
|
+
WHERE {{
|
|
110
|
+
?id a {_get_namespace(cls.__name__)} .
|
|
111
|
+
?id ?p ?o .
|
|
112
|
+
}}"""
|
|
113
|
+
return query_str
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _query_by_id(graph, _id: Union[str, rdflib.URIRef], add_type: bool) -> Dict:
|
|
117
|
+
"""Query the graph by the id. Return the data as a dictionary."""
|
|
118
|
+
_sub_query_string = """SELECT DISTINCT ?p ?o WHERE { <%s> ?p ?o }""" % _id
|
|
119
|
+
_sub_res = graph.query(_sub_query_string)
|
|
120
|
+
out = {'@id': str(_id)}
|
|
121
|
+
for binding in _sub_res.bindings:
|
|
122
|
+
predicate = binding['p']
|
|
123
|
+
obj = binding['o']
|
|
124
|
+
|
|
125
|
+
if predicate == rdflib.RDF.type:
|
|
126
|
+
if add_type:
|
|
127
|
+
out['@type'] = str(obj)
|
|
128
|
+
continue
|
|
129
|
+
|
|
130
|
+
_, key = split_uri(predicate)
|
|
131
|
+
if str(_id) == str(obj):
|
|
132
|
+
# would lead to a circular reference. Example for it: "landingPage" and "_id" are the same.
|
|
133
|
+
# in this case, we return the object as a string
|
|
134
|
+
out[key] = str(obj)
|
|
135
|
+
else:
|
|
136
|
+
if key in out:
|
|
137
|
+
if isinstance(out[key], list):
|
|
138
|
+
out[key].append(process_object(_id, predicate, obj, graph, add_type))
|
|
139
|
+
else:
|
|
140
|
+
out[key] = [out[key], process_object(_id, predicate, obj, graph, add_type)]
|
|
141
|
+
else:
|
|
142
|
+
out[key] = process_object(_id, predicate, obj, graph, add_type)
|
|
143
|
+
|
|
144
|
+
return out
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _is_type_definition(graph, iri: Union[str, rdflib.URIRef]):
|
|
148
|
+
_sub_query_string = """PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
|
|
149
|
+
SELECT DISTINCT ?o WHERE { <%s> rdf:type ?o }""" % iri
|
|
150
|
+
_sub_res = graph.query(_sub_query_string)
|
|
151
|
+
return len(_sub_res) == 1
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def expand_sparql_res(bindings,
|
|
155
|
+
graph,
|
|
156
|
+
add_type: bool,
|
|
157
|
+
add_context: bool) -> Dict:
|
|
158
|
+
"""Expand the SPARQL results. Return a dictionary."""
|
|
159
|
+
out = {}
|
|
160
|
+
# n_ = len(bindings)
|
|
161
|
+
for i, binding in enumerate(bindings):
|
|
162
|
+
logger.debug(
|
|
163
|
+
f'Expanding SPARQL results {i + 1}/{len(bindings)}: {binding["?id"]}, {binding["p"]}, {binding["?o"]}.')
|
|
164
|
+
|
|
165
|
+
if isinstance(binding['?id'], rdflib.URIRef):
|
|
166
|
+
_id = str(binding['?id'])
|
|
167
|
+
else:
|
|
168
|
+
_id = binding['?id'].n3()
|
|
169
|
+
if _id not in out:
|
|
170
|
+
out[_id] = {}
|
|
171
|
+
if add_context:
|
|
172
|
+
out[_id] = {'@context': {}}
|
|
173
|
+
p = binding['p'].__str__()
|
|
174
|
+
_, predicate = split_uri(p)
|
|
175
|
+
|
|
176
|
+
if predicate == 'type':
|
|
177
|
+
if add_type:
|
|
178
|
+
out[_id]['@type'] = str(binding['o'])
|
|
179
|
+
continue
|
|
180
|
+
if add_context:
|
|
181
|
+
out[_id]['@context'][predicate] = str(p)
|
|
182
|
+
|
|
183
|
+
obj = str(binding['?o'])
|
|
184
|
+
|
|
185
|
+
logger.debug(f'Processing object "{obj}" for predicate "{predicate}".')
|
|
186
|
+
data = process_object(_id, predicate, binding['?o'], graph, add_type)
|
|
187
|
+
|
|
188
|
+
# well obj is just a data field, add it
|
|
189
|
+
if predicate in out[_id]:
|
|
190
|
+
if isinstance(out[_id][predicate], list):
|
|
191
|
+
out[_id][predicate].append(data)
|
|
192
|
+
else:
|
|
193
|
+
out[_id][predicate] = [out[_id][predicate], data]
|
|
194
|
+
else:
|
|
195
|
+
out[_id][predicate] = data
|
|
196
|
+
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def dquery(subject: str,
|
|
201
|
+
source: Optional[Union[str, pathlib.Path]] = None,
|
|
202
|
+
data: Optional[Union[str, Dict]] = None,
|
|
203
|
+
context: Optional[Dict] = None) -> List[Dict]:
|
|
204
|
+
"""Return a list of resutls. The entries are dictionaries.
|
|
205
|
+
|
|
206
|
+
Example
|
|
207
|
+
-------
|
|
208
|
+
>>> # Query all agents from the source file
|
|
209
|
+
>>> import ontolutils
|
|
210
|
+
>>> ontolutils.dquery(subject='prov:Agent', source='agent1.jsonld')
|
|
211
|
+
"""
|
|
212
|
+
g = rdflib.Graph()
|
|
213
|
+
g.parse(source=source,
|
|
214
|
+
data=data,
|
|
215
|
+
format='json-ld',
|
|
216
|
+
context=context)
|
|
217
|
+
if context is None:
|
|
218
|
+
context = {}
|
|
219
|
+
prefixes = "".join([f"PREFIX {k}: <{p}>\n" for k, p in context.items() if not k.startswith('@')])
|
|
220
|
+
|
|
221
|
+
assert isinstance(subject, str), f"Subject must be a string, not {type(subject)}"
|
|
222
|
+
|
|
223
|
+
query_str = f"""
|
|
224
|
+
SELECT *
|
|
225
|
+
WHERE {{
|
|
226
|
+
?id a {subject}.
|
|
227
|
+
?id ?p ?o .
|
|
228
|
+
}}"""
|
|
229
|
+
|
|
230
|
+
res = g.query(prefixes + query_str)
|
|
231
|
+
|
|
232
|
+
if len(res) == 0:
|
|
233
|
+
return []
|
|
234
|
+
|
|
235
|
+
logger.debug(f'Querying subject="{subject}" with query: "{prefixes + query_str}" and got {len(res)} results')
|
|
236
|
+
|
|
237
|
+
kwargs: Dict = expand_sparql_res(res.bindings, g, True, True)
|
|
238
|
+
for _id in kwargs:
|
|
239
|
+
kwargs[_id]['@id'] = _id
|
|
240
|
+
return [v for v in kwargs.values()]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def query(cls: Type[Thing],
|
|
244
|
+
source: Optional[Union[str, pathlib.Path]] = None,
|
|
245
|
+
data: Optional[Union[str, Dict]] = None,
|
|
246
|
+
format: Optional[str] = None,
|
|
247
|
+
context: Optional[Union[Dict, str]] = None,
|
|
248
|
+
limit: Optional[int] = None) -> Union[Thing, List]:
|
|
249
|
+
"""Return a generator of results from the query.
|
|
250
|
+
|
|
251
|
+
Parameters
|
|
252
|
+
----------
|
|
253
|
+
cls : Thing
|
|
254
|
+
The class to query
|
|
255
|
+
source: Optional[Union[str, pathlib.Path]]
|
|
256
|
+
The source of the RDF file. see json.dump() for details
|
|
257
|
+
data : Optional[Union[str, Dict]]
|
|
258
|
+
The data of the RDF file
|
|
259
|
+
format : Optional[str]
|
|
260
|
+
The format of the RDF file. see rdflib.Graph.parse() for details
|
|
261
|
+
context : Optional[Union[Dict, str]]
|
|
262
|
+
The context of the RDF file
|
|
263
|
+
limit: Optional[int]
|
|
264
|
+
The limit of the query. Default is None (no limit).
|
|
265
|
+
If limit equals to 1, the result will be a single obj, not a list.
|
|
266
|
+
"""
|
|
267
|
+
if cls == Thing:
|
|
268
|
+
query_string = '\nSELECT *\nWHERE {\n ?id a ?type .\n ?id ?p ?o .\n}'
|
|
269
|
+
else:
|
|
270
|
+
query_string = get_query_string(
|
|
271
|
+
cls) # TODO: limit should be passed here, however the sparql query must be written yet
|
|
272
|
+
g = rdflib.Graph()
|
|
273
|
+
|
|
274
|
+
ns_keys = [_ns[0] for _ns in g.namespaces()]
|
|
275
|
+
|
|
276
|
+
prefixes = "".join([f"PREFIX {k}: <{p}>\n" for k, p in NamespaceManager[cls].items() if not k.startswith('@')])
|
|
277
|
+
for k, p in NamespaceManager[cls].items():
|
|
278
|
+
if k not in ns_keys:
|
|
279
|
+
g.bind(k, p)
|
|
280
|
+
# logger.debug(k)
|
|
281
|
+
g.bind(k, p)
|
|
282
|
+
|
|
283
|
+
if isinstance(data, dict):
|
|
284
|
+
data = json.dumps(data)
|
|
285
|
+
|
|
286
|
+
_context = cls.get_context()
|
|
287
|
+
|
|
288
|
+
if context is None:
|
|
289
|
+
context = {}
|
|
290
|
+
|
|
291
|
+
if not isinstance(context, dict):
|
|
292
|
+
raise TypeError(f"Context must be a dict, not {type(context)}")
|
|
293
|
+
|
|
294
|
+
_context.update(context)
|
|
295
|
+
|
|
296
|
+
g.parse(source=source,
|
|
297
|
+
data=data,
|
|
298
|
+
format=format)
|
|
299
|
+
# add context namespaces:
|
|
300
|
+
for k, p in _context.items():
|
|
301
|
+
if k.startswith('@'):
|
|
302
|
+
continue
|
|
303
|
+
if k not in ns_keys:
|
|
304
|
+
g.bind(k, p)
|
|
305
|
+
|
|
306
|
+
gquery = prefixes + query_string
|
|
307
|
+
|
|
308
|
+
logger.debug(f'Querying class "{cls.__name__}" with query: {gquery}')
|
|
309
|
+
# logger.debug(prefixes + query_string)
|
|
310
|
+
res = g.query(gquery)
|
|
311
|
+
|
|
312
|
+
logger.debug(f'Querying resulted in {len(res)} results')
|
|
313
|
+
|
|
314
|
+
if len(res) == 0:
|
|
315
|
+
return []
|
|
316
|
+
|
|
317
|
+
logger.debug(f'Expanding SPARQL results...')
|
|
318
|
+
kwargs: Dict = expand_sparql_res(res.bindings, g, False, False)
|
|
319
|
+
|
|
320
|
+
# in case that the model field names are different than the IRI names, we need to find the
|
|
321
|
+
# corresponding names. The urirefs translate the class model fields to a <prefix>:<name> format.
|
|
322
|
+
# As we have the latter, the inverse dictionary let's us find the model field names.
|
|
323
|
+
# inverse_urirefs = {_v.split(':', 1)[-1]: _k for _k, _v in get_urirefs(cls).items()}
|
|
324
|
+
|
|
325
|
+
kwargs = _at_id_to_id(_expand_compact_iris(kwargs, _context))
|
|
326
|
+
|
|
327
|
+
if limit is not None:
|
|
328
|
+
out = []
|
|
329
|
+
for i, (k, v) in enumerate(kwargs.items()):
|
|
330
|
+
model_field_dict = v # {inverse_urirefs.get(key, key): value for key, value in v.items()}
|
|
331
|
+
if limit == 1:
|
|
332
|
+
return cls.model_validate({'id': k, **model_field_dict})
|
|
333
|
+
out.append(cls.model_validate({'id': k, **model_field_dict}))
|
|
334
|
+
if i == limit - 1:
|
|
335
|
+
return out
|
|
336
|
+
|
|
337
|
+
return [cls.model_validate({'id': _id, **params}) for _id, params in kwargs.items()]
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
_SCHEME_RE = re.compile(r'^[A-Za-z][A-Za-z0-9+.-]*:')
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _expand_compact_iris(obj, context, *, transform_keys=False):
|
|
344
|
+
"""
|
|
345
|
+
Recursively expand 'prefix:suffix' strings using a JSON-LD-like context.
|
|
346
|
+
|
|
347
|
+
- obj: any nested structure (dict/list/tuple/set/str/…).
|
|
348
|
+
- context: mapping like {'pivmeta': 'https://…#', ...}.
|
|
349
|
+
If a context value is a dict (e.g. {'@id': '…'}), '@id' is used.
|
|
350
|
+
- transform_keys: if True, also expand dictionary KEYS that are 'prefix:suffix'.
|
|
351
|
+
|
|
352
|
+
Returns a new structure with expansions applied.
|
|
353
|
+
"""
|
|
354
|
+
# Normalize context to {prefix: base_iri_string}
|
|
355
|
+
prefixes = {}
|
|
356
|
+
for k, v in context.items():
|
|
357
|
+
if k.startswith('@'):
|
|
358
|
+
continue
|
|
359
|
+
if isinstance(v, str):
|
|
360
|
+
prefixes[k] = v
|
|
361
|
+
elif isinstance(v, Mapping):
|
|
362
|
+
iri = v.get('@id')
|
|
363
|
+
if isinstance(iri, str):
|
|
364
|
+
prefixes[k] = iri
|
|
365
|
+
|
|
366
|
+
def expand_str(s: str) -> str:
|
|
367
|
+
# Only consider exact 'prefix:suffix' forms where prefix is in context.
|
|
368
|
+
if ':' in s and not s.startswith(('http://', 'https://', 'urn:', 'mailto:')):
|
|
369
|
+
pref, rest = s.split(':', 1)
|
|
370
|
+
base = prefixes.get(pref)
|
|
371
|
+
if base:
|
|
372
|
+
# Ensure we don't accidentally drop/add separators incorrectly
|
|
373
|
+
needs_sep = not (base.endswith(('/', '#')) or rest.startswith(('/', '#')))
|
|
374
|
+
sep = '#' if needs_sep else ''
|
|
375
|
+
return f"{base}{sep}{rest}"
|
|
376
|
+
return s
|
|
377
|
+
|
|
378
|
+
def expand_any(x):
|
|
379
|
+
if isinstance(x, str):
|
|
380
|
+
return expand_str(x)
|
|
381
|
+
elif isinstance(x, Mapping):
|
|
382
|
+
if transform_keys:
|
|
383
|
+
return {expand_str(k) if isinstance(k, str) else k: expand_any(v)
|
|
384
|
+
for k, v in x.items()}
|
|
385
|
+
else:
|
|
386
|
+
return {k: expand_any(v) for k, v in x.items()}
|
|
387
|
+
elif isinstance(x, tuple):
|
|
388
|
+
return tuple(expand_any(i) for i in x)
|
|
389
|
+
elif isinstance(x, set):
|
|
390
|
+
return {expand_any(i) for i in x}
|
|
391
|
+
elif isinstance(x, list):
|
|
392
|
+
return [expand_any(i) for i in x]
|
|
393
|
+
else:
|
|
394
|
+
return x
|
|
395
|
+
|
|
396
|
+
return expand_any(obj)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _at_id_to_id(data: Dict) -> Dict:
|
|
400
|
+
"""Convert recursively '@id' keys to 'id' keys in a dictionary."""
|
|
401
|
+
"""Convert '@id' keys to 'id' keys in a dictionary."""
|
|
402
|
+
if isinstance(data, dict):
|
|
403
|
+
new_data = {}
|
|
404
|
+
for k, v in data.items():
|
|
405
|
+
if k == '@id':
|
|
406
|
+
new_data['id'] = v
|
|
407
|
+
else:
|
|
408
|
+
new_data[k] = _at_id_to_id(v)
|
|
409
|
+
return new_data
|
|
410
|
+
elif isinstance(data, list):
|
|
411
|
+
return [_at_id_to_id(item) for item in data]
|
|
412
|
+
else:
|
|
413
|
+
return data
|