ontolutils 0.2.7__tar.gz → 0.2.9__tar.gz
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-0.2.7 → ontolutils-0.2.9}/PKG-INFO +1 -1
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/__init__.py +4 -1
- ontolutils-0.2.9/ontolutils/classes/__init__.py +6 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/classes/decorator.py +1 -0
- ontolutils-0.2.9/ontolutils/classes/thing.py +440 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/__dev.py +16 -14
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/pivmeta.py +6 -2
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils.egg-info/PKG-INFO +1 -1
- {ontolutils-0.2.7 → ontolutils-0.2.9}/setup.cfg +1 -1
- {ontolutils-0.2.7 → ontolutils-0.2.9}/tests/test_classes.py +90 -56
- {ontolutils-0.2.7 → ontolutils-0.2.9}/tests/test_readme.py +14 -1
- ontolutils-0.2.7/ontolutils/classes/__init__.py +0 -6
- ontolutils-0.2.7/ontolutils/classes/thing.py +0 -289
- {ontolutils-0.2.7 → ontolutils-0.2.9}/LICENSE +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/README.md +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/_version.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/cache.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/classes/query_util.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/classes/typing.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/classes/utils.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/__init__.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/_iana_utils.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/codemeta.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/m4i.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/obo.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/qudt_kind.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/qudt_unit.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/schema.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils/namespacelib/ssno.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils.egg-info/SOURCES.txt +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils.egg-info/dependency_links.txt +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils.egg-info/requires.txt +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/ontolutils.egg-info/top_level.txt +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/pyproject.toml +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/setup.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/tests/test_decorator.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/tests/test_namespaces.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/tests/test_query.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/tests/test_typing.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/tests/test_utils.py +0 -0
- {ontolutils-0.2.7 → ontolutils-0.2.9}/tests/test_version.py +0 -0
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import logging
|
|
3
3
|
|
|
4
4
|
from ._version import __version__
|
|
5
|
-
from .classes import Thing
|
|
5
|
+
from .classes import Thing, get_urirefs, get_namespaces
|
|
6
6
|
from .classes import namespaces, urirefs
|
|
7
7
|
from .classes import query, dquery
|
|
8
8
|
from .classes.utils import merge_jsonld
|
|
@@ -35,4 +35,7 @@ __all__ = ['Thing',
|
|
|
35
35
|
'query',
|
|
36
36
|
'set_logging_level',
|
|
37
37
|
'merge_jsonld',
|
|
38
|
+
'dquery',
|
|
39
|
+
'get_urirefs',
|
|
40
|
+
'get_namespaces',
|
|
38
41
|
]
|
|
@@ -0,0 +1,6 @@
|
|
|
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
|
|
5
|
+
|
|
6
|
+
__all__ = ['namespaces', 'urirefs', 'Thing', 'query', 'dquery', 'get_urirefs', 'get_namespaces']
|
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import abc
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import pathlib
|
|
5
|
+
import rdflib
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pydantic import HttpUrl, FileUrl, BaseModel, ConfigDict
|
|
8
|
+
from typing import Dict, Union, Optional
|
|
9
|
+
|
|
10
|
+
from .decorator import urirefs, namespaces, URIRefManager, NamespaceManager, _is_http_url
|
|
11
|
+
from .typing import BlankNodeType
|
|
12
|
+
from .utils import split_URIRef
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger('ontolutils')
|
|
15
|
+
|
|
16
|
+
EXTRA = 'allow' # or 'forbid' or 'ignore'
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ThingModel(BaseModel, abc.ABC):
|
|
20
|
+
"""Abstract base model class to be used by model classes used within ontolutils"""
|
|
21
|
+
|
|
22
|
+
model_config = ConfigDict(extra=EXTRA)
|
|
23
|
+
|
|
24
|
+
@abc.abstractmethod
|
|
25
|
+
def _repr_html_(self) -> str:
|
|
26
|
+
"""Returns the HTML representation of the class"""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def resolve_iri(iri: str, context: Dict) -> str:
|
|
30
|
+
"""Resolves short iri string which uses prefix, e.g.
|
|
31
|
+
converts 'foaf:firstName' to 'http://xmlns.com/foaf/0.1/firstName'
|
|
32
|
+
if the prefix is not found in context, the input iri string is
|
|
33
|
+
returned.
|
|
34
|
+
"""
|
|
35
|
+
if iri.startswith('http'):
|
|
36
|
+
return iri
|
|
37
|
+
ns, key = split_URIRef(iri)
|
|
38
|
+
prefix_iri = context.get(ns, None)
|
|
39
|
+
if prefix_iri is None:
|
|
40
|
+
return iri
|
|
41
|
+
return f'{prefix_iri}{key}'
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@namespaces(owl='http://www.w3.org/2002/07/owl#',
|
|
45
|
+
rdfs='http://www.w3.org/2000/01/rdf-schema#')
|
|
46
|
+
@urirefs(Thing='owl:Thing', label='rdfs:label')
|
|
47
|
+
class Thing(ThingModel):
|
|
48
|
+
"""Most basic concept class owl:Thing (see also https://www.w3.org/TR/owl-guide/)
|
|
49
|
+
|
|
50
|
+
This class is basis to model other concepts.
|
|
51
|
+
|
|
52
|
+
Example for `prov:Person`:
|
|
53
|
+
|
|
54
|
+
>>> @namespaces(prov='http://www.w3.org/ns/prov#',
|
|
55
|
+
>>> foaf='http://xmlns.com/foaf/0.1/')
|
|
56
|
+
>>> @urirefs(Person='prov:Person', first_name='foaf:firstName')
|
|
57
|
+
>>> class Person(Thing):
|
|
58
|
+
>>> first_name: str = None
|
|
59
|
+
>>> last_name: str = None
|
|
60
|
+
|
|
61
|
+
>>> p = Person(first_name='John', last_name='Doe', age=30)
|
|
62
|
+
>>> # Note, that age is not defined in the class! This is allowed, but may not be
|
|
63
|
+
>>> # serialized into an IRI although the ontology defines it
|
|
64
|
+
|
|
65
|
+
>>> print(p.model_dump_jsonld())
|
|
66
|
+
>>> {
|
|
67
|
+
>>> "@context": {
|
|
68
|
+
>>> "prov": "http://www.w3.org/ns/prov#",
|
|
69
|
+
>>> "foaf": "http://xmlns.com/foaf/0.1/",
|
|
70
|
+
>>> "first_name": "foaf:firstName"
|
|
71
|
+
>>> },
|
|
72
|
+
>>> "@id": "N23036f1a4eb149edb7db41b2f5f4268c",
|
|
73
|
+
>>> "@type": "prov:Person",
|
|
74
|
+
>>> "foaf:firstName": "John",
|
|
75
|
+
>>> "last_name": "Doe",
|
|
76
|
+
>>> "age": "30" # Age appears as a field without context!
|
|
77
|
+
>>> }
|
|
78
|
+
|
|
79
|
+
Note, that values are validated, as `Thing` is a subclass of `pydantic.BaseModel`:
|
|
80
|
+
|
|
81
|
+
>>> Person(first_name=1)
|
|
82
|
+
|
|
83
|
+
Will lead to a validation error:
|
|
84
|
+
|
|
85
|
+
>>> # Traceback (most recent call last):
|
|
86
|
+
>>> # ...
|
|
87
|
+
>>> # pydantic_core._pydantic_core.ValidationError: 1 validation error for Person
|
|
88
|
+
>>> # first_name
|
|
89
|
+
>>> # Input should be a valid string [type=string_type, input_value=1, input_type=int]
|
|
90
|
+
>>> # For further information visit https://errors.pydantic.dev/2.4/v/string_type
|
|
91
|
+
|
|
92
|
+
"""
|
|
93
|
+
id: Union[str, HttpUrl, FileUrl, BlankNodeType, None] = None # @id
|
|
94
|
+
label: str = None # rdfs:label
|
|
95
|
+
|
|
96
|
+
def __lt__(self, other: ThingModel) -> bool:
|
|
97
|
+
"""Less than comparison. Useful to sort Thing objects.
|
|
98
|
+
Comparison can only be done with other Thing objects and if an ID is given.
|
|
99
|
+
If one of the objects has no ID, then False is returned."""
|
|
100
|
+
if not isinstance(other, ThingModel):
|
|
101
|
+
raise TypeError(f"Cannot compare {self.__class__} with {type(other)}")
|
|
102
|
+
if self.id is None or other.id is None:
|
|
103
|
+
return False
|
|
104
|
+
return self.id <= other.id
|
|
105
|
+
|
|
106
|
+
def get_jsonld_dict(self,
|
|
107
|
+
context: Optional[Union[Dict, str]] = None,
|
|
108
|
+
exclude_none: bool = True,
|
|
109
|
+
resolve_keys: bool = False) -> Dict:
|
|
110
|
+
"""Return the JSON-LD dictionary of the object. This will include the context
|
|
111
|
+
and the fields of the object.
|
|
112
|
+
|
|
113
|
+
Parameters
|
|
114
|
+
----------
|
|
115
|
+
context: Optional[Union[Dict, str]]
|
|
116
|
+
The context to use for the JSON-LD serialization. If a string is given, it will
|
|
117
|
+
be interpreted as an import statement and will be added to the context.
|
|
118
|
+
exclude_none: bool=True
|
|
119
|
+
Exclude fields with None values
|
|
120
|
+
resolve_keys: bool=False
|
|
121
|
+
If True, then attributes of a Thing class will be resolved to the full IRI and
|
|
122
|
+
explained in the context.
|
|
123
|
+
|
|
124
|
+
Example:
|
|
125
|
+
|
|
126
|
+
In the following example, first_name refers to foaf:firstName:
|
|
127
|
+
|
|
128
|
+
>>> @namespaces(foaf='http://xmlns.com/foaf/0.1/')
|
|
129
|
+
>>> @urirefs(Person='foaf:Person', first_name='foaf:firstName')
|
|
130
|
+
>>> class Person(Thing):
|
|
131
|
+
>>> first_name: str = None
|
|
132
|
+
|
|
133
|
+
>>> p = Person(first_name='John')
|
|
134
|
+
>>> p.model_dump_jsonld(resolve_keys=True)
|
|
135
|
+
|
|
136
|
+
This will result "first_name": "foaf:firstName" showing up in the context:
|
|
137
|
+
|
|
138
|
+
>>> {
|
|
139
|
+
>>> "@context": {
|
|
140
|
+
>>> "foaf": "http://xmlns.com/foaf/0.1/",
|
|
141
|
+
>>> "first_name": "foaf:firstName"
|
|
142
|
+
>>> },
|
|
143
|
+
>>> "@type": "foaf:Person",
|
|
144
|
+
>>> "foaf:firstName": "John"
|
|
145
|
+
>>> }
|
|
146
|
+
|
|
147
|
+
While resolve_keys=False will result in:
|
|
148
|
+
|
|
149
|
+
>>> {
|
|
150
|
+
>>> "@context": {
|
|
151
|
+
>>> "foaf": "http://xmlns.com/foaf/0.1/"
|
|
152
|
+
>>> },
|
|
153
|
+
>>> "@type": "foaf:Person",
|
|
154
|
+
>>> "foaf:firstName": "John"
|
|
155
|
+
>>> }
|
|
156
|
+
|
|
157
|
+
Returns
|
|
158
|
+
-------
|
|
159
|
+
Dict
|
|
160
|
+
The JSON-LD dictionary
|
|
161
|
+
"""
|
|
162
|
+
logger.debug('Initializing RDF graph to dump the Thing to JSON-LD')
|
|
163
|
+
|
|
164
|
+
# lets auto-generate the context
|
|
165
|
+
at_context: Dict = NamespaceManager.get(self.__class__, {})
|
|
166
|
+
|
|
167
|
+
if context is None:
|
|
168
|
+
context = {}
|
|
169
|
+
|
|
170
|
+
if not isinstance(context, dict):
|
|
171
|
+
raise TypeError(f"Context must be a dict, not {type(context)}")
|
|
172
|
+
|
|
173
|
+
at_context.update(**context)
|
|
174
|
+
|
|
175
|
+
logger.debug(f'The context is "{at_context}".')
|
|
176
|
+
|
|
177
|
+
def serialize_fields(
|
|
178
|
+
obj: Union[ThingModel, int, str, float, bool, datetime],
|
|
179
|
+
exclude_none: bool = True
|
|
180
|
+
) -> Union[Dict, int, str, float, bool]:
|
|
181
|
+
"""Serializes the fields of a Thing object into a json-ld
|
|
182
|
+
dictionary (without context!). Note, that IDs can automatically be
|
|
183
|
+
generated (with a local prefix)
|
|
184
|
+
|
|
185
|
+
Parameter
|
|
186
|
+
---------
|
|
187
|
+
obj: Union[ThingModel, int, str, float, bool, datetime]
|
|
188
|
+
The object to serialize (a subclass of ThingModel). All other types will
|
|
189
|
+
be returned as is. One exception is datetime, which will be serialized
|
|
190
|
+
to an ISO string.
|
|
191
|
+
exclude_none: bool=True
|
|
192
|
+
If True, fields with None values will be excluded from the
|
|
193
|
+
serialization
|
|
194
|
+
|
|
195
|
+
Returns
|
|
196
|
+
-------
|
|
197
|
+
Union[Dict, int, str, float, bool]
|
|
198
|
+
The serialized fields or the object as is
|
|
199
|
+
"""
|
|
200
|
+
if isinstance(obj, (int, str, float, bool)):
|
|
201
|
+
return obj
|
|
202
|
+
if isinstance(obj, datetime):
|
|
203
|
+
return obj.isoformat()
|
|
204
|
+
|
|
205
|
+
uri_ref_manager = URIRefManager.get(obj.__class__, None)
|
|
206
|
+
at_context.update(NamespaceManager.get(obj.__class__, {}))
|
|
207
|
+
if uri_ref_manager is None:
|
|
208
|
+
return obj
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
if exclude_none:
|
|
212
|
+
serialized_fields = {}
|
|
213
|
+
for k in obj.model_dump(exclude_none=True):
|
|
214
|
+
value = getattr(obj, k)
|
|
215
|
+
if value is not None and k not in ('id', '@id'):
|
|
216
|
+
iri = uri_ref_manager.get(k, k)
|
|
217
|
+
if _is_http_url(iri):
|
|
218
|
+
serialized_fields[iri] = value
|
|
219
|
+
if isinstance(value, str): # this turn URLs into base strings
|
|
220
|
+
ns, key = split_URIRef(iri)
|
|
221
|
+
if key != k and not resolve_keys:
|
|
222
|
+
at_context[k] = resolve_iri(iri,
|
|
223
|
+
at_context) # the key is not resolved, hence the key and iri is put into context dict:
|
|
224
|
+
serialized_fields[k] = str(value)
|
|
225
|
+
else:
|
|
226
|
+
serialized_fields[iri] = str(value)
|
|
227
|
+
else:
|
|
228
|
+
serialized_fields[iri] = value
|
|
229
|
+
else:
|
|
230
|
+
serialized_fields = {}
|
|
231
|
+
for k in obj.model_dump(exclude_none=True):
|
|
232
|
+
value = getattr(obj, k)
|
|
233
|
+
if value not in ('id', '@id'):
|
|
234
|
+
iri = uri_ref_manager[k]
|
|
235
|
+
if _is_http_url(iri):
|
|
236
|
+
serialized_fields[k] = value
|
|
237
|
+
else:
|
|
238
|
+
serialized_fields[iri] = value
|
|
239
|
+
except AttributeError as e:
|
|
240
|
+
raise AttributeError(f"Could not serialize {obj} ({obj.__class__}). Orig. err: {e}") from e
|
|
241
|
+
|
|
242
|
+
# if obj.model_config['extra'] == 'allow':
|
|
243
|
+
# for k, v in obj.model_extra.items():
|
|
244
|
+
# iri = uri_ref_manager.get(k, k)
|
|
245
|
+
# if _is_http_url(iri):
|
|
246
|
+
# serialized_fields[k] = v
|
|
247
|
+
# else:
|
|
248
|
+
# serialized_fields[iri] = v
|
|
249
|
+
|
|
250
|
+
# datetime
|
|
251
|
+
for k, v in serialized_fields.copy().items():
|
|
252
|
+
_field = serialized_fields.pop(k)
|
|
253
|
+
key = k
|
|
254
|
+
if isinstance(v, datetime):
|
|
255
|
+
serialized_fields[key] = serialize_fields(v)
|
|
256
|
+
elif isinstance(v, Thing):
|
|
257
|
+
serialized_fields[key] = serialize_fields(v, exclude_none=exclude_none)
|
|
258
|
+
elif isinstance(v, list):
|
|
259
|
+
serialized_fields[key] = [serialize_fields(i, exclude_none=exclude_none) for i in v]
|
|
260
|
+
else:
|
|
261
|
+
serialized_fields[key] = str(v)
|
|
262
|
+
|
|
263
|
+
_type = URIRefManager[obj.__class__].get(obj.__class__.__name__, obj.__class__.__name__)
|
|
264
|
+
|
|
265
|
+
out = {"@type": _type, **serialized_fields}
|
|
266
|
+
# if no ID is given, generate a local one:
|
|
267
|
+
if obj.id is not None:
|
|
268
|
+
out["@id"] = obj.id
|
|
269
|
+
else:
|
|
270
|
+
out["@id"] = rdflib.BNode()
|
|
271
|
+
return out
|
|
272
|
+
|
|
273
|
+
serialization = serialize_fields(self, exclude_none=exclude_none)
|
|
274
|
+
|
|
275
|
+
jsonld = {
|
|
276
|
+
"@context": at_context,
|
|
277
|
+
**serialization
|
|
278
|
+
}
|
|
279
|
+
return jsonld
|
|
280
|
+
|
|
281
|
+
def model_dump_jsonld(self,
|
|
282
|
+
context: Optional[Dict] = None,
|
|
283
|
+
exclude_none: bool = True,
|
|
284
|
+
rdflib_serialize: bool = False,
|
|
285
|
+
resolve_keys: bool = False) -> str:
|
|
286
|
+
"""Similar to model_dump_json() but will return a JSON string with
|
|
287
|
+
context resulting in a JSON-LD serialization. Using `rdflib_serialize=True`
|
|
288
|
+
will use the rdflib to serialize. This will make the output a bit cleaner
|
|
289
|
+
but is not needed in most cases and just takes a bit more time (and requires
|
|
290
|
+
an internet connection.
|
|
291
|
+
|
|
292
|
+
Note, that if `rdflib_serialize=True`, then a blank node will be generated if no ID is set.
|
|
293
|
+
|
|
294
|
+
Parameters
|
|
295
|
+
----------
|
|
296
|
+
context: Optional[Union[Dict, str]]
|
|
297
|
+
The context to use for the JSON-LD serialization. If a string is given, it will
|
|
298
|
+
be interpreted as an import statement and will be added to the context.
|
|
299
|
+
exclude_none: bool=True
|
|
300
|
+
Exclude fields with None values
|
|
301
|
+
rdflib_serialize: bool=False
|
|
302
|
+
If True, the output will be serialized using rdflib. This results in a cleaner
|
|
303
|
+
output but is not needed in most cases and just takes a bit more time (and requires
|
|
304
|
+
an internet connection). Will also generate a blank node if no ID is set.
|
|
305
|
+
resolve_keys: bool=False
|
|
306
|
+
If True, then attributes of a Thing class will be resolved to the full IRI and
|
|
307
|
+
explained in the context.
|
|
308
|
+
|
|
309
|
+
.. seealso:: `Thing.get_jsonld_dict`
|
|
310
|
+
|
|
311
|
+
Returns
|
|
312
|
+
-------
|
|
313
|
+
str
|
|
314
|
+
The JSON-LD string
|
|
315
|
+
"""
|
|
316
|
+
jsonld_dict = self.get_jsonld_dict(
|
|
317
|
+
context=context,
|
|
318
|
+
exclude_none=exclude_none,
|
|
319
|
+
resolve_keys=resolve_keys
|
|
320
|
+
)
|
|
321
|
+
jsonld_str = json.dumps(jsonld_dict, indent=4)
|
|
322
|
+
if not rdflib_serialize:
|
|
323
|
+
return jsonld_str
|
|
324
|
+
|
|
325
|
+
logger.debug(f'Parsing the following jsonld dict to the RDF graph: {jsonld_str}')
|
|
326
|
+
g = rdflib.Graph()
|
|
327
|
+
g.parse(data=jsonld_str, format='json-ld')
|
|
328
|
+
|
|
329
|
+
_context = jsonld_dict.get('@context', {})
|
|
330
|
+
if context:
|
|
331
|
+
_context.update(context)
|
|
332
|
+
|
|
333
|
+
return g.serialize(format='json-ld',
|
|
334
|
+
context=_context,
|
|
335
|
+
indent=4)
|
|
336
|
+
|
|
337
|
+
def __repr__(self):
|
|
338
|
+
_fields = {k: getattr(self, k) for k in self.model_fields if getattr(self, k) is not None}
|
|
339
|
+
repr_fields = ", ".join([f"{k}={v}" for k, v in _fields.items()])
|
|
340
|
+
if self.model_config['extra'] == 'allow':
|
|
341
|
+
if len(self.model_extra) > 0:
|
|
342
|
+
repr_extra = ", ".join([f"{k}={v}" for k, v in self.model_extra.items()])
|
|
343
|
+
return f"{self.__class__.__name__}({repr_fields}, {repr_extra})"
|
|
344
|
+
return f"{self.__class__.__name__}({repr_fields})"
|
|
345
|
+
|
|
346
|
+
def __str__(self):
|
|
347
|
+
return self.__repr__()
|
|
348
|
+
|
|
349
|
+
def _repr_html_(self) -> str:
|
|
350
|
+
"""Returns the HTML representation of the class"""
|
|
351
|
+
_fields = {k: getattr(self, k) for k in self.model_fields if getattr(self, k) is not None}
|
|
352
|
+
repr_fields = ", ".join([f"{k}={v}" for k, v in _fields.items()])
|
|
353
|
+
return f"{self.__class__.__name__}({repr_fields})"
|
|
354
|
+
|
|
355
|
+
@classmethod
|
|
356
|
+
def from_jsonld(cls,
|
|
357
|
+
source: Optional[Union[str, pathlib.Path]] = None,
|
|
358
|
+
data: Optional[Dict] = None,
|
|
359
|
+
limit: Optional[int] = None,
|
|
360
|
+
context: Optional[Dict] = None):
|
|
361
|
+
"""Initialize the class from a JSON-LD source
|
|
362
|
+
|
|
363
|
+
Note the inconsistency in the schema.org protocol. Codemeta for instance uses http whereas
|
|
364
|
+
https is the current standard. This repo only works with https. If you have a http schema,
|
|
365
|
+
this method will replace http with https.
|
|
366
|
+
|
|
367
|
+
Parameters
|
|
368
|
+
----------
|
|
369
|
+
source: Optional[Union[str, pathlib.Path]]=None
|
|
370
|
+
The source of the JSON-LD data (filename). Must be given if data is None.
|
|
371
|
+
data: Optional[str]=None
|
|
372
|
+
The JSON-LD data as a string. Must be given if source is None.
|
|
373
|
+
limit: Optional[int]=None
|
|
374
|
+
The limit of the number of objects to return. If None, all objects will be returned.
|
|
375
|
+
If limit is 1, then the first object will be returned, else a list of objects.
|
|
376
|
+
context: Optional[Dict]=None
|
|
377
|
+
The context to use for the JSON-LD serialization. If a string is given, it will
|
|
378
|
+
be interpreted as an import statement and will be added to the context.
|
|
379
|
+
|
|
380
|
+
"""
|
|
381
|
+
from . import query
|
|
382
|
+
if data is not None and isinstance(data, str):
|
|
383
|
+
if 'http://schema.org/' in data:
|
|
384
|
+
print(
|
|
385
|
+
'Replacing http with https in the JSON-LD data. This is a workaround for the schema.org inconsistency.')
|
|
386
|
+
data = data.replace('http://schema.org/', 'https://schema.org/')
|
|
387
|
+
return query(cls, source=source, data=data, limit=limit, context=context)
|
|
388
|
+
|
|
389
|
+
@classmethod
|
|
390
|
+
def iri(cls, key: str = None, compact: bool = False):
|
|
391
|
+
"""Return the IRI of the class or the key
|
|
392
|
+
|
|
393
|
+
Parameter
|
|
394
|
+
---------
|
|
395
|
+
key: str
|
|
396
|
+
The key (field) of the class
|
|
397
|
+
compact: bool
|
|
398
|
+
If True, returns the short form of the IRI, e.g. 'owl:Thing'
|
|
399
|
+
If False, returns the full IRI, e.g. 'http://www.w3.org/2002/07/owl#Thing'
|
|
400
|
+
|
|
401
|
+
Returns
|
|
402
|
+
-------
|
|
403
|
+
str
|
|
404
|
+
The IRI of the class or the key, e.g. 'http://www.w3.org/2002/07/owl#Thing' or
|
|
405
|
+
'owl:Thing' if compact is True
|
|
406
|
+
"""
|
|
407
|
+
if key is None:
|
|
408
|
+
iri_short = URIRefManager[cls][cls.__name__]
|
|
409
|
+
else:
|
|
410
|
+
iri_short = URIRefManager[cls][key]
|
|
411
|
+
if compact:
|
|
412
|
+
return iri_short
|
|
413
|
+
ns, key = split_URIRef(iri_short)
|
|
414
|
+
ns_iri = NamespaceManager[cls].get(ns, None)
|
|
415
|
+
return f'{ns_iri}{key}'
|
|
416
|
+
|
|
417
|
+
@property
|
|
418
|
+
def namespaces(self) -> Dict:
|
|
419
|
+
"""Return the namespaces of the class"""
|
|
420
|
+
return get_namespaces(self.__class__)
|
|
421
|
+
|
|
422
|
+
@property
|
|
423
|
+
def urirefs(self) -> Dict:
|
|
424
|
+
"""Return the urirefs of the class"""
|
|
425
|
+
return get_urirefs(self.__class__)
|
|
426
|
+
|
|
427
|
+
@classmethod
|
|
428
|
+
def get_context(cls) -> Dict:
|
|
429
|
+
"""Return the context of the class"""
|
|
430
|
+
return get_namespaces(cls)
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def get_urirefs(cls: Thing) -> Dict:
|
|
434
|
+
"""Return the URIRefs of the class"""
|
|
435
|
+
return URIRefManager[cls]
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def get_namespaces(cls: Thing) -> Dict:
|
|
439
|
+
"""Return the namespaces of the class"""
|
|
440
|
+
return NamespaceManager[cls]
|
|
@@ -300,29 +300,31 @@ def build_namespace_files():
|
|
|
300
300
|
# f.write('from ._version import __version__\n')
|
|
301
301
|
|
|
302
302
|
with open(__package_dir__ / '__init__.py', 'a') as f:
|
|
303
|
-
|
|
304
|
-
|
|
303
|
+
if False:
|
|
304
|
+
m4i()
|
|
305
|
+
f.write('from .m4i import M4I\n')
|
|
305
306
|
|
|
306
|
-
|
|
307
|
-
|
|
307
|
+
obo()
|
|
308
|
+
f.write('from .obo import OBO\n')
|
|
308
309
|
|
|
309
|
-
|
|
310
|
-
|
|
310
|
+
qudt_unit()
|
|
311
|
+
f.write('from .qudt_unit import QUDT_UNIT\n')
|
|
311
312
|
|
|
312
|
-
|
|
313
|
-
|
|
313
|
+
qudt_quantitykind()
|
|
314
|
+
f.write('from .qudt_kind import QUDT_KIND\n')
|
|
314
315
|
|
|
315
316
|
pivmeta()
|
|
316
317
|
f.write('from .pivmeta import PIVMETA\n')
|
|
317
318
|
|
|
318
|
-
|
|
319
|
-
|
|
319
|
+
if False:
|
|
320
|
+
codemeta()
|
|
321
|
+
f.write('from .codemeta import CODEMETA\n')
|
|
320
322
|
|
|
321
|
-
|
|
322
|
-
|
|
323
|
+
schema()
|
|
324
|
+
f.write('from .schema import SCHEMA\n')
|
|
323
325
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
+
ssno()
|
|
327
|
+
f.write('from .ssno import SSNO\n')
|
|
326
328
|
|
|
327
329
|
for jld in __package_dir__.glob('*.jsonld'):
|
|
328
330
|
jld.unlink()
|
|
@@ -7,8 +7,8 @@ class LanguageExtension:
|
|
|
7
7
|
|
|
8
8
|
class PIVMETA(DefinedNamespace):
|
|
9
9
|
# uri = "https://w3id.org/nfdi4ing/metadata4ing#"
|
|
10
|
-
# Generated with None version 0.2.
|
|
11
|
-
# Date: 2024-03-
|
|
10
|
+
# Generated with None version 0.2.8
|
|
11
|
+
# Date: 2024-03-21 14:56:33.894991
|
|
12
12
|
_fail = True
|
|
13
13
|
time: URIRef # ['time']
|
|
14
14
|
BackgroundImageGeneration: URIRef # ['background image generation']
|
|
@@ -44,10 +44,12 @@ class PIVMETA(DefinedNamespace):
|
|
|
44
44
|
fnumber: URIRef # ['fnumber']
|
|
45
45
|
numberOfRecords: URIRef # ['number of records']
|
|
46
46
|
ExperimentalImage: URIRef # ['experimental image']
|
|
47
|
+
GaussWindowWeightingFunction: URIRef # ['gauss']
|
|
47
48
|
Interpolation: URIRef # ['interpolation']
|
|
48
49
|
LeftRightFlip: URIRef # ['left right flip']
|
|
49
50
|
ReEvaluateWithLargerSample: URIRef # ['re-evaluate with larger sample']
|
|
50
51
|
SplitImage: URIRef # ['split image']
|
|
52
|
+
SquareWindowWeightingFunction: URIRef # ['square']
|
|
51
53
|
SyntheticImage: URIRef # ['synthetic image']
|
|
52
54
|
TopBottomFlip: URIRef # ['top bottom flip']
|
|
53
55
|
TryLowerOrderPeaks: URIRef # ['try lower order peaks']
|
|
@@ -141,10 +143,12 @@ setattr(PIVMETA, "filename_pattern", PIVMETA.filenamePattern)
|
|
|
141
143
|
setattr(PIVMETA, "fnumber", PIVMETA.fnumber)
|
|
142
144
|
setattr(PIVMETA, "number_of_records", PIVMETA.numberOfRecords)
|
|
143
145
|
setattr(PIVMETA, "experimental_image", PIVMETA.ExperimentalImage)
|
|
146
|
+
setattr(PIVMETA, "gauss", PIVMETA.GaussWindowWeightingFunction)
|
|
144
147
|
setattr(PIVMETA, "interpolation", PIVMETA.Interpolation)
|
|
145
148
|
setattr(PIVMETA, "left_right_flip", PIVMETA.LeftRightFlip)
|
|
146
149
|
setattr(PIVMETA, "re-evaluate_with_larger_sample", PIVMETA.ReEvaluateWithLargerSample)
|
|
147
150
|
setattr(PIVMETA, "split_image", PIVMETA.SplitImage)
|
|
151
|
+
setattr(PIVMETA, "square", PIVMETA.SquareWindowWeightingFunction)
|
|
148
152
|
setattr(PIVMETA, "synthetic_image", PIVMETA.SyntheticImage)
|
|
149
153
|
setattr(PIVMETA, "top_bottom_flip", PIVMETA.TopBottomFlip)
|
|
150
154
|
setattr(PIVMETA, "try_lower_order_peaks", PIVMETA.TryLowerOrderPeaks)
|
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
import datetime
|
|
2
1
|
import json
|
|
3
2
|
import logging
|
|
4
3
|
import pydantic
|
|
5
4
|
import unittest
|
|
6
5
|
from pydantic import EmailStr
|
|
7
|
-
from rdflib import FOAF
|
|
8
|
-
from typing import List
|
|
9
6
|
|
|
10
|
-
from ontolutils import Thing, urirefs, namespaces
|
|
7
|
+
from ontolutils import Thing, urirefs, namespaces, get_urirefs, get_namespaces
|
|
11
8
|
from ontolutils import set_logging_level
|
|
12
9
|
from ontolutils.classes import decorator
|
|
13
10
|
|
|
@@ -17,6 +14,7 @@ LOG_LEVEL = logging.DEBUG
|
|
|
17
14
|
class TestNamespaces(unittest.TestCase):
|
|
18
15
|
|
|
19
16
|
def setUp(self):
|
|
17
|
+
self.maxDiff = None
|
|
20
18
|
logger = logging.getLogger('ontolutils')
|
|
21
19
|
self.INITIAL_LOG_LEVEL = logger.level
|
|
22
20
|
|
|
@@ -28,6 +26,22 @@ class TestNamespaces(unittest.TestCase):
|
|
|
28
26
|
set_logging_level(self.INITIAL_LOG_LEVEL)
|
|
29
27
|
assert logging.getLogger('ontolutils').level == self.INITIAL_LOG_LEVEL
|
|
30
28
|
|
|
29
|
+
def test_thing_custom_prop(self):
|
|
30
|
+
"""It is helpful to have the properties equal to the urirefs keys,
|
|
31
|
+
however, this should not be required!"""
|
|
32
|
+
|
|
33
|
+
@namespaces(foaf='http://xmlns.com/foaf/0.1/',
|
|
34
|
+
prov='http://www.w3.org/ns/prov#')
|
|
35
|
+
@urirefs(Person='prov:Person',
|
|
36
|
+
first_name='foaf:firstName',
|
|
37
|
+
lastName='foaf:lastName')
|
|
38
|
+
class Person(Thing):
|
|
39
|
+
first_name: str = None
|
|
40
|
+
lastName: str
|
|
41
|
+
|
|
42
|
+
p = Person(first_name='John', lastName='Doe')
|
|
43
|
+
print(p.model_dump_jsonld(resolve_keys=False))
|
|
44
|
+
|
|
31
45
|
def test_sort_classes(self):
|
|
32
46
|
thing1 = Thing(label='Thing 1')
|
|
33
47
|
thing2 = Thing(label='Thing 2')
|
|
@@ -38,48 +52,48 @@ class TestNamespaces(unittest.TestCase):
|
|
|
38
52
|
thing2 = Thing(label='Thing 2', id='http://example.com/thing2')
|
|
39
53
|
self.assertTrue(thing1 < thing2)
|
|
40
54
|
|
|
41
|
-
def test_serialize_fields(self):
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
55
|
+
# def test_serialize_fields(self):
|
|
56
|
+
# from ontolutils.classes.thing import serialize_fields
|
|
57
|
+
# self.assertEqual(serialize_fields(1), 1)
|
|
58
|
+
# self.assertEqual(serialize_fields(1.1), 1.1)
|
|
59
|
+
# self.assertEqual(serialize_fields('1'), '1')
|
|
60
|
+
# self.assertEqual(serialize_fields(True), True)
|
|
61
|
+
# thing = Thing(label='Thing 1')
|
|
62
|
+
#
|
|
63
|
+
# class RandomClass:
|
|
64
|
+
# """Random Class"""
|
|
65
|
+
#
|
|
66
|
+
# rc = RandomClass()
|
|
67
|
+
# self.assertEqual(serialize_fields(rc), rc)
|
|
68
|
+
#
|
|
69
|
+
# self.assertDictEqual(serialize_fields(Thing(id='_:b1', label='Thing 1')),
|
|
70
|
+
# {'@type': 'owl:Thing', 'rdfs:label': 'Thing 1', '@id': '_:b1'})
|
|
71
|
+
#
|
|
72
|
+
# @namespaces(owl='http://www.w3.org/2002/07/owl#',
|
|
73
|
+
# local='http://example.org/')
|
|
74
|
+
# @urirefs(Process='local:Process',
|
|
75
|
+
# startTime='local:startTime',
|
|
76
|
+
# listOfTimes='local:listOfTimes')
|
|
77
|
+
# class Process(Thing):
|
|
78
|
+
# """Process Thing"""
|
|
79
|
+
# startTime: datetime.datetime = None
|
|
80
|
+
# listOfTimes: List[datetime.datetime] = None
|
|
81
|
+
#
|
|
82
|
+
# process = Process(id='_:b1', label='Process 1',
|
|
83
|
+
# startTime=datetime.datetime(2021, 1, 1))
|
|
84
|
+
# self.assertEqual(serialize_fields(process),
|
|
85
|
+
# {'@type': 'local:Process', 'rdfs:label': 'Process 1', 'local:startTime': '2021-01-01T00:00:00',
|
|
86
|
+
# '@id': '_:b1'})
|
|
87
|
+
#
|
|
88
|
+
# process = Process(id='_:b1',
|
|
89
|
+
# label='Process 1',
|
|
90
|
+
# listOfTimes=[datetime.datetime(2021, 1, 1),
|
|
91
|
+
# datetime.datetime(2021, 1, 2)])
|
|
92
|
+
#
|
|
93
|
+
# self.assertEqual(serialize_fields(process),
|
|
94
|
+
# {'@type': 'local:Process', 'rdfs:label': 'Process 1',
|
|
95
|
+
# 'local:listOfTimes': ['2021-01-01T00:00:00', '2021-01-02T00:00:00'],
|
|
96
|
+
# '@id': '_:b1'})
|
|
83
97
|
|
|
84
98
|
def test__repr_html_(self):
|
|
85
99
|
thing = Thing(label='Thing 1')
|
|
@@ -227,7 +241,8 @@ class TestNamespaces(unittest.TestCase):
|
|
|
227
241
|
foaf="http://xmlns.com/foaf/0.1/")
|
|
228
242
|
@urirefs(Person='prov:Person',
|
|
229
243
|
firstName='foaf:firstName',
|
|
230
|
-
lastName=FOAF.lastName,
|
|
244
|
+
# lastName=FOAF.lastName,
|
|
245
|
+
lastName='foaf:lastName',
|
|
231
246
|
mbox='foaf:mbox')
|
|
232
247
|
class Person(Thing):
|
|
233
248
|
firstName: str
|
|
@@ -239,14 +254,13 @@ class TestNamespaces(unittest.TestCase):
|
|
|
239
254
|
"@context": {
|
|
240
255
|
"owl": "http://www.w3.org/2002/07/owl#",
|
|
241
256
|
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
|
|
242
|
-
"
|
|
257
|
+
"foaf": "http://xmlns.com/foaf/0.1/",
|
|
243
258
|
"prov": "http://www.w3.org/ns/prov#",
|
|
244
|
-
"foaf": "http://xmlns.com/foaf/0.1/"
|
|
245
259
|
},
|
|
246
260
|
"@id": "local:cde4c79c-21f2-4ab7-b01d-28de6e4aade4",
|
|
247
261
|
"@type": "prov:Person",
|
|
248
262
|
"foaf:firstName": "John",
|
|
249
|
-
"lastName": "Doe"
|
|
263
|
+
"foaf:lastName": "Doe"
|
|
250
264
|
}
|
|
251
265
|
print(p.model_dump_jsonld())
|
|
252
266
|
|
|
@@ -258,15 +272,19 @@ class TestNamespaces(unittest.TestCase):
|
|
|
258
272
|
pass
|
|
259
273
|
|
|
260
274
|
mt = CustomPerson()
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
275
|
+
# custom person has no
|
|
276
|
+
self.assertDictEqual(mt.urirefs, get_urirefs(Thing))
|
|
277
|
+
self.assertDictEqual(mt.urirefs, {'Thing': 'owl:Thing', 'label': 'rdfs:label'})
|
|
278
|
+
self.assertDictEqual(mt.namespaces, get_namespaces(Thing))
|
|
279
|
+
self.assertDictEqual(mt.namespaces, {'owl': 'http://www.w3.org/2002/07/owl#',
|
|
280
|
+
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#'})
|
|
264
281
|
|
|
265
282
|
mt = CustomPerson(first_name='John', last_name='Doe')
|
|
266
283
|
with self.assertRaises(AttributeError):
|
|
267
284
|
mt.namespaces = 'http://xmlns.com/foaf/0.1/'
|
|
268
285
|
with self.assertRaises(AttributeError):
|
|
269
286
|
mt.urirefs = 'foaf:lastName'
|
|
287
|
+
|
|
270
288
|
mt.namespaces['foaf'] = 'http://xmlns.com/foaf/0.1/'
|
|
271
289
|
mt.urirefs['first_name'] = 'foaf:firstName'
|
|
272
290
|
mt.urirefs['last_name'] = 'foaf:lastName'
|
|
@@ -279,10 +297,26 @@ class TestNamespaces(unittest.TestCase):
|
|
|
279
297
|
},
|
|
280
298
|
"@type": "CustomPerson",
|
|
281
299
|
"foaf:firstName": "John",
|
|
282
|
-
"foaf:lastName": "Doe"
|
|
283
|
-
|
|
300
|
+
"foaf:lastName": "Doe"
|
|
301
|
+
}
|
|
302
|
+
jsonld_dict = json.loads(mt.model_dump_jsonld(resolve_keys=True))
|
|
303
|
+
jsonld_dict.pop('@id')
|
|
304
|
+
self.assertDictEqual(jsonld_dict,
|
|
305
|
+
ref_jsonld)
|
|
306
|
+
|
|
307
|
+
ref_jsonld = {
|
|
308
|
+
"@context": {
|
|
309
|
+
"owl": "http://www.w3.org/2002/07/owl#",
|
|
310
|
+
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
|
|
311
|
+
"foaf": "http://xmlns.com/foaf/0.1/",
|
|
312
|
+
"first_name": "http://xmlns.com/foaf/0.1/firstName",
|
|
313
|
+
"last_name": "http://xmlns.com/foaf/0.1/lastName"
|
|
314
|
+
},
|
|
315
|
+
"@type": "CustomPerson",
|
|
316
|
+
"first_name": "John",
|
|
317
|
+
"last_name": "Doe"
|
|
284
318
|
}
|
|
285
|
-
jsonld_dict = json.loads(mt.model_dump_jsonld())
|
|
319
|
+
jsonld_dict = json.loads(mt.model_dump_jsonld(resolve_keys=False))
|
|
286
320
|
jsonld_dict.pop('@id')
|
|
287
321
|
self.assertDictEqual(jsonld_dict,
|
|
288
322
|
ref_jsonld)
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
"""Testing code used in the README.md file"""
|
|
2
2
|
import pathlib
|
|
3
|
-
|
|
4
3
|
from pydantic import EmailStr
|
|
5
4
|
|
|
6
5
|
from ontolutils import Thing, namespaces, urirefs
|
|
@@ -38,3 +37,17 @@ found_agent = found_agents[0]
|
|
|
38
37
|
print(found_agent.mbox)
|
|
39
38
|
|
|
40
39
|
pathlib.Path("agent.json").unlink(missing_ok=True)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@namespaces(prov='http://www.w3.org/ns/prov#',
|
|
43
|
+
|
|
44
|
+
foaf='http://xmlns.com/foaf/0.1/')
|
|
45
|
+
@urirefs(Person='prov:Person', first_name='foaf:firstName')
|
|
46
|
+
class Person(Thing):
|
|
47
|
+
first_name: str = None
|
|
48
|
+
last_name: str = None
|
|
49
|
+
|
|
50
|
+
p = Person(first_name='John', last_name='Doe', age=30)
|
|
51
|
+
print(p.model_dump_jsonld())
|
|
52
|
+
|
|
53
|
+
# Person(first_name=1)
|
|
@@ -1,289 +0,0 @@
|
|
|
1
|
-
import abc
|
|
2
|
-
import json
|
|
3
|
-
import logging
|
|
4
|
-
import rdflib
|
|
5
|
-
from datetime import datetime
|
|
6
|
-
from pydantic import HttpUrl, FileUrl, BaseModel, ConfigDict
|
|
7
|
-
from typing import Dict, Union, Optional
|
|
8
|
-
|
|
9
|
-
from .decorator import urirefs, namespaces, URIRefManager, NamespaceManager, _is_http_url
|
|
10
|
-
from .typing import BlankNodeType
|
|
11
|
-
from .utils import split_URIRef
|
|
12
|
-
|
|
13
|
-
logger = logging.getLogger('ontolutils')
|
|
14
|
-
|
|
15
|
-
EXTRA = 'allow' # or 'forbid' or 'ignore'
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
class ThingModel(BaseModel, abc.ABC):
|
|
19
|
-
"""Abstract base model class to be used by model classes used within ontolutils"""
|
|
20
|
-
|
|
21
|
-
model_config = ConfigDict(extra=EXTRA)
|
|
22
|
-
|
|
23
|
-
@abc.abstractmethod
|
|
24
|
-
def _repr_html_(self) -> str:
|
|
25
|
-
"""Returns the HTML representation of the class"""
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
def serialize_fields(
|
|
29
|
-
obj: Union[ThingModel, int, str, float, bool, datetime],
|
|
30
|
-
exclude_none: bool = True
|
|
31
|
-
) -> Union[Dict, int, str, float, bool]:
|
|
32
|
-
"""Serializes the fields of a Thing object into a json-ld
|
|
33
|
-
dictionary (without context!). Note, that IDs can automatically be
|
|
34
|
-
generated (with a local prefix)
|
|
35
|
-
|
|
36
|
-
Parameter
|
|
37
|
-
---------
|
|
38
|
-
obj: Union[ThingModel, int, str, float, bool, datetime]
|
|
39
|
-
The object to serialize (a subclass of ThingModel). All other types will
|
|
40
|
-
be returned as is. One exception is datetime, which will be serialized
|
|
41
|
-
to an ISO string.
|
|
42
|
-
exclude_none: bool=True
|
|
43
|
-
If True, fields with None values will be excluded from the
|
|
44
|
-
serialization
|
|
45
|
-
|
|
46
|
-
Returns
|
|
47
|
-
-------
|
|
48
|
-
Union[Dict, int, str, float, bool]
|
|
49
|
-
The serialized fields or the object as is
|
|
50
|
-
"""
|
|
51
|
-
if isinstance(obj, (int, str, float, bool)):
|
|
52
|
-
return obj
|
|
53
|
-
if isinstance(obj, datetime):
|
|
54
|
-
return obj.isoformat()
|
|
55
|
-
|
|
56
|
-
uri_ref_manager = URIRefManager.get(obj.__class__, None)
|
|
57
|
-
if uri_ref_manager is None:
|
|
58
|
-
return obj
|
|
59
|
-
|
|
60
|
-
try:
|
|
61
|
-
if exclude_none:
|
|
62
|
-
serialized_fields = {}
|
|
63
|
-
for k in obj.model_fields:
|
|
64
|
-
value = getattr(obj, k)
|
|
65
|
-
if value is not None and k not in ('id', '@id'):
|
|
66
|
-
iri = uri_ref_manager[k]
|
|
67
|
-
if _is_http_url(iri):
|
|
68
|
-
serialized_fields[k] = value
|
|
69
|
-
else:
|
|
70
|
-
serialized_fields[iri] = value
|
|
71
|
-
else:
|
|
72
|
-
serialized_fields = {}
|
|
73
|
-
for k in obj.model_fields:
|
|
74
|
-
value = getattr(obj, k)
|
|
75
|
-
if value not in ('id', '@id'):
|
|
76
|
-
iri = uri_ref_manager[k]
|
|
77
|
-
if _is_http_url(iri):
|
|
78
|
-
serialized_fields[k] = value
|
|
79
|
-
else:
|
|
80
|
-
serialized_fields[iri] = value
|
|
81
|
-
except AttributeError as e:
|
|
82
|
-
raise AttributeError(f"Could not serialize {obj} ({obj.__class__}). Orig. err: {e}") from e
|
|
83
|
-
|
|
84
|
-
if obj.model_config['extra'] == 'allow':
|
|
85
|
-
for k, v in obj.model_extra.items():
|
|
86
|
-
iri = uri_ref_manager.get(k, k)
|
|
87
|
-
if _is_http_url(iri):
|
|
88
|
-
serialized_fields[k] = v
|
|
89
|
-
else:
|
|
90
|
-
serialized_fields[iri] = v
|
|
91
|
-
|
|
92
|
-
# datetime
|
|
93
|
-
for k, v in serialized_fields.copy().items():
|
|
94
|
-
_field = serialized_fields.pop(k)
|
|
95
|
-
key = k
|
|
96
|
-
if isinstance(v, datetime):
|
|
97
|
-
serialized_fields[key] = serialize_fields(v)
|
|
98
|
-
elif isinstance(v, Thing):
|
|
99
|
-
serialized_fields[key] = serialize_fields(v, exclude_none=exclude_none)
|
|
100
|
-
elif isinstance(v, list):
|
|
101
|
-
serialized_fields[key] = [serialize_fields(i, exclude_none=exclude_none) for i in v]
|
|
102
|
-
else:
|
|
103
|
-
serialized_fields[key] = str(v)
|
|
104
|
-
|
|
105
|
-
_type = URIRefManager[obj.__class__].get(obj.__class__.__name__, obj.__class__.__name__)
|
|
106
|
-
|
|
107
|
-
out = {"@type": _type, **serialized_fields}
|
|
108
|
-
# if no ID is given, generate a local one:
|
|
109
|
-
if obj.id is not None:
|
|
110
|
-
out["@id"] = obj.id
|
|
111
|
-
else:
|
|
112
|
-
out["@id"] = rdflib.BNode()
|
|
113
|
-
return out
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
@namespaces(owl='http://www.w3.org/2002/07/owl#',
|
|
117
|
-
rdfs='http://www.w3.org/2000/01/rdf-schema#')
|
|
118
|
-
@urirefs(Thing='owl:Thing', label='rdfs:label')
|
|
119
|
-
class Thing(ThingModel):
|
|
120
|
-
"""owl:Thing
|
|
121
|
-
"""
|
|
122
|
-
id: Union[str, HttpUrl, FileUrl, BlankNodeType, None] = None # @id
|
|
123
|
-
label: str = None # rdfs:label
|
|
124
|
-
|
|
125
|
-
def __lt__(self, other: ThingModel) -> bool:
|
|
126
|
-
"""Less than comparison. Useful to sort Thing objects.
|
|
127
|
-
Comparison can only be done with other Thing objects and if an ID is given.
|
|
128
|
-
If one of the objects has no ID, then False is returned."""
|
|
129
|
-
if not isinstance(other, ThingModel):
|
|
130
|
-
raise TypeError(f"Cannot compare {self.__class__} with {type(other)}")
|
|
131
|
-
if self.id is None or other.id is None:
|
|
132
|
-
return False
|
|
133
|
-
return self.id <= other.id
|
|
134
|
-
|
|
135
|
-
def get_jsonld_dict(self,
|
|
136
|
-
context: Optional[Union[Dict, str]] = None,
|
|
137
|
-
exclude_none: bool = True) -> Dict:
|
|
138
|
-
"""Return the JSON-LD dictionary of the object. This will include the context
|
|
139
|
-
and the fields of the object.
|
|
140
|
-
|
|
141
|
-
Parameters
|
|
142
|
-
----------
|
|
143
|
-
context: Optional[Union[Dict, str]]
|
|
144
|
-
The context to use for the JSON-LD serialization. If a string is given, it will
|
|
145
|
-
be interpreted as an import statement and will be added to the context.
|
|
146
|
-
exclude_none: bool=True
|
|
147
|
-
Exclude fields with None values
|
|
148
|
-
|
|
149
|
-
Returns
|
|
150
|
-
-------
|
|
151
|
-
Dict
|
|
152
|
-
The JSON-LD dictionary
|
|
153
|
-
"""
|
|
154
|
-
logger.debug('Initializing RDF graph to dump the Thing to JSON-LD')
|
|
155
|
-
|
|
156
|
-
# lets auto-generate the context
|
|
157
|
-
at_context: Dict = NamespaceManager.get(self.__class__, {})
|
|
158
|
-
|
|
159
|
-
if context is None:
|
|
160
|
-
context = {}
|
|
161
|
-
|
|
162
|
-
if not isinstance(context, dict):
|
|
163
|
-
raise TypeError(f"Context must be a dict, not {type(context)}")
|
|
164
|
-
|
|
165
|
-
at_context.update(**context)
|
|
166
|
-
|
|
167
|
-
logger.debug(f'The context is "{at_context}".')
|
|
168
|
-
|
|
169
|
-
jsonld = {
|
|
170
|
-
"@context": at_context,
|
|
171
|
-
**serialize_fields(self, exclude_none=exclude_none)
|
|
172
|
-
}
|
|
173
|
-
return jsonld
|
|
174
|
-
|
|
175
|
-
def model_dump_jsonld(self,
|
|
176
|
-
context: Optional[Dict] = None,
|
|
177
|
-
exclude_none: bool = True,
|
|
178
|
-
rdflib_serialize: bool = False) -> str:
|
|
179
|
-
"""Similar to model_dump_json() but will return a JSON string with
|
|
180
|
-
context resulting in a JSON-LD serialization. Using `rdflib_serialize=True`
|
|
181
|
-
will use the rdflib to serialize. This will make the output a bit cleaner
|
|
182
|
-
but is not needed in most cases and just takes a bit more time (and requires
|
|
183
|
-
an internet connection.
|
|
184
|
-
|
|
185
|
-
Note, that if `rdflib_serialize=True`, then a blank node will be generated if no ID is set.
|
|
186
|
-
|
|
187
|
-
Parameters
|
|
188
|
-
----------
|
|
189
|
-
context: Optional[Union[Dict, str]]
|
|
190
|
-
The context to use for the JSON-LD serialization. If a string is given, it will
|
|
191
|
-
be interpreted as an import statement and will be added to the context.
|
|
192
|
-
exclude_none: bool=True
|
|
193
|
-
Exclude fields with None values
|
|
194
|
-
rdflib_serialize: bool=False
|
|
195
|
-
If True, the output will be serialized using rdflib. This results in a cleaner
|
|
196
|
-
output but is not needed in most cases and just takes a bit more time (and requires
|
|
197
|
-
an internet connection). Will also generate a blank node if no ID is set.
|
|
198
|
-
|
|
199
|
-
Returns
|
|
200
|
-
-------
|
|
201
|
-
str
|
|
202
|
-
The JSON-LD string
|
|
203
|
-
"""
|
|
204
|
-
jsonld_dict = self.get_jsonld_dict(
|
|
205
|
-
context=context,
|
|
206
|
-
exclude_none=exclude_none
|
|
207
|
-
)
|
|
208
|
-
jsonld_str = json.dumps(jsonld_dict, indent=4)
|
|
209
|
-
if not rdflib_serialize:
|
|
210
|
-
return jsonld_str
|
|
211
|
-
|
|
212
|
-
logger.debug(f'Parsing the following jsonld dict to the RDF graph: {jsonld_str}')
|
|
213
|
-
g = rdflib.Graph()
|
|
214
|
-
g.parse(data=jsonld_str, format='json-ld')
|
|
215
|
-
|
|
216
|
-
_context = jsonld_dict.get('@context', {})
|
|
217
|
-
if context:
|
|
218
|
-
_context.update(context)
|
|
219
|
-
|
|
220
|
-
return g.serialize(format='json-ld',
|
|
221
|
-
context=_context,
|
|
222
|
-
indent=4)
|
|
223
|
-
|
|
224
|
-
def __repr__(self):
|
|
225
|
-
_fields = {k: getattr(self, k) for k in self.model_fields if getattr(self, k) is not None}
|
|
226
|
-
repr_fields = ", ".join([f"{k}={v}" for k, v in _fields.items()])
|
|
227
|
-
if self.model_config['extra'] == 'allow':
|
|
228
|
-
if len(self.model_extra) > 0:
|
|
229
|
-
repr_extra = ", ".join([f"{k}={v}" for k, v in self.model_extra.items()])
|
|
230
|
-
return f"{self.__class__.__name__}({repr_fields}, {repr_extra})"
|
|
231
|
-
return f"{self.__class__.__name__}({repr_fields})"
|
|
232
|
-
|
|
233
|
-
def __str__(self):
|
|
234
|
-
return self.__repr__()
|
|
235
|
-
|
|
236
|
-
def _repr_html_(self) -> str:
|
|
237
|
-
"""Returns the HTML representation of the class"""
|
|
238
|
-
_fields = {k: getattr(self, k) for k in self.model_fields if getattr(self, k) is not None}
|
|
239
|
-
repr_fields = ", ".join([f"{k}={v}" for k, v in _fields.items()])
|
|
240
|
-
return f"{self.__class__.__name__}({repr_fields})"
|
|
241
|
-
|
|
242
|
-
@classmethod
|
|
243
|
-
def from_jsonld(cls, source=None, data=None, limit=None, context=None):
|
|
244
|
-
"""Initialize the class from a JSON-LD source"""
|
|
245
|
-
from . import query
|
|
246
|
-
return query(cls, source=source, data=data, limit=limit, context=context)
|
|
247
|
-
|
|
248
|
-
@classmethod
|
|
249
|
-
def iri(cls, key: str = None, compact: bool = False):
|
|
250
|
-
"""Return the IRI of the class or the key
|
|
251
|
-
|
|
252
|
-
Parameter
|
|
253
|
-
---------
|
|
254
|
-
key: str
|
|
255
|
-
The key (field) of the class
|
|
256
|
-
compact: bool
|
|
257
|
-
If True, returns the short form of the IRI, e.g. 'owl:Thing'
|
|
258
|
-
If False, returns the full IRI, e.g. 'http://www.w3.org/2002/07/owl#Thing'
|
|
259
|
-
|
|
260
|
-
Returns
|
|
261
|
-
-------
|
|
262
|
-
str
|
|
263
|
-
The IRI of the class or the key, e.g. 'http://www.w3.org/2002/07/owl#Thing' or
|
|
264
|
-
'owl:Thing' if compact is True
|
|
265
|
-
"""
|
|
266
|
-
if key is None:
|
|
267
|
-
iri_short = URIRefManager[cls][cls.__name__]
|
|
268
|
-
else:
|
|
269
|
-
iri_short = URIRefManager[cls][key]
|
|
270
|
-
if compact:
|
|
271
|
-
return iri_short
|
|
272
|
-
ns, key = split_URIRef(iri_short)
|
|
273
|
-
ns_iri = NamespaceManager[cls].get(ns, None)
|
|
274
|
-
return f'{ns_iri}{key}'
|
|
275
|
-
|
|
276
|
-
@classmethod
|
|
277
|
-
def get_context(cls):
|
|
278
|
-
"""Return the context of the class"""
|
|
279
|
-
return NamespaceManager[cls]
|
|
280
|
-
|
|
281
|
-
@property
|
|
282
|
-
def namespaces(self):
|
|
283
|
-
"""Return the namespaces of the class"""
|
|
284
|
-
return NamespaceManager[self.__class__]
|
|
285
|
-
|
|
286
|
-
@property
|
|
287
|
-
def urirefs(self):
|
|
288
|
-
"""Return the URIRefs of the class"""
|
|
289
|
-
return URIRefManager[self.__class__]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|