Datasets:

Languages:
English
ArXiv:
License:
GlazyBench / tools /read_source_record.py
SiyouLi's picture
Upload folder using huggingface_hub
234f610 verified
"""Convenience reader for the supplemental Hugging Face source bundle.
This script lives inside the published `huggingface/` folder so users can read
source-side data directly from the exported package without depending on the
rest of the repository layout.
"""
import argparse
import json
import re
import sys
from pathlib import Path
HF_ROOT = Path(__file__).resolve().parents[1]
ROOT = HF_ROOT.parent
SOURCE_RECORDS_DIR = HF_ROOT / "source_records"
SOURCE_RECORDS_BY_ID_DIR = SOURCE_RECORDS_DIR / "by_id"
SUMMARY_PATH = SOURCE_RECORDS_DIR / "summary.json"
def flatten_sample_ids(sample_id_args):
sample_ids = []
for item in sample_id_args or []:
sample_ids.extend(item)
return [str(sample_id) for sample_id in sample_ids]
def load_json(path: Path):
with open(path, "r", encoding="utf-8") as handle:
return json.load(handle)
def load_sample_ids_from_file(path: Path):
sample_ids = []
with open(path, "r", encoding="utf-8") as handle:
for line in handle:
sample_id = line.strip()
if sample_id:
sample_ids.append(sample_id)
return sample_ids
def strip_html_tags(text: str):
text = re.sub(r"<script.*?</script>", " ", text, flags=re.IGNORECASE | re.DOTALL)
text = re.sub(r"<style.*?</style>", " ", text, flags=re.IGNORECASE | re.DOTALL)
text = re.sub(r"<[^>]+>", " ", text)
text = re.sub(r"\s+", " ", text)
return text.strip()
def walk_path(value, dotted_path: str):
current = value
for part in dotted_path.split("."):
if isinstance(current, dict):
if part not in current:
raise KeyError(part)
current = current[part]
continue
if isinstance(current, list):
index = int(part)
current = current[index]
continue
raise KeyError(part)
return current
def first_nonempty(values):
for value in values:
if value not in (None, "", [], {}):
return value
return None
def extract_preferred_umf(record):
candidates = []
for dataset_name in ("property_prediction", "image_generation"):
dataset_block = record.get(dataset_name, {})
for split_name in ("train", "test"):
split_block = dataset_block.get(split_name)
if not split_block:
continue
recipe = split_block.get("recipe") or {}
metadata = split_block.get("metadata") or {}
candidates.append(recipe.get("umf"))
candidates.append(metadata.get("umf"))
html_metadata = record.get("html_metadata") or {}
if isinstance(html_metadata, dict):
candidates.append(html_metadata.get("umf"))
return first_nonempty(candidates)
def extract_shortcut(record, field_name: str):
html_metadata = record.get("html_metadata") or {}
if field_name == "title":
return first_nonempty([
html_metadata.get("title") if isinstance(html_metadata, dict) else None,
])
if field_name == "author":
return first_nonempty([
html_metadata.get("author") if isinstance(html_metadata, dict) else None,
])
if field_name == "description":
return first_nonempty([
html_metadata.get("description") if isinstance(html_metadata, dict) else None,
html_metadata.get("notes") if isinstance(html_metadata, dict) else None,
])
if field_name == "umf":
return extract_preferred_umf(record)
raise KeyError(field_name)
def parse_args():
parser = argparse.ArgumentParser(
description="Read supplemental GlazyBench source-side data from the Hugging Face export."
)
parser.add_argument(
"--sample-id",
nargs="+",
action="append",
help="One or more sample IDs to read from huggingface/source_records/by_id.",
)
parser.add_argument(
"--sample-id-file",
help="Optional text file with one sample ID per line for batch reading.",
)
parser.add_argument(
"--field",
choices=[
"full",
"memberships",
"property_prediction",
"image_generation",
"html_metadata",
"raw_html_path",
"title",
"author",
"description",
"umf",
],
default="full",
help="Which part of the merged record to print.",
)
parser.add_argument(
"--dataset",
choices=["property_prediction", "image_generation"],
help="Optional dataset selector when printing dataset-specific content.",
)
parser.add_argument(
"--split",
choices=["train", "test"],
help="Optional split selector when printing dataset-specific content.",
)
parser.add_argument(
"--summary",
action="store_true",
help="Print source bundle summary instead of an individual sample.",
)
parser.add_argument(
"--list-sample-ids",
type=int,
default=0,
help="Print the first N sample IDs available in source_records/by_id.",
)
parser.add_argument(
"--list-fields",
action="store_true",
help="Print the top-level fields available in a sample record.",
)
parser.add_argument(
"--path",
help="Optional dotted path lookup inside the selected record value, for example property_prediction.test.recipe.umf.",
)
parser.add_argument(
"--html-preview-chars",
type=int,
default=0,
help="Also print the first N characters of the raw HTML file for the sample.",
)
parser.add_argument(
"--html-preview-strip-tags",
action="store_true",
help="When previewing HTML, strip tags into rough plain text.",
)
parser.add_argument(
"--output-format",
choices=["json", "jsonl", "text"],
default="json",
help="Output format for batch or single-sample exports.",
)
parser.add_argument(
"--output",
help="Optional output file path. If omitted, prints to stdout.",
)
parser.add_argument(
"--compact",
action="store_true",
help="Print compact JSON instead of pretty JSON.",
)
return parser.parse_args()
def render_json(value, compact: bool):
if compact:
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
return json.dumps(value, ensure_ascii=False, indent=2)
def write_output(text: str, output_path: str | None):
if output_path:
path = Path(output_path)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as handle:
handle.write(text)
return
print(text)
def list_sample_ids(limit: int):
sample_ids = sorted(path.stem for path in SOURCE_RECORDS_BY_ID_DIR.glob("*.json"))
if limit > 0:
sample_ids = sample_ids[:limit]
return sample_ids
def get_record(sample_id: str):
path = SOURCE_RECORDS_BY_ID_DIR / f"{sample_id}.json"
if not path.exists():
raise FileNotFoundError(f"Sample record not found: {path}")
return load_json(path), path
def select_value(record, args):
if args.field == "full":
value = record
elif args.field == "memberships":
value = record.get("memberships", [])
elif args.field == "html_metadata":
value = record.get("html_metadata")
elif args.field == "raw_html_path":
raw_relpath = record.get("raw_html_relpath")
value = None if raw_relpath is None else str(HF_ROOT / raw_relpath)
elif args.field in {"title", "author", "description", "umf"}:
value = extract_shortcut(record, args.field)
else:
dataset_block = record.get(args.field, {})
if args.split:
value = dataset_block.get(args.split)
elif args.dataset and args.dataset != args.field:
value = record.get(args.dataset, {})
else:
value = dataset_block
if args.path:
value = walk_path(value, args.path)
return value
def maybe_get_html_preview(record, chars: int, strip_tags: bool):
if chars <= 0:
return None
raw_relpath = record.get("raw_html_relpath")
if raw_relpath is None:
return "<missing raw html>"
html_path = HF_ROOT / raw_relpath
if not html_path.exists():
return f"<file missing: {html_path}>"
with open(html_path, "r", encoding="utf-8", errors="ignore") as handle:
preview = handle.read(chars)
if strip_tags:
preview = strip_html_tags(preview)
return preview
def build_sample_payload(sample_id: str, args):
record, record_path = get_record(str(sample_id))
if args.list_fields:
payload = {
"sample_id": str(sample_id),
"record_path": str(record_path),
"top_level_fields": sorted(record.keys()),
"memberships": record.get("memberships", []),
}
else:
value = select_value(record, args)
payload = {
"sample_id": str(sample_id),
"record_path": str(record_path),
"selected_field": args.field,
"value": value,
}
html_preview = maybe_get_html_preview(record, args.html_preview_chars, args.html_preview_strip_tags)
if html_preview is not None:
payload["raw_html_preview"] = html_preview
return payload
def render_payloads(payloads, args):
if args.output_format == "jsonl":
return "\n".join(render_json(payload, compact=True) for payload in payloads)
if args.output_format == "text":
lines = []
for payload in payloads:
lines.append(f"sample_id={payload.get('sample_id')}")
lines.append(f"record_path={payload.get('record_path')}")
if "selected_field" in payload:
lines.append(f"selected_field={payload['selected_field']}")
lines.append(f"value={payload.get('value')}")
else:
lines.append(f"top_level_fields={payload.get('top_level_fields')}")
if "raw_html_preview" in payload:
lines.append("raw_html_preview=")
lines.append(str(payload["raw_html_preview"]))
lines.append("")
return "\n".join(lines).rstrip()
if len(payloads) == 1:
return render_json(payloads[0], args.compact)
return render_json(payloads, args.compact)
def main():
args = parse_args()
if args.summary:
write_output(render_json(load_json(SUMMARY_PATH), args.compact), args.output)
return
if args.list_sample_ids:
payload = {
"count": len(list_sample_ids(0)),
"sample_ids": list_sample_ids(args.list_sample_ids),
}
write_output(render_json(payload, args.compact), args.output)
return
sample_ids = flatten_sample_ids(args.sample_id)
if args.sample_id_file:
sample_ids.extend(load_sample_ids_from_file(Path(args.sample_id_file)))
if not sample_ids:
raise SystemExit("Provide --sample-id, --sample-id-file, --summary, or --list-sample-ids.")
payloads = [build_sample_payload(sample_id, args) for sample_id in sample_ids]
write_output(render_payloads(payloads, args), args.output)
if __name__ == "__main__":
try:
main()
except FileNotFoundError as exc:
print(str(exc), file=sys.stderr)
raise SystemExit(1)