ontolutils 0.2.14__tar.gz → 0.2.16__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.14 → ontolutils-0.2.16}/PKG-INFO +10 -6
- {ontolutils-0.2.14 → ontolutils-0.2.16}/README.md +8 -4
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/classes/decorator.py +21 -5
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/classes/query_util.py +20 -25
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/classes/thing.py +62 -52
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/namespacelib/__dev.py +3 -1
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/namespacelib/codemeta.py +2 -2
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/namespacelib/m4i.py +2 -2
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/namespacelib/obo.py +2 -2
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/namespacelib/pivmeta.py +79 -37
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/namespacelib/qudt_kind.py +1090 -1090
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/namespacelib/qudt_unit.py +2413 -2413
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/namespacelib/schema.py +2770 -2770
- ontolutils-0.2.16/ontolutils/namespacelib/ssno.py +37 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils.egg-info/PKG-INFO +10 -6
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils.egg-info/requires.txt +1 -1
- {ontolutils-0.2.14 → ontolutils-0.2.16}/setup.cfg +2 -2
- {ontolutils-0.2.14 → ontolutils-0.2.16}/tests/test_classes.py +24 -24
- {ontolutils-0.2.14 → ontolutils-0.2.16}/tests/test_decorator.py +6 -7
- {ontolutils-0.2.14 → ontolutils-0.2.16}/tests/test_query.py +32 -23
- ontolutils-0.2.16/tests/test_readme.py +55 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/tests/test_utils.py +4 -0
- ontolutils-0.2.14/ontolutils/namespacelib/ssno.py +0 -37
- ontolutils-0.2.14/tests/test_readme.py +0 -53
- {ontolutils-0.2.14 → ontolutils-0.2.16}/LICENSE +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/__init__.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/_version.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/cache.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/classes/__init__.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/classes/typing.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/classes/utils.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/namespacelib/__init__.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils/namespacelib/_iana_utils.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils.egg-info/SOURCES.txt +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils.egg-info/dependency_links.txt +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/ontolutils.egg-info/top_level.txt +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/pyproject.toml +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/setup.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/tests/test_namespaces.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/tests/test_typing.py +0 -0
- {ontolutils-0.2.14 → ontolutils-0.2.16}/tests/test_version.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: ontolutils
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.16
|
|
4
4
|
Summary: Utility library for the work with ontologies.
|
|
5
5
|
Home-page: https://github.com/matthiasprobst/ontology-utils
|
|
6
6
|
Author: Matthias Probst
|
|
@@ -17,7 +17,7 @@ Requires-Python: <3.13,>=3.8
|
|
|
17
17
|
Description-Content-Type: text/markdown
|
|
18
18
|
License-File: LICENSE
|
|
19
19
|
Requires-Dist: rdflib
|
|
20
|
-
Requires-Dist: pydantic
|
|
20
|
+
Requires-Dist: pydantic[email]
|
|
21
21
|
Requires-Dist: python-dateutil
|
|
22
22
|
Requires-Dist: requests
|
|
23
23
|
Requires-Dist: appdirs
|
|
@@ -56,25 +56,29 @@ the JSON-LD file yourself is too cumbersome *and* you want validation of the par
|
|
|
56
56
|
lets you design classes, which describe ontology classes like this:
|
|
57
57
|
|
|
58
58
|
```python
|
|
59
|
+
from pydantic import EmailStr, Field
|
|
60
|
+
|
|
59
61
|
from ontolutils import Thing, urirefs, namespaces
|
|
60
|
-
from pydantic import EmailStr
|
|
61
|
-
from rdflib import FOAF
|
|
62
62
|
|
|
63
63
|
|
|
64
64
|
@namespaces(prov="http://www.w3.org/ns/prov#",
|
|
65
65
|
foaf="http://xmlns.com/foaf/0.1/")
|
|
66
66
|
@urirefs(Person='prov:Person',
|
|
67
67
|
firstName='foaf:firstName',
|
|
68
|
-
|
|
68
|
+
last_name='foaf:lastName',
|
|
69
69
|
mbox='foaf:mbox')
|
|
70
70
|
class Person(Thing):
|
|
71
71
|
firstName: str
|
|
72
|
-
|
|
72
|
+
last_name: str = Field(default=None, alias="lastName") # you may provide an alias
|
|
73
73
|
mbox: EmailStr = None
|
|
74
74
|
|
|
75
75
|
|
|
76
|
+
p = Person(id="cde4c79c-21f2-4ab7-b01d-28de6e4aade4",
|
|
77
|
+
firstName='John', last_name='Doe')
|
|
78
|
+
# as we have set an alias, we can also use "lastName":
|
|
76
79
|
p = Person(id="cde4c79c-21f2-4ab7-b01d-28de6e4aade4",
|
|
77
80
|
firstName='John', lastName='Doe')
|
|
81
|
+
# The jsonld representation of the object will be the same in both cases:
|
|
78
82
|
p.model_dump_jsonld()
|
|
79
83
|
```
|
|
80
84
|
|
|
@@ -24,25 +24,29 @@ the JSON-LD file yourself is too cumbersome *and* you want validation of the par
|
|
|
24
24
|
lets you design classes, which describe ontology classes like this:
|
|
25
25
|
|
|
26
26
|
```python
|
|
27
|
+
from pydantic import EmailStr, Field
|
|
28
|
+
|
|
27
29
|
from ontolutils import Thing, urirefs, namespaces
|
|
28
|
-
from pydantic import EmailStr
|
|
29
|
-
from rdflib import FOAF
|
|
30
30
|
|
|
31
31
|
|
|
32
32
|
@namespaces(prov="http://www.w3.org/ns/prov#",
|
|
33
33
|
foaf="http://xmlns.com/foaf/0.1/")
|
|
34
34
|
@urirefs(Person='prov:Person',
|
|
35
35
|
firstName='foaf:firstName',
|
|
36
|
-
|
|
36
|
+
last_name='foaf:lastName',
|
|
37
37
|
mbox='foaf:mbox')
|
|
38
38
|
class Person(Thing):
|
|
39
39
|
firstName: str
|
|
40
|
-
|
|
40
|
+
last_name: str = Field(default=None, alias="lastName") # you may provide an alias
|
|
41
41
|
mbox: EmailStr = None
|
|
42
42
|
|
|
43
43
|
|
|
44
|
+
p = Person(id="cde4c79c-21f2-4ab7-b01d-28de6e4aade4",
|
|
45
|
+
firstName='John', last_name='Doe')
|
|
46
|
+
# as we have set an alias, we can also use "lastName":
|
|
44
47
|
p = Person(id="cde4c79c-21f2-4ab7-b01d-28de6e4aade4",
|
|
45
48
|
firstName='John', lastName='Doe')
|
|
49
|
+
# The jsonld representation of the object will be the same in both cases:
|
|
46
50
|
p.model_dump_jsonld()
|
|
47
51
|
```
|
|
48
52
|
|
|
@@ -65,6 +65,15 @@ def namespaces(**kwargs):
|
|
|
65
65
|
return _decorator
|
|
66
66
|
|
|
67
67
|
|
|
68
|
+
_prefix_dict = {
|
|
69
|
+
'http://xmlns.com/foaf/0.1/': 'foaf',
|
|
70
|
+
'http://www.w3.org/ns/prov#': 'prov',
|
|
71
|
+
'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf',
|
|
72
|
+
'http://schema.org/': 'schema',
|
|
73
|
+
'http://w3id.org/nfdi4ing/metadata4ing#': 'm4i'
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
68
77
|
def urirefs(**kwargs):
|
|
69
78
|
"""decorator for model classes. It assigns the URIRefs to the fields of the class.
|
|
70
79
|
|
|
@@ -88,11 +97,18 @@ def urirefs(**kwargs):
|
|
|
88
97
|
raise TypeError(f"{v} must be a string, not {type(v)}")
|
|
89
98
|
if _is_http_url(v):
|
|
90
99
|
ns, key = split_URIRef(v)
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
100
|
+
prefix = _prefix_dict.get(ns, None)
|
|
101
|
+
if prefix is None:
|
|
102
|
+
URIRefManager[cls][k] = str(v)
|
|
103
|
+
else:
|
|
104
|
+
NamespaceManager[cls][prefix] = str(ns)
|
|
105
|
+
if k not in fields:
|
|
106
|
+
raise KeyError(f"Field '{k}' not found in {cls.__name__}")
|
|
107
|
+
URIRefManager[cls][k] = f"{prefix}:{key}"
|
|
108
|
+
else:
|
|
109
|
+
if k not in fields:
|
|
110
|
+
raise KeyError(f"Field '{k}' not found in {cls.__name__}")
|
|
111
|
+
URIRefManager[cls][k] = v
|
|
95
112
|
return cls
|
|
96
113
|
|
|
97
114
|
return _decorator
|
|
98
|
-
|
|
@@ -56,7 +56,13 @@ WHERE {
|
|
|
56
56
|
if p == rdflib.RDF.type and add_type:
|
|
57
57
|
sub_data["@type"] = str(o)
|
|
58
58
|
else:
|
|
59
|
-
|
|
59
|
+
# may point to another blank node:
|
|
60
|
+
if isinstance(o, rdflib.BNode):
|
|
61
|
+
logger.debug(f'"{o}" is a blank node. Need to find children of it...')
|
|
62
|
+
_, key = split_URIRef(p)
|
|
63
|
+
sub_data[key] = process_object(_id, p, o, graph, add_type)
|
|
64
|
+
else:
|
|
65
|
+
logger.debug(f'dont know what to do with {p} and {o}')
|
|
60
66
|
if predicate in sub_data:
|
|
61
67
|
return sub_data[predicate]
|
|
62
68
|
return sub_data
|
|
@@ -67,7 +73,7 @@ WHERE {
|
|
|
67
73
|
logger.debug('points to a type definition inside the data')
|
|
68
74
|
if obj == _id:
|
|
69
75
|
return str(obj)
|
|
70
|
-
return _query_by_id(graph=graph, _id=obj, add_type=
|
|
76
|
+
return _query_by_id(graph=graph, _id=obj, add_type=True)
|
|
71
77
|
|
|
72
78
|
logger.debug(f'"{obj}" for predicate "{predicate}" is a simple data field.')
|
|
73
79
|
return str(obj)
|
|
@@ -99,7 +105,7 @@ def _query_by_id(graph, _id: Union[str, rdflib.URIRef], add_type: bool) -> Dict:
|
|
|
99
105
|
"""Query the graph by the id. Return the data as a dictionary."""
|
|
100
106
|
_sub_query_string = """SELECT DISTINCT ?p ?o WHERE { <%s> ?p ?o }""" % _id
|
|
101
107
|
_sub_res = graph.query(_sub_query_string)
|
|
102
|
-
out = {'id': str(_id)}
|
|
108
|
+
out = {'@id': str(_id)}
|
|
103
109
|
for binding in _sub_res.bindings:
|
|
104
110
|
predicate = binding['p']
|
|
105
111
|
obj = binding['o']
|
|
@@ -127,24 +133,6 @@ SELECT DISTINCT ?o WHERE { <%s> rdf:type ?o }""" % iri
|
|
|
127
133
|
return len(_sub_res) == 1
|
|
128
134
|
|
|
129
135
|
|
|
130
|
-
def exists_as_type(obj: str, graph) -> bool:
|
|
131
|
-
"""Check if the object exists as a type in the graph."""
|
|
132
|
-
query = """SELECT ?x ?obj ?p ?o
|
|
133
|
-
WHERE {
|
|
134
|
-
?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?obj .
|
|
135
|
-
?x ?p ?o .
|
|
136
|
-
}"""
|
|
137
|
-
out = graph.query(query)
|
|
138
|
-
for _id, _type, _, _ in out:
|
|
139
|
-
if obj.startswith('_:'):
|
|
140
|
-
if str(_id) == str(obj[2:]):
|
|
141
|
-
return True
|
|
142
|
-
else:
|
|
143
|
-
if str(_id) == str(obj):
|
|
144
|
-
return True
|
|
145
|
-
return False
|
|
146
|
-
|
|
147
|
-
|
|
148
136
|
def expand_sparql_res(bindings,
|
|
149
137
|
graph,
|
|
150
138
|
add_type: bool,
|
|
@@ -154,8 +142,12 @@ def expand_sparql_res(bindings,
|
|
|
154
142
|
# n_ = len(bindings)
|
|
155
143
|
for i, binding in enumerate(bindings):
|
|
156
144
|
logger.debug(
|
|
157
|
-
f'Expanding SPARQL results {i}/{len(bindings)}: {binding["?id"]}, {binding["p"]}, {binding["?o"]}.')
|
|
158
|
-
|
|
145
|
+
f'Expanding SPARQL results {i + 1}/{len(bindings)}: {binding["?id"]}, {binding["p"]}, {binding["?o"]}.')
|
|
146
|
+
|
|
147
|
+
if isinstance(binding['?id'], rdflib.URIRef):
|
|
148
|
+
_id = str(binding['?id'])
|
|
149
|
+
else:
|
|
150
|
+
_id = binding['?id'].n3()
|
|
159
151
|
if _id not in out:
|
|
160
152
|
out[_id] = {}
|
|
161
153
|
if add_context:
|
|
@@ -223,7 +215,7 @@ def dquery(subject: str,
|
|
|
223
215
|
|
|
224
216
|
kwargs: Dict = expand_sparql_res(res.bindings, g, True, True)
|
|
225
217
|
for _id in kwargs:
|
|
226
|
-
kwargs[_id]['id'] = _id
|
|
218
|
+
kwargs[_id]['@id'] = _id
|
|
227
219
|
return [v for v in kwargs.values()]
|
|
228
220
|
|
|
229
221
|
|
|
@@ -248,7 +240,10 @@ def query(cls: Thing,
|
|
|
248
240
|
The limit of the query. Default is None (no limit).
|
|
249
241
|
If limit equals to 1, the result will be a single obj, not a list.
|
|
250
242
|
"""
|
|
251
|
-
|
|
243
|
+
if cls == Thing:
|
|
244
|
+
query_string = '\nSELECT *\nWHERE {\n ?id a ?type .\n ?id ?p ?o .\n}'
|
|
245
|
+
else:
|
|
246
|
+
query_string = get_query_string(cls)
|
|
252
247
|
g = rdflib.Graph()
|
|
253
248
|
|
|
254
249
|
ns_keys = [_ns[0] for _ns in g.namespaces()]
|
|
@@ -8,6 +8,7 @@ from typing import Dict, Union, Optional
|
|
|
8
8
|
|
|
9
9
|
import rdflib
|
|
10
10
|
from pydantic import HttpUrl, FileUrl, BaseModel, ConfigDict
|
|
11
|
+
from rdflib.plugins.shared.jsonld.context import Context
|
|
11
12
|
|
|
12
13
|
from .decorator import urirefs, namespaces, URIRefManager, NamespaceManager, _is_http_url
|
|
13
14
|
from .typing import BlankNodeType
|
|
@@ -28,35 +29,20 @@ class ThingModel(BaseModel, abc.ABC):
|
|
|
28
29
|
"""Returns the HTML representation of the class"""
|
|
29
30
|
|
|
30
31
|
|
|
31
|
-
def resolve_iri(
|
|
32
|
-
"""
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
_iri = context.get(iri, None)
|
|
44
|
-
if _iri is not None:
|
|
45
|
-
if isinstance(_iri, dict):
|
|
46
|
-
iri = _iri.get('@id', iri)
|
|
47
|
-
else:
|
|
48
|
-
iri = _iri
|
|
49
|
-
if iri.startswith('http'):
|
|
50
|
-
return iri
|
|
51
|
-
if ':' not in iri:
|
|
52
|
-
if iri == 'label':
|
|
32
|
+
def resolve_iri(key_or_iri: str, context: Context) -> Optional[str]:
|
|
33
|
+
"""Resolve a key or IRI to a full IRI using the context."""
|
|
34
|
+
if key_or_iri.startswith('http'):
|
|
35
|
+
return str(key_or_iri)
|
|
36
|
+
if ':' in key_or_iri:
|
|
37
|
+
iri = context.resolve(key_or_iri)
|
|
38
|
+
if iri.startswith('http'):
|
|
39
|
+
return iri
|
|
40
|
+
try:
|
|
41
|
+
return context.terms.get(key_or_iri).id
|
|
42
|
+
except AttributeError:
|
|
43
|
+
if key_or_iri == 'label':
|
|
53
44
|
return 'http://www.w3.org/2000/01/rdf-schema#label'
|
|
54
|
-
|
|
55
|
-
ns, key = split_URIRef(iri)
|
|
56
|
-
prefix_iri = context.get(ns, None)
|
|
57
|
-
if prefix_iri is None:
|
|
58
|
-
return None # could not resolve the iri
|
|
59
|
-
return f'{prefix_iri}{key}'
|
|
45
|
+
return
|
|
60
46
|
|
|
61
47
|
|
|
62
48
|
@namespaces(owl='http://www.w3.org/2002/07/owl#',
|
|
@@ -121,10 +107,21 @@ class Thing(ThingModel):
|
|
|
121
107
|
return False
|
|
122
108
|
return self.id <= other.id
|
|
123
109
|
|
|
110
|
+
def pop_blank_node_id(self) -> Union[None, str]:
|
|
111
|
+
"""Remove the ID if it is blank node"""
|
|
112
|
+
if self.id is None:
|
|
113
|
+
return
|
|
114
|
+
if self.id.startswith('http'):
|
|
115
|
+
return
|
|
116
|
+
_id = self.id
|
|
117
|
+
self.id = None
|
|
118
|
+
return _id
|
|
119
|
+
|
|
124
120
|
def get_jsonld_dict(self,
|
|
125
121
|
context: Optional[Union[Dict, str]] = None,
|
|
126
122
|
exclude_none: bool = True,
|
|
127
|
-
resolve_keys: bool = False
|
|
123
|
+
resolve_keys: bool = False,
|
|
124
|
+
assign_bnode: bool = True) -> Dict:
|
|
128
125
|
"""Return the JSON-LD dictionary of the object. This will include the context
|
|
129
126
|
and the fields of the object.
|
|
130
127
|
|
|
@@ -138,6 +135,8 @@ class Thing(ThingModel):
|
|
|
138
135
|
resolve_keys: bool=False
|
|
139
136
|
If True, then attributes of a Thing class will be resolved to the full IRI and
|
|
140
137
|
explained in the context.
|
|
138
|
+
assign_bnode: bool=True
|
|
139
|
+
Assigns a blank node if no ID is set.
|
|
141
140
|
|
|
142
141
|
Example:
|
|
143
142
|
|
|
@@ -172,6 +171,7 @@ class Thing(ThingModel):
|
|
|
172
171
|
>>> "foaf:firstName": "John"
|
|
173
172
|
>>> }
|
|
174
173
|
|
|
174
|
+
|
|
175
175
|
Returns
|
|
176
176
|
-------
|
|
177
177
|
Dict
|
|
@@ -190,11 +190,13 @@ class Thing(ThingModel):
|
|
|
190
190
|
|
|
191
191
|
at_context.update(**context)
|
|
192
192
|
|
|
193
|
+
ctx = Context(source={**at_context, **URIRefManager.get(self.__class__)})
|
|
194
|
+
|
|
193
195
|
logger.debug(f'The context is "{at_context}".')
|
|
194
196
|
|
|
195
197
|
def _serialize_fields(
|
|
196
198
|
obj: Union[ThingModel, int, str, float, bool, datetime],
|
|
197
|
-
exclude_none: bool
|
|
199
|
+
exclude_none: bool
|
|
198
200
|
) -> Union[Dict, int, str, float, bool]:
|
|
199
201
|
"""Serializes the fields of a Thing object into a json-ld
|
|
200
202
|
dictionary (without context!). Note, that IDs can automatically be
|
|
@@ -235,12 +237,16 @@ class Thing(ThingModel):
|
|
|
235
237
|
if _is_http_url(iri):
|
|
236
238
|
serialized_fields[iri] = value
|
|
237
239
|
|
|
238
|
-
|
|
239
|
-
if key != k and not resolve_keys:
|
|
240
|
-
at_context[k] = resolve_iri(iri, at_context)
|
|
241
|
-
serialized_fields[k] = value
|
|
242
|
-
else:
|
|
240
|
+
if resolve_keys:
|
|
243
241
|
serialized_fields[iri] = value
|
|
242
|
+
else:
|
|
243
|
+
term = ctx.find_term(ctx.expand(iri))
|
|
244
|
+
if term:
|
|
245
|
+
if ctx.shrink_iri(term.id).split(':')[1] != k:
|
|
246
|
+
at_context[k] = term.id
|
|
247
|
+
serialized_fields[k] = value
|
|
248
|
+
else:
|
|
249
|
+
serialized_fields[iri] = value
|
|
244
250
|
except AttributeError as e:
|
|
245
251
|
raise AttributeError(f"Could not serialize {obj} ({obj.__class__}). Orig. err: {e}") from e
|
|
246
252
|
|
|
@@ -251,7 +257,8 @@ class Thing(ThingModel):
|
|
|
251
257
|
if isinstance(v, Thing):
|
|
252
258
|
serialized_fields[key] = _serialize_fields(v, exclude_none=exclude_none)
|
|
253
259
|
elif isinstance(v, list):
|
|
254
|
-
serialized_fields[key] = [
|
|
260
|
+
serialized_fields[key] = [
|
|
261
|
+
_serialize_fields(i, exclude_none=exclude_none) for i in v]
|
|
255
262
|
elif isinstance(v, (int, float)):
|
|
256
263
|
serialized_fields[key] = v
|
|
257
264
|
else:
|
|
@@ -264,7 +271,8 @@ class Thing(ThingModel):
|
|
|
264
271
|
if obj.id is not None:
|
|
265
272
|
out["@id"] = obj.id
|
|
266
273
|
else:
|
|
267
|
-
|
|
274
|
+
if assign_bnode:
|
|
275
|
+
out["@id"] = rdflib.BNode().n3()
|
|
268
276
|
return out
|
|
269
277
|
|
|
270
278
|
serialization = _serialize_fields(self, exclude_none=exclude_none)
|
|
@@ -279,7 +287,8 @@ class Thing(ThingModel):
|
|
|
279
287
|
context: Optional[Dict] = None,
|
|
280
288
|
exclude_none: bool = True,
|
|
281
289
|
rdflib_serialize: bool = False,
|
|
282
|
-
resolve_keys: bool = True
|
|
290
|
+
resolve_keys: bool = True,
|
|
291
|
+
assign_bnode: bool = True) -> str:
|
|
283
292
|
"""Similar to model_dump_json() but will return a JSON string with
|
|
284
293
|
context resulting in a JSON-LD serialization. Using `rdflib_serialize=True`
|
|
285
294
|
will use the rdflib to serialize. This will make the output a bit cleaner
|
|
@@ -302,6 +311,8 @@ class Thing(ThingModel):
|
|
|
302
311
|
resolve_keys: bool=False
|
|
303
312
|
If True, then attributes of a Thing class will be resolved to the full IRI and
|
|
304
313
|
explained in the context.
|
|
314
|
+
assign_bnode: bool=True
|
|
315
|
+
Assigns a blank node if no ID is set.
|
|
305
316
|
|
|
306
317
|
.. seealso:: `Thing.get_jsonld_dict`
|
|
307
318
|
|
|
@@ -313,7 +324,8 @@ class Thing(ThingModel):
|
|
|
313
324
|
jsonld_dict = self.get_jsonld_dict(
|
|
314
325
|
context=context,
|
|
315
326
|
exclude_none=exclude_none,
|
|
316
|
-
resolve_keys=resolve_keys
|
|
327
|
+
resolve_keys=resolve_keys,
|
|
328
|
+
assign_bnode=assign_bnode
|
|
317
329
|
)
|
|
318
330
|
jsonld_str = json.dumps(jsonld_dict, indent=4)
|
|
319
331
|
if not rdflib_serialize:
|
|
@@ -331,23 +343,21 @@ class Thing(ThingModel):
|
|
|
331
343
|
context=_context,
|
|
332
344
|
indent=4)
|
|
333
345
|
|
|
334
|
-
def __repr__(self):
|
|
346
|
+
def __repr__(self, limit: Optional[int] = None):
|
|
335
347
|
_fields = {k: getattr(self, k) for k in self.model_fields if getattr(self, k) is not None}
|
|
336
|
-
|
|
337
|
-
if
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
def __str__(self):
|
|
344
|
-
return self.__repr__()
|
|
348
|
+
repr_extra = ", ".join([f"{k}={v}" for k, v in {**_fields, **self.model_extra}.items()])
|
|
349
|
+
if limit is None or len(repr_extra) < limit:
|
|
350
|
+
return f"{self.__class__.__name__}({repr_extra})"
|
|
351
|
+
return f"{self.__class__.__name__}({repr_extra[0:limit]}...)"
|
|
352
|
+
|
|
353
|
+
def __str__(self, limit: Optional[int] = None):
|
|
354
|
+
return self.__repr__(limit=limit)
|
|
345
355
|
|
|
346
356
|
def _repr_html_(self) -> str:
|
|
347
357
|
"""Returns the HTML representation of the class"""
|
|
348
|
-
_fields = {k: getattr(self, k) for k in self.model_fields if getattr(self, k) is not None}
|
|
349
|
-
repr_fields = ", ".join([f"{k}={v}" for k, v in _fields.items()])
|
|
350
|
-
return
|
|
358
|
+
# _fields = {k: getattr(self, k) for k in self.model_fields if getattr(self, k) is not None}
|
|
359
|
+
# repr_fields = ", ".join([f"{k}={v}" for k, v in _fields.items()])
|
|
360
|
+
return self.__repr__()
|
|
351
361
|
|
|
352
362
|
@classmethod
|
|
353
363
|
def from_jsonld(cls,
|
|
@@ -19,6 +19,7 @@ from ontolutils import __version__
|
|
|
19
19
|
__this_dir__ = pathlib.Path(__file__).parent
|
|
20
20
|
__package_dir__ = __this_dir__.parent / 'namespacelib'
|
|
21
21
|
|
|
22
|
+
FORCE_DOWNLOAD = True
|
|
22
23
|
|
|
23
24
|
def generate_namespace_file_from_ttl(namespace: str,
|
|
24
25
|
source: str,
|
|
@@ -74,7 +75,8 @@ def generate_namespace_file_from_context(namespace: str,
|
|
|
74
75
|
languages = languages or {}
|
|
75
76
|
assert isinstance(languages, dict)
|
|
76
77
|
context_file = __this_dir__ / f'{namespace}.jsonld'
|
|
77
|
-
|
|
78
|
+
|
|
79
|
+
if not context_file.exists() or FORCE_DOWNLOAD:
|
|
78
80
|
with open(context_file, 'w', encoding='utf-8') as f:
|
|
79
81
|
f.write(requests.get(context_ld).text, )
|
|
80
82
|
|
|
@@ -7,8 +7,8 @@ class LanguageExtension:
|
|
|
7
7
|
|
|
8
8
|
class CODEMETA(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.15
|
|
11
|
+
# Date: 2024-04-03 22:35:04.151807
|
|
12
12
|
_fail = True
|
|
13
13
|
softwareSuggestions: URIRef # ['softwareSuggestions']
|
|
14
14
|
contIntegration: URIRef # ['contIntegration']
|
|
@@ -7,8 +7,8 @@ class LanguageExtension:
|
|
|
7
7
|
|
|
8
8
|
class M4I(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.15
|
|
11
|
+
# Date: 2024-04-03 22:34:52.789096
|
|
12
12
|
_fail = True
|
|
13
13
|
Method: URIRef # ['Methode', 'method']
|
|
14
14
|
NumericalAssignment: URIRef # ['numerical assignment', 'numerische Zuweisung']
|
|
@@ -7,8 +7,8 @@ class LanguageExtension:
|
|
|
7
7
|
|
|
8
8
|
class OBO(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.15
|
|
11
|
+
# Date: 2024-04-03 22:34:54.041082
|
|
12
12
|
_fail = True
|
|
13
13
|
BFO_0000015: URIRef # ['Prozess', 'process']
|
|
14
14
|
BFO_0000017: URIRef # ['realisierbare Entität', 'realizable entity']
|