Coverage for rdgai/diff.py: 100.00%

95 statements  

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

1""" 

2A description of the change from one reading to another, from a word-level diff. 

3 

4It is a reading aid (e.g. "second reading adds: και"), never a label. ``label_warning`` flags a label that clearly 

5contradicts it, judged from the words in the category's name (e.g. an "Omission" when the second reading only adds 

6words); categories named otherwise are never flagged. 

7""" 

8import re 

9from dataclasses import dataclass, field 

10from collections import Counter, defaultdict, deque 

11from difflib import SequenceMatcher 

12 

13ADDITION_WORDS = {"addition", "additions", "add", "adds", "insertion", "insertions", "insert", "plus"} 

14OMISSION_WORDS = {"omission", "omissions", "omit", "omits", "deletion", "deletions", "delete", "minus"} 

15 

16 

17@dataclass 

18class ChangeDescription: 

19 kind: str # identical, addition, omission, reordering or changed (never named after a category) 

20 text: str 

21 added: list[str] = field(default_factory=list) 

22 removed: list[str] = field(default_factory=list) 

23 reordered: bool = False # words the readings share (or forms of them) come in a different order 

24 

25 

26# two words count as forms of the same word (αυτον/αυτων, αυτον/αυτω) when at least this alike, and this long 

27SIMILAR_WORD = 0.6 

28SIMILAR_WORD_LENGTH = 3 

29 

30 

31def _similar(first:str, second:str) -> bool: 

32 if min(len(first), len(second)) < SIMILAR_WORD_LENGTH: 

33 return False 

34 return SequenceMatcher(None, first, second, autojunk=False).ratio() >= SIMILAR_WORD 

35 

36 

37def _alignment(a:list[str], b:list[str]) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]: 

38 """ 

39 Which words of a correspond to which of b: (exact, similar) lists of (index in a, index in b). 

40 

41 The diff's in-order matches come first; words left over that occur in both readings are words that moved; then 

42 left-over words that are forms of each other (αυτον → αυτων) are paired, most alike first. 

43 """ 

44 exact = [] 

45 for block in SequenceMatcher(None, a, b, autojunk=False).get_matching_blocks(): 

46 exact += [(block.a + offset, block.b + offset) for offset in range(block.size)] 

47 matched_a, matched_b = {i for i, _ in exact}, {j for _, j in exact} 

48 left_in_b = defaultdict(deque) 

49 for j, word in enumerate(b): 

50 if j not in matched_b: 

51 left_in_b[word].append(j) 

52 for i, word in enumerate(a): 

53 if i not in matched_a and left_in_b[word]: 

54 j = left_in_b[word].popleft() 

55 exact.append((i, j)) 

56 matched_a.add(i) 

57 matched_b.add(j) 

58 

59 candidates = sorted( 

60 ((SequenceMatcher(None, a[i], b[j], autojunk=False).ratio(), i, j) 

61 for i in range(len(a)) if i not in matched_a 

62 for j in range(len(b)) if j not in matched_b and _similar(a[i], b[j])), 

63 reverse=True) 

64 similar = [] 

65 for _, i, j in candidates: 

66 if i not in matched_a and j not in matched_b: 

67 similar.append((i, j)) 

68 matched_a.add(i) 

69 matched_b.add(j) 

70 return exact, similar 

71 

72 

73def _runs(tokens:list[str], indexes:list[int]) -> str: 

74 """ The words at these indexes, consecutive ones together, separate runs joined by ' … '. """ 

75 runs = [] 

76 for index in sorted(indexes): 

77 if runs and runs[-1][-1] == index - 1: 

78 runs[-1].append(index) 

79 else: 

80 runs.append([index]) 

81 return " … ".join(" ".join(tokens[index] for index in run) for run in runs) 

82 

83 

84def _describe_reordered(a:list[str], b:list[str], exact:list[tuple[int, int]]) -> ChangeDescription: 

85 """ Words moved, and others added, omitted or changed: the words that differ, saying that the order changed too. """ 

86 in_a, in_b = {i for i, _ in exact}, {j for _, j in exact} 

87 removed_indexes = [i for i in range(len(a)) if i not in in_a] 

88 added_indexes = [j for j in range(len(b)) if j not in in_b] 

89 removed = [a[i] for i in removed_indexes] 

90 added = [b[j] for j in added_indexes] 

91 if added and removed: 

92 text = f"reordered and changed: {_runs(a, removed_indexes)} → {_runs(b, added_indexes)}" 

93 return ChangeDescription("changed", text, added, removed, reordered=True) 

94 if added: 

95 return ChangeDescription("addition", f"second reading reorders and adds: {_runs(b, added_indexes)}", added, removed, reordered=True) 

96 return ChangeDescription("omission", f"second reading reorders and omits: {_runs(a, removed_indexes)}", added, removed, reordered=True) 

97 

98 

99def _segments(tokens:list[str], spans:list[tuple[int, int]]) -> str: 

100 return " … ".join(" ".join(tokens[start:end]) for start, end in spans) 

101 

102 

103def describe_change(first:str, second:str) -> ChangeDescription: 

104 """ Describes the change from the first reading's text to the second's ('' for an omission). """ 

105 a, b = (first or "").split(), (second or "").split() 

106 if a == b: 

107 return ChangeDescription("identical", "readings are identical") 

108 if Counter(a) == Counter(b): 

109 return ChangeDescription("reordering", "same words, reordered", reordered=True) 

110 

111 # words (or forms of them) the readings share, in a different order: a move as well as a change 

112 exact, similar = _alignment(a, b) 

113 in_order_of_a = [j for _, j in sorted(exact + similar)] 

114 if any(later < earlier for earlier, later in zip(in_order_of_a, in_order_of_a[1:])): 

115 return _describe_reordered(a, b, exact) 

116 

117 removed_spans, added_spans = [], [] 

118 for tag, i1, i2, j1, j2 in SequenceMatcher(None, a, b, autojunk=False).get_opcodes(): 

119 if tag in ("delete", "replace"): 

120 removed_spans.append((i1, i2)) 

121 if tag in ("insert", "replace"): 

122 added_spans.append((j1, j2)) 

123 removed = [token for start, end in removed_spans for token in a[start:end]] 

124 added = [token for start, end in added_spans for token in b[start:end]] 

125 

126 if added and not removed: 

127 return ChangeDescription("addition", f"second reading adds: {_segments(b, added_spans)}", added, removed) 

128 if removed and not added: 

129 return ChangeDescription("omission", f"second reading omits: {_segments(a, removed_spans)}", added, removed) 

130 return ChangeDescription( 

131 # neutral wording: a different form of the same word (εξηλθεν → εξηλθον) is not a Substitution 

132 "changed", f"changed: {_segments(a, removed_spans)} → {_segments(b, added_spans)}", added, removed, 

133 ) 

134 

135 

136def label_warning(category:str|None, change:ChangeDescription) -> str|None: 

137 """ A warning if the category's name says addition/omission but the readings show the opposite, else None. """ 

138 if not category: 

139 return None 

140 words = set(re.split(r"[^a-z]+", category.lower())) 

141 if words & OMISSION_WORDS and change.kind == "addition": 

142 return f"{category} is for an omission, but the {change.text}." 

143 if words & ADDITION_WORDS and change.kind == "omission": 

144 return f"{category} is for an addition, but the {change.text}." 

145 return None