Coverage for lode / reader / pipeline.py: 99%
72 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"""Reader: runs the extraction pipeline and writes what it extracts on an Artefact.
3The Reader sits between the document loader and the viewers: it loads the graph, takes the
4configuration and the reader of the artefact's format, runs the reader phases and hands the
5result over by filling the Artefact it is given, so CLI, API and viewers never depend on
6parsing details. It keeps no state and imports nothing from lode.artefact: it only sets the
7attributes the Artefact declares.
8"""
9import logging
10from typing import Optional
12from rdflib import URIRef
14from lode.models import Model
15from lode.provenance_graph import ProvenanceGraph
16from lode.reader import modules
17from lode.reader.config_manager import ConfigManager
18from lode.reader.loader import load_document
20logger = logging.getLogger(__name__)
23# ==========================================================================
24# 1. ENTRY POINT
25# ==========================================================================
26def read_into(artefact, source: str, *, imported=None, closure=None, partial_import=None,
27 warnings: bool = False, source_name: Optional[str] = None) -> None:
28 """Load `source` and fill `artefact` with what the extraction pipeline produces.
30 The format comes from `artefact.profile`. Sets graph, artefact_iri, imported_uris,
31 entities, reader, warnings and provenance on `artefact` and returns nothing: the
32 Artefact is the only place where the result lives. `imported`, `closure` and
33 `partial_import` are forwarded to `load_graph`; `warnings` turns on the reader warnings;
34 `source_name` names the artefact when `source` is only a local copy of it. Blocking:
35 it may fetch remote documents.
36 """
37 graph, artefact_iri, imported_uris = load_graph(
38 source, imported=imported, closure=closure,
39 partial_import=partial_import, source_name=source_name)
40 artefact.graph = graph
41 artefact.artefact_iri = artefact_iri
42 artefact.imported_uris = imported_uris
43 artefact.entities = {}
45 configuration = ConfigManager(artefact.profile)
46 reader = artefact.profile.make_reader(artefact.graph, artefact.entities, configuration)
47 _extract_entities(reader, artefact.profile, warnings)
48 _populate_namespaces(artefact)
50 artefact.reader = reader
51 artefact.warnings = reader.warnings if warnings else []
52 artefact.provenance = reader.build_provenance_subgraph
53 # Documented semantic artefact first (only when a module is active)
54 if isinstance(artefact.graph, ProvenanceGraph):
55 _prioritize_documented_values(artefact)
58# ==========================================================================
59# 2. LOADING
60# ==========================================================================
61def load_graph(source: str, *, imported=None, closure=None, partial_import=None,
62 source_name: Optional[str] = None):
63 """Load the graph of an artefact: its document, named, with the requested modules applied.
65 Returns (graph, artefact_iri, imported_uris). The graph is a plain Graph, or a
66 ProvenanceGraph (one named graph per source document) when `imported`, `closure` or
67 `partial_import` is requested; in both cases `artefact_iri` names the loaded artefact.
68 `source_name` names the artefact when `source` is only a local copy of it (for example
69 a cached download): it names the graph if the ontology declares no IRI. `imported_uris`
70 holds the IRIs of the imported documents, so that the viewer can keep the metadata of
71 the original model.
72 """
73 graph = load_document(source)
74 name = source_name or source
75 if not (imported or closure or partial_import):
76 # No modules: the graph stays plain, only its name is needed so that the
77 # provenance of an entity can still be written as a quad.
78 return graph, ProvenanceGraph.artefact_iri(graph, name), set()
80 raw, graph = graph, ProvenanceGraph()
81 artefact_iri = graph.add_document(raw, name)
82 graph, imported_uris = modules.apply(graph, imported=imported, closure=closure,
83 partial_import=partial_import)
84 return graph, artefact_iri, imported_uris
87# ==========================================================================
88# 3. EXTRACTION
89# ==========================================================================
90def _extract_entities(reader, profile, warnings_enabled: bool) -> None:
91 """Run the extraction phases in order, delegating each one to the reader.
93 Phases 1-5 depend on the artefact type; the statements phase is shared.
94 The post-extraction checks of the profile run only when warnings are enabled.
95 """
96 reader.phase1_classify_from_predicates()
97 reader.phase2_create_from_types()
98 reader.phase3_populate_properties()
99 reader.phase4_process_group_axioms()
100 reader.phase5_fallback()
101 reader.phase6_create_statements()
103 if warnings_enabled:
104 profile.run_post_checks(reader)
106 if reader.warnings:
107 logger.warning("%d reader warnings", len(reader.warnings))
108 # details only at DEBUG: the viewer words them with display names
109 # for popups, report and CLI, so raw model names would be confusing
110 for w in reader.warnings:
111 logger.debug("[%s] %s", w['code'], w['message'])
114def _populate_namespaces(artefact) -> None:
115 """Give every Model of the artefact the prefixes declared in its graph.
117 The model knows nothing about RDF, so the pipeline copies the `{prefix: URI}`
118 pairs of the graph into `Model.has_namespaces`, from where the viewer shows
119 them. Runs once the extraction is over, so every Model exists; each one gets
120 the same dictionary.
121 """
122 ns = {prefix: str(uri) for prefix, uri in artefact.graph.namespaces()}
123 for entities in artefact.entities.values():
124 for entity in entities:
125 if isinstance(entity, Model):
126 entity.set_has_namespaces(ns)
129def _value_key(value) -> str:
130 """Comparable form of a model value: lexical form for literals, IRI otherwise."""
131 get_value = getattr(value, "get_has_value", None)
132 if get_value is not None and get_value() is not None:
133 return str(get_value())
134 get_id = getattr(value, "get_has_identifier", None)
135 if get_id is not None and get_id():
136 return str(get_id())
137 return str(value)
140def _prioritize_documented_values(artefact) -> None:
141 """Reorder every multi-valued field so that values asserted by the documented
142 semantic artefact (main named graph) come before those from imported or home graphs.
144 Needed because the graph does not preserve insertion order across named graphs.
145 The sort is stable: within each group the original order is kept.
146 """
147 main = artefact.graph.graph(artefact.artefact_iri)
148 for uri, entities in artefact.entities.items():
149 if not isinstance(uri, URIRef):
150 continue
151 local = {str(o) for o in main.objects(uri, None)}
152 if not local:
153 continue
154 for entity in entities:
155 for value in vars(entity).values():
156 if isinstance(value, list) and len(value) > 1:
157 value.sort(key=lambda v: _value_key(v) not in local)