File size: 2,809 Bytes
bc88160 | 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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | """
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]
|