Band-hashing LSH — same API as datasketch.MinHashLSH for the subset used here.
| 82 | |
| 83 | |
| 84 | class MinHashLSH: |
| 85 | """Band-hashing LSH — same API as datasketch.MinHashLSH for the subset used here.""" |
| 86 | |
| 87 | def __init__(self, threshold: float = 0.5, num_perm: int = 128) -> None: |
| 88 | self.b, self.r = _optimal_lsh_params(threshold, num_perm) |
| 89 | self._tables: list[dict[bytes, list[str]]] = [{} for _ in range(self.b)] |
| 90 | self._keys: set[str] = set() |
| 91 | |
| 92 | def insert(self, key: str, minhash: MinHash) -> None: |
| 93 | if key in self._keys: |
| 94 | raise ValueError(f"Key {key!r} already exists in MinHashLSH") |
| 95 | self._keys.add(key) |
| 96 | hv = minhash.hashvalues |
| 97 | for i, table in enumerate(self._tables): |
| 98 | band = hv[i * self.r : (i + 1) * self.r].tobytes() |
| 99 | table.setdefault(band, []).append(key) |
| 100 | |
| 101 | def query(self, minhash: MinHash) -> list[str]: |
| 102 | hv = minhash.hashvalues |
| 103 | candidates: set[str] = set() |
| 104 | for i, table in enumerate(self._tables): |
| 105 | band = hv[i * self.r : (i + 1) * self.r].tobytes() |
| 106 | candidates.update(table.get(band, [])) |
| 107 | return list(candidates) |
no outgoing calls