PERDYPTO
Upload 45 files
0109502 verified
Raw History Blame Contribute Delete
5.92 kB
from __future__ import annotations
import ast, hashlib, json, random, re, zlib
from pathlib import Path
def norm(code):
return "\n".join(x.rstrip() for x in code.replace("\r\n", "\n").splitlines()).strip()
def fp(code):
try:
t = ast.parse(code)
for n in ast.walk(t):
if isinstance(n, ast.Name):
n.id = "VAR"
elif isinstance(n, ast.arg):
n.arg = "VAR"
elif isinstance(n, ast.Constant) and isinstance(n.value, (str, int, float, complex)):
n.value = type(n.value).__name__
return hashlib.sha256(ast.dump(t, include_attributes=False).encode()).hexdigest()
except SyntaxError:
return None
def shingles(code):
x = re.findall(r"[A-Za-z_]\w*|==|!=|<=|>=|\S", code)
return set(" ".join(x[i:i + 4]) for i in range(max(1, len(x) - 3)))
def jac(a, b):
return len(a & b) / len(a | b) if a or b else 1
_MASK = (1 << 32) - 1
def _hash_funcs(num_hashes, seed=1337):
rng = random.Random(seed)
# (a, b) pairs for a universal hash family h(x) = (a*x + b) mod MASK
return [(rng.randrange(1, _MASK), rng.randrange(0, _MASK)) for _ in range(num_hashes)]
class MinHashLSH:
"""Approximate near-duplicate candidate lookup.
Instead of comparing a new record's shingle set against every previously
seen record (O(n) per record, O(n^2) per run), each record's shingle set
is summarized into a small MinHash signature. Signatures are split into
bands and hashed into buckets; two records can only ever be compared for
exact Jaccard similarity if they land in the same bucket in at least one
band. This turns "find near-duplicate candidates" into an expected O(1)
bucket lookup instead of a full scan, while keeping the final similarity
decision an exact Jaccard computation (no false accepts from hashing).
"""
def __init__(self, num_hashes: int = 32, bands: int = 8):
assert num_hashes % bands == 0, "num_hashes must be divisible by bands"
self.num_hashes = num_hashes
self.bands = bands
self.rows_per_band = num_hashes // bands
self.funcs = _hash_funcs(num_hashes)
self.buckets: list[dict] = [dict() for _ in range(bands)]
def signature(self, shingle_set) -> list[int]:
hashed = [zlib.crc32(s.encode("utf-8")) for s in shingle_set] or [0]
return [min((a * h + b) & _MASK for h in hashed) for a, b in self.funcs]
def candidates(self, sig: list[int]) -> set:
out = set()
for i in range(self.bands):
band = tuple(sig[i * self.rows_per_band:(i + 1) * self.rows_per_band])
bucket = self.buckets[i].get(band)
if bucket:
out.update(bucket)
return out
def add(self, sig: list[int], record_id: str) -> None:
for i in range(self.bands):
band = tuple(sig[i * self.rows_per_band:(i + 1) * self.rows_per_band])
self.buckets[i].setdefault(band, []).append(record_id)
class Deduper:
def __init__(self, path, similarity=.94, num_hashes: int = 32, bands: int = 8):
self.path = Path(path)
self.similarity = similarity
self.rows_by_id: dict[str, dict] = {}
self.by_hash: dict[str, str] = {} # exact hash -> record_id
self.by_fp: dict[str, str] = {} # ast fingerprint -> record_id
self.lsh = MinHashLSH(num_hashes=num_hashes, bands=bands)
if self.path.exists():
for line in self.path.read_text().splitlines():
try:
row = json.loads(line)
except Exception:
continue
self._index(row)
def _index(self, row: dict) -> None:
rid = row["id"]
self.rows_by_id[rid] = row
self.by_hash.setdefault(row["hash"], rid)
if row.get("fp"):
self.by_fp.setdefault(row["fp"], rid)
sig = row.get("sig")
if sig is None:
# Backward compatibility with dedupe files written before MinHash
# signatures existed: derive the signature from stored shingles.
sig = self.lsh.signature(set(row.get("shingles", [])))
self.lsh.add(sig, rid)
def check_and_add(self, code: str, record_id: str) -> dict:
h = hashlib.sha256(norm(code).encode()).hexdigest()
f = fp(code)
s = shingles(code)
sig = self.lsh.signature(s)
exact_id = self.by_hash.get(h)
if exact_id is not None:
return {"duplicate": True, "kind": "exact", "match_id": exact_id,
"similarity": 1, "exact_hash": h, "ast_fingerprint": f}
if f is not None:
struct_id = self.by_fp.get(f)
if struct_id is not None:
return {"duplicate": True, "kind": "structural", "match_id": struct_id,
"similarity": 1, "exact_hash": h, "ast_fingerprint": f}
best_id, best_score = None, 0.0
for cand_id in self.lsh.candidates(sig):
cand = self.rows_by_id.get(cand_id)
if not cand:
continue
q = jac(s, set(cand.get("shingles", [])))
if q > best_score:
best_id, best_score = cand_id, q
if best_id is not None and best_score >= self.similarity:
return {"duplicate": True, "kind": "near", "match_id": best_id,
"similarity": best_score, "exact_hash": h, "ast_fingerprint": f}
row = {"id": record_id, "hash": h, "fp": f, "shingles": sorted(s), "sig": sig}
self._index(row)
self.path.parent.mkdir(parents=True, exist_ok=True)
with self.path.open("a") as z:
z.write(json.dumps(row) + "\n")
return {"duplicate": False, "kind": None, "match_id": None, "similarity": 0,
"exact_hash": h, "ast_fingerprint": f}
ExactDeduper = Deduper