GENIUS / scripts /build_viewer_data.py
HankYang428's picture
Improve dataset card and enable Viewer
545c42e
Raw
History Blame Contribute Delete
3.43 kB
#!/usr/bin/env python3
"""Build schema-stable JSONL files for the Hugging Face Dataset Viewer."""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
OUTPUT_DIR = ROOT / "viewer"
IMAGE_TOKEN = re.compile(r"<image:([^>]+)>")
CONFIGS = {
"implicit_pattern": (
"Implicit Pattern Induction",
"Implicit Pattern Generation",
86,
),
"symbolic_constraint": (
"Ad-hoc Constraint Execution",
"Symbolic Constraint Generation",
153,
),
"visual_constraint": (
"Ad-hoc Constraint Execution",
"Visual Constraint Generation",
60,
),
"prior_conflicting": (
"Contextual Knowledge Adaptation",
"Prior-Conflicting Generation",
101,
),
"multi_semantic": (
"Contextual Knowledge Adaptation",
"Multi-Semantic Generation",
110,
),
}
def normalize_hint(value: Any) -> str | None:
"""Represent every optional hint as one nullable string column."""
if value is None:
return None
if isinstance(value, str):
return value
if isinstance(value, list) and all(isinstance(item, str) for item in value):
return "\n".join(value)
raise TypeError(f"Unsupported hint value: {value!r}")
def image_paths(config_name: str, row: dict[str, Any]) -> list[str]:
"""Resolve ordered, unique image tokens to repository-relative paths."""
text_parts = [
row.get("context", ""),
row.get("instruction", ""),
row.get("rc_hint", ""),
normalize_hint(row.get("vc_hint")) or "",
]
names = IMAGE_TOKEN.findall("\n".join(text_parts))
return list(dict.fromkeys(f"{config_name}/images/{name}.png" for name in names))
def build_config(config_name: str, dimension: str, task: str, expected: int) -> int:
source_path = ROOT / config_name / "test_data.json"
rows = json.loads(source_path.read_text(encoding="utf-8"))
if not isinstance(rows, list) or len(rows) != expected:
raise ValueError(f"{source_path}: expected {expected} rows, found {len(rows)}")
output_path = OUTPUT_DIR / f"{config_name}.jsonl"
with output_path.open("w", encoding="utf-8") as output:
for source in rows:
record = {
"id": source["id"],
"dimension": dimension,
"task": task,
"sub_dimension": source["sub_dimension"],
"sub_sub_dimension": source.get("sub_sub_dimension"),
"context": source["context"],
"instruction": source["instruction"],
"rc_hint": source["rc_hint"],
"vc_hint": normalize_hint(source.get("vc_hint")),
"image_paths": image_paths(config_name, source),
}
output.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")))
output.write("\n")
return len(rows)
def main() -> None:
OUTPUT_DIR.mkdir(exist_ok=True)
total = sum(
build_config(config_name, dimension, task, expected)
for config_name, (dimension, task, expected) in CONFIGS.items()
)
if total != 510:
raise ValueError(f"Expected 510 total rows, found {total}")
print(f"Wrote {total} records across {len(CONFIGS)} files to {OUTPUT_DIR}")
if __name__ == "__main__":
main()