forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rule_based_chatbot

Clone
★ 0

0 watching0 forksPython1.2 MiBbe255cdKadir Yönak4 months ago3 commits

rules.py257 lines, 9.8 KiBHistoryRawDownload
1"""Kural katmanı: yüksek-kesinlik, deterministik intent eşleşmesi.
2
3Felsefe: Bu katman HER soruyu kapsamaz; yalnızca anahtar kelimesi TEK ANLAMLI
4olan (ve özellikle güvenlik açısından kritik) soruları deterministik olarak
5bağlar. Belirsizlikte (birden çok intent eşit güçle eşleşirse) bilerek KARAR
6VERMEZ (None döner) ve kararı benzerlik katmanına bırakır. Amaç coverage değil,
7kapsanan sorularda ~%100 kesinliktir.
8
9Eş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
12Türkçe çekimi ('şifre' <- 'şifremi') çökertmeden yakalar.
13
14Kural grubu (group):
15 {"all": [kelime, ...], "none": [kelime, ...]?}
16Grup eşleşir <=> "all" içindeki her kelime soruda VAR ve "none" içindeki hiçbir
17kelime soruda YOK. Bir intent'in grupları OR ile birleşir; grup büyüklüğü (all
18uzunluğu) o eşleşmenin "özgüllük skoru"dur — belirsizlik çözümünde kullanılır.
19"""
20
21from __future__ import annotations
22
23from dataclasses import dataclass
24from typing import Any, Final
25
26from .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
159def _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)
166class _Group:
167 all_kw: tuple[str, ...]
168 none_kw: tuple[str, ...] = ()
169
170
171@dataclass(frozen=True)
172class _Rule:
173 intent: str
174 groups: tuple[_Group, ...]
175
176
177def _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)
195class RuleMatch:
196 """Kural katmanının kararı."""
197
198 intent: str
199 score: int
200 matched: tuple[str, ...]
201 reason: str
202
203
204def _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
212def _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
220def 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 )