kuramot6f's picture
Initial release (history squashed)
7a088d4
Raw History Blame Contribute Delete
4.78 kB
#!/usr/bin/env python3
"""Upload hf-staging/<repo> folders to Hugging Face as PRIVATE repos, then verify.
Usage: .venv-hf/bin/python scripts/hf_upload.py [--namespace NS] [--only REPO ...] [--verify-only]
Requires `hf auth login` beforehand. Verification compares every local file's
size (and LFS sha256 where available) with the remote repo listing.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
from pathlib import Path
from huggingface_hub import HfApi
DS = Path(__file__).resolve().parents[1]
STAGING = DS / "hf-staging"
SECRET_RE = re.compile(r"(sk-proj-[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9]{20,}|hf_[A-Za-z0-9]{30,}|ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16})")
SCAN_SUFFIX = {".py", ".md", ".json", ".txt", ".sh", ".yaml", ".yml", ".jsonl", ".org", ".log", ".csv", ".toml", ".cfg"}
def sha256(p: Path) -> str:
h = hashlib.sha256()
with p.open("rb") as f:
for b in iter(lambda: f.read(1 << 24), b""):
h.update(b)
return h.hexdigest()
def verify(api: HfApi, repo_id: str, kind: str, local: Path) -> dict:
remote = {}
for e in api.list_repo_tree(repo_id, repo_type=kind, recursive=True, expand=True):
if getattr(e, "size", None) is not None and not hasattr(e, "tree_id"):
remote[e.path] = e
bad, missing = [], []
files = [p for p in local.rglob("*") if p.is_file() and ".cache" not in p.parts]
for p in files:
rel = p.relative_to(local).as_posix()
e = remote.get(rel)
if e is None:
missing.append(rel)
continue
if e.size != p.stat().st_size:
bad.append((rel, "size"))
elif getattr(e, "lfs", None) is not None and getattr(e.lfs, "sha256", None) not in (None, sha256(p)):
bad.append((rel, "sha256"))
return {"repo": repo_id, "local_files": len(files), "remote_files": len(remote),
"missing": missing, "mismatch": bad, "ok": not missing and not bad}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--namespace")
ap.add_argument("--only", nargs="*")
ap.add_argument("--verify-only", action="store_true")
ap.add_argument("--recreate", nargs="*", default=[], help="repos to delete+recreate first (purge git history)")
ap.add_argument("--squash", action="store_true", help="super-squash history after upload")
ap.add_argument("--publish", action="store_true", help="set repos public after successful verification")
a = ap.parse_args()
api = HfApi()
ns = a.namespace or api.whoami()["name"]
results = []
for d in sorted(p for p in STAGING.iterdir() if p.is_dir()):
if a.only and d.name not in a.only:
continue
kind = json.loads((d / "pack_report.json").read_text())["type"]
repo_id = f"{ns}/{d.name}"
# refuse to publish anything containing a secret
leaks = [str(p.relative_to(d)) for p in d.rglob("*") if p.is_file() and p.suffix in SCAN_SUFFIX
and p.stat().st_size < 50_000_000 and SECRET_RE.search(p.read_text(errors="ignore"))]
if leaks:
raise SystemExit(f"secret pattern found in {repo_id}: {leaks}")
if not a.verify_only:
if d.name in a.recreate and api.repo_exists(repo_id, repo_type=kind):
print(f"[delete+recreate] {repo_id}", flush=True)
api.delete_repo(repo_id, repo_type=kind)
api.create_repo(repo_id, repo_type=kind, private=True, exist_ok=True)
print(f"[upload] {repo_id} ({kind})", flush=True)
# delete_patterns removes remote files that are no longer staged
api.upload_folder(repo_id=repo_id, repo_type=kind, folder_path=d, ignore_patterns=[".cache/**"],
delete_patterns=["*", "**/*"], commit_message="Upload curated artifacts (hf_pack.py)")
if a.squash:
api.super_squash_history(repo_id=repo_id, repo_type=kind,
commit_message="Initial release (history squashed)")
r = verify(api, repo_id, kind, d)
commits = api.list_repo_commits(repo_id, repo_type=kind)
r["commits"] = len(commits)
r["private"] = api.repo_info(repo_id, repo_type=kind).private
if a.publish and r["ok"]:
api.update_repo_settings(repo_id, repo_type=kind, private=False)
r["private"] = api.repo_info(repo_id, repo_type=kind).private
print(json.dumps(r, ensure_ascii=False), flush=True)
results.append(r)
(STAGING / f"upload_verification-{'_'.join(a.only or ['all'])}.json").write_text(json.dumps(results, ensure_ascii=False, indent=2))
print("ALL OK" if all(r["ok"] for r in results) else "SOME FAILED")
if __name__ == "__main__":
main()