File size: 3,269 Bytes
9c890d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | """Upload a checksum-verified view-count bundle under a dedicated HF prefix."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
from demo.scale4d_view_count.bundle import bundle_path, verify_bundle
def upload_bundle(
root: Path, repo_id: str, prefix: str = "examples/view_count"
) -> dict:
from huggingface_hub import (
CommitOperationAdd,
HfApi,
get_hf_file_metadata,
hf_hub_url,
)
manifest = verify_bundle(root)
prefix = prefix.strip("/")
if not prefix.startswith("examples/") or ".." in prefix.split("/"):
raise ValueError("Uploads must remain under an examples/ subdirectory")
paths = [row["path"] for row in manifest["files"]] + ["manifest.json"]
api = HfApi()
previous = api.model_info(repo_id)
operations = [
CommitOperationAdd(
path_in_repo=f"{prefix}/{name}", path_or_fileobj=bundle_path(root, name)
)
for name in paths
]
commit = api.create_commit(
repo_id=repo_id,
operations=operations,
commit_message=f"Add {manifest.get('title', 'SCALE4D visualization inputs and results')}",
parent_commit=previous.sha,
)
print(f"Created Hugging Face commit {commit.oid}; verifying objects", flush=True)
verified = []
for name in paths:
path = bundle_path(root, name)
remote = get_hf_file_metadata(
hf_hub_url(repo_id, f"{prefix}/{name}", revision=commit.oid),
token=api.token or True,
)
sha256 = next(
(row["sha256"] for row in manifest["files"] if row["path"] == name), None
)
if sha256 is None:
sha256 = hashlib.sha256(path.read_bytes()).hexdigest()
blob_hash = hashlib.sha1()
blob_hash.update(f"blob {path.stat().st_size}\0".encode())
with path.open("rb") as handle:
for block in iter(lambda: handle.read(8 * 1024 * 1024), b""):
blob_hash.update(block)
if remote.size != path.stat().st_size or remote.etag not in (
sha256,
blob_hash.hexdigest(),
):
raise RuntimeError(f"Uploaded object differs from the bundle: {name}")
verified.append(name)
return {
"repo_id": repo_id,
"prefix": prefix,
"parent_commit": previous.sha,
"commit": commit.oid,
"url": f"https://huggingface.co/{repo_id}/tree/{commit.oid}/{prefix}",
"verified_files": verified,
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--bundle", type=Path, required=True)
parser.add_argument("--repo-id", default="facebook/SCALE4D")
parser.add_argument("--prefix", default="examples/view_count")
parser.add_argument("--receipt", type=Path, required=True)
args = parser.parse_args()
if args.receipt.exists():
parser.error("The upload receipt already exists")
result = upload_bundle(args.bundle, args.repo_id, args.prefix)
args.receipt.parent.mkdir(parents=True, exist_ok=True)
args.receipt.write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()
|