File size: 7,518 Bytes
9e015d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""
Document processing module for extracting and chunking PDF content
"""
import re
import logging
from pathlib import Path
from typing import List, Dict, Any, Tuple
from dataclasses import dataclass

import pdfplumber
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_core.documents import Document

from config import (
    PAPERS_DIR, PDF_FILES, DOCUMENT_METADATA,
    CHUNK_SIZE, CHUNK_OVERLAP
)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


@dataclass
class ProcessedDocument:
    """Data class for processed document chunks"""
    content: str
    metadata: Dict[str, Any]
    page_number: int
    chunk_id: str


class PDFProcessor:
    """Processes PDF documents into chunks for vector storage"""
    
    def __init__(self):
        self.text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=CHUNK_SIZE,
            chunk_overlap=CHUNK_OVERLAP,
            length_function=len,
            separators=["\n\n", "\n", ". ", " ", ""],
            is_separator_regex=False,
        )
    
    def extract_text_from_pdf(self, pdf_path: Path) -> List[Tuple[str, int]]:
        """
        Extract text from PDF page by page
        
        Returns:
            List of (page_text, page_number) tuples
        """
        pages = []
        try:
            with pdfplumber.open(pdf_path) as pdf:
                for i, page in enumerate(pdf.pages, start=1):
                    text = page.extract_text() or ""
                    # Clean up text
                    text = self._clean_text(text)
                    if text.strip():
                        pages.append((text, i))
            logger.info(f"Extracted {len(pages)} pages from {pdf_path.name}")
        except Exception as e:
            logger.error(f"Error extracting {pdf_path}: {e}")
        return pages
    
    def _clean_text(self, text: str) -> str:
        """Clean extracted text"""
        # Remove excessive whitespace
        text = re.sub(r'\s+', ' ', text)
        # Fix common PDF artifacts
        text = re.sub(r'(\w)- (\w)', r'\1\2', text)  # hyphenation
        # Remove page numbers and headers/footers that repeat
        text = re.sub(r'\b\d{1,3}\s*$', '', text, flags=re.MULTILINE)
        return text.strip()
    
    def _detect_section(self, chunk_text: str) -> str:
        """Detect the section of the paper a chunk belongs to"""
        text_lower = chunk_text.lower()
        
        section_patterns = {
            "abstract": r"^abstract",
            "introduction": r"\b(introduction|1\. introduction)",
            "methods": r"\b(methods?|materials and methods|2\. materials)",
            "results": r"\b(results?|3\. results)",
            "discussion": r"\b(discussion)",
            "conclusion": r"\b(conclusions?|summary)",
            "references": r"\b(references|bibliography)",
        }
        
        for section, pattern in section_patterns.items():
            if re.search(pattern, text_lower[:200]):
                return section
        return "body"
    
    def process_pdf(self, pdf_path: Path, metadata: Dict[str, Any]) -> List[Document]:
        """
        Process a single PDF into LangChain Documents
        
        Args:
            pdf_path: Path to the PDF file
            metadata: Document metadata
            
        Returns:
            List of Document objects with rich metadata
        """
        documents = []
        pages = self.extract_text_from_pdf(pdf_path)
        
        for page_text, page_num in pages:
            # Skip reference pages (they're usually not useful for RAG)
            if self._detect_section(page_text) == "references":
                continue
            
            # Split page text into chunks
            chunks = self.text_splitter.split_text(page_text)
            
            for i, chunk in enumerate(chunks):
                chunk_id = f"{pdf_path.stem}_p{page_num}_c{i}"
                
                doc = Document(
                    page_content=chunk,
                    metadata={
                        **metadata,
                        "source": pdf_path.name,
                        "page": page_num,
                        "chunk_index": i,
                        "chunk_id": chunk_id,
                        "section": self._detect_section(chunk),
                        "char_count": len(chunk),
                    }
                )
                documents.append(doc)
        
        logger.info(f"Created {len(documents)} chunks from {pdf_path.name}")
        return documents
    
    def process_all_documents(self) -> List[Document]:
        """
        Process all PDF documents in the papers directory
        
        Returns:
            List of all Document chunks
        """
        all_documents = []
        
        for pdf_filename in PDF_FILES:
            pdf_path = PAPERS_DIR / pdf_filename
            
            if not pdf_path.exists():
                logger.warning(f"PDF not found: {pdf_path}")
                continue
            
            metadata = DOCUMENT_METADATA.get(pdf_filename, {
                "title": pdf_filename,
                "source": pdf_filename,
            })
            
            documents = self.process_pdf(pdf_path, metadata)
            all_documents.extend(documents)
        
        logger.info(f"Total documents processed: {len(all_documents)}")
        return all_documents


def add_contextual_metadata(documents: List[Document]) -> List[Document]:
    """
    Enrich document chunks with contextual metadata to improve retrieval
    
    This adds:
    - Paper title to each chunk (helps with retrieval)
    - Topic tags based on content
    """
    topic_keywords = {
        "flow cytometry": ["flow cytometry", "cytometer", "FACS", "scatter"],
        "microfluidics": ["microfluidic", "microchip", "lab-on-chip", "laminar"],
        "MDS": ["myelodysplastic", "MDS", "Ogata", "IPSS", "blast"],
        "leukemia": ["leukemia", "ALL", "AML", "CLL", "CML", "lymphoblast"],
        "photonics": ["waveguide", "photonic", "laser", "beam", "optic", "SU-8"],
        "biomarkers": ["biomarker", "CD45", "CD34", "CD117", "antigen"],
        "immunoassay": ["immunoassay", "antibody", "agglutination", "IgM", "IgG"],
        "COVID": ["SARS-CoV-2", "COVID", "coronavirus", "spike protein"],
        "beam shaping": ["bowtie", "beam waist", "FWHM", "excitation"],
        "point-of-care": ["point-of-care", "POC", "portable", "LOD", "detection limit"],
    }
    
    for doc in documents:
        content_lower = doc.page_content.lower()
        
        # Detect relevant topics in this chunk
        detected_topics = []
        for topic, keywords in topic_keywords.items():
            if any(kw.lower() in content_lower for kw in keywords):
                detected_topics.append(topic)
        
        doc.metadata["detected_topics"] = ", ".join(detected_topics)
        
        # Prepend title context for better retrieval
        title_prefix = f"[{doc.metadata.get('title', 'Document')}] "
        doc.page_content = title_prefix + doc.page_content
    
    return documents


if __name__ == "__main__":
    processor = PDFProcessor()
    docs = processor.process_all_documents()
    docs = add_contextual_metadata(docs)
    print(f"Processed {len(docs)} document chunks")
    for doc in docs[:3]:
        print(f"\n--- Chunk from {doc.metadata['source']} (p.{doc.metadata['page']}) ---")
        print(doc.page_content[:300])