#!/usr/bin/env python3 """Pack complete JPEG/caption pairs into reproducible six-pair tar shards.""" from pathlib import Path import tarfile DATASET = Path("data/dataset") OUT = Path("shards") SHARD_SIZE = 6 def complete_pairs(): images = {path.stem for path in DATASET.glob("*.jpg")} captions = {path.stem for path in DATASET.glob("*.txt")} return sorted(images & captions), len(images | captions) def add_bytes(archive, path): info = tarfile.TarInfo(path.name) info.size = path.stat().st_size info.mode = 0o644 info.mtime = 0 with path.open("rb") as source: archive.addfile(info, source) def main(): pairs, discovered = complete_pairs() OUT.mkdir(exist_ok=True) for stale in OUT.glob("dataset-*.tar"): stale.unlink() for offset in range(0, len(pairs), SHARD_SIZE): shard = OUT / f"dataset-{offset // SHARD_SIZE:06d}.tar" with tarfile.open(shard, "w") as archive: for key in pairs[offset:offset + SHARD_SIZE]: add_bytes(archive, DATASET / f"{key}.jpg") add_bytes(archive, DATASET / f"{key}.txt") Path("score.txt").write_text(f"{len(pairs)}/{discovered} complete image-caption pairs\n", encoding="utf-8") if __name__ == "__main__": main()