File size: 3,462 Bytes
b0d869f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""Fetch individual PartImageNet/Pascal-Part source images from the project Hugging Face dataset.

Reads only the needed members of the remote archives (HTTP range requests), instead of downloading
the full 2.9 GB / 1.1 GB archives. PartImageNet images sit in a nested, compressed <split>.zip, so
that one inner archive is copied to a temporary file and deleted afterwards. The repo is gated:
authenticate with `hf auth login` or the HF_TOKEN environment variable.

  python code/tools/fetch_hf_images.py datasets/Pascal-Part/JPEGImages/val/2008_000562.jpg ...
  python code/tools/fetch_hf_images.py --from-file needed_images.txt
"""
import argparse
from collections import defaultdict
from pathlib import Path, PurePosixPath
import shutil
import tempfile
import zipfile

from huggingface_hub import HfFileSystem

ROOT = Path(__file__).resolve().parents[2]
REPO = 'datasets/COT5415/COT5415_Computer_Vision'
REVISION = '7b246dcf846a05e4a29dcc0400b572296b294902'


def archive_member(image_path):
    """Map a unified image_path to (archive, inner split zip or None, member name)."""
    parts = PurePosixPath(image_path).parts
    if parts[:3] == ('datasets', 'PartImageNet', 'images'):
        split = parts[3]
        return 'PartImageNet_OOD.zip', split + '.zip', '/'.join(parts[3:])
    if parts[:3] == ('datasets', 'Pascal-Part', 'JPEGImages'):
        return 'Pascal_Part.zip', None, 'Pascal_Part/' + '/'.join(parts[2:])
    raise ValueError(f'Not a PartImageNet/Pascal-Part image path: {image_path}')


def write_member(archive, member, target):
    if target.exists():
        return False
    target.parent.mkdir(parents=True, exist_ok=True)
    with archive.open(member) as source, target.open('xb') as stream:
        shutil.copyfileobj(source, stream)
    return True


def fetch(paths, root=ROOT):
    fs = HfFileSystem()
    groups = defaultdict(list)
    for path in paths:
        if not (root / path).is_file():
            outer, inner, member = archive_member(path)
            groups[(outer, inner)].append((member, root / path))
    fetched = []
    for (outer, inner), items in groups.items():
        remote = fs.open(f'{REPO}@{REVISION}/datasets/archives/{outer}', 'rb', block_size=1 << 20)
        with zipfile.ZipFile(remote) as archive:
            if inner is None:
                for member, target in items:
                    fetched += [target] if write_member(archive, member, target) else []
                continue
            with tempfile.TemporaryDirectory(prefix='hf-images-') as temp:
                local = Path(temp) / inner
                with archive.open(inner) as source, local.open('wb') as stream:
                    shutil.copyfileobj(source, stream, length=1 << 22)
                with zipfile.ZipFile(local) as nested:
                    for member, target in items:
                        fetched += [target] if write_member(nested, member, target) else []
    return fetched


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('paths', nargs='*')
    parser.add_argument('--from-file', type=Path)
    args = parser.parse_args()
    paths = list(args.paths)
    if args.from_file:
        paths += [line.strip() for line in args.from_file.read_text().splitlines() if line.strip()]
    for target in fetch(paths):
        print('fetched', target.relative_to(ROOT))


if __name__ == '__main__':
    main()