Coverage for rdgai/apparatus.py: 93.71%

525 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-24 23:53 +0000

1import math 

2from typing import Optional 

3from pathlib import Path 

4from dataclasses import dataclass, field 

5from lxml.etree import _Element as Element 

6from lxml.etree import _ElementTree as ElementTree 

7from lxml import etree as ET 

8from rich.console import Console 

9import textwrap 

10from collections import defaultdict 

11 

12# from .relations import Relation, get_reading_identifier 

13from .tei import read_tei, find_elements, extract_text, find_parent, find_element, write_tei, make_nc_name, get_language, get_reading_identifier, extract_text_siblings 

14from .notes import parse_reading_notes 

15 

16 

17def unique(elements:list[Element]) -> list[Element]: 

18 """ Removes duplicates (find_elements can return the same element for namespaced and plain queries). """ 

19 seen = set() 

20 result = [] 

21 for element in elements: 

22 if id(element) not in seen: 

23 seen.add(id(element)) 

24 result.append(element) 

25 return result 

26 

27 

28def relation_provenance(relation:Element) -> dict: 

29 """ Reads resp, cert, change, the justification and the time saved from a <relation> element. """ 

30 justification_parts = [] 

31 when = "" 

32 justification_source = "" 

33 for desc in unique(find_elements(relation, "./desc")): 

34 if desc.attrib.get("type", "justification") != "justification": 

35 continue 

36 justification_source = justification_source or desc.attrib.get("resp", "").lstrip("#") 

37 text = desc.text or "" 

38 for child in desc: 

39 if isinstance(child.tag, str) and ET.QName(child).localname == "date": 

40 when = when or child.attrib.get("when", "") 

41 else: 

42 text += " " + extract_text(child, include_tail=False) 

43 text += child.tail or "" 

44 justification_parts.append(" ".join(text.split())) 

45 return dict( 

46 resp=relation.attrib.get("resp", ""), 

47 cert=relation.attrib.get("cert", ""), 

48 change=relation.attrib.get("change", ""), 

49 justification="\n".join(part for part in justification_parts if part).strip(), 

50 when=when, 

51 justification_source=justification_source, 

52 ) 

53 

54 

55def prune_empty_list(list_relation:Element|None): 

56 """ 

57 Removes a <listRelation> with no <relation> left (TEI requires at least one), and its <note> if that is now empty. 

58 """ 

59 if list_relation is None or len(list_relation) > 0: 

60 return 

61 parent = list_relation.getparent() 

62 if parent is None: 

63 return 

64 parent.remove(list_relation) 

65 if ET.QName(parent).localname == "note" and len(parent) == 0 and not (parent.text or "").strip(): 

66 grandparent = parent.getparent() 

67 if grandparent is not None: 

68 grandparent.remove(parent) 

69 

70 

71def tei_tag(reference:Element, tag:str) -> str: 

72 """ Returns the tag name in the same namespace as the reference element. """ 

73 namespace = ET.QName(reference).namespace 

74 return f"{{{namespace}}}{tag}" if namespace else tag 

75 

76@dataclass 

77class Reading(): 

78 element: Element 

79 app:"App" 

80 n: str = field(default=None) 

81 text: str = field(default=None) 

82 witnesses: list[str] = field(default_factory=list) 

83 type: str = field(default="") 

84 raw_text: str = field(default="") 

85 notes: list[str] = field(default_factory=list) 

86 

87 def __post_init__(self): 

88 self.n = get_reading_identifier(self.element) 

89 self.raw_text = extract_text(self.element).strip() 

90 self.text = self.raw_text 

91 if self.app.doc.reading_notes: 

92 self.text, self.notes = parse_reading_notes(self.raw_text) 

93 self.witnesses = self.element.attrib.get("wit", "").split() 

94 self.type = self.element.attrib.get("type", "") 

95 

96 def __str__(self): 

97 return self.text or 'OMIT' 

98 

99 def witnesses_str(self) -> str: 

100 return " ".join(self.witnesses) 

101 

102 def __hash__(self): 

103 return hash(self.element) 

104 

105 def text_in_context(self, text:str|None=None) -> str: 

106 text = self.text if text is None else text 

107 return self.app.text_in_context(text) 

108 

109 

110@dataclass 

111class RelationType(): 

112 element: Element 

113 name: str 

114 description: str 

115 inverse: Optional['RelationType'] = None 

116 pairs: set['Pair'] = field(default_factory=set) 

117 

118 def __str__(self): 

119 return self.name 

120 

121 def __repr__(self) -> str: 

122 return str(self) 

123 

124 def __eq__(self, other): 

125 if isinstance(other, RelationType): 

126 return (self.name, self.element, self.description) == (other.name, other.element, other.description) 

127 return False 

128 

129 def __hash__(self): 

130 return hash((self.name, self.element, self.description)) 

131 

132 def str_with_description(self) -> str: 

133 result = self.name 

134 if self.description: 

135 result += f": {self.description}" 

136 return result 

137 

138 def pairs_sorted(self, exclude_rdgai:bool = False) -> list['Pair']: 

139 pairs = sorted(self.pairs, key=lambda pair: (str(pair.active.app), pair.active.n, pair.passive.n)) 

140 if exclude_rdgai: 

141 pairs = [pair for pair in pairs if not pair.rdgai_responsible()] 

142 return pairs 

143 

144 def get_inverse(self) -> 'RelationType': 

145 return self.inverse if self.inverse else self 

146 

147 

148@dataclass 

149class Pair(): 

150 active: Reading 

151 passive: Reading 

152 types: set[RelationType] = field(default_factory=set) 

153 

154 def __post_init__(self): 

155 for relation_type in self.types: 

156 relation_type.pairs.add(self) 

157 

158 def __str__(self): 

159 return f"{self.active} ➞ {self.passive}" 

160 

161 def print(self, console): 

162 console.print(f"[bold red]{self.app}[/bold red]: [green]{self.active}[/green] [red]➞[/red] [green]{self.passive}[/green]") 

163 

164 def reading_transition_str(self) -> str: 

165 return f"{self.active or 'OMISSION'} → {self.passive or 'OMISSION'}" 

166 

167 def __repr__(self) -> str: 

168 return str(self) 

169 

170 @property 

171 def app(self) -> "App": 

172 # assert self.active.app == self.passive.app 

173 return self.active.app 

174 

175 def __hash__(self): 

176 return hash((self.active, self.passive)) 

177 

178 def app_element(self) -> Element: 

179 return find_parent(self.active.element, "app") 

180 

181 def relation_elements(self) -> list[Element]: 

182 list_relation = find_element(self.app_element(), ".//listRelation[@type='transcriptional']") 

183 if list_relation is None: 

184 return [] 

185 

186 return [ 

187 relation for relation in unique(find_elements(list_relation, ".//relation")) 

188 if relation.attrib.get("active") == self.active.n and relation.attrib.get("passive") == self.passive.n 

189 ] 

190 

191 def element_for_type(self, type:RelationType) -> Element|None: 

192 for relation in self.relation_elements(): 

193 if f"#{type.name}" in relation.attrib.get("ana").split(): 

194 return relation 

195 return None 

196 

197 def get_inverse(self) -> "Pair": 

198 found_pair = None 

199 for pair in self.app.pairs: 

200 if pair.active == self.passive and pair.passive == self.active: 

201 found_pair = pair 

202 break 

203 assert found_pair is not None, f"No inverse pair found for {self}" 

204 return found_pair 

205 

206 def add_type_with_inverse(self, type:RelationType, responsible:str|None=None, description:str="", inverse_description:str="") -> Element: 

207 relation = self.add_type(type, responsible=responsible, description=description) 

208 inverse = self.get_inverse() 

209 inverse.add_type(type.get_inverse(), responsible=responsible, description=inverse_description) 

210 return relation 

211 

212 def add_type(self, type:RelationType, responsible:str|None=None, description:str="") -> Element: 

213 self.types.add(type) 

214 type.pairs.add(self) 

215 

216 # Check if the relation already exists 

217 relation = self.element_for_type(type) 

218 if relation is not None: 

219 return relation 

220 

221 list_relation = self.list_relation_element() 

222 

223 relation = find_element(list_relation, f".//relation[@active='{self.active.n}'][@passive='{self.passive.n}']") 

224 if relation is not None: 

225 if type.name not in relation.attrib.get("ana").split(): 

226 relation.attrib["ana"] += f" #{type.name}" 

227 else: 

228 relation = ET.SubElement(list_relation, "relation", attrib={"active":self.active.n, "passive":self.passive.n, "ana":f"#{type.name}"}) 

229 

230 if responsible is not None: 

231 relation.set("resp", responsible) 

232 

233 self.add_description(description, relation) 

234 

235 return relation 

236 

237 def list_relation_element(self, create:bool=True) -> Element|None: 

238 """ Returns the <listRelation type="transcriptional"> of this pair's app, creating it if necessary. """ 

239 app_element = self.app_element() 

240 list_relation = find_element(app_element, ".//listRelation[@type='transcriptional']") 

241 if list_relation is None and create: 

242 # TEI does not allow <listRelation> directly in <app>, so it goes in a <note> (as teiphy expects). 

243 note = ET.SubElement(app_element, tei_tag(app_element, "note")) 

244 list_relation = ET.SubElement(note, tei_tag(app_element, "listRelation"), attrib={"type":"transcriptional"}) 

245 return list_relation 

246 

247 def set_type( 

248 self, 

249 type:RelationType, 

250 responsible:str|None=None, 

251 cert:str|None=None, 

252 description:str="", 

253 change:str|None=None, 

254 when:str|None=None, 

255 description_resp:str|None=None, 

256 ) -> Element: 

257 """ 

258 Sets the classification of this pair to a single relation type, replacing any existing classification. 

259 

260 The justification and the time it was saved (``when``) go in a single <desc type="justification">, 

261 as TEI allows only one <desc> in a <relation>. 

262 

263 Any existing <relation> elements for this pair are removed so that the pair has exactly one category 

264 (teiphy adds the rates of multiple categories on one pair). 

265 """ 

266 self.clear_types() 

267 self.types = {type} 

268 type.pairs.add(self) 

269 

270 list_relation = self.list_relation_element() 

271 attrib = {"active":self.active.n, "passive":self.passive.n, "ana":f"#{type.name}"} 

272 if responsible: 

273 attrib["resp"] = responsible 

274 if cert: 

275 attrib["cert"] = cert 

276 if change: 

277 attrib["change"] = change 

278 relation = ET.SubElement(list_relation, tei_tag(list_relation, "relation"), attrib=attrib) 

279 

280 description = (description or "").strip() 

281 if description or when: 

282 desc_attrib = {"type":"justification"} 

283 if description and description_resp: 

284 desc_attrib["resp"] = description_resp # whose wording the justification is, if not the label's resp 

285 desc = ET.SubElement(relation, tei_tag(relation, "desc"), attrib=desc_attrib) 

286 desc.text = description or None 

287 if when: 

288 ET.SubElement(desc, tei_tag(relation, "date"), attrib={"when": when}) 

289 

290 return relation 

291 

292 def set_type_with_inverse( 

293 self, 

294 type:RelationType, 

295 responsible:str|None=None, 

296 cert:str|None=None, 

297 description:str="", 

298 inverse_description:str|None=None, 

299 change:str|None=None, 

300 when:str|None=None, 

301 description_resp:str|None=None, 

302 ) -> Element: 

303 """ Sets the classification of this pair and sets the inverse category on the inverse pair. """ 

304 relation = self.set_type( 

305 type, responsible=responsible, cert=cert, description=description, change=change, when=when, description_resp=description_resp, 

306 ) 

307 inverse_description = description if inverse_description is None else inverse_description 

308 self.get_inverse().set_type( 

309 type.get_inverse(), responsible=responsible, cert=cert, description=inverse_description, change=change, when=when, 

310 description_resp=description_resp, 

311 ) 

312 return relation 

313 

314 def clear_types(self): 

315 """ Removes all classifications (and their <relation> elements) for this pair. """ 

316 for relation_type in list(self.types): 

317 relation_type.pairs.discard(self) 

318 self.types = set() 

319 for relation in self.relation_elements(): 

320 list_relation = relation.getparent() 

321 list_relation.remove(relation) 

322 prune_empty_list(list_relation) 

323 

324 def clear_types_with_inverse(self): 

325 self.clear_types() 

326 self.get_inverse().clear_types() 

327 

328 def relation_element(self) -> Element|None: 

329 elements = self.relation_elements() 

330 return elements[0] if elements else None 

331 

332 def provenance(self) -> dict: 

333 """ Returns the responsibility, certainty, change and justification recorded on this pair's relation. """ 

334 relation = self.relation_element() 

335 if relation is None: 

336 return {} 

337 return relation_provenance(relation) 

338 

339 def remove_description(self): 

340 for relation in self.relation_elements(): 

341 for desc in find_elements(relation, ".//desc"): 

342 relation.remove(desc) 

343 

344 def add_description(self, description:str, relation:Element|None=None): 

345 if relation is None: 

346 relation_elements = self.relation_elements() 

347 

348 if len(relation_elements) == 0: 

349 list_relation = self.list_relation_element() 

350 relation = ET.SubElement(list_relation, "relation", attrib={"active":self.active.n, "passive":self.passive.n}) 

351 else: 

352 relation = relation_elements[0] 

353 

354 description = description.strip() 

355 if description: 

356 description_element = find_element(relation, ".//desc") 

357 if description_element is None: 

358 description_element = ET.SubElement(relation, "desc") 

359 

360 description_element.text = description 

361 

362 def remove_type(self, relation_type:RelationType): 

363 if relation_type in self.types: 

364 self.types.remove(relation_type) 

365 

366 if self in relation_type.pairs: 

367 relation_type.pairs.remove(self) 

368 

369 list_relation = find_element(self.app_element(), ".//listRelation[@type='transcriptional']") 

370 for relation in find_elements(list_relation, f".//relation[@active='{self.active.n}'][@passive='{self.passive.n}']"): 

371 if f"#{relation_type.name}" in relation.attrib.get("ana").split(): 

372 relation.attrib['ana'] = " ".join([ana for ana in relation.attrib.get("ana").split() if ana != f"#{relation_type.name}"]) 

373 if not relation.attrib.get("ana"): 

374 relation.getparent().remove(relation) 

375 

376 def remove_type_with_inverse(self, relation_type:RelationType): 

377 self.remove_type(relation_type) 

378 inverse = self.get_inverse() 

379 inverse.remove_type(relation_type.get_inverse()) 

380 

381 def remove_all_types(self): 

382 for relation_type in set(self.types): 

383 self.remove_type_with_inverse(relation_type) 

384 

385 def rdgai_responsible(self) -> bool: 

386 for element in self.relation_elements(): 

387 if element.attrib.get('resp', '') == '#rdgai': 

388 return True 

389 return False 

390 

391 def relation_type_names(self) -> set[str]: 

392 return set(type.name for type in self.types) 

393 

394 def has_description(self) -> bool: 

395 for relation in self.relation_elements(): 

396 if find_element(relation, ".//desc") is not None: 

397 return True 

398 return False 

399 

400 def get_description(self) -> str: 

401 description = "" 

402 for relation_element in self.relation_elements(): 

403 for desc in find_elements(relation_element, ".//desc"): 

404 description += "\n" + extract_text(desc) 

405 return description.strip() 

406 

407 

408@dataclass 

409class App(): 

410 element: Element 

411 doc: "Doc" 

412 readings: list[Reading] = field(default_factory=list) 

413 pairs: list[Pair] = field(default_factory=list) 

414 non_redundant_pairs: list[Pair] = field(default_factory=list) 

415 id_to_reading: dict[str,Reading] = field(default_factory=dict) 

416 

417 def __post_init__(self): 

418 for reading in find_elements(self.element, ".//rdg"): 

419 self.readings.append(Reading(reading, app=self)) 

420 

421 # Index relation elements by (active, passive) 

422 relation_elements = defaultdict(list) 

423 for list_relation in unique(find_elements(self.element, ".//listRelation[@type='transcriptional']")): 

424 for relation_element in unique(find_elements(list_relation, ".//relation")): 

425 key = (relation_element.attrib.get("active"), relation_element.attrib.get("passive")) 

426 relation_elements[key].append(relation_element) 

427 

428 # Build list of relation pairs 

429 active_visited = set() 

430 for active in self.readings: 

431 active_visited.add(active) 

432 for passive in self.readings: 

433 if active == passive: 

434 continue 

435 

436 types = set() 

437 for relation_element in relation_elements.get((active.n, passive.n), []): 

438 for ana in relation_element.attrib.get("ana", "").split(): 

439 if ana.startswith("#"): 

440 ana = ana[1:] 

441 if ana: 

442 types.add(ana) 

443 

444 pair_relation_types = set() 

445 for type_name in types: 

446 relation_type = self.doc.relation_types[type_name] if type_name in self.doc.relation_types else self.doc.add_relation_type(type_name) 

447 pair_relation_types.add(relation_type) 

448 

449 pair = Pair(active=active, passive=passive, types=pair_relation_types) 

450 self.pairs.append(pair) 

451 if passive not in active_visited: 

452 self.non_redundant_pairs.append(pair) 

453 

454 for relation_type in pair_relation_types: 

455 relation_type.pairs.add(pair) 

456 

457 assert len(self.pairs) == len(self.non_redundant_pairs) * 2 

458 

459 self.id_to_reading = {reading.n: reading for reading in self.readings} 

460 

461 def __getitem__(self, key): 

462 return self.id_to_reading[key] 

463 

464 def __len__(self): 

465 return len(self.readings) 

466 

467 def get_classified_pairs(self, redundant:bool=True) -> list[Pair]: 

468 pairs = self.pairs if redundant else self.non_redundant_pairs 

469 return [pair for pair in pairs if len(pair.types) > 0] 

470 

471 def get_unclassified_pairs(self, redundant:bool=True) -> list[Pair]: 

472 pairs = self.pairs if redundant else self.non_redundant_pairs 

473 return [pair for pair in pairs if len(pair.types) == 0] 

474 

475 def __hash__(self): 

476 return hash(self.element) 

477 

478 def __str__(self): 

479 name = self.element.attrib.get('{http://www.w3.org/XML/1998/namespace}id', '') 

480 if not name: 

481 name = self.element.attrib.get('n', '') 

482 

483 if not name: 

484 ab = self.ab() 

485 if ab is not None: 

486 for index, app in enumerate(find_elements(ab, ".//app")): 

487 if app == self.element: 

488 name = make_nc_name(f"{self.ab_name()}-{index+1}") 

489 self.element.attrib['{http://www.w3.org/XML/1998/namespace}id'] = name 

490 break 

491 if not name: 

492 root = self.element.getroottree().getroot() 

493 for index, app in enumerate(find_elements(root, ".//app")): 

494 if app == self.element: 

495 name = make_nc_name(f"app-{index+1}") 

496 self.element.attrib['{http://www.w3.org/XML/1998/namespace}id'] = name 

497 break 

498 return str(name).replace(" ", "_").replace(":", "_") 

499 

500 def ab(self) -> Element|None: 

501 return find_parent(self.element, "ab") 

502 

503 def lacunae(self) -> list[str]: 

504 """ Returns the witnesses recorded as lacunose for this unit in <witDetail type="lac">. """ 

505 witnesses = [] 

506 for wit_detail in unique(find_elements(self.element, ".//witDetail[@type='lac']")): 

507 witnesses.extend(wit_detail.attrib.get("wit", "").split()) 

508 return witnesses 

509 

510 def ab_name(self) -> str: 

511 ab = self.ab() 

512 if ab is None: 

513 return "" 

514 return ab.attrib.get("n", "") 

515 

516 def text_before(self) -> str: 

517 ab = self.ab() 

518 if ab is None: 

519 return extract_text_siblings(self.element, "milestone", truncate=100, preceding=True) 

520 

521 items = [] 

522 for child in ab: 

523 if child == self.element: 

524 break 

525 child_text = extract_text(child) 

526 if child_text: 

527 items.append(child_text) 

528 

529 text = " ".join(items) 

530 return text.strip() 

531 

532 def text_in_context(self, text:str|None=None) -> str: 

533 return f"{self.text_before()} {self.text_with_signs(text)} {self.text_after()}".strip() 

534 

535 def text(self) -> str: 

536 text = extract_text(self.element) 

537 if self.doc.reading_notes: 

538 text, _ = parse_reading_notes(text) 

539 return text 

540 

541 def text_with_signs(self, text:str|None=None) -> str: 

542 text = self.text() if text is None else text 

543 if not text: 

544 return "⸆" 

545 return f"⸂{text}⸃" 

546 

547 def text_after(self) -> str: 

548 ab = self.ab() 

549 if ab is None: 

550 return extract_text_siblings(self.element, "milestone", truncate=100) 

551 

552 items = [] 

553 reached_element = False 

554 for child in ab: 

555 if reached_element: 

556 child_text = extract_text(child) 

557 if child_text: 

558 items.append(child_text) 

559 if child == self.element: 

560 reached_element = True 

561 

562 text = " ".join(items) 

563 return text.strip() 

564 

565 def entropy(self) -> float: 

566 counts = [len(reading.witnesses) for reading in self.readings if len(reading.witnesses) > 0] 

567 total = sum(counts) 

568 probabilities = [count / total for count in counts] 

569 entropy = sum(-p * math.log2(p) for p in probabilities) 

570 

571 return entropy 

572 

573 

574@dataclass 

575class Doc(): 

576 path: Path 

577 tree: ElementTree = field(default=None) 

578 apps: list[App] = field(default_factory=list) 

579 relation_types: dict[str,RelationType] = field(default_factory=dict) 

580 id_to_app: dict[str,App] = field(default_factory=dict) 

581 reading_notes: bool = True 

582 

583 def __post_init__(self): 

584 if self.tree is None: # a tree may be given already parsed (e.g. from bytes read with the file's identity) 

585 self.tree = read_tei(self.path) 

586 self.relation_types = self.get_relation_types() 

587 

588 for app_element in find_elements(self.tree, ".//app"): 

589 app = App(app_element, doc=self) 

590 self.apps.append(app) 

591 

592 self.id_to_app = {app.__str__(): app for app in self.apps} 

593 

594 def __getitem__(self, key): 

595 return self.id_to_app[key] 

596 

597 def __len__(self): 

598 return len(self.apps) 

599 

600 def get_interpgrp(self) -> Element: 

601 text = find_element(self.tree, ".//text") 

602 interp_group = find_element(text, ".//interpGrp[@type='transcriptional']") 

603 if interp_group is None: 

604 interp_group = ET.Element("interpGrp", attrib={"type":"transcriptional"}) 

605 text.insert(0, interp_group) 

606 

607 return interp_group 

608 

609 def get_definitions_comment(self) -> str: 

610 """ 

611 Returns the text of the XML comment(s) immediately preceding the <interpGrp type="transcriptional">. 

612 

613 This is where guidance such as a decision order for the categories is kept. 

614 """ 

615 interp_group = find_element(find_element(self.tree, ".//text"), ".//interpGrp[@type='transcriptional']") 

616 if interp_group is None: 

617 return "" 

618 comments = [] 

619 for sibling in interp_group.itersiblings(preceding=True): 

620 if not isinstance(sibling, ET._Comment): 

621 break 

622 comments.append(textwrap.dedent(sibling.text or "").strip()) 

623 return "\n\n".join(reversed(comments)) 

624 

625 def add_relation_type(self, name:str, description:str="") -> RelationType: 

626 if name in self.relation_types: 

627 assert self.relation_types[name].description == description, f"RelationType {name} already exists with a different description." 

628 return self.relation_types[name] 

629 

630 interp_group = self.get_interpgrp() 

631 interp = find_element(interp_group, f".//interp[@xml:id='{name}']") 

632 if interp is None: 

633 interp = ET.Element("interp", attrib={"{http://www.w3.org/XML/1998/namespace}id":name}) 

634 interp_group.append(interp) 

635 

636 relation_type = RelationType(name=name, element=interp, description="") 

637 self.relation_types[name] = relation_type 

638 return relation_type 

639 

640 def __str__(self): 

641 return str(self.path) 

642 

643 def __repr__(self) -> str: 

644 return str(self) 

645 

646 def write(self, output:str|Path): 

647 write_tei(self.tree, output) 

648 

649 @property 

650 def language(self): 

651 return get_language(self.tree) 

652 

653 def get_relation_types(self, categories_to_ignore:list[str]|None=None) -> list[RelationType]: 

654 interp_group = self.get_interpgrp() 

655 categories_to_ignore = categories_to_ignore or [] 

656 

657 relation_types = dict() 

658 assert interp_group is not None, "No interpGrp of type='transcriptional' found in TEI file." 

659 

660 for interp in find_elements(interp_group, "./interp"): 

661 name = interp.attrib.get("{http://www.w3.org/XML/1998/namespace}id", "") 

662 if name in categories_to_ignore: continue 

663 

664 description = extract_text(interp).strip() 

665 relation_types[name] = RelationType(name=name, element=interp, description=description) 

666 

667 # get corresponding relations 

668 for category in relation_types.values(): 

669 inverse_name = category.element.attrib.get("corresp", "") 

670 if inverse_name.startswith("#"): 

671 inverse_name = inverse_name[1:] 

672 

673 if inverse_name in relation_types: 

674 inverse = relation_types[inverse_name] 

675 category.inverse = inverse 

676 if inverse.inverse is None: 

677 inverse.inverse = category 

678 else: 

679 assert inverse.inverse == category, f"Inverse category {inverse} already has an inverse {inverse.inverse}." 

680 

681 return relation_types 

682 

683 def get_classified_pairs(self, redundant:bool=True) -> list[Pair]: 

684 pairs = [] 

685 for app in self.apps: 

686 pairs.extend(app.get_classified_pairs(redundant=redundant)) 

687 

688 return pairs 

689 

690 def get_unclassified_pairs(self, redundant:bool=True) -> list[Pair]: 

691 pairs = [] 

692 for app in self.apps: 

693 pairs.extend(app.get_unclassified_pairs(redundant=redundant)) 

694 

695 return pairs 

696 

697 def print_classified_pairs(self, console:Console|None=None) -> None: 

698 console = console or Console() 

699 for relation_type in self.relation_types.values(): 

700 console.rule(str(relation_type)) 

701 console.print(relation_type.description, style="grey46") 

702 for pair in relation_type.pairs_sorted(): 

703 pair.print(console) 

704 

705 console.print("") 

706 

707 def clean(self, output:Path|None=None): 

708 """ Cleans a TEI XML file for common errors. """ 

709 

710 # find all transcriptional listRelation elements (not suggestions or intrinsic relations) 

711 list_relations = unique(find_elements(self.tree, ".//listRelation[@type='transcriptional']")) 

712 for list_relation in list_relations: 

713 relations_so_far = set() 

714 for relation in find_elements(list_relation, ".//relation"): 

715 # make sure that relation elements have a # at the start of the ana attribute 

716 if not relation.attrib['ana'].startswith("#"): 

717 relation.attrib['ana'] = f"#{relation.attrib['ana']}" 

718 

719 relations_so_far.add( (relation.attrib['active'], relation.attrib['passive']) ) 

720 

721 # consolidate duplicate relations 

722 for active, passive in relations_so_far: 

723 relations = find_elements(list_relation, f".//relation[@active='{active}'][@passive='{passive}']") 

724 if len(relations) > 1: 

725 analytic_set = set() 

726 for relation in relations: 

727 analytic_set.update(relation.attrib['ana'].split()) 

728 

729 for relation in relations[1:]: 

730 list_relation.remove(relation) 

731 

732 relations[0].attrib['ana'] = " ".join(sorted(analytic_set)) 

733 

734 if output: 

735 output = Path(output) 

736 output.parent.mkdir(parents=True, exist_ok=True) 

737 print("Writing to", output) 

738 self.write(output)