File size: 2,614 Bytes
cd1ab8c
 
 
 
 
f80362a
 
cd1ab8c
f80362a
cd1ab8c
 
 
 
 
 
 
 
 
 
 
 
 
 
f80362a
cd1ab8c
 
 
 
e77b7e0
 
cd1ab8c
e77b7e0
cd1ab8c
 
 
e77b7e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd1ab8c
f80362a
 
 
 
 
 
 
 
 
 
 
2540499
 
cd1ab8c
 
bc5c1c0
cd1ab8c
 
 
 
 
 
 
2540499
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
66
67
68
69
70
71
72
73
74
75
76
# 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
@st.cache_resource
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")
"""