openai_humaneval-th / validate.py
chonlasit
Remove parse_check.py and add validate.py for dataset integrity checks
45eebad
Raw History Blame Contribute Delete
5.47 kB
#!/usr/bin/env python3
r"""Integrity checks for this dataset, run against the live English original.
Usage: python validate.py [--strict]
Requires: pandas, pyarrow (pip install pandas pyarrow)
Two tiers.
STRUCTURAL the claims the card makes about alignment and about the three
untranslated columns. `canonical_solution`, `test` and
`entry_point` are Python, were never translated, and must be
byte-identical to `openai/openai_humaneval` in all 164 rows. Every
prompt must parse as Python. Any failure here means the card is
wrong. Non-zero exit.
FIDELITY per-row translation quality: no doctest example lost, no code line
glued to a docstring delimiter, no stray doctest marker, every
docstring closed on its own line, every prompt actually in Thai.
Reported as counts; use --strict to make them fail the run too.
The reason this file leads with the byte-identical check is that it is what
justified deleting `parse_check.py` and rebuilding rather than hand-repairing:
if those three columns match, the only column that ever needed judgement is
`prompt`.
"""
import argparse
import ast
import json
import os
import re
import sys
import tempfile
import urllib.request
import pandas as pd
HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "data/test.jsonl")
ENGLISH = ("https://huggingface.co/datasets/openai/openai_humaneval/resolve/main/"
"openai_humaneval/test-00000-of-00001.parquet")
UNTRANSLATED = ["canonical_solution", "test", "entry_point"]
GLUED_CODE = re.compile(r"^\s*(def |from |import |return |@).*(\"\"\"|''')", re.M)
STRAY_MARKER = re.compile(r">>>\s*(\"\"\"|''')|>>>\s*$", re.M)
CLOSED_PROPERLY = re.compile(r"\n\s*(\"\"\"|''')\s*\n?$")
THAI = re.compile(r"[฀-๿]")
structural = []
fidelity = []
def report(ok, label, bucket, detail=""):
print(f" {'PASS' if ok else 'FAIL'} {label}{'' if ok else ' -- ' + detail}")
if not ok:
bucket.append(label)
def english():
request = urllib.request.Request(ENGLISH, headers={"User-Agent": "iapp-validate"})
with urllib.request.urlopen(request, timeout=300) as response:
blob = response.read()
with tempfile.NamedTemporaryFile(suffix=".parquet", delete=False) as handle:
handle.write(blob)
path = handle.name
try:
return pd.read_parquet(path)
finally:
os.unlink(path)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--strict", action="store_true")
args = parser.parse_args()
with open(DATA, encoding="utf-8") as handle:
rows = [json.loads(line) for line in handle]
print("Fetching openai/openai_humaneval ...")
frame = english()
source = {row.task_id: row for row in frame.itertuples()}
print("\nSTRUCTURAL")
report(len(rows) == 164, "164 rows", structural, f"found {len(rows)}")
report([row["task_id"] for row in rows] == list(frame.task_id),
"task_id matches the English original, in order", structural)
for column in UNTRANSLATED:
same = sum(1 for row in rows
if row["task_id"] in source
and row[column] == getattr(source[row["task_id"]], column))
report(same == len(rows), f"{column} byte-identical to the English original",
structural, f"{len(rows) - same} rows differ")
unparsed = []
for row in rows:
try:
ast.parse(row["prompt"])
except SyntaxError:
unparsed.append(row["task_id"])
report(not unparsed, "every prompt parses as Python", structural,
f"{len(unparsed)} do not: {unparsed[:5]}")
print("\nFIDELITY")
lost = {}
for row in rows:
if row["task_id"] not in source:
continue
missing = [line.strip() for line in source[row["task_id"]].prompt.split("\n")
if line.strip().startswith(">>>") and line.strip() not in row["prompt"]]
if missing:
lost[row["task_id"]] = missing
report(not lost, "every doctest example of the English original survives",
fidelity, f"{len(lost)} rows lost one: {sorted(lost)[:5]}")
glued = [row["task_id"] for row in rows if GLUED_CODE.search(row["prompt"])]
report(not glued, "no code line glued to a docstring delimiter", fidelity,
f"{len(glued)} rows: {glued[:5]}")
stray = [row["task_id"] for row in rows if STRAY_MARKER.search(row["prompt"])]
report(not stray, "no doctest marker without an example after it", fidelity,
f"{len(stray)} rows: {stray[:5]}")
open_ended = [row["task_id"] for row in rows
if not CLOSED_PROPERLY.search(row["prompt"])]
report(not open_ended, "every docstring closed on its own line", fidelity,
f"{len(open_ended)} rows: {open_ended[:5]}")
untranslated = [row["task_id"] for row in rows if not THAI.search(row["prompt"])]
report(not untranslated, "every prompt contains Thai", fidelity,
f"{len(untranslated)} rows: {untranslated[:5]}")
print()
if structural:
print(f"STRUCTURAL failed: {len(structural)}")
if fidelity:
print(f"FIDELITY failed: {len(fidelity)}")
if not structural and not fidelity:
print("all checks passed")
return 1 if structural or (fidelity and args.strict) else 0
if __name__ == "__main__":
sys.exit(main())