personal_knowledge_library 3.0.0__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.

Potentially problematic release.


This version of personal_knowledge_library might be problematic. Click here for more details.

Files changed (42) hide show
  1. knowledge/__init__.py +91 -0
  2. knowledge/base/__init__.py +22 -0
  3. knowledge/base/access.py +167 -0
  4. knowledge/base/entity.py +267 -0
  5. knowledge/base/language.py +27 -0
  6. knowledge/base/ontology.py +2734 -0
  7. knowledge/base/search.py +473 -0
  8. knowledge/base/tenant.py +192 -0
  9. knowledge/nel/__init__.py +11 -0
  10. knowledge/nel/base.py +495 -0
  11. knowledge/nel/engine.py +123 -0
  12. knowledge/ontomapping/__init__.py +667 -0
  13. knowledge/ontomapping/manager.py +320 -0
  14. knowledge/public/__init__.py +27 -0
  15. knowledge/public/cache.py +115 -0
  16. knowledge/public/helper.py +373 -0
  17. knowledge/public/relations.py +128 -0
  18. knowledge/public/wikidata.py +1324 -0
  19. knowledge/services/__init__.py +128 -0
  20. knowledge/services/asyncio/__init__.py +7 -0
  21. knowledge/services/asyncio/base.py +458 -0
  22. knowledge/services/asyncio/graph.py +1420 -0
  23. knowledge/services/asyncio/group.py +450 -0
  24. knowledge/services/asyncio/search.py +439 -0
  25. knowledge/services/asyncio/users.py +270 -0
  26. knowledge/services/base.py +533 -0
  27. knowledge/services/graph.py +1897 -0
  28. knowledge/services/group.py +819 -0
  29. knowledge/services/helper.py +142 -0
  30. knowledge/services/ontology.py +1234 -0
  31. knowledge/services/search.py +488 -0
  32. knowledge/services/session.py +444 -0
  33. knowledge/services/tenant.py +281 -0
  34. knowledge/services/users.py +445 -0
  35. knowledge/utils/__init__.py +10 -0
  36. knowledge/utils/graph.py +417 -0
  37. knowledge/utils/wikidata.py +197 -0
  38. knowledge/utils/wikipedia.py +175 -0
  39. personal_knowledge_library-3.0.0.dist-info/LICENSE +201 -0
  40. personal_knowledge_library-3.0.0.dist-info/METADATA +1163 -0
  41. personal_knowledge_library-3.0.0.dist-info/RECORD +42 -0
  42. personal_knowledge_library-3.0.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,1234 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright © 2021-present Wacom. All rights reserved.
3
+ import urllib.parse
4
+ from http import HTTPStatus
5
+ from typing import Any, Optional, Dict, Tuple, List
6
+
7
+ import requests
8
+ from requests import Response
9
+ from requests.adapters import HTTPAdapter
10
+ from urllib3 import Retry
11
+
12
+ from knowledge.base.ontology import (
13
+ OntologyClassReference,
14
+ OntologyPropertyReference,
15
+ OntologyProperty,
16
+ OntologyClass,
17
+ PropertyType,
18
+ THING_CLASS,
19
+ DataPropertyType,
20
+ InflectionSetting,
21
+ Comment,
22
+ OntologyContext,
23
+ OntologyLabel,
24
+ RESOURCE,
25
+ )
26
+ from knowledge.services import USER_AGENT_HEADER_FLAG, DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_FACTOR, STATUS_FORCE_LIST
27
+ from knowledge.services.base import WacomServiceAPIClient, handle_error
28
+ from knowledge.services.graph import AUTHORIZATION_HEADER_FLAG
29
+
30
+ # ------------------------------------------------- Constants ----------------------------------------------------------
31
+ BASE_URI_TAG: str = "baseUri"
32
+ COMMENTS_TAG: str = "comments"
33
+ USER_AGENT_TAG: str = "User-Agent"
34
+ DOMAIN_TAG: str = "domains"
35
+ ICON_TAG: str = "icon"
36
+ INVERSE_OF_TAG: str = "inverseOf"
37
+ KIND_TAG: str = "kind"
38
+ LABELS_TAG: str = "labels"
39
+ LANGUAGE_CODE: str = "lang"
40
+ NAME_TAG: str = "name"
41
+ CONTEXT_TAG: str = "context"
42
+ RANGE_TAG: str = "ranges"
43
+ SUB_CLASS_OF_TAG: str = "subClassOf"
44
+ SUB_PROPERTY_OF_TAG: str = "subPropertyOf"
45
+ LISTING_MODE_PARAM: str = "listingMode"
46
+ TEXT_TAG: str = "value"
47
+ DEFAULT_TIMEOUT: int = 30
48
+
49
+
50
+ class OntologyService(WacomServiceAPIClient):
51
+ """
52
+ Ontology API Client
53
+ -------------------
54
+ Client to access the ontology service. Offers the following functionality:
55
+ - Listing class names and property names
56
+ - Create new ontology types
57
+ - Update ontology types
58
+
59
+ Parameters
60
+ ----------
61
+ service_url: str
62
+ URL of the service
63
+ service_endpoint: str
64
+ Base endpoint
65
+ """
66
+
67
+ CONTEXT_ENDPOINT: str = "context"
68
+ CONCEPTS_ENDPOINT: str = "concepts"
69
+ PROPERTIES_ENDPOINT: str = "properties"
70
+ RDF_ENDPOINT: str = "context/{}/versions/rdf"
71
+ PROPERTY_ENDPOINT: str = "context/{}/properties/{}"
72
+
73
+ def __init__(self, service_url: str = WacomServiceAPIClient.SERVICE_URL, service_endpoint: str = "ontology/v1"):
74
+ super().__init__(
75
+ application_name="Ontology Service", service_url=service_url, service_endpoint=service_endpoint
76
+ )
77
+
78
+ def context(
79
+ self,
80
+ auth_key: Optional[str] = None,
81
+ timeout: int = DEFAULT_TIMEOUT,
82
+ max_retries: int = DEFAULT_MAX_RETRIES,
83
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
84
+ ) -> Optional[OntologyContext]:
85
+ """
86
+ Getting the information on the context.
87
+
88
+ Parameters
89
+ ----------
90
+ auth_key: Optional[str] = None
91
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
92
+ timeout: int
93
+ Timeout for the request (default: 60 seconds)
94
+ max_retries: int
95
+ Maximum number of retries
96
+ backoff_factor: float
97
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
98
+ second try without a delay)
99
+
100
+ Returns
101
+ -------
102
+ context_description: Optional[OntologyContext]
103
+ Context of the Ontology
104
+ """
105
+ if auth_key is None:
106
+ auth_key, _ = self.handle_token()
107
+ headers: dict = {AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}", USER_AGENT_HEADER_FLAG: self.user_agent}
108
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
109
+ with requests.Session() as session:
110
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
111
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
112
+ response: Response = session.get(
113
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}",
114
+ headers=headers,
115
+ timeout=timeout,
116
+ verify=self.verify_calls,
117
+ )
118
+ if response.ok:
119
+ return OntologyContext.from_dict(response.json())
120
+ return None
121
+
122
+ def context_metadata(
123
+ self,
124
+ context: str,
125
+ auth_key: Optional[str] = None,
126
+ timeout: int = DEFAULT_TIMEOUT,
127
+ max_retries: int = DEFAULT_MAX_RETRIES,
128
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
129
+ ) -> List[InflectionSetting]:
130
+ """
131
+ Getting the meta-data on the context.
132
+
133
+ Parameters
134
+ ----------
135
+ context: str
136
+ Name of the context.
137
+ auth_key: Optional[str] [default:= None]
138
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
139
+ timeout: int
140
+ Timeout for the request (default: 60 seconds)
141
+ max_retries: int
142
+ Maximum number of retries
143
+ backoff_factor: float
144
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
145
+ second try without a delay)
146
+
147
+ Returns
148
+ -------
149
+ list_inflection_settings: List[InflectionSetting]
150
+ List of inflection settings.
151
+ """
152
+ if auth_key is None:
153
+ auth_key, _ = self.handle_token()
154
+ headers: Dict[str, str] = {
155
+ USER_AGENT_HEADER_FLAG: self.user_agent,
156
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
157
+ }
158
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
159
+ with requests.Session() as session:
160
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
161
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
162
+ response: Response = session.get(
163
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/{context}" "/metadata",
164
+ headers=headers,
165
+ timeout=timeout,
166
+ verify=self.verify_calls,
167
+ )
168
+ if response.ok:
169
+ return [
170
+ InflectionSetting.from_dict(c)
171
+ for c in response.json()
172
+ if c.get("concept") is not None and not c.get("concept").startswith("http")
173
+ ]
174
+ raise handle_error("Failed to retrieve context metadata", response, headers=headers)
175
+
176
+ def concepts(
177
+ self,
178
+ context: str,
179
+ auth_key: Optional[str] = None,
180
+ timeout: int = DEFAULT_TIMEOUT,
181
+ max_retries: int = DEFAULT_MAX_RETRIES,
182
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
183
+ ) -> List[Tuple[OntologyClassReference, OntologyClassReference]]:
184
+ """Retrieve all concept classes.
185
+
186
+ **Remark:**
187
+ Works for users with role 'User' and 'TenantAdmin'.
188
+
189
+ Parameters
190
+ ----------
191
+ context: str
192
+ Context of the ontology
193
+ auth_key: Optional[str] = None
194
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
195
+ timeout: int
196
+ Timeout for the request (default: 60 seconds)
197
+ max_retries: int
198
+ Maximum number of retries
199
+ backoff_factor: float
200
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
201
+ second try without a delay)
202
+
203
+ Returns
204
+ -------
205
+ concepts: List[Tuple[OntologyClassReference, OntologyClassReference]]
206
+ List of ontology classes. Tuple<Classname, Superclass>
207
+ """
208
+ if auth_key is None:
209
+ auth_key, _ = self.handle_token()
210
+ headers: Dict[str, str] = {
211
+ USER_AGENT_HEADER_FLAG: self.user_agent,
212
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
213
+ }
214
+ url: str = (
215
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/{context}/"
216
+ f"{OntologyService.CONCEPTS_ENDPOINT}"
217
+ )
218
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
219
+ with requests.Session() as session:
220
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
221
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
222
+ response: Response = session.get(url, headers=headers, verify=self.verify_calls, timeout=timeout)
223
+ if response.ok:
224
+ response_list: List[Tuple[OntologyClassReference, OntologyClassReference]] = []
225
+ result = response.json()
226
+ for struct in result:
227
+ response_list.append(
228
+ (
229
+ OntologyClassReference.parse(struct[NAME_TAG]),
230
+ (
231
+ None
232
+ if struct[SUB_CLASS_OF_TAG] is None
233
+ else OntologyClassReference.parse(struct[SUB_CLASS_OF_TAG])
234
+ ),
235
+ )
236
+ )
237
+ return response_list
238
+ raise handle_error("Failed to retrieve concepts", response, headers=headers)
239
+
240
+ def concepts_types(
241
+ self,
242
+ context: str,
243
+ auth_key: Optional[str] = None,
244
+ timeout: int = DEFAULT_TIMEOUT,
245
+ max_retries: int = DEFAULT_MAX_RETRIES,
246
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
247
+ ) -> List[OntologyClass]:
248
+ """Retrieve all concept class types.
249
+
250
+ **Remark:**
251
+ Works for users with role 'User' and 'TenantAdmin'.
252
+
253
+ Parameters
254
+ ----------
255
+ context: str
256
+ Context of the ontology
257
+ auth_key: Optional[str] = None
258
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
259
+ timeout: int
260
+ Timeout for the request (default: 60 seconds)
261
+ max_retries: int
262
+ Maximum number of retries
263
+ backoff_factor: float
264
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
265
+ second try without a delay)
266
+ Returns
267
+ -------
268
+ concepts: List[OntologyClass]
269
+ List of ontology classes.
270
+ """
271
+ if auth_key is None:
272
+ auth_key, _ = self.handle_token()
273
+ headers: Dict[str, str] = {
274
+ USER_AGENT_HEADER_FLAG: self.user_agent,
275
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
276
+ }
277
+ url: str = (
278
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/{context}/"
279
+ f"{OntologyService.CONCEPTS_ENDPOINT}"
280
+ )
281
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
282
+ with requests.Session() as session:
283
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
284
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
285
+ response: Response = session.get(
286
+ url, headers=headers, verify=self.verify_calls, params={LISTING_MODE_PARAM: "Full"}, timeout=timeout
287
+ )
288
+ if response.ok:
289
+ response_list: List[OntologyClass] = []
290
+ for struct in response.json():
291
+ if struct[NAME_TAG] != RESOURCE:
292
+ response_list.append(OntologyClass.from_dict(struct))
293
+ return response_list
294
+ raise handle_error("Failed to retrieve concepts", response, headers=headers)
295
+
296
+ def properties(
297
+ self,
298
+ context: str,
299
+ auth_key: Optional[str] = None,
300
+ timeout: int = DEFAULT_TIMEOUT,
301
+ max_retries: int = DEFAULT_MAX_RETRIES,
302
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
303
+ ) -> List[Tuple[OntologyPropertyReference, OntologyPropertyReference]]:
304
+ """List all properties.
305
+
306
+ **Remark:**
307
+ Works for users with role 'User' and 'TenantAdmin'.
308
+
309
+ Parameters
310
+ ----------
311
+ context: str
312
+ Name of the context
313
+ auth_key: Optional[str] [default:= None]
314
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
315
+ timeout: int
316
+ Timeout for the request (default: 60 seconds)
317
+ max_retries: int
318
+ Maximum number of retries
319
+ backoff_factor: float
320
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
321
+ second try without a delay)
322
+
323
+ Returns
324
+ -------
325
+ contexts: List[Tuple[OntologyPropertyReference, OntologyPropertyReference]]
326
+ List of ontology contexts
327
+ """
328
+ if auth_key is None:
329
+ auth_key, _ = self.handle_token()
330
+ headers: Dict[str, str] = {
331
+ USER_AGENT_HEADER_FLAG: self.user_agent,
332
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
333
+ }
334
+ context_url: str = urllib.parse.quote_plus(context)
335
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
336
+ with requests.Session() as session:
337
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
338
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
339
+ response: Response = session.get(
340
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/"
341
+ f"{context_url}/{OntologyService.PROPERTIES_ENDPOINT}",
342
+ headers=headers,
343
+ timeout=timeout,
344
+ verify=self.verify_calls,
345
+ )
346
+ # Return empty list if the NOT_FOUND is reported
347
+ if response.status_code == HTTPStatus.NOT_FOUND:
348
+ return []
349
+ if response.ok:
350
+ response_list: List[Tuple[OntologyPropertyReference, OntologyPropertyReference]] = []
351
+ for c in response.json():
352
+ response_list.append(
353
+ (
354
+ OntologyPropertyReference.parse(c[NAME_TAG]),
355
+ (
356
+ None
357
+ if c[SUB_PROPERTY_OF_TAG] is None or c.get(SUB_PROPERTY_OF_TAG) == ""
358
+ else OntologyPropertyReference.parse(c[SUB_PROPERTY_OF_TAG])
359
+ ),
360
+ )
361
+ )
362
+ return response_list
363
+ raise handle_error("Failed to retrieve properties", response, headers=headers)
364
+
365
+ def properties_types(
366
+ self,
367
+ context: str,
368
+ auth_key: Optional[str] = None,
369
+ timeout: int = DEFAULT_TIMEOUT,
370
+ max_retries: int = DEFAULT_MAX_RETRIES,
371
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
372
+ ) -> List[OntologyProperty]:
373
+ """List all properties types.
374
+
375
+ **Remark:**
376
+ Works for users with role 'User' and 'TenantAdmin'.
377
+
378
+ Parameters
379
+ ----------
380
+ context: str
381
+ Name of the context
382
+ auth_key: Optional[str] [default:= None]
383
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
384
+ timeout: int
385
+ Timeout for the request (default: 60 seconds)
386
+ max_retries: int
387
+ Maximum number of retries
388
+ backoff_factor: float
389
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
390
+ second try without a delay)
391
+ Returns
392
+ -------
393
+ contexts: List[OntologyProperty]
394
+ List of ontology contexts
395
+ """
396
+ if auth_key is None:
397
+ auth_key, _ = self.handle_token()
398
+ headers: Dict[str, str] = {
399
+ USER_AGENT_HEADER_FLAG: self.user_agent,
400
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
401
+ }
402
+ context_url: str = urllib.parse.quote_plus(context)
403
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
404
+ with requests.Session() as session:
405
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
406
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
407
+ response: Response = session.get(
408
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/"
409
+ f"{context_url}/{OntologyService.PROPERTIES_ENDPOINT}",
410
+ params={LISTING_MODE_PARAM: "Full"},
411
+ headers=headers,
412
+ timeout=timeout,
413
+ verify=self.verify_calls,
414
+ )
415
+ # Return empty list if the NOT_FOUND is reported
416
+ if response.status_code == HTTPStatus.NOT_FOUND:
417
+ return []
418
+ if response.ok:
419
+ response_list: List[OntologyProperty] = []
420
+ for c in response.json():
421
+ response_list.append((OntologyProperty.from_dict(c)))
422
+ return response_list
423
+ raise handle_error("Failed to retrieve properties", response, headers=headers)
424
+
425
+ def concept(
426
+ self,
427
+ context: str,
428
+ concept_name: str,
429
+ auth_key: Optional[str] = None,
430
+ timeout: int = DEFAULT_TIMEOUT,
431
+ max_retries: int = DEFAULT_MAX_RETRIES,
432
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
433
+ ) -> OntologyClass:
434
+ """Retrieve a concept instance.
435
+
436
+ **Remark:**
437
+ Works for users with role 'User' and 'TenantAdmin'.
438
+
439
+ Parameters
440
+ ----------
441
+ context: str
442
+ Name of the context
443
+ concept_name: str
444
+ IRI of the concept
445
+ auth_key: Optional[str] [default:= None]
446
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
447
+ timeout: int
448
+ Timeout for the request (default: 60 seconds)
449
+ max_retries: int
450
+ Maximum number of retries
451
+ backoff_factor: float
452
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
453
+ second try without a delay)
454
+ Returns
455
+ -------
456
+ instance: OntologyClass
457
+ Instance of the concept
458
+ """
459
+ if auth_key is None:
460
+ auth_key, _ = self.handle_token()
461
+ headers: Dict[str, str] = {
462
+ USER_AGENT_HEADER_FLAG: self.user_agent,
463
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
464
+ }
465
+ context_url: str = urllib.parse.quote_plus(context)
466
+ concept_url: str = urllib.parse.quote_plus(concept_name)
467
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
468
+ with requests.Session() as session:
469
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
470
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
471
+ response: Response = session.get(
472
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/{context_url}"
473
+ f"/{OntologyService.CONCEPTS_ENDPOINT}/{concept_url}",
474
+ headers=headers,
475
+ verify=self.verify_calls,
476
+ timeout=timeout,
477
+ )
478
+ if response.ok:
479
+ result: Dict[str, Any] = response.json()
480
+ return OntologyClass.from_dict(result)
481
+ raise handle_error("Failed to retrieve concept", response, headers=headers)
482
+
483
+ def property(
484
+ self,
485
+ context: str,
486
+ property_name: str,
487
+ auth_key: Optional[str] = None,
488
+ timeout: int = DEFAULT_TIMEOUT,
489
+ max_retries: int = DEFAULT_MAX_RETRIES,
490
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
491
+ ) -> OntologyProperty:
492
+ """Retrieve a property instance.
493
+
494
+ **Remark:**
495
+ Works for users with role 'User' and 'TenantAdmin'.
496
+
497
+ Parameters
498
+ ----------
499
+ context: str
500
+ Name of the context
501
+ property_name: str
502
+ IRI of the property
503
+ auth_key: Optional[str] [default:= None]
504
+ If auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
505
+ timeout: int
506
+ Timeout for the request (default: 60 seconds)
507
+ max_retries: int
508
+ Maximum number of retries
509
+ backoff_factor: float
510
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
511
+ second try without a delay)
512
+
513
+ Returns
514
+ -------
515
+ instance: OntologyProperty
516
+ Instance of the property
517
+ """
518
+ if auth_key is None:
519
+ auth_key, _ = self.handle_token()
520
+ headers: Dict[str, str] = {
521
+ USER_AGENT_HEADER_FLAG: self.user_agent,
522
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
523
+ }
524
+ context_url: str = urllib.parse.quote_plus(context)
525
+ concept_url: str = urllib.parse.quote_plus(property_name)
526
+ param: str = f"context/{context_url}/properties/{concept_url}"
527
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
528
+ with requests.Session() as session:
529
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
530
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
531
+ response: Response = session.get(
532
+ f"{self.service_base_url}{param}", headers=headers, verify=self.verify_calls, timeout=timeout
533
+ )
534
+ if response.ok:
535
+ return OntologyProperty.from_dict(response.json())
536
+ raise handle_error("Failed to retrieve property", response, headers=headers)
537
+
538
+ def create_concept(
539
+ self,
540
+ context: str,
541
+ reference: OntologyClassReference,
542
+ subclass_of: OntologyClassReference = THING_CLASS,
543
+ icon: Optional[str] = None,
544
+ labels: Optional[List[OntologyLabel]] = None,
545
+ comments: Optional[List[Comment]] = None,
546
+ auth_key: Optional[str] = None,
547
+ timeout: int = DEFAULT_TIMEOUT,
548
+ max_retries: int = DEFAULT_MAX_RETRIES,
549
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
550
+ ) -> Dict[str, str]:
551
+ """Create concept class.
552
+
553
+ **Remark:**
554
+ Only works for users with role 'TenantAdmin'.
555
+
556
+ Parameters
557
+ ----------
558
+ context: str
559
+ Context of ontology
560
+ reference: OntologyClassReference
561
+ Name of the concept
562
+ subclass_of: OntologyClassReference (default:=wacom:core#Thing)
563
+ Super class of the concept
564
+ icon: Optional[str] (default:= None)
565
+ Icon representing the concept
566
+ labels: Optional[List[OntologyLabel]] (default:= None)
567
+ Labels for the class
568
+ comments: Optional[List[Comment]] (default:= None)
569
+ Comments for the class
570
+ auth_key: Optional[str] [default:= None]
571
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
572
+ timeout: int
573
+ Timeout for the request (default: 60 seconds)
574
+ max_retries: int
575
+ Maximum number of retries
576
+ backoff_factor: float
577
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
578
+ second try without a delay)
579
+
580
+ Returns
581
+ -------
582
+ result: Dict[str, str]
583
+ Result from the service
584
+
585
+ Raises
586
+ ------
587
+ WacomServiceException
588
+ If the ontology service returns an error code, exception is thrown.
589
+ """
590
+ if auth_key is None:
591
+ auth_key, _ = self.handle_token()
592
+ headers: Dict[str, str] = {
593
+ USER_AGENT_HEADER_FLAG: self.user_agent,
594
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
595
+ }
596
+ payload: Dict[str, Any] = {
597
+ SUB_CLASS_OF_TAG: subclass_of.iri,
598
+ NAME_TAG: reference.iri,
599
+ LABELS_TAG: [],
600
+ COMMENTS_TAG: [],
601
+ ICON_TAG: icon,
602
+ }
603
+ for label in labels if labels is not None else []:
604
+ payload[LABELS_TAG].append({TEXT_TAG: label.content, LANGUAGE_CODE: label.language_code})
605
+ for comment in comments if comments is not None else []:
606
+ payload[COMMENTS_TAG].append({TEXT_TAG: comment.content, LANGUAGE_CODE: comment.language_code})
607
+ url: str = (
608
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/{context}/"
609
+ f"{OntologyService.CONCEPTS_ENDPOINT}"
610
+ )
611
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
612
+ with requests.Session() as session:
613
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
614
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
615
+ response: Response = session.post(
616
+ url, headers=headers, json=payload, verify=self.verify_calls, timeout=timeout
617
+ )
618
+ if response.ok:
619
+ result_dict: Dict[str, str] = response.json()
620
+ return result_dict
621
+ raise handle_error("Failed to create concept", response, headers=headers, payload=payload)
622
+
623
+ def update_concept(
624
+ self,
625
+ context: str,
626
+ name: str,
627
+ subclass_of: Optional[str],
628
+ icon: Optional[str] = None,
629
+ labels: Optional[List[OntologyLabel]] = None,
630
+ comments: Optional[List[Comment]] = None,
631
+ auth_key: Optional[str] = None,
632
+ timeout: int = DEFAULT_TIMEOUT,
633
+ max_retries: int = DEFAULT_MAX_RETRIES,
634
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
635
+ ) -> Dict[str, str]:
636
+ """Update concept class.
637
+
638
+ **Remark:**
639
+ Only works for users with role 'TenantAdmin'.
640
+
641
+ Parameters
642
+ ----------
643
+ context: str
644
+ Context of ontology
645
+ name: str
646
+ Name of the concept
647
+ subclass_of: Optional[str]
648
+ Super class of the concept
649
+ icon: Optional[str] (default:= None)
650
+ Icon representing the concept
651
+ labels: Optional[List[OntologyLabel]] (default:= None)
652
+ Labels for the class
653
+ comments: Optional[List[Comment]] (default:= None)
654
+ Comments for the class
655
+ auth_key: Optional[str] [default:= None]
656
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
657
+ timeout: int
658
+ Timeout for the request (default: 60 seconds)
659
+ max_retries: int
660
+ Maximum number of retries
661
+ backoff_factor: float
662
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
663
+ second try without a delay)
664
+
665
+ Returns
666
+ -------
667
+ response: Dict[str, str]
668
+ Response from service
669
+
670
+ Raises
671
+ ------
672
+ WacomServiceException
673
+ If the ontology service returns an error code, exception is thrown.
674
+ """
675
+ if auth_key is None:
676
+ auth_key, _ = self.handle_token()
677
+ headers: Dict[str, str] = {
678
+ USER_AGENT_HEADER_FLAG: self.user_agent,
679
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
680
+ }
681
+ payload: Dict[str, Any] = {
682
+ SUB_CLASS_OF_TAG: subclass_of,
683
+ NAME_TAG: name,
684
+ LABELS_TAG: [],
685
+ COMMENTS_TAG: [],
686
+ ICON_TAG: icon,
687
+ }
688
+ for label in labels if labels is not None else []:
689
+ payload[LABELS_TAG].append({TEXT_TAG: label.content, LANGUAGE_CODE: label.language_code})
690
+ for comment in comments if comments is not None else []:
691
+ payload[COMMENTS_TAG].append({TEXT_TAG: comment.content, LANGUAGE_CODE: comment.language_code})
692
+ url: str = (
693
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/{context}/"
694
+ f"{OntologyService.CONCEPTS_ENDPOINT}"
695
+ )
696
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
697
+ with requests.Session() as session:
698
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
699
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
700
+ response: Response = session.put(
701
+ url, headers=headers, json=payload, verify=self.verify_calls, timeout=timeout
702
+ )
703
+ if response.ok:
704
+ return response.json()
705
+ raise handle_error("Failed to update concept", response, headers=headers, payload=payload)
706
+
707
+ def delete_concept(
708
+ self,
709
+ context: str,
710
+ reference: OntologyClassReference,
711
+ auth_key: Optional[str] = None,
712
+ timeout: int = DEFAULT_TIMEOUT,
713
+ max_retries: int = DEFAULT_MAX_RETRIES,
714
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
715
+ ):
716
+ """Delete concept class.
717
+
718
+ **Remark:**
719
+ Only works for users with role 'TenantAdmin'.
720
+
721
+ Parameters
722
+ ----------
723
+ context: str
724
+ Context of ontology
725
+ reference: OntologyClassReference
726
+ Name of the concept
727
+ auth_key: Optional[str] [default:= None]
728
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
729
+ timeout: int
730
+ Timeout for the request (default: 60 seconds)
731
+ max_retries: int
732
+ Maximum number of retries
733
+ backoff_factor: float
734
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
735
+ second try without a delay)
736
+
737
+ Raises
738
+ ------
739
+ WacomServiceException
740
+ If the ontology service returns an error code, exception is thrown.
741
+ """
742
+ if auth_key is None:
743
+ auth_key, _ = self.handle_token()
744
+ headers: Dict[str, str] = {
745
+ USER_AGENT_HEADER_FLAG: self.user_agent,
746
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
747
+ }
748
+ context_url: str = urllib.parse.quote_plus(context)
749
+ concept_url: str = urllib.parse.quote_plus(reference.iri)
750
+ url: str = f"{self.service_base_url}context/{context_url}/concepts/{concept_url}"
751
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
752
+ with requests.Session() as session:
753
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
754
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
755
+ response: Response = session.delete(url, headers=headers, verify=self.verify_calls, timeout=timeout)
756
+ if not response.ok:
757
+ raise handle_error("Failed to delete concept", response, headers=headers)
758
+
759
+ def create_object_property(
760
+ self,
761
+ context: str,
762
+ reference: OntologyPropertyReference,
763
+ domains_cls: List[OntologyClassReference],
764
+ ranges_cls: List[OntologyClassReference],
765
+ inverse_of: Optional[OntologyPropertyReference] = None,
766
+ subproperty_of: Optional[OntologyPropertyReference] = None,
767
+ icon: Optional[str] = None,
768
+ labels: Optional[List[OntologyLabel]] = None,
769
+ comments: Optional[List[Comment]] = None,
770
+ auth_key: Optional[str] = None,
771
+ timeout: int = DEFAULT_TIMEOUT,
772
+ max_retries: int = DEFAULT_MAX_RETRIES,
773
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
774
+ ) -> Dict[str, str]:
775
+ """Create property.
776
+
777
+ **Remark:**
778
+ Only works for users with role 'TenantAdmin'.
779
+
780
+ Parameters
781
+ ----------
782
+ context: str
783
+ Context of ontology
784
+ reference: OntologyPropertyReference
785
+ Name of the concept
786
+ domains_cls: List[OntologyClassReference]
787
+ IRI of the domain
788
+ ranges_cls: List[OntologyClassReference]
789
+ IRI of the range
790
+ inverse_of: Optional[OntologyPropertyReference] (default:= None)
791
+ Inverse property
792
+ subproperty_of: Optional[OntologyPropertyReference] = None,
793
+ Super property of the concept
794
+ icon: Optional[str] (default:= None)
795
+ Icon representing the concept
796
+ labels: Optional[List[OntologyLabel]] (default:= None)
797
+ Labels for the class
798
+ comments: Optional[List[Comment]] (default:= None)
799
+ Comments for the class
800
+ auth_key: Optional[str] [default:= None]
801
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
802
+ timeout: int
803
+ Timeout for the request (default: 60 seconds)
804
+ max_retries: int
805
+ Maximum number of retries
806
+ backoff_factor: float
807
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
808
+ second try without a delay)
809
+
810
+ Returns
811
+ -------
812
+ result: Dict[str, str]
813
+ Result from the service
814
+
815
+ Raises
816
+ ------
817
+ WacomServiceException
818
+ If the ontology service returns an error code, exception is thrown.
819
+ """
820
+ if auth_key is None:
821
+ auth_key, _ = self.handle_token()
822
+ headers: Dict[str, str] = {
823
+ USER_AGENT_HEADER_FLAG: self.user_agent,
824
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
825
+ }
826
+ payload: Dict[str, Any] = {
827
+ KIND_TAG: PropertyType.OBJECT_PROPERTY.value,
828
+ DOMAIN_TAG: [d.iri for d in domains_cls],
829
+ RANGE_TAG: [r.iri for r in ranges_cls],
830
+ SUB_PROPERTY_OF_TAG: subproperty_of.iri if subproperty_of is not None else None,
831
+ INVERSE_OF_TAG: inverse_of.iri if inverse_of is not None else None,
832
+ NAME_TAG: reference.iri,
833
+ LABELS_TAG: [],
834
+ COMMENTS_TAG: [],
835
+ ICON_TAG: icon,
836
+ }
837
+ context_url: str = urllib.parse.quote_plus(context)
838
+ for label in labels if labels is not None else []:
839
+ payload[LABELS_TAG].append({TEXT_TAG: label.content, LANGUAGE_CODE: label.language_code})
840
+ for comment in comments if comments is not None else []:
841
+ payload[COMMENTS_TAG].append({TEXT_TAG: comment.content, LANGUAGE_CODE: comment.language_code})
842
+ url: str = (
843
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/{context_url}/"
844
+ f"{OntologyService.PROPERTIES_ENDPOINT}"
845
+ )
846
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
847
+ with requests.Session() as session:
848
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
849
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
850
+ response: Response = session.post(
851
+ url, headers=headers, json=payload, verify=self.verify_calls, timeout=timeout
852
+ )
853
+ if response.ok:
854
+ return response.json()
855
+ raise handle_error("Failed to create object property", response, headers=headers, payload=payload)
856
+
857
+ def create_data_property(
858
+ self,
859
+ context: str,
860
+ reference: OntologyPropertyReference,
861
+ domains_cls: List[OntologyClassReference],
862
+ ranges_cls: List[DataPropertyType],
863
+ subproperty_of: Optional[OntologyPropertyReference] = None,
864
+ icon: Optional[str] = None,
865
+ labels: Optional[List[OntologyLabel]] = None,
866
+ comments: Optional[List[Comment]] = None,
867
+ auth_key: Optional[str] = None,
868
+ timeout: int = DEFAULT_TIMEOUT,
869
+ max_retries: int = DEFAULT_MAX_RETRIES,
870
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
871
+ ) -> Dict[str, str]:
872
+ """Create data property.
873
+
874
+ **Remark:**
875
+ Only works for users with role 'TenantAdmin'.
876
+
877
+ Parameters
878
+ ----------
879
+ context: str
880
+ Context of ontology
881
+ reference: OntologyPropertyReference
882
+ Name of the concept
883
+ domains_cls: List[OntologyClassReference]
884
+ IRI of the domain
885
+ ranges_cls: List[DataPropertyType]
886
+ Data property type
887
+ subproperty_of: Optional[OntologyPropertyReference] = None,
888
+ Super property of the concept
889
+ icon: Optional[str] (default:= None)
890
+ Icon representing the concept
891
+ labels: Optional[List[Label]] (default:= None)
892
+ Labels for the class
893
+ comments: Optional[List[Comment]] (default:= None)
894
+ Comments for the class
895
+ auth_key: Optional[str] [default:= None]
896
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
897
+ timeout: int
898
+ Timeout for the request (default: 60 seconds)
899
+ max_retries: int
900
+ Maximum number of retries
901
+ backoff_factor: float
902
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
903
+ second try without a delay)
904
+
905
+ Returns
906
+ -------
907
+ result: Dict[str, str]
908
+ Result from the service
909
+
910
+ Raises
911
+ ------
912
+ WacomServiceException
913
+ If the ontology service returns an error code, exception is thrown.
914
+ """
915
+ if auth_key is None:
916
+ auth_key, _ = self.handle_token()
917
+ headers: Dict[str, str] = {
918
+ USER_AGENT_HEADER_FLAG: self.user_agent,
919
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
920
+ }
921
+ payload: Dict[str, Any] = {
922
+ KIND_TAG: PropertyType.DATA_PROPERTY.value,
923
+ DOMAIN_TAG: [d.iri for d in domains_cls],
924
+ RANGE_TAG: [r.value for r in ranges_cls],
925
+ SUB_PROPERTY_OF_TAG: subproperty_of.iri if subproperty_of is not None else None,
926
+ NAME_TAG: reference.iri,
927
+ LABELS_TAG: [],
928
+ COMMENTS_TAG: [],
929
+ ICON_TAG: icon,
930
+ }
931
+ context_url: str = urllib.parse.quote_plus(context)
932
+ for label in labels if labels is not None else []:
933
+ payload[LABELS_TAG].append({TEXT_TAG: label.content, LANGUAGE_CODE: label.language_code})
934
+ for comment in comments if comments is not None else []:
935
+ payload[COMMENTS_TAG].append({TEXT_TAG: comment.content, LANGUAGE_CODE: comment.language_code})
936
+ url: str = (
937
+ f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/{context_url}/"
938
+ f"{OntologyService.PROPERTIES_ENDPOINT}"
939
+ )
940
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
941
+ with requests.Session() as session:
942
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
943
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
944
+ response: Response = session.post(
945
+ url, headers=headers, json=payload, verify=self.verify_calls, timeout=timeout
946
+ )
947
+ if response.ok:
948
+ return response.json()
949
+ raise handle_error("Failed to create data property", response, headers=headers, payload=payload)
950
+
951
+ def delete_property(
952
+ self,
953
+ context: str,
954
+ reference: OntologyPropertyReference,
955
+ auth_key: Optional[str] = None,
956
+ timeout: int = DEFAULT_TIMEOUT,
957
+ max_retries: int = DEFAULT_MAX_RETRIES,
958
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
959
+ ):
960
+ """Delete property.
961
+
962
+ **Remark:**
963
+ Only works for users with role 'TenantAdmin'.
964
+
965
+ Parameters
966
+ ----------
967
+ context: str
968
+ Context of ontology
969
+ reference: OntologyPropertyReference
970
+ Name of the property
971
+ auth_key: Optional[str] [default:= None]
972
+ If auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
973
+ timeout: int
974
+ Timeout for the request (default: 60 seconds)
975
+ max_retries: int
976
+ Maximum number of retries
977
+ backoff_factor: float
978
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
979
+ second try without a delay)
980
+
981
+ Raises
982
+ ------
983
+ WacomServiceException
984
+ If the ontology service returns an error code, exception is thrown.
985
+ """
986
+ if auth_key is None:
987
+ auth_key, _ = self.handle_token()
988
+ headers: Dict[str, str] = {
989
+ USER_AGENT_HEADER_FLAG: self.user_agent,
990
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
991
+ }
992
+ context_url: str = urllib.parse.quote_plus(context)
993
+ property_url: str = urllib.parse.quote_plus(reference.iri)
994
+ url: str = f"{self.service_base_url}context/{context_url}/properties/{property_url}"
995
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
996
+ with requests.Session() as session:
997
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
998
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
999
+ response: Response = session.delete(url, headers=headers, verify=self.verify_calls, timeout=timeout)
1000
+ if not response.ok:
1001
+ raise handle_error("Failed to delete property", response, headers=headers)
1002
+
1003
+ def create_context(
1004
+ self,
1005
+ name: str,
1006
+ context: Optional[str] = None,
1007
+ base_uri: Optional[str] = None,
1008
+ icon: Optional[str] = None,
1009
+ labels: List[OntologyLabel] = None,
1010
+ comments: List[Comment] = None,
1011
+ auth_key: Optional[str] = None,
1012
+ timeout: int = DEFAULT_TIMEOUT,
1013
+ max_retries: int = DEFAULT_MAX_RETRIES,
1014
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
1015
+ ) -> Dict[str, str]:
1016
+ """Create context.
1017
+
1018
+ **Remark:**
1019
+ Only works for users with role 'TenantAdmin'.
1020
+
1021
+ Parameters
1022
+ ----------
1023
+ base_uri: str
1024
+ Base URI
1025
+ name: str
1026
+ Name of the context.
1027
+ context: Optional[str] [default:= None]
1028
+ Context of ontology
1029
+ icon: Optional[str] (default:= None)
1030
+ Icon representing the concept
1031
+ labels: Optional[List[OntologyLabel]] (default:= None)
1032
+ Labels for the context
1033
+ comments: Optional[List[Comment]] (default:= None)
1034
+ Comments for the context
1035
+ auth_key: Optional[str] [default:= None]
1036
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
1037
+ timeout: int
1038
+ Timeout for the request (default: 60 seconds)
1039
+ timeout: int
1040
+ Timeout for the request (default: 60 seconds)
1041
+ max_retries: int
1042
+ Maximum number of retries
1043
+ backoff_factor: float
1044
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
1045
+ second try without a delay)
1046
+
1047
+ Returns
1048
+ -------
1049
+ result: Dict[str, str]
1050
+ Result from the service
1051
+
1052
+ Raises
1053
+ ------
1054
+ WacomServiceException
1055
+ If the ontology service returns an error code, exception is thrown.
1056
+ """
1057
+ if auth_key is None:
1058
+ auth_key, _ = self.handle_token()
1059
+ headers: Dict[str, str] = {
1060
+ USER_AGENT_HEADER_FLAG: self.user_agent,
1061
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
1062
+ }
1063
+ if base_uri is None:
1064
+ base_uri = f"wacom:{name}#"
1065
+ if not base_uri.endswith("#"):
1066
+ base_uri += "#"
1067
+
1068
+ payload: Dict[str, Any] = {
1069
+ BASE_URI_TAG: base_uri,
1070
+ NAME_TAG: name,
1071
+ LABELS_TAG: [],
1072
+ COMMENTS_TAG: [],
1073
+ ICON_TAG: icon,
1074
+ }
1075
+ if context is not None:
1076
+ payload[CONTEXT_TAG] = context
1077
+ for label in labels if labels is not None else []:
1078
+ payload[LABELS_TAG].append({TEXT_TAG: label.content, LANGUAGE_CODE: label.language_code})
1079
+ for comment in comments if comments is not None else []:
1080
+ payload[COMMENTS_TAG].append({TEXT_TAG: comment.content, LANGUAGE_CODE: comment.language_code})
1081
+ url: str = f"{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}"
1082
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
1083
+ with requests.Session() as session:
1084
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
1085
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
1086
+ response: Response = session.post(
1087
+ url, headers=headers, json=payload, verify=self.verify_calls, timeout=timeout
1088
+ )
1089
+ if response.ok:
1090
+ return response.json()
1091
+ raise handle_error("Creation of context failed.", response, headers=headers)
1092
+
1093
+ def remove_context(
1094
+ self,
1095
+ name: str,
1096
+ force: bool = False,
1097
+ auth_key: Optional[str] = None,
1098
+ timeout: int = DEFAULT_TIMEOUT,
1099
+ max_retries: int = DEFAULT_MAX_RETRIES,
1100
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
1101
+ ):
1102
+ """Remove context.
1103
+
1104
+ Parameters
1105
+ ----------
1106
+ name: str
1107
+ Name of the context
1108
+ force: bool (default:= False)
1109
+ Force removal of context
1110
+ auth_key: Optional[str] [default:= None]
1111
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
1112
+ timeout: int
1113
+ Timeout for the request (default: 60 seconds)
1114
+ max_retries: int
1115
+ Maximum number of retries
1116
+ backoff_factor: float
1117
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
1118
+ second try without a delay)
1119
+
1120
+ Returns
1121
+ -------
1122
+ result: Dict[str, str]
1123
+ Result from the service
1124
+ """
1125
+ if auth_key is None:
1126
+ auth_key, _ = self.handle_token()
1127
+ headers: Dict[str, str] = {
1128
+ USER_AGENT_HEADER_FLAG: self.user_agent,
1129
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
1130
+ }
1131
+ url: str = f'{self.service_base_url}{OntologyService.CONTEXT_ENDPOINT}/{name}{"/force" if force else ""}'
1132
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
1133
+ with requests.Session() as session:
1134
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
1135
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
1136
+ response: Response = session.delete(url, headers=headers, verify=self.verify_calls, timeout=timeout)
1137
+ if not response.ok:
1138
+ raise handle_error("Removing the context failed.", response, headers=headers)
1139
+
1140
+ def commit(
1141
+ self,
1142
+ context: str,
1143
+ auth_key: Optional[str] = None,
1144
+ timeout: int = DEFAULT_TIMEOUT,
1145
+ max_retries: int = DEFAULT_MAX_RETRIES,
1146
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
1147
+ ):
1148
+ """
1149
+ Commit the ontology.
1150
+
1151
+ Parameters
1152
+ ----------
1153
+ context: str
1154
+ Name of the context.
1155
+ auth_key: Optional[str] [default:= None]
1156
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
1157
+ timeout: int
1158
+ Timeout for the request (default: 60 seconds)
1159
+ max_retries: int
1160
+ Maximum number of retries
1161
+ backoff_factor: float
1162
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
1163
+ second try without a delay)
1164
+ """
1165
+ if auth_key is None:
1166
+ auth_key, _ = self.handle_token()
1167
+ headers: Dict[str, str] = {
1168
+ USER_AGENT_HEADER_FLAG: self.user_agent,
1169
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
1170
+ }
1171
+ context_url: str = urllib.parse.quote_plus(context)
1172
+ url: str = f"{self.service_base_url}context/{context_url}/commit"
1173
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
1174
+ with requests.Session() as session:
1175
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
1176
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
1177
+ response: Response = session.put(url, headers=headers, verify=self.verify_calls, timeout=timeout)
1178
+ if not response.ok:
1179
+ raise handle_error("Commit of ontology failed.", response, headers=headers)
1180
+
1181
+ def rdf_export(
1182
+ self,
1183
+ context: str,
1184
+ version: int = 0,
1185
+ auth_key: Optional[str] = None,
1186
+ timeout: int = DEFAULT_TIMEOUT,
1187
+ max_retries: int = DEFAULT_MAX_RETRIES,
1188
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
1189
+ ) -> str:
1190
+ """
1191
+ Export RDF.
1192
+
1193
+ Parameters
1194
+ ----------
1195
+ context: str
1196
+ Name of the context.
1197
+ version: int (default:= 0)
1198
+ Version of the context if 0 is set the latest version will be exported.
1199
+ auth_key: Optional[str] [default:= None]
1200
+ If the auth key is set the logged-in user (if any) will be ignored and the auth key will be used.
1201
+ timeout: int
1202
+ Timeout for the request (default: 60 seconds)
1203
+ max_retries: int
1204
+ Maximum number of retries
1205
+ backoff_factor: float
1206
+ A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a
1207
+ second try without a delay)
1208
+ Returns
1209
+ -------
1210
+ rdf: str
1211
+ Ontology as RDFS / OWL ontology
1212
+ """
1213
+ if auth_key is None:
1214
+ auth_key, _ = self.handle_token()
1215
+ headers: Dict[str, str] = {
1216
+ USER_AGENT_HEADER_FLAG: self.user_agent,
1217
+ AUTHORIZATION_HEADER_FLAG: f"Bearer {auth_key}",
1218
+ }
1219
+ if version > 0:
1220
+ params: Dict[str, int] = {"version": version}
1221
+ else:
1222
+ params: Dict[str, int] = {}
1223
+ context_url: str = urllib.parse.quote_plus(context)
1224
+ url: str = f"{self.service_base_url}context/{context_url}/versions/rdf"
1225
+ mount_point: str = "https://" if self.service_url.startswith("https") else "http://"
1226
+ with requests.Session() as session:
1227
+ retries: Retry = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=STATUS_FORCE_LIST)
1228
+ session.mount(mount_point, HTTPAdapter(max_retries=retries))
1229
+ response: Response = session.get(
1230
+ url, headers=headers, verify=self.verify_calls, params=params, timeout=timeout
1231
+ )
1232
+ if response.ok:
1233
+ return response.text
1234
+ raise handle_error("RDF export failed", response, headers=headers)