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
@@ -12,6 +12,7 @@ import pyclipper
12
12
  from shapely.geometry import Polygon
13
13
 
14
14
  from doctr.models.core import BaseModel
15
+ from doctr.utils import order_points
15
16
 
16
17
  from ..core import DetectionPostProcessor
17
18
 
@@ -78,7 +79,7 @@ class FASTPostProcessor(DetectionPostProcessor):
78
79
  return (
79
80
  cv2.boundingRect(expanded_points) # type: ignore[return-value]
80
81
  if self.assume_straight_pages
81
- else np.roll(cv2.boxPoints(cv2.minAreaRect(expanded_points)), -1, axis=0)
82
+ else order_points(cv2.boxPoints(cv2.minAreaRect(expanded_points)))
82
83
  )
83
84
 
84
85
  def bitmap_to_boxes(
@@ -91,8 +92,6 @@ class FASTPostProcessor(DetectionPostProcessor):
91
92
  Args:
92
93
  pred: Pred map from differentiable linknet output
93
94
  bitmap: Bitmap map computed from pred (binarized)
94
- angle_tol: Comparison tolerance of the angle with the median angle across the page
95
- ratio_tol: Under this limit aspect ratio, we cannot resolve the direction of the crop
96
95
 
97
96
  Returns:
98
97
  np tensor boxes for the bitmap, each box is a 6-element list
@@ -122,6 +121,9 @@ class FASTPostProcessor(DetectionPostProcessor):
122
121
  else:
123
122
  _box = self.polygon_to_box(np.squeeze(contour))
124
123
 
124
+ if _box is None: # pragma: no cover
125
+ continue
126
+
125
127
  if self.assume_straight_pages:
126
128
  # compute relative polygon to get rid of img shape
127
129
  x, y, w, h = _box
@@ -146,6 +148,8 @@ class _FAST(BaseModel):
146
148
  """
147
149
 
148
150
  min_size_box: int = 3
151
+ mask_empty_classes: bool = False
152
+ class_names: list[str] # set by the framework model
149
153
  assume_straight_pages: bool = True
150
154
  shrink_ratio = 0.4
151
155
 
@@ -179,10 +183,22 @@ class _FAST(BaseModel):
179
183
  shrunken_kernel: np.ndarray = np.zeros(target_shape, dtype=np.uint8)
180
184
 
181
185
  for idx, tgt in enumerate(target):
182
- for class_idx, _tgt in enumerate(tgt.values()):
186
+ unknown = set(tgt) - set(self.class_names)
187
+ missing = set(self.class_names) - set(tgt)
188
+ if unknown or missing:
189
+ raise ValueError(
190
+ f"target classes {sorted(tgt)} do not match the model classes {list(self.class_names)}"
191
+ + (f" (unknown: {sorted(unknown)})" if unknown else "")
192
+ + (f" (missing: {sorted(missing)})" if missing else "")
193
+ )
194
+ # Channels follow the order of the model's class names, whatever the order of the target dict
195
+ for class_idx, class_name in enumerate(self.class_names):
196
+ _tgt = tgt[class_name]
183
197
  # Draw each polygon on gt
184
- if _tgt.shape[0] == 0:
185
- # Empty image, full masked
198
+ if _tgt.shape[0] == 0 and self.mask_empty_classes:
199
+ # No box for this class: with `mask_empty_classes` the channel is ignored by the loss (partially
200
+ # annotated data); by default it is supervised as background, an image without any box being
201
+ # a true negative
186
202
  seg_mask[idx, class_idx] = False
187
203
 
188
204
  # Absolute bounding boxes
@@ -112,6 +112,8 @@ class FAST(_FAST, nn.Module):
112
112
  exportable: onnx exportable returns only logits
113
113
  cfg: the configuration dict of the model
114
114
  class_names: list of class names
115
+ mask_empty_classes: if True, a class without any box in an image is masked out of the loss (use it for
116
+ partially annotated data); by default the absence is supervised as background
115
117
  """
116
118
 
117
119
  def __init__(
@@ -125,9 +127,11 @@ class FAST(_FAST, nn.Module):
125
127
  exportable: bool = False,
126
128
  cfg: dict[str, Any] = {},
127
129
  class_names: list[str] = [CLASS_NAME],
130
+ mask_empty_classes: bool = False,
128
131
  ) -> None:
129
132
  super().__init__()
130
133
  self.class_names = class_names
134
+ self.mask_empty_classes = mask_empty_classes
131
135
  num_classes: int = len(self.class_names)
132
136
  self.cfg = cfg
133
137
 
@@ -265,12 +269,13 @@ class FAST(_FAST, nn.Module):
265
269
  # combine all masks to shape (len(masks), H, W)
266
270
  return torch.stack(masks).unsqueeze(0).float()
267
271
 
268
- if len(self.class_names) > 1:
269
- kernels = torch.softmax(out_map, dim=1)
270
- prob_map = torch.softmax(self.pooling(out_map), dim=1)
271
- else:
272
- kernels = torch.sigmoid(out_map)
273
- prob_map = torch.sigmoid(self.pooling(out_map))
272
+ pooled_logits = self.pooling(out_map)
273
+ kernels = torch.sigmoid(out_map)
274
+ prob_map = torch.sigmoid(pooled_logits)
275
+
276
+ def masked_class_mean(per_class: torch.Tensor, valid: torch.Tensor) -> torch.Tensor:
277
+ # Average over the classes that have something to supervise; a graph-preserving zero if none has
278
+ return (per_class * valid).sum() / valid.sum().clamp(min=1)
274
279
 
275
280
  # As described in the paper, we use the Dice loss for the text segmentation map and the Dice loss scaled by 0.5.
276
281
  selected_masks = torch.cat(
@@ -278,13 +283,21 @@ class FAST(_FAST, nn.Module):
278
283
  ).float()
279
284
  inter = (selected_masks * prob_map * seg_target).sum((0, 2, 3))
280
285
  cardinality = (selected_masks * (prob_map + seg_target)).sum((0, 2, 3))
281
- text_loss = (1 - 2 * inter / (cardinality + eps)).mean() * 0.5
286
+ text_dice = 1 - 2 * inter / (cardinality + eps)
287
+ # With no positive pixel in the batch, Dice is a constant with zero gradient: false positives of that class
288
+ # would never be penalised. Supervise such classes as background with a BCE on the selected pixels instead.
289
+ num_selected = selected_masks.sum((0, 2, 3))
290
+ has_pos = (selected_masks * seg_target).sum((0, 2, 3)) > 0
291
+ neg_bce = (selected_masks * F.softplus(pooled_logits)).sum((0, 2, 3)) / num_selected.clamp(min=1)
292
+ text_loss = masked_class_mean(torch.where(has_pos, text_dice, neg_bce), num_selected > 0) * 0.5
282
293
 
283
294
  # As described in the paper, we use the Dice loss for the text kernel map.
284
295
  selected_masks = seg_target * seg_mask
285
296
  inter = (selected_masks * kernels * shrunken_kernel).sum((0, 2, 3)) # noqa
286
297
  cardinality = (selected_masks * (kernels + shrunken_kernel)).sum((0, 2, 3)) # noqa
287
- kernel_loss = (1 - 2 * inter / (cardinality + eps)).mean()
298
+ # The kernel map is only defined inside text regions: skip the classes without any in the batch
299
+ kernel_dice = 1 - 2 * inter / (cardinality + eps)
300
+ kernel_loss = masked_class_mean(kernel_dice, selected_masks.sum((0, 2, 3)) > 0)
288
301
 
289
302
  return text_loss + kernel_loss
290
303
 
@@ -374,7 +387,7 @@ def fast_tiny(pretrained: bool = False, **kwargs: Any) -> FAST:
374
387
  >>> out = model(input_tensor)
375
388
 
376
389
  Args:
377
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
390
+ pretrained: If True, returns a model pre-trained on our text detection dataset
378
391
  **kwargs: keyword arguments of the DBNet architecture
379
392
 
380
393
  Returns:
@@ -401,7 +414,7 @@ def fast_small(pretrained: bool = False, **kwargs: Any) -> FAST:
401
414
  >>> out = model(input_tensor)
402
415
 
403
416
  Args:
404
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
417
+ pretrained: If True, returns a model pre-trained on our text detection dataset
405
418
  **kwargs: keyword arguments of the DBNet architecture
406
419
 
407
420
  Returns:
@@ -428,7 +441,7 @@ def fast_base(pretrained: bool = False, **kwargs: Any) -> FAST:
428
441
  >>> out = model(input_tensor)
429
442
 
430
443
  Args:
431
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
444
+ pretrained: If True, returns a model pre-trained on our text detection dataset
432
445
  **kwargs: keyword arguments of the DBNet architecture
433
446
 
434
447
  Returns:
@@ -12,6 +12,7 @@ import pyclipper
12
12
  from shapely.geometry import Polygon
13
13
 
14
14
  from doctr.models.core import BaseModel
15
+ from doctr.utils import order_points
15
16
 
16
17
  from ..core import DetectionPostProcessor
17
18
 
@@ -78,7 +79,7 @@ class LinkNetPostProcessor(DetectionPostProcessor):
78
79
  return (
79
80
  cv2.boundingRect(expanded_points) # type: ignore[return-value]
80
81
  if self.assume_straight_pages
81
- else np.roll(cv2.boxPoints(cv2.minAreaRect(expanded_points)), -1, axis=0)
82
+ else order_points(cv2.boxPoints(cv2.minAreaRect(expanded_points)))
82
83
  )
83
84
 
84
85
  def bitmap_to_boxes(
@@ -91,8 +92,6 @@ class LinkNetPostProcessor(DetectionPostProcessor):
91
92
  Args:
92
93
  pred: Pred map from differentiable linknet output
93
94
  bitmap: Bitmap map computed from pred (binarized)
94
- angle_tol: Comparison tolerance of the angle with the median angle across the page
95
- ratio_tol: Under this limit aspect ratio, we cannot resolve the direction of the crop
96
95
 
97
96
  Returns:
98
97
  np tensor boxes for the bitmap, each box is a 6-element list
@@ -122,6 +121,9 @@ class LinkNetPostProcessor(DetectionPostProcessor):
122
121
  else:
123
122
  _box = self.polygon_to_box(np.squeeze(contour))
124
123
 
124
+ if _box is None: # pragma: no cover
125
+ continue
126
+
125
127
  if self.assume_straight_pages:
126
128
  # compute relative polygon to get rid of img shape
127
129
  x, y, w, h = _box
@@ -150,6 +152,8 @@ class _LinkNet(BaseModel):
150
152
 
151
153
  min_size_box: int = 3
152
154
  assume_straight_pages: bool = True
155
+ mask_empty_classes: bool = False
156
+ class_names: list[str] # set by the framework model
153
157
  shrink_ratio = 0.5
154
158
 
155
159
  def build_target(
@@ -181,10 +185,22 @@ class _LinkNet(BaseModel):
181
185
  seg_mask: np.ndarray = np.ones(target_shape, dtype=bool)
182
186
 
183
187
  for idx, tgt in enumerate(target):
184
- for class_idx, _tgt in enumerate(tgt.values()):
188
+ unknown = set(tgt) - set(self.class_names)
189
+ missing = set(self.class_names) - set(tgt)
190
+ if unknown or missing:
191
+ raise ValueError(
192
+ f"target classes {sorted(tgt)} do not match the model classes {list(self.class_names)}"
193
+ + (f" (unknown: {sorted(unknown)})" if unknown else "")
194
+ + (f" (missing: {sorted(missing)})" if missing else "")
195
+ )
196
+ # Channels follow the order of the model's class names, whatever the order of the target dict
197
+ for class_idx, class_name in enumerate(self.class_names):
198
+ _tgt = tgt[class_name]
185
199
  # Draw each polygon on gt
186
- if _tgt.shape[0] == 0:
187
- # Empty image, full masked
200
+ if _tgt.shape[0] == 0 and self.mask_empty_classes:
201
+ # No box for this class: with `mask_empty_classes` the channel is ignored by the loss (partially
202
+ # annotated data); by default it is supervised as background, an image without any box being
203
+ # a true negative
188
204
  seg_mask[idx, class_idx] = False
189
205
 
190
206
  # Absolute bounding boxes
@@ -98,6 +98,8 @@ class LinkNet(nn.Module, _LinkNet):
98
98
  exportable: onnx exportable returns only logits
99
99
  cfg: the configuration dict of the model
100
100
  class_names: list of class names
101
+ mask_empty_classes: if True, a class without any box in an image is masked out of the loss (use it for
102
+ partially annotated data); by default the absence is supervised as background
101
103
  """
102
104
 
103
105
  def __init__(
@@ -110,9 +112,11 @@ class LinkNet(nn.Module, _LinkNet):
110
112
  exportable: bool = False,
111
113
  cfg: dict[str, Any] | None = None,
112
114
  class_names: list[str] = [CLASS_NAME],
115
+ mask_empty_classes: bool = False,
113
116
  ) -> None:
114
117
  super().__init__()
115
118
  self.class_names = class_names
119
+ self.mask_empty_classes = mask_empty_classes
116
120
  num_classes: int = len(self.class_names)
117
121
  self.cfg = cfg
118
122
  self.exportable = exportable
@@ -235,6 +239,9 @@ class LinkNet(nn.Module, _LinkNet):
235
239
  seg_target, seg_mask = torch.from_numpy(_target).to(dtype=out_map.dtype), torch.from_numpy(_mask)
236
240
  seg_target, seg_mask = seg_target.to(out_map.device), seg_mask.to(out_map.device)
237
241
  seg_mask = seg_mask.to(dtype=torch.float32)
242
+ if not torch.any(seg_mask):
243
+ # Fully masked batch: nothing to supervise
244
+ return out_map.sum() * 0
238
245
 
239
246
  bce_loss = F.binary_cross_entropy_with_logits(out_map, seg_target, reduction="none")
240
247
  proba_map = torch.sigmoid(out_map)
@@ -307,7 +314,7 @@ def linknet_resnet18(pretrained: bool = False, **kwargs: Any) -> LinkNet:
307
314
  >>> out = model(input_tensor)
308
315
 
309
316
  Args:
310
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
317
+ pretrained: If True, returns a model pre-trained on our text detection dataset
311
318
  **kwargs: keyword arguments of the LinkNet architecture
312
319
 
313
320
  Returns:
@@ -337,7 +344,7 @@ def linknet_resnet34(pretrained: bool = False, **kwargs: Any) -> LinkNet:
337
344
  >>> out = model(input_tensor)
338
345
 
339
346
  Args:
340
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
347
+ pretrained: If True, returns a model pre-trained on our text detection dataset
341
348
  **kwargs: keyword arguments of the LinkNet architecture
342
349
 
343
350
  Returns:
@@ -367,7 +374,7 @@ def linknet_resnet50(pretrained: bool = False, **kwargs: Any) -> LinkNet:
367
374
  >>> out = model(input_tensor)
368
375
 
369
376
  Args:
370
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
377
+ pretrained: If True, returns a model pre-trained on our text detection dataset
371
378
  **kwargs: keyword arguments of the LinkNet architecture
372
379
 
373
380
  Returns:
@@ -3,12 +3,15 @@
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
7
+ from functools import partial
6
8
  from typing import Any
7
9
 
8
10
  import numpy as np
9
11
  import torch
10
12
  from torch import nn
11
13
 
14
+ from doctr.models._utils import merge_columns, merge_items, predict_by_chunks
12
15
  from doctr.models.detection._utils import _remove_padding
13
16
  from doctr.models.preprocessor import PreProcessor
14
17
  from doctr.models.utils import set_device_and_dtype
@@ -22,24 +25,61 @@ class DetectionPredictor(nn.Module):
22
25
  Args:
23
26
  pre_processor: transform inputs for easier batched model inference
24
27
  model: core detection architecture
28
+ chunk_size: the maximum number of pages decoded and processed at once (32 by default). Longer
29
+ inputs, lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) and iterators are processed
30
+ chunk by chunk, with a memory footprint that does not grow with the number of pages. It is rounded
31
+ up to a multiple of the batch size, so that the predictions are the same as in a single pass.
25
32
  """
26
33
 
27
34
  def __init__(
28
35
  self,
29
36
  pre_processor: PreProcessor,
30
37
  model: nn.Module,
38
+ chunk_size: int = 32,
31
39
  ) -> None:
32
40
  super().__init__()
33
41
  self.pre_processor = pre_processor
34
42
  self.model = model.eval()
43
+ if chunk_size < 1:
44
+ raise ValueError("`chunk_size` must be a positive integer")
45
+ self.chunk_size = chunk_size
35
46
 
36
47
  @torch.inference_mode()
37
48
  def forward(
49
+ self,
50
+ pages: Sequence[np.ndarray] | Iterable[np.ndarray],
51
+ return_maps: bool = False,
52
+ **kwargs: Any,
53
+ ) -> list[dict[str, np.ndarray]] | tuple[list[dict[str, np.ndarray]], list[np.ndarray]]:
54
+ """Localize the text elements of pages
55
+
56
+ Args:
57
+ pages: a list of pages (numpy arrays of shape H x W x C), a lazy page source
58
+ (cf. `DocumentFile.from_pdf(..., lazy=True)`) or any iterable of pages
59
+ return_maps: whether to also return the segmentation map of each page
60
+ **kwargs: keyword arguments forwarded to the model
61
+
62
+ Returns:
63
+ the predictions of each page, and their segmentation maps if `return_maps` is True
64
+ """
65
+ return predict_by_chunks(
66
+ partial(self._predict, return_maps=return_maps, **kwargs),
67
+ pages,
68
+ self.chunk_size,
69
+ self.pre_processor.batch_size,
70
+ merge=merge_columns if return_maps else merge_items,
71
+ )
72
+
73
+ @torch.inference_mode()
74
+ def _predict(
38
75
  self,
39
76
  pages: list[np.ndarray],
40
77
  return_maps: bool = False,
41
78
  **kwargs: Any,
42
79
  ) -> list[dict[str, np.ndarray]] | tuple[list[dict[str, np.ndarray]], list[np.ndarray]]:
80
+ if len(pages) == 0:
81
+ return ([], []) if return_maps else []
82
+
43
83
  # Extract parameters from the preprocessor
44
84
  preserve_aspect_ratio = self.pre_processor.resize.preserve_aspect_ratio
45
85
  symmetric_pad = self.pre_processor.resize.symmetric_pad
@@ -51,11 +91,12 @@ class DetectionPredictor(nn.Module):
51
91
 
52
92
  processed_batches = self.pre_processor(pages)
53
93
  _params = next(self.model.parameters())
54
- self.model, processed_batches = set_device_and_dtype(
94
+ self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
55
95
  self.model, processed_batches, _params.device, _params.dtype
56
96
  )
57
97
  predicted_batches = [
58
- self.model(batch, return_preds=True, return_model_output=True, **kwargs) for batch in processed_batches
98
+ self.model(batch, return_preds=True, return_model_output=return_maps, **kwargs)
99
+ for batch in processed_batches
59
100
  ]
60
101
  # Remove padding from loc predictions
61
102
  preds = _remove_padding(
@@ -50,17 +50,19 @@ def _predictor(arch: Any, pretrained: bool, assume_straight_pages: bool = True,
50
50
  raise ValueError(f"unknown architecture: {type(arch)}")
51
51
 
52
52
  _model = arch
53
- _model.assume_straight_pages = assume_straight_pages
54
- _model.postprocessor.assume_straight_pages = assume_straight_pages
53
+ _model.assume_straight_pages = assume_straight_pages # type: ignore[attr-defined]
54
+ _model.postprocessor.assume_straight_pages = assume_straight_pages # type: ignore[attr-defined]
55
55
 
56
56
  kwargs.pop("pretrained_backbone", None)
57
57
 
58
58
  kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
59
59
  kwargs["std"] = kwargs.get("std", _model.cfg["std"])
60
60
  kwargs["batch_size"] = kwargs.get("batch_size", 2)
61
+ chunk_size = kwargs.pop("chunk_size", 32)
61
62
  predictor = DetectionPredictor(
62
63
  PreProcessor(_model.cfg["input_shape"][1:], **kwargs),
63
64
  _model,
65
+ chunk_size=chunk_size,
64
66
  )
65
67
  return predictor
66
68
 
@@ -90,6 +92,8 @@ def detection_predictor(
90
92
  running the detection model on it
91
93
  symmetric_pad: if True, pad the image symmetrically instead of padding at the bottom-right
92
94
  batch_size: number of samples the model processes in parallel
95
+ chunk_size: maximum number of pages decoded and processed at once (32 by default): longer inputs and
96
+ lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
93
97
  **kwargs: optional keyword arguments passed to the architecture
94
98
 
95
99
  Returns:
@@ -9,7 +9,6 @@ import json
9
9
  import logging
10
10
  import subprocess
11
11
  import tempfile
12
- import textwrap
13
12
  from pathlib import Path
14
13
  from typing import Any
15
14
 
@@ -25,11 +24,16 @@ from doctr import models
25
24
 
26
25
  __all__ = ["login_to_hub", "push_to_hf_hub", "from_hub", "_save_model_and_config_for_hf_hub"]
27
26
 
27
+ logger = logging.getLogger(__name__)
28
+
28
29
 
29
30
  AVAILABLE_ARCHS = {
30
31
  "classification": models.classification.zoo.ARCHS + models.classification.zoo.ORIENTATION_ARCHS,
31
32
  "detection": models.detection.zoo.ARCHS,
32
33
  "recognition": models.recognition.zoo.ARCHS,
34
+ "layout": models.layout.zoo.ARCHS,
35
+ "table_structure": models.table_structure.zoo.ARCHS,
36
+ "formula": models.formula.zoo.ARCHS,
33
37
  }
34
38
 
35
39
 
@@ -37,7 +41,7 @@ def login_to_hub() -> None: # pragma: no cover
37
41
  """Login to huggingface hub"""
38
42
  access_token = get_token()
39
43
  if access_token is not None:
40
- logging.info("Huggingface Hub token found and valid")
44
+ logger.info("Huggingface Hub token found and valid")
41
45
  login(token=access_token)
42
46
  else:
43
47
  login()
@@ -96,60 +100,66 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
96
100
 
97
101
  if run_config is None and arch is None:
98
102
  raise ValueError("run_config or arch must be specified")
99
- if task not in ["classification", "detection", "recognition"]:
100
- raise ValueError("task must be one of classification, detection, recognition")
103
+ if task not in ["classification", "detection", "recognition", "layout", "table_structure", "formula"]:
104
+ raise ValueError("task must be one of classification, detection, recognition, layout, table_structure, formula")
101
105
 
102
106
  # default readme
103
- readme = textwrap.dedent(
104
- f"""
105
-
106
- language: en
107
+ readme = f"""---
108
+ language: en
109
+ tags:
110
+ - ocr
111
+ - pytorch
112
+ - doctr
113
+ - {task}
114
+ ---
107
115
 
108
116
 
109
- <p align="center">
110
- <img src="https://doctr-static.mindee.com/models?id=v0.3.1/Logo_doctr.gif&src=0" width="60%">
111
- </p>
117
+ <p align="center">
118
+ <img src="https://doctr-static.mindee.com/models?id=v0.3.1/Logo_doctr.gif&src=0" width="60%">
119
+ </p>
112
120
 
113
- **Optical Character Recognition made seamless & accessible to anyone, powered by PyTorch**
121
+ **Optical Character Recognition made seamless & accessible to anyone, powered by PyTorch**
114
122
 
115
- ## Task: {task}
123
+ ## Task: {task}
116
124
 
117
- https://github.com/mindee/doctr
125
+ https://github.com/mindee/doctr
118
126
 
119
- ### Example usage:
127
+ ### Example usage:
120
128
 
121
- ```python
122
- >>> from doctr.io import DocumentFile
123
- >>> from doctr.models import ocr_predictor, from_hub
129
+ ```python
130
+ >>> from doctr.io import DocumentFile
131
+ >>> from doctr.models import ocr_predictor, from_hub
124
132
 
125
- >>> img = DocumentFile.from_images(['<image_path>'])
126
- >>> # Load your model from the hub
127
- >>> model = from_hub('mindee/my-model')
133
+ >>> img = DocumentFile.from_images(['<image_path>'])
134
+ >>> # Load your model from the hub
135
+ >>> model = from_hub('mindee/my-model')
128
136
 
129
- >>> # Pass it to the predictor
130
- >>> # If your model is a recognition model:
131
- >>> predictor = ocr_predictor(det_arch='db_mobilenet_v3_large',
132
- >>> reco_arch=model,
133
- >>> pretrained=True)
137
+ >>> # Pass it to the predictor
138
+ >>> # If your model is a recognition model:
139
+ >>> predictor = ocr_predictor(det_arch='db_mobilenet_v3_large',
140
+ >>> reco_arch=model,
141
+ >>> pretrained=True)
134
142
 
135
- >>> # If your model is a detection model:
136
- >>> predictor = ocr_predictor(det_arch=model,
137
- >>> reco_arch='crnn_mobilenet_v3_small',
138
- >>> pretrained=True)
143
+ >>> # If your model is a detection model:
144
+ >>> predictor = ocr_predictor(det_arch=model,
145
+ >>> reco_arch='crnn_mobilenet_v3_small',
146
+ >>> pretrained=True)
139
147
 
140
- >>> # Get your predictions
141
- >>> res = predictor(img)
142
- ```
143
- """
144
- )
148
+ >>> # Get your predictions
149
+ >>> res = predictor(img)
150
+ ```
151
+ """
145
152
 
146
153
  # add run configuration to readme if available
147
154
  if run_config is not None:
148
155
  arch = run_config.arch
149
- readme += textwrap.dedent(
150
- f"""### Run Configuration
151
- \n{json.dumps(vars(run_config), indent=2, ensure_ascii=False)}"""
152
- )
156
+ readme += f"""
157
+ ### Run Configuration
158
+
159
+ ```json
160
+ {json.dumps(vars(run_config), indent=2, ensure_ascii=False)}
161
+ ```
162
+ """
153
163
 
154
164
  if arch not in AVAILABLE_ARCHS[task]:
155
165
  raise ValueError(
@@ -161,7 +171,8 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
161
171
 
162
172
  # Create repository
163
173
  api = HfApi()
164
- api.create_repo(model_name, token=get_token(), exist_ok=False)
174
+ repo_url = api.create_repo(model_name, token=get_token(), repo_type="model", exist_ok=False)
175
+ full_repo_id = repo_url.repo_id
165
176
 
166
177
  # Save model files to a temporary directory
167
178
  with tempfile.TemporaryDirectory() as tmp_dir:
@@ -172,7 +183,8 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
172
183
  # Upload all files to the hub
173
184
  api.upload_folder(
174
185
  folder_path=tmp_dir,
175
- repo_id=model_name,
186
+ repo_id=full_repo_id,
187
+ repo_type="model",
176
188
  commit_message=commit_message,
177
189
  token=get_token(),
178
190
  )
@@ -208,6 +220,12 @@ def from_hub(repo_id: str, **kwargs: Any):
208
220
  model = models.detection.__dict__[arch](pretrained=False)
209
221
  elif task == "recognition":
210
222
  model = models.recognition.__dict__[arch](pretrained=False, input_shape=cfg["input_shape"], vocab=cfg["vocab"])
223
+ elif task == "layout":
224
+ model = models.layout.__dict__[arch](pretrained=False, class_names=cfg["class_names"])
225
+ elif task == "table_structure":
226
+ model = models.table_structure.__dict__[arch](pretrained=False)
227
+ elif task == "formula":
228
+ model = models.formula.__dict__[arch](pretrained=False, input_shape=cfg["input_shape"], vocab=cfg["vocab"])
211
229
 
212
230
  # update model cfg
213
231
  model.cfg = cfg
@@ -0,0 +1,2 @@
1
+ from .formulanet import *
2
+ from .zoo import *
@@ -0,0 +1,2 @@
1
+ from .base import *
2
+ from .pytorch import *
@@ -0,0 +1,70 @@
1
+ # Copyright (C) 2021-2026, Mindee.
2
+
3
+ # This program is licensed under the Apache License 2.0.
4
+ # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
+
6
+ from collections.abc import Sequence
7
+
8
+ import numpy as np
9
+
10
+ from doctr.datasets import encode_sequences, normalize_latex
11
+ from doctr.utils.repr import NestedObject
12
+
13
+ from ..._utils import ConfidenceAggregation, _confidence_aggregation_repr, _resolve_confidence_aggregation
14
+
15
+ __all__ = ["_FormulaNet", "_FormulaNetPostProcessor"]
16
+
17
+
18
+ class _FormulaNet:
19
+ vocab: list[str]
20
+ max_length: int
21
+
22
+ def build_target(self, gts: list[str]) -> tuple[np.ndarray, list[int]]:
23
+ r"""Encode LaTeX labels into token sequences `[SOS, tokens..., EOS, PAD...]`
24
+
25
+ The labels are tokenized first (cf. :func:`doctr.datasets.normalize_latex`), so they can be given either raw
26
+ (e.g. `\frac{a}{b}`) or normalized (e.g. `\frac { a } { b }`).
27
+
28
+ Args:
29
+ gts: list of ground-truth LaTeX labels
30
+
31
+ Returns:
32
+ the encoded sequences, of shape (N, L), and the number of tokens of each label
33
+ """
34
+ normalized = [normalize_latex(gt) for gt in gts]
35
+ encoded = encode_sequences(
36
+ sequences=normalized,
37
+ vocab=self.vocab,
38
+ target_size=self.max_length + 2, # SOS + tokens + EOS
39
+ eos=len(self.vocab),
40
+ sos=len(self.vocab) + 1,
41
+ pad=len(self.vocab) + 2,
42
+ dynamic_seq_length=True,
43
+ )
44
+ seq_len = [len(label.split()) for label in normalized]
45
+ return encoded, seq_len
46
+
47
+
48
+ class _FormulaNetPostProcessor(NestedObject):
49
+ """Turns the token scores of a formula recognition model into LaTeX strings
50
+
51
+ Args:
52
+ vocab: the list of LaTeX tokens of the model
53
+ confidence_aggregation: aggregation method of the token probabilities into the formula confidence:
54
+ "mean", "min", "max", "median", "geometric_mean", "harmonic_mean" or a callable
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ vocab: Sequence[str],
60
+ confidence_aggregation: ConfidenceAggregation = "mean",
61
+ ) -> None:
62
+ _resolve_confidence_aggregation(confidence_aggregation)
63
+ self.vocab = list(vocab)
64
+ self.confidence_aggregation = confidence_aggregation
65
+
66
+ def extra_repr(self) -> str:
67
+ return (
68
+ f"vocab_size={len(self.vocab)}, "
69
+ f"confidence_aggregation={_confidence_aggregation_repr(self.confidence_aggregation)}"
70
+ )