File size: 5,921 Bytes
0109502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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