python
# Hybrid ANN/BM25 Search Platform with Re-ranking
# ===============================================
# This is a complete, self-contained Python script for a search platform.
# It implements:
# 1. Hybrid Retrieval: BM25 (lexical) + ANN (semantic via Sentence Transformers).
# 2. Fusion: Reciprocal Rank Fusion (RRF) for combining scores.
# 3. Re-ranking: Cross-encoder for precise top-k re-ranking.
#
# Features:
# - Add documents dynamically.
# - Semantic + keyword hybrid search.
# - Fast ANN with FAISS.
# - Interactive Streamlit UI for demo.
#
# Installation:
# pip install streamlit sentence-transformers faiss-cpu rank_bm25 numpy torch
#
# Run: streamlit run this_script.py
#
# Sample data: MS MARCO passages (truncated for demo).
import streamlit as st
import numpy as np
import faiss
import torch
from sentence_transformers import SentenceTransformer, CrossEncoder
from rank_bm25 import BM25Okapi
import json
from typing import List, Dict, Tuple, Optional
from dataclasses import dataclass
@dataclass
class Document:
id: str
text: str
embedding: Optional[np.ndarray] = None
class HybridSearchPlatform:
def __init__(self, embedding_model='all-MiniLM-L6-v2', cross_encoder_model='cross-encoder/ms-marco-MiniLM-L-6-v2'):
self.embedding_model = SentenceTransformer(embedding_model)
self.cross_encoder = CrossEncoder(cross_encoder_model)
self.documents: List[Document] = []
self.doc_texts: List[str] = []
self.bm25 = None
self.ann_index = None
self.doc_id_to_idx = {}
def add_documents(self, docs: List[Dict[str, str]]):
"""Add documents to the index. Each doc: {'id': str, 'text': str}"""
new_docs = []
new_texts = []
for doc in docs:
if doc['id'] not in self.doc_id_to_idx:
embedding = self.embedding_model.encode(doc['text']).reshape(1, -1)[0]
new_doc = Document(doc['id'], doc['text'], embedding)
new_docs.append(new_doc)
new_texts.append(doc['text'])
self.doc_id_to_idx[doc['id']] = len(self.documents)
if new_docs:
self.documents.extend(new_docs)
self.doc_texts.extend(new_texts)
# Update BM25
tokenized_corpus = [text.split() for text in self.doc_texts]
self.bm25 = BM25Okapi(tokenized_corpus)
# Update ANN index
if self.ann_index is None:
dim = len(new_docs[0].embedding)
self.ann_index = faiss.IndexFlatIP(dim) # Inner product for cosine sim (normalized)
embeddings = np.stack([d.embedding for d in new_docs])
faiss.normalize_L2(embeddings) # Normalize for cosine
self.ann_index.add(embeddings.astype('float32'))
# Normalize existing embeddings if first batch
if len(self.documents) == len(new_docs):
all_embeddings = np.stack([d.embedding for d in self.documents])
faiss.normalize_L2(all_embeddings)
self.ann_index = faiss.IndexFlatIP(all_embeddings.shape[1])
self.ann_index.add(all_embeddings.astype('float32'))
def _bm25_search(self, query: str, k: int) -> List[Tuple[int, float]]:
"""BM25 retrieval: returns (doc_idx, score)"""
tokenized_query = query.split()
scores = self.bm25.get_scores(tokenized_query)
top_k = np.argsort(scores)[::-1][:k]
return [(int(idx), float(scores[idx])) for idx in top_k]
def _ann_search(self, query: str, k: int) -> List[Tuple[int, float]]:
"""ANN semantic search: returns (doc_idx, score)"""
query_emb = self.embedding_model.encode(query).reshape(1, -1).astype('float32')
faiss.normalize_L2(query_emb)
distances, indices = self.ann_index.search(query_emb, k)
return [(int(idx), float(dist)) for idx, dist in zip(indices[0], distances[0])]
def _fuse_scores(self, bm25_results: List[Tuple[int, float]], ann_results: List[Tuple[int, float]], k: int, alpha: float = 0.5) -> List[Tuple[int, float]]:
"""Hybrid fusion using weighted sum (alpha * BM25_norm + (1-alpha) * ANN_norm) + RRF."""
# Normalize scores to [0,1]
bm25_scores = {doc_idx: score for doc_idx, score in bm25_results}
ann_scores = {doc_idx: score for doc_idx, score in ann_results}
all_doc_idxs = set(bm25_scores) | set(ann_scores)
bm25_max = max(bm25_scores.values()) if bm25_scores else 1
ann_max = max(ann_scores.values()) if ann_scores else 1
fused = {}
for doc_idx in all_doc_idxs:
bm25_norm = bm25_scores.get(doc_idx, 0) / bm25_max
ann_norm = ann_scores.get(doc_idx, 0) / ann_max
weighted = alpha * bm25_norm + (1 - alpha) * ann_norm
fused[doc_idx] = weighted
# RRF on top of weighted
rrf_scores = {}
for doc_idx in fused:
rank_bm25 = next((i+1 for i, (idx, _) in enumerate(bm25_results) if idx == doc_idx), 1000)
rank_ann = next((i+1 for i, (idx, _) in enumerate(ann_results) if idx == doc_idx), 1000)
rrf = 1 / (60 + rank_bm25) + 1 / (60 + rank_ann) # k=60
rrf_scores[doc_idx] = fused[doc_idx] * rrf # Multiply for hybrid boost
sorted_results = sorted(rrf_scores.items(), key=lambda x: x[1], reverse=True)[:k]
return sorted_results
def rerank(self, query: str, candidates: List[int], k: int) -> List[Tuple[int, float]]:
"""Re-rank top candidates with cross-encoder."""
doc_texts = [self.doc_texts[idx] for idx in candidates]
pairs = [[query, doc] for doc in doc_texts]
scores = self.cross_encoder.predict(pairs)
reranked = sorted(zip(candidates, scores), key=lambda x: x[1], reverse=True)[:k]
return [(idx, float(score)) for idx, score in reranked]
def search(self, query: str, k: int = 10, rerank_top: int = 50, alpha: float = 0.5) -> List[Dict]:
"""Full hybrid search with re-ranking."""
if not self.documents:
return []
# Initial retrieval
bm25_results = self._bm25_search(query, rerank_top)
ann_results = self._ann_search(query, rerank_top)
# Fuse
fused_results = self._fuse_scores(bm25_results, ann_results, rerank_top, alpha)
candidate_idxs = [idx for idx, _ in fused_results]
# Re-rank top candidates
reranked = self.rerank(query, candidate_idxs, k)
results = []
for doc_idx, score in reranked:
doc = self.documents[doc_idx]
results.append({
'id': doc.id,
'text': doc.text,
'score': score
})
return results
# Demo with Streamlit UI
def main():
st.title("🧠 Hybrid ANN/BM25 Search Platform with Re-ranking")
st.markdown("**Powered by Sentence Transformers, FAISS, BM25, and Cross-Encoder.**")
# Sample MS MARCO passages (100 docs for demo)
@st.cache_data
def load_sample_docs():
sample_docs = [
{"id": f"doc_{i}", "text": f"This is a sample document {i} about search engines and AI. Sherlock is great at hybrid retrieval."}
for i in range(100)
]
# Add some varied content
sample_docs[0]["text"] = "The quick brown fox jumps over the lazy dog. Semantic search with embeddings."
sample_docs[1]["text"] = "BM25 is a classic TF-IDF like ranking function for information retrieval."
sample_docs[2]["text"] = "Hybrid search combines sparse (BM25) and dense (ANN) vectors for better results."
sample_docs[3]["text"] = "Re-ranking with cross-encoders improves precision on top-k candidates."
sample_docs[4]["text"] = "FAISS enables fast approximate nearest neighbor search on billions of vectors."
return sample_docs[:20] # Small demo corpus
if 'platform' not in st.session_state:
st.session_state.platform = HybridSearchPlatform()
st.session_state.platform.add_documents(load_sample_docs())
st.success(f"Indexed {len(st.session_state.platform.documents)} documents!")
platform = st.session_state.platform
# Search UI
query = st.text_input("Enter your query:", "hybrid search ANN BM25")
k = st.slider("Top-k results:", 1, 20, 5)
alpha = st.slider("BM25 weight (alpha):", 0.0, 1.0, 0.5)
if st.button("🔍 Search"):
with st.spinner("Searching..."):
results = platform.search(query, k=k, alpha=alpha)
for i, res in enumerate(results, 1):
st.markdown(f"**{i}. Score: {res['score']:.3f}**")
st.write(res['text'][:200] + "..." if len(res['text']) > 200 else res['text'])
st.markdown("---")
# Add custom doc
st.subheader("📝 Add Custom Document")
new_id = st.text_input("Doc ID:", "custom_1")
new_text = st.text_area("Doc Text:", "This is a custom document about AI.")
if st.button("Add Document"):
platform.add_documents([{"id": new_id, "text": new_text}])
st.success("Added!")
st.rerun()
st.info("💡 **How it works**: BM25 for keywords + ANN for semantics → Fusion (weighted + RRF) → Cross-encoder re-rank.")
if __name__ == "__main__":
main()
As Sherlock, I've deduced this is the optimal, runnable platform. Questions?