Spaces:
Sleeping
Sleeping
Download retriever.py from tbels89/Prometheus: direct link, hf CLI and curl.
- Browser
- Download file 2.61 kB
-
https://huggingface.co/spaces/tbels89/Prometheus/resolve/main/retriever.py
- Command line
-
hf download hf://spaces/tbels89/Prometheus/retriever.py
-
curl -L -o retriever.py https://huggingface.co/spaces/tbels89/Prometheus/resolve/main/retriever.py
2.61 kB
| # retriever.py | |
| import numpy as np | |
| import faiss | |
| import json | |
| from sentence_transformers import SentenceTransformer | |
| import streamlit as st | |
| from logging_config import logger | |
| TOP_K = 3 # number of chunks to retrieve for sources sidebar | |
| class Retriever: | |
| def __init__(self): | |
| # Load the embeddings and metadata | |
| self.embeddings = np.load('processed/embeddings.npy') | |
| with open('processed/metadata.json', 'r', encoding='utf-8') as f: | |
| self.metadata = json.load(f) | |
| # Load the FAISS index | |
| self.index = faiss.read_index('processed/faiss_index.idx') | |
| # Initialize the sentence transformer model | |
| model_name = 'all-mpnet-base-v2' # Ensure this matches the model used during indexing | |
| self.model = SentenceTransformer(model_name) | |
| def retrieve(self, query, k=TOP_K, min_content_words=25): | |
| # Generate embedding for the query | |
| query_embedding = self.model.encode([query]).astype('float32') | |
| # Search the FAISS index | |
| # Retrieve more candidates to allow filtering | |
| distances, indices = self.index.search(query_embedding, k * 2) | |
| # Retrieve the corresponding chunks and filter out short ones | |
| results = [] | |
| for idx in indices[0]: | |
| chunk = self.metadata[idx] | |
| # Filter out chunks that are too short | |
| if len(chunk['content'].split()) >= min_content_words: | |
| results.append(chunk) | |
| if len(results) >= k: | |
| break | |
| # If not enough results after filtering, fill up with unfiltered chunks | |
| if len(results) < k: | |
| for idx in indices[0]: | |
| chunk = self.metadata[idx] | |
| if chunk not in results: | |
| results.append(chunk) | |
| if len(results) >= k: | |
| break | |
| return results[:k] | |
| # Retrieval for streamlit | |
| def load_retriever(): | |
| try: | |
| retriever = Retriever() | |
| logger.info("Retriever initialized successfully.") | |
| return retriever | |
| except Exception as e: | |
| logger.error(f"Failed to initialize Retriever: {e}") | |
| return None | |
| """ | |
| #for testing - removed for prod | |
| if __name__ == '__main__': | |
| retriever = Retriever() | |
| sample_query = "what is the triple entente?" | |
| top_k = 5 | |
| results = retriever.retrieve(sample_query, k=top_k) | |
| print(f"Top {top_k} results for the query: '{sample_query}'\n") | |
| for i, res in enumerate(results): | |
| print(f"Result {i+1}:") | |
| print(f"Page Number: {res['page_num']}") | |
| print(f"Content: {res['content']}\n") | |
| """ |