-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcore.py
More file actions
2255 lines (2029 loc) · 95.2 KB
/
Copy pathcore.py
File metadata and controls
2255 lines (2029 loc) · 95.2 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
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import importlib
import json
import logging
import os
import pathlib
import re
import warnings
from copy import deepcopy
from enum import Enum
from typing import Any, Dict, List, Optional, Type, Union, overload
from uuid import UUID, uuid4
from warnings import warn
import black
import datamodel_code_generator
import isort
import rdflib
from jsonpath_ng.ext import parse
from mwclient.client import Site
from oold.backend.interface import (
Backend,
ResolveParam,
ResolveResult,
SetBackendParam,
SetResolverParam,
StoreParam,
StoreResult,
set_backend,
set_resolver,
)
from oold.generator import Generator
from oold.utils.codegen import OOLDJsonSchemaParser
from opensemantic.v1 import OswBaseModel
from pydantic import PydanticDeprecatedSince20
from pydantic.v1 import BaseModel, Field, PrivateAttr, create_model, validator
from pyld import jsonld
import osw.model.entity as model
from osw.defaults import params as default_params
from osw.utils.code_postprocessing import (
remove_constraints_from_forward_refs,
resolve_osw_id_type_hints,
)
from osw.utils.oold import (
AggregateGeneratedSchemasParam,
AggregateGeneratedSchemasParamMode,
aggregate_generated_schemas,
escape_json_strings,
merge_generated_definitions,
)
from osw.utils.templates import (
compile_handlebars_template,
eval_compiled_handlebars_template,
)
from osw.utils.util import parallelize
from osw.utils.wiki import (
get_full_title,
get_namespace,
get_title,
get_uuid,
is_empty,
namespace_from_full_title,
remove_empty,
title_from_full_title,
)
from osw.wiki_tools import SearchParam
from osw.wtsite import WtPage, WtSite
_logger = logging.getLogger(__name__)
def get_model_dir_path() -> str:
"""The directory the fetched json schemas are written to"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "model")
def write_schema_stub(model_dir_path: str, schema_name: str) -> str:
"""Writes an empty schema, so a $ref pointing at it still resolves
A $ref is rewritten to a local file name before the page it names is
fetched. When that page turns out not to exist, nothing writes the file,
and datamodel-code-generator later fails with FileNotFoundError far away
from the cause. An empty schema keeps generation going, and the reason is
reported in the FetchSchemaResult instead.
"""
schema_path = os.path.join(model_dir_path, schema_name + ".json")
os.makedirs(os.path.dirname(schema_path), exist_ok=True)
with open(schema_path, "w", encoding="utf-8") as f:
f.write("{}")
return schema_path
def collect_messages(
target: Optional[List[str]], source: Optional[List[str]]
) -> Optional[List[str]]:
"""Adds the messages in source to target, skipping duplicates
_FetchSchemaParam is copied shallowly for a recursive fetch, so target and
source can be the very same list. That case is already merged and is left
alone rather than iterated while being appended to.
"""
if not source or target is source:
return target
if target is None:
target = []
for message in source:
if message not in target:
target.append(message)
return target
# Reusable type definitions
class OverwriteOptions(Enum):
"""Options for overwriting properties"""
true = True
"""Always overwrite a property"""
false = False
"""Never overwrite a property"""
only_empty = "only empty"
"""Only overwrite if the property is empty"""
# todo: implement "merge",
# todo: implement "append",
# Don't replace the properties but for properties of type array or dict, append
# the values of the local entity to the remote entity, make sure # to not
# append duplicates
# todo: implement "only older",
# todo: implement read out from the version history of the page
class AddOverwriteClassOptions(Enum):
replace_remote = "replace remote"
"""Replace the entity with the new one, removes all properties that are not
present in the local entity"""
keep_existing = "keep existing"
"""Keep the entity, does not add or remove any properties, if the page exists, the
entity is not stored"""
none = None
"""Not an option to choose from, will be replaced by the default remote properties
"""
OVERWRITE_CLASS_OPTIONS = Union[OverwriteOptions, AddOverwriteClassOptions]
class OSW(BaseModel):
"""Bundles core functionalities of OpenSemanticWorld (OSW)"""
uuid: str = "2ea5b605-c91f-4e5a-9559-3dff79fdd4a5"
_protected_keywords = (
"_osl_template",
"_osl_footer",
) # private properties included in model export
class Config:
arbitrary_types_allowed = True # necessary to allow e.g. np.array as type
site: WtSite
def __init__(self, **data: Any):
super().__init__(**data)
# implement resolver backend with osw.load_entity
class OswDefaultBackend(Backend):
# oold.backend.interface is pydantic v2, so we cannot use
# our v1 OSW model as attribute directly
osw_obj: Any
# stub satisfying the oold Backend interface; resolve() does the work
def resolve_iris(self, iris: List[str]) -> dict[str, dict]: # ty: ignore[empty-body]
pass
def resolve(self, request: ResolveParam):
# print("RESOLVE", request)
osw_obj: OSW = self.osw_obj
entities = osw_obj.load_entity(
OSW.LoadEntityParam(titles=request.iris)
).entities
# create a dict with request.iris as keys and the loaded entities as values
# by iterating over both lists
nodes = {}
for iri, entity in zip(request.iris, entities):
nodes[iri] = entity
return ResolveResult(nodes=nodes)
def store_jsonld_dicts(self, jsonld_dicts):
pass
def store(self, request: StoreParam):
osw_obj: OSW = self.osw_obj
osw_obj.store_entity(
OSW.StoreEntityParam(
entities=list(request.nodes.values()), overwrite=True
),
)
return StoreResult(success=True)
def query():
pass
r = OswDefaultBackend(osw_obj=self)
set_resolver(SetResolverParam(iri="Item", resolver=r))
set_resolver(SetResolverParam(iri="Category", resolver=r))
set_resolver(SetResolverParam(iri="Property", resolver=r))
set_resolver(SetResolverParam(iri="File", resolver=r))
set_backend(SetBackendParam(iri="Item", backend=r))
set_backend(SetBackendParam(iri="Category", backend=r))
set_backend(SetBackendParam(iri="Property", backend=r))
set_backend(SetBackendParam(iri="File", backend=r))
@property
def mw_site(self) -> Site:
"""Returns the mwclient Site object of the OSW instance."""
return self.site.mw_site
def close_connection(self):
"""Close the connection to the OSL instance."""
self.mw_site.connection.close()
@staticmethod
def get_osw_id(uuid: Union[str, UUID]) -> str:
"""Generates a OSW-ID based on the given uuid by prefixing "OSW" and removing
all '-' from the uuid-string
Parameters
----------
uuid
uuid object, e.g. UUID("2ea5b605-c91f-4e5a-9559-3dff79fdd4a5")
Returns
-------
OSW-ID string, e.g. OSW2ea5b605c91f4e5a95593dff79fdd4a5
"""
return "OSW" + str(uuid).replace("-", "")
@staticmethod
def get_uuid(osw_id: str) -> UUID:
"""Returns the uuid for a given OSW-ID
Parameters
----------
osw_id
OSW-ID string, e.g. OSW2ea5b605c91f4e5a95593dff79fdd4a5
Returns
-------
uuid object, e.g. UUID("2ea5b605-c91f-4e5a-9559-3dff79fdd4a5")
"""
return UUID(osw_id.replace("OSW", ""))
class SortEntitiesResult(OswBaseModel):
by_name: Dict[str, List[OswBaseModel]]
by_type: Dict[str, List[OswBaseModel]]
@staticmethod
def sort_list_of_entities_by_class(
entities: List[OswBaseModel],
exclude_typeless: bool = True,
raise_error: bool = False,
) -> SortEntitiesResult:
"""Sorts a list of entities by class name and type.
Parameters
----------
entities:
List of entities to be sorted
exclude_typeless:
Exclude entities, which are instances of a class that does not
define a field 'type'
raise_error:
Raise an error if an entity can not be processed because it is an
instance of class that does not define a field 'type'
"""
by_name = {}
by_type = {}
for entity in entities:
# Get class name
name = entity.__class__.__name__
# See if the class has a type field
if "type" not in entity.__class__.__fields__:
if raise_error:
raise AttributeError(
f"Instance '{entity}' of class '{name}' can not be processed "
f"as the class does not define a field 'type'."
)
if exclude_typeless:
warn(
f"Skipping instance '{entity}' of class '{name}' as the class "
f"does not define a field 'type'."
)
# Excludes the respective entity from the list which will be
# processed further:
continue
model_type = None
else:
# Get class type if available
model_type = entity.__class__.__fields__["type"].get_default()[0]
# Add entity to by_name
if name not in by_name:
by_name[name] = []
by_name[name].append(entity)
# Add entity to by_type
if model_type not in by_type:
by_type[model_type] = []
by_type[model_type].append(entity)
return OSW.SortEntitiesResult(by_name=by_name, by_type=by_type)
class SchemaRegistration(BaseModel):
"""dataclass param of register_schema()"""
class Config:
arbitrary_types_allowed = True # allow any class as type
model_cls: Type[OswBaseModel]
"""The model class"""
schema_uuid: str # Optional[str] = model_cls.__uuid__
"""The schema uuid"""
schema_name: str # Optional[str] = model_cls.__name__
"""The schema name"""
schema_bases: List[str] = Field(default=["Category:Item"])
"""A list of base schemas (referenced by allOf)"""
def register_schema(self, schema_registration: SchemaRegistration):
"""Registers a new or updated schema in OSW by creating the corresponding
category page.
Parameters
----------
schema_registration
see SchemaRegistration
"""
entity = schema_registration.model_cls
jsondata = {}
jsondata["uuid"] = schema_registration.schema_uuid
jsondata["label"] = {"text": schema_registration.schema_name, "lang": "en"}
jsondata["subclass_of"] = schema_registration.schema_bases
if issubclass(entity, BaseModel):
entity_title = "Category:" + OSW.get_osw_id(schema_registration.schema_uuid)
page = WtPage(wtSite=self.site, title=entity_title)
if page.exists:
page = self.site.get_page(
WtSite.GetPageParam(titles=[entity_title])
).pages[0]
page.set_slot_content("jsondata", jsondata)
schema = json.loads(
entity.schema_json(indent=4).replace("$ref", "dollarref")
)
jsonpath_expr = parse("$..allOf")
# Replace local definitions (#/definitions/...) with embedded definitions
# to prevent resolve errors in json-editor
for match in jsonpath_expr.find(schema):
result_array = []
for subschema in match.value:
# pprint(subschema)
value = subschema["dollarref"]
if value.startswith("#"):
definition_jsonpath_expr = parse(
value.replace("#", "$").replace("/", ".")
)
for def_match in definition_jsonpath_expr.find(schema):
# pprint(def_match.value)
result_array.append(def_match.value)
else:
result_array.append(subschema)
match.full_path.update_or_create(schema, result_array)
if "definitions" in schema:
del schema["definitions"]
if "allOf" not in schema:
schema["allOf"] = []
for base in schema_registration.schema_bases:
schema["allOf"].append({
"$ref": f"/wiki/{base}?action=raw&slot=jsonschema"
})
page.set_slot_content("jsonschema", schema)
else:
print("Error: Unsupported entity type")
return
page.edit()
print("Entity stored at " + page.get_url())
class SchemaUnregistration(BaseModel):
"""dataclass param of register_schema()"""
class Config:
arbitrary_types_allowed = True # allow any class as type
model_cls: Optional[Type[OswBaseModel]]
"""The model class"""
model_uuid: Optional[str]
"""The model uuid"""
comment: Optional[str]
"""The comment for the deletion, to be left behind"""
def unregister_schema(self, schema_unregistration: SchemaUnregistration):
"""deletes the corresponding category page
Parameters
----------
schema_unregistration
see SchemaUnregistration
"""
uuid = ""
if schema_unregistration.model_uuid:
uuid = schema_unregistration.model_uuid
elif (
not uuid
and schema_unregistration.model_cls
and issubclass(schema_unregistration.model_cls, BaseModel)
):
uuid = schema_unregistration.model_cls.__uuid__
else:
print("Error: Neither model nor model id provided")
entity_title = "Category:" + OSW.get_osw_id(uuid)
page = self.site.get_page(WtSite.GetPageParam(titles=[entity_title])).pages[0]
page.delete(schema_unregistration.comment)
class FetchSchemaMode(Enum):
"""Modes of the FetchSchemaParam class
Attributes
----------
append:
append to the current model
replace:
replace the current model
"""
append = "append" # append to the current model
replace = "replace" # replace the current model
class FetchSchemaParam(BaseModel):
"""Param for fetch_schema()
Attributes
----------
schema_title:
one or multiple titles (wiki page name) of schemas (default: Category:Item)
mode:
append or replace (default) current schema, see FetchSchemaMode
"""
schema_title: Optional[Union[List[str], str]] = "Category:Item"
mode: Optional[str] = (
"replace"
# type 'FetchSchemaMode' requires: 'from __future__ import annotations'
)
generate_annotations: Optional[bool] = True
"""generate custom schema keywords in Fields and Classes.
Required to update the schema in OSW without information loss"""
generator_options: Optional[Dict[str, Any]] = None
"""custom options for the datamodel-code-generator"""
offline_pages: Optional[Dict[str, WtPage]] = None
"""pages to be used offline instead of fetching them from the OSW instance"""
result_model_path: Optional[Union[str, pathlib.Path]] = None
"""path to the generated model file, if None,
the default path ./model/entity.py is used"""
class Config:
arbitrary_types_allowed = True
class FetchSchemaResult(BaseModel):
fetched_schema_titles: Optional[List[str]] = None
"""List of titles of the schemas that were fetched.
This includes the requested schemas and their dependencies."""
error_messages: Optional[List[str]] = None
"""List of critical errors that did interrupt the fetch process"""
warning_messages: Optional[List[str]] = None
"""List of warnings that did not interrupt the fetch process"""
def fetch_schema(
self, fetchSchemaParam: FetchSchemaParam = None
) -> FetchSchemaResult:
"""Loads the given schemas from the OSW instance and auto-generates python
datasclasses within osw.model.entity from it
Parameters
----------
fetchSchemaParam
See FetchSchemaParam, by default None
"""
if not isinstance(fetchSchemaParam.schema_title, list):
fetchSchemaParam.schema_title = [fetchSchemaParam.schema_title]
first = True
last = False
results = []
for schema_title in fetchSchemaParam.schema_title:
last = schema_title == fetchSchemaParam.schema_title[-1]
mode = fetchSchemaParam.mode
if not first: # 'replace' makes only sense for the first schema
mode = "append"
res = self._fetch_schema(
OSW._FetchSchemaParam(
schema_title=schema_title,
mode=mode,
final=last,
generate_annotations=fetchSchemaParam.generate_annotations,
generator_options=fetchSchemaParam.generator_options,
offline_pages=fetchSchemaParam.offline_pages,
result_model_path=fetchSchemaParam.result_model_path,
)
)
results.append(res)
first = False
# merge unique results and return
merged_result = OSW.FetchSchemaResult(
fetched_schema_titles=[], error_messages=[], warning_messages=[]
)
for result in results:
if result.fetched_schema_titles:
merged_result.fetched_schema_titles.extend(result.fetched_schema_titles)
if result.error_messages:
merged_result.error_messages.extend(result.error_messages)
if result.warning_messages:
merged_result.warning_messages.extend(result.warning_messages)
return OSW.FetchSchemaResult(
fetched_schema_titles=(
list(set(merged_result.fetched_schema_titles))
if len(merged_result.fetched_schema_titles) > 0
else None
),
error_messages=(
list(set(merged_result.error_messages))
if len(merged_result.error_messages) > 0
else None
),
warning_messages=(
list(set(merged_result.warning_messages))
if len(merged_result.warning_messages) > 0
else None
),
)
class _FetchSchemaParam(BaseModel):
"""Internal param for _fetch_schema()
Attributes
----------
schema_title:
the title (wiki page name) of the schema (default: Category:Item)
root:
marks the root iteration for a recursive fetch (internal param,
default: True)
mode:
append or replace (default) current schema, see FetchSchemaMode
"""
schema_title: Optional[str] = "Category:Item"
root: Optional[bool] = True
"""marks the root iteration for a recursive fetch (internal param, default: True)"""
final: Optional[bool] = True
"""if multiple schemas are fetched this marks the final run to cleanup the code"""
mode: Optional[str] = (
"replace"
# type 'FetchSchemaMode' requires: 'from __future__ import annotations'
)
generate_annotations: Optional[bool] = False
"""generate custom schema keywords in Fields and Classes.
Required to update the schema in OSW without information loss"""
generator_options: Optional[Dict[str, Any]] = None
"""custom options for the datamodel-code-generator"""
offline_pages: Optional[Dict[str, WtPage]] = None
"""pages to be used offline instead of fetching them from the OSW instance"""
result_model_path: Optional[Union[str, pathlib.Path]] = None
"""path to the generated model file, if None,
the default path ./model/entity.py is used"""
fetched_schema_titles: Optional[List[str]] = []
"""keep track of fetched schema titles to prevent recursion"""
warning_messages: Optional[List[str]] = None
class Config:
arbitrary_types_allowed = True
def _fetch_schema(
self, fetchSchemaParam: _FetchSchemaParam = None
) -> FetchSchemaResult:
"""Loads the given schema from the OSW instance and autogenerates python
datasclasses within osw.model.entity from it
Parameters
----------
fetchSchemaParam
See FetchSchemaParam, by default None
"""
site_cache_state = self.site.get_cache_enabled()
self.site.enable_cache()
if fetchSchemaParam is None:
fetchSchemaParam = OSW._FetchSchemaParam()
schema_title = fetchSchemaParam.schema_title
fetchSchemaParam.fetched_schema_titles.append(schema_title)
root = fetchSchemaParam.root
schema_name = schema_title.split(":")[-1]
if (
fetchSchemaParam.offline_pages is not None
and schema_title in fetchSchemaParam.offline_pages
):
print(f"Fetch {schema_title} from offline pages")
page = fetchSchemaParam.offline_pages[schema_title]
else:
print(f"Fetch {schema_title} from online pages")
page = self.site.get_page(WtSite.GetPageParam(titles=[schema_title])).pages[
0
]
if not page.exists:
print(f"Error: Page {schema_title} does not exist")
# the $ref that led here was already rewritten to this file name
write_schema_stub(get_model_dir_path(), schema_name)
return OSW.FetchSchemaResult(
fetched_schema_titles=fetchSchemaParam.fetched_schema_titles,
warning_messages=fetchSchemaParam.warning_messages,
error_messages=[f"Page {schema_title} does not exist"],
)
# not only in the JsonSchema namespace the schema is located in the main slot
# in all other namespaces, the json_schema slot is used
if schema_title.startswith("JsonSchema:"):
schema_str = ""
if page.get_slot_content("main"):
schema_str = json.dumps(page.get_slot_content("main"))
else:
schema_str = ""
if page.get_slot_content("jsonschema"):
schema = merge_generated_definitions(
deepcopy(page.get_slot_content("jsonschema"))
)
schema_str = json.dumps(schema)
if (schema_str is None) or (schema_str == ""):
print(f"Warning: Schema slot of {schema_title} is empty")
schema_str = "{}" # empty schema to make reference work
if fetchSchemaParam.warning_messages is None:
fetchSchemaParam.warning_messages = []
fetchSchemaParam.warning_messages.append(
f"Schema slot of {schema_title} is empty"
)
generator = Generator()
schemas_for_preprocessing = [json.loads(schema_str)]
generator.preprocess(
Generator.GenerateParams(json_schemas=schemas_for_preprocessing)
)
schema_str = json.dumps(schemas_for_preprocessing[0])
schema = json.loads(schema_str.replace("$ref", "dollarref"))
jsonpath_expr = parse("$..dollarref")
ref_error_messages = None
for match in jsonpath_expr.find(schema):
# value = "https://" + self.mw_site.host + match.value
if match.value.startswith("#"):
continue # skip self references
ref_schema_title = match.value.replace("/wiki/", "").split("?")[0]
ref_schema_name = ref_schema_title.split(":")[-1] + ".json"
value = ""
for _i in range(0, schema_name.count("/")):
value += "../" # created relative path to top-level schema dir
value += ref_schema_name # create a reference to a local file
# keep document-relative jsonpointer if present
if "#/" in match.value:
value += "#/" + match.value.split("#/")[-1]
match.full_path.update_or_create(schema, value)
# print(f"replace {match.value} with {value}")
if (
ref_schema_title != schema_title
and ref_schema_title not in fetchSchemaParam.fetched_schema_titles
): # prevent recursion in case of self references
_param = fetchSchemaParam.copy()
_param.root = False
_param.schema_title = ref_schema_title
ref_result = self._fetch_schema(_param) # resolve refs recursive
# the recursive call is the only place that knows why a
# referenced schema could not be fetched, so its messages have
# to be carried up rather than dropped
ref_error_messages = collect_messages(
ref_error_messages, ref_result.error_messages
)
fetchSchemaParam.warning_messages = collect_messages(
fetchSchemaParam.warning_messages, ref_result.warning_messages
)
model_dir_path = get_model_dir_path() # src/model
schema_path = os.path.join(model_dir_path, schema_name + ".json")
os.makedirs(os.path.dirname(schema_path), exist_ok=True)
with open(schema_path, "w", encoding="utf-8") as f:
schema_str = json.dumps(schema, ensure_ascii=False, indent=4).replace(
"dollarref", "$ref"
)
# print(schema_str)
f.write(schema_str)
# result_model_path = schema_path.replace(".json", ".py")
result_model_path = os.path.join(model_dir_path, "entity.py")
if fetchSchemaParam.result_model_path:
result_model_path = fetchSchemaParam.result_model_path
if not isinstance(result_model_path, str):
result_model_path = str(result_model_path)
temp_model_path = os.path.join(model_dir_path, "temp.py")
data_model_type = "pydantic.BaseModel"
if fetchSchemaParam.generator_options is not None:
data_model_type = fetchSchemaParam.generator_options.get(
"output_model_type", "pydantic.BaseModel"
)
if root:
# suppress deprecation warnings from pydantic
# see https://github.com/koxudaxi/datamodel-code-generator/issues/2213
warnings.filterwarnings("ignore", category=PydanticDeprecatedSince20)
if fetchSchemaParam.generate_annotations:
# monkey patch class
datamodel_code_generator.parser.jsonschema.JsonSchemaParser = (
OOLDJsonSchemaParser
)
datamodel_code_generator.generate(
input_=pathlib.Path(schema_path),
input_file_type="jsonschema",
output=pathlib.Path(temp_model_path),
base_class=(
"opensemantic.v1.OswBaseModel"
if data_model_type == "pydantic.BaseModel"
else "opensemantic.OswBaseModel"
),
# use_default=True,
apply_default_values_for_required_fields=True,
use_unique_items_as_set=True,
enum_field_as_literal=datamodel_code_generator.LiteralType.Off,
# will create MyEnum(str, Enum) instead of MyEnum(Enum)
use_subclass_enum=True,
set_default_enum_member=True,
use_title_as_name=True,
use_schema_description=True,
use_field_description=True,
# https://github.com/koxudaxi/datamodel-code-generator/issues/2447
# use_standard_collections=data_model_type != "pydantic.BaseModel",
encoding="utf-8",
use_double_quotes=True,
collapse_root_models=True,
reuse_model=True,
field_include_all_keys=True,
allof_class_hierarchy=datamodel_code_generator.AllOfClassHierarchy.Always,
additional_imports=(
["uuid.uuid4", "pydantic.ConfigDict"]
if data_model_type != "pydantic.BaseModel"
else ["uuid.uuid4"]
),
**(fetchSchemaParam.generator_options or {}),
)
# note: we could use OOLDJsonSchemaParser directly (see below),
# but datamodel_code_generator.generate
# does some pre- and postprocessing we do not want to duplicate
# data_model_type = datamodel_code_generator.DataModelType.PydanticBaseModel
# #data_model_type = DataModelType.PydanticV2BaseModel
# target_python_version = datamodel_code_generator.PythonVersion.PY_38
# data_model_types = datamodel_code_generator.model.get_data_model_types(
# data_model_type, target_python_version
# )
# parser = OOLDJsonSchemaParserFixedRefs(
# source=pathlib.Path(schema_path),
# base_class="opensemantic.OswBaseModel",
# data_model_type=data_model_types.data_model,
# data_model_root_type=data_model_types.root_model,
# data_model_field_type=data_model_types.field_model,
# data_type_manager_type=data_model_types.data_type_manager,
# target_python_version=target_python_version,
# #use_default=True,
# apply_default_values_for_required_fields=True,
# use_unique_items_as_set=True,
# enum_field_as_literal=datamodel_code_generator.LiteralType.All,
# use_title_as_name=True,
# use_schema_description=True,
# use_field_description=True,
# encoding="utf-8",
# use_double_quotes=True,
# collapse_root_models=True,
# reuse_model=True,
# #field_include_all_keys=True
# )
# result = parser.parse()
# with open(temp_model_path, "w", encoding="utf-8") as f:
# f.write(result)
# see https://koxudaxi.github.io/datamodel-code-generator/
# --base-class OswBaseModel: use a custom base class
# --custom-template-dir src/model/template_data/
# --extra-template-data src/model/template_data/extra.json
# --use-default: Use default value even if a field is required
# --use-unique-items-as-set: define field type as `set` when the field
# attribute has`uniqueItems`
# --enum-field-as-literal all: prevent 'value is not a valid enumeration
# member' errors after schema reloading
# --use-schema-description: Use schema description to populate class
# docstring
# --use-field-description: Use schema description to populate field
# docstring
# --use-title-as-name: use titles as class names of models, e.g. for the
# footer templates
# --collapse-root-models: Models generated with a root-type field will be
# merged
# into the models using that root-type model, e.g. for Entity.statements
# --reuse-model: Re-use models on the field when a module has the model
# with the same content
content = ""
with open(temp_model_path, encoding="utf-8") as f:
content = f.read()
os.remove(temp_model_path)
content = re.sub(
r"(UUID = Field\(...)",
r"UUID = Field(default_factory=uuid4",
content,
) # enable default value for uuid
# we are now using pydantic.v1
# pydantic imports lead to uninitialized fields (FieldInfo still present)
# only if generator_options["data_model_type"] is not set or "pydantic.BaseModel"
if data_model_type == "pydantic.BaseModel":
content = re.sub(
r"(from pydantic import)", "from pydantic.v1 import", content
)
# remove field param unique_items
# --use-unique-items-as-set still keeps unique_items=True as Field param
# which was removed, see https://github.com/pydantic/pydantic-core/issues/296
# --output-model-type pydantic_v2.BaseModel fixes that but generated models
# are not v1 compatible mainly by using update_model()
content = re.sub(r"(,?\s*unique_items=True\s*)", "", content)
# Detect empty subclasses, replaces their occurrences with base classes,
# and removes the empty class definitions.
# Only processes subclasses that follow naming patterns:
# - BaseclassModel (e.g., DescriptionModel extends Description)
# - Baseclass<number> (e.g., Label1, Label2 extend Label)
# Pattern to match empty subclasses
# Matches: class SubClass(BaseClass):
# followed by optional whitespace/docstring and pass
pattern = "".join((
r"class\s+", # 'class' keyword
r"(\w+)", # capture subclass name
r"\s*\(\s*", # opening parenthesis
r"(\w+)", # capture base class name
r"\s*\)\s*:", # closing parenthesis and colon
r"\s*", # optional whitespace
r'(?:\n\s*(?:""".*?"""|\'\'\'.*?\'\'\')'
# optional docstring (triple quotes)
r"\s*)?", # end optional docstring
r"\n\s*pass\s*", # pass statement
r"(?:\n|$)", # newline or end of string
))
# Find all empty subclasses
matches = list(re.finditer(pattern, content, re.MULTILINE | re.DOTALL))
# Filter matches based on naming patterns
valid_matches = []
for match in matches:
subclass_name = match.group(1)
base_class_name = match.group(2)
# Check if subclass follows the naming patterns
if (
subclass_name == base_class_name + "Model" # BaseclassModel pattern
or re.match(
rf"^{re.escape(base_class_name)}\d+$", subclass_name
) # Baseclass<number> pattern
):
valid_matches.append(match)
content = content
replacements = []
# Process matches in reverse order to avoid offset issues when removing
for match in reversed(valid_matches):
subclass_name = match.group(1)
base_class_name = match.group(2)
replacements.append((subclass_name, base_class_name))
# Remove the entire class definition
start, end = match.span()
# Also remove any trailing newlines to avoid extra blank lines
while end < len(content) and content[end] == "\n":
end += 1
content = content[:start] + content[end:]
# Replace all occurrences of subclass names with base class names
for subclass_name, base_class_name in reversed(replacements):
pattern_replace = r"\b" + re.escape(subclass_name) + r"\b"
content = re.sub(pattern_replace, base_class_name, content)
if fetchSchemaParam.mode == "replace":
header = "from uuid import uuid4\n"
# if target path is default model/entity.py, we need to add imports
if fetchSchemaParam.result_model_path is None:
if data_model_type == "pydantic.BaseModel":
header += "from opensemantic.core.v1 import (\n"
else:
header += "from opensemantic.core import (\n"
header += (
" Label,\n"
" Entity,\n"
" Item,\n"
" DefinedTerm,\n"
" Keyword,\n"
" IntangibleItem,\n"
" Meta,\n"
" WikiPage,\n"
" LangCode,\n"
" Description,\n"
" ObjectStatement,\n"
" DataStatement,\n"
" QuantityStatement,\n"
" File,\n"
" LocalFile,\n"
" RemoteFile,\n"
" WikiFile,\n"
" PagePackage,\n"
") # noqa: F401, E402\n"
"\n"
)
# import Software, PrefectWorkflow from base
if data_model_type == "pydantic.BaseModel":
header += (
"from opensemantic.base.v1 import Software, PrefectFlow\n"
)
else:
header += (
"from opensemantic.base import Software, PrefectFlow\n"
)
content = re.sub(
pattern=r"(^class\s*\S*\s*\(\s*[\S\s]*?\s*\)\s*:.*\n)",
repl=header + r"\n\n\n\1",
string=content,
count=1,
flags=re.MULTILINE,
) # add header before first class declaration
if fetchSchemaParam.mode == "append":
org_content = ""
with open(result_model_path, encoding="utf-8") as f:
org_content = f.read()
pattern = re.compile(
r"^class\s*([\S]*)\s*\(\s*[\S\s]*?\s*\)\s*:.*\n", re.MULTILINE
) # match class definition [\s\S]*(?:[^\S\n]*\n){2,}
for cls in re.findall(pattern, org_content):
content = re.sub(
r"^(class\s*"
+ cls
+ r"\s*\(\s*[\S\s]*?\s*\)\s*:.*\n[\s\S]*?(?:[^\S\n]*\n){3,})",
"",
content,
count=1,
flags=re.MULTILINE,
) # replace duplicated classes
# combine original and new content
all_content = org_content + "\n\n\n" + content
content = all_content
if fetchSchemaParam.final:
# Resolve bare OSW ID type hints (e.g. OSW3886...)
# with actual class names (e.g. RiskAssessmentProcess)
# using UUID annotations from generated class definitions
content = resolve_osw_id_type_hints(content)
# Cleanup the combined content
# find all "<cls>.update_forward_refs()" lines,
# remove duplicates and put them to EOF
# do the same for "<cls>.model_rebuild()"
func_list = []
if data_model_type == "pydantic.BaseModel":
func_list.append("update_forward_refs")
if data_model_type == "pydantic_v2.BaseModel":
func_list.append("model_rebuild")
for func in func_list:
pattern_forward_ref = re.compile(r"(\w+)\." + func + r"\(\s*\)\s*")
forward_refs = pattern_forward_ref.findall(content)
if forward_refs:
# remove all occurrences
content = pattern_forward_ref.sub("", content)
# add unique occurrences to the end of the file