python-doctr 1.0.1__py3-none-any.whl → 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +669 -0
  3. doctr/datasets/__init__.py +2 -0
  4. doctr/datasets/coco_text.py +4 -2
  5. doctr/datasets/cord.py +2 -1
  6. doctr/datasets/datasets/base.py +12 -24
  7. doctr/datasets/datasets/pytorch.py +14 -4
  8. doctr/datasets/detection.py +14 -3
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +121 -37
  12. doctr/datasets/generator/pytorch.py +5 -6
  13. doctr/datasets/ic03.py +9 -7
  14. doctr/datasets/ic13.py +4 -2
  15. doctr/datasets/iiit5k.py +2 -1
  16. doctr/datasets/iiithws.py +4 -2
  17. doctr/datasets/imgur5k.py +4 -2
  18. doctr/datasets/layout.py +129 -0
  19. doctr/datasets/mjsynth.py +4 -2
  20. doctr/datasets/ocr.py +2 -1
  21. doctr/datasets/orientation.py +2 -1
  22. doctr/datasets/recognition.py +5 -4
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +10 -8
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +104 -21
  29. doctr/datasets/vocabs.py +320 -148
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +3 -0
  33. doctr/io/elements.py +381 -271
  34. doctr/io/exporters.py +1915 -0
  35. doctr/io/figures.py +313 -0
  36. doctr/io/image/base.py +54 -7
  37. doctr/io/image/pytorch.py +13 -5
  38. doctr/io/pdf.py +6 -5
  39. doctr/io/reader.py +268 -18
  40. doctr/io/sources.py +636 -0
  41. doctr/models/__init__.py +3 -0
  42. doctr/models/_utils.py +206 -13
  43. doctr/models/builder.py +590 -137
  44. doctr/models/classification/__init__.py +3 -0
  45. doctr/models/classification/hgnetv2/__init__.py +1 -0
  46. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  47. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  48. doctr/models/classification/mobilenet/pytorch.py +6 -6
  49. doctr/models/classification/predictor/pytorch.py +34 -2
  50. doctr/models/classification/resnet/pytorch.py +5 -5
  51. doctr/models/classification/starnet/__init__.py +1 -0
  52. doctr/models/classification/starnet/pytorch.py +202 -0
  53. doctr/models/classification/textnet/pytorch.py +6 -5
  54. doctr/models/classification/vgg/pytorch.py +3 -2
  55. doctr/models/classification/vip/layers/pytorch.py +4 -4
  56. doctr/models/classification/vip/pytorch.py +4 -4
  57. doctr/models/classification/vit/pytorch.py +3 -3
  58. doctr/models/classification/vit_det/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  60. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  61. doctr/models/classification/vit_det/pytorch.py +346 -0
  62. doctr/models/classification/zoo.py +14 -2
  63. doctr/models/detection/_utils/base.py +23 -7
  64. doctr/models/detection/core.py +32 -18
  65. doctr/models/detection/differentiable_binarization/base.py +23 -9
  66. doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
  67. doctr/models/detection/fast/base.py +22 -6
  68. doctr/models/detection/fast/pytorch.py +24 -11
  69. doctr/models/detection/linknet/base.py +22 -6
  70. doctr/models/detection/linknet/pytorch.py +10 -3
  71. doctr/models/detection/predictor/pytorch.py +43 -2
  72. doctr/models/detection/zoo.py +6 -2
  73. doctr/models/factory/hub.py +59 -41
  74. doctr/models/formula/__init__.py +2 -0
  75. doctr/models/formula/formulanet/__init__.py +2 -0
  76. doctr/models/formula/formulanet/base.py +70 -0
  77. doctr/models/formula/formulanet/pytorch.py +587 -0
  78. doctr/models/formula/predictor/__init__.py +1 -0
  79. doctr/models/formula/predictor/pytorch.py +132 -0
  80. doctr/models/formula/zoo.py +102 -0
  81. doctr/models/kie_predictor/base.py +23 -1
  82. doctr/models/kie_predictor/pytorch.py +87 -15
  83. doctr/models/layout/__init__.py +2 -0
  84. doctr/models/layout/lw_detr/__init__.py +1 -0
  85. doctr/models/layout/lw_detr/base.py +309 -0
  86. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  87. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  88. doctr/models/layout/lw_detr/pytorch.py +895 -0
  89. doctr/models/layout/predictor/__init__.py +1 -0
  90. doctr/models/layout/predictor/pytorch.py +114 -0
  91. doctr/models/layout/zoo.py +94 -0
  92. doctr/models/modules/layers/pytorch.py +139 -3
  93. doctr/models/modules/transformer/pytorch.py +151 -31
  94. doctr/models/predictor/base.py +415 -17
  95. doctr/models/predictor/pytorch.py +109 -12
  96. doctr/models/preprocessor/pytorch.py +82 -25
  97. doctr/models/reading_order/__init__.py +1 -0
  98. doctr/models/reading_order/base.py +1127 -0
  99. doctr/models/recognition/core.py +14 -1
  100. doctr/models/recognition/crnn/pytorch.py +40 -16
  101. doctr/models/recognition/master/base.py +4 -1
  102. doctr/models/recognition/master/pytorch.py +84 -22
  103. doctr/models/recognition/parseq/base.py +4 -1
  104. doctr/models/recognition/parseq/pytorch.py +126 -25
  105. doctr/models/recognition/predictor/_utils.py +131 -14
  106. doctr/models/recognition/predictor/pytorch.py +68 -12
  107. doctr/models/recognition/sar/pytorch.py +21 -7
  108. doctr/models/recognition/utils.py +80 -50
  109. doctr/models/recognition/viptr/pytorch.py +38 -14
  110. doctr/models/recognition/vitstr/base.py +4 -1
  111. doctr/models/recognition/vitstr/pytorch.py +11 -7
  112. doctr/models/recognition/zoo.py +36 -9
  113. doctr/models/table_structure/__init__.py +2 -0
  114. doctr/models/table_structure/grid.py +430 -0
  115. doctr/models/table_structure/predictor/__init__.py +1 -0
  116. doctr/models/table_structure/predictor/pytorch.py +231 -0
  117. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  118. doctr/models/table_structure/tablecenternet/base.py +675 -0
  119. doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
  120. doctr/models/table_structure/zoo.py +87 -0
  121. doctr/models/utils/pytorch.py +381 -25
  122. doctr/models/zoo.py +141 -4
  123. doctr/transforms/functional/base.py +6 -0
  124. doctr/transforms/functional/pytorch.py +134 -6
  125. doctr/transforms/modules/base.py +261 -82
  126. doctr/transforms/modules/pytorch.py +396 -76
  127. doctr/utils/common_types.py +21 -1
  128. doctr/utils/data.py +24 -11
  129. doctr/utils/fonts.py +64 -17
  130. doctr/utils/geometry.py +167 -28
  131. doctr/utils/metrics.py +481 -19
  132. doctr/utils/multithreading.py +127 -4
  133. doctr/utils/reconstitution.py +696 -132
  134. doctr/utils/visualization.py +73 -10
  135. doctr/version.py +1 -1
  136. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
  137. python_doctr-1.2.0.dist-info/RECORD +191 -0
  138. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  139. python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
  140. python_doctr-1.0.1.dist-info/RECORD +0 -149
  141. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  142. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  143. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
@@ -3,20 +3,42 @@
3
3
  # This program is licensed under the Apache License 2.0.
4
4
  # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
5
 
6
- from collections.abc import Callable
7
- from typing import Any
6
+ import logging
7
+ from collections.abc import Callable, Collection, Iterable, Iterator, Sequence
8
+ from typing import Any, Literal, TypeAlias
8
9
 
9
10
  import numpy as np
10
11
 
12
+ from doctr.io.elements import Document, KIEPage, Page
13
+ from doctr.io.sources import PageSource, _UnreadablePage
11
14
  from doctr.models.builder import DocumentBuilder
12
- from doctr.utils.geometry import extract_crops, extract_rcrops, remove_image_padding, rotate_image
15
+ from doctr.utils.geometry import (
16
+ extract_crops,
17
+ extract_rcrops,
18
+ remove_image_padding,
19
+ rotate_image,
20
+ straighten_page,
21
+ )
22
+ from doctr.utils.multithreading import prefetch_chunks
13
23
 
14
- from .._utils import estimate_orientation, rectify_crops, rectify_loc_preds
24
+ from .._utils import estimate_orientation, mask_boxes, rectify_crops, rectify_loc_preds
15
25
  from ..classification import crop_orientation_predictor, page_orientation_predictor
16
26
  from ..classification.predictor import OrientationPredictor
27
+ from ..detection.predictor import DetectionPredictor
17
28
 
18
29
  __all__ = ["_OCRPredictor"]
19
30
 
31
+ logger = logging.getLogger(__name__)
32
+
33
+ # What to do with a page of a lazy source that cannot be read (a corrupted file, or an input removed in the meantime):
34
+ # raise the error, skip the page with a warning, or skip it and call a function with its index and the error
35
+ OnPageError: TypeAlias = Literal["raise", "skip"] | Callable[[int, Exception], Any]
36
+
37
+
38
+ def _check_on_error(on_error: Any) -> None:
39
+ if not (on_error in ("raise", "skip") or callable(on_error)):
40
+ raise ValueError(f"`on_error` must be 'raise', 'skip' or a callable, got {on_error!r}")
41
+
20
42
 
21
43
  class _OCRPredictor:
22
44
  """Implements an object able to localize and identify text elements in a set of documents
@@ -31,10 +53,20 @@ class _OCRPredictor:
31
53
  symmetric_pad: if True and preserve_aspect_ratio is True, pas the image symmetrically.
32
54
  detect_orientation: if True, the estimated general page orientation will be added to the predictions for each
33
55
  page. Doing so will slightly deteriorate the overall latency.
56
+ ignore_regions: optional list of layout class names to ignore during detection/recognition. If provided, the
57
+ layout model will be used to locate the regions of the specified classes, and these regions will
58
+ be masked out (filled with black) before passing the pages to the detection/recognition modules.
59
+ preserve_original_coords: if True and straighten_pages is True, bounding boxes are mapped back to the
60
+ original page coordinates. Useful for redaction and annotation.
61
+ page_chunk_size: the maximum number of pages processed at once for lazy page sources
62
+ (cf. `DocumentFile.from_pdf(..., lazy=True)`), iterators and :meth:`stream`, so that the memory footprint
63
+ does not grow with the number of pages. Lists and tuples of pages are processed in a single pass.
34
64
  **kwargs: keyword args of `DocumentBuilder`
35
65
  """
36
66
 
37
67
  crop_orientation_predictor: OrientationPredictor | None
68
+ # Set by the framework-specific predictors
69
+ det_predictor: DetectionPredictor
38
70
  page_orientation_predictor: OrientationPredictor | None
39
71
 
40
72
  def __init__(
@@ -44,10 +76,17 @@ class _OCRPredictor:
44
76
  preserve_aspect_ratio: bool = True,
45
77
  symmetric_pad: bool = True,
46
78
  detect_orientation: bool = False,
79
+ ignore_regions: Collection[str] | None = None,
80
+ preserve_original_coords: bool = False,
81
+ page_chunk_size: int = 32,
47
82
  **kwargs: Any,
48
83
  ) -> None:
84
+ if page_chunk_size < 1:
85
+ raise ValueError("`page_chunk_size` must be a positive integer")
86
+ self.page_chunk_size = page_chunk_size
49
87
  self.assume_straight_pages = assume_straight_pages
50
88
  self.straighten_pages = straighten_pages
89
+ self.preserve_original_coords = preserve_original_coords
51
90
  self._page_orientation_disabled = kwargs.pop("disable_page_orientation", False)
52
91
  self._crop_orientation_disabled = kwargs.pop("disable_crop_orientation", False)
53
92
  self.crop_orientation_predictor = (
@@ -61,10 +100,130 @@ class _OCRPredictor:
61
100
  else None
62
101
  )
63
102
  self.doc_builder = DocumentBuilder(**kwargs)
103
+
64
104
  self.preserve_aspect_ratio = preserve_aspect_ratio
65
105
  self.symmetric_pad = symmetric_pad
106
+
107
+ self.ignore_regions = ignore_regions
108
+
66
109
  self.hooks: list[Callable] = []
67
110
 
111
+ # Type of the documents returned by the predictor
112
+ _document_cls: type[Document] = Document
113
+
114
+ def _predict_pages(self, pages: list[np.ndarray], **kwargs: Any) -> Document:
115
+ """Run the full pipeline on a list of pages held in memory"""
116
+ raise NotImplementedError
117
+
118
+ def _run(
119
+ self,
120
+ pages: Sequence[np.ndarray] | Iterable[np.ndarray],
121
+ on_error: OnPageError = "raise",
122
+ **kwargs: Any,
123
+ ) -> Document:
124
+ """Predict on any input: pages held in memory are processed in a single pass, exactly as before (hooks
125
+ receive all the pages at once), lazy page sources and iterators chunk by chunk"""
126
+ _check_on_error(on_error)
127
+ if isinstance(pages, (list, tuple, np.ndarray)):
128
+ # Nothing to decode, hence nothing to skip
129
+ return self._predict_pages(list(pages), **kwargs)
130
+ return self._document_cls(pages=list(self.stream(pages, on_error=on_error, **kwargs))) # type: ignore[arg-type]
131
+
132
+ @staticmethod
133
+ def _skip_page(on_error: OnPageError, page_idx: int, error: Exception) -> None:
134
+ """Report a page of the input that cannot be read, and is left out of the predictions"""
135
+ if callable(on_error):
136
+ on_error(page_idx, error)
137
+ else:
138
+ logger.warning(f"Skipping the page at index {page_idx} of the input, which cannot be read: {error}")
139
+
140
+ def stream(
141
+ self,
142
+ pages: Sequence[np.ndarray] | Iterable[np.ndarray],
143
+ page_chunk_size: int | None = None,
144
+ prefetch_pages: bool = True,
145
+ on_error: OnPageError = "raise",
146
+ **kwargs: Any,
147
+ ) -> Iterator[Page | KIEPage]:
148
+ """Predict on a document of any length, yielding the pages one by one as soon as they are processed
149
+
150
+ The pages are processed by chunks of `page_chunk_size`. For lazy page sources and iterators, the next chunk
151
+ is decoded in a background thread while the current one goes through the models, and only the pages of the
152
+ chunks in flight are held in memory, so that a 1000+ page PDF or a folder of 100k images can be processed
153
+ with a bounded memory footprint. In-memory inputs (lists, tuples, arrays) have nothing to decode: they are
154
+ chunked directly, without a background thread. Hooks are called once per chunk.
155
+
156
+ A page of a lazy source that cannot be read (e.g. an image with a valid header but corrupted content)
157
+ raises a :class:`~doctr.io.PageDecodeError` naming the file once the pages before it are yielded, which
158
+ ends the iteration. With `on_error="skip"`, the page is left out with a warning and the iteration goes on:
159
+ the `page_idx` of the other pages is unchanged, so the skipped ones show as gaps.
160
+
161
+ >>> from doctr.io import DocumentFile
162
+ >>> from doctr.models import ocr_predictor
163
+ >>> model = ocr_predictor(pretrained=True)
164
+ >>> doc = DocumentFile.from_pdf("path/to/your/long_doc.pdf", lazy=True)
165
+ >>> for page in model.stream(doc):
166
+ ... print(page.page_idx, page.render())
167
+ >>> # skip the pages that cannot be read, and keep track of them
168
+ >>> skipped = []
169
+ >>> for page in model.stream(doc, on_error=lambda page_idx, error: skipped.append(page_idx)):
170
+ ... ...
171
+
172
+ Args:
173
+ pages: a list of pages, a lazy page source (cf. `DocumentFile.from_pdf(..., lazy=True)`) or any
174
+ iterable of pages (e.g. a generator)
175
+ page_chunk_size: the number of pages processed at once (defaults to the `page_chunk_size` of the predictor)
176
+ prefetch_pages: whether the next chunk of pages is decoded in a background thread (only applies to lazy
177
+ page sources and iterators: in-memory inputs are never prefetched)
178
+ on_error: what to do with a page of a lazy page source that cannot be read: "raise" (default) the error,
179
+ "skip" the page with a warning, or a callable to skip it and call with the index of the page and the
180
+ error. Errors raised by an iterator (e.g. a generator) end it: they are always raised.
181
+ **kwargs: keyword arguments forwarded to the sub-predictors (as for a regular call)
182
+
183
+ Returns:
184
+ an iterator over the predicted pages, in the input order. `page_idx` is the index of the page in the
185
+ whole input. For lazy page sources, the predicted pages hold a reference to their image instead of the
186
+ image itself: `page.page` decodes it again on access. Pages transformed by the pipeline (e.g. with
187
+ `straighten_pages=True`) cannot be read again from the source: they keep their transformed image, as
188
+ for in-memory inputs. Stopping the iteration early (e.g. with `break`) stops decoding ahead after the
189
+ page in progress.
190
+ """
191
+ _check_on_error(on_error)
192
+ chunk_size = self.page_chunk_size if page_chunk_size is None else page_chunk_size
193
+ source = pages if isinstance(pages, PageSource) else None
194
+ # Unreadable pages of a source are replaced by placeholders: the iteration goes on when they are skipped, and
195
+ # otherwise the error is raised at their position, once the readable pages before them are yielded
196
+ inputs: Iterable[Any] = pages if source is None else source._iter_indices(range(len(source)), skip_errors=True)
197
+ # In-memory pages are only sliced. Closing the generator (early exit, error) stops decoding ahead after the page
198
+ # in progress instead of completing a whole chunk that nobody will process
199
+ chunks = prefetch_chunks(inputs, chunk_size, enabled=prefetch_pages)
200
+ offset = 0
201
+ try:
202
+ for chunk in chunks:
203
+ images = [item for item in chunk if not isinstance(item, _UnreadablePage)]
204
+ predicted = iter(self._predict_pages(images, **kwargs).pages if images else [])
205
+ for local_idx, item in enumerate(chunk):
206
+ page_idx = offset + local_idx
207
+ if isinstance(item, _UnreadablePage):
208
+ if on_error == "raise":
209
+ raise item.error
210
+ self._skip_page(on_error, page_idx, item.error)
211
+ continue
212
+ page = next(predicted)
213
+ page.page_idx = page_idx
214
+ # Unchanged pages are decoded again from their input on access (the pages of an in-memory part
215
+ # of the source are kept as is). Transformed ones (e.g. straightened) keep their image, exactly
216
+ # as for in-memory inputs
217
+ if source is not None and page.page is item:
218
+ ref = source._page_ref(page_idx)
219
+ if ref is not None:
220
+ page.page = ref
221
+ yield page
222
+ offset += len(chunk)
223
+ finally:
224
+ # Stops decoding ahead after the page in progress, and releases the input
225
+ chunks.close()
226
+
68
227
  def _general_page_orientations(
69
228
  self,
70
229
  pages: list[np.ndarray],
@@ -88,13 +247,42 @@ class _OCRPredictor:
88
247
  ]
89
248
  return general_pages_orientations, origin_page_orientations
90
249
 
250
+ def _masked_classes(self) -> set[str]:
251
+ """The layout classes masked out before text detection: the ignored regions, and the formula regions when
252
+ they are read by a formula model"""
253
+ classes = set(self.ignore_regions or ())
254
+ if getattr(self, "formula_predictor", None) is not None:
255
+ classes.add(getattr(self, "formula_class_name", "Formula"))
256
+ return classes
257
+
258
+ def _mask_regions(
259
+ self,
260
+ pages: list[np.ndarray],
261
+ regions: list[dict[str, Any]] | None,
262
+ fill_value: int = 0,
263
+ ) -> list[np.ndarray]:
264
+ masked_classes = self._masked_classes()
265
+ if regions is None or not masked_classes:
266
+ return pages
267
+
268
+ out_pages: list[np.ndarray] = []
269
+ for page, region in zip(pages, regions):
270
+ if region is None:
271
+ out_pages.append(page)
272
+ continue
273
+ boxes = np.asarray(region["boxes"], dtype=np.float32)
274
+ keep = np.array([name in masked_classes for name in region["class_names"]], dtype=bool)
275
+ out_pages.append(mask_boxes(page, boxes[keep], fill_value=fill_value) if keep.any() else page)
276
+
277
+ return out_pages
278
+
91
279
  def _straighten_pages(
92
280
  self,
93
281
  pages: list[np.ndarray],
94
282
  seg_maps: list[np.ndarray],
95
283
  general_pages_orientations: list[tuple[int, float]] | None = None,
96
284
  origin_pages_orientations: list[int] | None = None,
97
- ) -> list[np.ndarray]:
285
+ ) -> tuple[list[np.ndarray], list[np.ndarray]]:
98
286
  general_pages_orientations = (
99
287
  general_pages_orientations if general_pages_orientations else self._general_page_orientations(pages)
100
288
  )
@@ -106,11 +294,52 @@ class _OCRPredictor:
106
294
  for seq_map, general_orientation in zip(seg_maps, general_pages_orientations)
107
295
  ]
108
296
  )
109
- return [
297
+ if not self.preserve_original_coords:
110
298
  # expand if height and width are not equal, then remove the padding
111
- remove_image_padding(rotate_image(page, angle, expand=page.shape[0] != page.shape[1]))
112
- for page, angle in zip(pages, origin_pages_orientations)
299
+ return [
300
+ remove_image_padding(rotate_image(page, angle, expand=page.shape[0] != page.shape[1]))
301
+ for page, angle in zip(pages, origin_pages_orientations)
302
+ ], []
303
+
304
+ m_invs = []
305
+ out = []
306
+ for page, angle in zip(pages, origin_pages_orientations):
307
+ straightened, m_inv = straighten_page(page, angle)
308
+ m_invs.append(m_inv)
309
+ out.append(straightened)
310
+ return out, m_invs
311
+
312
+ def _detect_straightened(
313
+ self,
314
+ loc_preds: list[Any],
315
+ orig_pages: list[np.ndarray],
316
+ pages: list[np.ndarray],
317
+ det_pages: list[np.ndarray],
318
+ **kwargs: Any,
319
+ ) -> list[Any]:
320
+ """Detect the text again on the straightened pages, except on the ones left unchanged by the straightening
321
+ and the masking (e.g. straight pages): the detection made to estimate their orientation is reused
322
+
323
+ Args:
324
+ loc_preds: the detections on the original pages
325
+ orig_pages: the original pages
326
+ pages: the straightened pages
327
+ det_pages: the straightened pages passed to the detection model (masked layout regions)
328
+ **kwargs: keyword arguments of the detection predictor
329
+
330
+ Returns:
331
+ the detections on the straightened pages
332
+ """
333
+ out = list(loc_preds)
334
+ changed = [
335
+ idx
336
+ for idx, (orig, page, det_page) in enumerate(zip(orig_pages, pages, det_pages))
337
+ if det_page is not page or orig.shape != page.shape or not np.array_equal(orig, page)
113
338
  ]
339
+ if changed:
340
+ for idx, pred in zip(changed, self.det_predictor([det_pages[idx] for idx in changed], **kwargs)):
341
+ out[idx] = pred
342
+ return out
114
343
 
115
344
  @staticmethod
116
345
  def _generate_crops(
@@ -132,9 +361,10 @@ class _OCRPredictor:
132
361
  def _prepare_crops(
133
362
  pages: list[np.ndarray],
134
363
  loc_preds: list[np.ndarray],
364
+ objectness_scores: list[np.ndarray],
135
365
  assume_straight_pages: bool = False,
136
366
  assume_horizontal: bool = False,
137
- ) -> tuple[list[list[np.ndarray]], list[np.ndarray]]:
367
+ ) -> tuple[list[list[np.ndarray]], list[np.ndarray], list[np.ndarray]]:
138
368
  crops = _OCRPredictor._generate_crops(pages, loc_preds, assume_straight_pages, assume_horizontal)
139
369
 
140
370
  # Avoid sending zero-sized crops
@@ -144,27 +374,28 @@ class _OCRPredictor:
144
374
  for page_crops, page_kept in zip(crops, is_kept)
145
375
  ]
146
376
  loc_preds = [_boxes[_kept] for _boxes, _kept in zip(loc_preds, is_kept)]
377
+ # Drop the scores of the discarded boxes too, so that each kept box keeps its own score
378
+ objectness_scores = [_scores[_kept] for _scores, _kept in zip(objectness_scores, is_kept)]
147
379
 
148
- return crops, loc_preds
380
+ return crops, loc_preds, objectness_scores
149
381
 
150
382
  def _rectify_crops(
151
383
  self,
152
384
  crops: list[list[np.ndarray]],
153
385
  loc_preds: list[np.ndarray],
154
386
  ) -> tuple[list[list[np.ndarray]], list[np.ndarray], list[tuple[int, float]]]:
155
- # Work at a page level
156
- orientations, classes, probs = zip(*[self.crop_orientation_predictor(page_crops) for page_crops in crops]) # type: ignore[misc]
387
+ page_counts = [len(page_crops) for page_crops in crops]
388
+ flat_crops = [crop for page_crops in crops for crop in page_crops]
389
+ flat_orientations, flat_classes, flat_probs = self.crop_orientation_predictor(flat_crops) # type: ignore[misc]
390
+ _bounds = np.cumsum([0, *page_counts])
391
+ orientations = [flat_orientations[start:end] for start, end in zip(_bounds[:-1], _bounds[1:])]
157
392
  rect_crops = [rectify_crops(page_crops, orientation) for page_crops, orientation in zip(crops, orientations)]
158
393
  rect_loc_preds = [
159
394
  rectify_loc_preds(page_loc_preds, orientation) if len(page_loc_preds) > 0 else page_loc_preds
160
395
  for page_loc_preds, orientation in zip(loc_preds, orientations)
161
396
  ]
162
397
  # Flatten to list of tuples with (value, confidence)
163
- crop_orientations = [
164
- (orientation, prob)
165
- for page_classes, page_probs in zip(classes, probs)
166
- for orientation, prob in zip(page_classes, page_probs)
167
- ]
398
+ crop_orientations = [(orientation, prob) for orientation, prob in zip(flat_classes, flat_probs)]
168
399
  return rect_crops, rect_loc_preds, crop_orientations # type: ignore[return-value]
169
400
 
170
401
  @staticmethod
@@ -185,10 +416,177 @@ class _OCRPredictor:
185
416
 
186
417
  return loc_preds, text_preds, crop_orientation_preds
187
418
 
419
+ @staticmethod
420
+ def _remap_geometry(obj: Any, m_inv: np.ndarray, sw: int, sh: int, oh: int, ow: int) -> None:
421
+ """Remap a single geometry-bearing object from straightened to original coords."""
422
+ pts = np.asarray(obj.geometry, dtype=np.float64).reshape(-1, 2)
423
+ was_straight = pts.shape[0] == 2
424
+ if was_straight:
425
+ (x0, y0), (x1, y1) = pts
426
+ pts = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]], dtype=np.float64)
427
+ pts[:, 0] *= sw
428
+ pts[:, 1] *= sh
429
+ homo = np.column_stack([pts, np.ones(len(pts))])
430
+ orig = (homo @ m_inv.T)[:, :2]
431
+ orig[:, 0] = orig[:, 0].clip(0, ow - 1) / ow
432
+ orig[:, 1] = orig[:, 1].clip(0, oh - 1) / oh
433
+ if was_straight:
434
+ obj.geometry = (
435
+ (float(orig[:, 0].min()), float(orig[:, 1].min())),
436
+ (float(orig[:, 0].max()), float(orig[:, 1].max())),
437
+ )
438
+ else:
439
+ obj.geometry = tuple(tuple(r) for r in orig.tolist())
440
+
441
+ def _remap_to_original_coords(
442
+ self,
443
+ out: Document,
444
+ orig_shapes: list[tuple[int, int]],
445
+ straight_shapes: list[tuple[int, int]],
446
+ m_invs: list[np.ndarray],
447
+ orig_pages: list[np.ndarray] | None = None,
448
+ ) -> Document:
449
+ """Remap word geometries from straightened-page coordinates back to original page coordinates.
450
+
451
+ Args:
452
+ out: the document returned by the builder
453
+ orig_shapes: original (pre-straightening) page shapes (H, W)
454
+ straight_shapes: straightened page shapes (H, W)
455
+ m_invs: inverse affine matrices from the straightening pipeline, one per page
456
+ orig_pages: optional list of original page images to restore on `page.page`
457
+
458
+ Returns:
459
+ the document with remapped word geometries
460
+
461
+ """
462
+ for pidx, (page, m_inv) in enumerate(zip(out.pages, m_invs)):
463
+ sh, sw = straight_shapes[pidx] # straightened_height, straightened_width
464
+ oh, ow = orig_shapes[pidx] # original_height, original_width
465
+
466
+ if isinstance(page, KIEPage):
467
+ for preds in page.predictions.values():
468
+ for pred in preds:
469
+ self._remap_geometry(pred, m_inv, sw, sh, oh, ow)
470
+ for region in page.layout:
471
+ self._remap_geometry(region, m_inv, sw, sh, oh, ow)
472
+ else:
473
+ for block in page.blocks:
474
+ self._remap_geometry(block, m_inv, sw, sh, oh, ow)
475
+ for artefact in block.artefacts:
476
+ self._remap_geometry(artefact, m_inv, sw, sh, oh, ow)
477
+ for line in block.lines:
478
+ self._remap_geometry(line, m_inv, sw, sh, oh, ow)
479
+ for word in line.words:
480
+ self._remap_geometry(word, m_inv, sw, sh, oh, ow)
481
+ for region in page.layout:
482
+ self._remap_geometry(region, m_inv, sw, sh, oh, ow)
483
+ for table in page.tables:
484
+ self._remap_geometry(table, m_inv, sw, sh, oh, ow)
485
+ for cell in table.cells:
486
+ self._remap_geometry(cell, m_inv, sw, sh, oh, ow)
487
+ for formula in page.formulas:
488
+ self._remap_geometry(formula, m_inv, sw, sh, oh, ow)
489
+
490
+ if orig_pages is not None:
491
+ out.pages[pidx].page = orig_pages[pidx]
492
+ out.pages[pidx].dimensions = orig_shapes[pidx]
493
+
494
+ return out
495
+
188
496
  def add_hook(self, hook: Callable) -> None:
189
497
  """Add a hook to the predictor
190
498
 
499
+ Hooks run after text detection and before the word crops are extracted, in the order they were added.
500
+ Each hook receives the location predictions, one array of boxes per page in relative coordinates
501
+ (`(N, 4)` straight boxes or `(N, 4, 2)` polygons), and returns them in the same format. It can move,
502
+ resize, add or remove boxes: only the returned boxes are cropped and read by the recognition model.
503
+
504
+ Lazy page sources, iterators and :meth:`stream` are processed chunk by chunk (`page_chunk_size` pages at a
505
+ time): hooks are then called once per chunk, with the pages of that chunk only. A hook must therefore not rely
506
+ on the number of pages it receives, nor use a list position as the page index in the whole document. Lists
507
+ and tuples of pages are processed in a single pass: hooks receive all their pages at once.
508
+
191
509
  Args:
192
510
  hook: a callable that takes as input the `loc_preds` and returns the modified `loc_preds`
193
511
  """
194
512
  self.hooks.append(hook)
513
+
514
+ def _apply_hooks(
515
+ self, loc_preds: list[np.ndarray], objectness_scores: list[np.ndarray]
516
+ ) -> tuple[list[np.ndarray], list[np.ndarray]]:
517
+ """Run the hooks on the location predictions, before the word crops are extracted
518
+
519
+ Args:
520
+ loc_preds: one array of boxes per page, in relative coordinates
521
+ objectness_scores: one array of objectness scores per page
522
+
523
+ Returns:
524
+ the location predictions returned by the hooks, and the matching objectness scores
525
+ """
526
+ if not self.hooks:
527
+ return loc_preds, objectness_scores
528
+ # Pass a copy of the list, so that a hook replacing the arrays in place does not alter the reference
529
+ hooked_preds: Any = list(loc_preds)
530
+ for hook in self.hooks:
531
+ hooked_preds = hook(hooked_preds)
532
+ return self._align_hook_output(loc_preds, hooked_preds, objectness_scores)
533
+
534
+ @staticmethod
535
+ def _align_hook_output(
536
+ loc_preds: list[np.ndarray], hooked_preds: Any, objectness_scores: list[np.ndarray]
537
+ ) -> tuple[list[np.ndarray], list[np.ndarray]]:
538
+ """Check the location predictions returned by the hooks, and give each box an objectness score
539
+
540
+ A box keeps the score of the closest predicted box of its page, so that moved, resized, reordered or
541
+ filtered boxes keep their own score. A box added on a page without any prediction gets a score of 1.
542
+
543
+ Args:
544
+ loc_preds: the location predictions passed to the hooks, one array per page
545
+ hooked_preds: the location predictions returned by the hooks
546
+ objectness_scores: the objectness scores of `loc_preds`, one array per page
547
+
548
+ Returns:
549
+ the location predictions returned by the hooks as arrays, and their objectness scores
550
+ """
551
+ if not isinstance(hooked_preds, (list, tuple)) or len(hooked_preds) != len(loc_preds):
552
+ received = type(hooked_preds).__name__
553
+ if isinstance(hooked_preds, (list, tuple)):
554
+ received += f" of length {len(hooked_preds)}"
555
+ raise ValueError(
556
+ f"hooks must return one array of boxes per page: expected a list of {len(loc_preds)} arrays, "
557
+ f"got a {received}"
558
+ )
559
+
560
+ out_preds: list[np.ndarray] = []
561
+ out_scores: list[np.ndarray] = []
562
+ for page_idx, (boxes, new_boxes, scores) in enumerate(zip(loc_preds, hooked_preds, objectness_scores)):
563
+ new_boxes = np.asarray(new_boxes, dtype=boxes.dtype)
564
+ if new_boxes.size == 0:
565
+ new_boxes = new_boxes.reshape((0, *boxes.shape[1:]))
566
+ if new_boxes.shape[1:] != boxes.shape[1:]:
567
+ raise ValueError(
568
+ "hooks must keep the format of the boxes: expected an array of shape "
569
+ f"(N, {', '.join(map(str, boxes.shape[1:]))}) for page {page_idx}, got {new_boxes.shape}"
570
+ )
571
+
572
+ if new_boxes.shape == boxes.shape and np.array_equal(new_boxes, boxes):
573
+ new_scores = scores
574
+ elif len(new_boxes) == 0:
575
+ new_scores = scores[:0]
576
+ elif len(boxes) == 0:
577
+ new_scores = np.ones(len(new_boxes), dtype=scores.dtype)
578
+ else:
579
+ # Match each returned box with the closest predicted box (L1 distance between the corners),
580
+ # by chunks to bound the memory used on dense pages
581
+ ref = boxes.reshape(len(boxes), -1)
582
+ flat = new_boxes.reshape(len(new_boxes), -1)
583
+ idcs = np.concatenate([
584
+ np.abs(flat[start : start + 256, None, :] - ref[None, :, :]).sum(-1).argmin(axis=1)
585
+ for start in range(0, len(flat), 256)
586
+ ])
587
+ new_scores = scores[idcs]
588
+
589
+ out_preds.append(new_boxes)
590
+ out_scores.append(new_scores)
591
+
592
+ return out_preds, out_scores