File size: 1,282 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()