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 |
+
Pure Python BM25 / TF-IDF RAG Indexer for InfoVault data.
|
| 4 |
+
No GPU or heavy dependencies required.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import re
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
DUTCH_STOPWORDS = {
|
| 13 |
+
"de", "het", "een", "en", "van", "in", "is", "dat", "op", "te", "voor",
|
| 14 |
+
"met", "er", "als", "om", "ook", "niet", "aan", "omdat", "door", "over",
|
| 15 |
+
"bij", "of", "uit", "nog", "naar", "tot", "der", "die", "dit", "deze"
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
def tokenize(text):
|
| 19 |
+
if not text:
|
| 20 |
+
return []
|
| 21 |
+
text = text.lower()
|
| 22 |
+
words = re.findall(r'\b[a-z0-9_äöüéèêëáàåïîøâæç\-]+\b', text)
|
| 23 |
+
return [w for w in words if w not in DUTCH_STOPWORDS and len(w) > 1]
|
| 24 |
+
|
| 25 |
+
class BM25Index:
|
| 26 |
+
def __init__(self, k1=1.5, b=0.75):
|
| 27 |
+
self.k1 = k1
|
| 28 |
+
self.b = b
|
| 29 |
+
self.chunks = []
|
| 30 |
+
self.doc_tokens = []
|
| 31 |
+
self.doc_lens = []
|
| 32 |
+
self.avgdl = 0.0
|
| 33 |
+
self.df = {}
|
| 34 |
+
self.idf = {}
|
| 35 |
+
self.N = 0
|
| 36 |
+
|
| 37 |
+
def build_index(self, chunks):
|
| 38 |
+
self.chunks = chunks
|
| 39 |
+
self.N = len(chunks)
|
| 40 |
+
self.doc_tokens = []
|
| 41 |
+
self.doc_lens = []
|
| 42 |
+
self.df = {}
|
| 43 |
+
|
| 44 |
+
total_len = 0
|
| 45 |
+
for chunk in chunks:
|
| 46 |
+
# Title, tags and summary weighted higher by repetition
|
| 47 |
+
titel_text = (chunk.get("titel") or "") + " "
|
| 48 |
+
tags_text = (chunk.get("tags") or "") + " "
|
| 49 |
+
samenvatting_text = (chunk.get("samenvatting") or "") + " "
|
| 50 |
+
inhoud_text = chunk.get("ruwe_inhoud") or ""
|
| 51 |
+
|
| 52 |
+
full_text = (titel_text * 3) + (tags_text * 2) + (samenvatting_text * 2) + inhoud_text
|
| 53 |
+
tokens = tokenize(full_text)
|
| 54 |
+
|
| 55 |
+
self.doc_tokens.append(tokens)
|
| 56 |
+
doc_len = len(tokens)
|
| 57 |
+
self.doc_lens.append(doc_len)
|
| 58 |
+
total_len += doc_len
|
| 59 |
+
|
| 60 |
+
seen_terms = set(tokens)
|
| 61 |
+
for term in seen_terms:
|
| 62 |
+
self.df[term] = self.df.get(term, 0) + 1
|
| 63 |
+
|
| 64 |
+
self.avgdl = total_len / self.N if self.N > 0 else 1.0
|
| 65 |
+
|
| 66 |
+
# Precompute IDF for terms
|
| 67 |
+
for term, freq in self.df.items():
|
| 68 |
+
# Okapi BM25 IDF formula with smoothing
|
| 69 |
+
self.idf[term] = math.log((self.N - freq + 0.5) / (freq + 0.5) + 1.0)
|
| 70 |
+
|
| 71 |
+
def search(self, query, top_n=5):
|
| 72 |
+
query_tokens = tokenize(query)
|
| 73 |
+
if not query_tokens:
|
| 74 |
+
return []
|
| 75 |
+
|
| 76 |
+
scores = []
|
| 77 |
+
for i, tokens in enumerate(self.doc_tokens):
|
| 78 |
+
if not tokens:
|
| 79 |
+
scores.append((0.0, i))
|
| 80 |
+
continue
|
| 81 |
+
|
| 82 |
+
doc_len = self.doc_lens[i]
|
| 83 |
+
# Count term frequencies in this document
|
| 84 |
+
tf_dict = {}
|
| 85 |
+
for t in tokens:
|
| 86 |
+
tf_dict[t] = tf_dict.get(t, 0) + 1
|
| 87 |
+
|
| 88 |
+
doc_score = 0.0
|
| 89 |
+
for qt in query_tokens:
|
| 90 |
+
if qt in tf_dict:
|
| 91 |
+
freq = tf_dict[qt]
|
| 92 |
+
idf = self.idf.get(qt, 0.0)
|
| 93 |
+
numerator = freq * (self.k1 + 1.0)
|
| 94 |
+
denominator = freq + self.k1 * (1.0 - self.b + self.b * (doc_len / self.avgdl))
|
| 95 |
+
doc_score += idf * (numerator / denominator)
|
| 96 |
+
|
| 97 |
+
scores.append((doc_score, i))
|
| 98 |
+
|
| 99 |
+
scores.sort(key=lambda x: x[0], reverse=True)
|
| 100 |
+
|
| 101 |
+
results = []
|
| 102 |
+
for score, idx in scores[:top_n]:
|
| 103 |
+
if score <= 0.0:
|
| 104 |
+
continue
|
| 105 |
+
chunk = self.chunks[idx].copy()
|
| 106 |
+
chunk["bm25_score"] = round(score, 4)
|
| 107 |
+
chunk["bronverwijzing"] = f"[Titel: '{chunk.get('titel')}' | Record-ID: {chunk.get('id')}]"
|
| 108 |
+
results.append(chunk)
|
| 109 |
+
|
| 110 |
+
return results
|
| 111 |
+
|
| 112 |
+
_GLOBAL_INDEX = None
|
| 113 |
+
|
| 114 |
+
def get_index(jsonl_path="/app/conversations/6ab2da96a48131d332d2e28f/infovault_chunks.jsonl"):
|
| 115 |
+
global _GLOBAL_INDEX
|
| 116 |
+
if _GLOBAL_INDEX is None:
|
| 117 |
+
if not os.path.exists(jsonl_path):
|
| 118 |
+
raise FileNotFoundError(f"JSONL chunk file not found at {jsonl_path}")
|
| 119 |
+
chunks = []
|
| 120 |
+
with open(jsonl_path, "r", encoding="utf-8") as f:
|
| 121 |
+
for line in f:
|
| 122 |
+
if line.strip():
|
| 123 |
+
chunks.append(json.loads(line))
|
| 124 |
+
idx = BM25Index()
|
| 125 |
+
idx.build_index(chunks)
|
| 126 |
+
_GLOBAL_INDEX = idx
|
| 127 |
+
return _GLOBAL_INDEX
|
| 128 |
+
|
| 129 |
+
def rag_zoek(query, top_n=5, jsonl_path="/app/conversations/6ab2da96a48131d332d2e28f/infovault_chunks.jsonl"):
|
| 130 |
+
"""
|
| 131 |
+
Search RAG index for query and return top_n chunks with source attribution.
|
| 132 |
+
Returns list of top results with recordtitel and record-id.
|
| 133 |
+
"""
|
| 134 |
+
index = get_index(jsonl_path)
|
| 135 |
+
return index.search(query, top_n=top_n)
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
import sys
|
| 139 |
+
test_q = sys.argv[1] if len(sys.argv) > 1 else "STRATO OpenClaw VPS"
|
| 140 |
+
print(f"Testing rag_zoek with query: '{test_q}'\n")
|
| 141 |
+
results = rag_zoek(test_q, top_n=5)
|
| 142 |
+
for res in results:
|
| 143 |
+
print(f"Score: {res['bm25_score']}")
|
| 144 |
+
print(f"Bronverwijzing: {res['bronverwijzing']}")
|
| 145 |
+
print(f"Bron: {res['bron']}")
|
| 146 |
+
print(f"Datum: {res['datum']}")
|
| 147 |
+
print(f"Samenvatting: {res['samenvatting'][:120]}...")
|
| 148 |
+
print("-" * 60)
|