4 from typing import Dict, Mapping, Optional
11 cfg = config.add_commandline_args(
12 f'Unscrambler base library ({__file__})', 'A fast word unscrambler.'
15 "--unscrambler_default_indexfile",
16 help="Path to a file of signature -> word index.",
18 default="/usr/share/dict/sparse_index",
21 logger = logging.getLogger(__name__)
24 letters_mask = 2 ** letters_bits - 1
27 fprint_mask = (2 ** fprint_bits - 1) << letters_bits
29 fprint_feature_bit = {
88 class Unscrambler(object):
89 """A class that unscrambles words quickly by computing a signature
90 (sig) for the word based on its position independent letter
91 population and then using a pregenerated index to look up known
92 words the same set of letters.
94 Note that each instance of Unscrambler caches its index to speed
95 up lookups number 2..N; careless reinstantiation will by slower.
97 Sigs are designed to cluster similar words near each other so both
98 lookup methods support a "fuzzy match" argument that can be set to
99 request similar words that do not match exactly in addition to any
104 def __init__(self, indexfile: Optional[str] = None):
105 # Cached index per instance.
109 filename = self.get_indexfile(indexfile)
110 with open(filename, 'r') as rf:
111 lines = rf.readlines()
114 (fsig, word) = line.split('+')
116 self.sigs.append(isig)
117 self.words.append(word)
119 def get_indexfile(self, indexfile: Optional[str]) -> str:
120 if indexfile is None:
121 if 'unscrambler_default_indexfile' in config.config:
122 indexfile = config.config['unscramble_indexfile']
124 indexfile = "/usr/share/dict/sparse_index"
126 assert file_utils.file_is_readable(indexfile), f"Can't read {indexfile}"
131 def _compute_word_fingerprint(word: str, population: Mapping[str, int]) -> int:
133 for pair in sorted(population.items(), key=lambda x: x[1], reverse=True):
135 if letter in fprint_feature_bit:
139 shift = fprint_feature_bit[letter]
142 return fp << letters_bits
146 def _compute_word_letter_sig(
147 letter_sigs: Mapping[str, int],
149 population: Mapping[str, int],
152 for pair in sorted(population.items(), key=lambda x: x[1], reverse=True):
154 if letter not in letter_sigs:
156 s = letter_sigs[letter]
172 @decorator_utils.memoized
173 def compute_word_sig(word: str) -> int:
174 """Given a word, compute its signature for subsequent lookup
175 operations. Signatures are computed based on the letters in
176 the word and their frequencies. We try to cluster "similar"
177 words close to each other in the signature space.
179 >>> train = Unscrambler.compute_word_sig('train')
183 >>> retain = Unscrambler.compute_word_sig('retrain')
191 population = list_utils.population_counts(word)
192 fprint = Unscrambler._compute_word_fingerprint(word, population)
193 letter_sig = Unscrambler._compute_word_letter_sig(letter_sigs, word, population)
194 assert fprint & letter_sig == 0
195 sig = fprint | letter_sig
200 letter_sigs: Dict[str, int],
201 dictfile: str = '/usr/share/dict/words',
202 indexfile: str = '/usr/share/dict/sparse_index',
204 """Before calling this method, change letter_sigs from the default above
205 unless you want to populate the same exact files.
208 words_by_sigs: Dict[int, str] = {}
210 with open(dictfile, "r") as f:
212 word = word.replace('\n', '')
214 sig = Unscrambler.compute_word_sig(letter_sigs, word)
215 logger.debug("%s => 0x%x" % (word, sig))
219 if sig in words_by_sigs:
220 words_by_sigs[sig] += ",%s" % word
222 words_by_sigs[sig] = word
223 with open(indexfile, 'w') as f:
224 for sig in sorted(words_by_sigs.keys()):
225 word = words_by_sigs[sig]
226 print(f'0x{sig:x}+{word}', file=f)
228 def lookup(self, word: str, *, window_size: int = 5) -> Dict[str, bool]:
229 """Looks up a potentially scrambled word optionally including near
232 >>> u = Unscrambler()
233 >>> u.lookup('eanycleocipd', window_size=0)
234 {'encyclopedia': True}
237 sig = Unscrambler.compute_word_sig(word)
238 return self.lookup_by_sig(sig, window_size=window_size)
240 def lookup_by_sig(self, sig: int, *, window_size: int = 5) -> Dict[str, bool]:
241 """Looks up a word that has already been translated into a signature by
242 a previous call to Unscrambler.compute_word_sig. Optionally returns
243 near "fuzzy" matches.
245 >>> sig = Unscrambler.compute_word_sig('sunepsapetuargiarin')
249 >>> u = Unscrambler()
250 >>> u.lookup_by_sig(sig)
251 {'pupigerous': False, 'pupigenous': False, 'unpurposing': False, 'superpurgation': False, 'unsupporting': False, 'superseptuaginarian': True, 'purpurogallin': False, 'scuppaug': False, 'purpurigenous': False, 'purpurogenous': False, 'proppage': False}
255 (exact, location) = list_utils.binary_search(self.sigs, sig)
256 start = location - window_size
259 end = location + 1 + window_size
260 if end > len(self.words):
261 end = len(self.words)
263 for x in range(start, end):
266 if window_size > 0 or (fsig == sig):
267 ret[word] = fsig == sig
272 # To repopulate, change letter_sigs and then call Unscrambler.repopulate.
273 # See notes above. See also ~/bin/unscramble.py --populate_destructively.
277 if __name__ == "__main__":