forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rule_based_chatbot

Clone
★ 0

0 watching0 forksPython1.2 MiBdaf5582Kadir Yönak3 months ago37 commits

benchmark.py128 lines, 4.3 KiBHistoryRawDownload
1"""Benchmark (değerlendirme) setinin yüklenmesi ve doğrulanması.
2
3Benchmark, motorun DÜRÜST ölçülmesi için `example_questions`'tan AYRI tutulan
4etiketli sorulardır. Her kayıt:
5 {"question": str, "expected_intent": str | "oos", "role": str?}
6
7`expected_intent == "oos"` -> kapsam dışı; motor bunları FALLBACK'e atmalıdır.
8"""
9
10from __future__ import annotations
11
12import json
13from pathlib import Path
14from typing import Any, Final
15
16
17OOS_LABEL: Final[str] = "oos"
18
19# Depo kökü: src/evaluation/benchmark.py -> parents[2] = proje kökü.
20DEFAULT_BENCHMARK_PATH: Final[Path] = (
21 Path(__file__).resolve().parents[2] / "data" / "benchmark.jsonl"
22)
23
24
25def load_benchmark(path: str | Path | None = None) -> list[dict[str, Any]]:
26 """Benchmark kayıtlarını JSONL dosyasından yükler.
27
28 Boş satırlar atlanır. Her satır 'question' ve 'expected_intent' içermelidir.
29
30 Raises:
31 FileNotFoundError: Dosya yoksa.
32 ValueError: Bir satır bozuksa veya zorunlu alan eksikse.
33 """
34
35 benchmark_path = Path(path) if path is not None else DEFAULT_BENCHMARK_PATH
36 if not benchmark_path.exists():
37 raise FileNotFoundError(f"Benchmark dosyası bulunamadı: {benchmark_path}")
38
39 records: list[dict[str, Any]] = []
40 with benchmark_path.open("r", encoding="utf-8") as handle:
41 for line_no, raw_line in enumerate(handle, start=1):
42 line = raw_line.strip()
43 if not line:
44 continue
45 try:
46 record = json.loads(line)
47 except json.JSONDecodeError as exc:
48 raise ValueError(f"Benchmark satırı {line_no} geçersiz JSON: {exc}") from exc
49 if "question" not in record or "expected_intent" not in record:
50 raise ValueError(
51 f"Benchmark satırı {line_no}: 'question' ve 'expected_intent' zorunlu."
52 )
53 records.append(record)
54 return records
55
56
57def validate_benchmark(
58 records: list[dict[str, Any]],
59 known_intents: set[str],
60 known_roles: set[str] | None = None,
61 example_questions: set[str] | None = None,
62) -> dict[str, int]:
63 """Benchmark kayıtlarının tutarlılığını doğrular.
64
65 Kontroller:
66 - question boş olmayan metin.
67 - expected_intent ya bilinen bir intent ya da OOS_LABEL.
68 - (verilirse) role bilinen bir rol.
69 - benchmark içinde tekrarlanan soru yok.
70 - (verilirse) hiçbir soru example_questions ile örtüşmez.
71 - en az bir OOS kaydı bulunur.
72
73 Returns:
74 Sayımlar: total, in_scope, oos, intents_covered.
75
76 Raises:
77 ValueError: Herhangi bir kontrol başarısızsa.
78 """
79
80 errors: list[str] = []
81 if not records:
82 raise ValueError("Benchmark boş olamaz.")
83
84 seen_questions: set[str] = set()
85 covered: set[str] = set()
86 oos_count = 0
87
88 for index, record in enumerate(records):
89 question = record.get("question")
90 expected = record.get("expected_intent")
91 role = record.get("role")
92
93 if not isinstance(question, str) or not question.strip():
94 errors.append(f"[{index}] boş/metin olmayan question.")
95 continue
96
97 norm_q = question.strip().casefold()
98 if norm_q in seen_questions:
99 errors.append(f"[{index}] tekrarlanan soru: {question!r}")
100 seen_questions.add(norm_q)
101
102 if expected == OOS_LABEL:
103 oos_count += 1
104 elif expected in known_intents:
105 covered.add(expected)
106 else:
107 errors.append(f"[{index}] bilinmeyen expected_intent: {expected!r}")
108
109 if role is not None and known_roles is not None and role not in known_roles:
110 errors.append(f"[{index}] bilinmeyen rol: {role!r}")
111
112 if example_questions is not None and norm_q in example_questions:
113 errors.append(
114 f"[{index}] soru example_questions ile örtüşüyor (benchmark ayrı olmalı): {question!r}"
115 )
116
117 if oos_count == 0:
118 errors.append("En az bir OOS (kapsam dışı) kaydı gerekli.")
119
120 if errors:
121 raise ValueError("Benchmark doğrulanamadı:\n- " + "\n- ".join(errors))
122
123 return {
124 "total": len(records),
125 "in_scope": len(records) - oos_count,
126 "oos": oos_count,
127 "intents_covered": len(covered),
128 }