File size: 2,338 Bytes
2ab2b76 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | """Build and persist dense embedding and BM25 retrieval indexes from processed passages."""
import json
from pathlib import Path
from typing import List
from src.config import (
BM25_INDEX_PATH,
EMBEDDING_MODEL_ID,
EMBEDDINGS_INDEX_PATH,
PASSAGES_PATH,
SOURCE_MANIFEST_PATH,
)
from src.document_processing.chunker import build_passages_from_sources, load_passages
from src.retrieval.bm25 import tokenize_with_expansion
from src.retrieval.semantic import SemanticIndex, format_passage_for_search
from src.schemas import PassageRecord
def rebuild_all_indexes(
manifest_path: Path = SOURCE_MANIFEST_PATH,
passages_path: Path = PASSAGES_PATH,
embeddings_path: Path = EMBEDDINGS_INDEX_PATH,
bm25_path: Path = BM25_INDEX_PATH,
embedding_model_id: str = EMBEDDING_MODEL_ID,
) -> List[PassageRecord]:
"""Reparse raw notices -> save passages.jsonl -> rebuild dense & BM25 index files."""
passages = build_passages_from_sources(manifest_path=manifest_path, output_path=passages_path)
SemanticIndex(
passages=passages,
index_path=embeddings_path,
model_id=embedding_model_id,
rebuild=True,
)
bm25_payload = [
{
"passage_id": p.passage_id,
"tokens": tokenize_with_expansion(format_passage_for_search(p)),
}
for p in passages
]
bm25_path.parent.mkdir(parents=True, exist_ok=True)
bm25_path.write_text(json.dumps(bm25_payload, indent=2), encoding="utf-8")
return passages
def ensure_indexes_built() -> List[PassageRecord]:
"""Ensure processed passages and indexes exist without overwriting valid cached ones."""
if not PASSAGES_PATH.exists():
return rebuild_all_indexes()
passages = load_passages(PASSAGES_PATH)
if not EMBEDDINGS_INDEX_PATH.exists() or not BM25_INDEX_PATH.exists():
SemanticIndex(passages=passages, index_path=EMBEDDINGS_INDEX_PATH, rebuild=True)
bm25_payload = [
{
"passage_id": p.passage_id,
"tokens": tokenize_with_expansion(format_passage_for_search(p)),
}
for p in passages
]
BM25_INDEX_PATH.parent.mkdir(parents=True, exist_ok=True)
BM25_INDEX_PATH.write_text(json.dumps(bm25_payload, indent=2), encoding="utf-8")
return passages
|