from __future__ import annotations import argparse import gzip import hashlib import json import struct from pathlib import Path import numpy as np def main() -> int: parser = argparse.ArgumentParser(description="Export UFO-MNIST NPZ arrays to MNIST-style IDX gzip files.") parser.add_argument("--dataset", type=Path, default=Path("data/ufo_mnist_v1/ufo_mnist_28x28.npz")) parser.add_argument("--output", type=Path, default=Path("data/ufo")) parser.add_argument("--checksums", type=Path, default=Path("data/ufo_mnist_v1/checksums.json")) args = parser.parse_args() data = np.load(args.dataset) args.output.mkdir(parents=True, exist_ok=True) files = { "train-images-idx3-ubyte.gz": _write_images(args.output / "train-images-idx3-ubyte.gz", data["train_images"]), "train-labels-idx1-ubyte.gz": _write_labels(args.output / "train-labels-idx1-ubyte.gz", data["train_labels"]), "t10k-images-idx3-ubyte.gz": _write_images(args.output / "t10k-images-idx3-ubyte.gz", data["test_images"]), "t10k-labels-idx1-ubyte.gz": _write_labels(args.output / "t10k-labels-idx1-ubyte.gz", data["test_labels"]), } if args.checksums.exists(): checksums = json.loads(args.checksums.read_text(encoding="utf-8")) else: checksums = {} for name, digest in files.items(): checksums[f"data/ufo/{name}"] = digest args.checksums.write_text(json.dumps(checksums, indent=2, sort_keys=True) + "\n", encoding="utf-8") for name, digest in files.items(): print(f"{name} {digest}") return 0 def _write_images(path: Path, images: np.ndarray) -> str: images = np.asarray(images, dtype=np.uint8) if images.ndim != 3: raise ValueError("images must be shaped (N, rows, cols)") header = struct.pack(">IIII", 2051, images.shape[0], images.shape[1], images.shape[2]) return _write_gzip(path, header + images.tobytes()) def _write_labels(path: Path, labels: np.ndarray) -> str: labels = np.asarray(labels, dtype=np.uint8) if labels.ndim != 1: raise ValueError("labels must be shaped (N,)") header = struct.pack(">II", 2049, labels.shape[0]) return _write_gzip(path, header + labels.tobytes()) def _write_gzip(path: Path, payload: bytes) -> str: with gzip.GzipFile(filename="", mode="wb", fileobj=path.open("wb"), mtime=0) as handle: handle.write(payload) return hashlib.sha256(path.read_bytes()).hexdigest() if __name__ == "__main__": raise SystemExit(main())