| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | from __future__ import annotations |
| 16 | |
| 17 | from typing import Any |
| 18 | |
| 19 | from .benchmark import OOS_LABEL, load_benchmark |
| 20 | from ..catalog import INTENTS |
| 21 | from ..decision import DEFAULT_THRESHOLD, _is_confusable_pair |
| 22 | from ..engine import Engine |
| 23 | from .metrics import ( |
| 24 | accuracy, |
| 25 | macro_f1, |
| 26 | per_class_scores, |
| 27 | percentile, |
| 28 | topk_accuracy, |
| 29 | ) |
| 30 | from ..observability import process |
| 31 | from ..similarity import SimilarityMatcher, get_default_matcher |
| 32 | |
| 33 | |
| 34 | _FALLBACK_LABEL = "__fallback__" |
| 35 | |
| 36 | |
| 37 | def run_evaluation( |
| 38 | threshold: float = DEFAULT_THRESHOLD, |
| 39 | matcher: SimilarityMatcher | None = None, |
| 40 | records: list[dict[str, Any]] | None = None, |
| 41 | ) -> dict[str, Any]: |
| 42 | |
| 43 | |
| 44 | matcher = matcher or get_default_matcher() |
| 45 | records = records if records is not None else load_benchmark() |
| 46 | labels = {i["intent"] for i in INTENTS} |
| 47 | engine = Engine() |
| 48 | |
| 49 | in_pairs: list[tuple[str, str]] = [] |
| 50 | covered_pairs: list[tuple[str, str]] = [] |
| 51 | topk_records: list[tuple[str, list[str]]] = [] |
| 52 | latencies: list[float] = [] |
| 53 | |
| 54 | covered = correct = false_fallback = 0 |
| 55 | oos_total = oos_caught = 0 |
| 56 | confusable_wrong = nonconfusable_wrong = 0 |
| 57 | wrong_pairs: list[tuple[str, str]] = [] |
| 58 | |
| 59 | for r in records: |
| 60 | role = r.get("role", "ziyaretci") |
| 61 | authenticated = role != "ziyaretci" |
| 62 | _, trace = process( |
| 63 | r["question"], role=role, authenticated=authenticated, matcher=matcher |
| 64 | ) |
| 65 | |
| 66 | |
| 67 | |
| 68 | pred = _reconsider(trace, threshold) |
| 69 | latencies.append(trace["latency_ms"]["total"]) |
| 70 | |
| 71 | expected = r["expected_intent"] |
| 72 | if expected == OOS_LABEL: |
| 73 | oos_total += 1 |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | response = engine.handle({ |
| 79 | "query": r["question"], |
| 80 | "session": {"role": role, "authenticated": authenticated}, |
| 81 | }) |
| 82 | if response["intent"] is None: |
| 83 | oos_caught += 1 |
| 84 | continue |
| 85 | |
| 86 | |
| 87 | ranked_intents = _ranked_intents(trace) |
| 88 | topk_records.append((expected, ranked_intents)) |
| 89 | |
| 90 | if pred is None: |
| 91 | false_fallback += 1 |
| 92 | in_pairs.append((expected, _FALLBACK_LABEL)) |
| 93 | else: |
| 94 | covered += 1 |
| 95 | in_pairs.append((expected, pred)) |
| 96 | covered_pairs.append((expected, pred)) |
| 97 | if pred == expected: |
| 98 | correct += 1 |
| 99 | else: |
| 100 | wrong_pairs.append((expected, pred)) |
| 101 | if _is_confusable_pair(expected, pred): |
| 102 | confusable_wrong += 1 |
| 103 | else: |
| 104 | nonconfusable_wrong += 1 |
| 105 | |
| 106 | in_scope_total = len(in_pairs) |
| 107 | report: dict[str, Any] = { |
| 108 | "threshold": threshold, |
| 109 | "in_scope_total": in_scope_total, |
| 110 | "oos_total": oos_total, |
| 111 | "macro_f1": macro_f1(in_pairs, labels), |
| 112 | "accuracy": accuracy(in_pairs), |
| 113 | "coverage": covered / in_scope_total if in_scope_total else 0.0, |
| 114 | "accuracy_on_covered": correct / covered if covered else 0.0, |
| 115 | "false_fallback": false_fallback, |
| 116 | "oos_recall": oos_caught / oos_total if oos_total else 0.0, |
| 117 | "top1_accuracy": topk_accuracy(topk_records, 1), |
| 118 | "top3_accuracy": topk_accuracy(topk_records, 3), |
| 119 | "confusable_wrong": confusable_wrong, |
| 120 | "nonconfusable_wrong": nonconfusable_wrong, |
| 121 | "wrong_pairs": wrong_pairs, |
| 122 | "latency_p50_ms": percentile(latencies, 50), |
| 123 | "latency_p95_ms": percentile(latencies, 95), |
| 124 | "per_class": per_class_scores(covered_pairs, labels), |
| 125 | } |
| 126 | return report |
| 127 | |
| 128 | |
| 129 | def _ranked_intents(trace: dict[str, Any]) -> list[str]: |
| 130 | |
| 131 | |
| 132 | if trace["rule_layer"]["hit"]: |
| 133 | return [trace["rule_layer"]["intent"]] |
| 134 | return [item["intent"] for item in trace["similarity"]["top_k"]] |
| 135 | |
| 136 | |
| 137 | def _reconsider(trace: dict[str, Any], threshold: float) -> str | None: |
| 138 | |
| 139 | |
| 140 | if trace["rule_layer"]["hit"]: |
| 141 | return trace["rule_layer"]["intent"] |
| 142 | if not trace["similarity"].get("in_domain", True): |
| 143 | return None |
| 144 | top_k = trace["similarity"]["top_k"] |
| 145 | if not top_k: |
| 146 | return None |
| 147 | top = top_k[0] |
| 148 | if top["score"] < threshold: |
| 149 | return None |
| 150 | return top["intent"] |
| 151 | |
| 152 | |
| 153 | def format_report(report: dict[str, Any]) -> str: |
| 154 | |
| 155 | |
| 156 | lines = [ |
| 157 | "================ DEĞERLENDİRME RAPORU ================", |
| 158 | f"Eşik (threshold) : {report['threshold']:.3f}", |
| 159 | f"In-scope / OOS : {report['in_scope_total']} / {report['oos_total']}", |
| 160 | "--- Genel ---", |
| 161 | f"Macro-F1 (BAŞLIK) : {report['macro_f1']:.3f}", |
| 162 | f"Accuracy : {report['accuracy']:.1%}", |
| 163 | f"Top-1 / Top-3 acc : {report['top1_accuracy']:.1%} / {report['top3_accuracy']:.1%}", |
| 164 | "--- Abstention (eşik) ---", |
| 165 | f"Coverage : {report['coverage']:.1%}", |
| 166 | f"Accuracy-on-covered : {report['accuracy_on_covered']:.1%}", |
| 167 | f"False fallback : {report['false_fallback']}", |
| 168 | f"OOS recall : {report['oos_recall']:.1%}", |
| 169 | "--- must_not_match ---", |
| 170 | f"Karışan çift (confusable) yanlış : {report['confusable_wrong']}", |
| 171 | f"Diğer (beklenmedik) yanlış : {report['nonconfusable_wrong']}", |
| 172 | "--- Latency ---", |
| 173 | f"p50 / p95 (ms) : {report['latency_p50_ms']:.3f} / {report['latency_p95_ms']:.3f}", |
| 174 | "--- En zayıf 8 intent (F1, kapsananlarda) ---", |
| 175 | ] |
| 176 | worst = sorted(report["per_class"], key=lambda s: (s.f1, -s.support)) |
| 177 | for s in worst[:8]: |
| 178 | lines.append( |
| 179 | f" {s.label:26s} P={s.precision:.2f} R={s.recall:.2f} F1={s.f1:.2f} (n={s.support})" |
| 180 | ) |
| 181 | if report["wrong_pairs"]: |
| 182 | lines.append("--- Yanlış tahminler (beklenen -> bulunan) ---") |
| 183 | for true, pred in report["wrong_pairs"]: |
| 184 | mark = "~" if _is_confusable_pair(true, pred) else "x" |
| 185 | lines.append(f" [{mark}] {true} -> {pred}") |
| 186 | lines.append("=====================================================") |
| 187 | return "\n".join(lines) |
| 188 | |
| 189 | |
| 190 | if __name__ == "__main__": |
| 191 | print(format_report(run_evaluation())) |