| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | from __future__ import annotations |
| 17 | |
| 18 | import argparse |
| 19 | import json |
| 20 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 21 | |
| 22 | from .catalog import ROLE_HIERARCHY |
| 23 | from .engine import Engine, RequestError |
| 24 | from .safety import RateLimiter |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | FEEDBACK_LOG = "feedback.jsonl" |
| 31 | |
| 32 | |
| 33 | INDEX_HTML = """<!doctype html> |
| 34 | <html lang="tr"> |
| 35 | <head> |
| 36 | <meta charset="utf-8"> |
| 37 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 38 | <title>Çelebi · Hezarfen Asistanı — Dev</title> |
| 39 | <style> |
| 40 | :root { |
| 41 | --bg:#0f1115; --panel:#171a21; --panel2:#1f232c; --line:#2a2f3a; |
| 42 | --text:#e7e9ee; --muted:#9aa3b2; --accent:#5b8cff; --user:#264a8f; |
| 43 | --ok:#2f9e5a; --warn:#d0921f; --bad:#d0453b; --info:#7a5cff; |
| 44 | } |
| 45 | * { box-sizing:border-box; } |
| 46 | body { margin:0; font:15px/1.5 system-ui,Segoe UI,Roboto,sans-serif; |
| 47 | background:var(--bg); color:var(--text); height:100vh; display:flex; flex-direction:column; } |
| 48 | header { padding:12px 16px; background:var(--panel); border-bottom:1px solid var(--line); |
| 49 | display:flex; gap:12px; align-items:center; flex-wrap:wrap; } |
| 50 | header h1 { font-size:15px; margin:0; font-weight:600; } |
| 51 | header .grow { flex:1; } |
| 52 | label { color:var(--muted); font-size:13px; } |
| 53 | select, input[type=text] { background:var(--panel2); color:var(--text); |
| 54 | border:1px solid var(--line); border-radius:8px; padding:8px 10px; font:inherit; } |
| 55 | select:focus, input:focus { outline:1px solid var(--accent); } |
| 56 | .chk { display:flex; align-items:center; gap:6px; color:var(--muted); font-size:13px; } |
| 57 | #log { flex:1; overflow-y:auto; padding:20px; display:flex; flex-direction:column; gap:14px; } |
| 58 | .msg { max-width:min(760px,92%); } |
| 59 | .msg.user { align-self:flex-end; } |
| 60 | .bubble { padding:10px 14px; border-radius:12px; white-space:pre-wrap; word-wrap:break-word; } |
| 61 | .user .bubble { background:var(--user); border-bottom-right-radius:4px; } |
| 62 | .bot .bubble { background:var(--panel2); border:1px solid var(--line); border-bottom-left-radius:4px; } |
| 63 | .meta { margin-top:6px; display:flex; gap:6px; flex-wrap:wrap; font-size:11px; } |
| 64 | .tag { padding:2px 8px; border-radius:999px; background:var(--panel); |
| 65 | border:1px solid var(--line); color:var(--muted); } |
| 66 | .tag b { color:var(--text); font-weight:600; } |
| 67 | .tag.intent { border-color:var(--accent); } |
| 68 | .tag.fallback { border-color:var(--warn); color:var(--warn); } |
| 69 | .tag.safety { border-color:var(--info); color:#b9a9ff; } |
| 70 | .tag.auth { border-color:var(--bad); color:#ff9a91; } |
| 71 | .nav-cta { margin-top:11px; display:inline-flex; align-items:center; gap:9px; |
| 72 | background:var(--accent); color:#fff; border:0; border-radius:10px; padding:9px 14px; |
| 73 | font:inherit; font-weight:600; font-size:13.5px; cursor:pointer; } |
| 74 | .nav-cta .route { font-family:ui-monospace,monospace; font-size:11px; opacity:.8; } |
| 75 | .nav-cta .arr { font-size:15px; } |
| 76 | .nav-cta.off { background:var(--panel2); color:var(--muted); |
| 77 | border:1px solid var(--line); cursor:not-allowed; } |
| 78 | .sys { align-self:center; font-size:12px; color:var(--muted); font-style:italic; |
| 79 | padding:2px 0; } |
| 80 | .clarify { margin-top:10px; padding:10px 12px; background:var(--panel); |
| 81 | border:1px dashed var(--accent); border-radius:10px; } |
| 82 | .clarify-q { font-size:13px; color:var(--muted); margin-bottom:8px; } |
| 83 | .chip { background:var(--panel2); color:var(--text); border:1px solid var(--accent); |
| 84 | border-radius:999px; padding:6px 12px; margin:0 6px 6px 0; font-size:13px; |
| 85 | font-weight:500; cursor:pointer; } |
| 86 | .chip:hover { background:var(--accent); } |
| 87 | .fb { margin-top:8px; display:flex; align-items:center; gap:8px; } |
| 88 | .fb-label { font-size:12px; color:var(--muted); } |
| 89 | .fb-btn { background:transparent; padding:2px 8px; font-size:15px; border-radius:6px; } |
| 90 | .fb-btn:hover { background:var(--panel2); } |
| 91 | .fb-done { font-size:12px; color:var(--ok); } |
| 92 | .suggest { margin-top:12px; padding-top:10px; border-top:1px dashed var(--line); } |
| 93 | .suggest-q { font-size:12px; color:var(--muted); margin-bottom:8px; } |
| 94 | .bubble code { background:var(--panel); padding:1px 5px; border-radius:5px; |
| 95 | font-size:13px; } |
| 96 | .bubble strong { color:#fff; font-weight:700; } |
| 97 | footer { padding:12px 16px; background:var(--panel); border-top:1px solid var(--line); |
| 98 | display:flex; gap:10px; } |
| 99 | #q { flex:1; } |
| 100 | button { background:var(--accent); color:#fff; border:0; border-radius:8px; |
| 101 | padding:9px 18px; font:inherit; font-weight:600; cursor:pointer; } |
| 102 | button:disabled { opacity:.5; cursor:default; } |
| 103 | .hint { color:var(--muted); font-size:12px; align-self:center; } |
| 104 | </style> |
| 105 | </head> |
| 106 | <body> |
| 107 | <header> |
| 108 | <h1>🪽 Çelebi · Hezarfen Asistanı</h1> |
| 109 | <span class="tag">dev</span> |
| 110 | <div class="grow"></div> |
| 111 | <label>Rol</label> |
| 112 | <select id="role"> |
| 113 | <option value="ziyaretci">Ziyaretçi</option> |
| 114 | <option value="veli">Veli</option> |
| 115 | <option value="ogrenci" selected>Öğrenci</option> |
| 116 | <option value="ogretmen">Öğretmen</option> |
| 117 | <option value="yonetici">Yönetici</option> |
| 118 | <option value="admin">ADMIN</option> |
| 119 | </select> |
| 120 | <label>Ad</label> |
| 121 | <input type="text" id="uname" placeholder="ör. Kadir" value="Kadir" |
| 122 | style="width:90px; padding:6px 8px; border-radius:8px; border:1px solid var(--line); background:var(--panel2); color:var(--text);"> |
| 123 | <label class="chk"><input type="checkbox" id="devmeta" checked> dev etiketleri</label> |
| 124 | </header> |
| 125 | |
| 126 | <div id="log"></div> |
| 127 | |
| 128 | <footer> |
| 129 | <input type="text" id="q" placeholder="Bir soru yaz — ör. 'sınav nasıl oluşturulur'" |
| 130 | autocomplete="off" autofocus> |
| 131 | <button id="send">Gönder</button> |
| 132 | </footer> |
| 133 | |
| 134 | <script> |
| 135 | const log = document.getElementById('log'); |
| 136 | const q = document.getElementById('q'); |
| 137 | const send = document.getElementById('send'); |
| 138 | const roleSel = document.getElementById('role'); |
| 139 | const devmeta = document.getElementById('devmeta'); |
| 140 | |
| 141 | function el(tag, cls, text) { |
| 142 | const e = document.createElement(tag); |
| 143 | if (cls) e.className = cls; |
| 144 | if (text !== undefined) e.textContent = text; |
| 145 | return e; |
| 146 | } |
| 147 | |
| 148 | function addUser(text) { |
| 149 | const wrap = el('div', 'msg user'); |
| 150 | wrap.appendChild(el('div', 'bubble', text)); |
| 151 | log.appendChild(wrap); |
| 152 | log.scrollTop = log.scrollHeight; |
| 153 | } |
| 154 | |
| 155 | function escapeHtml(s) { |
| 156 | return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); |
| 157 | } |
| 158 | // Basit markdown: **kalın**, `kod`, satır sonu. Metin bizim şablonlarımızdan gelir |
| 159 | // (güvenilir); yine de önce HTML kaçışı yapılır. |
| 160 | function md(s) { |
| 161 | return escapeHtml(s || '(boş yanıt)') |
| 162 | .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>') |
| 163 | .replace(/`([^`]+)`/g, '<code>$1</code>') |
| 164 | .replace(/\n/g, '<br>'); |
| 165 | } |
| 166 | |
| 167 | function addBot(resp) { |
| 168 | const wrap = el('div', 'msg bot'); |
| 169 | const bubble = el('div', 'bubble'); |
| 170 | bubble.innerHTML = md(resp.text); |
| 171 | wrap.appendChild(bubble); |
| 172 | // Yönlendirme (route): ilgili sayfaya götüren buton. |
| 173 | if (resp.navigation) { |
| 174 | const nav = el('button', 'nav-cta' + (resp.navigation.available ? '' : ' off')); |
| 175 | nav.innerHTML = '<span>' + resp.navigation.label + '</span>' + |
| 176 | '<span class="route">' + resp.navigation.route + '</span><span class="arr">→</span>'; |
| 177 | if (resp.navigation.available) { |
| 178 | nav.addEventListener('click', () => |
| 179 | addSys('→ ' + resp.navigation.route + ' sayfasına yönlendirilir (gerçek gezinme front tarafında)')); |
| 180 | } else { |
| 181 | nav.title = 'Bu sayfa için yetkin yetmiyor'; |
| 182 | } |
| 183 | bubble.appendChild(nav); |
| 184 | } |
| 185 | if (devmeta.checked) { |
| 186 | const meta = el('div', 'meta'); |
| 187 | const safety = resp.safety || {}; |
| 188 | if (resp.intent) { |
| 189 | const t = el('span', 'tag intent'); t.innerHTML = 'intent <b>' + resp.intent + '</b>'; meta.appendChild(t); |
| 190 | } |
| 191 | if (resp.fallback) meta.appendChild(el('span', 'tag fallback', 'fallback')); |
| 192 | const conf = el('span', 'tag'); conf.innerHTML = 'güven <b>' + (resp.confidence ?? 0).toFixed(3) + '</b>'; meta.appendChild(conf); |
| 193 | if (safety.category && safety.category !== 'CLEAN') { |
| 194 | const t = el('span', 'tag safety'); t.innerHTML = 'safety <b>' + safety.category + '</b> · ' + safety.decision; meta.appendChild(t); |
| 195 | } |
| 196 | if (resp.auth_action) { |
| 197 | const t = el('span', 'tag auth'); t.innerHTML = resp.auth_action + (resp.required_role ? ' · ' + resp.required_role : ''); meta.appendChild(t); |
| 198 | } |
| 199 | wrap.appendChild(meta); |
| 200 | } |
| 201 | // Netleştirme (item 1): ilk iki aday yakınsa "Bunu mu demek istedin?" çipleri. |
| 202 | if (resp.clarification) { |
| 203 | const box = el('div', 'clarify'); |
| 204 | box.appendChild(el('div', 'clarify-q', '🤔 Bunu mu demek istedin?')); |
| 205 | resp.clarification.candidates.forEach(c => { |
| 206 | const chip = el('button', 'chip', c.label); |
| 207 | chip.addEventListener('click', () => { q.value = c.label; ask(); }); |
| 208 | box.appendChild(chip); |
| 209 | }); |
| 210 | wrap.appendChild(box); |
| 211 | } |
| 212 | // Geri-bildirim (item 5): gerçek cevaplarda 👍/👎 -> /api/feedback. |
| 213 | if (resp.intent && !resp.fallback) { |
| 214 | const fb = el('div', 'fb'); |
| 215 | fb.appendChild(el('span', 'fb-label', 'Yardımcı oldu mu?')); |
| 216 | ['up', 'down'].forEach(r => { |
| 217 | const b = el('button', 'fb-btn', r === 'up' ? '👍' : '👎'); |
| 218 | b.addEventListener('click', () => sendFeedback(resp, r, fb)); |
| 219 | fb.appendChild(b); |
| 220 | }); |
| 221 | wrap.appendChild(fb); |
| 222 | } |
| 223 | // Role göre başlangıç soru önerileri — yalnız "başlangıç/kayıp" anlarında |
| 224 | // (selam/yardım/tanıtım/fallback/netleştirme); somut cevaplarda gösterme. |
| 225 | const starterIntents = ['greeting', 'smalltalk', 'help_capabilities', |
| 226 | 'platform_info', 'bot_identity', 'farewell', 'thanks']; |
| 227 | const showSuggest = resp.fallback || !resp.intent || starterIntents.includes(resp.intent); |
| 228 | if (resp.suggestions && resp.suggestions.length && showSuggest) { |
| 229 | const sg = el('div', 'suggest'); |
| 230 | sg.appendChild(el('div', 'suggest-q', 'Şunları sorabilirsin:')); |
| 231 | resp.suggestions.forEach(s => { |
| 232 | const chip = el('button', 'chip', s); |
| 233 | chip.addEventListener('click', () => { q.value = s; ask(); }); |
| 234 | sg.appendChild(chip); |
| 235 | }); |
| 236 | wrap.appendChild(sg); |
| 237 | } |
| 238 | log.appendChild(wrap); |
| 239 | log.scrollTop = log.scrollHeight; |
| 240 | } |
| 241 | |
| 242 | function sendFeedback(resp, rating, fbEl) { |
| 243 | fetch('/api/feedback', { |
| 244 | method: 'POST', headers: {'Content-Type': 'application/json'}, |
| 245 | body: JSON.stringify({trace_id: resp.trace_id, response_id: resp.response_id, |
| 246 | intent: resp.intent, rating: rating}) |
| 247 | }); |
| 248 | fbEl.innerHTML = '<span class="fb-done">Teşekkürler! (' + (rating === 'up' ? '👍' : '👎') + ')</span>'; |
| 249 | } |
| 250 | |
| 251 | function addSys(text) { |
| 252 | const line = el('div', 'sys', text); |
| 253 | log.appendChild(line); |
| 254 | log.scrollTop = log.scrollHeight; |
| 255 | } |
| 256 | |
| 257 | function addError(text) { |
| 258 | const wrap = el('div', 'msg bot'); |
| 259 | const b = el('div', 'bubble', '⚠ ' + text); |
| 260 | b.style.borderColor = '#d0453b'; |
| 261 | wrap.appendChild(b); |
| 262 | log.appendChild(wrap); |
| 263 | log.scrollTop = log.scrollHeight; |
| 264 | } |
| 265 | |
| 266 | async function ask() { |
| 267 | const text = q.value.trim(); |
| 268 | if (!text) return; |
| 269 | addUser(text); |
| 270 | q.value = ''; |
| 271 | send.disabled = true; |
| 272 | try { |
| 273 | const r = await fetch('/api/chat', { |
| 274 | method: 'POST', |
| 275 | headers: {'Content-Type': 'application/json'}, |
| 276 | body: JSON.stringify({ |
| 277 | query: text, |
| 278 | role: roleSel.value, |
| 279 | authenticated: roleSel.value !== 'ziyaretci', |
| 280 | user_id: 'dev-user', |
| 281 | name: document.getElementById('uname').value |
| 282 | }) |
| 283 | }); |
| 284 | const data = await r.json(); |
| 285 | if (data.error) addError(data.error); else addBot(data); |
| 286 | } catch (e) { |
| 287 | addError('Sunucuya ulaşılamadı: ' + e.message); |
| 288 | } finally { |
| 289 | send.disabled = false; |
| 290 | q.focus(); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | send.addEventListener('click', ask); |
| 295 | q.addEventListener('keydown', e => { if (e.key === 'Enter') ask(); }); |
| 296 | |
| 297 | addBot({text: "Merhaba! Ben Çelebi 🪽 — Hezarfen kullanım asistanı. Yukarıdan rolü değiştirip \\n" + |
| 298 | "istediğini sorabilirsin. Örnekler: 'sınav nasıl oluşturulur', 'şifremi unuttum', \\n" + |
| 299 | "'karnemi nerede görürüm', 'başka bir öğrencinin notunu görebilir miyim'.", |
| 300 | safety: {}, confidence: 0}); |
| 301 | </script> |
| 302 | </body> |
| 303 | </html>""" |
| 304 | |
| 305 | |
| 306 | class Handler(BaseHTTPRequestHandler): |
| 307 | engine: Engine |
| 308 | |
| 309 | def log_message(self, fmt, *args): |
| 310 | pass |
| 311 | |
| 312 | def _send(self, code: int, body: bytes, content_type: str) -> None: |
| 313 | self.send_response(code) |
| 314 | self.send_header("Content-Type", content_type) |
| 315 | self.send_header("Content-Length", str(len(body))) |
| 316 | self.end_headers() |
| 317 | self.wfile.write(body) |
| 318 | |
| 319 | def _send_json(self, code: int, obj: dict) -> None: |
| 320 | self._send(code, json.dumps(obj, ensure_ascii=False).encode("utf-8"), |
| 321 | "application/json; charset=utf-8") |
| 322 | |
| 323 | def do_GET(self) -> None: |
| 324 | if self.path in ("/", "/index.html"): |
| 325 | self._send(200, INDEX_HTML.encode("utf-8"), "text/html; charset=utf-8") |
| 326 | else: |
| 327 | self._send_json(404, {"error": "Bulunamadı"}) |
| 328 | |
| 329 | def do_POST(self) -> None: |
| 330 | if self.path not in ("/api/chat", "/api/feedback"): |
| 331 | self._send_json(404, {"error": "Bulunamadı"}) |
| 332 | return |
| 333 | try: |
| 334 | length = int(self.headers.get("Content-Length", 0)) |
| 335 | payload_in = json.loads(self.rfile.read(length) or b"{}") |
| 336 | except (ValueError, json.JSONDecodeError): |
| 337 | self._send_json(400, {"error": "Geçersiz JSON"}) |
| 338 | return |
| 339 | |
| 340 | if self.path == "/api/feedback": |
| 341 | record = { |
| 342 | "trace_id": payload_in.get("trace_id"), |
| 343 | "response_id": payload_in.get("response_id"), |
| 344 | "query": payload_in.get("query"), |
| 345 | "intent": payload_in.get("intent"), |
| 346 | "rating": payload_in.get("rating"), |
| 347 | } |
| 348 | try: |
| 349 | with open(FEEDBACK_LOG, "a", encoding="utf-8") as fh: |
| 350 | fh.write(json.dumps(record, ensure_ascii=False) + "\n") |
| 351 | except OSError: |
| 352 | pass |
| 353 | self._send_json(200, {"ok": True}) |
| 354 | return |
| 355 | |
| 356 | role = payload_in.get("role", "ziyaretci") |
| 357 | request = { |
| 358 | "query": payload_in.get("query", ""), |
| 359 | "session": { |
| 360 | "role": role, |
| 361 | "authenticated": bool(payload_in.get("authenticated", role != "ziyaretci")), |
| 362 | "user_id": payload_in.get("user_id"), |
| 363 | "name": payload_in.get("name"), |
| 364 | }, |
| 365 | } |
| 366 | try: |
| 367 | resp = self.engine.handle(request) |
| 368 | except RequestError as exc: |
| 369 | self._send_json(400, {"error": str(exc)}) |
| 370 | return |
| 371 | except Exception as exc: |
| 372 | self._send_json(500, {"error": f"Sunucu hatası: {exc}"}) |
| 373 | return |
| 374 | self._send_json(200, resp) |
| 375 | |
| 376 | |
| 377 | def main() -> int: |
| 378 | parser = argparse.ArgumentParser(description="Hezarfen asistanı dev web arayüzü") |
| 379 | parser.add_argument("--host", default="127.0.0.1") |
| 380 | parser.add_argument("--port", type=int, default=8000) |
| 381 | parser.add_argument("--rate-limit", action="store_true", |
| 382 | help="RateLimiter'ı devreye al (spam/tekrar testi)") |
| 383 | args = parser.parse_args() |
| 384 | |
| 385 | limiter = RateLimiter() if args.rate_limit else None |
| 386 | Handler.engine = Engine(rate_limiter=limiter) |
| 387 | |
| 388 | server = ThreadingHTTPServer((args.host, args.port), Handler) |
| 389 | url = f"http://{args.host}:{args.port}" |
| 390 | print(f"Roller: {', '.join(ROLE_HIERARCHY)}") |
| 391 | print(f"Hezarfen dev arayüzü çalışıyor: {url} (Ctrl+C ile durdur)") |
| 392 | try: |
| 393 | server.serve_forever() |
| 394 | except KeyboardInterrupt: |
| 395 | print("\nDurduruldu.") |
| 396 | finally: |
| 397 | server.server_close() |
| 398 | return 0 |
| 399 | |
| 400 | |
| 401 | if __name__ == "__main__": |
| 402 | raise SystemExit(main()) |