/
propertyclass.py
506 lines (455 loc) · 20.3 KB
/
propertyclass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
import json
import re
from typing import Tuple, Optional, Any, Union
from urllib.parse import quote_plus
from pystrict import strict
from .connection import Connection
from .helpers import Actions, BaseError, Context, DateTimeStamp, WithId
from .langstring import Languages, LangString
from .listnode import ListNode
from .model import Model
from ..utils.set_encoder import SetEncoder
@strict
class PropertyClass(Model):
ROUTE: str = "/v2/ontologies/properties"
_context: Context
_id: str
_name: str
_ontology_id: str
_superproperties: list[str]
_object: str
_subject: str
_gui_element: str
_gui_attributes: dict[str, str]
_label: LangString
_comment: LangString
_editable: bool
_linkvalue: bool
def __init__(self,
con: Connection,
context: Context,
id: Optional[str] = None,
name: Optional[str] = None,
ontology_id: Optional[str] = None,
superproperties: Optional[list[Union['PropertyClass', str]]] = None,
object: Optional[str] = None,
subject: Optional[str] = None,
gui_element: Optional[str] = None,
gui_attributes: Optional[dict[str, str]] = None,
label: Optional[Union[LangString, str]] = None,
comment: Optional[Union[LangString, str]] = None,
editable: Optional[bool] = None,
linkvalue: Optional[bool] = None):
super().__init__(con)
if not isinstance(context, Context):
raise BaseError('"context"-parameter must be an instance of Context')
self._context = context
self._id = id
self._name = name
self._ontology_id = ontology_id
if isinstance(superproperties, PropertyClass):
self._superproperties = list(map(lambda a: a.id, superproperties))
else:
self._superproperties = superproperties
self._object = object
self._subject = subject
self._gui_element = gui_element
self._gui_attributes = gui_attributes
#
# process label
#
if label is not None:
if isinstance(label, str):
self._label = LangString(label)
elif isinstance(label, LangString):
self._label = label
else:
raise BaseError('Invalid LangString for label!')
else:
self._label = None
#
# process comment
#
if comment is not None:
if isinstance(comment, str):
self._comment = LangString(comment)
elif isinstance(comment, LangString):
self._comment = comment
else:
raise BaseError('Invalid LangString for comment!')
else:
self._comment = None
self._editable = editable
self._linkvalue = linkvalue
#
# Here follows a list of getters/setters
#
@property
def name(self) -> Optional[str]:
return self._name
@name.setter
def name(self, value: str) -> None:
raise BaseError('"name" cannot be modified!')
@property
def id(self) -> Optional[str]:
return self._id
@id.setter
def id(self, value: str) -> None:
raise BaseError('"id" cannot be modified!')
@property
def ontology_id(self) -> Optional[str]:
return self._ontology_id
@ontology_id.setter
def ontology_id(self, value: str) -> None:
raise BaseError('"ontology_id" cannot be modified!')
@property
def superproperties(self) -> Optional[list[str]]:
return self._superproperties
@superproperties.setter
def superproperties(self, value: str) -> None:
raise BaseError('"superproperties" cannot be modified!')
@property
def object(self) -> Optional[str]:
return self._object
@object.setter
def object(self, value: Any):
raise BaseError('"object" cannot be modified!')
@property
def subject(self) -> Optional[str]:
return self._subject
@subject.setter
def subject(self, value: Any):
raise BaseError('"subject" cannot be modified!')
@property
def gui_element(self) -> Optional[str]:
return self._gui_element
@gui_element.setter
def gui_element(self, value: str) -> None:
self._gui_element = value
self._changed.append('gui_element')
@property
def gui_attributes(self) -> Optional[dict[str, str]]:
return self._gui_attributes
@gui_attributes.setter
def gui_attributes(self, value: list[dict[str, str]]) -> None:
self._gui_attributes = value
self._changed.append('gui_attributes')
def addGuiAttribute(self, key: str, value: str) -> None:
self._gui_attributes[key] = value
self._changed.append('gui_attributes')
def rmGuiAttribute(self, key: str) -> None:
if self._gui_attributes.get(key) is not None:
del self._gui_attributes[key]
self._changed.append('gui_attributes')
@property
def label(self) -> Optional[LangString]:
return self._label
@label.setter
def label(self, value: Optional[Union[LangString, str]]) -> None:
if value is None:
self._label.empty() # clear all labels
else:
if isinstance(value, LangString):
self._label = value
elif isinstance(value, str):
self._label = LangString(value)
else:
raise BaseError('Not a valid LangString')
self._changed.add('label')
def addLabel(self, lang: Union[Languages, str], value: str) -> None:
self._label[lang] = value
self._changed.add('label')
def rmLabel(self, lang: Union[Languages, str]) -> None:
del self._label[lang]
self._changed.add('label')
@property
def comment(self) -> Optional[LangString]:
return self._comment
@comment.setter
def comment(self, value: Optional[LangString]) -> None:
if value is None:
self._comment.empty() # clear all comments!
else:
if isinstance(value, LangString):
self._comment = value
elif isinstance(value, str):
self._comment = LangString(value)
else:
raise BaseError('Not a valid LangString')
self._changed.add('comment')
def addComment(self, lang: Union[Languages, str], value: str) -> None:
self._comment[lang] = value
self._changed.add('comment')
def rmComment(self, lang: Union[Languages, str]) -> None:
del self._comment[lang]
self._changed.add('comment')
@property
def editable(self) -> bool:
return self._editable
@editable.setter
def editable(self, value: bool) -> None:
raise BaseError('"editable" cannot be modified!')
@property
def linkvalue(self) -> bool:
return self._linkvalue
@linkvalue.setter
def linkvalue(self) -> None:
raise BaseError('"linkvalue" cannot be modified!')
@classmethod
def fromJsonObj(cls, con: Connection, context: Context, json_obj: Any) -> Any:
if isinstance(json_obj, list):
json_obj = json_obj[0] # TODO: Is it possible to have more than one element in the list??
if not isinstance(con, Connection):
raise BaseError('"con"-parameter must be an instance of Connection')
if not isinstance(context, Context):
raise BaseError('"context"-parameter must be an instance of Context')
rdf = context.prefix_from_iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
rdfs = context.prefix_from_iri("http://www.w3.org/2000/01/rdf-schema#")
owl = context.prefix_from_iri("http://www.w3.org/2002/07/owl#")
xsd = context.prefix_from_iri("http://www.w3.org/2001/XMLSchema#")
knora_api = context.prefix_from_iri("http://api.knora.org/ontology/knora-api/v2#")
salsah_gui = context.prefix_from_iri("http://api.knora.org/ontology/salsah-gui/v2#")
if not (json_obj.get(knora_api + ':isResourceProperty')):
raise BaseError("This is not a property!")
if json_obj.get('@id') is None:
raise BaseError('Property class has no "@id"!')
tmp_id = json_obj.get('@id').split(':')
id = context.iri_from_prefix(tmp_id[0]) + '#' + tmp_id[1]
ontology_id = tmp_id[0]
name = tmp_id[1]
superproperties_obj = json_obj.get(rdfs + ':subPropertyOf')
superproperties: list[Union[None, str]]
if not isinstance(superproperties_obj, list):
superproperties_obj = [superproperties_obj] # make a list out of it
if superproperties_obj:
superproperties = [x['@id'] for x in superproperties_obj if x and x.get('@id')]
else:
superproperties = None
object = WithId(json_obj.get(knora_api + ':objectType')).str()
subject = WithId(json_obj.get(knora_api + ':subjectType')).str()
label = LangString.fromJsonLdObj(json_obj.get(rdfs + ':label'))
comment = LangString.fromJsonLdObj(json_obj.get(rdfs + ':comment'))
gui_element = None
if json_obj.get(salsah_gui + ':guiElement') is not None:
gui_element = WithId(json_obj.get(salsah_gui + ':guiElement')).str()
gui_attributes_list = json_obj.get(salsah_gui + ':guiAttribute')
gui_attributes: Union[None, dict[str, str]] = None
if gui_attributes_list is not None:
gui_attributes = {}
if not isinstance(gui_attributes_list, list):
gui_attributes_list = [gui_attributes_list]
for ga in gui_attributes_list:
tmp = ga.split('=')
if len(tmp) == 1:
gui_attributes[tmp[0]] = ''
else:
gui_attributes[tmp[0]] = tmp[1]
editable = json_obj.get(knora_api + ':isEditable')
linkvalue = json_obj.get(knora_api + ':isLinkProperty')
return cls(con=con,
context=context,
id=id,
name=name,
ontology_id=ontology_id,
superproperties=superproperties,
object=object,
subject=subject,
gui_element=gui_element,
gui_attributes=gui_attributes,
label=label,
comment=comment,
editable=editable,
linkvalue=linkvalue)
def toJsonObj(self, lastModificationDate: DateTimeStamp, action: Actions, what: Optional[str] = None) -> Any:
def resolve_propref(resref: str):
tmp = resref.split(':')
if len(tmp) > 1:
if tmp[0]:
# return {"@id": resref} # fully qualified name in the form "prefix:name"
return {"@id": self._context.get_qualified_iri(
resref)} # fully qualified name in the form "prefix:name"
else:
return {"@id": self._context.prefix_from_iri(self._ontology_id) + ':' + tmp[
1]} # ":name" in current ontology
else:
return {"@id": "knora-api:" + resref} # no ":", must be from knora-api!
tmp = {}
exp = re.compile('^http.*') # It is already a fully IRI
if exp.match(self._ontology_id):
propid = self._context.prefix_from_iri(self._ontology_id) + ":" + self._name
ontid = self._ontology_id
else:
propid = self._ontology_id + ":" + self._name
ontid = self._context.iri_from_prefix(self._ontology_id)
if action == Actions.Create:
if self._name is None:
raise BaseError("There must be a valid property class name!")
if self._ontology_id is None:
raise BaseError("There must be a valid ontology_id given!")
if self._superproperties is None:
superproperties = [{"@id": "knora-api:hasValue"}]
else:
superproperties = list(map(resolve_propref, self._superproperties))
tmp = {
"@id": ontid, # self._ontology_id,
"@type": "owl:Ontology",
"knora-api:lastModificationDate": lastModificationDate.toJsonObj(),
"@graph": [{
"@id": propid,
"@type": "owl:ObjectProperty",
"rdfs:label": self._label.toJsonLdObj(),
"rdfs:subPropertyOf": superproperties
}],
"@context": self._context.toJsonObj()
}
if self._comment:
tmp['@graph'][0]["rdfs:comment"] = self._comment.toJsonLdObj()
if self._subject:
tmp['@graph'][0]["knora-api:subjectType"] = resolve_propref(self._subject)
if self._object:
tmp['@graph'][0]["knora-api:objectType"] = resolve_propref(self._object)
if self._gui_element:
tmp['@graph'][0]["salsah-gui:guiElement"] = {
"@id": self._gui_element
}
if self._gui_attributes:
ga = list(map(lambda x: x[0] + '=' + str(x[1]), self._gui_attributes.items()))
tmp['@graph'][0]["salsah-gui:guiAttribute"] = ga
elif action == Actions.Update:
tmp = {
"@id": ontid, # self._ontology_id,
"@type": "owl:Ontology",
"knora-api:lastModificationDate": lastModificationDate.toJsonObj(),
"@graph": [{
"@id": propid,
"@type": "owl:ObjectProperty",
}],
"@context": self._context.toJsonObj(),
}
if what == 'label':
if not self._label.isEmpty() and 'label' in self._changed:
tmp['@graph'][0]['rdfs:label'] = self._label.toJsonLdObj()
if what == 'comment':
if not self._comment.isEmpty() and 'comment' in self._changed:
tmp['@graph'][0]['rdfs:comment'] = self._comment.toJsonLdObj()
return tmp
def create(self, last_modification_date: DateTimeStamp) -> Tuple[DateTimeStamp, 'PropertyClass']:
jsonobj = self.toJsonObj(last_modification_date, Actions.Create)
jsondata = json.dumps(jsonobj, cls=SetEncoder, indent=2)
result = self._con.post(PropertyClass.ROUTE, jsondata)
last_modification_date = DateTimeStamp(result['knora-api:lastModificationDate'])
return last_modification_date, PropertyClass.fromJsonObj(self._con, self._context, result['@graph'])
def update(self, last_modification_date: DateTimeStamp) -> Tuple[DateTimeStamp, 'ResourceClass']:
#
# Note: Knora is able to change only one thing per call, either label or comment!
#
result = None
something_changed = False
if 'label' in self._changed:
jsonobj = self.toJsonObj(last_modification_date, Actions.Update, 'label')
jsondata = json.dumps(jsonobj, cls=SetEncoder, indent=4)
result = self._con.put(PropertyClass.ROUTE, jsondata)
last_modification_date = DateTimeStamp(result['knora-api:lastModificationDate'])
something_changed = True
if 'comment' in self._changed:
jsonobj = self.toJsonObj(last_modification_date, Actions.Update, 'comment')
jsondata = json.dumps(jsonobj, cls=SetEncoder, indent=4)
result = self._con.put(PropertyClass.ROUTE, jsondata)
last_modification_date = DateTimeStamp(result['knora-api:lastModificationDate'])
something_changed = True
if something_changed:
return last_modification_date, PropertyClass.fromJsonObj(self._con, self._context, result['@graph'])
else:
return last_modification_date, self
def delete(self, last_modification_date: DateTimeStamp) -> DateTimeStamp:
result = self._con.delete(PropertyClass.ROUTE + '/' + quote_plus(self._id) + '?lastModificationDate=' + str(
last_modification_date))
return DateTimeStamp(result['knora-api:lastModificationDate'])
def createDefinitionFileObj(self, context: Context, shortname: str):
"""
Create an object that can be used as input for `create_onto()` to create an ontology on a DSP server
:param context: Context of the ontology
:param shortname: Shortname of the ontology
:return: Python object to be jsonfied
"""
property = {
"name": self.name
}
if self.object:
property["name"] = self.name
if self.superproperties:
superprops = []
for sc in self.superproperties:
superprops.append(context.reduce_iri(sc, shortname))
property["super"] = superprops
if self.object:
property["object"] = context.reduce_iri(self.object, shortname)
if self.label:
property["labels"] = self.label.createDefinitionFileObj()
if self.comment:
property["comments"] = self.comment.createDefinitionFileObj()
if self.gui_element:
property["gui_element"] = context.reduce_iri(self.gui_element, shortname)
if self.gui_attributes:
gui_elements = {}
for (attname, attvalue) in self.gui_attributes.items():
if attname == "size":
gui_elements[attname] = int(attvalue)
elif attname == "maxlength":
gui_elements[attname] = int(attvalue)
elif attname == "maxsize":
gui_elements[attname] = int(attvalue)
elif attname == "hlist":
iri = attvalue[1:-1]
rootnode = ListNode(con=self._con, id=iri).read()
gui_elements[attname] = rootnode.name
elif attname == "numprops":
gui_elements[attname] = int(attvalue)
elif attname == "ncolors":
gui_elements[attname] = int(attvalue)
elif attname == "cols":
gui_elements[attname] = int(attvalue)
elif attname == "rows":
gui_elements[attname] = int(attvalue)
elif attname == "width":
gui_elements[attname] = str(attvalue)
elif attname == "wrap":
gui_elements[attname] = str(attvalue)
elif attname == "max":
gui_elements[attname] = float(attvalue)
elif attname == "min":
gui_elements[attname] = float(attvalue)
else:
gui_elements[attname] = str(attvalue)
property["gui_attributes"] = gui_elements
return property
def print(self, offset: int = 0):
blank = ' '
print(f'{blank:>{offset}}Property Class Info')
print(f'{blank:>{offset + 2}}Name: {self._name}')
print(f'{blank:>{offset + 2}}Ontology prefix: {self._ontology_id}')
print(f'{blank:>{offset + 2}}Superproperties:')
if self._superproperties is not None:
for sc in self._superproperties:
print(f'{blank:>{offset + 4}}{sc}')
if self._label is not None:
print(f'{blank:>{offset + 2}}Labels:')
self._label.print(offset + 4)
if self._subject is not None:
print(f'{blank:>{offset + 4}}Subject: {self._subject}')
if self._object is not None:
print(f'{blank:>{offset + 4}}Object: {self._object}')
if self._gui_element is not None:
print(f'{blank:>{offset + 4}}Guielement: {self._gui_element}')
if self._gui_attributes is not None:
print(f'{blank:>{offset + 4}}Gui Attributes:')
if self._gui_attributes is not None:
for (attname, attvalue) in self._gui_attributes.items():
print(f'{blank:>{offset + 6}}Attribute: {attname} Value: {attvalue}')
if self._comment is not None:
print(f'{blank:>{offset + 2}}Comments:')
self._comment.print(offset + 4)
if self._editable is not None:
print(f'{blank:>{offset + 4}}Editable: {self._editable}')
if self._linkvalue is not None:
print(f'{blank:>{offset + 4}}Editable: {self._linkvalue}')