cognitive-ai-tutor / backend /document_processor.py
codedawakening's picture
Create backend/document_processor.py
7e933f7 verified
Raw History Blame Contribute Delete
2.73 kB
import os
from typing import List, Dict, Any
from langchain.text_splitter import RecursiveCharacterTextSplitter
import fitz # PyMuPDF
class DocumentProcessor:
def __init__(self, chunk_size=1000, chunk_overlap=200):
self.text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
length_function=len,
separators=["\n\n", "\n", " ", ""]
)
def load_pdf(self, file_path: str) -> List[Dict]:
"""Load and extract text from PDF"""
try:
documents = []
with fitz.open(file_path) as pdf_document:
for page_num in range(len(pdf_document)):
page = pdf_document.load_page(page_num)
text = page.get_text()
if text.strip():
metadata = {
"source": os.path.basename(file_path),
"page": page_num + 1,
"total_pages": len(pdf_document)
}
documents.append({
"content": text,
"metadata": metadata
})
# Chunk documents
return self._chunk_documents(documents)
except Exception as e:
print(f"Error loading PDF {file_path}: {e}")
# Return empty documents on error
return [{
"content": f"Error processing {os.path.basename(file_path)}",
"metadata": {"error": str(e)}
}]
def load_txt(self, file_path: str) -> List[Dict]:
"""Load text file"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read()
return [{
"content": text,
"metadata": {"source": os.path.basename(file_path)}
}]
except Exception as e:
print(f"Error loading text file {file_path}: {e}")
return []
def _chunk_documents(self, documents: List[Dict]) -> List[Dict]:
"""Split documents into chunks"""
chunks = []
for doc in documents:
text_chunks = self.text_splitter.split_text(doc["content"])
for i, chunk in enumerate(text_chunks):
chunks.append({
"content": chunk,
"metadata": {
**doc["metadata"],
"chunk": i + 1,
"total_chunks": len(text_chunks)
}
})
return chunks