File size: 3,581 Bytes
8d960ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/env python3
"""Create and upload tar shards to HuggingFace, one at a time to save disk."""

import argparse
import os
import tarfile
from pathlib import Path

from huggingface_hub import HfApi

SHARD_SIZE = 1_000_000_000  # ~1GB per shard


def get_existing_shards(api: HfApi, repo_id: str, prefix: str) -> set:
    """Check which shards already exist on HF."""
    try:
        files = api.list_repo_files(repo_id, repo_type="dataset")
        return {f for f in files if f.startswith(f"{prefix}/") and f.endswith(".tar")}
    except Exception:
        return set()


def upload_folder_as_shards(api: HfApi, repo_id: str, src_dir: Path, prefix: str, tmp_dir: Path):
    """Create tar shards from src_dir, upload each, delete after upload."""
    existing = get_existing_shards(api, repo_id, prefix)
    if existing:
        print(f"  Found {len(existing)} existing shards, will skip them", flush=True)

    files = sorted(f for f in src_dir.iterdir() if f.is_file())
    shard_idx = 0
    current_size = 0
    shard_files = []

    for f in files:
        shard_files.append(f)
        current_size += f.stat().st_size

        if current_size >= SHARD_SIZE:
            _make_and_upload(api, repo_id, shard_files, prefix, shard_idx, existing, tmp_dir)
            shard_idx += 1
            shard_files = []
            current_size = 0

    if shard_files:
        _make_and_upload(api, repo_id, shard_files, prefix, shard_idx, existing, tmp_dir)


def _make_and_upload(api: HfApi, repo_id: str, files: list, prefix: str, idx: int,
                     existing: set, tmp_dir: Path):
    name = f"{prefix}-{idx:04d}.tar"
    repo_path = f"{prefix}/{name}"
    if repo_path in existing:
        print(f"  Skipping {name} (already uploaded)", flush=True)
        return
    tar_path = tmp_dir / name
    print(f"  Creating {name} ({len(files)} files)...", flush=True)

    with tarfile.open(tar_path, "w") as tar:
        for f in files:
            tar.add(f, arcname=f.name)

    size_mb = tar_path.stat().st_size / 1_000_000
    print(f"  Uploading {name} ({size_mb:.0f} MB)...", flush=True)

    api.upload_file(
        path_or_fileobj=str(tar_path),
        path_in_repo=repo_path,
        repo_id=repo_id,
        repo_type="dataset",
    )

    tar_path.unlink()
    print(f"  Done {name}", flush=True)


def main():
    parser = argparse.ArgumentParser(description="Upload photo shards to HuggingFace")
    parser.add_argument("--src-dir", type=Path, required=True,
                        help="Directory containing photos to upload")
    parser.add_argument("--prefix", default="yfcc",
                        help="Prefix for shard names in repo (default: yfcc)")
    parser.add_argument("--repo", default="lightcella/photo-corpus",
                        help="HuggingFace dataset repo ID")
    parser.add_argument("--tmp-dir", type=Path, default=Path("."),
                        help="Directory for temporary tar files (default: current dir)")
    parser.add_argument("--shard-size", type=int, default=SHARD_SIZE,
                        help="Target shard size in bytes (default: 1GB)")
    args = parser.parse_args()

    global SHARD_SIZE
    SHARD_SIZE = args.shard_size

    api = HfApi()
    args.tmp_dir.mkdir(parents=True, exist_ok=True)

    n_files = sum(1 for f in args.src_dir.iterdir() if f.is_file())
    print(f"Uploading {n_files} files from {args.src_dir} as '{args.prefix}' shards...")
    upload_folder_as_shards(api, args.repo, args.src_dir, args.prefix, args.tmp_dir)
    print("All done!")


if __name__ == "__main__":
    main()