from dataclasses import dataclass from typing import Dict, Any, List import re REQ_KEYS = [ "inferred_tactical_rules", "rule_trigger_conditions", "rule_execution_latency", "rule_consistency_score", "dominant_rule_clusters", ] @dataclass class ScoreResult: score: float details: Dict[str, Any] def _has_if_then(p: str) -> bool: return ("if " in p and " then " in p) or ("r" in p and ":" in p and "if" in p) def _has_latency(p: str) -> bool: return bool(re.search(r"\b\d+(\.\d+)?\b", p)) and ("sec" in p or "s" in p or "latency" in p) def _has_trigger_fields(p: str) -> bool: # Look for simple key=value trigger style return bool(re.search(r"\b[a-z_]+=[a-z0-9_]+\b", p)) def _has_cluster(p: str) -> bool: return any(w in p for w in [ "counter_press", "rest_defense", "box_protection", "direct_defense", "shape_reset", "zone_press", "cluster", ]) def score(sample: Dict[str, Any], prediction: str) -> ScoreResult: p = (prediction or "").lower() words_ok = len(p.split()) <= 950 hits = sum(1 for k in REQ_KEYS if k.lower() in p) has_rule_form = _has_if_then(p) has_latency = _has_latency(p) has_triggers = _has_trigger_fields(p) has_cluster = _has_cluster(p) raw = ( 0.20 * int(words_ok) + 0.30 * (hits / len(REQ_KEYS)) + 0.20 * int(has_rule_form) + 0.15 * int(has_triggers) + 0.10 * int(has_latency) + 0.05 * int(has_cluster) ) return ScoreResult( score=min(1.0, raw), details={ "id": sample.get("id"), "hits": hits, "has_rule_form": has_rule_form, "has_triggers": has_triggers, "has_latency": has_latency, }, ) def aggregate(results: List[ScoreResult]) -> Dict[str, Any]: if not results: return {"mean": 0.0, "n": 0} return { "mean": sum(r.score for r in results) / len(results), "n": len(results), }