File size: 14,843 Bytes
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build dataset evaluation from explicitly pinned release inputs."""

from __future__ import annotations

from utils.paths import PROJECT_ROOT
from utils.io import sha256_file as _sha256
import json
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from utils.dataset import resolve_local_images
from statistics import mean, median
from scripts.datasets.dataset_quality import build_quality_slices
from utils.release import release_config, release_identity, release_paths, validate_population

ROOT = PROJECT_ROOT
FULL_DATASET = ROOT / "data" / "full_dataset"
MANIFEST_PATH = FULL_DATASET / "dataset_manifest.jsonl"
GOLD_DIR = FULL_DATASET / "ground_truth" / "gold"
IAA_DIR = FULL_DATASET / "ground_truth" / "iaa"
IMAGE_DIR = FULL_DATASET / "images"
DOMAIN_PATH = ROOT / "data" / "violation_domains.json"
DEFAULT_OUTPUT = ROOT / "frontend" / ".generated" / "dataset_eda.json"


def _latest(directory: Path, pattern: str) -> Path:
    candidates = sorted(directory.glob(pattern))
    if not candidates:
        raise FileNotFoundError(f"No {pattern} exports found in {directory}")
    return candidates[-1]


def _source(path: Path, records: int) -> dict:
    return {"filename": path.name, "records": records, "sha256": _sha256(path)}


def _valid_bbox(bbox: object) -> bool:
    if not isinstance(bbox, list) or len(bbox) != 4 or not all(isinstance(value, (int, float)) for value in bbox):
        return False
    x, y, width, height = bbox
    return width > 0 and height > 0 and x >= 0 and y >= 0 and x + width <= 1 and y + height <= 1


def _rating(values: list[int | None]) -> dict:
    clean = [value for value in values if value is not None]
    counts = Counter(clean)
    return {
        "eligible": len(clean),
        "missing": len(values) - len(clean),
        "counts": {str(score): counts[score] for score in range(1, 6)},
        "mean": round(mean(clean), 3) if clean else None,
        "median": median(clean) if clean else None,
        "low": sum(value <= 2 for value in clean),
        "high": sum(value >= 4 for value in clean),
    }


def _distribution(values: list[str], order: list[str] | None = None) -> list[dict]:
    counts = Counter(values)
    keys = order or sorted(counts)
    return [{"name": key, "count": counts[key]} for key in keys]


def summarize_gold(records: list[dict], domains: list[dict]) -> dict:
    domain_ids = {item["name"]: set(item["ids"]) for item in domains}
    image_classes = [set(item["use_case_id"] for item in row["violations"]) for row in records]
    instance_counts = Counter(
        item["use_case_id"] for row in records for item in row["violations"]
    )
    image_counts = Counter(use_case_id for values in image_classes for use_case_id in values)
    class_names = {}
    for row in records:
        for item in row["violations"]:
            class_names.setdefault(item["use_case_id"], item["name"])
    violations = []
    for domain in domains:
        for use_case_id in domain["ids"]:
            violations.append({
                "id": use_case_id,
                "name": class_names.get(use_case_id, f"Violation {use_case_id}"),
                "domain": domain["name"],
                "images": image_counts[use_case_id],
                "instances": instance_counts[use_case_id],
                "represented": image_counts[use_case_id] > 0,
            })
    domain_rows = []
    for name, ids in domain_ids.items():
        domain_rows.append({
            "name": name,
            "class_count": len(ids),
            "represented_classes": sum(image_counts[use_case_id] > 0 for use_case_id in ids),
            "images": sum(bool(values & ids) for values in image_classes),
            "instances": sum(instance_counts[use_case_id] for use_case_id in ids),
        })
    return {
        "records": len(records),
        "categories": _distribution([row["category"] for row in records]),
        "gold_kinds": _distribution([row["kind"] for row in records]),
        "gold_methods": _distribution([row.get("method", row["kind"]) for row in records]),
        "label_states": [
            {"name": "Violation present", "count": sum(bool(row["violations"]) for row in records)},
            {"name": "No violation", "count": sum(row["no_violation_detected"] for row in records)},
            {"name": "Reported / unusable", "count": sum(row["reported"] for row in records)},
        ],
        "plausibility": _rating([row["plausibility"] for row in records]),
        "naturalness": _rating([row["naturalness"] for row in records]),
        "domains": domain_rows,
        "violations": violations,
        "violation_instances": sum(instance_counts.values()),
        "represented_classes": sum(item["represented"] for item in violations),
    }


def _agreement_summary(records: list[dict]) -> dict:
    def values(key: str) -> list[float]:
        return [row["agreement"][key] for row in records if row["agreement"].get(key) is not None]

    plausibility = values("plausibility_delta")
    naturalness = values("naturalness_delta")
    jaccard = values("violation_jaccard")
    bbox = values("mean_bbox_iou")
    scores = values("disagreement_score")
    return {
        "records": len(records),
        "first_pass_submissions": sum(row["n_first_pass"] for row in records),
        "plausibility": {
            "eligible": len(plausibility), "exact": sum(value == 0 for value in plausibility),
            "within_one": sum(value <= 1 for value in plausibility),
            "counts": {str(delta): sum(value == delta for value in plausibility) for delta in range(5)},
        },
        "naturalness": {
            "eligible": len(naturalness), "exact": sum(value == 0 for value in naturalness),
            "within_one": sum(value <= 1 for value in naturalness),
            "counts": {str(delta): sum(value == delta for value in naturalness) for delta in range(5)},
        },
        "violation_jaccard": {
            "eligible": len(jaccard), "exact": sum(value == 1 for value in jaccard),
            "none": sum(value == 0 for value in jaccard),
            "partial": sum(0 < value < 1 for value in jaccard),
            "mean": round(mean(jaccard), 3) if jaccard else None,
        },
        "bbox_iou": {
            "eligible": len(bbox), "mean": round(mean(bbox), 3) if bbox else None,
            "median": round(median(bbox), 3) if bbox else None,
            "at_least_50": sum(value >= 0.50 for value in bbox),
            "at_least_75": sum(value >= 0.75 for value in bbox),
        },
        "reported_mismatches": sum(bool(row["agreement"].get("reported_mismatch")) for row in records),
        "disagreement_score": {
            "eligible": len(scores), "mean": round(mean(scores), 3) if scores else None,
            "median": round(median(scores), 3) if scores else None,
            "maximum": max(scores) if scores else None,
        },
    }


def _timeline(iaa_records: list[dict], gold_records: list[dict]) -> list[dict]:
    iaa_dates = Counter(row["completed_at"] for row in iaa_records if row["completed_at"])
    gold_dates = Counter(row["adjudicated_at"] for row in gold_records if row["adjudicated_at"])
    dates = sorted(set(iaa_dates) | set(gold_dates))
    rows, iaa_total, gold_total = [], 0, 0
    for date in dates:
        iaa_total += iaa_dates[date]
        gold_total += gold_dates[date]
        rows.append({"date": date, "iaa": iaa_total, "gold": gold_total})
    return rows


def build_dataset_eda(output: Path = DEFAULT_OUTPUT, *, gold_path: Path | None = None,
                      iaa_path: Path | None = None, manifest_path: Path | None = None) -> dict:
    pinned = gold_path is None and iaa_path is None and manifest_path is None
    paths = release_paths(verify=pinned)
    gold_path = gold_path or paths["gold"]
    iaa_path = iaa_path or paths["iaa"]
    manifest_path = manifest_path or paths["manifest"]
    manifest = [json.loads(line) for line in manifest_path.open(encoding="utf-8")]
    if len({row["image_id"] for row in manifest}) != len(manifest):
        raise ValueError("Full-dataset manifest contains duplicate image IDs")
    manifest_by_id = {row["image_id"]: row for row in manifest}
    domains_payload = json.loads(DOMAIN_PATH.read_text(encoding="utf-8"))
    domains = [{"name": name, "ids": ids} for name, ids in domains_payload.items()]
    domain_by_id = {use_case_id: name for name, ids in domains_payload.items() for use_case_id in ids}
    local_images = resolve_local_images(manifest, IMAGE_DIR)

    gold_source = json.loads(gold_path.read_text(encoding="utf-8"))
    if not isinstance(gold_source, list) or len({row["image_id"] for row in gold_source}) != len(gold_source):
        raise ValueError("Gold export must be an array with unique image IDs")
    invalid_gold_boxes = 0
    gold_records = []
    for record in gold_source:
        gold = record["gold"]
        for item in gold.get("violations", []):
            invalid_gold_boxes += int(not _valid_bbox(item.get("bbox")))
        gold_records.append({
            "image_id": record["image_id"],
            "category": manifest_by_id.get(record["image_id"], {}).get("category", "unmapped"),
            "kind": record["kind"],
            "method": record.get("edit_summary", {}).get("resolution", {}).get("method_id", record["kind"]),
            "adjudicated_at": (record.get("adjudicated_at") or "")[:10] or None,
            "plausibility": gold.get("plausibility"),
            "naturalness": gold.get("naturalness"),
            "no_violation_detected": bool(gold.get("no_violation_detected")),
            "reported": bool(gold.get("reported", False)),
            "violations": [{
                "use_case_id": item["use_case_id"],
                "name": item.get("use_case_name", f"Violation {item['use_case_id']}"),
                "domain": domain_by_id.get(item["use_case_id"], "Unmapped"),
                "bbox": item.get("bbox") if _valid_bbox(item.get("bbox")) else None,
            } for item in gold.get("violations", [])],
        })

    raw_iaa = json.loads(iaa_path.read_text(encoding="utf-8"))
    if pinned:
        validate_population(gold_source, raw_iaa, manifest, release_config()["expected"])
    if not isinstance(raw_iaa, list) or len({row["image_id"] for row in raw_iaa}) != len(raw_iaa):
        raise ValueError("IAA export must be an array with unique image IDs")
    iaa_records = []
    invalid_iaa_boxes = 0
    for row in raw_iaa:
        labels = []
        completed = []
        for index, label in enumerate(row.get("first_pass", [])):
            submitted_at = label.get("submitted_at")
            if submitted_at:
                completed.append(submitted_at[:10])
            violations = []
            for item in label.get("violations", []):
                if not _valid_bbox(item.get("bbox")):
                    invalid_iaa_boxes += 1
                    continue
                violations.append({
                    "use_case_id": item["use_case_id"],
                    "name": item.get("use_case_name", f"Violation {item['use_case_id']}"),
                    "bbox": item["bbox"],
                })
            labels.append({
                "label": f"Label {chr(65 + index)}",
                "plausibility": label.get("plausibility"),
                "naturalness": label.get("naturalness"),
                "no_violation_detected": bool(label.get("no_violation_detected")),
                "reported": bool(label.get("reported", False)),
                "violations": violations,
            })
        agreement = {
            key: row.get("agreement", {}).get(key)
            for key in ("plausibility_delta", "naturalness_delta", "violation_jaccard", "mean_bbox_iou", "reported_mismatch", "disagreement_score")
        }
        iaa_records.append({
            "image_id": row["image_id"],
            "category": manifest_by_id.get(row["image_id"], {}).get("category", "unmapped"),
            "l2_code": row.get("l2_code"),
            "n_first_pass": len(labels),
            "completed_at": max(completed) if completed else None,
            "agreement": agreement,
            "labels": labels,
            "image_available": row["image_id"] in local_images,
        })

    manifest_categories = _distribution([row.get("category", "unmapped") for row in manifest])
    artifact = {
        "schema_version": 1,
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "release": release_identity() if pinned else None,
        "sources": {
            "manifest": _source(manifest_path, len(manifest)),
            "gold": _source(gold_path, len(gold_records)),
            "iaa": _source(iaa_path, len(iaa_records)),
        },
        "progress": {
            "target_images": len(manifest),
            "iaa_ready_images": len(iaa_records),
            "gold_ready_images": len(gold_records),
            "local_images": len(local_images),
            "gold_in_iaa": len({row["image_id"] for row in gold_records} & {row["image_id"] for row in iaa_records}),
            "timeline": _timeline(iaa_records, gold_records),
        },
        "manifest_categories": manifest_categories,
        "domains": domains,
        "gold_summary": summarize_gold(gold_records, domains),
        "iaa_summary": _agreement_summary(iaa_records),
        "quality_audit": {
            "invalid_gold_boxes": invalid_gold_boxes,
            "invalid_iaa_boxes": invalid_iaa_boxes,
            "gold_missing_manifest": sum(row["category"] == "unmapped" for row in gold_records),
            "iaa_missing_manifest": sum(row["category"] == "unmapped" for row in iaa_records),
        },
        "filter_options": {
            "categories": [row["name"] for row in manifest_categories if row["count"]],
            "gold_kinds": sorted({row["kind"] for row in gold_records}),
        },
        "gold_records": gold_records,
        "iaa_records": iaa_records,
    }
    output.parent.mkdir(parents=True, exist_ok=True)
    artifact["quality_slices"] = build_quality_slices(gold_records, domains, artifact["gold_summary"]["violations"])
    output.write_text(json.dumps(artifact, indent=2), encoding="utf-8")
    return artifact


def main() -> None:
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument("--gold", type=Path)
    parser.add_argument("--iaa", type=Path)
    parser.add_argument("--manifest", type=Path)
    args = parser.parse_args()
    artifact = build_dataset_eda(args.output, gold_path=args.gold, iaa_path=args.iaa, manifest_path=args.manifest)
    print(
        f"Wrote {args.output} from {artifact['sources']['gold']['filename']} and "
        f"{artifact['sources']['iaa']['filename']}"
    )


if __name__ == "__main__":
    main()