File size: 6,069 Bytes
5f5554c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/env python3
"""Upload this dataset to the Hugging Face Hub over HTTP.

Deliberately does not use git. A 100GB+ push through git-lfs stalls, retries
from zero, and needs a working git-lfs install (this clone does not have one).
`upload_large_folder` is the Hub's own path for exactly this case: many
workers, resumable, and it picks up where it left off if you rerun it.

Usage:
    hf auth login                                  # once
    python scripts/upload_to_hub.py --dry-run      # see what would go up
    python scripts/upload_to_hub.py                # upload shards + metadata
    python scripts/upload_to_hub.py --only images  # shards alone

Requires: pip install -U "huggingface_hub[hf_xet]"
"""

from __future__ import annotations

import argparse
import sys
from fnmatch import fnmatch
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_REPO = "zidcenek/GLAMIDuplicationDetection"

GROUPS = {
    "images": ["images/*.parquet"],
    "metadata": ["*.csv", "README.md", "LICENSE"],
}

# .cache/huggingface holds upload_large_folder's own resume state; .git and the
# source tarball must never be shipped to the Hub.
# fnmatch's "*" crosses "/", so an allow pattern like "*.csv" sweeps up every
# nested CSV as well -- a virtualenv inside the repo is enough to leak numpy's
# test fixtures into a public dataset. These directories are excluded outright.
IGNORE = [
    ".git/*", "**/.git/*",
    ".cache/*", "**/.cache/*",
    ".venv/*", "**/.venv/*", "venv/*", "**/venv/*", "**/site-packages/*",
    "*.tar.gz", "scripts/*",
    ".build_state.json", "**/.build_state.json",
    ".seen_ids.bin", "**/.seen_ids.bin",
    ".DS_Store", "**/.DS_Store",
]


def human(n: float) -> str:
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if n < 1024:
            return f"{n:.1f}{unit}"
        n /= 1024
    return f"{n:.1f}PB"


def matching_files(root: Path, patterns: list[str]) -> list[Path]:
    hits = []
    for path in root.rglob("*"):
        if not path.is_file():
            continue
        rel = path.relative_to(root).as_posix()
        if any(fnmatch(rel, pat) for pat in IGNORE) or rel.startswith(".git/"):
            continue
        if any(fnmatch(rel, pat) for pat in patterns):
            hits.append(path)
    return sorted(hits)


def main() -> int:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--repo-id", default=DEFAULT_REPO)
    p.add_argument("--root", type=Path, default=REPO_ROOT)
    p.add_argument("--only", choices=sorted(GROUPS), action="append",
                   help="upload just one group (repeatable); default is all of them")
    p.add_argument("--workers", type=int, default=8,
                   help="parallel upload workers (default: 8; lower it if your uplink saturates)")
    p.add_argument("--dry-run", action="store_true", help="list the files and exit")
    p.add_argument("--yes", "-y", action="store_true", help="skip the confirmation prompt")
    args = p.parse_args()

    from huggingface_hub import HfApi
    from huggingface_hub.utils import HfHubHTTPError

    try:
        import hf_xet  # noqa: F401
    except ImportError:
        print("note: hf_xet is not installed. Install it -- 'pip install -U \"huggingface_hub[hf_xet]\"' --\n"
              "      for chunk-level deduplication, which matters a lot for a near-duplicate image set.\n")

    patterns = [pat for group in (args.only or sorted(GROUPS)) for pat in GROUPS[group]]
    files = matching_files(args.root, patterns)
    if not files:
        sys.exit(f"nothing matches {patterns} under {args.root} -- build the shards first")

    suspicious = [f for f in files
                  if any(part.startswith(".") or part in {"site-packages", "node_modules"}
                         for part in f.relative_to(args.root).parts[:-1])]
    if suspicious:
        print("refusing to upload -- these matched from inside a hidden or vendored directory:")
        for f in suspicious[:10]:
            print(f"          {f.relative_to(args.root).as_posix()}")
        sys.exit("widen IGNORE in this script, or move that directory out of the repo")

    total = sum(f.stat().st_size for f in files)
    print(f"repo    {args.repo_id}  (dataset)")
    print(f"root    {args.root}")
    print(f"files   {len(files):,}  totalling {human(total)}")
    for f in files[:6]:
        print(f"          {f.relative_to(args.root).as_posix()}  {human(f.stat().st_size)}")
    if len(files) > 6:
        print(f"          ... and {len(files) - 6:,} more")

    stubs = [f for f in files if f.suffix == ".csv" and f.stat().st_size < 200]
    if stubs:
        print("\nWARNING: these CSVs are 134-byte git-lfs pointer stubs, not real data.")
        for f in stubs:
            print(f"          {f.relative_to(args.root).as_posix()}")
        print("         Uploading them would overwrite the real files on the Hub.")
        print("         Install git-lfs and run 'git lfs pull' first, or exclude them.")
        if not args.yes:
            sys.exit("aborting -- rerun with --only images, or fix the stubs")

    if args.dry_run:
        return 0

    api = HfApi()
    try:
        who = api.whoami()
    except Exception:
        sys.exit("not authenticated -- run 'hf auth login' first")
    print(f"user    {who['name']}")

    if not args.yes:
        if input("\nupload? [y/N] ").strip().lower() not in {"y", "yes"}:
            return 1

    try:
        api.upload_large_folder(
            repo_id=args.repo_id,
            repo_type="dataset",
            folder_path=str(args.root),
            allow_patterns=patterns,
            ignore_patterns=IGNORE,
            num_workers=args.workers,
            print_report=True,
        )
    except HfHubHTTPError as exc:
        sys.exit(f"upload failed: {exc}\nRerun the same command -- it resumes from where it stopped.")

    print(f"\nDone: https://huggingface.co/datasets/{args.repo_id}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())