Download tasks/data/forward/adaptedas__url_parser.2635bab/tests/grader.py from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 9.71 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adaptedas__url_parser.2635bab/tests/grader.py
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/adaptedas__url_parser.2635bab/tests/grader.py
-
curl -L -o grader.py https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adaptedas__url_parser.2635bab/tests/grader.py
9.71 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| from pathlib import Path | |
| GRADER_SCHEMA_VERSION = "programgen.forward-grader.v2" | |
| _NO_TEST_MARKERS = ( | |
| "collected 0 items", | |
| "no tests ran", | |
| "[no test files]", | |
| "no tests were found", | |
| "total tests: 0", | |
| "running 0 tests", | |
| "0 tests passed", | |
| "0 passed; 0 failed", | |
| ) | |
| _COMPILE_FAILURE_MARKERS = ( | |
| "could not compile", | |
| "compilation terminated", | |
| "error: linking with", | |
| "fatal error:", | |
| "undefined reference to", | |
| "[build failed]", | |
| "cmake error", | |
| "ninja: build stopped", | |
| ) | |
| _ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]") | |
| def parse_test_output(text: str, *, return_code: int) -> dict[str, int | str] | None: | |
| # Normalize colored runner output before parsing summaries or verbose nodes. | |
| text = _ANSI_ESCAPE.sub("", text) | |
| # A verifier killed by the internal timeout may never print pytest's terminal | |
| # summary. ``-vv`` emits one outcome per completed node, which is sufficient | |
| # for honest partial credit against the persisted expected denominator. | |
| verbose = re.findall( | |
| r"(?m)^(.+?::.+?)\s+(PASSED|FAILED|ERROR)(?:\s+\[[^\]]+\])?\s*$", | |
| text, | |
| ) | |
| if verbose: | |
| outcomes: dict[str, str] = {} | |
| for test_id, outcome in verbose: | |
| outcomes[test_id.strip()] = outcome | |
| counts = { | |
| outcome: sum(value == outcome for value in outcomes.values()) | |
| for outcome in ("PASSED", "FAILED", "ERROR") | |
| } | |
| return { | |
| "passed": counts["PASSED"], | |
| "failed": counts["FAILED"], | |
| "errors": counts["ERROR"], | |
| "kind": "pytest-verbose", | |
| } | |
| cargo = re.findall( | |
| r"test result:\s+\w+\.\s+(\d+) passed;\s+(\d+) failed", | |
| text, | |
| ) | |
| if cargo: | |
| passed = sum(int(row[0]) for row in cargo) | |
| failed = sum(int(row[1]) for row in cargo) | |
| if passed + failed: | |
| return {"passed": passed, "failed": failed, "errors": 0, "kind": "cargo"} | |
| passed_matches = re.findall(r"(?<![\w%])(\d+)\s+passed\b", text) | |
| failed_matches = re.findall(r"(?<!\w)(\d+)\s+failed\b", text) | |
| error_matches = re.findall(r"(?<!\w)(\d+)\s+errors?\b", text) | |
| if passed_matches or failed_matches or error_matches: | |
| return { | |
| "passed": int(passed_matches[-1]) if passed_matches else 0, | |
| "failed": int(failed_matches[-1]) if failed_matches else 0, | |
| "errors": int(error_matches[-1]) if error_matches else 0, | |
| "kind": "summary", | |
| } | |
| unittest_runs = re.findall(r"(?m)^Ran\s+(\d+)\s+tests?\b", text) | |
| unittest_status = re.findall(r"(?m)^(OK|FAILED)(?:\s+\(([^)]*)\))?\s*$", text) | |
| if unittest_runs and unittest_status: | |
| ran = int(unittest_runs[-1]) | |
| _status, details = unittest_status[-1] | |
| counts = { | |
| key.strip().lower().replace("_", " "): int(value) | |
| for key, value in re.findall(r"([A-Za-z_ ]+?)=(\d+)", details) | |
| } | |
| excluded = counts.get("skipped", 0) + counts.get("expected failures", 0) | |
| errors = counts.get("errors", 0) + counts.get("unexpected successes", 0) | |
| failed = counts.get("failures", 0) | |
| total = max(0, ran - excluded) | |
| if total: | |
| return { | |
| "passed": max(0, total - failed - errors), | |
| "failed": failed, | |
| "errors": errors, | |
| "kind": "unittest", | |
| } | |
| declared = re.search( | |
| r"(?im)^\s*Total:\s*(\d+)\s*(?:\|\s*)?Passed:\s*(\d+)\s*" | |
| r"(?:\|\s*)?Failed:\s*(\d+)\s*$", | |
| text, | |
| ) | |
| if declared: | |
| total, passed, failed = map(int, declared.groups()) | |
| if total > 0 and passed + failed == total: | |
| return {"passed": passed, "failed": failed, "errors": 0, "kind": "declared"} | |
| go_passed = [ | |
| line | |
| for line in re.findall(r"(?m)^ok\s+\S+(?:\s+[^\n]+)?$", text) | |
| if "[no test files]" not in line.lower() | |
| ] | |
| go_failed = re.findall( | |
| r"(?m)^FAIL\s+\S+\s+(?:\d+(?:\.\d+)?s|\[(?:build|setup) failed\])\s*$", | |
| text, | |
| ) | |
| if go_passed or go_failed: | |
| return { | |
| "passed": len(go_passed), | |
| "failed": len(go_failed), | |
| "errors": 0, | |
| "kind": "go-packages", | |
| } | |
| ctest = re.search( | |
| r"(\d+)% tests passed,\s*(\d+) tests failed out of (\d+)", | |
| text, | |
| flags=re.IGNORECASE, | |
| ) | |
| if ctest and int(ctest.group(3)) > 0: | |
| failed = int(ctest.group(2)) | |
| total = int(ctest.group(3)) | |
| return { | |
| "passed": max(0, total - failed), | |
| "failed": failed, | |
| "errors": 0, | |
| "kind": "ctest", | |
| } | |
| meson_passed = re.search(r"(?m)^Ok:\s*(\d+)\s*$", text) | |
| meson_failed = re.search(r"(?m)^Fail:\s*(\d+)\s*$", text) | |
| if meson_passed: | |
| passed = int(meson_passed.group(1)) | |
| failed = int(meson_failed.group(1)) if meson_failed else 0 | |
| if passed + failed: | |
| return {"passed": passed, "failed": failed, "errors": 0, "kind": "meson"} | |
| if any(marker in text.lower() for marker in _NO_TEST_MARKERS): | |
| return {"passed": 0, "failed": 0, "errors": 0, "kind": "no-tests"} | |
| return None | |
| def score_test_run( | |
| text: str, | |
| *, | |
| return_code: int, | |
| expected_count: int, | |
| phase: str = "tests", | |
| reason: str = "", | |
| ) -> dict[str, object]: | |
| expected = max(0, int(expected_count)) | |
| parsed = ( | |
| parse_test_output(text, return_code=return_code) if phase == "tests" else None | |
| ) | |
| passed = int(parsed.get("passed", 0)) if parsed else 0 | |
| failed = int(parsed.get("failed", 0)) if parsed else 0 | |
| errors = int(parsed.get("errors", 0)) if parsed else 0 | |
| observed = passed + failed + errors | |
| denominator = max(expected, observed) | |
| lowered = text.lower() | |
| compile_failed = any(marker in lowered for marker in _COMPILE_FAILURE_MARKERS) | |
| completed_count = observed >= expected if expected else observed > 0 | |
| expected_exit = return_code == 0 or ( | |
| return_code in (1, 101) and failed + errors > 0 | |
| ) | |
| complete = bool(parsed and completed_count and expected_exit and not compile_failed) | |
| compiled = bool(parsed and observed > 0 and not compile_failed) | |
| reward = passed / denominator if denominator else 0.0 | |
| if reward >= 1.0 and not complete: | |
| reward = 0.0 | |
| if not reason: | |
| if phase != "tests": | |
| reason = f"{phase}-failed" | |
| elif parsed is None: | |
| reason = ( | |
| "test-output-unparsed" if return_code == 0 else "test-process-failed" | |
| ) | |
| elif parsed.get("kind") == "no-tests": | |
| reason = "no-tests-ran" | |
| elif compile_failed: | |
| reason = "compile-failed" | |
| elif observed < expected: | |
| reason = "incomplete-test-count" | |
| elif errors: | |
| reason = "test-errors" | |
| elif failed: | |
| reason = "test-failures" | |
| elif return_code != 0: | |
| reason = "unexpected-test-exit" | |
| else: | |
| reason = "complete" | |
| return { | |
| "schema_version": GRADER_SCHEMA_VERSION, | |
| "phase": phase, | |
| "reason": reason, | |
| "test_rc": int(return_code), | |
| "parser": str(parsed.get("kind")) if parsed else None, | |
| "passed": passed, | |
| "failed": failed, | |
| "errors": errors, | |
| "observed_test_count": observed, | |
| "expected_test_count": expected, | |
| "denominator": denominator, | |
| "compiled": compiled, | |
| "complete": complete, | |
| "reward": reward, | |
| } | |
| def write_result( | |
| text: str, | |
| *, | |
| return_code: int, | |
| expected_count: int, | |
| phase: str, | |
| reason: str, | |
| reward_path: Path, | |
| metrics_path: Path, | |
| ) -> dict[str, object]: | |
| result = score_test_run( | |
| text, | |
| return_code=return_code, | |
| expected_count=expected_count, | |
| phase=phase, | |
| reason=reason, | |
| ) | |
| reward_path.parent.mkdir(parents=True, exist_ok=True) | |
| metrics_path.parent.mkdir(parents=True, exist_ok=True) | |
| reward = result.get("reward") | |
| if not isinstance(reward, (int, float)): | |
| raise ValueError("grader result has no numeric reward") | |
| reward_path.write_text(f"{float(reward):.12g}\n", encoding="utf-8") | |
| metrics_path.write_text( | |
| json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8" | |
| ) | |
| return result | |
| def main(argv: list[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--output", type=Path) | |
| parser.add_argument("--return-code", type=int, required=True) | |
| parser.add_argument("--expected-count", type=int, required=True) | |
| parser.add_argument("--phase", default="tests") | |
| parser.add_argument("--reason", default="") | |
| parser.add_argument( | |
| "--reward-path", type=Path, default=Path("/logs/verifier/reward.txt") | |
| ) | |
| parser.add_argument( | |
| "--metrics-path", type=Path, default=Path("/logs/verifier/metrics.json") | |
| ) | |
| args = parser.parse_args(argv) | |
| text = "" | |
| if args.output and args.output.is_file(): | |
| text = args.output.read_text(encoding="utf-8", errors="replace") | |
| result = write_result( | |
| text, | |
| return_code=args.return_code, | |
| expected_count=args.expected_count, | |
| phase=args.phase, | |
| reason=args.reason, | |
| reward_path=args.reward_path, | |
| metrics_path=args.metrics_path, | |
| ) | |
| reward = result.get("reward") | |
| if not isinstance(reward, (int, float)): | |
| raise ValueError("grader result has no numeric reward") | |
| print(f"{float(reward):.12g}") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |