RAIL / scripts /push_to_hub.py
Hongyu Jin
remove files that are not part of the release (#2)
bff1d38
Raw History Blame Contribute Delete
5.69 kB
#!/usr/bin/env python3
"""Publish this repository to the Hugging Face dataset repo through one pull request.
The release is the git-tracked tree (data/, audio/, eval/, scripts/, metadata.json,
build_report.json) plus the dataset card written by build_rail_v2.py (README.md with the
Hub `configs` / `dataset_info` metadata that the Dataset Viewer reads). Files on the Hub that
are not part of the release are deleted. All changes go to a single PR in several commits;
with --merge the PR is merged after its file list is checked, so `main` switches in one step.
python scripts/push_to_hub.py --card /path/to/release/README.md --dry-run
python scripts/push_to_hub.py --card /path/to/release/README.md --tag-current v1.0 --merge
Uses the login from `hf auth login` (or HF_TOKEN).
"""
from __future__ import annotations
import argparse
import subprocess
import sys
from pathlib import Path
from typing import Dict, List
REPO_ROOT = Path(__file__).resolve().parents[1]
SKIP = {"README.md", ".gitignore", ".gitattributes"} # README comes from --card; .gitattributes is Hub-managed
def release_files(card: Path) -> Dict[str, Path]:
tracked = subprocess.run(["git", "-C", str(REPO_ROOT), "ls-files"], capture_output=True, text=True,
check=True).stdout.splitlines()
files = {p: REPO_ROOT / p for p in tracked if p not in SKIP}
files["README.md"] = card
missing = [p for p, f in files.items() if not f.is_file()]
if missing:
raise SystemExit(f"{len(missing)} release files missing locally, e.g. {missing[:3]}")
return files
def chunks(items: List, size: int):
for i in range(0, len(items), size):
yield items[i:i + size]
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--repo", default="AIMS-RAIL/RAIL")
ap.add_argument("--card", type=Path, required=True, help="dataset card (README.md) from build_rail_v2.py")
ap.add_argument("--tag-current", default=None, help="tag the Hub's current main before the update, e.g. v1.0")
ap.add_argument("--chunk", type=int, default=1000, help="files per commit")
ap.add_argument("--merge", action="store_true", help="merge the PR after checking its file list")
ap.add_argument("--dry-run", action="store_true")
args = ap.parse_args()
from huggingface_hub import CommitOperationAdd, CommitOperationDelete, HfApi
api = HfApi()
files = release_files(args.card.resolve())
info = api.dataset_info(args.repo)
remote = set(api.list_repo_files(args.repo, repo_type="dataset"))
stale = sorted(f for f in remote if f not in files and f != ".gitattributes")
stale_dirs = sorted({f.split("/", 1)[0] + "/" for f in stale if "/" in f})
stale_root = [f for f in stale if "/" not in f]
small = sorted(p for p in files if not p.startswith("audio/"))
audio = sorted(p for p in files if p.startswith("audio/"))
print(f"hub main {info.sha[:12]}: {len(remote)} files; release: {len(files)} files "
f"({len(small)} text/code, {len(audio)} audio); remove {len(stale)} files "
f"(folders {stale_dirs}, root files {stale_root})")
plan = [("remove files that are not part of the release",
[CommitOperationDelete(d, is_folder=True) for d in stale_dirs]
+ [CommitOperationDelete(f) for f in stale_root])]
plan.append(("add manifests, dataset card, metadata and code",
[CommitOperationAdd(p, str(files[p])) for p in small]))
for i, part in enumerate(chunks(audio, args.chunk), 1):
plan.append((f"add audio ({i}/{-(-len(audio) // args.chunk)})",
[CommitOperationAdd(p, str(files[p])) for p in part]))
for msg, ops in plan:
print(f" commit: {msg} [{len(ops)} operations]")
if args.dry_run:
return
print("logged in as", api.whoami()["name"])
if args.tag_current:
tags = {t.name for t in api.list_repo_refs(args.repo, repo_type="dataset").tags}
if args.tag_current not in tags:
api.create_tag(args.repo, tag=args.tag_current, revision=info.sha, repo_type="dataset",
tag_message=f"Release before the v2 re-organisation ({info.sha[:12]})")
print(f"tagged {info.sha[:12]} as {args.tag_current}")
pr_num = None
revision = None
for msg, ops in plan:
if not ops:
continue
res = api.create_commit(args.repo, operations=ops, commit_message=msg, repo_type="dataset",
revision=revision, create_pr=pr_num is None,
commit_description="RAIL v2: files organised by the paper's taxonomy." if pr_num is None else None)
if pr_num is None:
pr_num = res.pr_num
revision = f"refs/pr/{pr_num}"
print(f"opened PR #{pr_num}: {res.pr_url}")
print(f" committed: {msg}")
on_pr = set(api.list_repo_files(args.repo, repo_type="dataset", revision=revision))
missing = set(files) - on_pr
extra = on_pr - set(files) - {".gitattributes"}
print(f"PR #{pr_num}: {len(on_pr)} files; missing {len(missing)}, unexpected {len(extra)}")
if missing or extra:
print("not merging; missing e.g.", sorted(missing)[:5], "unexpected e.g.", sorted(extra)[:5])
sys.exit(1)
if args.merge:
api.merge_pull_request(args.repo, pr_num, repo_type="dataset",
comment="Merge RAIL v2 (files checked against the release).")
print(f"merged PR #{pr_num}; main is now {api.dataset_info(args.repo).sha[:12]}")
if __name__ == "__main__":
main()