forked from JPEWdev/shacl2code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.py
More file actions
284 lines (231 loc) · 8.02 KB
/
Copy pathcontext.py
File metadata and controls
284 lines (231 loc) · 8.02 KB
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
# Copyright (c) 2024 Joshua Watt
#
# SPDX-License-Identifier: MIT
"""JSON-LD context processing and IRI compaction/expansion utilities"""
import re
from contextlib import contextmanager
def foreach_context(contexts):
for ctx in contexts:
for name, value in ctx.items():
yield name, value
class Context(object):
def __init__(self, contexts=None):
if contexts is None:
contexts = [] # pragma: no cover
self.contexts = [c for c in contexts if c]
self.__vocabs = []
self.__expanded_iris = {}
self.__expanded_ids = {}
self.__expanded_vocabs = {}
self.__compacted_iris = {}
self.__compacted_ids = {}
self.__compacted_vocabs = {}
@contextmanager
def vocab_push(self, vocab):
if not vocab:
yield self
return
self.__vocabs.append(vocab)
try:
yield self
finally:
self.__vocabs.pop()
def __vocab_key(self):
if not self.__vocabs:
return ""
return self.__vocabs[-1]
def __get_vocab_contexts(self):
contexts = []
for v in self.__vocabs:
for _, value in foreach_context(self.contexts):
if (
isinstance(value, dict)
and value.get("@type", "") == "@vocab"
and v == self.expand_iri(value.get("@id", ""))
):
if "@context" in value:
contexts.insert(0, value["@context"])
contexts.extend(self.contexts)
return contexts
def __choose_possible(
self,
term,
default,
contexts,
*,
vocab=False,
base=False,
exact=False,
prefix=False,
):
def remove_prefix(_id, value):
expanded_id = self.expand_iri(_id)
expanded_value = self.expand_iri(value)
possible = set()
if expanded_id.startswith(expanded_value):
tmp_id = _id[len(expanded_value) :]
possible.add(tmp_id)
return possible
def helper(term):
possible = set()
for name, value in foreach_context(contexts):
if name == "@vocab":
if vocab:
possible |= remove_prefix(term, value)
continue
if name == "@base":
if base:
possible |= remove_prefix(term, value)
continue
if isinstance(value, dict):
value = value.get("@id", "")
if term == self.expand_iri(value):
if exact and name not in possible:
possible.add(name)
possible |= helper(name)
continue
if not prefix:
continue
if term.startswith(value) and value.endswith("/"):
tmp_id = name + ":" + term[len(value) :].lstrip("/")
if tmp_id not in possible:
possible.add(tmp_id)
possible |= helper(tmp_id)
continue
if term.startswith(value + ":") and self.expand_iri(value).endswith(
"/"
):
tmp_id = name + term[len(value) :]
if tmp_id not in possible:
possible.add(tmp_id)
possible |= helper(tmp_id)
continue
return possible
possible = helper(term)
if not possible:
return default
# To select from the possible identifiers, choose the one that has the
# least context (fewest ":"), then the shortest, and finally
# alphabetically
possible = list(possible)
possible.sort(key=lambda p: (p.count(":"), len(p), p))
return possible[0]
def compact_iri(self, iri):
if iri not in self.__compacted_iris:
self.__compacted_iris[iri] = self.__choose_possible(
iri,
iri,
self.contexts,
exact=True,
prefix=True,
)
return self.__compacted_iris[iri]
def compact_id(self, _id):
if ":" not in _id:
return _id
if _id not in self.__compacted_ids:
self.__compacted_ids[_id] = self.__choose_possible(
_id,
_id,
self.contexts,
base=True,
prefix=True,
)
return self.__compacted_ids[_id]
def compact_vocab(self, term, vocab=None):
with self.vocab_push(vocab):
v = self.__vocab_key()
if v in self.__compacted_vocabs and term in self.__compacted_vocabs[v]:
return self.__compacted_vocabs[v][term]
compact = self.__choose_possible(
term,
None,
self.__get_vocab_contexts(),
vocab=True,
exact=True,
)
if compact is not None:
self.__compacted_vocabs.setdefault(v, {})[term] = self.compact_id(
compact
)
return compact
# If unable to compact with a vocabulary, compact as an ID
return self.compact_id(term)
def expand_iri(self, iri):
if iri not in self.__expanded_iris:
self.__expanded_iris[iri] = self.__expand(
iri,
self.contexts,
exact=True,
prefix=True,
)
return self.__expanded_iris[iri]
def expand_id(self, _id):
if _id not in self.__expanded_ids:
self.__expanded_ids[_id] = self.__expand(
_id,
self.contexts,
base=True,
prefix=True,
)
return self.__expanded_ids[_id]
def expand_vocab(self, term, vocab=None):
with self.vocab_push(vocab):
v = self.__vocab_key()
if v not in self.__expanded_vocabs or term not in self.__expanded_vocabs[v]:
value = self.__expand(
term,
self.__get_vocab_contexts(),
vocab=True,
exact=True,
)
self.__expanded_vocabs.setdefault(v, {})[term] = self.expand_id(value)
return self.__expanded_vocabs[v][term]
def __expand(
self,
term,
contexts,
*,
base=False,
exact=False,
prefix=False,
vocab=False,
):
def helper(term):
vocabs = []
bases = []
prefixes = []
exacts = []
is_short = not re.match(r"[^:]+:", term)
for name, value in foreach_context(contexts):
if name == "@vocab":
if vocab and is_short:
vocabs.append(helper(value))
continue
if name == "@base":
if base and is_short:
bases.append(value)
continue
if isinstance(value, dict):
value = value.get("@id", "")
if not value:
continue
if term == name:
if exact:
exacts.append(helper(value))
continue
if prefix:
prefixes.append(name)
for e in exacts:
return e
if ":" in term:
p, suffix = term.split(":", 1)
for name in prefixes:
if p == name:
p = self.expand_iri(p)
if p.endswith("/"):
return p + suffix
for value in vocabs + bases:
return value + term
return term
return helper(term)