nikeshn commited on
Commit
be8b2de
Β·
verified Β·
1 Parent(s): bd35c25

Upload 8 files

Browse files
src/services/rag_service.py CHANGED
@@ -1,355 +1,355 @@
1
- """Local keyword retrieval first, with an optional cached semantic index.
2
-
3
- Initialization never needs an API key to serve the local KB. Dense failures
4
- leave keyword search available; callers may run initialize in the background.
5
- """
6
- import asyncio
7
- import hashlib
8
- import hmac
9
- import json
10
- import logging
11
- import os
12
- import re
13
- import time
14
- from pathlib import Path
15
- from typing import List
16
-
17
- from src.config import get_settings
18
-
19
- logger = logging.getLogger(__name__)
20
- CHUNK_WORDS = 260
21
- CHUNK_OVERLAP_WORDS = 40
22
- EMBEDDING_MODEL = "text-embedding-3-small"
23
- CACHE_SCHEMA = 2
24
- TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*", re.UNICODE)
25
- STOP_WORDS = {"about", "and", "are", "can", "for", "from", "how", "library", "please", "that", "the", "this", "what", "when", "where", "which", "with", "you"}
26
- # Passages with no shared words are returned only below this FAISS distance
27
- # (squared L2 on unit vectors: 1.0 is cosine similarity 0.5). Tune with the
28
- # Space variable RAG_DENSE_ONLY_MAX_DISTANCE; 0 restores keyword-only filtering.
29
- DENSE_ONLY_MAX_DISTANCE = float(os.getenv("RAG_DENSE_ONLY_MAX_DISTANCE", "1.0") or 0)
30
- DENSE_ONLY_LIMIT = 2
31
- HEADER_RE = re.compile(r"^(?:SOURCE|TITLE|AUTHORITY|LAST_REVIEWED|LAST_UPDATED):", re.IGNORECASE)
32
-
33
-
34
- class RAGService:
35
- def __init__(self):
36
- self.vectorstore = None
37
- self.bm25 = None
38
- self.bm25_corpus: List[str] = []
39
- self.bm25_meta: List[dict] = []
40
- self._embeddings = None
41
- self._ready = False
42
- self._kb_hash = ""
43
- self._status = "not_started"
44
- self._content_to_idx: dict[str, int] = {}
45
- self._init_lock = asyncio.Lock()
46
-
47
- def is_ready(self) -> bool:
48
- return self._ready
49
-
50
- def _knowledge_dir(self) -> Path:
51
- return get_settings().kb_dir
52
-
53
- def _cache_dir(self) -> Path:
54
- return get_settings().rag_cache_dir
55
-
56
- def _hash_knowledge_base(self, txt_files: List[Path]) -> str:
57
- # Deployments commonly reset mtimes. Hash content plus indexing settings
58
- # so unchanged data can reuse persisted embeddings across image rebuilds.
59
- digest = hashlib.sha256()
60
- digest.update(f"{CACHE_SCHEMA}:{EMBEDDING_MODEL}:{CHUNK_WORDS}:{CHUNK_OVERLAP_WORDS}".encode())
61
- for path in sorted(txt_files):
62
- digest.update(path.name.encode("utf-8"))
63
- digest.update(b"\0")
64
- digest.update(path.read_bytes())
65
- digest.update(b"\0")
66
- return digest.hexdigest()
67
-
68
- def _cache_paths(self) -> tuple[Path, Path, Path]:
69
- cache_dir = self._cache_dir()
70
- return cache_dir / "faiss_index", cache_dir / "bm25_cache.json", cache_dir / "kb_state.json"
71
-
72
- def _cache_signature(self, faiss_dir: Path, bm25_path: Path) -> str:
73
- key = get_settings().origin_token.encode("utf-8")
74
- if not key:
75
- return ""
76
- digest = hmac.new(key, digestmod=hashlib.sha256)
77
- for path in sorted([bm25_path, *faiss_dir.glob("*")]):
78
- if path.is_file():
79
- digest.update(path.name.encode("utf-8"))
80
- digest.update(path.read_bytes())
81
- return digest.hexdigest()
82
-
83
- @staticmethod
84
- def _tokens(value: str) -> List[str]:
85
- return TOKEN_RE.findall((value or "").casefold())
86
-
87
- def _build_reverse_index(self) -> None:
88
- self._content_to_idx = {chunk.strip(): i for i, chunk in enumerate(self.bm25_corpus)}
89
-
90
- def _build_keyword_index(self):
91
- from rank_bm25 import BM25Okapi
92
- files = sorted(self._knowledge_dir().glob("*.txt"))
93
- kb_hash = self._hash_knowledge_base(files)
94
- chunks, metadata = self._load_and_chunk_all()
95
- if not chunks:
96
- raise ValueError("No usable knowledge-base chunks found")
97
- bm25 = BM25Okapi([self._tokens(chunk) for chunk in chunks])
98
- return kb_hash, chunks, metadata, bm25
99
-
100
- async def initialize(self, openai_api_key: str = "", *, force_rebuild: bool = False) -> None:
101
- async with self._init_lock:
102
- started = time.monotonic()
103
- self._status = "initializing"
104
- try:
105
- # File reads, tokenization, and heavy imports must not block the
106
- # event loop serving /config, health checks, and chat requests.
107
- kb_hash, chunks, metadata, bm25 = await asyncio.to_thread(self._build_keyword_index)
108
- self.vectorstore = None
109
- self._embeddings = None
110
- self._kb_hash = kb_hash
111
- self.bm25_corpus, self.bm25_meta, self.bm25 = chunks, metadata, bm25
112
- self._build_reverse_index()
113
- self._ready = True
114
- self._status = "keyword_ready"
115
- logger.info("RAG keyword index ready: %d chunks in %.2fs", len(chunks), time.monotonic() - started)
116
- except Exception:
117
- self._status = ("ready" if self.vectorstore is not None else "keyword_ready") if self._ready else "failed"
118
- logger.exception("RAG keyword initialization failed; retaining any existing index")
119
- return
120
-
121
- if not openai_api_key:
122
- return
123
- self._status = "semantic_initializing"
124
- try:
125
- def load_embedding_tools():
126
- from langchain_openai import OpenAIEmbeddings
127
- from langchain_community.vectorstores import FAISS
128
- return OpenAIEmbeddings, FAISS
129
- OpenAIEmbeddings, FAISS = await asyncio.to_thread(load_embedding_tools)
130
- self._embeddings = OpenAIEmbeddings(
131
- model=EMBEDDING_MODEL, openai_api_key=openai_api_key,
132
- request_timeout=15, max_retries=1,
133
- )
134
- if not force_rebuild and await asyncio.to_thread(self._try_load_cached_indexes, FAISS):
135
- self._status = "ready"
136
- return
137
- vectorstore = await asyncio.wait_for(
138
- FAISS.afrom_texts(chunks, self._embeddings, metadatas=metadata), timeout=90
139
- )
140
- self.vectorstore = vectorstore
141
- self._status = "ready"
142
- try:
143
- await asyncio.to_thread(self._save_cached_indexes)
144
- except Exception:
145
- # An unwritable cache must not disable a working index.
146
- logger.exception("RAG cache save failed; retrieval remains available")
147
- logger.info("RAG semantic index ready in %.2fs", time.monotonic() - started)
148
- except asyncio.CancelledError:
149
- self._status = "keyword_ready"
150
- raise
151
- except Exception:
152
- self._status = "keyword_ready"
153
- logger.exception("RAG semantic index unavailable; using keyword retrieval")
154
-
155
- def _try_load_cached_indexes(self, FAISS, _BM25Okapi=None) -> bool:
156
- faiss_dir, bm25_path, state_path = self._cache_paths()
157
- if not (faiss_dir.exists() and bm25_path.exists() and state_path.exists()):
158
- return False
159
- try:
160
- state = json.loads(state_path.read_text(encoding="utf-8"))
161
- if state.get("kb_hash") != self._kb_hash or state.get("schema") != CACHE_SCHEMA:
162
- return False
163
- expected = self._cache_signature(faiss_dir, bm25_path)
164
- if not expected or not hmac.compare_digest(str(state.get("signature", "")), expected):
165
- logger.warning("RAG unsigned or modified cache ignored")
166
- return False
167
- cached = json.loads(bm25_path.read_text(encoding="utf-8"))
168
- if cached.get("corpus") != self.bm25_corpus or cached.get("meta") != self.bm25_meta:
169
- return False
170
- # FAISS uses pickle internally. Only load bytes authenticated with
171
- # the origin secret; never load unsigned/user-supplied index files.
172
- self.vectorstore = FAISS.load_local(
173
- str(faiss_dir), self._embeddings, allow_dangerous_deserialization=True
174
- )
175
- return True
176
- except Exception:
177
- logger.warning("RAG cache could not be loaded; rebuilding", exc_info=True)
178
- return False
179
-
180
- def _save_cached_indexes(self) -> None:
181
- if self.vectorstore is None or not get_settings().origin_token:
182
- return
183
- faiss_dir, bm25_path, state_path = self._cache_paths()
184
- faiss_dir.mkdir(parents=True, exist_ok=True)
185
- self.vectorstore.save_local(str(faiss_dir))
186
- bm25_tmp = bm25_path.with_suffix(".tmp")
187
- bm25_tmp.write_text(json.dumps({"corpus": self.bm25_corpus, "meta": self.bm25_meta}, ensure_ascii=False), encoding="utf-8")
188
- os.replace(bm25_tmp, bm25_path)
189
- state_tmp = state_path.with_suffix(".tmp")
190
- state_tmp.write_text(json.dumps({
191
- "schema": CACHE_SCHEMA, "kb_hash": self._kb_hash,
192
- "embedding_model": EMBEDDING_MODEL, "chunk_count": len(self.bm25_corpus),
193
- "signature": self._cache_signature(faiss_dir, bm25_path),
194
- }), encoding="utf-8")
195
- os.replace(state_tmp, state_path)
196
-
197
- def _load_and_chunk_all(self) -> tuple[List[str], List[dict]]:
198
- all_chunks, all_meta = [], []
199
- seen: set[str] = set()
200
- for path in sorted(self._knowledge_dir().glob("*.txt")):
201
- try:
202
- text = path.read_text(encoding="utf-8").strip()
203
- if not text:
204
- continue
205
- header, header_lines = {}, set()
206
- lines = text.splitlines()
207
- for index, line in enumerate(lines[:8]):
208
- if HEADER_RE.match(line.strip()):
209
- key, value = line.split(":", 1)
210
- header[key.strip().upper()] = value.strip()
211
- header_lines.add(index)
212
- body = "\n".join(line for index, line in enumerate(lines) if index not in header_lines)
213
- metadata = {
214
- "source": header.get("SOURCE", ""),
215
- "title": header.get("TITLE", path.stem.replace("_", " ")),
216
- "filename": path.name,
217
- "authority": header.get("AUTHORITY", "supplied_library_content"),
218
- "last_reviewed": header.get("LAST_REVIEWED", ""),
219
- "last_updated": header.get("LAST_UPDATED", ""),
220
- }
221
- for chunk in self._chunk_text(body):
222
- fingerprint = re.sub(r"\s+", " ", chunk).strip()
223
- if fingerprint in seen:
224
- continue
225
- seen.add(fingerprint)
226
- all_chunks.append(chunk)
227
- all_meta.append(dict(metadata))
228
- except Exception:
229
- logger.warning("Could not read knowledge file %s", path.name, exc_info=True)
230
- return all_chunks, all_meta
231
-
232
- def _chunk_text(self, text: str) -> List[str]:
233
- # Source files use RESOURCE 01:, all-caps headings without colons,
234
- # staff names, and === section markers. Keep each entry with its URL.
235
- sections, current = [], []
236
- for line in text.splitlines():
237
- stripped = line.strip()
238
- is_heading = bool(
239
- re.match(r"^(?:TOPIC:|RESOURCE\s+\d+:|===)", stripped)
240
- or (4 <= len(stripped) <= 100 and stripped.isupper()
241
- and any(char.isalpha() for char in stripped)
242
- and not stripped.startswith(("http", "SOURCE:", "TITLE:")))
243
- )
244
- if is_heading and current:
245
- sections.append("\n".join(current).strip())
246
- current = []
247
- current.append(line)
248
- if current:
249
- sections.append("\n".join(current).strip())
250
- chunks = []
251
- for section in sections:
252
- if len(section) < 30 or not self._tokens(section):
253
- continue
254
- words = section.split()
255
- if len(words) <= CHUNK_WORDS:
256
- chunks.append(section)
257
- continue
258
- heading = section.splitlines()[0].strip()
259
- for start in range(0, len(words), CHUNK_WORDS - CHUNK_OVERLAP_WORDS):
260
- chunk = " ".join(words[start:start + CHUNK_WORDS])
261
- if start and len(heading) < 100:
262
- chunk = heading + "\n" + chunk
263
- chunks.append(chunk)
264
- if start + CHUNK_WORDS >= len(words):
265
- break
266
- return chunks
267
-
268
- async def hybrid_search(self, query: str, top_k: int = 5, alpha: float = 0.6) -> List[dict]:
269
- if not self._ready or self.bm25 is None or not query.strip() or top_k <= 0:
270
- return []
271
- # Snapshot before awaiting dense search so an admin rebuild cannot mix
272
- # old vector document ids with a new corpus/metadata list.
273
- corpus, metadata, bm25 = self.bm25_corpus, self.bm25_meta, self.bm25
274
- vectorstore, reverse = self.vectorstore, self._content_to_idx
275
- tokens = self._tokens(query)
276
- meaningful = {token for token in tokens if token not in STOP_WORDS and len(token) > 1}
277
- if not meaningful:
278
- return []
279
- fetch_k = min(max(top_k * 3, 15), len(corpus))
280
- alpha = min(1.0, max(0.0, alpha))
281
- scores = bm25.get_scores(tokens)
282
- lexical_indices = sorted(range(len(corpus)), key=lambda idx: float(scores[idx]), reverse=True)
283
- lexical_indices = [idx for idx in lexical_indices
284
- if meaningful & set(self._tokens(corpus[idx]))][:fetch_k]
285
- dense_results = []
286
- if vectorstore is not None:
287
- try:
288
- dense_results = await asyncio.wait_for(
289
- vectorstore.asimilarity_search_with_score(query, k=fetch_k), timeout=4
290
- )
291
- except Exception:
292
- logger.warning("Semantic retrieval unavailable; using keywords", exc_info=True)
293
- rrf: dict[int, float] = {}
294
- dense_distance: dict[int, float] = {}
295
- for rank, (doc, score) in enumerate(dense_results):
296
- idx = reverse.get(doc.page_content.strip(), -1)
297
- if idx >= 0:
298
- rrf[idx] = rrf.get(idx, 0.0) + alpha / (61 + rank)
299
- try:
300
- dense_distance.setdefault(idx, float(score))
301
- except (TypeError, ValueError):
302
- pass
303
- lexical_weight = (1 - alpha) if dense_results else 1.0
304
- for rank, idx in enumerate(lexical_indices):
305
- rrf[idx] = rrf.get(idx, 0.0) + lexical_weight / (61 + rank)
306
- results = []
307
- # Filter before applying top_k: irrelevant dense hits must not crowd
308
- # relevant keyword hits out of the candidate pool.
309
- dense_only_left = DENSE_ONLY_LIMIT
310
- for idx in sorted(rrf, key=rrf.get, reverse=True):
311
- overlap = len(meaningful & set(self._tokens(corpus[idx])))
312
- if not overlap:
313
- # A paraphrased question can share no words with the passage that
314
- # answers it ("take books home" vs "borrowing"). Admit such a
315
- # passage only when the embedding match is very close, and only
316
- # a couple of them, so weak semantic hits still cannot crowd
317
- # out keyword hits.
318
- if dense_only_left <= 0 or dense_distance.get(idx, float("inf")) > DENSE_ONLY_MAX_DISTANCE:
319
- continue
320
- dense_only_left -= 1
321
- results.append({
322
- "content": corpus[idx], **metadata[idx], "score": round(rrf[idx], 6),
323
- "lexical_overlap": overlap,
324
- "retrieval_mode": "hybrid" if dense_results else "keyword",
325
- })
326
- if len(results) >= top_k:
327
- break
328
- return results
329
-
330
- def _find_corpus_index(self, content: str) -> int:
331
- return self._content_to_idx.get(content.strip(), -1)
332
-
333
- def audit_knowledge_base(self) -> dict:
334
- files = sorted(self._knowledge_dir().glob("*.txt"))
335
- titles, duplicates = {}, []
336
- for path in files:
337
- try:
338
- text = path.read_text(encoding="utf-8")[:500]
339
- title = next((line.split(":", 1)[1].strip() for line in text.splitlines() if line.startswith("TITLE:")), path.stem)
340
- if title in titles:
341
- duplicates.append({"title": title, "files": [titles[title], path.name]})
342
- else:
343
- titles[title] = path.name
344
- except OSError:
345
- continue
346
- return {"file_count": len(files), "duplicate_titles": duplicates[:20]}
347
-
348
- def get_stats(self) -> dict:
349
- return {
350
- "ready": self._ready, "status": self._status,
351
- "retrieval_mode": "hybrid" if self.vectorstore is not None else "keyword" if self._ready else "unavailable",
352
- "chunk_count": len(self.bm25_corpus), "knowledge_dir": str(self._knowledge_dir()),
353
- "vectorstore_loaded": self.vectorstore is not None, "bm25_loaded": self.bm25 is not None,
354
- "kb_hash": self._kb_hash,
355
- }
 
1
+ """Local keyword retrieval first, with an optional cached semantic index.
2
+
3
+ Initialization never needs an API key to serve the local KB. Dense failures
4
+ leave keyword search available; callers may run initialize in the background.
5
+ """
6
+ import asyncio
7
+ import hashlib
8
+ import hmac
9
+ import json
10
+ import logging
11
+ import os
12
+ import re
13
+ import time
14
+ from pathlib import Path
15
+ from typing import List
16
+
17
+ from src.config import get_settings
18
+
19
+ logger = logging.getLogger(__name__)
20
+ CHUNK_WORDS = 260
21
+ CHUNK_OVERLAP_WORDS = 40
22
+ EMBEDDING_MODEL = "text-embedding-3-small"
23
+ CACHE_SCHEMA = 2
24
+ TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*", re.UNICODE)
25
+ STOP_WORDS = {"about", "and", "are", "can", "for", "from", "how", "library", "please", "that", "the", "this", "what", "when", "where", "which", "with", "you"}
26
+ # Passages with no shared words are returned only below this FAISS distance
27
+ # (squared L2 on unit vectors: 1.0 is cosine similarity 0.5). Tune with the
28
+ # Space variable RAG_DENSE_ONLY_MAX_DISTANCE; 0 restores keyword-only filtering.
29
+ DENSE_ONLY_MAX_DISTANCE = float(os.getenv("RAG_DENSE_ONLY_MAX_DISTANCE", "1.0") or 0)
30
+ DENSE_ONLY_LIMIT = 2
31
+ HEADER_RE = re.compile(r"^(?:SOURCE|TITLE|AUTHORITY|LAST_REVIEWED|LAST_UPDATED):", re.IGNORECASE)
32
+
33
+
34
+ class RAGService:
35
+ def __init__(self):
36
+ self.vectorstore = None
37
+ self.bm25 = None
38
+ self.bm25_corpus: List[str] = []
39
+ self.bm25_meta: List[dict] = []
40
+ self._embeddings = None
41
+ self._ready = False
42
+ self._kb_hash = ""
43
+ self._status = "not_started"
44
+ self._content_to_idx: dict[str, int] = {}
45
+ self._init_lock = asyncio.Lock()
46
+
47
+ def is_ready(self) -> bool:
48
+ return self._ready
49
+
50
+ def _knowledge_dir(self) -> Path:
51
+ return get_settings().kb_dir
52
+
53
+ def _cache_dir(self) -> Path:
54
+ return get_settings().rag_cache_dir
55
+
56
+ def _hash_knowledge_base(self, txt_files: List[Path]) -> str:
57
+ # Deployments commonly reset mtimes. Hash content plus indexing settings
58
+ # so unchanged data can reuse persisted embeddings across image rebuilds.
59
+ digest = hashlib.sha256()
60
+ digest.update(f"{CACHE_SCHEMA}:{EMBEDDING_MODEL}:{CHUNK_WORDS}:{CHUNK_OVERLAP_WORDS}".encode())
61
+ for path in sorted(txt_files):
62
+ digest.update(path.name.encode("utf-8"))
63
+ digest.update(b"\0")
64
+ digest.update(path.read_bytes())
65
+ digest.update(b"\0")
66
+ return digest.hexdigest()
67
+
68
+ def _cache_paths(self) -> tuple[Path, Path, Path]:
69
+ cache_dir = self._cache_dir()
70
+ return cache_dir / "faiss_index", cache_dir / "bm25_cache.json", cache_dir / "kb_state.json"
71
+
72
+ def _cache_signature(self, faiss_dir: Path, bm25_path: Path) -> str:
73
+ key = get_settings().origin_token.encode("utf-8")
74
+ if not key:
75
+ return ""
76
+ digest = hmac.new(key, digestmod=hashlib.sha256)
77
+ for path in sorted([bm25_path, *faiss_dir.glob("*")]):
78
+ if path.is_file():
79
+ digest.update(path.name.encode("utf-8"))
80
+ digest.update(path.read_bytes())
81
+ return digest.hexdigest()
82
+
83
+ @staticmethod
84
+ def _tokens(value: str) -> List[str]:
85
+ return TOKEN_RE.findall((value or "").casefold())
86
+
87
+ def _build_reverse_index(self) -> None:
88
+ self._content_to_idx = {chunk.strip(): i for i, chunk in enumerate(self.bm25_corpus)}
89
+
90
+ def _build_keyword_index(self):
91
+ from rank_bm25 import BM25Okapi
92
+ files = sorted(self._knowledge_dir().glob("*.txt"))
93
+ kb_hash = self._hash_knowledge_base(files)
94
+ chunks, metadata = self._load_and_chunk_all()
95
+ if not chunks:
96
+ raise ValueError("No usable knowledge-base chunks found")
97
+ bm25 = BM25Okapi([self._tokens(chunk) for chunk in chunks])
98
+ return kb_hash, chunks, metadata, bm25
99
+
100
+ async def initialize(self, openai_api_key: str = "", *, force_rebuild: bool = False) -> None:
101
+ async with self._init_lock:
102
+ started = time.monotonic()
103
+ self._status = "initializing"
104
+ try:
105
+ # File reads, tokenization, and heavy imports must not block the
106
+ # event loop serving /config, health checks, and chat requests.
107
+ kb_hash, chunks, metadata, bm25 = await asyncio.to_thread(self._build_keyword_index)
108
+ self.vectorstore = None
109
+ self._embeddings = None
110
+ self._kb_hash = kb_hash
111
+ self.bm25_corpus, self.bm25_meta, self.bm25 = chunks, metadata, bm25
112
+ self._build_reverse_index()
113
+ self._ready = True
114
+ self._status = "keyword_ready"
115
+ logger.info("RAG keyword index ready: %d chunks in %.2fs", len(chunks), time.monotonic() - started)
116
+ except Exception:
117
+ self._status = ("ready" if self.vectorstore is not None else "keyword_ready") if self._ready else "failed"
118
+ logger.exception("RAG keyword initialization failed; retaining any existing index")
119
+ return
120
+
121
+ if not openai_api_key:
122
+ return
123
+ self._status = "semantic_initializing"
124
+ try:
125
+ def load_embedding_tools():
126
+ from langchain_openai import OpenAIEmbeddings
127
+ from langchain_community.vectorstores import FAISS
128
+ return OpenAIEmbeddings, FAISS
129
+ OpenAIEmbeddings, FAISS = await asyncio.to_thread(load_embedding_tools)
130
+ self._embeddings = OpenAIEmbeddings(
131
+ model=EMBEDDING_MODEL, openai_api_key=openai_api_key,
132
+ request_timeout=15, max_retries=1,
133
+ )
134
+ if not force_rebuild and await asyncio.to_thread(self._try_load_cached_indexes, FAISS):
135
+ self._status = "ready"
136
+ return
137
+ vectorstore = await asyncio.wait_for(
138
+ FAISS.afrom_texts(chunks, self._embeddings, metadatas=metadata), timeout=90
139
+ )
140
+ self.vectorstore = vectorstore
141
+ self._status = "ready"
142
+ try:
143
+ await asyncio.to_thread(self._save_cached_indexes)
144
+ except Exception:
145
+ # An unwritable cache must not disable a working index.
146
+ logger.exception("RAG cache save failed; retrieval remains available")
147
+ logger.info("RAG semantic index ready in %.2fs", time.monotonic() - started)
148
+ except asyncio.CancelledError:
149
+ self._status = "keyword_ready"
150
+ raise
151
+ except Exception:
152
+ self._status = "keyword_ready"
153
+ logger.exception("RAG semantic index unavailable; using keyword retrieval")
154
+
155
+ def _try_load_cached_indexes(self, FAISS, _BM25Okapi=None) -> bool:
156
+ faiss_dir, bm25_path, state_path = self._cache_paths()
157
+ if not (faiss_dir.exists() and bm25_path.exists() and state_path.exists()):
158
+ return False
159
+ try:
160
+ state = json.loads(state_path.read_text(encoding="utf-8"))
161
+ if state.get("kb_hash") != self._kb_hash or state.get("schema") != CACHE_SCHEMA:
162
+ return False
163
+ expected = self._cache_signature(faiss_dir, bm25_path)
164
+ if not expected or not hmac.compare_digest(str(state.get("signature", "")), expected):
165
+ logger.warning("RAG unsigned or modified cache ignored")
166
+ return False
167
+ cached = json.loads(bm25_path.read_text(encoding="utf-8"))
168
+ if cached.get("corpus") != self.bm25_corpus or cached.get("meta") != self.bm25_meta:
169
+ return False
170
+ # FAISS uses pickle internally. Only load bytes authenticated with
171
+ # the origin secret; never load unsigned/user-supplied index files.
172
+ self.vectorstore = FAISS.load_local(
173
+ str(faiss_dir), self._embeddings, allow_dangerous_deserialization=True
174
+ )
175
+ return True
176
+ except Exception:
177
+ logger.warning("RAG cache could not be loaded; rebuilding", exc_info=True)
178
+ return False
179
+
180
+ def _save_cached_indexes(self) -> None:
181
+ if self.vectorstore is None or not get_settings().origin_token:
182
+ return
183
+ faiss_dir, bm25_path, state_path = self._cache_paths()
184
+ faiss_dir.mkdir(parents=True, exist_ok=True)
185
+ self.vectorstore.save_local(str(faiss_dir))
186
+ bm25_tmp = bm25_path.with_suffix(".tmp")
187
+ bm25_tmp.write_text(json.dumps({"corpus": self.bm25_corpus, "meta": self.bm25_meta}, ensure_ascii=False), encoding="utf-8")
188
+ os.replace(bm25_tmp, bm25_path)
189
+ state_tmp = state_path.with_suffix(".tmp")
190
+ state_tmp.write_text(json.dumps({
191
+ "schema": CACHE_SCHEMA, "kb_hash": self._kb_hash,
192
+ "embedding_model": EMBEDDING_MODEL, "chunk_count": len(self.bm25_corpus),
193
+ "signature": self._cache_signature(faiss_dir, bm25_path),
194
+ }), encoding="utf-8")
195
+ os.replace(state_tmp, state_path)
196
+
197
+ def _load_and_chunk_all(self) -> tuple[List[str], List[dict]]:
198
+ all_chunks, all_meta = [], []
199
+ seen: set[str] = set()
200
+ for path in sorted(self._knowledge_dir().glob("*.txt")):
201
+ try:
202
+ text = path.read_text(encoding="utf-8").strip()
203
+ if not text:
204
+ continue
205
+ header, header_lines = {}, set()
206
+ lines = text.splitlines()
207
+ for index, line in enumerate(lines[:8]):
208
+ if HEADER_RE.match(line.strip()):
209
+ key, value = line.split(":", 1)
210
+ header[key.strip().upper()] = value.strip()
211
+ header_lines.add(index)
212
+ body = "\n".join(line for index, line in enumerate(lines) if index not in header_lines)
213
+ metadata = {
214
+ "source": header.get("SOURCE", ""),
215
+ "title": header.get("TITLE", path.stem.replace("_", " ")),
216
+ "filename": path.name,
217
+ "authority": header.get("AUTHORITY", "supplied_library_content"),
218
+ "last_reviewed": header.get("LAST_REVIEWED", ""),
219
+ "last_updated": header.get("LAST_UPDATED", ""),
220
+ }
221
+ for chunk in self._chunk_text(body):
222
+ fingerprint = re.sub(r"\s+", " ", chunk).strip()
223
+ if fingerprint in seen:
224
+ continue
225
+ seen.add(fingerprint)
226
+ all_chunks.append(chunk)
227
+ all_meta.append(dict(metadata))
228
+ except Exception:
229
+ logger.warning("Could not read knowledge file %s", path.name, exc_info=True)
230
+ return all_chunks, all_meta
231
+
232
+ def _chunk_text(self, text: str) -> List[str]:
233
+ # Source files use RESOURCE 01:, all-caps headings without colons,
234
+ # staff names, and === section markers. Keep each entry with its URL.
235
+ sections, current = [], []
236
+ for line in text.splitlines():
237
+ stripped = line.strip()
238
+ is_heading = bool(
239
+ re.match(r"^(?:TOPIC:|RESOURCE\s+\d+:|===)", stripped)
240
+ or (4 <= len(stripped) <= 100 and stripped.isupper()
241
+ and any(char.isalpha() for char in stripped)
242
+ and not stripped.startswith(("http", "SOURCE:", "TITLE:")))
243
+ )
244
+ if is_heading and current:
245
+ sections.append("\n".join(current).strip())
246
+ current = []
247
+ current.append(line)
248
+ if current:
249
+ sections.append("\n".join(current).strip())
250
+ chunks = []
251
+ for section in sections:
252
+ if len(section) < 30 or not self._tokens(section):
253
+ continue
254
+ words = section.split()
255
+ if len(words) <= CHUNK_WORDS:
256
+ chunks.append(section)
257
+ continue
258
+ heading = section.splitlines()[0].strip()
259
+ for start in range(0, len(words), CHUNK_WORDS - CHUNK_OVERLAP_WORDS):
260
+ chunk = " ".join(words[start:start + CHUNK_WORDS])
261
+ if start and len(heading) < 100:
262
+ chunk = heading + "\n" + chunk
263
+ chunks.append(chunk)
264
+ if start + CHUNK_WORDS >= len(words):
265
+ break
266
+ return chunks
267
+
268
+ async def hybrid_search(self, query: str, top_k: int = 5, alpha: float = 0.6) -> List[dict]:
269
+ if not self._ready or self.bm25 is None or not query.strip() or top_k <= 0:
270
+ return []
271
+ # Snapshot before awaiting dense search so an admin rebuild cannot mix
272
+ # old vector document ids with a new corpus/metadata list.
273
+ corpus, metadata, bm25 = self.bm25_corpus, self.bm25_meta, self.bm25
274
+ vectorstore, reverse = self.vectorstore, self._content_to_idx
275
+ tokens = self._tokens(query)
276
+ meaningful = {token for token in tokens if token not in STOP_WORDS and len(token) > 1}
277
+ if not meaningful:
278
+ return []
279
+ fetch_k = min(max(top_k * 3, 15), len(corpus))
280
+ alpha = min(1.0, max(0.0, alpha))
281
+ scores = bm25.get_scores(tokens)
282
+ lexical_indices = sorted(range(len(corpus)), key=lambda idx: float(scores[idx]), reverse=True)
283
+ lexical_indices = [idx for idx in lexical_indices
284
+ if meaningful & set(self._tokens(corpus[idx]))][:fetch_k]
285
+ dense_results = []
286
+ if vectorstore is not None:
287
+ try:
288
+ dense_results = await asyncio.wait_for(
289
+ vectorstore.asimilarity_search_with_score(query, k=fetch_k), timeout=4
290
+ )
291
+ except Exception:
292
+ logger.warning("Semantic retrieval unavailable; using keywords", exc_info=True)
293
+ rrf: dict[int, float] = {}
294
+ dense_distance: dict[int, float] = {}
295
+ for rank, (doc, score) in enumerate(dense_results):
296
+ idx = reverse.get(doc.page_content.strip(), -1)
297
+ if idx >= 0:
298
+ rrf[idx] = rrf.get(idx, 0.0) + alpha / (61 + rank)
299
+ try:
300
+ dense_distance.setdefault(idx, float(score))
301
+ except (TypeError, ValueError):
302
+ pass
303
+ lexical_weight = (1 - alpha) if dense_results else 1.0
304
+ for rank, idx in enumerate(lexical_indices):
305
+ rrf[idx] = rrf.get(idx, 0.0) + lexical_weight / (61 + rank)
306
+ results = []
307
+ # Filter before applying top_k: irrelevant dense hits must not crowd
308
+ # relevant keyword hits out of the candidate pool.
309
+ dense_only_left = DENSE_ONLY_LIMIT
310
+ for idx in sorted(rrf, key=rrf.get, reverse=True):
311
+ overlap = len(meaningful & set(self._tokens(corpus[idx])))
312
+ if not overlap:
313
+ # A paraphrased question can share no words with the passage that
314
+ # answers it ("take books home" vs "borrowing"). Admit such a
315
+ # passage only when the embedding match is very close, and only
316
+ # a couple of them, so weak semantic hits still cannot crowd
317
+ # out keyword hits.
318
+ if dense_only_left <= 0 or dense_distance.get(idx, float("inf")) > DENSE_ONLY_MAX_DISTANCE:
319
+ continue
320
+ dense_only_left -= 1
321
+ results.append({
322
+ "content": corpus[idx], **metadata[idx], "score": round(rrf[idx], 6),
323
+ "lexical_overlap": overlap,
324
+ "retrieval_mode": "hybrid" if dense_results else "keyword",
325
+ })
326
+ if len(results) >= top_k:
327
+ break
328
+ return results
329
+
330
+ def _find_corpus_index(self, content: str) -> int:
331
+ return self._content_to_idx.get(content.strip(), -1)
332
+
333
+ def audit_knowledge_base(self) -> dict:
334
+ files = sorted(self._knowledge_dir().glob("*.txt"))
335
+ titles, duplicates = {}, []
336
+ for path in files:
337
+ try:
338
+ text = path.read_text(encoding="utf-8")[:500]
339
+ title = next((line.split(":", 1)[1].strip() for line in text.splitlines() if line.startswith("TITLE:")), path.stem)
340
+ if title in titles:
341
+ duplicates.append({"title": title, "files": [titles[title], path.name]})
342
+ else:
343
+ titles[title] = path.name
344
+ except OSError:
345
+ continue
346
+ return {"file_count": len(files), "duplicate_titles": duplicates[:20]}
347
+
348
+ def get_stats(self) -> dict:
349
+ return {
350
+ "ready": self._ready, "status": self._status,
351
+ "retrieval_mode": "hybrid" if self.vectorstore is not None else "keyword" if self._ready else "unavailable",
352
+ "chunk_count": len(self.bm25_corpus), "knowledge_dir": str(self._knowledge_dir()),
353
+ "vectorstore_loaded": self.vectorstore is not None, "bm25_loaded": self.bm25 is not None,
354
+ "kb_hash": self._kb_hash,
355
+ }
src/services/runtime_store.py CHANGED
@@ -1,57 +1,57 @@
1
- """Small atomic JSON store for a single-process LibBee deployment."""
2
-
3
- import copy
4
- import json
5
- import os
6
- import tempfile
7
- import time
8
- from pathlib import Path
9
- from typing import Any, Dict, Optional
10
-
11
-
12
- class JsonRuntimeStore:
13
- def __init__(self, path: Path, default: Optional[Dict[str, Any]] = None):
14
- self.path = Path(path)
15
- self.path.parent.mkdir(parents=True, exist_ok=True)
16
- self.default = copy.deepcopy(default or {})
17
-
18
- def load(self) -> Dict[str, Any]:
19
- data = copy.deepcopy(self.default)
20
- try:
21
- loaded = json.loads(self.path.read_text(encoding="utf-8"))
22
- if isinstance(loaded, dict):
23
- data.update(loaded)
24
- except (OSError, UnicodeError, json.JSONDecodeError):
25
- pass
26
- return data
27
-
28
- def save(self, data: Dict[str, Any]) -> None:
29
- """Replace a complete object with a unique, owner-only temporary file.
30
-
31
- A shared fixed `.tmp` name allowed independent writers to overwrite or
32
- unlink each other's temporary file. Unique files prevent that race;
33
- callers still need a database for multi-process read/modify/write use.
34
- """
35
- if not isinstance(data, dict):
36
- raise TypeError("runtime data must be a JSON object")
37
- tmp = None
38
- try:
39
- with tempfile.NamedTemporaryFile(
40
- mode="w", encoding="utf-8", dir=self.path.parent,
41
- prefix=f".{self.path.name}.", suffix=".tmp", delete=False,
42
- ) as handle:
43
- tmp = Path(handle.name)
44
- json.dump(data, handle, ensure_ascii=False, indent=2, allow_nan=False)
45
- handle.flush()
46
- os.fsync(handle.fileno())
47
- os.replace(tmp, self.path)
48
- finally:
49
- if tmp is not None:
50
- tmp.unlink(missing_ok=True)
51
-
52
- def update(self, **kwargs: Any) -> Dict[str, Any]:
53
- data = self.load()
54
- data.update(kwargs)
55
- data["updated_at"] = time.time()
56
- self.save(data)
57
- return data
 
1
+ """Small atomic JSON store for a single-process LibBee deployment."""
2
+
3
+ import copy
4
+ import json
5
+ import os
6
+ import tempfile
7
+ import time
8
+ from pathlib import Path
9
+ from typing import Any, Dict, Optional
10
+
11
+
12
+ class JsonRuntimeStore:
13
+ def __init__(self, path: Path, default: Optional[Dict[str, Any]] = None):
14
+ self.path = Path(path)
15
+ self.path.parent.mkdir(parents=True, exist_ok=True)
16
+ self.default = copy.deepcopy(default or {})
17
+
18
+ def load(self) -> Dict[str, Any]:
19
+ data = copy.deepcopy(self.default)
20
+ try:
21
+ loaded = json.loads(self.path.read_text(encoding="utf-8"))
22
+ if isinstance(loaded, dict):
23
+ data.update(loaded)
24
+ except (OSError, UnicodeError, json.JSONDecodeError):
25
+ pass
26
+ return data
27
+
28
+ def save(self, data: Dict[str, Any]) -> None:
29
+ """Replace a complete object with a unique, owner-only temporary file.
30
+
31
+ A shared fixed `.tmp` name allowed independent writers to overwrite or
32
+ unlink each other's temporary file. Unique files prevent that race;
33
+ callers still need a database for multi-process read/modify/write use.
34
+ """
35
+ if not isinstance(data, dict):
36
+ raise TypeError("runtime data must be a JSON object")
37
+ tmp = None
38
+ try:
39
+ with tempfile.NamedTemporaryFile(
40
+ mode="w", encoding="utf-8", dir=self.path.parent,
41
+ prefix=f".{self.path.name}.", suffix=".tmp", delete=False,
42
+ ) as handle:
43
+ tmp = Path(handle.name)
44
+ json.dump(data, handle, ensure_ascii=False, indent=2, allow_nan=False)
45
+ handle.flush()
46
+ os.fsync(handle.fileno())
47
+ os.replace(tmp, self.path)
48
+ finally:
49
+ if tmp is not None:
50
+ tmp.unlink(missing_ok=True)
51
+
52
+ def update(self, **kwargs: Any) -> Dict[str, Any]:
53
+ data = self.load()
54
+ data.update(kwargs)
55
+ data["updated_at"] = time.time()
56
+ self.save(data)
57
+ return data
src/services/staff_service.py CHANGED
@@ -1,207 +1,207 @@
1
- """Deterministic staff matching using the supplied KU directory snapshot.
2
-
3
- Live roles and contact details still require checking against the official
4
- staff page; these helpers do not perform a live directory lookup.
5
- """
6
- import difflib
7
- import re
8
- from typing import Dict, List, Optional
9
-
10
- STAFF_DIRECTORY = [
11
- {
12
- "full_name": "Dr. Abdulla Al Hefeiti",
13
- "role": "Library Director / Assistant Provost, Libraries",
14
- "email": "abdulla.alhefeiti@ku.ac.ae",
15
- "phone": "+971 2 312 3331",
16
- "expertise": "strategic and institutional matters, library leadership, and partnerships",
17
- "tokens": ["abdulla", "hefeiti", "abdulla al hefeiti", "al hefeiti"],
18
- "aliases": ["library director", "director", "assistant provost"],
19
- },
20
- {
21
- "full_name": "Nikesh Narayanan",
22
- "role": "Research & Access Services Librarian",
23
- "email": "nikesh.narayanan@ku.ac.ae",
24
- "phone": "+971 2 312 3980",
25
- "expertise": "research support, Open Access publishing, Khazna repository, ORCID, Scopus, research impact, AI tools for research, bibliometrics, and scholarly communication",
26
- "tokens": ["nikesh", "narayanan", "nikesh narayanan"],
27
- "aliases": ["research librarian", "research support librarian"],
28
- },
29
- {
30
- "full_name": "Rani Anand",
31
- "role": "E-Resources Librarian",
32
- "email": "rani.anand@ku.ac.ae",
33
- "phone": "+971 2 312 3935",
34
- "expertise": "database access problems, e-resources troubleshooting, remote access, vendor issues, patents, e-books, and bibliometrics",
35
- "tokens": ["rani", "anand", "rani anand"],
36
- "aliases": ["e-resources librarian", "eresources librarian", "database librarian"],
37
- },
38
- {
39
- "full_name": "Jason Fetty",
40
- "role": "Medical Librarian",
41
- "email": "jason.fetty@ku.ac.ae",
42
- "phone": "+971 2 312 4722",
43
- "expertise": "medical and health sciences research, systematic reviews, PubMed, Embase, CINAHL, UpToDate, and clinical databases",
44
- "tokens": ["jason", "fetty", "jason fetty"],
45
- "aliases": ["medical librarian", "medical library", "health sciences librarian"],
46
- },
47
- {
48
- "full_name": "Walter Brian Hall",
49
- "role": "Digital & Technology Services Librarian / Systems Librarian",
50
- "email": "walter.hall@ku.ac.ae",
51
- "phone": "+971 2 312 3163",
52
- "expertise": "library website, systems, technology, digital infrastructure, ORCID, STEAM, coding, and Open Access support",
53
- "tokens": ["walter", "brian", "hall", "walter brian hall", "walter hall", "brian hall"],
54
- "aliases": ["systems librarian", "technology librarian", "digital librarian"],
55
- },
56
- {
57
- "full_name": "Alia Al-Harrasi",
58
- "role": "Manager, Technical Services",
59
- "email": "alia.alharrasi@ku.ac.ae",
60
- "phone": "+971 2 312 3180",
61
- "expertise": "cataloguing, metadata, acquisitions processing, and technical services",
62
- "tokens": ["alia", "alia al-harrasi", "alia alharrasi", "al harrasi", "alharrasi"],
63
- "aliases": ["technical services", "acquisitions processing", "cataloguing"],
64
- },
65
- {
66
- "full_name": "Zainab Al Ali",
67
- "role": "Library Information Senior Specialist (Interlibrary Loan)",
68
- "email": "zainab.alali@ku.ac.ae",
69
- "phone": "+971 2 312 4321",
70
- "expertise": "Interlibrary Loan (ILL) requests and status, document delivery, and obtaining books or articles that KU does not hold (ILL mailbox: ill@ku.ac.ae)",
71
- "tokens": ["zainab", "zainab al ali", "zainab alali", "alali"],
72
- "aliases": [
73
- "interlibrary loan", "inter library loan", "inter-library loan",
74
- "ill request", "ill requests", "document delivery",
75
- ],
76
- },
77
- ]
78
-
79
- _STOP_WORDS = {
80
- "who", "is", "are", "the", "a", "an", "can", "help", "me", "tell",
81
- "about", "find", "contact", "email", "phone", "number", "i", "need",
82
- "to", "speak", "with", "please", "get", "in", "touch", "reach", "how",
83
- "do", "what", "which", "where", "for", "of", "best", "person", "librarian",
84
- }
85
-
86
- _CONTACT_INTENT_RE = re.compile(
87
- r"\b(contact|email|phone|number|who is|who's|who handles|who can help|best person|best librarian|"
88
- r"which librarian|talk to|speak to|reach|appointment|book an appointment|schedule)",
89
- re.IGNORECASE,
90
- )
91
-
92
- _ROLE_INDEX: dict[str, Dict] = {}
93
-
94
-
95
- def build_staff_index() -> None:
96
- """Build role alias β†’ staff dict. Called once from app.py lifespan."""
97
- global _ROLE_INDEX
98
- _ROLE_INDEX = {}
99
- for staff in STAFF_DIRECTORY:
100
- for alias in [staff["full_name"], *staff.get("aliases", [])]:
101
- key = re.sub(r"[^a-z0-9]+", " ", alias.lower()).strip()
102
- _ROLE_INDEX[key] = staff
103
-
104
-
105
- def _normalize(text: str) -> List[str]:
106
- tokens = re.sub(r"[^a-z0-9 ]+", " ", (text or "").lower()).split()
107
- return [t for t in tokens if t not in _STOP_WORDS]
108
-
109
-
110
- def should_attempt_staff_lookup(question: str) -> bool:
111
- q = (question or "").strip().lower()
112
- if not q:
113
- return False
114
- if not _CONTACT_INTENT_RE.search(q):
115
- return False
116
- # Don't trigger on article/research queries that happen to contain contact words
117
- if re.search(
118
- r"\b(article|articles|paper|papers|study|studies|research article|research articles|literature)\b", q
119
- ) and not re.search(
120
- r"\b(who|contact|email|phone|which librarian|best person|who can help)\b", q
121
- ):
122
- return False
123
- return True
124
-
125
-
126
- def match_staff_name(question: str) -> Optional[Dict]:
127
- """Match alternative spellings independently, without combining aliases.
128
-
129
- A contact request can use a first name, surname or full-name alias. Common
130
- words such as "hall" cannot identify a person on their own. Ambiguous
131
- matches fall through to the KB instead of choosing the first staff entry.
132
- """
133
- if not should_attempt_staff_lookup(question):
134
- return None
135
- question_tokens = set(_normalize(question))
136
- weak = {"al", "dr", "hall", "brian"}
137
- candidates = []
138
- for staff in STAFF_DIRECTORY:
139
- strength = 0
140
- for alias in [staff["full_name"], *staff.get("tokens", [])]:
141
- tokens = set(_normalize(alias)) - {"dr"}
142
- if tokens and tokens.issubset(question_tokens):
143
- if len(tokens) >= 2 or next(iter(tokens)) not in weak:
144
- strength = max(strength, len(tokens))
145
- if strength:
146
- candidates.append(staff)
147
- if len(candidates) == 1:
148
- return candidates[0]
149
- if candidates:
150
- return None
151
- return _fuzzy_staff_match(question)
152
-
153
-
154
- def _fuzzy_staff_match(question: str) -> Optional[Dict]:
155
- """Compare probable name words with name words, not full sentences."""
156
- candidates = {}
157
- for token in _normalize(question):
158
- if len(token) < 6:
159
- continue
160
- for staff in STAFF_DIRECTORY:
161
- distinctive = {
162
- word for alias in staff.get("tokens", []) for word in _normalize(alias)
163
- if len(word) >= 6 and word not in {"librarian", "library"}
164
- }
165
- if difflib.get_close_matches(token, distinctive, n=1, cutoff=0.88):
166
- candidates[staff["email"]] = staff
167
- return next(iter(candidates.values())) if len(candidates) == 1 else None
168
-
169
-
170
- def match_staff_role(question: str) -> Optional[Dict]:
171
- """Match by role alias. Auto-builds index if empty (defensive guard)."""
172
- if not should_attempt_staff_lookup(question):
173
- return None
174
- if not _ROLE_INDEX:
175
- build_staff_index()
176
- q = re.sub(r"[^a-z0-9]+", " ", question.lower()).strip()
177
- # Longest alias first β€” prevents "librarian" matching before "medical librarian"
178
- for alias, staff in sorted(_ROLE_INDEX.items(), key=lambda item: len(item[0]), reverse=True):
179
- if len(alias) > 3 and re.search(r"(?<!\w)" + re.escape(alias) + r"(?!\w)", q):
180
- return staff
181
- return None
182
-
183
-
184
- def staff_name_answer(staff: Dict) -> str:
185
- return (
186
- f"<strong>{staff['full_name']}</strong> is the <strong>{staff['role']}</strong>.<br><br>"
187
- f"They can help with: {staff['expertise']}.<br><br>"
188
- f"πŸ“§ <a href=\"mailto:{staff['email']}\">{staff['email']}</a><br>"
189
- f"πŸ“ž <a href=\"tel:{staff['phone'].replace(' ', '')}\">{staff['phone']}</a>"
190
- '<br><br>Contact details are from the supplied directory. '
191
- '<a href="https://library.ku.ac.ae/librarystaff" target="_blank">Check the current staff directory</a>.'
192
- )
193
-
194
-
195
- def staff_role_answer(staff: Dict, question: str) -> str:
196
- return (
197
- f"For help with that, the best person to contact is <strong>{staff['full_name']}</strong> β€” "
198
- f"<strong>{staff['role']}</strong>.<br><br>"
199
- f"They can help with: {staff['expertise']}.<br><br>"
200
- f"πŸ“§ <a href=\"mailto:{staff['email']}\">{staff['email']}</a><br>"
201
- f"πŸ“ž <a href=\"tel:{staff['phone'].replace(' ', '')}\">{staff['phone']}</a>"
202
- '<br><br>Contact details are from the supplied directory. '
203
- '<a href="https://library.ku.ac.ae/librarystaff" target="_blank">Check the current staff directory</a>.'
204
- )
205
-
206
- # NOTE: build_staff_index() is NOT called here at module level.
207
- # It is called once from app.py lifespan to avoid double-build.
 
1
+ """Deterministic staff matching using the supplied KU directory snapshot.
2
+
3
+ Live roles and contact details still require checking against the official
4
+ staff page; these helpers do not perform a live directory lookup.
5
+ """
6
+ import difflib
7
+ import re
8
+ from typing import Dict, List, Optional
9
+
10
+ STAFF_DIRECTORY = [
11
+ {
12
+ "full_name": "Dr. Abdulla Al Hefeiti",
13
+ "role": "Library Director / Assistant Provost, Libraries",
14
+ "email": "abdulla.alhefeiti@ku.ac.ae",
15
+ "phone": "+971 2 312 3331",
16
+ "expertise": "strategic and institutional matters, library leadership, and partnerships",
17
+ "tokens": ["abdulla", "hefeiti", "abdulla al hefeiti", "al hefeiti"],
18
+ "aliases": ["library director", "director", "assistant provost"],
19
+ },
20
+ {
21
+ "full_name": "Nikesh Narayanan",
22
+ "role": "Research & Access Services Librarian",
23
+ "email": "nikesh.narayanan@ku.ac.ae",
24
+ "phone": "+971 2 312 3980",
25
+ "expertise": "research support, Open Access publishing, Khazna repository, ORCID, Scopus, research impact, AI tools for research, bibliometrics, and scholarly communication",
26
+ "tokens": ["nikesh", "narayanan", "nikesh narayanan"],
27
+ "aliases": ["research librarian", "research support librarian"],
28
+ },
29
+ {
30
+ "full_name": "Rani Anand",
31
+ "role": "E-Resources Librarian",
32
+ "email": "rani.anand@ku.ac.ae",
33
+ "phone": "+971 2 312 3935",
34
+ "expertise": "database access problems, e-resources troubleshooting, remote access, vendor issues, patents, e-books, and bibliometrics",
35
+ "tokens": ["rani", "anand", "rani anand"],
36
+ "aliases": ["e-resources librarian", "eresources librarian", "database librarian"],
37
+ },
38
+ {
39
+ "full_name": "Jason Fetty",
40
+ "role": "Medical Librarian",
41
+ "email": "jason.fetty@ku.ac.ae",
42
+ "phone": "+971 2 312 4722",
43
+ "expertise": "medical and health sciences research, systematic reviews, PubMed, Embase, CINAHL, UpToDate, and clinical databases",
44
+ "tokens": ["jason", "fetty", "jason fetty"],
45
+ "aliases": ["medical librarian", "medical library", "health sciences librarian"],
46
+ },
47
+ {
48
+ "full_name": "Walter Brian Hall",
49
+ "role": "Digital & Technology Services Librarian / Systems Librarian",
50
+ "email": "walter.hall@ku.ac.ae",
51
+ "phone": "+971 2 312 3163",
52
+ "expertise": "library website, systems, technology, digital infrastructure, ORCID, STEAM, coding, and Open Access support",
53
+ "tokens": ["walter", "brian", "hall", "walter brian hall", "walter hall", "brian hall"],
54
+ "aliases": ["systems librarian", "technology librarian", "digital librarian"],
55
+ },
56
+ {
57
+ "full_name": "Alia Al-Harrasi",
58
+ "role": "Manager, Technical Services",
59
+ "email": "alia.alharrasi@ku.ac.ae",
60
+ "phone": "+971 2 312 3180",
61
+ "expertise": "cataloguing, metadata, acquisitions processing, and technical services",
62
+ "tokens": ["alia", "alia al-harrasi", "alia alharrasi", "al harrasi", "alharrasi"],
63
+ "aliases": ["technical services", "acquisitions processing", "cataloguing"],
64
+ },
65
+ {
66
+ "full_name": "Zainab Al Ali",
67
+ "role": "Library Information Senior Specialist (Interlibrary Loan)",
68
+ "email": "zainab.alali@ku.ac.ae",
69
+ "phone": "+971 2 312 4321",
70
+ "expertise": "Interlibrary Loan (ILL) requests and status, document delivery, and obtaining books or articles that KU does not hold (ILL mailbox: ill@ku.ac.ae)",
71
+ "tokens": ["zainab", "zainab al ali", "zainab alali", "alali"],
72
+ "aliases": [
73
+ "interlibrary loan", "inter library loan", "inter-library loan",
74
+ "ill request", "ill requests", "document delivery",
75
+ ],
76
+ },
77
+ ]
78
+
79
+ _STOP_WORDS = {
80
+ "who", "is", "are", "the", "a", "an", "can", "help", "me", "tell",
81
+ "about", "find", "contact", "email", "phone", "number", "i", "need",
82
+ "to", "speak", "with", "please", "get", "in", "touch", "reach", "how",
83
+ "do", "what", "which", "where", "for", "of", "best", "person", "librarian",
84
+ }
85
+
86
+ _CONTACT_INTENT_RE = re.compile(
87
+ r"\b(contact|email|phone|number|who is|who's|who handles|who can help|best person|best librarian|"
88
+ r"which librarian|talk to|speak to|reach|appointment|book an appointment|schedule)",
89
+ re.IGNORECASE,
90
+ )
91
+
92
+ _ROLE_INDEX: dict[str, Dict] = {}
93
+
94
+
95
+ def build_staff_index() -> None:
96
+ """Build role alias β†’ staff dict. Called once from app.py lifespan."""
97
+ global _ROLE_INDEX
98
+ _ROLE_INDEX = {}
99
+ for staff in STAFF_DIRECTORY:
100
+ for alias in [staff["full_name"], *staff.get("aliases", [])]:
101
+ key = re.sub(r"[^a-z0-9]+", " ", alias.lower()).strip()
102
+ _ROLE_INDEX[key] = staff
103
+
104
+
105
+ def _normalize(text: str) -> List[str]:
106
+ tokens = re.sub(r"[^a-z0-9 ]+", " ", (text or "").lower()).split()
107
+ return [t for t in tokens if t not in _STOP_WORDS]
108
+
109
+
110
+ def should_attempt_staff_lookup(question: str) -> bool:
111
+ q = (question or "").strip().lower()
112
+ if not q:
113
+ return False
114
+ if not _CONTACT_INTENT_RE.search(q):
115
+ return False
116
+ # Don't trigger on article/research queries that happen to contain contact words
117
+ if re.search(
118
+ r"\b(article|articles|paper|papers|study|studies|research article|research articles|literature)\b", q
119
+ ) and not re.search(
120
+ r"\b(who|contact|email|phone|which librarian|best person|who can help)\b", q
121
+ ):
122
+ return False
123
+ return True
124
+
125
+
126
+ def match_staff_name(question: str) -> Optional[Dict]:
127
+ """Match alternative spellings independently, without combining aliases.
128
+
129
+ A contact request can use a first name, surname or full-name alias. Common
130
+ words such as "hall" cannot identify a person on their own. Ambiguous
131
+ matches fall through to the KB instead of choosing the first staff entry.
132
+ """
133
+ if not should_attempt_staff_lookup(question):
134
+ return None
135
+ question_tokens = set(_normalize(question))
136
+ weak = {"al", "dr", "hall", "brian"}
137
+ candidates = []
138
+ for staff in STAFF_DIRECTORY:
139
+ strength = 0
140
+ for alias in [staff["full_name"], *staff.get("tokens", [])]:
141
+ tokens = set(_normalize(alias)) - {"dr"}
142
+ if tokens and tokens.issubset(question_tokens):
143
+ if len(tokens) >= 2 or next(iter(tokens)) not in weak:
144
+ strength = max(strength, len(tokens))
145
+ if strength:
146
+ candidates.append(staff)
147
+ if len(candidates) == 1:
148
+ return candidates[0]
149
+ if candidates:
150
+ return None
151
+ return _fuzzy_staff_match(question)
152
+
153
+
154
+ def _fuzzy_staff_match(question: str) -> Optional[Dict]:
155
+ """Compare probable name words with name words, not full sentences."""
156
+ candidates = {}
157
+ for token in _normalize(question):
158
+ if len(token) < 6:
159
+ continue
160
+ for staff in STAFF_DIRECTORY:
161
+ distinctive = {
162
+ word for alias in staff.get("tokens", []) for word in _normalize(alias)
163
+ if len(word) >= 6 and word not in {"librarian", "library"}
164
+ }
165
+ if difflib.get_close_matches(token, distinctive, n=1, cutoff=0.88):
166
+ candidates[staff["email"]] = staff
167
+ return next(iter(candidates.values())) if len(candidates) == 1 else None
168
+
169
+
170
+ def match_staff_role(question: str) -> Optional[Dict]:
171
+ """Match by role alias. Auto-builds index if empty (defensive guard)."""
172
+ if not should_attempt_staff_lookup(question):
173
+ return None
174
+ if not _ROLE_INDEX:
175
+ build_staff_index()
176
+ q = re.sub(r"[^a-z0-9]+", " ", question.lower()).strip()
177
+ # Longest alias first β€” prevents "librarian" matching before "medical librarian"
178
+ for alias, staff in sorted(_ROLE_INDEX.items(), key=lambda item: len(item[0]), reverse=True):
179
+ if len(alias) > 3 and re.search(r"(?<!\w)" + re.escape(alias) + r"(?!\w)", q):
180
+ return staff
181
+ return None
182
+
183
+
184
+ def staff_name_answer(staff: Dict) -> str:
185
+ return (
186
+ f"<strong>{staff['full_name']}</strong> is the <strong>{staff['role']}</strong>.<br><br>"
187
+ f"They can help with: {staff['expertise']}.<br><br>"
188
+ f"πŸ“§ <a href=\"mailto:{staff['email']}\">{staff['email']}</a><br>"
189
+ f"πŸ“ž <a href=\"tel:{staff['phone'].replace(' ', '')}\">{staff['phone']}</a>"
190
+ '<br><br>Contact details are from the supplied directory. '
191
+ '<a href="https://library.ku.ac.ae/librarystaff" target="_blank">Check the current staff directory</a>.'
192
+ )
193
+
194
+
195
+ def staff_role_answer(staff: Dict, question: str) -> str:
196
+ return (
197
+ f"For help with that, the best person to contact is <strong>{staff['full_name']}</strong> β€” "
198
+ f"<strong>{staff['role']}</strong>.<br><br>"
199
+ f"They can help with: {staff['expertise']}.<br><br>"
200
+ f"πŸ“§ <a href=\"mailto:{staff['email']}\">{staff['email']}</a><br>"
201
+ f"πŸ“ž <a href=\"tel:{staff['phone'].replace(' ', '')}\">{staff['phone']}</a>"
202
+ '<br><br>Contact details are from the supplied directory. '
203
+ '<a href="https://library.ku.ac.ae/librarystaff" target="_blank">Check the current staff directory</a>.'
204
+ )
205
+
206
+ # NOTE: build_staff_index() is NOT called here at module level.
207
+ # It is called once from app.py lifespan to avoid double-build.