File size: 3,208 Bytes
9f88cb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
94
95
96
97
98
99
100
101
102
"""
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())