OPERA / load_example.py
Ameame1002's picture
Add OPERA 1.78M BGE-M3 retrieval corpus (index + meta + README)
06f4afc verified
"""
Minimal end-to-end retrieval example for the OPERA retrieval corpus.
Loads opera_corpus.index + opera_corpus.meta, encodes a query with
BGE-M3, and prints the top-5 documents.
Requirements:
pip install faiss-cpu FlagEmbedding numpy
# (or faiss-gpu if you have a CUDA build that matches your stack)
"""
from __future__ import annotations
import pickle
from pathlib import Path
import faiss
import numpy as np
from FlagEmbedding import BGEM3FlagModel
HERE = Path(__file__).resolve().parent
INDEX_PATH = HERE / "opera_corpus.index"
META_PATH = HERE / "opera_corpus.meta"
BGE_MODEL = "BAAI/bge-m3"
def main(query: str = "Who directed the film The Big Short?", top_k: int = 5) -> None:
print(f"loading FAISS index from {INDEX_PATH}")
index = faiss.read_index(str(INDEX_PATH))
print(f"loading metadata from {META_PATH}")
with open(META_PATH, "rb") as f:
meta = pickle.load(f)
assert index.ntotal == len(meta), (
f"count mismatch: index={index.ntotal} meta={len(meta)}"
)
print(f"corpus size: {index.ntotal}")
print(f"loading BGE-M3 ({BGE_MODEL})")
model = BGEM3FlagModel(BGE_MODEL, use_fp16=True)
print(f"encoding query: {query!r}")
encoded = model.encode([query], return_dense=True, return_sparse=False, return_colbert_vecs=False)
vec = np.asarray(encoded["dense_vecs"], dtype="float32")
vec /= np.linalg.norm(vec, axis=1, keepdims=True) + 1e-12
print(f"searching top-{top_k}")
scores, indices = index.search(vec, top_k)
for rank, (idx, score) in enumerate(zip(indices[0], scores[0]), start=1):
rec = meta[int(idx)]
snippet = rec["content"][:200].replace("\n", " ")
print(f" #{rank} score={score:.4f} {rec['title']!r}")
print(f" {snippet}")
if __name__ == "__main__":
main()