Download app/dutch_chatbot/document_processor.py from bmayfield/dutch_test_assistant: direct link, hf CLI and curl.
- Browser
- Download file 3.95 kB
-
https://huggingface.co/spaces/bmayfield/dutch_test_assistant/resolve/main/app/dutch_chatbot/document_processor.py
- Command line
-
hf download hf://spaces/bmayfield/dutch_test_assistant/app/dutch_chatbot/document_processor.py
-
curl -L -o document_processor.py https://huggingface.co/spaces/bmayfield/dutch_test_assistant/resolve/main/app/dutch_chatbot/document_processor.py
3.95 kB
| 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}") | |