"""Independent FTS5/BM25 and E5 candidates over witnessed source assertions. The checkpoint is an evidence store, not an alternative to text retrieval. Named finite scopes are expanded after ranking so a bounded candidate list cannot silently remove an assignment goal or one side of a comparison. """ from functools import lru_cache import base64 import sqlite3 import threading import zlib from tools.answers.context_policy import normalized _lock = threading.RLock() @lru_cache(maxsize=2) def lexical_index(version, texts): connection = sqlite3.connect(':memory:', check_same_thread=False) connection.execute('CREATE VIRTUAL TABLE evidence USING fts5(id UNINDEXED, text, tokenize="unicode61 remove_diacritics 2")') connection.executemany('INSERT INTO evidence VALUES (?,?)',texts) return connection RERANK_DEPTH = 60 _lemma_memo = {} def _unit_lemmas(index, data_dir): """Lemma strings of all units, read from the disk cache once per checkpoint.""" from tools.retrieval import lemmatize key=(index['version'],str(data_dir)) with _lock: if key not in _lemma_memo: _lemma_memo.clear() _lemma_memo[key]=lemmatize.LemmaCache(lemmatize.cache_path(data_dir)).many([r['text'] for r in index['units']]) return _lemma_memo[key] def retrieve_units(question, index, spec, *, limit=5, data_dir=None): from tools.knowledge.query import _terms from tools.knowledge.evidence import claim_eligible from tools.answers.question_intent import discovery_topic search_question=discovery_topic(question) if spec.intent=='discovery' else question people={p.name for p in spec.people if p.role=='student'} similar=spec.intent=='similar' def in_scope(row): if not spec.matches_evidence(row):return False if spec.period and spec.period.field!='work_year': value=row.get(spec.period.field) if not value or not spec.period.start<=value<=spec.period.end:return False return similar or not people or row['person'] in people candidates=[r for r in index['units'] if in_scope(r)] eligible={r['id'] for r in candidates} from tools.retrieval import lemmatize, rerank # Lemmas extend the indexed text ("chatbotom" also matches "chatbot"). lemma_on=lemmatize.available() lemma_strings=_unit_lemmas(index,data_dir) if lemma_on else ['']*len(index['units']) texts=tuple((r['id'],r['text']+' '+' '.join(r.get('concepts',[]))+' '+l) for r,l in zip(index['units'],lemma_strings)) connection=lexical_index((index['version'],lemma_on),texts) terms=_terms(search_question) if lemma_on and not similar: mapped=lemmatize.lemma_map(search_question) terms=terms|{mapped[t] for t in terms if t in mapped and len(mapped[t])>=3} if similar: # The reference's actual substantive topics seed the peer search. from tools.knowledge.concepts import substantive_concept terms={normalized(c) for r in candidates if r['person'] in people and claim_eligible(r) for c in r.get('concepts',[]) if substantive_concept(c)} or terms expression=' OR '.join('"'+term.replace('"','""')+'"*' for term in sorted(terms)) with _lock: lexical=[r[0] for r in connection.execute( 'SELECT id FROM evidence WHERE evidence MATCH ? ORDER BY bm25(evidence),id', (expression,)) if r[0] in eligible] if expression else [] semantic={} if index.get('vectors'): import numpy as np from tools.rag.embedding_utils import embed_query,model_profile,embedding_model_name if model_profile(embedding_model_name())['fingerprint']!=index['embedding_fingerprint']: raise RuntimeError('Content embeddings belong to another model') matrix=np.frombuffer(zlib.decompress(base64.b64decode(index['vectors'])),dtype='len(rows)}