""" 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])