Download validate.py from Squeal-Studio/ruIFEval: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/datasets/Squeal-Studio/ruIFEval/resolve/main/validate.py
- Command line
-
hf download hf://datasets/Squeal-Studio/ruIFEval/validate.py
-
curl -L -o validate.py https://huggingface.co/datasets/Squeal-Studio/ruIFEval/resolve/main/validate.py
13.1 kB
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| import sys | |
| from collections import Counter | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Set | |
| from eval import CHECK_CATALOG, evaluate_record | |
| REQUIRED_FIELDS: Dict[str, type] = { | |
| "id": str, | |
| "lang": str, | |
| "category": str, | |
| "subtopic": str, | |
| "domain": str, | |
| "difficulty": str, | |
| "eval_mode": str, | |
| "prompt": str, | |
| "instruction": str, | |
| "input": str, | |
| "expected": str, | |
| "checks": str, | |
| } | |
| VALID_CATEGORIES: Set[str] = { | |
| "formatting", | |
| "length", | |
| "lexical", | |
| "structure", | |
| "language_case_punct", | |
| "extraction", | |
| "classification", | |
| "multi_constraint", | |
| "edge_cases", | |
| "style_and_reasoning", | |
| } | |
| VALID_DOMAINS: Set[str] = { | |
| "business", | |
| "finance", | |
| "legal", | |
| "hr", | |
| "ecommerce", | |
| "logistics", | |
| "tech", | |
| "education", | |
| "science", | |
| "journalism", | |
| "everyday", | |
| "public_services", | |
| } | |
| VALID_DIFFICULTIES: Set[str] = {"easy", "medium", "hard"} | |
| VALID_EVAL_MODES: Set[str] = {"deterministic", "llm_judge"} | |
| VALID_OPS: Set[str] = {"==", ">=", "<=", ">", "<"} | |
| def expected_to_response(expected_json_str: str) -> str: | |
| val = json.loads(expected_json_str) | |
| if isinstance(val, str): | |
| return val | |
| return json.dumps(val, ensure_ascii=False) | |
| def validate_check_obj(chk: Any, eval_mode: str, idx: int) -> List[str]: | |
| errors: List[str] = [] | |
| if not isinstance(chk, dict): | |
| return [f"check[{idx}] must be a JSON object"] | |
| ctype = chk.get("type") | |
| if not isinstance(ctype, str) or ctype not in CHECK_CATALOG: | |
| return [f"check[{idx}] unknown or missing check type: {ctype!r}"] | |
| if ctype == "llm_rubric" and eval_mode != "llm_judge": | |
| errors.append(f"check[{idx}] llm_rubric is only allowed when eval_mode=='llm_judge'") | |
| spec = CHECK_CATALOG[ctype] | |
| for req in spec["required"]: | |
| if req not in chk: | |
| errors.append(f"check[{idx}] ({ctype}) missing required param '{req}'") | |
| allowed_keys = {"type", "loose", *spec["required"], *spec["optional"]} | |
| extra = set(chk.keys()) - allowed_keys | |
| if extra: | |
| errors.append(f"check[{idx}] ({ctype}) unexpected params: {sorted(extra)}") | |
| if "loose" in chk and not isinstance(chk["loose"], bool): | |
| errors.append(f"check[{idx}] ({ctype}) 'loose' must be boolean") | |
| if ctype in ("word_count", "sentence_count", "line_count"): | |
| if chk.get("min") is None and chk.get("max") is None: | |
| errors.append(f"check[{idx}] ({ctype}) requires at least one of 'min' or 'max'") | |
| for k in ("min", "max"): | |
| if chk.get(k) is not None and (not isinstance(chk[k], int) or isinstance(chk[k], bool) or chk[k] < 0): | |
| errors.append(f"check[{idx}] ({ctype}) '{k}' must be non-negative int") | |
| if ctype in ("paragraph_count", "bullet_count", "section_count", "placeholder_count"): | |
| n = chk.get("n") | |
| min_n = 0 if ctype == "placeholder_count" else 1 | |
| if not isinstance(n, int) or isinstance(n, bool) or n < min_n: | |
| errors.append(f"check[{idx}] ({ctype}) 'n' must be int >= {min_n}") | |
| if ctype in ("required_keys", "label_in_set", "contains_all", "contains_none"): | |
| key_name = "keys" if ctype == "required_keys" else ("labels" if ctype == "label_in_set" else "words") | |
| val = chk.get(key_name) | |
| if not isinstance(val, list) or not val or not all(isinstance(x, str) and x != "" for x in val): | |
| errors.append(f"check[{idx}] ({ctype}) '{key_name}' must be a non-empty list of non-empty strings") | |
| if ctype == "json_types": | |
| tmap = chk.get("types") | |
| valid_t = {"str", "string", "int", "integer", "float", "number", "bool", "boolean", "list", "array", "dict", "object", "null", "none"} | |
| if not isinstance(tmap, dict) or not tmap: | |
| errors.append(f"check[{idx}] (json_types) 'types' must be a non-empty dict") | |
| elif not all(isinstance(k, str) and isinstance(v, str) and v.lower() in valid_t for k, v in tmap.items()): | |
| errors.append(f"check[{idx}] (json_types) invalid type mapping in 'types'") | |
| if ctype == "keyword_frequency": | |
| if chk.get("op") not in VALID_OPS: | |
| errors.append(f"check[{idx}] (keyword_frequency) 'op' must be one of {sorted(VALID_OPS)}") | |
| if not isinstance(chk.get("n"), int) or isinstance(chk.get("n"), bool) or chk["n"] < 0: | |
| errors.append(f"check[{idx}] (keyword_frequency) 'n' must be non-negative int") | |
| if ctype in ("regex_match", "regex_absent"): | |
| pat = chk.get("pattern") | |
| if not isinstance(pat, str) or not pat: | |
| errors.append(f"check[{idx}] ({ctype}) 'pattern' must be non-empty string") | |
| else: | |
| try: | |
| re.compile(pat) | |
| except re.error as exc: | |
| errors.append(f"check[{idx}] ({ctype}) invalid regex: {exc}") | |
| if ctype == "language_ru" and "min_cyrillic_ratio" in chk: | |
| r = chk["min_cyrillic_ratio"] | |
| if not isinstance(r, (int, float)) or isinstance(r, bool) or not (0.0 < r <= 1.0): | |
| errors.append(f"check[{idx}] (language_ru) 'min_cyrillic_ratio' must be in (0, 1]") | |
| if ctype == "llm_rubric": | |
| crit = chk.get("criteria") | |
| if not isinstance(crit, list) or not (3 <= len(crit) <= 5) or not all(isinstance(c, str) and c.strip() for c in crit): | |
| errors.append(f"check[{idx}] (llm_rubric) 'criteria' must be a list of 3-5 non-empty strings") | |
| return errors | |
| def validate_record( | |
| rec: Any, | |
| line_num: int, | |
| seen_ids: Set[str], | |
| allow_working_fields: bool = False, | |
| check_expected: bool = False, | |
| check_negative: bool = False, | |
| ) -> List[str]: | |
| errors: List[str] = [] | |
| if not isinstance(rec, dict): | |
| return [f"Line {line_num}: record must be a JSON object"] | |
| allowed_fields = set(REQUIRED_FIELDS.keys()) | |
| if allow_working_fields: | |
| allowed_fields.add("_negative") | |
| extra = set(rec.keys()) - allowed_fields | |
| if extra: | |
| errors.append(f"Line {line_num}: unexpected fields: {sorted(extra)}") | |
| for field, ftype in REQUIRED_FIELDS.items(): | |
| if field not in rec: | |
| errors.append(f"Line {line_num}: missing required field '{field}'") | |
| elif not isinstance(rec[field], ftype): | |
| errors.append(f"Line {line_num}: field '{field}' must be {ftype.__name__}, got {type(rec[field]).__name__}") | |
| if errors: | |
| return errors | |
| rid = rec["id"] | |
| if not rid.strip(): | |
| errors.append(f"Line {line_num}: 'id' must be non-empty") | |
| elif rid in seen_ids: | |
| errors.append(f"Line {line_num}: duplicate id '{rid}'") | |
| else: | |
| seen_ids.add(rid) | |
| if rec["lang"] != "ru": | |
| errors.append(f"Line {line_num}: 'lang' must be 'ru'") | |
| if rec["category"] not in VALID_CATEGORIES: | |
| errors.append(f"Line {line_num}: invalid category '{rec['category']}'") | |
| if not rec["subtopic"].strip(): | |
| errors.append(f"Line {line_num}: 'subtopic' must be non-empty") | |
| if rec["domain"] not in VALID_DOMAINS: | |
| errors.append(f"Line {line_num}: invalid domain '{rec['domain']}'") | |
| if rec["difficulty"] not in VALID_DIFFICULTIES: | |
| errors.append(f"Line {line_num}: invalid difficulty '{rec['difficulty']}'") | |
| if rec["eval_mode"] not in VALID_EVAL_MODES: | |
| errors.append(f"Line {line_num}: invalid eval_mode '{rec['eval_mode']}'") | |
| if not rec["prompt"].strip(): | |
| errors.append(f"Line {line_num}: 'prompt' must be non-empty") | |
| if not rec["instruction"].strip(): | |
| errors.append(f"Line {line_num}: 'instruction' must be non-empty") | |
| eval_mode = rec["eval_mode"] | |
| if eval_mode == "llm_judge": | |
| if rec["category"] != "style_and_reasoning": | |
| errors.append(f"Line {line_num}: llm_judge must have category=='style_and_reasoning'") | |
| if rec["expected"] != "": | |
| errors.append(f"Line {line_num}: llm_judge must have expected==''") | |
| else: | |
| if rec["category"] == "style_and_reasoning": | |
| errors.append(f"Line {line_num}: style_and_reasoning must have eval_mode=='llm_judge'") | |
| if not rec["expected"].strip(): | |
| errors.append(f"Line {line_num}: deterministic record must have non-empty JSON string 'expected'") | |
| else: | |
| try: | |
| json.loads(rec["expected"]) | |
| except Exception as exc: | |
| errors.append(f"Line {line_num}: 'expected' is not valid JSON: {exc}") | |
| try: | |
| checks = json.loads(rec["checks"]) | |
| except Exception as exc: | |
| errors.append(f"Line {line_num}: 'checks' is not valid JSON: {exc}") | |
| return errors | |
| if not isinstance(checks, list) or not checks: | |
| errors.append(f"Line {line_num}: 'checks' must be a non-empty JSON list") | |
| return errors | |
| for i, chk in enumerate(checks): | |
| for err in validate_check_obj(chk, eval_mode, i): | |
| errors.append(f"Line {line_num} ({rid}): {err}") | |
| if eval_mode == "llm_judge": | |
| has_det = any(isinstance(c, dict) and c.get("type") != "llm_rubric" for c in checks) | |
| has_rubric = any(isinstance(c, dict) and c.get("type") == "llm_rubric" for c in checks) | |
| if not has_det: | |
| errors.append(f"Line {line_num} ({rid}): llm_judge must include at least one deterministic check") | |
| if not has_rubric: | |
| errors.append(f"Line {line_num} ({rid}): llm_judge must include an llm_rubric check") | |
| if errors: | |
| return errors | |
| if check_expected and eval_mode == "deterministic": | |
| exp_resp = expected_to_response(rec["expected"]) | |
| res = evaluate_record(rec, exp_resp) | |
| if not res["prompt_strict"]: | |
| errors.append(f"Line {line_num} ({rid}): expected FAILED strict checks: {res['strict_checks']}") | |
| if not res["prompt_loose"]: | |
| errors.append(f"Line {line_num} ({rid}): expected FAILED loose checks: {res['loose_checks']}") | |
| if check_negative: | |
| if "_negative" not in rec or not isinstance(rec["_negative"], str) or not rec["_negative"].strip(): | |
| errors.append(f"Line {line_num} ({rid}): missing or empty '_negative' string") | |
| else: | |
| res_neg = evaluate_record(rec, rec["_negative"]) | |
| if res_neg["prompt_strict"]: | |
| errors.append(f"Line {line_num} ({rid}): _negative PASSED all strict checks (must fail at least one)") | |
| return errors | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description="Validate ru_if JSONL dataset.") | |
| parser.add_argument("--file", required=True, type=Path, help="Path to JSONL file") | |
| parser.add_argument("--working", action="store_true", help="Allow _negative field and verify expected & _negative") | |
| parser.add_argument("--check-expected", action="store_true", help="Verify expected passes strict and loose checks") | |
| parser.add_argument("--check-negative", action="store_true", help="Verify _negative fails at least one strict check") | |
| parser.add_argument("--stats", action="store_true", help="Print distribution statistics") | |
| args = parser.parse_args() | |
| if not args.file.exists(): | |
| print(f"ERROR: File not found: {args.file}", file=sys.stderr) | |
| return 1 | |
| check_exp = args.check_expected or args.working | |
| check_neg = args.check_negative or args.working | |
| allow_work = args.working or args.check_negative | |
| seen_ids: Set[str] = set() | |
| all_errors: List[str] = [] | |
| records: List[Dict[str, Any]] = [] | |
| with args.file.open("r", encoding="utf-8") as f: | |
| for line_num, line in enumerate(f, start=1): | |
| stripped = line.strip() | |
| if not stripped: | |
| continue | |
| try: | |
| rec = json.loads(stripped) | |
| except Exception as exc: | |
| all_errors.append(f"Line {line_num}: invalid JSON: {exc}") | |
| continue | |
| records.append(rec) | |
| all_errors.extend( | |
| validate_record( | |
| rec, | |
| line_num=line_num, | |
| seen_ids=seen_ids, | |
| allow_working_fields=allow_work, | |
| check_expected=check_exp, | |
| check_negative=check_neg, | |
| ) | |
| ) | |
| if args.stats and records: | |
| total = len(records) | |
| print(f"Total records: {total}") | |
| for field in ("category", "difficulty", "domain", "eval_mode"): | |
| counts = Counter(r.get(field) for r in records) | |
| print(f"\n{field}:") | |
| for k, v in sorted(counts.items()): | |
| print(f" {k}: {v} ({v / total * 100:.1f}%)") | |
| if all_errors: | |
| print(f"\nVALIDATION FAILED: {len(all_errors)} error(s) in {args.file}", file=sys.stderr) | |
| for err in all_errors[:50]: | |
| print(f" - {err}", file=sys.stderr) | |
| if len(all_errors) > 50: | |
| print(f" ... and {len(all_errors) - 50} more", file=sys.stderr) | |
| return 1 | |
| print(f"OK: {len(records)} records validated in {args.file}") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |