"""Base Pydantic RDF model for CDIF profile classes."""
from __future__ import annotations
import contextvars
import functools
import json
import types
import warnings
from collections.abc import Sequence
from typing import Annotated, Any, ClassVar, Self, TypeAliasType, Union, cast, get_args, get_origin
from pydantic import ConfigDict, Field, model_validator
from rdflib import DCAT, RDF, XSD, BNode, Graph, Literal, URIRef
from rdflib.collection import Collection
from rdflib.term import Node, _is_valid_uri
from dartfx.cdif.namespaces import CDI, CDIF_PREFIXES, SCHEMA, expand_curie
from dartfx.rdf.pydantic import RdfBaseModel, RdfProperty
from dartfx.rdf.pydantic._base import DefaultUriGenerator, RdfUriGenerator
_CATALOG_RECORD_TOKENS = frozenset({"dcat:CatalogRecord", str(DCAT.CatalogRecord)})
_GENERIC_RDF_TYPE_URIS = frozenset(
{
str(SCHEMA.Thing),
str(CDI.DataStructure),
str(CDI.DataStructureComponent),
}
)
_SCHEMA_HTTPS_PREFIX = "https://schema.org/"
_SCHEMA_HTTP_PREFIX = "http://schema.org/"
def _normalize_type_uri(uri: str) -> str:
"""Normalize equivalent RDF type URIs (e.g. ``https://schema.org/`` -> ``http://schema.org/``)."""
if uri.startswith(_SCHEMA_HTTPS_PREFIX):
return _SCHEMA_HTTP_PREFIX + uri[len(_SCHEMA_HTTPS_PREFIX) :]
return uri
def _uri_local_name(uri: str) -> str:
"""Extract the local name after the final ``#`` or ``/`` of a URI."""
return uri.rsplit("#", 1)[-1].rsplit("/", 1)[-1]
def _extract_type_tokens(raw_type: Any) -> tuple[set[str], set[str]]:
"""Expand a JSON-LD ``@type`` value into ``(normalized_uris, bare_local_names)``."""
tokens = raw_type if isinstance(raw_type, list) else ([raw_type] if isinstance(raw_type, str) else [])
uris: set[str] = set()
bare_names: set[str] = set()
for tok in tokens:
if not isinstance(tok, str) or not tok:
continue
if ":" in tok:
uris.add(_normalize_type_uri(str(expand_curie(tok))))
else:
bare_names.add(tok)
return uris, bare_names
@functools.cache
def _model_rdf_type_info(model_cls: type[CdifBaseModel]) -> tuple[frozenset[str], frozenset[str]]:
"""Return ``(normalized_type_uris, local_names)`` declared on ``model_cls.rdf_type``."""
raw = model_cls.rdf_type
if raw is None:
return frozenset(), frozenset()
seq = list(raw) if isinstance(raw, (list, tuple, set)) else [raw]
uris = frozenset(_normalize_type_uri(str(t)) for t in seq)
locals_set = frozenset(_uri_local_name(u) for u in uris)
return uris, locals_set
@functools.cache
def _model_field_keys(model_cls: type[CdifBaseModel]) -> frozenset[str]:
"""Return the set of declared field names and JSON-LD aliases for ``model_cls``."""
keys: set[str] = set()
for fname, finfo in model_cls.model_fields.items():
if fname in {"id", "rdf_types_jsonld", "jsonld_context", "rdf_uri_generator"}:
continue
keys.add(fname)
if finfo.alias:
keys.add(finfo.alias)
return frozenset(keys)
def _extract_candidate_models(annotation: Any) -> list[type[CdifBaseModel]]:
"""Collect distinct ``CdifBaseModel`` subclasses referenced in a field type annotation."""
found: list[type[CdifBaseModel]] = []
def _walk(ann: Any) -> None:
if isinstance(ann, TypeAliasType):
_walk(ann.__value__)
return
origin = get_origin(ann)
if origin is Annotated:
args = get_args(ann)
if args:
_walk(args[0])
return
if origin in (Union, types.UnionType, list):
for arg in get_args(ann):
_walk(arg)
return
if isinstance(ann, type) and issubclass(ann, CdifBaseModel):
if ann not in found:
found.append(ann)
_walk(annotation)
return found
@functools.cache
def _field_union_candidates(cls: type[CdifBaseModel]) -> dict[str, list[type[CdifBaseModel]]]:
"""Map field names and JSON-LD aliases to candidate model lists for multi-model union fields."""
mapping: dict[str, list[type[CdifBaseModel]]] = {}
for fname, finfo in cls.model_fields.items():
candidates = _extract_candidate_models(finfo.annotation)
if len(candidates) > 1:
mapping[fname] = candidates
if finfo.alias:
mapping[finfo.alias] = candidates
return mapping
def _select_model_for_dict(
item: dict[str, Any],
candidates: list[type[CdifBaseModel]],
) -> type[CdifBaseModel] | None:
"""Choose the best-matching ``CdifBaseModel`` subclass for a JSON-LD dict in a union."""
# Pure @id reference (no @type or other properties) -> prefer ObjectReference
if "@id" in item and set(item.keys()) <= {"@id"}:
for candidate in candidates:
if candidate.cdif_forbid_extra and candidate.rdf_type is None:
return candidate
return None
raw_type = item.get("@type")
if raw_type is None:
return None
node_uris, bare_names = _extract_type_tokens(raw_type)
if not node_uris and not bare_names:
return None
item_keys = set(item.keys()) - {"@id", "@type", "@context"}
best_model: type[CdifBaseModel] | None = None
best_score: tuple[int, int, int, int, int, int, int] | None = None
for idx, candidate in enumerate(candidates):
model_uris, model_locals = _model_rdf_type_info(candidate)
if not model_uris:
continue
exact_matches = len(model_uris & node_uris)
bare_matches = len(model_locals & bare_names) if exact_matches == 0 else 0
if exact_matches == 0 and bare_matches == 0:
continue
is_subset = 1 if (exact_matches > 0 and model_uris.issubset(node_uris)) else 0
is_specific = 0 if model_uris <= _GENERIC_RDF_TYPE_URIS else 1
field_overlap = len(item_keys & _model_field_keys(candidate))
score = (
1 if exact_matches > 0 else 0,
is_subset,
exact_matches,
bare_matches,
is_specific,
field_overlap,
-idx,
)
if best_score is None or score > best_score:
best_score = score
best_model = candidate
return best_model
def _default_cdif_uri_generator() -> DefaultUriGenerator:
"""Return a URI generator that preserves blank nodes (``auto_uuid=False``)."""
return DefaultUriGenerator(auto_uuid=False)
_ACTIVE_JSONLD_CONTEXT: contextvars.ContextVar[tuple[dict[str, str], str | None, frozenset[str]]] = (
contextvars.ContextVar(
"_ACTIVE_JSONLD_CONTEXT",
default=({k: str(v) for k, v in CDIF_PREFIXES.items()}, None, frozenset()),
)
)
def _extract_context_mappings(ctx: Any) -> tuple[dict[str, str], str | None, frozenset[str]]:
"""Extract prefix/term mappings, optional ``@vocab``, and ``@type: @id`` predicate URIs."""
mappings: dict[str, str] = {}
vocab: str | None = None
raw_id_terms: list[str] = []
def _walk(node: Any) -> None:
nonlocal vocab
if isinstance(node, list):
for item in node:
_walk(item)
return
if not isinstance(node, dict):
return
for key, val in node.items():
if key == "@vocab" and isinstance(val, str):
vocab = val
elif key.startswith("@"):
continue
elif isinstance(val, str):
mappings[key] = val
elif isinstance(val, dict):
if isinstance(val.get("@id"), str):
mappings[key] = val["@id"]
if val.get("@type") == "@id":
raw_id_terms.append(val.get("@id") if isinstance(val.get("@id"), str) else key)
_walk(ctx)
merged_for_resolve = {**{k: str(v) for k, v in CDIF_PREFIXES.items()}, **mappings}
id_predicates: set[str] = set()
for term in raw_id_terms:
resolved = _resolve_jsonld_iri(term, merged_for_resolve, vocab)
if isinstance(resolved, URIRef):
id_predicates.add(str(resolved))
return mappings, vocab, frozenset(id_predicates)
def _resolve_jsonld_iri(
token: str,
mappings: dict[str, str],
vocab: str | None,
*,
_depth: int = 0,
) -> URIRef | BNode | None:
"""Resolve a JSON-LD CURIE, full IRI, blank-node ID, or context term into an rdflib node."""
if not token or _depth > 4 or any(ch.isspace() for ch in token):
return None
if token.startswith("_:"):
return BNode(token[2:]) if len(token) > 2 else BNode()
if token.startswith(("http://", "https://", "urn:", "mailto:", "doi:", "ftp://")):
return URIRef(token) if _is_valid_uri(token) else None
if token in mappings:
target = mappings[token]
if target != token:
return _resolve_jsonld_iri(target, mappings, vocab, _depth=_depth + 1)
if ":" in token:
prefix, local = token.split(":", 1)
if not local:
return None
base = mappings.get(prefix)
if base is not None and base.startswith(("http://", "https://", "urn:")):
candidate = base + local
return URIRef(candidate) if _is_valid_uri(candidate) else None
ns = CDIF_PREFIXES.get(prefix)
if ns is not None:
candidate = str(ns[local])
return URIRef(candidate) if _is_valid_uri(candidate) else None
return None
if vocab:
candidate = vocab + token
return URIRef(candidate) if _is_valid_uri(candidate) else None
return None
def _is_language_tagged_value(obj: Any) -> bool:
"""Return True if ``obj`` is a CDIF language-tagged value model (``@value`` / ``@language``)."""
if not isinstance(obj, CdifBaseModel) or obj.rdf_type is not None:
return False
fields = type(obj).model_fields
val_field = fields.get("value")
lang_field = fields.get("language")
return (
val_field is not None
and val_field.alias == "@value"
and lang_field is not None
and lang_field.alias == "@language"
)
def _compact_curie(uri: str | URIRef) -> str:
"""Shorten a URI into a CDIF CURIE when a known prefix matches."""
uri_str = str(uri)
for prefix, ns in CDIF_PREFIXES.items():
ns_str = str(ns)
if uri_str.startswith(ns_str):
local = uri_str[len(ns_str) :]
if local:
return f"{prefix}:{local}"
return uri_str
def _is_non_empty(value: Any) -> bool:
"""Return True if a field value is populated (not None or empty collection)."""
if value is None:
return False
if isinstance(value, (list, tuple, set, dict, str)):
return len(value) > 0
return True
[docs]
class CdifBaseModel(RdfBaseModel):
"""Base class for all generated CDIF Pydantic + RDF models.
Supports both:
* Direct framed JSON-LD validation/serialization via Pydantic aliases
(``from_jsonld`` / ``to_jsonld_dict``).
* Full RDF graph round-tripping (Turtle, JSON-LD, RDF/XML, N-Triples) via
``dartfx.rdf.pydantic.RdfBaseModel`` (``to_rdf`` / ``from_rdf``).
"""
model_config = ConfigDict(
arbitrary_types_allowed=True,
populate_by_name=True,
extra="allow",
)
rdf_prefixes: ClassVar[Any] = dict(CDIF_PREFIXES)
rdf_id_field: ClassVar[str | None] = "id"
# Profile conformance metadata populated by codegen on root/profile classes
cdif_profile_uri: ClassVar[str | None] = None
cdif_required_fields: ClassVar[tuple[str, ...]] = ()
cdif_any_of_required: ClassVar[tuple[tuple[str, ...], ...]] = ()
cdif_forbid_extra: ClassVar[bool] = False
rdf_uri_generator: RdfUriGenerator = Field(default_factory=_default_cdif_uri_generator, exclude=True)
id: str | None = Field(default=None, alias="@id", description="JSON-LD / RDF subject URI identifier.")
rdf_types_jsonld: str | list[str] | None = Field(
default=None,
alias="@type",
description="Explicit JSON-LD @type declaration(s).",
)
jsonld_context: dict[str, Any] | list[Any] | str | None = Field(
default=None,
alias="@context",
description="JSON-LD @context declaration.",
)
@model_validator(mode="before")
@classmethod
def _resolve_typed_union_fields(cls, data: Any) -> Any:
"""Disambiguate union fields of ``CdifBaseModel`` subclasses using JSON-LD ``@type``."""
if not isinstance(data, dict):
return data
union_map = _field_union_candidates(cls)
if not union_map:
return data
updated: dict[str, Any] | None = None
for key, candidates in union_map.items():
if key not in data:
continue
val = data[key]
if isinstance(val, dict):
chosen = _select_model_for_dict(val, candidates)
if chosen is not None:
if updated is None:
updated = dict(data)
updated[key] = chosen.model_validate(val)
elif isinstance(val, list):
new_list: list[Any] | None = None
for idx, elem in enumerate(val):
if isinstance(elem, dict):
chosen = _select_model_for_dict(elem, candidates)
if chosen is not None:
if new_list is None:
new_list = list(val)
new_list[idx] = chosen.model_validate(elem)
if new_list is not None:
if updated is None:
updated = dict(data)
updated[key] = new_list
return updated if updated is not None else data
@model_validator(mode="after")
def _enforce_forbid_extra(self) -> Self:
if self.model_extra:
if type(self).cdif_forbid_extra:
extra_keys = ", ".join(sorted(self.model_extra))
msg = f"Extra inputs are not permitted for {type(self).__name__}: {extra_keys}"
raise ValueError(msg)
if (
type(self).rdf_type is not None
and set(self.model_extra.keys()) == {"@list"}
and self.id is None
and self.rdf_types_jsonld is None
):
msg = f"JSON-LD @list container cannot be instantiated as {type(self).__name__}"
raise ValueError(msg)
return self
def _serialise_into_graph(
self,
graph: Graph,
*,
base_uri: str | None = None,
rdf_uri_generator: RdfUriGenerator | None = None,
) -> URIRef | BNode:
"""Serialize declared fields, extra ``@type`` values, and ``model_extra`` properties into RDF."""
parent_mappings, parent_vocab, parent_id_preds = _ACTIVE_JSONLD_CONTEXT.get()
token: contextvars.Token[tuple[dict[str, str], str | None, frozenset[str]]] | None = None
if self.jsonld_context is not None:
local_mappings, local_vocab, local_id_preds = _extract_context_mappings(self.jsonld_context)
merged_mappings = {**parent_mappings, **local_mappings}
merged_vocab = local_vocab if local_vocab is not None else parent_vocab
merged_id_preds = parent_id_preds | local_id_preds
token = _ACTIVE_JSONLD_CONTEXT.set((merged_mappings, merged_vocab, merged_id_preds))
for prefix, ns_uri in local_mappings.items():
if (
not prefix.startswith("@")
and ns_uri.startswith(("http://", "https://"))
and ns_uri.endswith(("/", "#"))
):
graph.bind(prefix, ns_uri)
try:
subject = super()._serialise_into_graph(
graph,
base_uri=base_uri,
rdf_uri_generator=rdf_uri_generator,
)
# Emit any additional @type assertions from rdf_types_jsonld
if self.rdf_types_jsonld is not None:
mappings, vocab, _ = _ACTIVE_JSONLD_CONTEXT.get()
declared_norm, _ = _model_rdf_type_info(type(self))
raw_types = (
self.rdf_types_jsonld if isinstance(self.rdf_types_jsonld, list) else [self.rdf_types_jsonld]
)
for raw_t in raw_types:
if not isinstance(raw_t, str):
continue
resolved_t = _resolve_jsonld_iri(raw_t, mappings, vocab)
if isinstance(resolved_t, URIRef) and _normalize_type_uri(str(resolved_t)) not in declared_norm:
graph.add((subject, RDF.type, resolved_t))
# Emit undeclared JSON-LD properties preserved in model_extra
if self.model_extra:
for extra_key, extra_val in self.model_extra.items():
if extra_key.startswith("@") or extra_val is None:
continue
self._add_extra_property_triples(
graph,
subject,
extra_key,
extra_val,
base_uri=base_uri,
rdf_uri_generator=rdf_uri_generator,
)
return subject
finally:
if token is not None:
_ACTIVE_JSONLD_CONTEXT.reset(token)
def _value_to_node(
self,
value: Any,
expected_type: Any,
prop: RdfProperty,
graph: Graph,
base_uri: str | None,
*,
rdf_uri_generator: RdfUriGenerator | None = None,
) -> URIRef | BNode | Literal:
if prop.serializer is None:
if isinstance(value, dict):
return self._jsonld_value_to_node(
value,
graph,
base_uri=base_uri,
rdf_uri_generator=rdf_uri_generator,
)
if _is_language_tagged_value(value):
val = getattr(value, "value", None)
lang = getattr(value, "language", None)
if val is not None:
return Literal(val, lang=lang)
if isinstance(value, str) and not isinstance(value, (URIRef, Literal)):
if prop.language:
return Literal(value, lang=prop.language)
datatype = prop.datatype_uri()
if datatype is not None:
return Literal(value, datatype=datatype)
mappings, vocab, id_preds = _ACTIVE_JSONLD_CONTEXT.get()
if str(prop.predicate_uri()) in id_preds:
resolved = _resolve_jsonld_iri(value, mappings, vocab)
if isinstance(resolved, URIRef):
return resolved
return Literal(value)
return super()._value_to_node(
value,
expected_type,
prop,
graph,
base_uri,
rdf_uri_generator=rdf_uri_generator,
)
def _add_extra_property_triples(
self,
graph: Graph,
subject: URIRef | BNode,
key: str,
value: Any,
*,
base_uri: str | None = None,
rdf_uri_generator: RdfUriGenerator | None = None,
) -> None:
"""Resolve an undeclared JSON-LD property key and emit its triples into ``graph``."""
mappings, vocab, _ = _ACTIVE_JSONLD_CONTEXT.get()
pred = _resolve_jsonld_iri(key, mappings, vocab)
if not isinstance(pred, URIRef):
warnings.warn(
f"Cannot serialize extra property {key!r} on {type(self).__name__} to RDF: "
"unable to resolve predicate URI",
UserWarning,
stacklevel=3,
)
return
if isinstance(value, dict) and "@set" in value and isinstance(value["@set"], list):
items: list[Any] = value["@set"]
elif isinstance(value, list):
items = value
else:
items = [value]
for item in items:
if item is None:
continue
node = self._jsonld_value_to_node(
item,
graph,
base_uri=base_uri,
rdf_uri_generator=rdf_uri_generator,
)
graph.add((subject, pred, node))
def _jsonld_value_to_node(
self,
value: Any,
graph: Graph,
*,
base_uri: str | None = None,
rdf_uri_generator: RdfUriGenerator | None = None,
) -> URIRef | BNode | Literal:
"""Convert an arbitrary JSON-LD value (dict, model, or scalar) into an rdflib node."""
if _is_language_tagged_value(value):
val = getattr(value, "value", None)
lang = getattr(value, "language", None)
if val is not None:
return Literal(val, lang=lang)
if isinstance(value, RdfBaseModel):
return value._serialise_into_graph(
graph,
base_uri=base_uri,
rdf_uri_generator=rdf_uri_generator,
)
if isinstance(value, (URIRef, BNode, Literal)):
return value
if isinstance(value, dict):
mappings, vocab, id_preds = _ACTIVE_JSONLD_CONTEXT.get()
local_token: contextvars.Token[tuple[dict[str, str], str | None, frozenset[str]]] | None = None
if "@context" in value:
local_map, local_vocab, local_id_preds = _extract_context_mappings(value["@context"])
mappings = {**mappings, **local_map}
vocab = local_vocab if local_vocab is not None else vocab
id_preds = id_preds | local_id_preds
local_token = _ACTIVE_JSONLD_CONTEXT.set((mappings, vocab, id_preds))
try:
# 1. JSON-LD value object: {"@value": ..., "@language": ... / "@type": ...}
if "@value" in value:
raw_val = value["@value"]
lang = value.get("@language")
if isinstance(lang, str) and lang:
return Literal(raw_val, lang=lang)
dt_raw = value.get("@type")
if isinstance(dt_raw, str) and dt_raw:
dt_uri = _resolve_jsonld_iri(dt_raw, mappings, vocab)
if isinstance(dt_uri, URIRef):
return Literal(raw_val, datatype=dt_uri)
return Literal(raw_val)
# 2. JSON-LD @list container -> RDF Collection
if "@list" in value and isinstance(value["@list"], list):
list_nodes: list[Node] = [
self._jsonld_value_to_node(
item,
graph,
base_uri=base_uri,
rdf_uri_generator=rdf_uri_generator,
)
for item in value["@list"]
if item is not None
]
if not list_nodes:
return RDF.nil
head = BNode()
Collection(graph, head, list_nodes)
return head
# 3. Pure @id reference -> URIRef or BNode
if "@id" in value and set(value.keys()) <= {"@id", "@context"}:
ref_id = value["@id"]
if isinstance(ref_id, str) and ref_id:
resolved = _resolve_jsonld_iri(ref_id, mappings, vocab)
if resolved is not None:
return resolved
return URIRef(ref_id)
# 4. General nested JSON-LD node object
node_subj: URIRef | BNode
raw_id = value.get("@id")
if isinstance(raw_id, str) and raw_id:
node_subj = _resolve_jsonld_iri(raw_id, mappings, vocab) or URIRef(raw_id)
else:
node_subj = BNode()
raw_types = value.get("@type")
if raw_types is not None:
type_list = raw_types if isinstance(raw_types, list) else [raw_types]
for raw_t in type_list:
if isinstance(raw_t, str):
t_uri = _resolve_jsonld_iri(raw_t, mappings, vocab)
if isinstance(t_uri, URIRef):
graph.add((node_subj, RDF.type, t_uri))
for k, v in value.items():
if k.startswith("@") or v is None:
continue
self._add_extra_property_triples(
graph,
node_subj,
k,
v,
base_uri=base_uri,
rdf_uri_generator=rdf_uri_generator,
)
return node_subj
finally:
if local_token is not None:
_ACTIVE_JSONLD_CONTEXT.reset(local_token)
if isinstance(value, bool):
return Literal(value, datatype=XSD.boolean)
if isinstance(value, int):
return Literal(value, datatype=XSD.integer)
if isinstance(value, float):
return Literal(value, datatype=XSD.double)
return Literal(value)
[docs]
@classmethod
def default_jsonld_context(cls) -> dict[str, str]:
"""Return the standard prefix dictionary for CDIF JSON-LD serialization."""
return {
prefix: str(ns)
for prefix, ns in CDIF_PREFIXES.items()
if prefix not in {"rdf", "rdfs", "owl", "xsd", "foaf"}
}
def _has_field_value(self, field_or_alias: str) -> bool:
"""Check whether a field (by Python name or JSON-LD alias) has a non-empty value."""
if field_or_alias == "@id":
return _is_non_empty(self.id)
if field_or_alias == "@type":
return _is_non_empty(self.rdf_types_jsonld) or bool(self.rdf_type)
if field_or_alias == "@context":
return _is_non_empty(self.jsonld_context)
for name, field_info in type(self).model_fields.items():
if name == field_or_alias or field_info.alias == field_or_alias:
return _is_non_empty(getattr(self, name))
extra = self.model_extra or {}
return _is_non_empty(extra.get(field_or_alias))
[docs]
def to_jsonld_dict(
self,
*,
exclude_none: bool = True,
include_context: bool = False,
) -> dict[str, Any]:
"""Serialize this model into a framed JSON-LD dictionary using JSON-LD aliases."""
data = self.model_dump(by_alias=True, exclude_none=exclude_none, exclude={"rdf_uri_generator"})
# Ensure @type is populated from class rdf_type when not explicitly set
if "@type" not in data and self.rdf_type is not None:
raw_types = self.rdf_type
if isinstance(raw_types, (list, tuple, set)):
data["@type"] = [_compact_curie(t) for t in raw_types]
else:
data["@type"] = [_compact_curie(cast(str | URIRef, raw_types))]
if include_context and "@context" not in data:
data["@context"] = self.default_jsonld_context()
return data
[docs]
def to_jsonld(self, *, indent: int | None = 2, include_context: bool = True) -> str:
"""Serialize this model to a framed JSON-LD string."""
return json.dumps(self.to_jsonld_dict(include_context=include_context), indent=indent)
[docs]
@classmethod
def from_jsonld(cls, data: str | bytes | dict[str, Any]) -> Self:
"""Deserialize a framed JSON-LD document (string, bytes, or dict) into this model."""
if isinstance(data, (str, bytes)):
parsed: Any = json.loads(data)
else:
parsed = data
if not isinstance(parsed, dict):
msg = f"Expected JSON-LD object dict, got {type(parsed).__name__}"
raise ValueError(msg)
# Unwrap framed @graph envelope if present
if "@graph" in parsed and isinstance(parsed["@graph"], list) and parsed["@graph"]:
graph_nodes = [n for n in parsed["@graph"] if isinstance(n, dict)]
chosen = _pick_main_jsonld_node(graph_nodes)
if chosen is not None:
merged = dict(chosen)
if "@context" in parsed and "@context" not in merged:
merged["@context"] = parsed["@context"]
parsed = merged
return cls.model_validate(parsed)
@classmethod
def _infer_subject(cls, graph: Graph) -> URIRef | BNode | None:
"""Disambiguate the main CDIF subject when a graph holds multiple typed nodes.
Real CDIF graphs routinely contain both the main ``schema:Dataset`` and
its ``schema:subjectOf`` catalog record (also typed ``schema:Dataset``),
as well as ``schema:hasPart`` child datasets.
"""
raw_type = cls.rdf_type
if raw_type is None:
return super()._infer_subject(graph)
types: list[URIRef] = []
seq: Sequence[str | URIRef] = (
list(raw_type) if isinstance(raw_type, (list, tuple, set)) else [cast(str | URIRef, raw_type)]
)
for t in seq:
uri = t if isinstance(t, URIRef) else URIRef(str(t))
if uri not in types:
types.append(uri)
if len(types) == 1:
candidates = list(dict.fromkeys(graph.subjects(RDF.type, types[0])))
else:
sets = [set(graph.subjects(RDF.type, t)) for t in types]
candidates = list(set.intersection(*sets)) if sets else []
if len(candidates) <= 1:
return cast(URIRef | BNode, candidates[0]) if candidates else None
# 1. Exclude catalog records (dcat:CatalogRecord or targets of schema:subjectOf)
subject_of_objs = set(graph.objects(None, SCHEMA.subjectOf))
non_catalog = []
for c in candidates:
c_types = {str(o) for o in graph.objects(c, RDF.type)} | {
str(o) for o in graph.objects(c, SCHEMA.additionalType)
}
if c in subject_of_objs or (c_types & _CATALOG_RECORD_TOKENS):
continue
non_catalog.append(c)
if non_catalog:
candidates = non_catalog
if len(candidates) == 1:
return cast(URIRef | BNode, candidates[0])
# 2. Exclude schema:hasPart members
has_part_objs = set(graph.objects(None, SCHEMA.hasPart))
non_parts = [c for c in candidates if c not in has_part_objs]
if non_parts:
candidates = non_parts
if len(candidates) == 1:
return cast(URIRef | BNode, candidates[0])
# 3. Prefer nodes carrying schema:subjectOf
with_subject_of = [c for c in candidates if any(graph.objects(c, SCHEMA.subjectOf))]
if with_subject_of:
candidates = with_subject_of
if len(candidates) == 1:
return cast(URIRef | BNode, candidates[0])
# 4. Prefer nodes carrying schema:distribution or schema:url
with_dist_or_url = [
c for c in candidates if any(graph.objects(c, SCHEMA.distribution)) or any(graph.objects(c, SCHEMA.url))
]
if len(with_dist_or_url) == 1:
return cast(URIRef | BNode, with_dist_or_url[0])
return super()._infer_subject(graph)
def _pick_main_jsonld_node(nodes: list[dict[str, Any]]) -> dict[str, Any] | None:
"""Pick the primary entity node from a framed JSON-LD ``@graph`` list."""
if not nodes:
return None
if len(nodes) == 1:
return nodes[0]
def _is_cat_rec(node: dict[str, Any]) -> bool:
at = node.get("schema:additionalType") or node.get("additionalType")
vals = at if isinstance(at, list) else ([at] if at is not None else [])
for v in vals:
tok = v.get("@id") if isinstance(v, dict) else v
if isinstance(tok, str) and tok in _CATALOG_RECORD_TOKENS:
return True
return False
candidates = [n for n in nodes if not _is_cat_rec(n)] or nodes
part_ids: set[str] = set()
for n in nodes:
hp = n.get("schema:hasPart") or n.get("hasPart")
for p in hp if isinstance(hp, list) else ([hp] if hp is not None else []):
if isinstance(p, dict) and isinstance(p.get("@id"), str):
part_ids.add(p["@id"])
non_parts = [n for n in candidates if n.get("@id") not in part_ids]
if non_parts:
candidates = non_parts
with_so = [n for n in candidates if "schema:subjectOf" in n or "subjectOf" in n]
if with_so:
return with_so[0]
return candidates[0]
__all__ = ["CdifBaseModel"]