File size: 12,257 Bytes
73dcd2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

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

from PIL import Image


PAIR_COLUMNS = [
    "latent",
    "mate",
    "identity_label",
    "subject",
    "fgp",
    "comp_path",
    "lffs_path",
    "domain",
    "device",
    "ppi",
    "capture",
    "split",
]


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


def write_csv(path: Path, rows: list[dict[str, str]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=PAIR_COLUMNS, extrasaction="ignore")
        writer.writeheader()
        writer.writerows(rows)


def parse_mate_domain(path: str) -> dict[str, str] | None:
    parts = Path(path).parts
    if "nist302g_png" not in parts:
        return None
    domain = "challenger" if "challengers" in parts else "baseline"
    capture = ""
    for idx, part in enumerate(parts):
        if part in {"R", "S", "U", "V", "C"} and idx + 1 < len(parts):
            ppi = parts[idx + 1]
            stem = Path(path).stem
            if "_roll_" in stem:
                capture = "roll"
            elif "_slap_" in stem:
                capture = "slap"
            return {
                "domain": domain,
                "device": part,
                "ppi": ppi,
                "capture": capture,
            }
    return None


def image_metadata(path: Path) -> dict[str, Any]:
    with Image.open(path) as image:
        dpi = image.info.get("dpi")
        return {
            "width": image.size[0],
            "height": image.size[1],
            "dpi_x": float(dpi[0]) if dpi else None,
            "dpi_y": float(dpi[1]) if dpi else None,
        }


def grayscale_quality(path: Path, max_side: int = 768) -> dict[str, float]:
    with Image.open(path) as image:
        image = image.convert("L")
        scale = min(1.0, max_side / max(image.size))
        if scale < 1.0:
            size = (
                max(1, int(round(image.size[0] * scale))),
                max(1, int(round(image.size[1] * scale))),
            )
            image = image.resize(size, Image.Resampling.BILINEAR)
        hist = image.histogram()
    total = sum(hist)
    if total <= 0:
        return {"mean": 0.0, "std": 0.0, "entropy": 0.0, "white_frac": 0.0}
    avg = sum(i * count for i, count in enumerate(hist)) / total
    var = sum(((i - avg) ** 2) * count for i, count in enumerate(hist)) / total
    entropy = 0.0
    for count in hist:
        if count:
            p = count / total
            entropy -= p * math.log2(p)
    return {
        "mean": avg,
        "std": math.sqrt(var),
        "entropy": entropy,
        "white_frac": sum(hist[250:]) / total,
    }


def quality_ok(path: Path, min_std: float, min_entropy: float, max_white_frac: float) -> tuple[bool, dict[str, float]]:
    q = grayscale_quality(path)
    ok = q["std"] >= min_std and q["entropy"] >= min_entropy and q["white_frac"] <= max_white_frac
    return ok, q


def is_hq_vu1000(row: dict[str, str]) -> bool:
    domain = parse_mate_domain(row.get("mate", ""))
    if not domain:
        return False
    return (
        domain["domain"] == "baseline"
        and domain["device"] in {"V", "U"}
        and domain["ppi"] == "1000"
        and domain["capture"] == "roll"
    )


def split_subjects(subjects: list[str], seed: int, train_frac: float, val_frac: float) -> dict[str, str]:
    shuffled = list(subjects)
    random.Random(seed).shuffle(shuffled)
    n_train = int(round(len(shuffled) * train_frac))
    n_val = int(round(len(shuffled) * val_frac))
    split: dict[str, str] = {}
    for subject in shuffled[:n_train]:
        split[subject] = "train"
    for subject in shuffled[n_train : n_train + n_val]:
        split[subject] = "val"
    for subject in shuffled[n_train + n_val :]:
        split[subject] = "test"
    return split


def describe(values: list[int]) -> dict[str, Any]:
    if not values:
        return {}
    return {
        "count": len(values),
        "min": min(values),
        "mean": mean(values),
        "median": median(values),
        "max": max(values),
    }


def summarize_rows(rows: list[dict[str, str]]) -> dict[str, Any]:
    by_id = Counter(row["identity_label"] for row in rows)
    by_subject = Counter(row["subject"] for row in rows)
    by_mate = Counter(row["mate"] for row in rows)
    by_split = Counter(row["split"] for row in rows)
    by_device = Counter((row["domain"], row["device"], row["ppi"], row["capture"]) for row in rows)
    return {
        "rows": len(rows),
        "unique_subjects": len(by_subject),
        "unique_identity_labels": len(by_id),
        "unique_mates": len(by_mate),
        "split_counts": dict(sorted(by_split.items())),
        "device_counts": {str(k): v for k, v in sorted(by_device.items())},
        "rows_per_identity": describe(list(by_id.values())),
        "rows_per_mate": describe(list(by_mate.values())),
        "identity_count_distribution": dict(sorted(Counter(by_id.values()).items())),
        "mate_fanout_distribution": dict(sorted(Counter(by_mate.values()).items())),
    }


def manifest_key(path: Path) -> tuple[str, str]:
    match = re.search(r"paired_302i_(original|enhanced)_(masked|unmasked)\.csv$", path.name)
    if not match:
        raise ValueError(f"Unexpected manifest name: {path}")
    return match.group(1), match.group(2)


def link_exemplars(rows: list[dict[str, str]], link_root: Path) -> int:
    link_root.mkdir(parents=True, exist_ok=True)
    created = 0
    seen: set[str] = set()
    for row in rows:
        src = Path(row["mate"]).resolve()
        if str(src) in seen:
            continue
        seen.add(str(src))
        domain = parse_mate_domain(str(src))
        if domain is None:
            continue
        subject = row["subject"]
        dst = link_root / domain["domain"] / "irr" / domain["device"] / domain["ppi"] / subject / src.name
        dst.parent.mkdir(parents=True, exist_ok=True)
        if dst.exists():
            continue
        rel_src = os.path.relpath(src, dst.parent)
        dst.symlink_to(rel_src)
        created += 1
    return created


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--manifest-root", default="manifests/nist302")
    parser.add_argument("--out-root", default="manifests/nist302_hq_pairs")
    parser.add_argument("--link-exemplar-root", default="data/derived/nist302g_hq_vu1000")
    parser.add_argument("--seed", type=int, default=302)
    parser.add_argument("--train-frac", type=float, default=0.80)
    parser.add_argument("--val-frac", type=float, default=0.10)
    parser.add_argument("--min-std", type=float, default=25.0)
    parser.add_argument("--min-entropy", type=float, default=1.20)
    parser.add_argument("--max-white-frac", type=float, default=0.92)
    parser.add_argument("--no-quality-filter", action="store_true")
    args = parser.parse_args()

    manifest_root = Path(args.manifest_root)
    out_root = Path(args.out_root)
    link_root = Path(args.link_exemplar_root)

    input_manifests = [
        path
        for path in sorted(manifest_root.glob("*_ready/paired_302i_*.csv"))
        if not path.name.endswith("_with_irr.csv")
    ]
    if not input_manifests:
        raise FileNotFoundError(f"No ready paired manifests found under {manifest_root}")

    base_rows = [row for path in input_manifests for row in read_csv(path) if is_hq_vu1000(row)]
    subjects = sorted({row["subject"] for row in base_rows if row.get("subject")})
    subject_split = split_subjects(subjects, args.seed, args.train_frac, args.val_frac)

    quality_cache: dict[str, tuple[bool, dict[str, float]]] = {}
    all_written_rows: list[dict[str, str]] = []
    reports: dict[str, Any] = {}

    for manifest_path in input_manifests:
        variant, mask = manifest_key(manifest_path)
        rows = read_csv(manifest_path)
        kept: list[dict[str, str]] = []
        drop_counts: Counter[str] = Counter()
        quality_values: dict[str, list[float]] = defaultdict(list)

        for row in rows:
            if not is_hq_vu1000(row):
                drop_counts["non_hq_domain"] += 1
                continue
            mate_path = Path(row["mate"])
            try:
                meta = image_metadata(mate_path)
            except Exception:
                drop_counts["mate_unreadable"] += 1
                continue
            if meta["width"] != 1600 or meta["height"] != 1500:
                drop_counts["non_1600x1500"] += 1
                continue
            if meta["dpi_x"] is None or abs(meta["dpi_x"] - 1000.0) > 2.0:
                drop_counts["non_1000dpi"] += 1
                continue
            if not args.no_quality_filter:
                key = str(mate_path)
                if key not in quality_cache:
                    quality_cache[key] = quality_ok(mate_path, args.min_std, args.min_entropy, args.max_white_frac)
                ok, quality = quality_cache[key]
                for q_key, q_value in quality.items():
                    quality_values[q_key].append(q_value)
                if not ok:
                    drop_counts["low_quality_mate"] += 1
                    continue

            domain = parse_mate_domain(row["mate"])
            assert domain is not None
            out_row = dict(row)
            out_row.update(domain)
            out_row["split"] = subject_split[row["subject"]]
            kept.append(out_row)

        out_dir = out_root / f"{variant}_{mask}"
        write_csv(out_dir / f"paired_302i_{variant}_{mask}_hq_vu1000_all.csv", kept)
        for split in ("train", "val", "test"):
            split_rows = [row for row in kept if row["split"] == split]
            write_csv(out_dir / f"paired_302i_{variant}_{mask}_hq_vu1000_{split}.csv", split_rows)
        all_written_rows.extend(kept)
        reports[f"{variant}_{mask}"] = {
            "source": str(manifest_path),
            "dropped": dict(sorted(drop_counts.items())),
            "quality_thresholds": {
                "min_std": args.min_std,
                "min_entropy": args.min_entropy,
                "max_white_frac": args.max_white_frac,
                "enabled": not args.no_quality_filter,
            },
            "quality_observed": {
                key: {
                    "min": min(values),
                    "mean": mean(values),
                    "max": max(values),
                }
                for key, values in quality_values.items()
            },
            "summary": summarize_rows(kept),
            "outputs": {
                "all": str(out_dir / f"paired_302i_{variant}_{mask}_hq_vu1000_all.csv"),
                "train": str(out_dir / f"paired_302i_{variant}_{mask}_hq_vu1000_train.csv"),
                "val": str(out_dir / f"paired_302i_{variant}_{mask}_hq_vu1000_val.csv"),
                "test": str(out_dir / f"paired_302i_{variant}_{mask}_hq_vu1000_test.csv"),
            },
        }

    linked = link_exemplars(all_written_rows, link_root)
    report = {
        "manifest_root": str(manifest_root),
        "out_root": str(out_root),
        "link_exemplar_root": str(link_root),
        "symlinks_created": linked,
        "seed": args.seed,
        "subject_split_counts": dict(sorted(Counter(subject_split.values()).items())),
        "subject_split": subject_split,
        "variants": reports,
    }
    out_root.mkdir(parents=True, exist_ok=True)
    (out_root / "summary_hq_vu1000.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
    print(json.dumps({
        "out_root": str(out_root),
        "link_exemplar_root": str(link_root),
        "subject_split_counts": report["subject_split_counts"],
        "variants": {key: value["summary"]["split_counts"] for key, value in reports.items()},
        "symlinks_created": linked,
    }, indent=2, sort_keys=True))
    return 0


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