Coverage for lode / viewer / base_viewer.py: 96%

342 statements  

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

1"""Generic viewer: turns model entities into the dictionaries the HTML templates render. 

2 

3Format-specific viewers (OWL, RDF, SKOS) extend it with their table of contents 

4and display names. It also serializes the provenance of each entity. 

5""" 

6import hashlib 

7import re 

8from typing import Dict, List, Optional, Tuple 

9from pathlib import Path 

10from rdflib import Graph, URIRef 

11 

12from lode.models import Literal, Model, Resource, Statement 

13from lode.helpers.formats import QUAD_SERIALIZATION_FORMATS, SERIALIZATION_FORMATS 

14from lode.helpers.rdf import iri_local_name 

15from lode.viewer.contract import resolve_links, to_model 

16from lode.helpers.links import Links 

17from lode.viewer.view_data import Card, TocEntry, TocSection, TypeLabel, Value, ViewData, new_value 

18 

19import lode.models as _models 

20 

21from lode.viewer.helpers import ( 

22 annotation_sort_key, 

23 clean_name, 

24 load_viewer_config, 

25 safe_serialize, 

26) 

27 

28_TEMPLATES_DIR = Path(__file__).resolve().parent.parent / "templates" 

29 

30class BaseViewer: 

31 """Base viewer to display the entities extracted by the Reader. 

32 

33 It orchestrates the view: everything that differs between formats (display 

34 names, table of contents, card template, vocabulary) is read from 

35 the viewer.yaml of the artefact's profile. Subclasses override only the 

36 steps that really need code. 

37 """ 

38 

39 # ========================================================================== 

40 # SETUP 

41 # ========================================================================== 

42 

43 def __init__(self, artefact): 

44 """Bind the viewer to an artefact and load the viewer config of its profile. 

45 

46 An artefact without a profile gets the generic flat list view. 

47 """ 

48 self.artefact = artefact 

49 self._internal_iris = None 

50 self._config = ( 

51 load_viewer_config(artefact.profile) if artefact.profile 

52 else {"type_map": {}, "toc": [], 

53 "vocabulary": {}, "characteristics": []} 

54 ) 

55 

56 def get_toc_config(self) -> List[Tuple[str, str, str]]: 

57 """Return the table of contents: (class name, section id, type_map key) in display order.""" 

58 return [tuple(entry) for entry in self._config["toc"]] 

59 

60 def template_dirs(self) -> List[Path]: 

61 """Return the folders the page templates are searched in; the first match wins. 

62 

63 A format keeps the templates that differ from the base ones in the templates/ folder of its profile: 

64 a file with the same name there replaces the base file, and every file it does not 

65 provide comes from the base. The adapters build their Jinja loader from this list, so 

66 the viewer itself knows nothing about Jinja. 

67 """ 

68 profile = self.artefact.profile 

69 own = profile.path() / "templates" if profile else None 

70 return [own, _TEMPLATES_DIR] if own and own.is_dir() else [_TEMPLATES_DIR] 

71 

72 

73 # ========================================================================== 

74 # 2. ARTEFACT ACCESS 

75 # ========================================================================== 

76 

77 def get_artefact_ns(self) -> str: 

78 """Return the namespace of the documented semantic artefact (its IRI ending in '/' or '#'), or ''. 

79 

80 Read from the artefact: the Reader derives it from the artefact IRI. 

81 """ 

82 return str(self.artefact.artefact_base_iri or '') 

83 

84 def _has_local_triples(self, uri) -> bool: 

85 """Return True if the graph has at least one triple whose subject is this IRI.""" 

86 if not uri: 

87 return False 

88 return (URIRef(str(uri)), None, None) in self.artefact.graph 

89 

90 # ========================================================================== 

91 # 3. NAVIGATION RULES 

92 # ========================================================================== 

93 

94 def _is_internal(self, uri) -> bool: 

95 """Return True if the IRI belongs to a browsable entity of this documentation. 

96 

97 The set of IRIs is built once, on first use. 

98 """ 

99 if not uri: 

100 return False 

101 if self._internal_iris is None: 

102 self._internal_iris = { 

103 str(i.get_has_identifier()) 

104 for i in self.get_toc_entities() 

105 if i.get_has_identifier() 

106 } 

107 return str(uri) in self._internal_iris 

108 

109 def _is_toc_entity(self, entity) -> bool: 

110 """Browsable (own card + clickable link) iff its type is in get_toc_config.  

111 Resources not listed in get_o_config are shown when mentioned as plain text  

112 in cards (external-ref), just never linked.""" 

113 toc_keys = {key for key, _id, _title in self.get_toc_config()} 

114 if type(entity).__name__ not in toc_keys: 

115 return False 

116 return self._has_local_triples(entity.get_has_identifier()) 

117 

118 def get_toc_entities(self) -> List: 

119 """Return the entities that get their own card and link (the browsable entities).""" 

120 return [i for i in self.artefact.get_entities() if self._is_toc_entity(i)] 

121 

122 # ========================================================================== 

123 # 3. LABELS AND LANGUAGES 

124 # ========================================================================== 

125 

126 def _clean_name(self, name: str) -> str: 

127 """Turn an attribute or getter name into a display label, using this viewer's vocabulary.""" 

128 return clean_name(name, self._config["vocabulary"]) 

129 

130 def _select_by_language(self, values: List, language: Optional[str] = None) -> List: 

131 """Keep the values of one property in the best available language. 

132 

133 The choice is made per property, not per literal: only with all the 

134 siblings in view can a fallback exist. Tags follow BCP 47, so they are 

135 compared case-insensitively. Order of preference (RFC 4647 lookup): the 

136 exact tag, the tag truncated from the right (en-GB, then en), 'en', 

137 untagged literals, then every literal sorted by tag (nothing disappears). 

138 Non-literal values always pass, and the input order is kept. 

139 """ 

140 lits = [v for v in values if isinstance(v, Literal)] 

141 parts = (language or "en").strip().lower().split("-") 

142 # shortcut: no skipping of singleton subtags (zh-x-private), upgrade if such tags matter 

143 chain = ["-".join(parts[:i]) for i in range(len(parts), 0, -1)] + ["en"] 

144 

145 def tagged(wanted: str) -> List: 

146 """Literals whose tag is exactly `wanted`, ignoring case.""" 

147 return [l for l in lits if (l.get_has_language() or "").lower() == wanted] 

148 

149 chosen = (next((m for m in map(tagged, chain) if m), None) 

150 or [l for l in lits if not l.get_has_language()] 

151 or sorted(lits, key=lambda l: str(l.get_has_language() or ""))) 

152 keep = {id(l) for l in chosen} 

153 return [v for v in values if not isinstance(v, Literal) or id(v) in keep] 

154 

155 def _get_best_label(self, resource, language: Optional[str] = None) -> Optional[str]: 

156 """Gets the best label to display: language > preferred_label > label > identifier.""" 

157 

158 # Preferred labels come first, so they win within the same language 

159 labels = list(resource.get_has_preferred_label()) + list(resource.get_has_label()) 

160 selected = self._select_by_language(labels, language) 

161 if selected: 

162 return selected[0].get_has_value() 

163 

164 # Final Fallback: The URI Identifier 

165 resource_id = resource.get_has_identifier() 

166 if resource_id: 

167 clean_resource_id = iri_local_name(resource_id) 

168 # ONLY clean the identifier! 

169 return self._clean_name(clean_resource_id) 

170 

171 return None 

172 

173 # ========================================================================== 

174 # 3. VIEW DATA 

175 # ==========================================================================  

176 

177 def view(self, resource_uri: Optional[str] = None, language: Optional[str] = None, 

178 links: Optional[Links] = None) -> ViewData: 

179 """Return the data of a page as the contract between viewers and templates defines it. 

180 

181 `resource_uri` asks for the page of one resource; without it, the whole artefact. The 

182 contract is described in lode.viewer.view_data. The page of one resource has no 

183 navigation (`toc` is empty): it shows its card and nothing else, so a site of N 

184 resources does not carry N copies of its own index. Main entry point of the viewer: 

185 the web service and the static builder both call it, each with its own `links`. 

186 """ 

187 language = language.strip() if language else "en" # no language means English 

188 links = links or Links() 

189 cards, error = self._build_cards(resource_uri, language) 

190 header = self._find_and_format_semantic_artefact_metadata(self.artefact.get_entities(), language) 

191 data = { 

192 'model': to_model(header, self._formats(), self.format_warnings(self.artefact.warnings)), 

193 'toc': [] if resource_uri else self._build_toc(language), 

194 'types': self._build_types(), 

195 'cards': cards, 

196 'focus': resource_uri or None, 

197 'error': error, 

198 } 

199 

200 # "Visualise it with LODE" is offered for the imported ontologies only: an import 

201 # is an ontology by definition, any other IRI (creator, licence...) is not 

202 for value in data['model']['metadata'].get(self._clean_name('get_imports'), []): 

203 if value['iri']: 

204 value['visualize'] = links.visualize(value['iri']) 

205 

206 resolve_links(data, links) 

207 return data 

208 

209 def _build_cards(self, resource_uri: Optional[str], language: str) -> Tuple[List[Card], Optional[str]]: 

210 """Return the cards of a page and the error, if there is one. 

211 

212 One resource gives its own cards (an IRI can name several entities: a class and an 

213 individual, punned); the whole artefact gives every browsable entity, grouped by 

214 section in the order of the table of contents. Without a table of contents (the generic 

215 viewer) the artefact is shown as a flat list. 

216 """ 

217 if resource_uri: 

218 found = self.artefact.get_entities_by_iri(resource_uri) 

219 if not found: 

220 return [], f'Resource {resource_uri} not found' 

221 candidates = list(found) if isinstance(found, set) else [found] 

222 candidates = [i for i in candidates if self._is_toc_entity(i)] 

223 if not candidates: 

224 return [], f'{resource_uri} is not a browsable entity' 

225 return self._format_cards(candidates, language), None 

226 

227 all_entities = self.artefact.get_entities() 

228 if not self._config["toc"]: 

229 return self._format_cards(all_entities, language), None 

230 cards = [] 

231 for class_key, _section_id, _title in self.get_toc_config(): 

232 members = [i for i in all_entities 

233 if type(i).__name__ == class_key and self._is_toc_entity(i)] 

234 cards += self._format_cards(members, language) 

235 return cards, None 

236 

237 

238 def _build_types(self) -> Dict[str, TypeLabel]: 

239 """How each type is called and abbreviated, keyed by the name of its model class. 

240 

241 The configuration keys the names by the lower-case class name; the contract uses the exact 

242 name, the one a Value, an Card and a section carry in `type`. 

243 """ 

244 exact = {name.lower(): name for name in _models.__all__} 

245 return {exact.get(key, key.capitalize()): {'singular': entry['singular'], 

246 'plural': entry['plural'], 

247 'abbreviation': entry['abb']} 

248 for key, entry in self._config["type_map"].items()} 

249 

250 

251 def _build_toc(self, language: str) -> List[TocSection]: 

252 """Build the navigation: every browsable entity as a short entry, grouped by section. 

253 

254 It does not depend on the view, so the page of one resource has the same navigation as 

255 the whole artefact. 

256 """ 

257 entities = self.artefact.get_entities() 

258 toc = [] 

259 for class_key, section_id, _ in self.get_toc_config(): 

260 members = [i for i in entities 

261 if type(i).__name__ == class_key and self._is_toc_entity(i)] 

262 if not members: 

263 continue 

264 entries = sorted((self._toc_entry(i, language) for i in members), 

265 key=lambda e: (e['label'] or e['iri']).lower()) 

266 names = self._config["type_map"].get(class_key.lower(), {}) 

267 toc.append({'id': section_id, 'type': class_key, 'label': names.get('plural', class_key), 

268 'entries': entries}) 

269 return toc 

270 

271 def _anchor(self, entity) -> str: 

272 """Return the HTML id of the card of an entity. 

273 

274 Derived from its IRI, so it is stable and safe in an attribute. The navigation  

275 and the card both use it: a link from the navigation reaches the card. 

276 """ 

277 type_name = type(entity).__name__.replace(" ", "_") 

278 digest = hashlib.md5(str(entity.has_identifier).encode('utf-8')).hexdigest() 

279 return f"id_{digest}_{type_name}" 

280 

281 

282 def _toc_entry(self, entity, language: str) -> TocEntry: 

283 """Reduce an entity to what a navigation needs: IRI, type, label and anchor. 

284 

285 The anchor has the same form as the one of its card, so a link from the navigation 

286 reaches the card. 

287 """ 

288 return {'iri': entity.has_identifier, 'type': type(entity).__name__.replace(" ", "_"), 

289 'label': self._get_best_label(entity, language), 

290 'anchor': self._anchor(entity), 'href': None, 'kind': "page"} 

291 

292 def _format_cards(self, members: List, language: Optional[str] = None) -> List[Card]: 

293 """ 

294 onverts Python Models -> contract Entities (the content of a card). 

295 Ensures the same keys across all viewers. 

296 """ 

297 all_entities = self.artefact.get_entities() 

298 

299 cards = [] 

300 for entity in members: 

301 uri = entity.has_identifier if hasattr(entity, 'has_identifier') else None 

302 

303 if not uri: 

304 continue 

305 

306 # Extract internal attributes (SuperClasses, etc.) 

307 relations = {} 

308 if hasattr(entity, '__dict__'): 

309 for attr, value in entity.__dict__.items(): 

310 if not attr.startswith('_') and value: 

311 # Skip attributes that are handled elsewhere or are empty 

312 # Clean up name: 

313 clean_name = self._clean_name(attr) 

314 

315 # Process value (could be a list of objects)clean 

316 # We use the helper to get clean text for each item 

317 formatted_values = [] 

318 if isinstance(value, list): 

319 for v in self._select_by_language(value, language): 

320 # Nested list (e.g. has_property_chain: list of chains) 

321 if isinstance(v, list): 

322 chain_dict = self._resolve_chain_value(v, language) 

323 if chain_dict and chain_dict['text']: 

324 formatted_values.append(chain_dict) 

325 continue 

326 # Normal list 

327 val_dict = self._resolve_resource_value(v, language) 

328 if val_dict['text']: formatted_values.append(val_dict) 

329 else: 

330 val_dict = self._resolve_resource_value(value, language) 

331 if val_dict['text']: formatted_values.append(val_dict) 

332 

333 if formatted_values: 

334 if attr in self._FULL_IRI_ATTRS: 

335 for fv in formatted_values: 

336 if fv['iri']: 

337 fv['text'] = str(fv['iri']) 

338 if clean_name not in relations: 

339 relations[clean_name] = [] 

340 for v in formatted_values: 

341 if v not in relations[clean_name]: # Valentina FIX: this do not add duplicates in metadata values  

342 relations[clean_name].append(v) 

343 # Sort relations 

344 ordered_relations = {} 

345 

346 # Define the exact order you 

347 priority_order = [ 

348 "is sub property of", 

349 "domain", 

350 "range", 

351 "is inverse Of", 

352 "property chain", 

353 "is disjoint with" 

354 ] 

355 

356 # Extract and insert the priority keys first 

357 for key in priority_order: 

358 if key in relations: 

359 ordered_relations[key] = relations[key] 

360 

361 # Insert all remaining keys alphabetically 

362 for key in sorted(relations.keys()): 

363 if key not in ordered_relations: 

364 ordered_relations[key] = relations[key] 

365 

366 characteristics = [] 

367 for attr in self._config["characteristics"]: 

368 getter = f"get_{attr}" 

369 # Safely get the boolean value 

370 is_true = getattr(entity, getter)() if hasattr(entity, getter) else getattr(entity, attr, False) 

371 

372 # Convert 'is_asymmetric' to 'is asymmetric' for the HTML label 

373 if is_true: 

374 characteristics.append(attr.replace('_', ' ')) 

375 

376 # Extract Statement Entities 

377 statements = self._format_statement(all_entities, entity, language) 

378 type_inst = type(entity).__name__.replace(" ", "_") 

379 

380 is_dep = getattr(entity, 'get_is_deprecated')() if hasattr(entity, 'get_is_deprecated') else getattr( 

381 entity, 'is_deprecated', False) 

382 

383 cards.append({ 

384 'iri': uri, 

385 'type': type_inst, 

386 'label': self._get_best_label(entity, language), 

387 'anchor': self._anchor(entity), 

388 'href': None, 

389 'kind': "page" if self._is_internal(uri) else "external", 

390 'deprecated': bool(is_dep), 

391 'relations': ordered_relations, 

392 'statements': statements, 

393 'characteristics': characteristics, 

394 'provenance': self._serialize_provenance(entity), 

395 }) 

396 

397 cards.sort(key=lambda x: (x['label'] or x['iri']).lower()) 

398 return cards 

399 

400 def _find_and_format_semantic_artefact_metadata(self, all_entities: List[Resource], language=None) -> Dict: 

401 """ 

402 Searches for the Model and its Statements and formatting them 

403 for the template. 

404 """ 

405 

406 # 1. Find the Model of the documented semantic artefact (not the imported ones): 

407 # the cache also holds Models for imports and version IRIs, so pick it by IRI. 

408 # A source that declares no ontology or concept scheme has none: no header. 

409 main_iri = str(self.artefact.artefact_iri) 

410 sem_art_model = next( 

411 (m for m in self.artefact.get_entities(Model) 

412 if str(m.get_has_identifier()) == main_iri), 

413 None, 

414 ) 

415 

416 if not sem_art_model: 

417 

418 return {} 

419 

420 # 2. Prepare Output 

421 data = { 

422 'uri': [self._resolve_resource_value(sem_art_model, language)], 

423 'label': [self._resolve_resource_value(self._get_best_label(sem_art_model, language))] 

424 } 

425 

426 # 3: Dynamic Extraction of Structural Data --- 

427 # Methods we want to skip because they belong in the Header or Annotations 

428 ignore_methods = [ 

429 'get_has_identifier', 

430 'get_has_label', 

431 'get_has_subject', 

432 'get_has_predicate', 

433 'get_has_object', 

434 'get_has_namespaces', 

435 ] 

436 

437 # 1. Loop through ALL attributes and methods of the Model object 

438 for attr_name in dir(sem_art_model): 

439 # 2. Look specifically for getter methods 

440 if attr_name.startswith('get_') and attr_name not in ignore_methods: 

441 

442 method = getattr(sem_art_model, attr_name) 

443 

444 if callable(method): 

445 try: 

446 values = method() 

447 except AttributeError: 

448 # skip attributes that are not initialized 

449 continue 

450 

451 if values: 

452 # 4. Auto-format the key name 

453 clean_key = self._clean_name(attr_name) 

454 

455 # 5. Ensure values are in a list 

456 if not isinstance(values, list): 

457 values = [values] 

458 

459 # 6. Extract the actual text values 

460 extracted_values = [] 

461 for val in self._select_by_language(values, language): 

462 entry = self._resolve_resource_value(val, language) 

463 if entry['text']: 

464 extracted_values.append(entry) 

465 

466 # 8. Add to structural data ONLY if we found valid text 

467 if extracted_values: 

468 data[clean_key] = extracted_values 

469 

470 # Namespaces (dict prefix -> URI), handled explicitly: not a Resource 

471 ns = sem_art_model.get_has_namespaces() 

472 if ns: 

473 data['_namespaces'] = [ 

474 {'prefix': prefix or 'default namespace', 'uri': uri} 

475 for prefix, uri in sorted(ns.items(), key=lambda kv: (kv[0] or '')) 

476 ] 

477 

478 # 9. Statements 

479 data.update(self._format_statement(all_entities, sem_art_model, language)) 

480 

481 # The header shows every link as its full IRI, not as a label or the last part of it: 

482 # the reader needs to see where it points. Applied here, once, because the values come 

483 # from two places (getters above, statements) and cards keep their labels. 

484 for key, values in data.items(): 

485 if key in ('uri', 'label', '_namespaces'): 

486 continue 

487 for value in values: 

488 if value['iri']: 

489 value['text'] = str(value['iri']) 

490 

491 # uri/label first, then the order from the YAML, then alphabetical 

492 pinned = ['uri', 'label'] 

493 rest = sorted((k for k in data if k not in pinned), key=annotation_sort_key) 

494 data = {k: data[k] for k in pinned if k in data} | {k: data[k] for k in rest} 

495 

496 return data 

497 

498 # ========================================================================== 

499 # 3. VALUE RESOLUTION 

500 # ==========================================================================  

501 

502 def _resolve_special(self, obj, value: Value, language=None) -> Optional[Value]: 

503 """Resolve a value only one format knows how to render, or return None. 

504 

505 The base knows none: a format viewer overrides this to intercept its own 

506 constructs (OWL class expressions) before the generic resolution runs. It 

507 fills in `value`, an empty Value, and returns it. 

508 """ 

509 return None 

510 

511 def _resolve_chain_value(self, chain, language=None) -> Optional[Value]: 

512 """Render an ordered property chain (a list of Relations) as a single Value. 

513 

514 The clickable parts are joined by the composition operator. Returns None 

515 when no member has a displayable text. 

516 """ 

517 members = [m for m in (self._resolve_resource_value(r, language) for r in chain) if m['text']] 

518 if not members: 

519 return None 

520 parts = [] 

521 for i, member in enumerate(members): 

522 if i > 0: 

523 parts.append(new_value(text=' o ')) # ring operator 

524 parts.append(member) 

525 return new_value(text=' o '.join(m['text'] for m in members), parts=parts, type='PropertyChain') 

526 

527 def _resolve_resource_value(self, obj, language=None) -> Value: 

528 """Turn any object (resource, literal, statement, string) into a contract Value. 

529 

530 The Value carries its IRI and a `kind` ("page" inside this documentation, "external" 

531 outside); the address (`href`) is filled in later, by the Links of the caller. 

532 """ 

533 value = new_value() 

534 

535 if not obj: 

536 return value 

537 

538 # --- 1. FORMAT-SPECIFIC VALUES (e.g. OWL restrictions) --- 

539 special = self._resolve_special(obj, value, language) 

540 if special is not None: 

541 return special 

542 

543 obj_type = type(obj).__name__ 

544 

545 # --- 2. String Handling --- 

546 if isinstance(obj, str): 

547 value['text'] = obj 

548 return value 

549 

550 # --- 3. Literal Handling --- 

551 if obj_type == 'Literal': 

552 if hasattr(obj, 'get_has_value') and obj.get_has_value(): 

553 is_dep = getattr(obj, 'get_is_deprecated')() if hasattr(obj, 'get_is_deprecated') else getattr( 

554 obj, 'is_deprecated', False) 

555 value['deprecated'] = bool(is_dep) 

556 value['text'] = obj.get_has_value() 

557 value['language'] = obj.get_has_language() 

558 value['type'] = obj_type 

559 return value 

560 

561 raw_str = str(obj) 

562 if "object at" not in raw_str: 

563 value['text'] = raw_str 

564 value['type'] = obj_type 

565 return value 

566 

567 # --- 4. Statement (nested annotation) --- 

568 if obj_type == 'Statement': 

569 value['type'] = 'Statement' # no IRI: never link to the id of the blank node 

570 inner_pred = obj.get_has_predicate() 

571 inner = { 

572 'predicate': self._get_best_label(inner_pred, language) if inner_pred else None, 

573 'value': self._resolve_resource_value(obj.get_has_object(), language), 

574 } 

575 # Walk Statement's own annotations (anything else in __dict__ besides 

576 # the reification slots), so dc:date, rdf:value siblings show up too. 

577 skip = {'has_subject', 'has_predicate', 'has_object', 

578 'has_identifier', 'is_positive_statement'} 

579 siblings = [] 

580 for attr, attr_value in obj.__dict__.items(): 

581 if attr.startswith('_') or attr in skip or not attr_value: 

582 continue 

583 values = attr_value if isinstance(attr_value, list) else [attr_value] 

584 for v in self._select_by_language(values, language): 

585 resolved = self._resolve_resource_value(v, language) 

586 if resolved['text'] or resolved['nested']: 

587 siblings.append({'predicate': self._clean_name(attr), 'value': resolved}) 

588 # Reader order depends on the source file: sort by label, then by value 

589 pairs = sorted([inner] + siblings, 

590 key=lambda p: ((p['predicate'] or '').lower(), (p['value']['text'] or '').lower())) 

591 value['nested'] = {'main': pairs[0], 'siblings': pairs[1:]} 

592 # The text for a collapsed display: the one of the inner value 

593 value['text'] = inner['value']['text'] or '[Statement]' 

594 return value 

595 

596 # --- 5. Normal Resource Handling (e.g., Concepts, Properties, Individuals) --- 

597 if hasattr(obj, 'get_has_identifier'): 

598 iri = obj.get_has_identifier() 

599 value['iri'] = iri 

600 ns = self.get_artefact_ns() 

601 internal = self._is_internal(iri) 

602 native = bool(iri) and bool(ns) and str(iri).startswith(ns) 

603 if iri: 

604 value['kind'] = "page" if internal else "external" 

605 value['imported'] = internal and not native 

606 is_dep = getattr(obj, 'get_is_deprecated')() if hasattr(obj, 'get_is_deprecated') else getattr( 

607 obj, 'is_deprecated', False) 

608 value['deprecated'] = bool(is_dep) 

609 value['type'] = obj_type 

610 try: 

611 value['text'] = self._get_best_label(obj, language) 

612 except AttributeError: 

613 value['text'] = iri 

614 

615 # Fallbacks 

616 if not value['text'] and value['iri']: 

617 value['text'] = value['iri'] 

618 value['type'] = obj_type 

619 

620 return value 

621 

622 def format_warnings(self, warnings: List[Dict]) -> List[Dict]: 

623 """Return the reader warnings with model class names replaced by this viewer's display names. 

624 

625 The reader words its messages with internal class names (Attribute, Annotation) and 

626 cannot know how a format shows them; the display names live in the type_map of this 

627 viewer, so the swap happens here, before the warnings reach any output. Only standalone 

628 words are replaced: a class name inside an IRI (.../Concept, ...#Concept) is left alone. 

629 Returns copies, the reader's own list is never modified. 

630 """ 

631 names = {key.capitalize(): entry["singular"] for key, entry in self._config["type_map"].items()} 

632 if not names: 

633 return [dict(w) for w in warnings] 

634 pattern = re.compile(r"(?<![\w/#:-])(" + "|".join(map(re.escape, names)) + r")(?![\w/#:-])") 

635 return [{**w, "message": pattern.sub(lambda m: names[m.group(1)], w["message"])} 

636 for w in warnings] 

637 

638 # ========================================================================== 

639 # RDF RELATED FEATURES = Provenance + Export RDF 

640 # ========================================================================== 

641 

642 def _formats(self): 

643 """Return the export formats (triples): the same whatever modules are active.""" 

644 return SERIALIZATION_FORMATS 

645 

646 def _format_statement(self, entities, target_entity, language=None) -> Dict: 

647 """ 

648 Extracts all statements where the subject matches the given target_entity. 

649 """ 

650 statements = {} 

651 

652 # 1. Validate the target entity 

653 if target_entity is None: 

654 return statements 

655 

656 # 2. Group the objects by predicate: the language is chosen per property 

657 grouped = {} 

658 for entity in entities: 

659 if not isinstance(entity, Statement): 

660 continue 

661 # Identity comparison (handles punning: same URI, different Python entities) 

662 if entity.get_has_subject() is not target_entity: 

663 continue 

664 obj = entity.get_has_object() 

665 if not obj: 

666 continue 

667 predicate = entity.get_has_predicate() 

668 pred_label = self._get_best_label(predicate, language) if predicate else "Annotation" 

669 grouped.setdefault(pred_label, []).append(obj) 

670 

671 # 3. Pick the language per property, resolve, drop empties and duplicates 

672 for pred_label, objs in grouped.items(): 

673 values = [] 

674 for obj in self._select_by_language(objs, language): 

675 obj_data = self._resolve_resource_value(obj, language) 

676 if obj_data['text'] and obj_data not in values: 

677 values.append(obj_data) 

678 if values: 

679 statements[pred_label] = sorted(values, key=lambda v: (str(v['nested']), v['text'].lower())) 

680 

681 return dict(sorted(statements.items(), key=lambda kv: kv[0].lower())) 

682 

683 _FULL_IRI_ATTRS = {'is_defined_by'} 

684 

685 # ========================================================================== 

686 # RDF RELATED FEATURES = Provenance + Export RDF 

687 # ========================================================================== 

688 

689 def _serialize_provenance(self, entity) -> List[Dict[str, str]]: 

690 """Serialize the triples an entity comes from, once per available format. 

691 

692 Returns an empty list when the entity has no provenance. 

693 """ 

694 sub = self.artefact.provenance(entity) 

695 if not any(True for _ in sub): 

696 return [] 

697 sub = self.artefact.with_provenance(sub) 

698 return [ 

699 {"label": f["label"], "code": safe_serialize(sub, f["fmt"])} 

700 for f in QUAD_SERIALIZATION_FORMATS 

701 ] 

702 

703 def _resource_graph(self, resource_uri: str) -> Graph: 

704 """Build the subgraph of a single resource (the union of its punned entities). 

705 

706 Only triples of the loaded artefact are kept; the ones that come from imported 

707 modules belong to the provenance, not to the export. The graph starts without 

708 the default rdflib prefixes: the artefact graph already carries them, and 

709 binding them twice is the most expensive part of an export. 

710 """ 

711 g = Graph(bind_namespaces="none") 

712 for prefix, ns in self.artefact.graph.namespaces(): 

713 g.bind(prefix, ns) 

714 main = self.artefact.main_graph() 

715 entities = self.artefact.get_entities_by_iri(resource_uri) 

716 if entities: 

717 inst_iter = entities if isinstance(entities, set) else [entities] 

718 for inst in inst_iter: 

719 for t in self.artefact.provenance(inst): 

720 if t in main: 

721 g.add(t) 

722 return g 

723 

724 def export_resource(self, resource_uri: str, fmt: str = "turtle") -> str: 

725 """Serialize the subgraph of a single resource in one format.""" 

726 return safe_serialize(self._resource_graph(resource_uri), fmt) 

727 

728 def export_resource_all(self, resource_uri: str, formats: List[str]) -> Dict[str, str]: 

729 """Serialize the subgraph of a single resource in several formats. 

730 

731 The subgraph is built once and reused: a static build asks for every format of 

732 every resource, and building it per format multiplied the cost by the number 

733 of formats. 

734 """ 

735 g = self._resource_graph(resource_uri) 

736 return {fmt: safe_serialize(g, fmt) for fmt in formats} 

737 

738 def export_main(self, fmt: str = "turtle") -> str: 

739 """Serialize the main graph, i.e. the triples of the loaded artefact only. 

740 

741 Imported modules are left out: they belong to the provenance, not to the 

742 export. A format that fails yields an error comment instead of raising, so 

743 one bad format cannot break the whole export or build. 

744 """ 

745 return safe_serialize(self.artefact.main_graph(), fmt)