File size: 35,059 Bytes
20f26bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
#!/usr/bin/env python3
"""Build the radiograph-dicom-ingest Hugging Face dataset folder. Nothing is uploaded.

Each row is one radiograph from GRAZPEDWRI-DX (figshare 14825193) or FracAtlas (figshare 22363012):
the unmodified source image file, the source annotation files verbatim, and normalized boxes derived
from the source YOLO labels. GRAZPEDWRI-DX PNGs are read out of the 4 GB figshare image zips with
HTTP range requests, so only the selected members are transferred.
"""
from __future__ import annotations

import argparse
import hashlib
import http.client
import io
import json
import math
import random
import shutil
import struct
import threading
import time
import urllib.request
import xml.etree.ElementTree as ET
import zipfile
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from datasets import Features, Image, List, Value, load_dataset_builder
from PIL import Image as PILImage

FIGSHARE_DOWNLOAD_URL = "https://ndownloader.figshare.com/files/{file_id}"
GRAZ_ARTICLE = {"id": 14825193, "version": 2, "doi": "10.6084/m9.figshare.14825193.v2"}
FRACATLAS_ARTICLE = {"id": 22363012, "version": 7, "doi": "10.6084/m9.figshare.22363012.v7"}
GRAZ_FILE_IDS = {
    "dataset.csv": 35026432,
    "folder_structure.zip": 34268819,
    "images_part1.zip": 34268828,
    "images_part2.zip": 34268849,
    "images_part3.zip": 34268864,
    "images_part4.zip": 34268891,
}
FRACATLAS_FILE_IDS = {"FracAtlas.zip": 65518038}
EXPECTED_MD5 = {
    "dataset.csv": "f2e996300443654faa62983b7ef1b4c1",
    "folder_structure.zip": "e484b434286428750e9c838a7ed6ada7",
    "FracAtlas.zip": "fe9da2c7c285915ebee69dfdab8fd396",
}
GRAZ_IMAGE_PARTS = ("images_part1.zip", "images_part2.zip", "images_part3.zip", "images_part4.zip")

GRAZ_YOLO_META = "yolov5/meta.yaml"
GRAZ_YOLO = "yolov5/labels/{stem}.txt"
GRAZ_VOC = "pascalvoc/{stem}.xml"
GRAZ_SUPERVISELY = "supervisely/wrist/ann/{stem}.json"
FA_CSV = "FracAtlas/dataset.csv"
FA_IMAGE = "FracAtlas/images/{folder}/{stem}.jpg"
FA_FOLDERS = {1: "Fractured", 0: "Non_fractured"}
FA_YOLO = "FracAtlas/Annotations/YOLO/{stem}.txt"
FA_YOLO_CLASSES = "FracAtlas/Annotations/YOLO/labels.txt"
FA_VOC = "FracAtlas/Annotations/PASCAL VOC/{stem}.xml"
FA_COCO = "FracAtlas/Annotations/COCO JSON/COCO_fracture_masks.json"

SPLITS = ("train", "test")
TEST_PERCENT = 15
SEED = 0
GRAZ_TRAIN_PATIENTS = 300
GRAZ_TEST_PATIENTS = 60
MIN_PATIENTS_PER_CLASS = 2
FRACATLAS_PER_CLASS = 200
BOX_TOLERANCE_PX = 1.0
YOLO_ROUNDING_SLACK_PX = 1e-3
BOX_DECIMALS = 7
MAX_SHARD_BYTES = 450_000_000
ROW_GROUP_SIZE = 50
FETCH_WORKERS = 6
FETCH_RETRIES = 5
RETRY_BACKOFF_S = 2.0
HTTP_TIMEOUT_S = 120
RANGE_DEADLINE_S = 90
RANGE_BUFFER_BYTES = 1 << 20
RANGE_CHUNK_BYTES = 1 << 16
USER_AGENT = "radiograph-dicom-ingest-builder"
EXIF_ORIENTATION_TAG = 0x0112
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
PNG_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}

FEATURES = Features({
    "image": Image(),
    "image_id": Value("string"),
    "source": Value("string"),
    "split": Value("string"),
    "patient_id": Value("string"),
    "width": Value("int32"),
    "height": Value("int32"),
    "bit_depth": Value("int32"),
    "pixel_spacing": Value("float64"),
    "laterality": Value("string"),
    "projection": Value("string"),
    "objects": {"label": List(Value("string")), "box": List(List(Value("float64"), length=4))},
    "voc_xml": Value("string"),
    "yolo_txt": Value("string"),
    "supervisely_json": Value("string"),
    "coco_annotations": Value("string"),
})


class RangedHttpFile(io.RawIOBase):
    """Read-only seekable view of a remote file that fetches only the byte ranges asked for."""

    def __init__(self, url: str):
        request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": USER_AGENT})
        with urllib.request.urlopen(request, timeout=HTTP_TIMEOUT_S) as response:
            self.url = response.geturl()
            self.size = int(response.headers["Content-Length"])
        self.position = 0

    def seekable(self) -> bool:
        return True

    def readable(self) -> bool:
        return True

    def tell(self) -> int:
        return self.position

    def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
        base = {io.SEEK_SET: 0, io.SEEK_CUR: self.position, io.SEEK_END: self.size}[whence]
        self.position = base + offset
        return self.position

    def readinto(self, buffer) -> int:
        if self.position >= self.size:
            return 0
        end = min(self.position + len(buffer), self.size) - 1
        headers = {"Range": f"bytes={self.position}-{end}", "User-Agent": USER_AGENT}
        deadline = time.monotonic() + RANGE_DEADLINE_S
        chunks = []
        with urllib.request.urlopen(urllib.request.Request(self.url, headers=headers), timeout=HTTP_TIMEOUT_S) as response:
            if response.status != 206:
                raise OSError(f"range request to {self.url} returned HTTP {response.status}, not 206")
            # A connection can trickle bytes forever without tripping the socket timeout.
            for chunk in iter(lambda: response.read(RANGE_CHUNK_BYTES), b""):
                if time.monotonic() > deadline:
                    raise TimeoutError(f"range request {headers['Range']} exceeded {RANGE_DEADLINE_S}s")
                chunks.append(chunk)
        data = b"".join(chunks)
        buffer[: len(data)] = data
        self.position += len(data)
        return len(data)


def open_remote_zip(file_id: int) -> zipfile.ZipFile:
    remote = RangedHttpFile(FIGSHARE_DOWNLOAD_URL.format(file_id=file_id))
    return zipfile.ZipFile(io.BufferedReader(remote, buffer_size=RANGE_BUFFER_BYTES))


def assign_split(key: str) -> str:
    bucket = int(hashlib.md5(key.encode("utf-8")).hexdigest(), 16) % 100
    return "test" if bucket < TEST_PERCENT else "train"


def read_text(archive: zipfile.ZipFile, member: str) -> str:
    return archive.read(member).decode("utf-8")


def verify_md5(path: Path, expected: str) -> None:
    digest = hashlib.md5()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(RANGE_BUFFER_BYTES), b""):
            digest.update(chunk)
    if digest.hexdigest() != expected:
        raise ValueError(f"{path} has md5 {digest.hexdigest()}, figshare publishes {expected}")


def parse_yolo(text: str, class_names: list[str]) -> list[tuple[str, tuple[float, ...]]]:
    """YOLO lines 'class cx cy w h' (normalized) -> (label, normalized x1, y1, x2, y2), unclipped."""
    objects = []
    for line_number, line in enumerate(text.splitlines(), start=1):
        fields = line.split()
        if not fields:
            continue
        if len(fields) != 5 or not 0 <= int(fields[0]) < len(class_names):
            raise ValueError(f"malformed YOLO line {line_number}: {line!r}")
        cx, cy, w, h = map(float, fields[1:])
        objects.append((class_names[int(fields[0])], (cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2)))
    return objects


def parse_voc(text: str) -> dict:
    root = ET.fromstring(text)
    size = root.find("size")
    size_empty = size is None or len(size) == 0
    objects = []
    for element in root.findall("object"):
        box = element.find("bndbox")
        corners = tuple(float(box.find(key).text.strip()) for key in ("xmin", "ymin", "xmax", "ymax"))
        objects.append((element.find("name").text.strip(), corners))
    padded = any(node.text and node.text.strip() and node.text != node.text.strip() for node in root.iter())
    return {
        "objects": objects,
        "size": None if size_empty else (int(size.find("width").text), int(size.find("height").text)),
        "size_empty": size_empty,
        "padded_text": padded,
    }


def compare_boxes(reference: list, candidate: list) -> tuple[bool, float | None]:
    """One-to-one greedy matching within each label; returns (label multisets equal, worst abs diff)."""
    if Counter(label for label, _ in reference) != Counter(label for label, _ in candidate):
        return False, None
    pairs = sorted(
        (max(abs(a - b) for a, b in zip(ref_box, cand_box)), i, j)
        for i, (ref_label, ref_box) in enumerate(reference)
        for j, (cand_label, cand_box) in enumerate(candidate)
        if ref_label == cand_label
    )
    used_ref, used_cand, worst = set(), set(), 0.0
    for diff, i, j in pairs:
        if i in used_ref or j in used_cand:
            continue
        used_ref.add(i)
        used_cand.add(j)
        worst = max(worst, diff)
    return True, worst


def to_pixels(objects: list, width: int, height: int) -> list:
    return [(label, (x1 * width, y1 * height, x2 * width, y2 * height)) for label, (x1, y1, x2, y2) in objects]


def check_yolo_voc(yolo_objects: list, voc_xml: str, width: int, height: int) -> dict:
    voc = parse_voc(voc_xml)
    labels_equal, max_diff = compare_boxes(to_pixels(yolo_objects, width, height), voc["objects"])
    within = labels_equal and max_diff <= BOX_TOLERANCE_PX + YOLO_ROUNDING_SLACK_PX
    return {
        "voc_labels_equal": labels_equal,
        "voc_max_diff_px": max_diff,
        "voc_within_tolerance": within,
        "voc_size": voc["size"],
        "voc_size_empty": voc["size_empty"],
        "voc_padded_text": voc["padded_text"],
        "voc_labels": sorted(label for label, _ in voc["objects"]),
        "yolo_labels": sorted(label for label, _ in yolo_objects),
    }


def to_objects(yolo_objects: list) -> tuple[dict, int]:
    boxes, clipped = [], 0
    for _, corners in yolo_objects:
        bounded = [min(1.0, max(0.0, value)) for value in corners]
        clipped += bounded != list(corners)
        boxes.append([round(value, BOX_DECIMALS) for value in bounded])
    return {"label": [label for label, _ in yolo_objects], "box": boxes}, clipped


def describe_image(data: bytes) -> dict:
    with PILImage.open(io.BytesIO(data)) as image:
        orientation = image.getexif().get(EXIF_ORIENTATION_TAG)
        if data.startswith(PNG_SIGNATURE):
            width, height, bit_depth, color_type = struct.unpack(">IIBB", data[16:26])
            channels = PNG_CHANNELS[color_type]
        elif image.format == "JPEG":
            (width, height), bit_depth, channels = image.size, image.bits, len(image.getbands())
        else:
            raise ValueError(f"unexpected image format {image.format}")
        if image.size != (width, height):
            raise ValueError(f"decoded size {image.size} differs from header size {(width, height)}")
        max_value = int(np.asarray(image).max())
    return {
        "width": width,
        "height": height,
        "bit_depth": bit_depth,
        "channels": channels,
        "mode": image.mode,
        "exif_orientation": orientation,
        "max_value": max_value,
        "sha256": hashlib.sha256(data).hexdigest(),
    }


def read_graz_class_names(label_zip: zipfile.ZipFile) -> list[str]:
    meta = read_text(label_zip, GRAZ_YOLO_META)
    return [line[2:].strip() for line in meta.splitlines() if line.startswith("- ")]


def select_graz(csv: pd.DataFrame, label_zip: zipfile.ZipFile, class_names: list[str]) -> tuple[list, list]:
    patient_ids = sorted({int(patient) for patient in csv["patient_id"]})
    pools = {split: [p for p in patient_ids if assign_split(str(p)) == split] for split in SPLITS}
    rng = random.Random(SEED)
    chosen = {
        "train": set(rng.sample(pools["train"], GRAZ_TRAIN_PATIENTS)),
        "test": set(rng.sample(pools["test"], GRAZ_TEST_PATIENTS)),
    }
    classes_by_patient = defaultdict(set)
    for stem, patient in zip(csv["filestem"], csv["patient_id"]):
        supervisely = json.loads(read_text(label_zip, GRAZ_SUPERVISELY.format(stem=stem)))
        classes_by_patient[int(patient)] |= {obj["classTitle"] for obj in supervisely["objects"]}
    topups = []
    for class_name in sorted(class_names):
        for split in SPLITS:
            have = sum(class_name in classes_by_patient[p] for p in chosen[split])
            need = MIN_PATIENTS_PER_CLASS - have
            if need <= 0:
                continue
            candidates = [p for p in pools[split] if class_name in classes_by_patient[p] and p not in chosen[split]]
            added = rng.sample(candidates, min(need, len(candidates)))
            chosen[split] |= set(added)
            topups.append({"class": class_name, "split": split, "had": have, "available": len(candidates), "added": sorted(added)})
    records = []
    for row in csv.sort_values("filestem").itertuples(index=False):
        patient = int(row.patient_id)
        split = assign_split(str(patient))
        if patient not in chosen[split]:
            continue
        records.append({
            "image_id": row.filestem,
            "source": "graz",
            "split": split,
            "patient_id": str(patient),
            "pixel_spacing": float(row.pixel_spacing) if row.pixel_spacing else None,
            "laterality": row.laterality or None,
            "projection": row.projection or None,
            "fracture_flag": row.fracture_visible == "1",
        })
    return records, topups


def find_exclusion_reason(data: bytes) -> str | None:
    """Reasons a FracAtlas JPEG cannot serve as a stored-frame, decodable ground-truth image."""
    with PILImage.open(io.BytesIO(data)) as image:
        orientation = image.getexif().get(EXIF_ORIENTATION_TAG)
        if orientation not in (None, 1):
            return f"exif_orientation={orientation}"
        try:
            image.load()
        except OSError as error:
            return f"decode_error: {error}"
    return None


def select_fracatlas(archive: zipfile.ZipFile) -> tuple[list, list]:
    csv = pd.read_csv(io.BytesIO(archive.read(FA_CSV)))
    candidates, excluded = {1: [], 0: []}, []
    for image_name, fractured in zip(csv["image_id"], csv["fractured"]):
        stem = Path(image_name).stem
        reason = find_exclusion_reason(archive.read(FA_IMAGE.format(folder=FA_FOLDERS[fractured], stem=stem)))
        if reason:
            excluded.append({"image_id": stem, "fractured": int(fractured), "reason": reason})
            continue
        candidates[int(fractured)].append(stem)
    rng = random.Random(SEED)
    records = []
    for fractured in (1, 0):
        for stem in sorted(rng.sample(sorted(candidates[fractured]), FRACATLAS_PER_CLASS)):
            records.append({
                "image_id": stem,
                "source": "fracatlas",
                "split": assign_split(stem),
                "patient_id": stem,
                "pixel_spacing": None,
                "laterality": None,
                "projection": None,
                "fracture_flag": fractured == 1,
                "member": FA_IMAGE.format(folder=FA_FOLDERS[fractured], stem=stem),
            })
    return sorted(records, key=lambda record: record["image_id"]), excluded


def list_graz_image_members() -> dict[str, tuple[str, int, int]]:
    members = {}
    for part in GRAZ_IMAGE_PARTS:
        with open_remote_zip(GRAZ_FILE_IDS[part]) as archive:
            for info in archive.infolist():
                members[info.filename] = (part, GRAZ_FILE_IDS[part], info.file_size)
    return members


def fetch_graz_images(records: list, members: dict, cache_dir: Path) -> None:
    cache_dir.mkdir(parents=True, exist_ok=True)
    missing = [r["image_id"] for r in records
               if not (cache_dir / f"{r['image_id']}.png").is_file()
               or (cache_dir / f"{r['image_id']}.png").stat().st_size != members[f"{r['image_id']}.png"][2]]
    local = threading.local()

    def fetch(stem: str) -> None:
        part, file_id, _ = members[f"{stem}.png"]
        zips = local.__dict__.setdefault("zips", {})
        last_error = None
        for attempt in range(FETCH_RETRIES):
            try:
                if file_id not in zips:
                    zips[file_id] = open_remote_zip(file_id)
                data = zips[file_id].read(f"{stem}.png")
                partial = cache_dir / f"{stem}.png.part"
                partial.write_bytes(data)
                partial.replace(cache_dir / f"{stem}.png")
                return
            except (OSError, zipfile.BadZipFile, http.client.HTTPException) as error:
                zips.pop(file_id, None)
                last_error = error
                time.sleep(RETRY_BACKOFF_S * 2 ** attempt)
        raise RuntimeError(f"could not fetch {stem}.png from {part} (figshare file {file_id}): {last_error}")

    print(f"fetching {len(missing)} GRAZPEDWRI-DX PNGs ({len(records) - len(missing)} already cached)", flush=True)
    with ThreadPoolExecutor(FETCH_WORKERS) as pool:
        for done, _ in enumerate(pool.map(fetch, missing), start=1):
            if done % 100 == 0:
                print(f"  fetched {done}/{len(missing)}", flush=True)


class SourceReader:
    """Loads image bytes and annotation text for selected records and turns them into dataset rows."""

    def __init__(self, label_zip: zipfile.ZipFile, fracatlas_zip: zipfile.ZipFile, graz_cache: Path):
        self.label_zip = label_zip
        self.fracatlas_zip = fracatlas_zip
        self.graz_cache = graz_cache
        self.graz_class_names = read_graz_class_names(label_zip)
        self.fa_class_names = read_text(fracatlas_zip, FA_YOLO_CLASSES).splitlines()
        coco = json.loads(read_text(fracatlas_zip, FA_COCO))
        coco_images = {image["id"]: image for image in coco["images"]}
        self.coco_by_file = {image["file_name"]: {"image": image, "annotations": []} for image in coco["images"]}
        for annotation in coco["annotations"]:
            self.coco_by_file[coco_images[annotation["image_id"]]["file_name"]]["annotations"].append(annotation)

    def image_size_bytes(self, record: dict) -> int:
        if record["source"] == "graz":
            return (self.graz_cache / f"{record['image_id']}.png").stat().st_size
        return self.fracatlas_zip.getinfo(record["member"]).file_size

    def build(self, record: dict) -> tuple[dict, dict]:
        if record["source"] == "graz":
            return self._build_graz(record)
        return self._build_fracatlas(record)

    def _build_graz(self, record: dict) -> tuple[dict, dict]:
        stem = record["image_id"]
        image_bytes = (self.graz_cache / f"{stem}.png").read_bytes()
        info = describe_image(image_bytes)
        yolo_txt = read_text(self.label_zip, GRAZ_YOLO.format(stem=stem))
        voc_xml = read_text(self.label_zip, GRAZ_VOC.format(stem=stem))
        supervisely_json = read_text(self.label_zip, GRAZ_SUPERVISELY.format(stem=stem))
        supervisely = json.loads(supervisely_json)
        yolo_objects = parse_yolo(yolo_txt, self.graz_class_names)
        summary = {
            **check_yolo_voc(yolo_objects, voc_xml, info["width"], info["height"]),
            "supervisely_size_matches": (supervisely["size"]["width"], supervisely["size"]["height"]) == (info["width"], info["height"]),
            "supervisely_classes": [obj["classTitle"] for obj in supervisely["objects"]],
            "supervisely_polygons": [obj["classTitle"] for obj in supervisely["objects"] if len(obj["points"]["exterior"]) > 2],
        }
        texts = {"voc_xml": voc_xml, "yolo_txt": yolo_txt, "supervisely_json": supervisely_json, "coco_annotations": None}
        return self._assemble(record, image_bytes, "png", info, yolo_objects, texts, summary)

    def _build_fracatlas(self, record: dict) -> tuple[dict, dict]:
        stem = record["image_id"]
        image_bytes = self.fracatlas_zip.read(record["member"])
        info = describe_image(image_bytes)
        yolo_txt = read_text(self.fracatlas_zip, FA_YOLO.format(stem=stem))
        voc_xml = read_text(self.fracatlas_zip, FA_VOC.format(stem=stem))
        yolo_objects = parse_yolo(yolo_txt, self.fa_class_names)
        coco = self.coco_by_file.get(f"{stem}.jpg", {"image": None, "annotations": []})
        coco_boxes = [("fractured", (x, y, x + w, y + h)) for x, y, w, h in (a["bbox"] for a in coco["annotations"])]
        coco_equal, coco_diff = compare_boxes(to_pixels(yolo_objects, info["width"], info["height"]), coco_boxes)
        voc_rounding = Counter(
            "round" if v == round(c) else "floor" if v == math.floor(c) else "other"
            for (_, voc_box), (_, coco_box) in zip(sorted(parse_voc(voc_xml)["objects"]), sorted(coco_boxes))
            for v, c in zip(voc_box, coco_box)
        )
        coco_size = None if coco["image"] is None else (coco["image"]["width"], coco["image"]["height"])
        summary = {
            **check_yolo_voc(yolo_objects, voc_xml, info["width"], info["height"]),
            "coco_labels_equal": coco_equal,
            "coco_max_diff_px": coco_diff,
            "coco_size_matches": coco_size in (None, (info["width"], info["height"])),
            "voc_vs_coco_rounding": dict(voc_rounding),
        }
        texts = {"voc_xml": voc_xml, "yolo_txt": yolo_txt, "supervisely_json": None,
                 "coco_annotations": json.dumps(coco["annotations"])}
        return self._assemble(record, image_bytes, "jpg", info, yolo_objects, texts, summary)

    @staticmethod
    def _assemble(record, image_bytes, extension, info, yolo_objects, texts, checks) -> tuple[dict, dict]:
        objects, clipped = to_objects(yolo_objects)
        row = {
            "image": {"bytes": image_bytes, "path": f"{record['image_id']}.{extension}"},
            "image_id": record["image_id"],
            "source": record["source"],
            "split": record["split"],
            "patient_id": record["patient_id"],
            "width": info["width"],
            "height": info["height"],
            "bit_depth": info["bit_depth"],
            "pixel_spacing": record["pixel_spacing"],
            "laterality": record["laterality"],
            "projection": record["projection"],
            "objects": objects,
            **texts,
        }
        summary = {
            **{key: record[key] for key in ("image_id", "source", "split", "patient_id", "fracture_flag", "laterality", "projection", "pixel_spacing")},
            **info,
            **checks,
            "labels": objects["label"],
            "clipped_boxes": clipped,
            "image_bytes": len(image_bytes),
        }
        return row, summary


def plan_shards(sizes: list[int]) -> list[int]:
    total = sum(sizes)
    shard_count = max(1, math.ceil(total / MAX_SHARD_BYTES))
    offsets = np.cumsum([0] + sizes[:-1])
    return [min(shard_count - 1, int(offset * shard_count // total)) for offset in offsets]


def write_split(split: str, records: list, reader: SourceReader, data_dir: Path) -> list[dict]:
    assignments = plan_shards([reader.image_size_bytes(record) for record in records])
    shard_count = max(assignments) + 1
    summaries = []
    for shard in range(shard_count):
        path = data_dir / f"{split}-{shard:05d}-of-{shard_count:05d}.parquet"
        shard_records = [record for record, assigned in zip(records, assignments) if assigned == shard]
        with pq.ParquetWriter(path, FEATURES.arrow_schema) as writer:
            for start in range(0, len(shard_records), ROW_GROUP_SIZE):
                built = [reader.build(record) for record in shard_records[start:start + ROW_GROUP_SIZE]]
                rows = [FEATURES.encode_example(row) for row, _ in built]
                writer.write_table(pa.Table.from_pylist(rows, schema=FEATURES.arrow_schema), row_group_size=ROW_GROUP_SIZE)
                summaries.extend({**summary, "shard": path.name} for _, summary in built)
        print(f"  wrote {path.name}: {len(shard_records)} rows, {path.stat().st_size / 1e6:.1f} MB", flush=True)
    return summaries


def audit_graz_label_files(label_zip: zipfile.ZipFile, class_names: list[str]) -> dict:
    """VOC vs YOLO over every GRAZPEDWRI-DX label file, using the image size recorded by Supervisely."""
    prefix = GRAZ_YOLO.split("{")[0]
    stems = sorted(name[len(prefix):-4] for name in label_zip.namelist() if name.startswith(prefix) and name.endswith(".txt"))
    label_mismatches, box_mismatches, worst, size_empty, padded = [], [], 0.0, 0, 0
    for stem in stems:
        supervisely = json.loads(read_text(label_zip, GRAZ_SUPERVISELY.format(stem=stem)))
        yolo_objects = parse_yolo(read_text(label_zip, GRAZ_YOLO.format(stem=stem)), class_names)
        check = check_yolo_voc(yolo_objects, read_text(label_zip, GRAZ_VOC.format(stem=stem)),
                               supervisely["size"]["width"], supervisely["size"]["height"])
        size_empty += check["voc_size_empty"]
        padded += check["voc_padded_text"]
        if not check["voc_labels_equal"]:
            label_mismatches.append({"image_id": stem, "yolo": check["yolo_labels"], "voc": check["voc_labels"]})
            continue
        worst = max(worst, check["voc_max_diff_px"])
        if check["voc_max_diff_px"] > BOX_TOLERANCE_PX:
            box_mismatches.append({"image_id": stem, "max_diff_px": round(check["voc_max_diff_px"], 6)})
    return {"files": len(stems), "voc_size_empty": size_empty, "voc_padded_text": padded,
            "label_mismatches": label_mismatches, "box_diff_over_1px": box_mismatches, "max_diff_px": round(worst, 6)}


def audit_fracatlas_archive(archive: zipfile.ZipFile) -> dict:
    names = archive.namelist()
    by_basename = defaultdict(list)
    for name in names:
        if "/images/" in name and name.endswith(".jpg"):
            by_basename[Path(name).name].append(name)
    duplicates = [
        {"image": base, "members": paths, "identical": len({archive.getinfo(p).CRC for p in paths}) == 1}
        for base, paths in sorted(by_basename.items()) if len(paths) > 1
    ]
    csv = pd.read_csv(io.BytesIO(archive.read(FA_CSV)))
    folder_counts = Counter(Path(p).parent.name for paths in by_basename.values() for p in paths)
    return {"duplicate_image_members": duplicates, "csv_rows": len(csv),
            "csv_fractured": int(csv["fractured"].sum()), "image_members_per_folder": dict(folder_counts),
            "yolo_files": sum(1 for n in names if n.startswith(FA_YOLO.split("{")[0]) and n.endswith(".txt")),
            "voc_files": sum(1 for n in names if n.startswith(FA_VOC.split("{")[0]) and n.endswith(".xml"))}


def compute_stats(summaries: list[dict], data_dir: Path) -> dict:
    frame = pd.DataFrame(summaries)
    group = frame.groupby(["split", "source"])
    per_class = Counter((s["split"], s["source"], label) for s in summaries for label in s["labels"])
    images_with_class = Counter((s["split"], s["source"], label) for s in summaries for label in set(s["labels"]))
    graz = frame[frame.source == "graz"]
    fracture_label = {"graz": "fracture", "fracatlas": "fractured"}
    flag_box_disagree = [s["image_id"] for s in summaries if s["fracture_flag"] != (fracture_label[s["source"]] in s["labels"])]
    return {
        "rows": {f"{split}/{source}": int(n) for (split, source), n in group.size().items()},
        "patients": {f"{split}/{source}": int(n) for (split, source), n in group["patient_id"].nunique().items()},
        "fracture_flag_true": {f"{split}/{source}": int(n) for (split, source), n in group["fracture_flag"].sum().items()},
        "instances": {f"{split}/{source}/{label}": n for (split, source, label), n in sorted(per_class.items())},
        "images_with_class": {f"{split}/{source}/{label}": n for (split, source, label), n in sorted(images_with_class.items())},
        "supervisely_objects": dict(Counter(c for s in summaries if s["source"] == "graz" for c in s["supervisely_classes"])),
        "supervisely_polygons": dict(Counter(c for s in summaries if s["source"] == "graz" for c in s["supervisely_polygons"])),
        "bit_depth": {f"{source}/{depth}": int(n) for (source, depth), n in frame.groupby(["source", "bit_depth"]).size().items()},
        "mode": {f"{source}/{mode}": int(n) for (source, mode), n in frame.groupby(["source", "mode"]).size().items()},
        "max_value_range": {source: [int(g.max_value.min()), int(g.max_value.max())] for source, g in frame.groupby("source")},
        "width_range": {source: [int(g.width.min()), int(g.width.max())] for source, g in frame.groupby("source")},
        "height_range": {source: [int(g.height.min()), int(g.height.max())] for source, g in frame.groupby("source")},
        "pixel_spacing": {str(k): int(v) for k, v in graz.pixel_spacing.value_counts().items()},
        "laterality": {str(k): int(v) for k, v in graz.laterality.value_counts().items()},
        "projection": {str(k): int(v) for k, v in graz.projection.value_counts().items()},
        "exif_orientation_present": int(frame.exif_orientation.notna().sum()),
        "voc_label_mismatches": [s["image_id"] for s in summaries if not s["voc_labels_equal"]],
        "voc_box_over_tolerance": [s["image_id"] for s in summaries if s["voc_labels_equal"] and not s["voc_within_tolerance"]],
        "voc_max_diff_px": {source: round(float(g.voc_max_diff_px.max()), 6) for source, g in frame.groupby("source")},
        "voc_size_empty": {source: int(g.voc_size_empty.sum()) for source, g in frame.groupby("source")},
        "voc_padded_text": {source: int(g.voc_padded_text.sum()) for source, g in frame.groupby("source")},
        "supervisely_size_mismatches": [s["image_id"] for s in summaries if s["source"] == "graz" and not s["supervisely_size_matches"]],
        "coco_label_mismatches": [s["image_id"] for s in summaries if s["source"] == "fracatlas" and not s["coco_labels_equal"]],
        "coco_max_diff_px": round(float(frame[frame.source == "fracatlas"].coco_max_diff_px.max()), 6),
        "coco_size_mismatches": [s["image_id"] for s in summaries if s["source"] == "fracatlas" and not s["coco_size_matches"]],
        "voc_vs_coco_rounding": dict(sum((Counter(s["voc_vs_coco_rounding"]) for s in summaries if s["source"] == "fracatlas"), Counter())),
        "fracture_flag_box_disagreements": flag_box_disagree,
        "clipped_boxes": int(frame.clipped_boxes.sum()),
        "image_bytes": {source: int(g.image_bytes.sum()) for source, g in frame.groupby("source")},
        "shards": {path.name: path.stat().st_size for path in sorted(data_dir.glob("*.parquet"))},
    }


def verify_row(row: dict, split: str, expected: dict, decoder: Image) -> None:
    source = expected[row["image_id"]]
    if hashlib.sha256(row["image"]["bytes"]).hexdigest() != source["sha256"]:
        raise ValueError(f"{row['image_id']}: stored bytes differ from the source file")
    with decoder.decode_example(row["image"]) as decoded:
        decoded_size = decoded.size
    if decoded_size != (row["width"], row["height"]) or row["split"] != split:
        raise ValueError(f"{row['image_id']}: decoded size {decoded_size} or split {row['split']} mismatch")
    if any(not (0 <= x1 <= x2 <= 1 and 0 <= y1 <= y2 <= 1) for x1, y1, x2, y2 in row["objects"]["box"]):
        raise ValueError(f"{row['image_id']}: box outside the unit square")


def verify_output(out_dir: Path, summaries: list[dict]) -> dict:
    """Resolve splits the way `datasets` does, then stream every row group and check each row."""
    data_files = load_dataset_builder(str(out_dir)).config.data_files
    expected = {s["image_id"]: s for s in summaries}
    decoder = Image()
    seen = Counter()
    for split in SPLITS:
        for path in data_files[split]:
            parquet = pq.ParquetFile(path)
            if Features.from_arrow_schema(parquet.schema_arrow) != FEATURES:
                raise ValueError(f"{path}: stored features differ from the declared features")
            for batch in parquet.iter_batches(batch_size=ROW_GROUP_SIZE):
                for row in batch.to_pylist():
                    verify_row(row, split, expected, decoder)
                    seen[(split, row["source"])] += 1
    if sum(seen.values()) != len(expected):
        raise ValueError(f"read back {sum(seen.values())} rows, wrote {len(expected)}")
    return {f"{split}/{source}": n for (split, source), n in sorted(seen.items())}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--graz-csv", type=Path, default=Path("/tmp/rr-src/graz_dataset.csv"))
    parser.add_argument("--graz-labels", type=Path, default=Path("/tmp/rr-src/graz_folder.zip"))
    parser.add_argument("--fracatlas-zip", type=Path, default=Path("/tmp/rfd/src/FracAtlas.zip"))
    parser.add_argument("--work", type=Path, default=Path("/tmp/rfd/work"))
    parser.add_argument("--out", type=Path, default=Path("/tmp/rfd/hf"))
    parser.add_argument("--verify-only", action="store_true", help="re-read --out and check it against --work/rows.jsonl")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    if args.verify_only:
        summaries = [json.loads(line) for line in (args.work / "rows.jsonl").read_text().splitlines()]
        print(json.dumps(verify_output(args.out, summaries)))
        return
    for path, name in ((args.graz_csv, "dataset.csv"), (args.graz_labels, "folder_structure.zip"), (args.fracatlas_zip, "FracAtlas.zip")):
        verify_md5(path, EXPECTED_MD5[name])
    args.work.mkdir(parents=True, exist_ok=True)
    label_zip = zipfile.ZipFile(args.graz_labels)
    fracatlas_zip = zipfile.ZipFile(args.fracatlas_zip)
    graz_csv = pd.read_csv(args.graz_csv, encoding="utf-8-sig", dtype=str, keep_default_na=False)

    graz_records, topups = select_graz(graz_csv, label_zip, read_graz_class_names(label_zip))
    fa_records, fa_excluded = select_fracatlas(fracatlas_zip)
    fetch_graz_images(graz_records, list_graz_image_members(), args.work / "graz_png")

    reader = SourceReader(label_zip, fracatlas_zip, args.work / "graz_png")
    data_dir, scripts_dir = args.out / "data", args.out / "scripts"
    for generated in (data_dir, scripts_dir):
        shutil.rmtree(generated, ignore_errors=True)
        generated.mkdir(parents=True)
    summaries = []
    for split in SPLITS:
        split_records = [r for r in graz_records + fa_records if r["split"] == split]
        summaries.extend(write_split(split, split_records, reader, data_dir))

    report = {
        "selection": {"graz_topups": topups, "fracatlas_excluded": fa_excluded},
        "stats": compute_stats(summaries, data_dir),
        "source_audit": {"graz": audit_graz_label_files(label_zip, reader.graz_class_names),
                         "fracatlas": audit_fracatlas_archive(fracatlas_zip)},
    }
    shutil.copy2(Path(__file__), scripts_dir / "build_dataset.py")
    (args.work / "report.json").write_text(json.dumps(report, indent=1, default=str))
    (args.work / "rows.jsonl").write_text("\n".join(json.dumps(s, default=str) for s in summaries) + "\n")
    report["verified_rows"] = verify_output(args.out, summaries)
    (args.work / "report.json").write_text(json.dumps(report, indent=1, default=str))
    print(json.dumps(report["verified_rows"]))


if __name__ == "__main__":
    main()