python-doctr 1.1.0__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 (93) hide show
  1. doctr/cli/main.py +186 -23
  2. doctr/datasets/detection.py +12 -2
  3. doctr/datasets/generator/base.py +118 -35
  4. doctr/datasets/generator/pytorch.py +1 -1
  5. doctr/datasets/ic03.py +6 -5
  6. doctr/datasets/layout.py +7 -1
  7. doctr/datasets/recognition.py +3 -3
  8. doctr/datasets/svt.py +7 -6
  9. doctr/datasets/utils.py +100 -26
  10. doctr/datasets/vocabs.py +320 -150
  11. doctr/io/__init__.py +2 -0
  12. doctr/io/elements.py +138 -20
  13. doctr/io/exporters.py +848 -208
  14. doctr/io/figures.py +313 -0
  15. doctr/io/image/base.py +54 -8
  16. doctr/io/image/pytorch.py +14 -8
  17. doctr/io/pdf.py +6 -5
  18. doctr/io/reader.py +268 -18
  19. doctr/io/sources.py +636 -0
  20. doctr/models/__init__.py +1 -0
  21. doctr/models/_utils.py +150 -5
  22. doctr/models/builder.py +316 -334
  23. doctr/models/classification/__init__.py +1 -0
  24. doctr/models/classification/hgnetv2/__init__.py +1 -0
  25. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  26. doctr/models/classification/predictor/pytorch.py +28 -0
  27. doctr/models/classification/zoo.py +11 -2
  28. doctr/models/detection/core.py +1 -2
  29. doctr/models/detection/differentiable_binarization/base.py +17 -5
  30. doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
  31. doctr/models/detection/fast/base.py +17 -5
  32. doctr/models/detection/fast/pytorch.py +21 -8
  33. doctr/models/detection/linknet/base.py +17 -5
  34. doctr/models/detection/linknet/pytorch.py +7 -0
  35. doctr/models/detection/predictor/pytorch.py +40 -0
  36. doctr/models/detection/zoo.py +4 -0
  37. doctr/models/factory/hub.py +5 -2
  38. doctr/models/formula/__init__.py +2 -0
  39. doctr/models/formula/formulanet/__init__.py +2 -0
  40. doctr/models/formula/formulanet/base.py +70 -0
  41. doctr/models/formula/formulanet/pytorch.py +587 -0
  42. doctr/models/formula/predictor/__init__.py +1 -0
  43. doctr/models/formula/predictor/pytorch.py +132 -0
  44. doctr/models/formula/zoo.py +102 -0
  45. doctr/models/kie_predictor/base.py +7 -0
  46. doctr/models/kie_predictor/pytorch.py +47 -6
  47. doctr/models/layout/lw_detr/pytorch.py +150 -93
  48. doctr/models/layout/predictor/pytorch.py +32 -0
  49. doctr/models/layout/zoo.py +4 -0
  50. doctr/models/modules/transformer/pytorch.py +151 -31
  51. doctr/models/predictor/base.py +283 -7
  52. doctr/models/predictor/pytorch.py +53 -98
  53. doctr/models/preprocessor/pytorch.py +13 -11
  54. doctr/models/reading_order/base.py +720 -260
  55. doctr/models/recognition/core.py +14 -1
  56. doctr/models/recognition/crnn/pytorch.py +37 -11
  57. doctr/models/recognition/master/base.py +4 -1
  58. doctr/models/recognition/master/pytorch.py +83 -20
  59. doctr/models/recognition/parseq/base.py +4 -1
  60. doctr/models/recognition/parseq/pytorch.py +123 -22
  61. doctr/models/recognition/predictor/_utils.py +131 -14
  62. doctr/models/recognition/predictor/pytorch.py +67 -11
  63. doctr/models/recognition/sar/pytorch.py +20 -6
  64. doctr/models/recognition/utils.py +75 -43
  65. doctr/models/recognition/viptr/pytorch.py +37 -11
  66. doctr/models/recognition/vitstr/base.py +4 -1
  67. doctr/models/recognition/vitstr/pytorch.py +7 -3
  68. doctr/models/recognition/zoo.py +31 -3
  69. doctr/models/table_structure/grid.py +430 -0
  70. doctr/models/table_structure/predictor/pytorch.py +152 -1
  71. doctr/models/table_structure/tablecenternet/base.py +206 -16
  72. doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
  73. doctr/models/table_structure/zoo.py +5 -0
  74. doctr/models/utils/pytorch.py +73 -16
  75. doctr/models/zoo.py +53 -4
  76. doctr/transforms/functional/base.py +6 -0
  77. doctr/transforms/functional/pytorch.py +134 -6
  78. doctr/transforms/modules/base.py +17 -3
  79. doctr/transforms/modules/pytorch.py +185 -4
  80. doctr/utils/data.py +20 -9
  81. doctr/utils/fonts.py +17 -9
  82. doctr/utils/geometry.py +36 -14
  83. doctr/utils/metrics.py +143 -13
  84. doctr/utils/multithreading.py +122 -2
  85. doctr/utils/visualization.py +11 -7
  86. doctr/version.py +1 -1
  87. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
  88. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
  89. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  90. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
  91. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  92. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  93. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
@@ -3,12 +3,14 @@
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, Collection
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
 
11
- from doctr.io.elements import Document, KIEPage
12
+ from doctr.io.elements import Document, KIEPage, Page
13
+ from doctr.io.sources import PageSource, _UnreadablePage
12
14
  from doctr.models.builder import DocumentBuilder
13
15
  from doctr.utils.geometry import (
14
16
  extract_crops,
@@ -17,13 +19,26 @@ from doctr.utils.geometry import (
17
19
  rotate_image,
18
20
  straighten_page,
19
21
  )
22
+ from doctr.utils.multithreading import prefetch_chunks
20
23
 
21
24
  from .._utils import estimate_orientation, mask_boxes, rectify_crops, rectify_loc_preds
22
25
  from ..classification import crop_orientation_predictor, page_orientation_predictor
23
26
  from ..classification.predictor import OrientationPredictor
27
+ from ..detection.predictor import DetectionPredictor
24
28
 
25
29
  __all__ = ["_OCRPredictor"]
26
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
+
27
42
 
28
43
  class _OCRPredictor:
29
44
  """Implements an object able to localize and identify text elements in a set of documents
@@ -43,10 +58,15 @@ class _OCRPredictor:
43
58
  be masked out (filled with black) before passing the pages to the detection/recognition modules.
44
59
  preserve_original_coords: if True and straighten_pages is True, bounding boxes are mapped back to the
45
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.
46
64
  **kwargs: keyword args of `DocumentBuilder`
47
65
  """
48
66
 
49
67
  crop_orientation_predictor: OrientationPredictor | None
68
+ # Set by the framework-specific predictors
69
+ det_predictor: DetectionPredictor
50
70
  page_orientation_predictor: OrientationPredictor | None
51
71
 
52
72
  def __init__(
@@ -58,8 +78,12 @@ class _OCRPredictor:
58
78
  detect_orientation: bool = False,
59
79
  ignore_regions: Collection[str] | None = None,
60
80
  preserve_original_coords: bool = False,
81
+ page_chunk_size: int = 32,
61
82
  **kwargs: Any,
62
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
63
87
  self.assume_straight_pages = assume_straight_pages
64
88
  self.straighten_pages = straighten_pages
65
89
  self.preserve_original_coords = preserve_original_coords
@@ -84,6 +108,122 @@ class _OCRPredictor:
84
108
 
85
109
  self.hooks: list[Callable] = []
86
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
+
87
227
  def _general_page_orientations(
88
228
  self,
89
229
  pages: list[np.ndarray],
@@ -107,13 +247,22 @@ class _OCRPredictor:
107
247
  ]
108
248
  return general_pages_orientations, origin_page_orientations
109
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
+
110
258
  def _mask_regions(
111
259
  self,
112
260
  pages: list[np.ndarray],
113
261
  regions: list[dict[str, Any]] | None,
114
262
  fill_value: int = 0,
115
263
  ) -> list[np.ndarray]:
116
- if regions is None or not self.ignore_regions:
264
+ masked_classes = self._masked_classes()
265
+ if regions is None or not masked_classes:
117
266
  return pages
118
267
 
119
268
  out_pages: list[np.ndarray] = []
@@ -122,7 +271,7 @@ class _OCRPredictor:
122
271
  out_pages.append(page)
123
272
  continue
124
273
  boxes = np.asarray(region["boxes"], dtype=np.float32)
125
- keep = np.array([name in self.ignore_regions for name in region["class_names"]], dtype=bool)
274
+ keep = np.array([name in masked_classes for name in region["class_names"]], dtype=bool)
126
275
  out_pages.append(mask_boxes(page, boxes[keep], fill_value=fill_value) if keep.any() else page)
127
276
 
128
277
  return out_pages
@@ -160,6 +309,38 @@ class _OCRPredictor:
160
309
  out.append(straightened)
161
310
  return out, m_invs
162
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)
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
343
+
163
344
  @staticmethod
164
345
  def _generate_crops(
165
346
  pages: list[np.ndarray],
@@ -180,9 +361,10 @@ class _OCRPredictor:
180
361
  def _prepare_crops(
181
362
  pages: list[np.ndarray],
182
363
  loc_preds: list[np.ndarray],
364
+ objectness_scores: list[np.ndarray],
183
365
  assume_straight_pages: bool = False,
184
366
  assume_horizontal: bool = False,
185
- ) -> tuple[list[list[np.ndarray]], list[np.ndarray]]:
367
+ ) -> tuple[list[list[np.ndarray]], list[np.ndarray], list[np.ndarray]]:
186
368
  crops = _OCRPredictor._generate_crops(pages, loc_preds, assume_straight_pages, assume_horizontal)
187
369
 
188
370
  # Avoid sending zero-sized crops
@@ -192,8 +374,10 @@ class _OCRPredictor:
192
374
  for page_crops, page_kept in zip(crops, is_kept)
193
375
  ]
194
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)]
195
379
 
196
- return crops, loc_preds
380
+ return crops, loc_preds, objectness_scores
197
381
 
198
382
  def _rectify_crops(
199
383
  self,
@@ -300,6 +484,8 @@ class _OCRPredictor:
300
484
  self._remap_geometry(table, m_inv, sw, sh, oh, ow)
301
485
  for cell in table.cells:
302
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)
303
489
 
304
490
  if orig_pages is not None:
305
491
  out.pages[pidx].page = orig_pages[pidx]
@@ -310,7 +496,97 @@ class _OCRPredictor:
310
496
  def add_hook(self, hook: Callable) -> None:
311
497
  """Add a hook to the predictor
312
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
+
313
509
  Args:
314
510
  hook: a callable that takes as input the `loc_preds` and returns the modified `loc_preds`
315
511
  """
316
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
@@ -3,9 +3,9 @@
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 Iterable, Sequence
6
7
  from typing import Any
7
8
 
8
- import cv2
9
9
  import numpy as np
10
10
  import torch
11
11
  from torch import nn
@@ -13,6 +13,7 @@ from torch import nn
13
13
  from doctr.io.elements import Document
14
14
  from doctr.models._utils import get_language
15
15
  from doctr.models.detection.predictor import DetectionPredictor
16
+ from doctr.models.formula.predictor import FormulaPredictor
16
17
  from doctr.models.layout.predictor import LayoutPredictor
17
18
  from doctr.models.recognition.predictor import RecognitionPredictor
18
19
  from doctr.models.table_structure.predictor import TablePredictor
@@ -44,6 +45,11 @@ class OCRPredictor(nn.Module, _OCRPredictor):
44
45
  table_predictor: optional table structure recognition module. Requires `layout_predictor`: table
45
46
  regions are located by the layout model, cropped, and passed to this module. Words falling inside a
46
47
  detected table are regrouped into a structured table and removed from the regular text output.
48
+ formula_predictor: optional formula recognition module. Requires `layout_predictor`: formula regions are
49
+ located by the layout model, masked out of the text detection, cropped, and read as LaTeX by this module.
50
+ page_chunk_size: the maximum number of pages processed at once (32 by default) for lazy page sources
51
+ (cf. `DocumentFile.from_pdf(..., lazy=True)`), iterators and :meth:`stream`, with a memory footprint that
52
+ does not grow with the number of pages. Lists and tuples of pages are processed in a single pass.
47
53
  **kwargs: keyword args of `DocumentBuilder`
48
54
  """
49
55
 
@@ -60,6 +66,7 @@ class OCRPredictor(nn.Module, _OCRPredictor):
60
66
  preserve_original_coords: bool = False,
61
67
  layout_predictor: LayoutPredictor | None = None,
62
68
  table_predictor: TablePredictor | None = None,
69
+ formula_predictor: FormulaPredictor | None = None,
63
70
  **kwargs: Any,
64
71
  ) -> None:
65
72
  nn.Module.__init__(self)
@@ -86,13 +93,44 @@ class OCRPredictor(nn.Module, _OCRPredictor):
86
93
  "`table_predictor` requires a `layout_predictor`: tables are located with the layout model, "
87
94
  "cropped, and then passed to the table model."
88
95
  )
96
+ self.formula_predictor = formula_predictor.eval() if formula_predictor is not None else None
97
+ # Layout class label whose regions are read by the formula model (and masked out of the text detection)
98
+ self.formula_class_name = "Formula"
99
+ if self.formula_predictor is not None and self.layout_predictor is None:
100
+ raise ValueError(
101
+ "`formula_predictor` requires a `layout_predictor`: formulas are located with the layout model, "
102
+ "cropped, and then passed to the formula model."
103
+ )
89
104
 
90
105
  @torch.inference_mode()
91
106
  def forward(
107
+ self,
108
+ pages: Sequence[np.ndarray] | Iterable[np.ndarray],
109
+ **kwargs: Any,
110
+ ) -> Document:
111
+ """Predict on a document
112
+
113
+ Args:
114
+ pages: a list of pages (numpy arrays of shape H x W x C), processed in a single pass, or a lazy page
115
+ source (cf. `DocumentFile.from_pdf(..., lazy=True)`) or any iterable of pages, processed chunk by
116
+ chunk (`page_chunk_size` pages at a time) with a bounded memory footprint
117
+ **kwargs: keyword arguments forwarded to the sub-predictors, and `on_error` for lazy page sources
118
+ (cf. :meth:`stream`): "skip" leaves out the pages that cannot be read instead of raising an error
119
+
120
+ Returns:
121
+ the predicted document
122
+ """
123
+ return self._run(pages, **kwargs)
124
+
125
+ @torch.inference_mode()
126
+ def _predict_pages(
92
127
  self,
93
128
  pages: list[np.ndarray],
94
129
  **kwargs: Any,
95
130
  ) -> Document:
131
+ if len(pages) == 0:
132
+ return Document(pages=[])
133
+
96
134
  # Dimension check
97
135
  if any(page.ndim != 3 for page in pages):
98
136
  raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
@@ -139,7 +177,7 @@ class OCRPredictor(nn.Module, _OCRPredictor):
139
177
  det_pages = self._mask_regions(pages, regions)
140
178
 
141
179
  # Forward again to get predictions on straight pages
142
- loc_preds = self.det_predictor(det_pages, **kwargs)
180
+ loc_preds = self._detect_straightened(loc_preds, _orig_pages, pages, det_pages, **kwargs)
143
181
 
144
182
  assert all(len(loc_pred) == 1 for loc_pred in loc_preds), (
145
183
  "Detection Model in ocr_predictor should output only one class"
@@ -149,17 +187,18 @@ class OCRPredictor(nn.Module, _OCRPredictor):
149
187
  # Detach objectness scores from loc_preds
150
188
  loc_preds, objectness_scores = detach_scores(loc_preds)
151
189
 
152
- # Apply hooks to loc_preds if any
153
- for hook in self.hooks:
154
- loc_preds = hook(loc_preds)
190
+ # Apply hooks to loc_preds if any, before the crops are extracted so that the hooked boxes are read
191
+ loc_preds, objectness_scores = self._apply_hooks(loc_preds, objectness_scores)
155
192
 
156
193
  # Crop images
157
- crops, loc_preds = self._prepare_crops(
194
+ crops, loc_preds, objectness_scores = self._prepare_crops(
158
195
  pages,
159
196
  loc_preds,
197
+ objectness_scores,
160
198
  assume_straight_pages=self.assume_straight_pages,
161
199
  assume_horizontal=self._page_orientation_disabled,
162
200
  )
201
+
163
202
  # Rectify crop orientation and get crop orientation predictions
164
203
  crop_orientations: Any = []
165
204
  if not self.assume_straight_pages:
@@ -183,10 +222,16 @@ class OCRPredictor(nn.Module, _OCRPredictor):
183
222
 
184
223
  # Recognize table structure: locate tables with the layout model, crop each one and run the table model
185
224
  tables = (
186
- self._tables_from_regions(pages, regions, **kwargs)
225
+ self.table_predictor.predict_regions(pages, regions, boxes, self.table_class_name, **kwargs)
187
226
  if self.table_predictor is not None and regions is not None
188
227
  else None
189
228
  )
229
+ # Recognize formulas: read the formula regions of the layout model as LaTeX
230
+ formulas = (
231
+ self.formula_predictor.predict_regions(pages, regions, self.formula_class_name, **kwargs)
232
+ if self.formula_predictor is not None and regions is not None
233
+ else None
234
+ )
190
235
 
191
236
  out = self.doc_builder(
192
237
  pages,
@@ -199,99 +244,9 @@ class OCRPredictor(nn.Module, _OCRPredictor):
199
244
  languages_dict,
200
245
  regions,
201
246
  tables,
247
+ formulas,
202
248
  )
203
249
 
204
250
  if self.straighten_pages and self.preserve_original_coords:
205
251
  out = self._remap_to_original_coords(out, _orig_shapes, _straight_shapes, m_invs, _orig_pages)
206
252
  return out
207
-
208
- def _tables_from_regions(
209
- self,
210
- pages: list[np.ndarray],
211
- regions: list[dict[str, Any]],
212
- **kwargs: Any,
213
- ) -> list[list[dict[str, Any]]]:
214
- """Crop the table regions found by the layout model and run the table model on each crop.
215
-
216
- Each `Table` region is rectified to an upright crop with a perspective transform (so straight boxes and
217
- rotated polygons are both handled), the table model is applied per crop, and the predicted cell polygons
218
- are mapped back to page-relative coordinates through the inverse transform. A page therefore yields one
219
- structured table per detected `Table` region.
220
-
221
- Args:
222
- pages: the (possibly straightened) page images
223
- regions: the per-page layout predictions `{"class_names", "boxes", "scores"}`
224
- **kwargs: keyword arguments forwarded to the table predictor
225
-
226
- Returns:
227
- a per-page list of table grids `{"cells": [...], "num_rows": int, "num_cols": int}` in page-relative
228
- coordinates
229
- """
230
- crops: list[np.ndarray] = []
231
- # (page index, inverse transform, crop width, crop height, page width, page height)
232
- crop_meta: list[tuple[int, np.ndarray, int, int, int, int]] = []
233
- for p_idx, (page, region) in enumerate(zip(pages, regions)):
234
- if region is None:
235
- continue
236
- h, w = page.shape[:2]
237
- for cls_name, box in zip(region["class_names"], region["boxes"]):
238
- if cls_name != self.table_class_name:
239
- continue
240
- pts = np.asarray(box, dtype=np.float32).reshape(-1, 2)
241
- if pts.shape[0] == 2: # straight box (x_min, y_min, x_max, y_max) -> corners
242
- (bx0, by0), (bx1, by1) = pts
243
- src = np.array([[bx0, by0], [bx1, by0], [bx1, by1], [bx0, by1]], dtype=np.float32)
244
- else: # rotated 4-point polygon, already ordered (top-left, top-right, bottom-right, bottom-left)
245
- src = pts.copy()
246
- # Relative -> absolute pixel corners
247
- src[:, 0] *= w
248
- src[:, 1] *= h
249
- # Upright crop size from the region side lengths
250
- crop_w = int(round(max(np.linalg.norm(src[1] - src[0]), np.linalg.norm(src[2] - src[3]))))
251
- crop_h = int(round(max(np.linalg.norm(src[3] - src[0]), np.linalg.norm(src[2] - src[1]))))
252
- if crop_w < 2 or crop_h < 2:
253
- continue
254
- # Map the region onto an inset rectangle so the warp samples `pad` extra pixels of page
255
- # context on each side. Crop-relative [0, 1] still maps exactly to [0, out_w] / [0, out_h].
256
- pad = max(20, round(0.01 * max(crop_w, crop_h)))
257
- out_w, out_h = crop_w + 2 * pad, crop_h + 2 * pad
258
- dst = np.array(
259
- [[pad, pad], [pad + crop_w, pad], [pad + crop_w, pad + crop_h], [pad, pad + crop_h]],
260
- dtype=np.float32,
261
- )
262
- transform = cv2.getPerspectiveTransform(src, dst)
263
- inverse = cv2.getPerspectiveTransform(dst, src)
264
- crops.append(cv2.warpPerspective(page, transform, (out_w, out_h), borderMode=cv2.BORDER_REPLICATE))
265
- crop_meta.append((p_idx, inverse, out_w, out_h, w, h))
266
-
267
- tables_per_page: list[list[dict[str, Any]]] = [[] for _ in pages]
268
- if len(crops) == 0:
269
- return tables_per_page
270
-
271
- grids = self.table_predictor(crops, **kwargs) # type: ignore[misc]
272
- for (p_idx, inverse, crop_w, crop_h, w, h), grid in zip(crop_meta, grids):
273
- remapped_cells: list[dict[str, Any]] = []
274
- for cell in grid["cells"]:
275
- # Cell polygon is crop-relative -> crop pixels -> page pixels (inverse transform) -> page-relative
276
- raw = np.asarray(cell["geometry"], dtype=np.float32)
277
- if raw.ndim == 1 and raw.size == 4: # straight box (xmin, ymin, xmax, ymax)
278
- x0, y0, x1, y1 = raw
279
- poly = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]], dtype=np.float32)
280
- else:
281
- poly = raw.reshape(-1, 2)
282
- poly[:, 0] *= crop_w
283
- poly[:, 1] *= crop_h
284
- poly = cv2.perspectiveTransform(poly[None, :, :], inverse)[0]
285
- poly[:, 0] /= w
286
- poly[:, 1] /= h
287
- new_cell = dict(cell)
288
- new_cell["geometry"] = poly.tolist()
289
- remapped_cells.append(new_cell)
290
- if not remapped_cells:
291
- continue
292
- tables_per_page[p_idx].append({
293
- "cells": remapped_cells,
294
- "num_rows": grid["num_rows"],
295
- "num_cols": grid["num_cols"],
296
- })
297
- return tables_per_page