File size: 2,732 Bytes
7e933f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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