Skip to content

OSW

The central class for interacting with an OpenSemanticWorld instance.

Bases: BaseModel

Bundles core functionalities of OpenSemanticWorld (OSW)

Source code in src/osw/core.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
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. Kept for backwards compatibility,
        the implementation lives in osw.utils.wiki.get_uuid()

        Parameters
        ----------
        osw_id
            OSW-ID string, e.g. OSW2ea5b605c91f4e5a95593dff79fdd4a5, with or
            without file suffixes, e.g.
            OSW2ea5b605c91f4e5a95593dff79fdd4a5.drawio.png

        Returns
        -------
            uuid object, e.g. UUID("2ea5b605-c91f-4e5a-9559-3dff79fdd4a5")
        """
        return get_uuid_from_osw_id(osw_id)

    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:
                    _logger.warning(
                        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:
            _logger.error("Unsupported entity type")
            return

        page.edit()
        _logger.info("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:
            _logger.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
        ):
            _logger.info(f"Fetch {schema_title} from offline pages")
            page = fetchSchemaParam.offline_pages[schema_title]
        else:
            _logger.info(f"Fetch {schema_title} from online pages")
            page = self.site.get_page(WtSite.GetPageParam(titles=[schema_title])).pages[
                0
            ]
            if not page.exists:
                _logger.error(f"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 == ""):
            _logger.warning(f"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)

            # fix unserializable defaults from datamodel-code-generator (#125)
            content = remove_unserializable_default_sentinels(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
                    unique_forward_refs = list()
                    for cls in forward_refs:
                        if f"{cls}.{func}()\n" not in unique_forward_refs:
                            unique_forward_refs.append(f"{cls}.{func}()\n")
                    content += "\n" + "".join(sorted(unique_forward_refs))

                # Moves all single-line import statements to the beginning of the file.
                import_pattern = (
                    r"^(?:\s*#\s*[^\n]*\n)?"
                    r"(?:from\s+(\w+(?:\.\w+)*)\s+)?import\s+(?:\w+(?:\s+as\s+\w+)?(?:\s*,\s*\w+(?:\s+as\s+\w+)?)*)"
                    r"|^(?:\s*#\s*[^\n]*\n)?(?:from\s+(\w+(?:\.\w+)*)\s+import\s+\((?:[^\n]*\n?)*?\))\s*(?:#\s*[^\n]*)?$"
                )

                # iterate over the matches
                # collect full import statements to move them to the top
                # replace the original location with an empty string
                imports = []
                for match in re.finditer(import_pattern, content, re.MULTILINE):
                    import_stmt = match.group(0)
                    # # if "from __future__ import annotations" insert at index 0
                    # if import_stmt.strip() == "from __future__ import annotations":
                    #     imports.insert(0, import_stmt)
                    # else:
                    imports.append(import_stmt)
                    # replace all occurrences with empty string
                    # make sure to use match line start and end since import pattern
                    # may overlap partially, e.g.
                    # from datetime import date
                    # from datetime import date, datetime
                    _logger.info(f"Replace import statement: {import_stmt}")
                    content = re.sub(
                        r"^" + re.escape(import_stmt) + r"$",
                        "",
                        content,
                        flags=re.MULTILINE,
                    )
                    # remove duplicate imports (done by isort later)
                    imports = list(set(imports))
                # add imports to the beginning of the file
                content = "\n".join(sorted(imports)) + "\n\n" + content

                # remove contrains from ForwardRefs
                content = remove_constraints_from_forward_refs(content)

                # run formatting tool black on the combined content
                # consolidate imports as well
                try:
                    content = black.format_str(content, mode=black.Mode())
                    # run isort to sort imports using Vertical Hanging Indent style
                    content = isort.code(content, profile="black")
                except Exception as e:
                    # black/isort are optional, continue without formatting, but
                    # do not hide a signal that the generated content is broken
                    _logger.warning(f"Failed to format generated model content: {e}")

            # validate before writing: a corrupt write poisons every later
            # import of this file, so leaving the previous valid content in
            # place is strictly better than writing invalid syntax (#125)
            ensure_valid_python_source(content, result_model_path)

            # keep the current file so that a model that parses but does not
            # import can be rolled back below (#125)
            previous_content = read_file_if_exists(result_model_path)

            with open(result_model_path, "w", encoding="utf-8") as f:
                f.write(content)

            if fetchSchemaParam.final:
                # reload the updated module, restoring the previous content if
                # the generated model turns out not to be importable
                reload_module_or_restore(model, result_model_path, previous_content)
                if not site_cache_state:
                    self.site.disable_cache()  # restore original state

        return OSW.FetchSchemaResult(
            fetched_schema_titles=fetchSchemaParam.fetched_schema_titles,
            warning_messages=fetchSchemaParam.warning_messages,
            error_messages=ref_error_messages,
        )

    def install_dependencies(
        self,
        dependencies: Dict[str, str] = None,
        mode: str = "append",
        policy: str = "force",
    ):
        """Installs data models, listed in the dependencies, in the osw.model.entity
        module.

        Parameters
        ----------
        dependencies
            A dictionary with the keys being the names of the dependencies and the
            values being the full page name (IRI) of the dependencies.
        mode
            The mode to use when loading the dependencies. Default is 'append',
            which will keep existing data models and only load the missing ones. The
            mode 'replace' will replace all existing data models with the new ones.
        policy
            The policy to use when loading the dependencies. Default is 'force',
            which will always load the dependencies. If policy is 'if-missing',
            dependencies will only be loaded if they are not already installed.
            This may lead to outdated dependencies, if the dependencies have been
            updated on the server. If policy is 'if-outdated', dependencies will only
            be loaded if they were updated on the server. (not implemented yet)
        """
        if dependencies is None:
            if default_params.dependencies is None:
                raise ValueError(
                    "No 'dependencies' parameter was passed to "
                    "install_dependencies() and "
                    "osw.defaults.params.dependencies was not set!"
                )
            dependencies = default_params.dependencies
        schema_fpts = []
        for k, v in dependencies.items():
            if policy != "if-missing" or not hasattr(model, k):
                schema_fpts.append(v)
            if policy == "if-outdated":
                raise NotImplementedError(
                    "The policy 'if-outdated' is not implemented yet."
                )
        schema_fpts = list(set(schema_fpts))
        for schema_fpt in schema_fpts:
            if not schema_fpt.count(":") == 1:
                raise ValueError(
                    f"Full page title '{schema_fpt}' does not have the correct format. "
                    "It should be 'Namespace:Name'."
                )
        self.fetch_schema(OSW.FetchSchemaParam(schema_title=schema_fpts, mode=mode))

    @staticmethod
    def check_dependencies(dependencies: Dict[str, str]) -> List[str]:
        """Check if the dependencies are installed in the osw.model.entity module.

        Parameters
        ----------
        dependencies
            A dictionary with the keys being the names of the dependencies and the
            values being the full page name (IRI) of the dependencies.
        """
        return [dep for dep in dependencies if not hasattr(model, dep)]

    def ensure_dependencies(self, dependencies: Dict[str, str]):
        """Ensure that the dependencies are installed in the osw.model.entity module.

        Parameters
        ----------
        dependencies
            A dictionary with the keys being the names of the dependencies and the
            values being the full page name (IRI) of the dependencies.
        """
        if self.check_dependencies(dependencies):
            self.install_dependencies(dependencies)

    class LoadEntityParam(BaseModel):
        """Param for load_entity()"""

        titles: Union[str, List[str]]
        """The pages titles to load - one or multiple titles (wiki page name) of
        entities"""
        autofetch_schema: Optional[bool] = True
        """If true, load the corresponding schemas /
        categories ad-hoc if not already present"""
        model_to_use: Optional[Type[OswBaseModel]] = None
        """If provided this model will be used to create an entity (instance of the
        model), instead of instantiating the autofetched schema."""
        remove_empty: Optional[bool] = True
        """If true, remove key with an empty string, list, dict or set as value
        from the jsondata."""
        disable_cache: bool = False
        """If true, disable the cache for the loading process"""
        offline_pages: Optional[Dict[str, WtPage]] = None
        """pages to be used offline instead of fetching them from the OSW instance"""

        class Config:
            arbitrary_types_allowed = True  # allow any class as type

        def __init__(self, **data):
            super().__init__(**data)
            if not isinstance(self.titles, list):
                self.titles = [self.titles]

    class LoadEntityResult(BaseModel):
        """Result of load_entity()"""

        entities: Union[model.OswBaseModel, List[model.OswBaseModel]]
        """The dataclass instance(s)"""

    # fmt: off
    @overload
    def load_entity(self, entity_title: str) -> model.Entity:
        ...

    @overload
    def load_entity(self, entity_title: List[str]) -> List[model.Entity]:
        ...

    @overload
    def load_entity(self, entity_title: LoadEntityParam) -> LoadEntityResult:
        ...

    # fmt: on

    def load_entity(
        self, entity_title: Union[str, List[str], LoadEntityParam]
    ) -> Union[model.Entity, List[model.Entity], LoadEntityResult]:
        """Loads the entity with the given wiki page name from the OSW instance.
        Creates an instance of the class specified by the "type" attribute, default
        model.Entity. An instance of model.Entity can be cast to any subclass with
        .cast(model.<class>) .

        Parameters
        ----------
        entity_title
            the wiki page name

        Returns
        -------
            the dataclass instance if only a single title is given
            a list of dataclass instances if a list of titles is given
            a LoadEntityResult instance if a LoadEntityParam is given
        """
        if isinstance(entity_title, str):
            param = OSW.LoadEntityParam(titles=[entity_title])
        elif isinstance(entity_title, list):
            param = OSW.LoadEntityParam(titles=entity_title)
        else:
            param = entity_title

        if param.model_to_use:
            _logger.info(f"Using schema {param.model_to_use.__name__} to create entity")

        # store original cache state
        cache_state = self.site.get_cache_enabled()
        if param.disable_cache:
            self.site.disable_cache()
        if not cache_state and param.disable_cache:
            # enable cache to speed up loading
            self.site.enable_cache()

        # the restore runs in a finally block so that an exception from any of the
        # calls below cannot leave the cache enabled for the rest of the process
        try:
            entities = []
            pages = self.site.get_page(
                WtSite.GetPageParam(
                    titles=param.titles, offline_pages=param.offline_pages
                )
            ).pages
            for page in pages:
                entity = None
                schemas = []
                schemas_fetched = True
                jsondata = page.get_slot_content("jsondata")
                if param.remove_empty:
                    remove_empty(jsondata)
                if jsondata:
                    for category in jsondata["type"]:
                        schema = (
                            self.site
                            .get_page(
                                WtSite.GetPageParam(
                                    titles=[category], offline_pages=param.offline_pages
                                )
                            )
                            .pages[0]
                            .get_slot_content("jsonschema")
                        )
                        schemas.append(schema)
                        # generate model if not already exists
                        cls_name: str = schema["title"]
                        # If a schema_to_use is provided, we do not need to check if
                        #  the model exists
                        if not param.model_to_use:
                            if not hasattr(model, cls_name):
                                if param.autofetch_schema:
                                    self.fetch_schema(
                                        OSW.FetchSchemaParam(
                                            schema_title=category,
                                            mode="append",
                                            offline_pages=param.offline_pages,
                                        )
                                    )
                            if not hasattr(model, cls_name):
                                schemas_fetched = False
                                _logger.error(
                                    f"Model {cls_name} not found. Schema {category} "
                                    f"needs to be fetched first."
                                )
                if not schemas_fetched:
                    continue

                try:
                    if param.model_to_use:
                        entity: model.OswBaseModel = param.model_to_use(**jsondata)

                    elif len(schemas) == 0:
                        _logger.error("no schema defined")

                    elif len(schemas) == 1:
                        cls: Type[model.Entity] = getattr(model, schemas[0]["title"])
                        entity: model.Entity = cls(**jsondata)

                    else:
                        bases = []
                        for schema in schemas:
                            bases.append(getattr(model, schema["title"]))
                        cls = create_model("Test", __base__=tuple(bases))
                        entity: model.Entity = cls(**jsondata)
                except Exception as e:
                    _logger.error(f"Error creating entity from page {page.title}: {e}")
                    # legacy: `entity` is annotated as OswBaseModel and Entity above
                    entity = None  # ty: ignore[conflicting-declarations]

                if entity is not None:
                    # make sure we do not override existing metadata
                    if not hasattr(entity, "meta") or entity.meta is None:
                        entity.meta = model.Meta()
                    if (
                        not hasattr(entity.meta, "wiki_page")
                        or entity.meta.wiki_page is None
                    ):
                        entity.meta.wiki_page = model.WikiPage()
                    entity.meta.wiki_page.namespace = namespace_from_full_title(
                        page.title
                    )
                    entity.meta.wiki_page.title = title_from_full_title(page.title)

                    entities.append(entity)
        finally:
            # restore original cache state
            if cache_state:
                self.site.enable_cache()
            else:
                self.site.disable_cache()

        if isinstance(entity_title, str):  # single title
            if len(entities) >= 1:
                return entities[0]
            else:
                return None
        if isinstance(entity_title, list):  # list of titles
            return entities
        if isinstance(entity_title, OSW.LoadEntityParam):  # LoadEntityParam
            return OSW.LoadEntityResult(entities=entities)

    class OverwriteClassParam(OswBaseModel):
        model: Type[OswBaseModel]  # ModelMetaclass
        """The model class for which this is the overwrite params object."""
        overwrite: Optional[OVERWRITE_CLASS_OPTIONS] = False
        """Defines the overall overwriting behavior. Used for any property if the
        property specific setting is not set."""
        per_property: Optional[Dict[str, OverwriteOptions]] = None
        """A key (property name) - value (overwrite setting) pair."""
        _per_property: Dict[str, OVERWRITE_CLASS_OPTIONS] = PrivateAttr()
        """Private property, for internal use only. Use 'per_property' instead"""

        @validator("per_property")
        def validate_per_property(cls, per_property, values):
            if per_property is None:  # nothing to check, the fallback applies
                return per_property
            model_ = values.get("model")
            if model_ is None:
                # 'model' itself did not validate; without it the property names
                # below cannot be checked at all
                raise ValueError("'model' is required to validate 'per_property'")
            field_names = list(model_.__fields__.keys())
            keys = per_property.keys()
            if not all(key in field_names for key in keys):
                missing_keys = [key for key in keys if key not in field_names]
                raise ValueError(
                    f"Property not found in model: {', '.join(missing_keys)}"
                )

            return per_property

        @classmethod
        def _normalize_overwrite(cls, value):
            """Replace the two non-policy values by the default setting.

            Neither ``None`` nor the ``none`` sentinel is a policy:
            ``get_overwrite_setting()`` would hand them to the merge, where they
            match no branch and silently behave like 'false'.
            """
            if value is None or value is AddOverwriteClassOptions.none:
                return cls.__fields__["overwrite"].get_default()
            return value

        def __setattr__(self, key, value):
            """Called when setting an attribute"""
            if key == "overwrite":
                value = self._normalize_overwrite(value)
            # the effective settings are derived from these three, so any of them
            # changing has to rebuild them
            if key not in ("model", "overwrite", "per_property"):
                super().__setattr__(key, value)
                return
            previous = getattr(self, key)
            super().__setattr__(key, value)
            try:
                self._sync_per_property()
            except ValueError:
                # _sync_per_property() rejects before it touches _per_property,
                # so restoring the field is enough to undo the assignment. Leaving
                # a rejected value in place would let it take effect later, on the
                # next assignment that happens to be accepted.
                super().__setattr__(key, previous)
                raise

        def __init__(self, **data):
            """Called after validation. Sets the fallback for every property that
            has not been specified in per_property."""
            super().__init__(**data)
            # routed through __setattr__, which normalizes and rebuilds
            self.overwrite = self.overwrite
            # todo: from class definition get properties with hidden /
            #  read_only option  #  those can be safely overwritten - set the to True

        def _sync_per_property(self) -> None:
            """Rebuild the effective overwrite setting of every model field."""
            if self.per_property and isinstance(
                self.overwrite, AddOverwriteClassOptions
            ):
                # _apply_overwrite_policy() short-circuits on 'replace remote'
                # and 'keep existing' before it looks at a single property, so
                # this combination would discard 'per_property' silently. Check
                # it here rather than in a validator so that it also holds when
                # either field is reassigned after construction.
                raise ValueError(
                    f"'per_property' cannot be combined with overwrite="
                    f"'{self.overwrite.value}', which acts on the entity as a "
                    f"whole. Use an OverwriteOptions value for 'overwrite'."
                )
            per_property_ = self.per_property or {}
            self._per_property = {
                field_name: per_property_.get(field_name, self.overwrite)
                for field_name in self.model.__fields__.keys()
            }

        def get_overwrite_setting(self, property_name: str) -> OverwriteOptions:
            """Returns the fallback overwrite option for the given field name"""
            return self._per_property.get(property_name, self.overwrite)

    class _ApplyOverwriteParam(OswBaseModel):
        page: WtPage
        entity: OswBaseModel  # actually model.Entity but this causes the "type" error
        policy: Union[OSW.OverwriteClassParam, OVERWRITE_CLASS_OPTIONS]
        namespace: Optional[str]
        remove_empty: Optional[bool] = True
        inplace: Optional[bool] = False
        debug: Optional[bool] = False
        offline: Optional[bool] = False

        class Config:
            arbitrary_types_allowed = True

        @validator("entity")
        def validate_entity(cls, entity, values):
            """Make sure that the passed entity has the same uuid as the page"""
            page: WtPage = values.get("page")
            if not page.exists:  # Guard clause
                return entity
            jsondata = page.get_slot_content("jsondata")
            if jsondata is None:  # Guard clause
                title = title_from_full_title(page.title)
                try:
                    uuid_from_title = get_uuid_from_osw_id(title)
                except ValueError:
                    _logger.error(
                        f"UUID could not be determined from title: '{title}', "
                        f"nor fromjsondata: {jsondata}"
                    )
                    return entity
                if str(uuid_from_title) != str(entity.uuid):
                    raise ValueError(
                        f"UUID mismatch: Page UUID: {uuid_from_title}, "
                        f"Entity UUID: {entity.uuid}"
                    )
                return entity
            page_uuid = str(jsondata.get("uuid"))
            entity_uuid = str(getattr(entity, "uuid", None))
            if page_uuid != entity_uuid or page_uuid == str(None):
                # Comparing string type UUIDs
                raise ValueError(
                    f"UUID mismatch: Page UUID: {page_uuid}, Entity UUID: {entity_uuid}"
                )
            return entity

        def __init__(self, **data):
            super().__init__(**data)
            if self.namespace is None:
                self.namespace = get_namespace(self.entity)
            if self.namespace is None:
                raise ValueError("Namespace could not be determined.")
            if not isinstance(self.policy, OSW.OverwriteClassParam):
                self.policy = OSW.OverwriteClassParam(
                    model=self.entity.__class__,
                    overwrite=self.policy,
                )

    @staticmethod
    def _apply_overwrite_policy(param: OSW._ApplyOverwriteParam) -> WtPage:
        if param.inplace:
            page = param.page
        else:
            page = deepcopy(param.page)
        entity_title = f"{param.namespace}:{get_title(param.entity)}"

        def set_content(content_to_set: dict) -> None:
            if param.debug:
                _logger.debug(f"content_to_set: {content_to_set!s}")
            for slot_ in content_to_set.keys():
                page.set_slot_content(slot_, content_to_set[slot_])

        # Create a variable to hold the new content
        new_content = {
            # required for json parsing and header rendering
            "header": "{{#invoke:Entity|header}}",
            # required for footer rendering
            "footer": "{{#invoke:Entity|footer}}",
        }
        # Take the shortcut if
        # 1. page does not exist AND any setting of overwrite
        # 2. overwrite is "replace remote"
        if (
            not page.exists
            or param.policy.overwrite == AddOverwriteClassOptions.replace_remote
            or param.offline is True
        ):
            # Use pydantic serialization, skip none values:
            new_content["jsondata"] = json.loads(param.entity.json(exclude_none=True))
            if param.remove_empty:
                remove_empty(new_content["jsondata"])
            set_content(new_content)
            page.changed = True
            return page  # Guard clause --> exit function
        # 3. pages does exist AND overwrite is "keep existing"
        if (
            page.exists
            and param.policy.overwrite == AddOverwriteClassOptions.keep_existing
        ):
            _logger.warning(
                f"Entity '{entity_title}' already exists and won't be stored "
                f"with overwrite set to 'keep existing'!"
            )
            return page  # Guard clause --> exit function
        # Apply the overwrite logic in any other case
        # 4. If per_property was None  -> overwrite will be used as a fallback
        # 4.1 If overwrite is True ---> overwrite existing properties
        # 4.2 If overwrite is False --> don't overwrite existing properties
        # 4.3 If overwrite is "only empty" --> overwrite existing properties if
        #     they are empty
        # * Download page
        # * Merge slots selectively based on per_property

        # Create variables to hold local and remote content prior to merging
        local_content = {}
        remote_content = {}
        # Get the remote content
        for slot in ["jsondata", "header", "footer"]:  # SLOTS:
            remote_content[slot] = page.get_slot_content(slot)
            # Todo: remote content does not contain properties that are not set
        if param.remove_empty:
            remove_empty(remote_content["jsondata"])
        if remote_content["header"]:  # not None or {} or ""
            new_content["header"] = remote_content["header"]
        if remote_content["footer"]:
            new_content["footer"] = remote_content["footer"]
        if param.debug:
            _logger.debug(f"'remote_content': {remote_content!s}")
        # Get the local content
        # Properties that are not set in the local content will be set to None
        # We want those not to be listed as keys
        local_content["jsondata"] = json.loads(param.entity.json(exclude_none=True))
        if param.remove_empty:
            remove_empty(local_content["jsondata"])
        if param.debug:
            _logger.debug(f"'local_content': {local_content!s}")
        # Apply the overwrite logic
        # a) If there is a key in the remote content that is not in the local
        #    content, we have to keep it
        if remote_content["jsondata"] is None:
            remote_content["jsondata"] = {}
        new_content["jsondata"] = remote_content["jsondata"]
        # new_content["jsondata"] = {
        #     key: value
        #     for (key, value) in remote_content["jsondata"].items()
        #     if key not in local_content["jsondata"].keys()
        # }
        if param.debug:
            _logger.debug(f"'New content' after 'remote' update: {new_content!s}")
        # b) If there is a key in the local content that is not in the remote
        #    content, we have to keep it
        new_content["jsondata"].update({
            key: value
            for (key, value) in local_content["jsondata"].items()
            if key not in remote_content["jsondata"].keys()
        })
        if param.debug:
            _logger.debug(f"'New content' after 'local' update: {new_content!s}")
        # c) If there is a key in both contents, we have to apply the overwrite
        #    logic
        # todo: include logic for hidden and read_only properties!
        new_content["jsondata"].update({
            key: value
            for (key, value) in local_content["jsondata"].items()
            if param.policy.get_overwrite_setting(key) == OverwriteOptions.true
        })
        if param.debug:
            _logger.debug(f"'New content' after 'True' update: {new_content!s}")
        new_content["jsondata"].update({
            key: value
            for (key, value) in remote_content["jsondata"].items()
            if param.policy.get_overwrite_setting(key) == OverwriteOptions.false
        })
        if param.debug:
            _logger.debug(f"'New content' after 'False' update: {new_content!s}")
        new_content["jsondata"].update({
            key: value
            for (key, value) in local_content["jsondata"].items()
            if (
                param.policy.get_overwrite_setting(key) == OverwriteOptions.only_empty
                and is_empty(remote_content["jsondata"].get(key))
            )
        })
        if param.debug:
            _logger.debug(f"'New content' after 'only empty' update: {new_content!s}")
            _logger.debug(f"'New content' to be stored: {new_content!s}")
        set_content(new_content)
        return page  # Guard clause --> exit function

    class StoreEntityParam(OswBaseModel):
        entities: Union[OswBaseModel, List[OswBaseModel]]  # actually model.Entity
        """The entities to store. Can be a single entity or a list of entities."""
        namespace: Optional[str]
        """The namespace of the entities. If not set, the namespace is derived from the
        entity."""
        parallel: Optional[bool] = None
        """If set to True, the entities are stored in parallel."""
        overwrite: Optional[OVERWRITE_CLASS_OPTIONS] = "keep existing"
        """If no class specific overwrite setting is set, this setting is used."""
        overwrite_per_class: Optional[List[OSW.OverwriteClassParam]] = None
        """A list of OverwriteClassParam objects. If a class specific overwrite setting
        is set, this setting is used.
        """
        remove_empty: Optional[bool] = True
        """If true, remove key with an empty string value from the jsondata."""
        change_id: Optional[str] = None
        """ID to document the change. Entities within the same store_entity() call will
        share the same change_id. This parameter can also be used to link multiple
        store_entity() calls."""
        bot_edit: Optional[bool] = True
        """Mark the edit as bot edit,
        which hides the edit from the recent changes in the default filer"""
        edit_comment: Optional[str] = None
        """Additional comment to explain the edit."""
        meta_category_title: Optional[Union[str, List[str]]] = "Category:Category"
        debug: Optional[bool] = False
        offline: Optional[bool] = False
        """If set to True, the processed entities are not upload but only returned as WtPages.
        Can be used to create WtPage objects from entities without uploading them."""
        verify_write: Optional[bool] = True
        """If set to True, the existence of every edited page is queried after the
        upload. A page that does not exist afterwards is reported in
        StoreEntityResult.failed instead of StoreEntityResult.pages. This costs one
        additional API request per 50 edited pages, and one further request some
        seconds later if a page is reported as missing. If the query itself fails,
        the pages are reported as stored and an error is logged. Has no effect if
        'offline' is True."""
        _overwrite_per_class: Dict[str, Dict[str, OSW.OverwriteClassParam]] = (
            PrivateAttr()
        )
        """Private attribute, for internal use only. Use 'overwrite_per_class'
        instead."""

        def __init__(self, **data):
            super().__init__(**data)
            if not isinstance(self.entities, list):
                self.entities = [self.entities]
            if self.change_id is None:
                self.change_id = str(uuid4())
            for entity in self.entities:
                if getattr(entity, "meta", None) is None:
                    entity.meta = model.Meta()
                if entity.meta.change_id is None:
                    entity.meta.change_id = []
                if self.change_id not in entity.meta.change_id:
                    entity.meta.change_id.append(self.change_id)
            if len(self.entities) > 5 and self.parallel is None:
                self.parallel = True
            if self.parallel is None:
                self.parallel = (
                    True  # Set to True after implementation of asynchronous upload
                )
            if self.overwrite is None:
                self.overwrite = self.__fields__["overwrite"].get_default()
            self._overwrite_per_class = {"by name": {}, "by type": {}}
            if self.overwrite_per_class is not None:
                for param in self.overwrite_per_class:
                    model_name = param.model.__name__
                    model_type = param.model.__fields__["type"].get_default()[0]
                    if (
                        model_name in self._overwrite_per_class["by name"].keys()
                        or model_type in self._overwrite_per_class["by type"].keys()
                    ):
                        raise ValueError(
                            f"More than one OverwriteClassParam for the class "
                            f"'{model_type}' ({model_name}) has been passed in the "
                            f"list to 'overwrite_per_class'!"
                        )
                    self._overwrite_per_class["by name"][model_name] = param
                    self._overwrite_per_class["by type"][model_type] = param

    class StoreEntityResult(OswBaseModel):
        """Result of store_entity()"""

        change_id: str
        """The ID of the change"""
        pages: Dict[str, WtPage]
        """The pages that have been successfully stored, keyed by full page title.
        On partial failure this contains only the successfully-stored pages."""
        failed: Dict[str, Exception] = {}
        """Entities that could not be stored, mapped to the exception that caused the
        failure. Empty on full success. The key is the full page title where one could
        be determined. For an entity whose title or namespace could not be resolved it
        falls back to the entity name, then to its uuid, then to 'unknown', so do not
        parse this key as 'namespace:title'."""

        class Config:
            arbitrary_types_allowed = True

    class StoreEntityPartialError(Exception):
        """Raised by store_entity() when one or more entities could not be stored.

        Carries the partial ``StoreEntityResult`` so callers can learn exactly which
        entities were written (``stored`` / ``result.pages``) and which failed
        (``failed`` / ``result.failed``) without a separate existence query.
        """

        def __init__(self, result: OSW.StoreEntityResult):
            self.result = result
            self.stored = list(result.pages.keys())
            self.failed = result.failed
            total = len(result.pages) + len(result.failed)
            failed_titles = ", ".join(result.failed.keys())
            super().__init__(
                f"store_entity failed for {len(result.failed)} of {total} "
                f"entities: {failed_titles}"
            )

    class PageNotCreatedError(Exception):
        """Raised for a page that does not exist after store_entity() edited it.

        The edit was sent and no exception was raised, but the page is absent when
        the wiki is asked afterwards. A form or template driven creation step on
        the category can reject the content server-side without reporting an error
        to the API client.
        """

        def __init__(self, title: str):
            self.title = title
            super().__init__(
                f"Page '{title}' does not exist after the edit. The write was "
                f"rejected by the wiki without an error response."
            )

    def _get_missing_page_titles(
        self, titles: List[str], confirm_delay_s: int = 5
    ) -> List[str]:
        """Returns those of the given page titles that do not exist on the wiki.

        A title the wiki reports as missing is queried a second time after
        confirm_delay_s seconds. A read can be answered by a database replica that
        does not have the write yet, and a title that is still absent seconds later
        is not explained by that lag.

        Parameters
        ----------
        titles:
            Full page titles to check.
        confirm_delay_s:
            Seconds to wait before the second query. Set to 0 to query only once.
        """
        missing = self._query_missing_page_titles(titles)
        if missing and confirm_delay_s:
            sleep(confirm_delay_s)
            missing = self._query_missing_page_titles(missing)
        return missing

    def _query_missing_page_titles(self, titles: List[str]) -> List[str]:
        """Asks the wiki once which of the given page titles do not exist.

        The query goes to the MediaWiki API directly and not through
        WtSite.get_page(), because the page cache would answer with the state from
        before the write.

        Parameters
        ----------
        titles:
            Full page titles to check.
        """
        missing = []
        batch_size = 50  # maximum number of titles per API query
        for start in range(0, len(titles), batch_size):
            batch = titles[start : start + batch_size]
            result = self.mw_site.api(
                "query", titles="|".join(batch), prop="info", format="json"
            )
            query = result.get("query", {})
            # the API normalizes titles, map them back to what was requested
            normalized = {n["to"]: n["from"] for n in query.get("normalized", [])}
            for page_info in query.get("pages", {}).values():
                if "missing" in page_info:
                    title = page_info.get("title")
                    missing.append(normalized.get(title, title))
        return missing

    def store_entity(
        self, param: Union[StoreEntityParam, OswBaseModel, List[OswBaseModel]]
    ) -> StoreEntityResult:
        """stores the given dataclass instance as OSW page by calling BaseModel.json()

        Parameters
        ----------
        param:
            StoreEntityParam, the dataclass instance or a list of instances
        """
        if isinstance(param, list):
            param = OSW.StoreEntityParam(entities=param)
        elif not isinstance(param, OSW.StoreEntityParam):
            # Accept any OswBaseModel / Entity / Controller instance
            param = OSW.StoreEntityParam(entities=[param])
        if not isinstance(param.entities, list):
            param.entities = [param.entities]

        param: OSW.StoreEntityParam = param

        max_index = len(param.entities)
        created_pages = {}
        edited_titles = set()
        """Titles of the pages an edit was sent for, to be verified below."""

        meta_category_templates = {}
        if param.namespace == "Category":
            meta_category_titles = param.meta_category_title
            if not isinstance(meta_category_titles, list):
                meta_category_titles = [meta_category_titles]
            meta_category_template_strs = {}
            # We have to do this iteratively to support meta categories inheritance
            while meta_category_titles is not None and len(meta_category_titles) > 0:
                meta_categories = self.site.get_page(
                    WtSite.GetPageParam(titles=meta_category_titles)
                ).pages
                for meta_category in meta_categories:
                    meta_category_template_strs[meta_category.title] = (
                        meta_category.get_slot_content("schema_template")
                    )

                meta_category_titles = meta_category.get_slot_content("jsondata").get(
                    "subclass_of"
                )

            for title in meta_category_template_strs.keys():
                meta_category_template_str = meta_category_template_strs[title]
                if meta_category_template_str:
                    meta_category_templates[title] = compile_handlebars_template(
                        meta_category_template_str
                    )
            # inverse order to have the most generic template first
            meta_category_templates = dict(reversed(meta_category_templates.items()))

        def store_entity_(
            entity_: model.Entity,
            namespace_: str = None,
            index: int = None,
            overwrite_class_param: OSW.OverwriteClassParam = None,
        ) -> None:
            try:
                title_ = get_title(entity_)
            except Exception as e:
                entity_name = getattr(entity_, "name", None) or getattr(
                    entity_, "uuid", "unknown"
                )
                # raise instead of returning: a plain return is not an exception,
                # so the collector loop below would record the entity in neither
                # created_pages nor failed and store_entity would report success
                raise ValueError(
                    f"Error getting title for entity '{entity_name}': {e}"
                ) from e
            if namespace_ is None:
                namespace_ = get_namespace(entity_)
            if namespace_ is None or title_ is None:
                entity_name = getattr(entity_, "name", None) or getattr(
                    entity_, "uuid", "unknown"
                )
                raise TypeError(
                    f"Unsupported entity type: namespace={namespace_}, "
                    f"title={title_}, entity name='{entity_name}', "
                    f"type={type(entity_).__name__}"
                )
            if overwrite_class_param is None:
                raise TypeError("'overwrite_class_param' must not be None!")
            entity_title = namespace_ + ":" + title_
            page = self._apply_overwrite_policy(
                OSW._ApplyOverwriteParam(
                    page=WtPage(
                        wtSite=self.site, title=entity_title, do_init=not param.offline
                    ),
                    entity=entity_,
                    namespace=namespace_,
                    policy=overwrite_class_param,
                    remove_empty=param.remove_empty,
                    debug=param.debug,
                    offline=param.offline,
                )
            )
            # _apply_overwrite_policy() returned the remote page untouched. The
            # schema regeneration below writes the jsonschema slot regardless of
            # the policy, which would edit a page the caller asked to keep.
            kept_existing = (
                page.exists
                # mirrors the branch order of _apply_overwrite_policy(), which
                # tests 'offline is True' before it tests 'keep existing'
                and param.offline is not True
                and overwrite_class_param.overwrite
                == AddOverwriteClassOptions.keep_existing
            )
            if not kept_existing and len(meta_category_templates.keys()) > 0:
                generated_schemas = {}
                try:
                    jsondata = page.get_slot_content("jsondata")
                    if param.remove_empty:
                        remove_empty(jsondata)

                    for key in meta_category_templates:
                        meta_category_template = meta_category_templates[key]
                        schema_str = eval_compiled_handlebars_template(
                            meta_category_template,
                            escape_json_strings(jsondata),
                            {
                                "_page_title": entity_title,  # Legacy
                                "_current_subject_": entity_title,
                            },
                        )
                        generated_schemas[key] = json.loads(schema_str)
                except Exception as e:
                    _logger.error(
                        f"Schema generation from template failed for {entity_}: {e}"
                    )

                mode = AggregateGeneratedSchemasParamMode.ROOT_LEVEL
                # Put generated schema in definitions section,
                #  currently only enabled for Characteristics
                if hasattr(model, "CharacteristicType") and isinstance(
                    entity_, model.CharacteristicType
                ):
                    mode = AggregateGeneratedSchemasParamMode.DEFINITIONS_SECTION

                new_schema = aggregate_generated_schemas(
                    AggregateGeneratedSchemasParam(
                        schema=page.get_slot_content("jsonschema"),
                        generated_schemas=generated_schemas,
                        mode=mode,
                    )
                ).aggregated_schema
                page.set_slot_content("jsonschema", new_schema)
            if param.offline is False and not kept_existing:
                page.edit(
                    param.edit_comment, bot_edit=param.bot_edit
                )  # will set page.changed if the content of the page has changed
                edited_titles.add(page.title)
            if not param.offline and page.changed:
                if index is None:
                    _logger.info(f"Entity stored at '{page.get_url()}'.")
                else:
                    _logger.info(
                        f"({index + 1}/{max_index}) Entity stored at "
                        f"'{page.get_url()}'."
                    )
            created_pages[page.title] = page

        sorted_entities = OSW.sort_list_of_entities_by_class(param.entities)
        _logger.info(
            "Entities to be uploaded have been sorted according to their type.\n"
            "If you would like to overwrite existing entities or properties, "
            "pass a StoreEntityParam to store_entity() with "
            "attribute 'overwrite' or 'overwrite_per_class' set to, e.g., "
            "True."
        )

        class UploadObject(BaseModel):
            entity: OswBaseModel
            # Actually model.Entity but this causes the "type" error
            namespace: Optional[str]
            index: int
            overwrite_class_param: OSW.OverwriteClassParam

        upload_object_list: List[UploadObject] = []

        upload_index = 0
        for class_type, entities in sorted_entities.by_type.items():
            # Try to get a class specific overwrite setting
            class_param = param._overwrite_per_class["by type"].get(class_type, None)
            if class_param is None:
                entity_model = entities[0].__class__
                class_param = OSW.OverwriteClassParam(
                    model=entity_model,
                    overwrite=param.overwrite,
                )
                if param.debug:
                    _logger.debug(
                        f"Now adding entities of class type '{class_type}' "
                        f"({entity_model.__name__}) to upload list. No class specific"
                        f" overwrite setting found. Using fallback option '"
                        f"{param.overwrite}' for all entities of this class."
                    )
            for entity in entities:
                upload_object_list.append(
                    UploadObject(
                        entity=entity,
                        namespace=param.namespace,
                        index=upload_index,
                        overwrite_class_param=class_param,
                    )
                )
                upload_index += 1

        def handle_upload_object_(upload_object: UploadObject) -> None:
            # Let exceptions propagate: the caller collects them per entity below,
            # so a single failure neither aborts the batch nor is silently
            # swallowed. store_entity_ records a page in created_pages whenever it
            # reaches its last statement, which only means that nothing raised.
            # Whether the page exists afterwards is checked by the verification
            # step below.
            store_entity_(
                upload_object.entity,
                upload_object.namespace,
                upload_object.index,
                upload_object.overwrite_class_param,
            )

        def failure_title_(upload_object: UploadObject) -> str:
            """Best-effort full page title of a failed entity, for error reporting."""
            try:
                namespace = upload_object.namespace or get_namespace(
                    upload_object.entity
                )
                return f"{namespace}:{get_title(upload_object.entity)}"
            except Exception:
                return (
                    getattr(upload_object.entity, "name", None)
                    or getattr(upload_object.entity, "uuid", None)
                    or "unknown"
                )

        if param.parallel:
            # return_exceptions=True keeps results aligned with upload_object_list
            # and lets every entity be attempted even if some fail.
            results = parallelize(
                handle_upload_object_,
                upload_object_list,
                flush_at_end=param.debug,
                return_exceptions=True,
            )
        else:
            results = []
            for upload_object in upload_object_list:
                try:
                    handle_upload_object_(upload_object)
                    results.append(None)
                except Exception as e:
                    results.append(e)

        failed: Dict[str, Exception] = {}
        for upload_object, result in zip(upload_object_list, results):
            if isinstance(result, Exception):
                title = failure_title_(upload_object)
                _logger.error(f"Error storing entity '{title}': {result}")
                failed[title] = result

        if param.verify_write and not param.offline and edited_titles:
            # An edit that raised no exception is not proof that the page exists:
            # a form or template driven creation step can reject the content
            # server-side. page.changed is no help either, it is True in that case.
            titles_to_verify = [
                title for title in edited_titles if title in created_pages
            ]
            try:
                missing_titles = self._get_missing_page_titles(titles_to_verify)
            except Exception as e:
                # A failed query is no evidence that the writes failed. Report it
                # and keep the pages, instead of discarding everything this call
                # has collected so far.
                missing_titles = []
                _logger.error(
                    f"Could not verify {len(titles_to_verify)} stored pages, they "
                    f"are reported as stored without being checked: {e}"
                )
            for title in missing_titles:
                error = OSW.PageNotCreatedError(title)
                _logger.error(f"Error storing entity '{title}': {error}")
                failed[title] = error
                del created_pages[title]

        store_result = OSW.StoreEntityResult(
            change_id=param.change_id, pages=created_pages, failed=failed
        )
        if failed:
            # Surface partial/total failure so callers cannot mistake a dropped
            # page for a success. The result (successes + failures) rides along.
            raise OSW.StoreEntityPartialError(store_result)
        return store_result

    class DeleteEntityParam(OswBaseModel):
        entities: Union[OswBaseModel, List[OswBaseModel]]
        comment: Optional[str] = None
        parallel: Optional[bool] = None
        debug: Optional[bool] = False

        def __init__(self, **data):
            super().__init__(**data)
            if not isinstance(self.entities, list):
                self.entities = [self.entities]
            if len(self.entities) > 5 and self.parallel is None:
                self.parallel = True
            if self.parallel is None:
                self.parallel = False

    def delete_entity(
        self,
        entity: Union[OswBaseModel, List[OswBaseModel], DeleteEntityParam],
        comment: str = None,
    ):
        """Deletes the given entity/entities from the OSW instance."""
        if not isinstance(entity, OSW.DeleteEntityParam):
            entity = OSW.DeleteEntityParam(entities=entity)
        if comment is not None:
            entity.comment = comment

        def delete_entity_(entity_, comment_: str = None):
            """Deletes the given entity from the OSW instance.

            Parameters
            ----------
            entity_:
                The dataclass instance to delete
            comment_:
                Command for the change log, by default None
            """
            title_ = None
            namespace_ = None
            if hasattr(entity_, "meta"):
                if entity_.meta and entity_.meta.wiki_page:
                    if entity_.meta.wiki_page.title:
                        title_ = entity_.meta.wiki_page.title
                    if entity_.meta.wiki_page.namespace:
                        namespace_ = entity_.meta.wiki_page.namespace
            if namespace_ is None:
                namespace_ = get_namespace(entity_)
            if title_ is None:
                title_ = OSW.get_osw_id(entity_.uuid)
            if namespace_ is None or title_ is None:
                _logger.error("Unsupported entity type")
                return
            entity_title = namespace_ + ":" + title_
            page = self.site.get_page(WtSite.GetPageParam(titles=[entity_title])).pages[
                0
            ]

            if page.exists:
                page.delete(comment_)
                _logger.info("Entity deleted: " + page.get_url())
            else:
                _logger.warning(f"Entity '{entity_title}' does not exist!")

        if entity.parallel:
            _ = parallelize(
                delete_entity_,
                entity.entities,
                flush_at_end=entity.debug,
                comment_=entity.comment,
            )
        else:
            _ = [delete_entity_(e, entity.comment) for e in entity.entities]

    class QueryInstancesParam(OswBaseModel):
        categories: Union[
            Union[str, Type[OswBaseModel]], List[Union[str, Type[OswBaseModel]]]
        ]
        parallel: Optional[bool] = None
        debug: Optional[bool] = False
        limit: Optional[int] = 1000
        _category_string_parts: List[Dict[str, str]] = PrivateAttr()
        _titles: List[str] = PrivateAttr()

        @staticmethod
        def get_full_page_name_parts(
            category_: Union[str, Type[OswBaseModel]],
        ) -> Dict[str, str]:
            error_msg = (
                f"Category must be a string like 'Category:<category name>' or a "
                f"dataclass subclass with a 'type' attribute. This error occurred on "
                f"'{category_!s}'"
            )
            if isinstance(category_, str):
                string_to_split = category_
            elif issubclass(category_, OswBaseModel):
                type_ = category_.__fields__.get("type")
                if getattr(type_, "default", None) is None:
                    raise TypeError(error_msg)
                string_to_split = type_.default[0]
            else:
                raise TypeError(error_msg)
            if "Category:" not in string_to_split:
                raise TypeError(error_msg)
            return {
                "namespace": string_to_split.split(":")[0],
                "title": string_to_split.split(":")[-1],
            }

        def __init__(self, **data):
            super().__init__(**data)
            if not isinstance(self.categories, list):
                self.categories = [self.categories]
            if len(self.categories) > 5 and self.parallel is None:
                self.parallel = True
            if self.parallel is None:
                self.parallel = False
            self._category_string_parts = [
                OSW.QueryInstancesParam.get_full_page_name_parts(cat)
                for cat in self.categories
            ]
            self._titles = [parts["title"] for parts in self._category_string_parts]

    def query_instances(
        self, category: Union[str, Type[OswBaseModel], OSW.QueryInstancesParam]
    ) -> List[str]:
        if not isinstance(category, OSW.QueryInstancesParam):
            category = OSW.QueryInstancesParam(categories=category)
        page_titles = category._titles
        search_param = SearchParam(
            query=[f"[[HasType::Category:{page_title}]]" for page_title in page_titles],
            **category.dict(
                exclude={"categories", "_category_string_parts", "_titles"}
            ),
        )
        full_page_titles = self.site.semantic_search(search_param)
        return full_page_titles

    class JsonLdMode(str, Enum):
        """enum for jsonld processing mode"""

        expand = "expand"
        flatten = "flatten"
        compact = "compact"
        frame = "frame"

    class ExportJsonLdParams(OswBaseModel):
        context_loader_config: Optional[WtSite.JsonLdContextLoaderParams] = None
        """The configuration for the JSON-LD context loader."""
        entities: Union[OswBaseModel, List[OswBaseModel]]
        """The entities to convert to JSON-LD. Can be a single entity or a list of
        entities."""
        id_keys: Optional[List[str]] = Field(default=["osw_id"])
        """The keys to use as @id in the JSON-LD output. If not found in the entity at root
        level, the full page title is used."""
        resolve_context: Optional[bool] = True
        """If True, remote context URLs are resolved."""
        mode: Optional[OSW.JsonLdMode] = "expand"
        """The JSON-LD processing mode to apply if resolve_context is True."""
        context: Optional[Union[str, list, Dict[str, Any]]] = None
        """The JSON-LD context to apply. Replaces any existing context."""
        additional_context: Optional[Union[str, list, Dict[str, Any]]] = None
        """The JSON-LD context to apply on top of the existing context."""
        frame: Optional[Dict[str, Any]] = None
        """The JSON-LD frame to use for framed mode. If not set, the existing context is used"""
        build_rdf_graph: Optional[bool] = False
        """If True, the output is a graph."""
        debug: Optional[bool] = False
        """If True, debug information is printed."""

        class Config:
            arbitrary_types_allowed = True

        def __init__(self, **data):
            super().__init__(**data)
            if not isinstance(self.entities, list):
                self.entities = [self.entities]

    class ExportJsonLdResult(OswBaseModel):
        documents: List[Union[Dict[str, Any]]]
        """A single JSON-LD document per entity"""
        graph_document: Dict[str, Any] = None
        """A single JSON-LD document with a @graph element containing all entities"""
        graph: rdflib.Graph = None
        """RDF graph containing all entities. Build only if build_rdf_graph is True"""

        class Config:
            arbitrary_types_allowed = True

    def export_jsonld(self, params: ExportJsonLdParams) -> ExportJsonLdResult:
        """Exports the given entity/entities as JSON-LD."""

        if params.resolve_context:
            jsonld.set_document_loader(
                self.site.get_jsonld_context_loader(params.context_loader_config)
            )

        documents = []
        graph_document = {"@graph": []}
        graph = None
        if params.build_rdf_graph:
            graph = rdflib.Graph()
            prefixes = self.site.get_prefix_dict()
            for prefix in prefixes:
                graph.bind(prefix, prefixes[prefix])

        for e in params.entities:
            data = json.loads(e.json(exclude_none=True, indent=4, ensure_ascii=False))

            data["@context"] = []
            if params.id_keys is not None:
                # append "@id" mappings to the context in an additional object
                id_mapping = {}
                for k in params.id_keys:
                    id_mapping[k] = "@id"
                data["@context"].append(id_mapping)
            if params.context is None:
                for t in e.type:
                    data["@context"].append("/wiki/" + t)
                if params.context is not None:
                    data["@context"].append(params.context)
            else:
                data["@context"].append(self.site.get_jsonld_context_prefixes())
                if isinstance(params.context, list):
                    data["@context"].extend(params.context)
                else:
                    data["@context"].append(params.context)
            if params.additional_context is not None:
                if data["@context"] is None:
                    data["@context"] = []
                elif not isinstance(data["@context"], list):
                    data["@context"] = [data["@context"]]
                data["@context"].append(params.additional_context)

            # if none of the id_keys is found, use the full title
            if not any(k in data for k in params.id_keys):
                data["@id"] = get_full_title(e)

            if params.resolve_context:
                graph_document["@graph"].append(jsonld.expand(data))
                if params.mode == "expand":
                    data = jsonld.expand(data)
                    if isinstance(data, list) and len(data) > 0:
                        data = data[0]
                elif params.mode == "flatten":
                    data = jsonld.flatten(data)
                elif params.mode == "compact":
                    # data = jsonld.expand(data)
                    # if isinstance(data, list): data = data[0]
                    data = jsonld.compact(
                        data,
                        data["@context"] if params.context is None else params.context,
                    )
                elif params.mode == "frame":
                    data = jsonld.frame(
                        data,
                        (
                            {"@context": data["@context"]}
                            if params.frame is None
                            else params.frame
                        ),
                    )

                if params.build_rdf_graph:
                    graph.parse(data=json.dumps(data), format="json-ld")

            documents.append(data)

        result = OSW.ExportJsonLdResult(
            documents=documents, graph_document=graph_document, graph=graph
        )
        return result

mw_site property

Returns the mwclient Site object of the OSW instance.

ExportJsonLdParams

Bases: OswBaseModel

Source code in src/osw/core.py
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
class ExportJsonLdParams(OswBaseModel):
    context_loader_config: Optional[WtSite.JsonLdContextLoaderParams] = None
    """The configuration for the JSON-LD context loader."""
    entities: Union[OswBaseModel, List[OswBaseModel]]
    """The entities to convert to JSON-LD. Can be a single entity or a list of
    entities."""
    id_keys: Optional[List[str]] = Field(default=["osw_id"])
    """The keys to use as @id in the JSON-LD output. If not found in the entity at root
    level, the full page title is used."""
    resolve_context: Optional[bool] = True
    """If True, remote context URLs are resolved."""
    mode: Optional[OSW.JsonLdMode] = "expand"
    """The JSON-LD processing mode to apply if resolve_context is True."""
    context: Optional[Union[str, list, Dict[str, Any]]] = None
    """The JSON-LD context to apply. Replaces any existing context."""
    additional_context: Optional[Union[str, list, Dict[str, Any]]] = None
    """The JSON-LD context to apply on top of the existing context."""
    frame: Optional[Dict[str, Any]] = None
    """The JSON-LD frame to use for framed mode. If not set, the existing context is used"""
    build_rdf_graph: Optional[bool] = False
    """If True, the output is a graph."""
    debug: Optional[bool] = False
    """If True, debug information is printed."""

    class Config:
        arbitrary_types_allowed = True

    def __init__(self, **data):
        super().__init__(**data)
        if not isinstance(self.entities, list):
            self.entities = [self.entities]

additional_context = None class-attribute instance-attribute

The JSON-LD context to apply on top of the existing context.

build_rdf_graph = False class-attribute instance-attribute

If True, the output is a graph.

context = None class-attribute instance-attribute

The JSON-LD context to apply. Replaces any existing context.

context_loader_config = None class-attribute instance-attribute

The configuration for the JSON-LD context loader.

debug = False class-attribute instance-attribute

If True, debug information is printed.

entities instance-attribute

The entities to convert to JSON-LD. Can be a single entity or a list of entities.

frame = None class-attribute instance-attribute

The JSON-LD frame to use for framed mode. If not set, the existing context is used

id_keys = Field(default=['osw_id']) class-attribute instance-attribute

The keys to use as @id in the JSON-LD output. If not found in the entity at root level, the full page title is used.

mode = 'expand' class-attribute instance-attribute

The JSON-LD processing mode to apply if resolve_context is True.

resolve_context = True class-attribute instance-attribute

If True, remote context URLs are resolved.

ExportJsonLdResult

Bases: OswBaseModel

Source code in src/osw/core.py
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
class ExportJsonLdResult(OswBaseModel):
    documents: List[Union[Dict[str, Any]]]
    """A single JSON-LD document per entity"""
    graph_document: Dict[str, Any] = None
    """A single JSON-LD document with a @graph element containing all entities"""
    graph: rdflib.Graph = None
    """RDF graph containing all entities. Build only if build_rdf_graph is True"""

    class Config:
        arbitrary_types_allowed = True

documents instance-attribute

A single JSON-LD document per entity

graph = None class-attribute instance-attribute

RDF graph containing all entities. Build only if build_rdf_graph is True

graph_document = None class-attribute instance-attribute

A single JSON-LD document with a @graph element containing all entities

FetchSchemaMode

Bases: Enum

Modes of the FetchSchemaParam class

Attributes:

Name Type Description
append

append to the current model

replace

replace the current model

Source code in src/osw/core.py
523
524
525
526
527
528
529
530
531
532
533
534
535
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

FetchSchemaParam

Bases: BaseModel

Param for fetch_schema()

Attributes:

Name Type Description
schema_title Optional[Union[List[str], str]]

one or multiple titles (wiki page name) of schemas (default: Category:Item)

mode Optional[str]

append or replace (default) current schema, see FetchSchemaMode

Source code in src/osw/core.py
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
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

generate_annotations = True class-attribute instance-attribute

generate custom schema keywords in Fields and Classes. Required to update the schema in OSW without information loss

generator_options = None class-attribute instance-attribute

custom options for the datamodel-code-generator

offline_pages = None class-attribute instance-attribute

pages to be used offline instead of fetching them from the OSW instance

result_model_path = None class-attribute instance-attribute

path to the generated model file, if None, the default path ./model/entity.py is used

FetchSchemaResult

Bases: BaseModel

Source code in src/osw/core.py
567
568
569
570
571
572
573
574
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"""

error_messages = None class-attribute instance-attribute

List of critical errors that did interrupt the fetch process

fetched_schema_titles = None class-attribute instance-attribute

List of titles of the schemas that were fetched. This includes the requested schemas and their dependencies.

warning_messages = None class-attribute instance-attribute

List of warnings that did not interrupt the fetch process

JsonLdMode

Bases: str, Enum

enum for jsonld processing mode

Source code in src/osw/core.py
2347
2348
2349
2350
2351
2352
2353
class JsonLdMode(str, Enum):
    """enum for jsonld processing mode"""

    expand = "expand"
    flatten = "flatten"
    compact = "compact"
    frame = "frame"

LoadEntityParam

Bases: BaseModel

Param for load_entity()

Source code in src/osw/core.py
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
class LoadEntityParam(BaseModel):
    """Param for load_entity()"""

    titles: Union[str, List[str]]
    """The pages titles to load - one or multiple titles (wiki page name) of
    entities"""
    autofetch_schema: Optional[bool] = True
    """If true, load the corresponding schemas /
    categories ad-hoc if not already present"""
    model_to_use: Optional[Type[OswBaseModel]] = None
    """If provided this model will be used to create an entity (instance of the
    model), instead of instantiating the autofetched schema."""
    remove_empty: Optional[bool] = True
    """If true, remove key with an empty string, list, dict or set as value
    from the jsondata."""
    disable_cache: bool = False
    """If true, disable the cache for the loading process"""
    offline_pages: Optional[Dict[str, WtPage]] = None
    """pages to be used offline instead of fetching them from the OSW instance"""

    class Config:
        arbitrary_types_allowed = True  # allow any class as type

    def __init__(self, **data):
        super().__init__(**data)
        if not isinstance(self.titles, list):
            self.titles = [self.titles]

autofetch_schema = True class-attribute instance-attribute

If true, load the corresponding schemas / categories ad-hoc if not already present

disable_cache = False class-attribute instance-attribute

If true, disable the cache for the loading process

model_to_use = None class-attribute instance-attribute

If provided this model will be used to create an entity (instance of the model), instead of instantiating the autofetched schema.

offline_pages = None class-attribute instance-attribute

pages to be used offline instead of fetching them from the OSW instance

remove_empty = True class-attribute instance-attribute

If true, remove key with an empty string, list, dict or set as value from the jsondata.

titles instance-attribute

The pages titles to load - one or multiple titles (wiki page name) of entities

LoadEntityResult

Bases: BaseModel

Result of load_entity()

Source code in src/osw/core.py
1280
1281
1282
1283
1284
class LoadEntityResult(BaseModel):
    """Result of load_entity()"""

    entities: Union[model.OswBaseModel, List[model.OswBaseModel]]
    """The dataclass instance(s)"""

entities instance-attribute

The dataclass instance(s)

OverwriteClassParam

Bases: OswBaseModel

Source code in src/osw/core.py
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
class OverwriteClassParam(OswBaseModel):
    model: Type[OswBaseModel]  # ModelMetaclass
    """The model class for which this is the overwrite params object."""
    overwrite: Optional[OVERWRITE_CLASS_OPTIONS] = False
    """Defines the overall overwriting behavior. Used for any property if the
    property specific setting is not set."""
    per_property: Optional[Dict[str, OverwriteOptions]] = None
    """A key (property name) - value (overwrite setting) pair."""
    _per_property: Dict[str, OVERWRITE_CLASS_OPTIONS] = PrivateAttr()
    """Private property, for internal use only. Use 'per_property' instead"""

    @validator("per_property")
    def validate_per_property(cls, per_property, values):
        if per_property is None:  # nothing to check, the fallback applies
            return per_property
        model_ = values.get("model")
        if model_ is None:
            # 'model' itself did not validate; without it the property names
            # below cannot be checked at all
            raise ValueError("'model' is required to validate 'per_property'")
        field_names = list(model_.__fields__.keys())
        keys = per_property.keys()
        if not all(key in field_names for key in keys):
            missing_keys = [key for key in keys if key not in field_names]
            raise ValueError(
                f"Property not found in model: {', '.join(missing_keys)}"
            )

        return per_property

    @classmethod
    def _normalize_overwrite(cls, value):
        """Replace the two non-policy values by the default setting.

        Neither ``None`` nor the ``none`` sentinel is a policy:
        ``get_overwrite_setting()`` would hand them to the merge, where they
        match no branch and silently behave like 'false'.
        """
        if value is None or value is AddOverwriteClassOptions.none:
            return cls.__fields__["overwrite"].get_default()
        return value

    def __setattr__(self, key, value):
        """Called when setting an attribute"""
        if key == "overwrite":
            value = self._normalize_overwrite(value)
        # the effective settings are derived from these three, so any of them
        # changing has to rebuild them
        if key not in ("model", "overwrite", "per_property"):
            super().__setattr__(key, value)
            return
        previous = getattr(self, key)
        super().__setattr__(key, value)
        try:
            self._sync_per_property()
        except ValueError:
            # _sync_per_property() rejects before it touches _per_property,
            # so restoring the field is enough to undo the assignment. Leaving
            # a rejected value in place would let it take effect later, on the
            # next assignment that happens to be accepted.
            super().__setattr__(key, previous)
            raise

    def __init__(self, **data):
        """Called after validation. Sets the fallback for every property that
        has not been specified in per_property."""
        super().__init__(**data)
        # routed through __setattr__, which normalizes and rebuilds
        self.overwrite = self.overwrite
        # todo: from class definition get properties with hidden /
        #  read_only option  #  those can be safely overwritten - set the to True

    def _sync_per_property(self) -> None:
        """Rebuild the effective overwrite setting of every model field."""
        if self.per_property and isinstance(
            self.overwrite, AddOverwriteClassOptions
        ):
            # _apply_overwrite_policy() short-circuits on 'replace remote'
            # and 'keep existing' before it looks at a single property, so
            # this combination would discard 'per_property' silently. Check
            # it here rather than in a validator so that it also holds when
            # either field is reassigned after construction.
            raise ValueError(
                f"'per_property' cannot be combined with overwrite="
                f"'{self.overwrite.value}', which acts on the entity as a "
                f"whole. Use an OverwriteOptions value for 'overwrite'."
            )
        per_property_ = self.per_property or {}
        self._per_property = {
            field_name: per_property_.get(field_name, self.overwrite)
            for field_name in self.model.__fields__.keys()
        }

    def get_overwrite_setting(self, property_name: str) -> OverwriteOptions:
        """Returns the fallback overwrite option for the given field name"""
        return self._per_property.get(property_name, self.overwrite)

model instance-attribute

The model class for which this is the overwrite params object.

overwrite = self.overwrite class-attribute instance-attribute

Defines the overall overwriting behavior. Used for any property if the property specific setting is not set.

per_property = None class-attribute instance-attribute

A key (property name) - value (overwrite setting) pair.

__init__(**data)

Called after validation. Sets the fallback for every property that has not been specified in per_property.

Source code in src/osw/core.py
1507
1508
1509
1510
1511
1512
def __init__(self, **data):
    """Called after validation. Sets the fallback for every property that
    has not been specified in per_property."""
    super().__init__(**data)
    # routed through __setattr__, which normalizes and rebuilds
    self.overwrite = self.overwrite

__setattr__(key, value)

Called when setting an attribute

Source code in src/osw/core.py
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
def __setattr__(self, key, value):
    """Called when setting an attribute"""
    if key == "overwrite":
        value = self._normalize_overwrite(value)
    # the effective settings are derived from these three, so any of them
    # changing has to rebuild them
    if key not in ("model", "overwrite", "per_property"):
        super().__setattr__(key, value)
        return
    previous = getattr(self, key)
    super().__setattr__(key, value)
    try:
        self._sync_per_property()
    except ValueError:
        # _sync_per_property() rejects before it touches _per_property,
        # so restoring the field is enough to undo the assignment. Leaving
        # a rejected value in place would let it take effect later, on the
        # next assignment that happens to be accepted.
        super().__setattr__(key, previous)
        raise

get_overwrite_setting(property_name)

Returns the fallback overwrite option for the given field name

Source code in src/osw/core.py
1537
1538
1539
def get_overwrite_setting(self, property_name: str) -> OverwriteOptions:
    """Returns the fallback overwrite option for the given field name"""
    return self._per_property.get(property_name, self.overwrite)

PageNotCreatedError

Bases: Exception

Raised for a page that does not exist after store_entity() edited it.

The edit was sent and no exception was raised, but the page is absent when the wiki is asked afterwards. A form or template driven creation step on the category can reject the content server-side without reporting an error to the API client.

Source code in src/osw/core.py
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
class PageNotCreatedError(Exception):
    """Raised for a page that does not exist after store_entity() edited it.

    The edit was sent and no exception was raised, but the page is absent when
    the wiki is asked afterwards. A form or template driven creation step on
    the category can reject the content server-side without reporting an error
    to the API client.
    """

    def __init__(self, title: str):
        self.title = title
        super().__init__(
            f"Page '{title}' does not exist after the edit. The write was "
            f"rejected by the wiki without an error response."
        )

SchemaRegistration

Bases: BaseModel

dataclass param of register_schema()

Source code in src/osw/core.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
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)"""

model_cls instance-attribute

The model class

schema_bases = Field(default=['Category:Item']) class-attribute instance-attribute

A list of base schemas (referenced by allOf)

schema_name instance-attribute

The schema name

schema_uuid instance-attribute

The schema uuid

SchemaUnregistration

Bases: BaseModel

dataclass param of register_schema()

Source code in src/osw/core.py
486
487
488
489
490
491
492
493
494
495
496
497
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"""

comment instance-attribute

The comment for the deletion, to be left behind

model_cls instance-attribute

The model class

model_uuid instance-attribute

The model uuid

StoreEntityParam

Bases: OswBaseModel

Source code in src/osw/core.py
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
class StoreEntityParam(OswBaseModel):
    entities: Union[OswBaseModel, List[OswBaseModel]]  # actually model.Entity
    """The entities to store. Can be a single entity or a list of entities."""
    namespace: Optional[str]
    """The namespace of the entities. If not set, the namespace is derived from the
    entity."""
    parallel: Optional[bool] = None
    """If set to True, the entities are stored in parallel."""
    overwrite: Optional[OVERWRITE_CLASS_OPTIONS] = "keep existing"
    """If no class specific overwrite setting is set, this setting is used."""
    overwrite_per_class: Optional[List[OSW.OverwriteClassParam]] = None
    """A list of OverwriteClassParam objects. If a class specific overwrite setting
    is set, this setting is used.
    """
    remove_empty: Optional[bool] = True
    """If true, remove key with an empty string value from the jsondata."""
    change_id: Optional[str] = None
    """ID to document the change. Entities within the same store_entity() call will
    share the same change_id. This parameter can also be used to link multiple
    store_entity() calls."""
    bot_edit: Optional[bool] = True
    """Mark the edit as bot edit,
    which hides the edit from the recent changes in the default filer"""
    edit_comment: Optional[str] = None
    """Additional comment to explain the edit."""
    meta_category_title: Optional[Union[str, List[str]]] = "Category:Category"
    debug: Optional[bool] = False
    offline: Optional[bool] = False
    """If set to True, the processed entities are not upload but only returned as WtPages.
    Can be used to create WtPage objects from entities without uploading them."""
    verify_write: Optional[bool] = True
    """If set to True, the existence of every edited page is queried after the
    upload. A page that does not exist afterwards is reported in
    StoreEntityResult.failed instead of StoreEntityResult.pages. This costs one
    additional API request per 50 edited pages, and one further request some
    seconds later if a page is reported as missing. If the query itself fails,
    the pages are reported as stored and an error is logged. Has no effect if
    'offline' is True."""
    _overwrite_per_class: Dict[str, Dict[str, OSW.OverwriteClassParam]] = (
        PrivateAttr()
    )
    """Private attribute, for internal use only. Use 'overwrite_per_class'
    instead."""

    def __init__(self, **data):
        super().__init__(**data)
        if not isinstance(self.entities, list):
            self.entities = [self.entities]
        if self.change_id is None:
            self.change_id = str(uuid4())
        for entity in self.entities:
            if getattr(entity, "meta", None) is None:
                entity.meta = model.Meta()
            if entity.meta.change_id is None:
                entity.meta.change_id = []
            if self.change_id not in entity.meta.change_id:
                entity.meta.change_id.append(self.change_id)
        if len(self.entities) > 5 and self.parallel is None:
            self.parallel = True
        if self.parallel is None:
            self.parallel = (
                True  # Set to True after implementation of asynchronous upload
            )
        if self.overwrite is None:
            self.overwrite = self.__fields__["overwrite"].get_default()
        self._overwrite_per_class = {"by name": {}, "by type": {}}
        if self.overwrite_per_class is not None:
            for param in self.overwrite_per_class:
                model_name = param.model.__name__
                model_type = param.model.__fields__["type"].get_default()[0]
                if (
                    model_name in self._overwrite_per_class["by name"].keys()
                    or model_type in self._overwrite_per_class["by type"].keys()
                ):
                    raise ValueError(
                        f"More than one OverwriteClassParam for the class "
                        f"'{model_type}' ({model_name}) has been passed in the "
                        f"list to 'overwrite_per_class'!"
                    )
                self._overwrite_per_class["by name"][model_name] = param
                self._overwrite_per_class["by type"][model_type] = param

bot_edit = True class-attribute instance-attribute

Mark the edit as bot edit, which hides the edit from the recent changes in the default filer

change_id = None class-attribute instance-attribute

ID to document the change. Entities within the same store_entity() call will share the same change_id. This parameter can also be used to link multiple store_entity() calls.

edit_comment = None class-attribute instance-attribute

Additional comment to explain the edit.

entities instance-attribute

The entities to store. Can be a single entity or a list of entities.

namespace instance-attribute

The namespace of the entities. If not set, the namespace is derived from the entity.

offline = False class-attribute instance-attribute

If set to True, the processed entities are not upload but only returned as WtPages. Can be used to create WtPage objects from entities without uploading them.

overwrite = 'keep existing' class-attribute instance-attribute

If no class specific overwrite setting is set, this setting is used.

overwrite_per_class = None class-attribute instance-attribute

A list of OverwriteClassParam objects. If a class specific overwrite setting is set, this setting is used.

parallel = None class-attribute instance-attribute

If set to True, the entities are stored in parallel.

remove_empty = True class-attribute instance-attribute

If true, remove key with an empty string value from the jsondata.

verify_write = True class-attribute instance-attribute

If set to True, the existence of every edited page is queried after the upload. A page that does not exist afterwards is reported in StoreEntityResult.failed instead of StoreEntityResult.pages. This costs one additional API request per 50 edited pages, and one further request some seconds later if a page is reported as missing. If the query itself fails, the pages are reported as stored and an error is logged. Has no effect if 'offline' is True.

StoreEntityPartialError

Bases: Exception

Raised by store_entity() when one or more entities could not be stored.

Carries the partial StoreEntityResult so callers can learn exactly which entities were written (stored / result.pages) and which failed (failed / result.failed) without a separate existence query.

Source code in src/osw/core.py
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
class StoreEntityPartialError(Exception):
    """Raised by store_entity() when one or more entities could not be stored.

    Carries the partial ``StoreEntityResult`` so callers can learn exactly which
    entities were written (``stored`` / ``result.pages``) and which failed
    (``failed`` / ``result.failed``) without a separate existence query.
    """

    def __init__(self, result: OSW.StoreEntityResult):
        self.result = result
        self.stored = list(result.pages.keys())
        self.failed = result.failed
        total = len(result.pages) + len(result.failed)
        failed_titles = ", ".join(result.failed.keys())
        super().__init__(
            f"store_entity failed for {len(result.failed)} of {total} "
            f"entities: {failed_titles}"
        )

StoreEntityResult

Bases: OswBaseModel

Result of store_entity()

Source code in src/osw/core.py
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
class StoreEntityResult(OswBaseModel):
    """Result of store_entity()"""

    change_id: str
    """The ID of the change"""
    pages: Dict[str, WtPage]
    """The pages that have been successfully stored, keyed by full page title.
    On partial failure this contains only the successfully-stored pages."""
    failed: Dict[str, Exception] = {}
    """Entities that could not be stored, mapped to the exception that caused the
    failure. Empty on full success. The key is the full page title where one could
    be determined. For an entity whose title or namespace could not be resolved it
    falls back to the entity name, then to its uuid, then to 'unknown', so do not
    parse this key as 'namespace:title'."""

    class Config:
        arbitrary_types_allowed = True

change_id instance-attribute

The ID of the change

failed = {} class-attribute instance-attribute

Entities that could not be stored, mapped to the exception that caused the failure. Empty on full success. The key is the full page title where one could be determined. For an entity whose title or namespace could not be resolved it falls back to the entity name, then to its uuid, then to 'unknown', so do not parse this key as 'namespace:title'.

pages instance-attribute

The pages that have been successfully stored, keyed by full page title. On partial failure this contains only the successfully-stored pages.

check_dependencies(dependencies) staticmethod

Check if the dependencies are installed in the osw.model.entity module.

Parameters:

Name Type Description Default
dependencies Dict[str, str]

A dictionary with the keys being the names of the dependencies and the values being the full page name (IRI) of the dependencies.

required
Source code in src/osw/core.py
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
@staticmethod
def check_dependencies(dependencies: Dict[str, str]) -> List[str]:
    """Check if the dependencies are installed in the osw.model.entity module.

    Parameters
    ----------
    dependencies
        A dictionary with the keys being the names of the dependencies and the
        values being the full page name (IRI) of the dependencies.
    """
    return [dep for dep in dependencies if not hasattr(model, dep)]

close_connection()

Close the connection to the OSL instance.

Source code in src/osw/core.py
308
309
310
def close_connection(self):
    """Close the connection to the OSL instance."""
    self.mw_site.connection.close()

delete_entity(entity, comment=None)

Deletes the given entity/entities from the OSW instance.

Source code in src/osw/core.py
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
def delete_entity(
    self,
    entity: Union[OswBaseModel, List[OswBaseModel], DeleteEntityParam],
    comment: str = None,
):
    """Deletes the given entity/entities from the OSW instance."""
    if not isinstance(entity, OSW.DeleteEntityParam):
        entity = OSW.DeleteEntityParam(entities=entity)
    if comment is not None:
        entity.comment = comment

    def delete_entity_(entity_, comment_: str = None):
        """Deletes the given entity from the OSW instance.

        Parameters
        ----------
        entity_:
            The dataclass instance to delete
        comment_:
            Command for the change log, by default None
        """
        title_ = None
        namespace_ = None
        if hasattr(entity_, "meta"):
            if entity_.meta and entity_.meta.wiki_page:
                if entity_.meta.wiki_page.title:
                    title_ = entity_.meta.wiki_page.title
                if entity_.meta.wiki_page.namespace:
                    namespace_ = entity_.meta.wiki_page.namespace
        if namespace_ is None:
            namespace_ = get_namespace(entity_)
        if title_ is None:
            title_ = OSW.get_osw_id(entity_.uuid)
        if namespace_ is None or title_ is None:
            _logger.error("Unsupported entity type")
            return
        entity_title = namespace_ + ":" + title_
        page = self.site.get_page(WtSite.GetPageParam(titles=[entity_title])).pages[
            0
        ]

        if page.exists:
            page.delete(comment_)
            _logger.info("Entity deleted: " + page.get_url())
        else:
            _logger.warning(f"Entity '{entity_title}' does not exist!")

    if entity.parallel:
        _ = parallelize(
            delete_entity_,
            entity.entities,
            flush_at_end=entity.debug,
            comment_=entity.comment,
        )
    else:
        _ = [delete_entity_(e, entity.comment) for e in entity.entities]

ensure_dependencies(dependencies)

Ensure that the dependencies are installed in the osw.model.entity module.

Parameters:

Name Type Description Default
dependencies Dict[str, str]

A dictionary with the keys being the names of the dependencies and the values being the full page name (IRI) of the dependencies.

required
Source code in src/osw/core.py
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
def ensure_dependencies(self, dependencies: Dict[str, str]):
    """Ensure that the dependencies are installed in the osw.model.entity module.

    Parameters
    ----------
    dependencies
        A dictionary with the keys being the names of the dependencies and the
        values being the full page name (IRI) of the dependencies.
    """
    if self.check_dependencies(dependencies):
        self.install_dependencies(dependencies)

export_jsonld(params)

Exports the given entity/entities as JSON-LD.

Source code in src/osw/core.py
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
def export_jsonld(self, params: ExportJsonLdParams) -> ExportJsonLdResult:
    """Exports the given entity/entities as JSON-LD."""

    if params.resolve_context:
        jsonld.set_document_loader(
            self.site.get_jsonld_context_loader(params.context_loader_config)
        )

    documents = []
    graph_document = {"@graph": []}
    graph = None
    if params.build_rdf_graph:
        graph = rdflib.Graph()
        prefixes = self.site.get_prefix_dict()
        for prefix in prefixes:
            graph.bind(prefix, prefixes[prefix])

    for e in params.entities:
        data = json.loads(e.json(exclude_none=True, indent=4, ensure_ascii=False))

        data["@context"] = []
        if params.id_keys is not None:
            # append "@id" mappings to the context in an additional object
            id_mapping = {}
            for k in params.id_keys:
                id_mapping[k] = "@id"
            data["@context"].append(id_mapping)
        if params.context is None:
            for t in e.type:
                data["@context"].append("/wiki/" + t)
            if params.context is not None:
                data["@context"].append(params.context)
        else:
            data["@context"].append(self.site.get_jsonld_context_prefixes())
            if isinstance(params.context, list):
                data["@context"].extend(params.context)
            else:
                data["@context"].append(params.context)
        if params.additional_context is not None:
            if data["@context"] is None:
                data["@context"] = []
            elif not isinstance(data["@context"], list):
                data["@context"] = [data["@context"]]
            data["@context"].append(params.additional_context)

        # if none of the id_keys is found, use the full title
        if not any(k in data for k in params.id_keys):
            data["@id"] = get_full_title(e)

        if params.resolve_context:
            graph_document["@graph"].append(jsonld.expand(data))
            if params.mode == "expand":
                data = jsonld.expand(data)
                if isinstance(data, list) and len(data) > 0:
                    data = data[0]
            elif params.mode == "flatten":
                data = jsonld.flatten(data)
            elif params.mode == "compact":
                # data = jsonld.expand(data)
                # if isinstance(data, list): data = data[0]
                data = jsonld.compact(
                    data,
                    data["@context"] if params.context is None else params.context,
                )
            elif params.mode == "frame":
                data = jsonld.frame(
                    data,
                    (
                        {"@context": data["@context"]}
                        if params.frame is None
                        else params.frame
                    ),
                )

            if params.build_rdf_graph:
                graph.parse(data=json.dumps(data), format="json-ld")

        documents.append(data)

    result = OSW.ExportJsonLdResult(
        documents=documents, graph_document=graph_document, graph=graph
    )
    return result

fetch_schema(fetchSchemaParam=None)

Loads the given schemas from the OSW instance and auto-generates python datasclasses within osw.model.entity from it

Parameters:

Name Type Description Default
fetchSchemaParam FetchSchemaParam

See FetchSchemaParam, by default None

None
Source code in src/osw/core.py
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
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
        ),
    )

get_osw_id(uuid) staticmethod

Generates a OSW-ID based on the given uuid by prefixing "OSW" and removing all '-' from the uuid-string

Parameters:

Name Type Description Default
uuid Union[str, UUID]

uuid object, e.g. UUID("2ea5b605-c91f-4e5a-9559-3dff79fdd4a5")

required

Returns:

Type Description
OSW-ID string, e.g. OSW2ea5b605c91f4e5a95593dff79fdd4a5
Source code in src/osw/core.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
@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("-", "")

get_uuid(osw_id) staticmethod

Returns the uuid for a given OSW-ID. Kept for backwards compatibility, the implementation lives in osw.utils.wiki.get_uuid()

Parameters:

Name Type Description Default
osw_id str

OSW-ID string, e.g. OSW2ea5b605c91f4e5a95593dff79fdd4a5, with or without file suffixes, e.g. OSW2ea5b605c91f4e5a95593dff79fdd4a5.drawio.png

required

Returns:

Type Description
uuid object, e.g. UUID("2ea5b605-c91f-4e5a-9559-3dff79fdd4a5")
Source code in src/osw/core.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
@staticmethod
def get_uuid(osw_id: str) -> UUID:
    """Returns the uuid for a given OSW-ID. Kept for backwards compatibility,
    the implementation lives in osw.utils.wiki.get_uuid()

    Parameters
    ----------
    osw_id
        OSW-ID string, e.g. OSW2ea5b605c91f4e5a95593dff79fdd4a5, with or
        without file suffixes, e.g.
        OSW2ea5b605c91f4e5a95593dff79fdd4a5.drawio.png

    Returns
    -------
        uuid object, e.g. UUID("2ea5b605-c91f-4e5a-9559-3dff79fdd4a5")
    """
    return get_uuid_from_osw_id(osw_id)

install_dependencies(dependencies=None, mode='append', policy='force')

Installs data models, listed in the dependencies, in the osw.model.entity module.

Parameters:

Name Type Description Default
dependencies Dict[str, str]

A dictionary with the keys being the names of the dependencies and the values being the full page name (IRI) of the dependencies.

None
mode str

The mode to use when loading the dependencies. Default is 'append', which will keep existing data models and only load the missing ones. The mode 'replace' will replace all existing data models with the new ones.

'append'
policy str

The policy to use when loading the dependencies. Default is 'force', which will always load the dependencies. If policy is 'if-missing', dependencies will only be loaded if they are not already installed. This may lead to outdated dependencies, if the dependencies have been updated on the server. If policy is 'if-outdated', dependencies will only be loaded if they were updated on the server. (not implemented yet)

'force'
Source code in src/osw/core.py
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
def install_dependencies(
    self,
    dependencies: Dict[str, str] = None,
    mode: str = "append",
    policy: str = "force",
):
    """Installs data models, listed in the dependencies, in the osw.model.entity
    module.

    Parameters
    ----------
    dependencies
        A dictionary with the keys being the names of the dependencies and the
        values being the full page name (IRI) of the dependencies.
    mode
        The mode to use when loading the dependencies. Default is 'append',
        which will keep existing data models and only load the missing ones. The
        mode 'replace' will replace all existing data models with the new ones.
    policy
        The policy to use when loading the dependencies. Default is 'force',
        which will always load the dependencies. If policy is 'if-missing',
        dependencies will only be loaded if they are not already installed.
        This may lead to outdated dependencies, if the dependencies have been
        updated on the server. If policy is 'if-outdated', dependencies will only
        be loaded if they were updated on the server. (not implemented yet)
    """
    if dependencies is None:
        if default_params.dependencies is None:
            raise ValueError(
                "No 'dependencies' parameter was passed to "
                "install_dependencies() and "
                "osw.defaults.params.dependencies was not set!"
            )
        dependencies = default_params.dependencies
    schema_fpts = []
    for k, v in dependencies.items():
        if policy != "if-missing" or not hasattr(model, k):
            schema_fpts.append(v)
        if policy == "if-outdated":
            raise NotImplementedError(
                "The policy 'if-outdated' is not implemented yet."
            )
    schema_fpts = list(set(schema_fpts))
    for schema_fpt in schema_fpts:
        if not schema_fpt.count(":") == 1:
            raise ValueError(
                f"Full page title '{schema_fpt}' does not have the correct format. "
                "It should be 'Namespace:Name'."
            )
    self.fetch_schema(OSW.FetchSchemaParam(schema_title=schema_fpts, mode=mode))

load_entity(entity_title)

load_entity(entity_title: str) -> model.Entity
load_entity(entity_title: List[str]) -> List[model.Entity]
load_entity(
    entity_title: LoadEntityParam,
) -> LoadEntityResult

Loads the entity with the given wiki page name from the OSW instance. Creates an instance of the class specified by the "type" attribute, default model.Entity. An instance of model.Entity can be cast to any subclass with .cast(model.) .

Parameters:

Name Type Description Default
entity_title Union[str, List[str], LoadEntityParam]

the wiki page name

required

Returns:

Type Description
the dataclass instance if only a single title is given

a list of dataclass instances if a list of titles is given a LoadEntityResult instance if a LoadEntityParam is given

Source code in src/osw/core.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
def load_entity(
    self, entity_title: Union[str, List[str], LoadEntityParam]
) -> Union[model.Entity, List[model.Entity], LoadEntityResult]:
    """Loads the entity with the given wiki page name from the OSW instance.
    Creates an instance of the class specified by the "type" attribute, default
    model.Entity. An instance of model.Entity can be cast to any subclass with
    .cast(model.<class>) .

    Parameters
    ----------
    entity_title
        the wiki page name

    Returns
    -------
        the dataclass instance if only a single title is given
        a list of dataclass instances if a list of titles is given
        a LoadEntityResult instance if a LoadEntityParam is given
    """
    if isinstance(entity_title, str):
        param = OSW.LoadEntityParam(titles=[entity_title])
    elif isinstance(entity_title, list):
        param = OSW.LoadEntityParam(titles=entity_title)
    else:
        param = entity_title

    if param.model_to_use:
        _logger.info(f"Using schema {param.model_to_use.__name__} to create entity")

    # store original cache state
    cache_state = self.site.get_cache_enabled()
    if param.disable_cache:
        self.site.disable_cache()
    if not cache_state and param.disable_cache:
        # enable cache to speed up loading
        self.site.enable_cache()

    # the restore runs in a finally block so that an exception from any of the
    # calls below cannot leave the cache enabled for the rest of the process
    try:
        entities = []
        pages = self.site.get_page(
            WtSite.GetPageParam(
                titles=param.titles, offline_pages=param.offline_pages
            )
        ).pages
        for page in pages:
            entity = None
            schemas = []
            schemas_fetched = True
            jsondata = page.get_slot_content("jsondata")
            if param.remove_empty:
                remove_empty(jsondata)
            if jsondata:
                for category in jsondata["type"]:
                    schema = (
                        self.site
                        .get_page(
                            WtSite.GetPageParam(
                                titles=[category], offline_pages=param.offline_pages
                            )
                        )
                        .pages[0]
                        .get_slot_content("jsonschema")
                    )
                    schemas.append(schema)
                    # generate model if not already exists
                    cls_name: str = schema["title"]
                    # If a schema_to_use is provided, we do not need to check if
                    #  the model exists
                    if not param.model_to_use:
                        if not hasattr(model, cls_name):
                            if param.autofetch_schema:
                                self.fetch_schema(
                                    OSW.FetchSchemaParam(
                                        schema_title=category,
                                        mode="append",
                                        offline_pages=param.offline_pages,
                                    )
                                )
                        if not hasattr(model, cls_name):
                            schemas_fetched = False
                            _logger.error(
                                f"Model {cls_name} not found. Schema {category} "
                                f"needs to be fetched first."
                            )
            if not schemas_fetched:
                continue

            try:
                if param.model_to_use:
                    entity: model.OswBaseModel = param.model_to_use(**jsondata)

                elif len(schemas) == 0:
                    _logger.error("no schema defined")

                elif len(schemas) == 1:
                    cls: Type[model.Entity] = getattr(model, schemas[0]["title"])
                    entity: model.Entity = cls(**jsondata)

                else:
                    bases = []
                    for schema in schemas:
                        bases.append(getattr(model, schema["title"]))
                    cls = create_model("Test", __base__=tuple(bases))
                    entity: model.Entity = cls(**jsondata)
            except Exception as e:
                _logger.error(f"Error creating entity from page {page.title}: {e}")
                # legacy: `entity` is annotated as OswBaseModel and Entity above
                entity = None  # ty: ignore[conflicting-declarations]

            if entity is not None:
                # make sure we do not override existing metadata
                if not hasattr(entity, "meta") or entity.meta is None:
                    entity.meta = model.Meta()
                if (
                    not hasattr(entity.meta, "wiki_page")
                    or entity.meta.wiki_page is None
                ):
                    entity.meta.wiki_page = model.WikiPage()
                entity.meta.wiki_page.namespace = namespace_from_full_title(
                    page.title
                )
                entity.meta.wiki_page.title = title_from_full_title(page.title)

                entities.append(entity)
    finally:
        # restore original cache state
        if cache_state:
            self.site.enable_cache()
        else:
            self.site.disable_cache()

    if isinstance(entity_title, str):  # single title
        if len(entities) >= 1:
            return entities[0]
        else:
            return None
    if isinstance(entity_title, list):  # list of titles
        return entities
    if isinstance(entity_title, OSW.LoadEntityParam):  # LoadEntityParam
        return OSW.LoadEntityResult(entities=entities)

register_schema(schema_registration)

Registers a new or updated schema in OSW by creating the corresponding category page.

Parameters:

Name Type Description Default
schema_registration SchemaRegistration

see SchemaRegistration

required
Source code in src/osw/core.py
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
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:
        _logger.error("Unsupported entity type")
        return

    page.edit()
    _logger.info("Entity stored at " + page.get_url())

sort_list_of_entities_by_class(entities, exclude_typeless=True, raise_error=False) staticmethod

Sorts a list of entities by class name and type.

Parameters:

Name Type Description Default
entities List[OswBaseModel]

List of entities to be sorted

required
exclude_typeless bool

Exclude entities, which are instances of a class that does not define a field 'type'

True
raise_error bool

Raise an error if an entity can not be processed because it is an instance of class that does not define a field 'type'

False
Source code in src/osw/core.py
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
@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:
                _logger.warning(
                    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)

store_entity(param)

stores the given dataclass instance as OSW page by calling BaseModel.json()

Parameters:

Name Type Description Default
param Union[StoreEntityParam, OswBaseModel, List[OswBaseModel]]

StoreEntityParam, the dataclass instance or a list of instances

required
Source code in src/osw/core.py
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
def store_entity(
    self, param: Union[StoreEntityParam, OswBaseModel, List[OswBaseModel]]
) -> StoreEntityResult:
    """stores the given dataclass instance as OSW page by calling BaseModel.json()

    Parameters
    ----------
    param:
        StoreEntityParam, the dataclass instance or a list of instances
    """
    if isinstance(param, list):
        param = OSW.StoreEntityParam(entities=param)
    elif not isinstance(param, OSW.StoreEntityParam):
        # Accept any OswBaseModel / Entity / Controller instance
        param = OSW.StoreEntityParam(entities=[param])
    if not isinstance(param.entities, list):
        param.entities = [param.entities]

    param: OSW.StoreEntityParam = param

    max_index = len(param.entities)
    created_pages = {}
    edited_titles = set()
    """Titles of the pages an edit was sent for, to be verified below."""

    meta_category_templates = {}
    if param.namespace == "Category":
        meta_category_titles = param.meta_category_title
        if not isinstance(meta_category_titles, list):
            meta_category_titles = [meta_category_titles]
        meta_category_template_strs = {}
        # We have to do this iteratively to support meta categories inheritance
        while meta_category_titles is not None and len(meta_category_titles) > 0:
            meta_categories = self.site.get_page(
                WtSite.GetPageParam(titles=meta_category_titles)
            ).pages
            for meta_category in meta_categories:
                meta_category_template_strs[meta_category.title] = (
                    meta_category.get_slot_content("schema_template")
                )

            meta_category_titles = meta_category.get_slot_content("jsondata").get(
                "subclass_of"
            )

        for title in meta_category_template_strs.keys():
            meta_category_template_str = meta_category_template_strs[title]
            if meta_category_template_str:
                meta_category_templates[title] = compile_handlebars_template(
                    meta_category_template_str
                )
        # inverse order to have the most generic template first
        meta_category_templates = dict(reversed(meta_category_templates.items()))

    def store_entity_(
        entity_: model.Entity,
        namespace_: str = None,
        index: int = None,
        overwrite_class_param: OSW.OverwriteClassParam = None,
    ) -> None:
        try:
            title_ = get_title(entity_)
        except Exception as e:
            entity_name = getattr(entity_, "name", None) or getattr(
                entity_, "uuid", "unknown"
            )
            # raise instead of returning: a plain return is not an exception,
            # so the collector loop below would record the entity in neither
            # created_pages nor failed and store_entity would report success
            raise ValueError(
                f"Error getting title for entity '{entity_name}': {e}"
            ) from e
        if namespace_ is None:
            namespace_ = get_namespace(entity_)
        if namespace_ is None or title_ is None:
            entity_name = getattr(entity_, "name", None) or getattr(
                entity_, "uuid", "unknown"
            )
            raise TypeError(
                f"Unsupported entity type: namespace={namespace_}, "
                f"title={title_}, entity name='{entity_name}', "
                f"type={type(entity_).__name__}"
            )
        if overwrite_class_param is None:
            raise TypeError("'overwrite_class_param' must not be None!")
        entity_title = namespace_ + ":" + title_
        page = self._apply_overwrite_policy(
            OSW._ApplyOverwriteParam(
                page=WtPage(
                    wtSite=self.site, title=entity_title, do_init=not param.offline
                ),
                entity=entity_,
                namespace=namespace_,
                policy=overwrite_class_param,
                remove_empty=param.remove_empty,
                debug=param.debug,
                offline=param.offline,
            )
        )
        # _apply_overwrite_policy() returned the remote page untouched. The
        # schema regeneration below writes the jsonschema slot regardless of
        # the policy, which would edit a page the caller asked to keep.
        kept_existing = (
            page.exists
            # mirrors the branch order of _apply_overwrite_policy(), which
            # tests 'offline is True' before it tests 'keep existing'
            and param.offline is not True
            and overwrite_class_param.overwrite
            == AddOverwriteClassOptions.keep_existing
        )
        if not kept_existing and len(meta_category_templates.keys()) > 0:
            generated_schemas = {}
            try:
                jsondata = page.get_slot_content("jsondata")
                if param.remove_empty:
                    remove_empty(jsondata)

                for key in meta_category_templates:
                    meta_category_template = meta_category_templates[key]
                    schema_str = eval_compiled_handlebars_template(
                        meta_category_template,
                        escape_json_strings(jsondata),
                        {
                            "_page_title": entity_title,  # Legacy
                            "_current_subject_": entity_title,
                        },
                    )
                    generated_schemas[key] = json.loads(schema_str)
            except Exception as e:
                _logger.error(
                    f"Schema generation from template failed for {entity_}: {e}"
                )

            mode = AggregateGeneratedSchemasParamMode.ROOT_LEVEL
            # Put generated schema in definitions section,
            #  currently only enabled for Characteristics
            if hasattr(model, "CharacteristicType") and isinstance(
                entity_, model.CharacteristicType
            ):
                mode = AggregateGeneratedSchemasParamMode.DEFINITIONS_SECTION

            new_schema = aggregate_generated_schemas(
                AggregateGeneratedSchemasParam(
                    schema=page.get_slot_content("jsonschema"),
                    generated_schemas=generated_schemas,
                    mode=mode,
                )
            ).aggregated_schema
            page.set_slot_content("jsonschema", new_schema)
        if param.offline is False and not kept_existing:
            page.edit(
                param.edit_comment, bot_edit=param.bot_edit
            )  # will set page.changed if the content of the page has changed
            edited_titles.add(page.title)
        if not param.offline and page.changed:
            if index is None:
                _logger.info(f"Entity stored at '{page.get_url()}'.")
            else:
                _logger.info(
                    f"({index + 1}/{max_index}) Entity stored at "
                    f"'{page.get_url()}'."
                )
        created_pages[page.title] = page

    sorted_entities = OSW.sort_list_of_entities_by_class(param.entities)
    _logger.info(
        "Entities to be uploaded have been sorted according to their type.\n"
        "If you would like to overwrite existing entities or properties, "
        "pass a StoreEntityParam to store_entity() with "
        "attribute 'overwrite' or 'overwrite_per_class' set to, e.g., "
        "True."
    )

    class UploadObject(BaseModel):
        entity: OswBaseModel
        # Actually model.Entity but this causes the "type" error
        namespace: Optional[str]
        index: int
        overwrite_class_param: OSW.OverwriteClassParam

    upload_object_list: List[UploadObject] = []

    upload_index = 0
    for class_type, entities in sorted_entities.by_type.items():
        # Try to get a class specific overwrite setting
        class_param = param._overwrite_per_class["by type"].get(class_type, None)
        if class_param is None:
            entity_model = entities[0].__class__
            class_param = OSW.OverwriteClassParam(
                model=entity_model,
                overwrite=param.overwrite,
            )
            if param.debug:
                _logger.debug(
                    f"Now adding entities of class type '{class_type}' "
                    f"({entity_model.__name__}) to upload list. No class specific"
                    f" overwrite setting found. Using fallback option '"
                    f"{param.overwrite}' for all entities of this class."
                )
        for entity in entities:
            upload_object_list.append(
                UploadObject(
                    entity=entity,
                    namespace=param.namespace,
                    index=upload_index,
                    overwrite_class_param=class_param,
                )
            )
            upload_index += 1

    def handle_upload_object_(upload_object: UploadObject) -> None:
        # Let exceptions propagate: the caller collects them per entity below,
        # so a single failure neither aborts the batch nor is silently
        # swallowed. store_entity_ records a page in created_pages whenever it
        # reaches its last statement, which only means that nothing raised.
        # Whether the page exists afterwards is checked by the verification
        # step below.
        store_entity_(
            upload_object.entity,
            upload_object.namespace,
            upload_object.index,
            upload_object.overwrite_class_param,
        )

    def failure_title_(upload_object: UploadObject) -> str:
        """Best-effort full page title of a failed entity, for error reporting."""
        try:
            namespace = upload_object.namespace or get_namespace(
                upload_object.entity
            )
            return f"{namespace}:{get_title(upload_object.entity)}"
        except Exception:
            return (
                getattr(upload_object.entity, "name", None)
                or getattr(upload_object.entity, "uuid", None)
                or "unknown"
            )

    if param.parallel:
        # return_exceptions=True keeps results aligned with upload_object_list
        # and lets every entity be attempted even if some fail.
        results = parallelize(
            handle_upload_object_,
            upload_object_list,
            flush_at_end=param.debug,
            return_exceptions=True,
        )
    else:
        results = []
        for upload_object in upload_object_list:
            try:
                handle_upload_object_(upload_object)
                results.append(None)
            except Exception as e:
                results.append(e)

    failed: Dict[str, Exception] = {}
    for upload_object, result in zip(upload_object_list, results):
        if isinstance(result, Exception):
            title = failure_title_(upload_object)
            _logger.error(f"Error storing entity '{title}': {result}")
            failed[title] = result

    if param.verify_write and not param.offline and edited_titles:
        # An edit that raised no exception is not proof that the page exists:
        # a form or template driven creation step can reject the content
        # server-side. page.changed is no help either, it is True in that case.
        titles_to_verify = [
            title for title in edited_titles if title in created_pages
        ]
        try:
            missing_titles = self._get_missing_page_titles(titles_to_verify)
        except Exception as e:
            # A failed query is no evidence that the writes failed. Report it
            # and keep the pages, instead of discarding everything this call
            # has collected so far.
            missing_titles = []
            _logger.error(
                f"Could not verify {len(titles_to_verify)} stored pages, they "
                f"are reported as stored without being checked: {e}"
            )
        for title in missing_titles:
            error = OSW.PageNotCreatedError(title)
            _logger.error(f"Error storing entity '{title}': {error}")
            failed[title] = error
            del created_pages[title]

    store_result = OSW.StoreEntityResult(
        change_id=param.change_id, pages=created_pages, failed=failed
    )
    if failed:
        # Surface partial/total failure so callers cannot mistake a dropped
        # page for a success. The result (successes + failures) rides along.
        raise OSW.StoreEntityPartialError(store_result)
    return store_result

unregister_schema(schema_unregistration)

deletes the corresponding category page

Parameters:

Name Type Description Default
schema_unregistration SchemaUnregistration

see SchemaUnregistration

required
Source code in src/osw/core.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
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:
        _logger.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)