Spaces:
Sleeping
Sleeping
updated preprocessing steps for consistency and correct model
Browse files- preprocess_curriculum.py +56 -35
- preprocess_textbook.py +3 -1
- retriever.py +21 -7
preprocess_curriculum.py
CHANGED
|
@@ -1,11 +1,10 @@
|
|
| 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_tab')
|
|
@@ -23,9 +22,10 @@ def extract_text_from_pdf(pdf_path, page_ranges):
|
|
| 23 |
# Pages are zero-indexed in PyPDF2
|
| 24 |
selected_pages.extend(range(start - 1, end))
|
| 25 |
|
| 26 |
-
|
|
|
|
| 27 |
|
| 28 |
-
for page_num in
|
| 29 |
if page_num < 0 or page_num >= num_pages:
|
| 30 |
print(f"Page {page_num + 1} is out of range.")
|
| 31 |
continue
|
|
@@ -33,54 +33,73 @@ def extract_text_from_pdf(pdf_path, page_ranges):
|
|
| 33 |
try:
|
| 34 |
page_text = page.extract_text()
|
| 35 |
if page_text:
|
| 36 |
-
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 |
-
|
| 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 |
-
|
|
|
|
| 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 +=
|
| 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
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
sentences = tokenizer.tokenize(text)
|
| 70 |
chunks = []
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
for
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
return chunks
|
| 85 |
|
| 86 |
if __name__ == '__main__':
|
|
@@ -89,7 +108,6 @@ if __name__ == '__main__':
|
|
| 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 |
(3, 59),
|
| 95 |
(103, 148),
|
|
@@ -106,13 +124,16 @@ if __name__ == '__main__':
|
|
| 106 |
total_text = extracted_text + ocr_text
|
| 107 |
|
| 108 |
if total_text:
|
| 109 |
-
#
|
| 110 |
-
chunks =
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
os.
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
| 117 |
else:
|
| 118 |
print("No text extracted from the curriculum.")
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import PyPDF2
|
| 3 |
import pytesseract
|
| 4 |
from pdf2image import convert_from_path
|
| 5 |
from PIL import Image
|
| 6 |
import nltk
|
| 7 |
+
import tiktoken
|
| 8 |
import json
|
| 9 |
|
| 10 |
nltk.download('punkt_tab')
|
|
|
|
| 22 |
# Pages are zero-indexed in PyPDF2
|
| 23 |
selected_pages.extend(range(start - 1, end))
|
| 24 |
|
| 25 |
+
selected_pages = sorted(set(selected_pages))
|
| 26 |
+
print(f"Processing pages: {selected_pages}")
|
| 27 |
|
| 28 |
+
for page_num in 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
|
|
|
|
| 33 |
try:
|
| 34 |
page_text = page.extract_text()
|
| 35 |
if page_text:
|
| 36 |
+
text += f"<PAGE {page_num+1}>\n{page_text}\n"
|
| 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 |
pages_to_process = []
|
| 47 |
for start, end in page_ranges:
|
| 48 |
pages_to_process.extend(range(start, end + 1))
|
| 49 |
+
print(f"Converting pages {start} to {end} to images...")
|
| 50 |
+
pages_to_process = sorted(set(pages_to_process))
|
| 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 |
+
print(f"Total number of pages processed: {len(image_page_numbers)}")
|
| 54 |
|
| 55 |
for i, image in enumerate(images):
|
| 56 |
page_num = image_page_numbers[i]
|
| 57 |
if page_num in pages_to_process:
|
| 58 |
ocr_text = pytesseract.image_to_string(image)
|
| 59 |
if ocr_text.strip():
|
| 60 |
+
text += f"<PAGE {page_num}>\n{ocr_text}\n"
|
| 61 |
else:
|
| 62 |
print(f"No text found in image of page {page_num}")
|
| 63 |
else:
|
| 64 |
print(f"Skipping OCR for page {page_num}")
|
| 65 |
return text
|
| 66 |
|
| 67 |
+
def split_into_chunks(text, max_tokens=512):
|
| 68 |
+
tokenizer = tiktoken.get_encoding('o200k_base')
|
| 69 |
+
sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
|
|
|
|
| 70 |
chunks = []
|
| 71 |
+
pages = text.split('<PAGE ')[1:]
|
| 72 |
+
print(f"Total number of pages processed: {len(pages)}")
|
| 73 |
+
for page in pages:
|
| 74 |
+
try:
|
| 75 |
+
page_num, page_content = page.split('>\n', 1)
|
| 76 |
+
sentences = sentence_tokenizer.tokenize(page_content)
|
| 77 |
+
current_chunk = ''
|
| 78 |
+
current_chunk_tokens = 0
|
| 79 |
+
for sentence in sentences:
|
| 80 |
+
sentence_tokens = len(tokenizer.encode(sentence))
|
| 81 |
+
if current_chunk_tokens + sentence_tokens <= max_tokens:
|
| 82 |
+
current_chunk += ' ' + sentence
|
| 83 |
+
current_chunk_tokens += sentence_tokens
|
| 84 |
+
else:
|
| 85 |
+
# Save the current chunk
|
| 86 |
+
chunks.append({
|
| 87 |
+
'page_num': page_num.strip(),
|
| 88 |
+
'content': current_chunk.strip()
|
| 89 |
+
})
|
| 90 |
+
# Start a new chunk with the current sentence
|
| 91 |
+
current_chunk = sentence
|
| 92 |
+
current_chunk_tokens = sentence_tokens
|
| 93 |
+
if current_chunk.strip():
|
| 94 |
+
# Add any remaining text as a chunk
|
| 95 |
+
chunks.append({
|
| 96 |
+
'page_num': page_num.strip(),
|
| 97 |
+
'content': current_chunk.strip()
|
| 98 |
+
})
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"An error occurred while processing page {page_num.strip()}: {e}")
|
| 101 |
+
continue
|
| 102 |
+
print(f"Total number of chunks created: {len(chunks)}")
|
| 103 |
return chunks
|
| 104 |
|
| 105 |
if __name__ == '__main__':
|
|
|
|
| 108 |
pdf_path = os.path.join(data_dir, curriculum_pdf)
|
| 109 |
|
| 110 |
# Define the page ranges you want to process
|
|
|
|
| 111 |
page_ranges = [
|
| 112 |
(3, 59),
|
| 113 |
(103, 148),
|
|
|
|
| 124 |
total_text = extracted_text + ocr_text
|
| 125 |
|
| 126 |
if total_text:
|
| 127 |
+
# Split into chunks
|
| 128 |
+
chunks = split_into_chunks(total_text, max_tokens=512)
|
| 129 |
+
if chunks:
|
| 130 |
+
# Ensure the 'processed' directory exists
|
| 131 |
+
if not os.path.exists('processed'):
|
| 132 |
+
os.makedirs('processed')
|
| 133 |
+
with open('processed/curriculum_chunks.json', 'w', encoding='utf-8') as f:
|
| 134 |
+
json.dump(chunks, f, ensure_ascii=False, indent=4)
|
| 135 |
+
print(f"Processed and saved {len(chunks)} curriculum chunks.")
|
| 136 |
+
else:
|
| 137 |
+
print("No chunks were created.")
|
| 138 |
else:
|
| 139 |
print("No text extracted from the curriculum.")
|
preprocess_textbook.py
CHANGED
|
@@ -22,7 +22,7 @@ def pdf_to_text(pdf_path):
|
|
| 22 |
return text
|
| 23 |
|
| 24 |
def split_into_chunks(text, max_tokens=512):
|
| 25 |
-
tokenizer = tiktoken.get_encoding('
|
| 26 |
# Load the pre-trained Punkt tokenizer for English
|
| 27 |
sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
|
| 28 |
chunks = []
|
|
@@ -36,6 +36,8 @@ def split_into_chunks(text, max_tokens=512):
|
|
| 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
|
|
|
|
| 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')
|
| 28 |
chunks = []
|
|
|
|
| 36 |
current_chunk_tokens = 0
|
| 37 |
for sentence in sentences:
|
| 38 |
sentence_tokens = len(tokenizer.encode(sentence))
|
| 39 |
+
print(f"Sentence tokens length: {len(sentence_tokens)}")
|
| 40 |
+
print(f"sentence tokens: {sentence_tokens}")
|
| 41 |
if current_chunk_tokens + sentence_tokens <= max_tokens:
|
| 42 |
current_chunk += ' ' + sentence
|
| 43 |
current_chunk_tokens += sentence_tokens
|
retriever.py
CHANGED
|
@@ -18,24 +18,38 @@ class Retriever:
|
|
| 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 |
-
|
|
|
|
| 27 |
|
| 28 |
-
# Retrieve the corresponding chunks
|
| 29 |
results = []
|
| 30 |
for idx in indices[0]:
|
| 31 |
chunk = self.metadata[idx]
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
if __name__ == '__main__':
|
| 37 |
retriever = Retriever()
|
| 38 |
-
sample_query = "
|
| 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")
|
|
|
|
| 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, min_content_words=25):
|
| 22 |
# Generate embedding for the query
|
| 23 |
query_embedding = self.model.encode([query]).astype('float32')
|
| 24 |
|
| 25 |
# Search the FAISS index
|
| 26 |
+
# Retrieve more candidates to allow filtering
|
| 27 |
+
distances, indices = self.index.search(query_embedding, k * 2)
|
| 28 |
|
| 29 |
+
# Retrieve the corresponding chunks and filter out short ones
|
| 30 |
results = []
|
| 31 |
for idx in indices[0]:
|
| 32 |
chunk = self.metadata[idx]
|
| 33 |
+
# Filter out chunks that are too short
|
| 34 |
+
if len(chunk['content'].split()) >= min_content_words:
|
| 35 |
+
results.append(chunk)
|
| 36 |
+
if len(results) >= k:
|
| 37 |
+
break
|
| 38 |
+
|
| 39 |
+
# If not enough results after filtering, fill up with unfiltered chunks
|
| 40 |
+
if len(results) < k:
|
| 41 |
+
for idx in indices[0]:
|
| 42 |
+
chunk = self.metadata[idx]
|
| 43 |
+
if chunk not in results:
|
| 44 |
+
results.append(chunk)
|
| 45 |
+
if len(results) >= k:
|
| 46 |
+
break
|
| 47 |
+
|
| 48 |
+
return results[:k]
|
| 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")
|