pcmt-artifact / scripts /upload_hf_artifact.py
Faruk Alpay
Use git dataset-tree upload flow
c3163a6
Raw
History Blame Contribute Delete
2.95 kB
from __future__ import annotations
import os
import shutil
import stat
import subprocess
import tempfile
from pathlib import Path
from huggingface_hub import HfFolder
ROOT = Path(__file__).resolve().parents[1]
REPO_ID = "Lightcap/pcmt-artifact"
PAYLOAD_DIR = ROOT / "submission" / "hf_dataset_tree"
CHECKOUT_DIR = ROOT / "submission" / "hf_git_repo"
REMOTE_URL = f"https://huggingface.co/datasets/{REPO_ID}"
LFS_PATTERNS = [
"data/fixtures/videos/*.mp4",
"data/real_videos/*.mp4",
"figures/*.pdf",
"figures/*.png",
"runs/remote_gpu/*/windows.jsonl",
]
def run(cmd: list[str], cwd: Path | None = None, env: dict[str, str] | None = None) -> None:
subprocess.run(cmd, cwd=cwd, env=env, check=True)
def main() -> int:
token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN") or HfFolder.get_token()
if not token:
raise SystemExit("HF_TOKEN is not set and no cached Hugging Face token was found")
if not PAYLOAD_DIR.exists():
raise SystemExit(f"Missing staged dataset tree: {PAYLOAD_DIR}")
if CHECKOUT_DIR.exists():
run(["git", "fetch", "origin"], cwd=CHECKOUT_DIR)
run(["git", "checkout", "main"], cwd=CHECKOUT_DIR)
run(["git", "pull", "--ff-only", "origin", "main"], cwd=CHECKOUT_DIR)
else:
CHECKOUT_DIR.parent.mkdir(parents=True, exist_ok=True)
run(["git", "clone", REMOTE_URL, str(CHECKOUT_DIR)])
run(["rsync", "-a", "--delete", "--exclude=.git", "--exclude=.cache", f"{PAYLOAD_DIR}/", f"{CHECKOUT_DIR}/"])
run(["git", "lfs", "install", "--local"], cwd=CHECKOUT_DIR)
for pattern in LFS_PATTERNS:
run(["git", "lfs", "track", pattern], cwd=CHECKOUT_DIR)
run(["git", "add", "-A"], cwd=CHECKOUT_DIR)
status = subprocess.run(["git", "status", "--porcelain"], cwd=CHECKOUT_DIR, text=True, capture_output=True, check=True)
if not status.stdout.strip():
print(f"No changes to upload: {REMOTE_URL}")
return 0
run(["git", "commit", "-m", "Publish PCMT artifact as dataset tree"], cwd=CHECKOUT_DIR)
push_with_token(token)
print(REMOTE_URL)
return 0
def push_with_token(token: str) -> None:
with tempfile.NamedTemporaryFile("w", delete=False, prefix="hf_askpass_", suffix=".sh") as handle:
askpass = Path(handle.name)
handle.write(
"#!/bin/sh\n"
'case "$1" in\n'
' *Username*) printf "%s" "Lightcap" ;;\n'
' *) printf "%s" "$HF_TOKEN_FOR_GIT" ;;\n'
"esac\n"
)
askpass.chmod(askpass.stat().st_mode | stat.S_IXUSR)
env = os.environ.copy()
env["GIT_ASKPASS"] = str(askpass)
env["GIT_TERMINAL_PROMPT"] = "0"
env["HF_TOKEN_FOR_GIT"] = token
try:
run(["git", "-c", "credential.helper=", "push", "origin", "main"], cwd=CHECKOUT_DIR, env=env)
finally:
askpass.unlink(missing_ok=True)
if __name__ == "__main__":
raise SystemExit(main())