#!/usr/bin/env python3 from __future__ import annotations import argparse import json import re import sys from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple CHECK_CATALOG: Dict[str, Dict[str, Any]] = { "valid_json": {"required": [], "optional": []}, "json_equals": {"required": ["ref"], "optional": []}, "json_subset": {"required": ["ref"], "optional": []}, "required_keys": {"required": ["keys"], "optional": []}, "json_types": {"required": ["types"], "optional": []}, "exact_match": {"required": ["ref"], "optional": []}, "normalized_match": {"required": ["ref"], "optional": []}, "numeric_equals": {"required": ["ref"], "optional": ["path", "tolerance"]}, "label_in_set": {"required": ["labels"], "optional": []}, "word_count": {"required": [], "optional": ["min", "max"]}, "sentence_count": {"required": [], "optional": ["min", "max"]}, "paragraph_count": {"required": ["n"], "optional": []}, "line_count": {"required": [], "optional": ["min", "max"]}, "bullet_count": {"required": ["n"], "optional": ["marker"]}, "section_count": {"required": ["marker", "n"], "optional": []}, "contains_all": {"required": ["words"], "optional": ["case_sensitive"]}, "contains_none": {"required": ["words"], "optional": ["case_sensitive"]}, "keyword_frequency": {"required": ["word", "op", "n"], "optional": ["case_sensitive"]}, "starts_with": {"required": ["text"], "optional": []}, "ends_with": {"required": ["text"], "optional": []}, "regex_match": {"required": ["pattern"], "optional": []}, "regex_absent": {"required": ["pattern"], "optional": []}, "lowercase_only": {"required": [], "optional": []}, "uppercase_only": {"required": [], "optional": []}, "no_char": {"required": ["chars"], "optional": []}, "language_ru": {"required": [], "optional": ["min_cyrillic_ratio"]}, "wrapped_in_quotes": {"required": [], "optional": []}, "title_in_angle_brackets": {"required": [], "optional": []}, "placeholder_count": {"required": ["n"], "optional": []}, "postscript": {"required": ["marker"], "optional": []}, "no_markdown_fences": {"required": [], "optional": []}, "llm_rubric": {"required": ["criteria"], "optional": []}, } _INTRO_PATTERNS = [ r"^(?:конечно|хорошо|разумеется|готово|пожалуйста|держите|с удовольствием|без проблем)[^\n]{0,60}[:.!]\s*$", r"^(?:вот\s+(?:ваш\s+)?ответ|ниже\s+(?:представлен|привед[её]н)[^\n]{0,60})[:.!]\s*$", ] _OUTRO_PATTERNS = [ r"^(?:если\s+(?:нужно|у\s+вас\s+есть\s+вопросы|потребуется)|надеюсь|обращайтесь|удачи|буду\s+рад\s+помочь)[^\n]*$", ] def normalize_loose(text: str) -> str: if not isinstance(text, str): return "" s = text.strip() fence_match = re.match(r"^```[a-zA-Z0-9_-]*\s*\n(.*?)\n```\s*$", s, flags=re.DOTALL) if fence_match: s = fence_match.group(1).strip() lines = s.splitlines() if len(lines) > 1: first = lines[0].strip() if any(re.match(pat, first, flags=re.IGNORECASE) for pat in _INTRO_PATTERNS): lines = lines[1:] while lines and not lines[0].strip(): lines = lines[1:] if len(lines) > 1: last = lines[-1].strip() if any(re.match(pat, last, flags=re.IGNORECASE) for pat in _OUTRO_PATTERNS): lines = lines[:-1] while lines and not lines[-1].strip(): lines = lines[:-1] s = "\n".join(lines).strip() fence_match = re.match(r"^```[a-zA-Z0-9_-]*\s*\n(.*?)\n```\s*$", s, flags=re.DOTALL) if fence_match: s = fence_match.group(1).strip() s = re.sub(r"\*\*(.*?)\*\*", r"\1", s, flags=re.DOTALL) s = re.sub(r"(? Tuple[bool, Any]: try: return True, json.loads(text.strip()) except Exception: return False, None def _is_subset(sub: Any, sup: Any) -> bool: if isinstance(sub, dict): if not isinstance(sup, dict): return False for k, v in sub.items(): if k not in sup or not _is_subset(v, sup[k]): return False return True if isinstance(sub, list): if not isinstance(sup, list): return False return all(any(_is_subset(item, cand) for cand in sup) for item in sub) return sub == sup def _match_json_type(val: Any, type_name: str) -> bool: t = type_name.lower() if t in ("bool", "boolean"): return isinstance(val, bool) if t in ("int", "integer"): return isinstance(val, int) and not isinstance(val, bool) if t in ("float", "number"): return isinstance(val, (int, float)) and not isinstance(val, bool) if t in ("str", "string"): return isinstance(val, str) if t in ("list", "array"): return isinstance(val, list) if t in ("dict", "object"): return isinstance(val, dict) if t in ("null", "none"): return val is None return False def _normalize_text_for_match(text: str) -> str: s = text.strip().lower().replace("ё", "е") s = re.sub(r"\s+", " ", s) s = s.strip(" \t\n\r\"'«»„“”.!?,;:") return s def _parse_number(val: Any) -> Optional[float]: if isinstance(val, bool): return None if isinstance(val, (int, float)): return float(val) if isinstance(val, str): cleaned = val.strip().replace("\u00a0", "").replace(" ", "").replace(",", ".") cleaned = re.sub(r"[₽$€%]", "", cleaned) try: return float(cleaned) except ValueError: return None return None def _get_by_path(data: Any, path: str) -> Any: if not path: return data cur = data for part in path.split("."): if isinstance(cur, dict) and part in cur: cur = cur[part] elif isinstance(cur, list): try: idx = int(part) cur = cur[idx] except (ValueError, IndexError): return None else: return None return cur def _count_words(text: str) -> int: return len(re.findall(r"[0-9A-Za-zА-Яа-яЁё]+(?:-[0-9A-Za-zА-Яа-яЁё]+)*", text)) def _word_prefix_present(text: str, word: str, case_sensitive: bool = False) -> bool: if not word: return False flags = 0 if case_sensitive else re.IGNORECASE prefix = r"(? int: s = text.strip() if not s: return 0 parts = [p.strip() for p in re.split(r"(?<=[.!?…])\s+", s) if p.strip() and _count_words(p) > 0] return len(parts) def evaluate_check( response: str, check: Dict[str, Any], mode: str = "strict", llm_judge_fn: Optional[Callable[[str, List[str]], bool]] = None, ) -> Optional[bool]: ctype = check["type"] use_loose = mode == "loose" and check.get("loose", True) text = normalize_loose(response) if use_loose else response if ctype == "llm_rubric": if llm_judge_fn is not None: return bool(llm_judge_fn(text, check["criteria"])) return None if not text.strip(): return False if ctype == "valid_json": ok, _ = _parse_json(text) return ok if ctype == "json_equals": ok, parsed = _parse_json(text) return ok and parsed == check["ref"] if ctype == "json_subset": ok, parsed = _parse_json(text) return ok and _is_subset(check["ref"], parsed) if ctype == "required_keys": ok, parsed = _parse_json(text) return ok and isinstance(parsed, dict) and all(k in parsed for k in check["keys"]) if ctype == "json_types": ok, parsed = _parse_json(text) if not ok or not isinstance(parsed, dict): return False return all(k in parsed and _match_json_type(parsed[k], tname) for k, tname in check["types"].items()) if ctype == "exact_match": ref = check["ref"] if isinstance(ref, list): return text in ref return text == ref if ctype == "normalized_match": norm_resp = _normalize_text_for_match(text) ref = check["ref"] if isinstance(ref, list): return any(norm_resp == _normalize_text_for_match(str(r)) for r in ref) return norm_resp == _normalize_text_for_match(str(ref)) if ctype == "numeric_equals": path = check.get("path", "") tol = float(check.get("tolerance", 1e-6)) ref_num = _parse_number(check["ref"]) if ref_num is None: return False if path: ok, parsed = _parse_json(text) if not ok: return False val = _get_by_path(parsed, path) else: ok, parsed = _parse_json(text) val = parsed if ok else text got_num = _parse_number(val) return got_num is not None and abs(got_num - ref_num) <= tol if ctype == "label_in_set": labels = check["labels"] if use_loose: norm = _normalize_text_for_match(text) return any(norm == _normalize_text_for_match(lbl) for lbl in labels) return text.strip() in labels if ctype == "word_count": cnt = _count_words(text) min_w = check["min"] if check.get("min") is not None else 1 if cnt < min_w: return False if "max" in check and check["max"] is not None and cnt > check["max"]: return False return True if ctype == "sentence_count": cnt = _count_sentences(text) if "min" in check and check["min"] is not None and cnt < check["min"]: return False if "max" in check and check["max"] is not None and cnt > check["max"]: return False return True if ctype == "paragraph_count": paras = [p.strip() for p in re.split(r"\n\s*\n", text.strip()) if p.strip() and _count_words(p) > 0] return len(paras) == check["n"] if ctype == "line_count": lines = [ln for ln in text.splitlines() if ln.strip()] cnt = len(lines) if "min" in check and check["min"] is not None and cnt < check["min"]: return False if "max" in check and check["max"] is not None and cnt > check["max"]: return False return True if ctype == "bullet_count": marker = check.get("marker", "-") if marker in ("numbered", "1."): pat = r"^\s*\d+[.)]\s+\S" else: pat = rf"^\s*{re.escape(marker)}\s+\S" cnt = sum(1 for ln in text.splitlines() if re.match(pat, ln)) return cnt == check["n"] if ctype == "section_count": marker = check["marker"] pat = rf"^\s*{re.escape(marker)}(?:\s|$)" cnt = sum(1 for ln in text.splitlines() if re.match(pat, ln)) return cnt == check["n"] if ctype == "contains_all": cs = check.get("case_sensitive", False) return all(_word_prefix_present(text, w, cs) for w in check["words"]) if ctype == "contains_none": if _count_words(text) == 0: return False cs = check.get("case_sensitive", False) return all(not _word_prefix_present(text, w, cs) for w in check["words"]) if ctype == "keyword_frequency": cs = check.get("case_sensitive", False) hay = text if cs else text.lower() needle = check["word"] if cs else check["word"].lower() cnt = hay.count(needle) op = check["op"] n = check["n"] ops = { "==": cnt == n, ">=": cnt >= n, "<=": cnt <= n, ">": cnt > n, "<": cnt < n, } return ops[op] if ctype == "starts_with": target = check["text"] return text.lstrip().startswith(target) if use_loose else text.startswith(target) if ctype == "ends_with": target = check["text"] return text.rstrip().endswith(target) if use_loose else text.endswith(target) if ctype == "regex_match": return re.search(check["pattern"], text, flags=re.MULTILINE) is not None if ctype == "regex_absent": if _count_words(text) == 0: return False return re.search(check["pattern"], text, flags=re.MULTILINE) is None if ctype == "lowercase_only": has_alpha = any(c.isalpha() for c in text) return has_alpha and not any(c.isupper() for c in text) if ctype == "uppercase_only": has_alpha = any(c.isalpha() for c in text) return has_alpha and not any(c.islower() for c in text) if ctype == "no_char": if _count_words(text) == 0: return False chars = check["chars"] return all(ch not in text for ch in chars) if ctype == "language_ru": min_ratio = float(check.get("min_cyrillic_ratio", 0.8)) alphas = [c for c in text if c.isalpha()] if not alphas: return False cyr = sum(1 for c in alphas if ("а" <= c.lower() <= "я") or c.lower() == "ё") return (cyr / len(alphas)) >= min_ratio if ctype == "wrapped_in_quotes": s = text.strip() pairs = [('"', '"'), ("'", "'"), ("«", "»"), ("„", "“"), ("“", "”")] return any(len(s) >= 2 and s.startswith(a) and s.endswith(b) for a, b in pairs) if ctype == "title_in_angle_brackets": return re.search(r"<<[^<>\n]+>>", text) is not None if ctype == "placeholder_count": found = re.findall(r"\[[^\[\]\n]+\]", text) return len(found) == check["n"] if ctype == "postscript": marker = check["marker"] m = re.search(rf"(?:^|\n)\s*{re.escape(marker)}(?:\s|$)", text) if not m: return False return bool(text[: m.start()].strip()) if ctype == "no_markdown_fences": return "```" not in text if ctype == "llm_rubric": if llm_judge_fn is not None: return bool(llm_judge_fn(text, check["criteria"])) return None raise ValueError(f"Unknown check type: {ctype}") def evaluate_record( record: Dict[str, Any], response: str, llm_judge_fn: Optional[Callable[[str, List[str]], bool]] = None, ) -> Dict[str, Any]: checks = json.loads(record["checks"]) if isinstance(record["checks"], str) else record["checks"] strict_results: List[Optional[bool]] = [] loose_results: List[Optional[bool]] = [] for chk in checks: strict_results.append(evaluate_check(response, chk, mode="strict", llm_judge_fn=llm_judge_fn)) loose_results.append(evaluate_check(response, chk, mode="loose", llm_judge_fn=llm_judge_fn)) det_strict = [r for r in strict_results if r is not None] det_loose = [r for r in loose_results if r is not None] return { "id": record.get("id"), "strict_checks": strict_results, "loose_checks": loose_results, "prompt_strict": all(det_strict) if det_strict else True, "prompt_loose": all(det_loose) if det_loose else True, "det_strict_pass": sum(1 for r in det_strict if r), "det_loose_pass": sum(1 for r in det_loose if r), "det_total": len(det_strict), } def evaluate_dataset( dataset_path: Path, responses: Dict[str, str], ) -> Dict[str, Any]: records = [json.loads(line) for line in dataset_path.read_text(encoding="utf-8").splitlines() if line.strip()] total_prompts = 0 prompt_strict_ok = 0 prompt_loose_ok = 0 total_instructions = 0 inst_strict_ok = 0 inst_loose_ok = 0 for rec in records: rid = rec["id"] if rid not in responses: continue total_prompts += 1 res = evaluate_record(rec, responses[rid]) if res["prompt_strict"]: prompt_strict_ok += 1 if res["prompt_loose"]: prompt_loose_ok += 1 total_instructions += res["det_total"] inst_strict_ok += res["det_strict_pass"] inst_loose_ok += res["det_loose_pass"] return { "evaluated_prompts": total_prompts, "evaluated_instructions": total_instructions, "prompt_level_strict": (prompt_strict_ok / total_prompts) if total_prompts else 0.0, "prompt_level_loose": (prompt_loose_ok / total_prompts) if total_prompts else 0.0, "instruction_level_strict": (inst_strict_ok / total_instructions) if total_instructions else 0.0, "instruction_level_loose": (inst_loose_ok / total_instructions) if total_instructions else 0.0, } def load_responses(path: Path) -> Dict[str, str]: raw = path.read_text(encoding="utf-8").strip() if raw.startswith("{"): return json.loads(raw) out: Dict[str, str] = {} for line in raw.splitlines(): if not line.strip(): continue obj = json.loads(line) out[obj["id"]] = obj["response"] return out def main() -> int: parser = argparse.ArgumentParser(description="Evaluate model responses on ru_if dataset.") parser.add_argument("--dataset", required=True, type=Path, help="Path to dataset JSONL") parser.add_argument("--responses", required=True, type=Path, help="Path to responses JSON/JSONL") args = parser.parse_args() responses = load_responses(args.responses) metrics = evaluate_dataset(args.dataset, responses) print(json.dumps(metrics, ensure_ascii=False, indent=2)) return 0 if __name__ == "__main__": sys.exit(main())