abforge-isambard-transfer / code /Abforge_Training /remove_rubric_v1_backup.py
SlowGuess's picture
Upload Abforge training code snapshot
1ce6f9b verified
Raw
History Blame Contribute Delete
3.99 kB
#!/usr/bin/env python3
"""Remove the legacy `Rubric_v1_backup` field from the ABForge HF dataset, and
(optionally) refresh the dataset card.
Usage:
# 1) make sure the cached HF token is SlowGuess's (write-enabled), e.g.
# python -c "from huggingface_hub import login; login()" # paste token
#
# 2) dry run -- only reports which files contain the field (no download of
# big files, no changes pushed):
DRY_RUN=1 /path/to/conda/abforge/bin/python remove_rubric_v1_backup.py
#
# 3) apply -- downloads matching files, strips the field, re-uploads, and
# updates the card, all in ONE commit:
DRY_RUN=0 /path/to/conda/abforge/bin/python remove_rubric_v1_backup.py
"""
import os
import json
from pathlib import Path
import requests
from huggingface_hub import HfApi, hf_hub_download, CommitOperationAdd
REPO = "SlowGuess/abforge-data"
FIELD = "Rubric_v1_backup"
CARD_LOCAL = "/gpfs/radev/project/cohan/yz979/xucai/Abforge_Training/abforge_dataset_card.md"
DRY = os.environ.get("DRY_RUN", "1") != "0"
token = Path.home().joinpath(".cache/huggingface/token").read_text().strip()
api = HfApi(token=token)
who = api.whoami()["name"]
print(f"Authenticated as: {who}")
if who != "SlowGuess":
print("!! WARNING: not SlowGuess -- writes will fail or go to the wrong repo.")
files = [f for f in api.list_repo_files(REPO, repo_type="dataset") if f.endswith(".jsonl")]
def first_row(rel):
"""Fetch just the first line via an HTTP Range request (no full download)."""
url = f"https://huggingface.co/datasets/{REPO}/resolve/main/{rel}"
r = requests.get(url, headers={"Authorization": f"Bearer {token}",
"Range": "bytes=0-5000000"}, timeout=120)
line = r.text.split("\n", 1)[0]
return json.loads(line)
# --- detect affected files (cheap: first row only) ---
affected = []
print("\n== Detection (first-row probe) ==")
for rel in files:
try:
keys = list(first_row(rel).keys())
except Exception as e:
print(f" {rel}: could not probe ({e})")
continue
has = FIELD in keys
other_v1 = [k for k in keys if "v1" in k.lower() and k != FIELD]
note = f" [other v1-ish keys: {other_v1}]" if other_v1 else ""
print(f" {rel}: {FIELD}={'YES' if has else 'no'}{note}")
if has:
affected.append(rel)
print(f"\nAffected files: {affected or '(none)'}")
if not affected:
print("Nothing to do for the data. (Card can still be updated below.)")
if DRY:
print("\nDRY RUN -- no files downloaded/rewritten, no commit. "
"Re-run with DRY_RUN=0 to apply.")
raise SystemExit(0)
# --- apply: download, strip field, rewrite, collect ops ---
ops = []
for rel in affected:
print(f"\n-- processing {rel} --")
local = hf_hub_download(REPO, rel, repo_type="dataset", token=token)
out = local + ".clean"
removed = 0
total = 0
with open(local, "r", encoding="utf-8") as fin, open(out, "w", encoding="utf-8") as fout:
for line in fin:
line = line.rstrip("\n")
if not line:
continue
total += 1
d = json.loads(line)
if FIELD in d:
del d[FIELD]
removed += 1
fout.write(json.dumps(d, ensure_ascii=False) + "\n")
print(f" rows={total}, removed {FIELD} from {removed} rows -> {out}")
ops.append(CommitOperationAdd(path_in_repo=rel, path_or_fileobj=out))
# refresh the card too (YAML header + no v1 mention)
if os.path.exists(CARD_LOCAL):
ops.append(CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=CARD_LOCAL))
print(f"\nWill also update README.md from {CARD_LOCAL}")
if ops:
info = api.create_commit(
repo_id=REPO, repo_type="dataset", operations=ops,
commit_message="Remove legacy Rubric_v1_backup field; refresh dataset card",
)
print("\nCOMMIT DONE:", getattr(info, "commit_url", info))
else:
print("\nNo operations to commit.")