|
| 1 | +import base64 |
| 2 | +import io |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import re |
| 6 | +from dataclasses import dataclass, field |
| 7 | +from typing import Any, Dict, List, Tuple |
| 8 | + |
| 9 | +from PIL import Image |
| 10 | + |
| 11 | +from ...type import DocumentMetadata, FileDescriptor, MultimodalSample |
| 12 | +from .base import Processor, ProcessorConfig |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | +# Env var that selects the PDF backend. When set to "mistral", MistralOCRProcessor |
| 17 | +# accepts .pdf files and the default PDFProcessor steps aside. |
| 18 | +PDF_BACKEND_ENV = "MMORE_PDF_BACKEND" |
| 19 | +MISTRAL_BACKEND = "mistral" |
| 20 | + |
| 21 | +IMG_REGEX = r"!\[[^\]]*\]\([^)]+\)" |
| 22 | + |
| 23 | + |
| 24 | +@dataclass |
| 25 | +class MistralOCRMetadata(DocumentMetadata): |
| 26 | + paragraph_starts: List[Tuple[int, int, int]] = field(default_factory=list) |
| 27 | + backend: str = "mistral-ocr" |
| 28 | + model: str = "mistral-ocr-latest" |
| 29 | + |
| 30 | + def to_dict(self) -> Dict[str, Any]: |
| 31 | + metadata = super().to_dict() |
| 32 | + if self.paragraph_starts: |
| 33 | + metadata["paragraph_starts"] = self.paragraph_starts |
| 34 | + metadata["backend"] = self.backend |
| 35 | + metadata["model"] = self.model |
| 36 | + return metadata |
| 37 | + |
| 38 | + |
| 39 | +class MistralOCRProcessor(Processor): |
| 40 | + """PDF processor backed by Mistral's hosted OCR endpoint. |
| 41 | +
|
| 42 | + Activated by setting MMORE_PDF_BACKEND=mistral. Requires MISTRAL_API_KEY. |
| 43 | + """ |
| 44 | + |
| 45 | + def __init__(self, config=None): |
| 46 | + super().__init__(config=config or ProcessorConfig()) |
| 47 | + self._client = None |
| 48 | + self._model = ( |
| 49 | + self.config.custom_config.get("mistral_ocr_model", "mistral-ocr-latest") |
| 50 | + if config is not None |
| 51 | + else "mistral-ocr-latest" |
| 52 | + ) |
| 53 | + |
| 54 | + @classmethod |
| 55 | + def accepts(cls, file: FileDescriptor) -> bool: |
| 56 | + if os.environ.get(PDF_BACKEND_ENV, "").lower() != MISTRAL_BACKEND: |
| 57 | + return False |
| 58 | + return file.file_extension.lower() == ".pdf" |
| 59 | + |
| 60 | + def _get_client(self): |
| 61 | + if self._client is not None: |
| 62 | + return self._client |
| 63 | + try: |
| 64 | + from mistralai import Mistral |
| 65 | + except ImportError as e: |
| 66 | + raise ImportError( |
| 67 | + "mistralai SDK is required for MistralOCRProcessor. " |
| 68 | + "Install with `pip install mistralai`." |
| 69 | + ) from e |
| 70 | + api_key = os.environ.get("MISTRAL_API_KEY") |
| 71 | + if not api_key: |
| 72 | + raise RuntimeError( |
| 73 | + "MISTRAL_API_KEY env var is not set. Required for MistralOCRProcessor." |
| 74 | + ) |
| 75 | + self._client = Mistral(api_key=api_key) |
| 76 | + return self._client |
| 77 | + |
| 78 | + def process(self, file_path: str) -> MultimodalSample: |
| 79 | + client = self._get_client() |
| 80 | + |
| 81 | + with open(file_path, "rb") as fh: |
| 82 | + pdf_bytes = fh.read() |
| 83 | + encoded = base64.b64encode(pdf_bytes).decode("utf-8") |
| 84 | + |
| 85 | + extract_images = self.config.custom_config.get("extract_images", True) |
| 86 | + |
| 87 | + response = client.ocr.process( |
| 88 | + model=self._model, |
| 89 | + document={ |
| 90 | + "type": "document_url", |
| 91 | + "document_url": f"data:application/pdf;base64,{encoded}", |
| 92 | + }, |
| 93 | + include_image_base64=extract_images, |
| 94 | + ) |
| 95 | + |
| 96 | + pages = getattr(response, "pages", None) or [] |
| 97 | + page_texts: List[Tuple[int, str]] = [] |
| 98 | + images: List[Image.Image] = [] |
| 99 | + |
| 100 | + for page_idx, page in enumerate(pages): |
| 101 | + md = getattr(page, "markdown", "") or "" |
| 102 | + if extract_images: |
| 103 | + for img in getattr(page, "images", []) or []: |
| 104 | + b64 = getattr(img, "image_base64", None) |
| 105 | + if not b64: |
| 106 | + continue |
| 107 | + try: |
| 108 | + raw = base64.b64decode(b64.split(",", 1)[-1]) |
| 109 | + images.append(Image.open(io.BytesIO(raw)).convert("RGB")) |
| 110 | + except Exception as e: |
| 111 | + logger.warning( |
| 112 | + f"Could not decode image on page {page_idx} of {file_path}: {e}" |
| 113 | + ) |
| 114 | + md = re.sub(IMG_REGEX, "<attachment>", md) |
| 115 | + page_texts.append((page_idx, md)) |
| 116 | + |
| 117 | + paragraph_starts, full_text = self._build_pagination(page_texts) |
| 118 | + |
| 119 | + metadata = MistralOCRMetadata( |
| 120 | + file_path=file_path, |
| 121 | + paragraph_starts=paragraph_starts, |
| 122 | + model=self._model, |
| 123 | + ) |
| 124 | + return self.create_sample([full_text], images, metadata) |
| 125 | + |
| 126 | + @staticmethod |
| 127 | + def _build_pagination( |
| 128 | + page_texts: List[Tuple[int, str]], |
| 129 | + ) -> Tuple[List[Tuple[int, int, int]], str]: |
| 130 | + paragraph_starts: List[Tuple[int, int, int]] = [] |
| 131 | + current_position = 0 |
| 132 | + parts: List[str] = [] |
| 133 | + for page_id, page_content in page_texts: |
| 134 | + para_idx = 0 |
| 135 | + offset_in_page = 0 |
| 136 | + for segment in page_content.split("\n\n"): |
| 137 | + if segment.strip(): |
| 138 | + paragraph_starts.append( |
| 139 | + (current_position + offset_in_page, page_id, para_idx) |
| 140 | + ) |
| 141 | + para_idx += 1 |
| 142 | + offset_in_page += len(segment) + 2 |
| 143 | + parts.append(page_content) |
| 144 | + current_position += len(page_content) |
| 145 | + paragraph_starts.append((current_position, -1, -1)) |
| 146 | + return paragraph_starts, "".join(parts) |
0 commit comments