File size: 1,084 Bytes
d5c3185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from PyPDF2 import PdfReader
from langchain.text_splitter import RecursiveCharacterTextSplitter

def extract_text_from_pdf(pdf_path):
    """Extract text from PDF with page numbers."""
    reader = PdfReader(pdf_path)
    text_with_pages = []
    
    for page_num, page in enumerate(reader.pages, start=1):
        text = page.extract_text()
        text_with_pages.append({
            "page": page_num,
            "content": text
        })
    
    return text_with_pages

def chunk_documents(text_with_pages, chunk_size=1000, chunk_overlap=200):
    """Split text into chunks while preserving page numbers."""
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=chunk_size,
        chunk_overlap=chunk_overlap,
        length_function=len
    )
    
    chunks = []
    for page_data in text_with_pages:
        page_chunks = text_splitter.split_text(page_data["content"])
        for chunk in page_chunks:
            chunks.append({
                "content": chunk,
                "page": page_data["page"]
            })
    
    return chunks