cenekzid
dataset: add README, LICENSE, and scripts for uploading
5f5554c
Raw
History Blame Contribute Delete
6.07 kB
#!/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())