File size: 2,332 Bytes
c58d6a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Materialise zh-plus/tiny-imagenet parquet files into the ImageFolder layout that the
author code (utils_data.tinyimgnet_dataloaders) expects:

    <root>/train/<label:03d>/images/*.JPEG      (100,000 images, 500 per class)
    <root>/val/<label:03d>/images/*.JPEG        ( 10,000 images,  50 per class)

Class directories are named with the zero-padded *integer* label, so that ImageFolder's
lexicographic sort of directory names reproduces the ClassLabel index order exactly
(000..199). Raw JPEG bytes are written unchanged (no re-encode).
"""
import io
import os
import sys
import time

import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download

REPO = "zh-plus/tiny-imagenet"
TRAIN = "data/train-00000-of-00001-1359597a978bc4fa.parquet"
VALID = "data/valid-00000-of-00001-70d52db3c749a935.parquet"


def dump(pq_path, split, root):
    out = os.path.join(root, split)
    pf = pq.ParquetFile(pq_path)
    n = 0
    t0 = time.time()
    for batch in pf.iter_batches(batch_size=2000, columns=["image", "label"]):
        img = batch.column("image")
        if hasattr(img, "field"):
            try:
                raw = img.field("bytes")
            except (KeyError, IndexError):
                raw = img.field(0)
        else:
            raw = img
        labels = batch.column("label").to_pylist()
        for i in range(batch.num_rows):
            y = int(labels[i])
            d = os.path.join(out, f"{y:03d}", "images")
            os.makedirs(d, exist_ok=True)
            with open(os.path.join(d, f"{split}_{n:06d}.JPEG"), "wb") as f:
                f.write(raw[i].as_py())
            n += 1
        if n % 20000 == 0:
            print(f"  {split}: {n} images ({time.time() - t0:.1f}s)", flush=True)
    return n


def main():
    root = sys.argv[1] if len(sys.argv) > 1 else "/work/tiny-imagenet-200"
    os.makedirs(root, exist_ok=True)
    n_tr = dump(hf_hub_download(REPO, TRAIN, repo_type="dataset"), "train", root)
    n_va = dump(hf_hub_download(REPO, VALID, repo_type="dataset"), "val", root)
    print(f"train={n_tr} val={n_va} at {root}")
    assert n_tr == 100000 and n_va == 10000, (n_tr, n_va)
    n_classes = len(os.listdir(os.path.join(root, "train")))
    print(f"classes: {n_classes}")
    assert n_classes == 200


if __name__ == "__main__":
    main()