Coverage for lode / reader / config_manager.py: 99%
101 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"""Configuration managers: bind each artefact type to its YAML mapper and reader.
3The mapping from RDF/OWL/SKOS constructs to the model lives in the YAML files
4under reader/config, not in Python: a manager loads base.yaml, merges the
5type-specific file on top and exposes the result to the reader classes.
6"""
8import yaml
9from pathlib import Path
10from rdflib import URIRef, Graph, Node
11from lode.models import *
12from lode import profiles
13from lode.profiles import Profile
15class ConfigManager:
16 """Strategy driven by a single merged YAML configuration.
18 One instance per artefact format: its `profile` gives the YAML file (see
19 lode.profiles), and the profile builds the reader with this manager. Adding a format
20 needs no new subclass. Viewers are not a concern of this layer: see lode.viewer.get_viewer.
21 """
23 def __init__(self, profile: Profile):
24 """Load and merge the YAML configuration of `profile`; mappings are parsed lazily."""
25 self.profile = profile
26 self.config = self._load_config()
27 self._type_mapping_cache = None
28 self._property_mapping_cache = None
30 def _load_config(self) -> dict:
31 """base.yaml sits next to this module, the type-specific file in the folder of the
32 profile; both are package data, so they ship inside the wheel.
33 """
34 with open(Path(__file__).parent / 'config' / 'base.yaml') as f:
35 base = yaml.safe_load(f)
37 with open(self.profile.path() / 'reader.yaml') as f:
38 specific = yaml.safe_load(f)
41 return self._deep_merge(base, specific)
43 def _deep_merge(self, base: dict, override: dict) -> dict:
44 """Merge `override` into a copy of `base`, recursing into nested dicts.
46 The 'name' and 'inherits' keys only describe the file and are not merged.
47 """
48 result = base.copy()
49 for key, value in override.items():
50 if key in ('name', 'inherits'):
51 continue
52 if key in result and isinstance(result[key], dict) and isinstance(value, dict):
53 result[key] = self._deep_merge(result[key], value)
54 else:
55 result[key] = value
56 return result
58 # ========== NAMESPACE MAP ==========
59 NAMESPACES = {
60 'owl': 'http://www.w3.org/2002/07/owl#',
61 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
62 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
63 'skos': 'http://www.w3.org/2004/02/skos/core#',
64 'xsd': "http://www.w3.org/2001/XMLSchema#",
65 'swrl': 'http://www.w3.org/2003/11/swrl#'
66 }
68 def _parse_uri(self, uri_str: str) -> URIRef:
69 """owl:Class -> URIRef"""
70 if ':' not in uri_str:
71 return URIRef(uri_str)
73 prefix, local = uri_str.split(':', 1)
74 return URIRef(self.NAMESPACES[prefix] + local)
76 def _parse_class(self, class_name: str):
77 """Resolve a model class name from the YAML into the class itself.
79 A bare name is looked up in lode.models; "module:Name" points to a class defined by
80 a profile plugin. Raises KeyError for an unknown name, so a typo in the config fails loudly.
81 """
82 if ':' in class_name:
83 try:
84 return profiles.resolve(class_name)
85 except (ImportError, AttributeError) as e:
86 raise KeyError(class_name) from e
87 import lode.models as _models
88 cls = getattr(_models, class_name, None)
89 if cls is None:
90 raise KeyError(class_name)
91 return cls
93 def _parse_value(self, value):
94 """Convert a setter argument from the YAML: model class names become classes.
96 'Literal', booleans and strings that are not model classes are kept as they are.
97 A dict is the long form {targets: <Class>, inverse_of: <setter name>}: only
98 'targets' is resolved, and it is required so a typo fails loudly at load time.
99 """
100 if value == 'Literal':
101 return 'Literal'
102 elif value is True or value is False:
103 return value
104 elif isinstance(value, dict):
105 if 'targets' not in value:
106 raise ValueError(f"setter long form needs 'targets': {value}")
107 return {**value, 'targets': self._parse_value(value['targets'])}
108 elif isinstance(value, list):
109 return [self._parse_value(v) for v in value]
110 elif isinstance(value, str):
111 import lode.models as _models
112 cls = getattr(_models, value, None)
113 if cls is not None:
114 return cls
115 return value
117 # ========== CONFIG ACCESSORS ==========
119 def get_type_mapping(self) -> dict[URIRef, dict]:
120 """rdf:type -> {target_class, setters, ...}"""
121 if self._type_mapping_cache is None:
122 self._type_mapping_cache = {
123 self._parse_uri(uri): self._parse_config(cfg)
124 for uri, cfg in self.config['mapper'].items()
125 if cfg.get('is') == 'class'
126 }
127 return self._type_mapping_cache
129 def get_property_mapping(self) -> dict[URIRef, dict]:
130 """predicate -> {target_classes, setters, handler, ...}"""
131 if self._property_mapping_cache is None:
132 self._property_mapping_cache = {
133 self._parse_uri(uri): self._parse_config(cfg)
134 for uri, cfg in self.config['mapper'].items()
135 if cfg.get('is') == 'predicate'
136 }
137 return self._property_mapping_cache
139 def _parse_config(self, cfg: dict) -> dict:
140 """Parse one mapper entry: resolve class names (and setter arguments) into classes."""
141 parsed = cfg.copy()
143 if 'target_class' in parsed:
144 parsed['target_class'] = self._parse_class(parsed['target_class'])
146 if 'inferred_class' in parsed:
147 parsed['inferred_class'] = self._parse_class(parsed['inferred_class'])
149 if 'target_classes' in parsed:
150 parsed['target_classes'] = [
151 self._parse_class(tc) for tc in parsed['target_classes']
152 ]
154 if 'setters' in parsed:
155 parsed['setters'] = [
156 {k: self._parse_value(v)} if isinstance(item, dict) else item
157 for item in parsed['setters']
158 for k, v in (item.items() if isinstance(item, dict) else [(item, None)])
159 ]
161 return parsed
163 def get_group_axioms(self) -> dict[URIRef, str]:
164 """Group axioms: URI -> handler_name"""
165 return {
166 self._parse_uri(uri): handler
167 for uri, handler in self.config.get('enricher', {}).items()
168 }
170 # ========== HELPER METHODS ==========
172 def get_classifier_predicates(self) -> set[URIRef]:
173 """Predicates whose config declares an 'inferred_class'."""
174 return {
175 pred for pred, cfg in self.get_property_mapping().items()
176 if 'inferred_class' in cfg
177 }
179 def classify_by_predicate(self, uri: Node, graph: Graph) -> type | None:
180 """Classify a subject by looking at the mapped predicates it uses.
181 - inferred_class: type of the subject (BNode restrictions, quantifiers, etc.) -> highest priority.
182 If several predicates have an inferred_class, the most specific class wins (issubclass).
183 - target_classes with 1 element, no inferred_class, classify != false:
184 implicit type of the subject (fallback)
185 - target_classes with 2+ elements: ambiguous, left to the handler -> None
186 - classify: false in the config: the predicate does not classify the subject,
187 it is only used by the setters in phase3 (e.g. XSD facets)
188 """
189 fallback = None
190 inferred = None
191 # one pass over the node's own predicates instead of one graph lookup per
192 # mapped predicate; the loop below still follows the mapping order
193 present = set(graph.predicates(uri))
194 for predicate, cfg in self.get_property_mapping().items():
195 if predicate in present:
196 if 'inferred_class' in cfg:
197 candidate = cfg['inferred_class']
198 if inferred is None or issubclass(candidate, inferred):
199 inferred = candidate
200 elif fallback is None and len(cfg.get('target_classes', [])) == 1:
201 if cfg.get('classify', True):
202 fallback = cfg['target_classes'][0]
203 return inferred if inferred else fallback
205 def get_punning_priority(self):
206 """Return the classes in the order that decides which one wins on a punned IRI."""
207 names = self.config.get('punning_priority', [])
208 return [self._parse_class(n) for n in names]