""" Document Loader Module ====================== Handles parsing and chunking of uploaded PDF and DOCX files. Supports: PDF, DOCX, TXT, CSV """ import os from typing import List import PyPDF2 import docx class DocumentLoader: """Handles parsing and chunking of uploaded documents.""" def __init__(self, chunk_size: int = 500, chunk_overlap: int = 50): self.chunk_size = chunk_size self.chunk_overlap = chunk_overlap def process_file(self, file_path: str, filename: str) -> List[str]: """Reads a file and returns overlapping text chunks.""" text = "" ext = os.path.splitext(filename)[1].lower() try: if ext == '.pdf': text = self._read_pdf(file_path) elif ext == '.docx': text = self._read_docx(file_path) elif ext in ['.txt', '.csv', '.json']: with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: text = f.read() else: raise ValueError(f"Unsupported file format: {ext}. Supported: PDF, DOCX, TXT") except Exception as e: raise RuntimeError(f"Failed to read file {filename}: {str(e)}") text = " ".join(text.split()) if not text.strip(): raise ValueError(f"No text could be extracted from {filename}") return self._chunk_text(text) def _read_pdf(self, file_path: str) -> str: """Extract text from PDF files.""" text = "" with open(file_path, 'rb') as f: reader = PyPDF2.PdfReader(f) for page in reader.pages: extracted = page.extract_text() if extracted: text += extracted + " " return text def _read_docx(self, file_path: str) -> str: """Extract text from DOCX files.""" doc = docx.Document(file_path) paragraphs = [] for para in doc.paragraphs: if para.text.strip(): paragraphs.append(para.text) # Also extract text from tables for table in doc.tables: for row in table.rows: row_text = " | ".join(cell.text.strip() for cell in row.cells if cell.text.strip()) if row_text: paragraphs.append(row_text) return "\n".join(paragraphs) def _chunk_text(self, text: str) -> List[str]: """Split text into overlapping chunks by word count.""" words = text.split() chunks = [] step = max(1, self.chunk_size - self.chunk_overlap) for i in range(0, len(words), step): chunk = " ".join(words[i: i + self.chunk_size]) if chunk.strip(): chunks.append(chunk) return chunks if chunks else [text]