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,6 +3,7 @@
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
9
  import numpy as np
@@ -12,7 +13,10 @@ from torch import nn
12
13
  from doctr.io.elements import Document
13
14
  from doctr.models._utils import get_language
14
15
  from doctr.models.detection.predictor import DetectionPredictor
16
+ from doctr.models.formula.predictor import FormulaPredictor
17
+ from doctr.models.layout.predictor import LayoutPredictor
15
18
  from doctr.models.recognition.predictor import RecognitionPredictor
19
+ from doctr.models.table_structure.predictor import TablePredictor
16
20
  from doctr.utils.geometry import detach_scores
17
21
 
18
22
  from .base import _OCRPredictor
@@ -35,6 +39,17 @@ class OCRPredictor(nn.Module, _OCRPredictor):
35
39
  page. Doing so will slightly deteriorate the overall latency.
36
40
  detect_language: if True, the language prediction will be added to the predictions for each
37
41
  page. Doing so will slightly deteriorate the overall latency.
42
+ preserve_original_coords: if True and straighten_pages is True, the returned bounding boxes are mapped back
43
+ to the original page coordinate space. Useful for redaction and annotation.
44
+ layout_predictor: optional layout detection module
45
+ table_predictor: optional table structure recognition module. Requires `layout_predictor`: table
46
+ regions are located by the layout model, cropped, and passed to this module. Words falling inside a
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.
38
53
  **kwargs: keyword args of `DocumentBuilder`
39
54
  """
40
55
 
@@ -48,6 +63,10 @@ class OCRPredictor(nn.Module, _OCRPredictor):
48
63
  symmetric_pad: bool = True,
49
64
  detect_orientation: bool = False,
50
65
  detect_language: bool = False,
66
+ preserve_original_coords: bool = False,
67
+ layout_predictor: LayoutPredictor | None = None,
68
+ table_predictor: TablePredictor | None = None,
69
+ formula_predictor: FormulaPredictor | None = None,
51
70
  **kwargs: Any,
52
71
  ) -> None:
53
72
  nn.Module.__init__(self)
@@ -60,31 +79,80 @@ class OCRPredictor(nn.Module, _OCRPredictor):
60
79
  preserve_aspect_ratio,
61
80
  symmetric_pad,
62
81
  detect_orientation,
82
+ preserve_original_coords=preserve_original_coords,
63
83
  **kwargs,
64
84
  )
65
85
  self.detect_orientation = detect_orientation
66
86
  self.detect_language = detect_language
87
+ self.layout_predictor = layout_predictor.eval() if layout_predictor is not None else None
88
+ self.table_predictor = table_predictor.eval() if table_predictor is not None else None
89
+ # Layout class label whose regions are cropped and passed to the table model
90
+ self.table_class_name = "Table"
91
+ if self.table_predictor is not None and self.layout_predictor is None:
92
+ raise ValueError(
93
+ "`table_predictor` requires a `layout_predictor`: tables are located with the layout model, "
94
+ "cropped, and then passed to the table model."
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
+ )
67
104
 
68
105
  @torch.inference_mode()
69
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(
70
127
  self,
71
128
  pages: list[np.ndarray],
72
129
  **kwargs: Any,
73
130
  ) -> Document:
131
+ if len(pages) == 0:
132
+ return Document(pages=[])
133
+
74
134
  # Dimension check
75
135
  if any(page.ndim != 3 for page in pages):
76
136
  raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
77
137
 
78
138
  origin_page_shapes = [page.shape[:2] for page in pages]
79
139
 
80
- # Localize text elements
81
- loc_preds, out_maps = self.det_predictor(pages, return_maps=True, **kwargs)
140
+ if not self.straighten_pages:
141
+ # Detect layout regions on the pages
142
+ regions = self.layout_predictor(pages, **kwargs) if self.layout_predictor is not None else None
143
+ det_pages = self._mask_regions(pages, regions)
144
+ else:
145
+ det_pages = pages
146
+
147
+ # Localize text elements (segmentation maps are only materialized when actually consumed)
148
+ if self.detect_orientation or self.straighten_pages:
149
+ loc_preds, out_maps = self.det_predictor(det_pages, return_maps=True, **kwargs)
150
+ bin_thresh = getattr(self.det_predictor.model.postprocessor, "bin_thresh")
151
+ seg_maps = [((out_map > bin_thresh).astype(np.uint8) * 255) for out_map in out_maps]
152
+ else:
153
+ loc_preds = self.det_predictor(det_pages, **kwargs)
82
154
 
83
155
  # Detect document rotation and rotate pages
84
- seg_maps = [
85
- np.where(out_map > getattr(self.det_predictor.model.postprocessor, "bin_thresh"), 255, 0).astype(np.uint8)
86
- for out_map in out_maps
87
- ]
88
156
  if self.detect_orientation:
89
157
  general_pages_orientations, origin_pages_orientations = self._get_orientations(pages, seg_maps)
90
158
  orientations = [
@@ -95,12 +163,21 @@ class OCRPredictor(nn.Module, _OCRPredictor):
95
163
  general_pages_orientations = None
96
164
  origin_pages_orientations = None
97
165
  if self.straighten_pages:
98
- pages = self._straighten_pages(pages, seg_maps, general_pages_orientations, origin_pages_orientations)
166
+ _orig_shapes = origin_page_shapes
167
+ _orig_pages = list(pages)
168
+ pages, m_invs = self._straighten_pages(
169
+ pages, seg_maps, general_pages_orientations, origin_pages_orientations
170
+ )
99
171
  # update page shapes after straightening
100
172
  origin_page_shapes = [page.shape[:2] for page in pages]
173
+ _straight_shapes = origin_page_shapes
174
+
175
+ # Detect layout regions on the pages
176
+ regions = self.layout_predictor(pages, **kwargs) if self.layout_predictor is not None else None
177
+ det_pages = self._mask_regions(pages, regions)
101
178
 
102
179
  # Forward again to get predictions on straight pages
103
- loc_preds = self.det_predictor(pages, **kwargs)
180
+ loc_preds = self._detect_straightened(loc_preds, _orig_pages, pages, det_pages, **kwargs)
104
181
 
105
182
  assert all(len(loc_pred) == 1 for loc_pred in loc_preds), (
106
183
  "Detection Model in ocr_predictor should output only one class"
@@ -110,17 +187,18 @@ class OCRPredictor(nn.Module, _OCRPredictor):
110
187
  # Detach objectness scores from loc_preds
111
188
  loc_preds, objectness_scores = detach_scores(loc_preds)
112
189
 
113
- # Apply hooks to loc_preds if any
114
- for hook in self.hooks:
115
- 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)
116
192
 
117
193
  # Crop images
118
- crops, loc_preds = self._prepare_crops(
194
+ crops, loc_preds, objectness_scores = self._prepare_crops(
119
195
  pages,
120
196
  loc_preds,
197
+ objectness_scores,
121
198
  assume_straight_pages=self.assume_straight_pages,
122
199
  assume_horizontal=self._page_orientation_disabled,
123
200
  )
201
+
124
202
  # Rectify crop orientation and get crop orientation predictions
125
203
  crop_orientations: Any = []
126
204
  if not self.assume_straight_pages:
@@ -142,6 +220,19 @@ class OCRPredictor(nn.Module, _OCRPredictor):
142
220
  else:
143
221
  languages_dict = None
144
222
 
223
+ # Recognize table structure: locate tables with the layout model, crop each one and run the table model
224
+ tables = (
225
+ self.table_predictor.predict_regions(pages, regions, boxes, self.table_class_name, **kwargs)
226
+ if self.table_predictor is not None and regions is not None
227
+ else None
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
+ )
235
+
145
236
  out = self.doc_builder(
146
237
  pages,
147
238
  boxes,
@@ -151,5 +242,11 @@ class OCRPredictor(nn.Module, _OCRPredictor):
151
242
  crop_orientations,
152
243
  orientations,
153
244
  languages_dict,
245
+ regions,
246
+ tables,
247
+ formulas,
154
248
  )
249
+
250
+ if self.straighten_pages and self.preserve_original_coords:
251
+ out = self._remap_to_original_coords(out, _orig_shapes, _straight_shapes, m_invs, _orig_pages)
155
252
  return out
@@ -4,7 +4,7 @@
4
4
  # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
5
 
6
6
  import math
7
- from typing import Any
7
+ from typing import Any, overload
8
8
 
9
9
  import numpy as np
10
10
  import torch
@@ -13,11 +13,20 @@ from torchvision.transforms import functional as F
13
13
  from torchvision.transforms import transforms as T
14
14
 
15
15
  from doctr.transforms import Resize
16
- from doctr.utils.multithreading import multithread_exec
16
+ from doctr.utils import Sample
17
17
 
18
18
  __all__ = ["PreProcessor"]
19
19
 
20
20
 
21
+ def _torch_compatible(x: np.ndarray) -> np.ndarray:
22
+ """Make an array readable by `torch.from_numpy`, which requires a writable buffer without negative strides.
23
+ `np.ascontiguousarray` is not enough: it keeps a negative stride on an axis of size 1 (e.g. `np.rot90` of a crop
24
+ of 1 pixel in height, as rectified crops can be), which numpy still considers contiguous."""
25
+ if not x.flags.writeable or any(stride < 0 for stride in x.strides):
26
+ return x.copy()
27
+ return np.ascontiguousarray(x)
28
+
29
+
21
30
  class PreProcessor(nn.Module):
22
31
  """Implements an abstract preprocessor object which performs casting, resizing, batching and normalization.
23
32
 
@@ -43,47 +52,85 @@ class PreProcessor(nn.Module):
43
52
  # Perform the division by 255 at the same time
44
53
  self.normalize = T.Normalize(mean, std)
45
54
 
46
- def batch_inputs(self, samples: list[torch.Tensor]) -> list[torch.Tensor]:
55
+ @overload
56
+ def batch_inputs(
57
+ self,
58
+ samples: list[torch.Tensor],
59
+ ) -> list[torch.Tensor]: ...
60
+
61
+ @overload
62
+ def batch_inputs(
63
+ self,
64
+ samples: list[tuple[torch.Tensor, torch.Tensor]],
65
+ ) -> tuple[list[torch.Tensor], list[torch.Tensor]]: ...
66
+
67
+ def batch_inputs(
68
+ self, samples: list[torch.Tensor] | list[tuple[torch.Tensor, torch.Tensor]]
69
+ ) -> list[torch.Tensor] | tuple[list[torch.Tensor], list[torch.Tensor]]:
47
70
  """Gather samples into batches for inference purposes
48
71
 
49
72
  Args:
50
- samples: list of samples of shape (C, H, W)
73
+ samples: list of samples of shape (C, H, W) or
74
+ list of tuples of samples and masks of shape (C, H, W) and (1, H, W) respectively
51
75
 
52
76
  Returns:
53
- list of batched samples (*, C, H, W)
77
+ list of batched samples (*, C, H, W) or tuple of lists of batched samples and masks
54
78
  """
55
79
  num_batches = int(math.ceil(len(samples) / self.batch_size))
56
- batches = [
57
- torch.stack(samples[idx * self.batch_size : min((idx + 1) * self.batch_size, len(samples))], dim=0)
58
- for idx in range(int(num_batches))
59
- ]
60
80
 
61
- return batches
81
+ if isinstance(samples[0], tuple):
82
+ imgs, masks = zip(*samples)
83
+
84
+ img_batches = [
85
+ torch.stack(imgs[idx * self.batch_size : min((idx + 1) * self.batch_size, len(imgs))], dim=0)
86
+ for idx in range(num_batches)
87
+ ]
62
88
 
63
- def sample_transforms(self, x: np.ndarray) -> torch.Tensor:
89
+ mask_batches = [
90
+ torch.stack(masks[idx * self.batch_size : min((idx + 1) * self.batch_size, len(masks))], dim=0)
91
+ for idx in range(num_batches)
92
+ ]
93
+
94
+ return img_batches, mask_batches
95
+
96
+ return [
97
+ torch.stack(
98
+ samples[idx * self.batch_size : min((idx + 1) * self.batch_size, len(samples))],
99
+ dim=0,
100
+ )
101
+ for idx in range(num_batches)
102
+ ]
103
+
104
+ def sample_transforms(self, x: np.ndarray) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
64
105
  if x.ndim != 3:
65
106
  raise AssertionError("expected list of 3D Tensors")
66
107
  if x.dtype not in (np.uint8, np.float32, np.float16):
67
108
  raise TypeError("unsupported data type for numpy.ndarray")
68
- tensor = torch.from_numpy(x.copy()).permute(2, 0, 1)
109
+ tensor = torch.from_numpy(_torch_compatible(x)).permute(2, 0, 1)
69
110
  # Resizing
70
- tensor = self.resize(tensor)
111
+ if self.resize.return_padding_mask:
112
+ sample = self.resize(Sample(image=tensor))
113
+ tensor, mask = sample.image, sample.mask
114
+ else:
115
+ tensor = self.resize(Sample(image=tensor)).image
71
116
  # Data type
72
117
  if tensor.dtype == torch.uint8:
73
- tensor = tensor.to(dtype=torch.float32).div(255).clip(0, 1)
118
+ tensor = tensor.to(dtype=torch.float32).div(255)
74
119
  else:
75
120
  tensor = tensor.to(dtype=torch.float32)
76
121
 
77
- return tensor
122
+ return (tensor, mask) if self.resize.return_padding_mask else tensor
78
123
 
79
- def __call__(self, x: np.ndarray | list[np.ndarray]) -> list[torch.Tensor]:
124
+ def __call__(
125
+ self, x: np.ndarray | list[np.ndarray]
126
+ ) -> list[torch.Tensor] | tuple[list[torch.Tensor], list[torch.Tensor]]:
80
127
  """Prepare document data for model forwarding
81
128
 
82
129
  Args:
83
130
  x: list of images (np.array) or a single image (np.array) of shape (H, W, C)
84
131
 
85
132
  Returns:
86
- list of page batches (*, C, H, W) ready for model inference
133
+ list of page batches (*, C, H, W) or tuple of lists of page batches and padding masks
87
134
  """
88
135
  # Input type check
89
136
  if isinstance(x, np.ndarray):
@@ -91,7 +138,7 @@ class PreProcessor(nn.Module):
91
138
  raise AssertionError("expected 4D Tensor")
92
139
  if x.dtype not in (np.uint8, np.float32, np.float16):
93
140
  raise TypeError("unsupported data type for numpy.ndarray")
94
- tensor = torch.from_numpy(x.copy()).permute(0, 3, 1, 2)
141
+ tensor = torch.from_numpy(_torch_compatible(x)).permute(0, 3, 1, 2)
95
142
 
96
143
  # Resizing
97
144
  if tensor.shape[-2] != self.resize.size[0] or tensor.shape[-1] != self.resize.size[1]:
@@ -100,20 +147,30 @@ class PreProcessor(nn.Module):
100
147
  )
101
148
  # Data type
102
149
  if tensor.dtype == torch.uint8:
103
- tensor = tensor.to(dtype=torch.float32).div(255).clip(0, 1)
150
+ tensor = tensor.to(dtype=torch.float32).div(255)
104
151
  else:
105
152
  tensor = tensor.to(dtype=torch.float32)
106
- batches = [tensor]
153
+ img_batches = [tensor]
154
+
155
+ if self.resize.return_padding_mask:
156
+ # Plain (stretching) resize adds no padding: every pixel is valid image content
157
+ h, w = self.resize.size
158
+ mask = torch.ones((x.shape[0], h, w), dtype=torch.bool)
159
+ mask_batches = [mask]
107
160
 
108
161
  elif isinstance(x, list) and all(isinstance(sample, np.ndarray) for sample in x):
109
162
  # Sample transform (to tensor, resize)
110
- samples = list(multithread_exec(self.sample_transforms, x))
163
+ samples: Any = [self.sample_transforms(sample) for sample in x]
111
164
  # Batching
112
- batches = self.batch_inputs(samples)
165
+ if self.resize.return_padding_mask:
166
+ img_batches, mask_batches = self.batch_inputs(samples)
167
+ else:
168
+ img_batches = self.batch_inputs(samples)
113
169
  else:
114
170
  raise TypeError(f"invalid input type: {type(x)}")
115
171
 
116
172
  # Batch transforms (normalize)
117
- batches = list(multithread_exec(self.normalize, batches))
118
-
119
- return batches
173
+ img_batches = [self.normalize(batch) for batch in img_batches]
174
+ if self.resize.return_padding_mask:
175
+ return img_batches, mask_batches
176
+ return img_batches
@@ -0,0 +1 @@
1
+ from .base import *