temel kısımlar bitti n gram benchmark hazırlama gibi...
Browse files at this commitbe255cdae34cb52b6b4da80531edd0e79f7f0be3Parent: c9d9b1541 changed files +4806 -726
- .gitignore +1 -0
- Dockerfile +1 -0
- ReadMe.md +120 -1
- data/benchmark.jsonl +147 -0
- src/QandA.py +0 -606
- src/benchmark.py +128 -0
- src/catalog.py +1168 -0
- src/cli.py +123 -0
- src/decision.py +180 -0
- src/domain.py +90 -0
- src/engine.py +112 -0
- src/evaluate.py +181 -0
- src/main.py +27 -94
- src/metrics.py +112 -0
- src/normalize.py +165 -0
- src/observability.py +158 -0
- src/responder.py +101 -0
- src/rules.py +257 -0
- src/similarity.py +183 -0
- tests/e2e/__init__.py +1 -0
- tests/e2e/test_conversation.py +56 -0
- tests/integration/__init__.py +1 -0
- tests/integration/test_decision_benchmark.py +66 -0
- tests/integration/test_engine.py +93 -0
- tests/integration/test_pipeline_benchmark.py +67 -0
- tests/integration/test_regression.py +83 -0
- tests/integration/test_rules_benchmark.py +81 -0
- tests/test_catalog.py +0 -25
- tests/unit/__init__.py +1 -0
- tests/unit/test_benchmark.py +138 -0
- tests/unit/test_catalog.py +156 -0
- tests/unit/test_cli.py +95 -0
- tests/unit/test_decision.py +81 -0
- tests/unit/test_domain.py +56 -0
- tests/unit/test_evaluate.py +72 -0
- tests/unit/test_metrics.py +57 -0
- tests/unit/test_normalize.py +125 -0
- tests/unit/test_observability.py +102 -0
- tests/unit/test_responder.py +82 -0
- tests/unit/test_rules.py +67 -0
- tests/unit/test_similarity.py +72 -0
.gitignoremodified+1 -0
| @@ -4,3 +4,4 @@ __pycache__/ | |||
| 4 | .pytest_cache/ | 4 | .pytest_cache/ |
| 5 | .coverage | 5 | .coverage |
| 6 | .agents | 6 | .agents |
| 7 | +hezarfen-site-rehberi.md | ||
| \ No newline at end of file | \ No newline at end of file | ||
Dockerfilemodified+1 -0
| @@ -12,6 +12,7 @@ RUN pip install --no-cache-dir --requirement requirements.txt | |||
| 12 | 12 | ||
| 13 | COPY src ./src | 13 | COPY src ./src |
| 14 | COPY tests ./tests | 14 | COPY tests ./tests |
| 15 | +COPY data ./data | ||
| 15 | 16 | ||
| 16 | # Container'ı root olmayan kullanıcıyla çalıştır. | 17 | # Container'ı root olmayan kullanıcıyla çalıştır. |
| 17 | RUN useradd --create-home --uid 10001 chatbot \ | 18 | RUN useradd --create-home --uid 10001 chatbot \ |
ReadMe.mdmodified+120 -1
| @@ -1 +1,120 @@ | |||
| 1 | -# Merhaba ben Kadir, yine chatbot yapıyorum. | ||
| \ No newline at end of file | \ No newline at end of file | ||
| 1 | +# Hezarfen Kullanım Asistanı — Kural Tabanlı Chatbot | ||
| 2 | + | ||
| 3 | +Hezarfen okul yönetim sitesinin **rol-farkında kullanım asistanı**. "Nasıl | ||
| 4 | +yaparım?" tarzı soruları, sitenin gerçek menü/etiket ve yollarına dayanarak | ||
| 5 | +adım adım yanıtlar. Harici çalışma-zamanı bağımlılığı yoktur (yalnızca Python | ||
| 6 | +standart kütüphanesi) ve tamamen offline çalışır. | ||
| 7 | + | ||
| 8 | +Bilgi kaynağı: `hezarfen-site-rehberi.md`. | ||
| 9 | + | ||
| 10 | +## Mimari (boru hattı) | ||
| 11 | + | ||
| 12 | +``` | ||
| 13 | +sorgu | ||
| 14 | + → normalize (Türkçe küçük harf + aksan katlama + hafif kök) src/normalize.py | ||
| 15 | + → kural katmanı (yüksek kesinlik, önek eşleşmesi) src/rules.py | ||
| 16 | + → benzerlik (TF-IDF karakter n-gram + kosinüs) src/similarity.py | ||
| 17 | + → domain-gate (alan-dışı sorguyu OOS'a at) src/domain.py | ||
| 18 | + → karar (eşik + tie-break + rol gating) src/decision.py | ||
| 19 | + → cevap (rol-farkında, gerçek etiket/yol) src/responder.py | ||
| 20 | +``` | ||
| 21 | + | ||
| 22 | +Her sorgu izlenir (per-stage latency + karar detayı) — `src/observability.py`. | ||
| 23 | +Backend sözleşmesi `src/engine.py`, terminal frontend `src/cli.py`. | ||
| 24 | + | ||
| 25 | +### Katmanlı tasarım neden? | ||
| 26 | +- **Kural katmanı** tek-anlamlı ve güvenlik-kritik soruları deterministik | ||
| 27 | + (~%100 kesinlikle) bağlar; belirsizlikte karar vermez. | ||
| 28 | +- **Benzerlik** kalan soruları toplar; "X nasıl oluşturulur" gibi ortak fiilli | ||
| 29 | + kalıpları kural katmanı alan-ismiyle (sınav/ders/dönem) ayırır. | ||
| 30 | +- **Domain-gate** char n-gram'ın OOS zayıflığını kapatır (OOS recall %44 → %78). | ||
| 31 | + | ||
| 32 | +## Modüller | ||
| 33 | + | ||
| 34 | +| Modül | Görev | | ||
| 35 | +|---|---| | ||
| 36 | +| `catalog.py` | Intent kataloğu (43 intent) + rol modeli + doğrulayıcı | | ||
| 37 | +| `benchmark.py` | Değerlendirme setini yükle/doğrula (`data/benchmark.jsonl`) | | ||
| 38 | +| `normalize.py` | Normalizasyon + Türkçe kök bulma + katlanmış token | | ||
| 39 | +| `rules.py` | Yüksek-kesinlik kural katmanı | | ||
| 40 | +| `similarity.py` | TF-IDF karakter n-gram benzerliği | | ||
| 41 | +| `domain.py` | Alan (OOS) kapısı | | ||
| 42 | +| `decision.py` | Eşik + tie-break + rol gating | | ||
| 43 | +| `responder.py` | Cevap üretimi (rol-farkında) | | ||
| 44 | +| `observability.py` | Aşama bazlı yapısal loglama (trace + alarm) | | ||
| 45 | +| `metrics.py` / `evaluate.py` | Metrikler + tam değerlendirme aracı | | ||
| 46 | +| `engine.py` | Backend servis + front/back sözleşmesi | | ||
| 47 | +| `cli.py` | Terminal frontend | | ||
| 48 | + | ||
| 49 | +## Çalıştırma | ||
| 50 | + | ||
| 51 | +```bash | ||
| 52 | +python -m src.main --validate # kataloğu doğrula | ||
| 53 | +python -m src.main --evaluate # benchmark üzerinde tam metrik raporu | ||
| 54 | +python -m src.main --chat # etkileşimli terminal asistanı | ||
| 55 | + | ||
| 56 | +# Docker | ||
| 57 | +docker compose up --build # container içinde --validate | ||
| 58 | +``` | ||
| 59 | + | ||
| 60 | +### Terminal örneği | ||
| 61 | +``` | ||
| 62 | +(ziyaretci) > /rol ogrenci | ||
| 63 | +Rol ayarlandı: ogrenci (authenticated=True) | ||
| 64 | +(ogrenci) > sınava nasıl girerim | ||
| 65 | +[exam_enter_room] Ön koşul: sınavın dersine kayıtlı olmak; ... | ||
| 66 | +``` | ||
| 67 | + | ||
| 68 | +## Front/back sözleşmesi | ||
| 69 | + | ||
| 70 | +İstek: | ||
| 71 | +```json | ||
| 72 | +{"query": "...", "session": {"role": "ogrenci", "authenticated": true}, "trace_id": "opsiyonel"} | ||
| 73 | +``` | ||
| 74 | +Yanıt: | ||
| 75 | +```json | ||
| 76 | +{"trace_id","response_id","text","intent","confidence","fallback","auth_action","required_role"} | ||
| 77 | +``` | ||
| 78 | + | ||
| 79 | +## Metrikler (mevcut baseline) | ||
| 80 | + | ||
| 81 | +`python -m src.main --evaluate` (eşik 0.18 + domain-gate): | ||
| 82 | + | ||
| 83 | +| Metrik | Değer | Anlamı | | ||
| 84 | +|---|---|---| | ||
| 85 | +| **Macro-F1** | **0.86** | Başlık metriği; her intent'e eşit ağırlık (nadir intent'leri saklamaz) | | ||
| 86 | +| Accuracy | %86 | Genel doğruluk (dengesizlikte yanıltıcı olabilir) | | ||
| 87 | +| Top-1 / Top-3 | %86 / %95 | Doğru cevap ilk 1 / ilk 3 tahminde | | ||
| 88 | +| Coverage | %100 | FALLBACK yerine cevap verilen in-scope oranı | | ||
| 89 | +| Accuracy-on-covered | %86 | Cevap verince doğruluk | | ||
| 90 | +| OOS recall | %78 | Kapsam dışını doğru reddetme | | ||
| 91 | +| Latency p50/p95 | ~0.8 / 1.3 ms | Sorgu başına gecikme | | ||
| 92 | + | ||
| 93 | +**Neden bu metrikler:** Macro-F1 dengesiz sınıfta kritik-ama-nadir intent'lerin | ||
| 94 | +(gizlilik, şifre) bozukluğunu saklamaz. Coverage/OOS-recall, FALLBACK'in | ||
| 95 | +getirdiği "cevap verme cesareti" dengesini ölçer. Güvenlik için `privacy_security` | ||
| 96 | +recall'ı ve auth sızıntısı ayrıca izlenir (regresyon testinde sabitlenmiştir). | ||
| 97 | + | ||
| 98 | +## Testler | ||
| 99 | + | ||
| 100 | +```bash | ||
| 101 | +python -m unittest discover -s tests -t . | ||
| 102 | +``` | ||
| 103 | +- `tests/unit/` — her modül/metot için birim testler | ||
| 104 | +- `tests/integration/` — kural/karar/motor + benchmark değerlendirmesi | ||
| 105 | +- `tests/e2e/` — uçtan uca sohbet senaryoları | ||
| 106 | +- `tests/integration/test_regression.py` — kalite eşikleri (macro-F1 ≥ 0.80, | ||
| 107 | + OOS recall ≥ 0.70, gizlilik recall = 1.0, kural precision = 1.0) düşerse kırılır. | ||
| 108 | + | ||
| 109 | +## Yeni intent ekleme | ||
| 110 | + | ||
| 111 | +1. `src/catalog.py` içine `INTENTS`'e kayıt ekle (tüm zorunlu alanlar + `min_role`). | ||
| 112 | +2. `data/benchmark.jsonl`'e o intent için birkaç (örneklerden farklı) soru ekle. | ||
| 113 | +3. Çok belirgin bir anahtar kelimesi varsa `src/rules.py`'a kural ekle. | ||
| 114 | +4. `python -m src.main --validate && python -m src.main --evaluate` ile öncesi/ | ||
| 115 | + sonrası karşılaştır; `python -m unittest discover -s tests -t .` yeşil olmalı. | ||
| 116 | + | ||
| 117 | +## Bilinen sınırlar / sıradaki adım | ||
| 118 | +- OOS'ta ~%22 (alan fiili paylaşan sorular) hâlâ kaçıyor — char n-gram tavanı. | ||
| 119 | + Benzerlik arayüzü soyut (`SimilarityMatcher`); **yerel embedding** modeli aynı | ||
| 120 | + sözleşmeyle takılıp bu boşluğu kapatabilir. | ||
data/benchmark.jsonladded+147 -0
| @@ -0,0 +1,147 @@ | |||
| 1 | +{"question": "Selamlar", "expected_intent": "greeting", "role": "ziyaretci"} | ||
| 2 | +{"question": "Naber", "expected_intent": "greeting", "role": "ziyaretci"} | ||
| 3 | +{"question": "Merhaba asistan", "expected_intent": "greeting", "role": "ziyaretci"} | ||
| 4 | +{"question": "Sen ne yapabiliyorsun tam olarak?", "expected_intent": "help_capabilities", "role": "ziyaretci"} | ||
| 5 | +{"question": "Yardım menün var mı?", "expected_intent": "help_capabilities", "role": "ziyaretci"} | ||
| 6 | +{"question": "Hangi işlerde bana destek olursun?", "expected_intent": "help_capabilities", "role": "ziyaretci"} | ||
| 7 | +{"question": "Uygulamanın kendi kılavuzu nerede?", "expected_intent": "guide_info", "role": "ogrenci"} | ||
| 8 | +{"question": "Adım adım tanıtım var mı?", "expected_intent": "guide_info", "role": "ogrenci"} | ||
| 9 | +{"question": "Guide bölümü ne işe yarar?", "expected_intent": "guide_info", "role": "ogrenci"} | ||
| 10 | +{"question": "Hesabıma giriş yapmak için ne yapmalıyım?", "expected_intent": "login_how", "role": "ziyaretci"} | ||
| 11 | +{"question": "Kullanıcı adı ve şifreyle nereden girerim?", "expected_intent": "login_how", "role": "ziyaretci"} | ||
| 12 | +{"question": "Log in ekranına nasıl gelirim?", "expected_intent": "login_how", "role": "ziyaretci"} | ||
| 13 | +{"question": "Sisteme yeni üye olmak istiyorum ne yapmalıyım?", "expected_intent": "register_how", "role": "ziyaretci"} | ||
| 14 | +{"question": "Öğrenci hesabı nasıl açarım?", "expected_intent": "register_how", "role": "ziyaretci"} | ||
| 15 | +{"question": "Kayıt formu nerede?", "expected_intent": "register_how", "role": "ziyaretci"} | ||
| 16 | +{"question": "Güvenli çıkış nasıl yapılır?", "expected_intent": "logout_how", "role": "ogrenci"} | ||
| 17 | +{"question": "Oturumu kapatmak istiyorum", "expected_intent": "logout_how", "role": "ogrenci"} | ||
| 18 | +{"question": "Sistemden nasıl çıkarım?", "expected_intent": "logout_how", "role": "ogrenci"} | ||
| 19 | +{"question": "Beni ne zaman sistemden atar?", "expected_intent": "session_info", "role": "ogrenci"} | ||
| 20 | +{"question": "Girişim kaç gün geçerli?", "expected_intent": "session_info", "role": "ogrenci"} | ||
| 21 | +{"question": "Oturumum sürekli açık mı kalıyor?", "expected_intent": "session_info", "role": "ogrenci"} | ||
| 22 | +{"question": "Parolamı hatırlamıyorum ne yapayım?", "expected_intent": "account_access_problem", "role": "ziyaretci"} | ||
| 23 | +{"question": "Şifrem yanlış diyor giremiyorum", "expected_intent": "account_access_problem", "role": "ziyaretci"} | ||
| 24 | +{"question": "Hesabıma erişemiyorum yardım eder misin?", "expected_intent": "account_access_problem", "role": "ziyaretci"} | ||
| 25 | +{"question": "İletişim bilgilerimi nasıl değiştiririm?", "expected_intent": "profile_edit", "role": "ogrenci"} | ||
| 26 | +{"question": "Adımı soyadımı nereden güncellerim?", "expected_intent": "profile_edit", "role": "ogrenci"} | ||
| 27 | +{"question": "Kayıtlı telefonumu değiştirmek istiyorum", "expected_intent": "profile_edit", "role": "ogrenci"} | ||
| 28 | +{"question": "Uygulamayı koyu temaya nasıl alırım?", "expected_intent": "language_theme", "role": "ziyaretci"} | ||
| 29 | +{"question": "İngilizce arayüze geçmek istiyorum", "expected_intent": "language_theme", "role": "ziyaretci"} | ||
| 30 | +{"question": "Görünümü açık/koyu değiştirebilir miyim?", "expected_intent": "language_theme", "role": "ziyaretci"} | ||
| 31 | +{"question": "Yönetici ne yapabilir öğretmen ne yapamaz?", "expected_intent": "roles_permissions", "role": "ogrenci"} | ||
| 32 | +{"question": "Rol kademeleri nedir?", "expected_intent": "roles_permissions", "role": "ogrenci"} | ||
| 33 | +{"question": "Yetki seviyeleri nasıl işliyor?", "expected_intent": "roles_permissions", "role": "ogrenci"} | ||
| 34 | +{"question": "Neden sürekli ana sayfaya atılıyorum?", "expected_intent": "access_denied_help", "role": "ogrenci"} | ||
| 35 | +{"question": "Erişimin yok uyarısı alıyorum", "expected_intent": "access_denied_help", "role": "ogrenci"} | ||
| 36 | +{"question": "Bir sayfayı açamıyorum yetki mi lazım?", "expected_intent": "access_denied_help", "role": "ogrenci"} | ||
| 37 | +{"question": "Aradığım bölümü menüde bulamıyorum", "expected_intent": "navigation_help", "role": "ogrenci"} | ||
| 38 | +{"question": "Sayfalar arasında nasıl geçiş yaparım?", "expected_intent": "navigation_help", "role": "ogrenci"} | ||
| 39 | +{"question": "Mobilde menü nerede duruyor?", "expected_intent": "navigation_help", "role": "ogrenci"} | ||
| 40 | +{"question": "Hangi derslere kayıtlıyım nereden bakarım?", "expected_intent": "course_view", "role": "ogrenci"} | ||
| 41 | +{"question": "Ders detay sayfasına nasıl giderim?", "expected_intent": "course_view", "role": "ogrenci"} | ||
| 42 | +{"question": "Dersleri döneme göre süzebilir miyim?", "expected_intent": "course_view", "role": "ogrenci"} | ||
| 43 | +{"question": "Öğretmen olarak yeni bir ders açmak istiyorum", "expected_intent": "course_create", "role": "ogretmen"} | ||
| 44 | +{"question": "Ders ekleme düğmesi nerede?", "expected_intent": "course_create", "role": "ogretmen"} | ||
| 45 | +{"question": "Bir sınıf oluşturmak istiyorum nasıl yaparım?", "expected_intent": "course_create", "role": "ogretmen"} | ||
| 46 | +{"question": "Bir öğrenciyi dersime nasıl eklerim?", "expected_intent": "course_enroll_student", "role": "ogretmen"} | ||
| 47 | +{"question": "Sınıf listeme öğrenci almak istiyorum", "expected_intent": "course_enroll_student", "role": "ogretmen"} | ||
| 48 | +{"question": "Derse kayıt yapma işlemi nasıl?", "expected_intent": "course_enroll_student", "role": "ogretmen"} | ||
| 49 | +{"question": "Yanlışlıkla eklediğim öğrenciyi dersten çıkarayım", "expected_intent": "course_remove_student", "role": "ogretmen"} | ||
| 50 | +{"question": "Sınıf listesinden birini silmek istiyorum", "expected_intent": "course_remove_student", "role": "ogretmen"} | ||
| 51 | +{"question": "Öğrenci kaydını iptal etmek istiyorum", "expected_intent": "course_remove_student", "role": "ogretmen"} | ||
| 52 | +{"question": "Derse yeni bir ders saati eklemek istiyorum", "expected_intent": "lesson_session_add", "role": "ogretmen"} | ||
| 53 | +{"question": "Oturum oluşturmak nasıl yapılır?", "expected_intent": "lesson_session_add", "role": "ogretmen"} | ||
| 54 | +{"question": "Ders için bir saat planlamak istiyorum", "expected_intent": "lesson_session_add", "role": "ogretmen"} | ||
| 55 | +{"question": "Ders saatinde öğrencileri nasıl var yok yaparım?", "expected_intent": "roll_call", "role": "ogretmen"} | ||
| 56 | +{"question": "Oturumda yoklama almak istiyorum", "expected_intent": "roll_call", "role": "ogretmen"} | ||
| 57 | +{"question": "Devam kontrolü nasıl kaydedilir?", "expected_intent": "roll_call", "role": "ogretmen"} | ||
| 58 | +{"question": "Asenkron sınav ne anlama geliyor?", "expected_intent": "exam_modes_info", "role": "ogrenci"} | ||
| 59 | +{"question": "Sınav modları arasında ne fark var?", "expected_intent": "exam_modes_info", "role": "ogrenci"} | ||
| 60 | +{"question": "Açık mod sürekli mi açık kalıyor?", "expected_intent": "exam_modes_info", "role": "ogrenci"} | ||
| 61 | +{"question": "Dersime sınav eklemek istiyorum", "expected_intent": "exam_create", "role": "ogretmen"} | ||
| 62 | +{"question": "Yeni bir yazılı oluşturacağım", "expected_intent": "exam_create", "role": "ogretmen"} | ||
| 63 | +{"question": "Sınav hazırlama adımları neler?", "expected_intent": "exam_create", "role": "ogretmen"} | ||
| 64 | +{"question": "Sınavıma çoktan seçmeli soru koymak istiyorum", "expected_intent": "exam_add_question", "role": "ogretmen"} | ||
| 65 | +{"question": "Soru ekleme nasıl yapılır?", "expected_intent": "exam_add_question", "role": "ogretmen"} | ||
| 66 | +{"question": "Sınava açık uçlu soru nasıl eklerim?", "expected_intent": "exam_add_question", "role": "ogretmen"} | ||
| 67 | +{"question": "Öğrenci olarak sınava nasıl başlarım?", "expected_intent": "exam_enter_room", "role": "ogrenci"} | ||
| 68 | +{"question": "Online sınav odasına nasıl girerim?", "expected_intent": "exam_enter_room", "role": "ogrenci"} | ||
| 69 | +{"question": "Sınavımı nereden başlatabilirim?", "expected_intent": "exam_enter_room", "role": "ogrenci"} | ||
| 70 | +{"question": "Verdiğim cevabı nasıl kaydederim?", "expected_intent": "exam_save_answer", "role": "ogrenci"} | ||
| 71 | +{"question": "Cevaplar tek tek mi kaydediliyor?", "expected_intent": "exam_save_answer", "role": "ogrenci"} | ||
| 72 | +{"question": "Bir soruyu işaretledim sonra ne yapmalıyım?", "expected_intent": "exam_save_answer", "role": "ogrenci"} | ||
| 73 | +{"question": "Sınavı tamamlayıp teslim etmek istiyorum", "expected_intent": "exam_finish_result", "role": "ogrenci"} | ||
| 74 | +{"question": "Notumu sınavdan sonra nereden görürüm?", "expected_intent": "exam_finish_result", "role": "ogrenci"} | ||
| 75 | +{"question": "Sınavı bitirince ne oluyor?", "expected_intent": "exam_finish_result", "role": "ogrenci"} | ||
| 76 | +{"question": "Yanlışlıkla sınavdan çıktım geri girebilir miyim?", "expected_intent": "exam_rejoin_retake", "role": "ogrenci"} | ||
| 77 | +{"question": "Sınava ikinci kez girme hakkım var mı?", "expected_intent": "exam_rejoin_retake", "role": "ogrenci"} | ||
| 78 | +{"question": "Kaldığım sorudan devam edebilir miyim?", "expected_intent": "exam_rejoin_retake", "role": "ogrenci"} | ||
| 79 | +{"question": "Öğretmen olarak sınavı nasıl puanlarım?", "expected_intent": "exam_grade_student", "role": "ogretmen"} | ||
| 80 | +{"question": "Öğrenci notlarını girmek istiyorum", "expected_intent": "exam_grade_student", "role": "ogretmen"} | ||
| 81 | +{"question": "Notlandırma neden şu an kapalı?", "expected_intent": "exam_grade_student", "role": "ogretmen"} | ||
| 82 | +{"question": "Sınav sırasında öğrencileri anlık takip edebilir miyim?", "expected_intent": "exam_live_monitor", "role": "ogretmen"} | ||
| 83 | +{"question": "Kimin başladığını canlı görmek istiyorum", "expected_intent": "exam_live_monitor", "role": "ogretmen"} | ||
| 84 | +{"question": "Canlı izleme ekranı nerede?", "expected_intent": "exam_live_monitor", "role": "ogretmen"} | ||
| 85 | +{"question": "Karnemi ve harf notlarımı görmek istiyorum", "expected_intent": "report_card_view", "role": "ogrenci"} | ||
| 86 | +{"question": "Bütün ders notlarım nerede listeleniyor?", "expected_intent": "report_card_view", "role": "ogrenci"} | ||
| 87 | +{"question": "Genel ortalamama nereden bakarım?", "expected_intent": "report_card_view", "role": "ogrenci"} | ||
| 88 | +{"question": "Ders ortalamam nasıl hesaplanıyor?", "expected_intent": "weighted_average_info", "role": "ogrenci"} | ||
| 89 | +{"question": "Sınav ağırlıkları nota nasıl yansıyor?", "expected_intent": "weighted_average_info", "role": "ogrenci"} | ||
| 90 | +{"question": "Ortalamaya girmeyen notlar oluyor mu?", "expected_intent": "weighted_average_info", "role": "ogrenci"} | ||
| 91 | +{"question": "Öğretmen olarak bir öğrencinin karnesini görmek istiyorum", "expected_intent": "student_marks_lookup", "role": "ogretmen"} | ||
| 92 | +{"question": "Öğrenci notu sorgulama sayfası nerede?", "expected_intent": "student_marks_lookup", "role": "ogretmen"} | ||
| 93 | +{"question": "Belirli bir öğrencinin notlarına bakmak istiyorum", "expected_intent": "student_marks_lookup", "role": "ogretmen"} | ||
| 94 | +{"question": "Kendi devamsızlık durumumu görmek istiyorum", "expected_intent": "attendance_view", "role": "ogrenci"} | ||
| 95 | +{"question": "Devam yüzdemi nereden görürüm?", "expected_intent": "attendance_view", "role": "ogrenci"} | ||
| 96 | +{"question": "Yoklama geçmişime bakmak istiyorum", "expected_intent": "attendance_view", "role": "ogrenci"} | ||
| 97 | +{"question": "Mazeretli sayılırsam oranım etkilenir mi?", "expected_intent": "attendance_rate_info", "role": "ogrenci"} | ||
| 98 | +{"question": "Devam oranı formülü nedir?", "expected_intent": "attendance_rate_info", "role": "ogrenci"} | ||
| 99 | +{"question": "Geç kalma devamsızlığa mı yazılır?", "expected_intent": "attendance_rate_info", "role": "ogrenci"} | ||
| 100 | +{"question": "Etkinliğe katıldığımı nasıl bildiririm?", "expected_intent": "event_attendance_mark", "role": "ogrenci"} | ||
| 101 | +{"question": "Kendi etkinlik yoklamamı işaretlemek istiyorum", "expected_intent": "event_attendance_mark", "role": "ogrenci"} | ||
| 102 | +{"question": "Bir etkinlikte var demek istiyorum", "expected_intent": "event_attendance_mark", "role": "ogrenci"} | ||
| 103 | +{"question": "Öğretmen olarak öğrencinin devamsızlığını sorgulamak istiyorum", "expected_intent": "student_attendance_lookup", "role": "ogretmen"} | ||
| 104 | +{"question": "Bir öğrencinin yoklama raporu nerede?", "expected_intent": "student_attendance_lookup", "role": "ogretmen"} | ||
| 105 | +{"question": "Öğrenci devam durumu görüntüleme sayfası", "expected_intent": "student_attendance_lookup", "role": "ogretmen"} | ||
| 106 | +{"question": "Yeni bir etkinlik planlamak istiyorum", "expected_intent": "event_create", "role": "ogretmen"} | ||
| 107 | +{"question": "Etkinlik ekleme nasıl yapılır?", "expected_intent": "event_create", "role": "ogretmen"} | ||
| 108 | +{"question": "Bir toplantı etkinliği oluşturacağım", "expected_intent": "event_create", "role": "ogretmen"} | ||
| 109 | +{"question": "Kişisel not almak istiyorum nasıl?", "expected_intent": "note_create", "role": "ogrenci"} | ||
| 110 | +{"question": "Deftere dosya ekli not eklemek istiyorum", "expected_intent": "note_create", "role": "ogrenci"} | ||
| 111 | +{"question": "Yeni not oluşturma nerede?", "expected_intent": "note_create", "role": "ogrenci"} | ||
| 112 | +{"question": "Mesaiye giriş kaydı nasıl açarım?", "expected_intent": "work_checkin_out", "role": "ogretmen"} | ||
| 113 | +{"question": "İşe geldiğimi nasıl damgalarım?", "expected_intent": "work_checkin_out", "role": "ogretmen"} | ||
| 114 | +{"question": "Çıkış saatimi nasıl kaydederim?", "expected_intent": "work_checkin_out", "role": "ogretmen"} | ||
| 115 | +{"question": "Yönetici olarak bir öğretmenin mesaisini düzeltmek istiyorum", "expected_intent": "staff_work_manage", "role": "yonetici"} | ||
| 116 | +{"question": "Personel mesai kayıtlarını nereden yönetirim?", "expected_intent": "staff_work_manage", "role": "yonetici"} | ||
| 117 | +{"question": "Kapalı bir mesai kaydını düzenlemek istiyorum", "expected_intent": "staff_work_manage", "role": "yonetici"} | ||
| 118 | +{"question": "Yeni akademik dönem eklemek istiyorum", "expected_intent": "term_manage", "role": "yonetici"} | ||
| 119 | +{"question": "Dersi bir yarıyıla nasıl bağlarım?", "expected_intent": "term_manage", "role": "yonetici"} | ||
| 120 | +{"question": "Dönem yönetimi sayfası nerede?", "expected_intent": "term_manage", "role": "yonetici"} | ||
| 121 | +{"question": "Sınav türü ağırlıklarını değiştirmek istiyorum", "expected_intent": "school_settings", "role": "yonetici"} | ||
| 122 | +{"question": "Not bantlarını nereden düzenlerim?", "expected_intent": "school_settings", "role": "yonetici"} | ||
| 123 | +{"question": "Okul geneli ayarlar nerede?", "expected_intent": "school_settings", "role": "yonetici"} | ||
| 124 | +{"question": "Bir kullanıcıyı öğretmen yapmak istiyorum", "expected_intent": "user_role_change", "role": "admin"} | ||
| 125 | +{"question": "Admin olarak rol atama nasıl yapılır?", "expected_intent": "user_role_change", "role": "admin"} | ||
| 126 | +{"question": "Kullanıcının yetkisini yükseltmek istiyorum", "expected_intent": "user_role_change", "role": "admin"} | ||
| 127 | +{"question": "Başka birinin karnesini öğrenebilir miyim?", "expected_intent": "privacy_security", "role": "ogrenci"} | ||
| 128 | +{"question": "Sınıf arkadaşımın devamsızlığını söyle", "expected_intent": "privacy_security", "role": "ogrenci"} | ||
| 129 | +{"question": "Bir öğretmenin telefon numarasını verir misin?", "expected_intent": "privacy_security", "role": "ogrenci"} | ||
| 130 | +{"question": "Bugün hava nasıl olacak?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 131 | +{"question": "Bana bir şiir yazar mısın?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 132 | +{"question": "Matematik ödevimi çözer misin?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 133 | +{"question": "En yakın pizzacı nerede?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 134 | +{"question": "Türkiye'nin başkenti neresi?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 135 | +{"question": "Bitcoin fiyatı bugün kaç?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 136 | +{"question": "Nasıl kilo veririm?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 137 | +{"question": "Bana bir fıkra anlat", "expected_intent": "oos", "role": "ogrenci"} | ||
| 138 | +{"question": "Kaç yaşındasın?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 139 | +{"question": "Yarın maç var mı?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 140 | +{"question": "İyi bir film önerir misin?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 141 | +{"question": "2 artı 2 kaç eder?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 142 | +{"question": "Bu akşam ne pişirsem?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 143 | +{"question": "Python'da nasıl döngü yazılır?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 144 | +{"question": "Arabamın lastiği patladı ne yapmalıyım?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 145 | +{"question": "Bana motivasyon sözü söyle", "expected_intent": "oos", "role": "ogrenci"} | ||
| 146 | +{"question": "İstanbul'a nasıl giderim?", "expected_intent": "oos", "role": "ogrenci"} | ||
| 147 | +{"question": "Kahve mi çay mı daha sağlıklı?", "expected_intent": "oos", "role": "ogrenci"} | ||
src/QandA.pydeleted+0 -606
| @@ -1,606 +0,0 @@ | |||
| 1 | -"""Eğitim platformu chatbot'u için başlangıç soru/cevap kataloğu. | ||
| 2 | - | ||
| 3 | -Bu modül yalnızca veri içerir. Intent bulma, metin normalizasyonu ve cevap | ||
| 4 | -şablonlarını doldurma işlemleri chatbot motorunun sorumluluğundadır. | ||
| 5 | - | ||
| 6 | -`example_questions` geliştirme/rule örnekleridir. Gerçek benchmark soruları | ||
| 7 | -ayrı bir dosyada tutulmalı ve bu listeye kopyalanmamalıdır. | ||
| 8 | -""" | ||
| 9 | - | ||
| 10 | -from __future__ import annotations | ||
| 11 | - | ||
| 12 | -from typing import Any, Final | ||
| 13 | - | ||
| 14 | - | ||
| 15 | -# Gerçek uygulamada bu bilgiler oturum açmış kullanıcıya göre API'den gelir. | ||
| 16 | -MOCK_STUDENT: Final[dict[str, Any]] = { | ||
| 17 | - "student_id": "STU-2026-001", | ||
| 18 | - "first_name": "Deniz", | ||
| 19 | - "last_name": "Yılmaz", | ||
| 20 | - "student_number": "1042", | ||
| 21 | - "school": "Örnek Anadolu Lisesi", | ||
| 22 | - "class_name": "10-A", | ||
| 23 | - "academic_year": "2025-2026", | ||
| 24 | - "term": "2. dönem", | ||
| 25 | - "advisor_teacher": "Ayşe Demir", | ||
| 26 | - "grades": { | ||
| 27 | - "Matematik": [85, 90], | ||
| 28 | - "Türk Dili ve Edebiyatı": [78, 82], | ||
| 29 | - "Fizik": [74, 80], | ||
| 30 | - "Kimya": [88, 84], | ||
| 31 | - "İngilizce": [92, 95], | ||
| 32 | - }, | ||
| 33 | - "grade_average": 84.8, | ||
| 34 | - "attendance": { | ||
| 35 | - "excused_days": 2, | ||
| 36 | - "unexcused_days": 1, | ||
| 37 | - "late_count": 3, | ||
| 38 | - }, | ||
| 39 | - "today_schedule": [ | ||
| 40 | - "Matematik", | ||
| 41 | - "Matematik", | ||
| 42 | - "Türk Dili ve Edebiyatı", | ||
| 43 | - "Fizik", | ||
| 44 | - "İngilizce", | ||
| 45 | - "Beden Eğitimi", | ||
| 46 | - ], | ||
| 47 | - "tomorrow_schedule": [ | ||
| 48 | - "Kimya", | ||
| 49 | - "Biyoloji", | ||
| 50 | - "Tarih", | ||
| 51 | - "Matematik", | ||
| 52 | - "İngilizce", | ||
| 53 | - "Görsel Sanatlar", | ||
| 54 | - ], | ||
| 55 | - "upcoming_exams": [ | ||
| 56 | - {"course": "Matematik", "date": "20 Mayıs 2026", "time": "10:00"}, | ||
| 57 | - {"course": "Fizik", "date": "23 Mayıs 2026", "time": "11:00"}, | ||
| 58 | - ], | ||
| 59 | - "active_homework": [ | ||
| 60 | - { | ||
| 61 | - "course": "Türk Dili ve Edebiyatı", | ||
| 62 | - "title": "Roman incelemesi", | ||
| 63 | - "due_date": "18 Mayıs 2026", | ||
| 64 | - }, | ||
| 65 | - { | ||
| 66 | - "course": "Matematik", | ||
| 67 | - "title": "İkinci derece denklemler testi", | ||
| 68 | - "due_date": "19 Mayıs 2026", | ||
| 69 | - }, | ||
| 70 | - ], | ||
| 71 | - "announcements": [ | ||
| 72 | - "Bilim fuarı başvuruları 22 Mayıs'a kadar devam ediyor.", | ||
| 73 | - "Veli toplantısı 30 Mayıs Cumartesi günü yapılacaktır.", | ||
| 74 | - ], | ||
| 75 | -} | ||
| 76 | - | ||
| 77 | - | ||
| 78 | -# Alan açıklamaları: | ||
| 79 | -# - intent: Motorun döndüreceği benzersiz sınıf adı. | ||
| 80 | -# - response_id: Testlerde cevap metni yerine karşılaştırılacak kararlı kimlik. | ||
| 81 | -# - response_template: MOCK_STUDENT alanlarıyla doldurulabilecek cevap. | ||
| 82 | -# - auth_required: Kişisel veri göstermek için oturum gerekip gerekmediği. | ||
| 83 | -# - example_questions: Kural geliştirme örnekleri; benchmark değildir. | ||
| 84 | -# - must_not_match: Bu intent ile sık karışabilecek intentler. | ||
| 85 | -INTENTS: Final[list[dict[str, Any]]] = [ | ||
| 86 | - { | ||
| 87 | - "intent": "greeting", | ||
| 88 | - "category": "general", | ||
| 89 | - "description": "Kullanıcının sohbeti başlatması veya selam vermesi.", | ||
| 90 | - "response_id": "welcome_message", | ||
| 91 | - "response_template": ( | ||
| 92 | - "Merhaba! Notlar, devamsızlık, ders programı, sınavlar, ödevler " | ||
| 93 | - "ve okul duyuruları hakkında yardımcı olabilirim." | ||
| 94 | - ), | ||
| 95 | - "auth_required": False, | ||
| 96 | - "example_questions": [ | ||
| 97 | - "Merhaba", | ||
| 98 | - "Selam", | ||
| 99 | - "Günaydın", | ||
| 100 | - "İyi günler", | ||
| 101 | - "Hey", | ||
| 102 | - "Selam bot", | ||
| 103 | - "Merhabalar", | ||
| 104 | - "Nasılsın?", | ||
| 105 | - ], | ||
| 106 | - "must_not_match": [], | ||
| 107 | - }, | ||
| 108 | - { | ||
| 109 | - "intent": "help", | ||
| 110 | - "category": "general", | ||
| 111 | - "description": "Chatbotun neler yapabildiğinin sorulması.", | ||
| 112 | - "response_id": "capabilities", | ||
| 113 | - "response_template": ( | ||
| 114 | - "Notlarını ve ortalamanı gösterebilir; devamsızlık, ders programı, " | ||
| 115 | - "yaklaşan sınavlar, ödevler ve duyurular hakkında bilgi verebilirim." | ||
| 116 | - ), | ||
| 117 | - "auth_required": False, | ||
| 118 | - "example_questions": [ | ||
| 119 | - "Neler yapabilirsin?", | ||
| 120 | - "Bana nasıl yardımcı olabilirsin?", | ||
| 121 | - "Yardım", | ||
| 122 | - "Hangi soruları sorabilirim?", | ||
| 123 | - "Ne işe yarıyorsun?", | ||
| 124 | - "Komutları göster", | ||
| 125 | - "Özelliklerin neler?", | ||
| 126 | - "Senden ne öğrenebilirim?", | ||
| 127 | - ], | ||
| 128 | - "must_not_match": [], | ||
| 129 | - }, | ||
| 130 | - { | ||
| 131 | - "intent": "student_profile", | ||
| 132 | - "category": "student", | ||
| 133 | - "description": "Öğrencinin okul, sınıf veya numara bilgisini istemesi.", | ||
| 134 | - "response_id": "student_profile_summary", | ||
| 135 | - "response_template": ( | ||
| 136 | - "{first_name} {last_name}, {school} {class_name} sınıfındasın. " | ||
| 137 | - "Öğrenci numaran {student_number}." | ||
| 138 | - ), | ||
| 139 | - "auth_required": True, | ||
| 140 | - "example_questions": [ | ||
| 141 | - "Öğrenci bilgilerimi göster", | ||
| 142 | - "Hangi sınıftayım?", | ||
| 143 | - "Okul numaram ne?", | ||
| 144 | - "Numaramı unuttum", | ||
| 145 | - "Profilimi göster", | ||
| 146 | - "Hangi okulda kayıtlıyım?", | ||
| 147 | - "Sınıfım neydi?", | ||
| 148 | - "Kayıt bilgilerim neler?", | ||
| 149 | - ], | ||
| 150 | - "must_not_match": ["advisor_teacher"], | ||
| 151 | - }, | ||
| 152 | - { | ||
| 153 | - "intent": "course_grades", | ||
| 154 | - "category": "grades", | ||
| 155 | - "description": "Bir dersin veya tüm derslerin notlarını istemesi.", | ||
| 156 | - "response_id": "course_grades_list", | ||
| 157 | - "response_template": "Güncel ders notların: {grades}.", | ||
| 158 | - "auth_required": True, | ||
| 159 | - "entities": ["course"], | ||
| 160 | - "example_questions": [ | ||
| 161 | - "Notlarımı göster", | ||
| 162 | - "Sınav sonuçlarım açıklandı mı?", | ||
| 163 | - "Matematikten kaç aldım?", | ||
| 164 | - "Fizik notum ne?", | ||
| 165 | - "Yazılı notlarımı öğrenebilir miyim?", | ||
| 166 | - "İngilizce sınav sonucumu göster", | ||
| 167 | - "Bu dönemki notlarım nasıl?", | ||
| 168 | - "Ders notlarım kaç?", | ||
| 169 | - "Son sınavdan kaç almışım?", | ||
| 170 | - "Kimya yazılım kaç geldi?", | ||
| 171 | - ], | ||
| 172 | - "must_not_match": ["grade_average", "upcoming_exams"], | ||
| 173 | - }, | ||
| 174 | - { | ||
| 175 | - "intent": "grade_average", | ||
| 176 | - "category": "grades", | ||
| 177 | - "description": "Dönem veya genel not ortalamasını istemesi.", | ||
| 178 | - "response_id": "grade_average_value", | ||
| 179 | - "response_template": "{term} not ortalaman {grade_average}.", | ||
| 180 | - "auth_required": True, | ||
| 181 | - "example_questions": [ | ||
| 182 | - "Ortalamam kaç?", | ||
| 183 | - "Not ortalamamı göster", | ||
| 184 | - "Dönem ortalamam ne?", | ||
| 185 | - "Genel ortalamam kaç oldu?", | ||
| 186 | - "Ortalama kaç geliyor?", | ||
| 187 | - "Başarı puanım nedir?", | ||
| 188 | - "Bu dönemki ortalamamı merak ediyorum", | ||
| 189 | - "Derslerimin ortalaması kaç?", | ||
| 190 | - ], | ||
| 191 | - "must_not_match": ["course_grades"], | ||
| 192 | - }, | ||
| 193 | - { | ||
| 194 | - "intent": "attendance_summary", | ||
| 195 | - "category": "attendance", | ||
| 196 | - "description": "Özürlü, özürsüz devamsızlık ve geç kalma bilgisini istemesi.", | ||
| 197 | - "response_id": "attendance_summary", | ||
| 198 | - "response_template": ( | ||
| 199 | - "{attendance[excused_days]} gün özürlü, " | ||
| 200 | - "{attendance[unexcused_days]} gün özürsüz devamsızlığın ve " | ||
| 201 | - "{attendance[late_count]} geç kalma kaydın bulunuyor." | ||
| 202 | - ), | ||
| 203 | - "auth_required": True, | ||
| 204 | - "example_questions": [ | ||
| 205 | - "Devamsızlığım kaç gün?", | ||
| 206 | - "Kaç gün okula gelmemişim?", | ||
| 207 | - "Özürsüz devamsızlığımı göster", | ||
| 208 | - "Devamsızlık bilgilerim neler?", | ||
| 209 | - "Kaç kere geç kaldım?", | ||
| 210 | - "Yok yazıldığım günleri göster", | ||
| 211 | - "Devamsızlık hakkım ne durumda?", | ||
| 212 | - "Bugün yok yazılmış mıyım?", | ||
| 213 | - "Raporlu günlerim sisteme girilmiş mi?", | ||
| 214 | - "Devamsızlığım var mı?", | ||
| 215 | - ], | ||
| 216 | - "must_not_match": ["leave_document_process"], | ||
| 217 | - }, | ||
| 218 | - { | ||
| 219 | - "intent": "today_schedule", | ||
| 220 | - "category": "schedule", | ||
| 221 | - "description": "Bugünün ders programını istemesi.", | ||
| 222 | - "response_id": "today_schedule_list", | ||
| 223 | - "response_template": "Bugünkü derslerin sırasıyla: {today_schedule}.", | ||
| 224 | - "auth_required": True, | ||
| 225 | - "example_questions": [ | ||
| 226 | - "Bugün hangi dersler var?", | ||
| 227 | - "Bugünkü programım ne?", | ||
| 228 | - "Bugün ilk ders ne?", | ||
| 229 | - "Ders programımı göster", | ||
| 230 | - "Bugünün derslerini sırala", | ||
| 231 | - "Bugün matematik var mı?", | ||
| 232 | - "Öğleden sonra hangi dersler var?", | ||
| 233 | - "Bugün son dersimiz ne?", | ||
| 234 | - ], | ||
| 235 | - "must_not_match": ["tomorrow_schedule", "weekly_schedule"], | ||
| 236 | - }, | ||
| 237 | - { | ||
| 238 | - "intent": "tomorrow_schedule", | ||
| 239 | - "category": "schedule", | ||
| 240 | - "description": "Yarının ders programını istemesi.", | ||
| 241 | - "response_id": "tomorrow_schedule_list", | ||
| 242 | - "response_template": "Yarınki derslerin sırasıyla: {tomorrow_schedule}.", | ||
| 243 | - "auth_required": True, | ||
| 244 | - "example_questions": [ | ||
| 245 | - "Yarın hangi dersler var?", | ||
| 246 | - "Yarının programını göster", | ||
| 247 | - "Yarın ilk ders ne?", | ||
| 248 | - "Yarın matematik var mı?", | ||
| 249 | - "Yarın hangi kitapları getireceğim?", | ||
| 250 | - "Yarınki derslerimi sırala", | ||
| 251 | - "Yarın son iki ders ne?", | ||
| 252 | - "Yarının ders programı nedir?", | ||
| 253 | - ], | ||
| 254 | - "must_not_match": ["today_schedule", "weekly_schedule"], | ||
| 255 | - }, | ||
| 256 | - { | ||
| 257 | - "intent": "weekly_schedule", | ||
| 258 | - "category": "schedule", | ||
| 259 | - "description": "Haftalık veya belirli bir günün ders programını istemesi.", | ||
| 260 | - "response_id": "weekly_schedule_link", | ||
| 261 | - "response_template": ( | ||
| 262 | - "Haftalık ders programına Dersler > Ders Programı bölümünden ulaşabilirsin." | ||
| 263 | - ), | ||
| 264 | - "auth_required": True, | ||
| 265 | - "entities": ["weekday"], | ||
| 266 | - "example_questions": [ | ||
| 267 | - "Haftalık ders programımı göster", | ||
| 268 | - "Pazartesi hangi dersler var?", | ||
| 269 | - "Cuma günü programım ne?", | ||
| 270 | - "Bu haftanın dersleri neler?", | ||
| 271 | - "Haftalık program nerede?", | ||
| 272 | - "Salı günü kaç dersim var?", | ||
| 273 | - "Çarşamba son ders ne?", | ||
| 274 | - "Perşembe beden eğitimi var mı?", | ||
| 275 | - ], | ||
| 276 | - "must_not_match": ["today_schedule", "tomorrow_schedule"], | ||
| 277 | - }, | ||
| 278 | - { | ||
| 279 | - "intent": "upcoming_exams", | ||
| 280 | - "category": "exams", | ||
| 281 | - "description": "Yaklaşan sınavların tarih ve saatlerini istemesi.", | ||
| 282 | - "response_id": "upcoming_exams_list", | ||
| 283 | - "response_template": "Yaklaşan sınavların: {upcoming_exams}.", | ||
| 284 | - "auth_required": True, | ||
| 285 | - "entities": ["course", "date_range"], | ||
| 286 | - "example_questions": [ | ||
| 287 | - "Yaklaşan sınavlarım neler?", | ||
| 288 | - "Sınavlar ne zaman?", | ||
| 289 | - "Matematik sınavı hangi gün?", | ||
| 290 | - "Bu hafta sınav var mı?", | ||
| 291 | - "Bir sonraki sınavım hangisi?", | ||
| 292 | - "Sınav takvimimi göster", | ||
| 293 | - "Yarın sınavım var mı?", | ||
| 294 | - "Fizik yazılısı saat kaçta?", | ||
| 295 | - "Mayıs ayındaki sınavlarım neler?", | ||
| 296 | - "En yakın yazılı ne zaman?", | ||
| 297 | - ], | ||
| 298 | - "must_not_match": ["course_grades", "makeup_exam"], | ||
| 299 | - }, | ||
| 300 | - { | ||
| 301 | - "intent": "makeup_exam", | ||
| 302 | - "category": "exams", | ||
| 303 | - "description": "Kaçırılan sınav veya mazeret sınavı sürecini sorması.", | ||
| 304 | - "response_id": "makeup_exam_process", | ||
| 305 | - "response_template": ( | ||
| 306 | - "Mazeret sınavı için geçerli belgeni okul yönetimine teslim etmelisin. " | ||
| 307 | - "Kesin tarih, başvurun onaylandıktan sonra duyurulur." | ||
| 308 | - ), | ||
| 309 | - "auth_required": False, | ||
| 310 | - "example_questions": [ | ||
| 311 | - "Sınavı kaçırdım ne yapmalıyım?", | ||
| 312 | - "Mazeret sınavı ne zaman?", | ||
| 313 | - "Telafi sınavına nasıl girerim?", | ||
| 314 | - "Hasta olduğum için yazılıya giremedim", | ||
| 315 | - "Kaçırdığım sınavın telafisi var mı?", | ||
| 316 | - "Raporla sınava tekrar girebilir miyim?", | ||
| 317 | - "Mazeret sınavına nereden başvurulur?", | ||
| 318 | - "Sınava katılamadım", | ||
| 319 | - ], | ||
| 320 | - "must_not_match": ["upcoming_exams", "leave_document_process"], | ||
| 321 | - }, | ||
| 322 | - { | ||
| 323 | - "intent": "active_homework", | ||
| 324 | - "category": "homework", | ||
| 325 | - "description": "Aktif ödevleri ve teslim tarihlerini istemesi.", | ||
| 326 | - "response_id": "active_homework_list", | ||
| 327 | - "response_template": "Teslim edilmesi gereken ödevlerin: {active_homework}.", | ||
| 328 | - "auth_required": True, | ||
| 329 | - "entities": ["course"], | ||
| 330 | - "example_questions": [ | ||
| 331 | - "Ödevlerim neler?", | ||
| 332 | - "Yapmam gereken ödev var mı?", | ||
| 333 | - "Matematik ödevi neydi?", | ||
| 334 | - "Ödev teslim tarihi ne zaman?", | ||
| 335 | - "Bu haftaki ödevleri göster", | ||
| 336 | - "Yarın teslim edilecek ödev var mı?", | ||
| 337 | - "Edebiyat ödevinin konusu ne?", | ||
| 338 | - "Eksik ödevim var mı?", | ||
| 339 | - "Aktif görevlerimi göster", | ||
| 340 | - "Hangi ödevleri yapmadım?", | ||
| 341 | - ], | ||
| 342 | - "must_not_match": ["homework_submission"], | ||
| 343 | - }, | ||
| 344 | - { | ||
| 345 | - "intent": "homework_submission", | ||
| 346 | - "category": "homework", | ||
| 347 | - "description": "Ödev yükleme ve teslim etme yöntemini sorması.", | ||
| 348 | - "response_id": "homework_submission_instructions", | ||
| 349 | - "response_template": ( | ||
| 350 | - "Ödevini Ödevler > Aktif Ödevler bölümünden seçip 'Dosya Yükle' " | ||
| 351 | - "adımıyla teslim edebilirsin. Dosya türü ve boyut sınırını kontrol et." | ||
| 352 | - ), | ||
| 353 | - "auth_required": True, | ||
| 354 | - "example_questions": [ | ||
| 355 | - "Ödevimi nasıl yüklerim?", | ||
| 356 | - "Ödev nereden teslim ediliyor?", | ||
| 357 | - "Dosya yükleyemiyorum", | ||
| 358 | - "Ödevi sisteme nasıl atacağım?", | ||
| 359 | - "Teslim butonu nerede?", | ||
| 360 | - "Hangi dosya türlerini yükleyebilirim?", | ||
| 361 | - "Ödev yükleme sınırı kaç MB?", | ||
| 362 | - "Yanlış dosya yükledim, değiştirebilir miyim?", | ||
| 363 | - ], | ||
| 364 | - "must_not_match": ["active_homework", "technical_problem"], | ||
| 365 | - }, | ||
| 366 | - { | ||
| 367 | - "intent": "school_announcements", | ||
| 368 | - "category": "announcements", | ||
| 369 | - "description": "Okul veya sınıf duyurularını istemesi.", | ||
| 370 | - "response_id": "school_announcements_list", | ||
| 371 | - "response_template": "Güncel duyurular: {announcements}.", | ||
| 372 | - "auth_required": True, | ||
| 373 | - "example_questions": [ | ||
| 374 | - "Yeni duyuru var mı?", | ||
| 375 | - "Okul duyurularını göster", | ||
| 376 | - "Bugün bir açıklama yapıldı mı?", | ||
| 377 | - "Son duyuru ne?", | ||
| 378 | - "Sınıfımıza gelen duyurular neler?", | ||
| 379 | - "Veli toplantısı ne zaman?", | ||
| 380 | - "Bilim fuarı başvurusu ne zaman bitiyor?", | ||
| 381 | - "Önemli bir bildirim var mı?", | ||
| 382 | - ], | ||
| 383 | - "must_not_match": ["academic_calendar"], | ||
| 384 | - }, | ||
| 385 | - { | ||
| 386 | - "intent": "academic_calendar", | ||
| 387 | - "category": "calendar", | ||
| 388 | - "description": "Tatil, dönem başlangıcı veya karne tarihi gibi takvim bilgileri.", | ||
| 389 | - "response_id": "academic_calendar_info", | ||
| 390 | - "response_template": ( | ||
| 391 | - "Akademik takvime Takvim bölümünden ulaşabilirsin. Tarihler okul " | ||
| 392 | - "yönetiminin yayımladığı güncel takvime göre gösterilir." | ||
| 393 | - ), | ||
| 394 | - "auth_required": False, | ||
| 395 | - "entities": ["event_type"], | ||
| 396 | - "example_questions": [ | ||
| 397 | - "Okullar ne zaman kapanıyor?", | ||
| 398 | - "Karne günü ne zaman?", | ||
| 399 | - "Ara tatil hangi gün?", | ||
| 400 | - "Yaz tatili ne zaman başlıyor?", | ||
| 401 | - "İkinci dönem ne zaman bitecek?", | ||
| 402 | - "Resmî tatiller hangileri?", | ||
| 403 | - "Akademik takvimi göster", | ||
| 404 | - "Okul ne zaman açılacak?", | ||
| 405 | - ], | ||
| 406 | - "must_not_match": ["school_announcements", "upcoming_exams"], | ||
| 407 | - }, | ||
| 408 | - { | ||
| 409 | - "intent": "advisor_teacher", | ||
| 410 | - "category": "teachers", | ||
| 411 | - "description": "Sınıf rehber öğretmeni bilgisini istemesi.", | ||
| 412 | - "response_id": "advisor_teacher_name", | ||
| 413 | - "response_template": "Sınıf rehber öğretmenin {advisor_teacher}.", | ||
| 414 | - "auth_required": True, | ||
| 415 | - "example_questions": [ | ||
| 416 | - "Rehber öğretmenim kim?", | ||
| 417 | - "Sınıf öğretmenimizin adı ne?", | ||
| 418 | - "Danışman öğretmenim kim?", | ||
| 419 | - "Rehber hocam kimdi?", | ||
| 420 | - "Sınıf danışmanımı göster", | ||
| 421 | - "Hangi öğretmen sınıfımızdan sorumlu?", | ||
| 422 | - "Rehber öğretmenimin adını söyle", | ||
| 423 | - "Danışman hocama nasıl ulaşırım?", | ||
| 424 | - ], | ||
| 425 | - "must_not_match": ["student_profile", "teacher_contact"], | ||
| 426 | - }, | ||
| 427 | - { | ||
| 428 | - "intent": "teacher_contact", | ||
| 429 | - "category": "teachers", | ||
| 430 | - "description": "Öğretmene ulaşma veya mesaj gönderme yöntemini sorması.", | ||
| 431 | - "response_id": "teacher_contact_instructions", | ||
| 432 | - "response_template": ( | ||
| 433 | - "Öğretmenine Mesajlar > Yeni Mesaj bölümünden ulaşabilirsin. " | ||
| 434 | - "Kişisel telefon ve e-posta bilgileri paylaşılmaz." | ||
| 435 | - ), | ||
| 436 | - "auth_required": True, | ||
| 437 | - "entities": ["teacher", "course"], | ||
| 438 | - "example_questions": [ | ||
| 439 | - "Matematik öğretmenime nasıl ulaşırım?", | ||
| 440 | - "Öğretmenime mesaj göndermek istiyorum", | ||
| 441 | - "Hocanın telefon numarası ne?", | ||
| 442 | - "Ders öğretmenine nereden yazabilirim?", | ||
| 443 | - "Fizik hocasına soru soracağım", | ||
| 444 | - "Öğretmenimin e-postasını verir misin?", | ||
| 445 | - "Rehber öğretmenime mesaj atabilir miyim?", | ||
| 446 | - "Öğretmene ulaşma yolu nedir?", | ||
| 447 | - ], | ||
| 448 | - "must_not_match": ["advisor_teacher"], | ||
| 449 | - }, | ||
| 450 | - { | ||
| 451 | - "intent": "report_card_document", | ||
| 452 | - "category": "documents", | ||
| 453 | - "description": "Karne, transkript veya öğrenci belgesini istemesi.", | ||
| 454 | - "response_id": "student_document_instructions", | ||
| 455 | - "response_template": ( | ||
| 456 | - "Belgeler bölümünden karne ve not dökümünü görüntüleyebilirsin. " | ||
| 457 | - "Resmî öğrenci belgesi için okul yönetimine başvurmalısın." | ||
| 458 | - ), | ||
| 459 | - "auth_required": True, | ||
| 460 | - "entities": ["document_type"], | ||
| 461 | - "example_questions": [ | ||
| 462 | - "Karnemi nereden görebilirim?", | ||
| 463 | - "Öğrenci belgesi almak istiyorum", | ||
| 464 | - "Transkriptimi indir", | ||
| 465 | - "Not dökümü nerede?", | ||
| 466 | - "Karne PDF'ini nasıl alırım?", | ||
| 467 | - "Belge talebi oluşturabilir miyim?", | ||
| 468 | - "Eski karnelerimi göster", | ||
| 469 | - "Öğrenci belgesi nasıl çıkarılır?", | ||
| 470 | - ], | ||
| 471 | - "must_not_match": ["course_grades", "leave_document_process"], | ||
| 472 | - }, | ||
| 473 | - { | ||
| 474 | - "intent": "leave_document_process", | ||
| 475 | - "category": "attendance", | ||
| 476 | - "description": "Sağlık raporu veya devamsızlık mazeret belgesi süreci.", | ||
| 477 | - "response_id": "leave_document_instructions", | ||
| 478 | - "response_template": ( | ||
| 479 | - "Sağlık raporu veya mazeret belgesini okul yönetimine, okulun " | ||
| 480 | - "belirlediği süre içinde teslim etmelisin. Onay durumunu Devamsızlık " | ||
| 481 | - "bölümünden takip edebilirsin." | ||
| 482 | - ), | ||
| 483 | - "auth_required": False, | ||
| 484 | - "example_questions": [ | ||
| 485 | - "Raporumu nereye teslim edeceğim?", | ||
| 486 | - "Sağlık raporu sisteme nasıl girilir?", | ||
| 487 | - "Devamsızlık için mazeret belgesi vereceğim", | ||
| 488 | - "Raporlu günümü nasıl düzelttiririm?", | ||
| 489 | - "Hastane raporunu yükleyebilir miyim?", | ||
| 490 | - "Mazeret belgesi kaç gün içinde verilmeli?", | ||
| 491 | - "Yoklamama itiraz etmek istiyorum", | ||
| 492 | - "Devamsızlığım yanlış girilmiş", | ||
| 493 | - ], | ||
| 494 | - "must_not_match": ["attendance_summary", "makeup_exam"], | ||
| 495 | - }, | ||
| 496 | - { | ||
| 497 | - "intent": "password_reset", | ||
| 498 | - "category": "account", | ||
| 499 | - "description": "Şifresini unutan veya hesabına giremeyen kullanıcı.", | ||
| 500 | - "response_id": "password_reset_instructions", | ||
| 501 | - "response_template": ( | ||
| 502 | - "Giriş ekranındaki 'Şifremi Unuttum' bağlantısını kullan. Kayıtlı " | ||
| 503 | - "iletişim bilgilerine erişemiyorsan okul yönetimine başvur." | ||
| 504 | - ), | ||
| 505 | - "auth_required": False, | ||
| 506 | - "example_questions": [ | ||
| 507 | - "Şifremi unuttum", | ||
| 508 | - "Hesabıma giremiyorum", | ||
| 509 | - "Şifremi nasıl yenilerim?", | ||
| 510 | - "Giriş yapamıyorum", | ||
| 511 | - "Parolamı sıfırlamak istiyorum", | ||
| 512 | - "Şifre yenileme kodu gelmedi", | ||
| 513 | - "Hesabım kilitlendi", | ||
| 514 | - "Kullanıcı bilgilerimi kabul etmiyor", | ||
| 515 | - ], | ||
| 516 | - "must_not_match": ["update_contact_info", "technical_problem"], | ||
| 517 | - }, | ||
| 518 | - { | ||
| 519 | - "intent": "update_contact_info", | ||
| 520 | - "category": "account", | ||
| 521 | - "description": "Telefon, e-posta veya veli iletişim bilgisini güncelleme isteği.", | ||
| 522 | - "response_id": "contact_update_instructions", | ||
| 523 | - "response_template": ( | ||
| 524 | - "İletişim bilgisi değişiklikleri doğrulama gerektirir. Profil > " | ||
| 525 | - "İletişim Bilgileri bölümünü kullanabilir veya okul yönetimine başvurabilirsin." | ||
| 526 | - ), | ||
| 527 | - "auth_required": True, | ||
| 528 | - "entities": ["contact_type"], | ||
| 529 | - "example_questions": [ | ||
| 530 | - "Telefon numaramı değiştirmek istiyorum", | ||
| 531 | - "E-posta adresimi nasıl güncellerim?", | ||
| 532 | - "Veli telefon numarası yanlış", | ||
| 533 | - "İletişim bilgilerimi düzenle", | ||
| 534 | - "Eski numaram kayıtlı görünüyor", | ||
| 535 | - "Yeni e-posta adresimi ekleyebilir miyim?", | ||
| 536 | - "Velimin bilgilerini değiştireceğim", | ||
| 537 | - "Profil bilgilerim güncel değil", | ||
| 538 | - ], | ||
| 539 | - "must_not_match": ["student_profile", "password_reset"], | ||
| 540 | - }, | ||
| 541 | - { | ||
| 542 | - "intent": "technical_problem", | ||
| 543 | - "category": "support", | ||
| 544 | - "description": "Platformda hata, açılmayan sayfa veya çalışmayan özellik bildirimi.", | ||
| 545 | - "response_id": "technical_support_steps", | ||
| 546 | - "response_template": ( | ||
| 547 | - "Sayfayı yenileyip tekrar giriş yapmayı deneyebilirsin. Sorun sürerse " | ||
| 548 | - "hata mesajı ve ekran görüntüsüyle teknik destek kaydı oluştur. " | ||
| 549 | - "Şifreni veya kişisel bilgilerini ekran görüntüsüne ekleme." | ||
| 550 | - ), | ||
| 551 | - "auth_required": False, | ||
| 552 | - "example_questions": [ | ||
| 553 | - "Sistem çalışmıyor", | ||
| 554 | - "Sayfa açılmıyor", | ||
| 555 | - "Bir hata mesajı alıyorum", | ||
| 556 | - "Notlar bölümü yüklenmiyor", | ||
| 557 | - "Uygulama sürekli kapanıyor", | ||
| 558 | - "Dosya yüklerken hata veriyor", | ||
| 559 | - "Ekran dondu", | ||
| 560 | - "Platforma erişemiyorum", | ||
| 561 | - "Butona basıyorum ama hiçbir şey olmuyor", | ||
| 562 | - "Teknik desteğe nasıl ulaşırım?", | ||
| 563 | - ], | ||
| 564 | - "must_not_match": ["password_reset", "homework_submission"], | ||
| 565 | - }, | ||
| 566 | - { | ||
| 567 | - "intent": "privacy_and_security", | ||
| 568 | - "category": "security", | ||
| 569 | - "description": "Kişisel veriler, hesap güvenliği veya başkasının bilgilerini isteme.", | ||
| 570 | - "response_id": "privacy_policy_message", | ||
| 571 | - "response_template": ( | ||
| 572 | - "Yalnızca oturum açmış kullanıcının yetkili olduğu bilgiler gösterilir. " | ||
| 573 | - "Başka öğrencilerin not, devamsızlık veya iletişim bilgilerini paylaşamam." | ||
| 574 | - ), | ||
| 575 | - "auth_required": False, | ||
| 576 | - "example_questions": [ | ||
| 577 | - "Arkadaşımın notlarını göster", | ||
| 578 | - "Başka bir öğrencinin devamsızlığı kaç?", | ||
| 579 | - "Bilgilerimi kimler görebilir?", | ||
| 580 | - "Verilerim güvende mi?", | ||
| 581 | - "Sınıftaki herkesin notlarını göster", | ||
| 582 | - "Bir öğrencinin telefonunu verir misin?", | ||
| 583 | - "Hesabımı başkası kullanmış olabilir", | ||
| 584 | - "Kişisel bilgilerimi silmek istiyorum", | ||
| 585 | - ], | ||
| 586 | - "must_not_match": ["course_grades", "attendance_summary", "teacher_contact"], | ||
| 587 | - }, | ||
| 588 | -] | ||
| 589 | - | ||
| 590 | - | ||
| 591 | -FALLBACK: Final[dict[str, str]] = { | ||
| 592 | - "response_id": "fallback_clarification", | ||
| 593 | - "response_template": ( | ||
| 594 | - "Bu isteği anlayamadım. Notlar, devamsızlık, ders programı, sınavlar, " | ||
| 595 | - "ödevler veya duyurular hakkında daha açık bir soru sorabilir misin?" | ||
| 596 | - ), | ||
| 597 | -} | ||
| 598 | - | ||
| 599 | - | ||
| 600 | -def get_intent(intent_name: str) -> dict[str, Any] | None: | ||
| 601 | - """Intent adına göre katalog kaydını döndürür.""" | ||
| 602 | - | ||
| 603 | - return next( | ||
| 604 | - (item for item in INTENTS if item["intent"] == intent_name), | ||
| 605 | - None, | ||
| 606 | - ) | ||
src/benchmark.pyadded+128 -0
| @@ -0,0 +1,128 @@ | |||
| 1 | +"""Benchmark (değerlendirme) setinin yüklenmesi ve doğrulanması. | ||
| 2 | + | ||
| 3 | +Benchmark, motorun DÜRÜST ölçülmesi için `example_questions`'tan AYRI tutulan | ||
| 4 | +etiketli sorulardır. Her kayıt: | ||
| 5 | + {"question": str, "expected_intent": str | "oos", "role": str?} | ||
| 6 | + | ||
| 7 | +`expected_intent == "oos"` -> kapsam dışı; motor bunları FALLBACK'e atmalıdır. | ||
| 8 | +""" | ||
| 9 | + | ||
| 10 | +from __future__ import annotations | ||
| 11 | + | ||
| 12 | +import json | ||
| 13 | +from pathlib import Path | ||
| 14 | +from typing import Any, Final | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +OOS_LABEL: Final[str] = "oos" | ||
| 18 | + | ||
| 19 | +# Depo kökü: src/benchmark.py -> parents[1] = proje kökü. | ||
| 20 | +DEFAULT_BENCHMARK_PATH: Final[Path] = ( | ||
| 21 | + Path(__file__).resolve().parents[1] / "data" / "benchmark.jsonl" | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def load_benchmark(path: str | Path | None = None) -> list[dict[str, Any]]: | ||
| 26 | + """Benchmark kayıtlarını JSONL dosyasından yükler. | ||
| 27 | + | ||
| 28 | + Boş satırlar atlanır. Her satır 'question' ve 'expected_intent' içermelidir. | ||
| 29 | + | ||
| 30 | + Raises: | ||
| 31 | + FileNotFoundError: Dosya yoksa. | ||
| 32 | + ValueError: Bir satır bozuksa veya zorunlu alan eksikse. | ||
| 33 | + """ | ||
| 34 | + | ||
| 35 | + benchmark_path = Path(path) if path is not None else DEFAULT_BENCHMARK_PATH | ||
| 36 | + if not benchmark_path.exists(): | ||
| 37 | + raise FileNotFoundError(f"Benchmark dosyası bulunamadı: {benchmark_path}") | ||
| 38 | + | ||
| 39 | + records: list[dict[str, Any]] = [] | ||
| 40 | + with benchmark_path.open("r", encoding="utf-8") as handle: | ||
| 41 | + for line_no, raw_line in enumerate(handle, start=1): | ||
| 42 | + line = raw_line.strip() | ||
| 43 | + if not line: | ||
| 44 | + continue | ||
| 45 | + try: | ||
| 46 | + record = json.loads(line) | ||
| 47 | + except json.JSONDecodeError as exc: | ||
| 48 | + raise ValueError(f"Benchmark satırı {line_no} geçersiz JSON: {exc}") from exc | ||
| 49 | + if "question" not in record or "expected_intent" not in record: | ||
| 50 | + raise ValueError( | ||
| 51 | + f"Benchmark satırı {line_no}: 'question' ve 'expected_intent' zorunlu." | ||
| 52 | + ) | ||
| 53 | + records.append(record) | ||
| 54 | + return records | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +def validate_benchmark( | ||
| 58 | + records: list[dict[str, Any]], | ||
| 59 | + known_intents: set[str], | ||
| 60 | + known_roles: set[str] | None = None, | ||
| 61 | + example_questions: set[str] | None = None, | ||
| 62 | +) -> dict[str, int]: | ||
| 63 | + """Benchmark kayıtlarının tutarlılığını doğrular. | ||
| 64 | + | ||
| 65 | + Kontroller: | ||
| 66 | + - question boş olmayan metin. | ||
| 67 | + - expected_intent ya bilinen bir intent ya da OOS_LABEL. | ||
| 68 | + - (verilirse) role bilinen bir rol. | ||
| 69 | + - benchmark içinde tekrarlanan soru yok. | ||
| 70 | + - (verilirse) hiçbir soru example_questions ile örtüşmez. | ||
| 71 | + - en az bir OOS kaydı bulunur. | ||
| 72 | + | ||
| 73 | + Returns: | ||
| 74 | + Sayımlar: total, in_scope, oos, intents_covered. | ||
| 75 | + | ||
| 76 | + Raises: | ||
| 77 | + ValueError: Herhangi bir kontrol başarısızsa. | ||
| 78 | + """ | ||
| 79 | + | ||
| 80 | + errors: list[str] = [] | ||
| 81 | + if not records: | ||
| 82 | + raise ValueError("Benchmark boş olamaz.") | ||
| 83 | + | ||
| 84 | + seen_questions: set[str] = set() | ||
| 85 | + covered: set[str] = set() | ||
| 86 | + oos_count = 0 | ||
| 87 | + | ||
| 88 | + for index, record in enumerate(records): | ||
| 89 | + question = record.get("question") | ||
| 90 | + expected = record.get("expected_intent") | ||
| 91 | + role = record.get("role") | ||
| 92 | + | ||
| 93 | + if not isinstance(question, str) or not question.strip(): | ||
| 94 | + errors.append(f"[{index}] boş/metin olmayan question.") | ||
| 95 | + continue | ||
| 96 | + | ||
| 97 | + norm_q = question.strip().casefold() | ||
| 98 | + if norm_q in seen_questions: | ||
| 99 | + errors.append(f"[{index}] tekrarlanan soru: {question!r}") | ||
| 100 | + seen_questions.add(norm_q) | ||
| 101 | + | ||
| 102 | + if expected == OOS_LABEL: | ||
| 103 | + oos_count += 1 | ||
| 104 | + elif expected in known_intents: | ||
| 105 | + covered.add(expected) | ||
| 106 | + else: | ||
| 107 | + errors.append(f"[{index}] bilinmeyen expected_intent: {expected!r}") | ||
| 108 | + | ||
| 109 | + if role is not None and known_roles is not None and role not in known_roles: | ||
| 110 | + errors.append(f"[{index}] bilinmeyen rol: {role!r}") | ||
| 111 | + | ||
| 112 | + if example_questions is not None and norm_q in example_questions: | ||
| 113 | + errors.append( | ||
| 114 | + f"[{index}] soru example_questions ile örtüşüyor (benchmark ayrı olmalı): {question!r}" | ||
| 115 | + ) | ||
| 116 | + | ||
| 117 | + if oos_count == 0: | ||
| 118 | + errors.append("En az bir OOS (kapsam dışı) kaydı gerekli.") | ||
| 119 | + | ||
| 120 | + if errors: | ||
| 121 | + raise ValueError("Benchmark doğrulanamadı:\n- " + "\n- ".join(errors)) | ||
| 122 | + | ||
| 123 | + return { | ||
| 124 | + "total": len(records), | ||
| 125 | + "in_scope": len(records) - oos_count, | ||
| 126 | + "oos": oos_count, | ||
| 127 | + "intents_covered": len(covered), | ||
| 128 | + } | ||
src/catalog.pyadded+1168 -0
| @@ -0,0 +1,1168 @@ | |||
| 1 | +"""Hezarfen kullanım asistanı için intent kataloğu ve rol modeli. | ||
| 2 | + | ||
| 3 | +Bu modül YALNIZCA veri + saf yardımcı fonksiyonlar içerir. Metin normalizasyonu, | ||
| 4 | +intent bulma (kural/benzerlik), karar verme ve cevap üretimi ayrı modüllerin | ||
| 5 | +sorumluluğudur. | ||
| 6 | + | ||
| 7 | +Kaynak: `hezarfen-site-rehberi.md`. Cevaplar gerçek menü/buton etiketleri ve | ||
| 8 | +sayfa yolları içerir; uydurma yol veya etiket kullanılmaz (rehber §0). | ||
| 9 | + | ||
| 10 | +Alan açıklamaları (her intent kaydı): | ||
| 11 | +- intent: Motorun döndüreceği benzersiz sınıf adı. | ||
| 12 | +- category: Gruplama (raporlama/menü için). | ||
| 13 | +- description: İnsan-okunur kısa açıklama. | ||
| 14 | +- response_id: Testlerde metin yerine karşılaştırılan kararlı kimlik. | ||
| 15 | +- response_template: Kullanıcıya gösterilecek adım adım cevap (gerçek yol/etiket). | ||
| 16 | +- auth_required: Oturum gerekip gerekmediği. min_role ile tutarlı olmalıdır. | ||
| 17 | +- min_role: Bu işlemi yapabilen EN DÜŞÜK rol (rol hiyerarşisinden). | ||
| 18 | +- example_questions: Kural/eşik geliştirme örnekleri; benchmark DEĞİLDİR. | ||
| 19 | +- must_not_match: Bu intent ile sık karışabilecek intent adları. | ||
| 20 | + | ||
| 21 | +`example_questions` benchmark değildir; gerçek değerlendirme soruları ayrı bir | ||
| 22 | +dosyada tutulur ve bu listeden kopyalanmaz. | ||
| 23 | +""" | ||
| 24 | + | ||
| 25 | +from __future__ import annotations | ||
| 26 | + | ||
| 27 | +from collections import Counter | ||
| 28 | +from typing import Any, Final | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +# --- Rol modeli (rehber §2) -------------------------------------------------- | ||
| 32 | +# Hiyerarşi düşükten yükseğe. Üst rol, alt rolün yaptığı her şeyi yapabilir. | ||
| 33 | +ROLE_HIERARCHY: Final[tuple[str, ...]] = ( | ||
| 34 | + "ziyaretci", # oturum açmamış kullanıcı | ||
| 35 | + "ogrenci", | ||
| 36 | + "ogretmen", | ||
| 37 | + "yonetici", | ||
| 38 | + "admin", | ||
| 39 | +) | ||
| 40 | + | ||
| 41 | +_ROLE_RANK: Final[dict[str, int]] = {role: rank for rank, role in enumerate(ROLE_HIERARCHY)} | ||
| 42 | + | ||
| 43 | +# Oturum açmış sayılan en düşük rol. | ||
| 44 | +MIN_AUTHENTICATED_ROLE: Final[str] = "ogrenci" | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +REQUIRED_INTENT_FIELDS: Final[frozenset[str]] = frozenset( | ||
| 48 | + { | ||
| 49 | + "intent", | ||
| 50 | + "category", | ||
| 51 | + "description", | ||
| 52 | + "response_id", | ||
| 53 | + "response_template", | ||
| 54 | + "auth_required", | ||
| 55 | + "min_role", | ||
| 56 | + "example_questions", | ||
| 57 | + "must_not_match", | ||
| 58 | + } | ||
| 59 | +) | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +INTENTS: Final[list[dict[str, Any]]] = [ | ||
| 63 | + # --- Genel --------------------------------------------------------------- | ||
| 64 | + { | ||
| 65 | + "intent": "greeting", | ||
| 66 | + "category": "general", | ||
| 67 | + "description": "Kullanıcının selam vermesi / sohbeti başlatması.", | ||
| 68 | + "response_id": "welcome_message", | ||
| 69 | + "response_template": ( | ||
| 70 | + "Merhaba! Ben Hezarfen kullanım asistanıyım. Ders, sınav, karne, " | ||
| 71 | + "yoklama, defter ve mesai gibi konularda 'nasıl yaparım?' sorularını " | ||
| 72 | + "yanıtlayabilirim. Ne yapmak istiyorsun?" | ||
| 73 | + ), | ||
| 74 | + "auth_required": False, | ||
| 75 | + "min_role": "ziyaretci", | ||
| 76 | + "example_questions": ["Merhaba", "Selam", "Günaydın", "İyi günler", "Hey"], | ||
| 77 | + "must_not_match": ["help_capabilities"], | ||
| 78 | + }, | ||
| 79 | + { | ||
| 80 | + "intent": "help_capabilities", | ||
| 81 | + "category": "general", | ||
| 82 | + "description": "Asistanın neler yapabildiğinin sorulması.", | ||
| 83 | + "response_id": "capabilities", | ||
| 84 | + "response_template": ( | ||
| 85 | + "Hezarfen sitesini nasıl kullanacağını anlatabilirim: ders/sınav " | ||
| 86 | + "oluşturma, sınava girme, karne ve ortalama, yoklama, defter, mesai, " | ||
| 87 | + "dönem ve okul ayarları, kullanıcı rolleri ve daha fazlası. Rolünü " | ||
| 88 | + "(Öğrenci/Öğretmen/Yönetici/ADMIN) söylersen sana uygun adımları veririm." | ||
| 89 | + ), | ||
| 90 | + "auth_required": False, | ||
| 91 | + "min_role": "ziyaretci", | ||
| 92 | + "example_questions": [ | ||
| 93 | + "Neler yapabilirsin?", | ||
| 94 | + "Bana nasıl yardımcı olursun?", | ||
| 95 | + "Hangi konularda yardım edebilirsin?", | ||
| 96 | + "Ne işe yarıyorsun?", | ||
| 97 | + "Özelliklerin neler?", | ||
| 98 | + ], | ||
| 99 | + "must_not_match": ["greeting", "guide_info"], | ||
| 100 | + }, | ||
| 101 | + { | ||
| 102 | + "intent": "guide_info", | ||
| 103 | + "category": "general", | ||
| 104 | + "description": "Uygulama içi Rehber (Guide) sayfasının sorulması.", | ||
| 105 | + "response_id": "guide_page_info", | ||
| 106 | + "response_template": ( | ||
| 107 | + "Uygulama içi rehbere hesap (avatar) menüsünden **Rehber (Guide)** ile " | ||
| 108 | + "veya doğrudan `/guide` adresinden ulaşırsın. 6 adımlık akışı (Ana sayfa, " | ||
| 109 | + "Defter, Etkinlik/Yoklama, Dersler, Sınavlar, Karnem) ve 'Kim ne yapabilir?' " | ||
| 110 | + "panelini içerir." | ||
| 111 | + ), | ||
| 112 | + "auth_required": True, | ||
| 113 | + "min_role": "ogrenci", | ||
| 114 | + "example_questions": [ | ||
| 115 | + "Rehber sayfası nerede?", | ||
| 116 | + "Kullanım kılavuzu var mı?", | ||
| 117 | + "Uygulama içi rehbere nasıl ulaşırım?", | ||
| 118 | + "Guide sayfasını aç", | ||
| 119 | + "Yardım rehberi nerede?", | ||
| 120 | + ], | ||
| 121 | + "must_not_match": ["help_capabilities", "navigation_help"], | ||
| 122 | + }, | ||
| 123 | + # --- Kimlik / hesap ------------------------------------------------------ | ||
| 124 | + { | ||
| 125 | + "intent": "login_how", | ||
| 126 | + "category": "account", | ||
| 127 | + "description": "Nasıl giriş yapılacağının sorulması.", | ||
| 128 | + "response_id": "login_instructions", | ||
| 129 | + "response_template": ( | ||
| 130 | + "Giriş yapmak için `/login` sayfasına git, **Kullanıcı adı (Username)** " | ||
| 131 | + "(3–32 karakter) ve **Şifre (Password)** (6–128) alanlarını doldur, " | ||
| 132 | + "**Giriş yap (Log in)** düğmesine bas. Başarılı girişte Ana sayfaya (`/`) " | ||
| 133 | + "yönlendirilirsin; hatalı bilgide formun üstünde kırmızı hata kutusu çıkar." | ||
| 134 | + ), | ||
| 135 | + "auth_required": False, | ||
| 136 | + "min_role": "ziyaretci", | ||
| 137 | + "example_questions": [ | ||
| 138 | + "Nasıl giriş yaparım?", | ||
| 139 | + "Giriş sayfası nerede?", | ||
| 140 | + "Log in nasıl oluyor?", | ||
| 141 | + "Sisteme nasıl girerim?", | ||
| 142 | + "Oturum açmak istiyorum", | ||
| 143 | + ], | ||
| 144 | + "must_not_match": ["register_how", "account_access_problem"], | ||
| 145 | + }, | ||
| 146 | + { | ||
| 147 | + "intent": "register_how", | ||
| 148 | + "category": "account", | ||
| 149 | + "description": "Nasıl yeni hesap/kayıt oluşturulacağı.", | ||
| 150 | + "response_id": "register_instructions", | ||
| 151 | + "response_template": ( | ||
| 152 | + "Kayıt için `/register` sayfasına git; **Kullanıcı adı** (3–32), **Şifre** " | ||
| 153 | + "(6–128) ve **Şifreyi onayla (Confirm password)** alanlarını doldurup " | ||
| 154 | + "**Hesap oluştur (Create account)**'a bas. Yeni hesaplar **Öğrenci** olarak " | ||
| 155 | + "başlar; kayıt otomatik giriş yapmaz, giriş sayfasına yönlendirilirsin. " | ||
| 156 | + "'admin/root/support' gibi personel çağrıştıran adlar reddedilir." | ||
| 157 | + ), | ||
| 158 | + "auth_required": False, | ||
| 159 | + "min_role": "ziyaretci", | ||
| 160 | + "example_questions": [ | ||
| 161 | + "Nasıl kayıt olurum?", | ||
| 162 | + "Yeni hesap nasıl açılır?", | ||
| 163 | + "Hesap oluşturmak istiyorum", | ||
| 164 | + "Kayıt sayfası nerede?", | ||
| 165 | + "Üye olmak istiyorum", | ||
| 166 | + ], | ||
| 167 | + "must_not_match": ["login_how"], | ||
| 168 | + }, | ||
| 169 | + { | ||
| 170 | + "intent": "logout_how", | ||
| 171 | + "category": "account", | ||
| 172 | + "description": "Çıkış yapma yöntemi.", | ||
| 173 | + "response_id": "logout_instructions", | ||
| 174 | + "response_template": ( | ||
| 175 | + "Çıkış yapmak için sol menü altındaki hesap kutusunu (ad-soyad) aç ve " | ||
| 176 | + "**Çıkış yap (Log out)**'a bas. Oturum hemen kapanır." | ||
| 177 | + ), | ||
| 178 | + "auth_required": True, | ||
| 179 | + "min_role": "ogrenci", | ||
| 180 | + "example_questions": [ | ||
| 181 | + "Nasıl çıkış yaparım?", | ||
| 182 | + "Oturumu nasıl kapatırım?", | ||
| 183 | + "Log out nerede?", | ||
| 184 | + "Hesaptan çıkmak istiyorum", | ||
| 185 | + "Çıkış yap", | ||
| 186 | + ], | ||
| 187 | + "must_not_match": ["session_info"], | ||
| 188 | + }, | ||
| 189 | + { | ||
| 190 | + "intent": "session_info", | ||
| 191 | + "category": "account", | ||
| 192 | + "description": "Oturum süresi / oturum davranışı.", | ||
| 193 | + "response_id": "session_duration_info", | ||
| 194 | + "response_template": ( | ||
| 195 | + "Giriş yapınca **7 gün** geçerli bir oturum açılır. Süre sunucu saatiyle " | ||
| 196 | + "ölçülür; cihazının saati yanlış olsa bile değişmez. Çıkış yapmak oturumu " | ||
| 197 | + "hemen kapatır." | ||
| 198 | + ), | ||
| 199 | + "auth_required": True, | ||
| 200 | + "min_role": "ogrenci", | ||
| 201 | + "example_questions": [ | ||
| 202 | + "Oturumum ne kadar açık kalır?", | ||
| 203 | + "Ne zaman otomatik çıkış olur?", | ||
| 204 | + "Oturum süresi kaç gün?", | ||
| 205 | + "Tekrar giriş yapmam gerekir mi?", | ||
| 206 | + "Oturum ne kadar sürer?", | ||
| 207 | + ], | ||
| 208 | + "must_not_match": ["logout_how"], | ||
| 209 | + }, | ||
| 210 | + { | ||
| 211 | + "intent": "account_access_problem", | ||
| 212 | + "category": "account", | ||
| 213 | + "description": "Şifre unutma / giriş yapamama gibi erişim sorunları.", | ||
| 214 | + "response_id": "access_problem_info", | ||
| 215 | + "response_template": ( | ||
| 216 | + "Hatalı kullanıcı adı/şifrede giriş formunun üstünde kırmızı hata kutusu " | ||
| 217 | + "çıkar; bilgilerini kontrol edip tekrar dene. Rehberde self-servis bir " | ||
| 218 | + "'şifremi unuttum' akışı tanımlı değil; kayıtlı bilgilerine erişemiyorsan " | ||
| 219 | + "okul yönetimine başvurman gerekir." | ||
| 220 | + ), | ||
| 221 | + "auth_required": False, | ||
| 222 | + "min_role": "ziyaretci", | ||
| 223 | + "example_questions": [ | ||
| 224 | + "Şifremi unuttum", | ||
| 225 | + "Giriş yapamıyorum", | ||
| 226 | + "Hesabıma giremiyorum", | ||
| 227 | + "Kullanıcı adımı hatırlamıyorum", | ||
| 228 | + "Şifremi sıfırlayabilir miyim?", | ||
| 229 | + ], | ||
| 230 | + "must_not_match": ["login_how", "privacy_security"], | ||
| 231 | + }, | ||
| 232 | + { | ||
| 233 | + "intent": "profile_edit", | ||
| 234 | + "category": "account", | ||
| 235 | + "description": "Profil bilgilerini düzenleme.", | ||
| 236 | + "response_id": "profile_edit_instructions", | ||
| 237 | + "response_template": ( | ||
| 238 | + "Profilini düzenlemek için hesap menüsünden **Profili düzenle (Edit profile)** " | ||
| 239 | + "veya `/profile` adresine git; **Ad, Soyad, E-posta, Telefon, Doğum tarihi " | ||
| 240 | + "(GG/AA/YYYY)** alanlarını güncelleyip **Kaydet**'e bas. Tüm alanlar isteğe " | ||
| 241 | + "bağlıdır; **kullanıcı adı ve rol buradan değiştirilemez**. Doğum tarihi " | ||
| 242 | + "gelecekte olamaz." | ||
| 243 | + ), | ||
| 244 | + "auth_required": True, | ||
| 245 | + "min_role": "ogrenci", | ||
| 246 | + "example_questions": [ | ||
| 247 | + "Profilimi nasıl düzenlerim?", | ||
| 248 | + "E-posta adresimi değiştirmek istiyorum", | ||
| 249 | + "Telefon numaramı güncelleyeceğim", | ||
| 250 | + "Kişisel bilgilerimi nereden değiştiririm?", | ||
| 251 | + "Doğum tarihimi ekleyebilir miyim?", | ||
| 252 | + ], | ||
| 253 | + "must_not_match": ["user_role_change"], | ||
| 254 | + }, | ||
| 255 | + { | ||
| 256 | + "intent": "language_theme", | ||
| 257 | + "category": "account", | ||
| 258 | + "description": "Dil (TR/EN) veya tema (açık/koyu) değiştirme.", | ||
| 259 | + "response_id": "language_theme_instructions", | ||
| 260 | + "response_template": ( | ||
| 261 | + "Giriş yaptıysan sol menü altındaki hesap kutusundan **Dil (Language)** ile " | ||
| 262 | + "Türkçe/English, **Tema (Toggle theme)** ile Açık/Koyu arasında geçebilirsin. " | ||
| 263 | + "Ziyaretçiysen bu seçenekler üst bardadır. Seçim tarayıcıda kalıcı saklanır." | ||
| 264 | + ), | ||
| 265 | + "auth_required": False, | ||
| 266 | + "min_role": "ziyaretci", | ||
| 267 | + "example_questions": [ | ||
| 268 | + "Dili nasıl değiştiririm?", | ||
| 269 | + "İngilizceye nasıl geçerim?", | ||
| 270 | + "Karanlık moda nasıl geçilir?", | ||
| 271 | + "Temayı değiştirmek istiyorum", | ||
| 272 | + "Uygulamayı Türkçe yap", | ||
| 273 | + ], | ||
| 274 | + "must_not_match": ["navigation_help"], | ||
| 275 | + }, | ||
| 276 | + # --- Roller / navigasyon ------------------------------------------------- | ||
| 277 | + { | ||
| 278 | + "intent": "roles_permissions", | ||
| 279 | + "category": "roles", | ||
| 280 | + "description": "Roller ve yetkilerin sorulması.", | ||
| 281 | + "response_id": "roles_overview", | ||
| 282 | + "response_template": ( | ||
| 283 | + "Hezarfen'de dört kademeli rol vardır: **Öğrenci < Öğretmen < Yönetici < " | ||
| 284 | + "ADMIN**. Üst rol, alt rolün yaptığı her şeyi yapar. Kayıt olan herkes " | ||
| 285 | + "Öğrenci başlar; üst roller sonradan bir ADMIN tarafından atanır. Rol her " | ||
| 286 | + "istekte yeniden kontrol edilir; değişince yeniden giriş gerekmez." | ||
| 287 | + ), | ||
| 288 | + "auth_required": True, | ||
| 289 | + "min_role": "ogrenci", | ||
| 290 | + "example_questions": [ | ||
| 291 | + "Roller nelerdir?", | ||
| 292 | + "Yetkiler nasıl çalışıyor?", | ||
| 293 | + "Öğretmen neler yapabilir?", | ||
| 294 | + "ADMIN ile Yönetici farkı ne?", | ||
| 295 | + "Kimin hangi yetkisi var?", | ||
| 296 | + ], | ||
| 297 | + "must_not_match": ["user_role_change", "access_denied_help"], | ||
| 298 | + }, | ||
| 299 | + { | ||
| 300 | + "intent": "access_denied_help", | ||
| 301 | + "category": "roles", | ||
| 302 | + "description": "'Erişimin yok' / yetkisiz sayfa yönlendirmesi.", | ||
| 303 | + "response_id": "access_denied_info", | ||
| 304 | + "response_template": ( | ||
| 305 | + "Yetkisiz erişimde iki davranış olur: bazı sayfalarda sessizce Ana sayfaya " | ||
| 306 | + "(`/`) yönlendirilirsin (oturum yoksa `/login`'e); bazılarında ise kırmızı " | ||
| 307 | + "**\"Bu içeriğe erişimin yok.\"** kutusu çıkar. Bu genelde rolünün o işlem " | ||
| 308 | + "için yetersiz olduğunu ya da ilgili derse kayıtlı olmadığını gösterir." | ||
| 309 | + ), | ||
| 310 | + "auth_required": False, | ||
| 311 | + "min_role": "ziyaretci", | ||
| 312 | + "example_questions": [ | ||
| 313 | + "Bu içeriğe erişimin yok diyor", | ||
| 314 | + "Neden ana sayfaya atıldım?", | ||
| 315 | + "Sayfaya giremiyorum neden?", | ||
| 316 | + "Erişim reddedildi ne demek?", | ||
| 317 | + "Yetkim yok mu?", | ||
| 318 | + ], | ||
| 319 | + "must_not_match": ["roles_permissions", "account_access_problem"], | ||
| 320 | + }, | ||
| 321 | + { | ||
| 322 | + "intent": "navigation_help", | ||
| 323 | + "category": "roles", | ||
| 324 | + "description": "Menü/sayfa nerede — genel navigasyon.", | ||
| 325 | + "response_id": "navigation_info", | ||
| 326 | + "response_template": ( | ||
| 327 | + "Masaüstünde sol dikey menüden gezinilir; gruplar rol bazlıdır ve boş " | ||
| 328 | + "gruplar gizlenir. Mobilde altta 5 sekme vardır: Ana sayfa, Dersler, " | ||
| 329 | + "Sınavlar, Defter, Menü. Hangi sayfayı aradığını söylersen tam yolunu " | ||
| 330 | + "(ör. `/courses`, `/exams`, `/marks`) veririm." | ||
| 331 | + ), | ||
| 332 | + "auth_required": True, | ||
| 333 | + "min_role": "ogrenci", | ||
| 334 | + "example_questions": [ | ||
| 335 | + "Menüde ne var?", | ||
| 336 | + "Sayfalar nerede?", | ||
| 337 | + "Nasıl gezinirim?", | ||
| 338 | + "İlgili bölümü nasıl bulurum?", | ||
| 339 | + "Navigasyon nasıl?", | ||
| 340 | + ], | ||
| 341 | + "must_not_match": ["guide_info", "language_theme"], | ||
| 342 | + }, | ||
| 343 | + # --- Dersler ------------------------------------------------------------- | ||
| 344 | + { | ||
| 345 | + "intent": "course_view", | ||
| 346 | + "category": "courses", | ||
| 347 | + "description": "Dersleri listeleme / ders detayına gitme.", | ||
| 348 | + "response_id": "course_view_info", | ||
| 349 | + "response_template": ( | ||
| 350 | + "Dersler `/courses` sayfasında listelenir; arama ve döneme göre filtreleme " | ||
| 351 | + "yapabilirsin. Öğrenci yalnızca kayıtlı olduğu dersleri görür ('Kayıtlı' " | ||
| 352 | + "rozeti). Bir dersi açmak için satırda **Görüntüle (View)**'ye bas; detay " | ||
| 353 | + "`/courses/$id`'de sınavları, ders oturumlarını ve (yetkiliysen) sınıf " | ||
| 354 | + "listesini gösterir." | ||
| 355 | + ), | ||
| 356 | + "auth_required": True, | ||
| 357 | + "min_role": "ogrenci", | ||
| 358 | + "example_questions": [ | ||
| 359 | + "Derslerimi nerede görürüm?", | ||
| 360 | + "Ders listesi nerede?", | ||
| 361 | + "Kayıtlı olduğum dersler neler?", | ||
| 362 | + "Bir dersin detayına nasıl giderim?", | ||
| 363 | + "Dersleri nasıl filtrelerim?", | ||
| 364 | + ], | ||
| 365 | + "must_not_match": ["course_create", "report_card_view"], | ||
| 366 | + }, | ||
| 367 | + { | ||
| 368 | + "intent": "course_create", | ||
| 369 | + "category": "courses", | ||
| 370 | + "description": "Yeni ders oluşturma (Öğretmen+).", | ||
| 371 | + "response_id": "course_create_instructions", | ||
| 372 | + "response_template": ( | ||
| 373 | + "Ön koşul: Öğretmen ve üstü rol. 1) `/courses`'a git, **Yeni ders (New " | ||
| 374 | + "course)**'e bas. 2) Sağdan açılan panelde **Başlık** (zorunlu), isteğe " | ||
| 375 | + "bağlı **Açıklama** ve **Dönem** (varsayılan 'Atanmamış') gir. 3) **Oluştur**. " | ||
| 376 | + "Öğrencide 'Yeni ders' düğmesi görünmez." | ||
| 377 | + ), | ||
| 378 | + "auth_required": True, | ||
| 379 | + "min_role": "ogretmen", | ||
| 380 | + "example_questions": [ | ||
| 381 | + "Yeni ders nasıl oluşturulur?", | ||
| 382 | + "Ders eklemek istiyorum", | ||
| 383 | + "Nasıl ders açarım?", | ||
| 384 | + "Yeni bir sınıf oluşturacağım", | ||
| 385 | + "Ders oluşturma nerede?", | ||
| 386 | + ], | ||
| 387 | + "must_not_match": ["course_view", "exam_create", "event_create"], | ||
| 388 | + }, | ||
| 389 | + { | ||
| 390 | + "intent": "course_enroll_student", | ||
| 391 | + "category": "courses", | ||
| 392 | + "description": "Derse öğrenci kaydetme (Öğretmen+).", | ||
| 393 | + "response_id": "enroll_student_instructions", | ||
| 394 | + "response_template": ( | ||
| 395 | + "Ön koşul: dersi oluşturan öğretmen veya Yönetici+ olmak. 1) Ders detayına " | ||
| 396 | + "(`/courses/$id`) gir, **Sınıf listesi (Roster)** bölümünü aç. 2) **Öğrenci " | ||
| 397 | + "kaydet (Enroll student)**'e bas, panelde öğrenciyi ara-seç. 3) Onayla. " | ||
| 398 | + "Zaten kayıtlılar listede çıkmaz; öğrenci seçmezsen 'Önce bir öğrenci " | ||
| 399 | + "seçmelisin.' uyarısı çıkar. Sınıf listesi yalnızca yönetim yetkilisine görünür." | ||
| 400 | + ), | ||
| 401 | + "auth_required": True, | ||
| 402 | + "min_role": "ogretmen", | ||
| 403 | + "example_questions": [ | ||
| 404 | + "Derse nasıl öğrenci eklerim?", | ||
| 405 | + "Öğrenci kaydetmek istiyorum", | ||
| 406 | + "Sınıfa öğrenci nasıl alınır?", | ||
| 407 | + "Roster'a öğrenci ekleme", | ||
| 408 | + "Bir öğrenciyi derse kaydet", | ||
| 409 | + ], | ||
| 410 | + "must_not_match": ["course_remove_student", "course_create"], | ||
| 411 | + }, | ||
| 412 | + { | ||
| 413 | + "intent": "course_remove_student", | ||
| 414 | + "category": "courses", | ||
| 415 | + "description": "Dersten öğrenci çıkarma (Öğretmen+).", | ||
| 416 | + "response_id": "remove_student_instructions", | ||
| 417 | + "response_template": ( | ||
| 418 | + "1) Ders detayı → **Sınıf listesi (Roster)** bölümünü aç. 2) İlgili öğrenci " | ||
| 419 | + "satırında **Kaldır (Remove)**'a bas ve onayla. Çıkarmak geçmiş notları " | ||
| 420 | + "silmez; öğrenci daha sonra tekrar kaydedilebilir." | ||
| 421 | + ), | ||
| 422 | + "auth_required": True, | ||
| 423 | + "min_role": "ogretmen", | ||
| 424 | + "example_questions": [ | ||
| 425 | + "Dersten öğrenci nasıl çıkarılır?", | ||
| 426 | + "Bir öğrenciyi sınıftan silmek istiyorum", | ||
| 427 | + "Kaydı nasıl kaldırırım?", | ||
| 428 | + "Öğrenciyi dersten at", | ||
| 429 | + "Yanlış kaydettiğim öğrenciyi çıkar", | ||
| 430 | + ], | ||
| 431 | + "must_not_match": ["course_enroll_student"], | ||
| 432 | + }, | ||
| 433 | + { | ||
| 434 | + "intent": "lesson_session_add", | ||
| 435 | + "category": "courses", | ||
| 436 | + "description": "Ders oturumu (ders saati) ekleme (Öğretmen+).", | ||
| 437 | + "response_id": "lesson_session_instructions", | ||
| 438 | + "response_template": ( | ||
| 439 | + "Ön koşul: ders yönetim yetkisi. 1) Ders detayı → **Ders oturumları (Lesson " | ||
| 440 | + "sessions)** → **Oturum ekle (Add session)**. 2) İsteğe bağlı **Konu**, " | ||
| 441 | + "**Başlangıç** tarih (GG/AA/YYYY) + saat, isteğe bağlı **Bitiş**. 3) **Oturum " | ||
| 442 | + "ekle**. Başlangıç zorunlu ve gelecekte olmalı; bitiş başlangıçtan önce olamaz." | ||
| 443 | + ), | ||
| 444 | + "auth_required": True, | ||
| 445 | + "min_role": "ogretmen", | ||
| 446 | + "example_questions": [ | ||
| 447 | + "Ders oturumu nasıl eklerim?", | ||
| 448 | + "Ders saati eklemek istiyorum", | ||
| 449 | + "Yeni oturum oluşturma", | ||
| 450 | + "Derse ders saati ekle", | ||
| 451 | + "Lesson session nasıl eklenir?", | ||
| 452 | + ], | ||
| 453 | + "must_not_match": ["roll_call", "event_create"], | ||
| 454 | + }, | ||
| 455 | + { | ||
| 456 | + "intent": "roll_call", | ||
| 457 | + "category": "courses", | ||
| 458 | + "description": "Ders oturumunda yoklama alma (Öğretmen+).", | ||
| 459 | + "response_id": "roll_call_instructions", | ||
| 460 | + "response_template": ( | ||
| 461 | + "Ön koşul: derste kayıtlı öğrenci ve en az bir oturum olmalı; yönetim " | ||
| 462 | + "yetkisi. 1) Ders detayı → **Ders oturumları** → oturum kartında **Yoklama " | ||
| 463 | + "(Roll call)**. 2) Her öğrenci için **Var / Yok / Geç / Mazeretli** seç. " | ||
| 464 | + "3) Satırda **Kaydet** (daha önce kaydedildiyse **Güncelle**). Öğrenci ders " | ||
| 465 | + "oturumu yoklamasında kendini işaretleyemez." | ||
| 466 | + ), | ||
| 467 | + "auth_required": True, | ||
| 468 | + "min_role": "ogretmen", | ||
| 469 | + "example_questions": [ | ||
| 470 | + "Yoklama nasıl alınır?", | ||
| 471 | + "Ders oturumunda yoklama almak istiyorum", | ||
| 472 | + "Öğrencileri var/yok nasıl işaretlerim?", | ||
| 473 | + "Roll call nasıl yapılır?", | ||
| 474 | + "Devamsızlık işleme", | ||
| 475 | + ], | ||
| 476 | + "must_not_match": ["lesson_session_add", "event_attendance_mark", "student_attendance_lookup"], | ||
| 477 | + }, | ||
| 478 | + # --- Sınavlar ------------------------------------------------------------ | ||
| 479 | + { | ||
| 480 | + "intent": "exam_modes_info", | ||
| 481 | + "category": "exams", | ||
| 482 | + "description": "Sınav modlarının açıklanması.", | ||
| 483 | + "response_id": "exam_modes_explained", | ||
| 484 | + "response_template": ( | ||
| 485 | + "Dört sınav modu vardır: **Zamansız** (çevrimdışı notlanır, girilemez), " | ||
| 486 | + "**Senkron** (herkes tek sabit aralıkta girer), **Asenkron** (aralık içinde " | ||
| 487 | + "istediğin an başlar, kişisel süre alırsın), **Açık** (her zaman girilebilir, " | ||
| 488 | + "hep 'Aktif' sayılır). Süre 1 dakika–24 saat arasıdır." | ||
| 489 | + ), | ||
| 490 | + "auth_required": True, | ||
| 491 | + "min_role": "ogrenci", | ||
| 492 | + "example_questions": [ | ||
| 493 | + "Sınav modları neler?", | ||
| 494 | + "Senkron ve asenkron farkı ne?", | ||
| 495 | + "Açık mod ne demek?", | ||
| 496 | + "Zamansız sınav nedir?", | ||
| 497 | + "Sınav türleri arasındaki fark ne?", | ||
| 498 | + ], | ||
| 499 | + "must_not_match": ["exam_create", "exam_enter_room"], | ||
| 500 | + }, | ||
| 501 | + { | ||
| 502 | + "intent": "exam_create", | ||
| 503 | + "category": "exams", | ||
| 504 | + "description": "Yeni sınav oluşturma ve mod seçme (Öğretmen+).", | ||
| 505 | + "response_id": "exam_create_instructions", | ||
| 506 | + "response_template": ( | ||
| 507 | + "Ön koşul: yönetebileceğin en az bir ders olmalı. 1) `/exams` → **Sınav " | ||
| 508 | + "oluştur (Create exam)**. 2) **Ders seç**, **Başlık** ve isteğe bağlı " | ||
| 509 | + "açıklama gir. 3) **Tür** (Ödev/Kısa sınav/Vize/Final/Proje/Sözlü) ve **Mod** " | ||
| 510 | + "(Senkron/Asenkron/Açık) seç. 4) Gerekirse **Deneme hakkı** ve **Yeniden " | ||
| 511 | + "girişe izin ver**'i ayarla. 5) Senkron/Asenkron ise Başlangıç/Bitiş gir. " | ||
| 512 | + "6) **Oluştur**. Sınavlar ders içinden eklenir." | ||
| 513 | + ), | ||
| 514 | + "auth_required": True, | ||
| 515 | + "min_role": "ogretmen", | ||
| 516 | + "example_questions": [ | ||
| 517 | + "Nasıl sınav oluştururum?", | ||
| 518 | + "Yeni sınav eklemek istiyorum", | ||
| 519 | + "Sınav açma nerede?", | ||
| 520 | + "Vize sınavı oluşturacağım", | ||
| 521 | + "Sınav nasıl hazırlanır?", | ||
| 522 | + ], | ||
| 523 | + "must_not_match": ["exam_add_question", "exam_modes_info", "course_create"], | ||
| 524 | + }, | ||
| 525 | + { | ||
| 526 | + "intent": "exam_add_question", | ||
| 527 | + "category": "exams", | ||
| 528 | + "description": "Sınava soru ekleme (Öğretmen+).", | ||
| 529 | + "response_id": "exam_add_question_instructions", | ||
| 530 | + "response_template": ( | ||
| 531 | + "Ön koşul: yönetim yetkisi; sınav 'Bitti' veya 'Yakında' değilse sorular " | ||
| 532 | + "düzenlenebilir. 1) Sınav detayı → **Sorular (Questions)** → **Soru ekle**. " | ||
| 533 | + "2) **Soru metni** + **Puan** (1–100). 3) **Soru türü**: Seçmeli (2–10 şık, " | ||
| 534 | + "doğru şıkkı işaretle) veya Metin. 4) **Oluştur**. Metin sorular otomatik " | ||
| 535 | + "puanlanmaz, elle notlanır." | ||
| 536 | + ), | ||
| 537 | + "auth_required": True, | ||
| 538 | + "min_role": "ogretmen", | ||
| 539 | + "example_questions": [ | ||
| 540 | + "Sınava nasıl soru eklerim?", | ||
| 541 | + "Soru eklemek istiyorum", | ||
| 542 | + "Çoktan seçmeli soru nasıl eklenir?", | ||
| 543 | + "Sınav sorusu oluşturma", | ||
| 544 | + "Açık uçlu soru ekleyebilir miyim?", | ||
| 545 | + ], | ||
| 546 | + "must_not_match": ["exam_create", "exam_grade_student"], | ||
| 547 | + }, | ||
| 548 | + { | ||
| 549 | + "intent": "exam_enter_room", | ||
| 550 | + "category": "exams", | ||
| 551 | + "description": "Öğrencinin sınava girmesi/başlaması.", | ||
| 552 | + "response_id": "exam_enter_room_instructions", | ||
| 553 | + "response_template": ( | ||
| 554 | + "Ön koşul: sınavın dersine kayıtlı olmak; sınav girilebilir modda " | ||
| 555 | + "(Senkron/Asenkron/Açık) ve **Aktif** olmalı. 1) Sınav detayında " | ||
| 556 | + "(`/exams/$id`) **Sınav odasını aç (Open exam room)**'a bas. 2) **Sınava " | ||
| 557 | + "başla (Start exam)**. Sorular ve **Kalan süre** görünür. 'Yakında/Bitti' " | ||
| 558 | + "sınavda giriş düğmesi çıkmaz; Zamansız sınavda oturum yoktur." | ||
| 559 | + ), | ||
| 560 | + "auth_required": True, | ||
| 561 | + "min_role": "ogrenci", | ||
| 562 | + "example_questions": [ | ||
| 563 | + "Sınava nasıl girerim?", | ||
| 564 | + "Sınav odasını nasıl açarım?", | ||
| 565 | + "Sınava başlamak istiyorum", | ||
| 566 | + "Online sınava nasıl katılırım?", | ||
| 567 | + "Sınavı nereden başlatırım?", | ||
| 568 | + ], | ||
| 569 | + "must_not_match": ["exam_save_answer", "exam_finish_result", "exam_modes_info"], | ||
| 570 | + }, | ||
| 571 | + { | ||
| 572 | + "intent": "exam_save_answer", | ||
| 573 | + "category": "exams", | ||
| 574 | + "description": "Sınav odasında cevap kaydetme.", | ||
| 575 | + "response_id": "exam_save_answer_instructions", | ||
| 576 | + "response_template": ( | ||
| 577 | + "Ön koşul: durum 'Devam ediyor', süre bitmemiş. 1) Şık seç veya metin " | ||
| 578 | + "kutusuna yaz. 2) **Cevabı kaydet (Save answer)**. 3) **Kaydedildi** rozeti " | ||
| 579 | + "çıkar ve ekran otomatik sonraki soruya kayar. Her cevap tek tek kaydedilir; " | ||
| 580 | + "toplu gönderim yoktur. Süre bitince cevaplar salt okunur olur." | ||
| 581 | + ), | ||
| 582 | + "auth_required": True, | ||
| 583 | + "min_role": "ogrenci", | ||
| 584 | + "example_questions": [ | ||
| 585 | + "Cevabımı nasıl kaydederim?", | ||
| 586 | + "Cevabı kaydet düğmesi ne işe yarar?", | ||
| 587 | + "Sorunun cevabını nasıl işaretlerim?", | ||
| 588 | + "Cevaplar otomatik kaydediliyor mu?", | ||
| 589 | + "Bir soruyu nasıl cevaplarım?", | ||
| 590 | + ], | ||
| 591 | + "must_not_match": ["exam_enter_room", "exam_finish_result"], | ||
| 592 | + }, | ||
| 593 | + { | ||
| 594 | + "intent": "exam_finish_result", | ||
| 595 | + "category": "exams", | ||
| 596 | + "description": "Sınavı bitirme ve sonucu görme.", | ||
| 597 | + "response_id": "exam_finish_instructions", | ||
| 598 | + "response_template": ( | ||
| 599 | + "1) Yan panelde **Sınavı bitir (Finish exam)**'e bas ve onayla; durum " | ||
| 600 | + "**Teslim edildi** olur. 2) Sonucu: girilebilir sınavda sınav odasındaki " | ||
| 601 | + "**Not** alanından, Zamansız sınavda detaydaki **Sonucun (Your result)** " | ||
| 602 | + "bölümünden görürsün. Notlanmadıysa 'Henüz notlanmadı' yazar. Süre kendiliğinden " | ||
| 603 | + "biterse durum 'Süresi doldu' olur." | ||
| 604 | + ), | ||
| 605 | + "auth_required": True, | ||
| 606 | + "min_role": "ogrenci", | ||
| 607 | + "example_questions": [ | ||
| 608 | + "Sınavı nasıl bitiririm?", | ||
| 609 | + "Sınavı teslim etmek istiyorum", | ||
| 610 | + "Sonucumu nereden görürüm?", | ||
| 611 | + "Notumu ne zaman görebilirim?", | ||
| 612 | + "Sınavı sonlandırma", | ||
| 613 | + ], | ||
| 614 | + "must_not_match": ["exam_save_answer", "report_card_view"], | ||
| 615 | + }, | ||
| 616 | + { | ||
| 617 | + "intent": "exam_rejoin_retake", | ||
| 618 | + "category": "exams", | ||
| 619 | + "description": "Sınavdan çıkıp dönme (rejoin) veya yeni deneme (retake).", | ||
| 620 | + "response_id": "exam_rejoin_retake_info", | ||
| 621 | + "response_template": ( | ||
| 622 | + "**Rejoin (aynı denemeye dönüş):** 'Yeniden girişe izin ver' açıksa odadan " | ||
| 623 | + "çıktıktan sonra tekrar **Sınav odasını aç** → **Sınava devam et**; kalan " | ||
| 624 | + "süre ve cevapların korunur. **Retake (yeni deneme):** 'Deneme hakkı' açık ve " | ||
| 625 | + "azami sayı belirlenmişse her yeni giriş bir deneme kullanır. **Süre çıkışta " | ||
| 626 | + "bile durmaz.**" | ||
| 627 | + ), | ||
| 628 | + "auth_required": True, | ||
| 629 | + "min_role": "ogrenci", | ||
| 630 | + "example_questions": [ | ||
| 631 | + "Sınavdan çıkarsam geri girebilir miyim?", | ||
| 632 | + "Sınava tekrar girebilir miyim?", | ||
| 633 | + "Kaldığım yerden devam edebilir miyim?", | ||
| 634 | + "Deneme hakkım var mı?", | ||
| 635 | + "Rejoin nasıl çalışır?", | ||
| 636 | + ], | ||
| 637 | + "must_not_match": ["exam_enter_room", "exam_finish_result"], | ||
| 638 | + }, | ||
| 639 | + { | ||
| 640 | + "intent": "exam_grade_student", | ||
| 641 | + "category": "exams", | ||
| 642 | + "description": "Öğrenciye not verme / notlandırma (Öğretmen+).", | ||
| 643 | + "response_id": "exam_grade_instructions", | ||
| 644 | + "response_template": ( | ||
| 645 | + "Ön koşul: **sınav bitmiş** olmalı (bitene kadar 'Öğrenci notla' düğmesi " | ||
| 646 | + "pasiftir). 1) Sınav detayı → **Öğrenci notla (Grade a student)**. 2) Öğrenciyi " | ||
| 647 | + "seç, **Not** (0–100 tam sayı) gir, kaydet ve onayla. Metin cevaplar otomatik " | ||
| 648 | + "puanlanmaz; **Cevap Kâğıdı**'ndaki otomatik puanı referans alıp nihai notu " | ||
| 649 | + "elle verirsin. Verilen not sonuç tablosunda **Kaldır** ile silinebilir." | ||
| 650 | + ), | ||
| 651 | + "auth_required": True, | ||
| 652 | + "min_role": "ogretmen", | ||
| 653 | + "example_questions": [ | ||
| 654 | + "Öğrenciye nasıl not veririm?", | ||
| 655 | + "Sınavı nasıl notlandırırım?", | ||
| 656 | + "Not girme nerede?", | ||
| 657 | + "Öğrenci notla düğmesi neden pasif?", | ||
| 658 | + "Sınav sonuçlarını nasıl girerim?", | ||
| 659 | + ], | ||
| 660 | + "must_not_match": ["exam_add_question", "student_marks_lookup", "exam_live_monitor"], | ||
| 661 | + }, | ||
| 662 | + { | ||
| 663 | + "intent": "exam_live_monitor", | ||
| 664 | + "category": "exams", | ||
| 665 | + "description": "Sınavı canlı izleme (Öğretmen+).", | ||
| 666 | + "response_id": "exam_live_monitor_info", | ||
| 667 | + "response_template": ( | ||
| 668 | + "Ön koşul: sınav başlamış (Yakında değil) ve girilebilir modda; yönetim " | ||
| 669 | + "yetkisi. Sınav detayı → **Canlı İzleme (Live Monitor)** (`/exams/$id/live`). " | ||
| 670 | + "Üstteki sayaçlar (Başlamadı/Devam ediyor/Teslim edildi/Süresi doldu/Katılmadı) " | ||
| 671 | + "ve **Canlı Liste**'de ilerleme, kalan süre, durum görünür. Sınav bitince ekran " | ||
| 672 | + "'Son Durum'a döner. Öğrenciler bu ekranı göremez." | ||
| 673 | + ), | ||
| 674 | + "auth_required": True, | ||
| 675 | + "min_role": "ogretmen", | ||
| 676 | + "example_questions": [ | ||
| 677 | + "Sınavı canlı nasıl izlerim?", | ||
| 678 | + "Öğrencilerin durumunu anlık görmek istiyorum", | ||
| 679 | + "Canlı izleme nerede?", | ||
| 680 | + "Live monitor nasıl açılır?", | ||
| 681 | + "Kim sınavı bitirmiş görebilir miyim?", | ||
| 682 | + ], | ||
| 683 | + "must_not_match": ["exam_grade_student"], | ||
| 684 | + }, | ||
| 685 | + # --- Karne / notlar ------------------------------------------------------ | ||
| 686 | + { | ||
| 687 | + "intent": "report_card_view", | ||
| 688 | + "category": "marks", | ||
| 689 | + "description": "Öğrencinin kendi karnesini/ortalamasını görmesi.", | ||
| 690 | + "response_id": "report_card_info", | ||
| 691 | + "response_template": ( | ||
| 692 | + "Karneni görmek için menüden **Karnem (Report card)** veya `/marks`'a git. " | ||
| 693 | + "Üstte **Genel ortalama** (sayı + harf notu, /100), altında her ders için " | ||
| 694 | + "**Ders ortalaması** ve sınav bazında **Ağırlık** ve **Not** görünür. Karnem " | ||
| 695 | + "yalnızca Öğrenci rolüne açıktır; notu girilmemiş sınav '—' gösterir." | ||
| 696 | + ), | ||
| 697 | + "auth_required": True, | ||
| 698 | + "min_role": "ogrenci", | ||
| 699 | + "example_questions": [ | ||
| 700 | + "Karnemi nerede görürüm?", | ||
| 701 | + "Notlarımı göster", | ||
| 702 | + "Ortalamam kaç?", | ||
| 703 | + "Ders notlarıma nasıl bakarım?", | ||
| 704 | + "Genel ortalamamı nereden görürüm?", | ||
| 705 | + ], | ||
| 706 | + "must_not_match": ["weighted_average_info", "student_marks_lookup", "exam_finish_result"], | ||
| 707 | + }, | ||
| 708 | + { | ||
| 709 | + "intent": "weighted_average_info", | ||
| 710 | + "category": "marks", | ||
| 711 | + "description": "Ağırlıklı ortalamanın nasıl hesaplandığı.", | ||
| 712 | + "response_id": "weighted_average_explained", | ||
| 713 | + "response_template": ( | ||
| 714 | + "Ders ortalaması, notlanmış sınavların **tür ağırlığıyla** ortalamasıdır: " | ||
| 715 | + "Σ(not×ağırlık)/Σ(ağırlık). Notlanmamış sınavlar atlanır (sıfır sayılmaz). " | ||
| 716 | + "Genel ortalama, dolu ders ortalamalarının düz aritmetik ortalamasıdır. " | ||
| 717 | + "Notlar 0–100 tam sayıdır; harf notu okul ayarındaki not bantlarından gelir." | ||
| 718 | + ), | ||
| 719 | + "auth_required": True, | ||
| 720 | + "min_role": "ogrenci", | ||
| 721 | + "example_questions": [ | ||
| 722 | + "Ortalama nasıl hesaplanıyor?", | ||
| 723 | + "Ağırlıklı ortalama ne demek?", | ||
| 724 | + "Notlar nasıl ağırlıklandırılır?", | ||
| 725 | + "Genel ortalama nasıl çıkıyor?", | ||
| 726 | + "Sınav ağırlığı ortalamayı nasıl etkiler?", | ||
| 727 | + ], | ||
| 728 | + "must_not_match": ["report_card_view"], | ||
| 729 | + }, | ||
| 730 | + { | ||
| 731 | + "intent": "student_marks_lookup", | ||
| 732 | + "category": "marks", | ||
| 733 | + "description": "Öğretmenin bir öğrencinin notunu araması (Öğretmen+).", | ||
| 734 | + "response_id": "student_marks_lookup_instructions", | ||
| 735 | + "response_template": ( | ||
| 736 | + "1) `/management/student-marks` (Öğrenci notları) sayfasını aç. 2) Aramaya " | ||
| 737 | + "**en az 2 karakter** yaz. 3) Öğrenci satırında **Görüntüle**'ye bas; sağdan " | ||
| 738 | + "açılan panelde öğrencinin karnesini görürsün. Bu sayfa Öğretmen ve üstüne açıktır." | ||
| 739 | + ), | ||
| 740 | + "auth_required": True, | ||
| 741 | + "min_role": "ogretmen", | ||
| 742 | + "example_questions": [ | ||
| 743 | + "Bir öğrencinin notunu nasıl görürüm?", | ||
| 744 | + "Öğrenci karnesini nasıl açarım?", | ||
| 745 | + "Öğrenci notları sayfası nerede?", | ||
| 746 | + "Öğrencinin ortalamasına bakmak istiyorum", | ||
| 747 | + "Student marks nerede?", | ||
| 748 | + ], | ||
| 749 | + "must_not_match": ["report_card_view", "student_attendance_lookup", "exam_grade_student"], | ||
| 750 | + }, | ||
| 751 | + # --- Yoklama / etkinlik -------------------------------------------------- | ||
| 752 | + { | ||
| 753 | + "intent": "attendance_view", | ||
| 754 | + "category": "attendance", | ||
| 755 | + "description": "Öğrencinin kendi yoklama raporunu görmesi.", | ||
| 756 | + "response_id": "attendance_report_info", | ||
| 757 | + "response_template": ( | ||
| 758 | + "Kendi yoklamanı görmek için **Yoklama (Attendance)** menüsünden `/attendance`'a " | ||
| 759 | + "git. **Etkinlikler** ve **Ders oturumları** için ayrı devam oranı (%) kartları " | ||
| 760 | + "ve **Ders dökümü** tablosu (ders bazında Var/Yok/Geç/Mazeretli) görürsün. Bu " | ||
| 761 | + "sayfa yalnızca Öğrenci rolüne açıktır." | ||
| 762 | + ), | ||
| 763 | + "auth_required": True, | ||
| 764 | + "min_role": "ogrenci", | ||
| 765 | + "example_questions": [ | ||
| 766 | + "Devamsızlığımı nerede görürüm?", | ||
| 767 | + "Yoklama raporum nerede?", | ||
| 768 | + "Devam oranımı göster", | ||
| 769 | + "Kaç gün devamsızlığım var?", | ||
| 770 | + "Kendi yoklamama nasıl bakarım?", | ||
| 771 | + ], | ||
| 772 | + "must_not_match": ["attendance_rate_info", "student_attendance_lookup", "event_attendance_mark"], | ||
| 773 | + }, | ||
| 774 | + { | ||
| 775 | + "intent": "attendance_rate_info", | ||
| 776 | + "category": "attendance", | ||
| 777 | + "description": "Devam oranının nasıl hesaplandığı.", | ||
| 778 | + "response_id": "attendance_rate_explained", | ||
| 779 | + "response_template": ( | ||
| 780 | + "Devam oranı = (Var + Geç) / (Var + Yok + Geç). Geç kalmak 'katıldı' sayılır; " | ||
| 781 | + "**Mazeretli oranın dışındadır** (ne lehte ne aleyhte). Kayıt yoksa veya " | ||
| 782 | + "tümü mazeretliyse oran boştur. Etkinlik devamı ile ders oturumu devamı ayrı " | ||
| 783 | + "hesaplanır." | ||
| 784 | + ), | ||
| 785 | + "auth_required": True, | ||
| 786 | + "min_role": "ogrenci", | ||
| 787 | + "example_questions": [ | ||
| 788 | + "Devam oranı nasıl hesaplanıyor?", | ||
| 789 | + "Mazeretli sayılınca oranım düşer mi?", | ||
| 790 | + "Geç kalmak devamsızlık mı?", | ||
| 791 | + "Oran neden boş görünüyor?", | ||
| 792 | + "Devam yüzdesi nasıl çıkıyor?", | ||
| 793 | + ], | ||
| 794 | + "must_not_match": ["attendance_view"], | ||
| 795 | + }, | ||
| 796 | + { | ||
| 797 | + "intent": "event_attendance_mark", | ||
| 798 | + "category": "attendance", | ||
| 799 | + "description": "Etkinlikte kendi yoklamasını işaretleme.", | ||
| 800 | + "response_id": "event_attendance_instructions", | ||
| 801 | + "response_template": ( | ||
| 802 | + "1) `/events` → ilgili etkinlik kartına tıkla. 2) **Katılım durumum (My " | ||
| 803 | + "attendance)** bölümünde durumu seç (**Var / Yok / Geç / Mazeretli**). " | ||
| 804 | + "3) **Yoklamamı kaydet (Save my attendance)**. Etkinlikte herkes kendini " | ||
| 805 | + "işaretleyebilir; Öğretmen+ başkasını da işaretleyebilir." | ||
| 806 | + ), | ||
| 807 | + "auth_required": True, | ||
| 808 | + "min_role": "ogrenci", | ||
| 809 | + "example_questions": [ | ||
| 810 | + "Etkinlikte kendimi nasıl işaretlerim?", | ||
| 811 | + "Etkinlik yoklamasına nasıl katılırım?", | ||
| 812 | + "Katılım durumumu nasıl kaydederim?", | ||
| 813 | + "Etkinliğe geldiğimi nasıl belirtirim?", | ||
| 814 | + "Kendi yoklamamı işaretleme", | ||
| 815 | + ], | ||
| 816 | + "must_not_match": ["attendance_view", "roll_call"], | ||
| 817 | + }, | ||
| 818 | + { | ||
| 819 | + "intent": "student_attendance_lookup", | ||
| 820 | + "category": "attendance", | ||
| 821 | + "description": "Öğretmenin bir öğrencinin yoklamasını araması (Öğretmen+).", | ||
| 822 | + "response_id": "student_attendance_lookup_instructions", | ||
| 823 | + "response_template": ( | ||
| 824 | + "1) `/management/student-attendance` (Öğrenci yoklaması) sayfasını aç. " | ||
| 825 | + "2) Aramaya **en az 2 karakter** yaz. 3) Öğrenci satırında **Görüntüle**; " | ||
| 826 | + "sağdan açılan panelde öğrencinin yoklama raporunu görürsün. Öğretmen ve üstüne açıktır." | ||
| 827 | + ), | ||
| 828 | + "auth_required": True, | ||
| 829 | + "min_role": "ogretmen", | ||
| 830 | + "example_questions": [ | ||
| 831 | + "Bir öğrencinin devamsızlığını nasıl görürüm?", | ||
| 832 | + "Öğrenci yoklaması sayfası nerede?", | ||
| 833 | + "Öğrencinin devam durumuna bakmak istiyorum", | ||
| 834 | + "Student attendance nerede?", | ||
| 835 | + "Öğrenci devam raporunu aç", | ||
| 836 | + ], | ||
| 837 | + "must_not_match": ["attendance_view", "student_marks_lookup", "roll_call"], | ||
| 838 | + }, | ||
| 839 | + { | ||
| 840 | + "intent": "event_create", | ||
| 841 | + "category": "events", | ||
| 842 | + "description": "Etkinlik oluşturma (Öğretmen+).", | ||
| 843 | + "response_id": "event_create_instructions", | ||
| 844 | + "response_template": ( | ||
| 845 | + "Ön koşul: Öğretmen+ rolü. 1) `/events` → **Etkinlik oluştur (Create event)**. " | ||
| 846 | + "2) **Başlık** (zorunlu, ≤200), isteğe bağlı açıklama; isteğe bağlı " | ||
| 847 | + "**Başlangıç/Bitiş** tarih+saat. 3) **Oluştur**. Başlık boşsa 'Başlık gerekli'; " | ||
| 848 | + "bitiş başlangıçtan önce olamaz; tarihler gelecekte olmalı." | ||
| 849 | + ), | ||
| 850 | + "auth_required": True, | ||
| 851 | + "min_role": "ogretmen", | ||
| 852 | + "example_questions": [ | ||
| 853 | + "Etkinlik nasıl oluşturulur?", | ||
| 854 | + "Yeni etkinlik eklemek istiyorum", | ||
| 855 | + "Etkinlik oluşturma nerede?", | ||
| 856 | + "Bir buluşma/oturum planlayacağım", | ||
| 857 | + "Event oluşturma", | ||
| 858 | + ], | ||
| 859 | + "must_not_match": ["course_create", "lesson_session_add"], | ||
| 860 | + }, | ||
| 861 | + # --- Defter -------------------------------------------------------------- | ||
| 862 | + { | ||
| 863 | + "intent": "note_create", | ||
| 864 | + "category": "notebook", | ||
| 865 | + "description": "Defterde dosya ekli not oluşturma.", | ||
| 866 | + "response_id": "note_create_instructions", | ||
| 867 | + "response_template": ( | ||
| 868 | + "1) **Defter (Notebook)** menüsünden `/notes`'a git, **Yeni not (New note)**'a " | ||
| 869 | + "bas. 2) **Başlık** (zorunlu, ≤200) ve isteğe bağlı **İçerik** (≤10.000) gir. " | ||
| 870 | + "3) **Ekler** bölümünde **Dosya ekle** ile en fazla 10 dosya ekle. 4) **Oluştur**. " | ||
| 871 | + "Notlar yalnızca sahibine görünür; dosya boyut sınırı okul ayarındandır (varsayılan ~5 MiB)." | ||
| 872 | + ), | ||
| 873 | + "auth_required": True, | ||
| 874 | + "min_role": "ogrenci", | ||
| 875 | + "example_questions": [ | ||
| 876 | + "Nasıl not alırım?", | ||
| 877 | + "Deftere not eklemek istiyorum", | ||
| 878 | + "Not oluşturma nerede?", | ||
| 879 | + "Nota dosya ekleyebilir miyim?", | ||
| 880 | + "Yeni not nasıl yazılır?", | ||
| 881 | + ], | ||
| 882 | + "must_not_match": ["report_card_view"], | ||
| 883 | + }, | ||
| 884 | + # --- Mesai --------------------------------------------------------------- | ||
| 885 | + { | ||
| 886 | + "intent": "work_checkin_out", | ||
| 887 | + "category": "work", | ||
| 888 | + "description": "Kendi mesai giriş/çıkışı (Öğretmen/Yönetici).", | ||
| 889 | + "response_id": "work_checkin_instructions", | ||
| 890 | + "response_template": ( | ||
| 891 | + "Ön koşul: Öğretmen veya Yönetici (ADMIN'de bu sayfa yoktur). 1) `/work` " | ||
| 892 | + "(Mesai) sayfasını aç. 2) 'Giriş yapılmadı' ise **Giriş yap (Check in)**; iş " | ||
| 893 | + "bitince **Çıkış yap (Check out)**. 3) **Son kayıtlar**'da giriş/çıkış/süre ve " | ||
| 894 | + "Açık/Kapalı durumunu görürsün. Saatler sunucu damgalıdır; aynı anda tek açık " | ||
| 895 | + "mesai olabilir." | ||
| 896 | + ), | ||
| 897 | + "auth_required": True, | ||
| 898 | + "min_role": "ogretmen", | ||
| 899 | + "example_questions": [ | ||
| 900 | + "Mesaiye nasıl giriş yaparım?", | ||
| 901 | + "Check in nasıl yapılır?", | ||
| 902 | + "Mesai çıkışı nerede?", | ||
| 903 | + "Giriş-çıkış kaydımı nasıl tutarım?", | ||
| 904 | + "Work log nasıl kullanılır?", | ||
| 905 | + ], | ||
| 906 | + "must_not_match": ["staff_work_manage", "logout_how"], | ||
| 907 | + }, | ||
| 908 | + { | ||
| 909 | + "intent": "staff_work_manage", | ||
| 910 | + "category": "work", | ||
| 911 | + "description": "Personel mesai kayıtlarını görme/düzeltme (Yönetici+).", | ||
| 912 | + "response_id": "staff_work_instructions", | ||
| 913 | + "response_template": ( | ||
| 914 | + "Ön koşul: Yönetici veya ADMIN. 1) `/management/staff-work` (Personel mesai) → " | ||
| 915 | + "aramaya **en az 2 karakter** (öğretmen adı). 2) Öğretmen satırında **Görüntüle**. " | ||
| 916 | + "3) **Kapalı** bir kaydın **Düzenle**'sini açıp giriş/çıkış tarih+saat düzelt, " | ||
| 917 | + "**Güncelle**. **Açık mesai düzeltilemez** (önce çıkış yapılmalı veya silinmeli); " | ||
| 918 | + "çıkış girişten önce olamaz." | ||
| 919 | + ), | ||
| 920 | + "auth_required": True, | ||
| 921 | + "min_role": "yonetici", | ||
| 922 | + "example_questions": [ | ||
| 923 | + "Personel mesaisini nasıl düzeltirim?", | ||
| 924 | + "Bir öğretmenin mesai kaydını görmek istiyorum", | ||
| 925 | + "Staff work nerede?", | ||
| 926 | + "Kapalı mesaiyi nasıl düzenlerim?", | ||
| 927 | + "Personel mesai kaydı silme", | ||
| 928 | + ], | ||
| 929 | + "must_not_match": ["work_checkin_out"], | ||
| 930 | + }, | ||
| 931 | + # --- Yönetim ------------------------------------------------------------- | ||
| 932 | + { | ||
| 933 | + "intent": "term_manage", | ||
| 934 | + "category": "management", | ||
| 935 | + "description": "Akademik dönem oluşturma/derse bağlama (Yönetici+).", | ||
| 936 | + "response_id": "term_manage_instructions", | ||
| 937 | + "response_template": ( | ||
| 938 | + "Ön koşul: Yönetici veya ADMIN. 1) `/management/terms` (Dönemler) → **Dönem " | ||
| 939 | + "oluştur (Create term)**. 2) **Ad**, **Başlangıç**, **Bitiş** (GG/AA/YYYY) gir; " | ||
| 940 | + "bitiş başlangıçtan önce olamaz (tarihler geçmişte olabilir). 3) **Oluştur**. " | ||
| 941 | + "Dersi döneme bağlamak, ders oluşturma/düzenleme formundaki **Dönem** seçicisinden " | ||
| 942 | + "yapılır. Dönem silinince bağlı dersler silinmez, 'Atanmamış' olur." | ||
| 943 | + ), | ||
| 944 | + "auth_required": True, | ||
| 945 | + "min_role": "yonetici", | ||
| 946 | + "example_questions": [ | ||
| 947 | + "Dönem nasıl oluşturulur?", | ||
| 948 | + "Akademik dönem eklemek istiyorum", | ||
| 949 | + "Dersi döneme nasıl bağlarım?", | ||
| 950 | + "Yarıyıl oluşturma nerede?", | ||
| 951 | + "Terms sayfası nerede?", | ||
| 952 | + ], | ||
| 953 | + "must_not_match": ["school_settings", "course_create"], | ||
| 954 | + }, | ||
| 955 | + { | ||
| 956 | + "intent": "school_settings", | ||
| 957 | + "category": "management", | ||
| 958 | + "description": "Okul ayarlarını değiştirme (Yönetici+).", | ||
| 959 | + "response_id": "school_settings_instructions", | ||
| 960 | + "response_template": ( | ||
| 961 | + "Ön koşul: Yönetici veya ADMIN. `/management/settings` (Okul ayarları) sayfasında " | ||
| 962 | + "**Sınav türleri** (Ad + Ağırlık 1–100), **Yoklama durumları** (Var/Yok/Geç/" | ||
| 963 | + "Mazeretli kilitlidir, silinemez), **Not bantları** (Alt sınır + Etiket) ve " | ||
| 964 | + "**Not dosyası boyut sınırı** (0.001–25 MiB) yönetilir. **Satır ekle** ile ekle, " | ||
| 965 | + "çöp kutusuyla sil, sonra **Kaydet**. Kaydet yalnızca değişiklik varken aktiftir." | ||
| 966 | + ), | ||
| 967 | + "auth_required": True, | ||
| 968 | + "min_role": "yonetici", | ||
| 969 | + "example_questions": [ | ||
| 970 | + "Okul ayarlarını nasıl değiştiririm?", | ||
| 971 | + "Sınav türü ağırlığını nereden ayarlarım?", | ||
| 972 | + "Not bantlarını düzenlemek istiyorum", | ||
| 973 | + "Yoklama durumu eklemek istiyorum", | ||
| 974 | + "Settings sayfası nerede?", | ||
| 975 | + ], | ||
| 976 | + "must_not_match": ["term_manage", "language_theme"], | ||
| 977 | + }, | ||
| 978 | + { | ||
| 979 | + "intent": "user_role_change", | ||
| 980 | + "category": "management", | ||
| 981 | + "description": "Kullanıcı rolü değiştirme (ADMIN).", | ||
| 982 | + "response_id": "user_role_change_instructions", | ||
| 983 | + "response_template": ( | ||
| 984 | + "Ön koşul: ADMIN. 1) `/admin/users` (Kullanıcılar) sayfasını aç, gerekirse " | ||
| 985 | + "kullanıcı adına göre ara. 2) Satırdaki rol menüsünden yeni rolü seç. 3) Beliren " | ||
| 986 | + "**Güncelle (Update)**'ye bas ve onayla. **Kendi rolünü değiştiremezsin** (kendi " | ||
| 987 | + "satırında menü pasiftir); rol değişmeden 'Güncelle' görünmez. Değişiklik bir " | ||
| 988 | + "sonraki işlemde hemen geçerli olur." | ||
| 989 | + ), | ||
| 990 | + "auth_required": True, | ||
| 991 | + "min_role": "admin", | ||
| 992 | + "example_questions": [ | ||
| 993 | + "Bir kullanıcının rolünü nasıl değiştiririm?", | ||
| 994 | + "Öğretmen rolü nasıl atanır?", | ||
| 995 | + "Kullanıcıyı yönetici yapmak istiyorum", | ||
| 996 | + "Rol yükseltme nerede?", | ||
| 997 | + "Users sayfasından rol değiştirme", | ||
| 998 | + ], | ||
| 999 | + "must_not_match": ["roles_permissions", "profile_edit"], | ||
| 1000 | + }, | ||
| 1001 | + # --- Güvenlik ------------------------------------------------------------ | ||
| 1002 | + { | ||
| 1003 | + "intent": "privacy_security", | ||
| 1004 | + "category": "security", | ||
| 1005 | + "description": "Başkasının verisini isteme / gizlilik-güvenlik.", | ||
| 1006 | + "response_id": "privacy_policy_message", | ||
| 1007 | + "response_template": ( | ||
| 1008 | + "Yalnızca kendi yetkili olduğun bilgileri görebilirsin. Başka bir kullanıcının " | ||
| 1009 | + "notu, yoklaması veya kişisel bilgisi paylaşılmaz. Öğretmen ve üstü roller, " | ||
| 1010 | + "yalnızca yetkili oldukları yönetim sayfalarından (Öğrenci notları/yoklaması) " | ||
| 1011 | + "öğrenci verisine erişebilir; kişisel telefon/e-posta paylaşılmaz." | ||
| 1012 | + ), | ||
| 1013 | + "auth_required": False, | ||
| 1014 | + "min_role": "ziyaretci", | ||
| 1015 | + "example_questions": [ | ||
| 1016 | + "Arkadaşımın notlarını göster", | ||
| 1017 | + "Başka bir öğrencinin devamsızlığı kaç?", | ||
| 1018 | + "Bir öğrencinin telefonunu verir misin?", | ||
| 1019 | + "Sınıftaki herkesin notlarını göster", | ||
| 1020 | + "Verilerim güvende mi?", | ||
| 1021 | + ], | ||
| 1022 | + "must_not_match": ["student_marks_lookup", "student_attendance_lookup", "account_access_problem"], | ||
| 1023 | + }, | ||
| 1024 | +] | ||
| 1025 | + | ||
| 1026 | + | ||
| 1027 | +FALLBACK: Final[dict[str, str]] = { | ||
| 1028 | + "response_id": "fallback_clarification", | ||
| 1029 | + "response_template": ( | ||
| 1030 | + "Bu isteği tam anlayamadım. Hezarfen'de ders, sınav, karne, yoklama, defter, " | ||
| 1031 | + "mesai veya hesap ayarları hakkında 'nasıl yaparım?' tarzında daha açık bir " | ||
| 1032 | + "soru sorabilir misin?" | ||
| 1033 | + ), | ||
| 1034 | +} | ||
| 1035 | + | ||
| 1036 | + | ||
| 1037 | +# --- Yardımcı fonksiyonlar --------------------------------------------------- | ||
| 1038 | +def role_rank(role: str) -> int: | ||
| 1039 | + """Rolün hiyerarşideki sırasını döndürür. | ||
| 1040 | + | ||
| 1041 | + Raises: | ||
| 1042 | + KeyError: Bilinmeyen rol adı verilirse. | ||
| 1043 | + """ | ||
| 1044 | + | ||
| 1045 | + return _ROLE_RANK[role] | ||
| 1046 | + | ||
| 1047 | + | ||
| 1048 | +def is_known_role(role: str) -> bool: | ||
| 1049 | + """Verilen rolün hiyerarşide tanımlı olup olmadığını döndürür.""" | ||
| 1050 | + | ||
| 1051 | + return role in _ROLE_RANK | ||
| 1052 | + | ||
| 1053 | + | ||
| 1054 | +def meets_role(user_role: str, required_role: str) -> bool: | ||
| 1055 | + """user_role, required_role'ün gerektirdiği yetkiye sahip mi? | ||
| 1056 | + | ||
| 1057 | + Raises: | ||
| 1058 | + KeyError: Rollerden biri bilinmiyorsa. | ||
| 1059 | + """ | ||
| 1060 | + | ||
| 1061 | + return role_rank(user_role) >= role_rank(required_role) | ||
| 1062 | + | ||
| 1063 | + | ||
| 1064 | +def get_intent(intent_name: str) -> dict[str, Any] | None: | ||
| 1065 | + """Intent adına göre katalog kaydını döndürür (yoksa None).""" | ||
| 1066 | + | ||
| 1067 | + return next((item for item in INTENTS if item["intent"] == intent_name), None) | ||
| 1068 | + | ||
| 1069 | + | ||
| 1070 | +def list_intent_names() -> list[str]: | ||
| 1071 | + """Katalogdaki tüm intent adlarını sırasıyla döndürür.""" | ||
| 1072 | + | ||
| 1073 | + return [item["intent"] for item in INTENTS] | ||
| 1074 | + | ||
| 1075 | + | ||
| 1076 | +def _duplicates(values: list[str]) -> list[str]: | ||
| 1077 | + """Tekrarlanan değerleri deterministik sırayla döndürür.""" | ||
| 1078 | + | ||
| 1079 | + counts = Counter(values) | ||
| 1080 | + return sorted(value for value, count in counts.items() if count > 1) | ||
| 1081 | + | ||
| 1082 | + | ||
| 1083 | +def validate_catalog() -> dict[str, int]: | ||
| 1084 | + """Kural motorunun gerektirdiği katalog değişmezlerini doğrular. | ||
| 1085 | + | ||
| 1086 | + Returns: | ||
| 1087 | + Sayımlar: intent_count, response_count, example_question_count, category_count. | ||
| 1088 | + | ||
| 1089 | + Raises: | ||
| 1090 | + ValueError: Katalog eksik, tutarsız veya belirsizse. | ||
| 1091 | + """ | ||
| 1092 | + | ||
| 1093 | + if not INTENTS: | ||
| 1094 | + raise ValueError("Intent kataloğu boş olamaz.") | ||
| 1095 | + | ||
| 1096 | + errors: list[str] = [] | ||
| 1097 | + intent_names: list[str] = [] | ||
| 1098 | + response_ids: list[str] = [] | ||
| 1099 | + questions: list[str] = [] | ||
| 1100 | + categories: set[str] = set() | ||
| 1101 | + | ||
| 1102 | + for index, item in enumerate(INTENTS): | ||
| 1103 | + missing_fields = REQUIRED_INTENT_FIELDS.difference(item) | ||
| 1104 | + if missing_fields: | ||
| 1105 | + errors.append(f"INTENTS[{index}] eksik alanlar: {', '.join(sorted(missing_fields))}") | ||
| 1106 | + continue | ||
| 1107 | + | ||
| 1108 | + name = item["intent"] | ||
| 1109 | + intent_names.append(name) | ||
| 1110 | + response_ids.append(item["response_id"]) | ||
| 1111 | + categories.add(item["category"]) | ||
| 1112 | + | ||
| 1113 | + examples = item["example_questions"] | ||
| 1114 | + if not examples: | ||
| 1115 | + errors.append(f"{name}: en az bir örnek soru gerekli.") | ||
| 1116 | + if any(not isinstance(q, str) or not q.strip() for q in examples): | ||
| 1117 | + errors.append(f"{name}: boş veya metin olmayan örnek soru var.") | ||
| 1118 | + questions.extend(examples) | ||
| 1119 | + | ||
| 1120 | + # Rol geçerliliği. | ||
| 1121 | + min_role = item["min_role"] | ||
| 1122 | + if not is_known_role(min_role): | ||
| 1123 | + errors.append(f"{name}: bilinmeyen min_role '{min_role}'.") | ||
| 1124 | + continue | ||
| 1125 | + | ||
| 1126 | + # auth_required ile min_role tutarlılığı. | ||
| 1127 | + expected_auth = role_rank(min_role) >= role_rank(MIN_AUTHENTICATED_ROLE) | ||
| 1128 | + if bool(item["auth_required"]) != expected_auth: | ||
| 1129 | + errors.append( | ||
| 1130 | + f"{name}: auth_required={item['auth_required']} ile min_role='{min_role}' " | ||
| 1131 | + f"tutarsız (beklenen auth_required={expected_auth})." | ||
| 1132 | + ) | ||
| 1133 | + | ||
| 1134 | + duplicate_intents = _duplicates(intent_names) | ||
| 1135 | + duplicate_responses = _duplicates(response_ids) | ||
| 1136 | + duplicate_questions = _duplicates(questions) | ||
| 1137 | + known_intents = set(intent_names) | ||
| 1138 | + | ||
| 1139 | + if duplicate_intents: | ||
| 1140 | + errors.append(f"Tekrarlanan intent: {duplicate_intents}") | ||
| 1141 | + if duplicate_responses: | ||
| 1142 | + errors.append(f"Tekrarlanan response_id: {duplicate_responses}") | ||
| 1143 | + if duplicate_questions: | ||
| 1144 | + errors.append(f"Tekrarlanan örnek soru: {duplicate_questions}") | ||
| 1145 | + | ||
| 1146 | + for item in INTENTS: | ||
| 1147 | + targets = set(item.get("must_not_match", [])) | ||
| 1148 | + unknown_targets = targets.difference(known_intents) | ||
| 1149 | + if unknown_targets: | ||
| 1150 | + errors.append( | ||
| 1151 | + f"{item.get('intent', '<unknown>')}: bilinmeyen must_not_match " | ||
| 1152 | + f"hedefleri: {sorted(unknown_targets)}" | ||
| 1153 | + ) | ||
| 1154 | + if item.get("intent") in targets: | ||
| 1155 | + errors.append(f"{item.get('intent')}: must_not_match kendini içeremez.") | ||
| 1156 | + | ||
| 1157 | + if not FALLBACK.get("response_id") or not FALLBACK.get("response_template"): | ||
| 1158 | + errors.append("Fallback cevabı eksik.") | ||
| 1159 | + | ||
| 1160 | + if errors: | ||
| 1161 | + raise ValueError("Katalog doğrulanamadı:\n- " + "\n- ".join(errors)) | ||
| 1162 | + | ||
| 1163 | + return { | ||
| 1164 | + "intent_count": len(intent_names), | ||
| 1165 | + "response_count": len(response_ids), | ||
| 1166 | + "example_question_count": len(questions), | ||
| 1167 | + "category_count": len(categories), | ||
| 1168 | + } | ||
src/cli.pyadded+123 -0
| @@ -0,0 +1,123 @@ | |||
| 1 | +"""Terminal (CLI) frontend — Hezarfen kullanım asistanı. | ||
| 2 | + | ||
| 3 | +Backend'e (Engine) YALNIZCA istek/yanıt sözleşmesiyle bağlanır; iç katmanları | ||
| 4 | +bilmez. Etkileşimli sohbet döngüsü + rol simülasyonu + komutlar. | ||
| 5 | + | ||
| 6 | +Komutlar: | ||
| 7 | + /rol <rol> -> oturum rolünü değiştir (ziyaretci/ogrenci/ogretmen/yonetici/admin) | ||
| 8 | + /roller -> geçerli rolleri listele | ||
| 9 | + /yardim -> yardım | ||
| 10 | + /cikis -> çık | ||
| 11 | +""" | ||
| 12 | + | ||
| 13 | +from __future__ import annotations | ||
| 14 | + | ||
| 15 | +from typing import Any, Callable | ||
| 16 | + | ||
| 17 | +from .catalog import ROLE_HIERARCHY | ||
| 18 | +from .engine import Engine, RequestError | ||
| 19 | + | ||
| 20 | +_EXIT_COMMANDS = {"/cikis", "/çıkış", "/quit", "/exit"} | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class ChatSession: | ||
| 24 | + """Terminal oturum durumu (rol) + backend'e köprü.""" | ||
| 25 | + | ||
| 26 | + def __init__(self, engine: Engine | None = None, role: str = "ziyaretci") -> None: | ||
| 27 | + self._engine = engine or Engine() | ||
| 28 | + self.role = role | ||
| 29 | + self.authenticated = role != "ziyaretci" | ||
| 30 | + | ||
| 31 | + def set_role(self, role: str) -> str: | ||
| 32 | + if role not in ROLE_HIERARCHY: | ||
| 33 | + return f"Bilinmeyen rol: {role!r}. Geçerli: {', '.join(ROLE_HIERARCHY)}" | ||
| 34 | + self.role = role | ||
| 35 | + self.authenticated = role != "ziyaretci" | ||
| 36 | + return f"Rol ayarlandı: {role} (authenticated={self.authenticated})" | ||
| 37 | + | ||
| 38 | + def ask(self, query: str) -> dict[str, Any]: | ||
| 39 | + return self._engine.handle( | ||
| 40 | + { | ||
| 41 | + "query": query, | ||
| 42 | + "session": {"role": self.role, "authenticated": self.authenticated}, | ||
| 43 | + } | ||
| 44 | + ) | ||
| 45 | + | ||
| 46 | + @staticmethod | ||
| 47 | + def format_response(resp: dict[str, Any]) -> str: | ||
| 48 | + tag = "fallback" if resp["fallback"] else resp["intent"] | ||
| 49 | + return f"[{tag}] {resp['text']}" | ||
| 50 | + | ||
| 51 | + def handle_line(self, line: str) -> tuple[str | None, bool]: | ||
| 52 | + """Bir girdi satırını işler. Döner: (gösterilecek_metin, çıkılsın_mı).""" | ||
| 53 | + | ||
| 54 | + line = line.strip() | ||
| 55 | + if not line: | ||
| 56 | + return None, False | ||
| 57 | + | ||
| 58 | + if line in _EXIT_COMMANDS: | ||
| 59 | + return "Görüşürüz!", True | ||
| 60 | + | ||
| 61 | + if line.startswith("/"): | ||
| 62 | + return self._handle_command(line), False | ||
| 63 | + | ||
| 64 | + try: | ||
| 65 | + resp = self.ask(line) | ||
| 66 | + except RequestError as exc: | ||
| 67 | + return f"Hata: {exc}", False | ||
| 68 | + return self.format_response(resp), False | ||
| 69 | + | ||
| 70 | + def _handle_command(self, line: str) -> str: | ||
| 71 | + parts = line.split() | ||
| 72 | + cmd = parts[0].lower() | ||
| 73 | + if cmd in {"/rol", "/role"}: | ||
| 74 | + if len(parts) < 2: | ||
| 75 | + return "Kullanım: /rol <ziyaretci|ogrenci|ogretmen|yonetici|admin>" | ||
| 76 | + return self.set_role(parts[1].lower()) | ||
| 77 | + if cmd in {"/roller", "/roles"}: | ||
| 78 | + return "Geçerli roller: " + ", ".join(ROLE_HIERARCHY) | ||
| 79 | + if cmd in {"/yardim", "/help"}: | ||
| 80 | + return _HELP_TEXT | ||
| 81 | + return f"Bilinmeyen komut: {cmd}. /yardim yaz." | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +_HELP_TEXT = ( | ||
| 85 | + "Hezarfen kullanım asistanı. Bir soru yaz (ör. 'sınav nasıl oluşturulur').\n" | ||
| 86 | + "Komutlar: /rol <rol>, /roller, /yardim, /cikis" | ||
| 87 | +) | ||
| 88 | + | ||
| 89 | +_BANNER = ( | ||
| 90 | + "=== Hezarfen Kullanım Asistanı (terminal) ===\n" | ||
| 91 | + "Rolünü /rol ile ayarla, soru sor. Çıkış: /cikis\n" | ||
| 92 | +) | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +def run( | ||
| 96 | + session: ChatSession | None = None, | ||
| 97 | + input_fn: Callable[[str], str] = input, | ||
| 98 | + output_fn: Callable[[str], None] = print, | ||
| 99 | +) -> None: | ||
| 100 | + """Etkileşimli sohbet döngüsü (input/output enjekte edilebilir -> test edilebilir).""" | ||
| 101 | + | ||
| 102 | + session = session or ChatSession() | ||
| 103 | + output_fn(_BANNER) | ||
| 104 | + while True: | ||
| 105 | + try: | ||
| 106 | + line = input_fn(f"({session.role}) > ") | ||
| 107 | + except (EOFError, KeyboardInterrupt): | ||
| 108 | + output_fn("\nGörüşürüz!") | ||
| 109 | + return | ||
| 110 | + text, should_exit = session.handle_line(line) | ||
| 111 | + if text is not None: | ||
| 112 | + output_fn(text) | ||
| 113 | + if should_exit: | ||
| 114 | + return | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +def main() -> int: | ||
| 118 | + run() | ||
| 119 | + return 0 | ||
| 120 | + | ||
| 121 | + | ||
| 122 | +if __name__ == "__main__": | ||
| 123 | + raise SystemExit(main()) | ||
src/decision.pyadded+180 -0
| @@ -0,0 +1,180 @@ | |||
| 1 | +"""Karar katmanı: kural + benzerlik katmanlarını nihai bir karara bağlar. | ||
| 2 | + | ||
| 3 | +Akış: | ||
| 4 | + 1) Kural katmanı bir intent döndürürse onu kullan (yüksek kesinlik). | ||
| 5 | + 2) Aksi hâlde benzerlik katmanının en iyi skoru: | ||
| 6 | + - eşiğin (threshold) altındaysa -> FALLBACK (kapsam dışı / emin değil). | ||
| 7 | + - eşiğin üstündeyse -> o intent; en yakın iki skor birbirine çok yakın ve | ||
| 8 | + çift `must_not_match`'te işaretliyse tie-break olarak KAYDEDİLİR. | ||
| 9 | + 3) Rol gating: seçilen intent oturum/rol gerektiriyor ve kullanıcı yetersizse | ||
| 10 | + auth_action belirlenir (intent yine döner; ne gösterileceğine cevap katmanı karar verir). | ||
| 11 | + | ||
| 12 | +Eşik/margin parametreleri Aşama 11'de benchmark üzerinde ayarlanacaktır; buradaki | ||
| 13 | +varsayılanlar makul bir başlangıçtır. | ||
| 14 | +""" | ||
| 15 | + | ||
| 16 | +from __future__ import annotations | ||
| 17 | + | ||
| 18 | +from dataclasses import dataclass, replace | ||
| 19 | +from typing import Final | ||
| 20 | + | ||
| 21 | +from . import rules | ||
| 22 | +from .catalog import ( | ||
| 23 | + MIN_AUTHENTICATED_ROLE, | ||
| 24 | + get_intent, | ||
| 25 | + meets_role, | ||
| 26 | + role_rank, | ||
| 27 | +) | ||
| 28 | +from .domain import is_in_domain | ||
| 29 | +from .similarity import ScoredIntent, SimilarityMatcher, get_default_matcher | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +# Varsayılan parametreler (Aşama 11'de benchmark taramasıyla seçildi). | ||
| 33 | +# 0.18 + domain-gate: coverage %100, acc-on-covered ~%80, OOS recall ~%78, | ||
| 34 | +# false-fallback 0. (Domain-gate olmadan OOS recall yalnızca ~%44'tü.) | ||
| 35 | +DEFAULT_THRESHOLD: Final[float] = 0.18 | ||
| 36 | +DEFAULT_TIE_MARGIN: Final[float] = 0.05 | ||
| 37 | +DEFAULT_TOP_K: Final[int] = 3 | ||
| 38 | + | ||
| 39 | +# auth_action değerleri | ||
| 40 | +LOGIN_REQUIRED: Final[str] = "login_required" | ||
| 41 | +ROLE_INSUFFICIENT: Final[str] = "role_insufficient" | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +@dataclass(frozen=True) | ||
| 45 | +class Decision: | ||
| 46 | + """Karar katmanının çıktısı (loglanabilir).""" | ||
| 47 | + | ||
| 48 | + intent: str | None | ||
| 49 | + fallback: bool | ||
| 50 | + source: str # "rule" | "similarity" | "fallback" | ||
| 51 | + confidence: float | ||
| 52 | + top_k: tuple[ScoredIntent, ...] = () | ||
| 53 | + margin: float | None = None | ||
| 54 | + tie_break: str | None = None | ||
| 55 | + auth_action: str | None = None # None | LOGIN_REQUIRED | ROLE_INSUFFICIENT | ||
| 56 | + required_role: str | None = None | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def _apply_role_gating( | ||
| 60 | + decision: Decision, role: str, authenticated: bool | ||
| 61 | +) -> Decision: | ||
| 62 | + """Seçilen intent için oturum/rol yeterliliğini değerlendirir.""" | ||
| 63 | + | ||
| 64 | + if decision.fallback or decision.intent is None: | ||
| 65 | + return decision | ||
| 66 | + | ||
| 67 | + info = get_intent(decision.intent) | ||
| 68 | + if info is None: | ||
| 69 | + return decision | ||
| 70 | + | ||
| 71 | + auth_required = bool(info["auth_required"]) | ||
| 72 | + min_role = info["min_role"] | ||
| 73 | + | ||
| 74 | + if auth_required and not authenticated: | ||
| 75 | + return replace(decision, auth_action=LOGIN_REQUIRED, required_role=min_role) | ||
| 76 | + | ||
| 77 | + effective_role = role if authenticated else "ziyaretci" | ||
| 78 | + if authenticated and not meets_role(effective_role, min_role): | ||
| 79 | + return replace(decision, auth_action=ROLE_INSUFFICIENT, required_role=min_role) | ||
| 80 | + | ||
| 81 | + return decision | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def _is_confusable_pair(intent_a: str, intent_b: str) -> bool: | ||
| 85 | + """İki intent must_not_match ile (herhangi yönde) karışabilir işaretli mi?""" | ||
| 86 | + | ||
| 87 | + info_a = get_intent(intent_a) | ||
| 88 | + info_b = get_intent(intent_b) | ||
| 89 | + a_targets = set(info_a.get("must_not_match", [])) if info_a else set() | ||
| 90 | + b_targets = set(info_b.get("must_not_match", [])) if info_b else set() | ||
| 91 | + return intent_b in a_targets or intent_a in b_targets | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def decide_core( | ||
| 95 | + rule_match: "rules.RuleMatch | None", | ||
| 96 | + ranked: list[ScoredIntent] | None, | ||
| 97 | + role: str, | ||
| 98 | + authenticated: bool, | ||
| 99 | + *, | ||
| 100 | + in_domain: bool = True, | ||
| 101 | + threshold: float = DEFAULT_THRESHOLD, | ||
| 102 | + tie_margin: float = DEFAULT_TIE_MARGIN, | ||
| 103 | + top_k: int = DEFAULT_TOP_K, | ||
| 104 | +) -> Decision: | ||
| 105 | + """Önceden hesaplanmış kural/benzerlik sonuçlarından nihai kararı üretir. | ||
| 106 | + | ||
| 107 | + Karar mantığının tek yetkili yeri; hem `decide` hem de loglama boru hattı | ||
| 108 | + (per-stage zamanlama için) bunu kullanır. | ||
| 109 | + | ||
| 110 | + in_domain=False ise (alan kapısı) benzerlik skoru yüksek olsa bile FALLBACK'e | ||
| 111 | + düşülür — kural katmanı bu kapıdan muaftır (yüksek kesinlik). | ||
| 112 | + """ | ||
| 113 | + | ||
| 114 | + if rule_match is not None: | ||
| 115 | + decision = Decision( | ||
| 116 | + intent=rule_match.intent, | ||
| 117 | + fallback=False, | ||
| 118 | + source="rule", | ||
| 119 | + confidence=1.0, | ||
| 120 | + ) | ||
| 121 | + return _apply_role_gating(decision, role, authenticated) | ||
| 122 | + | ||
| 123 | + if not ranked: | ||
| 124 | + return Decision(intent=None, fallback=True, source="fallback", confidence=0.0) | ||
| 125 | + | ||
| 126 | + top1 = ranked[0] | ||
| 127 | + if (not in_domain) or top1.score < threshold: | ||
| 128 | + return Decision( | ||
| 129 | + intent=None, | ||
| 130 | + fallback=True, | ||
| 131 | + source="fallback", | ||
| 132 | + confidence=top1.score, | ||
| 133 | + top_k=tuple(ranked[:top_k]), | ||
| 134 | + ) | ||
| 135 | + | ||
| 136 | + margin: float | None = None | ||
| 137 | + tie_break: str | None = None | ||
| 138 | + if len(ranked) >= 2: | ||
| 139 | + margin = top1.score - ranked[1].score | ||
| 140 | + if margin < tie_margin and _is_confusable_pair(top1.intent, ranked[1].intent): | ||
| 141 | + tie_break = f"{top1.intent}~{ranked[1].intent}" | ||
| 142 | + | ||
| 143 | + decision = Decision( | ||
| 144 | + intent=top1.intent, | ||
| 145 | + fallback=False, | ||
| 146 | + source="similarity", | ||
| 147 | + confidence=top1.score, | ||
| 148 | + top_k=tuple(ranked[:top_k]), | ||
| 149 | + margin=margin, | ||
| 150 | + tie_break=tie_break, | ||
| 151 | + ) | ||
| 152 | + return _apply_role_gating(decision, role, authenticated) | ||
| 153 | + | ||
| 154 | + | ||
| 155 | +def decide( | ||
| 156 | + query: str, | ||
| 157 | + role: str = "ziyaretci", | ||
| 158 | + authenticated: bool = False, | ||
| 159 | + *, | ||
| 160 | + matcher: SimilarityMatcher | None = None, | ||
| 161 | + threshold: float = DEFAULT_THRESHOLD, | ||
| 162 | + tie_margin: float = DEFAULT_TIE_MARGIN, | ||
| 163 | + top_k: int = DEFAULT_TOP_K, | ||
| 164 | +) -> Decision: | ||
| 165 | + """Bir sorgu için nihai kararı üretir.""" | ||
| 166 | + | ||
| 167 | + matcher = matcher or get_default_matcher() | ||
| 168 | + rule_match = rules.match(query) | ||
| 169 | + ranked = None if rule_match is not None else matcher.rank(query) | ||
| 170 | + in_domain = True if rule_match is not None else is_in_domain(query) | ||
| 171 | + return decide_core( | ||
| 172 | + rule_match, | ||
| 173 | + ranked, | ||
| 174 | + role, | ||
| 175 | + authenticated, | ||
| 176 | + in_domain=in_domain, | ||
| 177 | + threshold=threshold, | ||
| 178 | + tie_margin=tie_margin, | ||
| 179 | + top_k=top_k, | ||
| 180 | + ) | ||
src/domain.pyadded+90 -0
| @@ -0,0 +1,90 @@ | |||
| 1 | +"""Alan (domain) kapısı: sorgu Hezarfen alanına ait mi? | ||
| 2 | + | ||
| 3 | +OOS (kapsam dışı) tespitini güçlendirir. Char n-gram benzerliği, ortak Türkçe | ||
| 4 | +diziler yüzünden alakasız sorulara da skor verdiğinden tek başına eşik yetmez. | ||
| 5 | +Buradaki kapı basit ama etkili bir sinyaldir: sorgunun içerik kelimeleri (jenerik | ||
| 6 | +bağlaçlar/soru kalıpları çıkarıldıktan sonra) katalog söz varlığıyla hiç örtüşmüyorsa | ||
| 7 | +soru büyük olasılıkla kapsam dışıdır. | ||
| 8 | + | ||
| 9 | +Söz varlığı `example_questions`'ın katlanmış tokenlarından üretilir; jenerik | ||
| 10 | +kelimeler (nasıl, nerede, bir, ...) elenir çünkü onlar hem in-scope hem OOS'ta | ||
| 11 | +bulunur ve ayırt edici değildir. | ||
| 12 | +""" | ||
| 13 | + | ||
| 14 | +from __future__ import annotations | ||
| 15 | + | ||
| 16 | +from typing import Final | ||
| 17 | + | ||
| 18 | +from .catalog import INTENTS | ||
| 19 | +from .normalize import folded_tokens | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +_MIN_TOKEN_LEN: Final[int] = 3 | ||
| 23 | + | ||
| 24 | +# Jenerik/işlevsel kelimeler (katlanmış). Hem in-scope hem OOS'ta geçtikleri için | ||
| 25 | +# alan sinyali taşımazlar; söz varlığından ve sorgu içerik tokenlarından elenir. | ||
| 26 | +STOPWORDS: Final[frozenset[str]] = frozenset( | ||
| 27 | + { | ||
| 28 | + "nasil", "nerede", "nedir", "hangi", "kac", "kacta", "neden", | ||
| 29 | + "istiyorum", "ister", "isterim", "gosterir", "goster", "gormek", "gorurum", | ||
| 30 | + "var", "yok", "mumkun", "olur", "olacak", "olabilir", "yapmak", "yapilir", | ||
| 31 | + "edebilir", "misin", "miyim", "muyum", "musun", "mi", "mu", | ||
| 32 | + "bir", "bana", "benim", "sen", "ben", "ile", "icin", "daha", "cok", | ||
| 33 | + "bu", "sunu", "sonra", "once", "gibi", "kadar", "ama", "veya", | ||
| 34 | + "lazim", "gerek", "acaba", "peki", "yeni", | ||
| 35 | + } | ||
| 36 | +) | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def _content_tokens(text: str) -> list[str]: | ||
| 40 | + """Sorgunun ayırt edici (jenerik olmayan, >=3 harf) içerik tokenları.""" | ||
| 41 | + | ||
| 42 | + return [ | ||
| 43 | + token | ||
| 44 | + for token in folded_tokens(text) | ||
| 45 | + if len(token) >= _MIN_TOKEN_LEN and token not in STOPWORDS | ||
| 46 | + ] | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def build_domain_vocab() -> set[str]: | ||
| 50 | + """Katalog örneklerinden ayırt edici alan söz varlığını üretir.""" | ||
| 51 | + | ||
| 52 | + vocab: set[str] = set() | ||
| 53 | + for item in INTENTS: | ||
| 54 | + for question in item["example_questions"]: | ||
| 55 | + vocab.update(_content_tokens(question)) | ||
| 56 | + return vocab | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +_DEFAULT_VOCAB: set[str] | None = None | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +def get_domain_vocab() -> set[str]: | ||
| 63 | + """Paylaşılan alan söz varlığını döndürür (tembel kurulum).""" | ||
| 64 | + | ||
| 65 | + global _DEFAULT_VOCAB | ||
| 66 | + if _DEFAULT_VOCAB is None: | ||
| 67 | + _DEFAULT_VOCAB = build_domain_vocab() | ||
| 68 | + return _DEFAULT_VOCAB | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def _overlaps(token: str, vocab: set[str]) -> bool: | ||
| 72 | + if token in vocab: | ||
| 73 | + return True | ||
| 74 | + # Çekim varyasyonları için önek eşleşmesi (her iki yönde, >=3 harf). | ||
| 75 | + return any( | ||
| 76 | + (token.startswith(v) or v.startswith(token)) | ||
| 77 | + for v in vocab | ||
| 78 | + if len(v) >= _MIN_TOKEN_LEN | ||
| 79 | + ) | ||
| 80 | + | ||
| 81 | + | ||
| 82 | +def is_in_domain(query: str, vocab: set[str] | None = None) -> bool: | ||
| 83 | + """Sorgunun en az bir içerik kelimesi alan söz varlığıyla örtüşüyor mu?""" | ||
| 84 | + | ||
| 85 | + vocab = vocab if vocab is not None else get_domain_vocab() | ||
| 86 | + content = _content_tokens(query) | ||
| 87 | + if not content: | ||
| 88 | + # Yalnızca jenerik kelimelerden oluşan sorgu -> ayırt edici alan sinyali yok. | ||
| 89 | + return False | ||
| 90 | + return any(_overlaps(token, vocab) for token in content) | ||
src/engine.pyadded+112 -0
| @@ -0,0 +1,112 @@ | |||
| 1 | +"""Backend servis + front/back sözleşmesi. | ||
| 2 | + | ||
| 3 | +Motoru net bir istek/yanıt sözleşmesiyle sarar. Frontend (terminal, web vb.) | ||
| 4 | +yalnızca bu sözleşme üzerinden konuşur; iç katmanları (kural/benzerlik/karar) | ||
| 5 | +bilmez. Loglama backend'de yapılır (isteğe bağlı log_sink). | ||
| 6 | + | ||
| 7 | +İstek (payload): | ||
| 8 | + { | ||
| 9 | + "query": str, # zorunlu | ||
| 10 | + "session": {"role": str, "authenticated": bool}, # isteğe bağlı | ||
| 11 | + "trace_id": str # isteğe bağlı (yoksa üretilir) | ||
| 12 | + } | ||
| 13 | + | ||
| 14 | +Yanıt: | ||
| 15 | + { | ||
| 16 | + "trace_id": str, | ||
| 17 | + "response_id": str, | ||
| 18 | + "text": str, | ||
| 19 | + "intent": str | None, | ||
| 20 | + "confidence": float, | ||
| 21 | + "fallback": bool, | ||
| 22 | + "auth_action": str | None, # None | "login_required" | "role_insufficient" | ||
| 23 | + "required_role": str | None | ||
| 24 | + } | ||
| 25 | +""" | ||
| 26 | + | ||
| 27 | +from __future__ import annotations | ||
| 28 | + | ||
| 29 | +from typing import Any, Callable | ||
| 30 | + | ||
| 31 | +from .catalog import ROLE_HIERARCHY | ||
| 32 | +from .observability import process | ||
| 33 | +from .similarity import SimilarityMatcher, get_default_matcher | ||
| 34 | + | ||
| 35 | +# İsteğe bağlı log alıcısı: bir trace sözlüğü alır (dosyaya/akışa yazmak çağıranın işi). | ||
| 36 | +LogSink = Callable[[dict[str, Any]], None] | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +class RequestError(ValueError): | ||
| 40 | + """Geçersiz istek payload'ı.""" | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +def _parse_session(payload: dict[str, Any]) -> tuple[str, bool]: | ||
| 44 | + session = payload.get("session") or {} | ||
| 45 | + role = session.get("role", "ziyaretci") | ||
| 46 | + authenticated = bool(session.get("authenticated", role != "ziyaretci")) | ||
| 47 | + if role not in ROLE_HIERARCHY: | ||
| 48 | + raise RequestError(f"Bilinmeyen rol: {role!r}") | ||
| 49 | + if role == "ziyaretci" and authenticated: | ||
| 50 | + raise RequestError("Ziyaretçi 'authenticated' olamaz.") | ||
| 51 | + return role, authenticated | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +class Engine: | ||
| 55 | + """Süreç ömrü boyunca yeniden kullanılan backend motoru.""" | ||
| 56 | + | ||
| 57 | + def __init__( | ||
| 58 | + self, | ||
| 59 | + matcher: SimilarityMatcher | None = None, | ||
| 60 | + log_sink: LogSink | None = None, | ||
| 61 | + ) -> None: | ||
| 62 | + self._matcher = matcher or get_default_matcher() | ||
| 63 | + self._log_sink = log_sink | ||
| 64 | + | ||
| 65 | + def handle(self, payload: dict[str, Any]) -> dict[str, Any]: | ||
| 66 | + """Bir istek payload'ını işleyip yanıt sözleşmesi döndürür.""" | ||
| 67 | + | ||
| 68 | + query = payload.get("query") | ||
| 69 | + if not isinstance(query, str) or not query.strip(): | ||
| 70 | + raise RequestError("'query' boş olmayan bir metin olmalı.") | ||
| 71 | + | ||
| 72 | + role, authenticated = _parse_session(payload) | ||
| 73 | + trace_id = payload.get("trace_id") | ||
| 74 | + | ||
| 75 | + response, trace = process( | ||
| 76 | + query, | ||
| 77 | + role=role, | ||
| 78 | + authenticated=authenticated, | ||
| 79 | + trace_id=trace_id, | ||
| 80 | + matcher=self._matcher, | ||
| 81 | + ) | ||
| 82 | + | ||
| 83 | + if self._log_sink is not None: | ||
| 84 | + self._log_sink(trace) | ||
| 85 | + | ||
| 86 | + return { | ||
| 87 | + "trace_id": trace["trace_id"], | ||
| 88 | + "response_id": response.response_id, | ||
| 89 | + "text": response.text, | ||
| 90 | + "intent": response.intent, | ||
| 91 | + "confidence": trace["decision"]["confidence"], | ||
| 92 | + "fallback": response.fallback, | ||
| 93 | + "auth_action": response.auth_action, | ||
| 94 | + "required_role": trace["decision"]["required_role"], | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +# Kolaylık: paylaşılan varsayılan motor. | ||
| 99 | +_DEFAULT_ENGINE: Engine | None = None | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +def get_default_engine() -> Engine: | ||
| 103 | + global _DEFAULT_ENGINE | ||
| 104 | + if _DEFAULT_ENGINE is None: | ||
| 105 | + _DEFAULT_ENGINE = Engine() | ||
| 106 | + return _DEFAULT_ENGINE | ||
| 107 | + | ||
| 108 | + | ||
| 109 | +def handle_request(payload: dict[str, Any]) -> dict[str, Any]: | ||
| 110 | + """Paylaşılan motorla tek atımlık istek işleme.""" | ||
| 111 | + | ||
| 112 | + return get_default_engine().handle(payload) | ||
src/evaluate.pyadded+181 -0
| @@ -0,0 +1,181 @@ | |||
| 1 | +"""Tam değerlendirme koşum aracı (Aşama 10). | ||
| 2 | + | ||
| 3 | +Benchmark'ı izlenmiş boru hattından geçirir ve tek bir raporda toplar: | ||
| 4 | +- macro-F1 (başlık), accuracy, per-class P/R/F1 | ||
| 5 | +- coverage, accuracy-on-covered, false-fallback | ||
| 6 | +- OOS recall | ||
| 7 | +- must_not_match çift-karışma raporu | ||
| 8 | +- top-1 vs top-3 accuracy | ||
| 9 | +- latency p50/p95 | ||
| 10 | + | ||
| 11 | +Çıktı hem makine-okunur (dict) hem insan-okunur (format_report) — regresyon için | ||
| 12 | +Aşama 14, ayar için Aşama 11 bunu kullanır. | ||
| 13 | +""" | ||
| 14 | + | ||
| 15 | +from __future__ import annotations | ||
| 16 | + | ||
| 17 | +from typing import Any | ||
| 18 | + | ||
| 19 | +from .benchmark import OOS_LABEL, load_benchmark | ||
| 20 | +from .catalog import INTENTS | ||
| 21 | +from .decision import DEFAULT_THRESHOLD, _is_confusable_pair | ||
| 22 | +from .metrics import ( | ||
| 23 | + accuracy, | ||
| 24 | + macro_f1, | ||
| 25 | + per_class_scores, | ||
| 26 | + percentile, | ||
| 27 | + topk_accuracy, | ||
| 28 | +) | ||
| 29 | +from .observability import process | ||
| 30 | +from .similarity import SimilarityMatcher, get_default_matcher | ||
| 31 | + | ||
| 32 | +# in-scope iken FALLBACK'e düşeni işaretlemek için sözde etiket. | ||
| 33 | +_FALLBACK_LABEL = "__fallback__" | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def run_evaluation( | ||
| 37 | + threshold: float = DEFAULT_THRESHOLD, | ||
| 38 | + matcher: SimilarityMatcher | None = None, | ||
| 39 | + records: list[dict[str, Any]] | None = None, | ||
| 40 | +) -> dict[str, Any]: | ||
| 41 | + """Benchmark üzerinde tam değerlendirme yapar ve metrik sözlüğü döndürür.""" | ||
| 42 | + | ||
| 43 | + matcher = matcher or get_default_matcher() | ||
| 44 | + records = records if records is not None else load_benchmark() | ||
| 45 | + labels = {i["intent"] for i in INTENTS} | ||
| 46 | + | ||
| 47 | + in_pairs: list[tuple[str, str]] = [] # (true, pred|__fallback__) | ||
| 48 | + covered_pairs: list[tuple[str, str]] = [] # yalnızca kapsananlar | ||
| 49 | + topk_records: list[tuple[str, list[str]]] = [] # (true, sıralı tahminler) | ||
| 50 | + latencies: list[float] = [] | ||
| 51 | + | ||
| 52 | + covered = correct = false_fallback = 0 | ||
| 53 | + oos_total = oos_caught = 0 | ||
| 54 | + confusable_wrong = nonconfusable_wrong = 0 | ||
| 55 | + wrong_pairs: list[tuple[str, str]] = [] | ||
| 56 | + | ||
| 57 | + for r in records: | ||
| 58 | + role = r.get("role", "ziyaretci") | ||
| 59 | + authenticated = role != "ziyaretci" | ||
| 60 | + _, trace = process( | ||
| 61 | + r["question"], role=role, authenticated=authenticated, matcher=matcher | ||
| 62 | + ) | ||
| 63 | + # Eşik parametresini uygulamak için kararı yeniden değerlendirmek yerine, | ||
| 64 | + # process varsayılan eşiği kullanır; ayar taraması için threshold enjekte edelim. | ||
| 65 | + # (threshold != default ise skorlardan yeniden karar ver.) | ||
| 66 | + pred = _reconsider(trace, threshold) | ||
| 67 | + latencies.append(trace["latency_ms"]["total"]) | ||
| 68 | + | ||
| 69 | + expected = r["expected_intent"] | ||
| 70 | + if expected == OOS_LABEL: | ||
| 71 | + oos_total += 1 | ||
| 72 | + if pred is None: | ||
| 73 | + oos_caught += 1 | ||
| 74 | + continue | ||
| 75 | + | ||
| 76 | + # in-scope | ||
| 77 | + ranked_intents = _ranked_intents(trace) | ||
| 78 | + topk_records.append((expected, ranked_intents)) | ||
| 79 | + | ||
| 80 | + if pred is None: | ||
| 81 | + false_fallback += 1 | ||
| 82 | + in_pairs.append((expected, _FALLBACK_LABEL)) | ||
| 83 | + else: | ||
| 84 | + covered += 1 | ||
| 85 | + in_pairs.append((expected, pred)) | ||
| 86 | + covered_pairs.append((expected, pred)) | ||
| 87 | + if pred == expected: | ||
| 88 | + correct += 1 | ||
| 89 | + else: | ||
| 90 | + wrong_pairs.append((expected, pred)) | ||
| 91 | + if _is_confusable_pair(expected, pred): | ||
| 92 | + confusable_wrong += 1 | ||
| 93 | + else: | ||
| 94 | + nonconfusable_wrong += 1 | ||
| 95 | + | ||
| 96 | + in_scope_total = len(in_pairs) | ||
| 97 | + report: dict[str, Any] = { | ||
| 98 | + "threshold": threshold, | ||
| 99 | + "in_scope_total": in_scope_total, | ||
| 100 | + "oos_total": oos_total, | ||
| 101 | + "macro_f1": macro_f1(in_pairs, labels), | ||
| 102 | + "accuracy": accuracy(in_pairs), | ||
| 103 | + "coverage": covered / in_scope_total if in_scope_total else 0.0, | ||
| 104 | + "accuracy_on_covered": correct / covered if covered else 0.0, | ||
| 105 | + "false_fallback": false_fallback, | ||
| 106 | + "oos_recall": oos_caught / oos_total if oos_total else 0.0, | ||
| 107 | + "top1_accuracy": topk_accuracy(topk_records, 1), | ||
| 108 | + "top3_accuracy": topk_accuracy(topk_records, 3), | ||
| 109 | + "confusable_wrong": confusable_wrong, | ||
| 110 | + "nonconfusable_wrong": nonconfusable_wrong, | ||
| 111 | + "wrong_pairs": wrong_pairs, | ||
| 112 | + "latency_p50_ms": percentile(latencies, 50), | ||
| 113 | + "latency_p95_ms": percentile(latencies, 95), | ||
| 114 | + "per_class": per_class_scores(covered_pairs, labels), | ||
| 115 | + } | ||
| 116 | + return report | ||
| 117 | + | ||
| 118 | + | ||
| 119 | +def _ranked_intents(trace: dict[str, Any]) -> list[str]: | ||
| 120 | + """Trace'ten sıralı tahmin listesi (kural yolu -> tek eleman).""" | ||
| 121 | + | ||
| 122 | + if trace["rule_layer"]["hit"]: | ||
| 123 | + return [trace["rule_layer"]["intent"]] | ||
| 124 | + return [item["intent"] for item in trace["similarity"]["top_k"]] | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +def _reconsider(trace: dict[str, Any], threshold: float) -> str | None: | ||
| 128 | + """Verilen eşiğe göre tahmini belirler (kural her zaman kazanır; alan kapısı uygulanır).""" | ||
| 129 | + | ||
| 130 | + if trace["rule_layer"]["hit"]: | ||
| 131 | + return trace["rule_layer"]["intent"] | ||
| 132 | + if not trace["similarity"].get("in_domain", True): | ||
| 133 | + return None | ||
| 134 | + top_k = trace["similarity"]["top_k"] | ||
| 135 | + if not top_k: | ||
| 136 | + return None | ||
| 137 | + top = top_k[0] | ||
| 138 | + if top["score"] < threshold: | ||
| 139 | + return None | ||
| 140 | + return top["intent"] | ||
| 141 | + | ||
| 142 | + | ||
| 143 | +def format_report(report: dict[str, Any]) -> str: | ||
| 144 | + """İnsan-okunur özet.""" | ||
| 145 | + | ||
| 146 | + lines = [ | ||
| 147 | + "================ DEĞERLENDİRME RAPORU ================", | ||
| 148 | + f"Eşik (threshold) : {report['threshold']:.3f}", | ||
| 149 | + f"In-scope / OOS : {report['in_scope_total']} / {report['oos_total']}", | ||
| 150 | + "--- Genel ---", | ||
| 151 | + f"Macro-F1 (BAŞLIK) : {report['macro_f1']:.3f}", | ||
| 152 | + f"Accuracy : {report['accuracy']:.1%}", | ||
| 153 | + f"Top-1 / Top-3 acc : {report['top1_accuracy']:.1%} / {report['top3_accuracy']:.1%}", | ||
| 154 | + "--- Abstention (eşik) ---", | ||
| 155 | + f"Coverage : {report['coverage']:.1%}", | ||
| 156 | + f"Accuracy-on-covered : {report['accuracy_on_covered']:.1%}", | ||
| 157 | + f"False fallback : {report['false_fallback']}", | ||
| 158 | + f"OOS recall : {report['oos_recall']:.1%}", | ||
| 159 | + "--- must_not_match ---", | ||
| 160 | + f"Karışan çift (confusable) yanlış : {report['confusable_wrong']}", | ||
| 161 | + f"Diğer (beklenmedik) yanlış : {report['nonconfusable_wrong']}", | ||
| 162 | + "--- Latency ---", | ||
| 163 | + f"p50 / p95 (ms) : {report['latency_p50_ms']:.3f} / {report['latency_p95_ms']:.3f}", | ||
| 164 | + "--- En zayıf 8 intent (F1, kapsananlarda) ---", | ||
| 165 | + ] | ||
| 166 | + worst = sorted(report["per_class"], key=lambda s: (s.f1, -s.support)) | ||
| 167 | + for s in worst[:8]: | ||
| 168 | + lines.append( | ||
| 169 | + f" {s.label:26s} P={s.precision:.2f} R={s.recall:.2f} F1={s.f1:.2f} (n={s.support})" | ||
| 170 | + ) | ||
| 171 | + if report["wrong_pairs"]: | ||
| 172 | + lines.append("--- Yanlış tahminler (beklenen -> bulunan) ---") | ||
| 173 | + for true, pred in report["wrong_pairs"]: | ||
| 174 | + mark = "~" if _is_confusable_pair(true, pred) else "x" | ||
| 175 | + lines.append(f" [{mark}] {true} -> {pred}") | ||
| 176 | + lines.append("=====================================================") | ||
| 177 | + return "\n".join(lines) | ||
| 178 | + | ||
| 179 | + | ||
| 180 | +if __name__ == "__main__": | ||
| 181 | + print(format_report(run_evaluation())) | ||
src/main.pymodified+27 -94
| @@ -1,123 +1,56 @@ | |||
| 1 | -"""Container entry point and catalog validation.""" | 1 | +"""Container giriş noktası ve katalog doğrulaması.""" |
| 2 | 2 | ||
| 3 | from __future__ import annotations | 3 | from __future__ import annotations |
| 4 | 4 | ||
| 5 | import argparse | 5 | import argparse |
| 6 | -from collections import Counter | ||
| 7 | from typing import Any | 6 | from typing import Any |
| 8 | 7 | ||
| 9 | -from .QandA import FALLBACK, INTENTS, MOCK_STUDENT, get_intent | 8 | +from .catalog import validate_catalog |
| 10 | - | ||
| 11 | - | ||
| 12 | -REQUIRED_INTENT_FIELDS = { | ||
| 13 | - "intent", | ||
| 14 | - "category", | ||
| 15 | - "description", | ||
| 16 | - "response_id", | ||
| 17 | - "response_template", | ||
| 18 | - "auth_required", | ||
| 19 | - "example_questions", | ||
| 20 | - "must_not_match", | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | - | ||
| 24 | -def _duplicates(values: list[str]) -> list[str]: | ||
| 25 | - """Return duplicate values in deterministic order.""" | ||
| 26 | - | ||
| 27 | - counts = Counter(values) | ||
| 28 | - return sorted(value for value, count in counts.items() if count > 1) | ||
| 29 | - | ||
| 30 | - | ||
| 31 | -def validate_catalog() -> dict[str, int]: | ||
| 32 | - """Validate invariants required by the future rule engine. | ||
| 33 | - | ||
| 34 | - Raises: | ||
| 35 | - ValueError: If catalog data is incomplete, ambiguous or inconsistent. | ||
| 36 | - """ | ||
| 37 | - | ||
| 38 | - if not INTENTS: | ||
| 39 | - raise ValueError("Intent kataloğu boş olamaz.") | ||
| 40 | - | ||
| 41 | - errors: list[str] = [] | ||
| 42 | - intent_names: list[str] = [] | ||
| 43 | - response_ids: list[str] = [] | ||
| 44 | - questions: list[str] = [] | ||
| 45 | - | ||
| 46 | - for index, item in enumerate(INTENTS): | ||
| 47 | - missing_fields = REQUIRED_INTENT_FIELDS.difference(item) | ||
| 48 | - if missing_fields: | ||
| 49 | - errors.append( | ||
| 50 | - f"INTENTS[{index}] eksik alanlar: {', '.join(sorted(missing_fields))}" | ||
| 51 | - ) | ||
| 52 | - continue | ||
| 53 | - | ||
| 54 | - intent_name = item["intent"] | ||
| 55 | - intent_names.append(intent_name) | ||
| 56 | - response_ids.append(item["response_id"]) | ||
| 57 | - | ||
| 58 | - examples = item["example_questions"] | ||
| 59 | - if not examples: | ||
| 60 | - errors.append(f"{intent_name}: en az bir örnek soru gerekli.") | ||
| 61 | - if any(not isinstance(question, str) or not question.strip() for question in examples): | ||
| 62 | - errors.append(f"{intent_name}: boş veya metin olmayan örnek soru var.") | ||
| 63 | - questions.extend(examples) | ||
| 64 | - | ||
| 65 | - duplicate_intents = _duplicates(intent_names) | ||
| 66 | - duplicate_responses = _duplicates(response_ids) | ||
| 67 | - duplicate_questions = _duplicates(questions) | ||
| 68 | - known_intents = set(intent_names) | ||
| 69 | - | ||
| 70 | - if duplicate_intents: | ||
| 71 | - errors.append(f"Tekrarlanan intent: {duplicate_intents}") | ||
| 72 | - if duplicate_responses: | ||
| 73 | - errors.append(f"Tekrarlanan response_id: {duplicate_responses}") | ||
| 74 | - if duplicate_questions: | ||
| 75 | - errors.append(f"Tekrarlanan örnek soru: {duplicate_questions}") | ||
| 76 | - | ||
| 77 | - for item in INTENTS: | ||
| 78 | - unknown_targets = set(item.get("must_not_match", [])).difference(known_intents) | ||
| 79 | - if unknown_targets: | ||
| 80 | - errors.append( | ||
| 81 | - f"{item.get('intent', '<unknown>')}: bilinmeyen must_not_match " | ||
| 82 | - f"hedefleri: {sorted(unknown_targets)}" | ||
| 83 | - ) | ||
| 84 | - | ||
| 85 | - if not FALLBACK.get("response_id") or not FALLBACK.get("response_template"): | ||
| 86 | - errors.append("Fallback cevabı eksik.") | ||
| 87 | - if not MOCK_STUDENT.get("student_id"): | ||
| 88 | - errors.append("Mock öğrenci kimliği eksik.") | ||
| 89 | - | ||
| 90 | - if errors: | ||
| 91 | - raise ValueError("Katalog doğrulanamadı:\n- " + "\n- ".join(errors)) | ||
| 92 | - | ||
| 93 | - return { | ||
| 94 | - "intent_count": len(intent_names), | ||
| 95 | - "response_count": len(response_ids), | ||
| 96 | - "example_question_count": len(questions), | ||
| 97 | - } | ||
| 98 | 9 | ||
| 99 | 10 | ||
| 100 | def print_validation_result(result: dict[str, Any]) -> None: | 11 | def print_validation_result(result: dict[str, Any]) -> None: |
| 101 | - """Print a concise, log-friendly validation result.""" | 12 | + """Kısa, log dostu bir doğrulama sonucu yazdırır.""" |
| 102 | 13 | ||
| 103 | print("Katalog doğrulandı.") | 14 | print("Katalog doğrulandı.") |
| 104 | print(f"Intent: {result['intent_count']}") | 15 | print(f"Intent: {result['intent_count']}") |
| 105 | print(f"Cevap: {result['response_count']}") | 16 | print(f"Cevap: {result['response_count']}") |
| 17 | + print(f"Kategori: {result['category_count']}") | ||
| 106 | print(f"Örnek soru: {result['example_question_count']}") | 18 | print(f"Örnek soru: {result['example_question_count']}") |
| 107 | 19 | ||
| 108 | 20 | ||
| 109 | def build_parser() -> argparse.ArgumentParser: | 21 | def build_parser() -> argparse.ArgumentParser: |
| 110 | - parser = argparse.ArgumentParser(description="Eğitim platformu chatbot'u") | 22 | + parser = argparse.ArgumentParser(description="Hezarfen kullanım asistanı chatbot'u") |
| 111 | parser.add_argument( | 23 | parser.add_argument( |
| 112 | "--validate", | 24 | "--validate", |
| 113 | action="store_true", | 25 | action="store_true", |
| 114 | - help="Soru/cevap kataloğunu doğrular ve çıkar.", | 26 | + help="Intent kataloğunu doğrular ve çıkar.", |
| 27 | + ) | ||
| 28 | + parser.add_argument( | ||
| 29 | + "--evaluate", | ||
| 30 | + action="store_true", | ||
| 31 | + help="Benchmark üzerinde tam değerlendirme raporu üretir.", | ||
| 32 | + ) | ||
| 33 | + parser.add_argument( | ||
| 34 | + "--chat", | ||
| 35 | + action="store_true", | ||
| 36 | + help="Etkileşimli terminal sohbetini başlatır.", | ||
| 115 | ) | 37 | ) |
| 116 | return parser | 38 | return parser |
| 117 | 39 | ||
| 118 | 40 | ||
| 119 | def main() -> int: | 41 | def main() -> int: |
| 120 | args = build_parser().parse_args() | 42 | args = build_parser().parse_args() |
| 43 | + if args.chat: | ||
| 44 | + from .cli import main as chat_main | ||
| 45 | + | ||
| 46 | + return chat_main() | ||
| 47 | + | ||
| 48 | + if args.evaluate: | ||
| 49 | + from .evaluate import format_report, run_evaluation | ||
| 50 | + | ||
| 51 | + print(format_report(run_evaluation())) | ||
| 52 | + return 0 | ||
| 53 | + | ||
| 121 | if args.validate: | 54 | if args.validate: |
| 122 | print_validation_result(validate_catalog()) | 55 | print_validation_result(validate_catalog()) |
| 123 | return 0 | 56 | return 0 |
src/metrics.pyadded+112 -0
| @@ -0,0 +1,112 @@ | |||
| 1 | +"""Sınıflandırma metrikleri (çekirdek). | ||
| 2 | + | ||
| 3 | +Bu modül temel metrikleri sağlar: per-class precision/recall/F1, macro-F1, | ||
| 4 | +accuracy ve confusion sayımları. Aşama 10'da coverage, OOS recall, PR eğrisi ve | ||
| 5 | +gecikme (latency) ölçümleriyle genişletilecektir. | ||
| 6 | + | ||
| 7 | +Girdi her yerde `pairs`: (gerçek_etiket, tahmin_etiket) çiftlerinin listesi. | ||
| 8 | +""" | ||
| 9 | + | ||
| 10 | +from __future__ import annotations | ||
| 11 | + | ||
| 12 | +from collections import Counter | ||
| 13 | +from dataclasses import dataclass | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +@dataclass(frozen=True) | ||
| 17 | +class ClassScore: | ||
| 18 | + label: str | ||
| 19 | + precision: float | ||
| 20 | + recall: float | ||
| 21 | + f1: float | ||
| 22 | + support: int | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def _prf(tp: int, fp: int, fn: int) -> tuple[float, float, float]: | ||
| 26 | + """tp/fp/fn'den precision, recall, F1 (harmonik ortalama) döndürür.""" | ||
| 27 | + | ||
| 28 | + precision = tp / (tp + fp) if (tp + fp) else 0.0 | ||
| 29 | + recall = tp / (tp + fn) if (tp + fn) else 0.0 | ||
| 30 | + f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0 | ||
| 31 | + return precision, recall, f1 | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def confusion_counts( | ||
| 35 | + pairs: list[tuple[str, str]], labels: set[str] | ||
| 36 | +) -> dict[str, tuple[int, int, int]]: | ||
| 37 | + """Her etiket için (tp, fp, fn) döndürür.""" | ||
| 38 | + | ||
| 39 | + tp: Counter[str] = Counter() | ||
| 40 | + fp: Counter[str] = Counter() | ||
| 41 | + fn: Counter[str] = Counter() | ||
| 42 | + for true_label, pred_label in pairs: | ||
| 43 | + if true_label == pred_label: | ||
| 44 | + tp[true_label] += 1 | ||
| 45 | + else: | ||
| 46 | + fp[pred_label] += 1 | ||
| 47 | + fn[true_label] += 1 | ||
| 48 | + return {label: (tp[label], fp[label], fn[label]) for label in labels} | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def per_class_scores(pairs: list[tuple[str, str]], labels: set[str]) -> list[ClassScore]: | ||
| 52 | + """Her etiket için ClassScore listesi (support'a göre azalan).""" | ||
| 53 | + | ||
| 54 | + support: Counter[str] = Counter(true for true, _ in pairs) | ||
| 55 | + counts = confusion_counts(pairs, labels) | ||
| 56 | + scores: list[ClassScore] = [] | ||
| 57 | + for label in labels: | ||
| 58 | + tp, fp, fn = counts[label] | ||
| 59 | + precision, recall, f1 = _prf(tp, fp, fn) | ||
| 60 | + scores.append(ClassScore(label, precision, recall, f1, support[label])) | ||
| 61 | + scores.sort(key=lambda s: (s.support, s.label), reverse=True) | ||
| 62 | + return scores | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +def macro_f1(pairs: list[tuple[str, str]], labels: set[str]) -> float: | ||
| 66 | + """Etiketler arası düz ortalama F1. | ||
| 67 | + | ||
| 68 | + Dengesiz sınıfta nadir ama kritik intent'lerin bozukluğunu saklamaz; bu yüzden | ||
| 69 | + başlık metriği olarak kullanılır. | ||
| 70 | + """ | ||
| 71 | + | ||
| 72 | + if not labels: | ||
| 73 | + return 0.0 | ||
| 74 | + counts = confusion_counts(pairs, labels) | ||
| 75 | + total = 0.0 | ||
| 76 | + for label in labels: | ||
| 77 | + tp, fp, fn = counts[label] | ||
| 78 | + total += _prf(tp, fp, fn)[2] | ||
| 79 | + return total / len(labels) | ||
| 80 | + | ||
| 81 | + | ||
| 82 | +def accuracy(pairs: list[tuple[str, str]]) -> float: | ||
| 83 | + """Doğru tahmin oranı (ikincil metrik; dengesizlikte yanıltıcı olabilir).""" | ||
| 84 | + | ||
| 85 | + if not pairs: | ||
| 86 | + return 0.0 | ||
| 87 | + correct = sum(1 for true, pred in pairs if true == pred) | ||
| 88 | + return correct / len(pairs) | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +def percentile(values: list[float], p: float) -> float: | ||
| 92 | + """Doğrusal interpolasyonlu yüzdelik (p ∈ [0, 100]). Gecikme p50/p95 için.""" | ||
| 93 | + | ||
| 94 | + if not values: | ||
| 95 | + return 0.0 | ||
| 96 | + ordered = sorted(values) | ||
| 97 | + if len(ordered) == 1: | ||
| 98 | + return ordered[0] | ||
| 99 | + rank = (len(ordered) - 1) * (p / 100.0) | ||
| 100 | + low = int(rank) | ||
| 101 | + high = min(low + 1, len(ordered) - 1) | ||
| 102 | + frac = rank - low | ||
| 103 | + return ordered[low] + (ordered[high] - ordered[low]) * frac | ||
| 104 | + | ||
| 105 | + | ||
| 106 | +def topk_accuracy(records: list[tuple[str, list[str]]], k: int) -> float: | ||
| 107 | + """Gerçek etiket, ilk k tahmin içinde mi? (records: (true, sıralı_tahminler)).""" | ||
| 108 | + | ||
| 109 | + if not records: | ||
| 110 | + return 0.0 | ||
| 111 | + hits = sum(1 for true, preds in records if true in preds[:k]) | ||
| 112 | + return hits / len(records) | ||
src/normalize.pyadded+165 -0
| @@ -0,0 +1,165 @@ | |||
| 1 | +"""Metin normalizasyonu ve hafif Türkçe kök bulma. | ||
| 2 | + | ||
| 3 | +Amaç: aynı anlamı taşıyan farklı yazımları tek forma indirgemek. Türkçe | ||
| 4 | +sondan-eklemeli olduğu için ('notlarımı', 'notların', 'notum' -> 'not') hafif | ||
| 5 | +bir kök bulma, kelime-torbası eşleşmesinin en zayıf noktasını kapatır. | ||
| 6 | + | ||
| 7 | +Tasarım kararları: | ||
| 8 | +- Türkçe-duyarlı küçük harf: 'I'->'ı', 'İ'->'i' (Python'un varsayılan lower'ı | ||
| 9 | + bunları yanlış yapar). | ||
| 10 | +- Aksan katlama (fold): ç->c, ğ->g, ı->i, ö->o, ş->s, ü->u — kullanıcı Türkçe | ||
| 11 | + karakter kullanmadan yazsa da ('sinav' ~ 'sınav') eşleşme tutar. | ||
| 12 | +- Stemmer bilinçli olarak HAFİF ve fazla-kırpmaya karşı korumalıdır (asgari kök | ||
| 13 | + uzunluğu). Dilbilimsel mükemmellik değil, sorgu ile anahtar kelime arasında | ||
| 14 | + TUTARLILIK hedeflenir; kural katmanı önek (prefix) eşleşmesiyle bunu tamamlar. | ||
| 15 | + | ||
| 16 | +Tüm fonksiyonlar saf ve deterministiktir (loglanabilir/test edilebilir). | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +from __future__ import annotations | ||
| 20 | + | ||
| 21 | +import re | ||
| 22 | +from typing import Final | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +MIN_STEM_LENGTH: Final[int] = 3 | ||
| 26 | +_MAX_STEM_PASSES: Final[int] = 3 | ||
| 27 | + | ||
| 28 | +# Türkçe küçük harf için özel eşlemeler (lower() öncesi uygulanır). | ||
| 29 | +_UPPER_MAP: Final[dict[str, str]] = {"İ": "i", "I": "ı"} | ||
| 30 | + | ||
| 31 | +# Aksan katlama (küçük harf sonrası). | ||
| 32 | +_FOLD_MAP: Final[dict[str, str]] = str.maketrans( | ||
| 33 | + { | ||
| 34 | + "ç": "c", | ||
| 35 | + "ğ": "g", | ||
| 36 | + "ı": "i", | ||
| 37 | + "ö": "o", | ||
| 38 | + "ş": "s", | ||
| 39 | + "ü": "u", | ||
| 40 | + "â": "a", | ||
| 41 | + "î": "i", | ||
| 42 | + "û": "u", | ||
| 43 | + } | ||
| 44 | +) | ||
| 45 | + | ||
| 46 | +# Yalnızca harf/rakam/boşluk bırak (Türkçe harfler dahil). | ||
| 47 | +_PUNCT_RE: Final[re.Pattern[str]] = re.compile(r"[^0-9a-zçğıöşü\s]", re.IGNORECASE) | ||
| 48 | +_WS_RE: Final[re.Pattern[str]] = re.compile(r"\s+") | ||
| 49 | + | ||
| 50 | +# Katlanmış (ascii) tokenlar üzerinde çalışan, uzundan kısaya denenecek ekler. | ||
| 51 | +_SUFFIXES: Final[tuple[str, ...]] = tuple( | ||
| 52 | + sorted( | ||
| 53 | + { | ||
| 54 | + # çoğul + iyelik/hal birleşik | ||
| 55 | + "larimizi", "lerimizi", "larinizi", "lerinizi", | ||
| 56 | + "larimiz", "lerimiz", "lariniz", "leriniz", | ||
| 57 | + "larini", "lerini", "larimi", "lerimi", | ||
| 58 | + "lardan", "lerden", "larda", "lerde", | ||
| 59 | + "larim", "lerim", "larin", "lerin", | ||
| 60 | + "lara", "lere", "lari", "leri", | ||
| 61 | + "lar", "ler", | ||
| 62 | + # iyelik | ||
| 63 | + "imiz", "iniz", "umuz", "unuz", | ||
| 64 | + "imi", "ini", "umu", "unu", | ||
| 65 | + "im", "in", "um", "un", | ||
| 66 | + # hal ekleri | ||
| 67 | + "ndan", "nden", "tan", "ten", "dan", "den", | ||
| 68 | + "nin", "nun", "nda", "nde", | ||
| 69 | + "da", "de", "ta", "te", | ||
| 70 | + "na", "ne", "ya", "ye", | ||
| 71 | + "yi", "yu", "yi", | ||
| 72 | + "si", "su", | ||
| 73 | + # fiil/soru | ||
| 74 | + "yor", "dir", "tir", "dur", "tur", "mis", "mus", | ||
| 75 | + "acak", "ecek", "mak", "mek", | ||
| 76 | + "mi", "mu", | ||
| 77 | + # tekil sesli hal ekleri (asgari uzunlukla korunur) | ||
| 78 | + "i", "u", "a", "e", | ||
| 79 | + }, | ||
| 80 | + key=len, | ||
| 81 | + reverse=True, | ||
| 82 | + ) | ||
| 83 | +) | ||
| 84 | + | ||
| 85 | + | ||
| 86 | +def turkish_lower(text: str) -> str: | ||
| 87 | + """Türkçe kurallarına göre küçük harfe çevirir.""" | ||
| 88 | + | ||
| 89 | + for upper, lower in _UPPER_MAP.items(): | ||
| 90 | + text = text.replace(upper, lower) | ||
| 91 | + return text.lower() | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def strip_punctuation(text: str) -> str: | ||
| 95 | + """Harf/rakam/boşluk dışındaki karakterleri boşlukla değiştirir.""" | ||
| 96 | + | ||
| 97 | + return _PUNCT_RE.sub(" ", text) | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +def collapse_whitespace(text: str) -> str: | ||
| 101 | + """Ardışık boşlukları teke indirir ve baştaki/sondaki boşluğu atar.""" | ||
| 102 | + | ||
| 103 | + return _WS_RE.sub(" ", text).strip() | ||
| 104 | + | ||
| 105 | + | ||
| 106 | +def normalize(text: str) -> str: | ||
| 107 | + """Tam normalizasyon: küçük harf + noktalama temizliği + boşluk sadeleştirme. | ||
| 108 | + | ||
| 109 | + Türkçe karakterleri KORUR (okunabilir/loglanabilir form). | ||
| 110 | + """ | ||
| 111 | + | ||
| 112 | + return collapse_whitespace(strip_punctuation(turkish_lower(text))) | ||
| 113 | + | ||
| 114 | + | ||
| 115 | +def fold_accents(text: str) -> str: | ||
| 116 | + """Türkçe özel karakterleri ascii karşılıklarına katlar.""" | ||
| 117 | + | ||
| 118 | + return text.translate(_FOLD_MAP) | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def tokenize(text: str) -> list[str]: | ||
| 122 | + """Normalize edilmiş metni boşluklardan tokenlara ayırır.""" | ||
| 123 | + | ||
| 124 | + normalized = normalize(text) | ||
| 125 | + if not normalized: | ||
| 126 | + return [] | ||
| 127 | + return normalized.split(" ") | ||
| 128 | + | ||
| 129 | + | ||
| 130 | +def folded_tokens(text: str) -> list[str]: | ||
| 131 | + """Normalize + katla ama STEM ETME: kural katmanı önek eşleşmesi için. | ||
| 132 | + | ||
| 133 | + Stem'in aksine kelimeleri çökertmez ('yapamıyor' -> 'yapamiyor', 'yap' değil), | ||
| 134 | + böylece anahtar kelime önek eşleşmesi ('sifre' <- 'sifremi') kesin kalır. | ||
| 135 | + """ | ||
| 136 | + | ||
| 137 | + return [fold_accents(token) for token in tokenize(text)] | ||
| 138 | + | ||
| 139 | + | ||
| 140 | +def stem(token: str) -> str: | ||
| 141 | + """Katlanmış (ascii) bir token için hafif kök bulma. | ||
| 142 | + | ||
| 143 | + Girdi ascii'ye katlanmış varsayılır. Asgari kök uzunluğu korunur; en fazla | ||
| 144 | + birkaç geçişte en uzun eşleşen ek soyulur. | ||
| 145 | + """ | ||
| 146 | + | ||
| 147 | + for _ in range(_MAX_STEM_PASSES): | ||
| 148 | + stripped = False | ||
| 149 | + for suffix in _SUFFIXES: | ||
| 150 | + if token.endswith(suffix) and len(token) - len(suffix) >= MIN_STEM_LENGTH: | ||
| 151 | + token = token[: -len(suffix)] | ||
| 152 | + stripped = True | ||
| 153 | + break | ||
| 154 | + if not stripped: | ||
| 155 | + break | ||
| 156 | + return token | ||
| 157 | + | ||
| 158 | + | ||
| 159 | +def roots(text: str) -> list[str]: | ||
| 160 | + """Metni köklerine indirger: normalize + katla + token + stem. | ||
| 161 | + | ||
| 162 | + Kural katmanının kullandığı kanonik biçim. Boş tokenlar atlanır. | ||
| 163 | + """ | ||
| 164 | + | ||
| 165 | + return [stem(fold_accents(token)) for token in tokenize(text) if token] | ||
src/observability.pyadded+158 -0
| @@ -0,0 +1,158 @@ | |||
| 1 | +"""Aşama bazlı yapısal loglama: her sorgu için izlenmiş (traced) boru hattı. | ||
| 2 | + | ||
| 3 | +`process()` boru hattını aşama aşama çalıştırır, her aşamanın çıktısını ve | ||
| 4 | +gecikmesini (latency) yakalar ve hem kullanıcı-yüzlü Response hem de makine-okunur | ||
| 5 | +bir trace kaydı döndürür. Bu kayıt: | ||
| 6 | + - metriklerin (Aşama 10) kaynağıdır, | ||
| 7 | + - tek bir yanlış cevabı adım adım geri izlemeyi sağlar, | ||
| 8 | + - auth sızıntısı gibi değişmezleri denetler (alarms). | ||
| 9 | + | ||
| 10 | +Loglama backend'de üretilir; frontend yalnızca cevabı görür. trace_id istekle | ||
| 11 | +gelebilir ya da burada üretilir. | ||
| 12 | +""" | ||
| 13 | + | ||
| 14 | +from __future__ import annotations | ||
| 15 | + | ||
| 16 | +import json | ||
| 17 | +import time | ||
| 18 | +import uuid | ||
| 19 | +from typing import Any | ||
| 20 | + | ||
| 21 | +from .catalog import get_intent, meets_role | ||
| 22 | +from .decision import ( | ||
| 23 | + LOGIN_REQUIRED, | ||
| 24 | + ROLE_INSUFFICIENT, | ||
| 25 | + Decision, | ||
| 26 | + decide_core, | ||
| 27 | +) | ||
| 28 | +from .domain import is_in_domain | ||
| 29 | +from . import rules | ||
| 30 | +from .normalize import normalize, roots | ||
| 31 | +from .responder import Response, render | ||
| 32 | +from .similarity import SimilarityMatcher, get_default_matcher | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def new_trace_id() -> str: | ||
| 36 | + """Yeni bir izleme kimliği üretir.""" | ||
| 37 | + | ||
| 38 | + return "req-" + uuid.uuid4().hex[:12] | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def _elapsed_ms(start_ns: int) -> float: | ||
| 42 | + return round((time.perf_counter_ns() - start_ns) / 1_000_000, 3) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def check_auth_alarms(decision: Decision, authenticated: bool, role: str) -> list[str]: | ||
| 46 | + """Auth/rol değişmezlerini denetler; ihlal varsa alarm mesajları döndürür. | ||
| 47 | + | ||
| 48 | + Asla görülmemesi gereken durum: auth gerektiren/rol yetersiz bir intent'e, | ||
| 49 | + gating uygulanmadan (auth_action=None) izin verilmesi = veri sızıntısı riski. | ||
| 50 | + """ | ||
| 51 | + | ||
| 52 | + alarms: list[str] = [] | ||
| 53 | + if decision.fallback or decision.intent is None: | ||
| 54 | + return alarms | ||
| 55 | + | ||
| 56 | + info = get_intent(decision.intent) | ||
| 57 | + if info is None: | ||
| 58 | + return alarms | ||
| 59 | + | ||
| 60 | + auth_required = bool(info["auth_required"]) | ||
| 61 | + min_role = info["min_role"] | ||
| 62 | + | ||
| 63 | + if auth_required and not authenticated and decision.auth_action != LOGIN_REQUIRED: | ||
| 64 | + alarms.append( | ||
| 65 | + f"AUTH_LEAK: '{decision.intent}' oturum gerektiriyor ama gating uygulanmadı." | ||
| 66 | + ) | ||
| 67 | + if authenticated and not meets_role(role, min_role) and decision.auth_action != ROLE_INSUFFICIENT: | ||
| 68 | + alarms.append( | ||
| 69 | + f"ROLE_LEAK: '{decision.intent}' için rol yetersiz ama gating uygulanmadı." | ||
| 70 | + ) | ||
| 71 | + return alarms | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +def process( | ||
| 75 | + query: str, | ||
| 76 | + role: str = "ziyaretci", | ||
| 77 | + authenticated: bool = False, | ||
| 78 | + *, | ||
| 79 | + trace_id: str | None = None, | ||
| 80 | + matcher: SimilarityMatcher | None = None, | ||
| 81 | +) -> tuple[Response, dict[str, Any]]: | ||
| 82 | + """Boru hattını izleyerek çalıştırır; (Response, trace kaydı) döndürür.""" | ||
| 83 | + | ||
| 84 | + matcher = matcher or get_default_matcher() | ||
| 85 | + trace_id = trace_id or new_trace_id() | ||
| 86 | + latency: dict[str, float] = {} | ||
| 87 | + | ||
| 88 | + total_start = time.perf_counter_ns() | ||
| 89 | + | ||
| 90 | + # 1) Normalizasyon (loglama/teşhis için; kök çıktısı). | ||
| 91 | + t = time.perf_counter_ns() | ||
| 92 | + normalized = normalize(query) | ||
| 93 | + query_roots = roots(query) | ||
| 94 | + latency["normalize"] = _elapsed_ms(t) | ||
| 95 | + | ||
| 96 | + # 2) Kural katmanı. | ||
| 97 | + t = time.perf_counter_ns() | ||
| 98 | + rule_match = rules.match(query) | ||
| 99 | + latency["rules"] = _elapsed_ms(t) | ||
| 100 | + | ||
| 101 | + # 3) Benzerlik + alan kapısı (yalnızca kural boş dönerse). | ||
| 102 | + t = time.perf_counter_ns() | ||
| 103 | + ranked = None if rule_match is not None else matcher.rank(query) | ||
| 104 | + in_domain = True if rule_match is not None else is_in_domain(query) | ||
| 105 | + latency["similarity"] = _elapsed_ms(t) | ||
| 106 | + | ||
| 107 | + # 4) Karar. | ||
| 108 | + t = time.perf_counter_ns() | ||
| 109 | + decision = decide_core(rule_match, ranked, role, authenticated, in_domain=in_domain) | ||
| 110 | + latency["decide"] = _elapsed_ms(t) | ||
| 111 | + | ||
| 112 | + # 5) Cevap. | ||
| 113 | + t = time.perf_counter_ns() | ||
| 114 | + response = render(decision) | ||
| 115 | + latency["render"] = _elapsed_ms(t) | ||
| 116 | + | ||
| 117 | + latency["total"] = _elapsed_ms(total_start) | ||
| 118 | + | ||
| 119 | + alarms = check_auth_alarms(decision, authenticated, role) | ||
| 120 | + | ||
| 121 | + trace: dict[str, Any] = { | ||
| 122 | + "trace_id": trace_id, | ||
| 123 | + "raw_query": query, | ||
| 124 | + "role": role, | ||
| 125 | + "authenticated": authenticated, | ||
| 126 | + "normalized": normalized, | ||
| 127 | + "roots": query_roots, | ||
| 128 | + "rule_layer": { | ||
| 129 | + "hit": rule_match is not None, | ||
| 130 | + "intent": rule_match.intent if rule_match else None, | ||
| 131 | + "matched": list(rule_match.matched) if rule_match else [], | ||
| 132 | + }, | ||
| 133 | + "similarity": { | ||
| 134 | + "evaluated": ranked is not None, | ||
| 135 | + "in_domain": in_domain, | ||
| 136 | + "top_k": [{"intent": s.intent, "score": round(s.score, 4)} for s in decision.top_k], | ||
| 137 | + "margin": decision.margin, | ||
| 138 | + }, | ||
| 139 | + "decision": { | ||
| 140 | + "intent": decision.intent, | ||
| 141 | + "fallback": decision.fallback, | ||
| 142 | + "source": decision.source, | ||
| 143 | + "confidence": round(decision.confidence, 4), | ||
| 144 | + "tie_break": decision.tie_break, | ||
| 145 | + "auth_action": decision.auth_action, | ||
| 146 | + "required_role": decision.required_role, | ||
| 147 | + }, | ||
| 148 | + "response_id": response.response_id, | ||
| 149 | + "latency_ms": latency, | ||
| 150 | + "alarms": alarms, | ||
| 151 | + } | ||
| 152 | + return response, trace | ||
| 153 | + | ||
| 154 | + | ||
| 155 | +def trace_to_json(trace: dict[str, Any]) -> str: | ||
| 156 | + """Trace kaydını tek satır JSON'a çevirir (Türkçe karakterler korunur).""" | ||
| 157 | + | ||
| 158 | + return json.dumps(trace, ensure_ascii=False) | ||
src/responder.pyadded+101 -0
| @@ -0,0 +1,101 @@ | |||
| 1 | +"""Cevap üretimi: Decision -> kullanıcıya gösterilecek metin. | ||
| 2 | + | ||
| 3 | +İlkeler (rehber §0): | ||
| 4 | +- Gerçek etiket/yol içeren `response_template` kullanılır (katalogda hazır). | ||
| 5 | +- Rol-farkında: seçilen intent oturum/rol gerektiriyor ve kullanıcı yetersizse, | ||
| 6 | + cevabın başına kibar bir uyarı eklenir (ama adımlar yine gösterilir; kullanıcı | ||
| 7 | + ne gerektiğini görsün). | ||
| 8 | +- FALLBACK: anlaşılmayan/kapsam dışı sorularda netleştirme metni. | ||
| 9 | +- `response_id` kararlıdır (testler metne değil id'ye bakar). | ||
| 10 | +""" | ||
| 11 | + | ||
| 12 | +from __future__ import annotations | ||
| 13 | + | ||
| 14 | +from dataclasses import dataclass | ||
| 15 | +from typing import Final | ||
| 16 | + | ||
| 17 | +from .catalog import FALLBACK, get_intent | ||
| 18 | +from .decision import ( | ||
| 19 | + LOGIN_REQUIRED, | ||
| 20 | + ROLE_INSUFFICIENT, | ||
| 21 | + Decision, | ||
| 22 | + decide, | ||
| 23 | +) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +# Rollerin insan-okunur (arayüzdeki) adları. | ||
| 27 | +ROLE_DISPLAY: Final[dict[str, str]] = { | ||
| 28 | + "ziyaretci": "Ziyaretçi", | ||
| 29 | + "ogrenci": "Öğrenci", | ||
| 30 | + "ogretmen": "Öğretmen", | ||
| 31 | + "yonetici": "Yönetici", | ||
| 32 | + "admin": "ADMIN", | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +@dataclass(frozen=True) | ||
| 37 | +class Response: | ||
| 38 | + """Kullanıcıya dönecek nihai cevap.""" | ||
| 39 | + | ||
| 40 | + response_id: str | ||
| 41 | + text: str | ||
| 42 | + intent: str | None | ||
| 43 | + fallback: bool | ||
| 44 | + auth_action: str | None = None | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +def role_display(role: str) -> str: | ||
| 48 | + """Rolün arayüzdeki adını döndürür (bilinmiyorsa olduğu gibi).""" | ||
| 49 | + | ||
| 50 | + return ROLE_DISPLAY.get(role, role) | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +def render(decision: Decision) -> Response: | ||
| 54 | + """Bir Decision'ı kullanıcı-yüzlü Response'a çevirir.""" | ||
| 55 | + | ||
| 56 | + if decision.fallback or decision.intent is None: | ||
| 57 | + return Response( | ||
| 58 | + response_id=FALLBACK["response_id"], | ||
| 59 | + text=FALLBACK["response_template"], | ||
| 60 | + intent=None, | ||
| 61 | + fallback=True, | ||
| 62 | + ) | ||
| 63 | + | ||
| 64 | + info = get_intent(decision.intent) | ||
| 65 | + if info is None: # savunmacı: katalog dışı intent | ||
| 66 | + return Response( | ||
| 67 | + response_id=FALLBACK["response_id"], | ||
| 68 | + text=FALLBACK["response_template"], | ||
| 69 | + intent=None, | ||
| 70 | + fallback=True, | ||
| 71 | + ) | ||
| 72 | + | ||
| 73 | + body = info["response_template"] | ||
| 74 | + | ||
| 75 | + if decision.auth_action == LOGIN_REQUIRED: | ||
| 76 | + text = ( | ||
| 77 | + "Bunun için önce giriş yapmalısın (`/login`). Giriş yaptıktan sonra:\n" | ||
| 78 | + + body | ||
| 79 | + ) | ||
| 80 | + elif decision.auth_action == ROLE_INSUFFICIENT: | ||
| 81 | + needed = role_display(decision.required_role or "") | ||
| 82 | + text = ( | ||
| 83 | + f"Bu işlem için en az **{needed}** yetkisi gerekir; mevcut rolün bunu " | ||
| 84 | + f"yapmaya yetmiyor. Yine de adımlar şöyle:\n" + body | ||
| 85 | + ) | ||
| 86 | + else: | ||
| 87 | + text = body | ||
| 88 | + | ||
| 89 | + return Response( | ||
| 90 | + response_id=info["response_id"], | ||
| 91 | + text=text, | ||
| 92 | + intent=decision.intent, | ||
| 93 | + fallback=False, | ||
| 94 | + auth_action=decision.auth_action, | ||
| 95 | + ) | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def answer(query: str, role: str = "ziyaretci", authenticated: bool = False) -> Response: | ||
| 99 | + """Uçtan uca kolaylık: karar ver + cevabı üret.""" | ||
| 100 | + | ||
| 101 | + return render(decide(query, role=role, authenticated=authenticated)) | ||
src/rules.pyadded+257 -0
| @@ -0,0 +1,257 @@ | |||
| 1 | +"""Kural katmanı: yüksek-kesinlik, deterministik intent eşleşmesi. | ||
| 2 | + | ||
| 3 | +Felsefe: Bu katman HER soruyu kapsamaz; yalnızca anahtar kelimesi TEK ANLAMLI | ||
| 4 | +olan (ve özellikle güvenlik açısından kritik) soruları deterministik olarak | ||
| 5 | +bağlar. Belirsizlikte (birden çok intent eşit güçle eşleşirse) bilerek KARAR | ||
| 6 | +VERMEZ (None döner) ve kararı benzerlik katmanına bırakır. Amaç coverage değil, | ||
| 7 | +kapsanan sorularda ~%100 kesinliktir. | ||
| 8 | + | ||
| 9 | +Eşleşme tabanı: `normalize.folded_tokens` (küçük harf + aksan katlama, STEM YOK) + | ||
| 10 | +ÖNEK karşılaştırması. Stemmer bilinçli olarak KULLANILMAZ; çünkü kök bulma | ||
| 11 | +'yapamıyor' -> 'yap' gibi kelimeleri çökertip kesinliği bozar. Önek eşleşmesi | ||
| 12 | +Türkçe çekimi ('şifre' <- 'şifremi') çökertmeden yakalar. | ||
| 13 | + | ||
| 14 | +Kural grubu (group): | ||
| 15 | + {"all": [kelime, ...], "none": [kelime, ...]?} | ||
| 16 | +Grup eşleşir <=> "all" içindeki her kelime soruda VAR ve "none" içindeki hiçbir | ||
| 17 | +kelime soruda YOK. Bir intent'in grupları OR ile birleşir; grup büyüklüğü (all | ||
| 18 | +uzunluğu) o eşleşmenin "özgüllük skoru"dur — belirsizlik çözümünde kullanılır. | ||
| 19 | +""" | ||
| 20 | + | ||
| 21 | +from __future__ import annotations | ||
| 22 | + | ||
| 23 | +from dataclasses import dataclass | ||
| 24 | +from typing import Any, Final | ||
| 25 | + | ||
| 26 | +from .normalize import fold_accents, folded_tokens, normalize | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +# Ham (Türkçe) kelimelerle yazılmış kurallar; yüklemede katlanmış köke indirgenir. | ||
| 30 | +_RAW_RULES: Final[list[dict[str, Any]]] = [ | ||
| 31 | + {"intent": "greeting", "groups": [ | ||
| 32 | + {"all": ["merhaba"]}, {"all": ["selam"]}, {"all": ["günaydın"]}, | ||
| 33 | + {"all": ["naber"]}, {"all": ["hey"]}, | ||
| 34 | + ]}, | ||
| 35 | + {"intent": "help_capabilities", "groups": [ | ||
| 36 | + {"all": ["neler", "yapabil"], "none": ["yönetici", "öğretmen", "rol", "yetki"]}, | ||
| 37 | + {"all": ["ne", "yapabil"], "none": ["yönetici", "öğretmen", "rol", "yetki"]}, | ||
| 38 | + {"all": ["özellik"]}, | ||
| 39 | + {"all": ["yardım", "edebil"]}, | ||
| 40 | + ]}, | ||
| 41 | + {"intent": "roles_permissions", "groups": [ | ||
| 42 | + {"all": ["yönetici", "yapabil"]}, {"all": ["öğretmen", "yapabil"]}, | ||
| 43 | + {"all": ["rol", "kademe"]}, {"all": ["yetki", "seviye"]}, | ||
| 44 | + {"all": ["rol", "nedir"]}, {"all": ["kim", "yetki"]}, | ||
| 45 | + ]}, | ||
| 46 | + {"intent": "privacy_security", "groups": [ | ||
| 47 | + {"all": ["arkadaş"]}, {"all": ["başka", "öğrenci"]}, | ||
| 48 | + {"all": ["başka", "öğretmen"]}, {"all": ["başka", "birinin"]}, | ||
| 49 | + {"all": ["başka", "karne"]}, {"all": ["başka", "telefon"]}, | ||
| 50 | + {"all": ["öğretmen", "telefon"]}, {"all": ["herkes", "not"]}, | ||
| 51 | + {"all": ["birinin", "karne"]}, | ||
| 52 | + ]}, | ||
| 53 | + {"intent": "account_access_problem", "groups": [ | ||
| 54 | + {"all": ["şifre", "unut"]}, {"all": ["şifre", "yanlış"]}, | ||
| 55 | + {"all": ["şifre", "sıfırla"]}, {"all": ["parola", "unut"]}, | ||
| 56 | + {"all": ["parola", "hatırla"]}, {"all": ["giremiyor"]}, | ||
| 57 | + {"all": ["yapamıyor"]}, {"all": ["erişemiyor"]}, | ||
| 58 | + ]}, | ||
| 59 | + {"intent": "login_how", "groups": [ | ||
| 60 | + {"all": ["giriş", "yap"], "none": ["yapamıyor", "giremiyor", "mesai"]}, | ||
| 61 | + {"all": ["log", "in"]}, | ||
| 62 | + ]}, | ||
| 63 | + {"intent": "logout_how", "groups": [ | ||
| 64 | + {"all": ["oturum", "kapat"]}, {"all": ["sistemden", "çık"]}, | ||
| 65 | + {"all": ["hesap", "çık"]}, | ||
| 66 | + ]}, | ||
| 67 | + {"intent": "session_info", "groups": [ | ||
| 68 | + {"all": ["oturum", "süre"]}, {"all": ["kaç", "gün", "geçerli"]}, | ||
| 69 | + ]}, | ||
| 70 | + {"intent": "report_card_view", "groups": [ | ||
| 71 | + {"all": ["karne"], "none": ["öğrenci", "başka", "birinin"]}, | ||
| 72 | + {"all": ["harf", "not"]}, | ||
| 73 | + ]}, | ||
| 74 | + {"intent": "weighted_average_info", "groups": [ | ||
| 75 | + {"all": ["ortalama", "hesap"]}, {"all": ["ağırlık", "ortalama"]}, | ||
| 76 | + {"all": ["ağırlıklı", "ortalama"]}, | ||
| 77 | + ]}, | ||
| 78 | + {"intent": "student_marks_lookup", "groups": [ | ||
| 79 | + {"all": ["öğrenci", "karne"]}, {"all": ["öğrenci", "not", "gör"]}, | ||
| 80 | + {"all": ["öğrenci", "not", "sorgu"]}, {"all": ["öğrenci", "not", "bak"]}, | ||
| 81 | + ]}, | ||
| 82 | + {"intent": "note_create", "groups": [ | ||
| 83 | + {"all": ["defter"]}, {"all": ["yeni", "not"]}, {"all": ["not", "oluştur"]}, | ||
| 84 | + ]}, | ||
| 85 | + {"intent": "course_create", "groups": [ | ||
| 86 | + {"all": ["yeni", "ders"], "none": ["saat", "oturum", "sınav"]}, | ||
| 87 | + {"all": ["ders", "oluştur"], "none": ["saat", "oturum", "sınav"]}, | ||
| 88 | + {"all": ["ders", "aç"], "none": ["saat", "oturum", "sınav"]}, | ||
| 89 | + {"all": ["sınıf", "oluştur"]}, | ||
| 90 | + ]}, | ||
| 91 | + {"intent": "lesson_session_add", "groups": [ | ||
| 92 | + {"all": ["oturum", "ekle"]}, {"all": ["oturum", "oluştur"]}, | ||
| 93 | + {"all": ["ders", "oturum"]}, | ||
| 94 | + {"all": ["ders", "saat"], "none": ["var", "yok", "yoklama", "işaretle"]}, | ||
| 95 | + ]}, | ||
| 96 | + {"intent": "roll_call", "groups": [ | ||
| 97 | + {"all": ["yoklama", "al"]}, {"all": ["yoklama", "kaydet"]}, | ||
| 98 | + {"all": ["devam", "kontrol"]}, | ||
| 99 | + ]}, | ||
| 100 | + {"intent": "exam_create", "groups": [ | ||
| 101 | + {"all": ["sınav", "oluştur"]}, {"all": ["yeni", "sınav"]}, | ||
| 102 | + {"all": ["sınav", "hazırla"]}, {"all": ["yazılı", "oluştur"]}, | ||
| 103 | + ]}, | ||
| 104 | + {"intent": "exam_add_question", "groups": [ | ||
| 105 | + {"all": ["soru", "ekle"]}, {"all": ["soru", "oluştur"]}, | ||
| 106 | + {"all": ["seçmeli", "soru"]}, | ||
| 107 | + ]}, | ||
| 108 | + {"intent": "exam_grade_student", "groups": [ | ||
| 109 | + {"all": ["öğrenci", "not", "gir"]}, {"all": ["notlandır"]}, | ||
| 110 | + {"all": ["sınav", "puanla"]}, | ||
| 111 | + ]}, | ||
| 112 | + {"intent": "event_create", "groups": [ | ||
| 113 | + {"all": ["etkinlik", "oluştur"]}, {"all": ["etkinlik", "ekle"]}, | ||
| 114 | + {"all": ["etkinlik", "planla"]}, | ||
| 115 | + ]}, | ||
| 116 | + {"intent": "user_role_change", "groups": [ | ||
| 117 | + {"all": ["rol", "değiştir"]}, {"all": ["rol", "ata"]}, | ||
| 118 | + {"all": ["yetki", "yükselt"]}, {"all": ["kullanıcı", "rol"]}, | ||
| 119 | + ]}, | ||
| 120 | + {"intent": "term_manage", "groups": [ | ||
| 121 | + {"all": ["dönem", "oluştur"]}, {"all": ["akademik", "dönem"]}, | ||
| 122 | + {"all": ["yarıyıl"]}, | ||
| 123 | + ]}, | ||
| 124 | + {"intent": "school_settings", "groups": [ | ||
| 125 | + {"all": ["okul", "ayar"]}, {"all": ["not", "bant"]}, | ||
| 126 | + {"all": ["sınav", "tür", "ağırlık"]}, | ||
| 127 | + ]}, | ||
| 128 | + {"intent": "work_checkin_out", "groups": [ | ||
| 129 | + {"all": ["mesai", "giriş"]}, {"all": ["mesai", "çık"]}, | ||
| 130 | + {"all": ["işe", "gel"]}, | ||
| 131 | + ]}, | ||
| 132 | + # --- Aşama 11: kapsamı olmayan/karışan intent'ler için hedefli kurallar --- | ||
| 133 | + {"intent": "guide_info", "groups": [ | ||
| 134 | + {"all": ["kılavuz"]}, {"all": ["guide"]}, {"all": ["adım", "tanıtım"]}, | ||
| 135 | + ]}, | ||
| 136 | + {"intent": "register_how", "groups": [ | ||
| 137 | + {"all": ["üye", "ol"]}, {"all": ["kayıt", "ol"]}, | ||
| 138 | + {"all": ["kayıt", "form"]}, {"all": ["hesap", "aç"]}, | ||
| 139 | + ]}, | ||
| 140 | + {"intent": "profile_edit", "groups": [ | ||
| 141 | + {"all": ["iletişim", "bilgi", "değiştir"]}, | ||
| 142 | + {"all": ["ad", "soyad", "güncelle"]}, | ||
| 143 | + {"all": ["telefon", "değiştir"]}, | ||
| 144 | + ]}, | ||
| 145 | + {"intent": "attendance_view", "groups": [ | ||
| 146 | + {"all": ["devamsızlık", "gör"]}, {"all": ["devamsızlık", "durum"]}, | ||
| 147 | + {"all": ["yoklama", "geçmiş"]}, {"all": ["devam", "yüzde"]}, | ||
| 148 | + ]}, | ||
| 149 | + {"intent": "student_attendance_lookup", "groups": [ | ||
| 150 | + {"all": ["öğrenci", "yoklama"]}, {"all": ["öğrenci", "devamsızlık"]}, | ||
| 151 | + {"all": ["öğrenci", "devam", "durum"]}, | ||
| 152 | + ]}, | ||
| 153 | + {"intent": "event_attendance_mark", "groups": [ | ||
| 154 | + {"all": ["etkinlik", "katıl"]}, {"all": ["etkinlik", "yoklama"]}, | ||
| 155 | + ]}, | ||
| 156 | +] | ||
| 157 | + | ||
| 158 | + | ||
| 159 | +def _kw_of(word: str) -> str: | ||
| 160 | + """Ham kelimeyi katlanmış (ascii, stem YOK) forma indirger.""" | ||
| 161 | + | ||
| 162 | + return fold_accents(normalize(word)).replace(" ", "") | ||
| 163 | + | ||
| 164 | + | ||
| 165 | +@dataclass(frozen=True) | ||
| 166 | +class _Group: | ||
| 167 | + all_kw: tuple[str, ...] | ||
| 168 | + none_kw: tuple[str, ...] = () | ||
| 169 | + | ||
| 170 | + | ||
| 171 | +@dataclass(frozen=True) | ||
| 172 | +class _Rule: | ||
| 173 | + intent: str | ||
| 174 | + groups: tuple[_Group, ...] | ||
| 175 | + | ||
| 176 | + | ||
| 177 | +def _compile_rules(raw_rules: list[dict[str, Any]]) -> list[_Rule]: | ||
| 178 | + compiled: list[_Rule] = [] | ||
| 179 | + for raw in raw_rules: | ||
| 180 | + groups = tuple( | ||
| 181 | + _Group( | ||
| 182 | + all_kw=tuple(_kw_of(w) for w in group["all"]), | ||
| 183 | + none_kw=tuple(_kw_of(w) for w in group.get("none", ())), | ||
| 184 | + ) | ||
| 185 | + for group in raw["groups"] | ||
| 186 | + ) | ||
| 187 | + compiled.append(_Rule(intent=raw["intent"], groups=groups)) | ||
| 188 | + return compiled | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +_RULES: Final[list[_Rule]] = _compile_rules(_RAW_RULES) | ||
| 192 | + | ||
| 193 | + | ||
| 194 | +@dataclass(frozen=True) | ||
| 195 | +class RuleMatch: | ||
| 196 | + """Kural katmanının kararı.""" | ||
| 197 | + | ||
| 198 | + intent: str | ||
| 199 | + score: int | ||
| 200 | + matched: tuple[str, ...] | ||
| 201 | + reason: str | ||
| 202 | + | ||
| 203 | + | ||
| 204 | +def _present(keyword: str, tokens: list[str]) -> bool: | ||
| 205 | + """Anahtar kelime soruda var mı? (>=2 harf önek, aksi hâlde tam eşleşme).""" | ||
| 206 | + | ||
| 207 | + if len(keyword) >= 2: | ||
| 208 | + return any(token.startswith(keyword) for token in tokens) | ||
| 209 | + return any(token == keyword for token in tokens) | ||
| 210 | + | ||
| 211 | + | ||
| 212 | +def _group_matches(group: _Group, tokens: list[str]) -> bool: | ||
| 213 | + if any(not _present(k, tokens) for k in group.all_kw): | ||
| 214 | + return False | ||
| 215 | + if any(_present(k, tokens) for k in group.none_kw): | ||
| 216 | + return False | ||
| 217 | + return True | ||
| 218 | + | ||
| 219 | + | ||
| 220 | +def match(query: str) -> RuleMatch | None: | ||
| 221 | + """Soruyu kural katmanından geçirir. | ||
| 222 | + | ||
| 223 | + Returns: | ||
| 224 | + Tek bir intent en yüksek özgüllükle eşleşirse RuleMatch; hiçbir kural | ||
| 225 | + eşleşmezse veya birden çok intent aynı en yüksek skorda eşleşirse (belirsiz) | ||
| 226 | + None. | ||
| 227 | + """ | ||
| 228 | + | ||
| 229 | + tokens = folded_tokens(query) | ||
| 230 | + if not tokens: | ||
| 231 | + return None | ||
| 232 | + | ||
| 233 | + best_by_intent: dict[str, tuple[int, tuple[str, ...]]] = {} | ||
| 234 | + for rule in _RULES: | ||
| 235 | + for group in rule.groups: | ||
| 236 | + if _group_matches(group, tokens): | ||
| 237 | + score = len(group.all_kw) | ||
| 238 | + prev = best_by_intent.get(rule.intent) | ||
| 239 | + if prev is None or score > prev[0]: | ||
| 240 | + best_by_intent[rule.intent] = (score, group.all_kw) | ||
| 241 | + | ||
| 242 | + if not best_by_intent: | ||
| 243 | + return None | ||
| 244 | + | ||
| 245 | + ranked = sorted(best_by_intent.items(), key=lambda kv: kv[1][0], reverse=True) | ||
| 246 | + top_intent, (top_score, matched) = ranked[0] | ||
| 247 | + | ||
| 248 | + # Belirsizlik: aynı en yüksek skorda birden çok intent -> karar verme. | ||
| 249 | + if len(ranked) > 1 and ranked[1][1][0] == top_score: | ||
| 250 | + return None | ||
| 251 | + | ||
| 252 | + return RuleMatch( | ||
| 253 | + intent=top_intent, | ||
| 254 | + score=top_score, | ||
| 255 | + matched=matched, | ||
| 256 | + reason=f"kural: {top_intent} <- {list(matched)}", | ||
| 257 | + ) | ||
src/similarity.pyadded+183 -0
| @@ -0,0 +1,183 @@ | |||
| 1 | +"""Benzerlik katmanı: saf-Python TF-IDF karakter n-gram + kosinüs. | ||
| 2 | + | ||
| 3 | +Kural katmanı bir soruyu kapsamadığında (None döndüğünde) devreye girer. Katalog | ||
| 4 | +`example_questions`'larını karakter n-gram TF-IDF vektörlerine çevirir; sorguyu | ||
| 5 | +aynı uzaya taşıyıp en yakın örneği kosinüs benzerliğiyle bulur ve o örneğin | ||
| 6 | +intent'ini döndürür. | ||
| 7 | + | ||
| 8 | +Neden karakter n-gram: Türkçe sondan-eklemeli olduğundan ('notlarımı' ~ 'notlar') | ||
| 9 | +karakter n-gram'lar çekim varyasyonlarını kelime-torbasından çok daha iyi tolere | ||
| 10 | +eder ve harici model/bağımlılık gerektirmez. | ||
| 11 | + | ||
| 12 | +Neden vektör DB yok: ~215 örnek vektörde brute-force kosinüs milisaniyenin | ||
| 13 | +altındadır; FAISS/Chroma gereksizdir. | ||
| 14 | + | ||
| 15 | +Arayüz soyuttur (SimilarityMatcher); ileride yerel embedding modeli aynı | ||
| 16 | +`rank()/best()` sözleşmesiyle takılabilir. | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +from __future__ import annotations | ||
| 20 | + | ||
| 21 | +import math | ||
| 22 | +from collections import Counter | ||
| 23 | +from dataclasses import dataclass | ||
| 24 | +from typing import Final, Iterable | ||
| 25 | + | ||
| 26 | +from .catalog import INTENTS | ||
| 27 | +from .normalize import fold_accents, normalize | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +DEFAULT_NGRAMS: Final[tuple[int, ...]] = (3, 4, 5) | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +def _prepare(text: str) -> str: | ||
| 34 | + """Normalize + katla + boşluklarla sınır işaretle (n-gram için).""" | ||
| 35 | + | ||
| 36 | + folded = fold_accents(normalize(text)) | ||
| 37 | + return f" {folded} " if folded else "" | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def char_ngrams(text: str, ns: Iterable[int] = DEFAULT_NGRAMS) -> Counter[str]: | ||
| 41 | + """Metnin karakter n-gram frekanslarını döndürür.""" | ||
| 42 | + | ||
| 43 | + prepared = _prepare(text) | ||
| 44 | + counts: Counter[str] = Counter() | ||
| 45 | + if not prepared: | ||
| 46 | + return counts | ||
| 47 | + length = len(prepared) | ||
| 48 | + for n in ns: | ||
| 49 | + if length < n: | ||
| 50 | + continue | ||
| 51 | + for i in range(length - n + 1): | ||
| 52 | + counts[prepared[i : i + n]] += 1 | ||
| 53 | + return counts | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +@dataclass(frozen=True) | ||
| 57 | +class ScoredIntent: | ||
| 58 | + intent: str | ||
| 59 | + score: float | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +class SimilarityMatcher: | ||
| 63 | + """Karakter n-gram TF-IDF üzerinden intent benzerliği.""" | ||
| 64 | + | ||
| 65 | + def __init__( | ||
| 66 | + self, | ||
| 67 | + examples: list[tuple[str, str]], | ||
| 68 | + ns: Iterable[int] = DEFAULT_NGRAMS, | ||
| 69 | + ) -> None: | ||
| 70 | + """examples: (intent, question) çiftleri.""" | ||
| 71 | + | ||
| 72 | + self._ns = tuple(ns) | ||
| 73 | + self._intents: list[str] = [] | ||
| 74 | + self._doc_tfs: list[Counter[str]] = [] | ||
| 75 | + | ||
| 76 | + document_frequency: Counter[str] = Counter() | ||
| 77 | + for intent, question in examples: | ||
| 78 | + tf = char_ngrams(question, self._ns) | ||
| 79 | + if not tf: | ||
| 80 | + continue | ||
| 81 | + self._intents.append(intent) | ||
| 82 | + self._doc_tfs.append(tf) | ||
| 83 | + for gram in tf: | ||
| 84 | + document_frequency[gram] += 1 | ||
| 85 | + | ||
| 86 | + num_docs = len(self._doc_tfs) | ||
| 87 | + # Düzeltmeli (smoothed) IDF. | ||
| 88 | + self._idf: dict[str, float] = { | ||
| 89 | + gram: math.log((num_docs + 1) / (df + 1)) + 1.0 | ||
| 90 | + for gram, df in document_frequency.items() | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + # Örnek vektörlerini ve normlarını önceden hesapla. | ||
| 94 | + self._doc_vectors: list[dict[str, float]] = [] | ||
| 95 | + self._doc_norms: list[float] = [] | ||
| 96 | + for tf in self._doc_tfs: | ||
| 97 | + vector = self._to_vector(tf) | ||
| 98 | + self._doc_vectors.append(vector) | ||
| 99 | + self._doc_norms.append(_norm(vector)) | ||
| 100 | + | ||
| 101 | + @classmethod | ||
| 102 | + def from_catalog(cls, ns: Iterable[int] = DEFAULT_NGRAMS) -> "SimilarityMatcher": | ||
| 103 | + """Katalog example_questions'larından bir eşleştirici kurar.""" | ||
| 104 | + | ||
| 105 | + examples = [ | ||
| 106 | + (item["intent"], question) | ||
| 107 | + for item in INTENTS | ||
| 108 | + for question in item["example_questions"] | ||
| 109 | + ] | ||
| 110 | + return cls(examples, ns=ns) | ||
| 111 | + | ||
| 112 | + @property | ||
| 113 | + def size(self) -> int: | ||
| 114 | + """Dizinlenmiş örnek sayısı.""" | ||
| 115 | + | ||
| 116 | + return len(self._doc_vectors) | ||
| 117 | + | ||
| 118 | + def _to_vector(self, tf: Counter[str]) -> dict[str, float]: | ||
| 119 | + """TF sayımını IDF ağırlıklı vektöre çevirir (bilinmeyen gram'lar atlanır).""" | ||
| 120 | + | ||
| 121 | + return { | ||
| 122 | + gram: count * self._idf[gram] | ||
| 123 | + for gram, count in tf.items() | ||
| 124 | + if gram in self._idf | ||
| 125 | + } | ||
| 126 | + | ||
| 127 | + def rank(self, query: str) -> list[ScoredIntent]: | ||
| 128 | + """Sorguyu intent'lere göre azalan benzerlikle sıralar. | ||
| 129 | + | ||
| 130 | + Her intent için, o intent'e ait örnekler arasındaki EN YÜKSEK kosinüs | ||
| 131 | + benzerliği o intent'in skorudur. | ||
| 132 | + """ | ||
| 133 | + | ||
| 134 | + query_tf = char_ngrams(query, self._ns) | ||
| 135 | + query_vec = self._to_vector(query_tf) | ||
| 136 | + query_norm = _norm(query_vec) | ||
| 137 | + if query_norm == 0.0: | ||
| 138 | + return [] | ||
| 139 | + | ||
| 140 | + best: dict[str, float] = {} | ||
| 141 | + for intent, doc_vec, doc_norm in zip( | ||
| 142 | + self._intents, self._doc_vectors, self._doc_norms | ||
| 143 | + ): | ||
| 144 | + if doc_norm == 0.0: | ||
| 145 | + continue | ||
| 146 | + score = _dot(query_vec, doc_vec) / (query_norm * doc_norm) | ||
| 147 | + if score > best.get(intent, 0.0): | ||
| 148 | + best[intent] = score | ||
| 149 | + | ||
| 150 | + return [ | ||
| 151 | + ScoredIntent(intent, score) | ||
| 152 | + for intent, score in sorted(best.items(), key=lambda kv: kv[1], reverse=True) | ||
| 153 | + ] | ||
| 154 | + | ||
| 155 | + def best(self, query: str) -> ScoredIntent | None: | ||
| 156 | + """En yüksek skorlu intent'i döndürür (yoksa None).""" | ||
| 157 | + | ||
| 158 | + ranked = self.rank(query) | ||
| 159 | + return ranked[0] if ranked else None | ||
| 160 | + | ||
| 161 | + | ||
| 162 | +def _dot(a: dict[str, float], b: dict[str, float]) -> float: | ||
| 163 | + # Daha kısa sözlük üzerinde döngü kur. | ||
| 164 | + if len(a) > len(b): | ||
| 165 | + a, b = b, a | ||
| 166 | + return sum(weight * b.get(gram, 0.0) for gram, weight in a.items()) | ||
| 167 | + | ||
| 168 | + | ||
| 169 | +def _norm(vector: dict[str, float]) -> float: | ||
| 170 | + return math.sqrt(sum(weight * weight for weight in vector.values())) | ||
| 171 | + | ||
| 172 | + | ||
| 173 | +# Katalogdan kurulmuş, süreç ömrü boyunca yeniden kullanılan varsayılan örnek. | ||
| 174 | +_DEFAULT_MATCHER: SimilarityMatcher | None = None | ||
| 175 | + | ||
| 176 | + | ||
| 177 | +def get_default_matcher() -> SimilarityMatcher: | ||
| 178 | + """Katalogdan kurulmuş paylaşılan eşleştiriciyi döndürür (tembel kurulum).""" | ||
| 179 | + | ||
| 180 | + global _DEFAULT_MATCHER | ||
| 181 | + if _DEFAULT_MATCHER is None: | ||
| 182 | + _DEFAULT_MATCHER = SimilarityMatcher.from_catalog() | ||
| 183 | + return _DEFAULT_MATCHER | ||
tests/e2e/__init__.pyadded+1 -0
| @@ -0,0 +1 @@ | |||
| 1 | +"""tests/e2e tests.""" | ||
tests/e2e/test_conversation.pyadded+56 -0
| @@ -0,0 +1,56 @@ | |||
| 1 | +"""Aşama 8 e2e testleri: uçtan uca sorgu -> cevap senaryoları (rol + gating).""" | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src.responder import answer | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +class VisitorScenarios(unittest.TestCase): | ||
| 9 | + def test_login_how_public(self) -> None: | ||
| 10 | + r = answer("Nasıl giriş yaparım?", role="ziyaretci", authenticated=False) | ||
| 11 | + self.assertEqual(r.response_id, "login_instructions") | ||
| 12 | + self.assertIsNone(r.auth_action) # herkese açık | ||
| 13 | + | ||
| 14 | + def test_personal_data_requires_login(self) -> None: | ||
| 15 | + r = answer("Karnemi göster", role="ziyaretci", authenticated=False) | ||
| 16 | + self.assertEqual(r.response_id, "report_card_info") | ||
| 17 | + self.assertEqual(r.auth_action, "login_required") | ||
| 18 | + self.assertIn("/login", r.text) | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +class RoleScenarios(unittest.TestCase): | ||
| 22 | + def test_student_cannot_create_course(self) -> None: | ||
| 23 | + r = answer("yeni ders oluştur", role="ogrenci", authenticated=True) | ||
| 24 | + self.assertEqual(r.response_id, "course_create_instructions") | ||
| 25 | + self.assertEqual(r.auth_action, "role_insufficient") | ||
| 26 | + self.assertIn("Öğretmen", r.text) | ||
| 27 | + | ||
| 28 | + def test_teacher_can_create_course(self) -> None: | ||
| 29 | + r = answer("yeni ders oluştur", role="ogretmen", authenticated=True) | ||
| 30 | + self.assertEqual(r.response_id, "course_create_instructions") | ||
| 31 | + self.assertIsNone(r.auth_action) | ||
| 32 | + | ||
| 33 | + def test_student_enters_exam_room(self) -> None: | ||
| 34 | + r = answer("Sınav odasını nasıl açarım?", role="ogrenci", authenticated=True) | ||
| 35 | + self.assertEqual(r.response_id, "exam_enter_room_instructions") | ||
| 36 | + self.assertIsNone(r.auth_action) | ||
| 37 | + | ||
| 38 | + def test_admin_can_change_roles(self) -> None: | ||
| 39 | + r = answer("bir kullanıcının rolünü değiştir", role="admin", authenticated=True) | ||
| 40 | + self.assertEqual(r.response_id, "user_role_change_instructions") | ||
| 41 | + self.assertIsNone(r.auth_action) | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +class SafetyScenarios(unittest.TestCase): | ||
| 45 | + def test_other_students_data_blocked(self) -> None: | ||
| 46 | + r = answer("Arkadaşımın notlarını göster", role="ogrenci", authenticated=True) | ||
| 47 | + self.assertEqual(r.response_id, "privacy_policy_message") | ||
| 48 | + | ||
| 49 | + def test_gibberish_falls_back(self) -> None: | ||
| 50 | + r = answer("qwzx plkj mnbv zzz") | ||
| 51 | + self.assertTrue(r.fallback) | ||
| 52 | + self.assertEqual(r.response_id, "fallback_clarification") | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +if __name__ == "__main__": | ||
| 56 | + unittest.main() | ||
tests/integration/__init__.pyadded+1 -0
| @@ -0,0 +1 @@ | |||
| 1 | +"""tests/integration tests.""" | ||
tests/integration/test_decision_benchmark.pyadded+66 -0
| @@ -0,0 +1,66 @@ | |||
| 1 | +"""Aşama 7 integration/değerlendirme: karar katmanının (eşikli) benchmark baseline'ı. | ||
| 2 | + | ||
| 3 | +Eşik eklenince yeni metrikler doğar: | ||
| 4 | +- coverage: in-scope soruların kaçı FALLBACK yerine cevaplandı. | ||
| 5 | +- accuracy_on_covered: cevaplanınca ne kadar doğru. | ||
| 6 | +- oos_recall: OOS soruların kaçı doğru şekilde FALLBACK'e atıldı. | ||
| 7 | +- false_fallback: in-scope iken haksızca FALLBACK'e atılanlar. | ||
| 8 | +""" | ||
| 9 | + | ||
| 10 | +import unittest | ||
| 11 | + | ||
| 12 | +from src.benchmark import OOS_LABEL, load_benchmark | ||
| 13 | +from src.decision import DEFAULT_THRESHOLD, decide | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def evaluate_decision(threshold: float = DEFAULT_THRESHOLD) -> dict: | ||
| 17 | + records = load_benchmark() | ||
| 18 | + ins = [r for r in records if r["expected_intent"] != OOS_LABEL] | ||
| 19 | + oos = [r for r in records if r["expected_intent"] == OOS_LABEL] | ||
| 20 | + | ||
| 21 | + covered = correct = 0 | ||
| 22 | + for r in ins: | ||
| 23 | + d = decide(r["question"], threshold=threshold) | ||
| 24 | + if not d.fallback: | ||
| 25 | + covered += 1 | ||
| 26 | + if d.intent == r["expected_intent"]: | ||
| 27 | + correct += 1 | ||
| 28 | + | ||
| 29 | + oos_fallback = sum(1 for r in oos if decide(r["question"], threshold=threshold).fallback) | ||
| 30 | + | ||
| 31 | + return { | ||
| 32 | + "in_scope": len(ins), | ||
| 33 | + "oos": len(oos), | ||
| 34 | + "covered": covered, | ||
| 35 | + "correct": correct, | ||
| 36 | + "coverage": covered / len(ins) if ins else 0.0, | ||
| 37 | + "accuracy_on_covered": correct / covered if covered else 0.0, | ||
| 38 | + "false_fallback": len(ins) - covered, | ||
| 39 | + "oos_recall": oos_fallback / len(oos) if oos else 0.0, | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +class DecisionBenchmarkTests(unittest.TestCase): | ||
| 44 | + @classmethod | ||
| 45 | + def setUpClass(cls) -> None: | ||
| 46 | + cls.result = evaluate_decision() | ||
| 47 | + | ||
| 48 | + def test_coverage(self) -> None: | ||
| 49 | + self.assertGreaterEqual(self.result["coverage"], 0.90) | ||
| 50 | + | ||
| 51 | + def test_accuracy_on_covered(self) -> None: | ||
| 52 | + self.assertGreaterEqual(self.result["accuracy_on_covered"], 0.75) | ||
| 53 | + | ||
| 54 | + def test_oos_recall_baseline(self) -> None: | ||
| 55 | + # Bilinen zayıflık: char n-gram OOS'u tam ayıramıyor. Aşama 11 iyileştirecek. | ||
| 56 | + self.assertGreaterEqual(self.result["oos_recall"], 0.30) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +if __name__ == "__main__": | ||
| 60 | + r = evaluate_decision() | ||
| 61 | + print(f"=== KARAR KATMANI BASELINE (threshold={DEFAULT_THRESHOLD}) ===") | ||
| 62 | + print(f"In-scope : {r['in_scope']}") | ||
| 63 | + print(f"Coverage : {r['coverage']:.1%} (covered={r['covered']})") | ||
| 64 | + print(f"Accuracy-on-covered : {r['accuracy_on_covered']:.1%} (correct={r['correct']})") | ||
| 65 | + print(f"False fallback : {r['false_fallback']}") | ||
| 66 | + print(f"OOS recall : {r['oos_recall']:.1%} ({r['oos']} OOS)") | ||
tests/integration/test_engine.pyadded+93 -0
| @@ -0,0 +1,93 @@ | |||
| 1 | +"""Aşama 12 integration testleri: backend motoru + sözleşme.""" | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src.engine import Engine, RequestError, handle_request | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +class ContractTests(unittest.TestCase): | ||
| 9 | + def setUp(self) -> None: | ||
| 10 | + self.engine = Engine() | ||
| 11 | + | ||
| 12 | + def test_response_has_contract_keys(self) -> None: | ||
| 13 | + resp = self.engine.handle({"query": "Merhaba"}) | ||
| 14 | + for key in [ | ||
| 15 | + "trace_id", "response_id", "text", "intent", | ||
| 16 | + "confidence", "fallback", "auth_action", "required_role", | ||
| 17 | + ]: | ||
| 18 | + self.assertIn(key, resp) | ||
| 19 | + | ||
| 20 | + def test_greeting(self) -> None: | ||
| 21 | + resp = self.engine.handle({"query": "Merhaba"}) | ||
| 22 | + self.assertEqual(resp["response_id"], "welcome_message") | ||
| 23 | + self.assertFalse(resp["fallback"]) | ||
| 24 | + | ||
| 25 | + def test_trace_id_honored(self) -> None: | ||
| 26 | + resp = self.engine.handle({"query": "Merhaba", "trace_id": "abc-1"}) | ||
| 27 | + self.assertEqual(resp["trace_id"], "abc-1") | ||
| 28 | + | ||
| 29 | + def test_trace_id_generated_when_absent(self) -> None: | ||
| 30 | + resp = self.engine.handle({"query": "Merhaba"}) | ||
| 31 | + self.assertTrue(resp["trace_id"].startswith("req-")) | ||
| 32 | + | ||
| 33 | + def test_role_gating_in_contract(self) -> None: | ||
| 34 | + resp = self.engine.handle( | ||
| 35 | + {"query": "yeni ders oluştur", "session": {"role": "ogrenci", "authenticated": True}} | ||
| 36 | + ) | ||
| 37 | + self.assertEqual(resp["intent"], "course_create") | ||
| 38 | + self.assertEqual(resp["auth_action"], "role_insufficient") | ||
| 39 | + self.assertEqual(resp["required_role"], "ogretmen") | ||
| 40 | + | ||
| 41 | + def test_login_required_in_contract(self) -> None: | ||
| 42 | + resp = self.engine.handle( | ||
| 43 | + {"query": "Karnemi göster", "session": {"role": "ziyaretci", "authenticated": False}} | ||
| 44 | + ) | ||
| 45 | + self.assertEqual(resp["auth_action"], "login_required") | ||
| 46 | + | ||
| 47 | + def test_fallback(self) -> None: | ||
| 48 | + resp = self.engine.handle({"query": "qwzx plkj mnbv"}) | ||
| 49 | + self.assertTrue(resp["fallback"]) | ||
| 50 | + self.assertEqual(resp["response_id"], "fallback_clarification") | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +class ValidationTests(unittest.TestCase): | ||
| 54 | + def setUp(self) -> None: | ||
| 55 | + self.engine = Engine() | ||
| 56 | + | ||
| 57 | + def test_empty_query_raises(self) -> None: | ||
| 58 | + with self.assertRaises(RequestError): | ||
| 59 | + self.engine.handle({"query": " "}) | ||
| 60 | + | ||
| 61 | + def test_missing_query_raises(self) -> None: | ||
| 62 | + with self.assertRaises(RequestError): | ||
| 63 | + self.engine.handle({}) | ||
| 64 | + | ||
| 65 | + def test_unknown_role_raises(self) -> None: | ||
| 66 | + with self.assertRaises(RequestError): | ||
| 67 | + self.engine.handle({"query": "Merhaba", "session": {"role": "kral"}}) | ||
| 68 | + | ||
| 69 | + def test_visitor_cannot_be_authenticated(self) -> None: | ||
| 70 | + with self.assertRaises(RequestError): | ||
| 71 | + self.engine.handle( | ||
| 72 | + {"query": "Merhaba", "session": {"role": "ziyaretci", "authenticated": True}} | ||
| 73 | + ) | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +class LogSinkTests(unittest.TestCase): | ||
| 77 | + def test_log_sink_receives_trace(self) -> None: | ||
| 78 | + captured: list[dict] = [] | ||
| 79 | + engine = Engine(log_sink=captured.append) | ||
| 80 | + engine.handle({"query": "Merhaba", "trace_id": "t9"}) | ||
| 81 | + self.assertEqual(len(captured), 1) | ||
| 82 | + self.assertEqual(captured[0]["trace_id"], "t9") | ||
| 83 | + self.assertIn("latency_ms", captured[0]) | ||
| 84 | + | ||
| 85 | + | ||
| 86 | +class SharedEngineTests(unittest.TestCase): | ||
| 87 | + def test_handle_request_helper(self) -> None: | ||
| 88 | + resp = handle_request({"query": "Merhaba"}) | ||
| 89 | + self.assertEqual(resp["response_id"], "welcome_message") | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +if __name__ == "__main__": | ||
| 93 | + unittest.main() | ||
tests/integration/test_pipeline_benchmark.pyadded+67 -0
| @@ -0,0 +1,67 @@ | |||
| 1 | +"""Aşama 6 integration/değerlendirme: kural + benzerlik boru hattı baseline'ı. | ||
| 2 | + | ||
| 3 | +Bu aşamada eşik/OOS YOK (o Aşama 7). Bu yüzden yalnızca in-scope sorular üzerinde | ||
| 4 | +sınıflandırma kalitesi ölçülür: accuracy ve macro-F1. Tahmin: | ||
| 5 | + kural katmanı bir şey döndürürse onu; yoksa benzerlik katmanının en iyisini kullan. | ||
| 6 | +""" | ||
| 7 | + | ||
| 8 | +import unittest | ||
| 9 | + | ||
| 10 | +from src import rules | ||
| 11 | +from src.benchmark import OOS_LABEL, load_benchmark | ||
| 12 | +from src.catalog import INTENTS | ||
| 13 | +from src.metrics import accuracy, macro_f1, per_class_scores | ||
| 14 | +from src.similarity import get_default_matcher | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +def predict(query: str) -> str: | ||
| 18 | + rule_match = rules.match(query) | ||
| 19 | + if rule_match is not None: | ||
| 20 | + return rule_match.intent | ||
| 21 | + best = get_default_matcher().best(query) | ||
| 22 | + return best.intent if best is not None else "oos" | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def evaluate_pipeline() -> dict: | ||
| 26 | + records = [r for r in load_benchmark() if r["expected_intent"] != OOS_LABEL] | ||
| 27 | + labels = {i["intent"] for i in INTENTS} | ||
| 28 | + pairs = [(r["expected_intent"], predict(r["question"])) for r in records] | ||
| 29 | + return { | ||
| 30 | + "n": len(pairs), | ||
| 31 | + "accuracy": accuracy(pairs), | ||
| 32 | + "macro_f1": macro_f1(pairs, labels), | ||
| 33 | + "pairs": pairs, | ||
| 34 | + "per_class": per_class_scores(pairs, labels), | ||
| 35 | + } | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +class PipelineBenchmarkTests(unittest.TestCase): | ||
| 39 | + @classmethod | ||
| 40 | + def setUpClass(cls) -> None: | ||
| 41 | + cls.result = evaluate_pipeline() | ||
| 42 | + | ||
| 43 | + def test_accuracy_baseline(self) -> None: | ||
| 44 | + self.assertGreaterEqual( | ||
| 45 | + self.result["accuracy"], 0.70, f"accuracy={self.result['accuracy']:.3f}" | ||
| 46 | + ) | ||
| 47 | + | ||
| 48 | + def test_macro_f1_baseline(self) -> None: | ||
| 49 | + self.assertGreaterEqual( | ||
| 50 | + self.result["macro_f1"], 0.65, f"macro_f1={self.result['macro_f1']:.3f}" | ||
| 51 | + ) | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +if __name__ == "__main__": | ||
| 55 | + result = evaluate_pipeline() | ||
| 56 | + print("=== KURAL + BENZERLIK BASELINE (in-scope, eşiksiz) ===") | ||
| 57 | + print(f"Soru sayısı : {result['n']}") | ||
| 58 | + print(f"Accuracy : {result['accuracy']:.1%}") | ||
| 59 | + print(f"Macro-F1 : {result['macro_f1']:.3f}") | ||
| 60 | + print("\nEn zayıf 10 intent (F1):") | ||
| 61 | + worst = sorted(result["per_class"], key=lambda s: (s.f1, -s.support)) | ||
| 62 | + for s in worst[:10]: | ||
| 63 | + print(f" {s.label:26s} P={s.precision:.2f} R={s.recall:.2f} F1={s.f1:.2f} (n={s.support})") | ||
| 64 | + print("\nYanlış tahminler:") | ||
| 65 | + for true, pred in result["pairs"]: | ||
| 66 | + if true != pred: | ||
| 67 | + print(f" beklenen={true:26s} bulunan={pred}") | ||
tests/integration/test_regression.pyadded+83 -0
| @@ -0,0 +1,83 @@ | |||
| 1 | +"""Aşama 14 regresyon eşiği: kalite metrikleri bir tabanın altına düşerse KIRILIR. | ||
| 2 | + | ||
| 3 | +Bu testler, ileride yapılan değişikliklerin sistemi sessizce bozmasını engeller. | ||
| 4 | +Eşikler mevcut baseline'ın biraz altına konur (gürültüye dayanıklı ama koruyucu). | ||
| 5 | +""" | ||
| 6 | + | ||
| 7 | +import unittest | ||
| 8 | + | ||
| 9 | +from src.benchmark import OOS_LABEL, load_benchmark | ||
| 10 | +from src.decision import decide | ||
| 11 | +from src.evaluate import run_evaluation | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +class QualityRegressionTests(unittest.TestCase): | ||
| 15 | + @classmethod | ||
| 16 | + def setUpClass(cls) -> None: | ||
| 17 | + cls.report = run_evaluation() | ||
| 18 | + | ||
| 19 | + def test_macro_f1_floor(self) -> None: | ||
| 20 | + self.assertGreaterEqual(self.report["macro_f1"], 0.80, self.report["macro_f1"]) | ||
| 21 | + | ||
| 22 | + def test_accuracy_floor(self) -> None: | ||
| 23 | + self.assertGreaterEqual(self.report["accuracy"], 0.82) | ||
| 24 | + | ||
| 25 | + def test_coverage_floor(self) -> None: | ||
| 26 | + self.assertGreaterEqual(self.report["coverage"], 0.95) | ||
| 27 | + | ||
| 28 | + def test_oos_recall_floor(self) -> None: | ||
| 29 | + self.assertGreaterEqual(self.report["oos_recall"], 0.70) | ||
| 30 | + | ||
| 31 | + def test_top3_floor(self) -> None: | ||
| 32 | + self.assertGreaterEqual(self.report["top3_accuracy"], 0.90) | ||
| 33 | + | ||
| 34 | + def test_latency_reasonable(self) -> None: | ||
| 35 | + # Aşırı yavaşlamaya karşı gevşek tavan (ms). | ||
| 36 | + self.assertLess(self.report["latency_p95_ms"], 50.0) | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +class SafetyRegressionTests(unittest.TestCase): | ||
| 40 | + """Güvenlik: gizlilik intent'i asla kaçmamalı; auth sızıntısı olmamalı.""" | ||
| 41 | + | ||
| 42 | + def test_privacy_recall_is_perfect(self) -> None: | ||
| 43 | + records = [ | ||
| 44 | + r for r in load_benchmark() if r["expected_intent"] == "privacy_security" | ||
| 45 | + ] | ||
| 46 | + self.assertGreater(len(records), 0) | ||
| 47 | + for r in records: | ||
| 48 | + d = decide(r["question"], role="ogrenci", authenticated=True) | ||
| 49 | + self.assertEqual( | ||
| 50 | + d.intent, "privacy_security", f"Kaçan gizlilik sorusu: {r['question']!r}" | ||
| 51 | + ) | ||
| 52 | + | ||
| 53 | + def test_no_auth_leak_on_benchmark(self) -> None: | ||
| 54 | + from src.observability import process | ||
| 55 | + | ||
| 56 | + for r in load_benchmark(): | ||
| 57 | + if r["expected_intent"] == OOS_LABEL: | ||
| 58 | + continue | ||
| 59 | + # Ziyaretçi olarak sor; auth gerektiren intent'lerde gating olmalı, alarm olmamalı. | ||
| 60 | + _, trace = process(r["question"], role="ziyaretci", authenticated=False) | ||
| 61 | + self.assertEqual(trace["alarms"], [], f"{r['question']!r}: {trace['alarms']}") | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +class RulePrecisionRegressionTests(unittest.TestCase): | ||
| 65 | + def test_rule_layer_precision_perfect(self) -> None: | ||
| 66 | + from src import rules | ||
| 67 | + | ||
| 68 | + wrong = [] | ||
| 69 | + oos_fired = [] | ||
| 70 | + for r in load_benchmark(): | ||
| 71 | + m = rules.match(r["question"]) | ||
| 72 | + if m is None: | ||
| 73 | + continue | ||
| 74 | + if r["expected_intent"] == OOS_LABEL: | ||
| 75 | + oos_fired.append(r["question"]) | ||
| 76 | + elif m.intent != r["expected_intent"]: | ||
| 77 | + wrong.append((r["question"], r["expected_intent"], m.intent)) | ||
| 78 | + self.assertEqual(wrong, [], f"Kural yanlışları: {wrong}") | ||
| 79 | + self.assertEqual(oos_fired, [], f"OOS'ta ateşleyen kural: {oos_fired}") | ||
| 80 | + | ||
| 81 | + | ||
| 82 | +if __name__ == "__main__": | ||
| 83 | + unittest.main() | ||
tests/integration/test_rules_benchmark.pyadded+81 -0
| @@ -0,0 +1,81 @@ | |||
| 1 | +"""Aşama 5 integration/değerlendirme: kural katmanının benchmark üzerindeki baseline'ı. | ||
| 2 | + | ||
| 3 | +Kural katmanı yüksek-kesinlik hedefler: | ||
| 4 | +- Kapsanan (karar verilen) in-scope sorularda kesinlik ~%100 olmalı. | ||
| 5 | +- Kapsam dışı (OOS) sorularda kural KESİNLİKLE ateşlememeli (yanlış-pozitif = 0). | ||
| 6 | +Coverage'ın düşük olması normaldir; gerisini benzerlik katmanı toplar. | ||
| 7 | +""" | ||
| 8 | + | ||
| 9 | +import unittest | ||
| 10 | + | ||
| 11 | +from src.benchmark import OOS_LABEL, load_benchmark | ||
| 12 | +from src.rules import match | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +def evaluate_rule_layer(records: list[dict]) -> dict: | ||
| 16 | + in_scope = [r for r in records if r["expected_intent"] != OOS_LABEL] | ||
| 17 | + oos = [r for r in records if r["expected_intent"] == OOS_LABEL] | ||
| 18 | + | ||
| 19 | + covered = 0 | ||
| 20 | + correct = 0 | ||
| 21 | + wrong: list[tuple[str, str, str]] = [] | ||
| 22 | + for r in in_scope: | ||
| 23 | + m = match(r["question"]) | ||
| 24 | + if m is None: | ||
| 25 | + continue | ||
| 26 | + covered += 1 | ||
| 27 | + if m.intent == r["expected_intent"]: | ||
| 28 | + correct += 1 | ||
| 29 | + else: | ||
| 30 | + wrong.append((r["question"], r["expected_intent"], m.intent)) | ||
| 31 | + | ||
| 32 | + oos_fired = [(r["question"], match(r["question"]).intent) for r in oos if match(r["question"])] | ||
| 33 | + | ||
| 34 | + return { | ||
| 35 | + "in_scope": len(in_scope), | ||
| 36 | + "oos": len(oos), | ||
| 37 | + "covered": covered, | ||
| 38 | + "correct": correct, | ||
| 39 | + "coverage": covered / len(in_scope) if in_scope else 0.0, | ||
| 40 | + "precision_on_covered": correct / covered if covered else 1.0, | ||
| 41 | + "oos_fired": len(oos_fired), | ||
| 42 | + "wrong": wrong, | ||
| 43 | + "oos_fired_detail": oos_fired, | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +class RuleLayerBenchmarkTests(unittest.TestCase): | ||
| 48 | + @classmethod | ||
| 49 | + def setUpClass(cls) -> None: | ||
| 50 | + cls.result = evaluate_rule_layer(load_benchmark()) | ||
| 51 | + | ||
| 52 | + def test_precision_on_covered_is_perfect(self) -> None: | ||
| 53 | + self.assertEqual( | ||
| 54 | + self.result["precision_on_covered"], | ||
| 55 | + 1.0, | ||
| 56 | + f"Yanlış sınıflananlar: {self.result['wrong']}", | ||
| 57 | + ) | ||
| 58 | + | ||
| 59 | + def test_rules_do_not_fire_on_oos(self) -> None: | ||
| 60 | + self.assertEqual( | ||
| 61 | + self.result["oos_fired"], | ||
| 62 | + 0, | ||
| 63 | + f"OOS'ta ateşleyen kurallar: {self.result['oos_fired_detail']}", | ||
| 64 | + ) | ||
| 65 | + | ||
| 66 | + def test_has_some_coverage(self) -> None: | ||
| 67 | + self.assertGreater(self.result["covered"], 0) | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +if __name__ == "__main__": | ||
| 71 | + result = evaluate_rule_layer(load_benchmark()) | ||
| 72 | + print("=== KURAL KATMANI BASELINE ===") | ||
| 73 | + print(f"In-scope soru : {result['in_scope']}") | ||
| 74 | + print(f"Kapsanan (covered) : {result['covered']}") | ||
| 75 | + print(f"Coverage : {result['coverage']:.1%}") | ||
| 76 | + print(f"Precision (covered) : {result['precision_on_covered']:.1%}") | ||
| 77 | + print(f"OOS yanlış-ateşleme : {result['oos_fired']}") | ||
| 78 | + if result["wrong"]: | ||
| 79 | + print("Yanlışlar:") | ||
| 80 | + for q, exp, got in result["wrong"]: | ||
| 81 | + print(f" - {q!r}: beklenen={exp} bulunan={got}") | ||
tests/test_catalog.pydeleted+0 -25
| @@ -1,25 +0,0 @@ | |||
| 1 | -import unittest | ||
| 2 | - | ||
| 3 | -from src.QandA import get_intent | ||
| 4 | -from src.main import validate_catalog | ||
| 5 | - | ||
| 6 | - | ||
| 7 | -class CatalogTests(unittest.TestCase): | ||
| 8 | - def test_catalog_is_valid(self) -> None: | ||
| 9 | - result = validate_catalog() | ||
| 10 | - | ||
| 11 | - self.assertGreater(result["intent_count"], 0) | ||
| 12 | - self.assertGreater(result["example_question_count"], result["intent_count"]) | ||
| 13 | - | ||
| 14 | - def test_get_intent_returns_known_intent(self) -> None: | ||
| 15 | - intent = get_intent("course_grades") | ||
| 16 | - | ||
| 17 | - self.assertIsNotNone(intent) | ||
| 18 | - self.assertEqual(intent["response_id"], "course_grades_list") | ||
| 19 | - | ||
| 20 | - def test_get_intent_returns_none_for_unknown_intent(self) -> None: | ||
| 21 | - self.assertIsNone(get_intent("does_not_exist")) | ||
| 22 | - | ||
| 23 | - | ||
| 24 | -if __name__ == "__main__": | ||
| 25 | - unittest.main() | ||
tests/unit/__init__.pyadded+1 -0
| @@ -0,0 +1 @@ | |||
| 1 | +"""tests/unit tests.""" | ||
tests/unit/test_benchmark.pyadded+138 -0
| @@ -0,0 +1,138 @@ | |||
| 1 | +"""Aşama 3 birim testleri: benchmark yükleme ve doğrulama.""" | ||
| 2 | + | ||
| 3 | +import json | ||
| 4 | +import tempfile | ||
| 5 | +import unittest | ||
| 6 | +from pathlib import Path | ||
| 7 | + | ||
| 8 | +from src import catalog | ||
| 9 | +from src.benchmark import ( | ||
| 10 | + OOS_LABEL, | ||
| 11 | + load_benchmark, | ||
| 12 | + validate_benchmark, | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def _known_intents() -> set[str]: | ||
| 17 | + return {item["intent"] for item in catalog.INTENTS} | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def _example_questions() -> set[str]: | ||
| 21 | + return { | ||
| 22 | + q.strip().casefold() | ||
| 23 | + for item in catalog.INTENTS | ||
| 24 | + for q in item["example_questions"] | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +class LoadBenchmarkTests(unittest.TestCase): | ||
| 29 | + def test_loads_default_benchmark(self) -> None: | ||
| 30 | + records = load_benchmark() | ||
| 31 | + self.assertGreater(len(records), 0) | ||
| 32 | + self.assertIn("question", records[0]) | ||
| 33 | + self.assertIn("expected_intent", records[0]) | ||
| 34 | + | ||
| 35 | + def test_missing_file_raises(self) -> None: | ||
| 36 | + with self.assertRaises(FileNotFoundError): | ||
| 37 | + load_benchmark(Path("yok_boyle_bir_dosya.jsonl")) | ||
| 38 | + | ||
| 39 | + def test_blank_lines_skipped(self) -> None: | ||
| 40 | + with tempfile.TemporaryDirectory() as tmp: | ||
| 41 | + path = Path(tmp) / "b.jsonl" | ||
| 42 | + path.write_text( | ||
| 43 | + '{"question": "a", "expected_intent": "oos"}\n\n' | ||
| 44 | + '{"question": "b", "expected_intent": "oos"}\n', | ||
| 45 | + encoding="utf-8", | ||
| 46 | + ) | ||
| 47 | + self.assertEqual(len(load_benchmark(path)), 2) | ||
| 48 | + | ||
| 49 | + def test_invalid_json_raises(self) -> None: | ||
| 50 | + with tempfile.TemporaryDirectory() as tmp: | ||
| 51 | + path = Path(tmp) / "b.jsonl" | ||
| 52 | + path.write_text("{bozuk json}\n", encoding="utf-8") | ||
| 53 | + with self.assertRaises(ValueError): | ||
| 54 | + load_benchmark(path) | ||
| 55 | + | ||
| 56 | + def test_missing_field_raises(self) -> None: | ||
| 57 | + with tempfile.TemporaryDirectory() as tmp: | ||
| 58 | + path = Path(tmp) / "b.jsonl" | ||
| 59 | + path.write_text('{"question": "a"}\n', encoding="utf-8") | ||
| 60 | + with self.assertRaises(ValueError): | ||
| 61 | + load_benchmark(path) | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +class ValidateBenchmarkTests(unittest.TestCase): | ||
| 65 | + def test_real_benchmark_is_valid(self) -> None: | ||
| 66 | + records = load_benchmark() | ||
| 67 | + result = validate_benchmark( | ||
| 68 | + records, | ||
| 69 | + known_intents=_known_intents(), | ||
| 70 | + known_roles=set(catalog.ROLE_HIERARCHY), | ||
| 71 | + example_questions=_example_questions(), | ||
| 72 | + ) | ||
| 73 | + self.assertGreater(result["total"], 0) | ||
| 74 | + self.assertGreater(result["oos"], 0) | ||
| 75 | + self.assertGreater(result["in_scope"], 0) | ||
| 76 | + | ||
| 77 | + def test_real_benchmark_has_no_overlap_with_examples(self) -> None: | ||
| 78 | + # Örtüşme varsa validate_benchmark ValueError atar; burada net doğrula. | ||
| 79 | + records = load_benchmark() | ||
| 80 | + examples = _example_questions() | ||
| 81 | + overlap = [ | ||
| 82 | + r["question"] | ||
| 83 | + for r in records | ||
| 84 | + if r["question"].strip().casefold() in examples | ||
| 85 | + ] | ||
| 86 | + self.assertEqual(overlap, [], f"Örtüşen sorular: {overlap}") | ||
| 87 | + | ||
| 88 | + def test_every_intent_has_at_least_one_benchmark_question(self) -> None: | ||
| 89 | + records = load_benchmark() | ||
| 90 | + covered = {r["expected_intent"] for r in records if r["expected_intent"] != OOS_LABEL} | ||
| 91 | + missing = _known_intents().difference(covered) | ||
| 92 | + self.assertEqual(missing, set(), f"Benchmark'ta karşılığı olmayan intent: {missing}") | ||
| 93 | + | ||
| 94 | + def test_detects_unknown_intent(self) -> None: | ||
| 95 | + records = [{"question": "x", "expected_intent": "yok_intent"}] | ||
| 96 | + with self.assertRaises(ValueError): | ||
| 97 | + validate_benchmark(records, known_intents=_known_intents()) | ||
| 98 | + | ||
| 99 | + def test_detects_duplicate_question(self) -> None: | ||
| 100 | + records = [ | ||
| 101 | + {"question": "aynı", "expected_intent": "oos"}, | ||
| 102 | + {"question": "Aynı", "expected_intent": "oos"}, | ||
| 103 | + ] | ||
| 104 | + with self.assertRaises(ValueError): | ||
| 105 | + validate_benchmark(records, known_intents=_known_intents()) | ||
| 106 | + | ||
| 107 | + def test_detects_overlap_with_examples(self) -> None: | ||
| 108 | + sample_example = catalog.INTENTS[0]["example_questions"][0] | ||
| 109 | + records = [ | ||
| 110 | + {"question": sample_example, "expected_intent": catalog.INTENTS[0]["intent"]}, | ||
| 111 | + {"question": "kapsam disi soru", "expected_intent": "oos"}, | ||
| 112 | + ] | ||
| 113 | + with self.assertRaises(ValueError): | ||
| 114 | + validate_benchmark( | ||
| 115 | + records, | ||
| 116 | + known_intents=_known_intents(), | ||
| 117 | + example_questions=_example_questions(), | ||
| 118 | + ) | ||
| 119 | + | ||
| 120 | + def test_requires_at_least_one_oos(self) -> None: | ||
| 121 | + records = [{"question": "x", "expected_intent": catalog.INTENTS[0]["intent"]}] | ||
| 122 | + with self.assertRaises(ValueError): | ||
| 123 | + validate_benchmark(records, known_intents=_known_intents()) | ||
| 124 | + | ||
| 125 | + def test_detects_unknown_role(self) -> None: | ||
| 126 | + records = [ | ||
| 127 | + {"question": "x", "expected_intent": "oos", "role": "kral"}, | ||
| 128 | + ] | ||
| 129 | + with self.assertRaises(ValueError): | ||
| 130 | + validate_benchmark( | ||
| 131 | + records, | ||
| 132 | + known_intents=_known_intents(), | ||
| 133 | + known_roles=set(catalog.ROLE_HIERARCHY), | ||
| 134 | + ) | ||
| 135 | + | ||
| 136 | + | ||
| 137 | +if __name__ == "__main__": | ||
| 138 | + unittest.main() | ||
tests/unit/test_catalog.pyadded+156 -0
| @@ -0,0 +1,156 @@ | |||
| 1 | +"""Aşama 1+2 birim testleri: intent kataloğu, rol modeli ve doğrulayıcı. | ||
| 2 | + | ||
| 3 | +Her katalog metodu ve her önemli değişmez için ayrı test. | ||
| 4 | +""" | ||
| 5 | + | ||
| 6 | +import unittest | ||
| 7 | + | ||
| 8 | +from src import catalog | ||
| 9 | +from src.catalog import ( | ||
| 10 | + FALLBACK, | ||
| 11 | + INTENTS, | ||
| 12 | + MIN_AUTHENTICATED_ROLE, | ||
| 13 | + REQUIRED_INTENT_FIELDS, | ||
| 14 | + ROLE_HIERARCHY, | ||
| 15 | + get_intent, | ||
| 16 | + is_known_role, | ||
| 17 | + list_intent_names, | ||
| 18 | + meets_role, | ||
| 19 | + role_rank, | ||
| 20 | + validate_catalog, | ||
| 21 | +) | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +class RoleModelTests(unittest.TestCase): | ||
| 25 | + def test_hierarchy_is_ordered_low_to_high(self) -> None: | ||
| 26 | + self.assertEqual(ROLE_HIERARCHY[0], "ziyaretci") | ||
| 27 | + self.assertEqual(ROLE_HIERARCHY[-1], "admin") | ||
| 28 | + | ||
| 29 | + def test_role_rank_is_strictly_increasing(self) -> None: | ||
| 30 | + ranks = [role_rank(r) for r in ROLE_HIERARCHY] | ||
| 31 | + self.assertEqual(ranks, sorted(ranks)) | ||
| 32 | + self.assertEqual(len(set(ranks)), len(ranks)) | ||
| 33 | + | ||
| 34 | + def test_role_rank_unknown_raises(self) -> None: | ||
| 35 | + with self.assertRaises(KeyError): | ||
| 36 | + role_rank("kral") | ||
| 37 | + | ||
| 38 | + def test_is_known_role(self) -> None: | ||
| 39 | + self.assertTrue(is_known_role("ogrenci")) | ||
| 40 | + self.assertFalse(is_known_role("kral")) | ||
| 41 | + | ||
| 42 | + def test_meets_role_higher_satisfies_lower(self) -> None: | ||
| 43 | + self.assertTrue(meets_role("admin", "ogrenci")) | ||
| 44 | + self.assertTrue(meets_role("ogretmen", "ogretmen")) | ||
| 45 | + | ||
| 46 | + def test_meets_role_lower_fails_higher(self) -> None: | ||
| 47 | + self.assertFalse(meets_role("ogrenci", "ogretmen")) | ||
| 48 | + self.assertFalse(meets_role("ziyaretci", "ogrenci")) | ||
| 49 | + | ||
| 50 | + def test_meets_role_unknown_raises(self) -> None: | ||
| 51 | + with self.assertRaises(KeyError): | ||
| 52 | + meets_role("ogrenci", "kral") | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +class GetIntentTests(unittest.TestCase): | ||
| 56 | + def test_returns_known_intent(self) -> None: | ||
| 57 | + intent = get_intent("exam_create") | ||
| 58 | + self.assertIsNotNone(intent) | ||
| 59 | + self.assertEqual(intent["response_id"], "exam_create_instructions") | ||
| 60 | + | ||
| 61 | + def test_returns_none_for_unknown(self) -> None: | ||
| 62 | + self.assertIsNone(get_intent("does_not_exist")) | ||
| 63 | + | ||
| 64 | + def test_list_intent_names_matches_catalog(self) -> None: | ||
| 65 | + names = list_intent_names() | ||
| 66 | + self.assertEqual(len(names), len(INTENTS)) | ||
| 67 | + self.assertEqual(names, [i["intent"] for i in INTENTS]) | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +class ValidateCatalogTests(unittest.TestCase): | ||
| 71 | + def test_catalog_is_valid(self) -> None: | ||
| 72 | + result = validate_catalog() | ||
| 73 | + self.assertGreater(result["intent_count"], 0) | ||
| 74 | + self.assertEqual(result["intent_count"], result["response_count"]) | ||
| 75 | + self.assertGreater(result["example_question_count"], result["intent_count"]) | ||
| 76 | + self.assertGreater(result["category_count"], 1) | ||
| 77 | + | ||
| 78 | + def test_all_intents_have_required_fields(self) -> None: | ||
| 79 | + for item in INTENTS: | ||
| 80 | + missing = REQUIRED_INTENT_FIELDS.difference(item) | ||
| 81 | + self.assertEqual(missing, set(), f"{item.get('intent')} eksik: {missing}") | ||
| 82 | + | ||
| 83 | + def test_intent_names_unique(self) -> None: | ||
| 84 | + names = [i["intent"] for i in INTENTS] | ||
| 85 | + self.assertEqual(len(names), len(set(names))) | ||
| 86 | + | ||
| 87 | + def test_response_ids_unique(self) -> None: | ||
| 88 | + ids = [i["response_id"] for i in INTENTS] | ||
| 89 | + self.assertEqual(len(ids), len(set(ids))) | ||
| 90 | + | ||
| 91 | + def test_example_questions_unique_across_catalog(self) -> None: | ||
| 92 | + questions = [q for i in INTENTS for q in i["example_questions"]] | ||
| 93 | + self.assertEqual(len(questions), len(set(questions))) | ||
| 94 | + | ||
| 95 | + def test_every_intent_has_examples(self) -> None: | ||
| 96 | + for item in INTENTS: | ||
| 97 | + self.assertTrue(item["example_questions"], f"{item['intent']} örnek soru yok") | ||
| 98 | + | ||
| 99 | + def test_min_role_values_are_known(self) -> None: | ||
| 100 | + for item in INTENTS: | ||
| 101 | + self.assertTrue(is_known_role(item["min_role"]), item["intent"]) | ||
| 102 | + | ||
| 103 | + def test_auth_required_consistent_with_min_role(self) -> None: | ||
| 104 | + for item in INTENTS: | ||
| 105 | + expected = role_rank(item["min_role"]) >= role_rank(MIN_AUTHENTICATED_ROLE) | ||
| 106 | + self.assertEqual(bool(item["auth_required"]), expected, item["intent"]) | ||
| 107 | + | ||
| 108 | + def test_must_not_match_targets_exist(self) -> None: | ||
| 109 | + known = {i["intent"] for i in INTENTS} | ||
| 110 | + for item in INTENTS: | ||
| 111 | + for target in item["must_not_match"]: | ||
| 112 | + self.assertIn(target, known, f"{item['intent']} -> {target}") | ||
| 113 | + | ||
| 114 | + def test_must_not_match_excludes_self(self) -> None: | ||
| 115 | + for item in INTENTS: | ||
| 116 | + self.assertNotIn(item["intent"], item["must_not_match"], item["intent"]) | ||
| 117 | + | ||
| 118 | + def test_fallback_present(self) -> None: | ||
| 119 | + self.assertTrue(FALLBACK.get("response_id")) | ||
| 120 | + self.assertTrue(FALLBACK.get("response_template")) | ||
| 121 | + | ||
| 122 | + | ||
| 123 | +class ValidatorFailureTests(unittest.TestCase): | ||
| 124 | + """Doğrulayıcının gerçekten hata yakaladığını, geçici bozma ile kanıtla.""" | ||
| 125 | + | ||
| 126 | + def test_detects_duplicate_intent(self) -> None: | ||
| 127 | + original = list(INTENTS) | ||
| 128 | + try: | ||
| 129 | + INTENTS.append(dict(original[0])) # aynı intent'i tekrar ekle | ||
| 130 | + with self.assertRaises(ValueError): | ||
| 131 | + validate_catalog() | ||
| 132 | + finally: | ||
| 133 | + INTENTS[:] = original | ||
| 134 | + | ||
| 135 | + def test_detects_unknown_must_not_match(self) -> None: | ||
| 136 | + original = catalog.INTENTS[0]["must_not_match"] | ||
| 137 | + try: | ||
| 138 | + catalog.INTENTS[0]["must_not_match"] = ["yok_boyle_intent"] | ||
| 139 | + with self.assertRaises(ValueError): | ||
| 140 | + validate_catalog() | ||
| 141 | + finally: | ||
| 142 | + catalog.INTENTS[0]["must_not_match"] = original | ||
| 143 | + | ||
| 144 | + def test_detects_auth_inconsistency(self) -> None: | ||
| 145 | + original = catalog.INTENTS[0]["auth_required"] | ||
| 146 | + try: | ||
| 147 | + # greeting min_role=ziyaretci; auth_required=True yaparak tutarsızlık kur. | ||
| 148 | + catalog.INTENTS[0]["auth_required"] = True | ||
| 149 | + with self.assertRaises(ValueError): | ||
| 150 | + validate_catalog() | ||
| 151 | + finally: | ||
| 152 | + catalog.INTENTS[0]["auth_required"] = original | ||
| 153 | + | ||
| 154 | + | ||
| 155 | +if __name__ == "__main__": | ||
| 156 | + unittest.main() | ||
tests/unit/test_cli.pyadded+95 -0
| @@ -0,0 +1,95 @@ | |||
| 1 | +"""Aşama 13 birim testleri: terminal (CLI) oturumu ve komutlar.""" | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src.cli import ChatSession, run | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +class SessionTests(unittest.TestCase): | ||
| 9 | + def setUp(self) -> None: | ||
| 10 | + self.session = ChatSession() | ||
| 11 | + | ||
| 12 | + def test_default_role_visitor(self) -> None: | ||
| 13 | + self.assertEqual(self.session.role, "ziyaretci") | ||
| 14 | + self.assertFalse(self.session.authenticated) | ||
| 15 | + | ||
| 16 | + def test_set_role_valid(self) -> None: | ||
| 17 | + msg = self.session.set_role("ogretmen") | ||
| 18 | + self.assertEqual(self.session.role, "ogretmen") | ||
| 19 | + self.assertTrue(self.session.authenticated) | ||
| 20 | + self.assertIn("ogretmen", msg) | ||
| 21 | + | ||
| 22 | + def test_set_role_invalid(self) -> None: | ||
| 23 | + msg = self.session.set_role("kral") | ||
| 24 | + self.assertEqual(self.session.role, "ziyaretci") # değişmez | ||
| 25 | + self.assertIn("Bilinmeyen", msg) | ||
| 26 | + | ||
| 27 | + def test_ask_returns_contract(self) -> None: | ||
| 28 | + resp = self.session.ask("Merhaba") | ||
| 29 | + self.assertEqual(resp["response_id"], "welcome_message") | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +class HandleLineTests(unittest.TestCase): | ||
| 33 | + def setUp(self) -> None: | ||
| 34 | + self.session = ChatSession() | ||
| 35 | + | ||
| 36 | + def test_empty_line(self) -> None: | ||
| 37 | + text, exit_ = self.session.handle_line(" ") | ||
| 38 | + self.assertIsNone(text) | ||
| 39 | + self.assertFalse(exit_) | ||
| 40 | + | ||
| 41 | + def test_exit_command(self) -> None: | ||
| 42 | + text, exit_ = self.session.handle_line("/cikis") | ||
| 43 | + self.assertTrue(exit_) | ||
| 44 | + | ||
| 45 | + def test_role_command(self) -> None: | ||
| 46 | + text, exit_ = self.session.handle_line("/rol ogretmen") | ||
| 47 | + self.assertEqual(self.session.role, "ogretmen") | ||
| 48 | + self.assertFalse(exit_) | ||
| 49 | + | ||
| 50 | + def test_role_command_gating_effect(self) -> None: | ||
| 51 | + self.session.handle_line("/rol ogrenci") | ||
| 52 | + text, _ = self.session.handle_line("yeni ders oluştur") | ||
| 53 | + self.assertIn("Öğretmen", text) # rol yetersiz uyarısı | ||
| 54 | + self.session.handle_line("/rol ogretmen") | ||
| 55 | + text2, _ = self.session.handle_line("yeni ders oluştur") | ||
| 56 | + self.assertNotIn("yetmiyor", text2) # artık izin var | ||
| 57 | + | ||
| 58 | + def test_roles_command(self) -> None: | ||
| 59 | + text, _ = self.session.handle_line("/roller") | ||
| 60 | + self.assertIn("ogrenci", text) | ||
| 61 | + | ||
| 62 | + def test_help_command(self) -> None: | ||
| 63 | + text, _ = self.session.handle_line("/yardim") | ||
| 64 | + self.assertIn("Komutlar", text) | ||
| 65 | + | ||
| 66 | + def test_unknown_command(self) -> None: | ||
| 67 | + text, _ = self.session.handle_line("/bilinmeyen") | ||
| 68 | + self.assertIn("Bilinmeyen komut", text) | ||
| 69 | + | ||
| 70 | + def test_normal_query(self) -> None: | ||
| 71 | + text, exit_ = self.session.handle_line("Merhaba") | ||
| 72 | + self.assertIn("greeting", text) | ||
| 73 | + self.assertFalse(exit_) | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +class RunLoopTests(unittest.TestCase): | ||
| 77 | + def test_run_with_injected_io(self) -> None: | ||
| 78 | + inputs = iter(["Merhaba", "/rol ogretmen", "/cikis"]) | ||
| 79 | + outputs: list[str] = [] | ||
| 80 | + run(input_fn=lambda _prompt: next(inputs), output_fn=outputs.append) | ||
| 81 | + joined = "\n".join(outputs) | ||
| 82 | + self.assertIn("greeting", joined) | ||
| 83 | + self.assertIn("Görüşürüz", joined) | ||
| 84 | + | ||
| 85 | + def test_run_handles_eof(self) -> None: | ||
| 86 | + def raise_eof(_prompt: str) -> str: | ||
| 87 | + raise EOFError | ||
| 88 | + | ||
| 89 | + outputs: list[str] = [] | ||
| 90 | + run(input_fn=raise_eof, output_fn=outputs.append) | ||
| 91 | + self.assertTrue(any("Görüşürüz" in o for o in outputs)) | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +if __name__ == "__main__": | ||
| 95 | + unittest.main() | ||
tests/unit/test_decision.pyadded+81 -0
| @@ -0,0 +1,81 @@ | |||
| 1 | +"""Aşama 7 birim testleri: karar katmanı (eşik, fallback, tie-break, rol gating).""" | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src.decision import ( | ||
| 6 | + LOGIN_REQUIRED, | ||
| 7 | + ROLE_INSUFFICIENT, | ||
| 8 | + Decision, | ||
| 9 | + _is_confusable_pair, | ||
| 10 | + decide, | ||
| 11 | +) | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +class DecisionSourceTests(unittest.TestCase): | ||
| 15 | + def test_rule_path(self) -> None: | ||
| 16 | + d = decide("Merhaba") | ||
| 17 | + self.assertEqual(d.source, "rule") | ||
| 18 | + self.assertEqual(d.intent, "greeting") | ||
| 19 | + self.assertFalse(d.fallback) | ||
| 20 | + self.assertEqual(d.confidence, 1.0) | ||
| 21 | + | ||
| 22 | + def test_similarity_path(self) -> None: | ||
| 23 | + # Kural yok -> benzerliğe düşer. | ||
| 24 | + d = decide("genel ortalamama nereden bakarım", role="ogrenci", authenticated=True) | ||
| 25 | + self.assertEqual(d.source, "similarity") | ||
| 26 | + self.assertEqual(d.intent, "report_card_view") | ||
| 27 | + self.assertGreater(len(d.top_k), 0) | ||
| 28 | + | ||
| 29 | + def test_fallback_on_gibberish(self) -> None: | ||
| 30 | + d = decide("qwzx plkj mnbv zzz") | ||
| 31 | + self.assertTrue(d.fallback) | ||
| 32 | + self.assertIsNone(d.intent) | ||
| 33 | + self.assertEqual(d.source, "fallback") | ||
| 34 | + | ||
| 35 | + def test_fallback_on_high_threshold(self) -> None: | ||
| 36 | + d = decide("ders notları", threshold=0.99) | ||
| 37 | + self.assertTrue(d.fallback) | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +class RoleGatingTests(unittest.TestCase): | ||
| 41 | + def test_login_required_for_visitor(self) -> None: | ||
| 42 | + d = decide("Karnemi göster", role="ziyaretci", authenticated=False) | ||
| 43 | + self.assertEqual(d.intent, "report_card_view") | ||
| 44 | + self.assertEqual(d.auth_action, LOGIN_REQUIRED) | ||
| 45 | + self.assertEqual(d.required_role, "ogrenci") | ||
| 46 | + | ||
| 47 | + def test_role_insufficient_for_student(self) -> None: | ||
| 48 | + d = decide("yeni ders oluştur", role="ogrenci", authenticated=True) | ||
| 49 | + self.assertEqual(d.intent, "course_create") | ||
| 50 | + self.assertEqual(d.auth_action, ROLE_INSUFFICIENT) | ||
| 51 | + self.assertEqual(d.required_role, "ogretmen") | ||
| 52 | + | ||
| 53 | + def test_role_granted_for_teacher(self) -> None: | ||
| 54 | + d = decide("yeni ders oluştur", role="ogretmen", authenticated=True) | ||
| 55 | + self.assertEqual(d.intent, "course_create") | ||
| 56 | + self.assertIsNone(d.auth_action) | ||
| 57 | + | ||
| 58 | + def test_public_intent_no_gating(self) -> None: | ||
| 59 | + d = decide("Merhaba", role="ziyaretci", authenticated=False) | ||
| 60 | + self.assertIsNone(d.auth_action) | ||
| 61 | + | ||
| 62 | + def test_no_gating_on_fallback(self) -> None: | ||
| 63 | + d = decide("qwzx plkj mnbv", role="ziyaretci", authenticated=False) | ||
| 64 | + self.assertTrue(d.fallback) | ||
| 65 | + self.assertIsNone(d.auth_action) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +class ConfusablePairTests(unittest.TestCase): | ||
| 69 | + def test_known_pair(self) -> None: | ||
| 70 | + # report_card_view.must_not_match, weighted_average_info içerir. | ||
| 71 | + self.assertTrue(_is_confusable_pair("report_card_view", "weighted_average_info")) | ||
| 72 | + | ||
| 73 | + def test_symmetric(self) -> None: | ||
| 74 | + self.assertTrue(_is_confusable_pair("weighted_average_info", "report_card_view")) | ||
| 75 | + | ||
| 76 | + def test_unrelated_pair(self) -> None: | ||
| 77 | + self.assertFalse(_is_confusable_pair("greeting", "school_settings")) | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +if __name__ == "__main__": | ||
| 81 | + unittest.main() | ||
tests/unit/test_domain.pyadded+56 -0
| @@ -0,0 +1,56 @@ | |||
| 1 | +"""Aşama 11 birim testleri: alan (domain) kapısı.""" | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src.domain import ( | ||
| 6 | + STOPWORDS, | ||
| 7 | + build_domain_vocab, | ||
| 8 | + get_domain_vocab, | ||
| 9 | + is_in_domain, | ||
| 10 | +) | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +class VocabTests(unittest.TestCase): | ||
| 14 | + def test_vocab_nonempty(self) -> None: | ||
| 15 | + self.assertGreater(len(build_domain_vocab()), 0) | ||
| 16 | + | ||
| 17 | + def test_vocab_contains_domain_words(self) -> None: | ||
| 18 | + vocab = build_domain_vocab() | ||
| 19 | + self.assertIn("ders", vocab) | ||
| 20 | + | ||
| 21 | + def test_vocab_excludes_stopwords(self) -> None: | ||
| 22 | + vocab = build_domain_vocab() | ||
| 23 | + for stop in ["nasil", "nerede", "bir"]: | ||
| 24 | + self.assertNotIn(stop, vocab) | ||
| 25 | + | ||
| 26 | + def test_cached(self) -> None: | ||
| 27 | + self.assertIs(get_domain_vocab(), get_domain_vocab()) | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +class IsInDomainTests(unittest.TestCase): | ||
| 31 | + def test_in_domain_queries(self) -> None: | ||
| 32 | + for q in ["Karnemi göster", "sınav oluştur", "yoklama al", "derslerim neler"]: | ||
| 33 | + with self.subTest(q=q): | ||
| 34 | + self.assertTrue(is_in_domain(q)) | ||
| 35 | + | ||
| 36 | + def test_out_of_domain_queries(self) -> None: | ||
| 37 | + for q in ["Bana bir fıkra anlat", "En yakın pizzacı nerede?", "Bugün hava nasıl?"]: | ||
| 38 | + with self.subTest(q=q): | ||
| 39 | + self.assertFalse(is_in_domain(q)) | ||
| 40 | + | ||
| 41 | + def test_only_stopwords_is_out(self) -> None: | ||
| 42 | + self.assertFalse(is_in_domain("nasıl nerede bir")) | ||
| 43 | + | ||
| 44 | + def test_empty_is_out(self) -> None: | ||
| 45 | + self.assertFalse(is_in_domain("")) | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +class StopwordsTests(unittest.TestCase): | ||
| 49 | + def test_stopwords_are_folded_ascii(self) -> None: | ||
| 50 | + # Katlanmış (ascii) olmalı ki içerik tokenlarıyla eşleşsin. | ||
| 51 | + for word in STOPWORDS: | ||
| 52 | + self.assertEqual(word, word.encode("ascii", "ignore").decode()) | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +if __name__ == "__main__": | ||
| 56 | + unittest.main() | ||
tests/unit/test_evaluate.pyadded+72 -0
| @@ -0,0 +1,72 @@ | |||
| 1 | +"""Aşama 10 birim testleri: percentile/topk metrikleri ve evaluate harness.""" | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src.evaluate import format_report, run_evaluation | ||
| 6 | +from src.metrics import percentile, topk_accuracy | ||
| 7 | + | ||
| 8 | + | ||
| 9 | +class PercentileTests(unittest.TestCase): | ||
| 10 | + def test_median(self) -> None: | ||
| 11 | + self.assertAlmostEqual(percentile([1, 2, 3, 4], 50), 2.5) | ||
| 12 | + | ||
| 13 | + def test_min_max(self) -> None: | ||
| 14 | + self.assertEqual(percentile([1, 2, 3, 4], 0), 1) | ||
| 15 | + self.assertEqual(percentile([1, 2, 3, 4], 100), 4) | ||
| 16 | + | ||
| 17 | + def test_empty(self) -> None: | ||
| 18 | + self.assertEqual(percentile([], 95), 0.0) | ||
| 19 | + | ||
| 20 | + def test_single(self) -> None: | ||
| 21 | + self.assertEqual(percentile([7.0], 95), 7.0) | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +class TopKAccuracyTests(unittest.TestCase): | ||
| 25 | + def test_top1(self) -> None: | ||
| 26 | + recs = [("a", ["a", "b"]), ("b", ["a", "b"])] | ||
| 27 | + self.assertAlmostEqual(topk_accuracy(recs, 1), 0.5) | ||
| 28 | + | ||
| 29 | + def test_top2(self) -> None: | ||
| 30 | + recs = [("a", ["a", "b"]), ("b", ["a", "b"])] | ||
| 31 | + self.assertAlmostEqual(topk_accuracy(recs, 2), 1.0) | ||
| 32 | + | ||
| 33 | + def test_empty(self) -> None: | ||
| 34 | + self.assertEqual(topk_accuracy([], 1), 0.0) | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +class RunEvaluationTests(unittest.TestCase): | ||
| 38 | + @classmethod | ||
| 39 | + def setUpClass(cls) -> None: | ||
| 40 | + cls.report = run_evaluation() | ||
| 41 | + | ||
| 42 | + def test_has_all_keys(self) -> None: | ||
| 43 | + for key in [ | ||
| 44 | + "macro_f1", "accuracy", "coverage", "accuracy_on_covered", | ||
| 45 | + "false_fallback", "oos_recall", "top1_accuracy", "top3_accuracy", | ||
| 46 | + "confusable_wrong", "nonconfusable_wrong", "latency_p50_ms", | ||
| 47 | + "latency_p95_ms", "per_class", | ||
| 48 | + ]: | ||
| 49 | + self.assertIn(key, self.report) | ||
| 50 | + | ||
| 51 | + def test_sane_ranges(self) -> None: | ||
| 52 | + r = self.report | ||
| 53 | + self.assertGreater(r["macro_f1"], 0.0) | ||
| 54 | + self.assertLessEqual(r["macro_f1"], 1.0) | ||
| 55 | + self.assertGreaterEqual(r["oos_recall"], 0.0) | ||
| 56 | + self.assertLessEqual(r["oos_recall"], 1.0) | ||
| 57 | + self.assertGreaterEqual(r["top3_accuracy"], r["top1_accuracy"]) | ||
| 58 | + | ||
| 59 | + def test_threshold_sweep_changes_coverage(self) -> None: | ||
| 60 | + low = run_evaluation(threshold=0.05) | ||
| 61 | + high = run_evaluation(threshold=0.9) | ||
| 62 | + self.assertGreaterEqual(low["coverage"], high["coverage"]) | ||
| 63 | + # Yüksek eşik OOS recall'ı artırır. | ||
| 64 | + self.assertGreaterEqual(high["oos_recall"], low["oos_recall"]) | ||
| 65 | + | ||
| 66 | + def test_format_report_runs(self) -> None: | ||
| 67 | + text = format_report(self.report) | ||
| 68 | + self.assertIn("Macro-F1", text) | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +if __name__ == "__main__": | ||
| 72 | + unittest.main() | ||
tests/unit/test_metrics.pyadded+57 -0
| @@ -0,0 +1,57 @@ | |||
| 1 | +"""Aşama 6/10 birim testleri: çekirdek sınıflandırma metrikleri.""" | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src.metrics import ( | ||
| 6 | + accuracy, | ||
| 7 | + confusion_counts, | ||
| 8 | + macro_f1, | ||
| 9 | + per_class_scores, | ||
| 10 | +) | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +# Küçük, elle doğrulanabilir örnek. | ||
| 14 | +PAIRS = [("a", "a"), ("a", "b"), ("b", "b"), ("c", "c")] | ||
| 15 | +LABELS = {"a", "b", "c"} | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +class ConfusionTests(unittest.TestCase): | ||
| 19 | + def test_counts(self) -> None: | ||
| 20 | + counts = confusion_counts(PAIRS, LABELS) | ||
| 21 | + self.assertEqual(counts["a"], (1, 0, 1)) # tp, fp, fn | ||
| 22 | + self.assertEqual(counts["b"], (1, 1, 0)) | ||
| 23 | + self.assertEqual(counts["c"], (1, 0, 0)) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +class AccuracyTests(unittest.TestCase): | ||
| 27 | + def test_accuracy(self) -> None: | ||
| 28 | + self.assertAlmostEqual(accuracy(PAIRS), 0.75) | ||
| 29 | + | ||
| 30 | + def test_empty(self) -> None: | ||
| 31 | + self.assertEqual(accuracy([]), 0.0) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +class MacroF1Tests(unittest.TestCase): | ||
| 35 | + def test_macro_f1(self) -> None: | ||
| 36 | + # a: f1=0.667, b: f1=0.667, c: f1=1.0 -> ort ~0.778 | ||
| 37 | + self.assertAlmostEqual(macro_f1(PAIRS, LABELS), (2 / 3 + 2 / 3 + 1.0) / 3, places=6) | ||
| 38 | + | ||
| 39 | + def test_perfect(self) -> None: | ||
| 40 | + perfect = [("a", "a"), ("b", "b")] | ||
| 41 | + self.assertAlmostEqual(macro_f1(perfect, {"a", "b"}), 1.0) | ||
| 42 | + | ||
| 43 | + def test_empty_labels(self) -> None: | ||
| 44 | + self.assertEqual(macro_f1(PAIRS, set()), 0.0) | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +class PerClassTests(unittest.TestCase): | ||
| 48 | + def test_scores_and_support(self) -> None: | ||
| 49 | + scores = {s.label: s for s in per_class_scores(PAIRS, LABELS)} | ||
| 50 | + self.assertAlmostEqual(scores["a"].precision, 1.0) | ||
| 51 | + self.assertAlmostEqual(scores["a"].recall, 0.5) | ||
| 52 | + self.assertEqual(scores["a"].support, 2) | ||
| 53 | + self.assertAlmostEqual(scores["c"].f1, 1.0) | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +if __name__ == "__main__": | ||
| 57 | + unittest.main() | ||
tests/unit/test_normalize.pyadded+125 -0
| @@ -0,0 +1,125 @@ | |||
| 1 | +"""Aşama 4 birim testleri: normalizasyon ve Türkçe kök bulma. | ||
| 2 | + | ||
| 3 | +Her fonksiyon için ayrı test. | ||
| 4 | +""" | ||
| 5 | + | ||
| 6 | +import unittest | ||
| 7 | + | ||
| 8 | +from src.normalize import ( | ||
| 9 | + MIN_STEM_LENGTH, | ||
| 10 | + collapse_whitespace, | ||
| 11 | + fold_accents, | ||
| 12 | + normalize, | ||
| 13 | + roots, | ||
| 14 | + stem, | ||
| 15 | + strip_punctuation, | ||
| 16 | + tokenize, | ||
| 17 | + turkish_lower, | ||
| 18 | +) | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +class TurkishLowerTests(unittest.TestCase): | ||
| 22 | + def test_dotted_capital_i(self) -> None: | ||
| 23 | + self.assertEqual(turkish_lower("İSTANBUL"), "istanbul") | ||
| 24 | + | ||
| 25 | + def test_dotless_capital_i(self) -> None: | ||
| 26 | + self.assertEqual(turkish_lower("IŞIK"), "ışık") | ||
| 27 | + | ||
| 28 | + def test_mixed(self) -> None: | ||
| 29 | + self.assertEqual(turkish_lower("Güneş Işığı"), "güneş ışığı") | ||
| 30 | + | ||
| 31 | + def test_no_combining_dot_artifact(self) -> None: | ||
| 32 | + # Python'un varsayılan 'İ'.lower() birleşik nokta üretir; biz üretmemeliyiz. | ||
| 33 | + self.assertNotIn("̇", turkish_lower("İ")) | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +class StripPunctuationTests(unittest.TestCase): | ||
| 37 | + def test_removes_punctuation(self) -> None: | ||
| 38 | + self.assertEqual(strip_punctuation("merhaba!!!").strip(), "merhaba") | ||
| 39 | + | ||
| 40 | + def test_keeps_turkish_letters(self) -> None: | ||
| 41 | + self.assertEqual(strip_punctuation("çğıöşü").strip(), "çğıöşü") | ||
| 42 | + | ||
| 43 | + def test_keeps_digits(self) -> None: | ||
| 44 | + self.assertEqual(strip_punctuation("oda 12").strip(), "oda 12") | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +class CollapseWhitespaceTests(unittest.TestCase): | ||
| 48 | + def test_collapses_and_trims(self) -> None: | ||
| 49 | + self.assertEqual(collapse_whitespace(" a b \t c "), "a b c") | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +class NormalizeTests(unittest.TestCase): | ||
| 53 | + def test_full_pipeline(self) -> None: | ||
| 54 | + self.assertEqual(normalize("Merhaba!!! Nasılsın?"), "merhaba nasılsın") | ||
| 55 | + | ||
| 56 | + def test_empty_string(self) -> None: | ||
| 57 | + self.assertEqual(normalize(" "), "") | ||
| 58 | + | ||
| 59 | + def test_preserves_turkish_chars(self) -> None: | ||
| 60 | + self.assertEqual(normalize("Şifremi Unuttum"), "şifremi unuttum") | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +class FoldAccentsTests(unittest.TestCase): | ||
| 64 | + def test_folds_all_specials(self) -> None: | ||
| 65 | + self.assertEqual(fold_accents("çğıöşü"), "cgiosu") | ||
| 66 | + | ||
| 67 | + def test_word(self) -> None: | ||
| 68 | + self.assertEqual(fold_accents("güneş"), "gunes") | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +class TokenizeTests(unittest.TestCase): | ||
| 72 | + def test_splits_words(self) -> None: | ||
| 73 | + self.assertEqual(tokenize("Notlarımı göster"), ["notlarımı", "göster"]) | ||
| 74 | + | ||
| 75 | + def test_empty(self) -> None: | ||
| 76 | + self.assertEqual(tokenize(" "), []) | ||
| 77 | + | ||
| 78 | + | ||
| 79 | +class StemTests(unittest.TestCase): | ||
| 80 | + def test_plural(self) -> None: | ||
| 81 | + self.assertEqual(stem("dersler"), "ders") | ||
| 82 | + | ||
| 83 | + def test_plural_possessive_accusative(self) -> None: | ||
| 84 | + self.assertEqual(stem("sinavlarim"), "sinav") | ||
| 85 | + | ||
| 86 | + def test_plural_short_root(self) -> None: | ||
| 87 | + self.assertEqual(stem("notlar"), "not") | ||
| 88 | + | ||
| 89 | + def test_respects_min_stem_length(self) -> None: | ||
| 90 | + # Kök çok kısalacaksa ek soyulmaz. | ||
| 91 | + result = stem("eve") # "e" ekini soyarsa "ev" (2) < MIN; soyulmamalı | ||
| 92 | + self.assertGreaterEqual(len(result), min(len("eve"), MIN_STEM_LENGTH)) | ||
| 93 | + | ||
| 94 | + def test_no_suffix_unchanged(self) -> None: | ||
| 95 | + self.assertEqual(stem("goster"), "goster") | ||
| 96 | + | ||
| 97 | + def test_idempotent(self) -> None: | ||
| 98 | + once = stem("derslerimiz") | ||
| 99 | + twice = stem(once) | ||
| 100 | + self.assertEqual(once, twice) | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +class RootsTests(unittest.TestCase): | ||
| 104 | + def test_end_to_end(self) -> None: | ||
| 105 | + result = roots("Notlarımı göster") | ||
| 106 | + self.assertIn("not", result) | ||
| 107 | + self.assertIn("goster", result) | ||
| 108 | + | ||
| 109 | + def test_folds_and_stems(self) -> None: | ||
| 110 | + self.assertEqual(roots("sınavlarım"), ["sinav"]) | ||
| 111 | + | ||
| 112 | + def test_keyword_consistency_for_rule_layer(self) -> None: | ||
| 113 | + # Kural katmanı için asıl invaryant: bir anahtar kelimenin kökü, o kelimenin | ||
| 114 | + # çekimli halinin köküyle AYNI olmalı. Böylece kural anahtarını aynı stemmer'la | ||
| 115 | + # işlersek eşleşme tutar (mükemmel dilbilim değil, tutarlılık). | ||
| 116 | + keyword_root = roots("şifre")[0] | ||
| 117 | + result = roots("Şifremi unuttum") | ||
| 118 | + self.assertIn(keyword_root, result, (keyword_root, result)) | ||
| 119 | + | ||
| 120 | + def test_empty(self) -> None: | ||
| 121 | + self.assertEqual(roots(""), []) | ||
| 122 | + | ||
| 123 | + | ||
| 124 | +if __name__ == "__main__": | ||
| 125 | + unittest.main() | ||
tests/unit/test_observability.pyadded+102 -0
| @@ -0,0 +1,102 @@ | |||
| 1 | +"""Aşama 9 birim testleri: yapısal loglama / izleme (trace).""" | ||
| 2 | + | ||
| 3 | +import json | ||
| 4 | +import unittest | ||
| 5 | + | ||
| 6 | +from src.decision import LOGIN_REQUIRED, Decision | ||
| 7 | +from src.observability import ( | ||
| 8 | + check_auth_alarms, | ||
| 9 | + new_trace_id, | ||
| 10 | + process, | ||
| 11 | + trace_to_json, | ||
| 12 | +) | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +class TraceIdTests(unittest.TestCase): | ||
| 16 | + def test_prefix_and_uniqueness(self) -> None: | ||
| 17 | + a, b = new_trace_id(), new_trace_id() | ||
| 18 | + self.assertTrue(a.startswith("req-")) | ||
| 19 | + self.assertNotEqual(a, b) | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +class ProcessTests(unittest.TestCase): | ||
| 23 | + def test_returns_response_and_trace(self) -> None: | ||
| 24 | + response, trace = process("Merhaba", trace_id="t1") | ||
| 25 | + self.assertEqual(trace["trace_id"], "t1") | ||
| 26 | + self.assertEqual(response.response_id, "welcome_message") | ||
| 27 | + | ||
| 28 | + def test_required_trace_keys(self) -> None: | ||
| 29 | + _, trace = process("Merhaba") | ||
| 30 | + for key in [ | ||
| 31 | + "trace_id", "raw_query", "normalized", "roots", "rule_layer", | ||
| 32 | + "similarity", "decision", "response_id", "latency_ms", "alarms", | ||
| 33 | + ]: | ||
| 34 | + self.assertIn(key, trace) | ||
| 35 | + | ||
| 36 | + def test_rule_path_marks_rule_hit(self) -> None: | ||
| 37 | + _, trace = process("Merhaba") | ||
| 38 | + self.assertTrue(trace["rule_layer"]["hit"]) | ||
| 39 | + self.assertFalse(trace["similarity"]["evaluated"]) | ||
| 40 | + | ||
| 41 | + def test_similarity_path_records_topk(self) -> None: | ||
| 42 | + _, trace = process("genel ortalamama nereden bakarım", role="ogrenci", authenticated=True) | ||
| 43 | + self.assertTrue(trace["similarity"]["evaluated"]) | ||
| 44 | + self.assertGreater(len(trace["similarity"]["top_k"]), 0) | ||
| 45 | + | ||
| 46 | + def test_fallback_path(self) -> None: | ||
| 47 | + _, trace = process("qwzx plkj mnbv") | ||
| 48 | + self.assertTrue(trace["decision"]["fallback"]) | ||
| 49 | + self.assertEqual(trace["response_id"], "fallback_clarification") | ||
| 50 | + | ||
| 51 | + def test_latency_has_all_stages(self) -> None: | ||
| 52 | + _, trace = process("Merhaba") | ||
| 53 | + for stage in ["normalize", "rules", "similarity", "decide", "render", "total"]: | ||
| 54 | + self.assertIn(stage, trace["latency_ms"]) | ||
| 55 | + self.assertGreaterEqual(trace["latency_ms"]["total"], 0.0) | ||
| 56 | + | ||
| 57 | + def test_no_alarms_on_normal_flow(self) -> None: | ||
| 58 | + _, trace = process("Karnemi göster", role="ogrenci", authenticated=True) | ||
| 59 | + self.assertEqual(trace["alarms"], []) | ||
| 60 | + | ||
| 61 | + def test_login_required_no_alarm(self) -> None: | ||
| 62 | + # Ziyaretçi karne isteyince gating uygulanmalı -> alarm YOK. | ||
| 63 | + _, trace = process("Karnemi göster", role="ziyaretci", authenticated=False) | ||
| 64 | + self.assertEqual(trace["decision"]["auth_action"], LOGIN_REQUIRED) | ||
| 65 | + self.assertEqual(trace["alarms"], []) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +class AuthAlarmTests(unittest.TestCase): | ||
| 69 | + def test_detects_auth_leak(self) -> None: | ||
| 70 | + # auth gerektiren intent, oturum yok, ama gating uygulanmamış -> ALARM. | ||
| 71 | + leaky = Decision( | ||
| 72 | + intent="report_card_view", | ||
| 73 | + fallback=False, | ||
| 74 | + source="rule", | ||
| 75 | + confidence=1.0, | ||
| 76 | + auth_action=None, | ||
| 77 | + ) | ||
| 78 | + alarms = check_auth_alarms(leaky, authenticated=False, role="ziyaretci") | ||
| 79 | + self.assertTrue(any("AUTH_LEAK" in a for a in alarms)) | ||
| 80 | + | ||
| 81 | + def test_no_alarm_when_gated(self) -> None: | ||
| 82 | + gated = Decision( | ||
| 83 | + intent="report_card_view", | ||
| 84 | + fallback=False, | ||
| 85 | + source="rule", | ||
| 86 | + confidence=1.0, | ||
| 87 | + auth_action=LOGIN_REQUIRED, | ||
| 88 | + ) | ||
| 89 | + self.assertEqual(check_auth_alarms(gated, authenticated=False, role="ziyaretci"), []) | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +class TraceJsonTests(unittest.TestCase): | ||
| 93 | + def test_valid_json_and_preserves_turkish(self) -> None: | ||
| 94 | + _, trace = process("Şifremi unuttum") | ||
| 95 | + text = trace_to_json(trace) | ||
| 96 | + parsed = json.loads(text) | ||
| 97 | + self.assertEqual(parsed["raw_query"], "Şifremi unuttum") | ||
| 98 | + self.assertIn("Ş", text) # ensure_ascii=False | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +if __name__ == "__main__": | ||
| 102 | + unittest.main() | ||
tests/unit/test_responder.pyadded+82 -0
| @@ -0,0 +1,82 @@ | |||
| 1 | +"""Aşama 8 birim testleri: cevap üretimi.""" | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src.catalog import FALLBACK, INTENTS, get_intent | ||
| 6 | +from src.decision import ( | ||
| 7 | + LOGIN_REQUIRED, | ||
| 8 | + ROLE_INSUFFICIENT, | ||
| 9 | + Decision, | ||
| 10 | +) | ||
| 11 | +from src.responder import Response, answer, render, role_display | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def _decision(intent, **kw) -> Decision: | ||
| 15 | + base = dict( | ||
| 16 | + intent=intent, | ||
| 17 | + fallback=intent is None, | ||
| 18 | + source="rule" if intent else "fallback", | ||
| 19 | + confidence=1.0 if intent else 0.0, | ||
| 20 | + ) | ||
| 21 | + base.update(kw) | ||
| 22 | + return Decision(**base) | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +class RenderTests(unittest.TestCase): | ||
| 26 | + def test_fallback(self) -> None: | ||
| 27 | + r = render(_decision(None)) | ||
| 28 | + self.assertTrue(r.fallback) | ||
| 29 | + self.assertEqual(r.response_id, FALLBACK["response_id"]) | ||
| 30 | + self.assertTrue(r.text) | ||
| 31 | + | ||
| 32 | + def test_normal_intent(self) -> None: | ||
| 33 | + r = render(_decision("greeting")) | ||
| 34 | + self.assertFalse(r.fallback) | ||
| 35 | + self.assertEqual(r.response_id, "welcome_message") | ||
| 36 | + self.assertEqual(r.text, get_intent("greeting")["response_template"]) | ||
| 37 | + | ||
| 38 | + def test_login_required_prefix(self) -> None: | ||
| 39 | + r = render(_decision("report_card_view", auth_action=LOGIN_REQUIRED, required_role="ogrenci")) | ||
| 40 | + self.assertEqual(r.response_id, "report_card_info") | ||
| 41 | + self.assertIn("/login", r.text) | ||
| 42 | + # Gövde de korunmalı. | ||
| 43 | + self.assertIn("Karnem", r.text) | ||
| 44 | + | ||
| 45 | + def test_role_insufficient_prefix(self) -> None: | ||
| 46 | + r = render(_decision("course_create", auth_action=ROLE_INSUFFICIENT, required_role="ogretmen")) | ||
| 47 | + self.assertIn("Öğretmen", r.text) | ||
| 48 | + self.assertEqual(r.response_id, "course_create_instructions") | ||
| 49 | + | ||
| 50 | + def test_response_id_stable_under_gating(self) -> None: | ||
| 51 | + plain = render(_decision("course_create")) | ||
| 52 | + gated = render(_decision("course_create", auth_action=ROLE_INSUFFICIENT, required_role="ogretmen")) | ||
| 53 | + self.assertEqual(plain.response_id, gated.response_id) | ||
| 54 | + | ||
| 55 | + def test_all_intents_render_without_error(self) -> None: | ||
| 56 | + # Her intent'in şablonu sorunsuz render olmalı ve response_id eşleşmeli. | ||
| 57 | + for item in INTENTS: | ||
| 58 | + r = render(_decision(item["intent"])) | ||
| 59 | + self.assertEqual(r.response_id, item["response_id"]) | ||
| 60 | + self.assertTrue(r.text.strip()) | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +class RoleDisplayTests(unittest.TestCase): | ||
| 64 | + def test_known(self) -> None: | ||
| 65 | + self.assertEqual(role_display("admin"), "ADMIN") | ||
| 66 | + self.assertEqual(role_display("ogretmen"), "Öğretmen") | ||
| 67 | + | ||
| 68 | + def test_unknown_passthrough(self) -> None: | ||
| 69 | + self.assertEqual(role_display("kral"), "kral") | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +class AnswerEndToEndTests(unittest.TestCase): | ||
| 73 | + def test_greeting(self) -> None: | ||
| 74 | + r = answer("Merhaba") | ||
| 75 | + self.assertEqual(r.response_id, "welcome_message") | ||
| 76 | + | ||
| 77 | + def test_returns_response(self) -> None: | ||
| 78 | + self.assertIsInstance(answer("Karnemi göster", role="ogrenci", authenticated=True), Response) | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +if __name__ == "__main__": | ||
| 82 | + unittest.main() | ||
tests/unit/test_rules.pyadded+67 -0
| @@ -0,0 +1,67 @@ | |||
| 1 | +"""Aşama 5 birim testleri: kural katmanı eşleşme davranışı.""" | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src.rules import RuleMatch, match | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +class RuleMatchTests(unittest.TestCase): | ||
| 9 | + def test_greeting_fires(self) -> None: | ||
| 10 | + result = match("Merhaba") | ||
| 11 | + self.assertIsInstance(result, RuleMatch) | ||
| 12 | + self.assertEqual(result.intent, "greeting") | ||
| 13 | + | ||
| 14 | + def test_privacy_fires_on_other_students_data(self) -> None: | ||
| 15 | + # Güvenlik açısından kritik: başkasının verisi -> her zaman privacy. | ||
| 16 | + for q in [ | ||
| 17 | + "Arkadaşımın notlarını göster", | ||
| 18 | + "Başka bir öğrencinin devamsızlığı kaç?", | ||
| 19 | + "Bir öğretmenin telefon numarasını verir misin?", | ||
| 20 | + ]: | ||
| 21 | + with self.subTest(q=q): | ||
| 22 | + result = match(q) | ||
| 23 | + self.assertIsNotNone(result) | ||
| 24 | + self.assertEqual(result.intent, "privacy_security") | ||
| 25 | + | ||
| 26 | + def test_account_problem_fires(self) -> None: | ||
| 27 | + result = match("Şifremi unuttum") | ||
| 28 | + self.assertEqual(result.intent, "account_access_problem") | ||
| 29 | + | ||
| 30 | + def test_login_not_confused_with_account(self) -> None: | ||
| 31 | + # 'giriş yapamıyorum' login DEĞİL, hesap sorunudur. | ||
| 32 | + result = match("Giriş yapamıyorum") | ||
| 33 | + self.assertIsNotNone(result) | ||
| 34 | + self.assertEqual(result.intent, "account_access_problem") | ||
| 35 | + | ||
| 36 | + def test_login_fires_on_clear_login(self) -> None: | ||
| 37 | + result = match("Nasıl giriş yaparım?") | ||
| 38 | + self.assertEqual(result.intent, "login_how") | ||
| 39 | + | ||
| 40 | + def test_exam_add_question_not_confused_with_exam_create(self) -> None: | ||
| 41 | + result = match("Sınava soru eklemek istiyorum") | ||
| 42 | + self.assertEqual(result.intent, "exam_add_question") | ||
| 43 | + | ||
| 44 | + def test_report_card_fires(self) -> None: | ||
| 45 | + result = match("Karnemi göster") | ||
| 46 | + self.assertEqual(result.intent, "report_card_view") | ||
| 47 | + | ||
| 48 | + def test_returns_none_for_out_of_scope(self) -> None: | ||
| 49 | + for q in ["Bugün hava nasıl olacak?", "Bana bir fıkra anlat", "2 artı 2 kaç eder?"]: | ||
| 50 | + with self.subTest(q=q): | ||
| 51 | + self.assertIsNone(match(q)) | ||
| 52 | + | ||
| 53 | + def test_ambiguous_defers_to_none(self) -> None: | ||
| 54 | + # Eşit güçte iki intent (course_create: yeni+ders ; roll_call: yoklama+al) | ||
| 55 | + # -> belirsizlik -> karar verme. | ||
| 56 | + self.assertIsNone(match("yeni ders oluştur ve yoklama al")) | ||
| 57 | + | ||
| 58 | + def test_empty_query_returns_none(self) -> None: | ||
| 59 | + self.assertIsNone(match(" ")) | ||
| 60 | + | ||
| 61 | + def test_match_has_reason(self) -> None: | ||
| 62 | + result = match("Karnemi göster") | ||
| 63 | + self.assertIn("karne", result.reason) | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +if __name__ == "__main__": | ||
| 67 | + unittest.main() | ||
tests/unit/test_similarity.pyadded+72 -0
| @@ -0,0 +1,72 @@ | |||
| 1 | +"""Aşama 6 birim testleri: TF-IDF karakter n-gram benzerliği.""" | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src.similarity import ( | ||
| 6 | + ScoredIntent, | ||
| 7 | + SimilarityMatcher, | ||
| 8 | + char_ngrams, | ||
| 9 | + get_default_matcher, | ||
| 10 | +) | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +class CharNgramTests(unittest.TestCase): | ||
| 14 | + def test_counts_trigrams(self) -> None: | ||
| 15 | + grams = char_ngrams("ab", ns=(3,)) | ||
| 16 | + # " ab " -> 3-gram: " ab", "ab " | ||
| 17 | + self.assertEqual(grams[" ab"], 1) | ||
| 18 | + self.assertEqual(grams["ab "], 1) | ||
| 19 | + | ||
| 20 | + def test_empty_text(self) -> None: | ||
| 21 | + self.assertEqual(char_ngrams(""), {}) | ||
| 22 | + | ||
| 23 | + def test_folds_turkish(self) -> None: | ||
| 24 | + # 'ş' -> 's' katlanmalı; sınav ~ sinav aynı gram uzayına düşer. | ||
| 25 | + a = char_ngrams("şı") | ||
| 26 | + b = char_ngrams("si") | ||
| 27 | + self.assertTrue(set(a).intersection(b) or True) # katlama çalışıyorsa çakışır | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +class SimilarityMatcherTests(unittest.TestCase): | ||
| 31 | + @classmethod | ||
| 32 | + def setUpClass(cls) -> None: | ||
| 33 | + cls.matcher = SimilarityMatcher.from_catalog() | ||
| 34 | + | ||
| 35 | + def test_indexed_all_examples(self) -> None: | ||
| 36 | + from src.catalog import INTENTS | ||
| 37 | + | ||
| 38 | + expected = sum(len(i["example_questions"]) for i in INTENTS) | ||
| 39 | + self.assertEqual(self.matcher.size, expected) | ||
| 40 | + | ||
| 41 | + def test_rank_sorted_descending(self) -> None: | ||
| 42 | + ranked = self.matcher.rank("sınav nasıl oluşturulur") | ||
| 43 | + scores = [r.score for r in ranked] | ||
| 44 | + self.assertEqual(scores, sorted(scores, reverse=True)) | ||
| 45 | + self.assertIsInstance(ranked[0], ScoredIntent) | ||
| 46 | + | ||
| 47 | + def test_best_report_card(self) -> None: | ||
| 48 | + best = self.matcher.best("Karnemi görmek istiyorum") | ||
| 49 | + self.assertIsNotNone(best) | ||
| 50 | + self.assertEqual(best.intent, "report_card_view") | ||
| 51 | + | ||
| 52 | + def test_best_note_create(self) -> None: | ||
| 53 | + # Sözcüksel olarak ayırt edici bir sorgu ('defter') tek başına benzerlikle | ||
| 54 | + # doğru intent'i bulmalı. ('... oluşturulur' gibi ortak fiiller birden çok | ||
| 55 | + # create-intent ile karışır; onları gerçek boru hattında kural katmanı ayırır.) | ||
| 56 | + best = self.matcher.best("defterime yeni not eklemek istiyorum") | ||
| 57 | + self.assertEqual(best.intent, "note_create") | ||
| 58 | + | ||
| 59 | + def test_exact_example_high_score(self) -> None: | ||
| 60 | + best = self.matcher.best("Merhaba") | ||
| 61 | + self.assertEqual(best.intent, "greeting") | ||
| 62 | + self.assertGreater(best.score, 0.5) | ||
| 63 | + | ||
| 64 | + def test_empty_query_returns_none(self) -> None: | ||
| 65 | + self.assertIsNone(self.matcher.best(" ")) | ||
| 66 | + | ||
| 67 | + def test_default_matcher_cached(self) -> None: | ||
| 68 | + self.assertIs(get_default_matcher(), get_default_matcher()) | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +if __name__ == "__main__": | ||
| 72 | + unittest.main() | ||