File size: 13,831 Bytes
33c93f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#!/usr/bin/env python3
"""Reproducible EDA for the unlabeled image-to-image retrieval dataset."""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
import sys
import tempfile
from collections import Counter, defaultdict
from pathlib import Path

import cv2
os.environ.setdefault("MPLCONFIGDIR", str(Path(tempfile.gettempdir()) / "matplotlib-cache"))
import matplotlib
import numpy as np
import pandas as pd
from PIL import Image, ImageDraw, ImageOps

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402


MANIFESTS = {
    "train": "train_unlabeled.json",
    "gallery": "public_test/public_test/gallery.json",
    "query": "public_test/public_test/queries.json",
}
PLOT_METRICS = [
    "luminance_mean",
    "luminance_std",
    "blur_laplacian_var",
    "entropy",
    "high_frequency_energy",
    "near_black_ratio",
    "edge_density",
]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-root", type=Path, default=Path("data/dataset2"))
    parser.add_argument("--output-dir", type=Path, default=Path("eda_output"))
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--grid-size", type=int, default=48)
    return parser.parse_args()


def load_manifest(path: Path) -> list[dict[str, str]]:
    with path.open(encoding="utf-8") as handle:
        rows = json.load(handle)
    if not isinstance(rows, list):
        raise ValueError("manifest root must be a JSON list")
    for index, row in enumerate(rows):
        if not isinstance(row, dict) or not isinstance(row.get("image_id"), str) or not isinstance(row.get("image_path"), str):
            raise ValueError(f"row {index} must contain string image_id and image_path")
    return rows


def resolve_image(data_root: Path, manifest: Path, relative: str) -> Path:
    rel = Path(relative)
    candidates = [
        data_root / rel,
        manifest.parent / rel,
        manifest.parent.parent / rel,
    ]
    for candidate in candidates:
        if candidate.is_file():
            return candidate.resolve()
    return candidates[0].resolve()


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def image_metrics(rgb: np.ndarray) -> dict[str, float]:
    gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
    histogram = np.bincount(gray.ravel(), minlength=256).astype(np.float64)
    probabilities = histogram[histogram > 0] / gray.size
    blurred = cv2.GaussianBlur(gray, (0, 0), 1.0)
    edges = cv2.Canny(gray, 50, 150)
    return {
        "luminance_mean": float(gray.mean()),
        "luminance_std": float(gray.std()),
        "red_mean": float(rgb[..., 0].mean()),
        "red_std": float(rgb[..., 0].std()),
        "green_mean": float(rgb[..., 1].mean()),
        "green_std": float(rgb[..., 1].std()),
        "blue_mean": float(rgb[..., 2].mean()),
        "blue_std": float(rgb[..., 2].std()),
        "blur_laplacian_var": float(cv2.Laplacian(gray, cv2.CV_64F).var()),
        "entropy": float(-(probabilities * np.log2(probabilities)).sum()),
        "high_frequency_energy": float(np.mean(np.abs(gray.astype(np.float32) - blurred.astype(np.float32)))),
        "near_black_ratio": float(np.mean(np.all(rgb < 10, axis=2))),
        "edge_density": float(np.mean(edges > 0)),
    }


def inspect_dataset(data_root: Path) -> tuple[pd.DataFrame, dict, list[str]]:
    records: list[dict] = []
    integrity: dict = {"splits": {}, "hash_groups": {}}
    problems: list[str] = []
    hashes: defaultdict[str, list[str]] = defaultdict(list)

    for split, relative_manifest in MANIFESTS.items():
        manifest = data_root / relative_manifest
        rows = load_manifest(manifest)
        ids = [row["image_id"] for row in rows]
        paths = [row["image_path"] for row in rows]
        split_info = {
            "rows": len(rows),
            "unique_ids": len(set(ids)),
            "unique_manifest_paths": len(set(paths)),
            "duplicate_ids": sorted(key for key, count in Counter(ids).items() if count > 1),
            "duplicate_manifest_paths": sorted(key for key, count in Counter(paths).items() if count > 1),
            "missing": [],
            "broken": [],
        }
        integrity["splits"][split] = split_info

        for row in rows:
            path = resolve_image(data_root, manifest, row["image_path"])
            if not path.is_file():
                split_info["missing"].append(str(path))
                problems.append(f"missing: {path}")
                continue
            try:
                with Image.open(path) as image:
                    image.load()
                    mode, image_format, size = image.mode, image.format, image.size
                    rgb = np.asarray(image.convert("RGB"))
                digest = sha256(path)
                hashes[digest].append(f"{split}:{row['image_id']}")
                records.append(
                    {
                        "split": split,
                        "image_id": row["image_id"],
                        "manifest_path": row["image_path"],
                        "resolved_path": str(path),
                        "sha256": digest,
                        "format": image_format,
                        "mode": mode,
                        "width": size[0],
                        "height": size[1],
                        "file_size_bytes": path.stat().st_size,
                        **image_metrics(rgb),
                    }
                )
            except Exception as exc:  # report corrupt/unsupported images and continue
                message = f"{path}: {type(exc).__name__}: {exc}"
                split_info["broken"].append(message)
                problems.append(f"broken: {message}")

        if split_info["duplicate_ids"]:
            problems.append(f"{split}: duplicate image_id values")
        if split_info["duplicate_manifest_paths"]:
            problems.append(f"{split}: duplicate image_path values")

    integrity["hash_groups"] = {digest: items for digest, items in hashes.items() if len(items) > 1}
    return pd.DataFrame(records), integrity, problems


def create_summary(metrics: pd.DataFrame) -> pd.DataFrame:
    numeric = [
        "width", "height", "file_size_bytes", *PLOT_METRICS,
        "red_mean", "red_std", "green_mean", "green_std", "blue_mean", "blue_std",
    ]
    return metrics.groupby("split")[numeric].agg(["count", "mean", "std", "min", "median", "max"])


def thumbnail(path: str, size: int = 128) -> Image.Image:
    with Image.open(path) as image:
        return ImageOps.fit(image.convert("RGB"), (size, size), method=Image.Resampling.LANCZOS)


def save_grid(rows: pd.DataFrame, output: Path, title: str, limit: int = 48) -> None:
    rows = rows.head(limit)
    if rows.empty:
        return
    columns = min(8, len(rows))
    item_width, image_size, label_height = 128, 128, 32
    grid_rows = math.ceil(len(rows) / columns)
    canvas = Image.new("RGB", (columns * item_width, grid_rows * (image_size + label_height) + 28), "white")
    draw = ImageDraw.Draw(canvas)
    draw.text((6, 6), title, fill="black")
    for index, (_, row) in enumerate(rows.iterrows()):
        x = (index % columns) * item_width
        y = 28 + (index // columns) * (image_size + label_height)
        canvas.paste(thumbnail(row["resolved_path"], image_size), (x, y))
        draw.text((x + 2, y + image_size + 2), str(row["image_id"])[:20], fill="black")
        draw.text((x + 2, y + image_size + 16), str(row["split"]), fill="black")
    canvas.save(output, quality=92)


def save_grids(metrics: pd.DataFrame, output_dir: Path, seed: int, grid_size: int) -> None:
    for split in MANIFESTS:
        subset = metrics[metrics["split"] == split]
        sample = subset.sample(n=min(grid_size, len(subset)), random_state=seed)
        save_grid(sample, output_dir / f"grid_random_{split}.jpg", f"Random sample: {split}", grid_size)

    extremes = {
        "most_blurred": ("blur_laplacian_var", True),
        "most_noisy": ("high_frequency_energy", False),
        "darkest": ("luminance_mean", True),
        "brightest": ("luminance_mean", False),
        "most_near_black": ("near_black_ratio", False),
    }
    for name, (column, ascending) in extremes.items():
        ordered = metrics.sort_values([column, "image_id"], ascending=[ascending, True])
        save_grid(ordered, output_dir / f"grid_{name}.jpg", name.replace("_", " ").title(), grid_size)


def save_distributions(metrics: pd.DataFrame, output: Path) -> None:
    figure, axes = plt.subplots(3, 3, figsize=(15, 12))
    axes = axes.ravel()
    colors = {"train": "#4C78A8", "gallery": "#F58518", "query": "#E45756"}
    for axis, metric in zip(axes, PLOT_METRICS):
        for split in MANIFESTS:
            values = metrics.loc[metrics["split"] == split, metric].dropna()
            axis.hist(values, bins=40, density=True, alpha=0.4, label=split, color=colors[split])
        axis.set_title(metric.replace("_", " "))
        axis.grid(alpha=0.2)
    for axis in axes[len(PLOT_METRICS):]:
        axis.axis("off")
    axes[0].legend()
    figure.suptitle("Image degradation metrics by split", fontsize=16)
    figure.tight_layout()
    figure.savefig(output, dpi=150)
    plt.close(figure)


def write_integrity_report(path: Path, integrity: dict, problems: list[str]) -> None:
    lines = ["IMAGE RETRIEVAL DATASET INTEGRITY", "=" * 33]
    for split, info in integrity["splits"].items():
        lines.extend(
            [
                "",
                f"[{split}]",
                f"rows: {info['rows']}",
                f"unique_ids: {info['unique_ids']}",
                f"unique_manifest_paths: {info['unique_manifest_paths']}",
                f"missing: {len(info['missing'])}",
                f"broken: {len(info['broken'])}",
                f"duplicate_ids: {info['duplicate_ids'] or 'none'}",
                f"duplicate_manifest_paths: {info['duplicate_manifest_paths'] or 'none'}",
            ]
        )
    lines.extend(["", "[exact duplicate SHA-256 groups]"])
    if integrity["hash_groups"]:
        lines.extend(f"{digest}: {', '.join(items)}" for digest, items in integrity["hash_groups"].items())
    else:
        lines.append("none")
    lines.extend(["", "[problems]", *(problems or ["none"])])
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")


def write_markdown_report(path: Path, metrics: pd.DataFrame, integrity: dict) -> None:
    counts = metrics.groupby("split").size().to_dict()
    medians = metrics.groupby("split")[PLOT_METRICS].median().reindex(MANIFESTS)
    lines = [
        "# Image retrieval EDA",
        "",
        "## Dataset",
        "",
        f"- Readable images: **{len(metrics):,}**.",
        *[f"- {split}: **{counts.get(split, 0):,}** images." for split in MANIFESTS],
        f"- Exact duplicate groups: **{len(integrity['hash_groups'])}**.",
        "",
        "## Median degradation metrics",
        "",
        medians.round(4).to_markdown(),
        "",
        "## Distribution shift: query versus train",
        "",
    ]
    for metric in PLOT_METRICS:
        train = medians.loc["train", metric]
        query = medians.loc["query", metric]
        delta = query - train
        relative = delta / abs(train) * 100 if train else float("nan")
        lines.append(f"- `{metric}`: {delta:+.4f} ({relative:+.1f}% of train median).")
    lines.extend(
        [
            "",
            "## Retrieval implications",
            "",
            "- Large blur/noise shifts suggest matching augmentations for representation learning.",
            "- Near-black regions can represent rotation borders or occlusion; avoid treating them as scene content.",
            "- Inspect the extreme grids before choosing color, texture, or edge-sensitive descriptors.",
            "- This EDA does not infer labels or perform retrieval.",
            "",
            "See `distributions.png` and the `grid_*.jpg` files for visual evidence.",
        ]
    )
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")


def main() -> int:
    args = parse_args()
    data_root = args.data_root.resolve()
    output_dir = args.output_dir.resolve()
    if args.grid_size < 1:
        print("error: --grid-size must be at least 1", file=sys.stderr)
        return 2
    missing_manifests = [str(data_root / relative) for relative in MANIFESTS.values() if not (data_root / relative).is_file()]
    if missing_manifests:
        print("error: missing manifest(s):\n  " + "\n  ".join(missing_manifests), file=sys.stderr)
        return 2

    output_dir.mkdir(parents=True, exist_ok=True)
    try:
        metrics, integrity, problems = inspect_dataset(data_root)
    except (OSError, json.JSONDecodeError, ValueError) as exc:
        print(f"error: invalid manifest: {exc}", file=sys.stderr)
        return 2

    metrics.to_csv(output_dir / "image_metrics.csv", index=False)
    if not metrics.empty:
        create_summary(metrics).to_csv(output_dir / "summary.csv")
        save_grids(metrics, output_dir, args.seed, args.grid_size)
        save_distributions(metrics, output_dir / "distributions.png")
        write_markdown_report(output_dir / "report.md", metrics, integrity)
    write_integrity_report(output_dir / "integrity_report.txt", integrity, problems)

    print(f"EDA complete: {len(metrics):,} readable images -> {output_dir}")
    if problems:
        print(f"Integrity failed with {len(problems)} problem(s); see integrity_report.txt", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())