#!/usr/bin/env python3 """Score final answers and aggregate explicit reviews using only the standard library.""" import argparse import json from pathlib import Path from constraints import check ROOT = Path(__file__).resolve().parent def read_jsonl(path): rows = [] for line_number, line in enumerate(Path(path).read_text().splitlines(), 1): if line.strip(): row = json.loads(line) if not isinstance(row, dict): raise ValueError(f"{path}:{line_number}: expected an object") rows.append(row) return rows def unique_by_id(rows, label): result = {} for row in rows: key = row.get("id") if not isinstance(key, str) or key in result: raise ValueError(f"{label}: missing or duplicate ID {key!r}") result[key] = row return result def all_pass(values): if any(v is False for v in values): return False return None if any(v is None for v in values) else True def tally(values): values = list(values) passed = sum(v is True for v in values) failed = sum(v is False for v in values) pending = sum(v is None for v in values) return {"total": len(values), "passed": passed, "failed": failed, "pending": pending, "resolved_fraction": (passed + failed) / len(values) if values else None, "pass_rate": passed / len(values) if values and not pending else None} def valid_verdict(value): return value is None or type(value) is bool def evaluate(prompts, responses, reviews=None, response_format="final", allow_partial=False): if response_format not in ("final", "thinking"): raise ValueError("response_format must be final or thinking") dataset = unique_by_id(prompts, "dataset") answers = unique_by_id(responses, "responses") if not answers: raise ValueError("No responses supplied") unknown = answers.keys() - dataset.keys() if unknown: raise ValueError(f"Unknown response IDs: {sorted(unknown)}") missing = sorted(dataset.keys() - answers.keys()) if missing and not allow_partial: raise ValueError(f"Missing {len(missing)} responses; use --allow-partial for a subset") if reviews is None: reviews = {} if not isinstance(reviews, dict) or reviews.keys() - answers.keys(): raise ValueError("Reviews must be an object keyed only by supplied response IDs") detailed, template = [], {} for key, response in sorted(answers.items()): prompt = dataset[key] text = response.get("response") if not isinstance(text, str): raise ValueError(f"{key}: response must be a string") completed = response_format == "final" or "" in text final = (text.rsplit("", 1)[-1] if response_format == "thinking" and completed else text).strip() usable = completed and bool(final) machine = check({"id": key, "final": final if usable else "", "prompt": prompt}) mechanical = machine["checks"] review = reviews.get(key, {}) if not isinstance(review, dict): raise ValueError(f"{key}: review must be an object") overrides = review.get("constraint_overrides", {}) semantic = review.get("semantic_criteria", [None] * len(prompt["semantic_criteria"])) notes = review.get("notes", "") if not isinstance(notes, str) or not isinstance(overrides, dict): raise ValueError(f"{key}: notes must be a string and overrides an object") if overrides and not notes.strip(): raise ValueError(f"{key}: constraint overrides require explanatory notes") if not isinstance(semantic, list) or len(semantic) != len(prompt["semantic_criteria"]) or not all(valid_verdict(v) for v in semantic): raise ValueError(f"{key}: semantic_criteria must contain one boolean or null per criterion") constraints = mechanical.copy() sources = ["mechanical" if v is not None else "pending_review" for v in constraints] for index, value in overrides.items(): if index not in {str(i) for i in range(len(constraints))} or type(value) is not bool: raise ValueError(f"{key}: invalid zero-based constraint override {index!r}={value!r}") constraints[int(index)] = value sources[int(index)] = "review" if not usable: constraints = [False] * len(constraints) semantic = [False] * len(semantic) sources = ["missing_final_answer"] * len(constraints) c_pass, s_pass = all_pass(constraints), all_pass(semantic) detailed.append({ "id": key, "category": prompt["category"], "final": final if usable else "", "usable_final_answer": usable, "features": {k: v for k, v in machine.items() if k != "checks"}, "constraints": [{"check": label, "mechanical": raw, "passed": passed, "source": source} for label, raw, passed, source in zip(prompt["checks"], mechanical, constraints, sources)], "semantics": [{"criterion": label, "passed": passed} for label, passed in zip(prompt["semantic_criteria"], semantic)], "all_constraints_pass": c_pass, "all_semantics_pass": s_pass, "joint_pass": all_pass([c_pass, s_pass]), "review_notes": notes, }) template[key] = {"prompt": prompt["prompt"], "final": final if usable else "", "constraint_checks": prompt["checks"], "mechanical_checks": mechanical, "constraint_overrides": overrides, "semantic_criteria_text": prompt["semantic_criteria"], "semantic_criteria": semantic, "notes": notes} def summary(rows): return {"responses": len(rows), "constraints": tally(c["passed"] for r in rows for c in r["constraints"]), "semantics": tally(c["passed"] for r in rows for c in r["semantics"]), "prompt_constraints": tally(r["all_constraints_pass"] for r in rows), "prompt_semantics": tally(r["all_semantics_pass"] for r in rows), "joint": tally(r["joint_pass"] for r in rows)} report = {"dataset": "ifeval-vibe", "version": "1.0.0", "response_format": response_format, "dataset_size": len(dataset), "missing_ids": missing, "summary": summary(detailed), "by_category": {category: summary([r for r in detailed if r["category"] == category]) for category in sorted({r["category"] for r in detailed})}, "results": detailed} return report, template def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--responses", type=Path, required=True, help='JSONL rows: {"id": "chat_001", "response": "..."}') parser.add_argument("--data", type=Path, default=ROOT / "data/test.jsonl") parser.add_argument("--reviews", type=Path, help="Completed review template; no network judge is called") parser.add_argument("--response-format", choices=["final", "thinking"], default="final") parser.add_argument("--allow-partial", action="store_true") parser.add_argument("--output", type=Path, default=Path("scores.json")) parser.add_argument("--review-template", type=Path, help="Write a contextual review template for missing judgments") args = parser.parse_args() # Prevent accidentally replacing response data or completed judgments. inputs = [p.resolve() for p in [args.responses, args.data, args.reviews] if p is not None] outputs = [p.resolve() for p in [args.output, args.review_template] if p is not None] if len(set(outputs)) != len(outputs) or any(p in inputs for p in outputs): parser.error("Output paths must be distinct from each other and all input files") try: report, template = evaluate(read_jsonl(args.data), read_jsonl(args.responses), json.loads(args.reviews.read_text()) if args.reviews else None, args.response_format, args.allow_partial) except (ValueError, OSError) as exc: parser.error(str(exc)) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") if args.review_template: args.review_template.parent.mkdir(parents=True, exist_ok=True) args.review_template.write_text(json.dumps(template, ensure_ascii=False, indent=2) + "\n") print(json.dumps(report["summary"], indent=2)) if __name__ == "__main__": main()