Coverage for lode / reader / reader.py: 84%

474 statements  

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

1"""Format-independent core of the reader. 

2 

3Reader turns the triples of a graph into model entities in phases. What is 

4specific to OWL, RDF or SKOS lives in the subclasses and in the YAML mapper. 

5""" 

6from collections import deque 

7from rdflib import Graph, URIRef, Node, Literal as RDFlibLiteral, BNode 

8from rdflib.namespace import RDF, RDFS, OWL, SKOS, XSD, Namespace 

9from rdflib.collection import Collection as RDFLibCollection 

10 

11from lode.models import * 

12from lode.helpers.rdf import iri_local_name, iri_namespace 

13 

14import logging 

15logger = logging.getLogger(__name__) 

16 

17class Reader(): 

18 """ 

19 Common base reader for RDF parsing. 

20 

21 Owns the entity cache, the triples-to-entity provenance map and the 

22 generic machinery (get_or_create, _populate_entity, statements); 

23 subclasses implement the phases that differ between formats. 

24 """ 

25 

26 def __init__(self, graph: Graph, entities: dict, configuration): 

27 """Bind the reader to a graph, the shared `entities` dictionary and a config manager. 

28 

29 Fails fast if the config names a handler this reader does not implement. 

30 """ 

31 self.graph = graph 

32 self.entities = entities 

33 self._configuration = configuration 

34 self._property_mapping = configuration.get_property_mapping() 

35 self._triples_map = {} 

36 # Statement triples grouped by subject, built on the first provenance request 

37 self._statements_by_subject = None 

38 # Namespaces now driven by config YAML (key: 'namespaces') 

39 self._allowed_namespaces = self._get_allowed_namespaces() 

40 # Validate all handlers declared in config exist on this entity 

41 self._validate_handlers() 

42 # The reader warnings found while extracting: read by the reader and by the checks 

43 # of the profile, never by the viewers (they get them through the artefact). 

44 self.warnings = [] 

45 

46 def add_warning(self, code, subject, message): 

47 """Record a reader warning with a machine-readable code, its subject and a message.""" 

48 self.warnings.append({'code': code, 'subject': str(subject), 'message': message}) 

49 

50 def _get_allowed_namespaces(self) -> set: 

51 """ 

52 Reads namespaces from config YAML key 'namespaces'. 

53 Subclasses do NOT need to override this anymore. 

54 """ 

55 return set(self._configuration.config.get('namespaces', [])) 

56 

57 

58# ========================================================================== 

59# READER PHASES 

60# ========================================================================== 

61 

62 # Classes that exist only as blank nodes: in phase 1 an IRI is never given one of them. 

63 _BNODE_ONLY_CLASSES: tuple = () 

64 # Class given in phase 5 to the IRIs no earlier phase classified. A format that 

65 # types them differently overrides it (OWL: Individual); None turns the fallback off. 

66 _FALLBACK_CLASS = Resource 

67 

68 def phase1_classify_from_predicates(self): 

69 """Phase 1: create entities for subjects whose predicates reveal their class. 

70 

71 A subject that uses a mapped predicate gets the class the YAML implies for it 

72 (classify_by_predicate), even without an rdf:type. IRIs are created while 

73 scanning; blank nodes are collected and created at the end. A format with 

74 constructs of its own extends this method and calls super() first. A format 

75 that does not classify from predicates at all overrides the whole phase 

76 (SKOS does). 

77 """ 

78 classified = {} 

79 # a node uses several mapped predicates: classify it once, not once per predicate 

80 tried = set() 

81 

82 for pred in self._property_mapping: 

83 for node in self.graph.subjects(pred, None): 

84 if node in self.entities or node in tried: 

85 continue 

86 tried.add(node) 

87 python_class = self._configuration.classify_by_predicate(node, self.graph) 

88 if not python_class: 

89 continue 

90 if isinstance(node, BNode): 

91 classified.setdefault(node, python_class) 

92 elif isinstance(node, URIRef) and not issubclass(python_class, self._BNODE_ONLY_CLASSES): 

93 self.get_or_create(node, python_class, populate=False) 

94 

95 for bnode, python_class in classified.items(): 

96 self.get_or_create(bnode, python_class, populate=False) 

97 

98 

99 def phase2_create_from_types(self): 

100 """Phase 2: create entities from the rdf:type declarations of the graph. 

101 

102 Every subject typed with a type the YAML maps gets an entity of the mapped 

103 class, and the triple that says so becomes part of its provenance. The static 

104 setters of the mapping (constants such as set_is_ordered: True) are applied to 

105 every entity of the subject, also to one created by phase 1. A format with 

106 more to do for its types extends this and calls super() first. 

107 """ 

108 type_mapping = self._configuration.get_type_mapping() 

109 

110 for rdf_type, config in type_mapping.items(): 

111 py_class = config.get('target_class') 

112 if not py_class: 

113 continue 

114 for uri in self.graph.subjects(RDF.type, rdf_type): 

115 inst = self.get_or_create(uri, py_class, populate=False) 

116 if inst is not None: 

117 self._track(inst, (uri, RDF.type, rdf_type)) 

118 # Apply static setters (e.g. set_is_transitive: True) always, 

119 # even if entity already existed in cache from phase1. 

120 if 'setters' in config: 

121 for entity in self.entities.get(uri, set()): 

122 self._apply_setters_immediate(entity, config['setters']) 

123 

124 

125 def phase3_populate_properties(self): 

126 """Phase 3: fill every entity from its triples, through the property mapping. 

127 

128 Every cached entity goes through _populate_entity, which sends each 

129 predicate to the setters or handlers declared in the YAML mapper. A format 

130 overrides this only to add steps, and calls super() first. 

131 """ 

132 for uri in list(self.entities.keys()): 

133 # both levels are copied: populating an entity can add new ones to the cache 

134 for entity in list(self.entities[uri]): 

135 self._populate_entity(entity, uri) 

136 

137 def phase4_process_group_axioms(self): 

138 """Phase 4: process axioms that involve several entities at once (e.g. AllDisjointClasses). 

139 

140 Driven by the 'enricher' section of the YAML: each entry maps an rdf:type to 

141 the name of a handler, which receives every subject of that type. A format 

142 with no group axioms of its own can keep the default, or override it with a 

143 no-op when the inherited entries do not apply. 

144 """ 

145 for axiom_type, handler_name in self._configuration.get_group_axioms().items(): 

146 for uri in self.graph.subjects(RDF.type, axiom_type): 

147 # the handler is guaranteed to exist: _validate_handlers checks it at init 

148 getattr(self, handler_name)(uri) 

149 

150 def phase5_fallback(self): 

151 """Phase 5: give a class (and the format defaults) to whatever is still unclassified. 

152 

153 Every IRI subject that no earlier phase classified becomes an entity of 

154 _FALLBACK_CLASS, populated like any other. IRIs of the format's own 

155 vocabularies are skipped: they are the language, not data. A format extends 

156 this and calls super() first, so its own defaults reach the new entities too. 

157 """ 

158 if self._FALLBACK_CLASS is None: 

159 return 

160 

161 vocabularies = tuple(self._allowed_namespaces) 

162 # set(): each subject once, and a stable list while entities are created 

163 for subj in set(self.graph.subjects()): 

164 if (isinstance(subj, URIRef) and subj not in self.entities 

165 and not str(subj).startswith(vocabularies)): 

166 self.get_or_create(subj, self._FALLBACK_CLASS) 

167 

168 def phase6_create_statements(self): 

169 """Phase 6: reify every triple no earlier phase consumed as a Statement. 

170 

171 Structural list triples and structural vocabulary subjects without a type 

172 are skipped; triples already tracked by an entity are not duplicated. 

173 """ 

174 for subj, pred, obj in self.graph: 

175 if pred in [RDF.first, RDF.rest, RDF.nil, OWL.distinctMembers, OWL.members]: 

176 continue 

177 if isinstance(subj, URIRef): 

178 subj_str = str(subj) 

179 # structural entities from taken namespaces are not used for statements  

180 if any(subj_str.startswith(ns) for ns in self._allowed_namespaces): 

181 if not any(True for _ in self.graph.objects(subj, RDF.type)): 

182 continue 

183 if self._is_triple_mapped(subj, pred, obj): 

184 continue 

185 self._create_statement_for_triple(subj, pred, obj) 

186 

187 # ========== CONFIG -> READER VALIDATION ========== 

188 

189 def _validate_handlers(self): 

190 """ 

191 Fail-fast: check that every handler declared in the config 

192 exists as a method on this Reader entity. 

193 Raises AttributeError immediately, before any parsing. 

194 """ 

195 errors = [] 

196 

197 for uri_str, cfg in self._configuration.config.get('mapper', {}).items(): 

198 handler_name = cfg.get('handler') 

199 if handler_name and not hasattr(self, handler_name): 

200 errors.append( 

201 f"mapper['{uri_str}'].handler='{handler_name}' " 

202 f"not found on {type(self).__name__}" 

203 ) 

204 

205 for uri_str, handler_name in self._configuration.config.get('enricher', {}).items(): 

206 if isinstance(handler_name, str) and not hasattr(self, handler_name): 

207 errors.append( 

208 f"enricher['{uri_str}']='{handler_name}' " 

209 f"not found on {type(self).__name__}" 

210 ) 

211 

212 if errors: 

213 raise AttributeError( 

214 f"Config/Reader contract violations in {type(self).__name__}:\n" 

215 + "\n".join(f" - {e}" for e in errors) 

216 ) 

217 

218 # ========== PROVENANCE ========== (note: _triples_map is written only by these three methods.) 

219 

220 def _track(self, entity, *triples): 

221 """Attribute one or more triples to the provenance of `entity`.""" 

222 self._triples_map.setdefault(entity, set()).update(triples) 

223 

224 def _move_tracking(self, old, new): 

225 """Move the provenance from `old` to `new` when an entity is promoted or replaced.""" 

226 if old in self._triples_map: 

227 self._triples_map.setdefault(new, set()).update(self._triples_map.pop(old)) 

228 

229 # ========== UTILITIES ========== 

230 

231 def _apply_setters_immediate(self, entity, setters_config): 

232 """Apply the static setter values of a mapping directly to an entity. 

233 

234 No RDF object is resolved: this is for the constants declared next to an 

235 'is: class' entry (set_is_symmetric: True) and used in phase 2. 

236 """ 

237 for setter_item in setters_config: 

238 if isinstance(setter_item, dict): 

239 for setter_name, value in setter_item.items(): 

240 if hasattr(entity, setter_name): 

241 getattr(entity, setter_name)(value) 

242 else: 

243 if hasattr(entity, setter_item): 

244 getattr(entity, setter_item)() 

245 

246 

247 def _traverse_hierarchy( 

248 self, 

249 start: object, 

250 next_getter: str, 

251 direction: str = "up", # "up" | "down" | "both" 

252 collect: callable = None, # (node) -> value | None — stops and returns when not None 

253 visit_all: callable = None, # (node) -> None — visits every node without stopping 

254 ) -> object | None: 

255 """ 

256 Generic BFS traversal along a property hierarchy. 

257 

258 Parameters 

259 ---------- 

260 start : starting node (Python model entity) 

261 next_getter : name of the getter that returns the next nodes in the 

262 'up' direction (e.g. 'get_is_sub_property_of'). 

263 For 'down' the cache is scanned for entities that list 

264 `start` as one of their `next_getter` targets. 

265 direction : 'up' - follow next_getter only 

266 'down' - scan cache for reverse links only 

267 'both' - up first, then down 

268 collect : callable(node) -> value | None 

269 Called on every visited node (including start). 

270 When it returns a non-None value the traversal stops 

271 immediately and that value is returned. 

272 visit_all : callable(node) -> None 

273 Called on every visited node; traversal never stops early. 

274 Mutually exclusive with collect (collect takes priority). 

275 

276 Returns the first non-None value from collect, or None if visit_all is used. 

277 """ 

278 visited = set() 

279 queue = deque([start]) 

280 result = None 

281 children = None # reverse index, built once per call and only for "down" 

282 

283 while queue: 

284 current = queue.popleft() 

285 if id(current) in visited: 

286 continue 

287 visited.add(id(current)) 

288 

289 # --- collect / visit --- 

290 if collect: 

291 value = collect(current) 

292 if value is not None: 

293 return value 

294 elif visit_all: 

295 visit_all(current) 

296 

297 # --- enqueue next nodes --- 

298 if direction in ("up", "both"): 

299 getter = getattr(current, next_getter, None) 

300 if getter: 

301 nexts = getter() 

302 if nexts: 

303 if not isinstance(nexts, list): 

304 nexts = [nexts] 

305 queue.extend(nexts) 

306 

307 if direction in ("down", "both"): 

308 if children is None: 

309 # one scan of the cache instead of one per visited node 

310 children = {} 

311 for instances_set in self.entities.values(): 

312 for inst in instances_set: 

313 getter = getattr(inst, next_getter, None) 

314 if getter: 

315 parents = getter() or [] 

316 if not isinstance(parents, list): 

317 parents = [parents] 

318 for p in {id(p): p for p in parents}.values(): 

319 children.setdefault(id(p), []).append(inst) 

320 for inst in children.get(id(current), ()): 

321 if inst is not current and id(inst) not in visited: 

322 queue.append(inst) 

323 

324 return None 

325 

326 def _create_literal(self, rdflib_literal): 

327 """Return the model Literal for an rdflib literal, one per distinct lexical form. 

328 

329 The entity is cached under a LITERAL:: key built from lexical form, language 

330 and datatype: two literals with the same text but a different language tag 

331 or datatype are different values and must not share one entity. 

332 """ 

333 literal_key = ( 

334 f"LITERAL::{rdflib_literal}" 

335 f"@{rdflib_literal.language or ''}" 

336 f"^^{rdflib_literal.datatype or ''}" 

337 ) 

338 if literal_key in self.entities: 

339 return next(iter(self.entities[literal_key])) 

340 

341 literal = Literal() 

342 literal.set_has_value(str(rdflib_literal)) 

343 

344 if rdflib_literal.language: 

345 literal.set_has_language(rdflib_literal.language) 

346 

347 if rdflib_literal.datatype: 

348 dt = self.get_or_create(rdflib_literal.datatype, Datatype) 

349 if dt: 

350 literal.set_has_type(dt) 

351 

352 self.entities[literal_key] = {literal} 

353 return literal 

354 

355 def _is_rdf_collection(self, node: Node) -> bool: 

356 """Return True if the node is the head of an RDF list (it has an rdf:first).""" 

357 return (node, RDF.first, None) in self.graph 

358 

359 def _entity_matches_target(self, entity, target_classes: list) -> bool: 

360 """Return True if the entity is of one of the target classes, or a subclass of one.""" 

361 instance_class = entity.__class__ 

362 if instance_class in target_classes: 

363 return True 

364 for parent_class in instance_class.__mro__[1:]: 

365 if parent_class in target_classes: 

366 return True 

367 return False 

368 

369 def _resolve_target_class(self, obj, candidates: list) -> type: 

370 """Pick, among the candidate model classes, the one `obj` is declared as. 

371 

372 An entity already cached for `obj` wins (punning keeps its class);  

373 otherwise falls back to Resource. 

374 """ 

375 cached = {type(c) for c in self.entities.get(obj, ())} 

376 return next((c for c in candidates if c in cached), Resource) 

377 

378 

379 def _add_link(self, target, setter_name: str, value) -> None: 

380 """Call `target.<setter_name>(value)` unless `value` is already linked. 

381 

382 The model setters for match relations append blindly, so when both sides of a 

383 link are in the data (A broadMatch B, B narrowMatch A) the check here keeps 

384 each side listed once. Targets without that setter are skipped silently: the 

385 inverse is optional, e.g. for a Restriction or TruthFunction. 

386 """ 

387 if not hasattr(target, setter_name): 

388 return 

389 getter = getattr(target, setter_name.replace('set_', 'get_', 1), None) 

390 current = getter() if getter else None 

391 if isinstance(current, (list, tuple, set)) and value in current: 

392 return 

393 getattr(target, setter_name)(value) 

394 

395 

396 def _apply_setters(self, entity, setters_config, obj): 

397 """Call the setters declared in the config on `entity`, using `obj` as the value. 

398 

399 Per entry: 'Literal' builds a Literal from obj; a bool or a string is passed 

400 as a constant; a model class resolves obj to an entity of that class (the 

401 punned entity of the same class if one is cached); anything else passes 

402 obj as is. An entry with no value calls the setter with no argument. 

403 Structural vocabulary URIs are never added to has_type. 

404 

405 A dict value is the long form: targets is the class, inverse_of the  

406 setter called on the target to register the subject back. 

407 """ 

408 for setter_item in setters_config: 

409 if isinstance(setter_item, dict): 

410 for setter_name, value_type in setter_item.items(): 

411 if not hasattr(entity, setter_name): 

412 continue 

413 setter = getattr(entity, setter_name) 

414 # extracts declarative inverses (implicit) 

415 inverse_name = None 

416 if isinstance(value_type, dict): 

417 inverse_name = value_type.get('inverse_of') 

418 value_type = value_type['targets'] 

419 if isinstance(value_type, list): 

420 value_type = self._resolve_target_class(obj, value_type) 

421 if value_type == 'Literal': 

422 try: 

423 setter(self._create_literal(obj)) 

424 except: 

425 continue 

426 elif isinstance(value_type, bool): 

427 setter(value_type) 

428 elif isinstance(value_type, str): 

429 setter(value_type) 

430 elif isinstance(value_type, type): 

431 # Don't add structural OWL/RDFS/RDF URIs to has_type 

432 if setter_name == 'set_has_type' and isinstance(obj, URIRef): 

433 obj_str = str(obj) 

434 if any(obj_str.startswith(ns) for ns in self._allowed_namespaces) and obj not in (OWL.Thing, OWL.Nothing, RDFS.Literal): 

435 continue 

436 # punning: prefer the entity of obj with the same class as the subject 

437 obj_instance = next( 

438 (c for c in self.entities.get(obj, ()) 

439 if type(c) is type(entity) and isinstance(c, value_type)), 

440 None 

441 ) or self.get_or_create(obj, value_type) 

442 if not obj_instance: 

443 continue 

444 if inverse_name: 

445 self._add_link(entity, setter_name, obj_instance) 

446 self._add_link(obj_instance, inverse_name, entity) 

447 else: 

448 setter(obj_instance) 

449 else: 

450 setter(obj) 

451 else: 

452 if hasattr(entity, setter_item): 

453 getattr(entity, setter_item)() 

454 

455 def _handle_collection_object(self, entity, predicate, collection_uri): 

456 """Resolve an RDF list used as an object and pass its members to the first matching setter. 

457 

458 Failures are logged and swallowed: one malformed list must not stop the read. 

459 """ 

460 try: 

461 collection = RDFLibCollection(self.graph, collection_uri) 

462 items = [] 

463 for item in collection: 

464 if isinstance(item, RDFlibLiteral): 

465 items.append(self._create_literal(item)) 

466 else: 

467 item_instance = self.get_or_create(item, Resource) 

468 if item_instance: 

469 items.append(item_instance) 

470 

471 config = self._property_mapping.get(predicate, {}) 

472 for setter_item in config.get('setters', []): 

473 if isinstance(setter_item, dict): 

474 for setter_name in setter_item: 

475 if hasattr(entity, setter_name): 

476 getattr(entity, setter_name)(items) 

477 break 

478 except Exception: 

479 logger.warning("Collection handling failed on %s (predicate %s)", 

480 entity, predicate, exc_info=True) 

481 

482 # ========== READER CORE ========== 

483 

484 def get_or_create(self, id: Node, python_class: type = None, populate: bool = True): 

485 """Return the model entity for a node, creating (and populating) it when needed. 

486 

487 Literals go through _create_literal; built-in datatypes and undeclared XSD 

488 terms are always Datatype. A cached entity is reused; a single cached 

489 entity of a broader class is promoted to the requested one, so punning 

490 keeps working. Returns None, after logging, when creation fails. 

491 """ 

492 try: 

493 

494 if isinstance(id, RDFlibLiteral): 

495 return self._create_literal(id) 

496 

497 DATATYPE_BUILTINS = frozenset({ 

498 RDFS.Literal, RDF.XMLLiteral, RDF.HTML, 

499 RDF.PlainLiteral, RDF.langString, RDF.JSON, 

500 OWL.real, OWL.rational 

501 }) 

502 

503 if isinstance(id, URIRef): 

504 if id in DATATYPE_BUILTINS: 

505 python_class = Datatype # built-ins: always Datatype, no exceptions 

506 elif str(id).startswith(str(XSD)) and str(id) != str(XSD): 

507 if (id, RDF.type, None) not in self.graph: 

508 python_class = Datatype # XSD: only if explicitly declared as something else 

509 

510 # Individual punning: do not override existing non-Individual types 

511 if python_class == Individual and id in self.entities: 

512 is_named_individual = (id, RDF.type, OWL.NamedIndividual) in self.graph 

513 if not is_named_individual: 

514 for existing in self.entities[id]: 

515 if not isinstance(existing, Individual): 

516 return existing 

517 

518 if id in self.entities: 

519 if isinstance(id, BNode): 

520 return next(iter(self.entities[id])) 

521 if isinstance(id, URIRef): 

522 for obj in self.entities[id]: 

523 if isinstance(obj, python_class): 

524 return obj 

525 # Promote only if there is exactly one cached entity and 

526 # the requested class is strictly more specific than it 

527 # so punning is mantained 

528 cached = list(self.entities[id]) 

529 if len(cached) == 1 and issubclass(python_class, type(cached[0])): 

530 old = cached[0] 

531 new = python_class() 

532 new.__dict__.update(old.__dict__) 

533 self.entities[id].discard(old) 

534 self.entities[id].add(new) 

535 self._move_tracking(old, new) 

536 return new 

537 

538 entity = python_class() 

539 if id not in self.entities: 

540 self.entities[id] = set() 

541 self.entities[id].add(entity) 

542 entity.set_has_identifier(str(id)) 

543 

544 if populate: 

545 self._populate_entity(entity, id) 

546 

547 return entity 

548 

549 except Exception: 

550 logger.warning("Cannot create %s for %s", 

551 python_class.__name__ if python_class else "Unknown", id, exc_info=True) 

552 return None 

553 

554 def _populate_entity(self, entity, uri: Node): 

555 """Fill an entity from the triples of `uri`, following the property mapping. 

556 

557 Only predicates in the allowed namespaces are read. A configured handler or 

558 setters list runs for each predicate; failures are logged and skipped. Every 

559 handled triple is recorded in the provenance map, except the rdf:type that 

560 selected the entity's class. 

561 """ 

562 if isinstance(uri, URIRef): 

563 entity.set_has_identifier(str(uri)) 

564 elif isinstance(uri, BNode): 

565 entity.has_identifier = str(uri) 

566 

567 for predicate, obj in self.graph.predicate_objects(uri): 

568 if iri_namespace(str(predicate)) not in self._allowed_namespaces: 

569 continue 

570 

571 handled = False 

572 config = self._property_mapping.get(predicate) 

573 

574 if config is not None: 

575 target_classes = config.get('target_classes', []) 

576 if target_classes and not self._entity_matches_target(entity, target_classes): 

577 continue 

578 

579 if 'handler' in config: 

580 try: 

581 # An explicit False means "not admissible for this entity". 

582 result = getattr(self, config['handler'])(entity, uri, predicate, obj, None) 

583 handled = result is not False 

584 except Exception: 

585 logger.warning("Handler %s failed on %s (predicate %s)", 

586 config['handler'], uri, predicate, exc_info=True) 

587 elif 'setters' in config: 

588 try: 

589 self._apply_setters(entity, config['setters'], obj) 

590 handled = True 

591 except Exception: 

592 logger.warning("Setters failed on %s (predicate %s)", 

593 uri, predicate, exc_info=True) 

594 

595 if not handled and config is None and self._is_rdf_collection(obj): 

596 self._handle_collection_object(entity, predicate, obj) 

597 handled = True 

598 

599 if handled and not (predicate == RDF.type and obj in self._configuration.get_type_mapping()): 

600 self._track(entity, (uri, predicate, obj)) 

601 

602 # ========== HELPERS ========== 

603 

604 def _is_triple_mapped(self, subj, pred, obj) -> bool: 

605 """Return True if some entity already tracks this triple in its provenance.""" 

606 if subj not in self.entities: 

607 return False 

608 entities = self.entities[subj] 

609 instances_list = entities if isinstance(entities, set) else [entities] 

610 for entity in instances_list: 

611 if entity in self._triples_map: 

612 if (subj, pred, obj) in self._triples_map[entity]: 

613 return True 

614 return False 

615 

616 def _convert_collection_to_container(self, collection_uri): 

617 """Return the Container that represents an RDF list, building and caching it once. 

618 

619 The container is cached before its members are resolved, so a list that 

620 contains itself cannot loop forever. 

621 """ 

622 if collection_uri in self.entities: 

623 for cached in self.entities[collection_uri]: 

624 if isinstance(cached, Container): 

625 return cached 

626 

627 container = Container() 

628 container.set_has_identifier(str(collection_uri)) 

629 

630 if collection_uri not in self.entities: 

631 self.entities[collection_uri] = set() 

632 self.entities[collection_uri].add(container) 

633 

634 try: 

635 collection = RDFLibCollection(self.graph, collection_uri) 

636 members = [] 

637 for item in collection: 

638 if isinstance(item, RDFlibLiteral): 

639 members.append(self._create_literal(item)) 

640 else: 

641 member_instance = self.get_or_create(item, Resource) 

642 if member_instance: 

643 members.append(member_instance) 

644 container.set_has_members(members) 

645 except Exception: 

646 logger.warning("Collection to container conversion failed for %s", 

647 collection_uri, exc_info=True) 

648 

649 return container 

650 

651 def _create_statement_for_triple(self, subj, pred, obj): 

652 """Reify one triple as a Statement, unless its predicate is already mapped. 

653 

654 Lists in object position become Containers and literals become Literals. 

655 """ 

656 

657 if pred in self._property_mapping: 

658 return 

659 

660 statement = Statement() 

661 stmt_bnode = BNode() 

662 statement.set_has_identifier(str(stmt_bnode)) 

663 

664 self._track(statement, (subj, pred, obj)) 

665 

666 subj_obj = self.get_or_create(subj, Resource) 

667 if subj_obj: 

668 statement.set_has_subject(subj_obj) 

669 

670 pred_inst = self.get_or_create(pred, Property) 

671 if pred_inst: 

672 statement.set_has_predicate(pred_inst) 

673 

674 if self._is_rdf_collection(obj): 

675 obj_inst = self._convert_collection_to_container(obj) 

676 elif isinstance(obj, RDFlibLiteral): 

677 obj_inst = self._create_literal(obj) 

678 else: 

679 obj_inst = self.get_or_create(obj, Resource) 

680 

681 if obj_inst: 

682 statement.set_has_object(obj_inst) 

683 

684 if stmt_bnode not in self.entities: 

685 self.entities[stmt_bnode] = set() 

686 self.entities[stmt_bnode].add(statement) 

687 

688 def _is_unmapped_structured_bnode(self, node) -> bool: 

689 """A BNode is a structured Statement value if: 

690 - it's a BNode (not URIRef, not Literal) 

691 - it's not already classified by any phase (a bare Resource in the cache is 

692 only a placeholder made by a mapped predicate such as rdfs:seeAlso) 

693 - it has at least one outgoing triple 

694 - none of its outgoing predicates carry a useful rdf:type for our model 

695 (i.e. it's not declaring itself as a typed entity) 

696 """ 

697 if not isinstance(node, BNode): 

698 return False 

699 if any(type(i) is not Resource for i in self.entities.get(node, ())): 

700 return False 

701 has_out = False 

702 for _ in self.graph.predicate_objects(node): 

703 has_out = True 

704 break 

705 if not has_out: 

706 return False 

707 # if it declares an rdf:type that we know how to map, leave it alone 

708 for t in self.graph.objects(node, RDF.type): 

709 if t in self._configuration.get_type_mapping(): 

710 return False 

711 return True 

712 

713 def _create_nested_statement(self, node): 

714 """Materialises an unmapped structured BNode as a Statement whose own 

715 triples become its annotations. Recurses for nested structured BNodes. 

716 """ 

717 statement = Statement() 

718 statement.set_has_identifier(str(node)) 

719 

720 # drop the placeholder Resource: the node is represented by the Statement 

721 self.entities[node] = {statement} 

722 

723 for p, o in self.graph.predicate_objects(node): 

724 self._track(statement, (node, p, o)) 

725 

726 # The predicate becomes an Annotation if not otherwise known 

727 if p in self.entities: 

728 pred_inst = next( 

729 (i for i in self.entities[p] if isinstance(i, Property)), 

730 None 

731 ) 

732 else: 

733 pred_inst = None 

734 if pred_inst is None: 

735 pred_inst = Annotation() 

736 pred_inst.set_has_identifier(str(p)) 

737 self.entities.setdefault(p, set()).add(pred_inst) 

738 

739 # Resolve the object recursively 

740 if self._is_rdf_collection(o): 

741 o_inst = self._convert_collection_to_container(o) 

742 elif isinstance(o, RDFlibLiteral): 

743 o_inst = self._create_literal(o) 

744 elif self._is_unmapped_structured_bnode(o): 

745 o_inst = self._create_nested_statement(o) 

746 else: 

747 o_inst = self.get_or_create(o, Resource) 

748 

749 # The first (predicate, object) pair fills the Statement slots; 

750 # additional pairs are stored as side annotations on the Statement 

751 # itself via setattr (a Statement keeps its own __dict__). 

752 if statement.get_has_predicate() is None: 

753 statement.set_has_predicate(pred_inst) 

754 if o_inst: 

755 statement.set_has_object(o_inst) 

756 else: 

757 # extra triples live as ad-hoc attributes keyed by the predicate label 

758 attr_name = iri_local_name(p) # rdf helper 

759 existing = getattr(statement, attr_name, None) 

760 if existing is None: 

761 setattr(statement, attr_name, o_inst) 

762 elif isinstance(existing, list): 

763 existing.append(o_inst) 

764 else: 

765 setattr(statement, attr_name, [existing, o_inst]) 

766 

767 return statement 

768 

769 def _get_punning_dominant(self, uri): 

770 """Return the entity that wins when an IRI is used as several things (punning). 

771 

772 The winner follows the config's punning priority; with no match, any cached one. 

773 """ 

774 if uri not in self.entities: 

775 return None 

776 cached = self.entities[uri] 

777 if not cached: 

778 return None 

779 if len(cached) == 1: 

780 return next(iter(cached)) 

781 priority = self._configuration.get_punning_priority() 

782 for cls in priority: 

783 for inst in cached: 

784 if type(inst) is cls: 

785 return inst 

786 return next(iter(cached)) 

787 

788 def _is_punning_subordinate(self, entity, uri): 

789 """Return True if `entity` loses against another entity of the same IRI.""" 

790 dom = self._get_punning_dominant(uri) 

791 return dom is not None and dom is not entity 

792 

793 # ========== PROVENANCE SUBGRAPH ========== 

794 

795 def build_provenance_subgraph(self, entity): 

796 """ 

797 Build the RDF subgraph that provenanced `entity`: 

798 - direct triples from _triples_map[entity] 

799 - BNode-transitive closure on object positions 

800 - reified Statements with `entity` as has_subject 

801 - format-specific axioms (hook: _add_axiom_provenance) 

802 

803 No prefix is bound on the subgraph: callers only iterate its triples, and 

804 Artefact.with_provenance binds the artefact prefixes on the graph it serializes. 

805 Binding them here cost one bind per prefix per entity, the largest share of 

806 the provenance time in a static build. 

807 """ 

808 from rdflib import Graph, BNode 

809 

810 sub = Graph(bind_namespaces="none") 

811 

812 # 1. direct triples 

813 source_triples = self._triples_map.get(entity, set()) 

814 for t in source_triples: 

815 sub.add(t) 

816 

817 # 2. BNode-transitive closure on objects 

818 seen = set() 

819 for (_s, _p, o) in source_triples: 

820 if isinstance(o, BNode): 

821 self._expand_bnode_into(o, sub, seen) 

822 

823 # 3. reified Statements pointing at entity 

824 for other_triples in self._get_statements_by_subject().get(id(entity), ()): 

825 for t in other_triples: 

826 sub.add(t) 

827 _, _, o = t 

828 if isinstance(o, BNode) and o not in seen: 

829 self._expand_bnode_into(o, sub, seen) 

830 

831 # 4. format-specific axioms (hook) 

832 self._add_axiom_provenance(entity, sub) 

833 

834 return sub 

835 

836 def _get_statements_by_subject(self) -> dict: 

837 """Group the triples of every reified Statement by the id of its subject entity. 

838 

839 Built once, on the first provenance request, so each request is a lookup instead of 

840 a scan of the whole triples map (quadratic in a static build). The map is complete 

841 by then: provenance is only asked for after the extraction phases. 

842 """ 

843 if self._statements_by_subject is None: 

844 index = {} 

845 for inst, triples in self._triples_map.items(): 

846 if isinstance(inst, Statement): 

847 subject = inst.get_has_subject() 

848 if subject is not None: 

849 index.setdefault(id(subject), []).append(triples) 

850 self._statements_by_subject = index 

851 return self._statements_by_subject 

852 

853 def _expand_bnode_into(self, bn, sub, seen): 

854 """Add `bn` and its BNode-transitive closure to `sub`.""" 

855 from rdflib import BNode 

856 stack = [bn] 

857 while stack: 

858 n = stack.pop() 

859 if n in seen: 

860 continue 

861 seen.add(n) 

862 for p, o in self.graph.predicate_objects(n): 

863 sub.add((n, p, o)) 

864 if isinstance(o, BNode) and o not in seen: 

865 stack.append(o) 

866 

867 def _add_axiom_provenance(self, entity, sub): 

868 """Hook for subclasses. Default: no format-specific axioms.""" 

869 pass 

870