"""Split the QC figures out of the dataset annotation archives. Datasets/.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/.zip annotations only Datasets/_fig.zip the figures, when they fit in one file Datasets/_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(/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 //, but BraTS24 and MSD carry a # subset level in between (BraTS24/BraTS24-GLI//). 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 .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())