Coverage for lode / provenance_graph.py: 96%

28 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-11-22 15:54 +0000

1"""Named-graph container that keeps track of which ontology each triple comes from. 

2 

3Used when imports or partial imports are enabled: every loaded document lives 

4in its own named graph, named after its ontology IRI, while the rest of the 

5pipeline keeps reading the union of all of them as if it were a single Graph. 

6""" 

7import os 

8from pathlib import Path 

9from urllib.parse import urlparse, quote 

10from rdflib import Dataset, Graph, URIRef, OWL, RDF 

11from rdflib.namespace import SKOS 

12 

13_SEMANTIC_ARTEFACTS_TYPES = (OWL.Ontology, SKOS.ConceptScheme) 

14QUAD_FORMATS = frozenset({"trig", "nquads"}) 

15 

16class ProvenanceGraph(Dataset): 

17 """Dataset with one named graph per source ontology, presented to the pipeline as a Graph. 

18 

19 default_union makes queries see the union of all named graphs, so readers 

20 and viewers need no knowledge of the provenance; only the code that cares 

21 about the origin of a triple asks for a specific named graph. 

22 """ 

23 

24 def __init__(self, **kw): 

25 """Create an empty dataset whose default graph is the union of its named graphs.""" 

26 super().__init__(default_union=True, **kw) 

27 

28 def __iter__(self): 

29 """Iterate over the plain triples of the union, like a Graph does.""" 

30 return self.triples((None, None, None)) 

31 

32 def add_document(self, g: Graph, fallback: str) -> URIRef: 

33 """Copy the triples of `g` into the named graph of its ontology and return its IRI. 

34 

35 The graph is named by `artefact_iri`; `fallback` (usually the source URL 

36 or path) is used when the document declares no ontology. 

37 """ 

38 ctx =self.artefact_iri(g, fallback) 

39 self.graph(ctx).__iadd__(g) 

40 return ctx 

41 

42 @staticmethod 

43 def artefact_iri(g: Graph, fallback: str) -> URIRef: 

44 """Return the IRI that names the graph of a document. 

45 

46 Uses the first owl:Ontology or skos:ConceptScheme subject with an IRI. 

47 Without one, falls back to the source itself: http(s)/file URLs as they 

48 are, local paths as file:// URIs (a one-letter scheme is a Windows 

49 drive), anything else as a urn:lode:source: URN. 

50 """ 

51 for t in _SEMANTIC_ARTEFACTS_TYPES: 

52 for s in g.subjects(RDF.type, t): 

53 if isinstance(s, URIRef): 

54 return s 

55 parsed = urlparse(fallback) 

56 if parsed.scheme in {"http", "https", "file"}: 

57 return URIRef(fallback) 

58 if not parsed.scheme or len(parsed.scheme) == 1: 

59 return URIRef(Path(os.path.abspath(fallback)).as_uri()) 

60 return URIRef(f"urn:lode:source:{quote(fallback, safe='')}")