Download src/document_processing/index_builder.py from Estarcode/campusdesk-ai: direct link, hf CLI and curl.
- Browser
- Download file 2.34 kB
-
https://huggingface.co/Estarcode/campusdesk-ai/resolve/main/src/document_processing/index_builder.py
- Command line
-
hf download hf://Estarcode/campusdesk-ai/src/document_processing/index_builder.py
-
curl -L -o index_builder.py https://huggingface.co/Estarcode/campusdesk-ai/resolve/main/src/document_processing/index_builder.py
2.34 kB
| """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 | |