FNE-AXIOMESH / upload_hf.py
PureOne's picture
FNE-AXIOMESH v0.2.0: dataset release with agent and expert support
1c1abed verified
Raw History Blame Contribute Delete
5.8 kB
#!/usr/bin/env python3
"""Upload the checksum-controlled AXIOMESH release using the Hub client."""
from __future__ import annotations
import argparse
import os
from pathlib import Path
import re
import sys
import time
from validate_release import check_manifest
ROOT = Path(__file__).resolve().parent
DEFAULT_SLUG = "FNE-AXIOMESH"
DEFAULT_COMMIT = "FNE-AXIOMESH v0.2.0: dataset release with agent and expert support"
REPO_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*\Z")
def parse_args(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo-id", help="namespace/name; default: authenticated account/FNE-AXIOMESH")
parser.add_argument("--repo-type", choices=("model", "dataset"), default="dataset")
parser.add_argument("--private", action="store_true", help="create a new private repository; existing visibility is unchanged")
parser.add_argument("--commit-message", default=DEFAULT_COMMIT)
parser.add_argument("--dry-run", action="store_true", help="check local files only; no client import, authentication, or upload")
parser.add_argument("--list-files", action="store_true", help="show checksum-controlled upload paths")
parser.add_argument("--max-attempts", type=int, choices=range(1, 6), default=3, metavar="1..5")
return parser.parse_args(argv)
def repo_id(value):
if not isinstance(value, str) or not REPO_ID.fullmatch(value):
raise ValueError("repository id must be namespace/name")
if any(".." in part or "--" in part or part.endswith((".", ".git")) for part in value.split("/")):
raise ValueError("repository id contains a disallowed component")
return value
def upload_paths(root=ROOT):
manifest = check_manifest(root)
return sorted([*manifest["files"], "MANIFEST.json"])
def status_code(exc):
return getattr(getattr(exc, "response", None), "status_code", None)
def transient(exc):
return status_code(exc) in {429, 500, 502, 503, 504} or type(exc).__name__ in {
"ConnectError", "ConnectTimeout", "ReadTimeout", "WriteTimeout", "PoolTimeout", "ConnectionError", "TimeoutError"
}
def retry(operation, attempts, label, sleep=time.sleep):
for attempt in range(1, attempts + 1):
try:
return operation()
except Exception as exc:
if attempt == attempts or not transient(exc):
raise
delay = min(2 ** (attempt - 1), 4)
code = status_code(exc)
print(f"{label}: temporary failure ({code or type(exc).__name__}); retry {attempt + 1}/{attempts} in {delay}s.", flush=True)
sleep(delay)
def upload(api, target, args, paths):
retry(lambda: api.create_repo(repo_id=target, repo_type=args.repo_type,
private=args.private, exist_ok=True), args.max_attempts, "Create/check repository")
# Only explicitly checksum-controlled release files; no remote deletions.
return retry(lambda: api.upload_folder(repo_id=target, repo_type=args.repo_type,
folder_path=str(ROOT), commit_message=args.commit_message,
allow_patterns=paths), args.max_attempts, "Upload")
def main(argv=None):
args = parse_args(argv)
try:
paths = upload_paths()
target = repo_id(args.repo_id) if args.repo_id else None
total = sum((ROOT / name).stat().st_size for name in paths)
print(f"Verified release: {len(paths)} files, {total} bytes.")
if args.list_files:
print("\n".join(paths))
if args.dry_run:
print(f"DRY RUN: {target or '<authenticated-account>/FNE-AXIOMESH'} ({args.repo_type})")
print("No network calls or authentication performed.")
return 0
try:
from huggingface_hub import HfApi
except ImportError:
print("Install the Hub client: python -m pip install -U huggingface_hub", file=sys.stderr)
return 2
api = HfApi(token=os.environ.get("HF_TOKEN") or None)
if target is None:
identity = retry(api.whoami, args.max_attempts, "Account lookup")
name = identity.get("name")
if not name:
raise ValueError("Hub account lookup returned no username; pass --repo-id")
target = repo_id(f"{name}/{DEFAULT_SLUG}")
print(f"Target: {target} ({args.repo_type})", flush=True)
result = upload(api, target, args, paths)
print("Upload completed.")
if getattr(result, "commit_url", None):
print(result.commit_url)
if getattr(result, "oid", None):
print(f"Commit: {result.oid}")
return 0
except Exception as exc:
code = status_code(exc)
print(f"UPLOAD FAILED: {type(exc).__name__}" + (f" (HTTP {code})" if code else ""), file=sys.stderr)
if isinstance(exc, (ValueError, OSError)) and code is None:
print(str(exc), file=sys.stderr)
else:
print("Raw server details are omitted so access tokens are not printed.", file=sys.stderr)
if code in {401, 403}:
print("Run hf auth login with a write-capable token and check the target namespace.", file=sys.stderr)
elif code == 404:
print("Check --repo-id, --repo-type, and your namespace permissions.", file=sys.stderr)
elif code in {429, 500, 502, 503, 504}:
print("Retry later. The uploader makes bounded retries and does not delete remote files.", file=sys.stderr)
else:
print("Check local validation, client installation, connectivity and hf auth login.", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())