File size: 9,019 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
from __future__ import annotations

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

FS = "\x1c"
GS = "\x1d"
RS = "\x1e"
US = "\x1f"


def read_text_prefix(path: Path, max_bytes: int = 2_000_000) -> str:
    data = path.read_bytes()[:max_bytes]
    return data.decode("latin-1", errors="replace")


def split_ebts_records(path: Path) -> dict[str, list[dict[str, str]]]:
    text = read_text_prefix(path)
    png_idx = text.find("\x89PNG\r\n\x1a\n")
    if png_idx >= 0:
        text = text[:png_idx]
    records: dict[str, list[dict[str, str]]] = defaultdict(list)
    for record in text.split(FS):
        record = record.strip("\x00\r\n")
        if not record:
            continue
        fields: dict[str, str] = {}
        for field in record.split(GS):
            if ":" not in field:
                continue
            key, value = field.split(":", 1)
            if "." not in key:
                continue
            record_type = key.split(".", 1)[0]
            fields[key] = value
        if fields:
            record_type = next(iter(fields)).split(".", 1)[0]
            records[record_type].append(fields)
    return dict(records)


def count_subfields(value: str | None) -> int:
    if not value:
        return 0
    return len([part for part in value.split(RS) if part])


def segmentation_grid_shape(value: str | None) -> tuple[int | None, int | None, set[str]]:
    if not value:
        return None, None, set()
    rows = [row for row in value.split(RS) if row]
    widths = {len(row) for row in rows}
    chars = set("".join(rows))
    width = widths.pop() if len(widths) == 1 else None
    return len(rows), width, chars


def parse_int_pair(value: str | None) -> tuple[int | None, int | None]:
    if not value:
        return None, None
    parts = value.split(US)
    if len(parts) < 2:
        return None, None
    try:
        return int(parts[0]), int(parts[1])
    except ValueError:
        return None, None


def png_ihdr_from_text(text: str) -> tuple[int | None, int | None]:
    marker = "\x89PNG\r\n\x1a\n"
    idx = text.find(marker)
    if idx < 0:
        return None, None
    raw = text.encode("latin-1", errors="replace")
    pos = idx + len(marker)
    if len(raw) < pos + 16:
        return None, None
    # IHDR chunk: length(4), type(4), width(4), height(4)
    if raw[pos + 4 : pos + 8] != b"IHDR":
        return None, None
    width = int.from_bytes(raw[pos + 8 : pos + 12], "big")
    height = int.from_bytes(raw[pos + 12 : pos + 16], "big")
    return width, height


def comp_references(path: Path) -> tuple[str | None, str | None]:
    text = read_text_prefix(path, 400_000)
    lffs = None
    irr = None
    # Field 2.1406 contains references with labels LFFS/IRR in the current data.
    m = re.search(r"LFFS" + US + r"[^" + RS + FS + r"]*" + US + r"([^" + US + RS + FS + r"]+\.lffs)", text)
    if m:
        lffs = Path(m.group(1)).name
    m = re.search(r"IRR" + US + r"[^" + RS + FS + r"]*" + US + r"([^" + US + RS + FS + r"]+\.irr)", text)
    if m:
        irr = Path(m.group(1)).name
    return lffs, irr


def summarize_ebts_file(path: Path) -> dict[str, Any]:
    records = split_ebts_records(path)
    out: dict[str, Any] = {
        "record_types": {record_type: len(items) for record_type, items in sorted(records.items())},
        "type_1_file_content": records.get("1", [{}])[0].get("1.003"),
        "type_1_type_of_transaction": records.get("1", [{}])[0].get("1.004"),
    }
    type9 = records.get("9", [])
    out["type9_count"] = len(type9)
    out["type13_count"] = len(records.get("13", []))
    out["type9_minutiae_counts"] = [count_subfields(r.get("9.331")) for r in type9]
    out["type9_core_counts"] = [count_subfields(r.get("9.320")) for r in type9]
    out["type9_delta_counts"] = [count_subfields(r.get("9.321")) for r in type9]
    out["type9_seg_shapes"] = []
    out["type9_image_sizes"] = []
    out["type9_imp"] = []
    for r in type9:
        seg_h, seg_w, chars = segmentation_grid_shape(r.get("9.308"))
        out["type9_seg_shapes"].append([seg_w, seg_h, "".join(sorted(chars))])
        out["type9_image_sizes"].append(list(parse_int_pair(r.get("9.300"))))
        out["type9_imp"].append(r.get("9.004"))
    type13 = records.get("13", [])
    out["type13_image_sizes"] = []
    out["type13_hll_vll"] = []
    for r in type13:
        out["type13_hll_vll"].append([r.get("13.006"), r.get("13.007"), r.get("13.009"), r.get("13.010")])
    text = read_text_prefix(path, 2_000_000)
    out["embedded_png_ihdr"] = list(png_ihdr_from_text(text))
    if path.suffix == ".comp":
        out["comp_references"] = list(comp_references(path))
    return out


def counter_to_dict(counter: Counter[Any]) -> dict[str, int]:
    return {str(k): int(v) for k, v in counter.most_common()}


def summarize_manifest(path: Path) -> dict[str, Any]:
    with path.open(newline="", encoding="utf-8") as handle:
        rows = list(csv.DictReader(handle))
    out: dict[str, Any] = {"path": str(path), "rows": len(rows), "columns": list(rows[0].keys()) if rows else []}
    for col in ("latent", "mate", "mate_irr", "comp_path", "lffs_path", "identity_label", "subject", "fgp", "status"):
        if rows and col in rows[0]:
            vals = [r.get(col, "") for r in rows]
            out[f"{col}_nonempty"] = sum(1 for v in vals if v)
            out[f"{col}_unique"] = len(set(v for v in vals if v))
            if col in ("status", "fgp"):
                out[f"{col}_counts"] = counter_to_dict(Counter(vals))
    return out


def summarize_image_csv(path: Path, limit: int = 300) -> dict[str, Any]:
    try:
        from PIL import Image
    except Exception:
        return {"path": str(path), "status": "PIL_unavailable"}
    with path.open(newline="", encoding="utf-8") as handle:
        rows = list(csv.DictReader(handle))
    stats: dict[str, list[float]] = defaultdict(list)
    for row in rows[:limit]:
        for col in ("latent", "mate"):
            image_path = row.get(col)
            if not image_path:
                continue
            p = Path(image_path)
            if not p.exists():
                continue
            try:
                im = Image.open(p)
            except Exception:
                continue
            stats[f"{col}_width"].append(float(im.size[0]))
            stats[f"{col}_height"].append(float(im.size[1]))
            dpi = im.info.get("dpi")
            if dpi:
                stats[f"{col}_dpi_x"].append(float(dpi[0]))
                stats[f"{col}_dpi_y"].append(float(dpi[1]))
    return {
        "path": str(path),
        "sampled_rows": min(limit, len(rows)),
        "stats": {
            key: {
                "min": min(values),
                "mean": mean(values),
                "max": max(values),
                "unique": sorted(set(values))[:20],
            }
            for key, values in stats.items()
        },
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    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_nist302_inputs.json")
    parser.add_argument("--sample-files", type=int, default=20)
    args = parser.parse_args()

    dataset_root = Path(args.dataset_root)
    manifest_root = Path(args.manifest_root)
    out_path = Path(args.out)

    report: dict[str, Any] = {}

    nist_dirs = sorted(p for p in dataset_root.iterdir() if p.is_dir() and p.name.startswith("nist302"))
    report["dataset_roots"] = [str(p) for p in nist_dirs]
    report["extension_counts_by_root"] = {}
    for root in nist_dirs:
        counter: Counter[str] = Counter()
        for path in root.rglob("*"):
            if path.is_file():
                counter[path.suffix.lower() or "<none>"] += 1
        report["extension_counts_by_root"][root.name] = counter_to_dict(counter)

    manifest_files = sorted(manifest_root.rglob("*.csv"))
    report["manifests"] = [summarize_manifest(p) for p in manifest_files]
    ready_manifests = sorted(manifest_root.glob("*_ready/paired_302i_*.csv"))
    report["ready_manifest_image_stats_sample"] = [summarize_image_csv(p) for p in ready_manifests]

    ebts_samples: dict[str, list[dict[str, Any]]] = {}
    for suffix in (".comp", ".lffs", ".irr"):
        files = sorted(dataset_root.rglob(f"*{suffix}"))[: args.sample_files]
        ebts_samples[suffix] = [{"path": str(p), **summarize_ebts_file(p)} for p in files]
    report["ebts_samples"] = ebts_samples

    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), "dataset_roots": len(nist_dirs), "manifests": len(manifest_files)}, indent=2))
    return 0


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