ops-lite / update_croissant.py
anon-ops's picture
Add files using upload-large-folder tool
9f88cb7 verified
"""
Refresh ops-lite/croissant.json after data files are uploaded.
Usage:
HF_TOKEN=hf_xxx python update_croissant.py [--repo anon-ops/ops-lite]
What it does:
1. Pulls the auto-generated Croissant from
https://huggingface.co/api/datasets/<repo>/croissant
2. Loads the hand-authored croissant.json from the repo
(which carries the RAI fields and the manual recordSet schema).
3. Splices auto-Croissant's `distribution` (with real sha256 hashes
and the actual file list) into the hand-authored skeleton, so we
keep the rich descriptions + RAI fields but get accurate hashes.
4. Re-uploads the merged file.
Run after every data push that changes file content or count.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import tempfile
from pathlib import Path
import httpx
from huggingface_hub import HfApi, hf_hub_download
DEFAULT_REPO = "anon-ops/ops-lite"
def fetch_auto_croissant(repo: str) -> dict:
url = f"https://huggingface.co/api/datasets/{repo}/croissant"
r = httpx.get(url, timeout=30, follow_redirects=True)
r.raise_for_status()
return r.json()
def load_repo_croissant(repo: str, token: str) -> dict:
path = hf_hub_download(
repo_id=repo, repo_type="dataset",
filename="croissant.json", token=token,
)
return json.loads(Path(path).read_text())
def splice_distribution(manual: dict, auto: dict) -> dict:
"""Replace manual.distribution with auto's, carrying over manual descriptions where ids match."""
manual_by_id = {d.get("@id") or d.get("name"): d for d in manual.get("distribution", [])}
spliced = []
for d in auto.get("distribution", []):
key = d.get("@id") or d.get("name")
if key in manual_by_id and "description" in manual_by_id[key]:
d.setdefault("description", manual_by_id[key]["description"])
spliced.append(d)
if spliced:
manual["distribution"] = spliced
return manual
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--repo", default=DEFAULT_REPO)
args = ap.parse_args()
token = os.environ.get("HF_TOKEN")
if not token:
print("ERROR: HF_TOKEN env var not set", file=sys.stderr)
return 2
print(f"[1/4] fetching auto-Croissant for {args.repo} ...")
auto = fetch_auto_croissant(args.repo)
print(f"[2/4] downloading hand-authored croissant.json ...")
manual = load_repo_croissant(args.repo, token)
print(f"[3/4] splicing distribution ({len(auto.get('distribution', []))} items) ...")
merged = splice_distribution(manual, auto)
api = HfApi()
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:
json.dump(merged, f, indent=2, ensure_ascii=False)
out = f.name
print(f"[4/4] uploading merged croissant.json ...")
api.upload_file(
path_or_fileobj=out,
path_in_repo="croissant.json",
repo_id=args.repo,
repo_type="dataset",
commit_message="Refresh Croissant (core from auto + manual RAI)",
token=token,
)
print("done.")
return 0
if __name__ == "__main__":
raise SystemExit(main())