File size: 12,605 Bytes
693bf28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""Deduplication engine (global across all classes and queries).

Layer 1  exact       SHA-256 of the original bytes (already the image_id, so identical downloads
                     collapse at download time) + SHA-256 of the decoded normalized pixels.
Layer 2  near-dup    pHash AND dHash (64-bit each) within a Hamming-distance budget. Every image
                     also stores the hashes of its horizontally FLIPPED version, and a pair counts
                     as a duplicate if it matches in either orientation (mirror copies).
Layer 3  semantic    CLIP-embedding cosine clustering. This layer never deletes anything; it only
                     merges cluster ids so the splitter keeps "same board, different angle" together.

Layers 1-2 remove images: within a duplicate group the keeper is chosen by
    (already-processed before new) > (real-world before web) > higher resolution > larger file > id
so re-running the pipeline never swaps out an image that was already kept or annotated.
Duplicate groups are connected components (union-find), so chains A~B~C collapse into one group.
"""
from __future__ import annotations

import logging
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Sequence

import imagehash
import numpy as np
from PIL import Image, ImageOps
from tqdm import tqdm

from .manifest import Manifest

log = logging.getLogger(__name__)

# Statuses whose images are candidates for duplicate comparison (hashes present).
_PROCESSED = ("deduped", "kept", "review")
_CANDIDATES = ("normalized",) + _PROCESSED

_POP8 = np.array([bin(i).count("1") for i in range(256)], dtype=np.uint8)


# ------------------------------------------------------------------------------------ hashing
def compute_hashes(path: str | Path) -> dict[str, str]:
    """pHash/dHash (8x8 => 64 bit, hex) for an image and for its horizontal mirror."""
    with Image.open(path) as im:
        im.draft("RGB", (512, 512))  # cheap JPEG downscale on decode; same procedure for all images
        im = ImageOps.exif_transpose(im).convert("RGB")
        flipped = ImageOps.mirror(im)
        return {
            "phash": str(imagehash.phash(im, hash_size=8)),
            "dhash": str(imagehash.dhash(im, hash_size=8)),
            "phash_flip": str(imagehash.phash(flipped, hash_size=8)),
            "dhash_flip": str(imagehash.dhash(flipped, hash_size=8)),
        }


def hex_to_u64(values: Sequence[str]) -> np.ndarray:
    return np.array([int(v, 16) for v in values], dtype=np.uint64)


def popcount64(x: np.ndarray) -> np.ndarray:
    """Per-element population count of a uint64 array."""
    if hasattr(np, "bitwise_count"):  # numpy >= 2.0
        return np.bitwise_count(x)
    x = np.ascontiguousarray(x)
    return _POP8[x.view(np.uint8).reshape(*x.shape, 8)].sum(axis=-1)


# --------------------------------------------------------------------------------- union-find
class UnionFind:
    def __init__(self, n: int):
        self.parent = list(range(n))

    def find(self, a: int) -> int:
        while self.parent[a] != a:
            self.parent[a] = self.parent[self.parent[a]]
            a = self.parent[a]
        return a

    def union(self, a: int, b: int) -> None:
        ra, rb = self.find(a), self.find(b)
        if ra != rb:
            self.parent[max(ra, rb)] = min(ra, rb)

    def groups(self) -> list[list[int]]:
        out: dict[int, list[int]] = defaultdict(list)
        for i in range(len(self.parent)):
            out[self.find(i)].append(i)
        return [g for g in out.values() if len(g) > 1]


def near_duplicate_pairs(ph: np.ndarray, dh: np.ndarray, phf: np.ndarray, dhf: np.ndarray,
                         phash_max: int, dhash_max: int, block_cells: int = 4_000_000):
    """Yield (i, j), i < j, whose pHash *and* dHash are within budget in the same orientation
    (direct, or with j mirrored). Vectorized in row blocks to bound memory."""
    n = len(ph)
    if n < 2:
        return
    block = max(1, block_cells // n)
    cols = np.arange(n)
    for a in range(0, n, block):
        b = min(n, a + block)
        upper = cols[None, :] > np.arange(a, b)[:, None]
        direct = (popcount64(ph[a:b, None] ^ ph[None, :]) <= phash_max) & \
                 (popcount64(dh[a:b, None] ^ dh[None, :]) <= dhash_max)
        mirrored = (popcount64(ph[a:b, None] ^ phf[None, :]) <= phash_max) & \
                   (popcount64(dh[a:b, None] ^ dhf[None, :]) <= dhash_max)
        ii, jj = np.nonzero((direct | mirrored) & upper)
        for i, j in zip(ii + a, jj):
            yield int(i), int(j)


def find_duplicate_groups(rows: list[dict], phash_max: int, dhash_max: int) -> list[list[int]]:
    """Group row indices by exact pixel hash + near-duplicate hashes (connected components)."""
    n = len(rows)
    uf = UnionFind(n)
    by_pixels: dict[str, int] = {}
    for i, r in enumerate(rows):
        px = r.get("pixel_sha256")
        if px:
            if px in by_pixels:
                uf.union(by_pixels[px], i)
            else:
                by_pixels[px] = i
    if n >= 2:
        ph = hex_to_u64([r["phash"] for r in rows])
        dh = hex_to_u64([r["dhash"] for r in rows])
        phf = hex_to_u64([r["phash_flip"] for r in rows])
        dhf = hex_to_u64([r["dhash_flip"] for r in rows])
        for i, j in near_duplicate_pairs(ph, dh, phf, dhf, phash_max, dhash_max):
            uf.union(i, j)
    return uf.groups()


def keeper_rank(row: dict) -> tuple:
    """Lower sorts first = preferred keeper."""
    processed = 0 if row["status"] in _PROCESSED else 1
    realworld = 0 if row.get("origin") == "realworld" else 1
    pixels = (row.get("norm_width") or row.get("width") or 0) * (row.get("norm_height") or row.get("height") or 0)
    return (processed, realworld, -pixels, -(row.get("filesize") or 0), row["image_id"])


# ------------------------------------------------------------------------------------- stage
def run(manifest: Manifest, cfg: dict, data_dir: Path) -> dict[str, int]:
    """Hash new images, then discard exact/near duplicates across the whole candidate pool."""
    dcfg = cfg["dedup"]
    stats = {"hashed": 0, "exact_duplicate": 0, "near_duplicate": 0, "deduped": 0, "hash_failed": 0}

    # 1. hashes for images that do not have them yet
    fresh = [r for r in manifest.images(statuses=["normalized"]) if not r["phash"]]
    if fresh:
        def work(r: dict):
            try:
                return r, compute_hashes(data_dir / r["norm_path"]), None
            except Exception as exc:  # noqa: BLE001
                return r, None, exc

        with ThreadPoolExecutor(max_workers=int(dcfg.get("hash_workers", 4))) as ex:
            futures = [ex.submit(work, r) for r in fresh]
            with manifest.transaction():
                for fut in tqdm(as_completed(futures), total=len(futures), desc="hash", unit="img"):
                    r, hashes, err = fut.result()
                    if err is not None:
                        log.warning("hashing failed for %s: %s", r["image_id"], err)
                        manifest.discard(r["image_id"], "hash_failed")
                        stats["hash_failed"] += 1
                    else:
                        manifest.update_image(r["image_id"], **hashes)
                        stats["hashed"] += 1

    # 2. group duplicates over the full candidate pool (new + previously processed)
    rows = [r for r in manifest.images(statuses=_CANDIDATES) if r["phash"]]
    groups = find_duplicate_groups(rows, int(dcfg["phash_max_dist"]), int(dcfg["dhash_max_dist"]))
    log.info("dedup: %d candidates, %d duplicate group(s)", len(rows), len(groups))

    discarded: set[str] = set()
    cluster_of: dict[str, str] = {}  # cluster ids assigned during this run
    with manifest.transaction():
        for group in groups:
            members = sorted((rows[i] for i in group), key=keeper_rank)
            keeper, losers = members[0], members[1:]
            # Reuse the keeper's existing cluster id: a previous semantic merge may have
            # renamed it, and a rerun must never undo that.
            cid = keeper["cluster_id"] or keeper["image_id"]
            for member in members:
                cluster_of[member["image_id"]] = cid
                manifest.update_image(member["image_id"], cluster_id=cid)
            for loser in losers:
                exact = bool(loser["pixel_sha256"]) and loser["pixel_sha256"] == keeper["pixel_sha256"]
                reason = "exact_duplicate" if exact else "near_duplicate"
                if loser["status"] == "normalized":
                    manifest.discard(loser["image_id"], reason, dup_of=keeper["image_id"])
                    discarded.add(loser["image_id"])
                    stats[reason] += 1
                else:
                    # An already-processed image is never removed retroactively (it may already
                    # be annotated); it only joins the cluster so splits stay leak-free.
                    log.warning("kept %s although it duplicates %s (already processed)",
                                loser["image_id"], keeper["image_id"])
        # Survivors advance; singletons get their own cluster id.
        for r in rows:
            if r["status"] != "normalized" or r["image_id"] in discarded:
                continue
            updates = {"status": "deduped"}
            if not cluster_of.get(r["image_id"]) and not r["cluster_id"]:
                updates["cluster_id"] = r["image_id"]
            manifest.update_image(r["image_id"], **updates)
            stats["deduped"] += 1
    log.info("dedup: %s", stats)
    return stats


# ------------------------------------------------------------------------- semantic clustering
def semantic_clusters(ids: list[str], emb: np.ndarray, threshold: float,
                      existing: dict[str, str] | None = None, block_cells: int = 4_000_000) -> dict[str, str]:
    """Merge images into clusters by embedding cosine >= threshold (and by existing cluster ids).

    Returns image_id -> cluster id (the smallest image_id in the component, deterministic).
    Assumes rows of ``emb`` are L2-normalized.
    """
    n = len(ids)
    uf = UnionFind(n)
    if existing:
        first_seen: dict[str, int] = {}
        for i, image_id in enumerate(ids):
            cid = existing.get(image_id)
            if cid:
                if cid in first_seen:
                    uf.union(first_seen[cid], i)
                else:
                    first_seen[cid] = i
    if n >= 2:
        block = max(1, block_cells // n)
        cols = np.arange(n)
        for a in range(0, n, block):
            b = min(n, a + block)
            sim = emb[a:b] @ emb.T
            ii, jj = np.nonzero((sim >= threshold) & (cols[None, :] > np.arange(a, b)[:, None]))
            for i, j in zip(ii + a, jj):
                uf.union(int(i), int(j))
    comp: dict[int, list[str]] = defaultdict(list)
    for i, image_id in enumerate(ids):
        comp[uf.find(i)].append(image_id)
    return {image_id: min(members) for members in comp.values() for image_id in members}


def run_semantic(manifest: Manifest, cfg: dict) -> dict[str, int]:
    """Layer 3: merge cluster ids using stored CLIP embeddings (labels only, deletes nothing)."""
    rows = manifest.images(statuses=["kept", "review"])
    ids, emb = manifest.load_embeddings([r["image_id"] for r in rows])
    if not ids:
        log.warning("cluster: no embeddings found (run `filter` with CLIP first); skipping")
        return {"clustered": 0, "merged_clusters": 0}
    existing = {r["image_id"]: r["cluster_id"] or r["image_id"] for r in rows}
    norms = np.linalg.norm(emb, axis=1, keepdims=True)
    emb = emb / np.clip(norms, 1e-9, None)
    new_ids = semantic_clusters(ids, emb, float(cfg["dedup"]["semantic_cosine"]), existing)

    remap: dict[str, str] = {}
    for image_id, new in new_ids.items():
        old = existing[image_id]
        if old != new:
            remap[old] = new
    with manifest.transaction():
        # Update *all* rows (incl. discarded duplicates) that carry a merged cluster id.
        for old, new in remap.items():
            manifest.execute("UPDATE images SET cluster_id=? WHERE cluster_id=?", (new, old))
        for image_id, new in new_ids.items():
            if image_id not in remap and existing[image_id] != new:
                manifest.update_image(image_id, cluster_id=new)
    stats = {"clustered": len(ids), "merged_clusters": len(remap)}
    log.info("cluster: %s", stats)
    return stats