Coverage for rdgai/rules.py: 95.35%

86 statements  

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

1""" 

2Rule-based labels for typed subreadings. 

3 

4ECM apparatuses type some readings as subreadings of another reading: e.g. orthographic readings ``ao``, 

5``ao1``, ``ao2`` are spellings of reading ``a``. Given a mapping from reading type to category 

6(e.g. orthographic → Orthography), the pairs these readings form with their parent are labelled by rule: 

7 

81. subreading ↔ its parent: the mapped category; 

92. two subreadings of the same parent and type: the mapped category. 

10 

11Any other pair with a subreading (e.g. ``ao``–``b`` or ``ao``–``bo``) is an ordinary pair, classified by an annotator 

12or the pipeline like any other. 

13 

14A subreading's parent is found by removing the rule's suffix and any digits after it from the reading's id 

15(``ao2`` → ``a``). Readings whose parent cannot be found, and subreadings of subreadings, are reported, never guessed. 

16 

17The rules are stored in the TEI file next to the category definitions:: 

18 

19 <interpGrp type="subreading-rules"> 

20 <interp xml:id="rule-orthographic" type="orthographic" ana="#Orthography" n="o">…</interp> 

21 </interpGrp> 

22 

23``@type`` is the reading type, ``@ana`` the category and ``@n`` the id suffix. Labels made by a rule have 

24``resp="#rule-orthographic"``, pointing to the rule. 

25""" 

26import re 

27from dataclasses import dataclass, field 

28 

29DEFAULT_SUFFIXES = {"orthographic": "o", "defective": "f"} 

30RULE_GROUP_TYPE = "subreading-rules" 

31 

32 

33@dataclass(frozen=True) 

34class SubreadingRule: 

35 reading_type: str 

36 category: str 

37 suffix: str 

38 

39 @property 

40 def resp_id(self) -> str: 

41 return "rule-" + re.sub(r"[^A-Za-z0-9_.\-]", "-", self.reading_type) 

42 

43 def description(self) -> str: 

44 return ( 

45 f"Readings of type '{self.reading_type}' are subreadings of the reading whose id is theirs without the suffix " 

46 f"'{self.suffix}' and any digits after it. A subreading and its parent, and two such subreadings of the same " 

47 f"parent, are labelled {self.category}." 

48 ) 

49 

50 

51@dataclass 

52class Parents: 

53 parents: dict[str, str] = field(default_factory=dict) # subreading id -> parent id 

54 types: dict[str, str] = field(default_factory=dict) # subreading id -> reading type 

55 unresolved: list[str] = field(default_factory=list) # typed readings whose parent is not in the unit 

56 nested: list[tuple[str, str]] = field(default_factory=list) # (subreading, parent) where the parent is itself typed 

57 

58 @property 

59 def skipped(self) -> set[str]: 

60 return set(self.unresolved) | {reading for reading, _ in self.nested} 

61 

62 

63@dataclass 

64class Coverage: 

65 rule: int # 1 (subreading and parent) or 2 (sibling subreadings) 

66 reading_type: str 

67 

68 

69def find_parents(app, rules:list[SubreadingRule]) -> Parents: 

70 """ Finds the parent of each typed subreading in a unit (an rdgai.apparatus.App). """ 

71 by_type = {rule.reading_type: rule for rule in rules} 

72 readings = {reading.n: reading for reading in app.readings} 

73 result = Parents() 

74 for reading in app.readings: 

75 rule = by_type.get(reading.type) 

76 if rule is None: 

77 continue 

78 match = re.match(rf"^(?P<parent>.+?){re.escape(rule.suffix)}\d*$", reading.n) 

79 if not match or match["parent"] not in readings: 

80 result.unresolved.append(reading.n) 

81 continue 

82 parent = readings[match["parent"]] 

83 if parent.type: 

84 result.nested.append((reading.n, parent.n)) 

85 continue 

86 result.parents[reading.n] = parent.n 

87 result.types[reading.n] = rule.reading_type 

88 return result 

89 

90 

91def coverage(active:str, passive:str, parents:Parents) -> Coverage | None: 

92 """ Which rule covers the pair active → passive, or None if it is a pair for an annotator. """ 

93 if active in parents.skipped or passive in parents.skipped: 

94 return None 

95 if active not in parents.parents and passive not in parents.parents: 

96 return None 

97 active_parent = parents.parents.get(active, active) 

98 passive_parent = parents.parents.get(passive, passive) 

99 active_type = parents.types.get(active) 

100 passive_type = parents.types.get(passive) 

101 if active_parent != passive_parent: 

102 return None # a subreading and another reading (or another reading's subreading): an ordinary pair 

103 if active == active_parent: 

104 return Coverage(1, passive_type) 

105 if passive == passive_parent: 

106 return Coverage(1, active_type) 

107 if active_type == passive_type: 

108 return Coverage(2, active_type) 

109 return None # subreadings of the same parent but of different types: no rule 

110 

111 

112def build_rules(stored:list[SubreadingRule], rules:dict[str, str]|None=None, suffixes:dict[str, str]|None=None) -> list[SubreadingRule] | None: 

113 """ 

114 Combines rules given as options ({reading type: category}, {reading type: suffix}) with the stored rules. 

115 Given rules replace the stored ones; suffixes alone change the suffix of stored rules. Returns None if 

116 nothing was given (use the stored rules). 

117 """ 

118 suffixes = suffixes or {} 

119 known = {rule.reading_type: rule for rule in stored} 

120 if not rules and not suffixes: 

121 return None 

122 if not rules: 

123 rules = {rule.reading_type: rule.category for rule in stored} 

124 result = [] 

125 for reading_type, category in rules.items(): 

126 suffix = suffixes.get(reading_type) or (known[reading_type].suffix if reading_type in known else DEFAULT_SUFFIXES.get(reading_type)) 

127 if not suffix: 

128 raise ValueError(f"No id suffix known for reading type '{reading_type}': give one, e.g. {reading_type}=o.") 

129 result.append(SubreadingRule(reading_type=reading_type, category=category, suffix=suffix)) 

130 return result 

131 

132 

133def parse_assignments(values:list[str]|None, option:str) -> dict[str, str]: 

134 """ ['orthographic=Orthography'] -> {'orthographic': 'Orthography'} """ 

135 result = {} 

136 for value in values or []: 

137 key, separator, item = value.partition("=") 

138 if not separator or not key.strip() or not item.strip(): 

139 raise ValueError(f"{option} expects TYPE=VALUE, e.g. orthographic=Orthography (got '{value}').") 

140 result[key.strip()] = item.strip() 

141 return result