| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | from __future__ import annotations |
| 13 | |
| 14 | import argparse |
| 15 | import hashlib |
| 16 | import json |
| 17 | import re |
| 18 | import unicodedata |
| 19 | from collections import Counter, defaultdict |
| 20 | from dataclasses import dataclass, replace |
| 21 | from pathlib import Path |
| 22 | from typing import Any, Final, Iterable, Iterator, Mapping, Sequence |
| 23 | |
| 24 | from src.access import AccessOutcome |
| 25 | from src.catalog import FALLBACK, INTENTS, ROLE_HIERARCHY, route_for |
| 26 | from src.engine import Engine |
| 27 | from src.role_spaces import get_role_space |
| 28 | |
| 29 | |
| 30 | PROJECT_ROOT: Final[Path] = Path(__file__).resolve().parent |
| 31 | DEFAULT_BENCHMARK_PATH: Final[Path] = PROJECT_ROOT / "data" / "benchmark.jsonl" |
| 32 | DEFAULT_NEAR_OOS_PATH: Final[Path] = PROJECT_ROOT / "data" / "near_oos.jsonl" |
| 33 | DEFAULT_DATA_OUTPUT: Final[Path] = PROJECT_ROOT / "data" / "stress_benchmark.jsonl" |
| 34 | DEFAULT_RESULTS_OUTPUT: Final[Path] = PROJECT_ROOT / "data" / "stress_benchmark_results.jsonl" |
| 35 | DEFAULT_REPORT_OUTPUT: Final[Path] = ( |
| 36 | PROJECT_ROOT / "docs" / "benchmarks" / "STRES_BENCHMARK_SONUCLARI.md" |
| 37 | ) |
| 38 | |
| 39 | GENERATOR_VERSION: Final[str] = "stress-v3.5.0" |
| 40 | |
| 41 | |
| 42 | |
| 43 | MUTATION_SEED_VERSION: Final[str] = "stress-v3.4.0" |
| 44 | OOS_LABEL: Final[str] = "oos" |
| 45 | DEFAULT_IN_SCOPE_COUNT: Final[int] = 9_000 |
| 46 | DEFAULT_OOS_COUNT: Final[int] = 1_000 |
| 47 | DEFAULT_TOTAL_COUNT: Final[int] = DEFAULT_IN_SCOPE_COUNT + DEFAULT_OOS_COUNT |
| 48 | DEFAULT_REPORT_CHUNK_SIZE: Final[int] = 400 |
| 49 | MIN_REPORT_CHUNK_SIZE: Final[int] = 250 |
| 50 | MAX_REPORT_CHUNK_SIZE: Final[int] = 500 |
| 51 | |
| 52 | MUTATION_FAMILIES: Final[tuple[str, ...]] = ( |
| 53 | "semantic_paraphrase", "sentence_form", "ui_label_tr_en", "role_context", |
| 54 | "turkish_ascii", "conversational_filler", "punctuation_case", "single_typo", |
| 55 | "state_error", "compound", |
| 56 | ) |
| 57 | OOS_MUTATION_FAMILIES: Final[tuple[str, ...]] = ( |
| 58 | "semantic_paraphrase", "sentence_form", "role_context", "turkish_ascii", |
| 59 | "conversational_filler", "punctuation_case", "single_typo", "compound", |
| 60 | ) |
| 61 | |
| 62 | ROLE_LABELS: Final[dict[str, str]] = { |
| 63 | "ziyaretci": "Ziyaretçi", "veli": "Veli", "ogrenci": "Öğrenci", |
| 64 | "ogretmen": "Öğretmen", "yonetici": "Yönetici", "admin": "ADMIN", |
| 65 | } |
| 66 | SOCIAL_INTENTS: Final[frozenset[str]] = frozenset({ |
| 67 | "greeting", "smalltalk", "thanks", "farewell", "bot_identity", |
| 68 | }) |
| 69 | _OTHER_PERSON_SAFETY_INTENTS: Final[frozenset[str]] = frozenset({ |
| 70 | "exam_grade_student", "student_marks_lookup", "student_attendance_lookup", |
| 71 | }) |
| 72 | _POSSESSIVE_NAME_RE: Final[re.Pattern[str]] = re.compile( |
| 73 | r"\b[A-ZÇĞİÖŞÜ][a-zçğıöşü]{2,}['’](?:n?in|n?ın|n?un|n?ün)\b" |
| 74 | ) |
| 75 | STATE_ERROR_ALWAYS_EXCLUDED: Final[frozenset[str]] = SOCIAL_INTENTS | frozenset({ |
| 76 | "platform_info", "help_capabilities", "guide_info", "roles_permissions", |
| 77 | "privacy_security", "exam_modes_info", "weighted_average_info", |
| 78 | "attendance_rate_info", "parent_info", "calendar_info", "today_info", |
| 79 | "nav_overview", "branches_info", "notification_settings_info", |
| 80 | }) |
| 81 | |
| 82 | _WORD_RE: Final[re.Pattern[str]] = re.compile(r"[^\W\d_]+", re.UNICODE) |
| 83 | _TRAILING_PUNCTUATION: Final[str] = " \t\r\n?!.,;:…" |
| 84 | _TURKISH_ASCII_TABLE: Final[dict[int, str]] = str.maketrans({ |
| 85 | "ç": "c", "Ç": "C", "ğ": "g", "Ğ": "G", "ı": "i", "İ": "I", |
| 86 | "ö": "o", "Ö": "O", "ş": "s", "Ş": "S", "ü": "u", "Ü": "U", |
| 87 | "â": "a", "Â": "A", "î": "i", "Î": "I", "û": "u", "Û": "U", |
| 88 | }) |
| 89 | |
| 90 | _FILLER_PREFIXES: Final[tuple[str, ...]] = ( |
| 91 | "hocam", "dostum", "rica etsem", "bir şey soracağım", "acaba", "şimdi ben", |
| 92 | "yardım eder misin", "kısaca", "müsaitsen", "peki", "uygulamada", "Hezarfen'de", |
| 93 | ) |
| 94 | _FILLER_SUFFIXES: Final[tuple[str, ...]] = ( |
| 95 | "lütfen", "hangi adımları izlemeliyim", "bir bakar mısın", "nereden başlamalıyım", |
| 96 | "yardımcı olur musun", "nasıl ilerleyeceğim", "doğru ekran hangisi", |
| 97 | "bunu açıklayabilir misin", "ne yapmam gerekiyor", "kısaca anlatır mısın", |
| 98 | "yol gösterir misin", "mümkün mü", |
| 99 | ) |
| 100 | _ASCII_PREFIXES: Final[tuple[str, ...]] = ( |
| 101 | "hocam", "lutfen", "uygulamada", "hesabimda", "acaba", "kisa bir soru", |
| 102 | "yardim", "hezarfende", |
| 103 | ) |
| 104 | _ASCII_SUFFIXES: Final[tuple[str, ...]] = ( |
| 105 | "nasil yapilir", "yardim eder misin", "nereden baslamaliyim", "hangi ekranda", |
| 106 | "bir bakar misin", "ne yapmaliyim", "mumkun mu", "adimlari nedir", |
| 107 | ) |
| 108 | |
| 109 | _SEMANTIC_REPLACEMENTS: Final[tuple[tuple[re.Pattern[str], tuple[str, ...]], ...]] = ( |
| 110 | (re.compile(r"\bnasıl\b", re.IGNORECASE), ("hangi adımlarla", "ne şekilde", "hangi yolu izleyerek")), |
| 111 | (re.compile(r"\bnereden\b", re.IGNORECASE), ("hangi ekrandan", "hangi bölümden", "hangi sayfadan")), |
| 112 | (re.compile(r"\bnerede\b", re.IGNORECASE), ("hangi ekranda", "hangi bölümde", "hangi sayfada")), |
| 113 | |
| 114 | |
| 115 | |
| 116 | (re.compile(r"\bistiyorum\b", re.IGNORECASE), ("isterim", "niyetindeyim")), |
| 117 | (re.compile(r"\bsilmek\b", re.IGNORECASE), ("kaldırmak", "listeden çıkarmak", "kaydı kaldırmak")), |
| 118 | (re.compile(r"\bsil\b", re.IGNORECASE), ("kaldır", "listeden çıkar")), |
| 119 | (re.compile(r"\bdeğiştirmek\b", re.IGNORECASE), ("güncellemek", "düzenlemek")), |
| 120 | (re.compile(r"\bdüzenlemek\b", re.IGNORECASE), ("güncellemek", "değiştirmek")), |
| 121 | (re.compile(r"\boluşturmak\b", re.IGNORECASE), ("eklemek", "tanımlamak")), |
| 122 | (re.compile(r"\beklemek\b", re.IGNORECASE), ("ilave etmek",)), |
| 123 | (re.compile(r"\bgörmek\b", re.IGNORECASE), ("görüntülemek", "incelemek", "bakmak")), |
| 124 | (re.compile(r"\bgörüntülemek\b", re.IGNORECASE), ("görmek", "incelemek", "ekranda açmak")), |
| 125 | (re.compile(r"\bgiremiyorum\b", re.IGNORECASE), ("erişemiyorum", "açamıyorum", "içeri alınmıyorum")), |
| 126 | (re.compile(r"\bolmuyor\b", re.IGNORECASE), ("çalışmıyor", "tamamlanmıyor", "sonuç vermiyor")), |
| 127 | (re.compile(r"\bkaydetmek\b", re.IGNORECASE), ("kayda almak", "saklamak", "değişiklikleri uygulamak")), |
| 128 | (re.compile(r"\bgöndermek\b", re.IGNORECASE), ("teslim etmek", "iletmek", "sisteme yollamak")), |
| 129 | (re.compile(r"\bkaldırmak\b", re.IGNORECASE), ("listeden çıkarmak", "kaydı silmek")), |
| 130 | ) |
| 131 | |
| 132 | _SENTENCE_FRAMES: Final[tuple[tuple[str, str], ...]] = ( |
| 133 | ("direct_goal", "Şunu yapmak istiyorum: {q}."), |
| 134 | ("step_request", "{q}; hangi adımları sırayla izlemeliyim?"), |
| 135 | ("screen_request", "{q}. Bu işlem hangi ekrandan yapılıyor?"), |
| 136 | ("how_to", "Hezarfen'de {q} konusunda yol gösterir misin?"), |
| 137 | ("first_person", "Ben {q_lower}; nereden başlamalıyım?"), |
| 138 | ("concise", "Kısaca sorayım: {q}?"), |
| 139 | ("need", "{q} gerekiyor; doğru işlem akışı nedir?"), |
| 140 | ("where_then", "Önce hangi sayfaya gitmeliyim: {q}?"), |
| 141 | ("explain", "{q} konusunu adım adım açıklayabilir misin?"), |
| 142 | ("task", "Yapmak istediğim işlem şu: {q}. Nasıl ilerlerim?"), |
| 143 | ("new_user", "Uygulamayı yeni kullanıyorum; {q}?"), |
| 144 | ("short", "{q} — doğru yol nedir?"), |
| 145 | ) |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | |
| 151 | _OOS_NEUTRAL_FRAMES: Final[dict[str, tuple[tuple[str, str], ...]]] = { |
| 152 | "fallback": ( |
| 153 | ("curious", "Şunu merak ediyorum: {q}."), |
| 154 | ("plain_question", "Bir sorum var: {q}?"), |
| 155 | ("ask_opinion", "{q}; bu konuda ne söyleyebilirsin?"), |
| 156 | ("request_answer", "Sana şunu sormak istiyorum: {q}."), |
| 157 | ("topic", "Merak ettiğim konu şu: {q}."), |
| 158 | ("brief", "Kısaca şunu sorayım: {q}?"), |
| 159 | ), |
| 160 | "action": ( |
| 161 | ("direct_action", "Senden şu isteği yerine getirmeni istiyorum: {q}."), |
| 162 | ("explicit_request", "Talebim şu: {q}."), |
| 163 | ("perform", "{q}; bunu benim için gerçekleştir."), |
| 164 | ("imperative", "Şunu doğrudan yap: {q}."), |
| 165 | ("request", "Yapmanı istediğim şey şu: {q}."), |
| 166 | ("fulfil", "{q}; bu isteği yerine getir."), |
| 167 | ), |
| 168 | "data": ( |
| 169 | ("direct_data", "Senden şu bilgiyi istiyorum: {q}."), |
| 170 | ("disclose", "{q}; bu bilgiyi benimle paylaş."), |
| 171 | ("data_request", "İstediğim veri şu: {q}."), |
| 172 | ("reveal", "Şu bilgiyi bana açıkla: {q}."), |
| 173 | ("provide_data", "{q}; ilgili veriyi bana ver."), |
| 174 | ("explicit_data", "Bilgi talebim şu: {q}."), |
| 175 | ), |
| 176 | } |
| 177 | |
| 178 | _OOS_FILLER_PREFIXES: Final[dict[str, tuple[str, ...]]] = { |
| 179 | "fallback": ("merak ettim", "bir soru soracağım", "acaba", "kısaca", "şunu sorayım"), |
| 180 | "action": ("açıkça istiyorum", "talebim şu", "doğrudan yap", "lütfen yerine getir", "isteğim şu"), |
| 181 | "data": ("bilgi talebim var", "açıkça soruyorum", "bu veriyi istiyorum", "lütfen paylaş", "merak ettiğim veri şu"), |
| 182 | } |
| 183 | |
| 184 | _OOS_FILLER_SUFFIXES: Final[dict[str, tuple[str, ...]]] = { |
| 185 | "fallback": ("cevaplar mısın", "ne düşünüyorsun", "bilgi verir misin", "fikrin nedir", "anlatır mısın"), |
| 186 | "action": ("bu isteği yerine getir", "bunu benim için yap", "talebimi gerçekleştir", "doğrudan uygula", "bunu tamamla"), |
| 187 | "data": ("bu bilgiyi paylaş", "veriyi bana ver", "bilgiyi açıkla", "bunu benimle paylaş", "talebimi yanıtla"), |
| 188 | } |
| 189 | |
| 190 | _OOS_ASCII_PREFIXES: Final[dict[str, tuple[str, ...]]] = { |
| 191 | kind: tuple(turkish.translate(_TURKISH_ASCII_TABLE) for turkish in values) |
| 192 | for kind, values in _OOS_FILLER_PREFIXES.items() |
| 193 | } |
| 194 | _OOS_ASCII_SUFFIXES: Final[dict[str, tuple[str, ...]]] = { |
| 195 | kind: tuple(turkish.translate(_TURKISH_ASCII_TABLE) for turkish in values) |
| 196 | for kind, values in _OOS_FILLER_SUFFIXES.items() |
| 197 | } |
| 198 | |
| 199 | _UI_LABELS: Final[tuple[tuple[re.Pattern[str], str, str], ...]] = ( |
| 200 | (re.compile(r"\bprofil(?:im|i|de|den)?\b", re.IGNORECASE), "Profil", "Profile"), |
| 201 | (re.compile(r"\bayarlar(?:ı|da|dan)?\b", re.IGNORECASE), "Ayarlar", "Settings"), |
| 202 | (re.compile(r"\bhesap(?:ta|tan|ım)?\b", re.IGNORECASE), "Hesap", "Account"), |
| 203 | (re.compile(r"\bdersler(?:de|den|i)?\b", re.IGNORECASE), "Dersler", "Courses"), |
| 204 | (re.compile(r"\bsınavlar(?:da|dan|ı)?\b", re.IGNORECASE), "Sınavlar", "Exams"), |
| 205 | (re.compile(r"\bödev(?:ler|de|i)?\b", re.IGNORECASE), "Ödev", "Homework"), |
| 206 | (re.compile(r"\bmesajlar(?:da|ı)?\b", re.IGNORECASE), "Mesajlar", "Messages"), |
| 207 | (re.compile(r"\bdefter(?:de|i)?\b", re.IGNORECASE), "Defter", "Notebook"), |
| 208 | (re.compile(r"\bkaydet\b", re.IGNORECASE), "Kaydet", "Save"), |
| 209 | (re.compile(r"\bkaldır\b", re.IGNORECASE), "Kaldır", "Remove"), |
| 210 | (re.compile(r"\bgönder\b", re.IGNORECASE), "Gönder", "Submit"), |
| 211 | (re.compile(r"\bgiriş\b", re.IGNORECASE), "Giriş", "Login"), |
| 212 | (re.compile(r"\bçıkış\b", re.IGNORECASE), "Çıkış", "Logout"), |
| 213 | (re.compile(r"\byoklama\b", re.IGNORECASE), "Yoklama", "Attendance"), |
| 214 | (re.compile(r"\bkarne(?:m|yi)?\b", re.IGNORECASE), "Karnem", "Report Card"), |
| 215 | (re.compile(r"\brandevu(?:lar)?\b", re.IGNORECASE), "Randevular", "Appointments"), |
| 216 | ) |
| 217 | |
| 218 | _PUNCTUATION_STYLES: Final[tuple[tuple[str, str], ...]] = ( |
| 219 | ("lower_questions", "{lower}???"), ("upper_exclaims", "{upper}!!!"), |
| 220 | ("swapcase_ellipsis", "{swap}..."), ("alternating_mixed", "{alternating}?!"), |
| 221 | ("lower_spaced", "{lower} ? ! ?"), ("upper_question", "{upper}????"), |
| 222 | ("quoted", "“{base}?”"), ("parenthesized", "({base})?"), |
| 223 | ("colon", "Soru: {base}?"), ("dash", "{base} — ?"), |
| 224 | ) |
| 225 | |
| 226 | _GENERIC_ACTION_ERRORS: Final[tuple[tuple[str, str], ...]] = ( |
| 227 | ("button_disabled", "İlgili işlem düğmesi pasif görünüyor; neden olabilir?"), |
| 228 | ("save_no_effect", "Kaydet'e bastığım halde değişiklik uygulanmıyor."), |
| 229 | ("validation", "Formu doldurdum fakat doğrulama hatası alıyorum."), |
| 230 | ("state_conflict", "İşlem mevcut durum nedeniyle tamamlanamadı uyarısı veriyor."), |
| 231 | ("stale_screen", "İşlemden sonra liste güncellenmiyor."), |
| 232 | ("permission", "Butona basınca yetki uyarısı çıkıyor."), |
| 233 | ) |
| 234 | _GENERIC_VIEW_ERRORS: Final[tuple[tuple[str, str], ...]] = ( |
| 235 | ("empty_screen", "Sayfa açılıyor fakat kayıtlar boş görünüyor."), |
| 236 | ("not_visible", "Beklediğim kayıt ekranda görünmüyor."), |
| 237 | ("loading", "Ekran yükleniyor durumunda kalıyor."), |
| 238 | ("wrong_scope", "Yalnız bazı kayıtları görebiliyorum; kapsam neden dar?"), |
| 239 | ("navigation_missing", "Menüde ilgili bölümü bulamıyorum."), |
| 240 | ) |
| 241 | _SPECIAL_STATE_ERRORS: Final[dict[str, tuple[tuple[str, str], ...]]] = { |
| 242 | "account_access_problem": ( |
| 243 | ("invalid_credentials", "Bilgiler doğru görünse de 401 alıyorum."), |
| 244 | ("registered_no_login", "Kayıt başarılı göründü ama giriş yapamıyorum."), |
| 245 | ), |
| 246 | "upload_problem": ( |
| 247 | ("payload_too_large", "Dosya yüklerken 413 hatası alıyorum."), |
| 248 | ("bad_type", "Dosya türü kabul edilmiyor uyarısı çıkıyor."), |
| 249 | ("missing_multipart", "Dosya seçili olduğu halde file alanı eksik deniyor."), |
| 250 | ("attachment_cap", "On birinci eki eklemeye çalışınca işlem reddediliyor."), |
| 251 | ), |
| 252 | "chatbot_service_problem": ( |
| 253 | ("service_unavailable", "Çelebi yanıt vermiyor ve 503 görünüyor."), |
| 254 | ("rate_limit", "Çok istek uyarısıyla 429 alıyorum."), |
| 255 | ("pending", "Yanıt sürekli pending durumunda kalıyor."), |
| 256 | ("bridge", "AI bridge bağlı değil uyarısı çıkıyor."), |
| 257 | ), |
| 258 | "exam_enter_room": ( |
| 259 | ("not_started", "Başla düğmesi görünmüyor; sınav henüz açılmamış olabilir mi?"), |
| 260 | ("expired", "Sınav süresi dışında olduğum için odaya alınmıyorum."), |
| 261 | ), |
| 262 | "exam_rejoin_retake": ( |
| 263 | ("attempt_limit", "Deneme hakkı tükendi uyarısı alıyorum."), |
| 264 | ("already_submitted", "Teslim edilmiş sınava yeniden giremiyorum."), |
| 265 | ), |
| 266 | "homework_submit": ( |
| 267 | ("deadline", "Teslim tarihi geçti uyarısıyla gönderemiyorum."), |
| 268 | ("graded_lock", "Notlandırılmış teslimi değiştiremiyorum."), |
| 269 | ("attachment_cap", "On birinci dosyada ek sınırı hatası çıkıyor."), |
| 270 | ), |
| 271 | "appointment_book": ( |
| 272 | ("slot_taken", "Seçtiğim saat artık müsait değil uyarısı veriyor."), |
| 273 | ("duplicate", "Aynı saat için ikinci talep oluşturamıyorum."), |
| 274 | ), |
| 275 | "meal_book": ( |
| 276 | ("insufficient_credit", "Bakiye yetersiz olduğu için rezervasyon olmuyor."), |
| 277 | ("closed_day", "Geçmiş veya kapalı gün için ayıramıyorum."), |
| 278 | ), |
| 279 | "course_remove_student": ( |
| 280 | ("not_enrolled", "Öğrenci listede olmadığı için kaldırılamıyor."), |
| 281 | ("history_retained", "Öğrenciyi çıkardım ama eski notları hâlâ görünüyor."), |
| 282 | ), |
| 283 | "board_view": ( |
| 284 | ("capacity", "Tahtaya katılırken katılımcı sınırı dolu uyarısı çıkıyor."), |
| 285 | ("loading", "Tahta açılıyor durumunda kalıyor."), |
| 286 | ), |
| 287 | "board_create": ( |
| 288 | ("board_closed", "Tahtayı kapattıktan sonra yeniden açamıyorum."), |
| 289 | ("board_locked", "Tahta kilitli olduğu için düzenleyemiyorum."), |
| 290 | ), |
| 291 | } |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | _STATE_ACTION_INTENTS: Final[frozenset[str]] = frozenset({ |
| 298 | "profile_edit", "personal_settings", "language_theme", |
| 299 | "course_create", "course_enroll_student", "course_subject_manage", |
| 300 | "course_note_manage", "course_teacher_manage", "lesson_session_add", "roll_call", |
| 301 | "exam_create", "exam_add_question", "exam_save_answer", "exam_finish_result", |
| 302 | "exam_grade_student", "homework_withdraw_submission", "homework_assign", |
| 303 | "homework_manage", "homework_grade", "event_attendance_mark", "event_create", |
| 304 | "note_import_ocr", "note_file_manage", "note_create", "note_edit", "note_delete", |
| 305 | "work_checkin_out", "staff_work_manage", "term_manage", "school_settings", |
| 306 | "user_role_change", "pomodoro_use", "fees_manage", "class_section_manage", |
| 307 | "question_bank_manage", "appointment_slot_open", "meal_service_mark", |
| 308 | "meal_menu_manage", "meal_dietary_profile_manage", "meal_credit_manage", |
| 309 | "question_ask", "question_solve", "question_approve", "board_create", |
| 310 | }) |
| 311 | _STATE_VIEW_INTENTS: Final[frozenset[str]] = frozenset({ |
| 312 | "profile_view", "navigation_help", "course_view", "exam_live_monitor", |
| 313 | "homework_view", "report_card_view", "student_marks_lookup", "attendance_view", |
| 314 | "student_attendance_lookup", "event_view", "student_pomodoro_lookup", |
| 315 | "messages_use", "fees_info", "calendar_info", "today_info", |
| 316 | "question_bank_info", "exam_schedule_info", "course_materials_info", |
| 317 | "appointment_requests", "meal_view", |
| 318 | }) |
| 319 | STATE_ERROR_ELIGIBLE: Final[frozenset[str]] = frozenset(_SPECIAL_STATE_ERRORS) | _STATE_ACTION_INTENTS | _STATE_VIEW_INTENTS |
| 320 | |
| 321 | |
| 322 | def _supports_state_error(intent: str | None) -> bool: |
| 323 | return bool(intent) and intent not in STATE_ERROR_ALWAYS_EXCLUDED and intent in STATE_ERROR_ELIGIBLE |
| 324 | |
| 325 | _PII_SECRET_PATTERNS: Final[tuple[tuple[str, re.Pattern[str]], ...]] = ( |
| 326 | ("email", re.compile(r"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b", re.IGNORECASE)), |
| 327 | ("phone", re.compile(r"(?<!\d)(?:\+?90[\s.-]?)?0?5\d{2}(?:[\s.-]?\d{3}){2}(?!\d)")), |
| 328 | ("national_id", re.compile(r"(?<!\d)[1-9]\d{10}(?!\d)")), |
| 329 | ("api_key", re.compile(r"\b(?:sk|pk|api)[-_][A-Za-z0-9_-]{16,}\b", re.IGNORECASE)), |
| 330 | ("assigned_secret", re.compile(r"\b(?:api[_ -]?key|access[_ -]?token|bearer|password|parola|şifre)\s*[:=]\s*\S+", re.IGNORECASE)), |
| 331 | ("private_key", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----")), |
| 332 | ) |
| 333 | |
| 334 | |
| 335 | @dataclass(frozen=True) |
| 336 | class Seed: |
| 337 | question: str |
| 338 | expected_intent: str |
| 339 | role: str |
| 340 | source_dataset: str |
| 341 | source_index: int |
| 342 | expected_outcome: str | None = None |
| 343 | expected_response_ids: tuple[str, ...] = () |
| 344 | expected_reason_code: str | None = None |
| 345 | scope_boundary_type: str | None = None |
| 346 | |
| 347 | |
| 348 | @dataclass(frozen=True) |
| 349 | class MutationContext: |
| 350 | seed: Seed |
| 351 | role: str |
| 352 | intent: str | None |
| 353 | family: str |
| 354 | round_index: int |
| 355 | variant: int |
| 356 | ui_label: str | None |
| 357 | allow_state_error: bool |
| 358 | scope: str |
| 359 | |
| 360 | |
| 361 | def _read_jsonl(path: Path) -> list[dict[str, Any]]: |
| 362 | records: list[dict[str, Any]] = [] |
| 363 | with path.open("r", encoding="utf-8") as handle: |
| 364 | for line_number, raw_line in enumerate(handle, start=1): |
| 365 | line = raw_line.strip() |
| 366 | if not line: |
| 367 | continue |
| 368 | try: |
| 369 | value = json.loads(line) |
| 370 | except json.JSONDecodeError as exc: |
| 371 | raise ValueError(f"{path}:{line_number} geçersiz JSON: {exc}") from exc |
| 372 | if not isinstance(value, dict): |
| 373 | raise ValueError(f"{path}:{line_number} JSON nesnesi olmalı.") |
| 374 | records.append(value) |
| 375 | return records |
| 376 | |
| 377 | |
| 378 | def privacy_findings(text: str) -> list[str]: |
| 379 | return [label for label, pattern in _PII_SECRET_PATTERNS if pattern.search(text)] |
| 380 | |
| 381 | |
| 382 | def normalise_question_key(text: str) -> str: |
| 383 | value = unicodedata.normalize("NFKC", text).replace("I", "ı").replace("İ", "i").casefold() |
| 384 | |
| 385 | |
| 386 | |
| 387 | return " ".join(re.findall(r"[^\W_]+", value, flags=re.UNICODE)).strip() |
| 388 | |
| 389 | |
| 390 | def _clean_question(value: object, *, source: str) -> str: |
| 391 | if not isinstance(value, str) or not value.strip(): |
| 392 | raise ValueError(f"{source}: question boş olmayan metin olmalı.") |
| 393 | question = " ".join(value.split()) |
| 394 | findings = privacy_findings(question) |
| 395 | if findings: |
| 396 | raise ValueError(f"{source}: PII/secret bulundu: {', '.join(findings)}") |
| 397 | return question |
| 398 | |
| 399 | |
| 400 | def _clean_role(value: object, *, source: str) -> str: |
| 401 | role = value if isinstance(value, str) else "ziyaretci" |
| 402 | if role not in ROLE_HIERARCHY: |
| 403 | raise ValueError(f"{source}: bilinmeyen rol {role!r}.") |
| 404 | return role |
| 405 | |
| 406 | |
| 407 | def _optional_string(record: Mapping[str, Any], key: str, source: str) -> str | None: |
| 408 | value = record.get(key) |
| 409 | if value is None: |
| 410 | return None |
| 411 | if not isinstance(value, str) or not value.strip(): |
| 412 | raise ValueError(f"{source}: {key} metin olmalı.") |
| 413 | return value.strip() |
| 414 | |
| 415 | |
| 416 | def _response_ids(record: Mapping[str, Any], source: str) -> tuple[str, ...]: |
| 417 | plural = record.get("expected_response_ids") |
| 418 | single = record.get("expected_response_id") |
| 419 | if plural is None: |
| 420 | values: Sequence[object] = (single,) if single is not None else () |
| 421 | elif isinstance(plural, list): |
| 422 | values = plural |
| 423 | else: |
| 424 | raise ValueError(f"{source}: expected_response_ids liste olmalı.") |
| 425 | cleaned: list[str] = [] |
| 426 | for value in values: |
| 427 | if not isinstance(value, str) or not value.strip(): |
| 428 | raise ValueError(f"{source}: response_id boş olmayan metin olmalı.") |
| 429 | if value.strip() not in cleaned: |
| 430 | cleaned.append(value.strip()) |
| 431 | return tuple(cleaned) |
| 432 | |
| 433 | |
| 434 | def _scope_boundary_type(record: Mapping[str, Any], reason_code: str | None) -> str | None: |
| 435 | explicit = record.get("scope_boundary_type") or record.get("scope_boundary") |
| 436 | if isinstance(explicit, str) and explicit.strip(): |
| 437 | return explicit.strip() |
| 438 | if reason_code and reason_code.startswith("scope_boundary_"): |
| 439 | return reason_code.removeprefix("scope_boundary_") |
| 440 | return None |
| 441 | |
| 442 | |
| 443 | def _seed_from_record(record: Mapping[str, Any], *, dataset: str, index: int, require_oos: bool = False) -> Seed: |
| 444 | source = f"{dataset}:{index}" |
| 445 | expected = record.get("expected_intent", OOS_LABEL if require_oos else None) |
| 446 | if not isinstance(expected, str) or not expected: |
| 447 | raise ValueError(f"{source}: expected_intent zorunlu.") |
| 448 | if require_oos and expected != OOS_LABEL: |
| 449 | raise ValueError(f"{source}: near-OOS expected_intent='oos' olmalı.") |
| 450 | known = {item["intent"] for item in INTENTS} |
| 451 | if expected != OOS_LABEL and expected not in known: |
| 452 | raise ValueError(f"{source}: katalog dışı intent {expected!r}.") |
| 453 | reason_code = _optional_string(record, "expected_reason_code", source) |
| 454 | return Seed( |
| 455 | question=_clean_question(record.get("question"), source=source), |
| 456 | expected_intent=expected, |
| 457 | role=_clean_role(record.get("role"), source=source), |
| 458 | source_dataset=dataset, |
| 459 | source_index=index, |
| 460 | expected_outcome=_optional_string(record, "expected_outcome", source), |
| 461 | expected_response_ids=_response_ids(record, source), |
| 462 | expected_reason_code=reason_code, |
| 463 | scope_boundary_type=_scope_boundary_type(record, reason_code), |
| 464 | ) |
| 465 | |
| 466 | |
| 467 | def _deduplicate_seeds(seeds: Iterable[Seed]) -> list[Seed]: |
| 468 | output: list[Seed] = [] |
| 469 | seen: set[tuple[str, str, str, str | None]] = set() |
| 470 | for seed in seeds: |
| 471 | key = (normalise_question_key(seed.question), seed.role, seed.expected_intent, seed.expected_outcome) |
| 472 | if key not in seen: |
| 473 | seen.add(key) |
| 474 | output.append(seed) |
| 475 | return output |
| 476 | |
| 477 | |
| 478 | def load_source_seeds( |
| 479 | benchmark_path: str | Path = DEFAULT_BENCHMARK_PATH, |
| 480 | near_oos_path: str | Path = DEFAULT_NEAR_OOS_PATH, |
| 481 | ) -> tuple[list[Seed], list[Seed]]: |
| 482 | |
| 483 | in_scope: list[Seed] = [] |
| 484 | oos: list[Seed] = [] |
| 485 | for index, record in enumerate(_read_jsonl(Path(benchmark_path)), start=1): |
| 486 | seed = _seed_from_record(record, dataset="benchmark", index=index) |
| 487 | (oos if seed.expected_intent == OOS_LABEL else in_scope).append(seed) |
| 488 | for index, record in enumerate(_read_jsonl(Path(near_oos_path)), start=1): |
| 489 | oos.append(_seed_from_record(record, dataset="near_oos", index=index, require_oos=True)) |
| 490 | in_scope = _deduplicate_seeds(in_scope) |
| 491 | oos = _deduplicate_seeds(oos) |
| 492 | if not in_scope: |
| 493 | raise ValueError("Uygulama-içi üretim için elle etiketli seed bulunamadı.") |
| 494 | if not oos: |
| 495 | raise ValueError("OOS üretim için elle etiketli seed bulunamadı.") |
| 496 | return in_scope, oos |
| 497 | |
| 498 | |
| 499 | def turkish_ascii(text: str) -> str: |
| 500 | translated = text.translate(_TURKISH_ASCII_TABLE) |
| 501 | decomposed = unicodedata.normalize("NFKD", translated) |
| 502 | return decomposed.encode("ascii", "ignore").decode("ascii") |
| 503 | |
| 504 | |
| 505 | def _base(text: str) -> str: |
| 506 | return " ".join(text.split()).rstrip(_TRAILING_PUNCTUATION) |
| 507 | |
| 508 | |
| 509 | def _stable_int(*parts: object) -> int: |
| 510 | raw = "\x1f".join(str(part) for part in parts).encode("utf-8") |
| 511 | return int.from_bytes(hashlib.sha256(raw).digest()[:8], "big") |
| 512 | |
| 513 | |
| 514 | def _variant_for(seed: Seed, round_index: int, family: str, role: str) -> int: |
| 515 | return _stable_int( |
| 516 | MUTATION_SEED_VERSION, seed.source_dataset, seed.source_index, seed.question, |
| 517 | round_index, family, role, |
| 518 | ) |
| 519 | |
| 520 | |
| 521 | def _is_information_intent(intent: str | None) -> bool: |
| 522 | if not intent: |
| 523 | return False |
| 524 | return ( |
| 525 | intent in SOCIAL_INTENTS |
| 526 | or intent.endswith(("_info", "_view", "_lookup")) |
| 527 | or intent in { |
| 528 | "platform_info", "guide_info", "help_capabilities", "roles_permissions", |
| 529 | "privacy_security", "nav_overview", "navigation_help", "profile_view", |
| 530 | "branches_info", "today_info", "course_materials_info", |
| 531 | "notification_settings_info", |
| 532 | } |
| 533 | ) |
| 534 | |
| 535 | |
| 536 | def _semantic_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 537 | base = _base(ctx.seed.question) |
| 538 | applicable = [item for item in _SEMANTIC_REPLACEMENTS if item[0].search(base)] |
| 539 | if applicable: |
| 540 | pattern, alternatives = applicable[ctx.variant % len(applicable)] |
| 541 | replacement = alternatives[(ctx.variant // max(1, len(applicable))) % len(alternatives)] |
| 542 | out, count = pattern.subn(replacement, base, count=1) |
| 543 | return out, ["semantic_paraphrase"], { |
| 544 | "strategy": "lexical_replacement", "pattern": pattern.pattern, |
| 545 | "replacement": replacement, "replacement_count": count, "variant": ctx.variant, |
| 546 | } |
| 547 | if ctx.intent in SOCIAL_INTENTS: |
| 548 | frames = ( |
| 549 | "Şunu sorayım: {q}?", |
| 550 | "Kısaca: {q}.", |
| 551 | "Sohbet arasında merak ettim: {q}?", |
| 552 | "Bir şey soracağım: {q}.", |
| 553 | ) |
| 554 | elif _is_information_intent(ctx.intent): |
| 555 | frames = ( |
| 556 | "{q} hakkında bilgi verir misin?", |
| 557 | "Şunu öğrenmek istiyorum: {q}.", |
| 558 | "Merak ettiğim konu: {q}.", |
| 559 | "{q}; bunu açıklayabilir misin?", |
| 560 | ) |
| 561 | else: |
| 562 | frames = ( |
| 563 | "{q} konusunda hangi yolu izlemeliyim?", |
| 564 | "{q}; bunu uygulamada hangi adımlarla yaparım?", |
| 565 | "Amacım şu: {q}. Bana işlem yolunu anlatır mısın?", |
| 566 | "{q} için izlenecek doğru akış nedir?", |
| 567 | "Hezarfen'de {q} işlemini yapmak istiyorum.", |
| 568 | "{q} konusunu farklı bir ifadeyle soruyorum; nasıl ilerlerim?", |
| 569 | ) |
| 570 | frame = frames[ctx.variant % len(frames)] |
| 571 | return frame.format(q=base), ["semantic_paraphrase"], { |
| 572 | "strategy": "meaning_preserving_frame", "frame": frame, "variant": ctx.variant, |
| 573 | } |
| 574 | |
| 575 | |
| 576 | def _sentence_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 577 | frames = ( |
| 578 | (("plain", "{q}?"), ("curious", "Şunu merak ettim: {q}."), |
| 579 | ("chat", "Sohbet arasında sorayım: {q}?"), ("concise", "Kısaca: {q}.")) |
| 580 | if ctx.intent in SOCIAL_INTENTS else _SENTENCE_FRAMES |
| 581 | ) |
| 582 | label, frame = frames[ctx.variant % len(frames)] |
| 583 | base = _base(ctx.seed.question) |
| 584 | return frame.format(q=base, q_lower=base[:1].lower() + base[1:]), ["sentence_form"], { |
| 585 | "frame": label, "variant": ctx.variant, |
| 586 | } |
| 587 | |
| 588 | |
| 589 | def _oos_semantics(ctx: MutationContext) -> str: |
| 590 | |
| 591 | |
| 592 | boundary = (ctx.seed.scope_boundary_type or "").strip().casefold() |
| 593 | if boundary == "action": |
| 594 | return "action" |
| 595 | if boundary == "data": |
| 596 | return "data" |
| 597 | return "fallback" |
| 598 | |
| 599 | |
| 600 | def _oos_neutral_frame(ctx: MutationContext) -> tuple[str, str, str]: |
| 601 | semantics = _oos_semantics(ctx) |
| 602 | frames = _OOS_NEUTRAL_FRAMES[semantics] |
| 603 | label, frame = frames[ctx.variant % len(frames)] |
| 604 | return frame.format(q=_base(ctx.seed.question)), label, semantics |
| 605 | |
| 606 | |
| 607 | def _oos_semantic_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 608 | out, label, semantics = _oos_neutral_frame(ctx) |
| 609 | return out, ["semantic_paraphrase"], { |
| 610 | "strategy": "neutral_scope_frame", "frame": label, |
| 611 | "boundary_semantics": semantics, "variant": ctx.variant, |
| 612 | } |
| 613 | |
| 614 | |
| 615 | def _oos_sentence_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 616 | out, label, semantics = _oos_neutral_frame(ctx) |
| 617 | return out, ["sentence_form"], { |
| 618 | "frame": label, "scope_framing": "neutral_oos", |
| 619 | "boundary_semantics": semantics, "variant": ctx.variant, |
| 620 | } |
| 621 | |
| 622 | |
| 623 | def _ui_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 624 | base = _base(ctx.seed.question) |
| 625 | matches = [item for item in _UI_LABELS if item[0].search(base)] |
| 626 | if matches: |
| 627 | pattern, tr_label, en_label = matches[ctx.variant % len(matches)] |
| 628 | styles = (f"{tr_label} ({en_label})", f"{tr_label}/{en_label}", f"{en_label} [{tr_label}]") |
| 629 | replacement = styles[(ctx.variant // max(1, len(matches))) % len(styles)] |
| 630 | out, _ = pattern.subn(replacement, base, count=1) |
| 631 | return out, ["ui_label_tr_en"], { |
| 632 | "strategy": "inline_label", "tr": tr_label, "en": en_label, |
| 633 | "replacement": replacement, "variant": ctx.variant, |
| 634 | } |
| 635 | label = ctx.ui_label or "ilgili" |
| 636 | frames = ( |
| 637 | "Arayüzde {label} ekranındayım; {q}?", |
| 638 | "Türkçe/English arayüzde {label} sayfasında {q}?", |
| 639 | "UI etiketi {label} olarak görünüyor. {q}?", |
| 640 | ) |
| 641 | frame = frames[ctx.variant % len(frames)] |
| 642 | return frame.format(label=label, q=base), ["ui_label_tr_en"], { |
| 643 | "strategy": "screen_context", "label": label, "frame": frame, "variant": ctx.variant, |
| 644 | } |
| 645 | |
| 646 | |
| 647 | def _role_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 648 | role = ROLE_LABELS[ctx.role] |
| 649 | base = _base(ctx.seed.question) |
| 650 | frames = ( |
| 651 | "{role} hesabımla {q}?", "Oturum rolüm {role}; {q}?", |
| 652 | "{role} olarak şunu yapmak istiyorum: {q}.", "Ben {role} rolündeyim. {q}?", |
| 653 | "{role} panelinden soruyorum: {q}?", "Hesabım {role} yetkisinde; {q}?", |
| 654 | ) |
| 655 | frame = frames[ctx.variant % len(frames)] |
| 656 | return frame.format(role=role, q=base), ["role_context"], { |
| 657 | "frame": frame, "served_role": ctx.role, "variant": ctx.variant, |
| 658 | } |
| 659 | |
| 660 | |
| 661 | def _oos_role_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 662 | role = ROLE_LABELS[ctx.role] |
| 663 | base = _base(ctx.seed.question) |
| 664 | semantics = _oos_semantics(ctx) |
| 665 | role_frames = { |
| 666 | "fallback": ( |
| 667 | ("identity", "{role} olduğumu belirteyim: {q}?"), |
| 668 | ("speaking_as", "Bir {role} olarak soruyorum: {q}?"), |
| 669 | ("context", "Durumumu belirteyim, ben {role} rolündeyim: {q}."), |
| 670 | ("perspective", "{role} açısından şunu soruyorum: {q}?"), |
| 671 | ("plain", "Ben {role}; sorum şu: {q}?"), |
| 672 | ("preface", "Ön bilgi: Rolüm {role}. {q}?"), |
| 673 | ), |
| 674 | "action": ( |
| 675 | ("identity_action", "{role} olduğumu belirteyim. Talebim: {q}."), |
| 676 | ("speaking_as_action", "Bir {role} olarak senden şunu yapmanı istiyorum: {q}."), |
| 677 | ("context_action", "Durumumu belirteyim, ben {role} rolündeyim. Şunu yap: {q}."), |
| 678 | ("perspective_action", "{role} olarak doğrudan talebim şu: {q}."), |
| 679 | ("plain_action", "Ben {role}; şu isteği yerine getir: {q}."), |
| 680 | ("preface_action", "Ön bilgi: Rolüm {role}. Yapmanı istediğim şey: {q}."), |
| 681 | ), |
| 682 | "data": ( |
| 683 | ("identity_data", "{role} olduğumu belirteyim. Şu bilgiyi istiyorum: {q}."), |
| 684 | ("speaking_as_data", "Bir {role} olarak şu veriyi talep ediyorum: {q}."), |
| 685 | ("context_data", "Durumumu belirteyim, ben {role} rolündeyim. Bilgi talebim: {q}."), |
| 686 | ("perspective_data", "{role} olarak doğrudan veri talebim şu: {q}."), |
| 687 | ("plain_data", "Ben {role}; şu bilgiyi benimle paylaş: {q}."), |
| 688 | ("preface_data", "Ön bilgi: Rolüm {role}. İstediğim veri: {q}."), |
| 689 | ), |
| 690 | } |
| 691 | frames = role_frames[semantics] |
| 692 | label, frame = frames[ctx.variant % len(frames)] |
| 693 | return frame.format(role=role, q=base), ["role_context"], { |
| 694 | "frame": label, "served_role": ctx.role, "scope_framing": "neutral_oos", |
| 695 | "boundary_semantics": semantics, "variant": ctx.variant, |
| 696 | } |
| 697 | |
| 698 | |
| 699 | def _ascii_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 700 | base = turkish_ascii(_base(ctx.seed.question)) |
| 701 | prefix = _ASCII_PREFIXES[ctx.variant % len(_ASCII_PREFIXES)] |
| 702 | suffix = _ASCII_SUFFIXES[(ctx.variant // len(_ASCII_PREFIXES)) % len(_ASCII_SUFFIXES)] |
| 703 | mode = (ctx.variant // (len(_ASCII_PREFIXES) * len(_ASCII_SUFFIXES))) % 4 |
| 704 | if mode == 0: |
| 705 | out = f"{prefix} {base}?" |
| 706 | elif mode == 1: |
| 707 | out = f"{base}; {suffix}?" |
| 708 | elif mode == 2: |
| 709 | out = f"{prefix}, {base}; {suffix}?" |
| 710 | else: |
| 711 | out = f"{base}... {suffix}" |
| 712 | return turkish_ascii(out), ["turkish_ascii"], { |
| 713 | "mode": mode, "prefix": prefix, "suffix": suffix, "variant": ctx.variant, |
| 714 | } |
| 715 | |
| 716 | |
| 717 | def _oos_ascii_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 718 | semantics = _oos_semantics(ctx) |
| 719 | base = turkish_ascii(_base(ctx.seed.question)) |
| 720 | prefixes = _OOS_ASCII_PREFIXES[semantics] |
| 721 | suffixes = _OOS_ASCII_SUFFIXES[semantics] |
| 722 | prefix = prefixes[ctx.variant % len(prefixes)] |
| 723 | suffix = suffixes[(ctx.variant // len(prefixes)) % len(suffixes)] |
| 724 | mode = (ctx.variant // (len(prefixes) * len(suffixes))) % 4 |
| 725 | if mode == 0: |
| 726 | out = f"{prefix}: {base}?" |
| 727 | elif mode == 1: |
| 728 | out = f"{base}; {suffix}." |
| 729 | elif mode == 2: |
| 730 | out = f"{prefix}, {base}; {suffix}." |
| 731 | else: |
| 732 | out = f"{base}... {suffix}." |
| 733 | return turkish_ascii(out), ["turkish_ascii"], { |
| 734 | "mode": mode, "prefix": prefix, "suffix": suffix, |
| 735 | "scope_framing": "neutral_oos", "boundary_semantics": semantics, |
| 736 | "variant": ctx.variant, |
| 737 | } |
| 738 | |
| 739 | |
| 740 | def _filler_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 741 | base = _base(ctx.seed.question) |
| 742 | prefix = _FILLER_PREFIXES[ctx.variant % len(_FILLER_PREFIXES)] |
| 743 | suffix = _FILLER_SUFFIXES[(ctx.variant // len(_FILLER_PREFIXES)) % len(_FILLER_SUFFIXES)] |
| 744 | mode = (ctx.variant // (len(_FILLER_PREFIXES) * len(_FILLER_SUFFIXES))) % 4 |
| 745 | if mode == 0: |
| 746 | out = f"{prefix}, {base}?" |
| 747 | elif mode == 1: |
| 748 | out = f"{base}; {suffix}?" |
| 749 | elif mode == 2: |
| 750 | out = f"{prefix}, {base}; {suffix}?" |
| 751 | else: |
| 752 | out = f"{prefix} — {base}. {suffix}?" |
| 753 | return out, ["conversational_filler"], { |
| 754 | "mode": mode, "prefix": prefix, "suffix": suffix, "variant": ctx.variant, |
| 755 | } |
| 756 | |
| 757 | |
| 758 | def _oos_filler_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 759 | semantics = _oos_semantics(ctx) |
| 760 | base = _base(ctx.seed.question) |
| 761 | prefixes = _OOS_FILLER_PREFIXES[semantics] |
| 762 | suffixes = _OOS_FILLER_SUFFIXES[semantics] |
| 763 | prefix = prefixes[ctx.variant % len(prefixes)] |
| 764 | suffix = suffixes[(ctx.variant // len(prefixes)) % len(suffixes)] |
| 765 | mode = (ctx.variant // (len(prefixes) * len(suffixes))) % 4 |
| 766 | if mode == 0: |
| 767 | out = f"{prefix}: {base}?" |
| 768 | elif mode == 1: |
| 769 | out = f"{base}; {suffix}." |
| 770 | elif mode == 2: |
| 771 | out = f"{prefix}, {base}; {suffix}." |
| 772 | else: |
| 773 | out = f"{prefix} — {base}. {suffix}." |
| 774 | return out, ["conversational_filler"], { |
| 775 | "mode": mode, "prefix": prefix, "suffix": suffix, |
| 776 | "scope_framing": "neutral_oos", "boundary_semantics": semantics, |
| 777 | "variant": ctx.variant, |
| 778 | } |
| 779 | |
| 780 | |
| 781 | def _alternating_case(text: str) -> str: |
| 782 | upper = True |
| 783 | output: list[str] = [] |
| 784 | for char in text: |
| 785 | if char.isalpha(): |
| 786 | output.append(char.upper() if upper else char.lower()) |
| 787 | upper = not upper |
| 788 | else: |
| 789 | output.append(char) |
| 790 | return "".join(output) |
| 791 | |
| 792 | |
| 793 | def _punctuation_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 794 | base = _base(ctx.seed.question) |
| 795 | label, frame = _PUNCTUATION_STYLES[ctx.variant % len(_PUNCTUATION_STYLES)] |
| 796 | out = frame.format(base=base, lower=base.lower(), upper=base.upper(), swap=base.swapcase(), alternating=_alternating_case(base)) |
| 797 | return out, ["punctuation_case"], {"style": label, "variant": ctx.variant} |
| 798 | |
| 799 | |
| 800 | def _replacement_for(char: str) -> str: |
| 801 | neighbors = { |
| 802 | "a": "s", "b": "v", "c": "v", "ç": "c", "d": "s", "e": "r", |
| 803 | "f": "g", "g": "h", "ğ": "g", "h": "j", "ı": "i", "i": "o", |
| 804 | "j": "k", "k": "l", "l": "k", "m": "n", "n": "m", "o": "p", |
| 805 | "ö": "o", "p": "o", "r": "t", "s": "d", "ş": "s", "t": "y", |
| 806 | "u": "ı", "ü": "u", "v": "b", "y": "u", "z": "x", |
| 807 | } |
| 808 | replacement = neighbors.get(char.casefold(), "x") |
| 809 | return replacement.upper() if char.isupper() else replacement |
| 810 | |
| 811 | |
| 812 | def _single_typo(text: str, variant: int) -> tuple[str, dict[str, Any]]: |
| 813 | base = _base(text) |
| 814 | words = [match for match in _WORD_RE.finditer(base) if len(match.group(0)) >= 2] |
| 815 | if not words: |
| 816 | return base + "x", {"operation": "insert", "index": len(base), "before": "", "after": "x"} |
| 817 | operation = ("delete", "duplicate", "transpose", "substitute")[variant % 4] |
| 818 | word = words[(variant // 4) % len(words)] |
| 819 | relative = 1 + ((variant // max(1, 4 * len(words))) % (len(word.group(0)) - 1)) |
| 820 | index = word.start() + relative |
| 821 | if operation == "delete": |
| 822 | out = base[:index] + base[index + 1:] |
| 823 | detail = {"operation": operation, "index": index, "before": base[index], "after": ""} |
| 824 | elif operation == "duplicate": |
| 825 | char = base[index] |
| 826 | out = base[:index] + char + base[index:] |
| 827 | detail = {"operation": operation, "index": index, "before": char, "after": char * 2} |
| 828 | elif operation == "transpose" and index + 1 < word.end() and base[index] != base[index + 1]: |
| 829 | pair = base[index:index + 2] |
| 830 | out = base[:index] + pair[::-1] + base[index + 2:] |
| 831 | detail = {"operation": operation, "index": index, "before": pair, "after": pair[::-1]} |
| 832 | else: |
| 833 | char = base[index] |
| 834 | replacement = _replacement_for(char) |
| 835 | out = base[:index] + replacement + base[index + 1:] |
| 836 | detail = {"operation": "substitute", "index": index, "before": char, "after": replacement} |
| 837 | return out, detail |
| 838 | |
| 839 | |
| 840 | def _typo_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 841 | out, detail = _single_typo(ctx.seed.question, ctx.variant) |
| 842 | return out, ["single_typo"], {"typo": detail, "typo_count": 1, "variant": ctx.variant} |
| 843 | |
| 844 | |
| 845 | def _state_frames(intent: str | None) -> tuple[tuple[str, str], ...]: |
| 846 | if not _supports_state_error(intent): |
| 847 | return () |
| 848 | if intent in _SPECIAL_STATE_ERRORS: |
| 849 | return _SPECIAL_STATE_ERRORS[intent] |
| 850 | if intent in _STATE_ACTION_INTENTS: |
| 851 | return _GENERIC_ACTION_ERRORS |
| 852 | return _GENERIC_VIEW_ERRORS |
| 853 | |
| 854 | |
| 855 | def _state_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 856 | if not ctx.allow_state_error or not _supports_state_error(ctx.intent): |
| 857 | raise ValueError(f"{ctx.intent}: state/error ailesi bu intent için uygun değil.") |
| 858 | frames = _state_frames(ctx.intent) |
| 859 | label, detail = frames[ctx.variant % len(frames)] |
| 860 | return f"{_base(ctx.seed.question)}. {detail}", ["state_error"], { |
| 861 | "state": label, "detail": detail, "variant": ctx.variant, |
| 862 | } |
| 863 | |
| 864 | |
| 865 | def _compound_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 866 | semantic_ctx = MutationContext( |
| 867 | seed=ctx.seed, role=ctx.role, intent=ctx.intent, family="semantic_paraphrase", |
| 868 | round_index=ctx.round_index, variant=ctx.variant, ui_label=ctx.ui_label, |
| 869 | allow_state_error=ctx.allow_state_error, scope=ctx.scope, |
| 870 | ) |
| 871 | mode_count = 5 if ctx.allow_state_error and _supports_state_error(ctx.intent) else 4 |
| 872 | mode = ctx.variant % mode_count |
| 873 | if mode == 0: |
| 874 | |
| 875 | |
| 876 | typo_core, typo_meta = _single_typo(ctx.seed.question, ctx.variant // max(1, mode_count)) |
| 877 | typo_ctx = replace(semantic_ctx, seed=replace(ctx.seed, question=typo_core)) |
| 878 | first, _, semantic_meta = _semantic_variant(typo_ctx) |
| 879 | out = f"{_FILLER_PREFIXES[ctx.variant % len(_FILLER_PREFIXES)]}, {first}?" |
| 880 | transforms = ["semantic_paraphrase", "single_typo", "conversational_filler"] |
| 881 | extra = {"typo": typo_meta, "typo_count": 1} |
| 882 | elif mode == 1: |
| 883 | first, _, semantic_meta = _semantic_variant(semantic_ctx) |
| 884 | out = turkish_ascii(first) + "; " + _ASCII_SUFFIXES[ctx.variant % len(_ASCII_SUFFIXES)] + "?" |
| 885 | transforms = ["semantic_paraphrase", "turkish_ascii", "sentence_form"] |
| 886 | extra = {"ascii": True} |
| 887 | elif mode == 2: |
| 888 | first, _, semantic_meta = _semantic_variant(semantic_ctx) |
| 889 | out = f"{ROLE_LABELS[ctx.role]} hesabımla, {first}; {_FILLER_SUFFIXES[ctx.variant % len(_FILLER_SUFFIXES)]}?" |
| 890 | transforms = ["semantic_paraphrase", "role_context", "conversational_filler"] |
| 891 | extra = {"served_role": ctx.role} |
| 892 | elif mode == 3: |
| 893 | first, _, semantic_meta = _semantic_variant(semantic_ctx) |
| 894 | out = f"Soru: {_alternating_case(first)}?!" |
| 895 | transforms = ["semantic_paraphrase", "punctuation_case"] |
| 896 | extra = {"style": "alternating_mixed"} |
| 897 | else: |
| 898 | first, _, semantic_meta = _semantic_variant(semantic_ctx) |
| 899 | frames = _state_frames(ctx.intent) |
| 900 | state_label, detail = frames[(ctx.variant // mode_count) % len(frames)] |
| 901 | out = f"{first}. {detail}" |
| 902 | transforms = ["semantic_paraphrase", "state_error"] |
| 903 | extra = {"state": state_label, "detail": detail} |
| 904 | return out, transforms, {"mode": mode, "semantic": semantic_meta, "variant": ctx.variant, **extra} |
| 905 | |
| 906 | |
| 907 | def _oos_compound_variant(ctx: MutationContext) -> tuple[str, list[str], dict[str, Any]]: |
| 908 | semantics = _oos_semantics(ctx) |
| 909 | neutral, frame_label, _ = _oos_neutral_frame(ctx) |
| 910 | mode = ctx.variant % 5 |
| 911 | if mode == 0: |
| 912 | mutated, typo_meta = _single_typo(neutral, ctx.variant // 5) |
| 913 | out = mutated |
| 914 | transforms = ["semantic_paraphrase", "single_typo"] |
| 915 | extra: dict[str, Any] = {"typo": typo_meta, "typo_count": 1} |
| 916 | elif mode == 1: |
| 917 | suffixes = _OOS_ASCII_SUFFIXES[semantics] |
| 918 | out = f"{turkish_ascii(neutral)} {suffixes[ctx.variant % len(suffixes)]}." |
| 919 | transforms = ["semantic_paraphrase", "turkish_ascii"] |
| 920 | extra = {"ascii": True} |
| 921 | elif mode == 2: |
| 922 | role = ROLE_LABELS[ctx.role] |
| 923 | out = f"Bir {role} olarak soruyorum: {neutral}" |
| 924 | transforms = ["semantic_paraphrase", "role_context"] |
| 925 | extra = {"served_role": ctx.role} |
| 926 | elif mode == 3: |
| 927 | out = f"Soru: {_alternating_case(neutral)}?!" |
| 928 | transforms = ["semantic_paraphrase", "punctuation_case"] |
| 929 | extra = {"style": "alternating_mixed"} |
| 930 | else: |
| 931 | prefixes = _OOS_FILLER_PREFIXES[semantics] |
| 932 | suffixes = _OOS_FILLER_SUFFIXES[semantics] |
| 933 | out = ( |
| 934 | f"{prefixes[ctx.variant % len(prefixes)]}, {neutral} " |
| 935 | f"{suffixes[(ctx.variant // len(prefixes)) % len(suffixes)]}." |
| 936 | ) |
| 937 | transforms = ["semantic_paraphrase", "conversational_filler"] |
| 938 | extra = {"neutral_filler": True} |
| 939 | return out, transforms, { |
| 940 | "mode": mode, "semantic_frame": frame_label, |
| 941 | "scope_framing": "neutral_oos", "boundary_semantics": semantics, |
| 942 | "variant": ctx.variant, **extra, |
| 943 | } |
| 944 | |
| 945 | |
| 946 | _TRANSFORMERS: Final[Mapping[str, Any]] = { |
| 947 | "semantic_paraphrase": _semantic_variant, "sentence_form": _sentence_variant, |
| 948 | "ui_label_tr_en": _ui_variant, "role_context": _role_variant, |
| 949 | "turkish_ascii": _ascii_variant, "conversational_filler": _filler_variant, |
| 950 | "punctuation_case": _punctuation_variant, "single_typo": _typo_variant, |
| 951 | "state_error": _state_variant, "compound": _compound_variant, |
| 952 | } |
| 953 | |
| 954 | _OOS_TRANSFORMERS: Final[Mapping[str, Any]] = { |
| 955 | "semantic_paraphrase": _oos_semantic_variant, |
| 956 | "sentence_form": _oos_sentence_variant, |
| 957 | "role_context": _oos_role_variant, |
| 958 | "turkish_ascii": _oos_ascii_variant, |
| 959 | "conversational_filler": _oos_filler_variant, |
| 960 | |
| 961 | "punctuation_case": _punctuation_variant, |
| 962 | "single_typo": _typo_variant, |
| 963 | "compound": _oos_compound_variant, |
| 964 | } |
| 965 | |
| 966 | |
| 967 | def _ui_context(intent: str, seed_question: str) -> tuple[bool, str | None]: |
| 968 | route = route_for(intent) |
| 969 | label = route[1] if route else None |
| 970 | return route is not None or any(pattern.search(seed_question) for pattern, _, _ in _UI_LABELS), label |
| 971 | |
| 972 | |
| 973 | def _eligible_families(intent: str, seed_question: str) -> tuple[str, ...]: |
| 974 | has_ui, _ = _ui_context(intent, seed_question) |
| 975 | return tuple( |
| 976 | family for family in MUTATION_FAMILIES |
| 977 | if not (family == "state_error" and not _supports_state_error(intent)) |
| 978 | and not (family == "ui_label_tr_en" and not has_ui) |
| 979 | ) |
| 980 | |
| 981 | |
| 982 | def _policy_roles(intent: str) -> dict[str, tuple[str, ...]]: |
| 983 | groups: dict[str, list[str]] = defaultdict(list) |
| 984 | for role in ROLE_HIERARCHY: |
| 985 | redirect = _report_redirect(role, intent) |
| 986 | view = redirect[1] if redirect is not None else get_role_space(role).view_for(intent) |
| 987 | if view is None: |
| 988 | raise ValueError(f"{role}:{intent} rol görünümü bulunamadı.") |
| 989 | groups[view.outcome.value].append(role) |
| 990 | ordered: dict[str, tuple[str, ...]] = {} |
| 991 | for outcome in (AccessOutcome.ALLOW.value, AccessOutcome.DENY.value): |
| 992 | if groups.get(outcome): |
| 993 | ordered[outcome] = tuple(groups[outcome]) |
| 994 | for outcome in sorted(set(groups).difference(ordered)): |
| 995 | ordered[outcome] = tuple(groups[outcome]) |
| 996 | return ordered |
| 997 | |
| 998 | |
| 999 | _UPPER_ROLES: Final[frozenset[str]] = frozenset({"ogretmen", "yonetici", "admin"}) |
| 1000 | _REPORT_REDIRECTS: Final[dict[str, str]] = { |
| 1001 | "report_card_view": "student_marks_lookup", |
| 1002 | "attendance_view": "student_attendance_lookup", |
| 1003 | "exam_finish_result": "student_marks_lookup", |
| 1004 | } |
| 1005 | |
| 1006 | |
| 1007 | def _report_redirect(role: str, intent: str): |
| 1008 | |
| 1009 | |
| 1010 | if role not in _UPPER_ROLES or intent not in _REPORT_REDIRECTS: |
| 1011 | return None |
| 1012 | target_intent = _REPORT_REDIRECTS[intent] |
| 1013 | target_view = get_role_space(role).view_for(target_intent) |
| 1014 | target_route = route_for(target_intent) |
| 1015 | if ( |
| 1016 | target_view is None |
| 1017 | or target_view.outcome is not AccessOutcome.ALLOW |
| 1018 | or target_route is None |
| 1019 | ): |
| 1020 | return None |
| 1021 | return target_intent, target_view, target_route |
| 1022 | |
| 1023 | |
| 1024 | def _expected_in_scope_contract(seed: Seed, role: str) -> tuple[dict[str, Any], dict[str, Any]]: |
| 1025 | intent = seed.expected_intent |
| 1026 | source_view = get_role_space(role).view_for(intent) |
| 1027 | if source_view is None: |
| 1028 | raise ValueError(f"{role}:{intent} rol görünümü bulunamadı.") |
| 1029 | redirect = _report_redirect(role, intent) |
| 1030 | served_intent = redirect[0] if redirect is not None else intent |
| 1031 | view = redirect[1] if redirect is not None else source_view |
| 1032 | policy = { |
| 1033 | "outcome": view.outcome.value, "action_id": view.action_id, |
| 1034 | "scope": view.scope.value if view.scope else None, |
| 1035 | "reason_code": view.reason_code.value, "route_key": view.route_key, |
| 1036 | } |
| 1037 | outcome = view.outcome.value |
| 1038 | auth_action = None |
| 1039 | if view.outcome is AccessOutcome.DENY: |
| 1040 | auth_action = "login_required" if role == "ziyaretci" else "role_insufficient" |
| 1041 | response_ids = list(seed.expected_response_ids or (source_view.response_id,)) |
| 1042 | route = route_for(intent) |
| 1043 | legacy_route = route[0] if view.outcome is AccessOutcome.ALLOW and route else None |
| 1044 | if intent in {"report_card_view", "attendance_view"} and role != "ogrenci": |
| 1045 | legacy_route = None |
| 1046 | if redirect is not None: |
| 1047 | outcome, auth_action = "allow", None |
| 1048 | response_ids, legacy_route = ["student_report_redirect"], redirect[2][0] |
| 1049 | |
| 1050 | if intent == "nav_overview": |
| 1051 | response_ids.append("section_overview") |
| 1052 | expected = { |
| 1053 | "intent": intent, "outcome": outcome, "meta_outcome": outcome, |
| 1054 | "meta_action_id": served_intent, |
| 1055 | "response_ids": response_ids, "auth_action": auth_action, "fallback": False, |
| 1056 | "navigation_route": legacy_route if auth_action is None else None, |
| 1057 | "meta_route_key": view.route_key if outcome == "allow" else None, |
| 1058 | "reason_code": view.reason_code.value, |
| 1059 | } |
| 1060 | return expected, policy |
| 1061 | |
| 1062 | |
| 1063 | def _expected_oos_contract(seed: Seed) -> tuple[dict[str, Any], dict[str, Any]]: |
| 1064 | outcome = seed.expected_outcome or "fallback" |
| 1065 | response_ids = list(seed.expected_response_ids) |
| 1066 | if not response_ids: |
| 1067 | response_ids = [FALLBACK["response_id"] if outcome == "fallback" else "out_of_scope_action"] |
| 1068 | reason_code = seed.expected_reason_code or ("out_of_scope" if outcome == "fallback" else seed.scope_boundary_type) |
| 1069 | expected = { |
| 1070 | "intent": None, "outcome": outcome, "meta_outcome": outcome, |
| 1071 | "meta_action_id": None, |
| 1072 | "response_ids": response_ids, "auth_action": None, |
| 1073 | "fallback": outcome == "fallback", "navigation_route": None, |
| 1074 | "meta_route_key": None, "reason_code": reason_code, |
| 1075 | } |
| 1076 | policy = { |
| 1077 | "outcome": outcome, "action_id": None, "scope": seed.scope_boundary_type, |
| 1078 | "reason_code": reason_code, "route_key": None, |
| 1079 | } |
| 1080 | return expected, policy |
| 1081 | |
| 1082 | |
| 1083 | def _expected_other_person_safety_contract( |
| 1084 | intent: str, role: str, question: str, |
| 1085 | ) -> tuple[dict[str, Any], dict[str, Any]] | None: |
| 1086 | |
| 1087 | |
| 1088 | if ( |
| 1089 | role in {"ogretmen", "yonetici", "admin"} |
| 1090 | or intent not in _OTHER_PERSON_SAFETY_INTENTS |
| 1091 | or _POSSESSIVE_NAME_RE.search(question) is None |
| 1092 | ): |
| 1093 | return None |
| 1094 | reason = "safety_other_person_data" |
| 1095 | expected = { |
| 1096 | "intent": None, "outcome": "deny", "meta_outcome": "deny", |
| 1097 | "meta_action_id": None, "response_ids": [reason], "auth_action": None, |
| 1098 | "fallback": False, "navigation_route": None, "meta_route_key": None, |
| 1099 | "reason_code": reason, |
| 1100 | } |
| 1101 | policy = { |
| 1102 | "outcome": "deny", "action_id": None, "scope": "other_person_data", |
| 1103 | "reason_code": reason, "route_key": None, |
| 1104 | } |
| 1105 | return expected, policy |
| 1106 | |
| 1107 | |
| 1108 | def _make_record(seed: Seed, *, role: str, family: str, round_index: int, scope: str) -> dict[str, Any]: |
| 1109 | intent = None if seed.expected_intent == OOS_LABEL else seed.expected_intent |
| 1110 | supports_ui, ui_label = _ui_context(intent, seed.question) if intent else (False, None) |
| 1111 | allow_state = scope == "in_scope" and _supports_state_error(intent) |
| 1112 | if family == "ui_label_tr_en" and not supports_ui: |
| 1113 | raise ValueError(f"{intent}: UI ailesi için ekran/etiket bağlamı yok.") |
| 1114 | variant = _variant_for(seed, round_index, family, role) |
| 1115 | ctx = MutationContext( |
| 1116 | seed=seed, role=role, intent=intent, family=family, round_index=round_index, |
| 1117 | variant=variant, ui_label=ui_label, allow_state_error=allow_state, scope=scope, |
| 1118 | ) |
| 1119 | transformer = _OOS_TRANSFORMERS[family] if scope == "oos" else _TRANSFORMERS[family] |
| 1120 | question, transformations, mutation = transformer(ctx) |
| 1121 | if scope == "oos": |
| 1122 | |
| 1123 | |
| 1124 | mutation = { |
| 1125 | **mutation, |
| 1126 | "scope_framing": "neutral_oos", |
| 1127 | "boundary_semantics": _oos_semantics(ctx), |
| 1128 | } |
| 1129 | question = " ".join(question.split()) |
| 1130 | findings = privacy_findings(question) |
| 1131 | if findings: |
| 1132 | raise ValueError(f"{seed.source_dataset}:{seed.source_index} mutasyonu PII/secret üretti: {', '.join(findings)}") |
| 1133 | expected, policy = ( |
| 1134 | _expected_in_scope_contract(seed, role) if scope == "in_scope" |
| 1135 | else _expected_oos_contract(seed) |
| 1136 | ) |
| 1137 | if scope == "in_scope": |
| 1138 | safety_contract = _expected_other_person_safety_contract( |
| 1139 | seed.expected_intent, role, question, |
| 1140 | ) |
| 1141 | if safety_contract is not None: |
| 1142 | expected, policy = safety_contract |
| 1143 | return { |
| 1144 | "question": question, "expected_intent": seed.expected_intent, |
| 1145 | "expected": expected, "role": role, "scope": scope, |
| 1146 | "scope_boundary_type": seed.scope_boundary_type, "family": family, |
| 1147 | "transformations": transformations, |
| 1148 | "mutation": {**mutation, "variant_hash": f"{variant:016x}"}, |
| 1149 | "policy": policy, |
| 1150 | "source": { |
| 1151 | "dataset": seed.source_dataset, "index": seed.source_index, |
| 1152 | "question": seed.question, "role": seed.role, |
| 1153 | }, |
| 1154 | "synthetic": True, "is_gold": False, "generator_version": GENERATOR_VERSION, |
| 1155 | "generation_round": round_index, |
| 1156 | "privacy_scan": {"passed": True, "findings": []}, |
| 1157 | } |
| 1158 | |
| 1159 | |
| 1160 | def _iter_intent_candidates(intent: str, seeds: Sequence[Seed]) -> Iterator[dict[str, Any]]: |
| 1161 | role_groups = _policy_roles(intent) |
| 1162 | outcomes = tuple(role_groups) |
| 1163 | for slot in range(200_000): |
| 1164 | outcome = outcomes[slot % len(outcomes)] |
| 1165 | seed_cycle = slot // len(outcomes) |
| 1166 | seed = seeds[seed_cycle % len(seeds)] |
| 1167 | families = _eligible_families(intent, seed.question) |
| 1168 | family = families[(seed_cycle // len(seeds)) % len(families)] |
| 1169 | round_index = seed_cycle // max(1, len(seeds) * len(families)) |
| 1170 | roles = role_groups[outcome] |
| 1171 | role = roles[_stable_int(MUTATION_SEED_VERSION, intent, seed.question, round_index, family, outcome) % len(roles)] |
| 1172 | yield _make_record(seed, role=role, family=family, round_index=round_index, scope="in_scope") |
| 1173 | |
| 1174 | |
| 1175 | def _intent_quotas(intents: Sequence[str], target: int) -> dict[str, int]: |
| 1176 | if target < 0: |
| 1177 | raise ValueError("Hedef kayıt sayısı negatif olamaz.") |
| 1178 | if not intents and target: |
| 1179 | raise ValueError("Intent kotası için intent bulunamadı.") |
| 1180 | base, remainder = divmod(target, len(intents)) if intents else (0, 0) |
| 1181 | return {intent: base + (1 if index < remainder else 0) for index, intent in enumerate(intents)} |
| 1182 | |
| 1183 | |
| 1184 | def _accept_unique(record: dict[str, Any], records: list[dict[str, Any]], seen_questions: set[str]) -> bool: |
| 1185 | key = normalise_question_key(record["question"]) |
| 1186 | if key in seen_questions: |
| 1187 | return False |
| 1188 | seen_questions.add(key) |
| 1189 | records.append(record) |
| 1190 | return True |
| 1191 | |
| 1192 | |
| 1193 | def _generate_in_scope(seeds: Sequence[Seed], target: int, seen_questions: set[str]) -> list[dict[str, Any]]: |
| 1194 | grouped: dict[str, list[Seed]] = defaultdict(list) |
| 1195 | for seed in seeds: |
| 1196 | grouped[seed.expected_intent].append(seed) |
| 1197 | catalog_order = [item["intent"] for item in INTENTS if item["intent"] in grouped] |
| 1198 | intents = catalog_order + sorted(set(grouped).difference(catalog_order)) |
| 1199 | quotas = _intent_quotas(intents, target) |
| 1200 | records: list[dict[str, Any]] = [] |
| 1201 | for intent in intents: |
| 1202 | wanted, accepted = quotas[intent], 0 |
| 1203 | for candidate in _iter_intent_candidates(intent, grouped[intent]): |
| 1204 | if _accept_unique(candidate, records, seen_questions): |
| 1205 | accepted += 1 |
| 1206 | if accepted == wanted: |
| 1207 | break |
| 1208 | if accepted != wanted: |
| 1209 | raise ValueError(f"{intent} için {wanted} normalize-benzersiz vaka üretilemedi; {accepted} kayıtta kaldı.") |
| 1210 | return records |
| 1211 | |
| 1212 | |
| 1213 | def _iter_oos_candidates(seeds: Sequence[Seed]) -> Iterator[dict[str, Any]]: |
| 1214 | for slot in range(500_000): |
| 1215 | seed = seeds[slot % len(seeds)] |
| 1216 | cycle = slot // len(seeds) |
| 1217 | family = OOS_MUTATION_FAMILIES[cycle % len(OOS_MUTATION_FAMILIES)] |
| 1218 | round_index = cycle // len(OOS_MUTATION_FAMILIES) |
| 1219 | role = ROLE_HIERARCHY[_stable_int(MUTATION_SEED_VERSION, "oos", seed.question, round_index, family) % len(ROLE_HIERARCHY)] |
| 1220 | yield _make_record(seed, role=role, family=family, round_index=round_index, scope="oos") |
| 1221 | |
| 1222 | |
| 1223 | def _generate_oos(seeds: Sequence[Seed], target: int, seen_questions: set[str]) -> list[dict[str, Any]]: |
| 1224 | if target < 0: |
| 1225 | raise ValueError("Hedef kayıt sayısı negatif olamaz.") |
| 1226 | records: list[dict[str, Any]] = [] |
| 1227 | for candidate in _iter_oos_candidates(seeds): |
| 1228 | _accept_unique(candidate, records, seen_questions) |
| 1229 | if len(records) == target: |
| 1230 | return records |
| 1231 | raise ValueError(f"OOS için {target} normalize-benzersiz vaka üretilemedi; {len(records)} kayıtta kaldı.") |
| 1232 | |
| 1233 | |
| 1234 | def _stable_record_id(record: Mapping[str, Any]) -> str: |
| 1235 | identity = { |
| 1236 | "generator_version": GENERATOR_VERSION, |
| 1237 | "question_key": normalise_question_key(str(record["question"])), |
| 1238 | "role": record["role"], "expected": record["expected"], |
| 1239 | "source": record["source"], "family": record["family"], |
| 1240 | } |
| 1241 | raw = json.dumps(identity, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") |
| 1242 | return "stress-" + hashlib.sha256(raw).hexdigest()[:20] |
| 1243 | |
| 1244 | |
| 1245 | def generate_stress_records( |
| 1246 | *, benchmark_path: str | Path = DEFAULT_BENCHMARK_PATH, |
| 1247 | near_oos_path: str | Path = DEFAULT_NEAR_OOS_PATH, |
| 1248 | in_scope_count: int = DEFAULT_IN_SCOPE_COUNT, |
| 1249 | oos_count: int = DEFAULT_OOS_COUNT, |
| 1250 | ) -> list[dict[str, Any]]: |
| 1251 | in_scope_seeds, oos_seeds = load_source_seeds(benchmark_path, near_oos_path) |
| 1252 | seen_questions: set[str] = set() |
| 1253 | records = _generate_in_scope(in_scope_seeds, in_scope_count, seen_questions) |
| 1254 | records.extend(_generate_oos(oos_seeds, oos_count, seen_questions)) |
| 1255 | output: list[dict[str, Any]] = [] |
| 1256 | seen_ids: set[str] = set() |
| 1257 | for record in records: |
| 1258 | record_id = _stable_record_id(record) |
| 1259 | if record_id in seen_ids: |
| 1260 | raise ValueError(f"Kararlı vaka kimliği çakıştı: {record_id}") |
| 1261 | seen_ids.add(record_id) |
| 1262 | output.append({"id": record_id, **record}) |
| 1263 | return output |
| 1264 | |
| 1265 | |
| 1266 | def write_jsonl(records: Iterable[dict[str, Any]], output: str | Path) -> Path: |
| 1267 | path = Path(output) |
| 1268 | path.parent.mkdir(parents=True, exist_ok=True) |
| 1269 | lines = [json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) for record in records] |
| 1270 | path.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n") |
| 1271 | return path |
| 1272 | |
| 1273 | |
| 1274 | def load_stress_records(path: str | Path = DEFAULT_DATA_OUTPUT) -> list[dict[str, Any]]: |
| 1275 | return _read_jsonl(Path(path)) |
| 1276 | |
| 1277 | |
| 1278 | def _actual_outcome(response: Mapping[str, Any]) -> str: |
| 1279 | response_id = response.get("response_id") |
| 1280 | meta = response.get("assistant_meta") |
| 1281 | if response_id == "out_of_scope_action": |
| 1282 | return "deny" |
| 1283 | if response_id == "clarification_prompt": |
| 1284 | return "clarify" |
| 1285 | if bool(response.get("fallback")): |
| 1286 | return "fallback" |
| 1287 | if response.get("auth_action") is not None: |
| 1288 | return "deny" |
| 1289 | if isinstance(response_id, str) and response_id.startswith("safety_"): |
| 1290 | return "deny" |
| 1291 | if isinstance(meta, Mapping) and isinstance(meta.get("outcome"), str): |
| 1292 | return str(meta["outcome"]) |
| 1293 | return "allow" |
| 1294 | |
| 1295 | |
| 1296 | def _nested_route(response: Mapping[str, Any], *, meta: bool) -> str | None: |
| 1297 | if meta: |
| 1298 | assistant_meta = response.get("assistant_meta") |
| 1299 | if not isinstance(assistant_meta, Mapping): |
| 1300 | return None |
| 1301 | navigation, key = assistant_meta.get("navigation"), "route_key" |
| 1302 | else: |
| 1303 | navigation, key = response.get("navigation"), "route" |
| 1304 | if not isinstance(navigation, Mapping): |
| 1305 | return None |
| 1306 | value = navigation.get(key) |
| 1307 | return value if isinstance(value, str) else None |
| 1308 | |
| 1309 | |
| 1310 | def _contract_checks(expected: Mapping[str, Any], response: Mapping[str, Any]) -> tuple[dict[str, dict[str, Any]], list[str]]: |
| 1311 | meta = response.get("assistant_meta") |
| 1312 | meta_mapping = meta if isinstance(meta, Mapping) else {} |
| 1313 | actual = { |
| 1314 | "intent": response.get("intent"), "outcome": _actual_outcome(response), |
| 1315 | "meta_outcome": meta_mapping.get("outcome"), "response_id": response.get("response_id"), |
| 1316 | "meta_action_id": meta_mapping.get("action_id"), |
| 1317 | "auth_action": response.get("auth_action"), "fallback": bool(response.get("fallback")), |
| 1318 | "navigation_route": _nested_route(response, meta=False), |
| 1319 | "meta_route_key": _nested_route(response, meta=True), |
| 1320 | "reason_code": meta_mapping.get("reason_code"), |
| 1321 | } |
| 1322 | response_ids = list(expected.get("response_ids") or []) |
| 1323 | predicates = { |
| 1324 | "intent": actual["intent"] == expected.get("intent"), |
| 1325 | "outcome": actual["outcome"] == expected.get("outcome"), |
| 1326 | "meta_outcome": actual["meta_outcome"] == expected.get("meta_outcome"), |
| 1327 | "meta_action_id": actual["meta_action_id"] == expected.get("meta_action_id"), |
| 1328 | "response_id": actual["response_id"] in response_ids, |
| 1329 | "auth_action": actual["auth_action"] == expected.get("auth_action"), |
| 1330 | "fallback": actual["fallback"] is bool(expected.get("fallback")), |
| 1331 | "navigation_route": actual["navigation_route"] == expected.get("navigation_route"), |
| 1332 | "meta_route_key": actual["meta_route_key"] == expected.get("meta_route_key"), |
| 1333 | "reason_code": expected.get("reason_code") is None or actual["reason_code"] == expected.get("reason_code"), |
| 1334 | } |
| 1335 | checks = { |
| 1336 | key: { |
| 1337 | "passed": passed, |
| 1338 | "expected": response_ids if key == "response_id" else expected.get(key), |
| 1339 | "actual": actual["response_id"] if key == "response_id" else actual.get(key), |
| 1340 | } |
| 1341 | for key, passed in predicates.items() |
| 1342 | } |
| 1343 | reasons = [f"{key}_mismatch" for key, passed in predicates.items() if not passed] |
| 1344 | text = response.get("text") |
| 1345 | if not isinstance(text, str) or not text.strip(): |
| 1346 | checks["visible_text"] = {"passed": False, "expected": "non_empty", "actual": text} |
| 1347 | reasons.append("empty_visible_text") |
| 1348 | else: |
| 1349 | checks["visible_text"] = {"passed": True, "expected": "non_empty", "actual": "present"} |
| 1350 | findings = privacy_findings(text) |
| 1351 | checks["response_privacy"] = {"passed": not findings, "expected": [], "actual": findings} |
| 1352 | if findings: |
| 1353 | reasons.append("response_privacy_finding") |
| 1354 | return checks, reasons |
| 1355 | |
| 1356 | |
| 1357 | def _is_semantic_safe_oos_clarification( |
| 1358 | record: Mapping[str, Any], response: Mapping[str, Any], reasons: Sequence[str], |
| 1359 | ) -> bool: |
| 1360 | |
| 1361 | |
| 1362 | |
| 1363 | |
| 1364 | |
| 1365 | |
| 1366 | |
| 1367 | expected = record.get("expected") |
| 1368 | meta = response.get("assistant_meta") |
| 1369 | if not reasons or not isinstance(expected, Mapping) or not isinstance(meta, Mapping): |
| 1370 | return False |
| 1371 | if record.get("scope") != "oos" or record.get("scope_boundary_type"): |
| 1372 | return False |
| 1373 | if expected.get("outcome") != "fallback" or expected.get("intent") is not None: |
| 1374 | return False |
| 1375 | if {"engine_exception", "empty_visible_text", "response_privacy_finding"}.intersection(reasons): |
| 1376 | return False |
| 1377 | return ( |
| 1378 | response.get("intent") is None |
| 1379 | and response.get("response_id") == "clarification_prompt" |
| 1380 | and _actual_outcome(response) == "clarify" |
| 1381 | and meta.get("outcome") == "clarify" |
| 1382 | and meta.get("action_id") is None |
| 1383 | and response.get("auth_action") is None |
| 1384 | and _nested_route(response, meta=False) is None |
| 1385 | and _nested_route(response, meta=True) is None |
| 1386 | ) |
| 1387 | |
| 1388 | |
| 1389 | def collect_results(records: Iterable[dict[str, Any]], *, engine: Engine | None = None) -> list[dict[str, Any]]: |
| 1390 | runner = engine or Engine() |
| 1391 | results: list[dict[str, Any]] = [] |
| 1392 | for index, record in enumerate(records, start=1): |
| 1393 | role = record.get("role", "ziyaretci") |
| 1394 | payload = { |
| 1395 | "query": record["question"], "trace_id": f"stress-{index:05d}", |
| 1396 | "session": {"role": role, "authenticated": role != "ziyaretci"}, |
| 1397 | } |
| 1398 | engine_exception: dict[str, str] | None = None |
| 1399 | try: |
| 1400 | response = runner.handle(payload) |
| 1401 | if not isinstance(response, dict): |
| 1402 | raise TypeError("Engine.handle bir sözlük döndürmeli.") |
| 1403 | except Exception as exc: |
| 1404 | engine_exception = {"type": type(exc).__name__, "message": str(exc)} |
| 1405 | response = {"exception": engine_exception} |
| 1406 | expected = record.get("expected") |
| 1407 | if not isinstance(expected, Mapping): |
| 1408 | raise ValueError(f"{record.get('id', index)}: expected sözleşmesi eksik.") |
| 1409 | checks, reasons = _contract_checks(expected, response) |
| 1410 | if engine_exception is not None: |
| 1411 | reasons.insert(0, "engine_exception") |
| 1412 | actual_intent = response.get("intent") if engine_exception is None else None |
| 1413 | failure_severity = None |
| 1414 | if reasons: |
| 1415 | failure_severity = ( |
| 1416 | "soft" if _is_semantic_safe_oos_clarification(record, response, reasons) |
| 1417 | else "hard" |
| 1418 | ) |
| 1419 | results.append({ |
| 1420 | "index": index, **record, "actual_intent": actual_intent or OOS_LABEL, |
| 1421 | "actual_outcome": _actual_outcome(response), "contract_checks": checks, |
| 1422 | "failure_reasons": reasons, "failure_severity": failure_severity, |
| 1423 | "passed": not reasons, "response": response, |
| 1424 | }) |
| 1425 | return results |
| 1426 | |
| 1427 | |
| 1428 | def _table_text(value: object) -> str: |
| 1429 | return str(value).replace("|", "\\|").replace("\n", "<br>") |
| 1430 | |
| 1431 | |
| 1432 | def _quote(text: object) -> str: |
| 1433 | lines = str(text).splitlines() or [""] |
| 1434 | return "\n".join("> " + line if line else ">" for line in lines) |
| 1435 | |
| 1436 | |
| 1437 | def _value_at(row: Mapping[str, Any], path: str) -> str: |
| 1438 | value: Any = row |
| 1439 | for key in path.split("."): |
| 1440 | if not isinstance(value, Mapping): |
| 1441 | return "-" |
| 1442 | value = value.get(key) |
| 1443 | return "-" if value is None else str(value) |
| 1444 | |
| 1445 | |
| 1446 | def _ordered_values(key: str, values: Iterable[str]) -> list[str]: |
| 1447 | unique = set(values) |
| 1448 | if key == "family": |
| 1449 | fixed = [value for value in MUTATION_FAMILIES if value in unique] |
| 1450 | return fixed + sorted(unique.difference(fixed)) |
| 1451 | if key == "role": |
| 1452 | fixed = [value for value in ROLE_HIERARCHY if value in unique] |
| 1453 | return fixed + sorted(unique.difference(fixed)) |
| 1454 | return sorted(unique) |
| 1455 | |
| 1456 | |
| 1457 | def _breakdown_table(rows: Sequence[dict[str, Any]], key: str, heading: str) -> list[str]: |
| 1458 | counts: dict[str, Counter[str]] = {} |
| 1459 | for row in rows: |
| 1460 | value = _value_at(row, key) |
| 1461 | bucket = counts.setdefault(value, Counter()) |
| 1462 | bucket["total"] += 1 |
| 1463 | bucket["passed" if row["passed"] else "failed"] += 1 |
| 1464 | output = [f"## {heading}", "", "| Değer | Toplam | PASS | FAIL | Başarı |", "|---|---:|---:|---:|---:|"] |
| 1465 | for value in _ordered_values(key, counts): |
| 1466 | count = counts[value] |
| 1467 | rate = count["passed"] / count["total"] if count["total"] else 0.0 |
| 1468 | label = ROLE_LABELS.get(value, value) if key == "role" else value |
| 1469 | output.append(f"| {_table_text(label)} | {count['total']} | {count['passed']} | {count['failed']} | {rate:.1%} |") |
| 1470 | return output |
| 1471 | |
| 1472 | |
| 1473 | def _failure_cluster_table(rows: Sequence[dict[str, Any]]) -> list[str]: |
| 1474 | clusters: Counter[str] = Counter(reason for row in rows for reason in row.get("failure_reasons", [])) |
| 1475 | output = ["## Hata kümeleri", ""] |
| 1476 | if not clusters: |
| 1477 | return output + ["Sözleşme ihlali oluşmadı."] |
| 1478 | output.extend(["| Failure reason | Vaka |", "|---|---:|"]) |
| 1479 | output.extend(f"| `{reason}` | {count} |" for reason, count in clusters.most_common()) |
| 1480 | return output |
| 1481 | |
| 1482 | |
| 1483 | def _oos_case_type(row: Mapping[str, Any]) -> str: |
| 1484 | boundary = row.get("scope_boundary_type") |
| 1485 | if not boundary: |
| 1486 | expected = row.get("expected") |
| 1487 | reason = expected.get("reason_code") if isinstance(expected, Mapping) else None |
| 1488 | if isinstance(reason, str) and reason.startswith("scope_boundary_"): |
| 1489 | boundary = reason.removeprefix("scope_boundary_") |
| 1490 | if not boundary: |
| 1491 | return "fallback" |
| 1492 | normalized = str(boundary).strip().casefold() |
| 1493 | return f"{normalized}-boundary" |
| 1494 | |
| 1495 | |
| 1496 | def _oos_quality_table(rows: Sequence[dict[str, Any]]) -> list[str]: |
| 1497 | oos_rows = [row for row in rows if row.get("scope") == "oos"] |
| 1498 | counts: dict[str, Counter[str]] = {} |
| 1499 | for row in oos_rows: |
| 1500 | bucket = counts.setdefault(_oos_case_type(row), Counter()) |
| 1501 | bucket["total"] += 1 |
| 1502 | if row.get("passed"): |
| 1503 | bucket["passed"] += 1 |
| 1504 | elif row.get("failure_severity") == "soft": |
| 1505 | bucket["soft"] += 1 |
| 1506 | else: |
| 1507 | bucket["hard"] += 1 |
| 1508 | |
| 1509 | |
| 1510 | ordered = ["fallback", "action-boundary", "data-boundary"] |
| 1511 | ordered.extend(sorted(set(counts).difference(ordered))) |
| 1512 | output = [ |
| 1513 | "## OOS türü ve FAIL şiddeti", "", |
| 1514 | "`soft`, yalnız katı fallback sözleşmesi yerine intent/action/route üretmeden " |
| 1515 | "netleştirme isteyen semantik olarak güvenli yanıttır; sözleşme sonucu yine FAIL kalır. " |
| 1516 | "Diğer bütün sözleşme ihlalleri `hard` sayılır.", "", |
| 1517 | "| OOS türü | Toplam | PASS | Soft FAIL | Hard FAIL | Sözleşme başarısı |", |
| 1518 | "|---|---:|---:|---:|---:|---:|", |
| 1519 | ] |
| 1520 | for kind in ordered: |
| 1521 | count = counts.get(kind, Counter()) |
| 1522 | rate = count["passed"] / count["total"] if count["total"] else 0.0 |
| 1523 | output.append( |
| 1524 | f"| `{kind}` | {count['total']} | {count['passed']} | {count['soft']} | " |
| 1525 | f"{count['hard']} | {rate:.1%} |" |
| 1526 | ) |
| 1527 | return output |
| 1528 | |
| 1529 | |
| 1530 | def _failure_examples(rows: Sequence[dict[str, Any]], *, scope: str, limit: int = 50) -> list[str]: |
| 1531 | failures = [row for row in rows if row.get("scope") == scope and not row.get("passed")] |
| 1532 | heading = "İlk uygulama-içi FAIL örnekleri" if scope == "in_scope" else "İlk OOS FAIL örnekleri" |
| 1533 | output = [f"## {heading}", ""] |
| 1534 | if not failures: |
| 1535 | return output + ["FAIL oluşmadı."] |
| 1536 | if scope == "oos": |
| 1537 | output.extend([ |
| 1538 | "| ID | Tür | Şiddet | Rol | Soru | Nedenler |", |
| 1539 | "|---|---|---|---|---|---|", |
| 1540 | ]) |
| 1541 | for row in failures[:limit]: |
| 1542 | output.append( |
| 1543 | f"| `{row.get('id', '-')}` | `{_oos_case_type(row)}` | " |
| 1544 | f"`{row.get('failure_severity') or 'hard'}` | " |
| 1545 | f"{_table_text(ROLE_LABELS.get(row['role'], row['role']))} | " |
| 1546 | f"{_table_text(row['question'])} | " |
| 1547 | f"{_table_text(', '.join(row.get('failure_reasons', [])))} |" |
| 1548 | ) |
| 1549 | else: |
| 1550 | output.extend(["| ID | Rol | Soru | Nedenler |", "|---|---|---|---|"]) |
| 1551 | for row in failures[:limit]: |
| 1552 | output.append( |
| 1553 | f"| `{row.get('id', '-')}` | {_table_text(ROLE_LABELS.get(row['role'], row['role']))} | " |
| 1554 | f"{_table_text(row['question'])} | {_table_text(', '.join(row.get('failure_reasons', [])))} |" |
| 1555 | ) |
| 1556 | return output |
| 1557 | |
| 1558 | |
| 1559 | def render_markdown( |
| 1560 | results: Iterable[dict[str, Any]], *, part_links: Sequence[str] = (), |
| 1561 | results_link: str = "data/stress_benchmark_results.jsonl", |
| 1562 | ) -> str: |
| 1563 | rows = list(results) |
| 1564 | passed = sum(bool(row["passed"]) for row in rows) |
| 1565 | failed = len(rows) - passed |
| 1566 | soft_failed = sum( |
| 1567 | not row.get("passed") and row.get("failure_severity") == "soft" |
| 1568 | for row in rows |
| 1569 | ) |
| 1570 | hard_failed = failed - soft_failed |
| 1571 | rate = passed / len(rows) if rows else 0.0 |
| 1572 | output = [ |
| 1573 | "# Çelebi Sentetik Stres Benchmarkı Sonuçları", "", "> [!IMPORTANT]", |
| 1574 | "> Bu küme bağımsız bir **gold benchmark değildir**. Yalnız insan etiketli " |
| 1575 | "sorulardan türetilen tanısal/metamorfik stres testidir; katalog örnekleri " |
| 1576 | "değerlendirme seed'i değildir.", "", f"- Generator: `{GENERATOR_VERSION}`", |
| 1577 | f"- Toplam vaka: **{len(rows)}**", |
| 1578 | f"- Uygulama-içi: **{sum(row.get('scope') == 'in_scope' for row in rows)}**", |
| 1579 | f"- OOS: **{sum(row.get('scope') == 'oos' for row in rows)}**", |
| 1580 | f"- PASS: **{passed}**", f"- FAIL: **{failed}**", |
| 1581 | f"- Soft FAIL: **{soft_failed}**", f"- Hard FAIL: **{hard_failed}**", |
| 1582 | f"- Tam sözleşme başarı oranı: **{rate:.1%}**", "", |
| 1583 | "Tam Engine payload'ı `python stress_benchmark.py` çalıştırıldığında yerelde " |
| 1584 | f"`{results_link}` olarak üretilir (büyük ve yeniden üretilebilir olduğu için " |
| 1585 | "Git'e alınmaz). Markdown parçaları inceleme metadata'sı ile kullanıcıya " |
| 1586 | "görünen soru/cevabı gösterir; iç içe makine payload'ını göstermez.", "", |
| 1587 | ] |
| 1588 | for key, heading in ( |
| 1589 | ("source.dataset", "Kaynak bazında"), |
| 1590 | ("expected.outcome", "Beklenen outcome bazında"), |
| 1591 | ("actual_outcome", "Gerçek outcome bazında"), |
| 1592 | ("family", "Varyasyon ailesi bazında"), |
| 1593 | ("expected_intent", "Beklenen intent bazında"), |
| 1594 | ("role", "Rol bazında"), |
| 1595 | ): |
| 1596 | output.extend(_breakdown_table(rows, key, heading)) |
| 1597 | output.append("") |
| 1598 | output.extend(_oos_quality_table(rows)) |
| 1599 | output.append("") |
| 1600 | output.extend(_failure_cluster_table(rows)) |
| 1601 | output.extend(["", "## Okunabilir rapor parçaları", ""]) |
| 1602 | output.extend(f"- [{Path(link).name}]({link})" for link in part_links) if part_links else output.append("Parça bağlantısı verilmedi.") |
| 1603 | output.append("") |
| 1604 | output.extend(_failure_examples(rows, scope="in_scope")) |
| 1605 | output.append("") |
| 1606 | output.extend(_failure_examples(rows, scope="oos")) |
| 1607 | return "\n".join(output).rstrip() + "\n" |
| 1608 | |
| 1609 | |
| 1610 | def render_markdown_part(rows: Sequence[dict[str, Any]], *, part_number: int, total_parts: int) -> str: |
| 1611 | output = [ |
| 1612 | f"# Çelebi Stres Vakaları · Parça {part_number}/{total_parts}", "", |
| 1613 | "Bu dosyada her vaka için kısa inceleme metadata'sı ile kullanıcıya görünen soru ve cevap " |
| 1614 | "vardır. Tam Engine yanıtı ve iç içe makine alanları results JSONL artefaktındadır.", "", |
| 1615 | ] |
| 1616 | for row in rows: |
| 1617 | status = "PASS" if row["passed"] else "FAIL" |
| 1618 | response = row.get("response") or {} |
| 1619 | visible_text = response.get("text", "[Engine görünür metin döndürmedi]") |
| 1620 | output.extend([ |
| 1621 | f"## {row['index']:05d} · {status} · {ROLE_LABELS.get(row['role'], row['role'])}", "", |
| 1622 | f"- ID: `{row.get('id', '-')}`", f"- Aile: `{row.get('family', '-')}`", |
| 1623 | f"- Kaynak: `{_value_at(row, 'source.dataset')}:{_value_at(row, 'source.index')}`", |
| 1624 | f"- Beklenen: `{_value_at(row, 'expected.intent')}` / `{_value_at(row, 'expected.outcome')}`", |
| 1625 | f"- Gerçek: `{row.get('actual_intent', '-')}` / `{row.get('actual_outcome', '-')}`", |
| 1626 | f"- Failure reasons: `{', '.join(row.get('failure_reasons', [])) or '-'}`", "", |
| 1627 | "### Soru", "", _quote(row["question"]), "", |
| 1628 | "### Kullanıcıya görünen cevap", "", _quote(visible_text), "", |
| 1629 | ]) |
| 1630 | return "\n".join(output).rstrip() + "\n" |
| 1631 | |
| 1632 | |
| 1633 | def write_report( |
| 1634 | results: Iterable[dict[str, Any]], output: str | Path, *, chunk_size: int = DEFAULT_REPORT_CHUNK_SIZE, |
| 1635 | results_path: str | Path = DEFAULT_RESULTS_OUTPUT, |
| 1636 | ) -> Path: |
| 1637 | if not MIN_REPORT_CHUNK_SIZE <= chunk_size <= MAX_REPORT_CHUNK_SIZE: |
| 1638 | raise ValueError(f"Markdown parça boyutu {MIN_REPORT_CHUNK_SIZE}-{MAX_REPORT_CHUNK_SIZE} olmalı.") |
| 1639 | rows = list(results) |
| 1640 | path = Path(output) |
| 1641 | path.parent.mkdir(parents=True, exist_ok=True) |
| 1642 | part_dir = path.with_name(path.stem + "_parcalar") |
| 1643 | part_dir.mkdir(parents=True, exist_ok=True) |
| 1644 | |
| 1645 | |
| 1646 | |
| 1647 | for stale_part in part_dir.glob("part-*.md"): |
| 1648 | if stale_part.is_file(): |
| 1649 | stale_part.unlink() |
| 1650 | total_parts = max(1, (len(rows) + chunk_size - 1) // chunk_size) |
| 1651 | part_paths: list[Path] = [] |
| 1652 | for part_index in range(total_parts): |
| 1653 | chunk = rows[part_index * chunk_size:(part_index + 1) * chunk_size] |
| 1654 | part_path = part_dir / f"part-{part_index + 1:04d}.md" |
| 1655 | part_path.write_text( |
| 1656 | render_markdown_part(chunk, part_number=part_index + 1, total_parts=total_parts), |
| 1657 | encoding="utf-8", newline="\n", |
| 1658 | ) |
| 1659 | part_paths.append(part_path) |
| 1660 | links = [part.relative_to(path.parent).as_posix() for part in part_paths] |
| 1661 | result_target = Path(results_path) |
| 1662 | try: |
| 1663 | result_link = result_target.resolve().relative_to(path.parent.resolve()).as_posix() |
| 1664 | except ValueError: |
| 1665 | result_link = result_target.resolve().as_posix() |
| 1666 | path.write_text( |
| 1667 | render_markdown(rows, part_links=links, results_link=result_link), |
| 1668 | encoding="utf-8", newline="\n", |
| 1669 | ) |
| 1670 | return path |
| 1671 | |
| 1672 | |
| 1673 | def build_artifacts( |
| 1674 | *, benchmark_path: str | Path = DEFAULT_BENCHMARK_PATH, |
| 1675 | near_oos_path: str | Path = DEFAULT_NEAR_OOS_PATH, |
| 1676 | data_output: str | Path = DEFAULT_DATA_OUTPUT, |
| 1677 | results_output: str | Path = DEFAULT_RESULTS_OUTPUT, |
| 1678 | report_output: str | Path = DEFAULT_REPORT_OUTPUT, |
| 1679 | report_chunk_size: int = DEFAULT_REPORT_CHUNK_SIZE, |
| 1680 | engine: Engine | None = None, |
| 1681 | ) -> tuple[Path, Path, list[dict[str, Any]]]: |
| 1682 | records = generate_stress_records(benchmark_path=benchmark_path, near_oos_path=near_oos_path) |
| 1683 | data_path = write_jsonl(records, data_output) |
| 1684 | persisted_records = load_stress_records(data_path) |
| 1685 | results = collect_results(persisted_records, engine=engine) |
| 1686 | results_path = write_jsonl(results, results_output) |
| 1687 | report_path = write_report( |
| 1688 | results, report_output, chunk_size=report_chunk_size, |
| 1689 | results_path=results_path, |
| 1690 | ) |
| 1691 | return data_path, report_path, results |
| 1692 | |
| 1693 | |
| 1694 | def main(argv: Sequence[str] | None = None) -> int: |
| 1695 | parser = argparse.ArgumentParser(description=__doc__) |
| 1696 | parser.add_argument("--benchmark", type=Path, default=DEFAULT_BENCHMARK_PATH) |
| 1697 | parser.add_argument("--near-oos", type=Path, default=DEFAULT_NEAR_OOS_PATH) |
| 1698 | parser.add_argument("--data-output", type=Path, default=DEFAULT_DATA_OUTPUT) |
| 1699 | parser.add_argument("--results-output", type=Path, default=DEFAULT_RESULTS_OUTPUT) |
| 1700 | parser.add_argument("--report-output", type=Path, default=DEFAULT_REPORT_OUTPUT) |
| 1701 | parser.add_argument("--report-chunk-size", type=int, default=DEFAULT_REPORT_CHUNK_SIZE, |
| 1702 | help="Okunabilir Markdown parçası başına 250-500 vaka (varsayılan 400).") |
| 1703 | parser.add_argument("--strict", action="store_true", help="En az bir sözleşme FAIL'inde exit 1 kullan.") |
| 1704 | parser.add_argument("--allow-failures", action="store_true", |
| 1705 | help="Geriye uyumlu no-op; tanısal varsayılan zaten FAIL'de exit 0 kullanır.") |
| 1706 | args = parser.parse_args(argv) |
| 1707 | data_path, report_path, results = build_artifacts( |
| 1708 | benchmark_path=args.benchmark, near_oos_path=args.near_oos, |
| 1709 | data_output=args.data_output, results_output=args.results_output, |
| 1710 | report_output=args.report_output, report_chunk_size=args.report_chunk_size, |
| 1711 | ) |
| 1712 | failed = sum(not row["passed"] for row in results) |
| 1713 | print( |
| 1714 | f"{len(results)} sentetik vaka -> {data_path}, {args.results_output}, {report_path} " |
| 1715 | f"(PASS={len(results) - failed}, FAIL={failed})" |
| 1716 | ) |
| 1717 | return 1 if args.strict and failed else 0 |
| 1718 | |
| 1719 | |
| 1720 | if __name__ == "__main__": |
| 1721 | raise SystemExit(main()) |