cv-data-audit 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cv_data_audit-0.2.0/LICENSE +21 -0
- cv_data_audit-0.2.0/PKG-INFO +97 -0
- cv_data_audit-0.2.0/README.md +81 -0
- cv_data_audit-0.2.0/cv_data_audit/__init__.py +0 -0
- cv_data_audit-0.2.0/cv_data_audit/cli.py +61 -0
- cv_data_audit-0.2.0/cv_data_audit/detectors.py +64 -0
- cv_data_audit-0.2.0/cv_data_audit/scanner.py +17 -0
- cv_data_audit-0.2.0/cv_data_audit.egg-info/PKG-INFO +97 -0
- cv_data_audit-0.2.0/cv_data_audit.egg-info/SOURCES.txt +13 -0
- cv_data_audit-0.2.0/cv_data_audit.egg-info/dependency_links.txt +1 -0
- cv_data_audit-0.2.0/cv_data_audit.egg-info/entry_points.txt +2 -0
- cv_data_audit-0.2.0/cv_data_audit.egg-info/requires.txt +6 -0
- cv_data_audit-0.2.0/cv_data_audit.egg-info/top_level.txt +1 -0
- cv_data_audit-0.2.0/pyproject.toml +25 -0
- cv_data_audit-0.2.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 VartikaRaj2512
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cv-data-audit
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Zero-config pre-flight scanner for Computer Vision dataset leakage and shortcut learning.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: opencv-python-headless>=4.8.0
|
|
10
|
+
Requires-Dist: numpy>=1.24.0
|
|
11
|
+
Requires-Dist: scikit-learn>=1.3.0
|
|
12
|
+
Requires-Dist: Pillow>=10.0.0
|
|
13
|
+
Requires-Dist: rich>=13.0.0
|
|
14
|
+
Requires-Dist: typer>=0.9.0
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# cv-data-audit
|
|
18
|
+
|
|
19
|
+
[](https://www.python.org/downloads/)
|
|
20
|
+
[](https://opencv.org/)
|
|
21
|
+
[](https://opensource.org/licenses/MIT)
|
|
22
|
+
|
|
23
|
+
**Zero-config pre-flight scanner for Computer Vision dataset leakage and "Clever Hans" shortcut learning.**
|
|
24
|
+
|
|
25
|
+
Models frequently hit 99% validation accuracy during training only to fail in production because of subtle dataset flaws—such as burst-mode photos split across `train`/`val`, hospital watermarks hidden in image borders, or class-specific camera EXIF signatures. `cv-data-audit` catches these silent bugs on your CPU in seconds **before** you burn GPU hours training.
|
|
26
|
+
|
|
27
|
+

|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Features & What It Catches
|
|
32
|
+
|
|
33
|
+
| Audit Check | How It Works | Real-World Failure Prevented |
|
|
34
|
+
| :--- | :--- | :--- |
|
|
35
|
+
| **1. Cross-Split Near-Duplicates** | Computes 64-bit difference hashes (**dHash**) across all images and flags pairs across different splits (`train` vs. `val`/`test`) within a configurable Hamming distance. | Burst-mode frames, slightly cropped photos, or re-compressed JPEGs leaking between training and validation sets. |
|
|
36
|
+
| **2. Outer 5% Border Shortcut Probe** | Masks out the center 90% of every image, extracts 16-bin RGB histograms from only the outer 5% border pixels, and runs cross-validated Logistic Regression. | **"Clever Hans" learning**—where models cheat by memorizing background frames, scanner borders, or corner watermarks instead of the object. |
|
|
37
|
+
| **3. EXIF & Dimension Fingerprints** | Audits image `(Width, Height)` tuples and EXIF camera model tags (`0x0110`) per class to detect disjoint distributions. | Models memorizing image resolution or camera sensor noise because positive and negative classes were collected from different sources. |
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Quickstart
|
|
42
|
+
|
|
43
|
+
### Installation
|
|
44
|
+
```bash
|
|
45
|
+
git clone https://github.com/VartikaRaj2512/cv-data-audit.git
|
|
46
|
+
cd cv-data-audit
|
|
47
|
+
pip install -e .
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Run an Audit
|
|
51
|
+
Point `cv-data-audit` at any standard ImageFolder dataset directory:
|
|
52
|
+
```bash
|
|
53
|
+
cv-data-audit ./my_dataset
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### CLI Options
|
|
57
|
+
```bash
|
|
58
|
+
# Adjust near-duplicate sensitivity (default: 4; lower = stricter, higher = catches heavier crops/edits)
|
|
59
|
+
cv-data-audit ./my_dataset --hash-threshold 6
|
|
60
|
+
|
|
61
|
+
# Automatically quarantine leaked validation/test duplicates into _quarantine/
|
|
62
|
+
cv-data-audit ./my_dataset --dedupe
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Expected Dataset Structure
|
|
68
|
+
|
|
69
|
+
Works out-of-the-box with standard `split/class/image` directory layouts (`.jpg`, `.jpeg`, `.png`, `.bmp`, `.webp`, `.tiff`):
|
|
70
|
+
|
|
71
|
+
```text
|
|
72
|
+
my_dataset/
|
|
73
|
+
├── train/
|
|
74
|
+
│ ├── class_a/
|
|
75
|
+
│ │ ├── img_001.jpg
|
|
76
|
+
│ │ └── img_002.jpg
|
|
77
|
+
│ └── class_b/
|
|
78
|
+
│ └── img_003.jpg
|
|
79
|
+
└── val/
|
|
80
|
+
├── class_a/
|
|
81
|
+
└── class_b/
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## Roadmap
|
|
87
|
+
|
|
88
|
+
- [x] `--dedupe` flag to automatically quarantine leaked validation duplicates
|
|
89
|
+
- [ ] PyTorch `Dataset` & Hugging Face `datasets` in-memory audit wrappers
|
|
90
|
+
- [ ] Exportable HTML visual diff report highlighting border shortcut heatmaps
|
|
91
|
+
- [ ] FAISS indexing for sub-second duplicate detection on 100k+ image datasets
|
|
92
|
+
|
|
93
|
+
## Contributing
|
|
94
|
+
|
|
95
|
+
Contributions, bug reports, and feature requests are welcome! Feel free to open an issue or submit a pull request.
|
|
96
|
+
|
|
97
|
+
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# cv-data-audit
|
|
2
|
+
|
|
3
|
+
[](https://www.python.org/downloads/)
|
|
4
|
+
[](https://opencv.org/)
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
6
|
+
|
|
7
|
+
**Zero-config pre-flight scanner for Computer Vision dataset leakage and "Clever Hans" shortcut learning.**
|
|
8
|
+
|
|
9
|
+
Models frequently hit 99% validation accuracy during training only to fail in production because of subtle dataset flaws—such as burst-mode photos split across `train`/`val`, hospital watermarks hidden in image borders, or class-specific camera EXIF signatures. `cv-data-audit` catches these silent bugs on your CPU in seconds **before** you burn GPU hours training.
|
|
10
|
+
|
|
11
|
+

|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## Features & What It Catches
|
|
16
|
+
|
|
17
|
+
| Audit Check | How It Works | Real-World Failure Prevented |
|
|
18
|
+
| :--- | :--- | :--- |
|
|
19
|
+
| **1. Cross-Split Near-Duplicates** | Computes 64-bit difference hashes (**dHash**) across all images and flags pairs across different splits (`train` vs. `val`/`test`) within a configurable Hamming distance. | Burst-mode frames, slightly cropped photos, or re-compressed JPEGs leaking between training and validation sets. |
|
|
20
|
+
| **2. Outer 5% Border Shortcut Probe** | Masks out the center 90% of every image, extracts 16-bin RGB histograms from only the outer 5% border pixels, and runs cross-validated Logistic Regression. | **"Clever Hans" learning**—where models cheat by memorizing background frames, scanner borders, or corner watermarks instead of the object. |
|
|
21
|
+
| **3. EXIF & Dimension Fingerprints** | Audits image `(Width, Height)` tuples and EXIF camera model tags (`0x0110`) per class to detect disjoint distributions. | Models memorizing image resolution or camera sensor noise because positive and negative classes were collected from different sources. |
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Quickstart
|
|
26
|
+
|
|
27
|
+
### Installation
|
|
28
|
+
```bash
|
|
29
|
+
git clone https://github.com/VartikaRaj2512/cv-data-audit.git
|
|
30
|
+
cd cv-data-audit
|
|
31
|
+
pip install -e .
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Run an Audit
|
|
35
|
+
Point `cv-data-audit` at any standard ImageFolder dataset directory:
|
|
36
|
+
```bash
|
|
37
|
+
cv-data-audit ./my_dataset
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### CLI Options
|
|
41
|
+
```bash
|
|
42
|
+
# Adjust near-duplicate sensitivity (default: 4; lower = stricter, higher = catches heavier crops/edits)
|
|
43
|
+
cv-data-audit ./my_dataset --hash-threshold 6
|
|
44
|
+
|
|
45
|
+
# Automatically quarantine leaked validation/test duplicates into _quarantine/
|
|
46
|
+
cv-data-audit ./my_dataset --dedupe
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Expected Dataset Structure
|
|
52
|
+
|
|
53
|
+
Works out-of-the-box with standard `split/class/image` directory layouts (`.jpg`, `.jpeg`, `.png`, `.bmp`, `.webp`, `.tiff`):
|
|
54
|
+
|
|
55
|
+
```text
|
|
56
|
+
my_dataset/
|
|
57
|
+
├── train/
|
|
58
|
+
│ ├── class_a/
|
|
59
|
+
│ │ ├── img_001.jpg
|
|
60
|
+
│ │ └── img_002.jpg
|
|
61
|
+
│ └── class_b/
|
|
62
|
+
│ └── img_003.jpg
|
|
63
|
+
└── val/
|
|
64
|
+
├── class_a/
|
|
65
|
+
└── class_b/
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## Roadmap
|
|
71
|
+
|
|
72
|
+
- [x] `--dedupe` flag to automatically quarantine leaked validation duplicates
|
|
73
|
+
- [ ] PyTorch `Dataset` & Hugging Face `datasets` in-memory audit wrappers
|
|
74
|
+
- [ ] Exportable HTML visual diff report highlighting border shortcut heatmaps
|
|
75
|
+
- [ ] FAISS indexing for sub-second duplicate detection on 100k+ image datasets
|
|
76
|
+
|
|
77
|
+
## Contributing
|
|
78
|
+
|
|
79
|
+
Contributions, bug reports, and feature requests are welcome! Feel free to open an issue or submit a pull request.
|
|
80
|
+
|
|
81
|
+
|
|
File without changes
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import shutil
|
|
2
|
+
import typer
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from rich.console import Console
|
|
5
|
+
from rich.table import Table
|
|
6
|
+
from rich.panel import Panel
|
|
7
|
+
from .scanner import crawl_dataset
|
|
8
|
+
from .detectors import detect_cross_split_duplicates, detect_border_shortcut, detect_metadata_leaks
|
|
9
|
+
|
|
10
|
+
app = typer.Typer(help="Pre-flight dataset leakage & shortcut hunter for Computer Vision.")
|
|
11
|
+
console = Console()
|
|
12
|
+
|
|
13
|
+
@app.command()
|
|
14
|
+
def scan(
|
|
15
|
+
dataset_dir: Path = typer.Argument(..., exists=True),
|
|
16
|
+
hash_threshold: int = typer.Option(4, help="Max Hamming distance for near-duplicates"),
|
|
17
|
+
dedupe: bool = typer.Option(False, "--dedupe", help="Move leaked val/test duplicates to _quarantine/"),
|
|
18
|
+
):
|
|
19
|
+
console.print(Panel.fit(f"[bold cyan]cv-data-audit[/bold cyan] scanning [yellow]{dataset_dir}[/yellow]"))
|
|
20
|
+
records = crawl_dataset(dataset_dir)
|
|
21
|
+
if not records:
|
|
22
|
+
console.print("[bold red]No images found![/bold red] Expected structure: dataset/split/class/img.jpg")
|
|
23
|
+
raise typer.Exit(code=1)
|
|
24
|
+
splits, classes = set(r.split for r in records), set(r.label for r in records)
|
|
25
|
+
console.print(f"Found [bold]{len(records)}[/bold] images across splits [cyan]{splits}[/cyan] and classes [green]{classes}[/green]\n")
|
|
26
|
+
with console.status("[bold green]Auditing dataset..."):
|
|
27
|
+
dups = detect_cross_split_duplicates(records, max_dist=hash_threshold)
|
|
28
|
+
border_res = detect_border_shortcut(records)
|
|
29
|
+
meta_warnings = detect_metadata_leaks(records)
|
|
30
|
+
table = Table(title="Pre-Flight Audit Results", show_header=True, header_style="bold magenta")
|
|
31
|
+
table.add_column("Check", style="bold")
|
|
32
|
+
table.add_column("Finding")
|
|
33
|
+
table.add_column("Risk Level")
|
|
34
|
+
table.add_row("Cross-Split Near-Duplicates", f"{len(dups)} leaked pairs found across splits", "[bold red]HIGH[/bold red]" if dups else "[bold green]PASS[/bold green]")
|
|
35
|
+
if border_res["status"] == "ok":
|
|
36
|
+
b_risk = "[bold red]HIGH[/bold red]" if border_res["leak_severity"] == "HIGH" else "[bold green]PASS[/bold green]"
|
|
37
|
+
b_acc, base_acc = border_res["border_only_accuracy"], border_res["baseline_accuracy"]
|
|
38
|
+
b_msg = f"Border-only accuracy: {b_acc}% (Baseline: {base_acc}%)"
|
|
39
|
+
else:
|
|
40
|
+
b_risk, b_msg = "[yellow]SKIPPED[/yellow]", border_res["reason"]
|
|
41
|
+
table.add_row("Outer 5% Border Shortcut", b_msg, b_risk)
|
|
42
|
+
table.add_row("EXIF & Dimension Fingerprints", "; ".join(meta_warnings) if meta_warnings else "No resolution or EXIF camera leaks detected", "[bold red]HIGH[/bold red]" if meta_warnings else "[bold green]PASS[/bold green]")
|
|
43
|
+
console.print(table)
|
|
44
|
+
if dups:
|
|
45
|
+
console.print("\n[bold red]Top Cross-Split Leaks:[/bold red]")
|
|
46
|
+
for item in dups[:5]:
|
|
47
|
+
sa, fa, sb, fb, dist = item["split_a"], item["file_a"], item["split_b"], item["file_b"], item["distance"]
|
|
48
|
+
console.print(f" - [{sa}] {fa} <--> [{sb}] {fb} (dist={dist})")
|
|
49
|
+
if dedupe:
|
|
50
|
+
q_dir = dataset_dir / "_quarantine"
|
|
51
|
+
q_dir.mkdir(exist_ok=True)
|
|
52
|
+
moved = 0
|
|
53
|
+
for item in dups:
|
|
54
|
+
target = Path(item["file_a"]) if item["split_b"] == "train" else Path(item["file_b"])
|
|
55
|
+
if target.exists():
|
|
56
|
+
shutil.move(str(target), str(q_dir / target.name))
|
|
57
|
+
moved += 1
|
|
58
|
+
console.print(f"\n[bold yellow]Quarantined {moved} leaked duplicate(s) to {q_dir}[/bold yellow]")
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
app()
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import cv2, numpy as np
|
|
2
|
+
from PIL import Image
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from sklearn.linear_model import LogisticRegression
|
|
5
|
+
from sklearn.model_selection import cross_val_score
|
|
6
|
+
from typing import List, Dict, Any
|
|
7
|
+
from .scanner import ImageRecord
|
|
8
|
+
|
|
9
|
+
def compute_dhash(img_gray, hash_size=8):
|
|
10
|
+
resized = cv2.resize(img_gray, (hash_size + 1, hash_size), interpolation=cv2.INTER_AREA)
|
|
11
|
+
diff = resized[:, 1:] > resized[:, :-1]
|
|
12
|
+
return sum([2 ** i for (i, v) in enumerate(diff.flatten()) if v])
|
|
13
|
+
|
|
14
|
+
def hamming_distance(h1, h2):
|
|
15
|
+
return bin(h1 ^ h2).count("1")
|
|
16
|
+
|
|
17
|
+
def detect_cross_split_duplicates(records: List[ImageRecord], max_dist: int = 4) -> List[Dict[str, Any]]:
|
|
18
|
+
hashes = [(rec, compute_dhash(cv2.imread(str(rec.path), cv2.IMREAD_GRAYSCALE))) for rec in records if cv2.imread(str(rec.path), cv2.IMREAD_GRAYSCALE) is not None]
|
|
19
|
+
leaks = []
|
|
20
|
+
for i in range(len(hashes)):
|
|
21
|
+
rec_a, h_a = hashes[i]
|
|
22
|
+
for j in range(i + 1, len(hashes)):
|
|
23
|
+
rec_b, h_b = hashes[j]
|
|
24
|
+
if rec_a.split != rec_b.split:
|
|
25
|
+
dist = hamming_distance(h_a, h_b)
|
|
26
|
+
if dist <= max_dist:
|
|
27
|
+
leaks.append({"file_a": str(rec_a.path), "split_a": rec_a.split, "file_b": str(rec_b.path), "split_b": rec_b.split, "distance": dist})
|
|
28
|
+
return leaks
|
|
29
|
+
|
|
30
|
+
def detect_border_shortcut(records: List[ImageRecord], border_pct: float = 0.05) -> Dict[str, Any]:
|
|
31
|
+
X_border, y = [], []
|
|
32
|
+
for rec in records:
|
|
33
|
+
img = cv2.imread(str(rec.path))
|
|
34
|
+
if img is None: continue
|
|
35
|
+
img = cv2.resize(img, (128, 128))
|
|
36
|
+
h, w, _ = img.shape
|
|
37
|
+
bh, bw = max(1, int(h * border_pct)), max(1, int(w * border_pct))
|
|
38
|
+
border_pixels = np.vstack([img[:bh, :].reshape(-1, 3), img[-bh:, :].reshape(-1, 3), img[bh:-bh, :bw].reshape(-1, 3), img[bh:-bh, -bw:].reshape(-1, 3)])
|
|
39
|
+
hist_features = [val for c in range(3) for val in np.histogram(border_pixels[:, c], bins=16, range=(0, 256), density=True)[0]]
|
|
40
|
+
X_border.append(hist_features)
|
|
41
|
+
y.append(rec.label)
|
|
42
|
+
X_border, y = np.array(X_border), np.array(y)
|
|
43
|
+
unique_classes, counts = np.unique(y, return_counts=True)
|
|
44
|
+
if len(unique_classes) < 2 or min(counts) < 5:
|
|
45
|
+
return {"status": "skipped", "reason": "Insufficient samples per class"}
|
|
46
|
+
baseline_acc = max(counts) / len(y)
|
|
47
|
+
border_acc = float(np.mean(cross_val_score(LogisticRegression(max_iter=500), X_border, y, cv=min(5, min(counts)))))
|
|
48
|
+
return {"status": "ok", "baseline_accuracy": round(baseline_acc * 100, 2), "border_only_accuracy": round(border_acc * 100, 2), "leak_severity": "HIGH" if (border_acc - baseline_acc) > 0.15 else "LOW"}
|
|
49
|
+
|
|
50
|
+
def detect_metadata_leaks(records: List[ImageRecord]) -> List[str]:
|
|
51
|
+
dim_by_class, camera_by_class = defaultdict(set), defaultdict(set)
|
|
52
|
+
for rec in records:
|
|
53
|
+
try:
|
|
54
|
+
with Image.open(rec.path) as im:
|
|
55
|
+
dim_by_class[rec.label].add(im.size)
|
|
56
|
+
exif = im.getexif()
|
|
57
|
+
if exif and exif.get(272): camera_by_class[rec.label].add(str(exif.get(272)).strip())
|
|
58
|
+
except Exception: continue
|
|
59
|
+
warnings = []
|
|
60
|
+
if len(dim_by_class) >= 2 and not set.intersection(*(dim_by_class[c] for c in dim_by_class)):
|
|
61
|
+
warnings.append("Disjoint image resolutions detected: Every class has unique (W, H) dimensions!")
|
|
62
|
+
if len(camera_by_class) >= 2 and not set.intersection(*(camera_by_class[c] for c in camera_by_class)):
|
|
63
|
+
warnings.append("EXIF Camera Model leak: Different classes were shot on completely different cameras!")
|
|
64
|
+
return warnings
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import List
|
|
4
|
+
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tiff"}
|
|
5
|
+
@dataclass
|
|
6
|
+
class ImageRecord:
|
|
7
|
+
path: Path
|
|
8
|
+
split: str
|
|
9
|
+
label: str
|
|
10
|
+
def crawl_dataset(root_dir: Path) -> List[ImageRecord]:
|
|
11
|
+
records = []
|
|
12
|
+
for path in root_dir.rglob("*"):
|
|
13
|
+
if path.suffix.lower() in IMAGE_EXTS and path.is_file():
|
|
14
|
+
rel_parts = path.relative_to(root_dir).parts
|
|
15
|
+
if len(rel_parts) >= 3:
|
|
16
|
+
records.append(ImageRecord(path=path, split=rel_parts[0], label=rel_parts[1]))
|
|
17
|
+
return records
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cv-data-audit
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Zero-config pre-flight scanner for Computer Vision dataset leakage and shortcut learning.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: opencv-python-headless>=4.8.0
|
|
10
|
+
Requires-Dist: numpy>=1.24.0
|
|
11
|
+
Requires-Dist: scikit-learn>=1.3.0
|
|
12
|
+
Requires-Dist: Pillow>=10.0.0
|
|
13
|
+
Requires-Dist: rich>=13.0.0
|
|
14
|
+
Requires-Dist: typer>=0.9.0
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# cv-data-audit
|
|
18
|
+
|
|
19
|
+
[](https://www.python.org/downloads/)
|
|
20
|
+
[](https://opencv.org/)
|
|
21
|
+
[](https://opensource.org/licenses/MIT)
|
|
22
|
+
|
|
23
|
+
**Zero-config pre-flight scanner for Computer Vision dataset leakage and "Clever Hans" shortcut learning.**
|
|
24
|
+
|
|
25
|
+
Models frequently hit 99% validation accuracy during training only to fail in production because of subtle dataset flaws—such as burst-mode photos split across `train`/`val`, hospital watermarks hidden in image borders, or class-specific camera EXIF signatures. `cv-data-audit` catches these silent bugs on your CPU in seconds **before** you burn GPU hours training.
|
|
26
|
+
|
|
27
|
+

|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Features & What It Catches
|
|
32
|
+
|
|
33
|
+
| Audit Check | How It Works | Real-World Failure Prevented |
|
|
34
|
+
| :--- | :--- | :--- |
|
|
35
|
+
| **1. Cross-Split Near-Duplicates** | Computes 64-bit difference hashes (**dHash**) across all images and flags pairs across different splits (`train` vs. `val`/`test`) within a configurable Hamming distance. | Burst-mode frames, slightly cropped photos, or re-compressed JPEGs leaking between training and validation sets. |
|
|
36
|
+
| **2. Outer 5% Border Shortcut Probe** | Masks out the center 90% of every image, extracts 16-bin RGB histograms from only the outer 5% border pixels, and runs cross-validated Logistic Regression. | **"Clever Hans" learning**—where models cheat by memorizing background frames, scanner borders, or corner watermarks instead of the object. |
|
|
37
|
+
| **3. EXIF & Dimension Fingerprints** | Audits image `(Width, Height)` tuples and EXIF camera model tags (`0x0110`) per class to detect disjoint distributions. | Models memorizing image resolution or camera sensor noise because positive and negative classes were collected from different sources. |
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Quickstart
|
|
42
|
+
|
|
43
|
+
### Installation
|
|
44
|
+
```bash
|
|
45
|
+
git clone https://github.com/VartikaRaj2512/cv-data-audit.git
|
|
46
|
+
cd cv-data-audit
|
|
47
|
+
pip install -e .
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Run an Audit
|
|
51
|
+
Point `cv-data-audit` at any standard ImageFolder dataset directory:
|
|
52
|
+
```bash
|
|
53
|
+
cv-data-audit ./my_dataset
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### CLI Options
|
|
57
|
+
```bash
|
|
58
|
+
# Adjust near-duplicate sensitivity (default: 4; lower = stricter, higher = catches heavier crops/edits)
|
|
59
|
+
cv-data-audit ./my_dataset --hash-threshold 6
|
|
60
|
+
|
|
61
|
+
# Automatically quarantine leaked validation/test duplicates into _quarantine/
|
|
62
|
+
cv-data-audit ./my_dataset --dedupe
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Expected Dataset Structure
|
|
68
|
+
|
|
69
|
+
Works out-of-the-box with standard `split/class/image` directory layouts (`.jpg`, `.jpeg`, `.png`, `.bmp`, `.webp`, `.tiff`):
|
|
70
|
+
|
|
71
|
+
```text
|
|
72
|
+
my_dataset/
|
|
73
|
+
├── train/
|
|
74
|
+
│ ├── class_a/
|
|
75
|
+
│ │ ├── img_001.jpg
|
|
76
|
+
│ │ └── img_002.jpg
|
|
77
|
+
│ └── class_b/
|
|
78
|
+
│ └── img_003.jpg
|
|
79
|
+
└── val/
|
|
80
|
+
├── class_a/
|
|
81
|
+
└── class_b/
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## Roadmap
|
|
87
|
+
|
|
88
|
+
- [x] `--dedupe` flag to automatically quarantine leaked validation duplicates
|
|
89
|
+
- [ ] PyTorch `Dataset` & Hugging Face `datasets` in-memory audit wrappers
|
|
90
|
+
- [ ] Exportable HTML visual diff report highlighting border shortcut heatmaps
|
|
91
|
+
- [ ] FAISS indexing for sub-second duplicate detection on 100k+ image datasets
|
|
92
|
+
|
|
93
|
+
## Contributing
|
|
94
|
+
|
|
95
|
+
Contributions, bug reports, and feature requests are welcome! Feel free to open an issue or submit a pull request.
|
|
96
|
+
|
|
97
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
cv_data_audit/__init__.py
|
|
5
|
+
cv_data_audit/cli.py
|
|
6
|
+
cv_data_audit/detectors.py
|
|
7
|
+
cv_data_audit/scanner.py
|
|
8
|
+
cv_data_audit.egg-info/PKG-INFO
|
|
9
|
+
cv_data_audit.egg-info/SOURCES.txt
|
|
10
|
+
cv_data_audit.egg-info/dependency_links.txt
|
|
11
|
+
cv_data_audit.egg-info/entry_points.txt
|
|
12
|
+
cv_data_audit.egg-info/requires.txt
|
|
13
|
+
cv_data_audit.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cv_data_audit
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cv-data-audit"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Zero-config pre-flight scanner for Computer Vision dataset leakage and shortcut learning."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"opencv-python-headless>=4.8.0",
|
|
14
|
+
"numpy>=1.24.0",
|
|
15
|
+
"scikit-learn>=1.3.0",
|
|
16
|
+
"Pillow>=10.0.0",
|
|
17
|
+
"rich>=13.0.0",
|
|
18
|
+
"typer>=0.9.0",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
cv-data-audit = "cv_data_audit.cli:app"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
include = ["cv_data_audit*"]
|