"""Perceptual-hash de-duplication (pHash).""" from __future__ import annotations import json from pathlib import Path from typing import Any, Optional import imagehash from PIL import Image def phash_path(path: Path, hash_size: int = 16) -> Optional[imagehash.ImageHash]: try: with Image.open(path) as im: im = im.convert("RGB") return imagehash.phash(im, hash_size=hash_size) except Exception: return None def hamming(a: imagehash.ImageHash, b: imagehash.ImageHash) -> int: return int(a - b) def cluster_duplicates( records: list[dict[str, Any]], image_key: str, hash_size: int, max_dist: int = 6, ) -> tuple[list[dict[str, Any]], list[str]]: """ Greedy clustering: first occurrence is canonical; later near-duplicates get duplicate_of set. Returns (updated_records, log_lines). """ canonicals: list[tuple[str, imagehash.ImageHash]] = [] logs: list[str] = [] for row in records: p = Path(row[image_key]) h = phash_path(p, hash_size=hash_size) if h is None: row["dedup_status"] = "hash_fail" continue row["phash"] = str(h) rid = str(row["id"]) dup_of: Optional[str] = None for cid, ch in canonicals: if hamming(h, ch) <= max_dist: dup_of = cid break if dup_of is None: canonicals.append((rid, h)) row["dedup_status"] = "canonical" row["duplicate_of"] = None else: row["dedup_status"] = "duplicate" row["duplicate_of"] = dup_of logs.append(f"duplicate {rid} -> {dup_of}") return records, logs def load_jsonl(path: Path) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] if not path.is_file(): return rows with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue rows.append(json.loads(line)) return rows def save_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with open(path, "w", encoding="utf-8") as f: for r in rows: f.write(json.dumps(r, ensure_ascii=False) + "\n")