KeremTT's picture
Update code
c02657c verified
Raw History Blame Contribute Delete
1.86 kB
"""Exact and MinHash-LSH near-duplicate removal (pure numpy, no external services)."""
import numpy as np
from .text import key, words
_MERSENNE = np.uint64((1 << 61) - 1)
class ExactDeduper:
def __init__(self):
self.seen = set()
def is_dup(self, text: str) -> bool:
k = key(text)
if k in self.seen:
return True
self.seen.add(k)
return False
class MinHashLSH:
"""Jaccard near-duplicate detector over word 5-gram shingles.
num_perm = bands * rows. With bands=16, rows=8 a pair with Jaccard 0.8 collides
with probability ~0.98, a pair with Jaccard 0.5 with probability ~0.06.
"""
def __init__(self, bands=16, rows=8, shingle=5, seed=1234):
self.bands, self.rows, self.shingle = bands, rows, shingle
rng = np.random.default_rng(seed)
n = bands * rows
self.a = rng.integers(1, (1 << 61) - 1, n, dtype=np.uint64)
self.b = rng.integers(0, (1 << 61) - 1, n, dtype=np.uint64)
self.tables = [dict() for _ in range(bands)]
def signature(self, text):
toks = words(text)
if len(toks) < self.shingle:
toks = toks + [""] * (self.shingle - len(toks))
sh = {hash(" ".join(toks[i:i + self.shingle])) & ((1 << 61) - 1)
for i in range(len(toks) - self.shingle + 1)}
x = np.fromiter(sh, dtype=np.uint64)
with np.errstate(over="ignore"):
h = (np.outer(x, self.a) + self.b) % _MERSENNE
return h.min(axis=0)
def is_dup(self, text: str) -> bool:
sig = self.signature(text)
keys = [sig[i * self.rows:(i + 1) * self.rows].tobytes() for i in range(self.bands)]
if any(k in t for k, t in zip(keys, self.tables)):
return True
for k, t in zip(keys, self.tables):
t[k] = True
return False