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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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
from __future__ import annotations

import argparse
import csv
import hashlib
import json
import math
import re
from collections import Counter, defaultdict
from pathlib import Path
from statistics import mean, median
from typing import Any

import numpy as np
from PIL import Image


def percentile(values: list[float], q: float) -> float | None:
    if not values:
        return None
    return float(np.percentile(np.asarray(values, dtype=np.float64), q))


def describe(values: list[float]) -> dict[str, Any]:
    if not values:
        return {}
    return {
        "count": len(values),
        "min": float(min(values)),
        "p05": percentile(values, 5),
        "mean": float(mean(values)),
        "median": float(median(values)),
        "p95": percentile(values, 95),
        "max": float(max(values)),
    }


def counter_dict(counter: Counter[Any], limit: int = 30) -> dict[str, int]:
    return {str(key): int(value) for key, value in counter.most_common(limit)}


def file_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_entropy(arr: np.ndarray) -> float:
    hist = np.bincount(arr.reshape(-1), minlength=256).astype(np.float64)
    probs = hist[hist > 0] / hist.sum()
    return float(-(probs * np.log2(probs)).sum())


def laplacian_variance(arr: np.ndarray) -> float:
    if min(arr.shape) < 3:
        return 0.0
    center = arr[1:-1, 1:-1].astype(np.float32)
    lap = (
        arr[:-2, 1:-1].astype(np.float32)
        + arr[2:, 1:-1].astype(np.float32)
        + arr[1:-1, :-2].astype(np.float32)
        + arr[1:-1, 2:].astype(np.float32)
        - 4.0 * center
    )
    return float(lap.var())


def downsample_for_stats(image: Image.Image, max_side: int = 768) -> Image.Image:
    width, height = image.size
    scale = min(1.0, max_side / max(width, height))
    if scale >= 1.0:
        return image
    size = (max(1, int(round(width * scale))), max(1, int(round(height * scale))))
    return image.resize(size, Image.Resampling.BILINEAR)


def image_record(path: Path, hash_files: bool) -> dict[str, Any]:
    with Image.open(path) as image:
        mode = image.mode
        fmt = image.format
        width, height = image.size
        dpi = image.info.get("dpi")
        gray = downsample_for_stats(image.convert("L"))
        arr = np.asarray(gray, dtype=np.uint8)

    foreground = arr < 245
    if foreground.any():
        ys, xs = np.where(foreground)
        bbox_area_ratio = float(((xs.max() - xs.min() + 1) * (ys.max() - ys.min() + 1)) / arr.size)
    else:
        bbox_area_ratio = 0.0

    p05 = float(np.percentile(arr, 5))
    p95 = float(np.percentile(arr, 95))
    out = {
        "path": str(path),
        "mode": mode,
        "format": fmt,
        "width": width,
        "height": height,
        "area": width * height,
        "aspect": width / height if height else None,
        "dpi_x": float(dpi[0]) if dpi else None,
        "dpi_y": float(dpi[1]) if dpi else None,
        "mean": float(arr.mean()),
        "std": float(arr.std()),
        "p01": float(np.percentile(arr, 1)),
        "p05": p05,
        "p50": float(np.percentile(arr, 50)),
        "p95": p95,
        "p99": float(np.percentile(arr, 99)),
        "contrast_p95_p05": p95 - p05,
        "black_frac_lte_5": float((arr <= 5).mean()),
        "dark_frac_lt_80": float((arr < 80).mean()),
        "ink_frac_lt_245": float(foreground.mean()),
        "white_frac_gte_250": float((arr >= 250).mean()),
        "entropy": image_entropy(arr),
        "laplacian_var": laplacian_variance(arr),
        "foreground_bbox_area_ratio": bbox_area_ratio,
        "sha256": file_sha256(path) if hash_files else None,
    }
    return out


def metadata_record(path: Path, hash_files: bool) -> dict[str, Any]:
    with Image.open(path) as image:
        dpi = image.info.get("dpi")
        return {
            "path": str(path),
            "mode": image.mode,
            "format": image.format,
            "width": image.size[0],
            "height": image.size[1],
            "area": image.size[0] * image.size[1],
            "aspect": image.size[0] / image.size[1] if image.size[1] else None,
            "dpi_x": float(dpi[0]) if dpi else None,
            "dpi_y": float(dpi[1]) if dpi else None,
            "sha256": file_sha256(path) if hash_files else None,
        }


def even_sample(paths: list[Path], limit: int | None) -> list[Path]:
    if limit is None or limit <= 0 or len(paths) <= limit:
        return paths
    if limit == 1:
        return [paths[0]]
    indexes = np.linspace(0, len(paths) - 1, limit, dtype=np.int64)
    return [paths[int(index)] for index in indexes]


def summarize_images(
    paths: list[Path],
    sample_records: int,
    hash_files: bool,
    quality_limit: int | None,
) -> dict[str, Any]:
    metadata: list[dict[str, Any]] = []
    errors: list[dict[str, str]] = []
    for path in paths:
        try:
            metadata.append(metadata_record(path, hash_files))
        except Exception as exc:
            errors.append({"path": str(path), "error": repr(exc)})

    quality_paths = even_sample([Path(item["path"]) for item in metadata], quality_limit)
    quality_records: list[dict[str, Any]] = []
    quality_errors: list[dict[str, str]] = []
    for path in quality_paths:
        try:
            quality_records.append(image_record(path, False))
        except Exception as exc:
            quality_errors.append({"path": str(path), "error": repr(exc)})

    metadata_numeric_keys = [
        "width",
        "height",
        "area",
        "aspect",
        "dpi_x",
        "dpi_y",
    ]
    quality_numeric_keys = [
        "mean",
        "std",
        "p01",
        "p05",
        "p50",
        "p95",
        "p99",
        "contrast_p95_p05",
        "black_frac_lte_5",
        "dark_frac_lt_80",
        "ink_frac_lt_245",
        "white_frac_gte_250",
        "entropy",
        "laplacian_var",
        "foreground_bbox_area_ratio",
    ]
    summary: dict[str, Any] = {
        "files": len(paths),
        "ok": len(metadata),
        "errors": errors[:20],
        "mode_counts": counter_dict(Counter(r["mode"] for r in metadata)),
        "format_counts": counter_dict(Counter(r["format"] for r in metadata)),
        "dimension_counts": counter_dict(Counter((r["width"], r["height"]) for r in metadata)),
        "dpi_counts": counter_dict(Counter((r["dpi_x"], r["dpi_y"]) for r in metadata)),
        "stats": {
            key: describe([float(r[key]) for r in metadata if r.get(key) is not None])
            for key in metadata_numeric_keys
        },
        "quality_sample_files": len(quality_paths),
        "quality_sample_ok": len(quality_records),
        "quality_sample_errors": quality_errors[:20],
        "quality_stats": {
            key: describe([float(r[key]) for r in quality_records if r.get(key) is not None])
            for key in quality_numeric_keys
        },
        "samples": quality_records[:sample_records],
    }
    if hash_files:
        hashes = Counter(r["sha256"] for r in metadata if r.get("sha256"))
        summary["unique_sha256"] = len(hashes)
        summary["duplicate_sha256_groups"] = sum(1 for value in hashes.values() if value > 1)
        summary["duplicate_sha256_files"] = sum(value for value in hashes.values() if value > 1)

    anomaly_keys = [
        ("smallest_area", "area", False),
        ("largest_area", "area", True),
        ("lowest_std", "std", False),
        ("highest_white_frac", "white_frac_gte_250", True),
        ("lowest_entropy", "entropy", False),
        ("lowest_laplacian_var", "laplacian_var", False),
    ]
    for out_key, sort_key, reverse in anomaly_keys:
        source = metadata if sort_key in metadata_numeric_keys else quality_records
        summary[out_key] = [
            {
                "path": r["path"],
                "width": r["width"],
                "height": r["height"],
                "std": r.get("std"),
                "white_frac_gte_250": r.get("white_frac_gte_250"),
                "entropy": r.get("entropy"),
                "laplacian_var": r.get("laplacian_var"),
            }
            for r in sorted(source, key=lambda item: item[sort_key], reverse=reverse)[:10]
        ]
    return summary


def pngs(root: Path) -> list[Path]:
    if not root.exists():
        return []
    return sorted(root.rglob("*.png"))


def read_csv(path: Path) -> list[dict[str, str]]:
    with path.open(newline="", encoding="utf-8") as handle:
        return list(csv.DictReader(handle))


def subject_from_path(path: str) -> str | None:
    match = re.search(r"/(\d{8})/", path)
    return match.group(1) if match else None


def fgp_from_roll_name(path: str) -> str | None:
    match = re.search(r"_roll_(\d{2})\.png$", path)
    return match.group(1) if match else None


def device_ppi_from_nist302g(path: str) -> tuple[str | None, str | None, str | None]:
    parts = Path(path).parts
    for idx, part in enumerate(parts):
        if part in {"R", "S", "U", "V", "C"} and idx + 1 < len(parts):
            return part, parts[idx + 1], "challenger" if "challengers" in parts else "baseline"
    return None, None, None


def summarize_manifest(path: Path) -> dict[str, Any]:
    rows = read_csv(path)
    mates = [row.get("mate", "") for row in rows if row.get("mate")]
    unique_mates = sorted(set(mates))
    mate_counter = Counter(mates)
    fanouts = list(mate_counter.values())
    device_counts: Counter[tuple[str | None, str | None, str | None]] = Counter(
        device_ppi_from_nist302g(mate) for mate in unique_mates
    )
    row_device_counts: Counter[tuple[str | None, str | None, str | None]] = Counter(
        device_ppi_from_nist302g(mate) for mate in mates
    )
    return {
        "path": str(path),
        "rows": len(rows),
        "unique_mates": len(unique_mates),
        "unique_latents": len({row.get("latent", "") for row in rows if row.get("latent")}),
        "unique_identity_labels": len({row.get("identity_label", "") for row in rows if row.get("identity_label")}),
        "unique_subjects": len({row.get("subject", "") for row in rows if row.get("subject")}),
        "fgp_counts": counter_dict(Counter(row.get("fgp", "") for row in rows if row.get("fgp"))),
        "unique_mate_device_ppi_counts": counter_dict(device_counts),
        "row_mate_device_ppi_counts": counter_dict(row_device_counts),
        "latent_per_mate": describe([float(v) for v in fanouts]),
        "top_mate_fanout": [
            {"mate": mate, "rows": count}
            for mate, count in mate_counter.most_common(10)
        ],
    }


def collect_unique_manifest_mates(manifest_paths: list[Path]) -> list[Path]:
    mates: set[str] = set()
    for manifest_path in manifest_paths:
        for row in read_csv(manifest_path):
            mate = row.get("mate")
            if mate:
                mates.add(mate)
    return sorted(Path(mate) for mate in mates)


def summarize_nist302a_group(paths: list[Path]) -> dict[str, Any]:
    subjects = Counter(subject_from_path(str(path)) for path in paths)
    fingers = Counter(fgp_from_roll_name(path.name) for path in paths)
    per_subject = Counter(subject for subject in subjects if subject)
    return {
        "unique_subjects": len([subject for subject in subjects if subject]),
        "fgp_counts": counter_dict(fingers),
        "images_per_subject": describe([float(v) for k, v in per_subject.items() if k]),
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--repo-root", default=".")
    parser.add_argument("--dataset-root", default="/home/aiserver/works/fingerprint/dataset")
    parser.add_argument("--manifest-root", default="manifests/nist302")
    parser.add_argument("--out", default="outputs/eda_hq_image_groups.json")
    parser.add_argument("--sample-records", type=int, default=5)
    parser.add_argument("--quality-limit", type=int, default=500)
    parser.add_argument("--hash-files", action="store_true")
    args = parser.parse_args()

    repo_root = Path(args.repo_root).resolve()
    dataset_root = Path(args.dataset_root).resolve()
    manifest_root = Path(args.manifest_root).resolve()

    nist302g_root = repo_root / "data/converted/nist302g_png"
    nist302a_root = dataset_root / "nist302a/images/challengers"

    groups: dict[str, list[Path]] = {
        "nist302g_baseline_V_1000_roll": pngs(nist302g_root / "baseline/irr/V/1000"),
        "nist302g_baseline_U_1000_plain": pngs(nist302g_root / "baseline/irr/U/1000"),
        "nist302g_baseline_R_1000_slap": pngs(nist302g_root / "baseline/irr/R/1000"),
        "nist302g_baseline_S_500_slap": pngs(nist302g_root / "baseline/irr/S/500"),
        "nist302g_challenger_C_500_roll": pngs(nist302g_root / "challengers/irr/C/500"),
    }

    for challenger in "ABCDEFGH":
        groups[f"nist302a_challenger_{challenger}_500_roll"] = pngs(
            nist302a_root / challenger / "roll/png"
        )
    groups["nist302a_challengers_all_500_roll"] = sorted(
        path for challenger in "ABCDEFGH" for path in pngs(nist302a_root / challenger / "roll/png")
    )

    ready_manifests = sorted(manifest_root.glob("*_ready/paired_302i_*.csv"))
    ready_manifests = [path for path in ready_manifests if not path.name.endswith("_with_irr.csv")]
    manifest_mates = collect_unique_manifest_mates(ready_manifests)
    groups["nist302i_ready_unique_mates"] = manifest_mates

    report: dict[str, Any] = {
        "paths": {
            "repo_root": str(repo_root),
            "dataset_root": str(dataset_root),
            "manifest_root": str(manifest_root),
            "nist302g_converted_root": str(nist302g_root),
            "nist302a_challengers_root": str(nist302a_root),
        },
        "manifest_summaries": [summarize_manifest(path) for path in ready_manifests],
        "groups": {},
        "cross_coverage": {},
    }

    nist302g_sets = {name: {str(path) for path in paths} for name, paths in groups.items() if name.startswith("nist302g_")}
    manifest_mate_set = {str(path) for path in manifest_mates}
    report["cross_coverage"]["nist302i_ready_mates_in_nist302g_groups"] = {
        name: len(manifest_mate_set & path_set) for name, path_set in nist302g_sets.items()
    }

    for name, paths in groups.items():
        image_summary = summarize_images(paths, args.sample_records, args.hash_files, args.quality_limit)
        if name.startswith("nist302a_challenger"):
            image_summary["identity_summary"] = summarize_nist302a_group(paths)
        report["groups"][name] = image_summary
        print(json.dumps({"group": name, "files": len(paths), "ok": image_summary["ok"]}))

    out_path = Path(args.out)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    print(json.dumps({"out": str(out_path), "groups": len(groups)}, indent=2))
    return 0


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