#!/usr/bin/env python3 """ Build a standalone BM25 index from chunks + the prebuilt vocabulary. Output: a pickle containing the BM25 state (token IDs, IDF, doc lengths, posting list) keyed by chunk id. Load it back with `pickle.load` in any retriever. This is for users who want plain BM25 *without* Qdrant. If you're going to use Qdrant hybrid search, `load_qdrant.py` already does sparse encoding from the same vocab.json and pushes sparse vectors into Qdrant. Usage: python load_bm25.py \ --vocab ./data/knowledge_base/bm25/vocab.json \ --chunks ./data/knowledge_base/rag_exports/cve_chunks.json \ --out ./data/knowledge_base/bm25/index.pkl """ from __future__ import annotations import argparse import json import logging import math import pickle import re import sys from collections import Counter from pathlib import Path from typing import Dict, List, Tuple logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") log = logging.getLogger("load_bm25") K1 = 1.5 B = 0.75 TOKEN_RE = re.compile(r"[a-z0-9][a-z0-9_-]*", re.IGNORECASE) def tokenize(text: str) -> List[str]: return [t.lower() for t in TOKEN_RE.findall(text or "")] def main() -> int: p = argparse.ArgumentParser(description=__doc__) p.add_argument("--vocab", required=True, type=Path) p.add_argument("--chunks", required=True, type=Path, help="Path to a *_chunks.json. Pass multiple via --chunks repeatedly.", action="append") p.add_argument("--out", required=True, type=Path) args = p.parse_args() log.info(f"Loading vocab from {args.vocab}") with args.vocab.open("r", encoding="utf-8") as f: vocab_raw = json.load(f) # vocab.json schema: {token: {"id": int, "df": int, "idf": float}} token_to_id: Dict[str, int] = {t: int(v["id"]) for t, v in vocab_raw.items()} idf: Dict[int, float] = {int(v["id"]): float(v["idf"]) for v in vocab_raw.values()} log.info(f" vocab size: {len(token_to_id):,}") # Pass 1: stream all chunks, compute term frequencies + lengths all_chunks: List[str] = [] chunk_paths = [Path(c) for c in args.chunks] for path in chunk_paths: if not path.exists(): log.warning(f"{path} missing, skipping") continue all_chunks.append(str(path)) log.info("Scanning chunks…") doc_ids: List[str] = [] doc_lens: List[int] = [] postings: Dict[int, List[Tuple[int, int]]] = {} # tid -> [(doc_idx, tf), …] for src in all_chunks: with open(src, "r", encoding="utf-8") as f: chunks = json.load(f) log.info(f" {src}: {len(chunks):,} chunks") for ch in chunks: doc_idx = len(doc_ids) doc_ids.append(ch["id"]) tokens = tokenize(ch.get("text", "")) doc_lens.append(len(tokens)) tf = Counter(tokens) for tok, count in tf.items(): tid = token_to_id.get(tok) if tid is None: continue postings.setdefault(tid, []).append((doc_idx, count)) avgdl = sum(doc_lens) / max(1, len(doc_lens)) log.info(f"Indexed {len(doc_ids):,} documents | avgdl={avgdl:.1f} | " f"postings for {len(postings):,} tokens") state = { "k1": K1, "b": B, "avgdl": avgdl, "token_to_id": token_to_id, "idf": idf, "doc_ids": doc_ids, "doc_lens": doc_lens, "postings": postings, } args.out.parent.mkdir(parents=True, exist_ok=True) with args.out.open("wb") as f: pickle.dump(state, f, protocol=pickle.HIGHEST_PROTOCOL) log.info(f"Wrote {args.out} ({args.out.stat().st_size/1024/1024:.1f} MB)") # Quick sanity query query = "log4j remote code execution" log.info(f"Sanity query: {query!r}") q_tokens = [token_to_id[t] for t in tokenize(query) if t in token_to_id] scores: Dict[int, float] = {} for tid in q_tokens: for doc_idx, tf in postings.get(tid, []): dl = doc_lens[doc_idx] num = tf * (K1 + 1) den = tf + K1 * (1 - B + B * dl / avgdl) scores[doc_idx] = scores.get(doc_idx, 0.0) + idf[tid] * num / den top = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:5] for idx, score in top: log.info(f" {doc_ids[idx]:<40s} {score:.3f}") return 0 if __name__ == "__main__": sys.exit(main())