File size: 3,947 Bytes
a40563f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c40af6d
a40563f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c40af6d
a40563f
 
 
 
 
 
 
 
 
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import fitz #PyMuPDF
import os
import json
from pathlib import Path
import logging
from .config import Config


logging.basicConfig(level=getattr(logging, Config.LOG_LEVEL))
logger = logging.getLogger(__name__)


class DocumentProcessor:
    def __init__(self):
        self.config = Config()

    def extract_text_from_pdf(self, pdf_path: str) -> str:
        """Extract text from a PDF file."""
        try:
            doc = fitz.open(pdf_path)
            text = ""

            for page_num in range(doc.page_count):
                page = doc.load_page(page_num)
                text += page.get_text("text")
                text += "\n" # Add a page break
            
            doc.close()
            return text.strip()
        except Exception as e:
            logger.error(f"Error extracting text from {pdf_path}: {e}")
            return ""
    
    def chunk_text(self, text: str, chunk_size: int = None, overlap: int = None) -> list[str]:
        """Split text into overlapping chunks."""

        chunk_size = chunk_size or self.config.CHUNK_SIZE
        overlap = overlap or self.config.CHUNK_OVERLAP

        words = text.split() #TODO Reevaluate this approach later 
        chunks = []

        for i in range(0, len(words), chunk_size - overlap):
            chunk = " ".join(words[i:i + chunk_size])
            if chunk.strip(): # only want to add non-empty chunks 
                chunks.append(chunk.strip())
        
        return chunks
    
    def process_pdf(self, pdf_path: str) -> list[dict]:
        """Process a single PDF into chunks with metadata."""
        filename = os.path.basename(pdf_path)
        logger.info(f"Processing {filename}...") 

        # Extract text 
        text = self.extract_text_from_pdf(pdf_path)
        if not text:
            logger.warning(f"No text extracted from {filename}")
            return []
        
        # Create Chunks
        chunks = self.chunk_text(text)


        # Create chunk objects with metabdata 
        processed_chunks = []
        for i, chunk in enumerate(chunks):
            chunk_data = {
                "id": f"{filename}_{i}",
                "text": chunk,
                "metadata": {
                    "source": filename,
                    "chunk_index": i,
                    "total_chunks": len(chunks),
                    "source_path": pdf_path
                }
            }
            processed_chunks.append(chunk_data)
        
        logger.info(f"Created {len(processed_chunks)} chunks from {filename}")
        return processed_chunks
    
    def process_all_pdfs(self, pdf_directory: str = None) -> list[dict]:
        """Process all PDFs in the specified directory"""
        pdf_dir = pdf_directory or self.config.PDF_DATA_PATH

        if not os.path.exists(pdf_dir):
            logger.error(f"PDF directory not found: {pdf_dir}")
            return []
        
        all_chunks = []
        pdf_files = [f for f in os.listdir(pdf_dir) if f.lower().endswith('.pdf')]
        if not pdf_files:
            logger.warning(f"No PDF files found in {pdf_dir}")
            return []
        
        for pdf_file in pdf_files:
            pdf_path = os.path.join(pdf_dir, pdf_file)
            chunks = self.process_pdf(pdf_path)
            all_chunks.extend(chunks)
        
        logger.info(f"Total chunks created: {len(all_chunks)}")
        return all_chunks
    

    def save_processed_chunks(self, chunks: list[dict], output_path: str = None):
        """Save processes chunks to JSON file"""
        if not output_path:
            os.makedirs(self.config.PROCESSED_DATA_PATH, exist_ok=True)
            output_path = os.path.join(self.config.PROCESSED_DATA_PATH, "processed_chunks.json")
        
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(chunks, f, indent=2, ensure_ascii=False)

        logger.info(f"Saved {len(chunks)} chunks to {output_path}")