Coverage for rdgai/search.py: 98.72%

78 statements  

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

1""" 

2Similarity search over labelled pairs: BM25 over terms describing each pair's change. 

3 

4A pair's terms are what the second reading adds (``+word``) and omits (``-word``), the kind of change 

5(``kind:addition`` …), character n-grams of the added and omitted words (``+g:κρα``, ``-g:#κρ``, with ``#`` marking 

6the word's edges, so that other forms of a word still match: κραζον / κραυγαζον, πρωτη / πρωτου) and the words just 

7before and after the variation unit (``ctx:word``). Words are normalized (combining marks removed, 

8case-folded), so accented and unaccented texts match. N-gram terms are weighted by 

9``NGRAM_WEIGHT``; a whole-word match shares the word term and all its n-grams, so it still ranks first. 

10""" 

11import math 

12import os 

13import re 

14import unicodedata 

15from collections import Counter 

16 

17from .diff import describe_change 

18 

19WORD = re.compile(r"\w+") 

20UNIT_ID = re.compile(r"^(?P<book>[^.]+)\.(?P<chapter>\d+)\.(?P<verse>\d+)\.") 

21CONTEXT_WORDS = 2 

22DEFAULT_NGRAM_SIZES = (2,) # chosen by measurement (results/mark-cv/retrieval.py, retrieval.txt) 

23DEFAULT_NGRAM_WEIGHT = 1.0 # per n-gram term, as for a whole-word term (the word term counts twice) 

24NGRAM_PREFIXES = ("+g:", "-g:") 

25 

26 

27def settings_from_env(environ=os.environ) -> tuple[tuple[int, ...], float]: 

28 """ N-gram sizes and weight, overridable for experiments by RDGAI_NGRAMS ("3,4"; empty for none) and RDGAI_NGRAM_WEIGHT. """ 

29 sizes = environ.get("RDGAI_NGRAMS") 

30 sizes = DEFAULT_NGRAM_SIZES if sizes is None else tuple(int(size) for size in sizes.split(",") if size.strip()) 

31 return sizes, float(environ.get("RDGAI_NGRAM_WEIGHT", DEFAULT_NGRAM_WEIGHT)) 

32 

33 

34NGRAM_SIZES, NGRAM_WEIGHT = settings_from_env() 

35 

36 

37def normalize(text:str) -> str: 

38 """ 

39 Removes accents, breathings and other combining marks and case-folds (any script; case-folding also writes Greek 

40 final sigma as σ), so accented and unaccented texts match. 

41 """ 

42 decomposed = unicodedata.normalize("NFD", text or "") 

43 stripped = "".join(character for character in decomposed if unicodedata.category(character) != "Mn") 

44 return unicodedata.normalize("NFC", stripped).casefold() 

45 

46 

47normalize_greek = normalize # the older name 

48 

49 

50def tokens(text:str) -> list[str]: 

51 return WORD.findall(normalize(text)) 

52 

53 

54def character_ngrams(word:str, sizes) -> list[str]: 

55 """ The character n-grams of a word with ``#`` marking its start and end (a short word is one n-gram). """ 

56 marked = f"#{word}#" 

57 grams = [] 

58 for size in sizes: 

59 if len(marked) <= size: 

60 grams.append(marked) 

61 else: 

62 grams += [marked[index:index + size] for index in range(len(marked) - size + 1)] 

63 return list(dict.fromkeys(grams)) 

64 

65 

66def ngram_weights() -> dict[str, float]: 

67 return {prefix: NGRAM_WEIGHT for prefix in NGRAM_PREFIXES} 

68 

69 

70def pair_terms(active_text:str, passive_text:str, before:str="", after:str="", ngrams=None) -> list[str]: 

71 """ 

72 The search terms for the change from the active reading to the passive reading. `ngrams` gives the n-gram sizes 

73 (default ``NGRAM_SIZES``; empty for none). 

74 """ 

75 sizes = NGRAM_SIZES if ngrams is None else ngrams 

76 change = describe_change(" ".join(tokens(active_text)), " ".join(tokens(passive_text))) 

77 terms = [f"kind:{change.kind}"] 

78 if change.reordered and change.kind != "reordering": 

79 terms.append("kind:reordering") # moved as well as changed 

80 # the difference is what matters most, so its terms count twice 

81 terms += [f"+{word}" for word in change.added] * 2 

82 terms += [f"-{word}" for word in change.removed] * 2 

83 if sizes: 

84 terms += [f"+g:{gram}" for word in change.added for gram in character_ngrams(word, sizes)] 

85 terms += [f"-g:{gram}" for word in change.removed for gram in character_ngrams(word, sizes)] 

86 terms += [f"ctx:{word}" for word in tokens(before)[-CONTEXT_WORDS:]] 

87 terms += [f"ctx:{word}" for word in tokens(after)[:CONTEXT_WORDS]] 

88 return terms 

89 

90 

91def verse_label(unit_id:str) -> str: 

92 """ 'Mark.2.27.20' -> 'Mark 2:27' (other ids are returned unchanged). """ 

93 match = UNIT_ID.match(unit_id) 

94 return f"{match['book']} {match['chapter']}:{match['verse']}" if match else unit_id 

95 

96 

97class BM25: 

98 """ 

99 Okapi BM25 over pre-tokenized documents. `weights` scales the score of query terms by prefix (default: n-gram 

100 terms count ``NGRAM_WEIGHT``). 

101 """ 

102 def __init__(self, documents:list[list[str]], k1:float=1.5, b:float=0.75, weights:dict[str, float]|None=None): 

103 self.k1, self.b = k1, b 

104 self.weights = ngram_weights() if weights is None else weights 

105 self.frequencies = [Counter(document) for document in documents] 

106 self.lengths = [len(document) for document in documents] 

107 self.average_length = (sum(self.lengths) / len(documents)) if documents else 0.0 

108 document_frequency = Counter(term for frequencies in self.frequencies for term in frequencies) 

109 count = len(documents) 

110 self.idf = { 

111 term: math.log(1 + (count - frequency + 0.5) / (frequency + 0.5)) 

112 for term, frequency in document_frequency.items() 

113 } 

114 

115 def weight(self, term:str) -> float: 

116 for prefix, weight in self.weights.items(): 

117 if term.startswith(prefix): 

118 return weight 

119 return 1.0 

120 

121 def scores(self, query:list[str]) -> list[float]: 

122 weights = {term: self.weight(term) for term in set(query)} 

123 results = [] 

124 for frequencies, length in zip(self.frequencies, self.lengths): 

125 score = 0.0 

126 norm = self.k1 * (1 - self.b + self.b * length / self.average_length) if self.average_length else self.k1 

127 for term in set(query): 

128 frequency = frequencies.get(term, 0) 

129 if frequency: 

130 score += weights[term] * self.idf[term] * frequency * (self.k1 + 1) / (frequency + norm) 

131 results.append(score) 

132 return results