""" Clarus F1 Binary Scorer v1.0.0 DETERMINISTIC GUARANTEE: This scorer produces identical results for identical inputs. No randomness, no probabilistic thresholds, no subjective parameters. Suitable for: - Performance system validation - Audit trail documentation - Reproducible research - Pre-failure stint monitoring """ import csv import hashlib import json import sys from datetime import datetime, timezone from typing import Dict, List __version__ = "1.0.0" __scorer_id__ = "clarus-f1-stint-collapse-v1" def _find_label_column(fieldnames: List[str]) -> str: for name in fieldnames: if name.startswith("label_"): return name raise ValueError("No label_ target column found in reference CSV.") def _normalize_binary(value: str) -> int: value = str(value).strip().lower() positive_values = { "1", "1.0", "true", "yes", "y", "positive", "pos", "present", "active" } negative_values = { "0", "0.0", "false", "no", "n", "negative", "neg", "absent", "inactive" } if value in positive_values: return 1 if value in negative_values: return 0 raise ValueError(f"Invalid binary label value: {value}") def _safe_div(n: float, d: float) -> float: return n / d if d else 0.0 def _read_rows(path: str) -> List[Dict[str, str]]: with open(path, "r", encoding="utf-8") as f: return list(csv.DictReader(f)) def _sha256_file(path: str) -> str: hasher = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(8192), b""): hasher.update(chunk) return hasher.hexdigest() def score(reference_path: str, predictions_path: str) -> Dict[str, object]: reference_rows = _read_rows(reference_path) prediction_rows = _read_rows(predictions_path) if not reference_rows: raise ValueError("Reference CSV is empty.") if not prediction_rows: raise ValueError("Predictions CSV is empty.") if len(reference_rows) != len(prediction_rows): raise ValueError("Prediction row count does not match reference row count.") label_col = _find_label_column(list(reference_rows[0].keys())) y_true = [_normalize_binary(row[label_col]) for row in reference_rows] pred_key = None for candidate in ["prediction", "pred", "label", "output"]: if candidate in prediction_rows[0]: pred_key = candidate break if pred_key is None: raise ValueError( "Predictions file must contain one of: prediction, pred, label, output" ) y_pred = [_normalize_binary(row[pred_key]) for row in prediction_rows] tp = sum(1 for yt, yp in zip(y_true, y_pred) if yt == 1 and yp == 1) tn = sum(1 for yt, yp in zip(y_true, y_pred) if yt == 0 and yp == 0) fp = sum(1 for yt, yp in zip(y_true, y_pred) if yt == 0 and yp == 1) fn = sum(1 for yt, yp in zip(y_true, y_pred) if yt == 1 and yp == 0) accuracy = _safe_div(tp + tn, len(y_true)) precision = _safe_div(tp, tp + fp) recall = _safe_div(tp, tp + fn) f1 = _safe_div(2 * precision * recall, precision + recall) false_activation_rate = _safe_div(fp, fp + tn) missed_latent_activation_rate = _safe_div(fn, fn + tp) positive_rate = _safe_div(sum(y_true), len(y_true)) negative_rate = _safe_div(len(y_true) - sum(y_true), len(y_true)) return { "scorer_version": __version__, "scorer_id": __scorer_id__, "evaluation_timestamp_utc": datetime.now(timezone.utc).isoformat(), "reference_file_hash_sha256": _sha256_file(reference_path), "predictions_file_hash_sha256": _sha256_file(predictions_path), "label_column": label_col, "primary_metric": "missed_latent_activation_rate", "secondary_metric": "false_activation_rate", "num_rows": len(y_true), "prediction_interpretation": "binary labels only; no score threshold applied", "class_balance": { "positive_rate": round(positive_rate, 4), "negative_rate": round(negative_rate, 4), }, "metrics": { "accuracy": round(accuracy, 4), "precision": round(precision, 4), "recall": round(recall, 4), "f1": round(f1, 4), "false_activation_rate": round(false_activation_rate, 4), "missed_latent_activation_rate": round(missed_latent_activation_rate, 4), }, "confusion_matrix": { "tp": tp, "tn": tn, "fp": fp, "fn": fn, }, "compliance_metadata": { "scorer_type": "binary_classification", "deterministic": True, "threshold_free": True, "strict_row_alignment_required": True, "accepted_prediction_columns": ["prediction", "pred", "label", "output"], "accepted_positive_labels": [ "1", "1.0", "true", "yes", "y", "positive", "pos", "present", "active" ], "accepted_negative_labels": [ "0", "0.0", "false", "no", "n", "negative", "neg", "absent", "inactive" ], }, } if __name__ == "__main__": if len(sys.argv) != 3: print( "Usage: python scorer.py ", file=sys.stderr, ) sys.exit(1) reference_path = sys.argv[1] predictions_path = sys.argv[2] results = score(reference_path, predictions_path) print(json.dumps(results, indent=2))