|
| 1 | +import logging |
| 2 | +import platform |
| 3 | +import sys |
| 4 | +from collections.abc import Iterable, Sequence |
| 5 | +from pathlib import Path |
| 6 | +from typing import Optional, Type, TypedDict, cast |
| 7 | + |
| 8 | +import numpy |
| 9 | +from docling_core.types.doc import BoundingBox, CoordOrigin |
| 10 | +from docling_core.types.doc.page import BoundingRectangle, TextCell |
| 11 | + |
| 12 | +from docling.datamodel.accelerator_options import AcceleratorOptions |
| 13 | +from docling.datamodel.base_models import Page |
| 14 | +from docling.datamodel.document import ConversionResult |
| 15 | +from docling.datamodel.pipeline_options import ( |
| 16 | + NemotronOcrOptions, |
| 17 | + OcrOptions, |
| 18 | +) |
| 19 | +from docling.datamodel.settings import settings |
| 20 | +from docling.models.base_ocr_model import BaseOcrModel |
| 21 | +from docling.utils.accelerator_utils import decide_device |
| 22 | +from docling.utils.profiling import TimeRecorder |
| 23 | + |
| 24 | +_log = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +class NemotronOcrPrediction(TypedDict): |
| 28 | + """Exact prediction schema returned by `nemotron_ocr` 1.0.1.""" |
| 29 | + |
| 30 | + text: str |
| 31 | + confidence: float |
| 32 | + left: float |
| 33 | + upper: float |
| 34 | + right: float |
| 35 | + lower: float |
| 36 | + |
| 37 | + |
| 38 | +class NemotronOcrModel(BaseOcrModel): |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + enabled: bool, |
| 42 | + artifacts_path: Optional[Path], |
| 43 | + options: NemotronOcrOptions, |
| 44 | + accelerator_options: AcceleratorOptions, |
| 45 | + ): |
| 46 | + super().__init__( |
| 47 | + enabled=enabled, |
| 48 | + artifacts_path=artifacts_path, |
| 49 | + options=options, |
| 50 | + accelerator_options=accelerator_options, |
| 51 | + ) |
| 52 | + self.options: NemotronOcrOptions |
| 53 | + self.scale = 3 # multiplier for 72 dpi == 216 dpi. |
| 54 | + |
| 55 | + if self.enabled: |
| 56 | + self._validate_runtime(accelerator_options=accelerator_options) |
| 57 | + |
| 58 | + try: |
| 59 | + from nemotron_ocr.inference.pipeline import NemotronOCR |
| 60 | + except ImportError as exc: |
| 61 | + raise ImportError( |
| 62 | + "Nemotron OCR is not installed. Install the optional dependency " |
| 63 | + 'via `pip install "docling[nemotron-ocr]"` on Linux x86_64 with ' |
| 64 | + "Python 3.12 and CUDA 13.x." |
| 65 | + ) from exc |
| 66 | + |
| 67 | + model_dir = ( |
| 68 | + str(self.options.model_dir) |
| 69 | + if self.options.model_dir is not None |
| 70 | + else None |
| 71 | + ) |
| 72 | + self.reader = NemotronOCR(model_dir=model_dir) |
| 73 | + |
| 74 | + @staticmethod |
| 75 | + def _fail_runtime(message: str) -> None: |
| 76 | + _log.warning(message) |
| 77 | + raise RuntimeError(message) |
| 78 | + |
| 79 | + @classmethod |
| 80 | + def _validate_runtime(cls, accelerator_options: AcceleratorOptions) -> None: |
| 81 | + if sys.platform != "linux": |
| 82 | + cls._fail_runtime("Nemotron OCR is only supported on Linux.") |
| 83 | + |
| 84 | + if platform.machine() != "x86_64": |
| 85 | + cls._fail_runtime("Nemotron OCR is only supported on x86_64 machines.") |
| 86 | + |
| 87 | + if sys.version_info[:2] != (3, 12): |
| 88 | + cls._fail_runtime("Nemotron OCR requires Python 3.12.") |
| 89 | + |
| 90 | + requested_device = decide_device(accelerator_options.device) |
| 91 | + if not requested_device.startswith("cuda"): |
| 92 | + cls._fail_runtime( |
| 93 | + "Nemotron OCR requires a CUDA accelerator. Set " |
| 94 | + "`pipeline_options.accelerator_options.device` to CUDA or AUTO on a " |
| 95 | + "CUDA-enabled machine." |
| 96 | + ) |
| 97 | + |
| 98 | + import torch |
| 99 | + |
| 100 | + if not torch.cuda.is_available(): |
| 101 | + cls._fail_runtime( |
| 102 | + "Nemotron OCR requires CUDA at initialization time, but " |
| 103 | + "`torch.cuda.is_available()` is false." |
| 104 | + ) |
| 105 | + |
| 106 | + cuda_version = torch.version.cuda |
| 107 | + if cuda_version is None or not cuda_version.startswith("13."): |
| 108 | + cls._fail_runtime( |
| 109 | + "Nemotron OCR requires CUDA 13.x, but the current PyTorch runtime " |
| 110 | + f"reports CUDA {cuda_version!r}." |
| 111 | + ) |
| 112 | + |
| 113 | + @staticmethod |
| 114 | + def _prediction_to_cell( |
| 115 | + prediction: NemotronOcrPrediction, |
| 116 | + index: int, |
| 117 | + ocr_rect: BoundingBox, |
| 118 | + image_width: int, |
| 119 | + image_height: int, |
| 120 | + scale: int, |
| 121 | + ) -> TextCell: |
| 122 | + # `nemotron_ocr` 1.0.1 returns normalized `left/right` and an inverted |
| 123 | + # pair `lower/upper`, where `lower` is the top Y and `upper` is the |
| 124 | + # bottom Y in image coordinates. |
| 125 | + left = (prediction["left"] * image_width) / scale + ocr_rect.l |
| 126 | + top = (prediction["lower"] * image_height) / scale + ocr_rect.t |
| 127 | + right = (prediction["right"] * image_width) / scale + ocr_rect.l |
| 128 | + bottom = (prediction["upper"] * image_height) / scale + ocr_rect.t |
| 129 | + text = prediction["text"] |
| 130 | + |
| 131 | + return TextCell( |
| 132 | + index=index, |
| 133 | + text=text, |
| 134 | + orig=text, |
| 135 | + from_ocr=True, |
| 136 | + confidence=float(prediction["confidence"]), |
| 137 | + rect=BoundingRectangle.from_bounding_box( |
| 138 | + BoundingBox( |
| 139 | + l=left, |
| 140 | + t=top, |
| 141 | + r=right, |
| 142 | + b=bottom, |
| 143 | + coord_origin=CoordOrigin.TOPLEFT, |
| 144 | + ) |
| 145 | + ), |
| 146 | + ) |
| 147 | + |
| 148 | + def __call__( |
| 149 | + self, conv_res: ConversionResult, page_batch: Iterable[Page] |
| 150 | + ) -> Iterable[Page]: |
| 151 | + if not self.enabled: |
| 152 | + yield from page_batch |
| 153 | + return |
| 154 | + |
| 155 | + for page in page_batch: |
| 156 | + assert page._backend is not None |
| 157 | + if not page._backend.is_valid(): |
| 158 | + yield page |
| 159 | + else: |
| 160 | + with TimeRecorder(conv_res, "ocr"): |
| 161 | + ocr_rects = self.get_ocr_rects(page) |
| 162 | + |
| 163 | + all_ocr_cells = [] |
| 164 | + for ocr_rect in ocr_rects: |
| 165 | + if ocr_rect.area() == 0: |
| 166 | + continue |
| 167 | + |
| 168 | + high_res_image = page._backend.get_page_image( |
| 169 | + scale=self.scale, cropbox=ocr_rect |
| 170 | + ) |
| 171 | + image_width, image_height = high_res_image.size |
| 172 | + image_array = numpy.array(high_res_image) |
| 173 | + |
| 174 | + raw_predictions = cast( |
| 175 | + Sequence[NemotronOcrPrediction], |
| 176 | + self.reader( |
| 177 | + image_array, |
| 178 | + merge_level=self.options.merge_level, |
| 179 | + visualize=False, |
| 180 | + ), |
| 181 | + ) |
| 182 | + |
| 183 | + del high_res_image |
| 184 | + del image_array |
| 185 | + |
| 186 | + cells = [ |
| 187 | + self._prediction_to_cell( |
| 188 | + prediction=prediction, |
| 189 | + index=index, |
| 190 | + ocr_rect=ocr_rect, |
| 191 | + image_width=image_width, |
| 192 | + image_height=image_height, |
| 193 | + scale=self.scale, |
| 194 | + ) |
| 195 | + for index, prediction in enumerate(raw_predictions) |
| 196 | + ] |
| 197 | + all_ocr_cells.extend(cells) |
| 198 | + |
| 199 | + self.post_process_cells(all_ocr_cells, page) |
| 200 | + |
| 201 | + if settings.debug.visualize_ocr: |
| 202 | + self.draw_ocr_rects_and_cells(conv_res, page, ocr_rects) |
| 203 | + |
| 204 | + yield page |
| 205 | + |
| 206 | + @classmethod |
| 207 | + def get_options_type(cls) -> Type[OcrOptions]: |
| 208 | + return NemotronOcrOptions |
0 commit comments