Coverage for lode / helpers / rdf.py: 77%
35 statements
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-22 15:54 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-22 15:54 +0000
1"""RDF helpers shared across LODE: IRIs and graphs.
3Stateless utilities with no knowledge of the LODE pipeline (no models, no reader
4phases, no network): they take IRIs or rdflib graphs and return plain values.
5Pipeline types built on top of them (e.g. ProvenanceGraph) live in lode.provenance_graph,
6shared by the reader and the artefact.
7"""
8from pathlib import Path
9from typing import Optional
11from rdflib import Graph, URIRef
12from rdflib.namespace import OWL, RDF, SKOS
14# ----------------------------------------------------------
15# IRIs
16# ----------------------------------------------------------
19def iri_namespace(iri) -> str:
20 """Namespace of an IRI, trailing separator included.
22 Splits on the last '#' if the IRI has one, otherwise on the last '/':
23 'http://ex.org/onto#T' -> 'http://ex.org/onto#'
24 'http://ex.org/voc/t' -> 'http://ex.org/voc/'
25 """
26 s = str(iri)
27 if "#" in s:
28 return s.rsplit("#", 1)[0] + "#"
29 return s.rsplit("/", 1)[0] + "/"
32def iri_local_name(iri) -> str:
33 """Local name of an IRI: the last segment after '#' and '/', trailing '/' ignored.
34 Never contains '#' or '/', so it is safe as a file name or attribute name:
35 'http://ex.org/onto#T' -> 'T'
36 'http://ex.org/voc/t/' -> 't'
37 """
38 return str(iri).rstrip("/").split("#")[-1].split("/")[-1]
41def iri_stem(iri) -> str:
42 """IRI without trailing '/' or '#', to compare IRIs that differ only in the
43 separator ('http://ex.org/onto#' == 'http://ex.org/onto' == 'http://ex.org/onto/')."""
44 return str(iri).rstrip("/#")
47def source_iri(source: str) -> str:
48 """IRI of a load source: URLs as they are, local paths as absolute file: URIs."""
49 if "://" in source:
50 return source
51 return Path(source).resolve().as_uri()
54# ----------------------------------------------------------
55# Graphs
56# ----------------------------------------------------------
58# Node types that name a document: owl:Ontology first, then skos:ConceptScheme.
59ONTOLOGY_TYPES = (OWL.Ontology, SKOS.ConceptScheme)
62def declared_ontology_iri(g: Graph) -> Optional[URIRef]:
63 """IRI of the ontology (or concept scheme) a document declares, or None.
64 owl:Ontology wins over skos:ConceptScheme; blank nodes are ignored."""
65 for t in ONTOLOGY_TYPES:
66 for s in g.subjects(RDF.type, t):
67 if isinstance(s, URIRef):
68 return s
69 return None
71# Formats tried, in order, when the serialization is unknown. Turtle comes before N3
72# (N3 is a superset and slower to fail); N-Triples is also valid Turtle.
73PARSE_FORMATS = ("xml", "turtle", "json-ld", "nt", "n3")
76def parse_any(data, preferred: Optional[str] = None) -> Optional[Graph]:
77 """Parse RDF `data` (str or bytes) of unknown serialization.
79 Tries `preferred` first (e.g. the format declared by the Content-Type), then
80 PARSE_FORMATS in order. Returns the first graph that parses, or None if no
81 format works: raising a meaningful error is left to the caller."""
82 formats = ([preferred] if preferred else []) + [f for f in PARSE_FORMATS if f != preferred]
83 for fmt in formats:
84 g = Graph()
85 try:
86 g.parse(data=data, format=fmt)
87 return g
88 except Exception:
89 continue
90 return None