generated from ioggstream/draft-polli-foo-media-type
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoasld.py
216 lines (197 loc) · 7.73 KB
/
oasld.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
import logging
from copy import deepcopy
from typing import Dict
import jsonschema
from typing_extensions import Self
CTX = "@context"
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class RefResolver:
def __init__(self, schema: Dict) -> None:
self.resolver = jsonschema.RefResolver("/", "")
self.schema = schema
def resolve(self, ref):
return self.resolver.resolve_fragment(self.schema, ref)
class Instance:
NO_CONTEXT = object()
def __init__(
self,
instance: Dict,
schema: Dict,
context: Dict = None,
parent: Self = None,
) -> None:
self.json_instance = instance
self.schema = schema
self.ld = deepcopy(instance) if parent is None else instance
self.parent = parent
self.safe_mode = self.parent.safe_mode if self.parent else True
if jtype := schema.get("x-jsonld-type"):
self.ld["@type"] = jtype
self.jcontext = schema.get("x-jsonld-context", {})
if context is Instance.NO_CONTEXT:
# Explicitly skipping context merge.
self.subentry_context_ref = Instance.NO_CONTEXT
return
self.subentry_context_ref = context
if self.jcontext:
if not self.is_subentry:
# Initialize.
self.subentry_context_ref = {CTX: deepcopy(self.jcontext)}
elif CTX in context or ():
if self.safe_mode:
raise ValueError(
"Cannot overwrite a @context defined in the super-schema"
)
else:
log.warning(
"Skipping nested context because it is already defined."
)
elif isinstance(context, dict):
# Merge in the passed context
self.subentry_context_ref[CTX] = deepcopy(self.jcontext)
elif isinstance(context, str):
if isinstance(self.jcontext, dict):
log.warning(
"The parent entry defines a string context, while the child has a dict context"
)
raise NotImplementedError(
f"Possibly conflicting contexts between the instance [{self.jcontext}] and its parent [{context}]"
)
else:
raise NotImplementedError("An sub-entry MUST have a context")
def is_decontext(self):
return self.subentry_context_ref == Instance.NO_CONTEXT
@property
def is_subentry(self):
return self.parent is not None
def process_instance(self, resolver: RefResolver):
properties = self.schema["properties"]
for k, v in self.ld.items():
process_keywords = {"@context", "@type"} - set(self.jcontext.get(k) or {})
property_schema = properties.get(k, {})
log.debug(f"Looking for {process_keywords} on {k} => {property_schema}")
if schema_ref := property_schema.get("$ref"):
property_schema = resolver.resolve(schema_ref.strip("#"))
if all(
(property_schema.get("type") in ("object", "array"), process_keywords)
):
if property_schema["type"] == "array":
subschema = resolver.resolve(
property_schema["items"]["$ref"].strip("#")
)
subcontext = (
Instance.NO_CONTEXT
if self.is_decontext()
else self.subentry_context_ref[CTX][k]
)
for idx, subinstance in enumerate(v):
log.debug(f"Integrating context id {id(subcontext)}")
i = Instance(
subinstance, subschema, context=subcontext, parent=self
)
i.process_instance(resolver)
# Only merge context for the first processing entry.
# This can be somewhat limitative because the traversing process
# depends on the subinstance properties and not on the ones
# of the schema.
subcontext = Instance.NO_CONTEXT
elif property_schema["type"] == "object":
subschema = property_schema
subcontext = self.subentry_context_ref[CTX].setdefault(k, {})
# if k == "spouse": import pdb; pdb.set_trace()
i = Instance(v, subschema, context=subcontext, parent=self)
i.process_instance(resolver)
else:
raise NotImplementedError
if not self.is_subentry:
self.ld[CTX] = self.subentry_context_ref[CTX]
def process_schema(schema_name, schemas):
schema = schemas[schema_name]
example = schema["example"]
instance = Instance(example, schema)
instance.safe_mode = False
resolver = RefResolver(schemas)
instance.process_instance(resolver=resolver)
return instance
sample_schema = schema_json = {
"Person": {
"description": "Simple cyclic example.",
"x-jsonld-type": "Person",
"x-jsonld-context": {
"email": "@id",
"@vocab": "https://w3.org/ns/person#",
"children": {"@container": "@set"},
},
"type": "object",
"properties": {
"email": {"type": "string"},
"birthplace": {"$ref": "#/BirthPlace"},
"children": {"type": "array", "items": {"$ref": "#/Person"}},
},
"example": {
"email": "mailto:a@example",
"givenName": "Alice",
"familyName": "Smith",
"birthplace": {
"city": "Roma",
"province": "RM",
"country": "ITA",
"interno": "Interno 8",
},
"children": [
{"email": "mailto:dough@example"},
{"email": "mailto:son@example"},
],
},
},
"BirthPlace": {
"type": "object",
"additionalProperties": False,
"required": ["city", "province", "country"],
"x-jsonld-type": "https://w3id.org/italia/onto/CLV/Feature",
"x-jsonld-context": {
"@vocab": "https://w3id.org/italia/onto/CLV/",
"city": "hasCity",
"country": {
"@id": "hasCountry",
"@type": "@id",
"@context": {
"@base": "http://publications.europa.eu/resource/authority/country/"
},
},
"province": {
"@id": "hasProvince",
"@type": "@id",
"@context": {
"@base": "https://w3id.org/italia/data/identifiers/provinces-identifiers/vehicle-code/"
},
},
"interno": None,
},
"properties": {
"city": {
"type": "string",
"description": "The city where the person was born.",
"example": "Roma",
},
"province": {
"type": "string",
"description": "The province where the person was born.",
"example": "RM",
},
"country": {
"type": "string",
"description": "The iso alpha-3 code of the country where the person was born.",
"example": "ITA",
},
"interno": {"type": "string", "maxLength": 32},
},
"example": {
"city": "Roma",
"province": "RM",
"country": "ITA",
"interno": "Interno 8",
},
},
}