"""Shared metric utilities for the Assistive Prompt Mediation benchmark.""" from __future__ import annotations import json import math import re from collections import Counter from pathlib import Path from typing import Any, Dict, List, Mapping, Optional META_PATTERNS = [ r"\bAs an AI\b", r"\bI (can|will|cannot|can't)\b", r"\bSure[, ]", r"\bHere(?: is|'s)\b", r"\bLet me\b", ] ASSISTED_TEXT_FIELDS = ( "model_response", "response", "assistant_response", "assist_prompt", "assisted_prompt", "mediated_prompt", "output", ) RAW_PROMPT_FIELDS = ( "noisy_prompt", "input_prompt", "prompt", "user_prompt", ) CHINESE_LANGUAGE_CODES = {"cn", "zh", "zh-cn", "zh_hans", "zh-hans"} CJK_REGEX = re.compile(r"[\u4e00-\u9fff]") def load_json_or_jsonl(path: str | Path) -> List[Dict[str, Any]]: """Load a JSON array or JSONL file as a list of dictionaries.""" path = Path(path) with path.open("r", encoding="utf-8") as f: first_char = f.read(1) f.seek(0) if not first_char: return [] if first_char == "[": data = json.load(f) if not isinstance(data, list): raise ValueError(f"{path} must contain a JSON array") return data return [json.loads(line) for line in f if line.strip()] def write_json(data: Any, path: str | Path) -> None: """Write JSON with stable UTF-8 formatting.""" path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) def entropy(text: str) -> float: """Character-level Shannon entropy used by the structural burden score.""" if not text: return 0.0 counts = Counter(text) total = sum(counts.values()) return -sum((count / total) * math.log2(count / total) for count in counts.values()) def cognitive_burden(text: str) -> float: """Compute the structural cognitive burden proxy B(p).""" tokens = re.findall(r"\w+|[^\w\s]", text) length = len(tokens) punctuation_density = sum(1 for token in tokens if re.match(r"[^\w\s]", token)) / max(length, 1) return round( 0.4 * length + 0.3 * punctuation_density * 100 + 0.3 * entropy(text) * 10, 3, ) def protocol_compliance(text: str) -> Dict[str, Any]: """Detect responses that ask questions or add meta/explanatory text.""" question_marks = text.count("?") + text.count("\uff1f") meta_hits = sum(bool(re.search(pattern, text, re.IGNORECASE)) for pattern in META_PATTERNS) asked_question = question_marks > 0 added_explanation = meta_hits > 0 return { "asked_question": asked_question, "added_explanation": added_explanation, "protocol_compliant": not (asked_question or added_explanation), "question_marks": question_marks, "meta_phrase_hits": meta_hits, } def language_script_match(text: str, language: Optional[str]) -> Dict[str, Any]: """Check whether Chinese outputs are mostly CJK characters. Non-Chinese languages return null values because this lightweight diagnostic is only defined for the Chinese-script condition used in the benchmark workflow. """ lang = (language or "").lower() if lang not in CHINESE_LANGUAGE_CODES: return {"script_match": None, "script_ratio": None} chars = [char for char in text if char.strip()] if not chars: return {"script_match": False, "script_ratio": 0.0} cjk_count = sum(bool(CJK_REGEX.match(char)) for char in chars) ratio = cjk_count / len(chars) return {"script_match": ratio >= 0.9, "script_ratio": round(ratio, 3)} def first_present(record: Mapping[str, Any], fields: tuple[str, ...]) -> Optional[str]: """Return the first non-empty string-like value from a set of fields.""" for field in fields: value = record.get(field) if value is None: continue value = str(value) if value.strip(): return value return None def extract_assisted_text(record: Mapping[str, Any]) -> Optional[str]: """Extract a model's mediated/assisted prompt from common output fields.""" return first_present(record, ASSISTED_TEXT_FIELDS) def extract_raw_prompt(record: Mapping[str, Any]) -> Optional[str]: """Extract the noisy user prompt from common input fields.""" return first_present(record, RAW_PROMPT_FIELDS) def compute_metrics( record: Mapping[str, Any], *, model: Optional[str] = None, noise: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Compute row-level APM benchmark metrics for one model output.""" raw_prompt = extract_raw_prompt(record) assisted_text = extract_assisted_text(record) if raw_prompt is None or assisted_text is None: return None b_raw = cognitive_burden(raw_prompt) b_assist = cognitive_burden(assisted_text) language = record.get("language") row: Dict[str, Any] = { "example_id": record.get("example_id"), "model": record.get("model") or model, "noise": record.get("noise") or noise, "language": language, "alpha": record.get("alpha"), **protocol_compliance(assisted_text), **language_script_match(assisted_text, language), "B_raw": b_raw, "B_assist": b_assist, "BRS": round(b_raw - b_assist, 3), } return row def flatten_judge_fields(record: Mapping[str, Any]) -> Dict[str, Any]: """Collect judge metrics, accepting nested or already-prefixed schemas.""" flattened: Dict[str, Any] = {} judge = record.get("judge") if isinstance(judge, Mapping): for key, value in judge.items(): flattened[f"judge_{key}"] = value for key, value in record.items(): if key.startswith("judge_"): flattened[key] = value return flattened def normalize_bool(value: Any) -> bool: """Convert common serialized boolean values into Python booleans.""" if isinstance(value, bool): return value if value is None: return False if isinstance(value, (int, float)): return bool(value) if isinstance(value, str): return value.strip().lower() in {"1", "true", "yes", "y", "pass"} return bool(value)