File size: 10,070 Bytes
b040668
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Split the QC figures out of the dataset annotation archives.

Datasets/<name>.zip used to carry the annotations AND the per-slice QC figures in
one file. The figures are ~99% of the payload -- 298 GB of PNG against 3 GB of
annotation -- MedVision.py never reads them, and at v1.4.0 two archives outgrew
HuggingFace's 50 GB per-file limit purely because of them:

    BraTS24.zip  72.58 GB   (71.89 GB figures,  0.42 GB annotations)
    MSD.zip      51.35 GB   (50.97 GB figures,  0.28 GB annotations)

Both were rejected with HTTP 422 and took the whole push down with them.

This rewrites every figure-bearing archive into

    Datasets/<name>.zip              annotations only
    Datasets/<name>_fig.zip          the figures, when they fit in one file
    Datasets/<name>_fig.partNN.zip   ...otherwise, sharded under --shard-bytes

Sharding is needed because two of the figure sets are themselves over the limit.
The shards are independent, self-contained archives -- NOT `zip -s` split volumes,
which are useless on their own and need reassembly before they can be read.

Arcnames are preserved EXACTLY. MedVision.py extracts the dataset archive with
`extractall(<data_dir>/Datasets)`, so restoring the figures is the same call on
the figure archives: every entry lands back where it is today. The archive is the
position map, so there is no path rewriting to get wrong and re-running is
harmless. That is the whole reason the split is done at the archive level rather
than by moving directories around after extraction.

A zip with no figure entries is left untouched, so a second run is a no-op and
costs nothing but a central-directory read.

Usage:
    python scripts/split_qc_figures.py --datasets-dir Datasets
    python scripts/split_qc_figures.py --datasets-dir Datasets --dry-run
    python scripts/split_qc_figures.py --datasets-dir Datasets --workers 4
"""

import argparse
import concurrent.futures
import os
import re
import shutil
import sys
import zipfile

# A path COMPONENT that is a figure directory: 'Landmarks-Label1-fig-v1.4.0',
# 'Landmarks-fig', 'Landmarks-fig-w-projection'. The leading hyphen is what keeps
# this off innocent names -- 'config' contains 'fig' but not '-fig'. Matched at
# ANY depth: most datasets nest <dataset>/<figdir>/, but BraTS24 and MSD carry a
# subset level in between (BraTS24/BraTS24-GLI/<figdir>/).
FIG_COMPONENT = re.compile(r"-fig(?:-|$)")

# HuggingFace rejects any single file over 50 GB (decimal). 40 GB leaves room and
# keeps a shard downloadable in one sitting. Note the units: MSD's figure set is
# 47.5 GiB, which reads as "under 50" but is 51.0 GB and was rejected.
DEFAULT_SHARD_BYTES = 40_000_000_000


def is_figure_entry(name):
    """True when any component of the archive path is a QC-figure directory."""
    return any(FIG_COMPONENT.search(c) for c in name.split("/"))


def plan_shards(infos, shard_bytes):
    """Greedily pack figure entries into shards of at most `shard_bytes`.

    Packing is by stored (compressed) size, which for these archives is also the
    on-disk size: the entries are PNG, so 2.04M of 2.21M are already ZIP_STORED
    and deflate buys 0.3% on the rest. An entry larger than shard_bytes still
    gets its own shard rather than being dropped.
    """
    shards = [[]]
    used = 0
    for info in infos:
        size = info.compress_size
        if shards[-1] and used + size > shard_bytes:
            shards.append([])
            used = 0
        shards[-1].append(info)
        used += size
    return [s for s in shards if s]


def copy_entries(src_zip, infos, out_path):
    """Copy `infos` from an open ZipFile into a new archive at `out_path`.

    Entries are streamed rather than read whole, and the original ZipInfo is
    reused so compress_type, timestamp and permission bits survive. CRC and sizes
    are recomputed by zipfile as it writes, which is what makes the verify pass
    below meaningful rather than circular.
    """
    with zipfile.ZipFile(out_path, "w", allowZip64=True) as zout:
        for info in infos:
            if info.is_dir():
                # Streaming a directory entry through open(mode="w") is not
                # meaningful; write the zero-length record directly.
                zout.writestr(info, b"")
                continue
            with src_zip.open(info) as src, zout.open(info, "w") as dst:
                shutil.copyfileobj(src, dst, 1024 * 1024)


def verify(source_index, out_paths):
    """Assert the outputs together reproduce the source archive exactly.

    Compares name -> (CRC, uncompressed size) across the union of the outputs
    against the index taken from the source before it was rewritten. Catches a
    dropped entry, a duplicated entry, a truncated stream and a misrouted figure
    in one check.
    """
    seen = {}
    for path in out_paths:
        with zipfile.ZipFile(path) as zf:
            for info in zf.infolist():
                if info.filename in seen:
                    raise AssertionError(
                        f"entry duplicated across outputs: {info.filename}"
                    )
                seen[info.filename] = (info.CRC, info.file_size)

    if seen != source_index:
        missing = set(source_index) - set(seen)
        extra = set(seen) - set(source_index)
        changed = [
            n for n in set(seen) & set(source_index) if seen[n] != source_index[n]
        ]
        raise AssertionError(
            f"outputs do not reproduce the source: "
            f"{len(missing)} missing, {len(extra)} unexpected, {len(changed)} corrupt"
            + (f" | first missing: {sorted(missing)[:3]}" if missing else "")
            + (f" | first corrupt: {sorted(changed)[:3]}" if changed else "")
        )


def split_one(zip_path, shard_bytes, dry_run):
    """Split one dataset archive. Returns a one-line report."""
    name = os.path.basename(zip_path)[: -len(".zip")]
    out_dir = os.path.dirname(zip_path)

    with zipfile.ZipFile(zip_path) as zf:
        infos = zf.infolist()
        fig = [i for i in infos if is_figure_entry(i.filename)]
        keep = [i for i in infos if not is_figure_entry(i.filename)]

        if not fig:
            return f"{name:<24} no figures, untouched"

        fig_bytes = sum(i.compress_size for i in fig)
        keep_bytes = sum(i.compress_size for i in keep)
        shards = plan_shards(fig, shard_bytes)

        if len(shards) == 1:
            shard_names = [f"{name}_fig.zip"]
        else:
            shard_names = [
                f"{name}_fig.part{n:02d}.zip" for n in range(1, len(shards) + 1)
            ]

        if dry_run:
            return (
                f"{name:<24} {len(keep):>7} keep ({keep_bytes/1e9:6.2f} GB) | "
                f"{len(fig):>8} fig ({fig_bytes/1e9:6.2f} GB) -> {', '.join(shard_names)}"
            )

        # Index the source before anything is written, so verification compares
        # against the archive as it was, not against what we just produced.
        source_index = {i.filename: (i.CRC, i.file_size) for i in infos}

        # Everything is staged to .tmp and only swapped in once the whole set
        # verifies. A crash mid-run therefore leaves the original archive intact.
        tmp_dataset = os.path.join(out_dir, f"{name}.zip.tmp")
        tmp_shards = [os.path.join(out_dir, f"{s}.tmp") for s in shard_names]
        try:
            copy_entries(zf, keep, tmp_dataset)
            for shard_infos, tmp_shard in zip(shards, tmp_shards):
                copy_entries(zf, shard_infos, tmp_shard)
            verify(source_index, [tmp_dataset] + tmp_shards)
        except BaseException:
            for p in [tmp_dataset] + tmp_shards:
                if os.path.exists(p):
                    os.remove(p)
            raise

    os.replace(tmp_dataset, zip_path)
    for tmp_shard, shard_name in zip(tmp_shards, shard_names):
        os.replace(tmp_shard, os.path.join(out_dir, shard_name))

    produced = " ".join(
        f"{s}={os.path.getsize(os.path.join(out_dir, s))/1e9:.2f}GB" for s in shard_names
    )
    return (
        f"{name:<24} {os.path.getsize(zip_path)/1e9:6.2f} GB annotations | {produced}"
    )


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument(
        "--datasets-dir", required=True, help="directory holding <name>.zip"
    )
    ap.add_argument(
        "--shard-bytes",
        type=int,
        default=DEFAULT_SHARD_BYTES,
        help=f"max bytes per figure shard (default {DEFAULT_SHARD_BYTES})",
    )
    ap.add_argument("--dry-run", action="store_true", help="report, write nothing")
    ap.add_argument(
        "--workers", type=int, default=1, help="datasets to process in parallel"
    )
    args = ap.parse_args(argv)

    if args.shard_bytes > 50_000_000_000:
        ap.error("--shard-bytes above HuggingFace's 50 GB per-file limit")

    zips = sorted(
        os.path.join(args.datasets_dir, f)
        for f in os.listdir(args.datasets_dir)
        if f.endswith(".zip") and "_fig" not in f
    )
    if not zips:
        ap.error(f"no dataset archives found in {args.datasets_dir}")

    failures = 0
    if args.workers > 1 and not args.dry_run:
        with concurrent.futures.ProcessPoolExecutor(args.workers) as pool:
            futures = {
                pool.submit(split_one, z, args.shard_bytes, args.dry_run): z
                for z in zips
            }
            for fut in concurrent.futures.as_completed(futures):
                try:
                    print(fut.result(), flush=True)
                except Exception as e:
                    failures += 1
                    print(f"FAILED {os.path.basename(futures[fut])}: {e}", flush=True)
    else:
        for z in zips:
            try:
                print(split_one(z, args.shard_bytes, args.dry_run), flush=True)
            except Exception as e:
                failures += 1
                print(f"FAILED {os.path.basename(z)}: {e}", flush=True)

    return 1 if failures else 0


if __name__ == "__main__":
    sys.exit(main())