Skip to content

Wikibase Module API

Overview

The gkc.wikibase module is the package-facing access layer for package-owned Wikibase runtime contracts.

It exposes the canonical datatype registry used to normalize datatype semantics across validation, payload shaping, and ontology initialization flows.

Quick Start

from gkc.wikibase import (
    build_wikibase_init_index,
    get_wikibase_datatype_spec,
    list_wikibase_datatypes,
)

spec = get_wikibase_datatype_spec("wikibase-item")
init_index = build_wikibase_init_index()

print(spec.ontology_uri)
print(spec.datavalue_type)
print(spec.entity_value_kind)
print(list_wikibase_datatypes())
print(init_index.properties["instance_of"].datatype)
print(init_index.items["entity_profile"].subclass_of)

The module now exposes both package-owned datatype registry helpers and package-owned Wikibase init helpers.

API Reference

gkc.wikibase

Wikibase-specific runtime helpers and package-owned registries.

MetaWikibaseCompiledEntity dataclass

Compiled symbolic Wikibase payload for one init-fixture entity.

Source code in gkc/wikibase.py
76
77
78
79
80
81
82
83
84
85
86
@dataclass(frozen=True)
class MetaWikibaseCompiledEntity:
    """Compiled symbolic Wikibase payload for one init-fixture entity."""

    key: str
    kind: str
    internal_name_identifier: str
    entity_type: str
    datatype: str | None
    claims: dict[str, list[dict[str, Any]]]
    payload: dict[str, Any]

MetaWikibaseInitEntity dataclass

Normalized entity entry from the package-owned Meta-Wikibase init fixture.

Source code in gkc/wikibase.py
32
33
34
35
36
37
38
39
40
41
42
43
44
@dataclass(frozen=True)
class MetaWikibaseInitEntity:
    """Normalized entity entry from the package-owned Meta-Wikibase init fixture."""

    key: str
    kind: str
    label: str
    description: str
    internal_name_identifier: str
    datatype: str | None = None
    instance_of: str | None = None
    subclass_of: str | None = None
    attributes: dict[str, Any] | None = None

MetaWikibaseInitIndex dataclass

Indexed access surface for the package-owned Meta-Wikibase init fixture.

Source code in gkc/wikibase.py
47
48
49
50
51
52
53
54
55
@dataclass(frozen=True)
class MetaWikibaseInitIndex:
    """Indexed access surface for the package-owned Meta-Wikibase init fixture."""

    metadata: MetaWikibaseInitMetadata
    entities: dict[str, MetaWikibaseInitEntity]
    properties: dict[str, MetaWikibaseInitEntity]
    items: dict[str, MetaWikibaseInitEntity]
    by_internal_name_identifier: dict[str, MetaWikibaseInitEntity]

MetaWikibaseInitMetadata dataclass

Package-owned metadata for the Meta-Wikibase init fixture.

Source code in gkc/wikibase.py
21
22
23
24
25
26
27
28
29
@dataclass(frozen=True)
class MetaWikibaseInitMetadata:
    """Package-owned metadata for the Meta-Wikibase init fixture."""

    name: str
    description: str
    source: str
    reference: str
    internal_name_identifier_prefix: str

MetaWikibaseSeedCompilation dataclass

Compiled symbolic Wikibase payload set derived from the init fixture.

Source code in gkc/wikibase.py
89
90
91
92
93
94
95
@dataclass(frozen=True)
class MetaWikibaseSeedCompilation:
    """Compiled symbolic Wikibase payload set derived from the init fixture."""

    metadata: MetaWikibaseInitMetadata
    entities: dict[str, MetaWikibaseCompiledEntity]
    by_internal_name_identifier: dict[str, MetaWikibaseCompiledEntity]

MetaWikibaseSeedPlan dataclass

Dry-run baseline plan for the package-owned Meta-Wikibase seed.

Source code in gkc/wikibase.py
113
114
115
116
117
118
@dataclass(frozen=True)
class MetaWikibaseSeedPlan:
    """Dry-run baseline plan for the package-owned Meta-Wikibase seed."""

    metadata: MetaWikibaseInitMetadata
    operations: list[MetaWikibaseSeedPlanEntry]

MetaWikibaseSeedPlanEntry dataclass

One dry-run baseline action derived from the compiled init fixture.

Source code in gkc/wikibase.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
@dataclass(frozen=True)
class MetaWikibaseSeedPlanEntry:
    """One dry-run baseline action derived from the compiled init fixture."""

    action: str
    key: str
    internal_name_identifier: str
    entity_type: str
    datatype: str | None
    payload: dict[str, Any]
    current_entity_id: str | None = None
    changed_fields: list[str] | None = None
    details: str | None = None

MetaWikibaseSemanticAnchorContract dataclass

Compiled required semantic-anchor contract derived from the init fixture.

Source code in gkc/wikibase.py
68
69
70
71
72
73
@dataclass(frozen=True)
class MetaWikibaseSemanticAnchorContract:
    """Compiled required semantic-anchor contract derived from the init fixture."""

    internal_name_identifier_prefix: str
    requirements: dict[str, MetaWikibaseSemanticAnchorRequirement]

MetaWikibaseSemanticAnchorRequirement dataclass

Required internal semantic anchor compiled from the init fixture.

Source code in gkc/wikibase.py
58
59
60
61
62
63
64
65
@dataclass(frozen=True)
class MetaWikibaseSemanticAnchorRequirement:
    """Required internal semantic anchor compiled from the init fixture."""

    key: str
    internal_name_identifier: str
    kind: str
    datatype: str | None = None

WikibaseDatatypeSpec dataclass

Canonical runtime specification for one Wikibase datatype.

Source code in gkc/wikibase.py
121
122
123
124
125
126
127
@dataclass(frozen=True)
class WikibaseDatatypeSpec:
    """Canonical runtime specification for one Wikibase datatype."""

    ontology_uri: str
    datavalue_type: str
    entity_value_kind: str | None = None

build_wikibase_init_index(document=None)

Build a typed index over the package-owned Meta-Wikibase init fixture.

Source code in gkc/wikibase.py
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
def build_wikibase_init_index(
    document: dict[str, Any] | None = None,
) -> MetaWikibaseInitIndex:
    """Build a typed index over the package-owned Meta-Wikibase init fixture."""

    normalized_document = (
        load_wikibase_init_document()
        if document is None
        else normalize_wikibase_init_document(document)
    )
    metadata_payload = normalized_document["metadata"]
    metadata = MetaWikibaseInitMetadata(
        name=str(metadata_payload.get("name", "")).strip(),
        description=str(metadata_payload.get("description", "")).strip(),
        source=str(metadata_payload.get("source", "")).strip(),
        reference=str(metadata_payload.get("reference", "")).strip(),
        internal_name_identifier_prefix=str(
            metadata_payload.get("internal_name_identifier_prefix", "_")
        ),
    )

    entities_block = normalized_document["entities"]
    entities: dict[str, MetaWikibaseInitEntity] = {}
    properties: dict[str, MetaWikibaseInitEntity] = {}
    items: dict[str, MetaWikibaseInitEntity] = {}
    by_internal_name_identifier: dict[str, MetaWikibaseInitEntity] = {}

    for key, payload in entities_block.items():
        kind = str(payload.get("kind", "")).strip()
        internal_name_identifier = f"{metadata.internal_name_identifier_prefix}{key}"
        attributes = {
            attr_key: attr_value
            for attr_key, attr_value in payload.items()
            if attr_key
            not in {
                "kind",
                "label",
                "description",
                "datatype",
                "instance_of",
                "subclass_of",
            }
        }
        entity = MetaWikibaseInitEntity(
            key=key,
            kind=kind,
            label=str(payload.get("label", "")).strip(),
            description=str(payload.get("description", "")).strip(),
            internal_name_identifier=internal_name_identifier,
            datatype=payload.get("datatype"),
            instance_of=payload.get("instance_of"),
            subclass_of=payload.get("subclass_of"),
            attributes=attributes or None,
        )
        entities[key] = entity
        by_internal_name_identifier[internal_name_identifier] = entity
        if kind == "property":
            properties[key] = entity
        elif kind == "item":
            items[key] = entity

    return MetaWikibaseInitIndex(
        metadata=metadata,
        entities=entities,
        properties=properties,
        items=items,
        by_internal_name_identifier=by_internal_name_identifier,
    )

build_wikibase_semantic_anchor_contract(document=None, *, internal_name_identifier_prefix=None)

Compile the package-owned init fixture into a required anchor contract.

Source code in gkc/wikibase.py
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
def build_wikibase_semantic_anchor_contract(
    document: dict[str, Any] | None = None,
    *,
    internal_name_identifier_prefix: str | None = None,
) -> MetaWikibaseSemanticAnchorContract:
    """Compile the package-owned init fixture into a required anchor contract."""

    index = build_wikibase_init_index(document)
    prefix = (
        internal_name_identifier_prefix
        if isinstance(internal_name_identifier_prefix, str)
        and internal_name_identifier_prefix
        else index.metadata.internal_name_identifier_prefix
    )

    requirements: dict[str, MetaWikibaseSemanticAnchorRequirement] = {}
    for entity in index.entities.values():
        requirement = MetaWikibaseSemanticAnchorRequirement(
            key=entity.key,
            internal_name_identifier=f"{prefix}{entity.key}",
            kind=entity.kind,
            datatype=entity.datatype if entity.kind == "property" else None,
        )
        requirements[requirement.internal_name_identifier] = requirement

    return MetaWikibaseSemanticAnchorContract(
        internal_name_identifier_prefix=prefix,
        requirements=requirements,
    )

canonicalize_wikibase_datatype(datatype, *, strict=False)

Normalize a Wikibase datatype token to its canonical runtime spelling.

Source code in gkc/wikibase.py
228
229
230
231
232
233
234
235
236
237
238
239
def canonicalize_wikibase_datatype(
    datatype: str,
    *,
    strict: bool = False,
) -> str:
    """Normalize a Wikibase datatype token to its canonical runtime spelling."""

    normalized = datatype.strip()
    canonical = _build_wikibase_datatype_aliases().get(normalized, normalized)
    if strict and canonical not in load_wikibase_datatype_registry():
        raise KeyError(f"Unknown Wikibase datatype: {canonical}")
    return canonical

compare_wikibase_entity_views(required_view, current_view, *, issues=None)

Compare canonical required and current views and return changed-field codes.

Source code in gkc/wikibase.py
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
def compare_wikibase_entity_views(
    required_view: dict[str, Any],
    current_view: dict[str, Any],
    *,
    issues: list[str] | None = None,
) -> list[str]:
    """Compare canonical required and current views and return changed-field codes."""

    changed_fields: list[str] = []
    for field_name in _declared_meta_wikibase_fields(required_view):
        if field_name == "claims":
            changed_fields.extend(
                _compare_meta_wikibase_claim_field_changes(
                    required_view.get("claims"),
                    current_view.get("claims"),
                )
            )
            continue
        if required_view.get(field_name) != current_view.get(field_name):
            changed_fields.append(field_name)

    for issue in issues or []:
        if issue not in changed_fields:
            changed_fields.append(issue)

    return changed_fields

compile_wikibase_seed(document=None, *, label_language=None)

Compile the init fixture into symbolic Wikibase JSON payloads.

The compiled payloads use internal name identifiers such as _instance_of as unresolved placeholders for entity references. This keeps the output in a deterministic dry-run form that can be inspected before any live baseline orchestration resolves or writes entities.

Source code in gkc/wikibase.py
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
def compile_wikibase_seed(
    document: dict[str, Any] | None = None,
    *,
    label_language: str | None = None,
) -> MetaWikibaseSeedCompilation:
    """Compile the init fixture into symbolic Wikibase JSON payloads.

    The compiled payloads use internal name identifiers such as ``_instance_of``
    as unresolved placeholders for entity references. This keeps the output in a
    deterministic dry-run form that can be inspected before any live baseline
    orchestration resolves or writes entities.
    """

    from gkc.bottler import (
        ClaimBuilder,
        DataTypeTransformer,
        EntityShellBuilder,
        SnakBuilder,
    )

    index = build_wikibase_init_index(document)
    entity_shell_builder = EntityShellBuilder()
    claim_builder = ClaimBuilder(SnakBuilder(DataTypeTransformer()))
    resolved_label_language = _resolve_meta_wikibase_label_language(label_language)

    compiled_entities: dict[str, MetaWikibaseCompiledEntity] = {}
    compiled_by_internal_name_identifier: dict[str, MetaWikibaseCompiledEntity] = {}

    for entity in index.entities.values():
        symbolic_claims = _compile_meta_wikibase_entity_claims(
            entity,
            index=index,
            claim_builder=claim_builder,
        )

        shell = entity_shell_builder.build_entity_shell(
            {
                "labels": {resolved_label_language: entity.label},
                "descriptions": {resolved_label_language: entity.description},
                "statement_pids": sorted(symbolic_claims.keys()),
            }
        )
        payload = dict(shell)
        payload["type"] = entity.kind
        if entity.kind == "property" and entity.datatype is not None:
            payload["datatype"] = entity.datatype

        if symbolic_claims:
            payload_claims = payload.setdefault("claims", {})
            for property_id in sorted(symbolic_claims.keys()):
                payload_claims[property_id] = list(symbolic_claims[property_id])

        compiled_entity = MetaWikibaseCompiledEntity(
            key=entity.key,
            kind=entity.kind,
            internal_name_identifier=entity.internal_name_identifier,
            entity_type=entity.kind,
            datatype=entity.datatype,
            claims=symbolic_claims,
            payload=payload,
        )
        compiled_entities[entity.key] = compiled_entity
        compiled_by_internal_name_identifier[entity.internal_name_identifier] = (
            compiled_entity
        )

    return MetaWikibaseSeedCompilation(
        metadata=index.metadata,
        entities=compiled_entities,
        by_internal_name_identifier=compiled_by_internal_name_identifier,
    )

get_wikibase_datatype_spec(canonical_name)

Return the registry entry for one canonical datatype token.

Source code in gkc/wikibase.py
200
201
202
203
204
205
206
207
208
def get_wikibase_datatype_spec(canonical_name: str) -> WikibaseDatatypeSpec:
    """Return the registry entry for one canonical datatype token."""

    registry = load_wikibase_datatype_registry()
    canonical_name = canonicalize_wikibase_datatype(canonical_name)
    try:
        return registry[canonical_name]
    except KeyError as exc:
        raise KeyError(f"Unknown Wikibase datatype: {canonical_name}") from exc

get_wikibase_init_contract_digest(document=None)

Return a stable digest for the normalized Meta-Wikibase init contract.

Source code in gkc/wikibase.py
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def get_wikibase_init_contract_digest(
    document: dict[str, Any] | None = None,
) -> str:
    """Return a stable digest for the normalized Meta-Wikibase init contract."""

    normalized_document = (
        load_wikibase_init_document()
        if document is None
        else normalize_wikibase_init_document(document)
    )
    serialized = json.dumps(
        normalized_document,
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(serialized.encode("utf-8")).hexdigest()

get_wikibase_init_entity(entity_key)

Return one normalized entity entry from the package-owned init fixture.

Source code in gkc/wikibase.py
424
425
426
427
428
429
430
431
def get_wikibase_init_entity(entity_key: str) -> MetaWikibaseInitEntity:
    """Return one normalized entity entry from the package-owned init fixture."""

    index = build_wikibase_init_index()
    try:
        return index.entities[entity_key]
    except KeyError as exc:
        raise KeyError(f"Unknown Meta-Wikibase init entity: {entity_key}") from exc

is_known_wikibase_datatype(datatype)

Return whether a datatype token resolves to a known registry entry.

Source code in gkc/wikibase.py
242
243
244
245
246
247
248
def is_known_wikibase_datatype(datatype: str) -> bool:
    """Return whether a datatype token resolves to a known registry entry."""

    if not isinstance(datatype, str):
        return False
    canonical = canonicalize_wikibase_datatype(datatype)
    return canonical in load_wikibase_datatype_registry()

is_wikibase_item_datatype(datatype)

Return whether a datatype token resolves to the Wikibase item datatype.

Source code in gkc/wikibase.py
251
252
253
254
255
256
def is_wikibase_item_datatype(datatype: str) -> bool:
    """Return whether a datatype token resolves to the Wikibase item datatype."""

    if not isinstance(datatype, str):
        return False
    return canonicalize_wikibase_datatype(datatype) == "wikibase-item"

list_wikibase_datatypes()

Return the canonical runtime datatype tokens in stable order.

Source code in gkc/wikibase.py
211
212
213
214
def list_wikibase_datatypes() -> list[str]:
    """Return the canonical runtime datatype tokens in stable order."""

    return sorted(load_wikibase_datatype_registry().keys())

load_wikibase_datatype_registry() cached

Load the package-owned Wikibase datatype registry.

Returns:

Type Description
dict[str, WikibaseDatatypeSpec]

Mapping from canonical Wikibase datatype token to typed registry entry.

Source code in gkc/wikibase.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
@lru_cache(maxsize=1)
def load_wikibase_datatype_registry() -> dict[str, WikibaseDatatypeSpec]:
    """Load the package-owned Wikibase datatype registry.

    Returns:
        Mapping from canonical Wikibase datatype token to typed registry entry.
    """

    registry_path = files("gkc.registry").joinpath("wikibase_datatypes.json")
    raw_registry = json.loads(registry_path.read_text(encoding="utf-8"))
    if not isinstance(raw_registry, dict):
        raise RuntimeError("wikibase datatype registry must be a JSON object")

    registry: dict[str, WikibaseDatatypeSpec] = {}
    for canonical_name, payload in raw_registry.items():
        if not isinstance(canonical_name, str) or not canonical_name.strip():
            raise RuntimeError(
                "wikibase datatype registry keys must be non-empty strings"
            )
        if not isinstance(payload, dict):
            raise RuntimeError(
                "wikibase datatype registry entries must be JSON objects"
            )

        ontology_uri = payload.get("ontology_uri")
        datavalue_type = payload.get("datavalue_type")
        entity_value_kind = payload.get("entity_value_kind")

        if not isinstance(ontology_uri, str) or not ontology_uri.strip():
            raise RuntimeError(
                f"wikibase datatype '{canonical_name}' is missing ontology_uri"
            )
        if not isinstance(datavalue_type, str) or not datavalue_type.strip():
            raise RuntimeError(
                f"wikibase datatype '{canonical_name}' is missing datavalue_type"
            )
        if entity_value_kind is not None and (
            not isinstance(entity_value_kind, str) or not entity_value_kind.strip()
        ):
            raise RuntimeError(
                f"wikibase datatype '{canonical_name}' has invalid entity_value_kind"
            )

        registry[canonical_name] = WikibaseDatatypeSpec(
            ontology_uri=ontology_uri.strip(),
            datavalue_type=datavalue_type.strip(),
            entity_value_kind=(
                entity_value_kind.strip()
                if isinstance(entity_value_kind, str)
                else None
            ),
        )

    return registry

load_wikibase_datatype_registry_json()

Return the raw JSON-compatible registry mapping.

Source code in gkc/wikibase.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def load_wikibase_datatype_registry_json() -> dict[str, dict[str, str]]:
    """Return the raw JSON-compatible registry mapping."""

    registry = load_wikibase_datatype_registry()
    return {
        canonical_name: {
            "ontology_uri": spec.ontology_uri,
            "datavalue_type": spec.datavalue_type,
            **(
                {"entity_value_kind": spec.entity_value_kind}
                if spec.entity_value_kind is not None
                else {}
            ),
        }
        for canonical_name, spec in registry.items()
    }

load_wikibase_init_document()

Load the package-owned Meta-Wikibase init document and normalize it.

Source code in gkc/wikibase.py
193
194
195
196
197
def load_wikibase_init_document() -> dict[str, Any]:
    """Load the package-owned Meta-Wikibase init document and normalize it."""

    raw_document = yaml.safe_load(_load_meta_wikibase_init_yaml_text())
    return normalize_wikibase_init_document(raw_document)

normalize_wikibase_current_entity_view(entity, *, entity_id_to_internal_name_identifier, label_language, required_value_language, required_monolingualtext_properties, expected_property_ids)

Return the canonical comparable view for one current Wikibase entity.

Source code in gkc/wikibase.py
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
def normalize_wikibase_current_entity_view(
    entity: dict[str, Any],
    *,
    entity_id_to_internal_name_identifier: dict[str, str],
    label_language: str,
    required_value_language: str,
    required_monolingualtext_properties: set[str],
    expected_property_ids: set[str],
) -> tuple[dict[str, Any], list[str]]:
    """Return the canonical comparable view for one current Wikibase entity."""

    return _normalize_meta_wikibase_live_entity(
        entity,
        entity_id_to_internal_name_identifier=entity_id_to_internal_name_identifier,
        label_language=label_language,
        required_value_language=required_value_language,
        required_monolingualtext_properties=required_monolingualtext_properties,
        expected_property_ids=expected_property_ids,
    )

normalize_wikibase_init_document(document)

Normalize a Meta-Wikibase init document to canonical runtime datatypes.

Source code in gkc/wikibase.py
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
def normalize_wikibase_init_document(document: dict[str, Any]) -> dict[str, Any]:
    """Normalize a Meta-Wikibase init document to canonical runtime datatypes."""

    if not isinstance(document, dict):
        raise RuntimeError("meta_wb_init document must be a mapping")

    metadata = document.get("metadata")
    if not isinstance(metadata, dict):
        raise RuntimeError("meta_wb_init document is missing metadata")

    entities = document.get("entities")
    if not isinstance(entities, dict):
        raise RuntimeError("meta_wb_init document is missing entities")

    metadata_languages = _normalize_meta_wikibase_languages(metadata)

    normalized_entities: dict[str, dict[str, Any]] = {}
    normalized_properties: dict[str, dict[str, Any]] = {}

    for key, payload in entities.items():
        if not isinstance(payload, dict):
            raise RuntimeError(f"meta_wb_init entity '{key}' must be a mapping")
        normalized_payload = dict(payload)
        kind = normalized_payload.get("kind")
        if kind not in {"property", "item"}:
            raise RuntimeError(
                f"meta_wb_init entity '{key}' must define kind 'property' or 'item'"
            )

        normalized_payload["label"] = _normalize_meta_wikibase_authored_text(
            normalized_payload,
            field_name="label",
            languages=metadata_languages,
            entity_key=key,
        )
        normalized_payload["description"] = _normalize_meta_wikibase_authored_text(
            normalized_payload,
            field_name="description",
            languages=metadata_languages,
            entity_key=key,
        )

        if kind == "property":
            datatype = normalized_payload.get("datatype")
            if not isinstance(datatype, str) or not datatype.strip():
                raise RuntimeError(f"meta_wb_init property '{key}' is missing datatype")
            normalized_payload["datatype"] = canonicalize_wikibase_datatype(
                datatype,
                strict=True,
            )
            normalized_properties[key] = normalized_payload

        normalized_entities[key] = normalized_payload

    property_datatypes = {
        property_key: str(property_payload["datatype"])
        for property_key, property_payload in normalized_properties.items()
    }

    for key, payload in normalized_entities.items():
        normalized_entities[key] = _normalize_meta_wikibase_entity_attributes(
            payload,
            property_datatypes=property_datatypes,
            metadata_languages=metadata_languages,
        )

    _validate_meta_wikibase_value_list_contract(normalized_entities)

    normalized_metadata = dict(metadata)
    normalized_metadata["languages"] = metadata_languages

    return {
        "metadata": normalized_metadata,
        "entities": normalized_entities,
    }

normalize_wikibase_required_entity_view(payload)

Return the canonical comparable view for one compiled seed payload.

Source code in gkc/wikibase.py
634
635
636
637
638
639
def normalize_wikibase_required_entity_view(
    payload: dict[str, Any],
) -> dict[str, Any]:
    """Return the canonical comparable view for one compiled seed payload."""

    return _normalize_meta_wikibase_compiled_payload(payload)

plan_wikibase_seed_baseline(document=None, *, current_entities_by_internal_name_identifier=None, entity_id_to_internal_name_identifier=None, label_language=None, required_value_language='mul')

Return a dry-run baseline plan for the package-owned init fixture.

Source code in gkc/wikibase.py
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
def plan_wikibase_seed_baseline(
    document: dict[str, Any] | None = None,
    *,
    current_entities_by_internal_name_identifier: (
        dict[str, dict[str, Any]] | None
    ) = None,
    entity_id_to_internal_name_identifier: dict[str, str] | None = None,
    label_language: str | None = None,
    required_value_language: str = "mul",
) -> MetaWikibaseSeedPlan:
    """Return a dry-run baseline plan for the package-owned init fixture."""

    compilation = compile_wikibase_seed(
        document,
        label_language=label_language,
    )
    operations: list[MetaWikibaseSeedPlanEntry] = []
    resolved_label_language = _resolve_meta_wikibase_label_language(label_language)
    required_monolingualtext_properties = {
        entity.internal_name_identifier
        for entity in build_wikibase_init_index(document).properties.values()
        if entity.datatype == "monolingualtext"
    }

    for entity in compilation.entities.values():
        current_entity = None
        if current_entities_by_internal_name_identifier is not None:
            current_entity = current_entities_by_internal_name_identifier.get(
                entity.internal_name_identifier
            )

        if current_entity is None:
            operations.append(
                MetaWikibaseSeedPlanEntry(
                    action="create",
                    key=entity.key,
                    internal_name_identifier=entity.internal_name_identifier,
                    entity_type=entity.entity_type,
                    datatype=entity.datatype,
                    current_entity_id=None,
                    changed_fields=None,
                    details="missing from current state",
                    payload=entity.payload,
                )
            )
            continue

        comparison = _compare_meta_wikibase_compiled_to_current(
            entity.payload,
            current_entity=current_entity,
            entity_id_to_internal_name_identifier=(
                entity_id_to_internal_name_identifier or {}
            ),
            label_language=resolved_label_language,
            required_value_language=required_value_language,
            required_monolingualtext_properties=required_monolingualtext_properties,
        )
        operations.append(
            MetaWikibaseSeedPlanEntry(
                action="skip" if comparison["matches"] else "update",
                key=entity.key,
                internal_name_identifier=entity.internal_name_identifier,
                entity_type=entity.entity_type,
                datatype=entity.datatype,
                current_entity_id=str(current_entity.get("id") or "").strip() or None,
                changed_fields=comparison["changed_fields"] or None,
                details=comparison["details"],
                payload=entity.payload,
            )
        )

    operations.sort(key=lambda operation: operation.internal_name_identifier)
    return MetaWikibaseSeedPlan(
        metadata=compilation.metadata,
        operations=operations,
    )