| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | from __future__ import annotations |
| 18 | |
| 19 | import argparse |
| 20 | import json |
| 21 | from collections import Counter |
| 22 | from pathlib import Path |
| 23 | from typing import Any, Iterable |
| 24 | |
| 25 | from src.access import AccessOutcome |
| 26 | from src.catalog import route_for |
| 27 | from src.engine import Engine |
| 28 | from src.evaluation.benchmark import DEFAULT_BENCHMARK_PATH, OOS_LABEL, load_benchmark |
| 29 | from src.role_spaces import get_role_space |
| 30 | |
| 31 | |
| 32 | PROJECT_ROOT = Path(__file__).resolve().parent |
| 33 | DEFAULT_JSON_OUTPUT = PROJECT_ROOT / "data" / "benchmark_results.json" |
| 34 | DEFAULT_MARKDOWN_OUTPUT = PROJECT_ROOT / "docs" / "benchmarks" / "BENCHMARK_SONUCLARI.md" |
| 35 | RESULT_SCHEMA_VERSION = "benchmark-results-v1" |
| 36 | ROLE_LABELS = { |
| 37 | "ziyaretci": "Ziyaretçi", |
| 38 | "veli": "Veli", |
| 39 | "ogrenci": "Öğrenci", |
| 40 | "ogretmen": "Öğretmen", |
| 41 | "yonetici": "Yönetici", |
| 42 | "admin": "ADMIN", |
| 43 | } |
| 44 | |
| 45 | _UPPER_REPORT_REDIRECTS = { |
| 46 | "report_card_view": "student_marks_lookup", |
| 47 | "attendance_view": "student_attendance_lookup", |
| 48 | "exam_finish_result": "student_marks_lookup", |
| 49 | } |
| 50 | _UPPER_ROLES = {"ogretmen", "yonetici", "admin"} |
| 51 | |
| 52 | |
| 53 | def _expected_contract(record: dict[str, Any]) -> dict[str, Any]: |
| 54 | |
| 55 | |
| 56 | expected = record["expected_intent"] |
| 57 | role = record.get("role", "ziyaretci") |
| 58 | if expected == OOS_LABEL: |
| 59 | outcome = str(record.get("expected_outcome") or "fallback") |
| 60 | response_id = str( |
| 61 | record.get("expected_response_id") |
| 62 | or ("fallback_clarification" if outcome == "fallback" else "out_of_scope_action") |
| 63 | ) |
| 64 | reason = str( |
| 65 | record.get("expected_reason_code") |
| 66 | or ("out_of_scope" if outcome == "fallback" else "scope_boundary_action") |
| 67 | ) |
| 68 | return { |
| 69 | "intent": OOS_LABEL, |
| 70 | "outcome": outcome, |
| 71 | "meta_action_id": None, |
| 72 | "response_ids": [response_id], |
| 73 | "reason_code": reason, |
| 74 | "fallback": outcome == "fallback", |
| 75 | "auth_action": None, |
| 76 | "navigation_route": None, |
| 77 | "meta_route_key": None, |
| 78 | } |
| 79 | |
| 80 | view = get_role_space(role).view_for(expected) |
| 81 | if view is None: |
| 82 | |
| 83 | |
| 84 | return {"intent": expected} |
| 85 | |
| 86 | served_intent = expected |
| 87 | redirected = _UPPER_REPORT_REDIRECTS.get(expected) if role in _UPPER_ROLES else None |
| 88 | redirect_route: tuple[str, str] | None = None |
| 89 | if redirected is not None: |
| 90 | target_view = get_role_space(role).view_for(redirected) |
| 91 | target_route = route_for(redirected) |
| 92 | if ( |
| 93 | target_view is not None |
| 94 | and target_view.outcome is AccessOutcome.ALLOW |
| 95 | and target_route is not None |
| 96 | ): |
| 97 | view = target_view |
| 98 | served_intent = redirected |
| 99 | redirect_route = target_route |
| 100 | |
| 101 | denied = view.outcome is AccessOutcome.DENY |
| 102 | response_ids = [view.response_id] |
| 103 | navigation_route: str | None = None |
| 104 | if redirect_route is not None: |
| 105 | response_ids = ["student_report_redirect"] |
| 106 | navigation_route = redirect_route[0] |
| 107 | elif not denied: |
| 108 | if expected in {"report_card_view", "attendance_view"} and role != "ogrenci": |
| 109 | navigation_route = None |
| 110 | else: |
| 111 | target = route_for(expected) |
| 112 | navigation_route = target[0] if target else None |
| 113 | |
| 114 | |
| 115 | if expected == "nav_overview": |
| 116 | response_ids.append("section_overview") |
| 117 | |
| 118 | return { |
| 119 | "intent": expected, |
| 120 | "outcome": view.outcome.value, |
| 121 | "meta_action_id": served_intent, |
| 122 | "response_ids": sorted(set(response_ids)), |
| 123 | "reason_code": view.reason_code.value, |
| 124 | "fallback": False, |
| 125 | "auth_action": ( |
| 126 | "login_required" if denied and role == "ziyaretci" |
| 127 | else "role_insufficient" if denied |
| 128 | else None |
| 129 | ), |
| 130 | "navigation_route": navigation_route, |
| 131 | "meta_route_key": view.route_key if not denied else None, |
| 132 | } |
| 133 | |
| 134 | |
| 135 | def _contract_failures( |
| 136 | expectation: dict[str, Any], |
| 137 | response: dict[str, Any], |
| 138 | ) -> list[str]: |
| 139 | |
| 140 | |
| 141 | actual_intent = response.get("intent") or OOS_LABEL |
| 142 | failures: list[str] = [] |
| 143 | if actual_intent != expectation["intent"]: |
| 144 | failures.append(f"intent: {expectation['intent']} != {actual_intent}") |
| 145 | if "outcome" not in expectation: |
| 146 | return failures |
| 147 | |
| 148 | response_id = response.get("response_id") |
| 149 | if response_id not in expectation["response_ids"]: |
| 150 | failures.append( |
| 151 | "response_id: " + "/".join(expectation["response_ids"]) |
| 152 | + f" != {response_id}" |
| 153 | ) |
| 154 | if bool(response.get("fallback")) != expectation["fallback"]: |
| 155 | failures.append( |
| 156 | f"fallback: {expectation['fallback']} != {bool(response.get('fallback'))}" |
| 157 | ) |
| 158 | if response.get("auth_action") != expectation["auth_action"]: |
| 159 | failures.append( |
| 160 | f"auth_action: {expectation['auth_action']} != {response.get('auth_action')}" |
| 161 | ) |
| 162 | |
| 163 | navigation = response.get("navigation") |
| 164 | actual_route = navigation.get("route") if isinstance(navigation, dict) else None |
| 165 | if actual_route != expectation["navigation_route"]: |
| 166 | failures.append( |
| 167 | f"navigation.route: {expectation['navigation_route']} != {actual_route}" |
| 168 | ) |
| 169 | if isinstance(navigation, dict) and navigation.get("available") is not True: |
| 170 | failures.append("navigation.available true değil") |
| 171 | |
| 172 | meta = response.get("assistant_meta") |
| 173 | if not isinstance(meta, dict): |
| 174 | failures.append("assistant_meta eksik") |
| 175 | else: |
| 176 | if meta.get("outcome") != expectation["outcome"]: |
| 177 | failures.append( |
| 178 | f"assistant_meta.outcome: {expectation['outcome']} != {meta.get('outcome')}" |
| 179 | ) |
| 180 | if meta.get("action_id") != expectation["meta_action_id"]: |
| 181 | failures.append( |
| 182 | "assistant_meta.action_id: " |
| 183 | f"{expectation['meta_action_id']} != {meta.get('action_id')}" |
| 184 | ) |
| 185 | if meta.get("reason_code") != expectation["reason_code"]: |
| 186 | failures.append( |
| 187 | "assistant_meta.reason_code: " |
| 188 | f"{expectation['reason_code']} != {meta.get('reason_code')}" |
| 189 | ) |
| 190 | meta_navigation = meta.get("navigation") |
| 191 | actual_key = ( |
| 192 | meta_navigation.get("route_key") if isinstance(meta_navigation, dict) else None |
| 193 | ) |
| 194 | if actual_key != expectation["meta_route_key"]: |
| 195 | failures.append( |
| 196 | f"assistant_meta.navigation: {expectation['meta_route_key']} != {actual_key}" |
| 197 | ) |
| 198 | |
| 199 | if not isinstance(response.get("text"), str) or not response.get("text", "").strip(): |
| 200 | failures.append("kullanıcı metni boş") |
| 201 | return failures |
| 202 | |
| 203 | |
| 204 | def collect_results( |
| 205 | records: Iterable[dict[str, Any]] | None = None, |
| 206 | *, |
| 207 | engine: Engine | None = None, |
| 208 | ) -> list[dict[str, Any]]: |
| 209 | |
| 210 | |
| 211 | rows = list(load_benchmark() if records is None else records) |
| 212 | runner = engine or Engine() |
| 213 | results: list[dict[str, Any]] = [] |
| 214 | |
| 215 | for index, record in enumerate(rows, start=1): |
| 216 | role = record.get("role", "ziyaretci") |
| 217 | trace_id = f"benchmark-{index:04d}" |
| 218 | response = runner.handle({ |
| 219 | "query": record["question"], |
| 220 | "trace_id": trace_id, |
| 221 | "session": { |
| 222 | "role": role, |
| 223 | "authenticated": role != "ziyaretci", |
| 224 | }, |
| 225 | }) |
| 226 | expected = record["expected_intent"] |
| 227 | actual = response.get("intent") or OOS_LABEL |
| 228 | expectation = _expected_contract(record) |
| 229 | failure_reasons = _contract_failures(expectation, response) |
| 230 | meta = response.get("assistant_meta") or {} |
| 231 | results.append({ |
| 232 | "index": index, |
| 233 | "trace_id": trace_id, |
| 234 | "question": record["question"], |
| 235 | "role": role, |
| 236 | "expected_intent": expected, |
| 237 | "actual_intent": actual, |
| 238 | "passed": not failure_reasons, |
| 239 | "failure_reasons": failure_reasons, |
| 240 | "expectation": expectation, |
| 241 | "response_id": response.get("response_id"), |
| 242 | "confidence": float(response.get("confidence") or 0.0), |
| 243 | "fallback": bool(response.get("fallback")), |
| 244 | "auth_action": response.get("auth_action"), |
| 245 | "navigation": response.get("navigation"), |
| 246 | "assistant_outcome": meta.get("outcome"), |
| 247 | "assistant_reason_code": meta.get("reason_code"), |
| 248 | "text": response.get("text") or "", |
| 249 | "response": response, |
| 250 | }) |
| 251 | return results |
| 252 | |
| 253 | |
| 254 | def summarize_results(results: Iterable[dict[str, Any]]) -> dict[str, Any]: |
| 255 | |
| 256 | |
| 257 | rows = list(results) |
| 258 | role_counts: dict[str, Counter[str]] = {} |
| 259 | for row in rows: |
| 260 | stats = role_counts.setdefault(row["role"], Counter()) |
| 261 | stats["total"] += 1 |
| 262 | stats["passed" if row["passed"] else "failed"] += 1 |
| 263 | |
| 264 | ordered_roles = [role for role in ROLE_LABELS if role in role_counts] |
| 265 | ordered_roles.extend(sorted(set(role_counts) - set(ordered_roles))) |
| 266 | by_role: dict[str, dict[str, int | float]] = {} |
| 267 | for role in ordered_roles: |
| 268 | stats = role_counts[role] |
| 269 | total = stats["total"] |
| 270 | by_role[role] = { |
| 271 | "total": total, |
| 272 | "passed": stats["passed"], |
| 273 | "failed": stats["failed"], |
| 274 | "pass_rate": stats["passed"] / total if total else 0.0, |
| 275 | } |
| 276 | |
| 277 | total = len(rows) |
| 278 | passed = sum(bool(row["passed"]) for row in rows) |
| 279 | return { |
| 280 | "total": total, |
| 281 | "passed": passed, |
| 282 | "failed": total - passed, |
| 283 | "pass_rate": passed / total if total else 0.0, |
| 284 | "by_role": by_role, |
| 285 | } |
| 286 | |
| 287 | |
| 288 | def _portable_source_path(path: Path) -> str: |
| 289 | resolved = path.resolve() |
| 290 | try: |
| 291 | return resolved.relative_to(PROJECT_ROOT).as_posix() |
| 292 | except ValueError: |
| 293 | return str(resolved) |
| 294 | |
| 295 | |
| 296 | def build_json_report( |
| 297 | results: Iterable[dict[str, Any]], |
| 298 | *, |
| 299 | source: Path = DEFAULT_BENCHMARK_PATH, |
| 300 | ) -> dict[str, Any]: |
| 301 | |
| 302 | |
| 303 | rows = list(results) |
| 304 | serialized_results = [ |
| 305 | { |
| 306 | "index": row["index"], |
| 307 | "trace_id": row["trace_id"], |
| 308 | "question": row["question"], |
| 309 | "role": row["role"], |
| 310 | "expected_intent": row["expected_intent"], |
| 311 | "actual_intent": row["actual_intent"], |
| 312 | "passed": row["passed"], |
| 313 | "failure_reasons": row["failure_reasons"], |
| 314 | "expected_contract": row["expectation"], |
| 315 | "response": row["response"], |
| 316 | } |
| 317 | for row in rows |
| 318 | ] |
| 319 | return { |
| 320 | "schema_version": RESULT_SCHEMA_VERSION, |
| 321 | "source": _portable_source_path(source), |
| 322 | "summary": summarize_results(rows), |
| 323 | "results": serialized_results, |
| 324 | } |
| 325 | |
| 326 | |
| 327 | def _table_text(value: object) -> str: |
| 328 | return str(value).replace("|", "\\|").replace("\n", "<br>") |
| 329 | |
| 330 | |
| 331 | def _quote(text: str) -> str: |
| 332 | lines = text.splitlines() or [""] |
| 333 | return "\n".join("> " + line if line else ">" for line in lines) |
| 334 | |
| 335 | |
| 336 | def _inline_json(value: object) -> str: |
| 337 | if value is None: |
| 338 | return "None" |
| 339 | return json.dumps(value, ensure_ascii=False, sort_keys=True) |
| 340 | |
| 341 | |
| 342 | def render_markdown(results: Iterable[dict[str, Any]]) -> str: |
| 343 | |
| 344 | |
| 345 | rows = list(results) |
| 346 | passed = sum(bool(row["passed"]) for row in rows) |
| 347 | failed = len(rows) - passed |
| 348 | rate = passed / len(rows) if rows else 0.0 |
| 349 | by_role: dict[str, Counter[str]] = {} |
| 350 | for row in rows: |
| 351 | stats = by_role.setdefault(row["role"], Counter()) |
| 352 | stats["total"] += 1 |
| 353 | stats["passed" if row["passed"] else "failed"] += 1 |
| 354 | |
| 355 | out = [ |
| 356 | "# Çelebi Benchmark Soru-Cevap Sonuçları", |
| 357 | "", |
| 358 | "Bu dosya `python benchmark_qa_report.py` komutuyla tek gold kaynak " |
| 359 | "`data/benchmark.jsonl` üzerinden üretilir. Birleşik ve rol bazında " |
| 360 | "filtrelenebilir makine sonucu `data/benchmark_results.json` dosyasındadır. " |
| 361 | "Her soru, kullanıcının gördüğü tam `Engine.handle` akışında çalıştırılır. " |
| 362 | "PASS; intent, rol sonucu, response kimliği ve iki yönlendirme " |
| 363 | "sözleşmesinin tamamını kapsar.", |
| 364 | "", |
| 365 | "## Özet", |
| 366 | "", |
| 367 | f"- Toplam soru: **{len(rows)}**", |
| 368 | f"- PASS: **{passed}**", |
| 369 | f"- FAIL: **{failed}**", |
| 370 | f"- Kullanıcı-akışı sözleşme başarısı: **{rate:.1%}**", |
| 371 | "", |
| 372 | "| Rol | Toplam | PASS | FAIL |", |
| 373 | "|---|---:|---:|---:|", |
| 374 | ] |
| 375 | for role in ("ziyaretci", "veli", "ogrenci", "ogretmen", "yonetici", "admin"): |
| 376 | stats = by_role.get(role) |
| 377 | if not stats: |
| 378 | continue |
| 379 | out.append( |
| 380 | f"| {ROLE_LABELS.get(role, role)} | {stats['total']} | " |
| 381 | f"{stats['passed']} | {stats['failed']} |" |
| 382 | ) |
| 383 | |
| 384 | failures = [row for row in rows if not row["passed"]] |
| 385 | out.extend(["", "## Hatalar", ""]) |
| 386 | if not failures: |
| 387 | out.append("Tüm benchmark soruları beklenen intent ile sonuçlandı.") |
| 388 | else: |
| 389 | out.extend([ |
| 390 | "| # | Rol | Soru | Beklenen | Gerçek | Sözleşme hataları |", |
| 391 | "|---:|---|---|---|---|---|", |
| 392 | ]) |
| 393 | for row in failures: |
| 394 | out.append( |
| 395 | f"| {row['index']} | {ROLE_LABELS.get(row['role'], row['role'])} | " |
| 396 | f"{_table_text(row['question'])} | `{row['expected_intent']}` | " |
| 397 | f"`{row['actual_intent']}` | {_table_text('; '.join(row['failure_reasons']))} |" |
| 398 | ) |
| 399 | |
| 400 | out.extend(["", "## Tüm soru ve cevaplar", ""]) |
| 401 | for row in rows: |
| 402 | status = "PASS" if row["passed"] else "FAIL" |
| 403 | role_label = ROLE_LABELS.get(row["role"], row["role"]) |
| 404 | out.extend([ |
| 405 | f"### {row['index']:03d} · {status} · {role_label}", |
| 406 | "", |
| 407 | f"- Soru: {_table_text(row['question'])}", |
| 408 | f"- Beklenen intent: `{row['expected_intent']}`", |
| 409 | f"- Gerçek intent: `{row['actual_intent']}`", |
| 410 | f"- response_id: `{row['response_id']}`", |
| 411 | f"- confidence: `{row['confidence']:.4f}`", |
| 412 | f"- fallback: `{str(row['fallback']).lower()}`", |
| 413 | f"- auth_action: `{row['auth_action']}`", |
| 414 | f"- navigation: `{_inline_json(row['navigation'])}`", |
| 415 | f"- assistant outcome/reason: `{row['assistant_outcome']}` / " |
| 416 | f"`{row['assistant_reason_code']}`", |
| 417 | f"- Sözleşme: `{'PASS' if row['passed'] else '; '.join(row['failure_reasons'])}`", |
| 418 | "", |
| 419 | _quote(row["text"]), |
| 420 | "", |
| 421 | ]) |
| 422 | return "\n".join(out).rstrip() + "\n" |
| 423 | |
| 424 | |
| 425 | def write_reports( |
| 426 | *, |
| 427 | benchmark_path: Path = DEFAULT_BENCHMARK_PATH, |
| 428 | json_output: Path = DEFAULT_JSON_OUTPUT, |
| 429 | markdown_output: Path | None = DEFAULT_MARKDOWN_OUTPUT, |
| 430 | engine: Engine | None = None, |
| 431 | ) -> tuple[Path, Path | None, list[dict[str, Any]]]: |
| 432 | |
| 433 | |
| 434 | records = load_benchmark(benchmark_path) |
| 435 | results = collect_results(records, engine=engine) |
| 436 | |
| 437 | json_output.parent.mkdir(parents=True, exist_ok=True) |
| 438 | report = build_json_report(results, source=benchmark_path) |
| 439 | json_output.write_text( |
| 440 | json.dumps(report, ensure_ascii=False, indent=2) + "\n", |
| 441 | encoding="utf-8", |
| 442 | ) |
| 443 | |
| 444 | if markdown_output is not None: |
| 445 | markdown_output.parent.mkdir(parents=True, exist_ok=True) |
| 446 | markdown_output.write_text(render_markdown(results), encoding="utf-8") |
| 447 | return json_output, markdown_output, results |
| 448 | |
| 449 | |
| 450 | def main() -> int: |
| 451 | parser = argparse.ArgumentParser(description=__doc__) |
| 452 | parser.add_argument("--benchmark", type=Path, default=DEFAULT_BENCHMARK_PATH) |
| 453 | parser.add_argument("--json-output", type=Path, default=DEFAULT_JSON_OUTPUT) |
| 454 | parser.add_argument("--markdown-output", type=Path, default=DEFAULT_MARKDOWN_OUTPUT) |
| 455 | parser.add_argument( |
| 456 | "--no-markdown", |
| 457 | action="store_true", |
| 458 | help="İnsan raporunu yazma; yalnız birleşik JSON üret.", |
| 459 | ) |
| 460 | parser.add_argument( |
| 461 | "--strict", |
| 462 | action="store_true", |
| 463 | help="En az bir FAIL varsa süreç kodunu 1 yap.", |
| 464 | ) |
| 465 | args = parser.parse_args() |
| 466 | json_output, markdown_output, results = write_reports( |
| 467 | benchmark_path=args.benchmark, |
| 468 | json_output=args.json_output, |
| 469 | markdown_output=None if args.no_markdown else args.markdown_output, |
| 470 | ) |
| 471 | failed = sum(not row["passed"] for row in results) |
| 472 | outputs = str(json_output) |
| 473 | if markdown_output is not None: |
| 474 | outputs += f", {markdown_output}" |
| 475 | print(f"{len(results)} soru -> {outputs} (FAIL={failed})") |
| 476 | return 1 if args.strict and failed else 0 |
| 477 | |
| 478 | |
| 479 | if __name__ == "__main__": |
| 480 | raise SystemExit(main()) |