tbels89 commited on
Commit
bc5c1c0
·
1 Parent(s): e98bc36

updates to retriever and embeddings for testing

Browse files
preprocess_textbook.py CHANGED
@@ -21,7 +21,7 @@ def pdf_to_text(pdf_path):
21
  print(f"Warning: No text extracted from page {page_num+1}")
22
  return text
23
 
24
- def split_into_chunks(text, max_tokens=512):
25
  tokenizer = tiktoken.get_encoding('o200k_base')
26
  # Load the pre-trained Punkt tokenizer for English
27
  sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
 
21
  print(f"Warning: No text extracted from page {page_num+1}")
22
  return text
23
 
24
+ def split_into_chunks(text, max_tokens=512): #can play with max_tokens to get larger or smaller outputs
25
  tokenizer = tiktoken.get_encoding('o200k_base')
26
  # Load the pre-trained Punkt tokenizer for English
27
  sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
processed/curriculum_chunks.json ADDED
The diff for this file is too large to render. See raw diff
 
processed/metadata.json ADDED
The diff for this file is too large to render. See raw diff
 
retrieval_log.csv ADDED
The diff for this file is too large to render. See raw diff
 
retriever.py CHANGED
@@ -49,7 +49,7 @@ class Retriever:
49
 
50
  if __name__ == '__main__':
51
  retriever = Retriever()
52
- sample_query = "What was the cause of World War I?"
53
  top_k = 5
54
  results = retriever.retrieve(sample_query, k=top_k)
55
  print(f"Top {top_k} results for the query: '{sample_query}'\n")
 
49
 
50
  if __name__ == '__main__':
51
  retriever = Retriever()
52
+ sample_query = "what is the triple entente?"
53
  top_k = 5
54
  results = retriever.retrieve(sample_query, k=top_k)
55
  print(f"Top {top_k} results for the query: '{sample_query}'\n")
retriever_logger.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # retriever.py with logging included
2
+ import numpy as np
3
+ import faiss
4
+ import json
5
+ import csv
6
+ import os
7
+ from sentence_transformers import SentenceTransformer
8
+
9
+ class Retriever:
10
+ def __init__(self):
11
+ # Load the embeddings and metadata
12
+ try:
13
+ self.embeddings = np.load('processed/embeddings.npy')
14
+ with open('processed/metadata.json', 'r', encoding='utf-8') as f:
15
+ self.metadata = json.load(f)
16
+ except FileNotFoundError:
17
+ print("Embeddings and metadata not found. Please run 'build_vector_store.py' first.")
18
+ exit(1)
19
+
20
+ # Load the FAISS index
21
+ try:
22
+ self.index = faiss.read_index('processed/faiss_index.idx')
23
+ except FileNotFoundError:
24
+ print("FAISS index not found. Please run 'build_vector_store.py' first.")
25
+ exit(1)
26
+
27
+ # Initialize the sentence transformer model
28
+ model_name = 'all-mpnet-base-v2' # Ensure this matches the model used during indexing
29
+ try:
30
+ self.model = SentenceTransformer(model_name)
31
+ except Exception as e:
32
+ print(f"Error initializing SentenceTransformer model: {e}")
33
+ exit(1)
34
+
35
+ def retrieve(self, query, k=5, min_content_words=25):
36
+ # Generate embedding for the query
37
+ try:
38
+ query_embedding = self.model.encode([query]).astype('float32')
39
+ except Exception as e:
40
+ print(f"Error generating embedding for query: {e}")
41
+ # Search the FAISS index
42
+ # Retrieve more candidates to allow filtering
43
+ distances, indices = self.index.search(query_embedding, k * 2)
44
+
45
+ # Retrieve the corresponding chunks and filter out short ones
46
+ results = []
47
+ try:
48
+ for idx in indices[0]:
49
+ chunk = self.metadata[idx]
50
+ # Filter out chunks that are too short
51
+ if len(chunk['content'].split()) >= min_content_words:
52
+ results.append(chunk)
53
+ if len(results) >= k:
54
+ break
55
+ except Exception as e:
56
+ print(f"Error retrieving chunks: {e}")
57
+
58
+ # If not enough results after filtering, fill up with unfiltered chunks
59
+ if len(results) < k:
60
+ try:
61
+ for idx in indices[0]:
62
+ chunk = self.metadata[idx]
63
+ if chunk not in results:
64
+ results.append(chunk)
65
+ if len(results) >= k:
66
+ break
67
+ except Exception as e:
68
+ print(f"Error retrieving unfiltered chunks: {e}")
69
+
70
+ return results[:k]
71
+
72
+ if __name__ == '__main__':
73
+ retriever = Retriever()
74
+ top_k = 5
75
+ log_file = 'retrieval_log.csv'
76
+
77
+ # Check if log file exists
78
+ file_exists = os.path.isfile(log_file)
79
+
80
+ # Open the log file once and keep it open
81
+ try:
82
+ with open(log_file, mode='a', encoding='utf-8', newline='') as csvfile:
83
+ fieldnames = ['Query', 'Result Number', 'Page Number', 'Content']
84
+ writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
85
+
86
+ # Write header only if file did not exist before
87
+ if not file_exists:
88
+ writer.writeheader()
89
+
90
+ while True:
91
+ sample_query = input("Enter your query (or type 'quit' to exit): ")
92
+ if sample_query.lower() == 'quit':
93
+ print("Exiting the program.")
94
+ break
95
+
96
+ results = retriever.retrieve(sample_query, k=top_k)
97
+ print(f"\nTop {top_k} results for the query: '{sample_query}'\n")
98
+ for i, res in enumerate(results):
99
+ print(f"Result {i+1}:")
100
+ print(f"Page Number: {res['page_num']}")
101
+ print(f"Content: {res['content']}\n")
102
+
103
+ # Log each result
104
+ writer.writerow({
105
+ 'Query': sample_query,
106
+ 'Result Number': i + 1,
107
+ 'Page Number': res['page_num'],
108
+ 'Content': res['content']
109
+ })
110
+
111
+ print(f"Results for query '{sample_query}' logged to {log_file}\n")
112
+ except Exception as e:
113
+ print(f"Error: {e}")