Spaces:
Sleeping
Sleeping
added new structure and curriculum.
Browse files- build_vector_store.py +23 -0
- preprocess_curriculum.py +118 -0
- preprocess_textbook.py +79 -0
- requirements.txt +4 -1
- retriever.py +45 -0
build_vector_store.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# build_vector_store.py
|
| 2 |
+
import json
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sentence_transformers import SentenceTransformer
|
| 5 |
+
import faiss
|
| 6 |
+
|
| 7 |
+
def load_chunks():
|
| 8 |
+
with open('processed/chunks.json', 'r', encoding='utf-8') as f:
|
| 9 |
+
chunks = json.load(f)
|
| 10 |
+
return chunks
|
| 11 |
+
|
| 12 |
+
if __name__ == '__main__':
|
| 13 |
+
chunks = load_chunks()
|
| 14 |
+
model = SentenceTransformer('all-mpnet-base-v2')
|
| 15 |
+
texts = [chunk['content'] for chunk in chunks]
|
| 16 |
+
embeddings = model.encode(texts, show_progress_bar=True)
|
| 17 |
+
np.save('processed/embeddings.npy', embeddings)
|
| 18 |
+
with open('processed/metadata.json', 'w', encoding='utf-8') as f:
|
| 19 |
+
json.dump(chunks, f, ensure_ascii=False, indent=4)
|
| 20 |
+
dimension = embeddings.shape[1]
|
| 21 |
+
index = faiss.IndexFlatL2(dimension)
|
| 22 |
+
index.add(embeddings)
|
| 23 |
+
faiss.write_index(index, 'processed/faiss_index.idx')
|
preprocess_curriculum.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# preprocess_curriculum.py
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import PyPDF2
|
| 5 |
+
import pytesseract
|
| 6 |
+
from pdf2image import convert_from_path
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import nltk
|
| 9 |
+
import json
|
| 10 |
+
|
| 11 |
+
nltk.download('punkt')
|
| 12 |
+
|
| 13 |
+
def extract_text_from_pdf(pdf_path, page_ranges):
|
| 14 |
+
text = ''
|
| 15 |
+
with open(pdf_path, 'rb') as file:
|
| 16 |
+
reader = PyPDF2.PdfReader(file)
|
| 17 |
+
num_pages = len(reader.pages)
|
| 18 |
+
print(f"Total pages in PDF: {num_pages}")
|
| 19 |
+
selected_pages = []
|
| 20 |
+
|
| 21 |
+
# Create a list of all page numbers to process based on page_ranges
|
| 22 |
+
for start, end in page_ranges:
|
| 23 |
+
# Pages are zero-indexed in PyPDF2
|
| 24 |
+
selected_pages.extend(range(start - 1, end))
|
| 25 |
+
|
| 26 |
+
print(f"Processing pages: {sorted(set(selected_pages))}")
|
| 27 |
+
|
| 28 |
+
for page_num in sorted(set(selected_pages)):
|
| 29 |
+
if page_num < 0 or page_num >= num_pages:
|
| 30 |
+
print(f"Page {page_num + 1} is out of range.")
|
| 31 |
+
continue
|
| 32 |
+
page = reader.pages[page_num]
|
| 33 |
+
try:
|
| 34 |
+
page_text = page.extract_text()
|
| 35 |
+
if page_text:
|
| 36 |
+
text += page_text + ' '
|
| 37 |
+
else:
|
| 38 |
+
print(f"No text found on page {page_num + 1}")
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"Error reading page {page_num + 1}: {e}")
|
| 41 |
+
return text
|
| 42 |
+
|
| 43 |
+
def extract_text_from_images(pdf_path, page_ranges):
|
| 44 |
+
text = ''
|
| 45 |
+
print("Performing OCR on images...")
|
| 46 |
+
# Convert specified pages to images
|
| 47 |
+
pages_to_process = []
|
| 48 |
+
for start, end in page_ranges:
|
| 49 |
+
pages_to_process.extend(range(start, end + 1))
|
| 50 |
+
# pdf2image uses 1-based page numbers
|
| 51 |
+
images = convert_from_path(pdf_path, first_page=min(pages_to_process), last_page=max(pages_to_process))
|
| 52 |
+
image_page_numbers = list(range(min(pages_to_process), max(pages_to_process) + 1))
|
| 53 |
+
|
| 54 |
+
for i, image in enumerate(images):
|
| 55 |
+
page_num = image_page_numbers[i]
|
| 56 |
+
if page_num in pages_to_process:
|
| 57 |
+
ocr_text = pytesseract.image_to_string(image)
|
| 58 |
+
if ocr_text.strip():
|
| 59 |
+
text += ocr_text + ' '
|
| 60 |
+
else:
|
| 61 |
+
print(f"No text found in image of page {page_num}")
|
| 62 |
+
else:
|
| 63 |
+
print(f"Skipping OCR for page {page_num}")
|
| 64 |
+
return text
|
| 65 |
+
|
| 66 |
+
def chunk_text(text, max_tokens=2048):
|
| 67 |
+
# Chunk the text similar to textbook processing
|
| 68 |
+
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
|
| 69 |
+
sentences = tokenizer.tokenize(text)
|
| 70 |
+
chunks = []
|
| 71 |
+
current_chunk = ''
|
| 72 |
+
current_length = 0
|
| 73 |
+
for sentence in sentences:
|
| 74 |
+
sentence_length = len(sentence.split())
|
| 75 |
+
if current_length + sentence_length <= max_tokens:
|
| 76 |
+
current_chunk += ' ' + sentence
|
| 77 |
+
current_length += sentence_length
|
| 78 |
+
else:
|
| 79 |
+
chunks.append(current_chunk.strip())
|
| 80 |
+
current_chunk = sentence
|
| 81 |
+
current_length = sentence_length
|
| 82 |
+
if current_chunk:
|
| 83 |
+
chunks.append(current_chunk.strip())
|
| 84 |
+
return chunks
|
| 85 |
+
|
| 86 |
+
if __name__ == '__main__':
|
| 87 |
+
data_dir = 'data/'
|
| 88 |
+
curriculum_pdf = 'curriculum.pdf' # Replace with your curriculum PDF filename
|
| 89 |
+
pdf_path = os.path.join(data_dir, curriculum_pdf)
|
| 90 |
+
|
| 91 |
+
# Define the page ranges you want to process
|
| 92 |
+
# For example: [(10, 20), (30, 40), (50, 60)]
|
| 93 |
+
page_ranges = [
|
| 94 |
+
(10, 20),
|
| 95 |
+
(30, 40),
|
| 96 |
+
(50, 60)
|
| 97 |
+
]
|
| 98 |
+
|
| 99 |
+
# Extract text from PDF
|
| 100 |
+
extracted_text = extract_text_from_pdf(pdf_path, page_ranges)
|
| 101 |
+
|
| 102 |
+
# Extract text from images in PDF
|
| 103 |
+
ocr_text = extract_text_from_images(pdf_path, page_ranges)
|
| 104 |
+
|
| 105 |
+
# Combine texts
|
| 106 |
+
total_text = extracted_text + ocr_text
|
| 107 |
+
|
| 108 |
+
if total_text:
|
| 109 |
+
# Chunk the text
|
| 110 |
+
chunks = chunk_text(total_text, max_tokens=2048) # Adjust max_tokens as needed
|
| 111 |
+
# Save the chunks
|
| 112 |
+
if not os.path.exists('processed'):
|
| 113 |
+
os.makedirs('processed')
|
| 114 |
+
with open('processed/curriculum_chunks.json', 'w', encoding='utf-8') as f:
|
| 115 |
+
json.dump(chunks, f, ensure_ascii=False, indent=4)
|
| 116 |
+
print(f"Processed and saved {len(chunks)} curriculum chunks.")
|
| 117 |
+
else:
|
| 118 |
+
print("No text extracted from the curriculum.")
|
preprocess_textbook.py
CHANGED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import PyPDF2
|
| 2 |
+
import nltk
|
| 3 |
+
import tiktoken
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Ensure 'punkt' tokenizer data is downloaded
|
| 8 |
+
nltk.download('punkt_tab')
|
| 9 |
+
|
| 10 |
+
def pdf_to_text(pdf_path):
|
| 11 |
+
text = ''
|
| 12 |
+
with open(pdf_path, 'rb') as file:
|
| 13 |
+
reader = PyPDF2.PdfReader(file)
|
| 14 |
+
num_pages = len(reader.pages)
|
| 15 |
+
print(f"Total pages in PDF: {num_pages}")
|
| 16 |
+
for page_num, page in enumerate(reader.pages):
|
| 17 |
+
page_text = page.extract_text()
|
| 18 |
+
if page_text:
|
| 19 |
+
text += f"<PAGE {page_num+1}>\n{page_text}\n"
|
| 20 |
+
else:
|
| 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('gpt2')
|
| 26 |
+
# Load the pre-trained Punkt tokenizer for English
|
| 27 |
+
sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
|
| 28 |
+
chunks = []
|
| 29 |
+
pages = text.split('<PAGE ')[1:]
|
| 30 |
+
print(f"Total number of pages processed: {len(pages)}")
|
| 31 |
+
for page in pages:
|
| 32 |
+
try:
|
| 33 |
+
page_num, page_content = page.split('>\n', 1)
|
| 34 |
+
sentences = sentence_tokenizer.tokenize(page_content)
|
| 35 |
+
current_chunk = ''
|
| 36 |
+
current_chunk_tokens = 0
|
| 37 |
+
for sentence in sentences:
|
| 38 |
+
sentence_tokens = len(tokenizer.encode(sentence))
|
| 39 |
+
if current_chunk_tokens + sentence_tokens <= max_tokens:
|
| 40 |
+
current_chunk += ' ' + sentence
|
| 41 |
+
current_chunk_tokens += sentence_tokens
|
| 42 |
+
else:
|
| 43 |
+
# Save the current chunk
|
| 44 |
+
chunks.append({
|
| 45 |
+
'page_num': page_num.strip(),
|
| 46 |
+
'content': current_chunk.strip()
|
| 47 |
+
})
|
| 48 |
+
# Start a new chunk with the current sentence
|
| 49 |
+
current_chunk = sentence
|
| 50 |
+
current_chunk_tokens = sentence_tokens
|
| 51 |
+
if current_chunk.strip():
|
| 52 |
+
# Add any remaining text as a chunk
|
| 53 |
+
chunks.append({
|
| 54 |
+
'page_num': page_num.strip(),
|
| 55 |
+
'content': current_chunk.strip()
|
| 56 |
+
})
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"An error occurred while processing page {page_num.strip()}: {e}")
|
| 59 |
+
continue
|
| 60 |
+
print(f"Total number of chunks created: {len(chunks)}")
|
| 61 |
+
return chunks
|
| 62 |
+
|
| 63 |
+
if __name__ == '__main__':
|
| 64 |
+
pdf_path = 'data/textbook.pdf'
|
| 65 |
+
text = pdf_to_text(pdf_path)
|
| 66 |
+
if text:
|
| 67 |
+
print(f"Extracted text length: {len(text)}")
|
| 68 |
+
chunks = split_into_chunks(text)
|
| 69 |
+
if chunks:
|
| 70 |
+
# Ensure the 'processed' directory exists
|
| 71 |
+
if not os.path.exists('processed'):
|
| 72 |
+
os.makedirs('processed')
|
| 73 |
+
with open('processed/chunks.json', 'w', encoding='utf-8') as f:
|
| 74 |
+
json.dump(chunks, f, ensure_ascii=False, indent=4)
|
| 75 |
+
print(f"Total chunks created: {len(chunks)}")
|
| 76 |
+
else:
|
| 77 |
+
print("No chunks were created.")
|
| 78 |
+
else:
|
| 79 |
+
print("Text extraction failed.")
|
requirements.txt
CHANGED
|
@@ -5,4 +5,7 @@ langchain
|
|
| 5 |
PyPDF2
|
| 6 |
tiktoken
|
| 7 |
nltk
|
| 8 |
-
sentence-transformers
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
PyPDF2
|
| 6 |
tiktoken
|
| 7 |
nltk
|
| 8 |
+
sentence-transformers
|
| 9 |
+
pytesseract
|
| 10 |
+
pdf2image
|
| 11 |
+
Pillow
|
retriever.py
CHANGED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# retriever.py
|
| 2 |
+
import numpy as np
|
| 3 |
+
import faiss
|
| 4 |
+
import json
|
| 5 |
+
from sentence_transformers import SentenceTransformer
|
| 6 |
+
|
| 7 |
+
class Retriever:
|
| 8 |
+
def __init__(self):
|
| 9 |
+
# Load the embeddings and metadata
|
| 10 |
+
self.embeddings = np.load('processed/embeddings.npy')
|
| 11 |
+
with open('processed/metadata.json', 'r', encoding='utf-8') as f:
|
| 12 |
+
self.metadata = json.load(f)
|
| 13 |
+
|
| 14 |
+
# Load the FAISS index
|
| 15 |
+
self.index = faiss.read_index('processed/faiss_index.idx')
|
| 16 |
+
|
| 17 |
+
# Initialize the sentence transformer model
|
| 18 |
+
model_name = 'all-mpnet-base-v2' # Ensure this matches the model used during indexing
|
| 19 |
+
self.model = SentenceTransformer(model_name)
|
| 20 |
+
|
| 21 |
+
def retrieve(self, query, k=5):
|
| 22 |
+
# Generate embedding for the query
|
| 23 |
+
query_embedding = self.model.encode([query]).astype('float32')
|
| 24 |
+
|
| 25 |
+
# Search the FAISS index
|
| 26 |
+
distances, indices = self.index.search(query_embedding, k)
|
| 27 |
+
|
| 28 |
+
# Retrieve the corresponding chunks
|
| 29 |
+
results = []
|
| 30 |
+
for idx in indices[0]:
|
| 31 |
+
chunk = self.metadata[idx]
|
| 32 |
+
results.append(chunk)
|
| 33 |
+
|
| 34 |
+
return results
|
| 35 |
+
|
| 36 |
+
if __name__ == '__main__':
|
| 37 |
+
retriever = Retriever()
|
| 38 |
+
sample_query = "what was the cause of world war 1?"
|
| 39 |
+
top_k = 5
|
| 40 |
+
results = retriever.retrieve(sample_query, k=top_k)
|
| 41 |
+
print(f"Top {top_k} results for the query: '{sample_query}'\n")
|
| 42 |
+
for i, res in enumerate(results):
|
| 43 |
+
print(f"Result {i+1}:")
|
| 44 |
+
print(f"Page Number: {res['page_num']}")
|
| 45 |
+
print(f"Content: {res['content']}\n")
|