Metadata-Version: 2.4
Name: imgcheck
Version: 0.2.1
Summary: Fast perceptual-hash image deduplication, anti-drift clustering, and train/test leakage detection for computer vision datasets
Author-email: Rama Narasimha Kanduri <kramanarasimha1@gmail.com>, CS Hari Krishna <csharikrishna1806@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Rama Narasimha Kanduri & CS Hari Krishna
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
        -------------------------------------------------------------------------------
        
        ACKNOWLEDGEMENT REQUEST (not legally binding, but appreciated)
        
        If you use imgcheck in your research, project, or product, we would really
        appreciate it if you could — if possible — give a small credit in any of
        these ways, whichever feels right to you:
        
          Option 1 — Credit the tool:
              "Dataset auditing was performed using imgcheck
               (https://pypi.org/project/imgcheck)."
        
          Option 2 — Credit the authors:
              "Dataset auditing was performed using imgcheck
               (Rama Narasimha Kanduri & CS Hari Krishna, 2026)."
        
          Option 3 — Credit both:
              "Dataset auditing was performed using imgcheck by
               Rama Narasimha Kanduri & CS Hari Krishna
               (https://pypi.org/project/imgcheck)."
        
        Any acknowledgement — the tool name, the authors, or both — is warmly
        appreciated. Thank you for using imgcheck!
        
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Pillow>=9.0
Requires-Dist: ImageHash>=4.3
Requires-Dist: pandas>=1.5
Requires-Dist: openpyxl>=3.0
Requires-Dist: tqdm>=4.60
Provides-Extra: pdf
Requires-Dist: fpdf2>=2.7; extra == "pdf"
Provides-Extra: fast
Requires-Dist: xxhash>=3.0; extra == "fast"
Provides-Extra: all
Requires-Dist: fpdf2>=2.7; extra == "all"
Requires-Dist: xxhash>=3.0; extra == "all"
Dynamic: license-file

# imgcheck

> Fast perceptual-hash & metric-indexed toolkit for auditing and cleaning image classification datasets — find duplicates, prevent transitive clustering drift, detect train/test leakage, and catch cross-label mislabelling.

[![PyPI version](https://img.shields.io/badge/pypi-v0.2.1-blue.svg)](https://pypi.org/project/imgcheck/)
[![Python](https://img.shields.io/badge/python-3.9+-brightgreen.svg)](https://pypi.org/project/imgcheck/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

---

## What it does

Image classification datasets silently suffer from three data quality problems that hurt model accuracy:

| Problem | What it means | Detect | Remove |
|---|---|---|---|
| **Within-class duplicates** | Same image appears multiple times in one class, inflating dataset size | `imgcheck clean` | `imgcheck clean-inplace` |
| **Train/test leakage** | A test image is a near-duplicate of a train image — model has effectively "seen" it, inflating test accuracy | `imgcheck leakage` | `imgcheck leakage-fix` |
| **Cross-label duplicates** | Same image appears under two *different* class labels — contradictory training signal | `imgcheck cross-label` | `imgcheck cross-label-fix` |

Plus a fast no-hashing sanity check:

| Command | What it gives you |
|---|---|
| `imgcheck stats` | Per-class image counts, resolutions, class imbalance ratio, corrupt files |

---

## Key Features in v0.2.0

- ⚡ **Ultra-Fast Engine:**
  - **31.8x faster** Hamming distance calculation via hardware POPCNT.
  - **122.1x faster** candidate pair search via sub-quadratic Multi-Index Hashing (MIH) with inline verification.
  - **6.9x faster** JPEG decoding using draft DCT downsampling.
- 🧩 **Customizable Block Sizes & Block Hashing:**
  - `--block-size N`: Fine-grained frequency and spatial resolution control (e.g. 16, 32, 64, 128). Controls the pre-DCT transform block in `phash`, wavelet scale in `whash`, and spatial tile resolution in `blockhash`.
  - `blockhash`: First-class Block Mean Hash (BMH) partitioning images into spatial grid tiles for patch-level duplicate auditing.
- 🎯 **Anti-Drift Clustering:** Choice of **Medoid Star-Clustering** (mathematically prevents runaway transitive chaining drift where distinct images get falsely grouped), **Complete Linkage** (cliques), or **Single Linkage** (Union-Find).
- 🏆 **Smart Exemplar Keep Policies:** Choose which duplicate image to keep:
  - `--keep-policy highest_resolution`: Automatically preserves the highest-resolution image (never deletes a 4K raw asset in favor of a 100x100 thumbnail).
  - `--keep-policy sharpest`: Uses 2D discrete Laplacian variance to keep the sharpest, least blurry image.
  - `--keep-policy largest_file_size`: Keeps the highest bitrate / least compressed copy.
  - `--keep-policy medoid`: Keeps the most central, representative sample in each cluster.
- 🔄 **Rotation & Flip Invariance:** `--rotation-invariant` detects duplicates even if rotated ($90^\circ, 180^\circ, 270^\circ$) or horizontally/vertically flipped ($D_4$ dihedral group).
- 💾 **Persistent SQLite Cache:** `--cache` stores fingerprints in `.imgcheck_cache.sqlite` based on file size and mtime. Subsequent runs on unchanged datasets execute in seconds.
- 📏 **Configurable Hash Dimensions:** `--hash-size 8` (64-bit) or `--hash-size 16` (256-bit) for fine-grained medical, microscopy, or satellite imagery.

---

## Performance Benchmarks

Measured on 5,000 images (12,497,500 pair combinations):

| Operation | Legacy Method | `imgcheck v0.2.0` | Speedup |
|---|---|---|---|
| **Hamming Distance (200k pairs)** | `0.3959s` (str diff) | `0.0124s` (hardware popcount) | **31.8x faster** |
| **Duplicate Candidate Search** | `1.1977s` ($O(N^2)$ scan) | `0.0098s` (Multi-Index Hashing) | **122.1x faster** |
| **Parallel Hashing (with decode)** | `0.3944s` (full decode) | `0.0303s` (JPEG draft + workers) | **13.0x faster** |

---

## Installation

```bash
pip install imgcheck
```

### Optional Extras

```bash
# For visual PDF reports (fpdf2)
pip install "imgcheck[pdf]"

# For ultra-fast exact-content hashing (xxhash)
pip install "imgcheck[fast]"

# Complete installation
pip install "imgcheck[all]"
```

---

## Quick-Start CLI Examples

### 1. Fast Dataset Sanity Check (Instant, No Hashing)
```bash
imgcheck stats --dataset dataset/ --report reports/stats.xlsx
```

### 2. Within-Class Duplicate Cleaning
```bash
# Copy clean survivors to a new folder (safe):
imgcheck clean \
    --dataset dataset/ \
    --output  dataset_clean/ \
    --report  reports/duplicates.xlsx \
    --html    reports/duplicates.html \
    --clustering medoid \
    --keep-policy highest_resolution \
    --cache

# Or remove duplicates directly in-place:
imgcheck clean-inplace \
    --dataset dataset/ \
    --report  reports/duplicates_removed.xlsx \
    --clustering medoid \
    --keep-policy sharpest
```

### 3. Detect & Fix Train/Test Leakage
```bash
# Detect (read-only):
imgcheck leakage \
    --train  train/ \
    --test   test/ \
    --report reports/leakage.xlsx \
    --html   reports/leakage.html \
    --cache

# Remove leaked test images:
imgcheck leakage-fix \
    --train   train/ \
    --test    test/ \
    --report  reports/leakage_removed.xlsx \
    --mode    copy \
    --output  test_clean/
```

### 4. Detect & Fix Cross-Label Mislabelling
```bash
# Detect (read-only):
imgcheck cross-label \
    --dataset dataset/ \
    --report  reports/crosslabel.xlsx \
    --html    reports/crosslabel.html

# Remove contradictory copies:
imgcheck cross-label-fix \
    --dataset dataset/ \
    --report  reports/crosslabel_removed.xlsx \
    --mode    inplace
```

---

## Python API

```python
import imgcheck

# 1. Dataset stats
stats = imgcheck.compute_dataset_stats("dataset/", report_path="reports/stats.xlsx")

# 2. Clean duplicates with smart keep policy & medoid anti-drift clustering
duplicate_counts = imgcheck.clean_duplicates(
    dataset_path="dataset/",
    clean_dataset_path="dataset_clean/",
    report_path="reports/duplicates.xlsx",
    threshold=3,
    clustering_method="medoid",
    keep_policy="highest_resolution",
    rotation_invariant=True,
    use_cache=True,
)

# 3. Check train/test leakage
leakage_counts = imgcheck.check_train_test_leakage(
    train_root="train/",
    test_root="test/",
    report_path="reports/leakage.xlsx",
    threshold=3,
    use_cache=True,
)

# 4. Check cross-label duplicates
cross_rows = imgcheck.check_cross_label_duplicates(
    dataset_root="dataset/",
    report_path="reports/crosslabel.xlsx",
    threshold=3,
    use_cache=True,
)

# 5. Granular low-level hashing with custom block size and hash size
hashes = imgcheck.compute_hashes(
    image_paths=["img1.jpg", "img2.jpg"],
    algo="phash",
    hash_size=16,          # 256-bit high-precision hash
    block_size=64,         # 64x64 pre-DCT transform block resolution
    rotation_invariant=True,
    use_cache=True,
)
```

---

## 🛠️ Complete Customization Guide

### 1. Customizing Hash Size (`--hash-size` / `hash_size`)
Controls the output fingerprint resolution:
* **`8` (Default):** $8 \times 8 = 64$ bits. Fast, lightweight, ideal for standard image classification (ImageNet, natural scenes, consumer photos).
* **`16`:** $16 \times 16 = 256$ bits. High-precision fingerprinting. Ideal for specialized domains (MRI/CT scans, microscopy, satellite imagery, industrial defect inspection) where distinct images share similar global illumination and require fine frequency discrimination.
* **`32`:** $32 \times 32 = 1024$ bits. Ultra-high precision for near-identical patent or copyright scans.

```bash
# Clean with 256-bit hash precision:
imgcheck clean --dataset dataset/ --output clean/ --report report.xlsx --hash-size 16 --threshold 8
```

### 2. Customizing Image Block Size (`--block-size` / `block_size`)
Controls the intermediate frequency and spatial resolution before hash compression:
* **In `phash` (DCT Frequency Block):** Sets the image resample dimension before the 2D Discrete Cosine Transform. With `--hash-size 8`, the default is $32 \times 32$. Setting `--block-size 64` or `128` captures subtle high-frequency textures before low-frequency DCT energy extraction.
* **In `whash` (Wavelet Decomposition Scale):** Sets the wavelet decomposition tree scale (`image_scale = block_size`, e.g. `32`, `64`, `128`).
* **In `blockhash` (Spatial Tile Dimension):** Sets the spatial pixel size of each local patch ($4 \times 4$, $8 \times 8$, $16 \times 16$).

```bash
# Capture fine micro-textures with a 64x64 block resolution:
imgcheck clean --dataset dataset/ --output clean/ --report report.xlsx --algo phash --hash-size 8 --block-size 64
```

### 3. Choosing the Right Hash Algorithm (`--algo` / `algo`)
| Algorithm | Underlying Mechanism | Best For |
|---|---|---|
| **`phash`** (Default) | 2D Discrete Cosine Transform (DCT) | General datasets, robust to compression, scaling, slight color shifts |
| **`dhash`** | Directional horizontal/vertical pixel gradients | Edge-heavy images, CAD diagrams, sketches, text/documents |
| **`whash`** | Discrete Wavelet Transform (Haar DWT) | Compression-heavy datasets, noisy textures |
| **`blockhash`** | Spatial Block Mean Luminance (BMH) | Detecting local crops, inserted watermarks, and partial image modifications |
| **`ahash`** | Average global luminance thresholding | Coarse, ultra-fast pre-filtering |

### 4. Customizing Clustering & Preventing Chaining Drift (`--clustering` / `clustering_method`)
Traditional duplicate finders use transitive single-linkage (Union-Find): if A matches B (dist=2) and B matches C (dist=2), A and C are merged. In large datasets, this causes **transitive chaining drift**, where 20 subtly different images merge into one monster cluster and 19 valid images get accidentally deleted!

`imgcheck` gives you full mathematical control:
* **`--clustering medoid` (Recommended):** Star-clustering around medoid exemplars. Guarantees that **every single duplicate inside a cluster is strictly within threshold of the kept exemplar**. Eliminates transitive chaining drift completely.
* **`--clustering complete`:** Maximal clique clustering. Guarantees that **all pairs** within a cluster have distance $\le \text{threshold}$ to each other.
* **`--clustering single`:** Legacy Union-Find. Best when threshold is `0` or `1` for strict identical matching.

```bash
# Guaranteed anti-drift clustering:
imgcheck clean --dataset dataset/ --output clean/ --report report.xlsx --clustering medoid --threshold 3
```

### 5. Customizing Exemplar Selection (`--keep-policy` / `keep_policy`)
When duplicate images are detected, which copy should be preserved in the clean dataset?
* **`--keep-policy highest_resolution`:** Automatically preserves the image with the largest `width * height`. Never accidentally deletes a 4K raw asset in favor of a 100x100 preview thumbnail!
* **`--keep-policy sharpest`:** Computes 2D discrete Laplacian variance across candidates; automatically preserves the sharpest, least blurry image.
* **`--keep-policy largest_file_size`:** Keeps the least compressed, highest-bitrate file.
* **`--keep-policy medoid`:** Keeps the centroid image having the minimal sum of distances to all other cluster members (the most representative exemplar).
* **`--keep-policy first`:** Alphabetical order by file path (legacy default).
* **`--keep-policy newest` / `oldest`:** By file modification timestamp.

```bash
# Always keep the sharpest, highest-resolution survivor:
imgcheck clean --dataset dataset/ --output clean/ --report report.xlsx --keep-policy highest_resolution
```

### 6. Rotation & Flip Invariance (`--rotation-invariant`)
In machine learning datasets, data augmentation often produces flipped or rotated variants that leak across train and test sets.
* Enabling `--rotation-invariant` calculates the canonical minimal fingerprint across all 8 dihedral transformations ($D_4$ group: $0^\circ, 90^\circ, 180^\circ, 270^\circ$ and horizontal/vertical flips).

```bash
imgcheck leakage --train train/ --test test/ --report leakage.xlsx --rotation-invariant
```

### 7. Persistent Cache for Instant Re-Runs (`--cache`)
* Enabling `--cache` creates a local `.imgcheck_cache.sqlite` database storing fingerprints keyed by file path, size, modification time, hash algorithm, and block parameters.
* Re-auditing 100,000 images with different thresholds or keep policies completes in seconds instead of hours.

```bash
imgcheck clean --dataset dataset/ --output clean/ --report report.xlsx --cache
```

---

## CLI Options Reference

| Flag | Default | Description |
|---|---|---|
| `--threshold N` | `3` | Max Hamming distance to count as a match (`0`=exact only, `1–3`=near-duplicates) |
| `--algo NAME` | `phash` | Hash algorithm: `phash` (default), `dhash`, `ahash`, `whash`, `blockhash` |
| `--hash-size N` | `8` | Grid size: `8` for 64-bit, `16` for 256-bit |
| `--block-size N` | `None` | Transform block size (e.g. 16, 32, 64, 128) for frequency control in phash/whash and spatial patch size in blockhash |
| `--clustering METHOD` | `single` | Clustering strategy: `medoid` (star-clustering, prevents chaining drift), `complete` (cliques), or `single` (Union-Find) |
| `--keep-policy POLICY` | `first` | Which image to keep: `highest_resolution`, `sharpest`, `largest_file_size`, `medoid`, `first`, `newest`, `oldest` |
| `--rotation-invariant` | `False` | Detects rotated (90/180/270 deg) or flipped duplicates |
| `--cache` | `False` | Enables persistent SQLite caching (`.imgcheck_cache.sqlite`) for instant repeat runs |
| `--workers N` | `auto` | Number of worker threads for parallel image decoding |
| `--html PATH` | `None` | Exports self-contained interactive visual HTML gallery |
| `--pdf PATH` | `None` | Exports visual PDF report (requires `pip install imgcheck[pdf]`) |
| `--formats LIST` | `None` | Comma-separated extra export formats (e.g. `csv,json`) |

---

## Authors

**Rama Narasimha Kanduri**  
kramanarasimha1@gmail.com

**CS Hari Krishna**  
csharikrishna1806@gmail.com

---

## License

MIT License. See [LICENSE](LICENSE) for details.
